From bc00eaf53ee998abaf516865db7d6031fa727c60 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 08:26:52 +0200 Subject: [PATCH 01/75] docs: add client magic links design spec Co-Authored-By: Claude Opus 4.6 (1M context) --- .../2026-04-15-client-magic-links-design.md | 222 ++++++++++++++++++ 1 file changed, 222 insertions(+) create mode 100644 docs/superpowers/specs/2026-04-15-client-magic-links-design.md diff --git a/docs/superpowers/specs/2026-04-15-client-magic-links-design.md b/docs/superpowers/specs/2026-04-15-client-magic-links-design.md new file mode 100644 index 0000000..690d46c --- /dev/null +++ b/docs/superpowers/specs/2026-04-15-client-magic-links-design.md @@ -0,0 +1,222 @@ +# Client Magic Links — Design Spec + +## Overview + +Replace the temporary user invitation model with a magic link system for external client access. Clients access tablos via a dedicated portal at `clients.xtablo.com` (`apps/clients`), authenticated through Supabase passwordless magic links. Tablo view components are extracted into a shared `packages/tablo-views` package consumed by both `apps/main` and `apps/clients`. + +Temporary users remain untouched during the transition period. + +## Data Model + +### New column: `profiles.is_client` + +- `is_client: boolean NOT NULL DEFAULT false` +- Marks users created via client magic link invites +- Distinct from `is_temporary` — clean separation for the transition +- Excluded from billing (`getBillableMemberCount` filters out `is_client` users) + +### New table: `client_invites` + +| Column | Type | Notes | +|--------|------|-------| +| `id` | serial PK | | +| `tablo_id` | text FK -> tablos | | +| `invited_email` | varchar(255) | | +| `invited_by` | uuid FK -> profiles | | +| `invite_token` | text | URL-safe token for the magic link | +| `expires_at` | timestamptz | Default: `now() + interval '30 days'` | +| `is_pending` | boolean DEFAULT true | Flipped to false on acceptance | +| `created_at` | timestamptz DEFAULT now() | | + +RLS policies: +- Admins (invite senders) can read/manage their invites +- Client users can read their own invites by email match + +### Existing table: `tablo_access` + +No schema changes. Client users get a standard row with `is_admin: false`, `is_active: true`. Access revocation uses the existing `is_active = false` pattern. + +## Magic Link Invitation Flow + +### Sending an invite (admin in `apps/main`) + +1. Admin opens tablo share dialog, enters client email +2. `POST /api/v1/tablos/:tabloId/client-invites` — validates admin access, creates `client_invites` row with generated token and `expires_at = now() + 30 days` +3. If no Supabase account exists for that email, the API creates one via `supabase.auth.admin.createUser({ email })` and sets `is_client: true` on the resulting profile row. A `tablo_access` row is pre-granted (`is_admin: false`, `is_active: true`). +4. API calls `supabase.auth.admin.generateLink({ type: 'magiclink', email, options: { redirectTo: 'https://clients.xtablo.com/auth/callback?token=' } })` to generate the magic link +5. Supabase sends the magic link email to the client + +### Client clicks the link + +1. Supabase verifies the auth token, redirects to `clients.xtablo.com/auth/callback?token=` +2. Callback page exchanges the Supabase auth token for a session +3. The `invite_token` is used to call `POST /api/v1/client-invites/:token/accept` — marks invite as accepted (`is_pending: false`), confirms `tablo_access` is active +4. Client is redirected to `clients.xtablo.com/tablo/:tabloId` + +### Expiration and renewal + +- Expired invites (past `expires_at`) are rejected at acceptance time with a clear error message +- Admins can re-invite the same email, creating a new `client_invites` row with a fresh 30-day window +- Admin can revoke access by setting `tablo_access.is_active = false` + +### Returning clients + +- Active session + valid `tablo_access` = direct access, no re-invitation needed +- Expired session requires a new magic link from the admin + +## API Permission Scoping + +### Middleware + +New middleware variant: `clientUserCheckMiddleware` — returns `403` for `is_client` users on non-client-accessible routes. + +### Client-accessible endpoints + +- `GET /api/v1/tablos/:tabloId` — view tablo details +- `GET /api/v1/tablo-data/:tabloId/*` — tasks, etapes, events, files metadata +- `GET /api/v1/tablo-files/:tabloId/*` — file downloads +- `POST /api/v1/tablo-files/:tabloId/upload` — file uploads +- Chat endpoints (messages, typing, presence via WebSocket) +- `GET /api/v1/user/me` — own profile + +### Blocked for client users + +- Tablo CRUD (create, update, delete) +- Invite management (sending/cancelling invites) +- Organization endpoints +- Billing/Stripe endpoints +- Settings, user management + +### Billing + +`getBillableMemberCount` updated to exclude `is_client` users (same pattern as `is_temporary`). + +### RLS policies + +New row-level policies on `client_invites`: +- Admins can manage invites they created +- Clients can read their own invites (by email match) + +## `packages/tablo-views` — Shared Package + +Source-only package (TypeScript directly, no build step). Same pattern as `@xtablo/shared` and `@xtablo/ui`. + +### Structure + +``` +packages/tablo-views/ +├── package.json (@xtablo/tablo-views) +├── tsconfig.json +└── src/ + ├── TabloOverviewSection.tsx + ├── TabloEtapesSection.tsx + ├── TabloTasksSection.tsx + ├── TabloFilesSection.tsx + ├── TabloDiscussionSection.tsx + ├── TabloEventsSection.tsx + ├── TabloRoadmapSection.tsx + ├── components/ (shared sub-components these sections depend on) + └── hooks/ (data-fetching hooks for tablo views, including useChat) +``` + +### What moves from `apps/main` + +- The 7 tab section components +- Sub-components they directly depend on (task cards, file list items, gantt chart, etc.) +- Data-fetching hooks used exclusively by these views (including `useChat` from `apps/main/src/hooks/useChat.ts`) + +### What stays in `apps/main` + +- `TabloDetailsPage` (page shell with tab navigation, share dialog, invite management) +- Layout, navigation, routing +- App-level providers + +### Dependencies + +`@xtablo/tablo-views` depends on: +- `@xtablo/ui` +- `@xtablo/shared` +- `@xtablo/shared-types` +- `@xtablo/chat-ui` + +Consumed by both `apps/main` and `apps/clients`. + +### Refactor in `apps/main` + +`TabloDetailsPage` imports sections from `@xtablo/tablo-views` instead of local files. Behavior stays identical — this is a move, not a rewrite. + +## `apps/clients` — Client Portal App + +### Structure + +``` +apps/clients/ +├── package.json (@xtablo/clients) +├── vite.config.ts +├── wrangler.toml (clients.xtablo.com) +├── worker/index.ts +├── index.html +├── tsconfig.json +├── tsconfig.app.json +└── src/ + ├── main.tsx + ├── App.tsx + ├── routes.tsx + ├── pages/ + │ ├── AuthCallback.tsx + │ └── ClientTabloPage.tsx + └── components/ + └── ClientLayout.tsx +``` + +### Cloudflare Worker + +`wrangler.toml` routes `clients.xtablo.com` with SPA not-found handling. Same asset-serving pattern as `apps/main` and `apps/external`. + +### Layout + +`ClientLayout.tsx` — no sidebar. Minimal top bar with: +- Tablo name and color +- Client user avatar and name +- Logout action + +### Routes + +| Path | Component | Purpose | +|------|-----------|---------| +| `/auth/callback` | `AuthCallback` | Supabase magic link redirect + invite token acceptance | +| `/tablo/:tabloId` | `ClientTabloPage` | Scoped tablo view with all tabs | +| `/` | Redirect | To `/tablo/:tabloId` if one tablo, or simple list if multiple | + +### `ClientTabloPage` + +Renders the same tab system as `TabloDetailsPage` using components from `@xtablo/tablo-views`. Differences from `apps/main`: +- No share/invite dialog +- No tablo settings or delete actions +- No admin-only actions in the UI +- File section: download and upload enabled, no delete + +### Providers + +`QueryClientProvider`, `SessionProvider`, `ThemeProvider`, i18n — same setup as other apps. No `UserStoreProvider` or organization context (clients don't belong to orgs). + +### Dev server + +Port 5175 via `pnpm dev:clients`. + +## Chat Integration + +Client users get real Supabase accounts, so chat works with minimal changes: + +- **Authentication:** Same JWT-based auth for WebSocket connections +- **Identity:** Profile row (name, optional avatar) used for chat display. Profile seeded with invited email on creation. Client can update display name on first access. +- **Permissions:** Client users can send messages and see typing indicators in tablo discussions they have access to. Tablo ID maps to channel ID. +- **`@xtablo/chat-ui`:** No changes needed. Components are already app-agnostic. +- **`useChat` hook:** Moves to `packages/tablo-views/src/hooks/` so both apps can use it. + +## Migration Strategy + +- Temporary users (`is_temporary`) remain untouched +- Existing tablo invitations continue to work via `apps/main` +- New client invites use the magic link flow via `apps/clients` +- Once all clients have migrated to magic links, a future phase removes `is_temporary` and related code From 3bed5e20be44ac261a734200b349db7fcec84922 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 08:32:06 +0200 Subject: [PATCH 02/75] docs: add expiration warning for admins to client magic links spec Co-Authored-By: Claude Opus 4.6 (1M context) --- docs/superpowers/specs/2026-04-15-client-magic-links-design.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/superpowers/specs/2026-04-15-client-magic-links-design.md b/docs/superpowers/specs/2026-04-15-client-magic-links-design.md index 690d46c..ffabd8c 100644 --- a/docs/superpowers/specs/2026-04-15-client-magic-links-design.md +++ b/docs/superpowers/specs/2026-04-15-client-magic-links-design.md @@ -57,6 +57,7 @@ No schema changes. Client users get a standard row with `is_admin: false`, `is_a - Expired invites (past `expires_at`) are rejected at acceptance time with a clear error message - Admins can re-invite the same email, creating a new `client_invites` row with a fresh 30-day window +- Admins are warned in the UI when the expiration is soon (less than 5 days) - Admin can revoke access by setting `tablo_access.is_active = false` ### Returning clients From 05c552ce730b6cc2659f3e84da7e4353eed6a5b2 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 08:53:22 +0200 Subject: [PATCH 03/75] docs: add client magic links implementation plan Co-Authored-By: Claude Opus 4.6 (1M context) --- .../plans/2026-04-15-client-magic-links.md | 1822 +++++++++++++++++ 1 file changed, 1822 insertions(+) create mode 100644 docs/superpowers/plans/2026-04-15-client-magic-links.md diff --git a/docs/superpowers/plans/2026-04-15-client-magic-links.md b/docs/superpowers/plans/2026-04-15-client-magic-links.md new file mode 100644 index 0000000..5fb702e --- /dev/null +++ b/docs/superpowers/plans/2026-04-15-client-magic-links.md @@ -0,0 +1,1822 @@ +# Client Magic Links Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Replace temporary user invitations with magic links, served via a new `apps/clients` portal at `clients.xtablo.com`, powered by shared tablo view components extracted into `packages/tablo-views`. + +**Architecture:** Three parallel workstreams — (1) database + API changes for `is_client` users and `client_invites`, (2) extract tablo view components into `packages/tablo-views`, (3) scaffold `apps/clients` portal. The API serves both `apps/main` and `apps/clients` with permission scoping via middleware. + +**Tech Stack:** React 19, Vite, Cloudflare Workers, Hono, Supabase Auth (magic links), TanStack Query, Tailwind CSS v4, pnpm workspaces, Turborepo. + +**Spec:** `docs/superpowers/specs/2026-04-15-client-magic-links-design.md` + +--- + +## File Structure + +### New files + +**Database:** +- `supabase/migrations/20260415120000_add_client_invites.sql` — migration: `is_client` column + `client_invites` table + RLS + +**API:** +- `apps/api/src/routers/clientInvites.ts` — client invite endpoints (create, accept, list, cancel) +- `apps/api/src/__tests__/routes/clientInvites.test.ts` — tests for client invite routes + +**Package: `packages/tablo-views`:** +- `packages/tablo-views/package.json` +- `packages/tablo-views/tsconfig.json` +- `packages/tablo-views/src/index.ts` — barrel export +- `packages/tablo-views/src/TabloTasksSection.tsx` — moved from apps/main +- `packages/tablo-views/src/TabloFilesSection.tsx` — moved from apps/main +- `packages/tablo-views/src/TabloDiscussionSection.tsx` — moved from apps/main +- `packages/tablo-views/src/TabloEventsSection.tsx` — moved from apps/main +- `packages/tablo-views/src/EtapesSection.tsx` — extracted from tablo-details.tsx +- `packages/tablo-views/src/RoadmapSection.tsx` — extracted from tablo-details.tsx +- `packages/tablo-views/src/ChatMessages.tsx` — moved from apps/main +- `packages/tablo-views/src/TabloHeaderActions.tsx` — moved from apps/main +- `packages/tablo-views/src/hooks/useChat.ts` — moved from apps/main +- `packages/tablo-views/src/hooks/useChatUnread.ts` — moved from apps/main +- `packages/tablo-views/src/components/gantt/GanttChart.tsx` — moved from apps/main +- `packages/tablo-views/src/components/kanban/KanbanBoard.tsx` — moved from apps/main +- `packages/tablo-views/src/components/kanban/KanbanColumn.tsx` — moved from apps/main +- `packages/tablo-views/src/components/kanban/KanbanTaskCard.tsx` — moved from apps/main +- `packages/tablo-views/src/components/kanban/InlineTaskCreate.tsx` — moved from apps/main +- `packages/tablo-views/src/components/kanban/TaskModal.tsx` — moved from apps/main +- `packages/tablo-views/src/components/kanban/types.ts` — moved from apps/main + +**App: `apps/clients`:** +- `apps/clients/package.json` +- `apps/clients/vite.config.ts` +- `apps/clients/wrangler.toml` +- `apps/clients/worker/index.ts` +- `apps/clients/index.html` +- `apps/clients/tsconfig.json` +- `apps/clients/src/main.tsx` +- `apps/clients/src/main.css` +- `apps/clients/src/App.tsx` +- `apps/clients/src/routes.tsx` +- `apps/clients/src/i18n.ts` +- `apps/clients/src/pages/AuthCallback.tsx` +- `apps/clients/src/pages/ClientTabloPage.tsx` +- `apps/clients/src/pages/ClientTabloListPage.tsx` +- `apps/clients/src/components/ClientLayout.tsx` + +### Modified files + +- `apps/api/src/middlewares/middleware.ts` — add `is_client` check to `createProfileAccessMiddleware` +- `apps/api/src/routers/authRouter.ts` — mount `clientInvites` router +- `apps/api/src/routers/tablo.ts` — add `checkTabloAdmin` to new client invite endpoint +- `apps/api/src/helpers/helpers.ts` — add `createClientUser()` function +- `apps/api/src/helpers/billing.ts` — exclude `is_client` from `getBillableMemberCount` +- `apps/api/src/__tests__/middlewares/middlewares.test.ts` — add `is_client` middleware tests +- `apps/main/src/pages/tablo-details.tsx` — import sections from `@xtablo/tablo-views` instead of local +- `apps/main/src/components/TabloHeaderActions.tsx` — add client invite UI to share dialog +- `packages/shared-types/src/database.types.ts` — regenerated after migration (or manually add types) +- `package.json` (root) — add `dev:clients` script +- `pnpm-workspace.yaml` — already covers `apps/*` and `packages/*`, no change needed + +--- + +## Task 1: Database Migration — `is_client` Column and `client_invites` Table + +**Files:** +- Create: `supabase/migrations/20260415120000_add_client_invites.sql` +- Modify: `packages/shared-types/src/database.types.ts` + +- [ ] **Step 1: Write the migration SQL** + +```sql +-- Add is_client column to profiles +ALTER TABLE public.profiles + ADD COLUMN is_client boolean NOT NULL DEFAULT false; + +-- Create client_invites table +CREATE TABLE public.client_invites ( + id serial PRIMARY KEY, + tablo_id text NOT NULL REFERENCES public.tablos(id) ON DELETE CASCADE, + invited_email varchar(255) NOT NULL, + invited_by uuid NOT NULL REFERENCES public.profiles(id), + invite_token text NOT NULL, + expires_at timestamptz NOT NULL DEFAULT (now() + interval '30 days'), + is_pending boolean NOT NULL DEFAULT true, + created_at timestamptz NOT NULL DEFAULT now() +); + +-- Index for token lookups +CREATE UNIQUE INDEX idx_client_invites_token ON public.client_invites(invite_token); + +-- Index for listing invites by tablo +CREATE INDEX idx_client_invites_tablo ON public.client_invites(tablo_id, is_pending); + +-- RLS +ALTER TABLE public.client_invites ENABLE ROW LEVEL SECURITY; + +-- Admins can manage invites they created +CREATE POLICY "Admins can manage their client invites" + ON public.client_invites + FOR ALL + USING (invited_by = auth.uid()); + +-- Client users can read invites sent to their email +CREATE POLICY "Clients can read their own invites" + ON public.client_invites + FOR SELECT + USING ( + invited_email = ( + SELECT email FROM auth.users WHERE id = auth.uid() + ) + ); +``` + +Save to `supabase/migrations/20260415120000_add_client_invites.sql`. + +- [ ] **Step 2: Add TypeScript types for `client_invites`** + +Add the following types to `packages/shared-types/src/database.types.ts` in the `Tables` interface, following the existing pattern used by `tablo_invites`: + +```typescript +client_invites: { + Row: { + id: number; + tablo_id: string; + invited_email: string; + invited_by: string; + invite_token: string; + expires_at: string; + is_pending: boolean; + created_at: string; + }; + Insert: { + id?: number; + tablo_id: string; + invited_email: string; + invited_by: string; + invite_token: string; + expires_at?: string; + is_pending?: boolean; + created_at?: string; + }; + Update: { + id?: number; + tablo_id?: string; + invited_email?: string; + invited_by?: string; + invite_token?: string; + expires_at?: string; + is_pending?: boolean; + created_at?: string; + }; + Relationships: [ + { + foreignKeyName: "client_invites_tablo_id_fkey"; + columns: ["tablo_id"]; + isOneToOne: false; + referencedRelation: "tablos"; + referencedColumns: ["id"]; + }, + { + foreignKeyName: "client_invites_invited_by_fkey"; + columns: ["invited_by"]; + isOneToOne: false; + referencedRelation: "profiles"; + referencedColumns: ["id"]; + } + ]; +}; +``` + +Also add `is_client: boolean` to the `profiles` Row, Insert, and Update types. + +- [ ] **Step 3: Commit** + +```bash +git add supabase/migrations/20260415120000_add_client_invites.sql packages/shared-types/src/database.types.ts +git commit -m "feat(db): add is_client column and client_invites table" +``` + +--- + +## Task 2: API Middleware — Add `is_client` Permission Check + +**Files:** +- Modify: `apps/api/src/middlewares/middleware.ts:77-100` +- Modify: `apps/api/src/helpers/billing.ts:89-90` +- Test: `apps/api/src/__tests__/middlewares/middlewares.test.ts` + +- [ ] **Step 1: Write failing test for `is_client` user blocked by `regularUserCheckMiddleware`** + +In `apps/api/src/__tests__/middlewares/middlewares.test.ts`, add a new test in the "Regular user check middleware" describe block: + +```typescript +it("should return 401 for client users", async () => { + const app = new Hono(); + const middlewareManager = MiddlewareManager.getInstance(); + + app.use(middlewareManager.supabase); + app.use(middlewareManager.auth); + app.use(middlewareManager.regularUserCheck); + app.get("/test", (c) => c.json({ success: true })); + + mockSupabaseFrom.mockImplementation((table: string) => { + if (table === "profiles") { + return { + select: () => ({ + eq: () => ({ + single: () => + Promise.resolve({ + data: { is_temporary: false, is_client: true }, + error: null, + }), + }), + }), + }; + } + return {}; + }); + + const res = await app.request("/test", { + headers: { Authorization: "Bearer valid-token" }, + }); + + expect(res.status).toBe(401); + const body = await res.json(); + expect(body.error).toBe("User is read only"); +}); +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `cd apps/api && pnpm test -- --run src/__tests__/middlewares/middlewares.test.ts` +Expected: FAIL — the current middleware only checks `is_temporary`, not `is_client` + +- [ ] **Step 3: Update middleware to check `is_client`** + +In `apps/api/src/middlewares/middleware.ts`, modify `createProfileAccessMiddleware` (line 77-100): + +Change the select from: +```typescript +.select("is_temporary") +``` +to: +```typescript +.select("is_temporary, is_client") +``` + +Change the check from: +```typescript +if (!allowTemporaryUsers && profile.is_temporary) { +``` +to: +```typescript +if ((!allowTemporaryUsers && profile.is_temporary) || profile.is_client) { +``` + +This blocks `is_client` users from all routes that use `regularUserCheckMiddleware`. Client-accessible routes don't use this middleware — they only require `auth`. + +- [ ] **Step 4: Update billing exclusion** + +In `apps/api/src/helpers/billing.ts`, change `getBillableMemberCount` (line 89-90): + +From: +```typescript +export const getBillableMemberCount = (profiles: BillingProfileRow[]) => + profiles.filter((profile) => profile.is_temporary !== true).length; +``` +To: +```typescript +export const getBillableMemberCount = (profiles: BillingProfileRow[]) => + profiles.filter((profile) => profile.is_temporary !== true && profile.is_client !== true).length; +``` + +Note: The `BillingProfileRow` type (defined earlier in billing.ts) needs `is_client` added. Find the type definition and add `is_client: boolean` alongside the existing `is_temporary: boolean`. + +- [ ] **Step 5: Run tests to verify they pass** + +Run: `cd apps/api && pnpm test -- --run src/__tests__/middlewares/middlewares.test.ts` +Expected: PASS + +- [ ] **Step 6: Commit** + +```bash +git add apps/api/src/middlewares/middleware.ts apps/api/src/helpers/billing.ts apps/api/src/__tests__/middlewares/middlewares.test.ts +git commit -m "feat(api): add is_client check to middleware and billing" +``` + +--- + +## Task 3: API — Client Invite Endpoints + +**Files:** +- Create: `apps/api/src/routers/clientInvites.ts` +- Modify: `apps/api/src/routers/authRouter.ts` +- Modify: `apps/api/src/helpers/helpers.ts` +- Create: `apps/api/src/__tests__/routes/clientInvites.test.ts` + +- [ ] **Step 1: Add `createClientUser` helper** + +In `apps/api/src/helpers/helpers.ts`, add a new function after `createInvitedUser`: + +```typescript +export async function createClientUser( + supabase: SupabaseClient, + recipientEmail: string, + tabloId: string, + grantedBy: string +): Promise<{ success: boolean; error?: string; userId?: string }> { + // Check if user already exists + const { data: existingUsers } = await supabase.auth.admin.listUsers(); + const existingUser = existingUsers?.users?.find( + (u) => u.email?.toLowerCase() === recipientEmail.toLowerCase() + ); + + let userId: string; + + if (existingUser) { + userId = existingUser.id; + + // Mark as client if not already + await supabase + .from("profiles") + .update({ is_client: true }) + .eq("id", userId) + .eq("is_client", false); + } else { + // Create new auth user (no password — magic link only) + const { data: authData, error: authError } = await supabase.auth.admin.createUser({ + email: recipientEmail, + email_confirm: true, + user_metadata: { role: "client" }, + }); + + if (authError || !authData?.user) { + return { success: false, error: authError?.message ?? "Failed to create user" }; + } + + userId = authData.user.id; + + // Set is_client on profile + await supabase.from("profiles").update({ is_client: true }).eq("id", userId); + } + + // Grant tablo access if not already granted + const { data: existingAccess } = await supabase + .from("tablo_access") + .select("id, is_active") + .eq("tablo_id", tabloId) + .eq("user_id", userId) + .single(); + + if (!existingAccess) { + await supabase.from("tablo_access").insert({ + tablo_id: tabloId, + user_id: userId, + granted_by: grantedBy, + is_admin: false, + is_active: true, + }); + } else if (!existingAccess.is_active) { + await supabase + .from("tablo_access") + .update({ is_active: true }) + .eq("id", existingAccess.id); + } + + return { success: true, userId }; +} +``` + +- [ ] **Step 2: Create client invites router** + +Create `apps/api/src/routers/clientInvites.ts`: + +```typescript +import { Hono } from "hono"; +import { checkTabloAdmin } from "../helpers/helpers.js"; +import { generateToken } from "../helpers/token.js"; +import { MiddlewareManager } from "../middlewares/middleware.js"; +import { createClientUser } from "../helpers/helpers.js"; +import type { SupabaseClient, User } from "@supabase/supabase-js"; + +type Env = { + Variables: { + supabase: SupabaseClient; + user: User; + }; +}; + +export const getClientInvitesRouter = () => { + const router = new Hono(); + const middlewareManager = MiddlewareManager.getInstance(); + + // Create client invite (admin only) + router.post( + "/:tabloId", + middlewareManager.regularUserCheck, + checkTabloAdmin, + async (c) => { + const supabase = c.get("supabase"); + const user = c.get("user"); + const tabloId = c.req.param("tabloId"); + const { email } = await c.req.json<{ email: string }>(); + + if (!email || !email.includes("@")) { + return c.json({ error: "Invalid email" }, 400); + } + + const token = generateToken(); + + // Create client user + tablo access + const result = await createClientUser(supabase, email, tabloId, user.id); + if (!result.success) { + return c.json({ error: result.error }, 500); + } + + // Create client_invites record + const { error: insertError } = await supabase.from("client_invites").insert({ + tablo_id: tabloId, + invited_email: email.toLowerCase(), + invited_by: user.id, + invite_token: token, + }); + + if (insertError) { + return c.json({ error: insertError.message }, 500); + } + + // Generate Supabase magic link + const redirectTo = `${c.req.header("origin")?.replace("app.", "clients.") ?? "https://clients.xtablo.com"}/auth/callback?token=${token}`; + + const { error: linkError } = await supabase.auth.admin.generateLink({ + type: "magiclink", + email, + options: { redirectTo }, + }); + + if (linkError) { + return c.json({ error: "Failed to send magic link" }, 500); + } + + return c.json({ success: true }); + } + ); + + // Accept client invite via token + router.post("/accept/:token", async (c) => { + const supabase = c.get("supabase"); + const user = c.get("user"); + const token = c.req.param("token"); + + const { data: invite, error } = await supabase + .from("client_invites") + .select("*") + .eq("invite_token", token) + .eq("is_pending", true) + .single(); + + if (error || !invite) { + return c.json({ error: "Invalid or expired invite" }, 404); + } + + // Check expiration + if (new Date(invite.expires_at) < new Date()) { + return c.json({ error: "Invite has expired" }, 410); + } + + // Verify email matches + const { data: userProfile } = await supabase + .from("profiles") + .select("email") + .eq("id", user.id) + .single(); + + if (userProfile?.email?.toLowerCase() !== invite.invited_email.toLowerCase()) { + return c.json({ error: "Email mismatch" }, 403); + } + + // Mark invite as accepted + await supabase + .from("client_invites") + .update({ is_pending: false }) + .eq("id", invite.id); + + // Ensure tablo_access is active + const { data: access } = await supabase + .from("tablo_access") + .select("id, is_active") + .eq("tablo_id", invite.tablo_id) + .eq("user_id", user.id) + .single(); + + if (access && !access.is_active) { + await supabase + .from("tablo_access") + .update({ is_active: true }) + .eq("id", access.id); + } + + return c.json({ success: true, tabloId: invite.tablo_id }); + }); + + // List pending client invites for a tablo (admin only) + router.get( + "/:tabloId/pending", + middlewareManager.regularUserCheck, + checkTabloAdmin, + async (c) => { + const supabase = c.get("supabase"); + const tabloId = c.req.param("tabloId"); + + const { data, error } = await supabase + .from("client_invites") + .select("id, invited_email, expires_at, is_pending, created_at") + .eq("tablo_id", tabloId) + .eq("is_pending", true) + .order("created_at", { ascending: false }); + + if (error) { + return c.json({ error: error.message }, 500); + } + + return c.json({ invites: data }); + } + ); + + // Cancel client invite (admin only) + router.delete( + "/:tabloId/:inviteId", + middlewareManager.regularUserCheck, + checkTabloAdmin, + async (c) => { + const supabase = c.get("supabase"); + const inviteId = c.req.param("inviteId"); + const tabloId = c.req.param("tabloId"); + + const { data: invite } = await supabase + .from("client_invites") + .select("invited_email") + .eq("id", Number(inviteId)) + .eq("tablo_id", tabloId) + .single(); + + if (!invite) { + return c.json({ error: "Invite not found" }, 404); + } + + // Mark as not pending + await supabase + .from("client_invites") + .update({ is_pending: false }) + .eq("id", Number(inviteId)); + + // Revoke tablo access for client user + const { data: profile } = await supabase + .from("profiles") + .select("id, is_client") + .eq("email", invite.invited_email) + .single(); + + if (profile?.is_client) { + await supabase + .from("tablo_access") + .update({ is_active: false }) + .eq("tablo_id", tabloId) + .eq("user_id", profile.id); + } + + return c.json({ success: true }); + } + ); + + return router; +}; +``` + +- [ ] **Step 3: Mount the router in authRouter.ts** + +In `apps/api/src/routers/authRouter.ts`, add the import and route: + +```typescript +import { getClientInvitesRouter } from "./clientInvites.js"; +``` + +Add after the existing routes (before `return authRouter`): +```typescript +authRouter.route("/client-invites", getClientInvitesRouter()); +``` + +- [ ] **Step 4: Write tests for client invite endpoints** + +Create `apps/api/src/__tests__/routes/clientInvites.test.ts`. Follow the existing test patterns from `apps/api/src/__tests__/routes/tablo.test.ts` for mocking supabase. Key test cases: + +```typescript +import { describe, it, expect, vi, beforeEach } from "vitest"; +// ... test setup matching existing patterns + +describe("Client Invites Router", () => { + describe("POST /:tabloId (create invite)", () => { + it("should create client invite and return success", async () => { + // Mock admin access check, user creation, invite insert, magic link generation + // Assert: 200, { success: true } + }); + + it("should reject non-admin users", async () => { + // Mock non-admin tablo_access + // Assert: 403 + }); + + it("should reject invalid email", async () => { + // Send email without @ + // Assert: 400 + }); + }); + + describe("POST /accept/:token", () => { + it("should accept valid invite and return tabloId", async () => { + // Mock valid pending invite, matching email, active tablo_access + // Assert: 200, { success: true, tabloId: "..." } + }); + + it("should reject expired invite", async () => { + // Mock invite with expires_at in the past + // Assert: 410 + }); + + it("should reject email mismatch", async () => { + // Mock invite with different email than authenticated user + // Assert: 403 + }); + }); + + describe("GET /:tabloId/pending", () => { + it("should return pending invites for admin", async () => { + // Mock admin + pending invites + // Assert: 200, { invites: [...] } + }); + }); + + describe("DELETE /:tabloId/:inviteId", () => { + it("should cancel invite and revoke access for client user", async () => { + // Mock invite + client profile + // Assert: 200, tablo_access set to inactive + }); + }); +}); +``` + +Fill in complete mock setup following the patterns in `apps/api/src/__tests__/routes/tablo.test.ts`. + +- [ ] **Step 5: Run tests** + +Run: `cd apps/api && pnpm test -- --run` +Expected: All tests pass + +- [ ] **Step 6: Commit** + +```bash +git add apps/api/src/routers/clientInvites.ts apps/api/src/routers/authRouter.ts apps/api/src/helpers/helpers.ts apps/api/src/__tests__/routes/clientInvites.test.ts +git commit -m "feat(api): add client invite endpoints with magic link flow" +``` + +--- + +## Task 4: Scaffold `packages/tablo-views` + +**Files:** +- Create: `packages/tablo-views/package.json` +- Create: `packages/tablo-views/tsconfig.json` +- Create: `packages/tablo-views/src/index.ts` + +- [ ] **Step 1: Create `packages/tablo-views/package.json`** + +```json +{ + "name": "@xtablo/tablo-views", + "version": "0.0.0", + "private": true, + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": "./src/index.ts", + "./components/*": "./src/components/*.tsx", + "./hooks/*": "./src/hooks/*.ts", + "./*": "./src/*.tsx" + }, + "scripts": { + "lint": "biome check .", + "lint:fix": "biome check --write .", + "format": "biome format --write .", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@tanstack/react-query": "^5.69.0", + "@xtablo/chat-ui": "workspace:*", + "@xtablo/shared": "workspace:*", + "@xtablo/shared-types": "workspace:*", + "@xtablo/ui": "workspace:*", + "date-fns": "^4.1.0", + "lucide-react": "^0.460.0", + "react": "19.0.0", + "react-dom": "19.0.0", + "react-i18next": "^16.2.0", + "react-router-dom": "^7.9.4", + "tailwind-merge": "^3.0.2" + }, + "devDependencies": { + "@biomejs/biome": "2.2.5", + "@types/react": "19.0.10", + "@types/react-dom": "19.0.4", + "typescript": "^5.7.0" + } +} +``` + +- [ ] **Step 2: Create `packages/tablo-views/tsconfig.json`** + +```json +{ + "compilerOptions": { + "target": "ES2020", + "useDefineForClassFields": true, + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "module": "ESNext", + "skipLibCheck": true, + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "jsx": "react-jsx", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "baseUrl": ".", + "paths": { + "@xtablo/ui": ["../ui/src"], + "@xtablo/ui/*": ["../ui/src/*"], + "@xtablo/shared": ["../shared/src"], + "@xtablo/shared/*": ["../shared/src/*"] + } + }, + "include": ["src"] +} +``` + +- [ ] **Step 3: Create `packages/tablo-views/src/index.ts`** + +```typescript +// Section components +export { TabloTasksSection } from "./TabloTasksSection"; +export { TabloFilesSection } from "./TabloFilesSection"; +export { TabloDiscussionSection } from "./TabloDiscussionSection"; +export { TabloEventsSection } from "./TabloEventsSection"; +export { EtapesSection } from "./EtapesSection"; +export { RoadmapSection } from "./RoadmapSection"; +export { TabloHeaderActions } from "./TabloHeaderActions"; +export { ChatMessages } from "./ChatMessages"; + +// Sub-components +export { GanttChart } from "./components/gantt/GanttChart"; +export { TaskModal } from "./components/kanban/TaskModal"; +export { KanbanBoard } from "./components/kanban/KanbanBoard"; + +// Hooks +export { useChat } from "./hooks/useChat"; +export { useChatUnread } from "./hooks/useChatUnread"; + +// Types +export type { TabloMember } from "./components/kanban/types"; +``` + +- [ ] **Step 4: Install dependencies** + +Run: `pnpm install` + +- [ ] **Step 5: Commit** + +```bash +git add packages/tablo-views/ +git commit -m "feat: scaffold packages/tablo-views package" +``` + +--- + +## Task 5: Move Tablo View Components to `packages/tablo-views` + +This is the largest task. Move each component from `apps/main/src/` to `packages/tablo-views/src/`, updating internal imports. + +**Files to move** (source -> destination): +- `apps/main/src/components/TabloTasksSection.tsx` -> `packages/tablo-views/src/TabloTasksSection.tsx` +- `apps/main/src/components/TabloFilesSection.tsx` -> `packages/tablo-views/src/TabloFilesSection.tsx` +- `apps/main/src/components/TabloDiscussionSection.tsx` -> `packages/tablo-views/src/TabloDiscussionSection.tsx` +- `apps/main/src/components/TabloEventsSection.tsx` -> `packages/tablo-views/src/TabloEventsSection.tsx` +- `apps/main/src/components/TabloHeaderActions.tsx` -> `packages/tablo-views/src/TabloHeaderActions.tsx` +- `apps/main/src/components/ChatMessages.tsx` -> `packages/tablo-views/src/ChatMessages.tsx` +- `apps/main/src/hooks/useChat.ts` -> `packages/tablo-views/src/hooks/useChat.ts` +- `apps/main/src/hooks/useChatUnread.ts` -> `packages/tablo-views/src/hooks/useChatUnread.ts` +- `apps/main/src/components/gantt/GanttChart.tsx` -> `packages/tablo-views/src/components/gantt/GanttChart.tsx` +- `apps/main/src/components/kanban/KanbanBoard.tsx` -> `packages/tablo-views/src/components/kanban/KanbanBoard.tsx` +- `apps/main/src/components/kanban/KanbanColumn.tsx` -> `packages/tablo-views/src/components/kanban/KanbanColumn.tsx` +- `apps/main/src/components/kanban/KanbanTaskCard.tsx` -> `packages/tablo-views/src/components/kanban/KanbanTaskCard.tsx` +- `apps/main/src/components/kanban/InlineTaskCreate.tsx` -> `packages/tablo-views/src/components/kanban/InlineTaskCreate.tsx` +- `apps/main/src/components/kanban/TaskModal.tsx` -> `packages/tablo-views/src/components/kanban/TaskModal.tsx` +- `apps/main/src/components/kanban/types.ts` -> `packages/tablo-views/src/components/kanban/types.ts` + +**Files to extract from `tablo-details.tsx`:** +- `EtapesSection` function (lines 950-1288) -> `packages/tablo-views/src/EtapesSection.tsx` +- `RoadmapSection` function (lines 1292-1309) -> `packages/tablo-views/src/RoadmapSection.tsx` + +- [ ] **Step 1: Move kanban sub-components first (no import changes needed between them)** + +Copy each file from `apps/main/src/components/kanban/` to `packages/tablo-views/src/components/kanban/`. The internal relative imports between kanban files (`./KanbanColumn`, `./KanbanTaskCard`, `./InlineTaskCreate`, `./types`) stay the same. + +For `TaskModal.tsx`, update the hook imports from: +```typescript +import { useTabloMembers } from "../../hooks/tablos"; +import { useCreateTask, useTabloEtapes, useTask, useUpdateTask } from "../../hooks/tasks"; +``` +to: +```typescript +import { useTabloMembers } from "@xtablo/shared/hooks/tablos"; +import { useCreateTask, useTabloEtapes, useTask, useUpdateTask } from "@xtablo/shared/hooks/tasks"; +``` + +**Important:** Check if these hooks exist in `@xtablo/shared`. If they are in `apps/main/src/hooks/`, they need to stay as peer dependencies. In that case, `TaskModal` should accept the needed callbacks as props instead of importing hooks directly. Examine the actual hooks to decide. If the hooks are in `apps/main`, accept them as props: + +```typescript +interface TaskModalProps { + isOpen: boolean; + tabloId?: string; + taskId?: string; + onClose: () => void; + members?: TabloMember[]; + initialStatus?: TaskStatus; + etapes?: Etape[]; + tablos?: UserTablo[]; + allowTabloSelection?: boolean; + initialDueDate?: Date; +} +``` + +The hooks are already used within TaskModal, so the simplest approach is to keep `@xtablo/tablo-views` depending on the same hooks the main app uses. Since hooks like `useCreateTask`, `useTabloMembers` etc. are in `apps/main/src/hooks/`, they need to either: +1. Move to `@xtablo/shared/hooks/` (if they're pure React Query wrappers around API calls), OR +2. Stay in `apps/main` and be passed as props/callbacks + +The decision depends on whether these hooks have dependencies on app-specific context (like `UserStoreProvider`). Check each hook — if it only uses `useSession` and API calls, move it to `@xtablo/shared`. If it uses `useUser()` from `UserStoreProvider`, keep it in the app and pass data as props. + +- [ ] **Step 2: Move GanttChart** + +Copy `apps/main/src/components/gantt/GanttChart.tsx` to `packages/tablo-views/src/components/gantt/GanttChart.tsx`. + +Update the `LoadingSpinner` import. If it comes from `@ui/components/LoadingSpinner` (a local alias in apps/main), change to the full path or use a simple inline spinner. + +- [ ] **Step 3: Move section components** + +For each section component (`TabloTasksSection`, `TabloFilesSection`, `TabloDiscussionSection`, `TabloEventsSection`, `TabloHeaderActions`, `ChatMessages`): + +1. Copy the file to `packages/tablo-views/src/` +2. Update local imports to either: + - Use `@xtablo/shared/hooks/*` if the hook exists there + - Use relative imports within `packages/tablo-views/` for co-located files (e.g., `./ChatMessages`, `./components/kanban/KanbanBoard`) +3. Replace `@ui/components/LoadingSpinner` with `@xtablo/ui/components/loading-spinner` or equivalent + +Key import changes per file: + +**TabloTasksSection.tsx:** +- `../hooks/tablos` -> check if available in `@xtablo/shared/hooks/tablos` +- `../hooks/tasks` -> check if available in `@xtablo/shared/hooks/tasks` +- `./kanban/KanbanBoard` -> `./components/kanban/KanbanBoard` +- `./kanban/TaskModal` -> `./components/kanban/TaskModal` +- `./TabloHeaderActions` -> `./TabloHeaderActions` + +**TabloFilesSection.tsx:** +- `../hooks/tablo_data` -> check if in `@xtablo/shared` +- `../hooks/tablo_folders` -> check if in `@xtablo/shared` +- `../providers/UserStoreProvider` -> This is app-specific. The `useIsReadOnlyUser` and `useUser` hooks depend on Zustand store from `apps/main`. Solution: accept `isReadOnly: boolean` and `currentUser` as props instead. + +**TabloDiscussionSection.tsx:** +- `../hooks/useChat` -> `./hooks/useChat` +- `../hooks/tablos` -> check availability +- `../providers/UserStoreProvider` -> accept `currentUser` as prop +- `./ChatMessages` -> `./ChatMessages` + +**TabloEventsSection.tsx:** +- `../hooks/events` -> check availability +- `../providers/UserStoreProvider` -> accept `isReadOnly` as prop +- `./TabloHeaderActions` -> `./TabloHeaderActions` + +- [ ] **Step 4: Extract EtapesSection from tablo-details.tsx** + +Create `packages/tablo-views/src/EtapesSection.tsx` with the content from lines 950-1288 of `tablo-details.tsx`. Add the necessary imports at the top: + +```typescript +import { cn } from "@xtablo/shared"; +import type { Etape, KanbanTask } from "@xtablo/shared-types"; +import { Button } from "@xtablo/ui/components/button"; +import { Input } from "@xtablo/ui/components/input"; +import { + CalendarIcon, + ChevronDownIcon, + ChevronRightIcon, + CircleCheckIcon, + PlusIcon, +} from "lucide-react"; +import { useState } from "react"; +``` + +The hooks `useCreateTask` and `useCreateEtape` need to be available. If they're in `apps/main/src/hooks/tasks.ts`, accept callbacks as props: + +```typescript +interface EtapesSectionProps { + etapes: Etape[]; + tabloTasks: KanbanTask[]; + tabloId: string; + isAdmin: boolean; + onCreateTask: (task: { tablo_id: string; title: string; status: string; parent_task_id: string; is_parent: boolean; position: number }) => void; + onCreateEtape: (params: { tabloId: string; title: string; position: number }) => Promise; + isCreatingEtape?: boolean; +} +``` + +- [ ] **Step 5: Extract RoadmapSection from tablo-details.tsx** + +Create `packages/tablo-views/src/RoadmapSection.tsx`: + +```typescript +import type { Etape, KanbanTask } from "@xtablo/shared-types"; +import { GanttChart } from "./components/gantt/GanttChart"; + +interface RoadmapSectionProps { + etapes: Etape[]; + tabloTasks: KanbanTask[]; + onDateClick: (date: Date) => void; + onTaskStatusChange: (taskId: string, status: string) => void; +} + +export function RoadmapSection({ + tabloTasks, + onDateClick, + onTaskStatusChange, +}: RoadmapSectionProps) { + return ( + + ); +} +``` + +- [ ] **Step 6: Delete moved files from `apps/main`** + +Remove the original files from `apps/main` that were moved. Do NOT delete files that are still needed by other parts of `apps/main` (e.g., `ClickOutside`, `ImageColorPicker` used by `TabloHeaderActions` — move those too or keep them and import from the new location). + +- [ ] **Step 7: Run typecheck** + +Run: `pnpm typecheck` +Expected: No errors. Fix any broken imports. + +- [ ] **Step 8: Commit** + +```bash +git add packages/tablo-views/src/ apps/main/src/ +git commit -m "refactor: move tablo view components to packages/tablo-views" +``` + +--- + +## Task 6: Update `apps/main` to Import from `packages/tablo-views` + +**Files:** +- Modify: `apps/main/package.json` +- Modify: `apps/main/src/pages/tablo-details.tsx` +- Modify: `apps/main/src/pages/chat.tsx` (if it imports useChat or ChatMessages) + +- [ ] **Step 1: Add `@xtablo/tablo-views` dependency to `apps/main`** + +In `apps/main/package.json`, add to dependencies: +```json +"@xtablo/tablo-views": "workspace:*" +``` + +- [ ] **Step 2: Update imports in `tablo-details.tsx`** + +Replace the local imports with package imports: + +From: +```typescript +import { GanttChart } from "../components/gantt/GanttChart"; +import { TaskModal } from "../components/kanban/TaskModal"; +import { TabloDiscussionSection } from "../components/TabloDiscussionSection"; +import { TabloEventsSection } from "../components/TabloEventsSection"; +import { TabloFilesSection } from "../components/TabloFilesSection"; +import { TabloTasksSection } from "../components/TabloTasksSection"; +import { useChatUnread } from "../hooks/useChatUnread"; +``` + +To: +```typescript +import { + TabloDiscussionSection, + TabloEventsSection, + TabloFilesSection, + TabloTasksSection, + EtapesSection, + RoadmapSection, + TaskModal, + useChatUnread, +} from "@xtablo/tablo-views"; +``` + +Remove the inline `EtapesSection` and `RoadmapSection` function definitions from `tablo-details.tsx` (they now live in the package). + +Update the JSX where `EtapesSection` and `RoadmapSection` are rendered to pass the new callback props (if hooks were replaced with props in Task 5). + +- [ ] **Step 3: Update chat.tsx if needed** + +If `apps/main/src/pages/chat.tsx` imports `useChat` or `ChatMessages` from local paths, update to import from `@xtablo/tablo-views`. + +- [ ] **Step 4: Run pnpm install and typecheck** + +Run: `pnpm install && pnpm typecheck` +Expected: No errors + +- [ ] **Step 5: Run dev server and verify tablo details page works** + +Run: `pnpm dev:main` +Navigate to a tablo details page. Verify all tabs render correctly: overview, etapes, tasks, files, discussion, events, roadmap. + +- [ ] **Step 6: Commit** + +```bash +git add apps/main/package.json apps/main/src/ +git commit -m "refactor: update apps/main to import tablo views from shared package" +``` + +--- + +## Task 7: Scaffold `apps/clients` + +**Files:** +- Create: all files under `apps/clients/` +- Modify: `package.json` (root) — add `dev:clients` script + +- [ ] **Step 1: Create `apps/clients/package.json`** + +```json +{ + "name": "@xtablo/clients", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite dev --port 5175", + "build": "tsc -b && vite build --mode production", + "build:staging": "tsc -b && vite build --mode staging", + "build:prod": "tsc -b && vite build --mode production", + "deploy": "wrangler deploy", + "typecheck": "tsc -b", + "lint": "biome check .", + "lint:fix": "biome check --write .", + "format": "biome format --write .", + "preview": "vite preview", + "clean": "rm -rf dist .vite tsconfig.tsbuildinfo node_modules/.vite" + }, + "devDependencies": { + "@biomejs/biome": "2.2.5", + "@cloudflare/vite-plugin": "^1.9.4", + "@tailwindcss/vite": "^4.0.14", + "@types/react": "19.0.10", + "@types/react-dom": "19.0.4", + "@vitejs/plugin-react": "^4.3.4", + "tailwindcss": "^4.0.14", + "tw-animate-css": "^1.4.0", + "typescript": "^5.7.0", + "vite": "^6.2.2", + "vite-tsconfig-paths": "^5.1.4", + "wrangler": "^4.24.3" + }, + "dependencies": { + "@tanstack/react-query": "^5.69.0", + "@xtablo/shared": "workspace:*", + "@xtablo/shared-types": "workspace:*", + "@xtablo/tablo-views": "workspace:*", + "@xtablo/ui": "workspace:*", + "@xtablo/chat-ui": "workspace:*", + "i18next": "^25.6.0", + "i18next-browser-languagedetector": "^8.2.0", + "lucide-react": "^0.460.0", + "react": "19.0.0", + "react-dom": "19.0.0", + "react-i18next": "^16.2.0", + "react-router-dom": "^7.9.4", + "tailwind-merge": "^3.0.2", + "zustand": "^5.0.5" + } +} +``` + +- [ ] **Step 2: Create `apps/clients/vite.config.ts`** + +```typescript +import { cloudflare } from "@cloudflare/vite-plugin"; +import tailwindcss from "@tailwindcss/vite"; +import react from "@vitejs/plugin-react"; +import { defineConfig, type PluginOption } from "vite"; +import tsconfigPaths from "vite-tsconfig-paths"; + +export default defineConfig(({ mode }) => { + const plugins: PluginOption[] = [ + react(), + tailwindcss(), + tsconfigPaths(), + ]; + + if (mode !== "test" && process.env.VITEST !== "true") { + plugins.push(cloudflare()); + } + + return { + plugins, + server: { + cors: false, + }, + }; +}); +``` + +- [ ] **Step 3: Create `apps/clients/wrangler.toml`** + +```toml +name = "xtablo-clients" +main = "worker/index.ts" +compatibility_date = "2025-07-09" + +[assets] +directory = "./dist/" +not_found_handling = "single-page-application" + +[observability] +enabled = true + +[env.staging] +route = { pattern = "clients-staging.xtablo.com", custom_domain = true } + +[env.production] +route = { pattern = "clients.xtablo.com", custom_domain = true } +``` + +- [ ] **Step 4: Create `apps/clients/worker/index.ts`** + +```typescript +export default { + fetch(request: Request) { + const url = new URL(request.url); + + if (url.pathname.startsWith("/api/")) { + return Response.json({ name: "Cloudflare" }); + } + return new Response(null, { status: 404 }); + }, +}; +``` + +- [ ] **Step 5: Create `apps/clients/tsconfig.json`** + +```json +{ + "compilerOptions": { + "target": "ES2020", + "useDefineForClassFields": true, + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "module": "ESNext", + "skipLibCheck": true, + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "jsx": "react-jsx", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "baseUrl": ".", + "paths": { + "@xtablo/ui": ["../../packages/ui/src"], + "@xtablo/ui/*": ["../../packages/ui/src/*"], + "@xtablo/shared": ["../../packages/shared/src"], + "@xtablo/shared/*": ["../../packages/shared/src/*"], + "@xtablo/tablo-views": ["../../packages/tablo-views/src"], + "@xtablo/tablo-views/*": ["../../packages/tablo-views/src/*"] + } + }, + "include": ["src"], + "references": [] +} +``` + +- [ ] **Step 6: Create `apps/clients/index.html`** + +```html + + + + + + Xtablo — Client Portal + + +
+ + + +``` + +- [ ] **Step 7: Create `apps/clients/src/main.css`** + +Copy from `apps/external/src/main.css` (or `apps/main/src/main.css` if it has Tailwind imports). At minimum: + +```css +@import "tailwindcss"; +@import "tw-animate-css"; +@import "@xtablo/ui/styles/globals.css"; +``` + +- [ ] **Step 8: Create `apps/clients/src/i18n.ts`** + +Copy from `apps/external/src/i18n.ts` — same i18next setup with browser language detection. + +- [ ] **Step 9: Create `apps/clients/src/main.tsx`** + +```typescript +import { QueryClientProvider } from "@tanstack/react-query"; +import { queryClient } from "@xtablo/shared"; +import { SessionProvider } from "@xtablo/shared/contexts/SessionContext"; +import { ThemeProvider } from "@xtablo/shared/contexts/ThemeContext"; +import { Toaster } from "@xtablo/ui/components/sonner"; +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import { BrowserRouter as Router } from "react-router-dom"; +import App from "./App"; + +import "@xtablo/ui/styles/globals.css"; +import "./main.css"; +import "./i18n"; + +createRoot(document.getElementById("client-root")!).render( + + + + + + + + + + + + +); +``` + +- [ ] **Step 10: Create `apps/clients/src/App.tsx`** + +```typescript +import AppRoutes from "./routes"; + +export default function App() { + return ( +
+ +
+ ); +} +``` + +- [ ] **Step 11: Create `apps/clients/src/routes.tsx`** + +```typescript +import { Route, Routes } from "react-router-dom"; +import { ClientLayout } from "./components/ClientLayout"; +import { AuthCallback } from "./pages/AuthCallback"; +import { ClientTabloPage } from "./pages/ClientTabloPage"; +import { ClientTabloListPage } from "./pages/ClientTabloListPage"; + +export default function AppRoutes() { + return ( + + } /> + }> + } /> + } /> + + + ); +} +``` + +- [ ] **Step 12: Add `dev:clients` script to root `package.json`** + +Add to the `scripts` section of the root `package.json`: +```json +"dev:clients": "turbo dev --filter=@xtablo/clients" +``` + +- [ ] **Step 13: Run pnpm install** + +Run: `pnpm install` + +- [ ] **Step 14: Commit** + +```bash +git add apps/clients/ package.json +git commit -m "feat: scaffold apps/clients Cloudflare Worker app" +``` + +--- + +## Task 8: Build `apps/clients` Pages and Layout + +**Files:** +- Create: `apps/clients/src/components/ClientLayout.tsx` +- Create: `apps/clients/src/pages/AuthCallback.tsx` +- Create: `apps/clients/src/pages/ClientTabloPage.tsx` +- Create: `apps/clients/src/pages/ClientTabloListPage.tsx` + +- [ ] **Step 1: Create `ClientLayout.tsx`** + +```typescript +import { useSession } from "@xtablo/shared/contexts/SessionContext"; +import { Avatar, AvatarFallback } from "@xtablo/ui/components/avatar"; +import { Button } from "@xtablo/ui/components/button"; +import { LogOut } from "lucide-react"; +import { Outlet, useNavigate } from "react-router-dom"; +import { supabase } from "@xtablo/shared/lib/supabase"; + +export function ClientLayout() { + const { session } = useSession(); + const navigate = useNavigate(); + + const handleLogout = async () => { + await supabase.auth.signOut(); + navigate("/auth/callback"); + }; + + if (!session) { + return ( +
+

+ Your session has expired. Please use the link sent to your email to access this portal. +

+
+ ); + } + + const userEmail = session.user.email ?? ""; + const initials = userEmail.substring(0, 2).toUpperCase(); + + return ( +
+
+
+ Xtablo +
+
+ + {initials} + + {userEmail} + +
+
+
+ +
+
+ ); +} +``` + +- [ ] **Step 2: Create `AuthCallback.tsx`** + +```typescript +import { useSession } from "@xtablo/shared/contexts/SessionContext"; +import { useEffect, useState } from "react"; +import { useNavigate, useSearchParams } from "react-router-dom"; +import { supabase } from "@xtablo/shared/lib/supabase"; + +export function AuthCallback() { + const [searchParams] = useSearchParams(); + const { session } = useSession(); + const navigate = useNavigate(); + const [error, setError] = useState(null); + + const inviteToken = searchParams.get("token"); + + useEffect(() => { + if (!session || !inviteToken) return; + + const acceptInvite = async () => { + const apiBase = import.meta.env.VITE_API_URL as string; + const res = await fetch(`${apiBase}/api/v1/client-invites/accept/${inviteToken}`, { + method: "POST", + headers: { + Authorization: `Bearer ${session.access_token}`, + "Content-Type": "application/json", + }, + }); + + if (!res.ok) { + const body = await res.json(); + setError(body.error ?? "Failed to accept invite"); + return; + } + + const { tabloId } = await res.json(); + navigate(`/tablo/${tabloId}`, { replace: true }); + }; + + acceptInvite(); + }, [session, inviteToken, navigate]); + + if (error) { + return ( +
+
+

{error}

+

+ Please contact the person who invited you for a new link. +

+
+
+ ); + } + + return ( +
+

Authenticating...

+
+ ); +} +``` + +- [ ] **Step 3: Create `ClientTabloPage.tsx`** + +```typescript +import { useQuery } from "@tanstack/react-query"; +import { useSession } from "@xtablo/shared/contexts/SessionContext"; +import { api } from "@xtablo/shared/lib/api"; +import type { UserTablo } from "@xtablo/shared/types/tablos.types"; +import { + TabloDiscussionSection, + TabloEventsSection, + TabloFilesSection, + TabloTasksSection, + EtapesSection, + RoadmapSection, +} from "@xtablo/tablo-views"; +import { + CalendarIcon, + FolderIcon, + KanbanIcon, + LayoutDashboardIcon, + ListChecksIcon, + MapIcon, + MessageCircleIcon, +} from "lucide-react"; +import { useState } from "react"; +import { useParams, useSearchParams } from "react-router-dom"; + +type TabSection = "overview" | "etapes" | "tasks" | "files" | "discussion" | "events" | "roadmap"; + +const TABS: { id: TabSection; label: string; icon: React.ElementType }[] = [ + { id: "overview", label: "Overview", icon: LayoutDashboardIcon }, + { id: "etapes", label: "Stages", icon: ListChecksIcon }, + { id: "tasks", label: "Tasks", icon: KanbanIcon }, + { id: "files", label: "Files", icon: FolderIcon }, + { id: "discussion", label: "Discussion", icon: MessageCircleIcon }, + { id: "events", label: "Events", icon: CalendarIcon }, + { id: "roadmap", label: "Roadmap", icon: MapIcon }, +]; + +export function ClientTabloPage() { + const { tabloId } = useParams<{ tabloId: string }>(); + const [searchParams, setSearchParams] = useSearchParams(); + const { session } = useSession(); + + const sectionParam = searchParams.get("section") as TabSection | null; + const activeSection: TabSection = + sectionParam && TABS.some((t) => t.id === sectionParam) ? sectionParam : "overview"; + + // Fetch tablo details via API + const { data: tablo, isLoading } = useQuery({ + queryKey: ["tablos", tabloId], + queryFn: async () => { + const res = await api.get(`/api/v1/tablos/${tabloId}`, { + headers: { Authorization: `Bearer ${session?.access_token}` }, + }); + return res.data; + }, + enabled: !!tabloId && !!session, + }); + + if (isLoading) { + return ( +
+

Loading...

+
+ ); + } + + if (!tablo) return null; + + return ( +
+ {/* Tablo header */} +
+

{tablo.name}

+ {tablo.description && ( +

{tablo.description}

+ )} +
+ + {/* Tab navigation */} +
+ {TABS.map((tab) => { + const Icon = tab.icon; + const isActive = activeSection === tab.id; + return ( + + ); + })} +
+ + {/* Tab content */} +
+ {activeSection === "tasks" && ( + + )} + {activeSection === "files" && ( + + )} + {activeSection === "discussion" && ( + + )} + {activeSection === "events" && ( + + )} + {/* etapes, roadmap, overview sections rendered similarly */} +
+
+ ); +} +``` + +Adapt the props to match whatever interface the extracted components expose after Task 5. The key difference from `apps/main` is: `isAdmin` is always `false`, and no share/invite/delete UI is rendered. + +- [ ] **Step 4: Create `ClientTabloListPage.tsx`** + +```typescript +import { useQuery } from "@tanstack/react-query"; +import { useSession } from "@xtablo/shared/contexts/SessionContext"; +import { api } from "@xtablo/shared/lib/api"; +import type { UserTablo } from "@xtablo/shared/types/tablos.types"; +import { FolderIcon } from "lucide-react"; +import { Link, Navigate } from "react-router-dom"; + +export function ClientTabloListPage() { + const { session } = useSession(); + + const { data: tablos, isLoading } = useQuery({ + queryKey: ["tablos"], + queryFn: async () => { + const res = await api.get("/api/v1/tablos", { + headers: { Authorization: `Bearer ${session?.access_token}` }, + }); + return res.data; + }, + enabled: !!session, + }); + + if (isLoading) { + return ( +
+

Loading...

+
+ ); + } + + if (!tablos || tablos.length === 0) { + return ( +
+

No projects available.

+
+ ); + } + + // If only one tablo, redirect directly + if (tablos.length === 1) { + return ; + } + + return ( +
+

Your Projects

+
+ {tablos.map((tablo) => ( + + +
+

{tablo.name}

+ {tablo.description && ( +

{tablo.description}

+ )} +
+ + ))} +
+
+ ); +} +``` + +- [ ] **Step 5: Run dev server and verify** + +Run: `pnpm dev:clients` +Expected: App starts on port 5175. The auth callback page shows "Authenticating..." without a session. The list page shows "No projects available" when not authenticated. + +- [ ] **Step 6: Commit** + +```bash +git add apps/clients/src/ +git commit -m "feat(clients): add layout, auth callback, tablo page, and list page" +``` + +--- + +## Task 9: Client Invite UI in `apps/main` Share Dialog + +**Files:** +- Modify: `apps/main/src/components/TabloHeaderActions.tsx` (or wherever the share dialog lives) +- Create: `apps/main/src/hooks/client_invites.ts` + +- [ ] **Step 1: Create client invite hooks** + +Create `apps/main/src/hooks/client_invites.ts`: + +```typescript +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { useSession } from "@xtablo/shared/contexts/SessionContext"; +import { api } from "@xtablo/shared/lib/api"; +import { toast } from "@xtablo/shared"; + +export function usePendingClientInvites(tabloId: string) { + const { session } = useSession(); + + return useQuery({ + queryKey: ["client-invites", tabloId], + queryFn: async () => { + const res = await api.get(`/api/v1/client-invites/${tabloId}/pending`, { + headers: { Authorization: `Bearer ${session?.access_token}` }, + }); + return res.data.invites as { + id: number; + invited_email: string; + expires_at: string; + is_pending: boolean; + created_at: string; + }[]; + }, + enabled: !!tabloId && !!session, + }); +} + +export function useCreateClientInvite() { + const { session } = useSession(); + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async ({ tabloId, email }: { tabloId: string; email: string }) => { + const res = await api.post( + `/api/v1/client-invites/${tabloId}`, + { email }, + { headers: { Authorization: `Bearer ${session?.access_token}` } } + ); + return res.data; + }, + onSuccess: (_, { tabloId }) => { + queryClient.invalidateQueries({ queryKey: ["client-invites", tabloId] }); + toast.add({ title: "Client invite sent", type: "success" }, { timeout: 3000 }); + }, + onError: () => { + toast.add({ title: "Failed to send invite", type: "error" }, { timeout: 5000 }); + }, + }); +} + +export function useCancelClientInvite() { + const { session } = useSession(); + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async ({ tabloId, inviteId }: { tabloId: string; inviteId: number }) => { + const res = await api.delete(`/api/v1/client-invites/${tabloId}/${inviteId}`, { + headers: { Authorization: `Bearer ${session?.access_token}` }, + }); + return res.data; + }, + onSuccess: (_, { tabloId }) => { + queryClient.invalidateQueries({ queryKey: ["client-invites", tabloId] }); + }, + }); +} +``` + +- [ ] **Step 2: Add client invite section to the share dialog** + +In the share dialog component (either in `TabloHeaderActions.tsx` or in the share dialog in `tablo-details.tsx`), add a section below the existing invite section for client invites. This should include: + +1. A "Client Access" heading with a description +2. An email input + "Send Magic Link" button +3. A list of pending client invites with expiration dates and cancel buttons +4. An expiration warning badge when `expires_at` is less than 5 days away + +Use the hooks from step 1 (`usePendingClientInvites`, `useCreateClientInvite`, `useCancelClientInvite`). + +The exact JSX depends on the existing share dialog structure. Follow the same patterns used for the existing `pendingInvites` list. + +- [ ] **Step 3: Run typecheck and verify** + +Run: `pnpm typecheck` +Run: `pnpm dev:main` +Navigate to a tablo, open the share dialog. Verify the client invite section appears. + +- [ ] **Step 4: Commit** + +```bash +git add apps/main/src/hooks/client_invites.ts apps/main/src/components/ apps/main/src/pages/ +git commit -m "feat(main): add client invite UI to share dialog" +``` + +--- + +## Task 10: End-to-End Verification + +- [ ] **Step 1: Run full typecheck** + +Run: `pnpm typecheck` +Expected: No errors across all packages + +- [ ] **Step 2: Run all tests** + +Run: `pnpm test` +Expected: All tests pass + +- [ ] **Step 3: Run linter** + +Run: `pnpm lint` +Expected: No errors (run `pnpm lint:fix` if needed) + +- [ ] **Step 4: Verify `apps/main` dev server** + +Run: `pnpm dev:main` +- Navigate to a tablo details page +- Verify all tabs work (overview, etapes, tasks, files, discussion, events, roadmap) +- Open share dialog, verify client invite section + +- [ ] **Step 5: Verify `apps/clients` dev server** + +Run: `pnpm dev:clients` +- Verify app loads on port 5175 +- Verify auth callback page renders +- Verify tablo list page renders + +- [ ] **Step 6: Final commit if any fixes were needed** + +```bash +git add -A +git commit -m "fix: resolve typecheck and lint issues from client magic links implementation" +``` From ec9c9622aa5e29bea4157219ac8d6b2dfd06b6e3 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 08:58:10 +0200 Subject: [PATCH 04/75] feat(db): add is_client column and client_invites table --- packages/shared-types/src/database.types.ts | 51 +++++++++++++++++++ .../20260415120000_add_client_invites.sql | 40 +++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 supabase/migrations/20260415120000_add_client_invites.sql diff --git a/packages/shared-types/src/database.types.ts b/packages/shared-types/src/database.types.ts index c48c314..3ab03a5 100644 --- a/packages/shared-types/src/database.types.ts +++ b/packages/shared-types/src/database.types.ts @@ -78,6 +78,54 @@ export type Database = { }, ]; }; + client_invites: { + Row: { + created_at: string; + expires_at: string; + id: number; + invited_by: string; + invited_email: string; + invite_token: string; + is_pending: boolean; + tablo_id: string; + }; + Insert: { + created_at?: string; + expires_at?: string; + id?: number; + invited_by: string; + invited_email: string; + invite_token: string; + is_pending?: boolean; + tablo_id: string; + }; + Update: { + created_at?: string; + expires_at?: string; + id?: number; + invited_by?: string; + invited_email?: string; + invite_token?: string; + is_pending?: boolean; + tablo_id?: string; + }; + Relationships: [ + { + foreignKeyName: "client_invites_tablo_id_fkey"; + columns: ["tablo_id"]; + isOneToOne: false; + referencedRelation: "tablos"; + referencedColumns: ["id"]; + }, + { + foreignKeyName: "client_invites_invited_by_fkey"; + columns: ["invited_by"]; + isOneToOne: false; + referencedRelation: "profiles"; + referencedColumns: ["id"]; + }, + ]; + }; devis: { Row: { client_email: string; @@ -385,6 +433,7 @@ export type Database = { email: string | null; first_name: string | null; id: string; + is_client: boolean; is_temporary: boolean; last_name: string | null; last_signed_in: string | null; @@ -398,6 +447,7 @@ export type Database = { email?: string | null; first_name?: string | null; id: string; + is_client?: boolean; is_temporary?: boolean; last_name?: string | null; last_signed_in?: string | null; @@ -411,6 +461,7 @@ export type Database = { email?: string | null; first_name?: string | null; id?: string; + is_client?: boolean; is_temporary?: boolean; last_name?: string | null; last_signed_in?: string | null; diff --git a/supabase/migrations/20260415120000_add_client_invites.sql b/supabase/migrations/20260415120000_add_client_invites.sql new file mode 100644 index 0000000..7ee07fd --- /dev/null +++ b/supabase/migrations/20260415120000_add_client_invites.sql @@ -0,0 +1,40 @@ +-- Add is_client column to profiles +ALTER TABLE public.profiles + ADD COLUMN is_client boolean NOT NULL DEFAULT false; + +-- Create client_invites table +CREATE TABLE public.client_invites ( + id serial PRIMARY KEY, + tablo_id text NOT NULL REFERENCES public.tablos(id) ON DELETE CASCADE, + invited_email varchar(255) NOT NULL, + invited_by uuid NOT NULL REFERENCES public.profiles(id), + invite_token text NOT NULL, + expires_at timestamptz NOT NULL DEFAULT (now() + interval '30 days'), + is_pending boolean NOT NULL DEFAULT true, + created_at timestamptz NOT NULL DEFAULT now() +); + +-- Index for token lookups +CREATE UNIQUE INDEX idx_client_invites_token ON public.client_invites(invite_token); + +-- Index for listing invites by tablo +CREATE INDEX idx_client_invites_tablo ON public.client_invites(tablo_id, is_pending); + +-- RLS +ALTER TABLE public.client_invites ENABLE ROW LEVEL SECURITY; + +-- Admins can manage invites they created +CREATE POLICY "Admins can manage their client invites" + ON public.client_invites + FOR ALL + USING (invited_by = auth.uid()); + +-- Client users can read invites sent to their email +CREATE POLICY "Clients can read their own invites" + ON public.client_invites + FOR SELECT + USING ( + invited_email = ( + SELECT email FROM auth.users WHERE id = auth.uid() + ) + ); From 9e75f9b78d251bc463f0021a1aec9389dcfa11e5 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 09:00:33 +0200 Subject: [PATCH 05/75] feat: scaffold packages/tablo-views package --- packages/tablo-views/package.json | 40 ++++++++++++++++++++++++++++++ packages/tablo-views/src/index.ts | 21 ++++++++++++++++ packages/tablo-views/tsconfig.json | 27 ++++++++++++++++++++ 3 files changed, 88 insertions(+) create mode 100644 packages/tablo-views/package.json create mode 100644 packages/tablo-views/src/index.ts create mode 100644 packages/tablo-views/tsconfig.json diff --git a/packages/tablo-views/package.json b/packages/tablo-views/package.json new file mode 100644 index 0000000..464a36f --- /dev/null +++ b/packages/tablo-views/package.json @@ -0,0 +1,40 @@ +{ + "name": "@xtablo/tablo-views", + "version": "0.0.0", + "private": true, + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": "./src/index.ts", + "./components/*": "./src/components/*.tsx", + "./hooks/*": "./src/hooks/*.ts", + "./*": "./src/*.tsx" + }, + "scripts": { + "lint": "biome check .", + "lint:fix": "biome check --write .", + "format": "biome format --write .", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "@tanstack/react-query": "^5.69.0", + "@xtablo/chat-ui": "workspace:*", + "@xtablo/shared": "workspace:*", + "@xtablo/shared-types": "workspace:*", + "@xtablo/ui": "workspace:*", + "date-fns": "^4.1.0", + "lucide-react": "^0.460.0", + "react": "19.0.0", + "react-dom": "19.0.0", + "react-i18next": "^16.2.0", + "react-router-dom": "^7.9.4", + "tailwind-merge": "^3.0.2" + }, + "devDependencies": { + "@biomejs/biome": "2.2.5", + "@types/react": "19.0.10", + "@types/react-dom": "19.0.4", + "typescript": "^5.7.0" + } +} diff --git a/packages/tablo-views/src/index.ts b/packages/tablo-views/src/index.ts new file mode 100644 index 0000000..c60efd7 --- /dev/null +++ b/packages/tablo-views/src/index.ts @@ -0,0 +1,21 @@ +// Section components — will be populated as components are moved from apps/main +// export { TabloTasksSection } from "./TabloTasksSection"; +// export { TabloFilesSection } from "./TabloFilesSection"; +// export { TabloDiscussionSection } from "./TabloDiscussionSection"; +// export { TabloEventsSection } from "./TabloEventsSection"; +// export { EtapesSection } from "./EtapesSection"; +// export { RoadmapSection } from "./RoadmapSection"; +// export { TabloHeaderActions } from "./TabloHeaderActions"; +// export { ChatMessages } from "./ChatMessages"; + +// Sub-components +// export { GanttChart } from "./components/gantt/GanttChart"; +// export { TaskModal } from "./components/kanban/TaskModal"; +// export { KanbanBoard } from "./components/kanban/KanbanBoard"; + +// Hooks +// export { useChat } from "./hooks/useChat"; +// export { useChatUnread } from "./hooks/useChatUnread"; + +// Types +// export type { TabloMember } from "./components/kanban/types"; diff --git a/packages/tablo-views/tsconfig.json b/packages/tablo-views/tsconfig.json new file mode 100644 index 0000000..8fc29d8 --- /dev/null +++ b/packages/tablo-views/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "target": "ES2020", + "useDefineForClassFields": true, + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "module": "ESNext", + "skipLibCheck": true, + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "jsx": "react-jsx", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "baseUrl": ".", + "paths": { + "@xtablo/ui": ["../ui/src"], + "@xtablo/ui/*": ["../ui/src/*"], + "@xtablo/shared": ["../shared/src"], + "@xtablo/shared/*": ["../shared/src/*"] + } + }, + "include": ["src"] +} From ccb66f99d8adb11d8385b97096ed784c2356c1a6 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 09:03:00 +0200 Subject: [PATCH 06/75] feat(api): add is_client check to middleware and billing --- .../api/src/__tests__/helpers/billing.test.ts | 5 ++++ .../__tests__/middlewares/middlewares.test.ts | 29 ++++++++++++++++++- apps/api/src/helpers/billing.ts | 5 ++-- apps/api/src/middlewares/middleware.ts | 4 +-- 4 files changed, 38 insertions(+), 5 deletions(-) diff --git a/apps/api/src/__tests__/helpers/billing.test.ts b/apps/api/src/__tests__/helpers/billing.test.ts index c43a874..62c0d11 100644 --- a/apps/api/src/__tests__/helpers/billing.test.ts +++ b/apps/api/src/__tests__/helpers/billing.test.ts @@ -28,12 +28,14 @@ describe("billing helpers", () => { id: "owner-user", created_at: "2026-01-01T10:00:00.000Z", is_temporary: false, + is_client: false, plan: "annual", }, { id: "late-user", created_at: "2026-01-02T10:00:00.000Z", is_temporary: false, + is_client: false, plan: "solo", }, ]); @@ -47,18 +49,21 @@ describe("billing helpers", () => { id: "user-1", created_at: "2026-01-01T10:00:00.000Z", is_temporary: false, + is_client: false, plan: "solo", }, { id: "temp-1", created_at: "2026-01-02T10:00:00.000Z", is_temporary: true, + is_client: false, plan: "solo", }, { id: "user-2", created_at: "2026-01-03T10:00:00.000Z", is_temporary: null, + is_client: false, plan: "team", }, ]); diff --git a/apps/api/src/__tests__/middlewares/middlewares.test.ts b/apps/api/src/__tests__/middlewares/middlewares.test.ts index 489506f..52a9b20 100644 --- a/apps/api/src/__tests__/middlewares/middlewares.test.ts +++ b/apps/api/src/__tests__/middlewares/middlewares.test.ts @@ -12,7 +12,7 @@ describe("Middleware Tests", () => { const middlewareManager = MiddlewareManager.getInstance(); const createProfilesSupabaseMock = (result: { - data: { is_temporary: boolean } | null; + data: { is_temporary?: boolean; is_client?: boolean } | null; error: { message: string } | null; }) => ({ from: vi.fn().mockReturnValue({ @@ -342,6 +342,33 @@ describe("Middleware Tests", () => { expect(res.status).toBe(401); expect(data.error).toBe("User is read only"); }); + + it("should return 401 for client users", async () => { + const app = new Hono(); + app.use(async (c, next) => { + // biome-ignore lint/suspicious/noExplicitAny: Test-only context injection + (c as any).set( + "supabase", + createProfilesSupabaseMock({ + data: { is_temporary: false, is_client: true }, + error: null, + }) as any + ); + // biome-ignore lint/suspicious/noExplicitAny: Test-only context injection + (c as any).set("user", { id: "client-user" } as any); + await next(); + }); + app.use(middlewareManager.regularUserCheck); + app.get("/test", (c) => c.json({ success: true })); + + // biome-ignore lint/suspicious/noExplicitAny: testClient requires any for dynamic route access + const client = testClient(app) as any; + const res = await client.test.$get(); + const data = await res.json(); + + expect(res.status).toBe(401); + expect(data.error).toBe("User is read only"); + }); }); describe("Billing Checkout Access Middleware", () => { diff --git a/apps/api/src/helpers/billing.ts b/apps/api/src/helpers/billing.ts index 0e043d4..e0e10da 100644 --- a/apps/api/src/helpers/billing.ts +++ b/apps/api/src/helpers/billing.ts @@ -7,6 +7,7 @@ type BillingProfileRow = { id: string; created_at: string | null; is_temporary: boolean | null; + is_client: boolean | null; plan: string | null; }; @@ -87,7 +88,7 @@ export const parseTrialRolloutDate = ( export const getOrganizationOwner = (profiles: BillingProfileRow[]) => profiles[0] ?? null; export const getBillableMemberCount = (profiles: BillingProfileRow[]) => - profiles.filter((profile) => profile.is_temporary !== true).length; + profiles.filter((profile) => profile.is_temporary !== true && profile.is_client !== true).length; export const getTrialWindow = (input: { ownerCreatedAt: Date; @@ -179,7 +180,7 @@ const getPlanHint = (price: StripePriceRow | undefined, product: StripeProductRo const getOrganizationProfiles = async (supabase: SupabaseClient, organizationId: number) => { const { data, error } = await supabase .from("profiles") - .select("id, created_at, is_temporary, plan") + .select("id, created_at, is_temporary, is_client, plan") .eq("organization_id", organizationId) .order("created_at", { ascending: true }); diff --git a/apps/api/src/middlewares/middleware.ts b/apps/api/src/middlewares/middleware.ts index 773a20b..7c153e6 100644 --- a/apps/api/src/middlewares/middleware.ts +++ b/apps/api/src/middlewares/middleware.ts @@ -84,7 +84,7 @@ export class MiddlewareManager { const { data: profile, error } = await supabase .from("profiles") - .select("is_temporary") + .select("is_temporary, is_client") .eq("id", user.id) .single(); @@ -92,7 +92,7 @@ export class MiddlewareManager { return c.json({ error: error?.message ?? "Profile not found" }, 500); } - if (!allowTemporaryUsers && profile.is_temporary) { + if ((!allowTemporaryUsers && profile.is_temporary) || profile.is_client) { return c.json({ error: "User is read only" }, 401); } From e10145d991231454c8b95e38aea146e3be7f2903 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 09:22:11 +0200 Subject: [PATCH 07/75] feat(api): add client invite endpoints with magic link flow Adds createClientUser helper, POST/GET/DELETE /client-invites routes, and mounts the router at /client-invites in authRouter. Co-Authored-By: Claude Opus 4.6 (1M context) --- .../__tests__/routes/clientInvites.test.ts | 386 ++++++++++++++++++ apps/api/src/helpers/helpers.ts | 65 +++ apps/api/src/routers/authRouter.ts | 2 + apps/api/src/routers/clientInvites.ts | 223 ++++++++++ 4 files changed, 676 insertions(+) create mode 100644 apps/api/src/__tests__/routes/clientInvites.test.ts create mode 100644 apps/api/src/routers/clientInvites.ts diff --git a/apps/api/src/__tests__/routes/clientInvites.test.ts b/apps/api/src/__tests__/routes/clientInvites.test.ts new file mode 100644 index 0000000..6b7cb25 --- /dev/null +++ b/apps/api/src/__tests__/routes/clientInvites.test.ts @@ -0,0 +1,386 @@ +import { createClient } from "@supabase/supabase-js"; +import { testClient } from "hono/testing"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { createConfig } from "../../config.js"; +import { MiddlewareManager } from "../../middlewares/middleware.js"; +import { getMainRouter } from "../../routers/index.js"; +import type { TestUserData } from "../helpers/dbSetup.js"; +import { getTestUser } from "../helpers/dbSetup.js"; + +// Mock nodemailer +const mockSendMail = vi.fn(); +vi.mock("nodemailer", () => ({ + default: { + createTransport: vi.fn(() => ({ + sendMail: mockSendMail, + })), + }, + createTransport: vi.fn(() => ({ + sendMail: mockSendMail, + })), +})); + +describe("Client Invites Endpoints", () => { + const config = createConfig(); + MiddlewareManager.initialize(config); + const app = getMainRouter(config); + // biome-ignore lint/suspicious/noExplicitAny: testClient requires any for dynamic route access + const client = testClient(app) as any; + + const ownerUser = getTestUser("owner"); + const tempUser = getTestUser("temp"); + + const supabaseAdmin = createClient(config.SUPABASE_URL, config.SUPABASE_SERVICE_ROLE_KEY, { + auth: { persistSession: false }, + }); + + // The owner has admin access to this tablo (created via TEST_TABLOS with owner_key: "owner") + const adminTabloId = "test_tablo_owner_private"; + + beforeEach(() => { + vi.clearAllMocks(); + mockSendMail.mockResolvedValue({ messageId: "test-message-id" }); + }); + + // ─── Helpers ──────────────────────────────────────────────────────────────── + + const postInvite = (user: TestUserData, tabloId: string, email: string) => + client["client-invites"][":tabloId"].$post( + { param: { tabloId }, json: { email } }, + { headers: { Authorization: `Bearer ${user.accessToken}` } } + ); + + const getPending = (user: TestUserData, tabloId: string) => + client["client-invites"][":tabloId"].pending.$get( + { param: { tabloId } }, + { headers: { Authorization: `Bearer ${user.accessToken}` } } + ); + + const deleteInvite = (user: TestUserData, tabloId: string, inviteId: number) => + client["client-invites"][":tabloId"][":inviteId"].$delete( + { param: { tabloId, inviteId: String(inviteId) } }, + { headers: { Authorization: `Bearer ${user.accessToken}` } } + ); + + const acceptInvite = (user: TestUserData, token: string) => + client["client-invites"].accept[":token"].$post( + { param: { token } }, + { headers: { Authorization: `Bearer ${user.accessToken}` } } + ); + + // ─── Helper: insert a client_invite row directly via admin ────────────────── + + const insertClientInvite = async (opts: { + tabloId: string; + invitedEmail: string; + invitedBy: string; + token: string; + isPending?: boolean; + expiresAt?: string; + }) => { + const expiresAt = opts.expiresAt ?? new Date(Date.now() + 72 * 60 * 60 * 1000).toISOString(); + + const { data, error } = await supabaseAdmin + .from("client_invites") + .insert({ + tablo_id: opts.tabloId, + invited_email: opts.invitedEmail, + invited_by: opts.invitedBy, + invite_token: opts.token, + is_pending: opts.isPending ?? true, + expires_at: expiresAt, + }) + .select("id") + .single(); + + if (error) throw new Error(`Failed to insert client_invite: ${error.message}`); + return data.id as number; + }; + + // ─── Cleanup helper ────────────────────────────────────────────────────────── + + const cleanupInvitesByEmail = async (email: string) => { + await supabaseAdmin.from("client_invites").delete().eq("invited_email", email); + // Also clean up any client user that may have been created + const { data: usersData } = await supabaseAdmin.auth.admin.listUsers(); + // biome-ignore lint/suspicious/noExplicitAny: admin.listUsers returns typed data at runtime + const users = usersData as any; + // biome-ignore lint/suspicious/noExplicitAny: admin user type + const clientUser = users?.users?.find((u: any) => u.email === email); + if (clientUser) { + await supabaseAdmin.from("tablo_access").delete().eq("user_id", clientUser.id); + await supabaseAdmin.auth.admin.deleteUser(clientUser.id); + } + }; + + // ════════════════════════════════════════════════════════════════════════════ + // POST /:tabloId — Create client invite + // ════════════════════════════════════════════════════════════════════════════ + + describe("POST /client-invites/:tabloId", () => { + const testEmail = "test_client_invite_new@example.com"; + + beforeEach(async () => { + await cleanupInvitesByEmail(testEmail); + }); + + it("should create a client invite for a valid email (admin)", async () => { + const res = await postInvite(ownerUser, adminTabloId, testEmail); + + expect(res.status).toBe(200); + const data = await res.json(); + expect(data.success).toBe(true); + + // Verify row was inserted + const { data: invite } = await supabaseAdmin + .from("client_invites") + .select("id, invited_email, is_pending") + .eq("tablo_id", adminTabloId) + .eq("invited_email", testEmail) + .single(); + + expect(invite).toBeDefined(); + expect(invite?.is_pending).toBe(true); + }); + + it("should reject non-admin users with 403", async () => { + // tempUser is NOT admin of adminTabloId (owner user owns it) + const res = await postInvite(tempUser, adminTabloId, testEmail); + expect(res.status).toBe(403); + }); + + it("should return 400 for an invalid email", async () => { + const res = await postInvite(ownerUser, adminTabloId, "not-an-email"); + expect(res.status).toBe(400); + const data = await res.json(); + expect(data.error).toContain("valid email"); + }); + + it("should return 400 for a missing email", async () => { + const res = client["client-invites"][":tabloId"].$post( + { param: { tabloId: adminTabloId }, json: {} }, + { headers: { Authorization: `Bearer ${ownerUser.accessToken}` } } + ); + expect((await res).status).toBe(400); + }); + + it("should return 401 for unauthenticated requests", async () => { + const res = await client["client-invites"][":tabloId"].$post({ + param: { tabloId: adminTabloId }, + json: { email: testEmail }, + }); + expect(res.status).toBe(401); + }); + }); + + // ════════════════════════════════════════════════════════════════════════════ + // POST /accept/:token — Accept a client invite + // ════════════════════════════════════════════════════════════════════════════ + + describe("POST /client-invites/accept/:token", () => { + it("should accept an invite and return tabloId", async () => { + const token = `test_accept_valid_${Date.now()}`; + + // Insert invite for the owner user's email + await insertClientInvite({ + tabloId: adminTabloId, + invitedEmail: ownerUser.email, + invitedBy: ownerUser.userId, + token, + }); + + try { + const res = await acceptInvite(ownerUser, token); + expect(res.status).toBe(200); + const data = await res.json(); + expect(data.success).toBe(true); + expect(data.tabloId).toBe(adminTabloId); + + // Verify invite is now not pending + const { data: invite } = await supabaseAdmin + .from("client_invites") + .select("is_pending") + .eq("invite_token", token) + .single(); + expect(invite?.is_pending).toBe(false); + } finally { + await supabaseAdmin.from("client_invites").delete().eq("invite_token", token); + } + }); + + it("should return 410 for an expired invite", async () => { + const token = `test_expired_${Date.now()}`; + const pastDate = new Date(Date.now() - 1000).toISOString(); // already expired + + await insertClientInvite({ + tabloId: adminTabloId, + invitedEmail: ownerUser.email, + invitedBy: ownerUser.userId, + token, + expiresAt: pastDate, + }); + + try { + const res = await acceptInvite(ownerUser, token); + expect(res.status).toBe(410); + const data = await res.json(); + expect(data.error).toContain("expired"); + } finally { + await supabaseAdmin.from("client_invites").delete().eq("invite_token", token); + } + }); + + it("should return 403 when email does not match the authenticated user", async () => { + const token = `test_email_mismatch_${Date.now()}`; + + // Invite is for tempUser's email but we authenticate as ownerUser + await insertClientInvite({ + tabloId: adminTabloId, + invitedEmail: tempUser.email, + invitedBy: ownerUser.userId, + token, + }); + + try { + const res = await acceptInvite(ownerUser, token); // wrong user + expect(res.status).toBe(403); + } finally { + await supabaseAdmin.from("client_invites").delete().eq("invite_token", token); + } + }); + + it("should return 404 for a non-existent token", async () => { + const res = await acceptInvite(ownerUser, "nonexistent_token_xyz"); + expect(res.status).toBe(404); + }); + + it("should return 401 for unauthenticated requests", async () => { + const res = await client["client-invites"].accept[":token"].$post({ + param: { token: "some_token" }, + }); + expect(res.status).toBe(401); + }); + }); + + // ════════════════════════════════════════════════════════════════════════════ + // GET /:tabloId/pending — List pending client invites + // ════════════════════════════════════════════════════════════════════════════ + + describe("GET /client-invites/:tabloId/pending", () => { + const pendingEmail = "test_client_pending_list@example.com"; + let insertedId: number; + + beforeEach(async () => { + await cleanupInvitesByEmail(pendingEmail); + insertedId = await insertClientInvite({ + tabloId: adminTabloId, + invitedEmail: pendingEmail, + invitedBy: ownerUser.userId, + token: `test_pending_${Date.now()}`, + }); + }); + + it("should return pending invites for an admin", async () => { + const res = await getPending(ownerUser, adminTabloId); + expect(res.status).toBe(200); + const data = await res.json(); + expect(Array.isArray(data.invites)).toBe(true); + + const found = data.invites.find((inv: { id: number }) => inv.id === insertedId); + expect(found).toBeDefined(); + expect(found.invited_email).toBe(pendingEmail); + expect(found.is_pending).toBe(true); + }); + + it("should return 403 for a non-admin user", async () => { + const res = await getPending(tempUser, adminTabloId); + expect(res.status).toBe(403); + }); + + it("should return 401 for unauthenticated requests", async () => { + const res = await client["client-invites"][":tabloId"].pending.$get({ + param: { tabloId: adminTabloId }, + }); + expect(res.status).toBe(401); + }); + }); + + // ════════════════════════════════════════════════════════════════════════════ + // DELETE /:tabloId/:inviteId — Cancel a client invite + // ════════════════════════════════════════════════════════════════════════════ + + describe("DELETE /client-invites/:tabloId/:inviteId", () => { + const cancelEmail = "test_client_cancel@example.com"; + + beforeEach(async () => { + await cleanupInvitesByEmail(cancelEmail); + }); + + it("should cancel a pending invite and revoke client access", async () => { + // First create a client user and tablo_access entry via the API + const token = `test_cancel_${Date.now()}`; + const inviteId = await insertClientInvite({ + tabloId: adminTabloId, + invitedEmail: cancelEmail, + invitedBy: ownerUser.userId, + token, + }); + + // Create a mock profile to revoke (uses admin client to simulate client user existing) + // We'll skip verifying the user's actual auth account since we just need to test cancellation + const res = await deleteInvite(ownerUser, adminTabloId, inviteId); + expect(res.status).toBe(200); + const data = await res.json(); + expect(data.success).toBe(true); + + // Verify invite is now not pending + const { data: invite } = await supabaseAdmin + .from("client_invites") + .select("is_pending") + .eq("id", inviteId) + .single(); + expect(invite?.is_pending).toBe(false); + }); + + it("should return 403 for a non-admin user", async () => { + const token = `test_cancel_nonadmin_${Date.now()}`; + const inviteId = await insertClientInvite({ + tabloId: adminTabloId, + invitedEmail: cancelEmail, + invitedBy: ownerUser.userId, + token, + }); + + const res = await deleteInvite(tempUser, adminTabloId, inviteId); + expect(res.status).toBe(403); + }); + + it("should return 404 for a non-existent invite", async () => { + const res = await deleteInvite(ownerUser, adminTabloId, 999999); + expect(res.status).toBe(404); + }); + + it("should return 400 for an already-cancelled invite", async () => { + const token = `test_cancel_already_${Date.now()}`; + const inviteId = await insertClientInvite({ + tabloId: adminTabloId, + invitedEmail: cancelEmail, + invitedBy: ownerUser.userId, + token, + isPending: false, // already cancelled + }); + + const res = await deleteInvite(ownerUser, adminTabloId, inviteId); + expect(res.status).toBe(400); + const data = await res.json(); + expect(data.error).toContain("pending"); + }); + + it("should return 401 for unauthenticated requests", async () => { + const res = await client["client-invites"][":tabloId"][":inviteId"].$delete({ + param: { tabloId: adminTabloId, inviteId: "1" }, + }); + expect(res.status).toBe(401); + }); + }); +}); diff --git a/apps/api/src/helpers/helpers.ts b/apps/api/src/helpers/helpers.ts index 25ec729..f559288 100644 --- a/apps/api/src/helpers/helpers.ts +++ b/apps/api/src/helpers/helpers.ts @@ -363,3 +363,68 @@ export const createInvitedUser = async ( return { success: true, userId: newUser.user.id }; }; + +/** + * Creates or finds a client user, marks them as is_client, and grants tablo access. + */ +export async function createClientUser( + supabase: SupabaseClient, + recipientEmail: string, + tabloId: string, + grantedBy: string +): Promise<{ success: boolean; error?: string; userId?: string }> { + // Check if user already exists + const { data: existingUsersData } = await supabase.auth.admin.listUsers(); + // biome-ignore lint/suspicious/noExplicitAny: admin.listUsers returns typed data at runtime + const existingUsers = existingUsersData as any; + const existingUser = existingUsers?.users?.find( + // biome-ignore lint/suspicious/noExplicitAny: admin user type + (u: any) => u.email?.toLowerCase() === recipientEmail.toLowerCase() + ); + + let userId: string; + + if (existingUser) { + userId = existingUser.id; + // Mark as client if not already + await supabase + .from("profiles") + .update({ is_client: true }) + .eq("id", userId) + .eq("is_client", false); + } else { + // Create new auth user (no password — magic link only) + const { data: authData, error: authError } = await supabase.auth.admin.createUser({ + email: recipientEmail, + email_confirm: true, + user_metadata: { role: "client" }, + }); + if (authError || !authData?.user) { + return { success: false, error: authError?.message ?? "Failed to create user" }; + } + userId = authData.user.id; + await supabase.from("profiles").update({ is_client: true }).eq("id", userId); + } + + // Grant tablo access if not already granted + const { data: existingAccess } = await supabase + .from("tablo_access") + .select("id, is_active") + .eq("tablo_id", tabloId) + .eq("user_id", userId) + .single(); + + if (!existingAccess) { + await supabase.from("tablo_access").insert({ + tablo_id: tabloId, + user_id: userId, + granted_by: grantedBy, + is_admin: false, + is_active: true, + }); + } else if (!existingAccess.is_active) { + await supabase.from("tablo_access").update({ is_active: true }).eq("id", existingAccess.id); + } + + return { success: true, userId }; +} diff --git a/apps/api/src/routers/authRouter.ts b/apps/api/src/routers/authRouter.ts index 41f2c53..4c308b8 100644 --- a/apps/api/src/routers/authRouter.ts +++ b/apps/api/src/routers/authRouter.ts @@ -1,6 +1,7 @@ import { Hono } from "hono"; import type { AppConfig } from "../config.js"; import { MiddlewareManager } from "../middlewares/middleware.js"; +import { getClientInvitesRouter } from "./clientInvites.js"; import { getNotesRouter } from "./notes.js"; import { getStripeRouter } from "./stripe.js"; import { getTabloRouter } from "./tablo.js"; @@ -19,6 +20,7 @@ export const getAuthenticatedRouter = (config: AppConfig) => { authRouter.route("/tablos", getTabloRouter(config)); authRouter.route("/tablo-data", getTabloDataRouter()); authRouter.route("/notes", getNotesRouter()); + authRouter.route("/client-invites", getClientInvitesRouter()); // stripe routes authRouter.route("/stripe", getStripeRouter(config)); diff --git a/apps/api/src/routers/clientInvites.ts b/apps/api/src/routers/clientInvites.ts new file mode 100644 index 0000000..c93f7c0 --- /dev/null +++ b/apps/api/src/routers/clientInvites.ts @@ -0,0 +1,223 @@ +import { Hono } from "hono"; +import { createFactory } from "hono/factory"; +import { checkTabloAdmin, createClientUser } from "../helpers/helpers.js"; +import { generateToken } from "../helpers/token.js"; +import { MiddlewareManager } from "../middlewares/middleware.js"; +import type { AuthEnv } from "../types/app.types.js"; + +const factory = createFactory(); + +const CLIENT_INVITE_EXPIRY_HOURS = 72; + +/** POST /:tabloId — Create a client invite (admin only) */ +const createClientInvite = (middlewareManager: ReturnType) => + factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { + const user = c.get("user"); + const supabase = c.get("supabase"); + const tabloId = c.req.param("tabloId"); + + const body = await c.req.json(); + const rawEmail = String(body.email || "") + .trim() + .toLowerCase(); + + if (!rawEmail || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(rawEmail)) { + return c.json({ error: "A valid email is required" }, 400); + } + + // Create / find the client user and grant tablo access + const result = await createClientUser(supabase, rawEmail, tabloId, user.id); + if (!result.success || !result.userId) { + return c.json({ error: result.error ?? "Failed to create client user" }, 500); + } + + const token = generateToken(); + const expiresAt = new Date( + Date.now() + CLIENT_INVITE_EXPIRY_HOURS * 60 * 60 * 1000 + ).toISOString(); + + const { error: insertError } = await supabase.from("client_invites").insert({ + tablo_id: tabloId, + invited_email: rawEmail, + invited_by: user.id, + invite_token: token, + is_pending: true, + expires_at: expiresAt, + }); + + if (insertError) { + if (insertError.code === "23505") { + return c.json({ error: "A pending invite already exists for this email and tablo" }, 409); + } + return c.json({ error: insertError.message }, 500); + } + + // Generate a Supabase magic link that redirects to the client portal callback + const clientsUrl = process.env.CLIENTS_URL || "https://clients.xtablo.com"; + const redirectTo = `${clientsUrl}/auth/callback?token=${encodeURIComponent(token)}`; + + const { error: magicLinkError } = await supabase.auth.admin.generateLink({ + type: "magiclink", + email: rawEmail, + options: { redirectTo }, + }); + + if (magicLinkError) { + console.error("Failed to generate magic link:", magicLinkError); + // Non-fatal: invite record is already created + } + + return c.json({ success: true }); + }); + +/** POST /accept/:token — Accept a client invite */ +const acceptClientInvite = (middlewareManager: ReturnType) => + factory.createHandlers(middlewareManager.regularUserCheck, async (c) => { + const user = c.get("user"); + const supabase = c.get("supabase"); + const token = c.req.param("token"); + + const { data: invite, error: inviteError } = await supabase + .from("client_invites") + .select("id, tablo_id, invited_email, invited_by, is_pending, expires_at") + .eq("invite_token", token) + .maybeSingle(); + + if (inviteError) { + return c.json({ error: inviteError.message }, 500); + } + + if (!invite || !invite.is_pending) { + return c.json({ error: "Invite not found or already used" }, 404); + } + + // Check expiration + if (invite.expires_at && new Date(invite.expires_at) < new Date()) { + return c.json({ error: "This invite has expired" }, 410); + } + + // Email must match the authenticated user + if (invite.invited_email?.toLowerCase() !== user.email?.toLowerCase()) { + return c.json({ error: "This invite was not issued to your account" }, 403); + } + + // Mark invite as accepted + await supabase.from("client_invites").update({ is_pending: false }).eq("id", invite.id); + + // Ensure tablo access is active + const { data: existingAccess } = await supabase + .from("tablo_access") + .select("id, is_active") + .eq("tablo_id", invite.tablo_id) + .eq("user_id", user.id) + .maybeSingle(); + + if (!existingAccess) { + await supabase.from("tablo_access").insert({ + tablo_id: invite.tablo_id, + user_id: user.id, + granted_by: invite.invited_by, + is_admin: false, + is_active: true, + }); + } else if (!existingAccess.is_active) { + await supabase.from("tablo_access").update({ is_active: true }).eq("id", existingAccess.id); + } + + return c.json({ success: true, tabloId: invite.tablo_id }); + }); + +/** GET /:tabloId/pending — List pending client invites (admin only) */ +const getPendingClientInvites = ( + middlewareManager: ReturnType +) => + factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { + const supabase = c.get("supabase"); + const tabloId = c.req.param("tabloId"); + + const { data: invites, error } = await supabase + .from("client_invites") + .select("id, invited_email, expires_at, is_pending, created_at") + .eq("tablo_id", tabloId) + .eq("is_pending", true) + .order("created_at", { ascending: false }); + + if (error) { + return c.json({ error: error.message }, 500); + } + + return c.json({ invites: invites ?? [] }); + }); + +/** DELETE /:tabloId/:inviteId — Cancel a client invite (admin only) */ +const cancelClientInvite = (middlewareManager: ReturnType) => + factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { + const supabase = c.get("supabase"); + const tabloId = c.req.param("tabloId"); + const inviteId = Number(c.req.param("inviteId")); + + if (!Number.isInteger(inviteId) || inviteId <= 0) { + return c.json({ error: "Invalid invite id" }, 400); + } + + const { data: invite, error: inviteError } = await supabase + .from("client_invites") + .select("id, invited_email, is_pending") + .eq("id", inviteId) + .eq("tablo_id", tabloId) + .maybeSingle(); + + if (inviteError) { + return c.json({ error: inviteError.message }, 500); + } + + if (!invite) { + return c.json({ error: "Invite not found" }, 404); + } + + if (!invite.is_pending) { + return c.json({ error: "Invite is no longer pending" }, 400); + } + + // Mark invite as cancelled + const { error: cancelError } = await supabase + .from("client_invites") + .update({ is_pending: false }) + .eq("id", inviteId) + .eq("tablo_id", tabloId); + + if (cancelError) { + return c.json({ error: cancelError.message }, 500); + } + + // Revoke tablo access for the client user + if (invite.invited_email) { + const { data: clientProfile } = await supabase + .from("profiles") + .select("id") + .eq("email", invite.invited_email) + .maybeSingle(); + + if (clientProfile?.id) { + await supabase + .from("tablo_access") + .update({ is_active: false }) + .eq("tablo_id", tabloId) + .eq("user_id", clientProfile.id); + } + } + + return c.json({ success: true }); + }); + +export const getClientInvitesRouter = () => { + const router = new Hono(); + const middlewareManager = MiddlewareManager.getInstance(); + + router.post("/:tabloId", ...createClientInvite(middlewareManager)); + router.post("/accept/:token", ...acceptClientInvite(middlewareManager)); + router.get("/:tabloId/pending", ...getPendingClientInvites(middlewareManager)); + router.delete("/:tabloId/:inviteId", ...cancelClientInvite(middlewareManager)); + + return router; +}; From bc28194d3db50b9254c1e34f1051813d3bbf4f57 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 09:23:06 +0200 Subject: [PATCH 08/75] refactor: move tablo view components to packages/tablo-views Moves kanban, gantt, section components, chat hooks and extracted EtapesSection/RoadmapSection from apps/main into the new shared packages/tablo-views package. Components that previously depended on app-specific providers (UserStoreProvider, useIsReadOnlyUser, etc.) are refactored to receive data/callbacks as props, keeping the package free of apps/main dependencies. Co-Authored-By: Claude Opus 4.6 (1M context) --- packages/tablo-views/package.json | 3 +- .../tablo-views/src}/ChatMessages.tsx | 0 packages/tablo-views/src/ClickOutside.tsx | 37 ++ packages/tablo-views/src/EtapesSection.tsx | 366 ++++++++++++++++++ packages/tablo-views/src/ImageColorPicker.tsx | 114 ++++++ packages/tablo-views/src/RoadmapSection.tsx | 23 ++ .../src}/TabloDiscussionSection.tsx | 25 +- .../tablo-views/src}/TabloEventsSection.tsx | 89 ++++- .../tablo-views/src}/TabloFilesSection.tsx | 168 +++++--- .../tablo-views/src}/TabloHeaderActions.tsx | 63 ++- .../tablo-views/src}/TabloTasksSection.tsx | 103 +++-- .../src/components/gantt/GanttChart.tsx | 3 +- .../components/kanban/InlineTaskCreate.tsx | 18 - .../src/components/kanban/KanbanBoard.tsx | 0 .../src/components/kanban/KanbanColumn.tsx | 0 .../src/components/kanban/KanbanTaskCard.tsx | 0 .../src/components/kanban/TaskModal.tsx | 64 ++- .../src/components/kanban/types.ts | 0 .../tablo-views}/src/hooks/useChat.ts | 0 .../tablo-views}/src/hooks/useChatUnread.ts | 0 packages/tablo-views/src/index.ts | 29 +- packages/tablo-views/src/vite-env.d.ts | 1 + packages/tablo-views/tsconfig.json | 3 +- pnpm-lock.yaml | 55 +++ 24 files changed, 961 insertions(+), 203 deletions(-) rename {apps/main/src/components => packages/tablo-views/src}/ChatMessages.tsx (100%) create mode 100644 packages/tablo-views/src/ClickOutside.tsx create mode 100644 packages/tablo-views/src/EtapesSection.tsx create mode 100644 packages/tablo-views/src/ImageColorPicker.tsx create mode 100644 packages/tablo-views/src/RoadmapSection.tsx rename {apps/main/src/components => packages/tablo-views/src}/TabloDiscussionSection.tsx (68%) rename {apps/main/src/components => packages/tablo-views/src}/TabloEventsSection.tsx (78%) rename {apps/main/src/components => packages/tablo-views/src}/TabloFilesSection.tsx (90%) rename {apps/main/src/components => packages/tablo-views/src}/TabloHeaderActions.tsx (90%) rename {apps/main/src/components => packages/tablo-views/src}/TabloTasksSection.tsx (75%) rename {apps/main => packages/tablo-views}/src/components/gantt/GanttChart.tsx (99%) rename {apps/main => packages/tablo-views}/src/components/kanban/InlineTaskCreate.tsx (87%) rename {apps/main => packages/tablo-views}/src/components/kanban/KanbanBoard.tsx (100%) rename {apps/main => packages/tablo-views}/src/components/kanban/KanbanColumn.tsx (100%) rename {apps/main => packages/tablo-views}/src/components/kanban/KanbanTaskCard.tsx (100%) rename {apps/main => packages/tablo-views}/src/components/kanban/TaskModal.tsx (82%) rename {apps/main => packages/tablo-views}/src/components/kanban/types.ts (100%) rename {apps/main => packages/tablo-views}/src/hooks/useChat.ts (100%) rename {apps/main => packages/tablo-views}/src/hooks/useChatUnread.ts (100%) create mode 100644 packages/tablo-views/src/vite-env.d.ts diff --git a/packages/tablo-views/package.json b/packages/tablo-views/package.json index 464a36f..5de94b5 100644 --- a/packages/tablo-views/package.json +++ b/packages/tablo-views/package.json @@ -35,6 +35,7 @@ "@biomejs/biome": "2.2.5", "@types/react": "19.0.10", "@types/react-dom": "19.0.4", - "typescript": "^5.7.0" + "typescript": "^5.7.0", + "vite": "^6.2.2" } } diff --git a/apps/main/src/components/ChatMessages.tsx b/packages/tablo-views/src/ChatMessages.tsx similarity index 100% rename from apps/main/src/components/ChatMessages.tsx rename to packages/tablo-views/src/ChatMessages.tsx diff --git a/packages/tablo-views/src/ClickOutside.tsx b/packages/tablo-views/src/ClickOutside.tsx new file mode 100644 index 0000000..f39778d --- /dev/null +++ b/packages/tablo-views/src/ClickOutside.tsx @@ -0,0 +1,37 @@ +import { useClickOutside } from "@xtablo/shared/hooks/useClickOutside"; +import React from "react"; + +interface ClickOutsideProps { + children: React.ReactNode; + onClickOutside: () => void; + className?: string; + disabled?: boolean; +} + +/** + * Component that wraps children and detects clicks outside + * @param children - The content to wrap + * @param onClickOutside - Function to call when clicking outside + * @param className - Optional className for the wrapper + * @param disabled - Disable click outside detection + */ +export const ClickOutside: React.FC = ({ + children, + onClickOutside, + className, + disabled = false, +}) => { + const ref = useClickOutside( + disabled + ? () => { + // Do nothing + } + : onClickOutside + ); + + return ( +
+ {children} +
+ ); +}; diff --git a/packages/tablo-views/src/EtapesSection.tsx b/packages/tablo-views/src/EtapesSection.tsx new file mode 100644 index 0000000..c671847 --- /dev/null +++ b/packages/tablo-views/src/EtapesSection.tsx @@ -0,0 +1,366 @@ +import { cn } from "@xtablo/shared"; +import type { Etape, KanbanTask } from "@xtablo/shared-types"; +import { Button } from "@xtablo/ui/components/button"; +import { Input } from "@xtablo/ui/components/input"; +import { + CalendarIcon, + ChevronDownIcon, + ChevronRightIcon, + CircleCheckIcon, + ListChecksIcon, + PlusIcon, +} from "lucide-react"; +import { useState } from "react"; + +interface EtapesSectionProps { + etapes: Etape[]; + tabloTasks: KanbanTask[]; + tabloId: string; + isAdmin: boolean; + onCreateTask: (task: { + tablo_id: string; + title: string; + status: string; + parent_task_id: string; + is_parent: boolean; + position: number; + }) => void; + onCreateEtape: (params: { tabloId: string; title: string; position: number }) => Promise; + isCreatingEtape?: boolean; +} + +export function EtapesSection({ + etapes, + tabloTasks, + tabloId, + isAdmin, + onCreateTask, + onCreateEtape, + isCreatingEtape = false, +}: EtapesSectionProps) { + const [expandedEtapes, setExpandedEtapes] = useState>( + new Set(etapes.map((e) => e.id)) + ); + const [addingTaskToEtape, setAddingTaskToEtape] = useState(null); + const [newEtapeTitle, setNewEtapeTitle] = useState(""); + const [newTaskTitle, setNewTaskTitle] = useState(""); + + const toggleEtape = (id: string) => { + setExpandedEtapes((prev) => { + const next = new Set(prev); + if (next.has(id)) next.delete(id); + else next.add(id); + return next; + }); + }; + + const handleAddTask = (etapeId: string) => { + const title = newTaskTitle.trim(); + if (!title || !tabloId) return; + onCreateTask({ + tablo_id: tabloId, + title, + status: "todo", + parent_task_id: etapeId, + is_parent: false, + position: tabloTasks.filter((t) => t.parent_task_id === etapeId).length, + }); + setNewTaskTitle(""); + setAddingTaskToEtape(null); + }; + + const handleAddEtape = async () => { + const title = newEtapeTitle.trim(); + if (!title || !tabloId) { + return; + } + + const nextPosition = etapes.reduce((max, etape) => Math.max(max, etape.position), -1) + 1; + + await onCreateEtape({ + tabloId, + title, + position: nextPosition, + }); + + setNewEtapeTitle(""); + }; + + const statusConfig: Record = { + todo: { + label: "À faire", + color: "bg-blue-100 text-blue-700 dark:bg-blue-950/30 dark:text-blue-400", + }, + in_progress: { + label: "En cours", + color: "bg-yellow-100 text-yellow-700 dark:bg-yellow-950/30 dark:text-yellow-400", + }, + in_review: { + label: "Vérification", + color: "bg-purple-100 text-purple-700 dark:bg-purple-950/30 dark:text-purple-400", + }, + done: { + label: "Terminé", + color: "bg-green-100 text-green-700 dark:bg-green-950/30 dark:text-green-400", + }, + }; + + return ( +
+ {isAdmin && ( +
+ setNewEtapeTitle(event.target.value)} + placeholder="Nom de la nouvelle étape..." + onKeyDown={(event) => { + if (event.key === "Enter") { + void handleAddEtape(); + } + }} + className="h-11 sm:h-9 sm:w-80" + /> + +
+ )} + + {etapes.length === 0 ? ( +
+ +

Aucune étape

+

+ Les étapes permettent de structurer votre projet en grandes phases +

+
+ ) : ( + etapes.map((etape, index) => { + const childTasks = tabloTasks.filter((t) => t.parent_task_id === etape.id); + const doneCount = childTasks.filter((t) => t.status === "done").length; + const totalCount = childTasks.length; + const progressPct = totalCount > 0 ? Math.round((doneCount / totalCount) * 100) : 0; + const isExpanded = expandedEtapes.has(etape.id); + + // Derive status from child tasks instead of etape.status + const derivedStatus = + totalCount === 0 + ? "todo" + : doneCount === totalCount + ? "done" + : doneCount > 0 + ? "in_progress" + : "todo"; + const status = statusConfig[derivedStatus] ?? statusConfig.todo; + + return ( +
+ {/* Etape header */} + + + {/* Child tasks + add task */} + {isExpanded && ( +
+ {childTasks.length > 0 && ( +
+ {childTasks.map((task) => ( +
+ {task.status === "done" ? ( + + ) : ( +
+ )} + + {task.title} + + {task.due_date && ( +
+ + + {new Intl.DateTimeFormat("fr-FR", { + day: "2-digit", + month: "short", + }).format(new Date(task.due_date))} + +
+ )} + {task.status && ( + + {(statusConfig[task.status] ?? statusConfig.todo).label} + + )} +
+ ))} +
+ )} + + {childTasks.length === 0 && addingTaskToEtape !== etape.id && ( +
+ Aucune tâche dans cette étape +
+ )} + + {/* Inline add task */} + {addingTaskToEtape === etape.id ? ( +
+
+ setNewTaskTitle(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter") handleAddTask(etape.id); + if (e.key === "Escape") { + setAddingTaskToEtape(null); + setNewTaskTitle(""); + } + }} + placeholder="Nom de la tâche..." + className="flex-1 text-sm bg-transparent border-none outline-none text-gray-900 dark:text-gray-100 placeholder-gray-400 min-w-0" + /> + + +
+ ) : ( + + )} +
+ )} +
+ ); + }) + )} +
+ ); +} diff --git a/packages/tablo-views/src/ImageColorPicker.tsx b/packages/tablo-views/src/ImageColorPicker.tsx new file mode 100644 index 0000000..27d8a6a --- /dev/null +++ b/packages/tablo-views/src/ImageColorPicker.tsx @@ -0,0 +1,114 @@ +interface ImageColorPickerProps { + creationMode: "image" | "color"; + setCreationMode: (mode: "image" | "color") => void; + selectedColor: string; + setSelectedColor: (color: string) => void; +} + +const AVAILABLE_COLORS = [ + "bg-blue-500", + "bg-green-500", + "bg-purple-500", + "bg-red-500", + "bg-yellow-500", + "bg-indigo-500", + "bg-pink-500", + "bg-teal-500", + "bg-orange-500", + "bg-cyan-500", +]; + +export const ImageColorPicker = ({ + creationMode, + setCreationMode, + selectedColor, + setSelectedColor, +}: ImageColorPickerProps) => { + return ( +
+ {/* Mode Toggle */} +
+ +
+ + +
+
+ + {/* Image Mode */} + {creationMode === "image" && ( +
+ {/* File Upload - Coming Soon */} +
+
+ + + +

+ Import d'images +

+

Bientôt disponible

+
+
+
+ )} + + {/* Color Mode */} + {creationMode === "color" && ( +
+ +
+ {AVAILABLE_COLORS.map((color) => ( + + ))} +
+
+ )} +
+ ); +}; diff --git a/packages/tablo-views/src/RoadmapSection.tsx b/packages/tablo-views/src/RoadmapSection.tsx new file mode 100644 index 0000000..6d6bcb9 --- /dev/null +++ b/packages/tablo-views/src/RoadmapSection.tsx @@ -0,0 +1,23 @@ +import type { KanbanTask, TaskStatus } from "@xtablo/shared-types"; +import { GanttChart } from "./components/gantt/GanttChart"; + +interface RoadmapSectionProps { + tabloTasks: KanbanTask[]; + onDateClick: (date: Date) => void; + onTaskStatusChange: (taskId: string, status: TaskStatus) => void; +} + +export function RoadmapSection({ + tabloTasks, + onDateClick, + onTaskStatusChange, +}: RoadmapSectionProps) { + return ( + + ); +} diff --git a/apps/main/src/components/TabloDiscussionSection.tsx b/packages/tablo-views/src/TabloDiscussionSection.tsx similarity index 68% rename from apps/main/src/components/TabloDiscussionSection.tsx rename to packages/tablo-views/src/TabloDiscussionSection.tsx index 4f9256b..8973a7f 100644 --- a/apps/main/src/components/TabloDiscussionSection.tsx +++ b/packages/tablo-views/src/TabloDiscussionSection.tsx @@ -1,17 +1,26 @@ -import { UserTablo } from "@xtablo/shared/types/tablos.types"; +import type { UserTablo } from "@xtablo/shared/types/tablos.types"; import { useEffect } from "react"; -import { useChat } from "../hooks/useChat"; -import { useTabloMembers } from "../hooks/tablos"; -import { useUser } from "../providers/UserStoreProvider"; +import { useChat } from "./hooks/useChat"; import { ChatMessages } from "./ChatMessages"; +interface Member { + id: string; + name: string; + avatar_url: string | null; +} + interface TabloDiscussionSectionProps { tablo: UserTablo; isAdmin: boolean; + currentUserId: string; + members?: Member[]; } -export const TabloDiscussionSection = ({ tablo }: TabloDiscussionSectionProps) => { - const user = useUser(); +export const TabloDiscussionSection = ({ + tablo, + currentUserId, + members = [], +}: TabloDiscussionSectionProps) => { const { messages, sendMessage, @@ -22,8 +31,6 @@ export const TabloDiscussionSection = ({ tablo }: TabloDiscussionSectionProps) = markAsRead, } = useChat(tablo.id); - const { data: members = [] } = useTabloMembers(tablo.id); - // Mark as read when opening the discussion useEffect(() => { if (messages.length > 0) { @@ -36,7 +43,7 @@ export const TabloDiscussionSection = ({ tablo }: TabloDiscussionSectionProps) =
void; + onUpdateTablo?: (data: { id: string; name?: string | null; color?: string | null }) => Promise; + onInviteUser?: (params: { email: string; tablo_id: string }) => void; + onCancelInvite?: (params: { tabloId: string; inviteId: string }) => void; } -export const TabloEventsSection = ({ tablo, isAdmin }: TabloEventsSectionProps) => { - const navigate = useNavigate(); +export const TabloEventsSection = ({ + tablo, + isAdmin, + isReadOnly = false, + events, + isLoading, + error, + currentUser, + members, + pendingInvites, + isInvitingUser, + isCancellingInvite, + onCreateEvent, + onUpdateTablo, + onInviteUser, + onCancelInvite, +}: TabloEventsSectionProps) => { const { t } = useTranslation(); - const { data: events, isLoading, error } = useEventsByTablo(tablo.id); - const isReadOnly = useIsReadOnlyUser(); // Filter upcoming events (events in the future or today) const today = new Date(); @@ -34,10 +85,6 @@ export const TabloEventsSection = ({ tablo, isAdmin }: TabloEventsSectionProps) return (a.start_time || "").localeCompare(b.start_time || ""); }); - const handleCreateEvent = () => { - navigate(`/planning/create?tablo_id=${tablo.id}`); - }; - const formatDate = (dateStr: string) => { const date = new Date(dateStr); return new Intl.DateTimeFormat("fr-FR", { @@ -50,7 +97,6 @@ export const TabloEventsSection = ({ tablo, isAdmin }: TabloEventsSectionProps) const formatTime = (timeStr: string) => { if (!timeStr) return ""; - return timeStr.slice(0, 5); // HH:MM }; @@ -66,7 +112,7 @@ export const TabloEventsSection = ({ tablo, isAdmin }: TabloEventsSectionProps) {!isReadOnly && ( )}
- +
{/* Events List */}
@@ -176,7 +233,7 @@ export const TabloEventsSection = ({ tablo, isAdmin }: TabloEventsSectionProps)

{!isReadOnly && (
- +
{/* Error Banner */} @@ -987,7 +1045,7 @@ export const TabloFilesSection = ({ tablo, isAdmin }: TabloFilesSectionProps) => }} onSave={handleSaveFolder} folder={editingFolder} - isLoading={createFolder.isPending || updateFolder.isPending} + isLoading={isCreatingFolder || isUpdatingFolder} /> ); diff --git a/apps/main/src/components/TabloHeaderActions.tsx b/packages/tablo-views/src/TabloHeaderActions.tsx similarity index 90% rename from apps/main/src/components/TabloHeaderActions.tsx rename to packages/tablo-views/src/TabloHeaderActions.tsx index e4f1757..1b3e54c 100644 --- a/apps/main/src/components/TabloHeaderActions.tsx +++ b/packages/tablo-views/src/TabloHeaderActions.tsx @@ -1,5 +1,5 @@ import { toast } from "@xtablo/shared"; -import { TabloUpdate, UserTablo } from "@xtablo/shared/types/tablos.types"; +import type { TabloUpdate, UserTablo } from "@xtablo/shared/types/tablos.types"; import { Avatar, AvatarFallback, AvatarImage } from "@xtablo/ui/components/avatar"; import { Button } from "@xtablo/ui/components/button"; import { @@ -13,21 +13,52 @@ import { Input } from "@xtablo/ui/components/input"; import { Popover, PopoverContent, PopoverTrigger } from "@xtablo/ui/components/popover"; import { Loader2, Settings, Share2, X } from "lucide-react"; import { useEffect, useRef, useState } from "react"; -import { useInviteUser } from "../hooks/invite"; -import { useCancelTabloInvite, usePendingTabloInvitesByTablo } from "../hooks/tablo_invites"; -import { useTabloMembers, useUpdateTablo } from "../hooks/tablos"; -import { useUser } from "../providers/UserStoreProvider"; import { ClickOutside } from "./ClickOutside"; import { ImageColorPicker } from "./ImageColorPicker"; +interface PendingInvite { + id: string; + invited_email: string; +} + +interface Member { + id: string; + name: string; + email?: string; + avatar_url?: string | null; + is_admin?: boolean; +} + +interface CurrentUser { + id: string; + avatar_url?: string | null; +} + interface TabloHeaderActionsProps { tablo: UserTablo; isAdmin: boolean; + currentUser: CurrentUser; + members?: Member[]; + pendingInvites?: PendingInvite[]; + isInvitingUser?: boolean; + isCancellingInvite?: boolean; + onUpdateTablo?: (data: TabloUpdate & { id: string }) => Promise; + onInviteUser?: (params: { email: string; tablo_id: string }) => void; + onCancelInvite?: (params: { tabloId: string; inviteId: string }) => void; } -export const TabloHeaderActions = ({ tablo, isAdmin }: TabloHeaderActionsProps) => { - const { mutateAsync: updateTablo } = useUpdateTablo(); - const currentUser = useUser(); +export const TabloHeaderActions = ({ + tablo, + isAdmin, + currentUser, + members = [], + pendingInvites = [], + isInvitingUser = false, + isCancellingInvite = false, + onUpdateTablo, + onInviteUser, + onCancelInvite, +}: TabloHeaderActionsProps) => { const [isShareDialogOpen, setIsShareDialogOpen] = useState(false); const [inviteEmail, setInviteEmail] = useState(""); @@ -39,12 +70,6 @@ export const TabloHeaderActions = ({ tablo, isAdmin }: TabloHeaderActionsProps) const nameInputRef = useRef(null); - // Fetch members and invites for share dialog - const { data: members } = useTabloMembers(tablo?.id || ""); - const { data: pendingInvites } = usePendingTabloInvitesByTablo(tablo?.id || ""); - const { mutate: cancelInvite, isPending: isCancellingInvite } = useCancelTabloInvite(); - const { mutate: inviteUser, isPending: isInvitingUser } = useInviteUser(); - useEffect(() => { setEditData(tablo); setSelectedColor(tablo.color || "bg-blue-500"); @@ -59,14 +84,14 @@ export const TabloHeaderActions = ({ tablo, isAdmin }: TabloHeaderActionsProps) }, [isEditingName]); const handleSaveSettings = async () => { - if (editData && tablo) { + if (editData && tablo && onUpdateTablo) { const updatedTablo: TabloUpdate & { id: string } = { id: editData.id, name: editData.name, color: creationMode === "color" ? selectedColor : null, }; try { - await updateTablo(updatedTablo); + await onUpdateTablo(updatedTablo); toast.add( { title: "Tablo mis à jour", @@ -89,8 +114,8 @@ export const TabloHeaderActions = ({ tablo, isAdmin }: TabloHeaderActionsProps) }; const handleSendInvite = () => { - if (inviteEmail.trim() && tablo) { - inviteUser({ email: inviteEmail, tablo_id: tablo.id }); + if (inviteEmail.trim() && tablo && onInviteUser) { + onInviteUser({ email: inviteEmail, tablo_id: tablo.id }); setInviteEmail(""); } }; @@ -278,7 +303,7 @@ export const TabloHeaderActions = ({ tablo, isAdmin }: TabloHeaderActionsProps) size="icon" variant="ghost" className="h-8 w-8" - onClick={() => cancelInvite({ tabloId: tablo.id, inviteId: invite.id })} + onClick={() => onCancelInvite?.({ tabloId: tablo.id, inviteId: invite.id })} disabled={isCancellingInvite} title="Retirer l'invitation" > diff --git a/apps/main/src/components/TabloTasksSection.tsx b/packages/tablo-views/src/TabloTasksSection.tsx similarity index 75% rename from apps/main/src/components/TabloTasksSection.tsx rename to packages/tablo-views/src/TabloTasksSection.tsx index eccf7b5..0743baa 100644 --- a/apps/main/src/components/TabloTasksSection.tsx +++ b/packages/tablo-views/src/TabloTasksSection.tsx @@ -1,37 +1,71 @@ import { pluralize, toast } from "@xtablo/shared"; -import { UserTablo } from "@xtablo/shared/types/tablos.types"; -import type { KanbanColumn, KanbanTask, KanbanTaskInsert, TaskStatus } from "@xtablo/shared-types"; +import type { UserTablo } from "@xtablo/shared/types/tablos.types"; +import type { + Etape, + KanbanColumn, + KanbanTask, + KanbanTaskInsert, + KanbanTaskUpdate, + TaskStatus, +} from "@xtablo/shared-types"; import { TypographyH3, TypographyMuted } from "@xtablo/ui/components/typography"; import { AlertTriangle, ListChecks } from "lucide-react"; import { useCallback, useEffect, useMemo, useState } from "react"; -import { useTabloMembers } from "../hooks/tablos"; -import { - useCreateTask, - useTabloEtapes, - useTasksByTablo, - useUpdateTaskPositions, -} from "../hooks/tasks"; -import { KanbanBoard } from "./kanban/KanbanBoard"; -import { TaskModal } from "./kanban/TaskModal"; +import { KanbanBoard } from "./components/kanban/KanbanBoard"; +import type { TabloMember } from "./components/kanban/types"; +import { TaskModal } from "./components/kanban/TaskModal"; import { TabloHeaderActions } from "./TabloHeaderActions"; +interface CurrentUser { + id: string; + avatar_url?: string | null; +} + +interface PendingInvite { + id: string; + invited_email: string; +} + interface TabloTasksSectionProps { tablo: UserTablo; isAdmin: boolean; + tasks?: KanbanTask[]; + members?: TabloMember[]; + etapes?: Etape[]; + currentUser: CurrentUser; + pendingInvites?: PendingInvite[]; + isInvitingUser?: boolean; + isCancellingInvite?: boolean; + onCreateTask?: (task: KanbanTaskInsert) => void; + onUpdateTask?: (task: KanbanTaskUpdate & { id: string; tablo_id: string }) => void; + onUpdateTaskPositions?: (updates: Array<{ id: string; position: number; status: TaskStatus }>) => void; + onUpdateTablo?: (data: { id: string; name?: string | null; color?: string | null }) => Promise; + onInviteUser?: (params: { email: string; tablo_id: string }) => void; + onCancelInvite?: (params: { tabloId: string; inviteId: string }) => void; } -export const TabloTasksSection = ({ tablo, isAdmin }: TabloTasksSectionProps) => { - const { data: members = [] } = useTabloMembers(tablo.id); +export const TabloTasksSection = ({ + tablo, + isAdmin, + tasks, + members = [], + etapes = [], + currentUser, + pendingInvites, + isInvitingUser, + isCancellingInvite, + onCreateTask, + onUpdateTask, + onUpdateTaskPositions, + onUpdateTablo, + onInviteUser, + onCancelInvite, +}: TabloTasksSectionProps) => { const [columns, setColumns] = useState([]); const [isModalOpen, setIsModalOpen] = useState(false); const [selectedTask, setSelectedTask] = useState(null); const [modalStatus, setModalStatus] = useState("todo"); - const { data: tasks } = useTasksByTablo(tablo.id); - const { data: etapes = [] } = useTabloEtapes(tablo.id); - const { mutate: updateTaskPositions } = useUpdateTaskPositions(); - const { mutate: createTask } = useCreateTask(); - const memberById = useMemo( () => new Map(members.map((member) => [member.id, member])), [members] @@ -72,7 +106,6 @@ export const TabloTasksSection = ({ tablo, isAdmin }: TabloTasksSectionProps) => return tasksWithAssigneeFallback.filter((task) => !task.parent_task_id); }, [tasksWithAssigneeFallback]); - // Helper functions defined before use const initializeColumns = useCallback((tasks: KanbanTask[]): KanbanColumn[] => { const defaultColumns: KanbanColumn[] = [ { @@ -137,19 +170,7 @@ export const TabloTasksSection = ({ tablo, isAdmin }: TabloTasksSectionProps) => parent_task_id: taskData.parent_task_id ?? null, }; - createTask(newTask); - - // setColumns((prevColumns) => - // prevColumns.map((column: KanbanColumn) => { - // if (column.status === (taskData.status as TaskStatus)) { - // return { - // ...column, - // tasks: [newTask, ...column.tasks], - // }; - // } - // return column; - // }) - // ); + onCreateTask?.(newTask); toast.add( { @@ -162,7 +183,7 @@ export const TabloTasksSection = ({ tablo, isAdmin }: TabloTasksSectionProps) => }; const handleTaskMove = (taskId: string, newStatus: TaskStatus) => { - updateTaskPositions([ + onUpdateTaskPositions?.([ { id: taskId, position: columns.find((column) => column.status === newStatus)?.position ?? 0, @@ -198,7 +219,18 @@ export const TabloTasksSection = ({ tablo, isAdmin }: TabloTasksSectionProps) => Gérez vos tâches avec un tableau Kanban - + {/* Warning for orphaned tasks */} @@ -238,11 +270,14 @@ export const TabloTasksSection = ({ tablo, isAdmin }: TabloTasksSectionProps) => setIsModalOpen(false)} members={members} initialStatus={modalStatus} etapes={etapes} + onCreateTask={onCreateTask} + onUpdateTask={onUpdateTask} /> ); diff --git a/apps/main/src/components/gantt/GanttChart.tsx b/packages/tablo-views/src/components/gantt/GanttChart.tsx similarity index 99% rename from apps/main/src/components/gantt/GanttChart.tsx rename to packages/tablo-views/src/components/gantt/GanttChart.tsx index 49c90f8..9f24854 100644 --- a/apps/main/src/components/gantt/GanttChart.tsx +++ b/packages/tablo-views/src/components/gantt/GanttChart.tsx @@ -1,4 +1,3 @@ -import { LoadingSpinner } from "@ui/components/LoadingSpinner"; import type { KanbanTask, TaskStatus } from "@xtablo/shared-types"; import { Button } from "@xtablo/ui/components/button"; import { @@ -253,7 +252,7 @@ export function GanttChart({ tasks, isLoading, onDateClick, onTaskStatusChange } if (isLoading) { return (
- +
); } diff --git a/apps/main/src/components/kanban/InlineTaskCreate.tsx b/packages/tablo-views/src/components/kanban/InlineTaskCreate.tsx similarity index 87% rename from apps/main/src/components/kanban/InlineTaskCreate.tsx rename to packages/tablo-views/src/components/kanban/InlineTaskCreate.tsx index 0d96492..9d03af2 100644 --- a/apps/main/src/components/kanban/InlineTaskCreate.tsx +++ b/packages/tablo-views/src/components/kanban/InlineTaskCreate.tsx @@ -130,24 +130,6 @@ export const InlineTaskCreate = ({ status, members, etapes, onSubmit }: InlineTa {/* Type and Assignee */}
- {/*
- - -
*/} -
{/* Étape */} - {etapes.length > 0 && ( + {providedEtapes.length > 0 && (
setNewEtapeTitle(event.target.value)} - placeholder="Nom de la nouvelle étape..." - onKeyDown={(event) => { - if (event.key === "Enter") { - void handleAddEtape(); - } - }} - className="h-11 sm:h-9 sm:w-80" - /> - -
- )} - - {etapes.length === 0 ? ( -
- -

Aucune étape

-

- Les étapes permettent de structurer votre projet en grandes phases -

-
- ) : ( - etapes.map((etape, index) => { - const childTasks = tabloTasks.filter((t) => t.parent_task_id === etape.id); - const doneCount = childTasks.filter((t) => t.status === "done").length; - const totalCount = childTasks.length; - const progressPct = totalCount > 0 ? Math.round((doneCount / totalCount) * 100) : 0; - const isExpanded = expandedEtapes.has(etape.id); - - // Derive status from child tasks instead of etape.status - const derivedStatus = - totalCount === 0 - ? "todo" - : doneCount === totalCount - ? "done" - : doneCount > 0 - ? "in_progress" - : "todo"; - const status = statusConfig[derivedStatus] ?? statusConfig.todo; - - return ( -
- {/* Etape header */} - - - {/* Child tasks + add task */} - {isExpanded && ( -
- {childTasks.length > 0 && ( -
- {childTasks.map((task) => ( -
- {task.status === "done" ? ( - - ) : ( -
- )} - - {task.title} - - {task.due_date && ( -
- - - {new Intl.DateTimeFormat("fr-FR", { - day: "2-digit", - month: "short", - }).format(new Date(task.due_date))} - -
- )} - {task.status && ( - - {(statusConfig[task.status] ?? statusConfig.todo).label} - - )} -
- ))} -
- )} - - {childTasks.length === 0 && addingTaskToEtape !== etape.id && ( -
- Aucune tâche dans cette étape -
- )} - - {/* Inline add task */} - {addingTaskToEtape === etape.id ? ( -
-
- setNewTaskTitle(e.target.value)} - onKeyDown={(e) => { - if (e.key === "Enter") handleAddTask(etape.id); - if (e.key === "Escape") { - setAddingTaskToEtape(null); - setNewTaskTitle(""); - } - }} - placeholder="Nom de la tâche..." - className="flex-1 text-sm bg-transparent border-none outline-none text-gray-900 dark:text-gray-100 placeholder-gray-400 min-w-0" - /> - - -
- ) : ( - - )} -
- )} -
- ); - }) - )} -
- ); -} - -// ─── Roadmap Section ───────────────────────────────────────────────────────── - -function RoadmapSection({ - tabloTasks, - onDateClick, -}: { - etapes: Etape[]; - tabloTasks: KanbanTask[]; - onDateClick: (date: Date) => void; -}) { - const { mutate: updateTask } = useUpdateTask(); - - return ( - updateTask({ id: taskId, status })} - /> - ); -} diff --git a/apps/main/src/pages/tablo.tsx b/apps/main/src/pages/tablo.tsx index 6221881..622e533 100644 --- a/apps/main/src/pages/tablo.tsx +++ b/apps/main/src/pages/tablo.tsx @@ -40,7 +40,7 @@ import { useNavigate, useSearchParams } from "react-router-dom"; import { DashboardActionCards } from "src/components/DashboardActionCards"; import { DashboardTaskList } from "src/components/DashboardTaskList"; import { InviteOrganizationModal } from "src/components/InviteOrganizationModal"; -import { TaskModal } from "src/components/kanban/TaskModal"; +import { TaskModal } from "@xtablo/tablo-views"; import { ProjectCardList } from "src/components/ProjectCardList"; import { Badge } from "@xtablo/ui/components/badge"; import { useCanCreateTablo, useCreateTablo, useDeleteTablo, useTablosList } from "../hooks/tablos"; diff --git a/apps/main/src/pages/tasks.tsx b/apps/main/src/pages/tasks.tsx index f4fa3f9..a2763d2 100644 --- a/apps/main/src/pages/tasks.tsx +++ b/apps/main/src/pages/tasks.tsx @@ -40,8 +40,7 @@ import { useMemo, useState } from "react"; import { useTranslation } from "react-i18next"; import { useNavigate, useSearchParams } from "react-router-dom"; import { twMerge } from "tailwind-merge"; -import { GanttChart } from "../components/gantt/GanttChart"; -import { TaskModal } from "../components/kanban/TaskModal"; +import { GanttChart, TaskModal } from "@xtablo/tablo-views"; import { useTablosList } from "../hooks/tablos"; import { useAllTasks, useUpdateTask } from "../hooks/tasks"; import { useUser } from "../providers/UserStoreProvider"; diff --git a/apps/main/src/providers/UserStoreProvider.test.tsx b/apps/main/src/providers/UserStoreProvider.test.tsx index d445b17..7f7e908 100644 --- a/apps/main/src/providers/UserStoreProvider.test.tsx +++ b/apps/main/src/providers/UserStoreProvider.test.tsx @@ -62,6 +62,7 @@ describe("TestUserStoreProvider", () => { email: null, first_name: null, is_temporary: false, + is_client: false, last_name: null, short_user_id: "short-id", last_signed_in: null, diff --git a/apps/main/src/utils/testHelpers.tsx b/apps/main/src/utils/testHelpers.tsx index 5a49fb2..f370ba2 100644 --- a/apps/main/src/utils/testHelpers.tsx +++ b/apps/main/src/utils/testHelpers.tsx @@ -18,6 +18,7 @@ const defaultUser = { email: "john@example.com", avatar_url: "https://example.com/avatar.jpg", is_temporary: false, + is_client: false, last_signed_in: null, plan: "none" as const, created_at: new Date().toISOString(), diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f0e6669..ecad098 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -140,6 +140,91 @@ importers: specifier: ^4.14.0 version: 4.44.0(@cloudflare/workers-types@4.20260411.1) + apps/clients: + dependencies: + '@tanstack/react-query': + specifier: ^5.69.0 + version: 5.90.5(react@19.0.0) + '@xtablo/chat-ui': + specifier: workspace:* + version: link:../../packages/chat-ui + '@xtablo/shared': + specifier: workspace:* + version: link:../../packages/shared + '@xtablo/shared-types': + specifier: workspace:* + version: link:../../packages/shared-types + '@xtablo/tablo-views': + specifier: workspace:* + version: link:../../packages/tablo-views + '@xtablo/ui': + specifier: workspace:* + version: link:../../packages/ui + i18next: + specifier: ^25.6.0 + version: 25.6.0(typescript@5.9.3) + i18next-browser-languagedetector: + specifier: ^8.2.0 + version: 8.2.0 + lucide-react: + specifier: ^0.460.0 + version: 0.460.0(react@19.0.0) + react: + specifier: 19.0.0 + version: 19.0.0 + react-dom: + specifier: 19.0.0 + version: 19.0.0(react@19.0.0) + react-i18next: + specifier: ^16.2.0 + version: 16.2.0(i18next@25.6.0(typescript@5.9.3))(react-dom@19.0.0(react@19.0.0))(react@19.0.0)(typescript@5.9.3) + react-router-dom: + specifier: ^7.9.4 + version: 7.9.4(react-dom@19.0.0(react@19.0.0))(react@19.0.0) + tailwind-merge: + specifier: ^3.0.2 + version: 3.3.1 + zustand: + specifier: ^5.0.5 + version: 5.0.8(@types/react@19.0.10)(react@19.0.0)(use-sync-external-store@1.6.0(react@19.0.0)) + devDependencies: + '@biomejs/biome': + specifier: 2.2.5 + version: 2.2.5 + '@cloudflare/vite-plugin': + specifier: ^1.9.4 + version: 1.13.14(vite@6.4.1(@types/node@22.18.12)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6))(workerd@1.20251011.0)(wrangler@4.44.0(@cloudflare/workers-types@4.20260411.1)) + '@tailwindcss/vite': + specifier: ^4.0.14 + version: 4.1.15(vite@6.4.1(@types/node@22.18.12)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6)) + '@types/react': + specifier: 19.0.10 + version: 19.0.10 + '@types/react-dom': + specifier: 19.0.4 + version: 19.0.4(@types/react@19.0.10) + '@vitejs/plugin-react': + specifier: ^4.3.4 + version: 4.7.0(vite@6.4.1(@types/node@22.18.12)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6)) + tailwindcss: + specifier: ^4.0.14 + version: 4.1.15 + tw-animate-css: + specifier: ^1.4.0 + version: 1.4.0 + typescript: + specifier: ^5.7.0 + version: 5.9.3 + vite: + specifier: ^6.2.2 + version: 6.4.1(@types/node@22.18.12)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6) + vite-tsconfig-paths: + specifier: ^5.1.4 + version: 5.1.4(typescript@5.9.3)(vite@6.4.1(@types/node@22.18.12)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6)) + wrangler: + specifier: ^4.24.3 + version: 4.44.0(@cloudflare/workers-types@4.20260411.1) + apps/external: dependencies: '@tanstack/react-query': @@ -314,6 +399,9 @@ importers: '@xtablo/shared-types': specifier: workspace:* version: link:../../packages/shared-types + '@xtablo/tablo-views': + specifier: workspace:* + version: link:../../packages/tablo-views '@xtablo/ui': specifier: workspace:* version: link:../../packages/ui From 118b23bfb1a45e0cd6df10fd88599dd2716a5ce8 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 14:18:27 +0200 Subject: [PATCH 12/75] feat(main): add client invite UI to share dialog Adds three React Query hooks (usePendingClientInvites, useCreateClientInvite, useCancelClientInvite) and a new Client Access section in the share dialog with email input, pending invite list, expiry countdown, and orange warning badge for invites expiring in less than 5 days. Co-Authored-By: Claude Sonnet 4.6 --- apps/main/src/hooks/client_invites.ts | 89 ++++++++++++++++++ apps/main/src/pages/tablo-details.tsx | 126 ++++++++++++++++++++++++++ 2 files changed, 215 insertions(+) create mode 100644 apps/main/src/hooks/client_invites.ts diff --git a/apps/main/src/hooks/client_invites.ts b/apps/main/src/hooks/client_invites.ts new file mode 100644 index 0000000..ea6d49b --- /dev/null +++ b/apps/main/src/hooks/client_invites.ts @@ -0,0 +1,89 @@ +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { toast, useSession } from "@xtablo/shared"; +import { useAuthedApi } from "./auth"; + +type PendingClientInvite = { + id: number; + invited_email: string; + expires_at: string; + is_pending: boolean; + created_at: string; +}; + +export const usePendingClientInvites = (tabloId: string) => { + const api = useAuthedApi(); + const { session } = useSession(); + + return useQuery({ + queryKey: ["client-invites", tabloId], + queryFn: async () => { + const { data } = await api.get( + `/api/v1/client-invites/${tabloId}/pending` + ); + return data; + }, + enabled: !!tabloId && !!session, + }); +}; + +export const useCreateClientInvite = () => { + const api = useAuthedApi(); + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async ({ tabloId, email }: { tabloId: string; email: string }) => { + const { data } = await api.post( + `/api/v1/client-invites/${tabloId}`, + { email } + ); + return data; + }, + onSuccess: (_data, { tabloId }) => { + queryClient.invalidateQueries({ queryKey: ["client-invites", tabloId] }); + toast.add( + { + title: "Lien magique envoyé", + description: "L'invitation client a été envoyée avec succès", + type: "success", + }, + { timeout: 3000 } + ); + }, + onError: (error) => { + console.error("Error creating client invite:", error); + toast.add( + { + title: "Erreur", + description: "Impossible d'envoyer l'invitation client", + type: "error", + }, + { timeout: 5000 } + ); + }, + }); +}; + +export const useCancelClientInvite = () => { + const api = useAuthedApi(); + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async ({ tabloId, inviteId }: { tabloId: string; inviteId: number }) => { + await api.delete(`/api/v1/client-invites/${tabloId}/${inviteId}`); + }, + onSuccess: (_data, { tabloId }) => { + queryClient.invalidateQueries({ queryKey: ["client-invites", tabloId] }); + }, + onError: (error) => { + console.error("Error cancelling client invite:", error); + toast.add( + { + title: "Erreur", + description: "Impossible d'annuler l'invitation client", + type: "error", + }, + { timeout: 5000 } + ); + }, + }); +}; diff --git a/apps/main/src/pages/tablo-details.tsx b/apps/main/src/pages/tablo-details.tsx index 940ba76..42d82f2 100644 --- a/apps/main/src/pages/tablo-details.tsx +++ b/apps/main/src/pages/tablo-details.tsx @@ -34,6 +34,7 @@ import { Sun, UserPlusIcon, Waves, + XIcon, Zap, } from "lucide-react"; import { useEffect, useState } from "react"; @@ -52,6 +53,11 @@ import { useInviteUser } from "../hooks/invite"; import { useTabloFileNames, useDownloadTabloFile, useUploadTabloFile, useDeleteTabloFile } from "../hooks/tablo_data"; import { useTabloFolders, useCreateTabloFolder, useUpdateTabloFolder, useDeleteTabloFolder } from "../hooks/tablo_folders"; import { useCancelTabloInvite, usePendingTabloInvitesByTablo } from "../hooks/tablo_invites"; +import { + usePendingClientInvites, + useCreateClientInvite, + useCancelClientInvite, +} from "../hooks/client_invites"; import { useTabloMembers, useTabloOverviewLayout, @@ -187,6 +193,7 @@ export const TabloDetailsPage = () => { const [showAllOverviewTasks, setShowAllOverviewTasks] = useState(false); const [isShareDialogOpen, setIsShareDialogOpen] = useState(false); const [inviteEmail, setInviteEmail] = useState(""); + const [clientInviteEmail, setClientInviteEmail] = useState(""); const [isLayoutEditMode, setIsLayoutEditMode] = useState(false); const [draggedOverviewBlock, setDraggedOverviewBlock] = useState<{ zone: "left" | "right"; @@ -200,6 +207,9 @@ export const TabloDetailsPage = () => { const { data: pendingInvites } = usePendingTabloInvitesByTablo(tabloId ?? ""); const { mutate: cancelInvite, isPending: isCancellingInvite } = useCancelTabloInvite(); const { mutate: inviteUser, isPending: isInvitingUser } = useInviteUser(); + const { data: pendingClientInvites } = usePendingClientInvites(tabloId ?? ""); + const { mutate: createClientInvite, isPending: isCreatingClientInvite } = useCreateClientInvite(); + const { mutate: cancelClientInvite, isPending: isCancellingClientInvite } = useCancelClientInvite(); const { mutate: updateTask } = useUpdateTask(); const { mutate: updateTablo, mutateAsync: updateTabloAsync } = useUpdateTablo(); const { mutate: createTask } = useCreateTask(); @@ -1032,6 +1042,122 @@ export const TabloDetailsPage = () => {
)} + + {/* Separator */} +
+ {/* Client Access Section */} +
+

Accès client

+

+ Invitez des clients externes via un lien magique +

+
+ + {/* Client Invite Input */} +
+ setClientInviteEmail(e.target.value)} + placeholder="Email du client" + className="flex-1 min-h-[44px]" + /> + {isCreatingClientInvite ? ( +
+
+
+ ) : ( + + )} +
+ + {/* Pending Client Invites */} + {pendingClientInvites && pendingClientInvites.length > 0 && ( +
+

+ Invitations client en attente ({pendingClientInvites.length}) +

+
+ {pendingClientInvites.map((invite) => { + const daysUntilExpiry = Math.ceil( + (new Date(invite.expires_at).getTime() - Date.now()) / (1000 * 60 * 60 * 24) + ); + const isExpiringSoon = daysUntilExpiry < 5; + return ( +
+
+ + + +
+
+ + {invite.invited_email} + + + {isExpiringSoon && "⚠ "} + Expire dans {daysUntilExpiry} jour{daysUntilExpiry !== 1 ? "s" : ""} + +
+ {isExpiringSoon && ( + + Bientôt expiré + + )} + +
+ ); + })} +
+
+ )} +
From f3fb08c9b2b60b8b487b3db8f3d03923fba3d45b Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 14:30:55 +0200 Subject: [PATCH 13/75] feat(clients): add layout, auth callback, tablo page, and list page Adds SessionProvider to main.tsx, creates ClientLayout with minimal top bar, AuthCallback for magic link handling, ClientTabloPage with all 7 tabs using tablo-views components, and ClientTabloListPage with auto-redirect for single tablo. Co-Authored-By: Claude Opus 4.6 (1M context) --- apps/clients/src/components/ClientLayout.tsx | 67 ++++ apps/clients/src/lib/supabase.ts | 10 + apps/clients/src/main.tsx | 16 +- apps/clients/src/pages/AuthCallback.tsx | 66 ++++ .../clients/src/pages/ClientTabloListPage.tsx | 63 ++++ apps/clients/src/pages/ClientTabloPage.tsx | 310 ++++++++++++++++++ apps/clients/src/routes.tsx | 12 +- apps/clients/tsconfig.json | 1 + 8 files changed, 536 insertions(+), 9 deletions(-) create mode 100644 apps/clients/src/components/ClientLayout.tsx create mode 100644 apps/clients/src/lib/supabase.ts create mode 100644 apps/clients/src/pages/AuthCallback.tsx create mode 100644 apps/clients/src/pages/ClientTabloListPage.tsx create mode 100644 apps/clients/src/pages/ClientTabloPage.tsx diff --git a/apps/clients/src/components/ClientLayout.tsx b/apps/clients/src/components/ClientLayout.tsx new file mode 100644 index 0000000..20719a0 --- /dev/null +++ b/apps/clients/src/components/ClientLayout.tsx @@ -0,0 +1,67 @@ +import { useSession } from "@xtablo/shared/contexts/SessionContext"; +import { Avatar, AvatarFallback } from "@xtablo/ui/components/avatar"; +import { Button } from "@xtablo/ui/components/button"; +import { Outlet } from "react-router-dom"; +import { supabase } from "../lib/supabase"; + +function getInitials(email: string): string { + const parts = email.split("@")[0].split(/[._-]/); + return parts + .slice(0, 2) + .map((p) => p[0]?.toUpperCase() ?? "") + .join(""); +} + +export function ClientLayout() { + const { session } = useSession(); + + if (!session) { + return ( +
+
+

Accès non autorisé

+

+ Veuillez utiliser le lien reçu dans votre email pour accéder à cette page. +

+
+
+ ); + } + + const email = session.user.email ?? ""; + const initials = email ? getInitials(email) : "?"; + + const handleLogout = async () => { + await supabase.auth.signOut(); + }; + + return ( +
+ {/* Top bar */} +
+
+ {/* Brand */} + Xtablo + + {/* User info + logout */} +
+
+ + {initials} + + {email} +
+ +
+
+
+ + {/* Page content */} +
+ +
+
+ ); +} diff --git a/apps/clients/src/lib/supabase.ts b/apps/clients/src/lib/supabase.ts new file mode 100644 index 0000000..99c2e17 --- /dev/null +++ b/apps/clients/src/lib/supabase.ts @@ -0,0 +1,10 @@ +import { createSupabaseClient } from "@xtablo/shared"; + +const supabaseUrl = import.meta.env.VITE_SUPABASE_URL; +const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY; + +if (!supabaseUrl || !supabaseAnonKey) { + throw new Error("Missing Supabase environment variables"); +} + +export const supabase = createSupabaseClient(supabaseUrl, supabaseAnonKey); diff --git a/apps/clients/src/main.tsx b/apps/clients/src/main.tsx index ecf1020..d158df1 100644 --- a/apps/clients/src/main.tsx +++ b/apps/clients/src/main.tsx @@ -1,11 +1,13 @@ import { QueryClientProvider } from "@tanstack/react-query"; import { queryClient } from "@xtablo/shared"; +import { SessionProvider } from "@xtablo/shared/contexts/SessionContext"; import { ThemeProvider } from "@xtablo/shared/contexts/ThemeContext"; import { Toaster } from "@xtablo/ui/components/sonner"; import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; import { BrowserRouter as Router } from "react-router-dom"; import App from "./App"; +import { supabase } from "./lib/supabase"; import "@xtablo/ui/styles/globals.css"; import "./main.css"; @@ -14,12 +16,14 @@ import "./i18n"; createRoot(document.getElementById("client-root")!).render( - - - - - - + + + + + + + + ); diff --git a/apps/clients/src/pages/AuthCallback.tsx b/apps/clients/src/pages/AuthCallback.tsx new file mode 100644 index 0000000..b34427b --- /dev/null +++ b/apps/clients/src/pages/AuthCallback.tsx @@ -0,0 +1,66 @@ +import { useSession } from "@xtablo/shared/contexts/SessionContext"; +import { useEffect, useRef, useState } from "react"; +import { useNavigate, useSearchParams } from "react-router-dom"; + +export function AuthCallback() { + const [searchParams] = useSearchParams(); + const token = searchParams.get("token"); + const { session } = useSession(); + const navigate = useNavigate(); + const [error, setError] = useState(null); + const hasAccepted = useRef(false); + + useEffect(() => { + if (!session || !token || hasAccepted.current) { + return; + } + + hasAccepted.current = true; + + const apiUrl = import.meta.env.VITE_API_URL as string; + + fetch(`${apiUrl}/api/v1/client-invites/accept/${token}`, { + method: "POST", + headers: { + Authorization: `Bearer ${session.access_token}`, + "Content-Type": "application/json", + }, + }) + .then(async (res) => { + if (!res.ok) { + const body = await res.json().catch(() => ({})); + throw new Error((body as { message?: string }).message ?? "Erreur lors de l'acceptation de l'invitation"); + } + return res.json() as Promise<{ tabloId: string }>; + }) + .then((data) => { + navigate(`/tablo/${data.tabloId}`, { replace: true }); + }) + .catch((err: unknown) => { + console.error("Accept invite error:", err); + setError( + "Une erreur est survenue lors de l'acceptation de l'invitation. Veuillez contacter la personne qui vous a invité." + ); + }); + }, [session, token, navigate]); + + if (error) { + return ( +
+
+

Erreur

+

{error}

+
+
+ ); + } + + return ( +
+
+
+

Authentification en cours...

+
+
+ ); +} diff --git a/apps/clients/src/pages/ClientTabloListPage.tsx b/apps/clients/src/pages/ClientTabloListPage.tsx new file mode 100644 index 0000000..e3ce7c6 --- /dev/null +++ b/apps/clients/src/pages/ClientTabloListPage.tsx @@ -0,0 +1,63 @@ +import { useQuery } from "@tanstack/react-query"; +import type { UserTablo } from "@xtablo/shared-types"; +import { Navigate, Link } from "react-router-dom"; +import { supabase } from "../lib/supabase"; + +function useClientTablosList() { + return useQuery({ + queryKey: ["client-tablos-list"], + queryFn: async () => { + const { data, error } = await supabase.from("user_tablos").select("*"); + if (error) throw error; + return (data ?? []) as UserTablo[]; + }, + }); +} + +export function ClientTabloListPage() { + const { data: tablos, isLoading } = useClientTablosList(); + + if (isLoading) { + return ( +
+
+
+ ); + } + + if (!tablos || tablos.length === 0) { + return ( +
+

Aucun projet disponible.

+
+ ); + } + + if (tablos.length === 1) { + return ; + } + + return ( +
+
+

Mes projets

+

Sélectionnez un projet pour y accéder.

+
+ +
+ {tablos.map((tablo) => ( + + {tablo.color && ( +
+ )} +

{tablo.name}

+ + ))} +
+
+ ); +} diff --git a/apps/clients/src/pages/ClientTabloPage.tsx b/apps/clients/src/pages/ClientTabloPage.tsx new file mode 100644 index 0000000..3da9be0 --- /dev/null +++ b/apps/clients/src/pages/ClientTabloPage.tsx @@ -0,0 +1,310 @@ +import { useQuery } from "@tanstack/react-query"; +import { buildApi } from "@xtablo/shared"; +import { useSession } from "@xtablo/shared/contexts/SessionContext"; +import type { Etape, KanbanTask, TabloFolder, UserTablo } from "@xtablo/shared-types"; +import { CalendarIcon, FolderIcon, KanbanIcon, ListChecksIcon, MapIcon, MessageCircleIcon } from "lucide-react"; +import { useState } from "react"; +import { useParams } from "react-router-dom"; +import { + EtapesSection, + RoadmapSection, + TabloDiscussionSection, + TabloEventsSection, + TabloFilesSection, + TabloTasksSection, +} from "@xtablo/tablo-views"; +import { supabase } from "../lib/supabase"; + +const API_URL = import.meta.env.VITE_API_URL as string; + +// ─── Local hooks ────────────────────────────────────────────────────────────── + +function useAuthedApi(accessToken: string | undefined) { + return buildApi(API_URL).create({ + headers: { + Authorization: `Bearer ${accessToken ?? ""}`, + }, + }); +} + +function useClientTablo(tabloId: string) { + return useQuery({ + queryKey: ["client-tablo", tabloId], + queryFn: async () => { + const { data, error } = await supabase + .from("user_tablos") + .select("*") + .eq("id", tabloId) + .single(); + if (error) throw error; + return data as UserTablo; + }, + enabled: !!tabloId, + }); +} + +function useClientTabloTasks(tabloId: string) { + return useQuery({ + queryKey: ["client-tasks", tabloId], + queryFn: async () => { + const { data, error } = await supabase + .from("tasks_with_assignee") + .select("*") + .eq("tablo_id", tabloId) + .eq("is_parent", false) + .order("updated_at", { ascending: false }); + if (error) throw error; + return (data ?? []) as KanbanTask[]; + }, + enabled: !!tabloId, + }); +} + +function useClientTabloEtapes(tabloId: string) { + return useQuery({ + queryKey: ["client-etapes", tabloId], + queryFn: async () => { + const { data, error } = await supabase + .from("tasks") + .select("*") + .eq("tablo_id", tabloId) + .eq("is_parent", true) + .order("position", { ascending: true }); + if (error) throw error; + return (data ?? []) as Etape[]; + }, + enabled: !!tabloId, + }); +} + +function useClientTabloEvents(tabloId: string) { + return useQuery({ + queryKey: ["client-events", tabloId], + queryFn: async () => { + const { data, error } = await supabase + .from("events_and_tablos") + .select("*") + .eq("tablo_id", tabloId) + .order("start_date", { ascending: false }); + if (error) throw error; + return data ?? []; + }, + enabled: !!tabloId, + }); +} + +function useClientTabloMembers(tabloId: string, accessToken: string | undefined) { + const api = useAuthedApi(accessToken); + return useQuery({ + queryKey: ["client-members", tabloId], + queryFn: async () => { + const { data } = await api.get<{ + members: { + id: string; + name: string; + is_admin: boolean; + email: string; + avatar_url: string | null; + }[]; + }>(`/api/v1/tablos/members/${tabloId}`); + return data.members; + }, + enabled: !!tabloId && !!accessToken, + }); +} + +function useClientTabloFiles(tabloId: string, accessToken: string | undefined) { + const api = useAuthedApi(accessToken); + return useQuery<{ fileNames: string[] }>({ + queryKey: ["client-tablo-files", tabloId], + queryFn: async () => { + const { data } = await api.get(`/api/v1/tablo-data/${tabloId}/filenames`); + return data as { fileNames: string[] }; + }, + enabled: !!tabloId && !!accessToken, + }); +} + +function useClientTabloFolders(tabloId: string, accessToken: string | undefined) { + const api = useAuthedApi(accessToken); + return useQuery({ + queryKey: ["client-tablo-folders", tabloId], + queryFn: async () => { + const { data } = await api.get<{ folders: TabloFolder[] }>(`/api/v1/tablo-folders/${tabloId}`); + return data.folders ?? []; + }, + enabled: !!tabloId && !!accessToken, + }); +} + +// ─── Tabs ───────────────────────────────────────────────────────────────────── + +type TabId = "overview" | "etapes" | "tasks" | "files" | "discussion" | "events" | "roadmap"; + +const TABS: { id: TabId; label: string; icon: React.ElementType }[] = [ + { id: "overview", label: "Aperçu", icon: ListChecksIcon }, + { id: "etapes", label: "Étapes", icon: ListChecksIcon }, + { id: "tasks", label: "Tâches", icon: KanbanIcon }, + { id: "files", label: "Fichiers", icon: FolderIcon }, + { id: "discussion", label: "Discussion", icon: MessageCircleIcon }, + { id: "events", label: "Événements", icon: CalendarIcon }, + { id: "roadmap", label: "Roadmap", icon: MapIcon }, +]; + +// ─── Page ───────────────────────────────────────────────────────────────────── + +export function ClientTabloPage() { + const { tabloId } = useParams<{ tabloId: string }>(); + const { session } = useSession(); + const [activeTab, setActiveTab] = useState("overview"); + + const accessToken = session?.access_token; + const currentUserId = session?.user.id ?? ""; + + const { data: tablo, isLoading: tabloLoading } = useClientTablo(tabloId ?? ""); + const { data: tasks = [] } = useClientTabloTasks(tabloId ?? ""); + const { data: etapes = [] } = useClientTabloEtapes(tabloId ?? ""); + const { data: events, isLoading: eventsLoading, error: eventsError } = useClientTabloEvents(tabloId ?? ""); + const { data: members = [] } = useClientTabloMembers(tabloId ?? "", accessToken); + const { data: filesData, isLoading: filesLoading, error: filesError } = useClientTabloFiles(tabloId ?? "", accessToken); + const { data: folders = [], isLoading: foldersLoading, error: foldersError } = useClientTabloFolders(tabloId ?? "", accessToken); + + const fileNames = (filesData?.fileNames ?? []).filter((f) => !f.startsWith(".")); + + const currentUser = { id: currentUserId, avatar_url: null }; + + if (tabloLoading) { + return ( +
+
+
+ ); + } + + if (!tablo) { + return ( +
+

Projet introuvable.

+
+ ); + } + + return ( +
+ {/* Tablo header */} +
+

{tablo.name}

+
+ + {/* Tab bar */} +
+ +
+ + {/* Tab content */} +
+ {activeTab === "overview" && ( +
+ {/* Simple overview: list etapes with progress */} + {}} + onCreateEtape={async () => {}} + /> +
+ )} + + {activeTab === "etapes" && ( + {}} + onCreateEtape={async () => {}} + /> + )} + + {activeTab === "tasks" && ( + + )} + + {activeTab === "files" && ( + + )} + + {activeTab === "discussion" && ( + + )} + + {activeTab === "events" && ( + [0]["events"]} + isLoading={eventsLoading} + error={eventsError instanceof Error ? eventsError : null} + currentUser={currentUser} + members={members} + /> + )} + + {activeTab === "roadmap" && ( + {}} + onTaskStatusChange={() => {}} + /> + )} +
+
+ ); +} diff --git a/apps/clients/src/routes.tsx b/apps/clients/src/routes.tsx index 4f94f7f..57a23ce 100644 --- a/apps/clients/src/routes.tsx +++ b/apps/clients/src/routes.tsx @@ -1,11 +1,17 @@ import { Route, Routes } from "react-router-dom"; +import { ClientLayout } from "./components/ClientLayout"; +import { AuthCallback } from "./pages/AuthCallback"; +import { ClientTabloListPage } from "./pages/ClientTabloListPage"; +import { ClientTabloPage } from "./pages/ClientTabloPage"; export default function AppRoutes() { return ( - Auth callback placeholder
} /> - Tablo view placeholder
} /> - Client portal placeholder
} /> + } /> + }> + } /> + } /> + ); } diff --git a/apps/clients/tsconfig.json b/apps/clients/tsconfig.json index 64a1401..f2fa327 100644 --- a/apps/clients/tsconfig.json +++ b/apps/clients/tsconfig.json @@ -3,6 +3,7 @@ "target": "ES2020", "useDefineForClassFields": true, "lib": ["ES2020", "DOM", "DOM.Iterable"], + "types": ["vite/client"], "module": "ESNext", "skipLibCheck": true, "moduleResolution": "bundler", From e8044182d8f9e39ab13078eba197d417160e2e7e Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 14:33:38 +0200 Subject: [PATCH 14/75] fix: resolve lint and formatting issues in apps/main Co-Authored-By: Claude Opus 4.6 (1M context) --- apps/main/src/components/ChatHeader.tsx | 4 +- .../main/src/components/DashboardTaskList.tsx | 2 +- apps/main/src/components/Layout.tsx | 10 +- apps/main/src/components/NavigationBar.tsx | 12 +- .../src/components/SubscriptionCard.test.tsx | 16 ++- .../TabloDiscussionSection.test.tsx | 2 +- .../components/TabloEventsSection.test.tsx | 2 +- .../src/components/TabloFilesSection.test.tsx | 9 +- .../src/components/TabloOverviewSection.tsx | 2 +- .../main/src/components/UpgradePanel.test.tsx | 14 ++- apps/main/src/components/UpgradePanel.tsx | 3 +- apps/main/src/components/kanban/index.ts | 2 +- .../src/contexts/UpgradeBlockContext.test.tsx | 16 ++- .../main/src/contexts/UpgradeBlockContext.tsx | 2 +- apps/main/src/hooks/auth.ts | 2 +- apps/main/src/hooks/client_invites.ts | 7 +- apps/main/src/hooks/tasks.ts | 2 +- apps/main/src/main.css | 8 +- apps/main/src/pages/chat.tsx | 4 +- apps/main/src/pages/settings.tsx | 6 +- apps/main/src/pages/tablo-details.tsx | 114 ++++++++++++------ apps/main/src/pages/tablo.tsx | 6 +- apps/main/src/pages/tasks.tsx | 2 +- 23 files changed, 153 insertions(+), 94 deletions(-) diff --git a/apps/main/src/components/ChatHeader.tsx b/apps/main/src/components/ChatHeader.tsx index da3664e..76a765f 100644 --- a/apps/main/src/components/ChatHeader.tsx +++ b/apps/main/src/components/ChatHeader.tsx @@ -42,9 +42,7 @@ export function ChatHeader({

{tablo.name}

{memberCount > 0 && ( -

- {memberCount} online -

+

{memberCount} online

)}
diff --git a/apps/main/src/components/DashboardTaskList.tsx b/apps/main/src/components/DashboardTaskList.tsx index 24c5772..0746bf5 100644 --- a/apps/main/src/components/DashboardTaskList.tsx +++ b/apps/main/src/components/DashboardTaskList.tsx @@ -1,5 +1,6 @@ import { cn } from "@xtablo/shared"; import type { KanbanTask, TaskStatus } from "@xtablo/shared-types"; +import { TaskModal } from "@xtablo/tablo-views"; import { CheckCircle2, Plus } from "lucide-react"; import { useState } from "react"; import { useTranslation } from "react-i18next"; @@ -7,7 +8,6 @@ import { useNavigate } from "react-router-dom"; import { useTablosList } from "../hooks/tablos"; import { useAllTasks, useUpdateTask } from "../hooks/tasks"; import { useUser } from "../providers/UserStoreProvider"; -import { TaskModal } from "@xtablo/tablo-views"; type TaskWithTablo = KanbanTask & { tablos: { id: string; name: string; color: string | null } | null; diff --git a/apps/main/src/components/Layout.tsx b/apps/main/src/components/Layout.tsx index a844ede..cf96f1b 100644 --- a/apps/main/src/components/Layout.tsx +++ b/apps/main/src/components/Layout.tsx @@ -54,11 +54,7 @@ export function Layout() { aria-label={isMobileMenuOpen ? "Close menu" : "Open menu"} aria-expanded={isMobileMenuOpen} > - {isMobileMenuOpen ? ( - - ) : ( - - )} + {isMobileMenuOpen ? : } {/* Mobile backdrop overlay */} @@ -66,9 +62,7 @@ export function Layout() { className={twMerge( "fixed inset-0 z-40 bg-black/50 md:hidden", "transition-opacity duration-300 ease-in-out", - isMobileMenuOpen - ? "opacity-100 pointer-events-auto" - : "opacity-0 pointer-events-none" + isMobileMenuOpen ? "opacity-100 pointer-events-auto" : "opacity-0 pointer-events-none" )} onClick={closeMobileMenu} aria-hidden="true" diff --git a/apps/main/src/components/NavigationBar.tsx b/apps/main/src/components/NavigationBar.tsx index adf6cc6..12ed900 100644 --- a/apps/main/src/components/NavigationBar.tsx +++ b/apps/main/src/components/NavigationBar.tsx @@ -301,11 +301,7 @@ export const SideNavigation = ({ isMobileMenuOpen }: { isMobileMenuOpen: boolean className={twMerge( "group isolate flex flex-col overflow-y-auto overflow-x-hidden bg-navbar-background transition-all duration-300", "h-full md:h-screen", - isMobileMenuOpen - ? "w-40" - : effectivelyCollapsed - ? "w-16" - : "w-48", + isMobileMenuOpen ? "w-40" : effectivelyCollapsed ? "w-16" : "w-48", "md:flex", // On mobile in standalone mode, respect safe area insets "pl-[env(safe-area-inset-left,0px)] pt-[env(safe-area-inset-top,0px)] pb-[env(safe-area-inset-bottom,0px)]" @@ -352,7 +348,11 @@ export const SideNavigation = ({ isMobileMenuOpen }: { isMobileMenuOpen: boolean "hover:scale-110" )} > - {effectivelyCollapsed ?
diff --git a/apps/main/src/components/SubscriptionCard.test.tsx b/apps/main/src/components/SubscriptionCard.test.tsx index c8a8af6..f065c5b 100644 --- a/apps/main/src/components/SubscriptionCard.test.tsx +++ b/apps/main/src/components/SubscriptionCard.test.tsx @@ -26,6 +26,7 @@ vi.mock("../hooks/auth", () => ({ import { useOrganization } from "../hooks/organization"; import { useSubscription } from "../hooks/stripe"; + const mockUseOrganization = vi.mocked(useOrganization); const mockUseSubscription = vi.mocked(useSubscription); @@ -51,7 +52,7 @@ const queryClient = new QueryClient({ function renderCard( user: User, orgData: ReturnType["data"], - subscription: ReturnType["data"] = undefined, + subscription: ReturnType["data"] = undefined ) { mockUseOrganization.mockReturnValue({ data: orgData, @@ -75,7 +76,14 @@ function renderCard( } const baseOrg = { - organization: { id: 1, name: "Org", plan: "none", member_count: 1, tablo_count: 0, logo_url: null }, + organization: { + id: 1, + name: "Org", + plan: "none", + member_count: 1, + tablo_count: 0, + logo_url: null, + }, members: [], invites_sent: [], trial_starts_at: "2026-01-01", @@ -123,9 +131,7 @@ describe("SubscriptionCard", () => { it("shows billing owner restriction when user is not billing owner", () => { const nonOwnerOrg = { ...baseOrg, is_billing_owner: false }; renderCard(baseUser, nonOwnerOrg); - expect( - screen.getByText(/Seul le propriétaire de facturation/) - ).toBeInTheDocument(); + expect(screen.getByText(/Seul le propriétaire de facturation/)).toBeInTheDocument(); expect(screen.queryByText(/Passer au plan/)).not.toBeInTheDocument(); }); diff --git a/apps/main/src/components/TabloDiscussionSection.test.tsx b/apps/main/src/components/TabloDiscussionSection.test.tsx index bac0eb6..08218e3 100644 --- a/apps/main/src/components/TabloDiscussionSection.test.tsx +++ b/apps/main/src/components/TabloDiscussionSection.test.tsx @@ -1,6 +1,6 @@ +import { TabloDiscussionSection } from "@xtablo/tablo-views"; import { describe, expect, it, vi } from "vitest"; import { renderWithProviders } from "../utils/testHelpers"; -import { TabloDiscussionSection } from "@xtablo/tablo-views"; vi.mock("@xtablo/tablo-views/hooks/useChat", () => ({ useChat: () => ({ diff --git a/apps/main/src/components/TabloEventsSection.test.tsx b/apps/main/src/components/TabloEventsSection.test.tsx index 3f06166..0fee1a3 100644 --- a/apps/main/src/components/TabloEventsSection.test.tsx +++ b/apps/main/src/components/TabloEventsSection.test.tsx @@ -1,6 +1,6 @@ +import { TabloEventsSection } from "@xtablo/tablo-views"; import { describe, expect, it, vi } from "vitest"; import { renderWithProviders } from "../utils/testHelpers"; -import { TabloEventsSection } from "@xtablo/tablo-views"; vi.mock("@xtablo/tablo-views/hooks/events", () => ({ useEventsByTablo: () => ({ diff --git a/apps/main/src/components/TabloFilesSection.test.tsx b/apps/main/src/components/TabloFilesSection.test.tsx index e8ec114..5aedd89 100644 --- a/apps/main/src/components/TabloFilesSection.test.tsx +++ b/apps/main/src/components/TabloFilesSection.test.tsx @@ -1,6 +1,6 @@ +import { TabloFilesSection } from "@xtablo/tablo-views"; import { describe, expect, it, vi } from "vitest"; import { renderWithProviders } from "../utils/testHelpers"; -import { TabloFilesSection } from "@xtablo/tablo-views"; vi.mock("../hooks/files", () => ({ useTabloFileNames: () => ({ @@ -29,7 +29,12 @@ describe("TabloFilesSection", () => { it("renders without crashing", () => { const { container } = renderWithProviders( - + ); expect(container).toBeInTheDocument(); }); diff --git a/apps/main/src/components/TabloOverviewSection.tsx b/apps/main/src/components/TabloOverviewSection.tsx index da680be..d111405 100644 --- a/apps/main/src/components/TabloOverviewSection.tsx +++ b/apps/main/src/components/TabloOverviewSection.tsx @@ -1,5 +1,6 @@ import { toast } from "@xtablo/shared"; import type { UserTablo } from "@xtablo/shared/types/tablos.types"; +import { TabloHeaderActions } from "@xtablo/tablo-views"; import { Button } from "@xtablo/ui/components/button"; import { Input } from "@xtablo/ui/components/input"; import { TypographyH3, TypographyMuted, TypographyP } from "@xtablo/ui/components/typography"; @@ -16,7 +17,6 @@ import { } from "../hooks/tasks"; import { useUser } from "../providers/UserStoreProvider"; import { getEtapeProgressStats } from "../utils/etapeProgress"; -import { TabloHeaderActions } from "@xtablo/tablo-views"; interface TabloOverviewSectionProps { tablo: UserTablo; diff --git a/apps/main/src/components/UpgradePanel.test.tsx b/apps/main/src/components/UpgradePanel.test.tsx index b1a0b6f..3b00d34 100644 --- a/apps/main/src/components/UpgradePanel.test.tsx +++ b/apps/main/src/components/UpgradePanel.test.tsx @@ -23,6 +23,7 @@ vi.mock("../hooks/auth", () => ({ })); import { useOrganization } from "../hooks/organization"; + const mockUseOrganization = vi.mocked(useOrganization); const baseUser: User = { @@ -63,7 +64,14 @@ function renderPanel(user: User, orgData: ReturnType["da } const noPlanOrg = { - organization: { id: 1, name: "Org", plan: "none", member_count: 1, tablo_count: 0, logo_url: null }, + organization: { + id: 1, + name: "Org", + plan: "none", + member_count: 1, + tablo_count: 0, + logo_url: null, + }, members: [], invites_sent: [], trial_starts_at: "2026-01-01", @@ -129,9 +137,7 @@ describe("UpgradePanel", () => { const soloButton = screen.getByText("Passer au plan Solo").closest("button"); expect(soloButton).toBeDisabled(); - expect( - screen.getByText(/Seul le propriétaire de facturation/) - ).toBeInTheDocument(); + expect(screen.getByText(/Seul le propriétaire de facturation/)).toBeInTheDocument(); }); it("renders nothing when org data is not yet loaded", () => { diff --git a/apps/main/src/components/UpgradePanel.tsx b/apps/main/src/components/UpgradePanel.tsx index aa2cbc9..12db069 100644 --- a/apps/main/src/components/UpgradePanel.tsx +++ b/apps/main/src/components/UpgradePanel.tsx @@ -129,7 +129,8 @@ export function UpgradePanel() { disabled={checkoutPending || !isBillingOwner} className="w-full" > - Passer au plan Teams ({requiredTeamQuantity} siège{requiredTeamQuantity > 1 ? "s" : ""}) + Passer au plan Teams ({requiredTeamQuantity} siège + {requiredTeamQuantity > 1 ? "s" : ""})
{/* ── Tab content ─────────────────────────────────────────────────── */} -
+
{activeSection === "overview" && (() => { const overviewBlocks: Record = { @@ -826,9 +850,13 @@ export const TabloDetailsPage = () => { onCreateTask={(task) => createTask(task)} onUpdateTask={(task) => updateTask(task)} onUpdateTaskPositions={(updates) => updateTaskPositions(updates)} - onUpdateTablo={(data) => updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => {})} + onUpdateTablo={(data) => + updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) + } onInviteUser={inviteUser} - onCancelInvite={(params) => cancelInvite({ ...params, inviteId: Number(params.inviteId) })} + onCancelInvite={(params) => + cancelInvite({ ...params, inviteId: Number(params.inviteId) }) + } /> )} {activeSection === "files" && ( @@ -849,15 +877,19 @@ export const TabloDetailsPage = () => { isCancellingInvite={isCancellingInvite} isCreatingFolder={isCreatingFolder} isUpdatingFolder={isUpdatingFolder} - onCreateFile={(params) => uploadFile(params).then(() => {})} - onDeleteFile={(params) => deleteFile(params).then(() => {})} - onDownloadFile={(params) => downloadFile(params).then(() => {})} - onCreateFolder={(params) => createFolder(params).then(() => {})} - onUpdateFolder={(params) => updateFolder(params).then(() => {})} - onDeleteFolder={(params) => deleteFolder(params).then(() => {})} - onUpdateTablo={(data) => updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => {})} + onCreateFile={(params) => uploadFile(params).then(() => undefined)} + onDeleteFile={(params) => deleteFile(params).then(() => undefined)} + onDownloadFile={(params) => downloadFile(params).then(() => undefined)} + onCreateFolder={(params) => createFolder(params).then(() => undefined)} + onUpdateFolder={(params) => updateFolder(params).then(() => undefined)} + onDeleteFolder={(params) => deleteFolder(params).then(() => undefined)} + onUpdateTablo={(data) => + updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) + } onInviteUser={inviteUser} - onCancelInvite={(params) => cancelInvite({ ...params, inviteId: Number(params.inviteId) })} + onCancelInvite={(params) => + cancelInvite({ ...params, inviteId: Number(params.inviteId) }) + } /> )} {activeSection === "discussion" && ( @@ -882,10 +914,14 @@ export const TabloDetailsPage = () => { pendingInvites={pendingInvites?.map((inv) => ({ ...inv, id: String(inv.id) }))} isInvitingUser={isInvitingUser} isCancellingInvite={isCancellingInvite} - onCreateEvent={() => {}} - onUpdateTablo={(data) => updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => {})} + onCreateEvent={() => undefined} + onUpdateTablo={(data) => + updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) + } onInviteUser={inviteUser} - onCancelInvite={(params) => cancelInvite({ ...params, inviteId: Number(params.inviteId) })} + onCancelInvite={(params) => + cancelInvite({ ...params, inviteId: Number(params.inviteId) }) + } /> )} @@ -895,8 +931,13 @@ export const TabloDetailsPage = () => { tabloTasks={tabloTasks} tabloId={tabloId ?? ""} isAdmin={isAdmin} - onCreateTask={(task) => createTask({ ...task, status: task.status as "todo" | "in_progress" | "in_review" | "done" })} - onCreateEtape={(params) => createEtape(params).then(() => {})} + onCreateTask={(task) => + createTask({ + ...task, + status: task.status as "todo" | "in_progress" | "in_review" | "done", + }) + } + onCreateEtape={(params) => createEtape(params).then(() => undefined)} isCreatingEtape={isCreatingEtape} /> )} @@ -1164,4 +1205,3 @@ export const TabloDetailsPage = () => {
); }; - diff --git a/apps/main/src/pages/tablo.tsx b/apps/main/src/pages/tablo.tsx index 622e533..f23fceb 100644 --- a/apps/main/src/pages/tablo.tsx +++ b/apps/main/src/pages/tablo.tsx @@ -3,6 +3,8 @@ import { DeleteTabloModal } from "@ui/components/DeleteTabloModal"; import { LoadingSpinner } from "@ui/components/LoadingSpinner"; import { toast } from "@xtablo/shared"; import { TabloInsert, UserTablo } from "@xtablo/shared/types/tablos.types"; +import { TaskModal } from "@xtablo/tablo-views"; +import { Badge } from "@xtablo/ui/components/badge"; import { Button } from "@xtablo/ui/components/button"; import { Empty, @@ -40,11 +42,9 @@ import { useNavigate, useSearchParams } from "react-router-dom"; import { DashboardActionCards } from "src/components/DashboardActionCards"; import { DashboardTaskList } from "src/components/DashboardTaskList"; import { InviteOrganizationModal } from "src/components/InviteOrganizationModal"; -import { TaskModal } from "@xtablo/tablo-views"; import { ProjectCardList } from "src/components/ProjectCardList"; -import { Badge } from "@xtablo/ui/components/badge"; -import { useCanCreateTablo, useCreateTablo, useDeleteTablo, useTablosList } from "../hooks/tablos"; import { useOrganization } from "../hooks/organization"; +import { useCanCreateTablo, useCreateTablo, useDeleteTablo, useTablosList } from "../hooks/tablos"; import { useIsReadOnlyUser, useUser } from "../providers/UserStoreProvider"; function getTabloIcon(color: string | null | undefined) { diff --git a/apps/main/src/pages/tasks.tsx b/apps/main/src/pages/tasks.tsx index a2763d2..40c6568 100644 --- a/apps/main/src/pages/tasks.tsx +++ b/apps/main/src/pages/tasks.tsx @@ -1,5 +1,6 @@ import { LoadingSpinner } from "@ui/components/LoadingSpinner"; import type { KanbanColumn, KanbanTask } from "@xtablo/shared-types"; +import { GanttChart, TaskModal } from "@xtablo/tablo-views"; import { Button } from "@xtablo/ui/components/button"; import { DropdownMenu, @@ -40,7 +41,6 @@ import { useMemo, useState } from "react"; import { useTranslation } from "react-i18next"; import { useNavigate, useSearchParams } from "react-router-dom"; import { twMerge } from "tailwind-merge"; -import { GanttChart, TaskModal } from "@xtablo/tablo-views"; import { useTablosList } from "../hooks/tablos"; import { useAllTasks, useUpdateTask } from "../hooks/tasks"; import { useUser } from "../providers/UserStoreProvider"; From a42b79574f82b89d7475d77c29560a8ec811dd8c Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 15:52:53 +0200 Subject: [PATCH 15/75] fix: unique inspector ports, remove temp invite UI, fix read-only race --- apps/clients/vite.config.ts | 4 +- apps/external/vite.config.ts | 4 +- apps/main/src/pages/tablo-details.tsx | 76 --------------------------- apps/main/src/pages/tablo.tsx | 2 +- apps/main/vite.config.ts | 2 +- 5 files changed, 6 insertions(+), 82 deletions(-) diff --git a/apps/clients/vite.config.ts b/apps/clients/vite.config.ts index 908aa8d..dfed7ff 100644 --- a/apps/clients/vite.config.ts +++ b/apps/clients/vite.config.ts @@ -5,10 +5,10 @@ import { defineConfig, type PluginOption } from "vite"; import tsconfigPaths from "vite-tsconfig-paths"; export default defineConfig(({ mode }) => { - const plugins: PluginOption[] = [react(), tailwindcss(), tsconfigPaths()]; + const plugins: PluginOption[] = [react(), tailwindcss(), tsconfigPaths({ ignoreConfigErrors: true })]; if (mode !== "test" && process.env.VITEST !== "true") { - plugins.push(cloudflare()); + plugins.push(cloudflare({ inspectorPort: 9232 })); } return { diff --git a/apps/external/vite.config.ts b/apps/external/vite.config.ts index 964bddd..8bd72da 100644 --- a/apps/external/vite.config.ts +++ b/apps/external/vite.config.ts @@ -16,12 +16,12 @@ export default defineConfig(({ mode }) => { react(), // visualizer() as PluginOption, tailwindcss(), - tsconfigPaths(), + tsconfigPaths({ ignoreConfigErrors: true }), ]; // Only include cloudflare plugin when not in test mode if (mode !== "test" && process.env.VITEST !== "true") { - plugins.push(cloudflare()); + plugins.push(cloudflare({ inspectorPort: 9231 })); } return { diff --git a/apps/main/src/pages/tablo-details.tsx b/apps/main/src/pages/tablo-details.tsx index c6eeb80..42988dd 100644 --- a/apps/main/src/pages/tablo-details.tsx +++ b/apps/main/src/pages/tablo-details.tsx @@ -971,82 +971,6 @@ export const TabloDetailsPage = () => {
- {/* Invite Input */} -
- setInviteEmail(e.target.value)} - placeholder="Email de l'utilisateur" - className="flex-1 min-h-[44px]" - /> - {isInvitingUser ? ( -
-
-
- ) : ( - - )} -
- - {/* Pending Invites */} - {pendingInvites && pendingInvites.length > 0 && ( -
-

- Invitations en attente ({pendingInvites.length}) -

-
- {pendingInvites.map((invite) => ( -
-
- - - -
-
- - {invite.invited_email} - -
- -
- ))} -
-
- )} - {/* Members List */} {filteredMembers && filteredMembers.length > 0 && (
diff --git a/apps/main/src/pages/tablo.tsx b/apps/main/src/pages/tablo.tsx index f23fceb..2a1caa3 100644 --- a/apps/main/src/pages/tablo.tsx +++ b/apps/main/src/pages/tablo.tsx @@ -107,7 +107,7 @@ export const TabloPage = () => { const user = useUser(); const { data: organizationData } = useOrganization(); - const isReadOnly = isReadOnlyUser || !canCreateTablo; + const isReadOnly = isReadOnlyUser || canCreateTablo === false; const getGreeting = () => { const hour = new Date().getHours(); diff --git a/apps/main/vite.config.ts b/apps/main/vite.config.ts index 87270d7..59e1e45 100644 --- a/apps/main/vite.config.ts +++ b/apps/main/vite.config.ts @@ -14,7 +14,7 @@ export default defineConfig(({ mode }) => { react(), visualizer() as PluginOption, tailwindcss(), - tsconfigPaths(), + tsconfigPaths({ ignoreConfigErrors: true }), ]; plugins.push( From 90fbbbfa53838cb9cee2979899ad7e2cead0a9c2 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 16:16:31 +0200 Subject: [PATCH 16/75] fix: remove unused handleSendInvite and inviteEmail state Co-Authored-By: Claude Opus 4.6 (1M context) --- apps/main/src/pages/tablo-details.tsx | 8 -------- 1 file changed, 8 deletions(-) diff --git a/apps/main/src/pages/tablo-details.tsx b/apps/main/src/pages/tablo-details.tsx index 42988dd..df06def 100644 --- a/apps/main/src/pages/tablo-details.tsx +++ b/apps/main/src/pages/tablo-details.tsx @@ -202,7 +202,6 @@ export const TabloDetailsPage = () => { ); const [showAllOverviewTasks, setShowAllOverviewTasks] = useState(false); const [isShareDialogOpen, setIsShareDialogOpen] = useState(false); - const [inviteEmail, setInviteEmail] = useState(""); const [clientInviteEmail, setClientInviteEmail] = useState(""); const [isLayoutEditMode, setIsLayoutEditMode] = useState(false); const [draggedOverviewBlock, setDraggedOverviewBlock] = useState<{ @@ -252,13 +251,6 @@ export const TabloDetailsPage = () => { return emailRegex.test(email); }; - const handleSendInvite = () => { - if (inviteEmail.trim() && tabloId) { - inviteUser({ email: inviteEmail, tablo_id: tabloId }); - setInviteEmail(""); - } - }; - const filteredMembers = members?.filter( (member) => !pendingInvites?.some((invite) => invite.invited_email === member.email) ); From abc0e65a86e394998658f6214130d85b84a84bc8 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 17:13:23 +0200 Subject: [PATCH 17/75] fix wrangler + send magic link --- apps/api/src/routers/clientInvites.ts | 20 +++++++++++++++++++- apps/clients/package.json | 2 +- apps/clients/tsconfig.tsbuildinfo | 1 + apps/clients/wrangler.toml | 7 +------ package.json | 1 + 5 files changed, 23 insertions(+), 8 deletions(-) create mode 100644 apps/clients/tsconfig.tsbuildinfo diff --git a/apps/api/src/routers/clientInvites.ts b/apps/api/src/routers/clientInvites.ts index c93f7c0..ba91a15 100644 --- a/apps/api/src/routers/clientInvites.ts +++ b/apps/api/src/routers/clientInvites.ts @@ -56,7 +56,7 @@ const createClientInvite = (middlewareManager: ReturnType", + to: rawEmail, + subject: "Vous avez été invité sur Xtablo", + html: ` +

Vous avez été invité à collaborer sur un tablo

+

Bonjour,

+

Cliquez sur le lien ci-dessous pour accéder à votre espace client :

+

Accéder à mon espace

+

Ce lien expire dans ${CLIENT_INVITE_EXPIRY_HOURS} heures.

+ `, + }); + } catch (emailError) { + console.error("Failed to send client invite email:", emailError); + } } return c.json({ success: true }); diff --git a/apps/clients/package.json b/apps/clients/package.json index 088606a..ce72e83 100644 --- a/apps/clients/package.json +++ b/apps/clients/package.json @@ -8,7 +8,7 @@ "build": "tsc -b && vite build --mode production", "build:staging": "tsc -b && vite build --mode staging", "build:prod": "tsc -b && vite build --mode production", - "deploy": "wrangler deploy", + "deploy:prod": "wrangler deploy --env=\"\"", "typecheck": "tsc -b", "lint": "biome check .", "lint:fix": "biome check --write .", diff --git a/apps/clients/tsconfig.tsbuildinfo b/apps/clients/tsconfig.tsbuildinfo new file mode 100644 index 0000000..a7db947 --- /dev/null +++ b/apps/clients/tsconfig.tsbuildinfo @@ -0,0 +1 @@ +{"root":["./src/app.tsx","./src/i18n.ts","./src/main.tsx","./src/routes.tsx","./src/components/clientlayout.tsx","./src/lib/supabase.ts","./src/pages/authcallback.tsx","./src/pages/clienttablolistpage.tsx","./src/pages/clienttablopage.tsx"],"version":"5.9.3"} \ No newline at end of file diff --git a/apps/clients/wrangler.toml b/apps/clients/wrangler.toml index 13aff9a..8baaf4a 100644 --- a/apps/clients/wrangler.toml +++ b/apps/clients/wrangler.toml @@ -1,6 +1,7 @@ name = "xtablo-clients" main = "worker/index.ts" compatibility_date = "2025-07-09" +route = { pattern = "clients.xtablo.com", custom_domain = true } [assets] directory = "./dist/" @@ -8,9 +9,3 @@ not_found_handling = "single-page-application" [observability] enabled = true - -[env.staging] -route = { pattern = "clients-staging.xtablo.com", custom_domain = true } - -[env.production] -route = { pattern = "clients.xtablo.com", custom_domain = true } diff --git a/package.json b/package.json index bf99826..5366d4f 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,7 @@ "deploy:main:prod": "turbo deploy:prod --filter=@xtablo/main", "deploy:chat": "turbo deploy --filter=@xtablo/chat-worker", "deploy:external": "turbo deploy --filter=@xtablo/external", + "deploy:clients": "turbo deploy:prod --filter=@xtablo/clients", "lint": "turbo lint", "lint:fix": "turbo lint:fix", "format": "turbo format", From 3c8e3c6af32956f557f1f4bb871319e809e1784d Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 17:19:13 +0200 Subject: [PATCH 18/75] Add recipes in turbo.json --- turbo.json | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/turbo.json b/turbo.json index 48afb1d..1a1beb2 100644 --- a/turbo.json +++ b/turbo.json @@ -43,6 +43,28 @@ "cache": false, "persistent": true }, + "deploy": { + "dependsOn": ["build"], + "cache": false + }, + "deploy:staging": { + "dependsOn": ["build:staging"], + "cache": false + }, + "deploy:prod": { + "dependsOn": ["build:prod"], + "cache": false + }, + "build:staging": { + "dependsOn": ["^build"], + "outputs": ["dist/**"], + "outputLogs": "new-only" + }, + "build:prod": { + "dependsOn": ["^build"], + "outputs": ["dist/**"], + "outputLogs": "new-only" + }, "clean": { "cache": false } From 29debcbf25f838edda98819c7606cdf780ee0f0b Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 21:39:08 +0200 Subject: [PATCH 19/75] Fix session context --- apps/clients/.env.production | 4 ++++ packages/shared/src/contexts/SessionContext.tsx | 4 ++++ 2 files changed, 8 insertions(+) create mode 100644 apps/clients/.env.production diff --git a/apps/clients/.env.production b/apps/clients/.env.production new file mode 100644 index 0000000..f63a9df --- /dev/null +++ b/apps/clients/.env.production @@ -0,0 +1,4 @@ +VITE_SUPABASE_URL=https://mhcafqvzbrrwvahpvvzd.supabase.co +VITE_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im1oY2FmcXZ6YnJyd3ZhaHB2dnpkIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDEyNDEzMjEsImV4cCI6MjA1NjgxNzMyMX0.Otxn5BWCPD2ABlMM59hCgeur9Tf_Q7PndAbTkqXDPtM + +VITE_API_URL=https://xablo-api-636270553187.europe-west1.run.app diff --git a/packages/shared/src/contexts/SessionContext.tsx b/packages/shared/src/contexts/SessionContext.tsx index e4fb6a9..6827fee 100644 --- a/packages/shared/src/contexts/SessionContext.tsx +++ b/packages/shared/src/contexts/SessionContext.tsx @@ -21,6 +21,10 @@ export const SessionProvider = ({ supabase, children }: Props) => { const [session, setSession] = useState(null); useEffect(() => { + supabase.auth.getSession().then(({ data: { session } }) => { + setSession(session); + }); + const authStateListener = supabase.auth.onAuthStateChange(async (_, session) => { setSession(session); }); From ebf6d8a25532d98d874c0172ece33a8b16249db4 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 21:51:20 +0200 Subject: [PATCH 20/75] Avoid checking regularUserCheck in acceptClientInvite --- apps/api/src/routers/clientInvites.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/api/src/routers/clientInvites.ts b/apps/api/src/routers/clientInvites.ts index ba91a15..f14f977 100644 --- a/apps/api/src/routers/clientInvites.ts +++ b/apps/api/src/routers/clientInvites.ts @@ -89,8 +89,8 @@ const createClientInvite = (middlewareManager: ReturnType) => - factory.createHandlers(middlewareManager.regularUserCheck, async (c) => { +const acceptClientInvite = (_middlewareManager: ReturnType) => + factory.createHandlers(async (c) => { const user = c.get("user"); const supabase = c.get("supabase"); const token = c.req.param("token"); From d69bfffd6fbccb18a44293f6fb47576df433d56a Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 22:18:27 +0200 Subject: [PATCH 21/75] docs: add client portal tablo parity design spec --- ...04-15-client-portal-tablo-parity-design.md | 216 ++++++++++++++++++ 1 file changed, 216 insertions(+) create mode 100644 docs/superpowers/specs/2026-04-15-client-portal-tablo-parity-design.md diff --git a/docs/superpowers/specs/2026-04-15-client-portal-tablo-parity-design.md b/docs/superpowers/specs/2026-04-15-client-portal-tablo-parity-design.md new file mode 100644 index 0000000..8cedbad --- /dev/null +++ b/docs/superpowers/specs/2026-04-15-client-portal-tablo-parity-design.md @@ -0,0 +1,216 @@ +# Client Portal Tablo Parity + +**Date**: 2026-04-15 +**Status**: Approved + +## Overview + +Make the client portal route in `apps/clients` match the visual design of the main app route `apps/main` `/tablos/:tabloId` as closely as possible. + +The target route in `apps/clients` remains `/tablo/:tabloId`, but it should present the same shell language as `TabloDetailsPage`: + +- same header structure +- same metadata bar +- same sticky tab navigation +- same overview card layout and styling +- same Tailwind/CSS visual system +- same translation strategy through i18n + +The client portal keeps its simpler local tab state and stays read-only except for discussion. + +## Goals + +- Match the current `apps/main` `TabloDetailsPage` look as closely as possible +- Prevent visual drift between `apps/main` and `apps/clients` +- Reuse the existing shared `@xtablo/tablo-views` section components +- Keep the client portal safe by removing admin and mutation affordances +- Use shared i18n keys wherever possible instead of hardcoded copy + +## Non-Goals + +- Rebuilding the client portal as a separate visual concept +- Copying the main app's `?section=` route model into `apps/clients` +- Enabling client file uploads, task completion, task creation, or layout editing +- Refactoring unrelated app-level layout or navigation outside the tablo detail view + +## Chosen Approach + +Use a shared presentational shell for the tablo detail page, backed by a shared stylesheet source. + +This shell should live close to the existing shared tablo view layer, likely in `packages/tablo-views`, because that package already contains the shared section components used by both apps. + +Each app remains responsible for its own routing, data hooks, and permissions: + +- `apps/main` keeps full `TabloDetailsPage` behavior +- `apps/clients` keeps local internal tab state and client-specific data loading + +The shared shell owns the route-level presentation so visual changes land in one place and are inherited by both apps. + +## Shared CSS Source + +Exact visual parity requires shared CSS, not just shared JSX. + +Today both apps import `@xtablo/ui/styles/globals.css`, but `apps/main/src/main.css` and `apps/clients/src/main.css` already diverge on important visual tokens such as: + +- navbar colors +- dark mode tokens +- chat surface colors +- other route-level color variables + +Because of that, `apps/clients` must not keep an independent competing style source for this page. + +### Requirement + +Extract the route-relevant visual styles currently coming from `apps/main/src/main.css` into a shared stylesheet layer that both apps import. + +This shared stylesheet should include whatever is required for the tablo detail route to render identically, including: + +- theme tokens needed by the page shell +- chat-related styling used in the discussion tab +- any utility styles relied on by the shared shell + +### Constraint + +Do not import `apps/main/src/main.css` directly from `apps/clients`. That would create brittle cross-app coupling and make ownership unclear. + +Instead: + +- move route-relevant shared styles into a shared import +- keep app-specific styles in each app-local `main.css` + +## Shared Shell Responsibilities + +The shared tablo detail shell should own: + +- the project header layout +- the icon/image block next to the project title +- header action placement +- the metadata bar layout and styling +- sticky tab navigation styling and behavior hooks +- the overview page card grid and visual treatment + +The shell should accept data and slots through props rather than owning app-specific mutations or routing decisions. + +Suggested inputs: + +- `tablo` +- status label and badge styling +- progress values +- role label +- created-at label +- tab definitions +- active tab +- tab change handler +- header action slot +- overview capability flags or overview card content +- per-section capability flags such as read-only settings + +## `apps/main` Responsibilities + +`apps/main` remains the owner of: + +- `?section=` URL state +- invite and share flows +- client invite management +- overview layout editing +- task creation and mutation +- file mutations +- admin-only controls + +The main app should adopt the shared shell without losing any existing behavior. + +## `apps/clients` Responsibilities + +`apps/clients` adopts the same visual shell, but keeps a restricted capability profile. + +### Navigation + +- Keep the current local tab state in React +- Do not add `?section=` routing +- Keep the same visible tab order, icons, and active styling as `apps/main` + +### Header + +- Keep the same header structure and spacing as `apps/main` +- Keep the discussion CTA styling and placement +- Remove the `Inviter` action entirely + +### Metadata Bar + +- Keep the same metadata structure and styling +- Use client-safe translated labels for role and status copy + +### Overview + +- Use the same card layout and card styling as the main app +- Remove layout edit controls +- Remove task creation controls +- Make task completion non-interactive +- Keep file previews informational only + +### Read-only Scope + +The client portal should be read-only except for discussion. + +That means: + +- `discussion`: interactive +- `tasks`: readable, no mutations +- `etapes`: readable, no mutations +- `events`: readable, no mutations +- `roadmap`: readable, no mutations +- `files`: readable, no upload, rename, move, create-folder, delete, or overflow action UI + +## i18n + +The shared shell must not introduce new hardcoded French strings. + +### Rules + +- Reuse existing translation keys from `apps/main` when the copy already matches the desired wording +- Add missing keys only where the shared shell needs copy that does not already exist +- Ensure both `apps/main` and `apps/clients` can resolve the keys used by the shared shell +- Prefer shared wording for labels like tab names, metadata labels, and overview headings + +This keeps parity at the copy level and avoids one app silently diverging from the other. + +## Testing And Verification + +Implementation should prove both parity and restrictions. + +### Automated + +- Add tests that verify the client shell renders the same key structure as the main shell +- Add tests that verify client mode hides admin and mutation controls +- Add tests that discussion remains interactive while other sections are read-only + +### Manual + +Perform side-by-side checks between: + +- `apps/main` `/tablos/:tabloId` +- `apps/clients` `/tablo/:tabloId` + +Compare at minimum: + +- header layout +- metadata bar +- sticky tabs +- overview cards +- tab content framing +- discussion styling + +## Risks + +- Shared CSS extraction may expose assumptions currently embedded in app-local stylesheets +- Some `TabloDetailsPage` copy is currently hardcoded and will need i18n cleanup before sharing +- If the shared shell grows to own business logic, parity will become harder to maintain + +## Success Criteria + +This work is successful when: + +- the client portal visually matches the main app tablo detail route +- the shared shell and shared style source make future parity maintainable +- the client portal remains read-only except for discussion +- the route continues to use simpler internal navigation rather than query-param section routing From 3c6a0fb037fa9a62a37dc52a99a34420356e0242 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 22:34:31 +0200 Subject: [PATCH 22/75] test: fix main app baseline chat and tablo tests --- apps/main/src/i18n.test.ts | 4 ++ .../src/pages/tablo-details.layout.test.tsx | 53 +++++++++++++++++++ apps/main/src/setupTests.ts | 1 + 3 files changed, 58 insertions(+) diff --git a/apps/main/src/i18n.test.ts b/apps/main/src/i18n.test.ts index 5254707..3dfccc7 100644 --- a/apps/main/src/i18n.test.ts +++ b/apps/main/src/i18n.test.ts @@ -2,6 +2,7 @@ import i18n from "i18next"; import { initReactI18next } from "react-i18next"; import authEn from "./locales/en/auth.json"; import availabilitiesEn from "./locales/en/availabilities.json"; +import chatEn from "./locales/en/chat.json"; import commonEn from "./locales/en/common.json"; import componentsEn from "./locales/en/components.json"; import modalsEn from "./locales/en/modals.json"; @@ -13,6 +14,7 @@ import settingsEn from "./locales/en/settings.json"; import tabloEn from "./locales/en/tablo.json"; import authFr from "./locales/fr/auth.json"; import availabilitiesFr from "./locales/fr/availabilities.json"; +import chatFr from "./locales/fr/chat.json"; import commonFr from "./locales/fr/common.json"; import componentsFr from "./locales/fr/components.json"; import modalsFr from "./locales/fr/modals.json"; @@ -31,6 +33,7 @@ i18n.use(initReactI18next).init({ pages: pagesFr, settings: settingsFr, availabilities: availabilitiesFr, + chat: chatFr, auth: authFr, planning: planningFr, modals: modalsFr, @@ -44,6 +47,7 @@ i18n.use(initReactI18next).init({ pages: pagesEn, settings: settingsEn, availabilities: availabilitiesEn, + chat: chatEn, auth: authEn, planning: planningEn, modals: modalsEn, diff --git a/apps/main/src/pages/tablo-details.layout.test.tsx b/apps/main/src/pages/tablo-details.layout.test.tsx index 67da71d..76bfe34 100644 --- a/apps/main/src/pages/tablo-details.layout.test.tsx +++ b/apps/main/src/pages/tablo-details.layout.test.tsx @@ -62,6 +62,20 @@ vi.mock("../hooks/tablo_invites", () => ({ }), })); +vi.mock("../hooks/client_invites", () => ({ + usePendingClientInvites: () => ({ + data: [], + }), + useCreateClientInvite: () => ({ + mutate: vi.fn(), + isPending: false, + }), + useCancelClientInvite: () => ({ + mutate: vi.fn(), + isPending: false, + }), +})); + vi.mock("../hooks/invite", () => ({ useInviteUser: () => ({ mutate: vi.fn(), @@ -69,6 +83,14 @@ vi.mock("../hooks/invite", () => ({ }), })); +vi.mock("../hooks/events", () => ({ + useEventsByTablo: () => ({ + data: [], + isLoading: false, + error: null, + }), +})); + vi.mock("../hooks/tasks", () => ({ useAllTasks: () => ({ data: [ @@ -97,6 +119,9 @@ vi.mock("../hooks/tasks", () => ({ useCreateTask: () => ({ mutate: vi.fn(), }), + useUpdateTaskPositions: () => ({ + mutate: vi.fn(), + }), })); vi.mock("../hooks/tablo_data", () => ({ @@ -105,6 +130,34 @@ vi.mock("../hooks/tablo_data", () => ({ fileNames: [], }, }), + useDownloadTabloFile: () => ({ + mutateAsync: vi.fn(), + }), + useUploadTabloFile: () => ({ + mutateAsync: vi.fn(), + }), + useDeleteTabloFile: () => ({ + mutateAsync: vi.fn(), + }), +})); + +vi.mock("../hooks/tablo_folders", () => ({ + useTabloFolders: () => ({ + data: [], + isLoading: false, + error: null, + }), + useCreateTabloFolder: () => ({ + mutateAsync: vi.fn(), + isPending: false, + }), + useUpdateTabloFolder: () => ({ + mutateAsync: vi.fn(), + isPending: false, + }), + useDeleteTabloFolder: () => ({ + mutateAsync: vi.fn(), + }), })); vi.mock("../providers/UserStoreProvider", async (importOriginal) => { diff --git a/apps/main/src/setupTests.ts b/apps/main/src/setupTests.ts index 9960601..1fa4e83 100644 --- a/apps/main/src/setupTests.ts +++ b/apps/main/src/setupTests.ts @@ -23,6 +23,7 @@ global.ResizeObserver = class ResizeObserver { // Mock scrollIntoView for Radix UI components Element.prototype.scrollIntoView = vi.fn(); +Element.prototype.scrollTo = vi.fn(); Object.defineProperty(window, "matchMedia", { writable: true, From 01960a0102dd8a3838d82ad37b0a842facc9b11a Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 22:34:37 +0200 Subject: [PATCH 23/75] test: add clients app vitest harness --- apps/clients/package.json | 7 +++ apps/clients/src/i18n.test.ts | 43 ++++++++++++++ apps/clients/src/i18n.ts | 20 +++++++ apps/clients/src/setupTests.ts | 31 +++++++++++ apps/clients/src/test/testHelpers.test.tsx | 11 ++++ apps/clients/src/test/testHelpers.tsx | 65 ++++++++++++++++++++++ apps/clients/vite.config.ts | 11 ++++ pnpm-lock.yaml | 15 +++++ 8 files changed, 203 insertions(+) create mode 100644 apps/clients/src/i18n.test.ts create mode 100644 apps/clients/src/setupTests.ts create mode 100644 apps/clients/src/test/testHelpers.test.tsx create mode 100644 apps/clients/src/test/testHelpers.tsx diff --git a/apps/clients/package.json b/apps/clients/package.json index ce72e83..68c5563 100644 --- a/apps/clients/package.json +++ b/apps/clients/package.json @@ -10,6 +10,8 @@ "build:prod": "tsc -b && vite build --mode production", "deploy:prod": "wrangler deploy --env=\"\"", "typecheck": "tsc -b", + "test": "vitest run --mode test --passWithNoTests", + "test:watch": "vitest watch --passWithNoTests", "lint": "biome check .", "lint:fix": "biome check --write .", "format": "biome format --write .", @@ -20,14 +22,19 @@ "@biomejs/biome": "2.2.5", "@cloudflare/vite-plugin": "^1.9.4", "@tailwindcss/vite": "^4.0.14", + "@testing-library/jest-dom": "^6.9.1", + "@testing-library/react": "^16.3.0", + "@testing-library/user-event": "^14.6.1", "@types/react": "19.0.10", "@types/react-dom": "19.0.4", "@vitejs/plugin-react": "^4.3.4", + "jsdom": "^20.0.3", "tailwindcss": "^4.0.14", "tw-animate-css": "^1.4.0", "typescript": "^5.7.0", "vite": "^6.2.2", "vite-tsconfig-paths": "^5.1.4", + "vitest": "^3.2.4", "wrangler": "^4.24.3" }, "dependencies": { diff --git a/apps/clients/src/i18n.test.ts b/apps/clients/src/i18n.test.ts new file mode 100644 index 0000000..e7747d7 --- /dev/null +++ b/apps/clients/src/i18n.test.ts @@ -0,0 +1,43 @@ +import i18n from "i18next"; +import { initReactI18next } from "react-i18next"; +import bookingEn from "./locales/en/booking.json"; +import bookingFr from "./locales/fr/booking.json"; +import chatEn from "../../main/src/locales/en/chat.json"; +import commonEn from "../../main/src/locales/en/common.json"; +import componentsEn from "../../main/src/locales/en/components.json"; +import pagesEn from "../../main/src/locales/en/pages.json"; +import tabloEn from "../../main/src/locales/en/tablo.json"; +import chatFr from "../../main/src/locales/fr/chat.json"; +import commonFr from "../../main/src/locales/fr/common.json"; +import componentsFr from "../../main/src/locales/fr/components.json"; +import pagesFr from "../../main/src/locales/fr/pages.json"; +import tabloFr from "../../main/src/locales/fr/tablo.json"; + +i18n.use(initReactI18next).init({ + resources: { + fr: { + booking: bookingFr, + chat: chatFr, + common: commonFr, + components: componentsFr, + pages: pagesFr, + tablo: tabloFr, + }, + en: { + booking: bookingEn, + chat: chatEn, + common: commonEn, + components: componentsEn, + pages: pagesEn, + tablo: tabloEn, + }, + }, + lng: "fr", + fallbackLng: "fr", + defaultNS: "booking", + interpolation: { + escapeValue: false, + }, +}); + +export default i18n; diff --git a/apps/clients/src/i18n.ts b/apps/clients/src/i18n.ts index 334b18e..5612ccd 100644 --- a/apps/clients/src/i18n.ts +++ b/apps/clients/src/i18n.ts @@ -4,6 +4,16 @@ import { initReactI18next } from "react-i18next"; import bookingEn from "./locales/en/booking.json"; // Import translation files import bookingFr from "./locales/fr/booking.json"; +import chatEn from "../../main/src/locales/en/chat.json"; +import commonEn from "../../main/src/locales/en/common.json"; +import componentsEn from "../../main/src/locales/en/components.json"; +import pagesEn from "../../main/src/locales/en/pages.json"; +import tabloEn from "../../main/src/locales/en/tablo.json"; +import chatFr from "../../main/src/locales/fr/chat.json"; +import commonFr from "../../main/src/locales/fr/common.json"; +import componentsFr from "../../main/src/locales/fr/components.json"; +import pagesFr from "../../main/src/locales/fr/pages.json"; +import tabloFr from "../../main/src/locales/fr/tablo.json"; i18n .use(LanguageDetector) @@ -12,9 +22,19 @@ i18n resources: { fr: { booking: bookingFr, + chat: chatFr, + common: commonFr, + components: componentsFr, + pages: pagesFr, + tablo: tabloFr, }, en: { booking: bookingEn, + chat: chatEn, + common: commonEn, + components: componentsEn, + pages: pagesEn, + tablo: tabloEn, }, }, fallbackLng: "fr", diff --git a/apps/clients/src/setupTests.ts b/apps/clients/src/setupTests.ts new file mode 100644 index 0000000..ae81371 --- /dev/null +++ b/apps/clients/src/setupTests.ts @@ -0,0 +1,31 @@ +import "@testing-library/jest-dom"; +import { cleanup } from "@testing-library/react"; +import { vi } from "vitest"; +import "./i18n.test"; + +afterEach(() => { + cleanup(); +}); + +global.ResizeObserver = class ResizeObserver { + observe() {} + unobserve() {} + disconnect() {} +}; + +Element.prototype.scrollIntoView = vi.fn(); +Element.prototype.scrollTo = vi.fn(); + +Object.defineProperty(window, "matchMedia", { + writable: true, + value: vi.fn().mockImplementation((query) => ({ + matches: false, + media: query, + onchange: null, + addListener: vi.fn(), + removeListener: vi.fn(), + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + dispatchEvent: vi.fn(), + })), +}); diff --git a/apps/clients/src/test/testHelpers.test.tsx b/apps/clients/src/test/testHelpers.test.tsx new file mode 100644 index 0000000..435c9bc --- /dev/null +++ b/apps/clients/src/test/testHelpers.test.tsx @@ -0,0 +1,11 @@ +import { describe, expect, it } from "vitest"; +import { screen } from "@testing-library/react"; +import { renderWithProviders } from "./testHelpers"; + +describe("client test harness", () => { + it("renders a smoke test placeholder", () => { + renderWithProviders(
client test harness
); + + expect(screen.getByText("client test harness")).toBeInTheDocument(); + }); +}); diff --git a/apps/clients/src/test/testHelpers.tsx b/apps/clients/src/test/testHelpers.tsx new file mode 100644 index 0000000..ede64d8 --- /dev/null +++ b/apps/clients/src/test/testHelpers.tsx @@ -0,0 +1,65 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { render, type RenderResult } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { SessionTestProvider } from "@xtablo/shared/contexts/SessionContext"; +import { ThemeProvider } from "@xtablo/shared/contexts/ThemeContext"; +import React from "react"; +import { I18nextProvider } from "react-i18next"; +import { MemoryRouter, Route, Routes } from "react-router-dom"; +import testI18n from "../i18n.test"; + +const defaultUser = { + id: "client-user-1", + app_metadata: {}, + aud: "test", + created_at: "2021-01-01", + email: "client@example.com", + user_metadata: { + full_name: "Client User", + }, +}; + +interface RenderWithProvidersOptions { + route?: string; + path?: string; + language?: string; +} + +export const renderWithProviders = ( + ui: React.ReactNode, + { route = "/", path, language = "fr" }: RenderWithProvidersOptions = {} +): RenderResult & { user: ReturnType } => { + testI18n.changeLanguage(language); + + const testQueryClient = new QueryClient({ + defaultOptions: { + queries: { + retry: false, + staleTime: Infinity, + }, + }, + }); + + const content = path ? ( + + + + ) : ( + ui + ); + + return { + user: userEvent.setup(), + ...render( + + + + + {content} + + + + + ), + }; +}; diff --git a/apps/clients/vite.config.ts b/apps/clients/vite.config.ts index dfed7ff..7b36df3 100644 --- a/apps/clients/vite.config.ts +++ b/apps/clients/vite.config.ts @@ -14,5 +14,16 @@ export default defineConfig(({ mode }) => { return { plugins, server: { cors: false }, + define: process.env.VITEST + ? { + "import.meta.env.VITE_SUPABASE_URL": JSON.stringify("https://test.supabase.co"), + "import.meta.env.VITE_SUPABASE_ANON_KEY": JSON.stringify("test-anon-key"), + } + : undefined, + test: { + globals: true, + environment: "jsdom", + setupFiles: "./src/setupTests.ts", + }, }; }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ecad098..e797dbd 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -197,6 +197,15 @@ importers: '@tailwindcss/vite': specifier: ^4.0.14 version: 4.1.15(vite@6.4.1(@types/node@22.18.12)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6)) + '@testing-library/jest-dom': + specifier: ^6.9.1 + version: 6.9.1 + '@testing-library/react': + specifier: ^16.3.0 + version: 16.3.0(@testing-library/dom@10.4.1)(@types/react-dom@19.0.4(@types/react@19.0.10))(@types/react@19.0.10)(react-dom@19.0.0(react@19.0.0))(react@19.0.0) + '@testing-library/user-event': + specifier: ^14.6.1 + version: 14.6.1(@testing-library/dom@10.4.1) '@types/react': specifier: 19.0.10 version: 19.0.10 @@ -206,6 +215,9 @@ importers: '@vitejs/plugin-react': specifier: ^4.3.4 version: 4.7.0(vite@6.4.1(@types/node@22.18.12)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6)) + jsdom: + specifier: ^20.0.3 + version: 20.0.3 tailwindcss: specifier: ^4.0.14 version: 4.1.15 @@ -221,6 +233,9 @@ importers: vite-tsconfig-paths: specifier: ^5.1.4 version: 5.1.4(typescript@5.9.3)(vite@6.4.1(@types/node@22.18.12)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6)) + vitest: + specifier: ^3.2.4 + version: 3.2.4(@types/debug@4.1.12)(@types/node@22.18.12)(happy-dom@20.0.7)(jiti@2.6.1)(jsdom@20.0.3)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6) wrangler: specifier: ^4.24.3 version: 4.44.0(@cloudflare/workers-types@4.20260411.1) From 8f3927b68d06df96750a11ba13c7aaf88e4f3fbe Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 22:42:02 +0200 Subject: [PATCH 24/75] feat: align client tablo page with main shell --- apps/clients/src/main.tsx | 1 + .../src/pages/ClientTabloPage.test.tsx | 131 +++++++ apps/clients/src/pages/ClientTabloPage.tsx | 327 +++++++++++++++--- apps/clients/src/setupTests.ts | 2 +- apps/main/src/locales/en/pages.json | 6 + apps/main/src/locales/fr/pages.json | 6 + packages/tablo-views/package.json | 1 + .../tablo-views/src/TabloDetailsShell.tsx | 119 +++++++ packages/tablo-views/src/index.ts | 2 + .../src/styles/tablo-details-shell.css | 40 +++ 10 files changed, 588 insertions(+), 47 deletions(-) create mode 100644 apps/clients/src/pages/ClientTabloPage.test.tsx create mode 100644 packages/tablo-views/src/TabloDetailsShell.tsx create mode 100644 packages/tablo-views/src/styles/tablo-details-shell.css diff --git a/apps/clients/src/main.tsx b/apps/clients/src/main.tsx index d158df1..073fb40 100644 --- a/apps/clients/src/main.tsx +++ b/apps/clients/src/main.tsx @@ -10,6 +10,7 @@ import App from "./App"; import { supabase } from "./lib/supabase"; import "@xtablo/ui/styles/globals.css"; +import "@xtablo/tablo-views/styles/tablo-details-shell.css"; import "./main.css"; import "./i18n"; diff --git a/apps/clients/src/pages/ClientTabloPage.test.tsx b/apps/clients/src/pages/ClientTabloPage.test.tsx new file mode 100644 index 0000000..8380d98 --- /dev/null +++ b/apps/clients/src/pages/ClientTabloPage.test.tsx @@ -0,0 +1,131 @@ +import { screen } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; +import { renderWithProviders } from "../test/testHelpers"; +import { ClientTabloPage } from "./ClientTabloPage"; + +vi.mock("@tanstack/react-query", async (importOriginal) => { + const actual = await importOriginal(); + + return { + ...actual, + useQuery: ({ queryKey }: { queryKey: string[] }) => { + switch (queryKey[0]) { + case "client-tablo": + return { + data: { + id: "tablo-1", + name: "Client Project", + color: "bg-blue-500", + image: null, + created_at: "2026-01-01T00:00:00.000Z", + deleted_at: null, + position: 0, + status: "todo", + user_id: "user-1", + is_admin: false, + access_level: "guest", + }, + isLoading: false, + }; + case "client-tasks": + return { + data: [ + { + id: "task-1", + title: "Prepare proposal", + status: "todo", + tablo_id: "tablo-1", + assignee_id: "client-user-1", + }, + ], + isLoading: false, + error: null, + }; + case "client-etapes": + return { + data: [ + { + id: "etape-1", + title: "Kickoff", + status: "in_progress", + position: 0, + }, + ], + isLoading: false, + error: null, + }; + case "client-events": + case "client-members": + case "client-tablo-folders": + return { + data: [], + isLoading: false, + error: null, + }; + case "client-tablo-files": + return { + data: { fileNames: [] }, + isLoading: false, + error: null, + }; + default: + return { + data: undefined, + isLoading: false, + error: null, + }; + } + }, + }; +}); + +vi.mock("@xtablo/tablo-views", async (importOriginal) => { + const actual = await importOriginal(); + + return { + ...actual, + EtapesSection: () =>
Etapes section
, + RoadmapSection: () =>
Roadmap section
, + TabloDiscussionSection: () =>
Discussion section
, + TabloEventsSection: () =>
Events section
, + TabloFilesSection: () =>
Files section
, + TabloTasksSection: () =>
Tasks section
, + }; +}); + +describe("ClientTabloPage parity shell", () => { + it("renders the main-route style header metadata and discussion CTA", () => { + renderWithProviders(, { + route: "/tablo/tablo-1", + path: "/tablo/:tabloId", + }); + + expect(screen.getByText("Client Project")).toBeInTheDocument(); + expect(screen.getAllByRole("button", { name: "Discussion" })).toHaveLength(2); + expect(screen.getByText("Rôle :")).toBeInTheDocument(); + expect(screen.getByText("Créé le :")).toBeInTheDocument(); + expect(screen.getByText("Progression :")).toBeInTheDocument(); + }); + + it("keeps client restrictions by hiding invite and layout-edit controls", () => { + renderWithProviders(, { + route: "/tablo/tablo-1", + path: "/tablo/:tabloId", + }); + + expect(screen.queryByRole("button", { name: "Inviter" })).not.toBeInTheDocument(); + expect(screen.queryByRole("button", { name: "Modifier la mise en page" })).not.toBeInTheDocument(); + }); + + it("renders a read-only overview matching the main route cards", () => { + renderWithProviders(, { + route: "/tablo/tablo-1", + path: "/tablo/:tabloId", + }); + + expect(screen.getByText("Description du projet")).toBeInTheDocument(); + expect(screen.getByText("Mes tâches")).toBeInTheDocument(); + expect(screen.getByText("Informations")).toBeInTheDocument(); + expect(screen.queryByRole("button", { name: "Ajouter" })).not.toBeInTheDocument(); + }); +}); diff --git a/apps/clients/src/pages/ClientTabloPage.tsx b/apps/clients/src/pages/ClientTabloPage.tsx index 3da9be0..0f536d4 100644 --- a/apps/clients/src/pages/ClientTabloPage.tsx +++ b/apps/clients/src/pages/ClientTabloPage.tsx @@ -1,13 +1,34 @@ import { useQuery } from "@tanstack/react-query"; +import { cn } from "@xtablo/shared"; import { buildApi } from "@xtablo/shared"; import { useSession } from "@xtablo/shared/contexts/SessionContext"; import type { Etape, KanbanTask, TabloFolder, UserTablo } from "@xtablo/shared-types"; -import { CalendarIcon, FolderIcon, KanbanIcon, ListChecksIcon, MapIcon, MessageCircleIcon } from "lucide-react"; +import { + CalendarIcon, + Compass, + Flame, + FolderIcon, + Gem, + Heart, + KanbanIcon, + LayoutDashboardIcon, + Leaf, + ListChecksIcon, + MapIcon, + MessageCircleIcon, + Sparkles, + Star, + Sun, + Waves, + Zap, +} from "lucide-react"; import { useState } from "react"; +import { useTranslation } from "react-i18next"; import { useParams } from "react-router-dom"; import { EtapesSection, RoadmapSection, + TabloDetailsShell, TabloDiscussionSection, TabloEventsSection, TabloFilesSection, @@ -137,12 +158,92 @@ function useClientTabloFolders(tabloId: string, accessToken: string | undefined) }); } +function getTabloIcon(color: string | null | undefined) { + switch (color) { + case "bg-blue-500": + return Zap; + case "bg-green-500": + return Leaf; + case "bg-purple-500": + return Gem; + case "bg-red-500": + return Flame; + case "bg-yellow-500": + return Star; + case "bg-indigo-500": + return Compass; + case "bg-pink-500": + return Heart; + case "bg-teal-500": + return Waves; + case "bg-orange-500": + return Sun; + case "bg-cyan-500": + return Sparkles; + default: + return FolderIcon; + } +} + +function getTabloIconColor(color: string | null | undefined): string { + switch (color) { + case "bg-yellow-500": + case "bg-cyan-500": + return "text-gray-700"; + default: + return "text-white"; + } +} + +function getStatusConfig(status: string) { + switch (status) { + case "in_progress": + return { + label: "En cours", + badgeClass: + "bg-yellow-50 text-yellow-700 border border-yellow-200 dark:bg-yellow-950/30 dark:text-yellow-400 dark:border-yellow-800", + }; + case "done": + return { + label: "Terminé", + badgeClass: + "bg-green-50 text-green-600 border border-green-200 dark:bg-green-950/30 dark:text-green-400 dark:border-green-800", + }; + default: + return { + label: "À faire", + badgeClass: + "bg-blue-50 text-blue-600 border border-blue-200 dark:bg-blue-950/30 dark:text-blue-400 dark:border-blue-800", + }; + } +} + +function getEtapeProgressStats(etapes: Etape[]) { + const total = etapes.length; + const done = etapes.filter((etape) => etape.status === "done").length; + const started = etapes.filter((etape) => + new Set(["in_progress", "in_review", "done"]).has(etape.status ?? "todo") + ).length; + + if (total === 0) { + return { + startedPercentage: 0, + donePercentage: 0, + }; + } + + return { + startedPercentage: Math.round((started / total) * 100), + donePercentage: Math.round((done / total) * 100), + }; +} + // ─── Tabs ───────────────────────────────────────────────────────────────────── type TabId = "overview" | "etapes" | "tasks" | "files" | "discussion" | "events" | "roadmap"; const TABS: { id: TabId; label: string; icon: React.ElementType }[] = [ - { id: "overview", label: "Aperçu", icon: ListChecksIcon }, + { id: "overview", label: "Aperçu", icon: LayoutDashboardIcon }, { id: "etapes", label: "Étapes", icon: ListChecksIcon }, { id: "tasks", label: "Tâches", icon: KanbanIcon }, { id: "files", label: "Fichiers", icon: FolderIcon }, @@ -154,6 +255,7 @@ const TABS: { id: TabId; label: string; icon: React.ElementType }[] = [ // ─── Page ───────────────────────────────────────────────────────────────────── export function ClientTabloPage() { + const { t } = useTranslation(["pages", "chat"]); const { tabloId } = useParams<{ tabloId: string }>(); const { session } = useSession(); const [activeTab, setActiveTab] = useState("overview"); @@ -189,50 +291,184 @@ export function ClientTabloPage() { ); } - return ( -
- {/* Tablo header */} -
-

{tablo.name}

-
+ const { label: statusLabel, badgeClass } = getStatusConfig(tablo.status); + const progress = getEtapeProgressStats(etapes); + const isDiscussionView = activeTab === "discussion"; + const TabloIcon = getTabloIcon(tablo.color); + const iconColor = getTabloIconColor(tablo.color); - {/* Tab bar */} -
- -
- - {/* Tab content */} -
- {activeTab === "overview" && ( -
- {/* Simple overview: list etapes with progress */} - {}} - onCreateEtape={async () => {}} + const metadata = [ + { + key: "role", + label: t("pages:tablo.details.roleLabel"), + value: ( + {t("pages:tablo.role.guest")} + ), + }, + { + key: "created-at", + label: t("pages:tablo.details.createdAtLabel"), + value: ( + + {new Intl.DateTimeFormat("fr-FR", { + year: "numeric", + month: "short", + day: "2-digit", + }).format(new Date(tablo.created_at))} + + ), + }, + { + key: "status", + label: t("pages:tablo.details.statusLabel"), + value: {statusLabel}, + }, + { + key: "progress", + label: t("pages:tablo.details.progressLabel"), + value: ( + <> +
+
+
+
+ {progress.donePercentage}% + + ), + }, + ]; + + const headerVisual = ( +
+ {tablo.image ? ( + {tablo.name} + ) : ( + + )} +
+ ); + + const headerActions = ( + + ); + + return ( + setActiveTab(tabId as TabId)} + isDiscussionView={isDiscussionView} + > + {activeTab === "overview" && ( +
+
+
+

+ Description du projet +

+

+ Ce projet regroupe les tâches, fichiers et événements associés. Utilisez les + onglets ci-dessus pour naviguer entre les différentes sections. +

+
+ +
+
+

+ Mes tâches +

+
+
+ {tasks.length === 0 ? ( +
+ Aucune tâche +
+ ) : ( + tasks.slice(0, 5).map((task) => ( +
+
+

+ {task.title} +

+
+ )) + )} +
+
+
+ +
+
+
+

Fichiers

+
+
+ {fileNames.length === 0 ? ( +

Aucun fichier

+ ) : ( + fileNames.slice(0, 5).map((fileName) => ( +
+
+ +
+
+

{fileName}

+
+
+ )) + )} +
+
+ +
+

Informations

+
+
+
Tâches
+
{tasks.length}
+
+
+
Fichiers
+
{fileNames.length}
+
+
+
Statut
+
+ {statusLabel} +
+
+
+
Rôle
+
{t("pages:tablo.role.guest")}
+
+
+
+
)} @@ -304,7 +540,6 @@ export function ClientTabloPage() { onTaskStatusChange={() => {}} /> )} -
-
+ ); } diff --git a/apps/clients/src/setupTests.ts b/apps/clients/src/setupTests.ts index ae81371..23c7532 100644 --- a/apps/clients/src/setupTests.ts +++ b/apps/clients/src/setupTests.ts @@ -1,6 +1,6 @@ import "@testing-library/jest-dom"; import { cleanup } from "@testing-library/react"; -import { vi } from "vitest"; +import { afterEach, vi } from "vitest"; import "./i18n.test"; afterEach(() => { diff --git a/apps/main/src/locales/en/pages.json b/apps/main/src/locales/en/pages.json index 1c2f7e9..2a173a0 100644 --- a/apps/main/src/locales/en/pages.json +++ b/apps/main/src/locales/en/pages.json @@ -27,6 +27,12 @@ "admin": "Admin", "guest": "Guest" }, + "details": { + "roleLabel": "Role:", + "createdAtLabel": "Created on:", + "statusLabel": "Status:", + "progressLabel": "Progress:" + }, "status": { "todo": "To Do", "inProgress": "In Progress", diff --git a/apps/main/src/locales/fr/pages.json b/apps/main/src/locales/fr/pages.json index ea5cd2b..e8b8fb2 100644 --- a/apps/main/src/locales/fr/pages.json +++ b/apps/main/src/locales/fr/pages.json @@ -27,6 +27,12 @@ "admin": "Admin", "guest": "Invité" }, + "details": { + "roleLabel": "Rôle :", + "createdAtLabel": "Créé le :", + "statusLabel": "Statut :", + "progressLabel": "Progression :" + }, "status": { "todo": "À faire", "inProgress": "En cours", diff --git a/packages/tablo-views/package.json b/packages/tablo-views/package.json index 5de94b5..c0a5110 100644 --- a/packages/tablo-views/package.json +++ b/packages/tablo-views/package.json @@ -7,6 +7,7 @@ "types": "./src/index.ts", "exports": { ".": "./src/index.ts", + "./styles/tablo-details-shell.css": "./src/styles/tablo-details-shell.css", "./components/*": "./src/components/*.tsx", "./hooks/*": "./src/hooks/*.ts", "./*": "./src/*.tsx" diff --git a/packages/tablo-views/src/TabloDetailsShell.tsx b/packages/tablo-views/src/TabloDetailsShell.tsx new file mode 100644 index 0000000..b0eae62 --- /dev/null +++ b/packages/tablo-views/src/TabloDetailsShell.tsx @@ -0,0 +1,119 @@ +import { cn } from "@xtablo/shared"; +import type { UserTablo } from "@xtablo/shared-types"; + +type TabId = string; + +export interface TabloDetailsShellTab { + id: TabId; + label: string; + icon: React.ElementType; + disabled?: boolean; + hasUnread?: boolean; +} + +export interface TabloDetailsShellMetadataItem { + key: string; + label: string; + value: React.ReactNode; +} + +interface TabloDetailsShellProps { + tablo: Pick; + headerVisual?: React.ReactNode; + headerActions?: React.ReactNode; + metadata: TabloDetailsShellMetadataItem[]; + tabs: TabloDetailsShellTab[]; + activeTab: TabId; + onTabChange: (tabId: TabId) => void; + children: React.ReactNode; + isDiscussionView?: boolean; +} + +export function TabloDetailsShell({ + tablo, + headerVisual, + headerActions, + metadata, + tabs, + activeTab, + onTabChange, + children, + isDiscussionView = false, +}: TabloDetailsShellProps) { + return ( +
+
+
+
+ {headerVisual} +

{tablo.name}

+
+ + {headerActions &&
{headerActions}
} +
+ +
+ {metadata.map((item, index) => ( +
+ {item.label} + {item.value} +
+ ))} +
+
+ +
+
+
+ {tabs.map((tab) => { + const isActive = activeTab === tab.id; + return ( + + ); + })} +
+
+
+ +
+ {children} +
+
+ ); +} diff --git a/packages/tablo-views/src/index.ts b/packages/tablo-views/src/index.ts index eb6ae02..b67c572 100644 --- a/packages/tablo-views/src/index.ts +++ b/packages/tablo-views/src/index.ts @@ -6,6 +6,7 @@ export { EtapesSection } from "./EtapesSection"; export { RoadmapSection } from "./RoadmapSection"; export { TabloHeaderActions } from "./TabloHeaderActions"; export { ChatMessages } from "./ChatMessages"; +export { TabloDetailsShell } from "./TabloDetailsShell"; // Sub-components export { GanttChart } from "./components/gantt/GanttChart"; @@ -18,3 +19,4 @@ export { useChatUnread } from "./hooks/useChatUnread"; // Types export type { TabloMember } from "./components/kanban/types"; +export type { TabloDetailsShellMetadataItem, TabloDetailsShellTab } from "./TabloDetailsShell"; diff --git a/packages/tablo-views/src/styles/tablo-details-shell.css b/packages/tablo-views/src/styles/tablo-details-shell.css new file mode 100644 index 0000000..c1a9286 --- /dev/null +++ b/packages/tablo-views/src/styles/tablo-details-shell.css @@ -0,0 +1,40 @@ +@import "@xtablo/chat-ui/chat-ui.css"; + +:root { + --navbar-background: rgb(249, 250, 251); + --navbar-darker: #e5e7eb; +} + +.dark { + --navbar-background: #1e1b2e; + --navbar-darker: #141121; +} + +.str-chat { + --str-chat__primary-color: #804eec; + --str-chat__active-primary-color: #6f3fd4; + --str-chat__surface-color: #f5f3f7; + --str-chat__secondary-surface-color: #e8e4ec; + --str-chat__primary-surface-color: #f4f3ff; + --str-chat__primary-surface-color-low-emphasis: #f8f7ff; + --str-chat__border-radius-circle: 6px; + --str-chat__own-message-bubble-color: #804eec; + --str-chat__own-message-text-color: #ffffff; +} + +.dark .str-chat { + --str-chat__primary-color: #9b6ff0; + --str-chat__active-primary-color: #804eec; + --str-chat__surface-color: rgba(128, 78, 236, 0.12); + --str-chat__secondary-surface-color: rgba(128, 78, 236, 0.08); + --str-chat__primary-surface-color: rgba(128, 78, 236, 0.1); + --str-chat__primary-surface-color-low-emphasis: rgba(128, 78, 236, 0.05); + --str-chat__background-color: rgba(30, 27, 46, 0.6); + --str-chat__secondary-background-color: rgba(20, 17, 33, 0.5); + --str-chat__border-color: rgba(128, 78, 236, 0.15); + --str-chat__text-color: #eeeaf5; + --str-chat__text-low-emphasis-color: #a8a0b8; + --str-chat__disabled-color: rgba(128, 78, 236, 0.2); + --str-chat__own-message-bubble-color: #804eec; + --str-chat__own-message-text-color: #ffffff; +} From 84d94c49e999f91abe4b521012d3d64739e77836 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 15 Apr 2026 23:00:12 +0200 Subject: [PATCH 25/75] fix: align client portal shell and chat styles --- .../src/components/ClientLayout.test.tsx | 23 ++++ apps/clients/src/components/ClientLayout.tsx | 15 +-- apps/clients/src/main.css | 106 ++++++++++-------- apps/clients/src/mainCss.test.ts | 15 +++ 4 files changed, 105 insertions(+), 54 deletions(-) create mode 100644 apps/clients/src/components/ClientLayout.test.tsx create mode 100644 apps/clients/src/mainCss.test.ts diff --git a/apps/clients/src/components/ClientLayout.test.tsx b/apps/clients/src/components/ClientLayout.test.tsx new file mode 100644 index 0000000..17c3972 --- /dev/null +++ b/apps/clients/src/components/ClientLayout.test.tsx @@ -0,0 +1,23 @@ +import { describe, expect, it } from "vitest"; +import { renderWithProviders } from "../test/testHelpers"; +import { ClientLayout } from "./ClientLayout"; + +describe("ClientLayout", () => { + it("uses the main app style header shell and centered content container", () => { + const { container } = renderWithProviders(); + + const header = container.querySelector("header"); + expect(header).toHaveClass("h-[75px]"); + expect(header).toHaveClass("bg-navbar-background"); + + const headerInner = header?.firstElementChild; + expect(headerInner).toHaveClass("w-full"); + expect(headerInner).toHaveClass("max-w-7xl"); + expect(headerInner).toHaveClass("mx-auto"); + + const main = container.querySelector("main"); + expect(main).toHaveClass("w-full"); + expect(main).toHaveClass("max-w-7xl"); + expect(main).toHaveClass("mx-auto"); + }); +}); diff --git a/apps/clients/src/components/ClientLayout.tsx b/apps/clients/src/components/ClientLayout.tsx index 20719a0..16609cf 100644 --- a/apps/clients/src/components/ClientLayout.tsx +++ b/apps/clients/src/components/ClientLayout.tsx @@ -36,14 +36,10 @@ export function ClientLayout() { }; return ( -
- {/* Top bar */} -
-
- {/* Brand */} - Xtablo - - {/* User info + logout */} +
+
+
+ Xtablo
@@ -58,8 +54,7 @@ export function ClientLayout() {
- {/* Page content */} -
+
diff --git a/apps/clients/src/main.css b/apps/clients/src/main.css index a896ff7..2782768 100644 --- a/apps/clients/src/main.css +++ b/apps/clients/src/main.css @@ -1,6 +1,8 @@ @import "tailwindcss"; @import "tw-animate-css"; +@source "../../../packages/chat-ui/src/**/*.{ts,tsx}"; + @custom-variant dark (&:is(.dark *)); :root { @@ -37,41 +39,45 @@ --sidebar-accent-foreground: oklch(0.205 0 0); --sidebar-border: oklch(0.922 0 0); --sidebar-ring: oklch(0.708 0 0); + --navbar-background: rgb(249, 250, 251); + --navbar-darker: #e5e7eb; } .dark { - --background: oklch(0.145 0 0); - --foreground: oklch(0.985 0 0); - --card: oklch(0.145 0 0); - --card-foreground: oklch(0.985 0 0); - --popover: oklch(0.145 0 0); - --popover-foreground: oklch(0.985 0 0); - --primary: oklch(0.985 0 0); - --primary-foreground: oklch(0.205 0 0); - --secondary: oklch(0.269 0 0); - --secondary-foreground: oklch(0.985 0 0); - --muted: oklch(0.269 0 0); - --muted-foreground: oklch(0.708 0 0); - --accent: oklch(0.269 0 0); - --accent-foreground: oklch(0.985 0 0); + --background: oklch(0.17 0.012 290); + --foreground: oklch(0.985 0.005 290); + --card: oklch(0.16 0.014 290); + --card-foreground: oklch(0.985 0.005 290); + --popover: oklch(0.16 0.014 290); + --popover-foreground: oklch(0.985 0.005 290); + --primary: oklch(0.985 0.005 290); + --primary-foreground: oklch(0.2 0.012 290); + --secondary: oklch(0.22 0.018 290); + --secondary-foreground: oklch(0.985 0.005 290); + --muted: oklch(0.22 0.018 290); + --muted-foreground: oklch(0.65 0.02 290); + --accent: oklch(0.22 0.018 290); + --accent-foreground: oklch(0.985 0.005 290); --destructive: oklch(0.396 0.141 25.723); --destructive-foreground: oklch(0.637 0.237 25.331); - --border: oklch(0.269 0 0); - --input: oklch(0.269 0 0); - --ring: oklch(0.439 0 0); - --chart-1: oklch(0.488 0.243 264.376); + --border: oklch(0.26 0.02 290); + --input: oklch(0.26 0.02 290); + --ring: oklch(0.45 0.03 290); + --chart-1: oklch(0.55 0.2 290); --chart-2: oklch(0.696 0.17 162.48); --chart-3: oklch(0.769 0.188 70.08); --chart-4: oklch(0.627 0.265 303.9); --chart-5: oklch(0.645 0.246 16.439); - --sidebar: oklch(0.205 0 0); - --sidebar-foreground: oklch(0.985 0 0); - --sidebar-primary: oklch(0.488 0.243 264.376); - --sidebar-primary-foreground: oklch(0.985 0 0); - --sidebar-accent: oklch(0.269 0 0); - --sidebar-accent-foreground: oklch(0.985 0 0); - --sidebar-border: oklch(0.269 0 0); - --sidebar-ring: oklch(0.439 0 0); + --sidebar: oklch(0.18 0.016 290); + --sidebar-foreground: oklch(0.985 0.005 290); + --sidebar-primary: oklch(0.55 0.2 290); + --sidebar-primary-foreground: oklch(0.985 0.005 290); + --sidebar-accent: oklch(0.24 0.02 290); + --sidebar-accent-foreground: oklch(0.985 0.005 290); + --sidebar-border: oklch(0.26 0.02 290); + --sidebar-ring: oklch(0.45 0.03 290); + --navbar-background: #1e1b2e; + --navbar-darker: #141121; } @theme inline { @@ -111,8 +117,8 @@ --color-sidebar-accent-foreground: var(--sidebar-accent-foreground); --color-sidebar-border: var(--sidebar-border); --color-sidebar-ring: var(--sidebar-ring); - --color-navbar-background: #292e39; - --color-navbar-darker: #171920; + --color-navbar-background: var(--navbar-background); + --color-navbar-darker: var(--navbar-darker); } @layer base { @@ -122,31 +128,43 @@ body { @apply bg-background text-foreground; } + @media (display-mode: standalone) { + body { + padding-top: env(safe-area-inset-top); + padding-bottom: env(safe-area-inset-bottom); + padding-left: env(safe-area-inset-left); + padding-right: env(safe-area-inset-right); + } + } } .str-chat { - --str-chat__primary-color: #8b7396; - --str-chat__active-primary-color: #6e5c7d; + --str-chat__primary-color: #804eec; + --str-chat__active-primary-color: #6f3fd4; --str-chat__surface-color: #f5f3f7; --str-chat__secondary-surface-color: #e8e4ec; - --str-chat__primary-surface-color: #ebe7f0; - --str-chat__primary-surface-color-low-emphasis: #f2f0f5; + --str-chat__primary-surface-color: #f4f3ff; + --str-chat__primary-surface-color-low-emphasis: #f8f7ff; --str-chat__border-radius-circle: 6px; + --str-chat__own-message-bubble-color: #804eec; + --str-chat__own-message-text-color: #ffffff; } .dark .str-chat { - --str-chat__primary-color: #a68bb5; - --str-chat__active-primary-color: #8b7396; - --str-chat__surface-color: rgba(120, 107, 130, 0.25); - --str-chat__secondary-surface-color: rgba(140, 130, 150, 0.18); - --str-chat__primary-surface-color: rgba(166, 139, 181, 0.12); - --str-chat__primary-surface-color-low-emphasis: rgba(166, 139, 181, 0.06); - --str-chat__background-color: rgba(110, 100, 120, 0.2); - --str-chat__secondary-background-color: rgba(80, 72, 88, 0.35); - --str-chat__border-color: rgba(120, 107, 130, 0.28); - --str-chat__text-color: #f5f3f7; - --str-chat__text-low-emphasis-color: #b8b0c0; - --str-chat__disabled-color: rgba(155, 143, 165, 0.35); + --str-chat__primary-color: #9b6ff0; + --str-chat__active-primary-color: #804eec; + --str-chat__surface-color: rgba(128, 78, 236, 0.12); + --str-chat__secondary-surface-color: rgba(128, 78, 236, 0.08); + --str-chat__primary-surface-color: rgba(128, 78, 236, 0.1); + --str-chat__primary-surface-color-low-emphasis: rgba(128, 78, 236, 0.05); + --str-chat__background-color: rgba(30, 27, 46, 0.6); + --str-chat__secondary-background-color: rgba(20, 17, 33, 0.5); + --str-chat__border-color: rgba(128, 78, 236, 0.15); + --str-chat__text-color: #eeeaf5; + --str-chat__text-low-emphasis-color: #a8a0b8; + --str-chat__disabled-color: rgba(128, 78, 236, 0.2); + --str-chat__own-message-bubble-color: #804eec; + --str-chat__own-message-text-color: #ffffff; } @keyframes gradient-x { diff --git a/apps/clients/src/mainCss.test.ts b/apps/clients/src/mainCss.test.ts new file mode 100644 index 0000000..c150cce --- /dev/null +++ b/apps/clients/src/mainCss.test.ts @@ -0,0 +1,15 @@ +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { describe, expect, it } from "vitest"; + +const mainCss = readFileSync(resolve(process.cwd(), "src/main.css"), "utf8"); + +describe("clients main.css", () => { + it("keeps the chat source and theme tokens aligned with the main app", () => { + expect(mainCss).toContain('@source "../../../packages/chat-ui/src/**/*.{ts,tsx}";'); + expect(mainCss).toContain("--navbar-background: rgb(249, 250, 251);"); + expect(mainCss).toContain("--color-navbar-background: var(--navbar-background);"); + expect(mainCss).toContain("--str-chat__own-message-bubble-color: #804eec;"); + expect(mainCss).toContain("--str-chat__own-message-text-color: #ffffff;"); + }); +}); From b1c1c595abfe3ee480a70fa1e33c6e246ebae630 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Thu, 16 Apr 2026 08:07:08 +0200 Subject: [PATCH 26/75] fix: restore standard tablo invite flow --- .../src/pages/tablo-details.layout.test.tsx | 17 + apps/main/src/pages/tablo-details.tsx | 313 ++++++++++++------ 2 files changed, 223 insertions(+), 107 deletions(-) diff --git a/apps/main/src/pages/tablo-details.layout.test.tsx b/apps/main/src/pages/tablo-details.layout.test.tsx index 76bfe34..e591c75 100644 --- a/apps/main/src/pages/tablo-details.layout.test.tsx +++ b/apps/main/src/pages/tablo-details.layout.test.tsx @@ -1,4 +1,5 @@ import { screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; import { describe, expect, it, vi } from "vitest"; import { renderWithProviders } from "../utils/testHelpers"; import { TabloDetailsPage } from "./tablo-details"; @@ -195,4 +196,20 @@ describe("TabloDetailsPage overview layout", () => { expect(screen.getByRole("button", { name: "Modifier la mise en page" })).toBeInTheDocument(); }); + + it("uses the standard email invite UI in the share dialog", async () => { + const user = userEvent.setup(); + + renderWithProviders(, { + route: "/tablos/tablo-1", + path: "/tablos/:tabloId", + }); + + await user.click(screen.getByRole("button", { name: "Inviter" })); + + expect(screen.getByText("Inviter un utilisateur")).toBeInTheDocument(); + expect(screen.getByPlaceholderText("Email de l'utilisateur à inviter")).toBeInTheDocument(); + expect(screen.queryByText("Accès client")).not.toBeInTheDocument(); + expect(screen.queryByRole("button", { name: "Envoyer le lien" })).not.toBeInTheDocument(); + }); }); diff --git a/apps/main/src/pages/tablo-details.tsx b/apps/main/src/pages/tablo-details.tsx index df06def..a9cd3e5 100644 --- a/apps/main/src/pages/tablo-details.tsx +++ b/apps/main/src/pages/tablo-details.tsx @@ -186,6 +186,9 @@ const TABS: { { id: "roadmap", label: "Roadmap", icon: MapIcon }, ]; +// Temporary rollback until the client portal invite flow is ready to be used again. +const USE_CLIENT_MAGIC_LINK_INVITES = false; + // ─── Page ───────────────────────────────────────────────────────────────────── export const TabloDetailsPage = () => { @@ -202,6 +205,7 @@ export const TabloDetailsPage = () => { ); const [showAllOverviewTasks, setShowAllOverviewTasks] = useState(false); const [isShareDialogOpen, setIsShareDialogOpen] = useState(false); + const [inviteEmail, setInviteEmail] = useState(""); const [clientInviteEmail, setClientInviteEmail] = useState(""); const [isLayoutEditMode, setIsLayoutEditMode] = useState(false); const [draggedOverviewBlock, setDraggedOverviewBlock] = useState<{ @@ -255,6 +259,13 @@ export const TabloDetailsPage = () => { (member) => !pendingInvites?.some((invite) => invite.invited_email === member.email) ); + const handleSendInvite = () => { + if (!tabloId || !inviteEmail.trim()) return; + + inviteUser({ email: inviteEmail, tablo_id: tabloId }); + setInviteEmail(""); + }; + const openTaskModal = (dueDate?: Date) => { setTaskModalInitialDueDate(dueDate ? new Date(dueDate) : undefined); setIsTaskModalOpen(true); @@ -1002,117 +1013,205 @@ export const TabloDetailsPage = () => { {/* Separator */}
- {/* Client Access Section */} -
-

Accès client

-

- Invitez des clients externes via un lien magique -

-
- - {/* Client Invite Input */} -
- setClientInviteEmail(e.target.value)} - placeholder="Email du client" - className="flex-1 min-h-[44px]" - /> - {isCreatingClientInvite ? ( -
-
+ {USE_CLIENT_MAGIC_LINK_INVITES ? ( + <> +
+

Accès client

+

+ Invitez des clients externes via un lien magique +

- ) : ( - - )} -
- {/* Pending Client Invites */} - {pendingClientInvites && pendingClientInvites.length > 0 && ( -
-

- Invitations client en attente ({pendingClientInvites.length}) -

-
- {pendingClientInvites.map((invite) => { - const daysUntilExpiry = Math.ceil( - (new Date(invite.expires_at).getTime() - Date.now()) / (1000 * 60 * 60 * 24) - ); - const isExpiringSoon = daysUntilExpiry < 5; - return ( -
-
- +
+
+
+ ) : ( + + )} +
+ + {pendingClientInvites && pendingClientInvites.length > 0 && ( +
+

+ Invitations client en attente ({pendingClientInvites.length}) +

+
+ {pendingClientInvites.map((invite) => { + const daysUntilExpiry = Math.ceil( + (new Date(invite.expires_at).getTime() - Date.now()) / + (1000 * 60 * 60 * 24) + ); + const isExpiringSoon = daysUntilExpiry < 5; + return ( +
- - -
-
- - {invite.invited_email} - - - {isExpiringSoon && "⚠ "} - Expire dans {daysUntilExpiry} jour{daysUntilExpiry !== 1 ? "s" : ""} - -
- {isExpiringSoon && ( - - Bientôt expiré - - )} - +
+ ); + })} +
+
+ )} + + ) : ( + <> +
+

Inviter un utilisateur

+

+ Utilisez le système d'invitation standard par email pour le moment +

+
+ +
+ setInviteEmail(e.target.value)} + placeholder="Email de l'utilisateur à inviter" + className="flex-1 min-h-[44px]" + /> + {isInvitingUser ? ( +
+
+
+ ) : ( + + )} +
+ + {pendingInvites && pendingInvites.length > 0 && ( +
+

+ Invitations en attente ({pendingInvites.length}) +

+
+ {pendingInvites.map((invite) => ( +
- - -
- ); - })} -
-
+
+ + + +
+
+ + {invite.invited_email} + + (En attente) +
+ +
+ ))} +
+
+ )} + )}
From 423d41989323c1b1358d68e6e58d3f3834390159 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Thu, 16 Apr 2026 09:01:39 +0200 Subject: [PATCH 27/75] docs: add exact clients tablo parity design --- ...04-16-clients-exact-tablo-parity-design.md | 249 ++++++++++++++++++ 1 file changed, 249 insertions(+) create mode 100644 docs/superpowers/specs/2026-04-16-clients-exact-tablo-parity-design.md diff --git a/docs/superpowers/specs/2026-04-16-clients-exact-tablo-parity-design.md b/docs/superpowers/specs/2026-04-16-clients-exact-tablo-parity-design.md new file mode 100644 index 0000000..3b43b5a --- /dev/null +++ b/docs/superpowers/specs/2026-04-16-clients-exact-tablo-parity-design.md @@ -0,0 +1,249 @@ +# Clients Exact Tablo Parity + +**Date**: 2026-04-16 +**Status**: Draft +**Supersedes**: `docs/superpowers/specs/2026-04-15-client-portal-tablo-parity-design.md` + +## Overview + +`clients.xtablo.com` is intended to be a portal for the clients of our clients. For the single-tablo experience, it must render the exact same UI surface as `app.xtablo.com` on `apps/main/src/pages/tablo-details.tsx`. + +The current codebase does not guarantee that outcome because `apps/main` and `apps/clients` still compose the page separately. Shared sections and some shared CSS exist, but the full single-tablo route is not owned by one shared render surface. + +The target is stricter than "close parity": + +- same page shell +- same header structure +- same metadata row +- same tab bar +- same overview layout +- same section framing +- same responsive behavior +- same route-level CSS source +- same component tree for the single-tablo view + +The only intended differences are: + +- `apps/main` keeps URL-backed section state +- `apps/clients` keeps in-memory section state +- `apps/main` exposes full admin and mutation capabilities +- `apps/clients` exposes a restricted client-safe capability set + +## Problem Statement + +`clients.xtablo.com` is not at feature parity today for structural reasons, not because of one isolated CSS bug. + +### Current causes of drift + +1. `apps/clients/src/pages/ClientTabloPage.tsx` reconstructs a client-specific page instead of rendering the same single-tablo surface as `apps/main`. +2. `apps/clients/src/components/ClientLayout.tsx` owns a separate app shell, so spacing, header behavior, and responsive layout can drift from the main app. +3. Shared CSS exists only partially. Route-level tokens and chat/page styling have been extracted in places, but the full single-tablo view is still not governed by one shared route stylesheet plus one shared render tree. +4. Permissions are mixed into page composition instead of being expressed as a clean capability model. That forces `clients` to fork render logic instead of rendering the same surface with different behavior gates. + +The result is predictable: any visual or structural change to the main tablo route risks being manually reimplemented in `clients`, and parity becomes a maintenance task instead of an invariant. + +## Goals + +- Make the single-tablo UI in `clients.xtablo.com` visually identical to `apps/main/src/pages/tablo-details.tsx` +- Enforce parity through one shared single-tablo render surface +- Share the route-level CSS and responsive behavior between both apps +- Keep `apps/clients` on in-memory tab state +- Keep `discussion` writable in client mode +- Keep the rest of the client experience read-only or admin-hidden as approved + +## Non-Goals + +- Rebuilding the client portal as a separate visual concept +- Introducing query-param section routing into `apps/clients` +- Enabling client-side admin actions +- Refactoring unrelated routes outside the single-tablo experience +- Deleting the newer client-specific invite system from the codebase + +## Hard Requirement + +The UI must be the exact same. + +That rules out maintaining two parallel page compositions for the single-tablo route. "Shared components plus duplicated page assembly" is not sufficient because parity will drift again. The single-tablo view must be rendered from one shared composition surface consumed by both apps. + +## Chosen Approach + +Create a shared single-tablo route surface in `packages/tablo-views` and make both apps consume it. + +This shared surface owns the exact structure, responsive layout, CSS import, tab order, overview composition, and section framing for the route. + +Each app becomes a thin adapter: + +- `apps/main` passes full-capability handlers and URL-backed section state +- `apps/clients` passes restricted capabilities and in-memory section state + +This is a consolidation, not a styling pass. + +## Architecture + +### Shared package ownership + +`packages/tablo-views` should own the single-tablo route surface for both apps, including: + +- header layout +- title and icon/image block +- metadata row +- sticky tab navigation +- overview block composition +- section container layout +- discussion full-height layout behavior +- route-specific CSS for this surface + +This shared surface should render the same DOM structure and use the same styling hooks regardless of app. + +### App adapter ownership + +`apps/main` should own: + +- `?section=` query-param state +- full mutation handlers +- admin-only actions +- share and invite workflows +- main-only routing integrations + +`apps/clients` should own: + +- local in-memory tab state +- client-safe data loading +- capability restrictions +- client-safe app shell concerns outside the single-tablo surface + +### Key principle + +The apps must differ by inputs, not by page composition. + +## Capability Model + +The shared single-tablo surface should branch on capabilities rather than on app identity. + +Suggested capability contract: + +- `canCreateTasks` +- `canEditTasks` +- `canEditEvents` +- `canManageFiles` +- `canManageMembers` +- `canInviteMembers` +- `canEditLayout` +- `canWriteDiscussion` + +### Approved client boundary + +For `clients.xtablo.com`: + +- `discussion`: writable +- file read/download behavior: allowed where already supported +- task edits: disabled +- event edits: disabled +- layout edits: hidden +- member management: hidden or read-only +- invite/share management: hidden + +This preserves the same page structure while changing behavior safely. + +## CSS And Responsiveness + +Exact UI parity requires a single route-level CSS source for the single-tablo experience. + +### Requirements + +- the shared single-tablo surface imports one shared route stylesheet from `packages/tablo-views` +- route-level tokens for navbar, metadata, sticky tabs, and discussion/chat visuals come from that shared stylesheet +- responsive breakpoints and overflow behavior are not redefined independently in `apps/main` and `apps/clients` + +### Constraint + +`apps/clients` must not carry a competing route-specific single-tablo style layer that can override the shared surface in divergent ways. + +App-local CSS can remain for app-wide concerns, but the single-tablo route must have one styling owner. + +## State Model + +The visual surface is shared, but tab state differs by app. + +### Main app + +- active section comes from `?section=...` +- existing route behavior remains intact + +### Clients app + +- active section is stored in local React state +- no query-param synchronization is required + +This is acceptable because the user explicitly approved in-memory state for clients. + +## Migration Plan + +### Phase 1: Consolidate the surface + +- identify all remaining structure in `apps/main/src/pages/tablo-details.tsx` that is still page-owned instead of shared +- move that structure into a shared single-tablo route surface in `packages/tablo-views` +- make `apps/main` consume the shared surface first, preserving current behavior + +### Phase 2: Convert the clients app into an adapter + +- remove duplicated page composition from `apps/clients/src/pages/ClientTabloPage.tsx` +- replace it with a thin adapter that passes client-safe data and capability flags into the shared surface +- keep local in-memory tab state in the adapter only + +### Phase 3: Normalize the shell + +- ensure the surrounding shell and route-level CSS used by the single-tablo surface are shared consistently +- keep `ClientLayout` responsible only for client-portal app concerns, not for redefining the single-tablo view + +### Phase 4: Lock parity with tests + +- add tests that assert `main` and `clients` render the same shared single-tablo structure +- add client-mode tests for capability restrictions +- add responsive regression coverage where practical + +## Testing Strategy + +Verification must prove parity, not just correctness. + +### Automated + +- shared render tests for the single-tablo route surface in `packages/tablo-views` +- adapter tests proving `apps/main` and `apps/clients` pass different state/capabilities into the same surface +- regression tests that the client app hides or disables admin-only actions while keeping discussion writable +- targeted CSS contract tests ensuring both apps import the same shared route stylesheet + +### Manual + +Side-by-side comparison between: + +- `apps/main` `/tablos/:tabloId` +- `apps/clients` `/tablo/:tabloId` + +At minimum verify: + +- desktop layout +- mobile layout +- sticky tabs +- overview cards +- discussion layout +- header wrapping and spacing +- empty states + +## Risks + +- `apps/main/src/pages/tablo-details.tsx` may still contain too much mixed business logic and render logic, making extraction noisy +- some shared sections may still assume main-app permissions implicitly +- partial CSS ownership may continue to cause drift if not fully normalized +- client-safe data access may reveal places where the UI currently assumes admin or member-level data is always present + +## Success Criteria + +This work is successful when: + +- `clients.xtablo.com` renders the same single-tablo UI as `app.xtablo.com` +- future UI changes to the single-tablo route normally require edits in one shared place +- `apps/clients` remains in-memory for tab state +- client restrictions match the approved boundary +- discussion remains writable in client mode +- parity is enforced structurally, not maintained manually From 1a404bb4368d75d05345558073a00fe801cd739a Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Thu, 16 Apr 2026 11:09:27 +0200 Subject: [PATCH 28/75] fix: restore etape and task ui actions --- .../src/pages/tablo-details.layout.test.tsx | 55 +- apps/main/src/pages/tablo-details.tsx | 825 ++++-------------- packages/tablo-views/src/EtapesSection.tsx | 20 +- .../tablo-views/src/TabloTasksSection.tsx | 3 + .../src/components/kanban/TaskModal.tsx | 19 + 5 files changed, 267 insertions(+), 655 deletions(-) diff --git a/apps/main/src/pages/tablo-details.layout.test.tsx b/apps/main/src/pages/tablo-details.layout.test.tsx index e591c75..17c103e 100644 --- a/apps/main/src/pages/tablo-details.layout.test.tsx +++ b/apps/main/src/pages/tablo-details.layout.test.tsx @@ -6,6 +6,8 @@ import { TabloDetailsPage } from "./tablo-details"; const mutateUpdateTablo = vi.fn(); const mutateUpdateTask = vi.fn(); +const mutateCreateEtape = vi.fn(); +const mutateDeleteTask = vi.fn(); const tablosData = [ { @@ -110,11 +112,14 @@ vi.mock("../hooks/tasks", () => ({ useUpdateTask: () => ({ mutate: mutateUpdateTask, }), + useDeleteTask: () => ({ + mutate: mutateDeleteTask, + }), useTask: () => ({ data: null, }), useCreateEtape: () => ({ - mutateAsync: vi.fn(), + mutateAsync: mutateCreateEtape, isPending: false, }), useCreateTask: () => ({ @@ -174,6 +179,54 @@ vi.mock("../providers/UserStoreProvider", async (importOriginal) => { }); describe("TabloDetailsPage overview layout", () => { + it("keeps the add etape action enabled before typing", async () => { + const user = userEvent.setup(); + + renderWithProviders(, { + route: "/tablos/tablo-1", + path: "/tablos/:tabloId", + }); + + await user.click(screen.getByRole("button", { name: "Étapes" })); + + expect(screen.getByRole("button", { name: "Ajouter une étape" })).toBeEnabled(); + }); + + it("creates an etape from the etapes tab", async () => { + const user = userEvent.setup(); + mutateCreateEtape.mockResolvedValueOnce(undefined); + + renderWithProviders(, { + route: "/tablos/tablo-1", + path: "/tablos/:tabloId", + }); + + await user.click(screen.getByRole("button", { name: "Étapes" })); + await user.type(screen.getByPlaceholderText("Nom de la nouvelle étape..."), "Kickoff"); + await user.click(screen.getByRole("button", { name: "Ajouter une étape" })); + + expect(mutateCreateEtape).toHaveBeenCalledWith({ + tabloId: "tablo-1", + title: "Kickoff", + position: 0, + }); + }); + + it("deletes a task from the task modal", async () => { + const user = userEvent.setup(); + + renderWithProviders(, { + route: "/tablos/tablo-1", + path: "/tablos/:tabloId", + }); + + await user.click(screen.getByRole("button", { name: "Tâches" })); + await user.click(screen.getByText("Task A")); + await user.click(screen.getByRole("button", { name: "Supprimer la tâche" })); + + expect(mutateDeleteTask).toHaveBeenCalledWith("task-1"); + }); + it("renders overview cards in persisted left-zone order", () => { renderWithProviders(, { route: "/tablos/tablo-1", diff --git a/apps/main/src/pages/tablo-details.tsx b/apps/main/src/pages/tablo-details.tsx index a9cd3e5..50dfa93 100644 --- a/apps/main/src/pages/tablo-details.tsx +++ b/apps/main/src/pages/tablo-details.tsx @@ -1,15 +1,24 @@ import { LoadingSpinner } from "@ui/components/LoadingSpinner"; -import { cn, toast } from "@xtablo/shared"; +import { toast } from "@xtablo/shared"; import type { UserTablo } from "@xtablo/shared/types/tablos.types"; import type { KanbanTask } from "@xtablo/shared-types"; import { + DEFAULT_OVERVIEW_LAYOUT, EtapesSection, + type OverviewLayoutV1, RoadmapSection, + SingleTabloOverview, + SingleTabloView, TabloDiscussionSection, TabloEventsSection, TabloFilesSection, TabloTasksSection, TaskModal, + getSingleTabloStatusConfig, + moveBetweenZones, + moveWithinZone, + sanitizeOverviewLayout, + type SingleTabloTabId, useChatUnread, } from "@xtablo/tablo-views"; import { Avatar, AvatarFallback, AvatarImage } from "@xtablo/ui/components/avatar"; @@ -22,33 +31,9 @@ import { DialogTitle, } from "@xtablo/ui/components/dialog"; import { Input } from "@xtablo/ui/components/input"; -import { - CalendarIcon, - CircleCheckIcon, - Compass, - EllipsisVerticalIcon, - FileTextIcon, - Flame, - FolderIcon, - Gem, - Heart, - KanbanIcon, - LayoutDashboardIcon, - Leaf, - ListChecksIcon, - MapIcon, - MessageCircleIcon, - PlusIcon, - Sparkles, - Star, - Sun, - UserPlusIcon, - Waves, - XIcon, - Zap, -} from "lucide-react"; +import { XIcon } from "lucide-react"; import { useEffect, useState } from "react"; -import { Link, useNavigate, useParams, useSearchParams } from "react-router-dom"; +import { useNavigate, useParams, useSearchParams } from "react-router-dom"; import { useCancelClientInvite, useCreateClientInvite, @@ -79,111 +64,24 @@ import { useAllTasks, useCreateEtape, useCreateTask, + useDeleteTask, useTabloEtapes, useUpdateTask, useUpdateTaskPositions, } from "../hooks/tasks"; import { useUser } from "../providers/UserStoreProvider"; import { getEtapeProgressStats } from "../utils/etapeProgress"; -import { - DEFAULT_OVERVIEW_LAYOUT, - type OverviewBlockId, - type OverviewLayoutV1, - sanitizeOverviewLayout, -} from "./tablo-details/overviewLayout"; -import { moveBetweenZones, moveWithinZone } from "./tablo-details/overviewReorder"; -// ─── Icon helpers ───────────────────────────────────────────────────────────── +type TabSection = SingleTabloTabId; -function getTabloIcon(color: string | null | undefined) { - switch (color) { - case "bg-blue-500": - return Zap; - case "bg-green-500": - return Leaf; - case "bg-purple-500": - return Gem; - case "bg-red-500": - return Flame; - case "bg-yellow-500": - return Star; - case "bg-indigo-500": - return Compass; - case "bg-pink-500": - return Heart; - case "bg-teal-500": - return Waves; - case "bg-orange-500": - return Sun; - case "bg-cyan-500": - return Sparkles; - default: - return FolderIcon; - } -} - -function getTabloIconColor(color: string | null | undefined): string { - switch (color) { - case "bg-yellow-500": - case "bg-cyan-500": - return "text-gray-700"; - default: - return "text-white"; - } -} - -// ─── Status helpers ─────────────────────────────────────────────────────────── - -function getStatusConfig(status: string) { - switch (status) { - case "in_progress": - return { - label: "En cours", - badgeClass: - "bg-yellow-50 text-yellow-700 border border-yellow-200 dark:bg-yellow-950/30 dark:text-yellow-400 dark:border-yellow-800", - }; - case "done": - return { - label: "Terminé", - badgeClass: - "bg-green-50 text-green-600 border border-green-200 dark:bg-green-950/30 dark:text-green-400 dark:border-green-800", - }; - default: - return { - label: "À faire", - badgeClass: - "bg-blue-50 text-blue-600 border border-blue-200 dark:bg-blue-950/30 dark:text-blue-400 dark:border-blue-800", - }; - } -} - -// ─── Tabs ───────────────────────────────────────────────────────────────────── - -type TabSection = - | "overview" - | "board" - | "list" - | "roadmap" - | "calendar" - | "files" - | "discussion" - | "events" - | "tasks" - | "etapes"; - -const TABS: { - id: TabSection; - label: string; - icon: React.ElementType; - disabled?: boolean; -}[] = [ - { id: "overview", label: "Aperçu", icon: LayoutDashboardIcon }, - { id: "etapes", label: "Étapes", icon: ListChecksIcon }, - { id: "tasks", label: "Tâches", icon: KanbanIcon }, - { id: "files", label: "Fichiers", icon: FolderIcon }, - { id: "discussion", label: "Discussion", icon: MessageCircleIcon }, - { id: "events", label: "Événements", icon: CalendarIcon }, - { id: "roadmap", label: "Roadmap", icon: MapIcon }, +const TAB_SECTIONS: TabSection[] = [ + "overview", + "etapes", + "tasks", + "files", + "discussion", + "events", + "roadmap", ]; // Temporary rollback until the client portal invite flow is ready to be used again. @@ -225,6 +123,7 @@ export const TabloDetailsPage = () => { const { mutate: cancelClientInvite, isPending: isCancellingClientInvite } = useCancelClientInvite(); const { mutate: updateTask } = useUpdateTask(); + const { mutate: deleteTask } = useDeleteTask(); const { mutate: updateTablo, mutateAsync: updateTabloAsync } = useUpdateTablo(); const { mutate: createTask } = useCreateTask(); const { mutateAsync: createEtape, isPending: isCreatingEtape } = useCreateEtape(); @@ -278,9 +177,7 @@ export const TabloDetailsPage = () => { const sectionParam = searchParams.get("section") as TabSection | null; const activeSection: TabSection = - sectionParam && TABS.some((t) => t.id === sectionParam && !t.disabled) - ? sectionParam - : "overview"; + sectionParam && TAB_SECTIONS.includes(sectionParam) ? sectionParam : "overview"; const [tablo, setTablo] = useState(null); @@ -330,11 +227,9 @@ export const TabloDetailsPage = () => { if (!tablo) return null; - const { label: statusLabel, badgeClass } = getStatusConfig(tablo.status); + const { label: statusLabel, badgeClass } = getSingleTabloStatusConfig(tablo.status); const progress = getEtapeProgressStats(etapes); const isAdmin = tablo.is_admin; - const TabloIcon = getTabloIcon(tablo.color); - const iconColor = getTabloIconColor(tablo.color); const persistOverviewLayout = ( nextLayout: OverviewLayoutV1, @@ -431,528 +326,165 @@ export const TabloDetailsPage = () => { }; return ( -
- {/* ── Header ──────────────────────────────────────────────────────── */} -
-
-
-
- {tablo.image ? ( - {tablo.name} - ) : ( - - )} -
-

{tablo.name}

-
+ <> + setSearchParams({ section: tabId })} + hasUnreadDiscussion={hasUnreadDiscussion} + discussionAction={{ kind: "link", to: `/chat/${tabloId}` }} + canInviteMembers={isAdmin} + onOpenInviteDialog={() => setIsShareDialogOpen(true)} + > + {activeSection === "overview" && ( + setSearchParams({ section: "tasks" })} + onOpenFiles={() => setSearchParams({ section: "files" })} + onCreateTask={() => openTaskModal()} + onToggleTaskDone={(taskId) => updateTask({ id: taskId, status: "done" })} + showAllTasks={showAllOverviewTasks} + onToggleShowAllTasks={() => setShowAllOverviewTasks((prev) => !prev)} + layout={overviewLayout} + canEditLayout={isAdmin} + isLayoutEditMode={isLayoutEditMode} + draggedBlock={draggedOverviewBlock} + onToggleLayoutEditMode={() => setIsLayoutEditMode((prev) => !prev)} + onResetLayout={handleResetOverviewLayout} + onBlockDragStart={handleOverviewBlockDragStart} + onBlockDragOver={handleOverviewBlockDragOver} + onBlockDrop={handleOverviewBlockDrop} + onBlockDragEnd={() => setDraggedOverviewBlock(null)} + /> + )} -
- - - Discussion - - {isAdmin && ( - - )} -
-
- - {/* ── Metadata bar ──────────────────────────────────────────────── */} -
-
- Rôle : - {isAdmin ? "Admin" : "Invité"} -
-
- Créé le : - - {new Intl.DateTimeFormat("fr-FR", { - year: "numeric", - month: "short", - day: "2-digit", - }).format(new Date(tablo.created_at))} - -
-
- Statut : - - {statusLabel} - -
-
- Progression : -
-
-
-
- {progress.donePercentage}% -
-
-
- - {/* ── Tab navigation ──────────────────────────────────────────────── */} -
-
-
- {TABS.map((tab) => { - const isActive = activeSection === tab.id; - return ( - - ); - })} -
-
-
- - {/* ── Tab content ─────────────────────────────────────────────────── */} -
- {activeSection === "overview" && - (() => { - const overviewBlocks: Record = { - description: ( -
-

- Description du projet -

-

- Ce projet regroupe les tâches, fichiers et événements associés. Utilisez les - onglets ci-dessus pour naviguer entre les différentes sections. -

-
- ), - myTasks: ( -
-
-

- Mes tâches -

- -
-
- {myTabloTasks.length === 0 ? ( -
- Aucune tâche -
- ) : ( - visibleOverviewTasks.map((task) => ( -
setSearchParams({ section: "tasks" })} - > - -

- {task.title} -

-
- )) - )} - {myTabloTasks.length > 5 && ( - - )} -
-
- ), - files: ( -
-
-

Fichiers

- -
-
- {fileNames.length === 0 ? ( -

Aucun fichier

- ) : ( - fileNames.slice(0, 5).map((fileName) => ( -
-
- -
-
-

- {fileName} -

-
- -
- )) - )} -
-
- ), - info: ( -
-

Informations

-
-
-
Tâches
-
{tabloTasks.length}
-
-
-
Fichiers
-
{fileNames.length}
-
-
-
Statut
-
- {statusLabel} -
-
-
-
Rôle
-
- {isAdmin ? "Admin" : "Invité"} -
-
-
-
- ), - }; - - return ( - <> - {isAdmin && ( -
- {isLayoutEditMode && ( - - )} - -
- )} - -
-
{ - event.preventDefault(); - handleOverviewBlockDrop("left", overviewLayout.leftZone.length); - }} - > - {overviewLayout.leftZone.map((blockId, index) => ( -
handleOverviewBlockDragStart(event, "left", index)} - onDragOver={handleOverviewBlockDragOver} - onDrop={(event) => { - event.preventDefault(); - event.stopPropagation(); - handleOverviewBlockDrop("left", index); - }} - onDragEnd={() => setDraggedOverviewBlock(null)} - className={cn( - isLayoutEditMode && "cursor-move", - isLayoutEditMode && - draggedOverviewBlock?.zone === "left" && - draggedOverviewBlock.index === index && - "opacity-60" - )} - > - {isLayoutEditMode && ( -
- - Glisser pour réorganiser -
- )} - {overviewBlocks[blockId]} -
- ))} - {isLayoutEditMode && overviewLayout.leftZone.length === 0 && ( -
- Déposez un bloc ici -
- )} -
- -
{ - event.preventDefault(); - handleOverviewBlockDrop("right", overviewLayout.rightZone.length); - }} - > - {overviewLayout.rightZone.map((blockId, index) => ( -
handleOverviewBlockDragStart(event, "right", index)} - onDragOver={handleOverviewBlockDragOver} - onDrop={(event) => { - event.preventDefault(); - event.stopPropagation(); - handleOverviewBlockDrop("right", index); - }} - onDragEnd={() => setDraggedOverviewBlock(null)} - className={cn( - isLayoutEditMode && "cursor-move", - isLayoutEditMode && - draggedOverviewBlock?.zone === "right" && - draggedOverviewBlock.index === index && - "opacity-60" - )} - > - {isLayoutEditMode && ( -
- - Glisser pour réorganiser -
- )} - {overviewBlocks[blockId]} -
- ))} - {isLayoutEditMode && overviewLayout.rightZone.length === 0 && ( -
- Déposez un bloc ici -
- )} -
-
- - ); - })()} - - {activeSection === "tasks" && ( - ({ ...inv, id: String(inv.id) }))} - isInvitingUser={isInvitingUser} - isCancellingInvite={isCancellingInvite} - onCreateTask={(task) => createTask(task)} - onUpdateTask={(task) => updateTask(task)} - onUpdateTaskPositions={(updates) => updateTaskPositions(updates)} - onUpdateTablo={(data) => - updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) - } - onInviteUser={inviteUser} - onCancelInvite={(params) => - cancelInvite({ ...params, inviteId: Number(params.inviteId) }) - } - /> - )} - {activeSection === "files" && ( - ({ ...inv, id: String(inv.id) }))} + isInvitingUser={isInvitingUser} + isCancellingInvite={isCancellingInvite} + onCreateTask={(task) => createTask(task)} + onUpdateTask={(task) => updateTask(task)} + onDeleteTask={(taskId) => deleteTask(taskId)} + onUpdateTaskPositions={(updates) => updateTaskPositions(updates)} + onUpdateTablo={(data) => + updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) + } + onInviteUser={inviteUser} + onCancelInvite={(params) => + cancelInvite({ ...params, inviteId: Number(params.inviteId) }) + } + /> + )} + {activeSection === "files" && ( + ({ ...inv, id: String(inv.id) }))} + isInvitingUser={isInvitingUser} + isCancellingInvite={isCancellingInvite} + isCreatingFolder={isCreatingFolder} + isUpdatingFolder={isUpdatingFolder} + onCreateFile={(params) => uploadFile(params).then(() => undefined)} + onDeleteFile={(params) => deleteFile(params).then(() => undefined)} + onDownloadFile={(params) => downloadFile(params).then(() => undefined)} + onCreateFolder={(params) => createFolder(params).then(() => undefined)} + onUpdateFolder={(params) => updateFolder(params).then(() => undefined)} + onDeleteFolder={(params) => deleteFolder(params).then(() => undefined)} + onUpdateTablo={(data) => + updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) + } + onInviteUser={inviteUser} + onCancelInvite={(params) => + cancelInvite({ ...params, inviteId: Number(params.inviteId) }) + } + /> + )} + {activeSection === "discussion" && ( +
+ !f.startsWith("."))} - filesLoading={false} - filesError={null} - folders={foldersData?.folders ?? []} - foldersLoading={foldersLoading} - foldersError={foldersError as Error | null} - currentUser={currentUser} members={members} - pendingInvites={pendingInvites?.map((inv) => ({ ...inv, id: String(inv.id) }))} - isInvitingUser={isInvitingUser} - isCancellingInvite={isCancellingInvite} - isCreatingFolder={isCreatingFolder} - isUpdatingFolder={isUpdatingFolder} - onCreateFile={(params) => uploadFile(params).then(() => undefined)} - onDeleteFile={(params) => deleteFile(params).then(() => undefined)} - onDownloadFile={(params) => downloadFile(params).then(() => undefined)} - onCreateFolder={(params) => createFolder(params).then(() => undefined)} - onUpdateFolder={(params) => updateFolder(params).then(() => undefined)} - onDeleteFolder={(params) => deleteFolder(params).then(() => undefined)} - onUpdateTablo={(data) => - updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) - } - onInviteUser={inviteUser} - onCancelInvite={(params) => - cancelInvite({ ...params, inviteId: Number(params.inviteId) }) - } /> - )} - {activeSection === "discussion" && ( -
- -
- )} - {activeSection === "events" && ( - ({ ...inv, id: String(inv.id) }))} - isInvitingUser={isInvitingUser} - isCancellingInvite={isCancellingInvite} - onCreateEvent={() => undefined} - onUpdateTablo={(data) => - updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) - } - onInviteUser={inviteUser} - onCancelInvite={(params) => - cancelInvite({ ...params, inviteId: Number(params.inviteId) }) - } - /> - )} +
+ )} + {activeSection === "events" && ( + ({ ...inv, id: String(inv.id) }))} + isInvitingUser={isInvitingUser} + isCancellingInvite={isCancellingInvite} + onCreateEvent={() => undefined} + onUpdateTablo={(data) => + updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) + } + onInviteUser={inviteUser} + onCancelInvite={(params) => + cancelInvite({ ...params, inviteId: Number(params.inviteId) }) + } + /> + )} - {activeSection === "etapes" && ( - - createTask({ - ...task, - status: task.status as "todo" | "in_progress" | "in_review" | "done", - }) - } - onCreateEtape={(params) => createEtape(params).then(() => undefined)} - isCreatingEtape={isCreatingEtape} - /> - )} + {activeSection === "etapes" && ( + + createTask({ + ...task, + status: task.status as "todo" | "in_progress" | "in_review" | "done", + }) + } + onCreateEtape={(params) => createEtape(params).then(() => undefined)} + isCreatingEtape={isCreatingEtape} + /> + )} - {activeSection === "roadmap" && ( - updateTask({ id: taskId, status })} - /> - )} -
+ {activeSection === "roadmap" && ( + updateTask({ id: taskId, status })} + /> + )} + {/* Task Create Modal */} {tabloId && ( @@ -962,6 +494,9 @@ export const TabloDetailsPage = () => { onClose={closeTaskModal} initialStatus="todo" initialDueDate={taskModalInitialDueDate} + onCreateTask={(task) => createTask(task)} + onUpdateTask={(task) => updateTask(task)} + onDeleteTask={(taskId) => deleteTask(taskId)} /> )} @@ -1217,6 +752,6 @@ export const TabloDetailsPage = () => {
-
+ ); }; diff --git a/packages/tablo-views/src/EtapesSection.tsx b/packages/tablo-views/src/EtapesSection.tsx index c671847..9f4d0f1 100644 --- a/packages/tablo-views/src/EtapesSection.tsx +++ b/packages/tablo-views/src/EtapesSection.tsx @@ -108,27 +108,29 @@ export function EtapesSection({ return (
{isAdmin && ( -
+
{ + event.preventDefault(); + void handleAddEtape(); + }} + > setNewEtapeTitle(event.target.value)} placeholder="Nom de la nouvelle étape..." - onKeyDown={(event) => { - if (event.key === "Enter") { - void handleAddEtape(); - } - }} + required className="h-11 sm:h-9 sm:w-80" /> -
+ )} {etapes.length === 0 ? ( diff --git a/packages/tablo-views/src/TabloTasksSection.tsx b/packages/tablo-views/src/TabloTasksSection.tsx index 0743baa..350a38c 100644 --- a/packages/tablo-views/src/TabloTasksSection.tsx +++ b/packages/tablo-views/src/TabloTasksSection.tsx @@ -38,6 +38,7 @@ interface TabloTasksSectionProps { isCancellingInvite?: boolean; onCreateTask?: (task: KanbanTaskInsert) => void; onUpdateTask?: (task: KanbanTaskUpdate & { id: string; tablo_id: string }) => void; + onDeleteTask?: (taskId: string) => void; onUpdateTaskPositions?: (updates: Array<{ id: string; position: number; status: TaskStatus }>) => void; onUpdateTablo?: (data: { id: string; name?: string | null; color?: string | null }) => Promise; onInviteUser?: (params: { email: string; tablo_id: string }) => void; @@ -56,6 +57,7 @@ export const TabloTasksSection = ({ isCancellingInvite, onCreateTask, onUpdateTask, + onDeleteTask, onUpdateTaskPositions, onUpdateTablo, onInviteUser, @@ -278,6 +280,7 @@ export const TabloTasksSection = ({ etapes={etapes} onCreateTask={onCreateTask} onUpdateTask={onUpdateTask} + onDeleteTask={onDeleteTask} />
); diff --git a/packages/tablo-views/src/components/kanban/TaskModal.tsx b/packages/tablo-views/src/components/kanban/TaskModal.tsx index 6fea2df..b87066b 100644 --- a/packages/tablo-views/src/components/kanban/TaskModal.tsx +++ b/packages/tablo-views/src/components/kanban/TaskModal.tsx @@ -40,6 +40,8 @@ interface TaskModalProps { onCreateTask?: (task: KanbanTaskInsert) => void; /** Called when updating an existing task. */ onUpdateTask?: (task: KanbanTaskUpdate & { id: string; tablo_id: string }) => void; + /** Called when deleting an existing task. */ + onDeleteTask?: (taskId: string) => void; } export const TaskModal = ({ @@ -56,6 +58,7 @@ export const TaskModal = ({ initialDueDate, onCreateTask, onUpdateTask, + onDeleteTask, }: TaskModalProps) => { const [title, setTitle] = useState(""); const [description, setDescription] = useState(""); @@ -137,6 +140,12 @@ export const TaskModal = ({ onClose(); }; + const handleDelete = () => { + if (!taskId || !task) return; + onDeleteTask?.(task.id); + onClose(); + }; + if (!isOpen) return null; return ( @@ -252,6 +261,16 @@ export const TaskModal = ({ {/* Actions */}
+ {taskId && task && ( + + )} From fc82ea1949c8e72084d634b2d90da7c46cb6a43b Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Thu, 16 Apr 2026 11:31:59 +0200 Subject: [PATCH 29/75] test: stabilize api suite --- .../__tests__/routes/clientInvites.test.ts | 12 ++++----- apps/api/src/__tests__/routes/tablo.test.ts | 26 +++++++++++++++++-- apps/api/vitest.config.ts | 1 + 3 files changed, 31 insertions(+), 8 deletions(-) diff --git a/apps/api/src/__tests__/routes/clientInvites.test.ts b/apps/api/src/__tests__/routes/clientInvites.test.ts index 6b7cb25..17bfc08 100644 --- a/apps/api/src/__tests__/routes/clientInvites.test.ts +++ b/apps/api/src/__tests__/routes/clientInvites.test.ts @@ -143,10 +143,10 @@ describe("Client Invites Endpoints", () => { expect(invite?.is_pending).toBe(true); }); - it("should reject non-admin users with 403", async () => { + it("should reject temporary users before admin check", async () => { // tempUser is NOT admin of adminTabloId (owner user owns it) const res = await postInvite(tempUser, adminTabloId, testEmail); - expect(res.status).toBe(403); + expect(res.status).toBe(401); }); it("should return 400 for an invalid email", async () => { @@ -292,9 +292,9 @@ describe("Client Invites Endpoints", () => { expect(found.is_pending).toBe(true); }); - it("should return 403 for a non-admin user", async () => { + it("should return 401 for a temporary user before admin check", async () => { const res = await getPending(tempUser, adminTabloId); - expect(res.status).toBe(403); + expect(res.status).toBe(401); }); it("should return 401 for unauthenticated requests", async () => { @@ -342,7 +342,7 @@ describe("Client Invites Endpoints", () => { expect(invite?.is_pending).toBe(false); }); - it("should return 403 for a non-admin user", async () => { + it("should return 401 for a temporary user before admin check", async () => { const token = `test_cancel_nonadmin_${Date.now()}`; const inviteId = await insertClientInvite({ tabloId: adminTabloId, @@ -352,7 +352,7 @@ describe("Client Invites Endpoints", () => { }); const res = await deleteInvite(tempUser, adminTabloId, inviteId); - expect(res.status).toBe(403); + expect(res.status).toBe(401); }); it("should return 404 for a non-existent invite", async () => { diff --git a/apps/api/src/__tests__/routes/tablo.test.ts b/apps/api/src/__tests__/routes/tablo.test.ts index b445c90..923fa38 100644 --- a/apps/api/src/__tests__/routes/tablo.test.ts +++ b/apps/api/src/__tests__/routes/tablo.test.ts @@ -1,7 +1,7 @@ import { createClient } from "@supabase/supabase-js"; import { randomUUID } from "node:crypto"; import { testClient } from "hono/testing"; -import { beforeEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { createConfig } from "../../config.js"; import { MiddlewareManager } from "../../middlewares/middleware.js"; import { getMainRouter } from "../../routers/index.js"; @@ -34,6 +34,7 @@ describe("Tablo Endpoint", () => { const supabaseAdmin = createClient(config.SUPABASE_URL, config.SUPABASE_SERVICE_ROLE_KEY, { auth: { persistSession: false }, }); + const createdTabloIds: string[] = []; beforeEach(() => { // Reset all mocks before each test @@ -41,6 +42,16 @@ describe("Tablo Endpoint", () => { mockSendMail.mockResolvedValue({ messageId: "test-message-id" }); }); + afterEach(async () => { + if (createdTabloIds.length === 0) { + return; + } + + const idsToDelete = createdTabloIds.splice(0, createdTabloIds.length); + await supabaseAdmin.from("tablo_access").delete().in("tablo_id", idsToDelete); + await supabaseAdmin.from("tablos").delete().in("id", idsToDelete); + }); + // Helper function to create tablo const createTabloRequest = async ( user: TestUserData, @@ -171,6 +182,8 @@ describe("Tablo Endpoint", () => { expect(res.status).toBe(200); const data = await res.json(); expect(data.message).toBe("Tablo created successfully"); + expect(data.tablo?.id).toBeDefined(); + createdTabloIds.push(data.tablo.id); }); it("should deny temp user from creating a tablo (regularUserCheck blocks temporary users)", async () => { @@ -271,7 +284,16 @@ describe("Tablo Endpoint", () => { } if (fillerTablos.length > 0) { - await supabaseAdmin.from("tablos").insert(fillerTablos); + const { data: insertedTablos, error: insertError } = await supabaseAdmin + .from("tablos") + .insert(fillerTablos) + .select("id"); + + if (insertError) { + throw new Error(`Failed to insert filler tablos: ${insertError.message}`); + } + + createdTabloIds.push(...(insertedTablos ?? []).map((tablo) => tablo.id)); } try { diff --git a/apps/api/vitest.config.ts b/apps/api/vitest.config.ts index e2c7fcf..8586540 100644 --- a/apps/api/vitest.config.ts +++ b/apps/api/vitest.config.ts @@ -12,6 +12,7 @@ export default defineConfig({ exclude: ["node_modules", "dist"], reporters: ["verbose"], pool: "forks", + fileParallelism: false, }, resolve: { alias: { From 37ab73bced34a847e56d50aacd4a188231f8ab23 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Thu, 16 Apr 2026 11:34:49 +0200 Subject: [PATCH 30/75] feat: add shared single tablo view --- apps/clients/tsconfig.tsbuildinfo | 2 +- packages/tablo-views/src/index.ts | 10 + .../src/single-tablo/SingleTabloOverview.tsx | 262 ++++++++++++++++++ .../src/single-tablo/SingleTabloView.tsx | 169 +++++++++++ .../src/single-tablo/overviewLayout.ts | 66 +++++ .../src/single-tablo/overviewReorder.ts | 46 +++ .../tablo-views/src/single-tablo/shared.tsx | 31 +++ 7 files changed, 585 insertions(+), 1 deletion(-) create mode 100644 packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx create mode 100644 packages/tablo-views/src/single-tablo/SingleTabloView.tsx create mode 100644 packages/tablo-views/src/single-tablo/overviewLayout.ts create mode 100644 packages/tablo-views/src/single-tablo/overviewReorder.ts create mode 100644 packages/tablo-views/src/single-tablo/shared.tsx diff --git a/apps/clients/tsconfig.tsbuildinfo b/apps/clients/tsconfig.tsbuildinfo index a7db947..1df4210 100644 --- a/apps/clients/tsconfig.tsbuildinfo +++ b/apps/clients/tsconfig.tsbuildinfo @@ -1 +1 @@ -{"root":["./src/app.tsx","./src/i18n.ts","./src/main.tsx","./src/routes.tsx","./src/components/clientlayout.tsx","./src/lib/supabase.ts","./src/pages/authcallback.tsx","./src/pages/clienttablolistpage.tsx","./src/pages/clienttablopage.tsx"],"version":"5.9.3"} \ No newline at end of file +{"root":["./src/app.tsx","./src/i18n.test.ts","./src/i18n.ts","./src/main.tsx","./src/maincss.test.ts","./src/routes.tsx","./src/setuptests.ts","./src/components/clientlayout.test.tsx","./src/components/clientlayout.tsx","./src/lib/supabase.ts","./src/pages/authcallback.tsx","./src/pages/clienttablolistpage.tsx","./src/pages/clienttablopage.test.tsx","./src/pages/clienttablopage.tsx","./src/test/testhelpers.test.tsx","./src/test/testhelpers.tsx"],"version":"5.9.3"} \ No newline at end of file diff --git a/packages/tablo-views/src/index.ts b/packages/tablo-views/src/index.ts index b67c572..ab47c35 100644 --- a/packages/tablo-views/src/index.ts +++ b/packages/tablo-views/src/index.ts @@ -7,6 +7,16 @@ export { RoadmapSection } from "./RoadmapSection"; export { TabloHeaderActions } from "./TabloHeaderActions"; export { ChatMessages } from "./ChatMessages"; export { TabloDetailsShell } from "./TabloDetailsShell"; +export { SingleTabloOverview } from "./single-tablo/SingleTabloOverview"; +export { SingleTabloView } from "./single-tablo/SingleTabloView"; +export { + DEFAULT_OVERVIEW_LAYOUT, + sanitizeOverviewLayout, +} from "./single-tablo/overviewLayout"; +export type { OverviewBlockId, OverviewLayoutV1 } from "./single-tablo/overviewLayout"; +export { moveBetweenZones, moveWithinZone } from "./single-tablo/overviewReorder"; +export { getSingleTabloStatusConfig } from "./single-tablo/shared"; +export type { SingleTabloTabId } from "./single-tablo/shared"; // Sub-components export { GanttChart } from "./components/gantt/GanttChart"; diff --git a/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx b/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx new file mode 100644 index 0000000..012828d --- /dev/null +++ b/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx @@ -0,0 +1,262 @@ +import { cn } from "@xtablo/shared"; +import type { KanbanTask } from "@xtablo/shared-types"; +import { Button } from "@xtablo/ui/components/button"; +import { FileIcon, GripVerticalIcon, LayoutPanelTopIcon, ListChecksIcon, RotateCcwIcon } from "lucide-react"; +import type { OverviewBlockId, OverviewLayoutV1 } from "./overviewLayout"; + +interface DraggedBlock { + zone: "left" | "right"; + index: number; +} + +interface SingleTabloOverviewProps { + roleLabel?: string; + statusLabel?: string; + statusBadgeClass?: string; + description: string; + tasks: KanbanTask[]; + projectTaskCount: number; + personalTaskCount: number; + fileNames: string[]; + showFileMenu?: boolean; + onOpenTasks: () => void; + onOpenFiles: () => void; + onCreateTask: () => void; + onToggleTaskDone: (taskId: string) => void; + showAllTasks: boolean; + onToggleShowAllTasks: () => void; + layout: OverviewLayoutV1; + canEditLayout: boolean; + isLayoutEditMode: boolean; + draggedBlock: DraggedBlock | null; + onToggleLayoutEditMode: () => void; + onResetLayout: () => void; + onBlockDragStart: ( + event: React.DragEvent, + zone: "left" | "right", + index: number + ) => void; + onBlockDragOver: (event: React.DragEvent) => void; + onBlockDrop: (zone: "left" | "right", index: number) => void; + onBlockDragEnd: () => void; +} + +function OverviewCard({ + title, + actions, + children, + draggable = false, + onDragStart, + onDragOver, + onDrop, + onDragEnd, + isDragged = false, +}: { + title: string; + actions?: React.ReactNode; + children: React.ReactNode; + draggable?: boolean; + onDragStart?: (event: React.DragEvent) => void; + onDragOver?: (event: React.DragEvent) => void; + onDrop?: (event: React.DragEvent) => void; + onDragEnd?: () => void; + isDragged?: boolean; +}) { + return ( +
+
+
+ {draggable && } +

{title}

+
+ {actions} +
+ {children} +
+ ); +} + +export function SingleTabloOverview({ + description, + tasks, + projectTaskCount, + personalTaskCount, + fileNames, + onOpenTasks, + onOpenFiles, + onCreateTask, + onToggleTaskDone, + showAllTasks, + onToggleShowAllTasks, + layout, + canEditLayout, + isLayoutEditMode, + draggedBlock, + onToggleLayoutEditMode, + onResetLayout, + onBlockDragStart, + onBlockDragOver, + onBlockDrop, + onBlockDragEnd, +}: SingleTabloOverviewProps) { + const renderBlockContent = (blockId: OverviewBlockId) => { + switch (blockId) { + case "description": + return { + title: "Description du projet", + children: ( +

+ {description} +

+ ), + }; + case "myTasks": + return { + title: "Mes tâches", + actions: ( +
+ + +
+ ), + children: ( +
+ {tasks.length === 0 ? ( +

Aucune tâche.

+ ) : ( + tasks.map((task) => ( + + )) + )} + {personalTaskCount > 5 && ( + + )} +
+ ), + }; + case "files": + return { + title: "Fichiers", + actions: ( + + ), + children: ( +
+ {fileNames.length === 0 ? ( +

Aucun fichier.

+ ) : ( + fileNames.slice(0, 5).map((fileName) => ( +
+ + {fileName} +
+ )) + )} +
+ ), + }; + case "info": + return { + title: "Informations", + children: ( +
+
+ + {projectTaskCount} tâches sur le projet +
+
+ + {personalTaskCount} tâches pour vous +
+
+ ), + }; + } + }; + + const renderZone = (zone: "left" | "right", blocks: OverviewBlockId[]) => ( +
+ {blocks.map((blockId, index) => { + const block = renderBlockContent(blockId); + + return ( +
onBlockDrop(zone, index)} + > + onBlockDragStart(event, zone, index)} + onDragOver={onBlockDragOver} + onDrop={() => onBlockDrop(zone, index)} + onDragEnd={onBlockDragEnd} + isDragged={draggedBlock?.zone === zone && draggedBlock.index === index} + > + {block.children} + +
+ ); + })} +
+ ); + + return ( +
+ {canEditLayout && ( +
+ + {isLayoutEditMode && ( + + )} +
+ )} + +
+
{renderZone("left", layout.leftZone)}
+
{renderZone("right", layout.rightZone)}
+
+
+ ); +} diff --git a/packages/tablo-views/src/single-tablo/SingleTabloView.tsx b/packages/tablo-views/src/single-tablo/SingleTabloView.tsx new file mode 100644 index 0000000..4e3b44e --- /dev/null +++ b/packages/tablo-views/src/single-tablo/SingleTabloView.tsx @@ -0,0 +1,169 @@ +import { cn } from "@xtablo/shared"; +import type { UserTablo } from "@xtablo/shared-types"; +import { Button } from "@xtablo/ui/components/button"; +import { + CalendarIcon, + FolderIcon, + KanbanIcon, + LayoutDashboardIcon, + ListChecksIcon, + MapIcon, + MessageCircleIcon, +} from "lucide-react"; +import { Link } from "react-router-dom"; +import { + TabloDetailsShell, + type TabloDetailsShellMetadataItem, + type TabloDetailsShellTab, +} from "../TabloDetailsShell"; +import type { SingleTabloTabId } from "./shared"; + +const TABS: TabloDetailsShellTab[] = [ + { id: "overview", label: "Aperçu", icon: LayoutDashboardIcon }, + { id: "etapes", label: "Étapes", icon: ListChecksIcon }, + { id: "tasks", label: "Tâches", icon: KanbanIcon }, + { id: "files", label: "Fichiers", icon: FolderIcon }, + { id: "discussion", label: "Discussion", icon: MessageCircleIcon }, + { id: "events", label: "Événements", icon: CalendarIcon }, + { id: "roadmap", label: "Roadmap", icon: MapIcon }, +]; + +type DiscussionAction = + | { + kind: "link"; + to: string; + } + | { + kind: "button"; + onClick: () => void; + }; + +interface SingleTabloViewProps { + tablo: Pick; + roleLabel: string; + statusLabel: string; + statusBadgeClass: string; + progress: { + startedPercentage: number; + donePercentage: number; + }; + activeTab: SingleTabloTabId; + onTabChange: (tabId: SingleTabloTabId) => void; + hasUnreadDiscussion?: boolean; + discussionAction?: DiscussionAction; + canInviteMembers?: boolean; + onOpenInviteDialog?: () => void; + children: React.ReactNode; +} + +export function SingleTabloView({ + tablo, + roleLabel, + statusLabel, + statusBadgeClass, + progress, + activeTab, + onTabChange, + hasUnreadDiscussion = false, + discussionAction, + canInviteMembers = false, + onOpenInviteDialog, + children, +}: SingleTabloViewProps) { + const metadata: TabloDetailsShellMetadataItem[] = [ + { + key: "role", + label: "Rôle", + value: {roleLabel}, + }, + { + key: "created-at", + label: "Créé le", + value: ( + + {new Intl.DateTimeFormat("fr-FR", { + year: "numeric", + month: "short", + day: "2-digit", + }).format(new Date(tablo.created_at))} + + ), + }, + { + key: "status", + label: "Statut", + value: ( + + {statusLabel} + + ), + }, + { + key: "progress", + label: "Progression", + value: ( + <> +
+
+
+
+ {progress.donePercentage}% + + ), + }, + ]; + + const tabs = TABS.map((tab) => + tab.id === "discussion" ? { ...tab, hasUnread: hasUnreadDiscussion } : tab + ); + + const discussionButton = + discussionAction?.kind === "link" ? ( + + ) : discussionAction?.kind === "button" ? ( + + ) : null; + + const inviteButton = + canInviteMembers && onOpenInviteDialog ? ( + + ) : null; + + const headerActions = + discussionButton || inviteButton ? ( + <> + {discussionButton} + {inviteButton} + + ) : undefined; + + return ( + onTabChange(tabId as SingleTabloTabId)} + isDiscussionView={activeTab === "discussion"} + headerActions={headerActions} + > + {children} + + ); +} diff --git a/packages/tablo-views/src/single-tablo/overviewLayout.ts b/packages/tablo-views/src/single-tablo/overviewLayout.ts new file mode 100644 index 0000000..6424602 --- /dev/null +++ b/packages/tablo-views/src/single-tablo/overviewLayout.ts @@ -0,0 +1,66 @@ +type OverviewLayoutVersion = 1; + +export type OverviewBlockId = "description" | "myTasks" | "files" | "info"; + +export type OverviewLayoutV1 = { + version: OverviewLayoutVersion; + leftZone: OverviewBlockId[]; + rightZone: OverviewBlockId[]; + updatedAt?: string; + updatedBy?: string; +}; + +const DEFAULT_LEFT_ZONE: OverviewBlockId[] = ["description", "myTasks"]; +const DEFAULT_RIGHT_ZONE: OverviewBlockId[] = ["files", "info"]; +const ALL_BLOCK_IDS: OverviewBlockId[] = ["description", "myTasks", "files", "info"]; + +export const DEFAULT_OVERVIEW_LAYOUT: OverviewLayoutV1 = { + version: 1, + leftZone: DEFAULT_LEFT_ZONE, + rightZone: DEFAULT_RIGHT_ZONE, +}; + +function unique(items: T[]): T[] { + return [...new Set(items)]; +} + +function isObject(value: unknown): value is Record { + return typeof value === "object" && value !== null; +} + +function parseZone(value: unknown): OverviewBlockId[] { + if (!Array.isArray(value)) return []; + const valid = value.filter( + (item): item is OverviewBlockId => + item === "description" || item === "myTasks" || item === "files" || item === "info" + ); + return unique(valid); +} + +export function sanitizeOverviewLayout(input: unknown): OverviewLayoutV1 { + if (!isObject(input)) { + return DEFAULT_OVERVIEW_LAYOUT; + } + + const leftZoneInput = parseZone(input.leftZone); + const rightZoneInput = parseZone(input.rightZone); + + const leftZoneSize = leftZoneInput.length; + const allBlocks = unique([...leftZoneInput, ...rightZoneInput]); + + for (const blockId of ALL_BLOCK_IDS) { + if (!allBlocks.includes(blockId)) { + allBlocks.push(blockId); + } + } + + const safeLeftZoneSize = Math.min(leftZoneSize, allBlocks.length); + const leftZone = allBlocks.slice(0, safeLeftZoneSize); + const rightZone = allBlocks.slice(safeLeftZoneSize); + + return { + version: 1, + leftZone, + rightZone, + }; +} diff --git a/packages/tablo-views/src/single-tablo/overviewReorder.ts b/packages/tablo-views/src/single-tablo/overviewReorder.ts new file mode 100644 index 0000000..c62c48d --- /dev/null +++ b/packages/tablo-views/src/single-tablo/overviewReorder.ts @@ -0,0 +1,46 @@ +export function moveWithinZone(items: T[], fromIndex: number, toIndex: number): T[] { + if (fromIndex < 0 || fromIndex >= items.length || toIndex < 0 || toIndex > items.length) { + return items; + } + + const next = [...items]; + const [moved] = next.splice(fromIndex, 1); + const insertionIndex = Math.min(toIndex, next.length); + next.splice(insertionIndex, 0, moved); + + if (next.every((item, index) => item === items[index])) { + return items; + } + + return next; +} + +export function moveBetweenZones( + sourceItems: T[], + targetItems: T[], + sourceIndex: number, + targetIndex: number +): { + sourceItems: T[]; + targetItems: T[]; +} { + if ( + sourceIndex < 0 || + sourceIndex >= sourceItems.length || + targetIndex < 0 || + targetIndex > targetItems.length + ) { + return { sourceItems, targetItems }; + } + + const nextSourceItems = [...sourceItems]; + const [moved] = nextSourceItems.splice(sourceIndex, 1); + const nextTargetItems = [...targetItems]; + const insertionIndex = Math.min(targetIndex, nextTargetItems.length); + nextTargetItems.splice(insertionIndex, 0, moved); + + return { + sourceItems: nextSourceItems, + targetItems: nextTargetItems, + }; +} diff --git a/packages/tablo-views/src/single-tablo/shared.tsx b/packages/tablo-views/src/single-tablo/shared.tsx new file mode 100644 index 0000000..2b879d3 --- /dev/null +++ b/packages/tablo-views/src/single-tablo/shared.tsx @@ -0,0 +1,31 @@ +export type SingleTabloTabId = + | "overview" + | "etapes" + | "tasks" + | "files" + | "discussion" + | "events" + | "roadmap"; + +export function getSingleTabloStatusConfig(status: string) { + switch (status) { + case "in_progress": + return { + label: "En cours", + badgeClass: + "bg-yellow-50 text-yellow-700 border border-yellow-200 dark:bg-yellow-950/30 dark:text-yellow-400 dark:border-yellow-800", + }; + case "done": + return { + label: "Terminé", + badgeClass: + "bg-green-50 text-green-600 border border-green-200 dark:bg-green-950/30 dark:text-green-400 dark:border-green-800", + }; + default: + return { + label: "À faire", + badgeClass: + "bg-blue-50 text-blue-600 border border-blue-200 dark:bg-blue-950/30 dark:text-blue-400 dark:border-blue-800", + }; + } +} From e36c536cf2e74ce1c6140dcc882ae06e1e022ef7 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Thu, 16 Apr 2026 11:54:41 +0200 Subject: [PATCH 31/75] Allow updates deletions on etapes / tasks --- .../src/pages/tablo-details.layout.test.tsx | 73 ++++++- apps/main/src/pages/tablo-details.tsx | 8 + packages/tablo-views/src/EtapesSection.tsx | 187 +++++++++++++++--- 3 files changed, 239 insertions(+), 29 deletions(-) diff --git a/apps/main/src/pages/tablo-details.layout.test.tsx b/apps/main/src/pages/tablo-details.layout.test.tsx index 17c103e..a327343 100644 --- a/apps/main/src/pages/tablo-details.layout.test.tsx +++ b/apps/main/src/pages/tablo-details.layout.test.tsx @@ -7,6 +7,8 @@ import { TabloDetailsPage } from "./tablo-details"; const mutateUpdateTablo = vi.fn(); const mutateUpdateTask = vi.fn(); const mutateCreateEtape = vi.fn(); +const mutateUpdateEtape = vi.fn(); +const mutateDeleteEtape = vi.fn(); const mutateDeleteTask = vi.fn(); const tablosData = [ @@ -107,7 +109,22 @@ vi.mock("../hooks/tasks", () => ({ ], }), useTabloEtapes: () => ({ - data: [], + data: [ + { + id: "etape-1", + tablo_id: "tablo-1", + title: "Kickoff", + description: null, + status: "todo", + assignee_id: null, + position: 0, + created_at: "2026-01-01T00:00:00.000Z", + updated_at: "2026-01-01T00:00:00.000Z", + is_parent: true, + parent_task_id: null, + due_date: null, + }, + ], }), useUpdateTask: () => ({ mutate: mutateUpdateTask, @@ -122,6 +139,14 @@ vi.mock("../hooks/tasks", () => ({ mutateAsync: mutateCreateEtape, isPending: false, }), + useUpdateEtape: () => ({ + mutateAsync: mutateUpdateEtape, + isPending: false, + }), + useDeleteEtape: () => ({ + mutateAsync: mutateDeleteEtape, + isPending: false, + }), useCreateTask: () => ({ mutate: vi.fn(), }), @@ -208,10 +233,54 @@ describe("TabloDetailsPage overview layout", () => { expect(mutateCreateEtape).toHaveBeenCalledWith({ tabloId: "tablo-1", title: "Kickoff", - position: 0, + position: 1, }); }); + it("updates an etape from the etapes tab", async () => { + const user = userEvent.setup(); + mutateUpdateEtape.mockResolvedValueOnce(undefined); + + renderWithProviders(, { + route: "/tablos/tablo-1", + path: "/tablos/:tabloId", + }); + + await user.click(screen.getByRole("button", { name: "Étapes" })); + await user.click(screen.getByRole("button", { name: "Modifier l'étape Kickoff" })); + await user.clear(screen.getByDisplayValue("Kickoff")); + await user.type(screen.getByPlaceholderText("Nom de l'étape"), "Planification"); + await user.click(screen.getByRole("button", { name: "Enregistrer l'étape" })); + + expect(mutateUpdateEtape).toHaveBeenCalledWith({ + id: "etape-1", + tabloId: "tablo-1", + title: "Planification", + }); + }); + + it("deletes an etape from the etapes tab", async () => { + const user = userEvent.setup(); + mutateDeleteEtape.mockResolvedValueOnce(undefined); + const confirmSpy = vi.spyOn(window, "confirm").mockReturnValue(true); + + renderWithProviders(, { + route: "/tablos/tablo-1", + path: "/tablos/:tabloId", + }); + + await user.click(screen.getByRole("button", { name: "Étapes" })); + await user.click(screen.getByRole("button", { name: "Supprimer l'étape Kickoff" })); + + expect(confirmSpy).toHaveBeenCalled(); + expect(mutateDeleteEtape).toHaveBeenCalledWith({ + id: "etape-1", + tabloId: "tablo-1", + }); + + confirmSpy.mockRestore(); + }); + it("deletes a task from the task modal", async () => { const user = userEvent.setup(); diff --git a/apps/main/src/pages/tablo-details.tsx b/apps/main/src/pages/tablo-details.tsx index 50dfa93..824a74e 100644 --- a/apps/main/src/pages/tablo-details.tsx +++ b/apps/main/src/pages/tablo-details.tsx @@ -64,8 +64,10 @@ import { useAllTasks, useCreateEtape, useCreateTask, + useDeleteEtape, useDeleteTask, useTabloEtapes, + useUpdateEtape, useUpdateTask, useUpdateTaskPositions, } from "../hooks/tasks"; @@ -127,6 +129,8 @@ export const TabloDetailsPage = () => { const { mutate: updateTablo, mutateAsync: updateTabloAsync } = useUpdateTablo(); const { mutate: createTask } = useCreateTask(); const { mutateAsync: createEtape, isPending: isCreatingEtape } = useCreateEtape(); + const { mutateAsync: updateEtape, isPending: isUpdatingEtape } = useUpdateEtape(); + const { mutateAsync: deleteEtape, isPending: isDeletingEtape } = useDeleteEtape(); const { mutate: updateTaskPositions } = useUpdateTaskPositions(); // Files & folders hooks @@ -473,7 +477,11 @@ export const TabloDetailsPage = () => { }) } onCreateEtape={(params) => createEtape(params).then(() => undefined)} + onUpdateEtape={(params) => updateEtape(params).then(() => undefined)} + onDeleteEtape={(params) => deleteEtape(params).then(() => undefined)} isCreatingEtape={isCreatingEtape} + isUpdatingEtape={isUpdatingEtape} + isDeletingEtape={isDeletingEtape} /> )} diff --git a/packages/tablo-views/src/EtapesSection.tsx b/packages/tablo-views/src/EtapesSection.tsx index 9f4d0f1..e1b22e8 100644 --- a/packages/tablo-views/src/EtapesSection.tsx +++ b/packages/tablo-views/src/EtapesSection.tsx @@ -4,11 +4,15 @@ import { Button } from "@xtablo/ui/components/button"; import { Input } from "@xtablo/ui/components/input"; import { CalendarIcon, + CheckIcon, ChevronDownIcon, ChevronRightIcon, CircleCheckIcon, + PencilIcon, ListChecksIcon, PlusIcon, + Trash2Icon, + XIcon, } from "lucide-react"; import { useState } from "react"; @@ -26,7 +30,11 @@ interface EtapesSectionProps { position: number; }) => void; onCreateEtape: (params: { tabloId: string; title: string; position: number }) => Promise; + onUpdateEtape?: (params: { id: string; tabloId: string; title: string }) => Promise; + onDeleteEtape?: (params: { id: string; tabloId: string }) => Promise; isCreatingEtape?: boolean; + isUpdatingEtape?: boolean; + isDeletingEtape?: boolean; } export function EtapesSection({ @@ -36,7 +44,11 @@ export function EtapesSection({ isAdmin, onCreateTask, onCreateEtape, + onUpdateEtape, + onDeleteEtape, isCreatingEtape = false, + isUpdatingEtape = false, + isDeletingEtape = false, }: EtapesSectionProps) { const [expandedEtapes, setExpandedEtapes] = useState>( new Set(etapes.map((e) => e.id)) @@ -44,6 +56,8 @@ export function EtapesSection({ const [addingTaskToEtape, setAddingTaskToEtape] = useState(null); const [newEtapeTitle, setNewEtapeTitle] = useState(""); const [newTaskTitle, setNewTaskTitle] = useState(""); + const [editingEtapeId, setEditingEtapeId] = useState(null); + const [editingEtapeTitle, setEditingEtapeTitle] = useState(""); const toggleEtape = (id: string) => { setExpandedEtapes((prev) => { @@ -86,6 +100,46 @@ export function EtapesSection({ setNewEtapeTitle(""); }; + const startEditingEtape = (etapeId: string, title: string) => { + setEditingEtapeId(etapeId); + setEditingEtapeTitle(title); + }; + + const cancelEditingEtape = () => { + setEditingEtapeId(null); + setEditingEtapeTitle(""); + }; + + const handleUpdateEtape = async (etapeId: string) => { + const title = editingEtapeTitle.trim(); + if (!title || !tabloId) { + return; + } + + await onUpdateEtape?.({ + id: etapeId, + tabloId, + title, + }); + + cancelEditingEtape(); + }; + + const handleDeleteEtape = async (etapeId: string, title: string) => { + if (!tabloId) { + return; + } + + if (!window.confirm(`Supprimer l'étape "${title}" ?`)) { + return; + } + + await onDeleteEtape?.({ + id: etapeId, + tabloId, + }); + }; + const statusConfig: Record = { todo: { label: "À faire", @@ -159,6 +213,7 @@ export function EtapesSection({ ? "in_progress" : "todo"; const status = statusConfig[derivedStatus] ?? statusConfig.todo; + const isEditing = editingEtapeId === etape.id; return (
{/* Etape header */} -
+ +
+ + {index + 1} + +
+ +
+ {isEditing ? ( + setEditingEtapeTitle(event.target.value)} + onClick={(event) => event.stopPropagation()} + onKeyDown={(event) => { + if (event.key === "Enter") { + event.preventDefault(); + void handleUpdateEtape(etape.id); + } + + if (event.key === "Escape") { + event.preventDefault(); + cancelEditingEtape(); + } + }} + placeholder="Nom de l'étape" + aria-label="Nom de l'étape" + autoFocus + className="h-9" + /> + ) : ( + <> +

+ {etape.title} +

+ {etape.description && ( +

+ {etape.description} +

+ )} + + )} +
+
{etape.due_date && ( @@ -237,8 +319,59 @@ export function EtapesSection({
)} + + {isAdmin && ( +
+ {isEditing ? ( + <> + + + + ) : ( + <> + + + + )} +
+ )}
- +
{/* Child tasks + add task */} {isExpanded && ( From 983dbb01b52cb26503119098942dbbbd1323b913 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Thu, 16 Apr 2026 12:02:18 +0200 Subject: [PATCH 32/75] fix: move task deletion to inline actions --- .../src/pages/tablo-details.layout.test.tsx | 5 +- apps/main/src/pages/tasks.test.tsx | 92 +++++++++++++++++++ apps/main/src/pages/tasks.tsx | 26 +++++- .../tablo-views/src/TabloTasksSection.tsx | 1 + .../src/components/kanban/KanbanBoard.tsx | 3 + .../src/components/kanban/KanbanColumn.tsx | 3 + .../src/components/kanban/KanbanTaskCard.tsx | 26 +++++- .../src/components/kanban/TaskModal.tsx | 17 ---- 8 files changed, 147 insertions(+), 26 deletions(-) create mode 100644 apps/main/src/pages/tasks.test.tsx diff --git a/apps/main/src/pages/tablo-details.layout.test.tsx b/apps/main/src/pages/tablo-details.layout.test.tsx index a327343..1e36a04 100644 --- a/apps/main/src/pages/tablo-details.layout.test.tsx +++ b/apps/main/src/pages/tablo-details.layout.test.tsx @@ -281,7 +281,7 @@ describe("TabloDetailsPage overview layout", () => { confirmSpy.mockRestore(); }); - it("deletes a task from the task modal", async () => { + it("deletes a task from the inline kanban action", async () => { const user = userEvent.setup(); renderWithProviders(, { @@ -290,8 +290,7 @@ describe("TabloDetailsPage overview layout", () => { }); await user.click(screen.getByRole("button", { name: "Tâches" })); - await user.click(screen.getByText("Task A")); - await user.click(screen.getByRole("button", { name: "Supprimer la tâche" })); + await user.click(screen.getByRole("button", { name: "Supprimer la tâche Task A" })); expect(mutateDeleteTask).toHaveBeenCalledWith("task-1"); }); diff --git a/apps/main/src/pages/tasks.test.tsx b/apps/main/src/pages/tasks.test.tsx new file mode 100644 index 0000000..e421f12 --- /dev/null +++ b/apps/main/src/pages/tasks.test.tsx @@ -0,0 +1,92 @@ +import { screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { TasksPage } from "./tasks"; +import { renderWithProviders } from "../utils/testHelpers"; + +const mutateUpdateTask = vi.fn(); +const mutateDeleteTask = vi.fn(); + +vi.mock("../hooks/tablos", () => ({ + useTablosList: () => ({ + data: [ + { + id: "tablo-1", + name: "Projet Alpha", + color: "bg-blue-500", + }, + ], + isLoading: false, + }), +})); + +vi.mock("../hooks/tasks", () => ({ + useAllTasks: () => ({ + data: [ + { + id: "task-1", + tablo_id: "tablo-1", + title: "Task A", + description: "Description", + status: "todo", + due_date: null, + assignee_id: "123", + assignee_name: "John Doe", + assignee_avatar: null, + tablos: { + id: "tablo-1", + name: "Projet Alpha", + color: "bg-blue-500", + }, + }, + ], + isLoading: false, + }), + useUpdateTask: () => ({ + mutate: mutateUpdateTask, + }), + useDeleteTask: () => ({ + mutate: mutateDeleteTask, + }), +})); + +vi.mock("@xtablo/tablo-views", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + GanttChart: () =>
, + TaskModal: () => null, + }; +}); + +describe("TasksPage", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("deletes a task from the inline kanban action", async () => { + const user = userEvent.setup(); + + renderWithProviders(, { + route: "/tasks?view=kanban", + path: "/tasks", + }); + + await user.click(screen.getByRole("button", { name: "Supprimer la tâche Task A" })); + + expect(mutateDeleteTask).toHaveBeenCalledWith("task-1"); + }); + + it("deletes a task from the inline list action", async () => { + const user = userEvent.setup(); + + renderWithProviders(, { + route: "/tasks?view=aggregated", + path: "/tasks", + }); + + await user.click(screen.getByRole("button", { name: "Supprimer la tâche Task A" })); + + expect(mutateDeleteTask).toHaveBeenCalledWith("task-1"); + }); +}); diff --git a/apps/main/src/pages/tasks.tsx b/apps/main/src/pages/tasks.tsx index 40c6568..97ff27b 100644 --- a/apps/main/src/pages/tasks.tsx +++ b/apps/main/src/pages/tasks.tsx @@ -33,6 +33,7 @@ import { Sparkles, Star, Sun, + Trash2Icon, UserIcon, Waves, Zap, @@ -42,7 +43,7 @@ import { useTranslation } from "react-i18next"; import { useNavigate, useSearchParams } from "react-router-dom"; import { twMerge } from "tailwind-merge"; import { useTablosList } from "../hooks/tablos"; -import { useAllTasks, useUpdateTask } from "../hooks/tasks"; +import { useAllTasks, useDeleteTask, useUpdateTask } from "../hooks/tasks"; import { useUser } from "../providers/UserStoreProvider"; type TaskStatus = "all" | "todo" | "in_progress" | "in_review" | "done"; @@ -134,6 +135,7 @@ export function TasksPage() { // Mutation for updating task status const updateTaskMutation = useUpdateTask(); + const deleteTaskMutation = useDeleteTask(); const openTaskModal = (dueDate?: Date) => { setTaskModalInitialDueDate(dueDate ? new Date(dueDate) : undefined); @@ -556,6 +558,17 @@ export function TasksPage() { ))} +
{formattedDate && ( @@ -878,6 +891,17 @@ export function TasksPage() { ))} + ); diff --git a/packages/tablo-views/src/TabloTasksSection.tsx b/packages/tablo-views/src/TabloTasksSection.tsx index 350a38c..90eef07 100644 --- a/packages/tablo-views/src/TabloTasksSection.tsx +++ b/packages/tablo-views/src/TabloTasksSection.tsx @@ -262,6 +262,7 @@ export const TabloTasksSection = ({ etapes={etapes} etapeTitles={etapeTitleMap} onTaskClick={handleTaskClick} + onDeleteTask={onDeleteTask} onAddTask={handleAddTask} onAddTaskInline={handleCreateTask} onTaskMove={handleTaskMove} diff --git a/packages/tablo-views/src/components/kanban/KanbanBoard.tsx b/packages/tablo-views/src/components/kanban/KanbanBoard.tsx index 35293c7..0522fd2 100644 --- a/packages/tablo-views/src/components/kanban/KanbanBoard.tsx +++ b/packages/tablo-views/src/components/kanban/KanbanBoard.tsx @@ -14,6 +14,7 @@ interface KanbanBoardProps { etapes: Etape[]; etapeTitles: Record; onTaskClick: (task: KanbanTask) => void; + onDeleteTask?: (taskId: string) => void; onAddTask: (status: TaskStatus) => void; onAddTaskInline: (task: { title: string; @@ -30,6 +31,7 @@ export const KanbanBoard = ({ members, etapes, onTaskClick, + onDeleteTask, onAddTask, onAddTaskInline, onTaskMove, @@ -63,6 +65,7 @@ export const KanbanBoard = ({ members={members} etapes={etapes} onTaskClick={onTaskClick} + onDeleteTask={onDeleteTask} onAddTask={onAddTask} onAddTaskInline={onAddTaskInline} onDragStart={handleDragStart} diff --git a/packages/tablo-views/src/components/kanban/KanbanColumn.tsx b/packages/tablo-views/src/components/kanban/KanbanColumn.tsx index 516db0a..a913ae6 100644 --- a/packages/tablo-views/src/components/kanban/KanbanColumn.tsx +++ b/packages/tablo-views/src/components/kanban/KanbanColumn.tsx @@ -15,6 +15,7 @@ interface KanbanColumnProps { members: TabloMember[]; etapes: Etape[]; onTaskClick: (task: KanbanTask) => void; + onDeleteTask?: (taskId: string) => void; onAddTask: (status: KanbanColumnType["status"]) => void; onAddTaskInline: (task: { title: string; @@ -33,6 +34,7 @@ export const KanbanColumn = ({ members, etapes, onTaskClick, + onDeleteTask, onAddTask, onAddTaskInline, onDragStart, @@ -84,6 +86,7 @@ export const KanbanColumn = ({ task={task} etapeTitle={etape?.title} onClick={() => onTaskClick(task)} + onDelete={onDeleteTask ? () => onDeleteTask(task.id) : undefined} />
); diff --git a/packages/tablo-views/src/components/kanban/KanbanTaskCard.tsx b/packages/tablo-views/src/components/kanban/KanbanTaskCard.tsx index ba58c74..8ceaae9 100644 --- a/packages/tablo-views/src/components/kanban/KanbanTaskCard.tsx +++ b/packages/tablo-views/src/components/kanban/KanbanTaskCard.tsx @@ -1,11 +1,12 @@ import type { KanbanTask } from "@xtablo/shared-types"; import { TypographyH4, TypographyMuted } from "@xtablo/ui/components/typography"; -import { CalendarIcon, User } from "lucide-react"; +import { CalendarIcon, Trash2Icon, User } from "lucide-react"; interface KanbanTaskCardProps { task: KanbanTask; etapeTitle?: string; onClick: () => void; + onDelete?: () => void; } function formatDueDate(dateStr: string): string { @@ -23,7 +24,7 @@ function isOverdue(dateStr: string): boolean { return due < today; } -export const KanbanTaskCard = ({ task, etapeTitle, onClick }: KanbanTaskCardProps) => { +export const KanbanTaskCard = ({ task, etapeTitle, onClick, onDelete }: KanbanTaskCardProps) => { const overdue = task.due_date && task.status !== "done" && isOverdue(task.due_date); return ( @@ -31,9 +32,24 @@ export const KanbanTaskCard = ({ task, etapeTitle, onClick }: KanbanTaskCardProp onClick={onClick} className="bg-card border border-border rounded-lg p-3 hover:shadow-md transition-shadow cursor-pointer group" > - - {task.title} - +
+ + {task.title} + + {onDelete && ( + + )} +
{task.description && ( diff --git a/packages/tablo-views/src/components/kanban/TaskModal.tsx b/packages/tablo-views/src/components/kanban/TaskModal.tsx index b87066b..aebfe4f 100644 --- a/packages/tablo-views/src/components/kanban/TaskModal.tsx +++ b/packages/tablo-views/src/components/kanban/TaskModal.tsx @@ -58,7 +58,6 @@ export const TaskModal = ({ initialDueDate, onCreateTask, onUpdateTask, - onDeleteTask, }: TaskModalProps) => { const [title, setTitle] = useState(""); const [description, setDescription] = useState(""); @@ -140,12 +139,6 @@ export const TaskModal = ({ onClose(); }; - const handleDelete = () => { - if (!taskId || !task) return; - onDeleteTask?.(task.id); - onClose(); - }; - if (!isOpen) return null; return ( @@ -261,16 +254,6 @@ export const TaskModal = ({ {/* Actions */}
- {taskId && task && ( - - )} From e3673b7040d6e3b030e9e8c1579a44e1f6f575be Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Thu, 16 Apr 2026 13:34:26 +0200 Subject: [PATCH 33/75] Fix tablo overview --- .../main/src/pages/tablo-details.layout.test.tsx | 16 ++++++++++++++++ .../src/single-tablo/SingleTabloOverview.tsx | 15 +++++++++------ 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/apps/main/src/pages/tablo-details.layout.test.tsx b/apps/main/src/pages/tablo-details.layout.test.tsx index 1e36a04..7314c00 100644 --- a/apps/main/src/pages/tablo-details.layout.test.tsx +++ b/apps/main/src/pages/tablo-details.layout.test.tsx @@ -309,6 +309,22 @@ describe("TabloDetailsPage overview layout", () => { ); }); + it("uses a dominant overview first column and purple primary actions", () => { + renderWithProviders(, { + route: "/tablos/tablo-1", + path: "/tablos/:tabloId", + }); + + expect(screen.getByTestId("single-tablo-overview-grid")).toHaveClass( + "lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]" + ); + expect(screen.getByRole("button", { name: "Modifier la mise en page" })).toHaveClass( + "bg-primary" + ); + expect(screen.getByRole("button", { name: "Ajouter" })).toHaveClass("bg-primary"); + expect(screen.getByRole("button", { name: "Ouvrir" })).toHaveClass("bg-primary"); + }); + it("shows layout edit toggle for admin users", () => { renderWithProviders(, { route: "/tablos/tablo-1", diff --git a/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx b/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx index 012828d..c652b23 100644 --- a/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx +++ b/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx @@ -126,7 +126,7 @@ export function SingleTabloOverview({ title: "Mes tâches", actions: (
- ), @@ -241,11 +241,11 @@ export function SingleTabloOverview({
{canEditLayout && (
- {isLayoutEditMode && ( - @@ -253,8 +253,11 @@ export function SingleTabloOverview({
)} -
-
{renderZone("left", layout.leftZone)}
+
+
{renderZone("left", layout.leftZone)}
{renderZone("right", layout.rightZone)}
From 916dba496a88f396bd663a10cc0e113626a6109f Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Thu, 16 Apr 2026 13:43:30 +0200 Subject: [PATCH 34/75] fix: restore tablo overview layout and colors --- .../src/pages/tablo-details.layout.test.tsx | 14 ++++++--- .../src/single-tablo/SingleTabloOverview.tsx | 30 ++++++++++++++++--- .../src/single-tablo/SingleTabloView.tsx | 22 ++++++++++---- 3 files changed, 53 insertions(+), 13 deletions(-) diff --git a/apps/main/src/pages/tablo-details.layout.test.tsx b/apps/main/src/pages/tablo-details.layout.test.tsx index 7314c00..43c80a9 100644 --- a/apps/main/src/pages/tablo-details.layout.test.tsx +++ b/apps/main/src/pages/tablo-details.layout.test.tsx @@ -318,11 +318,17 @@ describe("TabloDetailsPage overview layout", () => { expect(screen.getByTestId("single-tablo-overview-grid")).toHaveClass( "lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]" ); - expect(screen.getByRole("button", { name: "Modifier la mise en page" })).toHaveClass( - "bg-primary" + expect(screen.getByRole("link", { name: "Discussion" })).toHaveClass("bg-[#804EEC]"); + expect(screen.getByRole("button", { name: "Inviter" })).toHaveClass( + "border-[#804EEC]", + "text-[#804EEC]" ); - expect(screen.getByRole("button", { name: "Ajouter" })).toHaveClass("bg-primary"); - expect(screen.getByRole("button", { name: "Ouvrir" })).toHaveClass("bg-primary"); + expect(screen.getByRole("button", { name: "Modifier la mise en page" })).toHaveClass( + "border-[#804EEC]", + "text-[#804EEC]" + ); + expect(screen.getByRole("button", { name: "Ajouter" })).toHaveClass("bg-[#804EEC]"); + expect(screen.getByRole("button", { name: "Ouvrir" })).toHaveClass("text-[#804EEC]"); }); it("shows layout edit toggle for admin users", () => { diff --git a/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx b/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx index c652b23..a5646a9 100644 --- a/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx +++ b/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx @@ -126,10 +126,21 @@ export function SingleTabloOverview({ title: "Mes tâches", actions: (
- -
@@ -170,7 +181,13 @@ export function SingleTabloOverview({ return { title: "Fichiers", actions: ( - ), @@ -241,7 +258,12 @@ export function SingleTabloOverview({
{canEditLayout && (
- {isLayoutEditMode && ( diff --git a/packages/tablo-views/src/single-tablo/SingleTabloView.tsx b/packages/tablo-views/src/single-tablo/SingleTabloView.tsx index 4e3b44e..e95bc48 100644 --- a/packages/tablo-views/src/single-tablo/SingleTabloView.tsx +++ b/packages/tablo-views/src/single-tablo/SingleTabloView.tsx @@ -125,22 +125,34 @@ export function SingleTabloView({ const discussionButton = discussionAction?.kind === "link" ? ( - ) : discussionAction?.kind === "button" ? ( - ) : null; const inviteButton = canInviteMembers && onOpenInviteDialog ? ( - ) : null; From 740bedaf50a69f27e6ee0372c7524acaa24104d9 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Thu, 16 Apr 2026 22:21:16 +0200 Subject: [PATCH 35/75] Improve task management --- .../src/pages/tablo-details.layout.test.tsx | 72 ++++++++++++++++++- apps/main/src/pages/tablo-details.tsx | 12 +++- .../tablo-views/src/TabloTasksSection.tsx | 4 +- .../src/components/kanban/TaskModal.tsx | 38 ++++++++-- 4 files changed, 112 insertions(+), 14 deletions(-) diff --git a/apps/main/src/pages/tablo-details.layout.test.tsx b/apps/main/src/pages/tablo-details.layout.test.tsx index 43c80a9..e30a059 100644 --- a/apps/main/src/pages/tablo-details.layout.test.tsx +++ b/apps/main/src/pages/tablo-details.layout.test.tsx @@ -1,11 +1,24 @@ -import { screen } from "@testing-library/react"; +import { screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { describe, expect, it, vi } from "vitest"; import { renderWithProviders } from "../utils/testHelpers"; import { TabloDetailsPage } from "./tablo-details"; +if (!HTMLElement.prototype.hasPointerCapture) { + HTMLElement.prototype.hasPointerCapture = () => false; +} + +if (!HTMLElement.prototype.setPointerCapture) { + HTMLElement.prototype.setPointerCapture = () => undefined; +} + +if (!HTMLElement.prototype.releasePointerCapture) { + HTMLElement.prototype.releasePointerCapture = () => undefined; +} + const mutateUpdateTablo = vi.fn(); const mutateUpdateTask = vi.fn(); +const mutateCreateTask = vi.fn(); const mutateCreateEtape = vi.fn(); const mutateUpdateEtape = vi.fn(); const mutateDeleteEtape = vi.fn(); @@ -47,7 +60,15 @@ vi.mock("../hooks/tablos", () => ({ isLoading: false, }), useTabloMembers: () => ({ - data: [], + data: [ + { + id: "user-1", + name: "Test User", + email: "john@example.com", + avatar_url: null, + is_admin: true, + }, + ], }), useTabloOverviewLayout: () => ({ data: layoutData, @@ -105,6 +126,7 @@ vi.mock("../hooks/tasks", () => ({ assignee_id: "user-1", title: "Task A", status: "todo", + parent_task_id: "etape-1", }, ], }), @@ -148,7 +170,7 @@ vi.mock("../hooks/tasks", () => ({ isPending: false, }), useCreateTask: () => ({ - mutate: vi.fn(), + mutate: mutateCreateTask, }), useUpdateTaskPositions: () => ({ mutate: vi.fn(), @@ -295,6 +317,50 @@ describe("TabloDetailsPage overview layout", () => { expect(mutateDeleteTask).toHaveBeenCalledWith("task-1"); }); + it("restores the task etape when reopening the same edit modal", async () => { + const user = userEvent.setup(); + + renderWithProviders(, { + route: "/tablos/tablo-1?section=tasks", + path: "/tablos/:tabloId", + }); + + await user.click(screen.getByText("Task A")); + await user.click(screen.getByRole("combobox", { name: "Étape" })); + await user.click(screen.getByRole("option", { name: "Aucune" })); + await user.click(screen.getByRole("button", { name: "Annuler" })); + + await user.click(screen.getByText("Task A")); + + expect(screen.getByRole("combobox", { name: "Étape" })).toHaveTextContent("Kickoff"); + }); + + it("assigns the current user when creating from mes tâches in overview", async () => { + const user = userEvent.setup(); + + renderWithProviders(, { + route: "/tablos/tablo-1", + path: "/tablos/:tabloId", + }); + + await user.click(screen.getByRole("button", { name: "Ajouter" })); + + await waitFor(() => { + expect(screen.getByRole("combobox", { name: "Assigné à" })).toHaveTextContent("Test User"); + }); + + await user.type(screen.getByLabelText("Titre *"), "Nouvelle tâche"); + await user.click(screen.getByRole("button", { name: "Créer" })); + + expect(mutateCreateTask).toHaveBeenCalledWith( + expect.objectContaining({ + tablo_id: "tablo-1", + title: "Nouvelle tâche", + assignee_id: "user-1", + }) + ); + }); + it("renders overview cards in persisted left-zone order", () => { renderWithProviders(, { route: "/tablos/tablo-1", diff --git a/apps/main/src/pages/tablo-details.tsx b/apps/main/src/pages/tablo-details.tsx index 824a74e..4816bb3 100644 --- a/apps/main/src/pages/tablo-details.tsx +++ b/apps/main/src/pages/tablo-details.tsx @@ -103,6 +103,9 @@ export const TabloDetailsPage = () => { const [taskModalInitialDueDate, setTaskModalInitialDueDate] = useState( undefined ); + const [taskModalDefaultAssigneeId, setTaskModalDefaultAssigneeId] = useState( + undefined + ); const [showAllOverviewTasks, setShowAllOverviewTasks] = useState(false); const [isShareDialogOpen, setIsShareDialogOpen] = useState(false); const [inviteEmail, setInviteEmail] = useState(""); @@ -169,14 +172,16 @@ export const TabloDetailsPage = () => { setInviteEmail(""); }; - const openTaskModal = (dueDate?: Date) => { + const openTaskModal = (dueDate?: Date, defaultAssigneeId?: string) => { setTaskModalInitialDueDate(dueDate ? new Date(dueDate) : undefined); + setTaskModalDefaultAssigneeId(defaultAssigneeId); setIsTaskModalOpen(true); }; const closeTaskModal = () => { setIsTaskModalOpen(false); setTaskModalInitialDueDate(undefined); + setTaskModalDefaultAssigneeId(undefined); }; const sectionParam = searchParams.get("section") as TabSection | null; @@ -357,7 +362,7 @@ export const TabloDetailsPage = () => { showFileMenu={true} onOpenTasks={() => setSearchParams({ section: "tasks" })} onOpenFiles={() => setSearchParams({ section: "files" })} - onCreateTask={() => openTaskModal()} + onCreateTask={() => openTaskModal(undefined, currentUser.id)} onToggleTaskDone={(taskId) => updateTask({ id: taskId, status: "done" })} showAllTasks={showAllOverviewTasks} onToggleShowAllTasks={() => setShowAllOverviewTasks((prev) => !prev)} @@ -500,8 +505,11 @@ export const TabloDetailsPage = () => { tabloId={tabloId} isOpen={isTaskModalOpen} onClose={closeTaskModal} + members={members} + etapes={etapes} initialStatus="todo" initialDueDate={taskModalInitialDueDate} + defaultAssigneeId={taskModalDefaultAssigneeId} onCreateTask={(task) => createTask(task)} onUpdateTask={(task) => updateTask(task)} onDeleteTask={(taskId) => deleteTask(taskId)} diff --git a/packages/tablo-views/src/TabloTasksSection.tsx b/packages/tablo-views/src/TabloTasksSection.tsx index 90eef07..1839fe9 100644 --- a/packages/tablo-views/src/TabloTasksSection.tsx +++ b/packages/tablo-views/src/TabloTasksSection.tsx @@ -245,9 +245,7 @@ export const TabloTasksSection = ({ {orphanedTasks.length} {pluralize("tâche", orphanedTasks.length)} sans Étape

- {orphanedTasks.length === 1 - ? "Cette tâche n'est associée à aucune Étape. Modifiez-la pour l'associer à une Étape." - : "Ces tâches ne sont associées à aucune Étape. Modifiez-les pour les associer à une Étape."} + Associez {orphanedTasks.length > 1 ? "ces" : "cette"} {pluralize("tâche", orphanedTasks.length)} à une étape.

diff --git a/packages/tablo-views/src/components/kanban/TaskModal.tsx b/packages/tablo-views/src/components/kanban/TaskModal.tsx index aebfe4f..df1dd2b 100644 --- a/packages/tablo-views/src/components/kanban/TaskModal.tsx +++ b/packages/tablo-views/src/components/kanban/TaskModal.tsx @@ -36,6 +36,7 @@ interface TaskModalProps { tablos?: MinimalTablo[]; allowTabloSelection?: boolean; initialDueDate?: Date; + defaultAssigneeId?: string; /** Called when creating a new task. */ onCreateTask?: (task: KanbanTaskInsert) => void; /** Called when updating an existing task. */ @@ -56,6 +57,7 @@ export const TaskModal = ({ tablos, allowTabloSelection = false, initialDueDate, + defaultAssigneeId, onCreateTask, onUpdateTask, }: TaskModalProps) => { @@ -69,8 +71,20 @@ export const TaskModal = ({ ); const currentTabloId = allowTabloSelection ? selectedTabloId : initialTabloId || ""; + const selectedAssigneeLabel = + assigneeId === "unassigned" + ? "Non assigné" + : providedMembers.find((member) => member.id === assigneeId)?.name ?? "Non assigné"; + const selectedEtapeLabel = + etapeId === "none" + ? "Aucune Étape" + : providedEtapes.find((etape) => etape.id === etapeId)?.title ?? "Aucune Étape"; useEffect(() => { + if (!isOpen) { + return; + } + if (task) { setTitle(task.title ?? ""); setDescription(task.description ?? ""); @@ -83,14 +97,14 @@ export const TaskModal = ({ } else { setTitle(""); setDescription(""); - setAssigneeId("unassigned"); + setAssigneeId(defaultAssigneeId ?? "unassigned"); setEtapeId("none"); setDueDate(initialDueDate ? new Date(initialDueDate) : undefined); if (allowTabloSelection && tablos && tablos.length > 0) { setSelectedTabloId(tablos[0].id); } } - }, [task, initialTabloId, allowTabloSelection, tablos, initialDueDate]); + }, [isOpen, task, initialTabloId, allowTabloSelection, tablos, initialDueDate, defaultAssigneeId]); // Format Date to YYYY-MM-DD string for database storage const formatDateForDb = (date: Date | undefined): string | null => { @@ -217,9 +231,15 @@ export const TaskModal = ({ {/* Assignee */}
- { + if (!value) return; + setAssigneeId(value); + }} + > - + {selectedAssigneeLabel} Non assigné @@ -236,9 +256,15 @@ export const TaskModal = ({ {providedEtapes.length > 0 && (
- { + if (!value) return; + setEtapeId(value); + }} + > - + {selectedEtapeLabel} Aucune From c2ad27c8c7d3c4eb0b39bc7351d9431256df5e36 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sat, 18 Apr 2026 09:03:53 +0200 Subject: [PATCH 36/75] docs: add client password invite flow spec --- ...4-18-client-password-invite-flow-design.md | 318 ++++++++++++++++++ 1 file changed, 318 insertions(+) create mode 100644 docs/superpowers/specs/2026-04-18-client-password-invite-flow-design.md diff --git a/docs/superpowers/specs/2026-04-18-client-password-invite-flow-design.md b/docs/superpowers/specs/2026-04-18-client-password-invite-flow-design.md new file mode 100644 index 0000000..5ab20f9 --- /dev/null +++ b/docs/superpowers/specs/2026-04-18-client-password-invite-flow-design.md @@ -0,0 +1,318 @@ +# Client Password Invite Flow + +**Date**: 2026-04-18 +**Status**: Draft +**Supersedes**: `docs/superpowers/specs/2026-04-15-client-magic-links-design.md` + +## Overview + +The current client invite flow is built around a magic-link callback path. That model is no longer the target. + +`apps/clients` should become a normal password-based portal for invited client users. Invitations should bootstrap account access, not serve as the long-term authentication mechanism. + +The revised flow is: + +- a client is invited by email from `app.xtablo.com` +- if this email has not completed onboarding yet, the email contains a one-time password setup link +- the client sets a password once +- that setup link becomes invalid immediately after successful use +- all later access goes through a normal login form in `apps/clients` +- clients can reset their password themselves from the client login page + +Client accounts are reused across multiple tablos by email. If a client who already has a password-based account is invited to another tablo, they should receive an access notification email instead of another password-setup link. + +## Problem Statement + +The current magic-link callback flow creates the wrong steady-state model for the client portal. + +### Current issues + +1. The invite email behaves as an authentication mechanism instead of a one-time onboarding step. +2. `apps/clients` does not provide a standard login form for later access. +3. The current callback-style flow is a poor fit for a client portal meant to feel like a stable authenticated product. +4. Reinviting the same email is awkward because the current model is centered around link acceptance rather than an account reused across multiple tablos. +5. The current flow does not express a strong boundary between `apps/main` users and `apps/clients` users. + +## Goals + +- Replace callback-style magic-link onboarding with one-time password setup +- Make `apps/clients` a normal email/password application after onboarding +- Reuse one client account per email across multiple tablos +- Allow self-service password reset from the client login page +- Support direct notification links to `clients.xtablo.com/tablo/:tabloId` +- Keep clients restricted to `apps/clients` only +- Reuse the main login page visual design through a shared auth UI surface + +## Non-Goals + +- Permanent bearer links that grant direct tablo access without authentication +- Self-service client signup without invitation +- Creating a separate custom auth system outside Supabase +- Granting client-portal users access to `apps/main` +- Preserving the current callback-based onboarding as the primary flow + +## Hard Requirements + +- Client users must not have access to `apps/main` +- The password-setup link must be one-time use +- The setup link must become invalid immediately after successful password creation +- The same email must map to one reusable client account across multiple tablos +- Existing onboarded clients invited to another tablo must receive an access notification email, not a new setup link +- The notification email must link directly to `clients.xtablo.com/tablo/:tabloId` + +## Chosen Approach + +Keep Supabase as the underlying authentication provider, but move invitation control into an invite lifecycle owned by the backend. + +The backend creates or reuses a client auth user by email, grants access to the target tablo, and then chooses between two email modes: + +- onboarding email with a one-time setup token +- access notification email for an already-onboarded client + +`apps/clients` becomes a normal authenticated app with: + +- a login page +- a one-time set-password page +- a forgot-password flow +- protected routes that redirect unauthenticated users to login and then resume their intended destination + +## User Classes And App Boundary + +The system should treat main-app users and client-portal users as distinct user classes. + +### Main-app users + +- collaborators +- internal users +- users who are allowed to access `app.xtablo.com` + +### Client-portal users + +- external client users invited to tablos +- users who are allowed to access `clients.xtablo.com` +- users who must not be able to use `apps/main` + +### Boundary rule + +Sharing auth UI does not mean sharing authorization. + +Client accounts must be rejected by `apps/main` even if they hold a valid authenticated session. This boundary must be enforced in backend authorization as well as frontend routing. + +## Auth Model + +`apps/clients` becomes a normal password-based portal. + +### Steady state + +- one client account per email +- reused across multiple tablos +- normal email/password login after onboarding +- standard self-service password reset via "mot de passe oublié" + +### Invite role + +The invite email is no longer the long-term access credential. It is only the bootstrap mechanism for first-time password setup. + +## Invite Lifecycle + +Invite creation should branch based on whether the email already belongs to an onboarded client account. + +### First invite for an email without a password-based client account + +- create or reuse the client auth user for that email +- create or confirm the tablo access grant +- create a one-time setup token +- send a setup email to `clients.xtablo.com` + +### Later invite for an existing onboarded client account + +- create or confirm the tablo access grant +- do not create a setup token +- send a "you now have access" notification email + +This keeps onboarding single-use while allowing account reuse across many tablos. + +## End-To-End Flows + +### First-time onboarding flow + +1. Admin invites a client from `app.xtablo.com`. +2. Backend creates or reuses the client auth user. +3. Backend grants access to the target tablo. +4. Backend creates a one-time setup token. +5. Email sends a setup URL into `clients.xtablo.com`. +6. Client opens the link and validates the token. +7. Client sets a password. +8. Backend invalidates the token immediately. +9. Client is signed in and redirected into the client portal. + +### Additional tablo access for an already-onboarded client + +1. Admin invites the same email to another tablo. +2. Backend reuses the same client account. +3. Backend grants access to the target tablo. +4. Email sends a notification link to `clients.xtablo.com/tablo/:tabloId`. +5. If the client already has a session, the tablo opens directly. +6. If not authenticated, `apps/clients` redirects to login and returns to that tablo after successful login. + +## Frontend Design + +`apps/clients` should expose three auth surfaces: + +- `LoginPage` +- `SetPasswordPage` +- existing authenticated portal routes + +### LoginPage + +Requirements: + +- minimal standalone auth screen +- visually matches the main login page +- built from a shared auth UI package instead of importing directly from `apps/main` +- email and password fields +- forgot-password entry point +- no self-service signup + +### SetPasswordPage + +Requirements: + +- dedicated route for one-time invite setup +- validates token before allowing password creation +- handles invalid, expired, and already-used tokens clearly +- on success, invalidates token and transitions into an authenticated client session + +### Protected route behavior + +- unauthenticated access to `clients.xtablo.com/tablo/:tabloId` redirects to login +- login preserves and resumes the intended destination +- fallback destination remains the client tablo list if no target route was captured + +## Shared Auth UI + +The login page in `apps/clients` should look like the main login page, but this should be done through extraction, not duplication. + +Recommended ownership split: + +- shared package owns auth shell, layout, form framing, banners, and visual treatment +- `apps/main` and `apps/clients` own submit handlers, route targets, and app-specific copy + +This keeps visual parity durable without coupling `apps/clients` directly to `apps/main` internals. + +## Backend Design + +`client_invites` should remain the lifecycle/control record, but its meaning changes. + +### Previous role + +- pending invite accepted through callback-style magic-link flow + +### New role + +- one-time password-setup authorization record for first-time onboarding + +### Backend responsibilities + +`POST /client-invites/:tabloId` + +- create or reuse client auth user by email +- create or confirm tablo access +- decide whether this email needs onboarding or only an access notification +- send the correct email type + +Token validation endpoint: + +- used by `SetPasswordPage` +- verifies token exists, is pending, and is still valid + +Password setup completion endpoint: + +- verifies token again +- sets password for the underlying auth user +- invalidates token immediately +- completes the onboarding transition cleanly + +Admin visibility and cancellation endpoints: + +- remain available for operational control +- cancelling a pending setup invite invalidates that setup path immediately + +## Authorization Model + +Authorization must reflect the split between apps. + +### Required behavior + +- client-portal users can access `apps/clients` resources they were granted +- client-portal users cannot use `apps/main` flows +- main-app authorization cannot assume that every authenticated user is a main-app user + +This must be enforced on the backend, not only in the frontend shell. + +## Error Handling + +### Frontend + +`SetPasswordPage` must handle: + +- invalid token +- expired token +- already-used token +- password policy failure + +`LoginPage` must handle: + +- wrong credentials +- reset email sent state +- reset failure + +Protected routes must: + +- redirect unauthenticated users to login +- preserve intended destination +- resume navigation after login + +### Backend + +Invite creation must distinguish: + +- first-time onboarding invite +- additional-access notification + +Token completion must fail cleanly on: + +- expired token +- reused token +- cancelled token + +## Testing Strategy + +### API tests + +- first invite for a new client creates a setup token and sends setup email +- second invite for an already-onboarded client skips setup token creation and sends access notification +- setup token can be used exactly once +- expired or reused setup token is rejected +- client-only accounts are rejected by main-app authorization paths + +### Frontend tests + +- login page renders through shared auth UI and submits email/password flow +- forgot-password flow is reachable from the client login page +- set-password page handles success, invalid token, expired token, and reused token states +- protected `tablo/:tabloId` route redirects to login and resumes correctly after authentication +- access notification deep-link opens the intended tablo after login + +### Manual verification + +- first invite email for a new client leads to one-time setup, then normal login +- second invite for the same client leads to access notification only +- `clients.xtablo.com/tablo/:tabloId` works both with and without an existing session +- client user cannot enter `app.xtablo.com` + +## Migration Notes + +- the current `apps/clients/src/pages/AuthCallback.tsx` route should be removed or reduced to legacy compatibility once this flow is live +- existing frontend code that assumes invitation equals magic-link acceptance should be replaced with setup-token and login flows +- because the feature is not yet live, no legacy client-user migration path is required From f02c36dbb70d7ff2cc2dc09243c2ce44f944d08f Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sat, 18 Apr 2026 11:09:04 +0200 Subject: [PATCH 37/75] feat: add client password invite flow --- .../__tests__/routes/clientInvites.test.ts | 204 ++++-- apps/api/src/helpers/helpers.ts | 206 ++++-- apps/api/src/routers/clientInvites.ts | 336 +++++++--- apps/api/src/routers/maybeAuthRouter.ts | 2 + apps/clients/package.json | 1 + .../clients/src/components/ClientAuthGate.tsx | 56 ++ .../src/components/ClientLayout.test.tsx | 12 + apps/clients/src/components/ClientLayout.tsx | 14 +- apps/clients/src/i18n.test.ts | 4 + apps/clients/src/i18n.ts | 4 + apps/clients/src/pages/AuthCallback.tsx | 65 +- apps/clients/src/pages/LoginPage.test.tsx | 62 ++ apps/clients/src/pages/LoginPage.tsx | 102 +++ .../src/pages/ResetPasswordPage.test.tsx | 42 ++ apps/clients/src/pages/ResetPasswordPage.tsx | 71 ++ .../src/pages/SetPasswordPage.test.tsx | 91 +++ apps/clients/src/pages/SetPasswordPage.tsx | 205 ++++++ apps/clients/src/routes.tsx | 15 +- apps/clients/src/test/testHelpers.tsx | 10 +- apps/clients/tsconfig.json | 2 + apps/clients/tsconfig.tsbuildinfo | 2 +- apps/main/package.json | 1 + .../src/components/ProtectedRoute.test.tsx | 1 + .../src/components/SubscriptionCard.test.tsx | 1 + .../main/src/components/UpgradePanel.test.tsx | 1 + .../src/contexts/UpgradeBlockContext.test.tsx | 1 + apps/main/src/hooks/client_invites.ts | 23 +- apps/main/src/pages/login.test.tsx | 1 + apps/main/src/pages/login.tsx | 273 +++----- apps/main/src/pages/reset-password.test.tsx | 1 + apps/main/src/pages/reset-password.tsx | 162 ++--- .../src/pages/tablo-details.layout.test.tsx | 11 +- apps/main/src/pages/tablo-details.tsx | 10 +- .../src/providers/UserStoreProvider.test.tsx | 1 + apps/main/src/utils/testHelpers.tsx | 1 + apps/main/tsconfig.app.json | 2 + .../2026-04-18-client-password-invite-flow.md | 626 ++++++++++++++++++ packages/auth-ui/package.json | 32 + packages/auth-ui/src/AuthCardShell.tsx | 125 ++++ .../auth-ui/src/AuthEmailPasswordForm.tsx | 83 +++ packages/auth-ui/src/AuthInfoBanner.tsx | 33 + packages/auth-ui/src/index.ts | 3 + packages/auth-ui/tsconfig.json | 27 + packages/shared-types/src/database.types.ts | 15 + pnpm-lock.yaml | 43 ++ ...20260418110000_client_password_invites.sql | 27 + 46 files changed, 2419 insertions(+), 591 deletions(-) create mode 100644 apps/clients/src/components/ClientAuthGate.tsx create mode 100644 apps/clients/src/pages/LoginPage.test.tsx create mode 100644 apps/clients/src/pages/LoginPage.tsx create mode 100644 apps/clients/src/pages/ResetPasswordPage.test.tsx create mode 100644 apps/clients/src/pages/ResetPasswordPage.tsx create mode 100644 apps/clients/src/pages/SetPasswordPage.test.tsx create mode 100644 apps/clients/src/pages/SetPasswordPage.tsx create mode 100644 docs/superpowers/plans/2026-04-18-client-password-invite-flow.md create mode 100644 packages/auth-ui/package.json create mode 100644 packages/auth-ui/src/AuthCardShell.tsx create mode 100644 packages/auth-ui/src/AuthEmailPasswordForm.tsx create mode 100644 packages/auth-ui/src/AuthInfoBanner.tsx create mode 100644 packages/auth-ui/src/index.ts create mode 100644 packages/auth-ui/tsconfig.json create mode 100644 supabase/migrations/20260418110000_client_password_invites.sql diff --git a/apps/api/src/__tests__/routes/clientInvites.test.ts b/apps/api/src/__tests__/routes/clientInvites.test.ts index 17bfc08..5ffcefb 100644 --- a/apps/api/src/__tests__/routes/clientInvites.test.ts +++ b/apps/api/src/__tests__/routes/clientInvites.test.ts @@ -62,19 +62,23 @@ describe("Client Invites Endpoints", () => { { headers: { Authorization: `Bearer ${user.accessToken}` } } ); - const acceptInvite = (user: TestUserData, token: string) => - client["client-invites"].accept[":token"].$post( - { param: { token } }, - { headers: { Authorization: `Bearer ${user.accessToken}` } } - ); + const getSetupInvite = (token: string) => + client["client-invites"].setup[":token"].$get({ + param: { token }, + }); - // ─── Helper: insert a client_invite row directly via admin ────────────────── + const completeSetupInvite = (token: string, password: string) => + client["client-invites"].setup[":token"].$post({ + param: { token }, + json: { password }, + }); const insertClientInvite = async (opts: { tabloId: string; invitedEmail: string; invitedBy: string; token: string; + inviteType?: string; isPending?: boolean; expiresAt?: string; }) => { @@ -87,6 +91,7 @@ describe("Client Invites Endpoints", () => { invited_email: opts.invitedEmail, invited_by: opts.invitedBy, invite_token: opts.token, + invite_type: opts.inviteType ?? "setup", is_pending: opts.isPending ?? true, expires_at: expiresAt, }) @@ -97,11 +102,9 @@ describe("Client Invites Endpoints", () => { return data.id as number; }; - // ─── Cleanup helper ────────────────────────────────────────────────────────── - const cleanupInvitesByEmail = async (email: string) => { await supabaseAdmin.from("client_invites").delete().eq("invited_email", email); - // Also clean up any client user that may have been created + const { data: usersData } = await supabaseAdmin.auth.admin.listUsers(); // biome-ignore lint/suspicious/noExplicitAny: admin.listUsers returns typed data at runtime const users = usersData as any; @@ -113,50 +116,118 @@ describe("Client Invites Endpoints", () => { } }; + const createClientAccount = async ( + email: string, + input?: { onboarded?: boolean; password?: string } + ) => { + const password = input?.password ?? "client_password_123"; + const { data: authData, error: authError } = await supabaseAdmin.auth.admin.createUser({ + email, + password, + email_confirm: true, + user_metadata: { role: "client" }, + }); + + if (authError || !authData?.user) { + throw new Error(`Failed to create client account: ${authError?.message}`); + } + + const updates: Record = { is_client: true }; + if (input?.onboarded) { + updates.client_onboarded_at = new Date().toISOString(); + } + + const { error: profileError } = await supabaseAdmin + .from("profiles") + .update(updates) + .eq("id", authData.user.id); + + if (profileError) { + throw new Error(`Failed to update client profile: ${profileError.message}`); + } + + return authData.user; + }; + // ════════════════════════════════════════════════════════════════════════════ // POST /:tabloId — Create client invite // ════════════════════════════════════════════════════════════════════════════ describe("POST /client-invites/:tabloId", () => { const testEmail = "test_client_invite_new@example.com"; + const existingClientEmail = "test_existing_client_invite@example.com"; beforeEach(async () => { await cleanupInvitesByEmail(testEmail); + await cleanupInvitesByEmail(existingClientEmail); }); - it("should create a client invite for a valid email (admin)", async () => { + it("creates a setup token for a first-time client invite", async () => { const res = await postInvite(ownerUser, adminTabloId, testEmail); expect(res.status).toBe(200); const data = await res.json(); expect(data.success).toBe(true); + expect(data.inviteMode).toBe("setup"); - // Verify row was inserted const { data: invite } = await supabaseAdmin .from("client_invites") - .select("id, invited_email, is_pending") + .select("id, invited_email, is_pending, invite_token, invite_type") .eq("tablo_id", adminTabloId) .eq("invited_email", testEmail) .single(); expect(invite).toBeDefined(); expect(invite?.is_pending).toBe(true); + expect(invite?.invite_token).toBeTruthy(); + expect(invite?.invite_type).toBe("setup"); + expect(mockSendMail).toHaveBeenCalledTimes(1); + expect(mockSendMail.mock.calls[0]?.[0]?.html).toContain("/set-password?token="); }); - it("should reject temporary users before admin check", async () => { - // tempUser is NOT admin of adminTabloId (owner user owns it) + it("sends an access notification for an already-onboarded client", async () => { + await createClientAccount(existingClientEmail, { onboarded: true }); + + const res = await postInvite(ownerUser, adminTabloId, existingClientEmail); + + expect(res.status).toBe(200); + const data = await res.json(); + expect(data.success).toBe(true); + expect(data.inviteMode).toBe("notification"); + + const { data: invite } = await supabaseAdmin + .from("client_invites") + .select("id") + .eq("tablo_id", adminTabloId) + .eq("invited_email", existingClientEmail) + .maybeSingle(); + + expect(invite).toBeNull(); + expect(mockSendMail).toHaveBeenCalledTimes(1); + expect(mockSendMail.mock.calls[0]?.[0]?.html).toContain(`/tablo/${adminTabloId}`); + }); + + it("rejects emails already used by a main-app account", async () => { + const res = await postInvite(ownerUser, adminTabloId, ownerUser.email); + + expect(res.status).toBe(409); + const data = await res.json(); + expect(data.error).toContain("already belongs"); + }); + + it("rejects temporary users before admin check", async () => { const res = await postInvite(tempUser, adminTabloId, testEmail); expect(res.status).toBe(401); }); - it("should return 400 for an invalid email", async () => { + it("returns 400 for an invalid email", async () => { const res = await postInvite(ownerUser, adminTabloId, "not-an-email"); expect(res.status).toBe(400); const data = await res.json(); expect(data.error).toContain("valid email"); }); - it("should return 400 for a missing email", async () => { + it("returns 400 for a missing email", async () => { const res = client["client-invites"][":tabloId"].$post( { param: { tabloId: adminTabloId }, json: {} }, { headers: { Authorization: `Bearer ${ownerUser.accessToken}` } } @@ -164,7 +235,7 @@ describe("Client Invites Endpoints", () => { expect((await res).status).toBe(400); }); - it("should return 401 for unauthenticated requests", async () => { + it("returns 401 for unauthenticated requests", async () => { const res = await client["client-invites"][":tabloId"].$post({ param: { tabloId: adminTabloId }, json: { email: testEmail }, @@ -174,54 +245,50 @@ describe("Client Invites Endpoints", () => { }); // ════════════════════════════════════════════════════════════════════════════ - // POST /accept/:token — Accept a client invite + // GET/POST /setup/:token — Validate and complete a client setup invite // ════════════════════════════════════════════════════════════════════════════ - describe("POST /client-invites/accept/:token", () => { - it("should accept an invite and return tabloId", async () => { - const token = `test_accept_valid_${Date.now()}`; + describe("GET/POST /client-invites/setup/:token", () => { + const setupEmail = "test_client_setup@example.com"; - // Insert invite for the owner user's email + beforeEach(async () => { + await cleanupInvitesByEmail(setupEmail); + }); + + it("returns invite metadata for a valid pending setup token", async () => { + const token = `test_setup_valid_${Date.now()}`; await insertClientInvite({ tabloId: adminTabloId, - invitedEmail: ownerUser.email, + invitedEmail: setupEmail, invitedBy: ownerUser.userId, token, }); try { - const res = await acceptInvite(ownerUser, token); + const res = await getSetupInvite(token); expect(res.status).toBe(200); const data = await res.json(); - expect(data.success).toBe(true); + expect(data.email).toBe(setupEmail); expect(data.tabloId).toBe(adminTabloId); - - // Verify invite is now not pending - const { data: invite } = await supabaseAdmin - .from("client_invites") - .select("is_pending") - .eq("invite_token", token) - .single(); - expect(invite?.is_pending).toBe(false); } finally { await supabaseAdmin.from("client_invites").delete().eq("invite_token", token); } }); - it("should return 410 for an expired invite", async () => { + it("returns 410 for an expired invite", async () => { const token = `test_expired_${Date.now()}`; - const pastDate = new Date(Date.now() - 1000).toISOString(); // already expired + const pastDate = new Date(Date.now() - 1000).toISOString(); await insertClientInvite({ tabloId: adminTabloId, - invitedEmail: ownerUser.email, + invitedEmail: setupEmail, invitedBy: ownerUser.userId, token, expiresAt: pastDate, }); try { - const res = await acceptInvite(ownerUser, token); + const res = await getSetupInvite(token); expect(res.status).toBe(410); const data = await res.json(); expect(data.error).toContain("expired"); @@ -230,35 +297,50 @@ describe("Client Invites Endpoints", () => { } }); - it("should return 403 when email does not match the authenticated user", async () => { - const token = `test_email_mismatch_${Date.now()}`; - - // Invite is for tempUser's email but we authenticate as ownerUser + it("completes password setup once and rejects reuse", async () => { + const token = `test_setup_complete_${Date.now()}`; + await createClientAccount(setupEmail); await insertClientInvite({ tabloId: adminTabloId, - invitedEmail: tempUser.email, + invitedEmail: setupEmail, invitedBy: ownerUser.userId, token, }); try { - const res = await acceptInvite(ownerUser, token); // wrong user - expect(res.status).toBe(403); + const res = await completeSetupInvite(token, "new_password_123"); + expect(res.status).toBe(200); + const data = await res.json(); + expect(data.success).toBe(true); + expect(data.email).toBe(setupEmail); + expect(data.tabloId).toBe(adminTabloId); + + const reused = await completeSetupInvite(token, "new_password_456"); + expect(reused.status).toBe(404); } finally { await supabaseAdmin.from("client_invites").delete().eq("invite_token", token); } }); - it("should return 404 for a non-existent token", async () => { - const res = await acceptInvite(ownerUser, "nonexistent_token_xyz"); + it("returns 404 for a non-existent token", async () => { + const res = await getSetupInvite("nonexistent_token_xyz"); expect(res.status).toBe(404); }); - it("should return 401 for unauthenticated requests", async () => { - const res = await client["client-invites"].accept[":token"].$post({ - param: { token: "some_token" }, + it("marks cancelled pending setup tokens unusable", async () => { + const token = `test_setup_cancelled_${Date.now()}`; + const inviteId = await insertClientInvite({ + tabloId: adminTabloId, + invitedEmail: setupEmail, + invitedBy: ownerUser.userId, + token, }); - expect(res.status).toBe(401); + + const cancelRes = await deleteInvite(ownerUser, adminTabloId, inviteId); + expect(cancelRes.status).toBe(200); + + const res = await getSetupInvite(token); + expect(res.status).toBe(404); }); }); @@ -280,7 +362,7 @@ describe("Client Invites Endpoints", () => { }); }); - it("should return pending invites for an admin", async () => { + it("returns pending invites for an admin", async () => { const res = await getPending(ownerUser, adminTabloId); expect(res.status).toBe(200); const data = await res.json(); @@ -292,12 +374,12 @@ describe("Client Invites Endpoints", () => { expect(found.is_pending).toBe(true); }); - it("should return 401 for a temporary user before admin check", async () => { + it("returns 401 for a temporary user before admin check", async () => { const res = await getPending(tempUser, adminTabloId); expect(res.status).toBe(401); }); - it("should return 401 for unauthenticated requests", async () => { + it("returns 401 for unauthenticated requests", async () => { const res = await client["client-invites"][":tabloId"].pending.$get({ param: { tabloId: adminTabloId }, }); @@ -316,8 +398,7 @@ describe("Client Invites Endpoints", () => { await cleanupInvitesByEmail(cancelEmail); }); - it("should cancel a pending invite and revoke client access", async () => { - // First create a client user and tablo_access entry via the API + it("cancels a pending invite and revokes client access", async () => { const token = `test_cancel_${Date.now()}`; const inviteId = await insertClientInvite({ tabloId: adminTabloId, @@ -326,14 +407,11 @@ describe("Client Invites Endpoints", () => { token, }); - // Create a mock profile to revoke (uses admin client to simulate client user existing) - // We'll skip verifying the user's actual auth account since we just need to test cancellation const res = await deleteInvite(ownerUser, adminTabloId, inviteId); expect(res.status).toBe(200); const data = await res.json(); expect(data.success).toBe(true); - // Verify invite is now not pending const { data: invite } = await supabaseAdmin .from("client_invites") .select("is_pending") @@ -342,7 +420,7 @@ describe("Client Invites Endpoints", () => { expect(invite?.is_pending).toBe(false); }); - it("should return 401 for a temporary user before admin check", async () => { + it("returns 401 for a temporary user before admin check", async () => { const token = `test_cancel_nonadmin_${Date.now()}`; const inviteId = await insertClientInvite({ tabloId: adminTabloId, @@ -355,19 +433,19 @@ describe("Client Invites Endpoints", () => { expect(res.status).toBe(401); }); - it("should return 404 for a non-existent invite", async () => { + it("returns 404 for a non-existent invite", async () => { const res = await deleteInvite(ownerUser, adminTabloId, 999999); expect(res.status).toBe(404); }); - it("should return 400 for an already-cancelled invite", async () => { + it("returns 400 for an already-cancelled invite", async () => { const token = `test_cancel_already_${Date.now()}`; const inviteId = await insertClientInvite({ tabloId: adminTabloId, invitedEmail: cancelEmail, invitedBy: ownerUser.userId, token, - isPending: false, // already cancelled + isPending: false, }); const res = await deleteInvite(ownerUser, adminTabloId, inviteId); @@ -376,7 +454,7 @@ describe("Client Invites Endpoints", () => { expect(data.error).toContain("pending"); }); - it("should return 401 for unauthenticated requests", async () => { + it("returns 401 for unauthenticated requests", async () => { const res = await client["client-invites"][":tabloId"][":inviteId"].$delete({ param: { tabloId: adminTabloId, inviteId: "1" }, }); diff --git a/apps/api/src/helpers/helpers.ts b/apps/api/src/helpers/helpers.ts index f559288..99a3acb 100644 --- a/apps/api/src/helpers/helpers.ts +++ b/apps/api/src/helpers/helpers.ts @@ -364,67 +364,193 @@ export const createInvitedUser = async ( return { success: true, userId: newUser.user.id }; }; -/** - * Creates or finds a client user, marks them as is_client, and grants tablo access. - */ -export async function createClientUser( - supabase: SupabaseClient, - recipientEmail: string, - tabloId: string, - grantedBy: string -): Promise<{ success: boolean; error?: string; userId?: string }> { - // Check if user already exists - const { data: existingUsersData } = await supabase.auth.admin.listUsers(); +type ClientAccount = { + email: string; + is_client: boolean; + client_onboarded_at: string | null; + userId: string; +}; + +type ClientAccountResult = + | { success: true; account: ClientAccount; wasCreated: boolean } + | { success: false; error: string }; + +const getAuthUserByEmail = async (supabase: SupabaseClient, email: string) => { + const { data: existingUsersData, error } = await supabase.auth.admin.listUsers(); + if (error) { + return { user: null, error: error.message }; + } + // biome-ignore lint/suspicious/noExplicitAny: admin.listUsers returns typed data at runtime const existingUsers = existingUsersData as any; const existingUser = existingUsers?.users?.find( // biome-ignore lint/suspicious/noExplicitAny: admin user type - (u: any) => u.email?.toLowerCase() === recipientEmail.toLowerCase() + (u: any) => u.email?.toLowerCase() === email.toLowerCase() ); - let userId: string; + return { user: existingUser ?? null, error: null }; +}; - if (existingUser) { - userId = existingUser.id; - // Mark as client if not already - await supabase - .from("profiles") - .update({ is_client: true }) - .eq("id", userId) - .eq("is_client", false); - } else { - // Create new auth user (no password — magic link only) - const { data: authData, error: authError } = await supabase.auth.admin.createUser({ - email: recipientEmail, - email_confirm: true, - user_metadata: { role: "client" }, - }); - if (authError || !authData?.user) { - return { success: false, error: authError?.message ?? "Failed to create user" }; - } - userId = authData.user.id; - await supabase.from("profiles").update({ is_client: true }).eq("id", userId); +export async function hasCompletedClientOnboarding( + supabase: SupabaseClient, + userId: string +): Promise<{ completed: boolean; error?: string }> { + const { data: profile, error } = await supabase + .from("profiles") + .select("client_onboarded_at") + .eq("id", userId) + .maybeSingle(); + + if (error) { + return { completed: false, error: error.message }; } - // Grant tablo access if not already granted - const { data: existingAccess } = await supabase + return { completed: !!profile?.client_onboarded_at }; +} + +export async function findOrCreateClientAccount( + supabase: SupabaseClient, + recipientEmail: string +): Promise { + const normalizedEmail = recipientEmail.trim().toLowerCase(); + const { user: existingUser, error: lookupError } = await getAuthUserByEmail(supabase, normalizedEmail); + + if (lookupError) { + return { success: false, error: lookupError }; + } + + if (existingUser) { + const { data: existingProfile, error: profileError } = await supabase + .from("profiles") + .select("email, is_client, client_onboarded_at") + .eq("id", existingUser.id) + .maybeSingle(); + + if (profileError) { + return { success: false, error: profileError.message }; + } + + if (!existingProfile) { + return { success: false, error: "Client profile not found" }; + } + + if (!existingProfile.is_client) { + return { + success: false, + error: "This email already belongs to a main app account", + }; + } + + return { + success: true, + wasCreated: false, + account: { + email: existingProfile.email ?? normalizedEmail, + is_client: existingProfile.is_client, + client_onboarded_at: existingProfile.client_onboarded_at, + userId: existingUser.id, + }, + }; + } + + const { data: authData, error: authError } = await supabase.auth.admin.createUser({ + email: normalizedEmail, + email_confirm: true, + user_metadata: { role: "client" }, + }); + + if (authError || !authData?.user) { + return { success: false, error: authError?.message ?? "Failed to create client user" }; + } + + const { error: updateProfileError } = await supabase + .from("profiles") + .update({ is_client: true, client_onboarded_at: null }) + .eq("id", authData.user.id); + + if (updateProfileError) { + return { success: false, error: updateProfileError.message }; + } + + return { + success: true, + wasCreated: true, + account: { + email: normalizedEmail, + is_client: true, + client_onboarded_at: null, + userId: authData.user.id, + }, + }; +} + +export async function ensureClientTabloAccess( + supabase: SupabaseClient, + tabloId: string, + userId: string, + grantedBy: string +): Promise<{ success: boolean; error?: string }> { + const { data: existingAccess, error: accessError } = await supabase .from("tablo_access") .select("id, is_active") .eq("tablo_id", tabloId) .eq("user_id", userId) - .single(); + .maybeSingle(); + + if (accessError) { + return { success: false, error: accessError.message }; + } if (!existingAccess) { - await supabase.from("tablo_access").insert({ + const { error: insertError } = await supabase.from("tablo_access").insert({ tablo_id: tabloId, user_id: userId, granted_by: grantedBy, is_admin: false, is_active: true, }); - } else if (!existingAccess.is_active) { - await supabase.from("tablo_access").update({ is_active: true }).eq("id", existingAccess.id); + if (insertError) { + return { success: false, error: insertError.message }; + } + return { success: true }; } - return { success: true, userId }; + if (!existingAccess.is_active) { + const { error: updateError } = await supabase + .from("tablo_access") + .update({ is_active: true }) + .eq("id", existingAccess.id); + if (updateError) { + return { success: false, error: updateError.message }; + } + } + + return { success: true }; +} + +export async function createClientSetupInvite( + supabase: SupabaseClient, + input: { + tabloId: string; + invitedEmail: string; + invitedBy: string; + token: string; + expiresAt: string; + } +): Promise<{ success: boolean; error?: string }> { + const { error } = await supabase.from("client_invites").insert({ + tablo_id: input.tabloId, + invited_email: input.invitedEmail, + invited_by: input.invitedBy, + invite_token: input.token, + invite_type: "setup", + is_pending: true, + expires_at: input.expiresAt, + }); + + if (error) { + return { success: false, error: error.message }; + } + + return { success: true }; } diff --git a/apps/api/src/routers/clientInvites.ts b/apps/api/src/routers/clientInvites.ts index f14f977..d42da4c 100644 --- a/apps/api/src/routers/clientInvites.ts +++ b/apps/api/src/routers/clientInvites.ts @@ -1,19 +1,97 @@ import { Hono } from "hono"; import { createFactory } from "hono/factory"; -import { checkTabloAdmin, createClientUser } from "../helpers/helpers.js"; +import { + checkTabloAdmin, + createClientSetupInvite, + ensureClientTabloAccess, + findOrCreateClientAccount, +} from "../helpers/helpers.js"; import { generateToken } from "../helpers/token.js"; import { MiddlewareManager } from "../middlewares/middleware.js"; -import type { AuthEnv } from "../types/app.types.js"; +import type { AuthEnv, BaseEnv } from "../types/app.types.js"; -const factory = createFactory(); +const authFactory = createFactory(); +const publicFactory = createFactory(); const CLIENT_INVITE_EXPIRY_HOURS = 72; +const getClientsUrl = () => process.env.CLIENTS_URL || "https://clients.xtablo.com"; + +const isValidEmail = (value: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value); + +const findInviteByToken = async (token: string, supabase: BaseEnv["Variables"]["supabase"]) => + supabase + .from("client_invites") + .select( + "id, tablo_id, invited_email, invited_by, invite_type, is_pending, expires_at, used_at, cancelled_at, setup_completed_at" + ) + .eq("invite_token", token) + .maybeSingle(); + +const validateSetupInvite = async (token: string, supabase: BaseEnv["Variables"]["supabase"]) => { + const { data: invite, error } = await findInviteByToken(token, supabase); + + if (error) { + return { status: 500 as const, body: { error: error.message } }; + } + + if (!invite || invite.invite_type !== "setup" || !invite.is_pending) { + return { status: 404 as const, body: { error: "Invite not found or already used" } }; + } + + if (invite.cancelled_at || invite.used_at || invite.setup_completed_at) { + return { status: 404 as const, body: { error: "Invite not found or already used" } }; + } + + if (invite.expires_at && new Date(invite.expires_at) < new Date()) { + return { status: 410 as const, body: { error: "This invite has expired" } }; + } + + return { status: 200 as const, invite }; +}; + +const sendSetupEmail = async ( + transporter: BaseEnv["Variables"]["transporter"], + input: { email: string; setupUrl: string } +) => { + await transporter.sendMail({ + from: "Xtablo ", + to: input.email, + subject: "Configurez votre accès client Xtablo", + html: ` +

Vous avez été invité sur Xtablo

+

Bonjour,

+

Créez votre mot de passe via le lien ci-dessous pour accéder à votre espace client :

+

Configurer mon mot de passe

+

Ce lien expire dans ${CLIENT_INVITE_EXPIRY_HOURS} heures et ne peut être utilisé qu'une seule fois.

+ `, + }); +}; + +const sendAccessNotificationEmail = async ( + transporter: BaseEnv["Variables"]["transporter"], + input: { email: string; tabloUrl: string } +) => { + await transporter.sendMail({ + from: "Xtablo ", + to: input.email, + subject: "Vous avez maintenant accès à un nouveau tablo", + html: ` +

Vous avez maintenant accès à un tablo

+

Bonjour,

+

Votre accès a été ajouté. Utilisez le lien ci-dessous pour ouvrir directement le tablo :

+

Ouvrir le tablo

+

Si vous n'êtes pas connecté, vous serez redirigé vers la page de connexion.

+ `, + }); +}; + /** POST /:tabloId — Create a client invite (admin only) */ const createClientInvite = (middlewareManager: ReturnType) => - factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { + authFactory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { const user = c.get("user"); const supabase = c.get("supabase"); + const transporter = c.get("transporter"); const tabloId = c.req.param("tabloId"); const body = await c.req.json(); @@ -21,14 +99,42 @@ const createClientInvite = (middlewareManager: ReturnType", - to: rawEmail, - subject: "Vous avez été invité sur Xtablo", - html: ` -

Vous avez été invité à collaborer sur un tablo

-

Bonjour,

-

Cliquez sur le lien ci-dessous pour accéder à votre espace client :

-

Accéder à mon espace

-

Ce lien expire dans ${CLIENT_INVITE_EXPIRY_HOURS} heures.

- `, - }); - } catch (emailError) { - console.error("Failed to send client invite email:", emailError); - } + try { + await sendSetupEmail(transporter, { + email: rawEmail, + setupUrl: `${clientsUrl}/set-password?token=${encodeURIComponent(token)}`, + }); + } catch (emailError) { + console.error("Failed to send client setup email:", emailError); } - return c.json({ success: true }); + return c.json({ success: true, inviteMode: "setup" as const }); }); -/** POST /accept/:token — Accept a client invite */ -const acceptClientInvite = (_middlewareManager: ReturnType) => - factory.createHandlers(async (c) => { - const user = c.get("user"); +/** GET /setup/:token — Validate a setup invite token */ +const getSetupInvite = () => + publicFactory.createHandlers(async (c) => { const supabase = c.get("supabase"); const token = c.req.param("token"); - const { data: invite, error: inviteError } = await supabase + const validation = await validateSetupInvite(token, supabase); + if (validation.status !== 200) { + return c.json(validation.body, validation.status); + } + + return c.json({ + email: validation.invite.invited_email, + tabloId: validation.invite.tablo_id, + }); + }); + +/** POST /setup/:token — Complete one-time password setup */ +const completeSetupInvite = () => + publicFactory.createHandlers(async (c) => { + const supabase = c.get("supabase"); + const token = c.req.param("token"); + const body = await c.req.json(); + const password = String(body.password || ""); + + if (password.length < 8) { + return c.json({ error: "Password must be at least 8 characters long" }, 400); + } + + const validation = await validateSetupInvite(token, supabase); + if (validation.status !== 200) { + return c.json(validation.body, validation.status); + } + + const invite = validation.invite; + const { data: usersData, error: listUsersError } = await supabase.auth.admin.listUsers(); + if (listUsersError) { + return c.json({ error: listUsersError.message }, 500); + } + + // biome-ignore lint/suspicious/noExplicitAny: admin.listUsers returns typed data at runtime + const users = usersData as any; + // biome-ignore lint/suspicious/noExplicitAny: admin user type + const clientUser = users?.users?.find((candidate: any) => { + return candidate.email?.toLowerCase() === invite.invited_email?.toLowerCase(); + }); + + if (!clientUser?.id) { + return c.json({ error: "Client account not found" }, 404); + } + + const { error: updateUserError } = await supabase.auth.admin.updateUserById(clientUser.id, { + password, + }); + if (updateUserError) { + return c.json({ error: updateUserError.message }, 500); + } + + const completedAt = new Date().toISOString(); + + const { error: updateProfileError } = await supabase + .from("profiles") + .update({ client_onboarded_at: completedAt, is_client: true }) + .eq("id", clientUser.id); + if (updateProfileError) { + return c.json({ error: updateProfileError.message }, 500); + } + + const { error: consumeInviteError } = await supabase .from("client_invites") - .select("id, tablo_id, invited_email, invited_by, is_pending, expires_at") - .eq("invite_token", token) - .maybeSingle(); - - if (inviteError) { - return c.json({ error: inviteError.message }, 500); + .update({ + is_pending: false, + used_at: completedAt, + setup_completed_at: completedAt, + }) + .eq("id", invite.id) + .eq("is_pending", true); + if (consumeInviteError) { + return c.json({ error: consumeInviteError.message }, 500); } - if (!invite || !invite.is_pending) { - return c.json({ error: "Invite not found or already used" }, 404); - } - - // Check expiration - if (invite.expires_at && new Date(invite.expires_at) < new Date()) { - return c.json({ error: "This invite has expired" }, 410); - } - - // Email must match the authenticated user - if (invite.invited_email?.toLowerCase() !== user.email?.toLowerCase()) { - return c.json({ error: "This invite was not issued to your account" }, 403); - } - - // Mark invite as accepted - await supabase.from("client_invites").update({ is_pending: false }).eq("id", invite.id); - - // Ensure tablo access is active - const { data: existingAccess } = await supabase - .from("tablo_access") - .select("id, is_active") - .eq("tablo_id", invite.tablo_id) - .eq("user_id", user.id) - .maybeSingle(); - - if (!existingAccess) { - await supabase.from("tablo_access").insert({ - tablo_id: invite.tablo_id, - user_id: user.id, - granted_by: invite.invited_by, - is_admin: false, - is_active: true, - }); - } else if (!existingAccess.is_active) { - await supabase.from("tablo_access").update({ is_active: true }).eq("id", existingAccess.id); - } - - return c.json({ success: true, tabloId: invite.tablo_id }); + return c.json({ + success: true, + email: invite.invited_email, + tabloId: invite.tablo_id, + }); }); /** GET /:tabloId/pending — List pending client invites (admin only) */ const getPendingClientInvites = ( middlewareManager: ReturnType ) => - factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { + authFactory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { const supabase = c.get("supabase"); const tabloId = c.req.param("tabloId"); const { data: invites, error } = await supabase .from("client_invites") - .select("id, invited_email, expires_at, is_pending, created_at") + .select("id, invited_email, expires_at, is_pending, created_at, invite_type") .eq("tablo_id", tabloId) + .eq("invite_type", "setup") .eq("is_pending", true) .order("created_at", { ascending: false }); @@ -169,7 +282,7 @@ const getPendingClientInvites = ( /** DELETE /:tabloId/:inviteId — Cancel a client invite (admin only) */ const cancelClientInvite = (middlewareManager: ReturnType) => - factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { + authFactory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { const supabase = c.get("supabase"); const tabloId = c.req.param("tabloId"); const inviteId = Number(c.req.param("inviteId")); @@ -180,7 +293,7 @@ const cancelClientInvite = (middlewareManager: ReturnType { const middlewareManager = MiddlewareManager.getInstance(); router.post("/:tabloId", ...createClientInvite(middlewareManager)); - router.post("/accept/:token", ...acceptClientInvite(middlewareManager)); router.get("/:tabloId/pending", ...getPendingClientInvites(middlewareManager)); router.delete("/:tabloId/:inviteId", ...cancelClientInvite(middlewareManager)); return router; }; + +export const getPublicClientInvitesRouter = () => { + const router = new Hono(); + + router.get("/setup/:token", ...getSetupInvite()); + router.post("/setup/:token", ...completeSetupInvite()); + + return router; +}; diff --git a/apps/api/src/routers/maybeAuthRouter.ts b/apps/api/src/routers/maybeAuthRouter.ts index 7da5c8e..b01a6c5 100644 --- a/apps/api/src/routers/maybeAuthRouter.ts +++ b/apps/api/src/routers/maybeAuthRouter.ts @@ -1,6 +1,7 @@ import { Hono } from "hono"; import { MiddlewareManager } from "../middlewares/middleware.js"; import type { MaybeAuthEnv } from "../types/app.types.js"; +import { getPublicClientInvitesRouter } from "./clientInvites.js"; import { getBookingRouter } from "./invite.js"; export const getMaybeAuthenticatedRouter = () => { @@ -11,6 +12,7 @@ export const getMaybeAuthenticatedRouter = () => { maybeAuthenticated.use(middlewareManager.maybeAuthenticated); maybeAuthenticated.route("/book", getBookingRouter()); + maybeAuthenticated.route("/client-invites", getPublicClientInvitesRouter()); return maybeAuthenticated; }; diff --git a/apps/clients/package.json b/apps/clients/package.json index 68c5563..699fa82 100644 --- a/apps/clients/package.json +++ b/apps/clients/package.json @@ -39,6 +39,7 @@ }, "dependencies": { "@tanstack/react-query": "^5.69.0", + "@xtablo/auth-ui": "workspace:*", "@xtablo/shared": "workspace:*", "@xtablo/shared-types": "workspace:*", "@xtablo/tablo-views": "workspace:*", diff --git a/apps/clients/src/components/ClientAuthGate.tsx b/apps/clients/src/components/ClientAuthGate.tsx new file mode 100644 index 0000000..4c75eda --- /dev/null +++ b/apps/clients/src/components/ClientAuthGate.tsx @@ -0,0 +1,56 @@ +import { useSession } from "@xtablo/shared/contexts/SessionContext"; +import { useEffect, useState } from "react"; +import { Navigate, Outlet, useLocation } from "react-router-dom"; +import { supabase } from "../lib/supabase"; + +export function ClientAuthGate() { + const { session } = useSession(); + const location = useLocation(); + const [isCheckingSession, setIsCheckingSession] = useState(true); + const [hasSession, setHasSession] = useState(false); + + useEffect(() => { + let isMounted = true; + + if (session) { + setHasSession(true); + setIsCheckingSession(false); + return () => { + isMounted = false; + }; + } + + supabase.auth + .getSession() + .then(({ data }) => { + if (!isMounted) return; + setHasSession(Boolean(data.session)); + }) + .finally(() => { + if (isMounted) { + setIsCheckingSession(false); + } + }); + + return () => { + isMounted = false; + }; + }, [session]); + + if (session || hasSession) { + return ; + } + + if (isCheckingSession) { + return ( +
+
+
+ ); + } + + const redirectUrl = `${location.pathname}${location.search}${location.hash}`; + localStorage.setItem("clients.redirectUrl", redirectUrl); + + return ; +} diff --git a/apps/clients/src/components/ClientLayout.test.tsx b/apps/clients/src/components/ClientLayout.test.tsx index 17c3972..709a0c0 100644 --- a/apps/clients/src/components/ClientLayout.test.tsx +++ b/apps/clients/src/components/ClientLayout.test.tsx @@ -1,4 +1,6 @@ +import { screen } from "@testing-library/react"; import { describe, expect, it } from "vitest"; +import AppRoutes from "../routes"; import { renderWithProviders } from "../test/testHelpers"; import { ClientLayout } from "./ClientLayout"; @@ -20,4 +22,14 @@ describe("ClientLayout", () => { expect(main).toHaveClass("max-w-7xl"); expect(main).toHaveClass("mx-auto"); }); + + it("redirects unauthenticated client routes to the login page", async () => { + renderWithProviders(, { + route: "/tablo/tablo-1", + testUser: undefined, + }); + + expect(await screen.findByTestId("auth-card-shell")).toBeInTheDocument(); + expect(await screen.findByRole("button", { name: "Connexion" })).toBeInTheDocument(); + }); }); diff --git a/apps/clients/src/components/ClientLayout.tsx b/apps/clients/src/components/ClientLayout.tsx index 16609cf..5ef32f4 100644 --- a/apps/clients/src/components/ClientLayout.tsx +++ b/apps/clients/src/components/ClientLayout.tsx @@ -14,19 +14,7 @@ function getInitials(email: string): string { export function ClientLayout() { const { session } = useSession(); - - if (!session) { - return ( -
-
-

Accès non autorisé

-

- Veuillez utiliser le lien reçu dans votre email pour accéder à cette page. -

-
-
- ); - } + if (!session) return null; const email = session.user.email ?? ""; const initials = email ? getInitials(email) : "?"; diff --git a/apps/clients/src/i18n.test.ts b/apps/clients/src/i18n.test.ts index e7747d7..7ca4e6c 100644 --- a/apps/clients/src/i18n.test.ts +++ b/apps/clients/src/i18n.test.ts @@ -2,11 +2,13 @@ import i18n from "i18next"; import { initReactI18next } from "react-i18next"; import bookingEn from "./locales/en/booking.json"; import bookingFr from "./locales/fr/booking.json"; +import authEn from "../../main/src/locales/en/auth.json"; import chatEn from "../../main/src/locales/en/chat.json"; import commonEn from "../../main/src/locales/en/common.json"; import componentsEn from "../../main/src/locales/en/components.json"; import pagesEn from "../../main/src/locales/en/pages.json"; import tabloEn from "../../main/src/locales/en/tablo.json"; +import authFr from "../../main/src/locales/fr/auth.json"; import chatFr from "../../main/src/locales/fr/chat.json"; import commonFr from "../../main/src/locales/fr/common.json"; import componentsFr from "../../main/src/locales/fr/components.json"; @@ -16,6 +18,7 @@ import tabloFr from "../../main/src/locales/fr/tablo.json"; i18n.use(initReactI18next).init({ resources: { fr: { + auth: authFr, booking: bookingFr, chat: chatFr, common: commonFr, @@ -24,6 +27,7 @@ i18n.use(initReactI18next).init({ tablo: tabloFr, }, en: { + auth: authEn, booking: bookingEn, chat: chatEn, common: commonEn, diff --git a/apps/clients/src/i18n.ts b/apps/clients/src/i18n.ts index 5612ccd..92423b4 100644 --- a/apps/clients/src/i18n.ts +++ b/apps/clients/src/i18n.ts @@ -4,11 +4,13 @@ import { initReactI18next } from "react-i18next"; import bookingEn from "./locales/en/booking.json"; // Import translation files import bookingFr from "./locales/fr/booking.json"; +import authEn from "../../main/src/locales/en/auth.json"; import chatEn from "../../main/src/locales/en/chat.json"; import commonEn from "../../main/src/locales/en/common.json"; import componentsEn from "../../main/src/locales/en/components.json"; import pagesEn from "../../main/src/locales/en/pages.json"; import tabloEn from "../../main/src/locales/en/tablo.json"; +import authFr from "../../main/src/locales/fr/auth.json"; import chatFr from "../../main/src/locales/fr/chat.json"; import commonFr from "../../main/src/locales/fr/common.json"; import componentsFr from "../../main/src/locales/fr/components.json"; @@ -21,6 +23,7 @@ i18n .init({ resources: { fr: { + auth: authFr, booking: bookingFr, chat: chatFr, common: commonFr, @@ -29,6 +32,7 @@ i18n tablo: tabloFr, }, en: { + auth: authEn, booking: bookingEn, chat: chatEn, common: commonEn, diff --git a/apps/clients/src/pages/AuthCallback.tsx b/apps/clients/src/pages/AuthCallback.tsx index b34427b..806d3cb 100644 --- a/apps/clients/src/pages/AuthCallback.tsx +++ b/apps/clients/src/pages/AuthCallback.tsx @@ -1,66 +1,5 @@ -import { useSession } from "@xtablo/shared/contexts/SessionContext"; -import { useEffect, useRef, useState } from "react"; -import { useNavigate, useSearchParams } from "react-router-dom"; +import { Navigate } from "react-router-dom"; export function AuthCallback() { - const [searchParams] = useSearchParams(); - const token = searchParams.get("token"); - const { session } = useSession(); - const navigate = useNavigate(); - const [error, setError] = useState(null); - const hasAccepted = useRef(false); - - useEffect(() => { - if (!session || !token || hasAccepted.current) { - return; - } - - hasAccepted.current = true; - - const apiUrl = import.meta.env.VITE_API_URL as string; - - fetch(`${apiUrl}/api/v1/client-invites/accept/${token}`, { - method: "POST", - headers: { - Authorization: `Bearer ${session.access_token}`, - "Content-Type": "application/json", - }, - }) - .then(async (res) => { - if (!res.ok) { - const body = await res.json().catch(() => ({})); - throw new Error((body as { message?: string }).message ?? "Erreur lors de l'acceptation de l'invitation"); - } - return res.json() as Promise<{ tabloId: string }>; - }) - .then((data) => { - navigate(`/tablo/${data.tabloId}`, { replace: true }); - }) - .catch((err: unknown) => { - console.error("Accept invite error:", err); - setError( - "Une erreur est survenue lors de l'acceptation de l'invitation. Veuillez contacter la personne qui vous a invité." - ); - }); - }, [session, token, navigate]); - - if (error) { - return ( -
-
-

Erreur

-

{error}

-
-
- ); - } - - return ( -
-
-
-

Authentification en cours...

-
-
- ); + return ; } diff --git a/apps/clients/src/pages/LoginPage.test.tsx b/apps/clients/src/pages/LoginPage.test.tsx new file mode 100644 index 0000000..425eac6 --- /dev/null +++ b/apps/clients/src/pages/LoginPage.test.tsx @@ -0,0 +1,62 @@ +import { fireEvent, screen, waitFor } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { renderWithProviders } from "../test/testHelpers"; +import { LoginPage } from "./LoginPage"; + +const { mockSignInWithPassword, mockNavigate } = vi.hoisted(() => ({ + mockSignInWithPassword: vi.fn(), + mockNavigate: vi.fn(), +})); + +vi.mock("../lib/supabase", () => ({ + supabase: { + auth: { + signInWithPassword: mockSignInWithPassword, + }, + }, +})); + +vi.mock("react-router-dom", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + useNavigate: () => mockNavigate, + }; +}); + +describe("LoginPage", () => { + beforeEach(() => { + vi.clearAllMocks(); + localStorage.clear(); + mockSignInWithPassword.mockResolvedValue({ + data: { user: { email_confirmed_at: new Date().toISOString() } }, + error: null, + }); + }); + + it("renders the shared auth shell and form", () => { + renderWithProviders(, { testUser: undefined }); + + expect(screen.getByTestId("auth-card-shell")).toBeInTheDocument(); + expect(screen.getByLabelText("Email")).toBeInTheDocument(); + expect(screen.getByLabelText("Mot de passe")).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Connexion" })).toBeInTheDocument(); + }); + + it("submits email/password login and resumes the stored redirect", async () => { + localStorage.setItem("clients.redirectUrl", "/tablo/tablo-42"); + renderWithProviders(, { testUser: undefined }); + + fireEvent.change(screen.getByLabelText("Email"), { target: { value: "client@example.com" } }); + fireEvent.change(screen.getByLabelText("Mot de passe"), { target: { value: "password123" } }); + fireEvent.click(screen.getByRole("button", { name: "Connexion" })); + + await waitFor(() => { + expect(mockSignInWithPassword).toHaveBeenCalledWith({ + email: "client@example.com", + password: "password123", + }); + expect(mockNavigate).toHaveBeenCalledWith("/tablo/tablo-42"); + }); + }); +}); diff --git a/apps/clients/src/pages/LoginPage.tsx b/apps/clients/src/pages/LoginPage.tsx new file mode 100644 index 0000000..f38f582 --- /dev/null +++ b/apps/clients/src/pages/LoginPage.tsx @@ -0,0 +1,102 @@ +import { AuthCardShell, AuthEmailPasswordForm, AuthInfoBanner } from "@xtablo/auth-ui"; +import { useSession } from "@xtablo/shared/contexts/SessionContext"; +import { useState } from "react"; +import { useTranslation } from "react-i18next"; +import { Link, useNavigate } from "react-router-dom"; +import { supabase } from "../lib/supabase"; + +export function LoginPage() { + const { t } = useTranslation(["auth", "common"]); + const { session } = useSession(); + const navigate = useNavigate(); + const [email, setEmail] = useState(""); + const [password, setPassword] = useState(""); + const [isPending, setIsPending] = useState(false); + const [error, setError] = useState(null); + + if (session) { + const redirectUrl = localStorage.getItem("clients.redirectUrl"); + if (redirectUrl) { + localStorage.removeItem("clients.redirectUrl"); + navigate(redirectUrl); + } else { + navigate("/"); + } + } + + const onSubmit = async (event: React.FormEvent) => { + event.preventDefault(); + setIsPending(true); + setError(null); + + const { error: signInError } = await supabase.auth.signInWithPassword({ + email, + password, + }); + + if (signInError) { + setError(signInError.message); + setIsPending(false); + return; + } + + const redirectUrl = localStorage.getItem("clients.redirectUrl"); + if (redirectUrl) { + localStorage.removeItem("clients.redirectUrl"); + navigate(redirectUrl); + } else { + navigate("/"); + } + }; + + return ( + + + + + {t("auth:common.backHome")} + + } + showThemeToggle + > +
+ {error ? : null} + + + + {t("auth:login.forgotPassword")} + +
+ } + /> +
+ + ); +} diff --git a/apps/clients/src/pages/ResetPasswordPage.test.tsx b/apps/clients/src/pages/ResetPasswordPage.test.tsx new file mode 100644 index 0000000..18a4657 --- /dev/null +++ b/apps/clients/src/pages/ResetPasswordPage.test.tsx @@ -0,0 +1,42 @@ +import { fireEvent, screen, waitFor } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { renderWithProviders } from "../test/testHelpers"; +import { ResetPasswordPage } from "./ResetPasswordPage"; + +const { mockResetPasswordForEmail } = vi.hoisted(() => ({ + mockResetPasswordForEmail: vi.fn(), +})); + +vi.mock("../lib/supabase", () => ({ + supabase: { + auth: { + resetPasswordForEmail: mockResetPasswordForEmail, + }, + }, +})); + +describe("ResetPasswordPage", () => { + beforeEach(() => { + vi.clearAllMocks(); + mockResetPasswordForEmail.mockResolvedValue({ error: null }); + }); + + it("renders the shared auth shell", () => { + renderWithProviders(, { testUser: undefined }); + + expect(screen.getByTestId("auth-card-shell")).toBeInTheDocument(); + expect(screen.getByLabelText("Email")).toBeInTheDocument(); + }); + + it("submits a password reset email", async () => { + renderWithProviders(, { testUser: undefined }); + + fireEvent.change(screen.getByLabelText("Email"), { target: { value: "client@example.com" } }); + fireEvent.click(screen.getByRole("button", { name: "Envoyer le lien de réinitialisation" })); + + await waitFor(() => { + expect(mockResetPasswordForEmail).toHaveBeenCalled(); + expect(screen.getByText(/vérifiez votre boîte mail/i)).toBeInTheDocument(); + }); + }); +}); diff --git a/apps/clients/src/pages/ResetPasswordPage.tsx b/apps/clients/src/pages/ResetPasswordPage.tsx new file mode 100644 index 0000000..85d591e --- /dev/null +++ b/apps/clients/src/pages/ResetPasswordPage.tsx @@ -0,0 +1,71 @@ +import { AuthCardShell, AuthInfoBanner } from "@xtablo/auth-ui"; +import { Button } from "@xtablo/ui/components/button"; +import { Input } from "@xtablo/ui/components/input"; +import { Label } from "@xtablo/ui/components/label"; +import { useState } from "react"; +import { useTranslation } from "react-i18next"; +import { Link } from "react-router-dom"; +import { supabase } from "../lib/supabase"; + +export function ResetPasswordPage() { + const { t } = useTranslation(["auth", "common"]); + const [email, setEmail] = useState(""); + const [error, setError] = useState(null); + const [isPending, setIsPending] = useState(false); + const [isSubmitted, setIsSubmitted] = useState(false); + + const onSubmit = async (event: React.FormEvent) => { + event.preventDefault(); + setIsPending(true); + setError(null); + + const { error: resetError } = await supabase.auth.resetPasswordForEmail(email, { + redirectTo: `${window.location.origin}/set-password`, + }); + + if (resetError) { + setError(resetError.message); + setIsPending(false); + return; + } + + setIsSubmitted(true); + setIsPending(false); + }; + + return ( + +
+ {error ? : null} + {isSubmitted ? ( +
+ + + + +
+ ) : ( +
+
+ + setEmail(event.target.value)} + placeholder={t("auth:resetPassword.emailPlaceholder")} + required + disabled={isPending} + /> +
+ + +
+ )} +
+
+ ); +} diff --git a/apps/clients/src/pages/SetPasswordPage.test.tsx b/apps/clients/src/pages/SetPasswordPage.test.tsx new file mode 100644 index 0000000..1cce2ee --- /dev/null +++ b/apps/clients/src/pages/SetPasswordPage.test.tsx @@ -0,0 +1,91 @@ +import { fireEvent, screen, waitFor } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { renderWithProviders } from "../test/testHelpers"; +import { SetPasswordPage } from "./SetPasswordPage"; + +const { mockSignInWithPassword, mockUpdateUser, mockNavigate } = vi.hoisted(() => ({ + mockSignInWithPassword: vi.fn(), + mockUpdateUser: vi.fn(), + mockNavigate: vi.fn(), +})); + +vi.mock("../lib/supabase", () => ({ + supabase: { + auth: { + signInWithPassword: mockSignInWithPassword, + updateUser: mockUpdateUser, + }, + }, +})); + +vi.mock("react-router-dom", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + useNavigate: () => mockNavigate, + }; +}); + +describe("SetPasswordPage", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.stubGlobal("fetch", vi.fn()); + mockSignInWithPassword.mockResolvedValue({ data: {}, error: null }); + mockUpdateUser.mockResolvedValue({ data: {}, error: null }); + }); + + it("renders an invalid-token state when invite validation fails", async () => { + vi.mocked(fetch).mockResolvedValueOnce( + new Response(JSON.stringify({ error: "Invite not found or already used" }), { status: 404 }) + ); + + renderWithProviders(, { + route: "/set-password?token=bad-token", + path: "/set-password", + testUser: undefined, + }); + + await waitFor(() => { + expect(screen.getByText(/lien invalide/i)).toBeInTheDocument(); + }); + }); + + it("submits invite-based password setup once", async () => { + vi.mocked(fetch) + .mockResolvedValueOnce( + new Response(JSON.stringify({ email: "client@example.com", tabloId: "tablo-1" }), { + status: 200, + }) + ) + .mockResolvedValueOnce( + new Response(JSON.stringify({ success: true, email: "client@example.com", tabloId: "tablo-1" }), { + status: 200, + }) + ); + + renderWithProviders(, { + route: "/set-password?token=good-token", + path: "/set-password", + testUser: undefined, + }); + + await waitFor(() => { + expect(screen.getByLabelText("Mot de passe")).toBeInTheDocument(); + }); + + fireEvent.change(screen.getByLabelText("Mot de passe"), { target: { value: "password123" } }); + fireEvent.change(screen.getByLabelText("Confirmer le mot de passe"), { + target: { value: "password123" }, + }); + fireEvent.click(screen.getByRole("button", { name: "Définir mon mot de passe" })); + + await waitFor(() => { + expect(fetch).toHaveBeenCalledTimes(2); + expect(mockSignInWithPassword).toHaveBeenCalledWith({ + email: "client@example.com", + password: "password123", + }); + expect(mockNavigate).toHaveBeenCalledWith("/tablo/tablo-1"); + }); + }); +}); diff --git a/apps/clients/src/pages/SetPasswordPage.tsx b/apps/clients/src/pages/SetPasswordPage.tsx new file mode 100644 index 0000000..f775c4b --- /dev/null +++ b/apps/clients/src/pages/SetPasswordPage.tsx @@ -0,0 +1,205 @@ +import { AuthCardShell, AuthInfoBanner } from "@xtablo/auth-ui"; +import { useSession } from "@xtablo/shared/contexts/SessionContext"; +import { Button } from "@xtablo/ui/components/button"; +import { Input } from "@xtablo/ui/components/input"; +import { Label } from "@xtablo/ui/components/label"; +import { useEffect, useMemo, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { useNavigate, useSearchParams } from "react-router-dom"; +import { supabase } from "../lib/supabase"; + +type InviteDetails = { + email: string; + tabloId: string; +}; + +type InviteState = "loading" | "ready" | "invalid"; + +function getApiUrl() { + return import.meta.env.VITE_API_URL ?? ""; +} + +async function parseError(response: Response) { + const body = (await response.json().catch(() => ({}))) as { error?: string; message?: string }; + return body.error ?? body.message ?? "Une erreur est survenue."; +} + +export function SetPasswordPage() { + const { t } = useTranslation("auth"); + const { session } = useSession(); + const navigate = useNavigate(); + const [searchParams] = useSearchParams(); + const token = searchParams.get("token"); + const [inviteState, setInviteState] = useState(token ? "loading" : "ready"); + const [inviteDetails, setInviteDetails] = useState(null); + const [password, setPassword] = useState(""); + const [confirmPassword, setConfirmPassword] = useState(""); + const [error, setError] = useState(null); + const [isPending, setIsPending] = useState(false); + + const isInviteFlow = Boolean(token); + const description = useMemo( + () => + isInviteFlow + ? "Définissez votre mot de passe pour accéder à votre espace client." + : t("updatePassword.description"), + [isInviteFlow, t] + ); + + useEffect(() => { + if (!token) { + return; + } + + let isMounted = true; + + fetch(`${getApiUrl()}/api/v1/client-invites/setup/${token}`) + .then(async (response) => { + if (!response.ok) { + throw new Error(await parseError(response)); + } + + return (await response.json()) as InviteDetails; + }) + .then((details) => { + if (!isMounted) return; + setInviteDetails(details); + setInviteState("ready"); + }) + .catch((err: unknown) => { + if (!isMounted) return; + setError(err instanceof Error ? err.message : "Lien invalide"); + setInviteState("invalid"); + }); + + return () => { + isMounted = false; + }; + }, [token]); + + const onSubmit = async (event: React.FormEvent) => { + event.preventDefault(); + setError(null); + + if (password.length < 8) { + setError(t("signup.errors.passwordLength")); + return; + } + + if (password !== confirmPassword) { + setError(t("signup.errors.passwordMatch")); + return; + } + + setIsPending(true); + + try { + if (token && inviteDetails) { + const response = await fetch(`${getApiUrl()}/api/v1/client-invites/setup/${token}`, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ password }), + }); + + if (!response.ok) { + throw new Error(await parseError(response)); + } + + const result = (await response.json()) as InviteDetails & { success: boolean }; + const { error: signInError } = await supabase.auth.signInWithPassword({ + email: result.email, + password, + }); + + if (signInError) { + throw signInError; + } + + navigate(`/tablo/${result.tabloId}`); + return; + } + + const { error: updateError } = await supabase.auth.updateUser({ password }); + if (updateError) { + throw updateError; + } + + navigate("/login"); + } catch (err) { + setError(err instanceof Error ? err.message : "Une erreur est survenue."); + } finally { + setIsPending(false); + } + }; + + if (inviteState === "loading") { + return ( + +
+
+
+ + ); + } + + if (inviteState === "invalid") { + return ( + + + + ); + } + + const shouldShowRecoveryHint = !isInviteFlow && !session; + + return ( + +
+ {error ? : null} + {shouldShowRecoveryHint ? ( + + ) : null} + +
+
+ + setPassword(event.target.value)} + required + disabled={isPending} + /> +
+ +
+ + setConfirmPassword(event.target.value)} + required + disabled={isPending} + /> +
+ + +
+
+
+ ); +} diff --git a/apps/clients/src/routes.tsx b/apps/clients/src/routes.tsx index 57a23ce..e10531f 100644 --- a/apps/clients/src/routes.tsx +++ b/apps/clients/src/routes.tsx @@ -1,16 +1,25 @@ import { Route, Routes } from "react-router-dom"; +import { ClientAuthGate } from "./components/ClientAuthGate"; import { ClientLayout } from "./components/ClientLayout"; import { AuthCallback } from "./pages/AuthCallback"; import { ClientTabloListPage } from "./pages/ClientTabloListPage"; import { ClientTabloPage } from "./pages/ClientTabloPage"; +import { LoginPage } from "./pages/LoginPage"; +import { ResetPasswordPage } from "./pages/ResetPasswordPage"; +import { SetPasswordPage } from "./pages/SetPasswordPage"; export default function AppRoutes() { return ( + } /> + } /> + } /> } /> - }> - } /> - } /> + }> + }> + } /> + } /> + ); diff --git a/apps/clients/src/test/testHelpers.tsx b/apps/clients/src/test/testHelpers.tsx index ede64d8..ac7b2ab 100644 --- a/apps/clients/src/test/testHelpers.tsx +++ b/apps/clients/src/test/testHelpers.tsx @@ -23,12 +23,18 @@ interface RenderWithProvidersOptions { route?: string; path?: string; language?: string; + testUser?: typeof defaultUser | undefined; } export const renderWithProviders = ( ui: React.ReactNode, - { route = "/", path, language = "fr" }: RenderWithProvidersOptions = {} + options: RenderWithProvidersOptions = {} ): RenderResult & { user: ReturnType } => { + const { route = "/", path, language = "fr" } = options; + const testUser = Object.prototype.hasOwnProperty.call(options, "testUser") + ? options.testUser + : defaultUser; + testI18n.changeLanguage(language); const testQueryClient = new QueryClient({ @@ -55,7 +61,7 @@ export const renderWithProviders = ( - {content} + {content} diff --git a/apps/clients/tsconfig.json b/apps/clients/tsconfig.json index f2fa327..2431c00 100644 --- a/apps/clients/tsconfig.json +++ b/apps/clients/tsconfig.json @@ -18,6 +18,8 @@ "noFallthroughCasesInSwitch": true, "baseUrl": ".", "paths": { + "@xtablo/auth-ui": ["../../packages/auth-ui/src"], + "@xtablo/auth-ui/*": ["../../packages/auth-ui/src/*"], "@xtablo/ui": ["../../packages/ui/src"], "@xtablo/ui/*": ["../../packages/ui/src/*"], "@xtablo/shared": ["../../packages/shared/src"], diff --git a/apps/clients/tsconfig.tsbuildinfo b/apps/clients/tsconfig.tsbuildinfo index 1df4210..6ab4cf9 100644 --- a/apps/clients/tsconfig.tsbuildinfo +++ b/apps/clients/tsconfig.tsbuildinfo @@ -1 +1 @@ -{"root":["./src/app.tsx","./src/i18n.test.ts","./src/i18n.ts","./src/main.tsx","./src/maincss.test.ts","./src/routes.tsx","./src/setuptests.ts","./src/components/clientlayout.test.tsx","./src/components/clientlayout.tsx","./src/lib/supabase.ts","./src/pages/authcallback.tsx","./src/pages/clienttablolistpage.tsx","./src/pages/clienttablopage.test.tsx","./src/pages/clienttablopage.tsx","./src/test/testhelpers.test.tsx","./src/test/testhelpers.tsx"],"version":"5.9.3"} \ No newline at end of file +{"root":["./src/app.tsx","./src/i18n.test.ts","./src/i18n.ts","./src/main.tsx","./src/maincss.test.ts","./src/routes.tsx","./src/setuptests.ts","./src/components/clientauthgate.tsx","./src/components/clientlayout.test.tsx","./src/components/clientlayout.tsx","./src/lib/supabase.ts","./src/pages/authcallback.tsx","./src/pages/clienttablolistpage.tsx","./src/pages/clienttablopage.test.tsx","./src/pages/clienttablopage.tsx","./src/pages/loginpage.test.tsx","./src/pages/loginpage.tsx","./src/pages/resetpasswordpage.test.tsx","./src/pages/resetpasswordpage.tsx","./src/pages/setpasswordpage.test.tsx","./src/pages/setpasswordpage.tsx","./src/test/testhelpers.test.tsx","./src/test/testhelpers.tsx"],"version":"5.9.3"} \ No newline at end of file diff --git a/apps/main/package.json b/apps/main/package.json index 18574d9..97bdeda 100644 --- a/apps/main/package.json +++ b/apps/main/package.json @@ -100,6 +100,7 @@ "@types/react-router-dom": "^5.3.3", "@typescript/native-preview": "7.0.0-dev.20251010.1", "@xtablo/chat-ui": "workspace:*", + "@xtablo/auth-ui": "workspace:*", "@xtablo/shared": "workspace:*", "@xtablo/shared-types": "workspace:*", "@xtablo/tablo-views": "workspace:*", diff --git a/apps/main/src/components/ProtectedRoute.test.tsx b/apps/main/src/components/ProtectedRoute.test.tsx index 19143ed..c7e6375 100644 --- a/apps/main/src/components/ProtectedRoute.test.tsx +++ b/apps/main/src/components/ProtectedRoute.test.tsx @@ -85,6 +85,7 @@ describe("ProtectedRoute", () => { last_name: "User", is_temporary: false, is_client: false, + client_onboarded_at: null, last_signed_in: null, plan: "none" as const, created_at: new Date().toISOString(), diff --git a/apps/main/src/components/SubscriptionCard.test.tsx b/apps/main/src/components/SubscriptionCard.test.tsx index f065c5b..7eebb0e 100644 --- a/apps/main/src/components/SubscriptionCard.test.tsx +++ b/apps/main/src/components/SubscriptionCard.test.tsx @@ -40,6 +40,7 @@ const baseUser: User = { avatar_url: null, is_temporary: false, is_client: false, + client_onboarded_at: null, last_signed_in: null, plan: "none", created_at: new Date().toISOString(), diff --git a/apps/main/src/components/UpgradePanel.test.tsx b/apps/main/src/components/UpgradePanel.test.tsx index 3b00d34..b82f2a7 100644 --- a/apps/main/src/components/UpgradePanel.test.tsx +++ b/apps/main/src/components/UpgradePanel.test.tsx @@ -36,6 +36,7 @@ const baseUser: User = { avatar_url: null, is_temporary: false, is_client: false, + client_onboarded_at: null, last_signed_in: null, plan: "none", created_at: new Date().toISOString(), diff --git a/apps/main/src/contexts/UpgradeBlockContext.test.tsx b/apps/main/src/contexts/UpgradeBlockContext.test.tsx index f4b29f7..cedf044 100644 --- a/apps/main/src/contexts/UpgradeBlockContext.test.tsx +++ b/apps/main/src/contexts/UpgradeBlockContext.test.tsx @@ -23,6 +23,7 @@ const baseUser: User = { avatar_url: null, is_temporary: false, is_client: false, + client_onboarded_at: null, last_signed_in: null, plan: "none", created_at: new Date().toISOString(), diff --git a/apps/main/src/hooks/client_invites.ts b/apps/main/src/hooks/client_invites.ts index 3c6125e..71c6e5a 100644 --- a/apps/main/src/hooks/client_invites.ts +++ b/apps/main/src/hooks/client_invites.ts @@ -10,6 +10,11 @@ type PendingClientInvite = { created_at: string; }; +type CreateClientInviteResponse = { + success: true; + inviteMode: "notification" | "setup"; +}; + export const usePendingClientInvites = (tabloId: string) => { const api = useAuthedApi(); const { session } = useSession(); @@ -32,17 +37,23 @@ export const useCreateClientInvite = () => { return useMutation({ mutationFn: async ({ tabloId, email }: { tabloId: string; email: string }) => { - const { data } = await api.post(`/api/v1/client-invites/${tabloId}`, { - email, - }); + const { data } = await api.post( + `/api/v1/client-invites/${tabloId}`, + { + email, + } + ); return data; }, - onSuccess: (_data, { tabloId }) => { + onSuccess: (data, { tabloId }) => { queryClient.invalidateQueries({ queryKey: ["client-invites", tabloId] }); toast.add( { - title: "Lien magique envoyé", - description: "L'invitation client a été envoyée avec succès", + title: data.inviteMode === "setup" ? "Invitation client envoyée" : "Accès client accordé", + description: + data.inviteMode === "setup" + ? "Un email de configuration du mot de passe a été envoyé au client." + : "Le client a été informé de son nouvel accès et pourra se connecter à son espace.", type: "success", }, { timeout: 3000 } diff --git a/apps/main/src/pages/login.test.tsx b/apps/main/src/pages/login.test.tsx index a3c0361..b39deef 100644 --- a/apps/main/src/pages/login.test.tsx +++ b/apps/main/src/pages/login.test.tsx @@ -34,6 +34,7 @@ describe("LoginPage", () => { it("renders all form elements", () => { renderWithProviders(); + expect(screen.getByTestId("auth-card-shell")).toBeInTheDocument(); expect(screen.getByLabelText(/email/i)).toBeInTheDocument(); expect(screen.getByLabelText(/password/i)).toBeInTheDocument(); expect(screen.getByRole("button", { name: /log in/i })).toBeInTheDocument(); diff --git a/apps/main/src/pages/login.tsx b/apps/main/src/pages/login.tsx index 41ca566..c6e3eaa 100644 --- a/apps/main/src/pages/login.tsx +++ b/apps/main/src/pages/login.tsx @@ -1,10 +1,5 @@ import { LoginWithGoogle } from "@ui/components/BrandButtons/LoginWithGoogle"; -import { useTheme } from "@xtablo/shared/contexts/ThemeContext"; -import { Button } from "@xtablo/ui/components/button"; -import { FieldError } from "@xtablo/ui/components/field"; -import { Input } from "@xtablo/ui/components/input"; -import { Label } from "@xtablo/ui/components/label"; -import { MonitorIcon, MoonIcon, SunIcon } from "lucide-react"; +import { AuthCardShell, AuthEmailPasswordForm } from "@xtablo/auth-ui"; import { useRef, useState } from "react"; import { useTranslation } from "react-i18next"; import { Link, useSearchParams } from "react-router-dom"; @@ -60,32 +55,6 @@ export function LoginPage() { setIsHovered(false); }; - // Theme - const { theme, setTheme } = useTheme(); - - const toggleTheme = () => { - if (theme === "light") { - setTheme("dark"); - } else if (theme === "dark") { - setTheme("system"); - } else { - setTheme("light"); - } - }; - - const getThemeIcon = () => { - switch (theme) { - case "light": - return ; - case "dark": - return ; - case "system": - return ; - default: - return ; - } - }; - const onSubmit = (e: React.FormEvent) => { e.preventDefault(); login({ @@ -95,168 +64,100 @@ export function LoginPage() { }; return ( -
- -
e.stopPropagation()} - > - {/* Glow effect behind the card */} -
- -
} + topLeft={ + -
- - - - - {t("auth:common.backHome")} - - - {/* Theme Toggle */} - -
- - {/* Xtablo Icon */} -
- Xtablo + - Xtablo -
+ + {t("auth:common.backHome")} + + } + showThemeToggle + wrapperClassName="transition-transform duration-200 ease-out will-change-transform" + wrapperStyle={{ transform }} + onWrapperMouseMove={handleMouseMove} + onWrapperMouseLeave={handleMouseLeave} + isHovered={isHovered} + > +
+ + {t("auth:login.newExperienceLink")} + +
-

- {t("auth:login.title")} -

- -
- - {t("auth:login.newExperienceLink")} - -
- -
-
-
- - setFormData({ ...formData, email: e.target.value })} - required - placeholder={t("auth:login.emailPlaceholder")} - /> - {errors?.email && } -
- -
- - setFormData({ ...formData, password: e.target.value })} - required - placeholder={t("auth:login.passwordPlaceholder")} - /> - {errors?.password && } -
- -
- - {t("auth:login.forgotPassword")} - -
- - -
- -
-
-
-
-
- - {t("auth:common.orContinue")} - -
-
- - - -

- {t("auth:login.noAccount")}{" "} +

+ setFormData({ ...formData, email })} + onPasswordChange={(password: string) => setFormData({ ...formData, password })} + onSubmit={onSubmit} + submitLabel={isPending ? t("auth:common.connecting") : t("auth:login.loginButton")} + emailLabel={`${t("common:labels.email")} *`} + passwordLabel={`${t("common:labels.password")} *`} + emailPlaceholder={t("auth:login.emailPlaceholder")} + passwordPlaceholder={t("auth:login.passwordPlaceholder")} + emailError={errors?.email} + passwordError={errors?.password} + extraContent={ +
- {t("auth:login.signupLink")} + {t("auth:login.forgotPassword")} -

+
+ } + /> + +
+
+
+
+
+ + {t("auth:common.orContinue")} +
+ + + +

+ {t("auth:login.noAccount")}{" "} + + {t("auth:login.signupLink")} + +

-
+ ); } diff --git a/apps/main/src/pages/reset-password.test.tsx b/apps/main/src/pages/reset-password.test.tsx index beddf74..1e07af5 100644 --- a/apps/main/src/pages/reset-password.test.tsx +++ b/apps/main/src/pages/reset-password.test.tsx @@ -16,6 +16,7 @@ describe("ResetPasswordPage", () => { it("renders form with email input", () => { renderWithProviders(); + expect(screen.getByTestId("auth-card-shell")).toBeInTheDocument(); expect(screen.getByText(/forgot your password/i)).toBeInTheDocument(); expect(screen.getByLabelText(/email/i)).toBeInTheDocument(); expect(screen.getByRole("button", { name: /send reset link/i })).toBeInTheDocument(); diff --git a/apps/main/src/pages/reset-password.tsx b/apps/main/src/pages/reset-password.tsx index 9633d68..acc4a75 100644 --- a/apps/main/src/pages/reset-password.tsx +++ b/apps/main/src/pages/reset-password.tsx @@ -1,13 +1,13 @@ +import { AuthCardShell, AuthInfoBanner } from "@xtablo/auth-ui"; import { toast } from "@xtablo/shared"; import { Button } from "@xtablo/ui/components/button"; import { Input } from "@xtablo/ui/components/input"; import { Label } from "@xtablo/ui/components/label"; import { Text } from "@xtablo/ui/components/typography"; -import { AlertCircle, CheckCircle2, Loader2Icon, MailIcon } from "lucide-react"; +import { CheckCircle2, Loader2Icon, MailIcon } from "lucide-react"; import { useState } from "react"; import { useTranslation } from "react-i18next"; import { Link, useNavigate } from "react-router-dom"; -import { twMerge } from "tailwind-merge"; import { supabase } from "../lib/supabase"; export function ResetPasswordPage() { @@ -49,113 +49,83 @@ export function ResetPasswordPage() { if (isSubmitted) { return ( -
navigate("/login")} + {t("resetPassword.checkInbox", { email })}} + onBackdropClick={() => navigate("/login")} > -
e.stopPropagation()} - > -
-
-
- -
+
+
+
+
-
-

{t("resetPassword.emailSent")}

- - {t("resetPassword.checkInbox", { email })} - -
-
-
- - - {t("resetPassword.emailInstructions")} - -
-
- - -
+ + + + + +
-
+ ); } return ( -
navigate("/login")} + {t("resetPassword.description")}} + onBackdropClick={() => navigate("/login")} > -
e.stopPropagation()} - > -
-
-

{t("resetPassword.title")}

- {t("resetPassword.description")} +
+ {error ? : null} + +
+
+ + setEmail(e.target.value)} + placeholder={t("resetPassword.emailPlaceholder")} + required + disabled={isPending} + className="transition-opacity disabled:opacity-50" + />
- {error && ( -
-
- - {error} -
-
- )} + +
-
-
- - setEmail(e.target.value)} - placeholder={t("resetPassword.emailPlaceholder")} - required - disabled={isPending} - className="transition-opacity disabled:opacity-50" - /> -
- - -
- -

- - {t("resetPassword.backToLogin")} - -

+
+
+ + + {t("resetPassword.emailInstructions")} + +
+ +

+ + {t("resetPassword.backToLogin")} + +

-
+ ); } diff --git a/apps/main/src/pages/tablo-details.layout.test.tsx b/apps/main/src/pages/tablo-details.layout.test.tsx index e30a059..ec1ace7 100644 --- a/apps/main/src/pages/tablo-details.layout.test.tsx +++ b/apps/main/src/pages/tablo-details.layout.test.tsx @@ -406,7 +406,7 @@ describe("TabloDetailsPage overview layout", () => { expect(screen.getByRole("button", { name: "Modifier la mise en page" })).toBeInTheDocument(); }); - it("uses the standard email invite UI in the share dialog", async () => { + it("uses the client password invite UI in the share dialog", async () => { const user = userEvent.setup(); renderWithProviders(, { @@ -416,9 +416,10 @@ describe("TabloDetailsPage overview layout", () => { await user.click(screen.getByRole("button", { name: "Inviter" })); - expect(screen.getByText("Inviter un utilisateur")).toBeInTheDocument(); - expect(screen.getByPlaceholderText("Email de l'utilisateur à inviter")).toBeInTheDocument(); - expect(screen.queryByText("Accès client")).not.toBeInTheDocument(); - expect(screen.queryByRole("button", { name: "Envoyer le lien" })).not.toBeInTheDocument(); + expect(screen.getByText("Accès client")).toBeInTheDocument(); + expect(screen.getByPlaceholderText("Email du client")).toBeInTheDocument(); + expect(screen.getByText(/définir son mot de passe/i)).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Envoyer l'invitation" })).toBeInTheDocument(); + expect(screen.queryByText("Inviter un utilisateur")).not.toBeInTheDocument(); }); }); diff --git a/apps/main/src/pages/tablo-details.tsx b/apps/main/src/pages/tablo-details.tsx index 4816bb3..a6db9de 100644 --- a/apps/main/src/pages/tablo-details.tsx +++ b/apps/main/src/pages/tablo-details.tsx @@ -86,8 +86,7 @@ const TAB_SECTIONS: TabSection[] = [ "roadmap", ]; -// Temporary rollback until the client portal invite flow is ready to be used again. -const USE_CLIENT_MAGIC_LINK_INVITES = false; +const USE_CLIENT_PASSWORD_INVITES = true; // ─── Page ───────────────────────────────────────────────────────────────────── @@ -564,12 +563,13 @@ export const TabloDetailsPage = () => { {/* Separator */}
- {USE_CLIENT_MAGIC_LINK_INVITES ? ( + {USE_CLIENT_PASSWORD_INVITES ? ( <>

Accès client

- Invitez des clients externes via un lien magique + Le client recevra un email pour définir son mot de passe ou, s'il a déjà + un compte, une notification d'accès directe à ce tablo.

@@ -598,7 +598,7 @@ export const TabloDetailsPage = () => { }} disabled={!isEmailValid(clientInviteEmail)} > - Envoyer le lien + Envoyer l'invitation )}
diff --git a/apps/main/src/providers/UserStoreProvider.test.tsx b/apps/main/src/providers/UserStoreProvider.test.tsx index 7f7e908..84b9bb2 100644 --- a/apps/main/src/providers/UserStoreProvider.test.tsx +++ b/apps/main/src/providers/UserStoreProvider.test.tsx @@ -63,6 +63,7 @@ describe("TestUserStoreProvider", () => { first_name: null, is_temporary: false, is_client: false, + client_onboarded_at: null, last_name: null, short_user_id: "short-id", last_signed_in: null, diff --git a/apps/main/src/utils/testHelpers.tsx b/apps/main/src/utils/testHelpers.tsx index f370ba2..c3a4cab 100644 --- a/apps/main/src/utils/testHelpers.tsx +++ b/apps/main/src/utils/testHelpers.tsx @@ -19,6 +19,7 @@ const defaultUser = { avatar_url: "https://example.com/avatar.jpg", is_temporary: false, is_client: false, + client_onboarded_at: null, last_signed_in: null, plan: "none" as const, created_at: new Date().toISOString(), diff --git a/apps/main/tsconfig.app.json b/apps/main/tsconfig.app.json index b633f54..5b1c16f 100644 --- a/apps/main/tsconfig.app.json +++ b/apps/main/tsconfig.app.json @@ -27,6 +27,8 @@ "paths": { "*": ["./*"], "@ui/*": ["./src/*"], + "@xtablo/auth-ui": ["../../packages/auth-ui/src"], + "@xtablo/auth-ui/*": ["../../packages/auth-ui/src/*"], "@xtablo/ui/*": ["../../packages/ui/src/*"] } }, diff --git a/docs/superpowers/plans/2026-04-18-client-password-invite-flow.md b/docs/superpowers/plans/2026-04-18-client-password-invite-flow.md new file mode 100644 index 0000000..733f66e --- /dev/null +++ b/docs/superpowers/plans/2026-04-18-client-password-invite-flow.md @@ -0,0 +1,626 @@ +# Client Password Invite Flow Implementation Plan + +> **For agentic workers:** REQUIRED: Use superpowers:subagent-driven-development (if subagents available) or superpowers:executing-plans to implement this plan. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Replace the client magic-link callback flow with one-time password setup plus normal email/password login in `apps/clients`, while keeping client users restricted to the client portal. + +**Architecture:** Keep Supabase Auth as the identity provider, but move invite lifecycle decisions into the API. The backend creates or reuses one client account per email, then branches between an onboarding email with a one-time setup token and an access-notification email for already-onboarded clients. On the frontend, extract the main login visual shell into a shared auth UI surface, add client login/set-password/reset routes, and redirect protected client routes through login with destination resume. + +**Tech Stack:** Hono API, Supabase Auth, React 19, React Router, TanStack Query, Tailwind CSS v4, pnpm workspaces, Vitest. + +**Spec:** `docs/superpowers/specs/2026-04-18-client-password-invite-flow-design.md` + +--- + +## File Structure + +### New files + +**Database** +- `supabase/migrations/20260418110000_client_password_invites.sql` — replaces callback-oriented invite semantics with setup-token lifecycle fields and client-only auth metadata + +**Shared auth UI** +- `packages/auth-ui/package.json` — shared auth UI package manifest if no existing package is a clean fit +- `packages/auth-ui/tsconfig.json` — package tsconfig +- `packages/auth-ui/src/index.ts` — barrel exports +- `packages/auth-ui/src/AuthCardShell.tsx` — shared auth page background, card shell, logo, theme toggle, and content slot +- `packages/auth-ui/src/AuthEmailPasswordForm.tsx` — shared email/password form layout with error and loading states +- `packages/auth-ui/src/AuthInfoBanner.tsx` — shared inline success/error/info banner component used by login/reset/setup screens + +**Client auth pages** +- `apps/clients/src/pages/LoginPage.tsx` — client login screen using shared auth UI +- `apps/clients/src/pages/ResetPasswordPage.tsx` — client forgot-password page +- `apps/clients/src/pages/SetPasswordPage.tsx` — one-time invite setup screen +- `apps/clients/src/pages/LoginPage.test.tsx` +- `apps/clients/src/pages/ResetPasswordPage.test.tsx` +- `apps/clients/src/pages/SetPasswordPage.test.tsx` +- `apps/clients/src/components/ClientAuthGate.tsx` — preserves intended route and redirects unauthenticated users to login + +**API tests** +- No brand-new top-level test files required if the current route tests remain focused; extend: + - `apps/api/src/__tests__/routes/clientInvites.test.ts` + - `apps/api/src/__tests__/middlewares/middlewares.test.ts` + +### Modified files + +**API** +- `apps/api/src/routers/clientInvites.ts` — replace callback accept flow with setup-token create/validate/complete flow plus access-notification branch +- `apps/api/src/helpers/helpers.ts` — split current `createClientUser()` into clearer helpers for create/reuse account, detect onboarding state, and grant tablo access +- `apps/api/src/routers/index.ts` or the file that mounts `clientInvites` — ensure new routes are exposed +- `apps/api/src/middlewares/middleware.ts` — keep client users blocked from regular main-app routes; tighten behavior if needed +- `apps/api/src/__tests__/routes/clientInvites.test.ts` — cover onboarding vs notification, token validation, single use, cancellation, and app-boundary expectations +- `apps/api/src/__tests__/middlewares/middlewares.test.ts` — keep client-only users rejected by main-app middleware + +**Shared types** +- `packages/shared-types/src/database.types.ts` — add migration-driven type updates for `client_invites` and any new client auth columns + +**Main app frontend** +- `apps/main/src/pages/tablo-details.tsx` — update invite dialog submit flow and text for password-setup onboarding / access notification messaging +- `apps/main/src/pages/tablo-details.layout.test.tsx` — cover active magic-link invite UI copy and success states after the backend contract change +- `apps/main/src/pages/login.tsx` — consume shared auth shell/form pieces after extraction +- `apps/main/src/pages/reset-password.tsx` — consume shared auth shell/form pieces after extraction +- `apps/main/src/hooks/client_invites.ts` — adapt to the updated invite response shape if needed +- `apps/main/src/hooks/auth.ts` — optionally extract reusable login/reset behavior or keep app-specific logic while sharing visuals +- `apps/main/src/pages/login.test.tsx` +- `apps/main/src/pages/reset-password.test.tsx` + +**Client app frontend** +- `apps/clients/src/routes.tsx` — add `/login`, `/reset-password`, `/set-password`, and redirect handling; remove `/auth/callback` from primary flow +- `apps/clients/src/components/ClientLayout.tsx` — stop rendering dead-end unauthorized state and rely on auth gate redirect behavior +- `apps/clients/src/lib/supabase.ts` — no behavioral change expected, but verify redirect URLs and auth persistence assumptions +- `apps/clients/src/i18n.ts` — add auth namespaces reused from main or from shared locale files +- `apps/clients/src/main.tsx` — ensure new pages have needed providers +- `apps/clients/src/pages/AuthCallback.tsx` — remove or reduce to a temporary compatibility shim +- `apps/clients/src/pages/ClientTabloPage.tsx` +- `apps/clients/src/pages/ClientTabloListPage.tsx` +- `apps/clients/src/components/ClientLayout.test.tsx` +- `apps/clients/src/pages/ClientTabloPage.test.tsx` + +--- + +## Chunk 1: Database And API Invite Lifecycle + +### Task 1: Replace callback invite semantics with setup-token lifecycle + +**Files:** +- Create: `supabase/migrations/20260418110000_client_password_invites.sql` +- Modify: `packages/shared-types/src/database.types.ts` +- Test: `apps/api/src/__tests__/routes/clientInvites.test.ts` + +- [ ] **Step 1: Write the failing API test cases for the new lifecycle** + +Add or replace route tests in `apps/api/src/__tests__/routes/clientInvites.test.ts` for: + +```ts +it("creates a setup token for a first-time client invite", async () => {}); +it("does not create a setup token for an already-onboarded client", async () => {}); +it("rejects reused setup tokens", async () => {}); +it("rejects expired setup tokens", async () => {}); +it("marks cancelled pending setup tokens unusable", async () => {}); +``` + +Model the first-time case so it asserts: +- `client_invites.is_pending === true` +- a setup token exists +- `sendMail` is called with a setup URL targeting `clients.xtablo.com` + +Model the onboarded case so it asserts: +- no new setup token row is created +- `sendMail` is called with a direct `/tablo/:tabloId` URL + +- [ ] **Step 2: Run the targeted API tests to verify failure** + +Run: + +```bash +pnpm --filter @xtablo/api test -- clientInvites.test.ts +``` + +Expected: +- FAIL because the current router still creates magic-link callback invites and still exposes `/accept/:token` + +- [ ] **Step 3: Write the migration** + +In `supabase/migrations/20260418110000_client_password_invites.sql`, evolve `client_invites` for setup-token lifecycle. Prefer modifying the existing table shape over creating a second invite table. + +The migration should include the minimal schema required for: + +```sql +ALTER TABLE public.client_invites + ADD COLUMN IF NOT EXISTS invite_type text NOT NULL DEFAULT 'setup', + ADD COLUMN IF NOT EXISTS used_at timestamptz, + ADD COLUMN IF NOT EXISTS cancelled_at timestamptz, + ADD COLUMN IF NOT EXISTS setup_completed_at timestamptz; + +-- If the old callback flow uses invite_token generically, keep the column +-- but redefine its meaning as the setup token for setup invites. + +CREATE INDEX IF NOT EXISTS idx_client_invites_email_tablo_pending + ON public.client_invites (invited_email, tablo_id, is_pending); +``` + +Also add any client-account marker needed to distinguish: +- invited client users who have not completed password setup +- onboarded client users who already have password login + +Keep the schema minimal. Avoid adding fields that can be derived from auth state unless tests require them. + +- [ ] **Step 4: Update generated database types** + +Update `packages/shared-types/src/database.types.ts` to reflect the migration: +- new `client_invites` columns +- any added client-profile/account lifecycle columns + +Use the repo’s current type-generation practice if available; otherwise make the minimal manual edit and note it in the commit message. + +- [ ] **Step 5: Refactor helper boundaries before touching the router** + +In `apps/api/src/helpers/helpers.ts`, split the current client invite helper behavior into smaller pieces with one responsibility each: + +```ts +export async function findOrCreateClientAccount(...) {} +export async function ensureClientTabloAccess(...) {} +export async function hasCompletedClientOnboarding(...) {} +export async function createClientSetupInvite(...) {} +``` + +Do not keep all onboarding, auth-user creation, and tablo-access behavior fused into one large helper. + +- [ ] **Step 6: Replace callback endpoints with setup-token endpoints** + +In `apps/api/src/routers/clientInvites.ts`, change the route surface to: + +```ts +POST /client-invites/:tabloId +GET /client-invites/setup/:token +POST /client-invites/setup/:token +GET /client-invites/:tabloId/pending +DELETE /client-invites/:tabloId/:inviteId +``` + +Behavior: +- `POST /:tabloId` + - create/reuse client account + - ensure tablo access + - if account is not onboarded: create pending setup token + send setup email + - if account is onboarded: skip setup token + send access notification email to `/tablo/:tabloId` +- `GET /setup/:token` + - return token metadata for `SetPasswordPage` + - reject missing / expired / cancelled / already-used tokens +- `POST /setup/:token` + - validate token again + - set password for the client auth user + - mark invite consumed immediately + - return success payload for the frontend + +Remove callback-style `accept/:token` logic from the primary flow. + +- [ ] **Step 7: Keep `apps/main` protected from client-only users** + +In `apps/api/src/middlewares/middleware.ts`, verify that `regularUserCheck` or equivalent main-app guard rejects `is_client` users cleanly. If the current behavior is already correct, only tighten the tests and leave code untouched. + +Add or update targeted test coverage in `apps/api/src/__tests__/middlewares/middlewares.test.ts`: + +```ts +it("returns 401 for client-only users on main-app protected routes", async () => {}); +``` + +- [ ] **Step 8: Run API verification** + +Run: + +```bash +pnpm --filter @xtablo/api test -- clientInvites.test.ts middlewares.test.ts +pnpm --filter @xtablo/api typecheck +``` + +Expected: +- PASS for invite lifecycle and middleware protection coverage + +- [ ] **Step 9: Commit** + +```bash +git add supabase/migrations/20260418110000_client_password_invites.sql \ + packages/shared-types/src/database.types.ts \ + apps/api/src/helpers/helpers.ts \ + apps/api/src/routers/clientInvites.ts \ + apps/api/src/__tests__/routes/clientInvites.test.ts \ + apps/api/src/__tests__/middlewares/middlewares.test.ts \ + apps/api/src/middlewares/middleware.ts +git commit -m "feat(api): add client password setup invite flow" +``` + +--- + +## Chunk 2: Shared Auth UI Extraction + +### Task 2: Extract the main login visual shell into a shared package + +**Files:** +- Create: `packages/auth-ui/package.json` +- Create: `packages/auth-ui/tsconfig.json` +- Create: `packages/auth-ui/src/index.ts` +- Create: `packages/auth-ui/src/AuthCardShell.tsx` +- Create: `packages/auth-ui/src/AuthEmailPasswordForm.tsx` +- Create: `packages/auth-ui/src/AuthInfoBanner.tsx` +- Modify: `apps/main/src/pages/login.tsx` +- Modify: `apps/main/src/pages/reset-password.tsx` +- Test: `apps/main/src/pages/login.test.tsx` +- Test: `apps/main/src/pages/reset-password.test.tsx` + +- [ ] **Step 1: Write failing rendering tests around the shared auth shell contract** + +Before extracting, add or update tests that pin the current main auth page structure at the right level: + +```ts +it("renders the main login page through a reusable auth shell", async () => {}); +it("renders the reset-password page through the shared auth shell", async () => {}); +``` + +Assert only stable behavior: +- heading renders +- email/password fields render +- forgot-password link renders +- shared shell wrapper test id or landmark renders + +Do not snapshot the entire page. + +- [ ] **Step 2: Run the main auth tests to verify current coverage gap** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run src/pages/login.test.tsx src/pages/reset-password.test.tsx --mode dev +``` + +Expected: +- FAIL or insufficient coverage for the extraction seam + +- [ ] **Step 3: Extract presentation-only auth UI** + +Create `packages/auth-ui` and move only visual/auth-form composition into it. + +Recommended split: + +```tsx +// AuthCardShell.tsx +export function AuthCardShell(props: { + title: string; + children: React.ReactNode; + backHomeHref?: string; + footer?: React.ReactNode; +}) {} + +// AuthEmailPasswordForm.tsx +export function AuthEmailPasswordForm(props: { + email: string; + password: string; + onEmailChange: (value: string) => void; + onPasswordChange: (value: string) => void; + onSubmit: (e: React.FormEvent) => void; + isPending?: boolean; + emailError?: string; + passwordError?: string; + submitLabel: string; + forgotPasswordHref?: string; +}) {} +``` + +Keep: +- theme toggle +- background +- card framing +- logo block +- stable form spacing and typography + +Out of scope for the shared package: +- actual Supabase mutations +- route-specific navigation +- Google login wiring +- signup flow behavior + +- [ ] **Step 4: Refactor main login and reset pages onto the shared auth UI** + +Update: +- `apps/main/src/pages/login.tsx` +- `apps/main/src/pages/reset-password.tsx` + +Keep existing behavior intact while removing duplicated layout markup. + +- [ ] **Step 5: Run verification for main auth pages** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run src/pages/login.test.tsx src/pages/reset-password.test.tsx --mode dev +pnpm --filter @xtablo/main typecheck +pnpm --filter @xtablo/auth-ui typecheck +``` + +Expected: +- PASS with no behavior regression in main auth pages + +- [ ] **Step 6: Commit** + +```bash +git add packages/auth-ui \ + apps/main/src/pages/login.tsx \ + apps/main/src/pages/reset-password.tsx \ + apps/main/src/pages/login.test.tsx \ + apps/main/src/pages/reset-password.test.tsx +git commit -m "refactor(auth): extract shared auth ui" +``` + +--- + +## Chunk 3: Client Portal Auth Routes And Redirect Flow + +### Task 3: Add client login, reset-password, set-password, and redirect memory + +**Files:** +- Create: `apps/clients/src/components/ClientAuthGate.tsx` +- Create: `apps/clients/src/pages/LoginPage.tsx` +- Create: `apps/clients/src/pages/ResetPasswordPage.tsx` +- Create: `apps/clients/src/pages/SetPasswordPage.tsx` +- Modify: `apps/clients/src/routes.tsx` +- Modify: `apps/clients/src/components/ClientLayout.tsx` +- Modify: `apps/clients/src/pages/AuthCallback.tsx` +- Modify: `apps/clients/src/i18n.ts` +- Test: `apps/clients/src/pages/LoginPage.test.tsx` +- Test: `apps/clients/src/pages/ResetPasswordPage.test.tsx` +- Test: `apps/clients/src/pages/SetPasswordPage.test.tsx` +- Test: `apps/clients/src/components/ClientLayout.test.tsx` +- Test: `apps/clients/src/pages/ClientTabloPage.test.tsx` + +- [ ] **Step 1: Write failing client auth route tests** + +Add coverage for the new expected client behavior: + +```ts +it("redirects unauthenticated /tablo/:tabloId requests to /login and resumes after login", async () => {}); +it("renders the client login page with shared auth ui", async () => {}); +it("submits forgot-password from the client login flow", async () => {}); +it("renders an invalid-token state on the set-password page", async () => {}); +it("submits password setup once and rejects token reuse", async () => {}); +``` + +Prefer route-level tests with mocked Supabase/API behavior over isolated unit tests. + +- [ ] **Step 2: Run the client auth tests to verify failure** + +Run: + +```bash +pnpm --filter @xtablo/clients exec vitest run \ + src/components/ClientLayout.test.tsx \ + src/pages/ClientTabloPage.test.tsx \ + src/pages/LoginPage.test.tsx \ + src/pages/ResetPasswordPage.test.tsx \ + src/pages/SetPasswordPage.test.tsx \ + --mode dev +``` + +Expected: +- FAIL because `/login`, `/reset-password`, and `/set-password` do not exist and protected client routes do not redirect correctly + +- [ ] **Step 3: Add a client auth gate with redirect memory** + +Create `apps/clients/src/components/ClientAuthGate.tsx` with behavior like: + +```tsx +export function ClientAuthGate({ children }: { children: React.ReactNode }) { + // if no session: + // store current pathname + search in localStorage + // navigate("/login") + // else render children +} +``` + +Use a client-specific storage key such as: + +```ts +const CLIENT_REDIRECT_KEY = "clients.redirectUrl"; +``` + +Do not reuse the main app’s generic redirect key unless the semantics are already isolated per app. + +- [ ] **Step 4: Build the client login and reset pages on top of shared auth UI** + +Implement: +- `apps/clients/src/pages/LoginPage.tsx` +- `apps/clients/src/pages/ResetPasswordPage.tsx` + +Behavior: +- login via `supabase.auth.signInWithPassword` +- forgot-password via `supabase.auth.resetPasswordForEmail` +- no signup affordance +- successful login resumes `clients.redirectUrl` if present, otherwise `/` + +- [ ] **Step 5: Build the one-time set-password page** + +Implement `apps/clients/src/pages/SetPasswordPage.tsx`: +- read the token from the URL +- call `GET /api/v1/client-invites/setup/:token` on mount +- render clear invalid / expired / used states +- submit new password to `POST /api/v1/client-invites/setup/:token` +- after success, sign in the user and navigate to the granted destination + +If the API returns enough information to sign the user in directly, use it. If not, perform a normal `signInWithPassword` after successful setup using the freshly set password. + +- [ ] **Step 6: Update client routes and remove callback-first flow** + +In `apps/clients/src/routes.tsx`, move to: + +```tsx +} /> +} /> +} /> +}> + } /> + } /> + +``` + +Reduce `AuthCallback.tsx` to: +- temporary compatibility notice, or +- redirect to `/login` + +Do not leave it as the primary entry path. + +- [ ] **Step 7: Update client translations and copy** + +In `apps/clients/src/i18n.ts`, reuse the main auth namespace if practical. If not, add the minimal client auth keys needed without duplicating the entire namespace unnecessarily. + +Required copy states: +- login +- forgot password +- set password +- invalid token +- expired token +- already-used token +- access granted / password set success + +- [ ] **Step 8: Run client verification** + +Run: + +```bash +pnpm --filter @xtablo/clients exec vitest run \ + src/components/ClientLayout.test.tsx \ + src/pages/ClientTabloPage.test.tsx \ + src/pages/LoginPage.test.tsx \ + src/pages/ResetPasswordPage.test.tsx \ + src/pages/SetPasswordPage.test.tsx \ + --mode dev +pnpm --filter @xtablo/clients typecheck +``` + +Expected: +- PASS for login, reset-password, set-password, and redirect-resume flow + +- [ ] **Step 9: Commit** + +```bash +git add apps/clients/src/routes.tsx \ + apps/clients/src/components/ClientAuthGate.tsx \ + apps/clients/src/components/ClientLayout.tsx \ + apps/clients/src/pages/LoginPage.tsx \ + apps/clients/src/pages/ResetPasswordPage.tsx \ + apps/clients/src/pages/SetPasswordPage.tsx \ + apps/clients/src/pages/AuthCallback.tsx \ + apps/clients/src/i18n.ts \ + apps/clients/src/pages/LoginPage.test.tsx \ + apps/clients/src/pages/ResetPasswordPage.test.tsx \ + apps/clients/src/pages/SetPasswordPage.test.tsx \ + apps/clients/src/components/ClientLayout.test.tsx \ + apps/clients/src/pages/ClientTabloPage.test.tsx +git commit -m "feat(clients): add password auth onboarding flow" +``` + +--- + +## Chunk 4: Main Invite UI And Full Verification + +### Task 4: Update main-app invite UX to match the new backend contract + +**Files:** +- Modify: `apps/main/src/pages/tablo-details.tsx` +- Modify: `apps/main/src/hooks/client_invites.ts` +- Modify: `apps/main/src/pages/tablo-details.layout.test.tsx` + +- [ ] **Step 1: Write failing main invite flow tests** + +Extend `apps/main/src/pages/tablo-details.layout.test.tsx` with cases like: + +```ts +it("shows password-setup onboarding messaging for first-time client invites", async () => {}); +it("shows access-notification messaging for already-onboarded client invites", async () => {}); +``` + +Assert only the user-facing contract: +- client invite UI is visible +- email field submits +- success state reflects either setup email sent or access notification sent + +- [ ] **Step 2: Run the targeted main invite tests** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run src/pages/tablo-details.layout.test.tsx --mode dev +``` + +Expected: +- FAIL because current UI still assumes the callback-style invite flow + +- [ ] **Step 3: Update the main invite hook contract** + +In `apps/main/src/hooks/client_invites.ts`, align the mutation response typing with the new API payload, for example: + +```ts +type ClientInviteResponse = { + success: true; + inviteMode: "setup" | "notification"; +}; +``` + +Avoid frontend logic that infers email mode from copy alone. + +- [ ] **Step 4: Update share-dialog copy and success handling** + +In `apps/main/src/pages/tablo-details.tsx`, keep the client invite UI active, but change the submission/success states to match the new flow: +- first-time invite: explain that the client will receive a password-setup email +- existing client: explain that the client will receive a direct access notification + +Do not reintroduce the old standard-email collaborator invite UI for this flow. + +- [ ] **Step 5: Run focused frontend verification** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run \ + src/pages/tablo-details.layout.test.tsx \ + src/pages/login.test.tsx \ + src/pages/reset-password.test.tsx \ + --mode dev +pnpm --filter @xtablo/main typecheck +``` + +Expected: +- PASS for share dialog copy, login page extraction, and reset page extraction + +- [ ] **Step 6: Run cross-app final verification** + +Run: + +```bash +pnpm --filter @xtablo/api test -- clientInvites.test.ts middlewares.test.ts +pnpm --filter @xtablo/api typecheck +pnpm --filter @xtablo/auth-ui typecheck +pnpm --filter @xtablo/main typecheck +pnpm --filter @xtablo/clients typecheck +pnpm --filter @xtablo/main exec vitest run src/pages/tablo-details.layout.test.tsx src/pages/login.test.tsx src/pages/reset-password.test.tsx --mode dev +pnpm --filter @xtablo/clients exec vitest run src/components/ClientLayout.test.tsx src/pages/ClientTabloPage.test.tsx src/pages/LoginPage.test.tsx src/pages/ResetPasswordPage.test.tsx src/pages/SetPasswordPage.test.tsx --mode dev +``` + +If the API tests require local Supabase migrations first, run the repo-standard migration command before rerunning tests and record that in the implementation notes. + +- [ ] **Step 7: Commit** + +```bash +git add apps/main/src/pages/tablo-details.tsx \ + apps/main/src/hooks/client_invites.ts \ + apps/main/src/pages/tablo-details.layout.test.tsx +git commit -m "feat(main): update client invite onboarding messaging" +``` + +--- + +## Completion Notes + +- Keep commits small and aligned with the chunks above. +- Do not reintroduce permanent bearer links. +- Do not allow client-only users through `apps/main` guards, even if they authenticate successfully. +- Do not preserve `AuthCallback` as a hidden second primary flow; either remove it or make it an explicit compatibility dead-end. +- Prefer reusing the existing main auth translations where possible, but avoid coupling `apps/clients` directly to `apps/main` internals if extraction into a shared package is cleaner. diff --git a/packages/auth-ui/package.json b/packages/auth-ui/package.json new file mode 100644 index 0000000..7569c83 --- /dev/null +++ b/packages/auth-ui/package.json @@ -0,0 +1,32 @@ +{ + "name": "@xtablo/auth-ui", + "version": "0.0.0", + "private": true, + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "typecheck": "tsc --noEmit", + "lint": "biome check .", + "lint:fix": "biome check --write .", + "format": "biome format --write ." + }, + "dependencies": { + "@xtablo/shared": "workspace:*", + "@xtablo/ui": "workspace:*", + "lucide-react": "^0.460.0", + "react": "19.0.0", + "react-dom": "19.0.0", + "tailwind-merge": "^3.0.2" + }, + "devDependencies": { + "@biomejs/biome": "2.2.5", + "@types/react": "19.0.10", + "@types/react-dom": "19.0.4", + "typescript": "^5.7.0", + "vite": "^6.2.2" + } +} diff --git a/packages/auth-ui/src/AuthCardShell.tsx b/packages/auth-ui/src/AuthCardShell.tsx new file mode 100644 index 0000000..3baca34 --- /dev/null +++ b/packages/auth-ui/src/AuthCardShell.tsx @@ -0,0 +1,125 @@ +import { useTheme } from "@xtablo/shared/contexts/ThemeContext"; +import { Button } from "@xtablo/ui/components/button"; +import { MonitorIcon, MoonIcon, SunIcon } from "lucide-react"; +import type { CSSProperties, MouseEventHandler, ReactNode } from "react"; +import { twMerge } from "tailwind-merge"; + +type AuthCardShellProps = { + title: string; + description?: ReactNode; + children: ReactNode; + background?: ReactNode; + topLeft?: ReactNode; + showThemeToggle?: boolean; + onBackdropClick?: () => void; + wrapperClassName?: string; + wrapperStyle?: CSSProperties; + onWrapperMouseMove?: MouseEventHandler; + onWrapperMouseLeave?: () => void; + isHovered?: boolean; + cardClassName?: string; +}; + +export function AuthCardShell({ + title, + description, + children, + background, + topLeft, + showThemeToggle = false, + onBackdropClick, + wrapperClassName, + wrapperStyle, + onWrapperMouseMove, + onWrapperMouseLeave, + isHovered = false, + cardClassName, +}: AuthCardShellProps) { + const { theme, setTheme } = useTheme(); + + const toggleTheme = () => { + if (theme === "light") { + setTheme("dark"); + } else if (theme === "dark") { + setTheme("system"); + } else { + setTheme("light"); + } + }; + + const themeIcon = + theme === "light" ? ( + + ) : theme === "dark" ? ( + + ) : ( + + ); + + return ( +
+ {background} + +
event.stopPropagation()} + > +
+ +
+ {topLeft || showThemeToggle ? ( +
+
{topLeft}
+ {showThemeToggle ? ( + + ) : null} +
+ ) : null} + +
+ Xtablo + Xtablo +
+ +
+

{title}

+ {description ?
{description}
: null} +
+ + {children} +
+
+
+ ); +} diff --git a/packages/auth-ui/src/AuthEmailPasswordForm.tsx b/packages/auth-ui/src/AuthEmailPasswordForm.tsx new file mode 100644 index 0000000..b97c1be --- /dev/null +++ b/packages/auth-ui/src/AuthEmailPasswordForm.tsx @@ -0,0 +1,83 @@ +import { Button } from "@xtablo/ui/components/button"; +import { FieldError } from "@xtablo/ui/components/field"; +import { Input } from "@xtablo/ui/components/input"; +import { Label } from "@xtablo/ui/components/label"; +import type { ReactNode } from "react"; + +type AuthEmailPasswordFormProps = { + email: string; + password: string; + onEmailChange: (value: string) => void; + onPasswordChange: (value: string) => void; + onSubmit: (event: React.FormEvent) => void; + submitLabel: string; + emailLabel: string; + passwordLabel: string; + emailPlaceholder: string; + passwordPlaceholder: string; + emailError?: string; + passwordError?: string; + isPending?: boolean; + footer?: ReactNode; + extraContent?: ReactNode; +}; + +export function AuthEmailPasswordForm({ + email, + password, + onEmailChange, + onPasswordChange, + onSubmit, + submitLabel, + emailLabel, + passwordLabel, + emailPlaceholder, + passwordPlaceholder, + emailError, + passwordError, + isPending = false, + footer, + extraContent, +}: AuthEmailPasswordFormProps) { + return ( +
+
+ + onEmailChange(event.target.value)} + required + placeholder={emailPlaceholder} + disabled={isPending} + /> + {emailError ? : null} +
+ +
+ + onPasswordChange(event.target.value)} + required + placeholder={passwordPlaceholder} + disabled={isPending} + /> + {passwordError ? : null} +
+ + {extraContent} + + + + {footer} +
+ ); +} diff --git a/packages/auth-ui/src/AuthInfoBanner.tsx b/packages/auth-ui/src/AuthInfoBanner.tsx new file mode 100644 index 0000000..a5554d2 --- /dev/null +++ b/packages/auth-ui/src/AuthInfoBanner.tsx @@ -0,0 +1,33 @@ +import { AlertCircle, CheckCircle2, InfoIcon } from "lucide-react"; +import { twMerge } from "tailwind-merge"; + +type AuthInfoBannerProps = { + message: string; + variant: "error" | "info" | "success"; +}; + +const variantStyles: Record = { + error: "bg-red-50 text-red-800 border-red-200 dark:bg-red-950/20 dark:text-red-200 dark:border-red-800", + info: "bg-blue-50 text-blue-800 border-blue-200 dark:bg-blue-950/20 dark:text-blue-200 dark:border-blue-800", + success: + "bg-green-50 text-green-800 border-green-200 dark:bg-green-950/20 dark:text-green-200 dark:border-green-800", +}; + +const variantIcon = { + error: AlertCircle, + info: InfoIcon, + success: CheckCircle2, +} satisfies Record; + +export function AuthInfoBanner({ message, variant }: AuthInfoBannerProps) { + const Icon = variantIcon[variant]; + + return ( +
+
+ +

{message}

+
+
+ ); +} diff --git a/packages/auth-ui/src/index.ts b/packages/auth-ui/src/index.ts new file mode 100644 index 0000000..5c6d6f3 --- /dev/null +++ b/packages/auth-ui/src/index.ts @@ -0,0 +1,3 @@ +export { AuthCardShell } from "./AuthCardShell"; +export { AuthEmailPasswordForm } from "./AuthEmailPasswordForm"; +export { AuthInfoBanner } from "./AuthInfoBanner"; diff --git a/packages/auth-ui/tsconfig.json b/packages/auth-ui/tsconfig.json new file mode 100644 index 0000000..4976ebd --- /dev/null +++ b/packages/auth-ui/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "target": "ES2020", + "useDefineForClassFields": true, + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "module": "ESNext", + "skipLibCheck": true, + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "jsx": "react-jsx", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "baseUrl": ".", + "paths": { + "@xtablo/ui": ["../ui/src"], + "@xtablo/ui/*": ["../ui/src/*"], + "@xtablo/shared": ["../shared/src"], + "@xtablo/shared/*": ["../shared/src/*"] + } + }, + "include": ["src", "src/vite-env.d.ts"] +} diff --git a/packages/shared-types/src/database.types.ts b/packages/shared-types/src/database.types.ts index 3ab03a5..66b30a0 100644 --- a/packages/shared-types/src/database.types.ts +++ b/packages/shared-types/src/database.types.ts @@ -83,31 +83,43 @@ export type Database = { created_at: string; expires_at: string; id: number; + invite_type: string; invited_by: string; invited_email: string; invite_token: string; is_pending: boolean; + cancelled_at: string | null; + setup_completed_at: string | null; tablo_id: string; + used_at: string | null; }; Insert: { created_at?: string; expires_at?: string; id?: number; + invite_type?: string; invited_by: string; invited_email: string; invite_token: string; is_pending?: boolean; + cancelled_at?: string | null; + setup_completed_at?: string | null; tablo_id: string; + used_at?: string | null; }; Update: { created_at?: string; expires_at?: string; id?: number; + invite_type?: string; invited_by?: string; invited_email?: string; invite_token?: string; is_pending?: boolean; + cancelled_at?: string | null; + setup_completed_at?: string | null; tablo_id?: string; + used_at?: string | null; }; Relationships: [ { @@ -429,6 +441,7 @@ export type Database = { profiles: { Row: { avatar_url: string | null; + client_onboarded_at: string | null; created_at: string | null; email: string | null; first_name: string | null; @@ -443,6 +456,7 @@ export type Database = { }; Insert: { avatar_url?: string | null; + client_onboarded_at?: string | null; created_at?: string | null; email?: string | null; first_name?: string | null; @@ -457,6 +471,7 @@ export type Database = { }; Update: { avatar_url?: string | null; + client_onboarded_at?: string | null; created_at?: string | null; email?: string | null; first_name?: string | null; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e797dbd..240d4f4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -145,6 +145,9 @@ importers: '@tanstack/react-query': specifier: ^5.69.0 version: 5.90.5(react@19.0.0) + '@xtablo/auth-ui': + specifier: workspace:* + version: link:../../packages/auth-ui '@xtablo/chat-ui': specifier: workspace:* version: link:../../packages/chat-ui @@ -405,6 +408,9 @@ importers: '@typescript/native-preview': specifier: 7.0.0-dev.20251010.1 version: 7.0.0-dev.20251010.1 + '@xtablo/auth-ui': + specifier: workspace:* + version: link:../../packages/auth-ui '@xtablo/chat-ui': specifier: workspace:* version: link:../../packages/chat-ui @@ -629,6 +635,43 @@ importers: specifier: ^4.24.3 version: 4.44.0(@cloudflare/workers-types@4.20260411.1) + packages/auth-ui: + dependencies: + '@xtablo/shared': + specifier: workspace:* + version: link:../shared + '@xtablo/ui': + specifier: workspace:* + version: link:../ui + lucide-react: + specifier: ^0.460.0 + version: 0.460.0(react@19.0.0) + react: + specifier: 19.0.0 + version: 19.0.0 + react-dom: + specifier: 19.0.0 + version: 19.0.0(react@19.0.0) + tailwind-merge: + specifier: ^3.0.2 + version: 3.3.1 + devDependencies: + '@biomejs/biome': + specifier: 2.2.5 + version: 2.2.5 + '@types/react': + specifier: 19.0.10 + version: 19.0.10 + '@types/react-dom': + specifier: 19.0.4 + version: 19.0.4(@types/react@19.0.10) + typescript: + specifier: ^5.7.0 + version: 5.9.3 + vite: + specifier: ^6.2.2 + version: 6.4.1(@types/node@22.18.12)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6) + packages/chat-ui: dependencies: '@xtablo/shared': diff --git a/supabase/migrations/20260418110000_client_password_invites.sql b/supabase/migrations/20260418110000_client_password_invites.sql new file mode 100644 index 0000000..0746c80 --- /dev/null +++ b/supabase/migrations/20260418110000_client_password_invites.sql @@ -0,0 +1,27 @@ +ALTER TABLE public.profiles + ADD COLUMN IF NOT EXISTS client_onboarded_at timestamptz; + +COMMENT ON COLUMN public.profiles.client_onboarded_at IS + 'Timestamp when a client portal user completed their one-time password setup.'; + +ALTER TABLE public.client_invites + ADD COLUMN IF NOT EXISTS invite_type text NOT NULL DEFAULT 'setup', + ADD COLUMN IF NOT EXISTS used_at timestamptz, + ADD COLUMN IF NOT EXISTS cancelled_at timestamptz, + ADD COLUMN IF NOT EXISTS setup_completed_at timestamptz; + +COMMENT ON COLUMN public.client_invites.invite_type IS + 'Invite lifecycle type. setup = first-time password onboarding token.'; +COMMENT ON COLUMN public.client_invites.used_at IS + 'Timestamp when the setup token was consumed.'; +COMMENT ON COLUMN public.client_invites.cancelled_at IS + 'Timestamp when a pending setup invite was cancelled.'; +COMMENT ON COLUMN public.client_invites.setup_completed_at IS + 'Timestamp when password setup completed successfully.'; + +CREATE UNIQUE INDEX IF NOT EXISTS idx_client_invites_pending_setup_email_tablo + ON public.client_invites (tablo_id, invited_email) + WHERE is_pending = true AND invite_type = 'setup'; + +CREATE INDEX IF NOT EXISTS idx_client_invites_token_pending + ON public.client_invites (invite_token, is_pending); From fa12aa34a5c56ae0c5977fd10250aa04c169dd0c Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sat, 18 Apr 2026 11:39:38 +0200 Subject: [PATCH 38/75] fix: expose public client setup routes --- apps/api/src/routers/index.ts | 4 ++++ apps/api/src/routers/maybeAuthRouter.ts | 2 -- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/apps/api/src/routers/index.ts b/apps/api/src/routers/index.ts index 1ca996e..4c7928c 100644 --- a/apps/api/src/routers/index.ts +++ b/apps/api/src/routers/index.ts @@ -3,6 +3,7 @@ import type { AppConfig } from "../config.js"; import { MiddlewareManager } from "../middlewares/middleware.js"; import type { BaseEnv } from "../types/app.types.js"; import { getAuthenticatedRouter } from "./authRouter.js"; +import { getPublicClientInvitesRouter } from "./clientInvites.js"; import { getMaybeAuthenticatedRouter } from "./maybeAuthRouter.js"; import { getPublicRouter } from "./public.js"; import { getStripeWebhookRouter } from "./stripe.js"; @@ -31,6 +32,9 @@ export const getMainRouter = (config: AppConfig) => { // webhooks mainRouter.route("/stripe-webhook", getStripeWebhookRouter()); + // public client onboarding routes + mainRouter.route("/client-invites", getPublicClientInvitesRouter()); + // maybe authenticated routes (checked first to allow unauthenticated booking) mainRouter.route("/", getMaybeAuthenticatedRouter()); diff --git a/apps/api/src/routers/maybeAuthRouter.ts b/apps/api/src/routers/maybeAuthRouter.ts index b01a6c5..7da5c8e 100644 --- a/apps/api/src/routers/maybeAuthRouter.ts +++ b/apps/api/src/routers/maybeAuthRouter.ts @@ -1,7 +1,6 @@ import { Hono } from "hono"; import { MiddlewareManager } from "../middlewares/middleware.js"; import type { MaybeAuthEnv } from "../types/app.types.js"; -import { getPublicClientInvitesRouter } from "./clientInvites.js"; import { getBookingRouter } from "./invite.js"; export const getMaybeAuthenticatedRouter = () => { @@ -12,7 +11,6 @@ export const getMaybeAuthenticatedRouter = () => { maybeAuthenticated.use(middlewareManager.maybeAuthenticated); maybeAuthenticated.route("/book", getBookingRouter()); - maybeAuthenticated.route("/client-invites", getPublicClientInvitesRouter()); return maybeAuthenticated; }; From 4e6be584448db2b9a3a174126dd591401e58cd78 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sat, 18 Apr 2026 11:43:58 +0200 Subject: [PATCH 39/75] fix: load auth logos from assets host --- apps/clients/src/pages/LoginPage.test.tsx | 4 ++++ packages/auth-ui/src/AuthCardShell.tsx | 6 ++++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/apps/clients/src/pages/LoginPage.test.tsx b/apps/clients/src/pages/LoginPage.test.tsx index 425eac6..47f77d7 100644 --- a/apps/clients/src/pages/LoginPage.test.tsx +++ b/apps/clients/src/pages/LoginPage.test.tsx @@ -41,6 +41,10 @@ describe("LoginPage", () => { expect(screen.getByLabelText("Email")).toBeInTheDocument(); expect(screen.getByLabelText("Mot de passe")).toBeInTheDocument(); expect(screen.getByRole("button", { name: "Connexion" })).toBeInTheDocument(); + expect(screen.getAllByAltText("Xtablo")[0]).toHaveAttribute( + "src", + "https://assets.xtablo.com/logo_dark.png" + ); }); it("submits email/password login and resumes the stored redirect", async () => { diff --git a/packages/auth-ui/src/AuthCardShell.tsx b/packages/auth-ui/src/AuthCardShell.tsx index 3baca34..eaa1113 100644 --- a/packages/auth-ui/src/AuthCardShell.tsx +++ b/packages/auth-ui/src/AuthCardShell.tsx @@ -20,6 +20,8 @@ type AuthCardShellProps = { cardClassName?: string; }; +const XTABLO_ASSETS_BASE_URL = "https://assets.xtablo.com"; + export function AuthCardShell({ title, description, @@ -101,12 +103,12 @@ export function AuthCardShell({
Xtablo Xtablo From e568b342ade1f5cdac16e31abc8d4ed7ab7ded89 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sat, 18 Apr 2026 11:54:15 +0200 Subject: [PATCH 40/75] apps/clients target staging backend for now --- apps/clients/.env.production | 2 +- apps/clients/src/envProduction.test.ts | 13 +++++++++++++ apps/clients/tsconfig.tsbuildinfo | 2 +- 3 files changed, 15 insertions(+), 2 deletions(-) create mode 100644 apps/clients/src/envProduction.test.ts diff --git a/apps/clients/.env.production b/apps/clients/.env.production index f63a9df..7f10812 100644 --- a/apps/clients/.env.production +++ b/apps/clients/.env.production @@ -1,4 +1,4 @@ VITE_SUPABASE_URL=https://mhcafqvzbrrwvahpvvzd.supabase.co VITE_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im1oY2FmcXZ6YnJyd3ZhaHB2dnpkIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDEyNDEzMjEsImV4cCI6MjA1NjgxNzMyMX0.Otxn5BWCPD2ABlMM59hCgeur9Tf_Q7PndAbTkqXDPtM -VITE_API_URL=https://xablo-api-636270553187.europe-west1.run.app +VITE_API_URL=https://xablo-api-staging-636270553187.europe-west1.run.app diff --git a/apps/clients/src/envProduction.test.ts b/apps/clients/src/envProduction.test.ts new file mode 100644 index 0000000..a2481d2 --- /dev/null +++ b/apps/clients/src/envProduction.test.ts @@ -0,0 +1,13 @@ +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { describe, expect, it } from "vitest"; + +const productionEnv = readFileSync(resolve(process.cwd(), ".env.production"), "utf8"); + +describe("clients production env", () => { + it("points the API URL to staging while client portal testing is in progress", () => { + expect(productionEnv).toContain( + "VITE_API_URL=https://xablo-api-staging-636270553187.europe-west1.run.app" + ); + }); +}); diff --git a/apps/clients/tsconfig.tsbuildinfo b/apps/clients/tsconfig.tsbuildinfo index 6ab4cf9..ed49639 100644 --- a/apps/clients/tsconfig.tsbuildinfo +++ b/apps/clients/tsconfig.tsbuildinfo @@ -1 +1 @@ -{"root":["./src/app.tsx","./src/i18n.test.ts","./src/i18n.ts","./src/main.tsx","./src/maincss.test.ts","./src/routes.tsx","./src/setuptests.ts","./src/components/clientauthgate.tsx","./src/components/clientlayout.test.tsx","./src/components/clientlayout.tsx","./src/lib/supabase.ts","./src/pages/authcallback.tsx","./src/pages/clienttablolistpage.tsx","./src/pages/clienttablopage.test.tsx","./src/pages/clienttablopage.tsx","./src/pages/loginpage.test.tsx","./src/pages/loginpage.tsx","./src/pages/resetpasswordpage.test.tsx","./src/pages/resetpasswordpage.tsx","./src/pages/setpasswordpage.test.tsx","./src/pages/setpasswordpage.tsx","./src/test/testhelpers.test.tsx","./src/test/testhelpers.tsx"],"version":"5.9.3"} \ No newline at end of file +{"root":["./src/app.tsx","./src/envproduction.test.ts","./src/i18n.test.ts","./src/i18n.ts","./src/main.tsx","./src/maincss.test.ts","./src/routes.tsx","./src/setuptests.ts","./src/components/clientauthgate.tsx","./src/components/clientlayout.test.tsx","./src/components/clientlayout.tsx","./src/lib/supabase.ts","./src/pages/authcallback.tsx","./src/pages/clienttablolistpage.tsx","./src/pages/clienttablopage.test.tsx","./src/pages/clienttablopage.tsx","./src/pages/loginpage.test.tsx","./src/pages/loginpage.tsx","./src/pages/resetpasswordpage.test.tsx","./src/pages/resetpasswordpage.tsx","./src/pages/setpasswordpage.test.tsx","./src/pages/setpasswordpage.tsx","./src/test/testhelpers.test.tsx","./src/test/testhelpers.tsx"],"version":"5.9.3"} \ No newline at end of file From cc37bf2a7870d92e093589cc25d431ac855f94b1 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sat, 18 Apr 2026 12:04:55 +0200 Subject: [PATCH 41/75] Improve client portal --- .../src/pages/ClientTabloPage.test.tsx | 21 ++- apps/clients/src/pages/ClientTabloPage.tsx | 168 ++---------------- 2 files changed, 30 insertions(+), 159 deletions(-) diff --git a/apps/clients/src/pages/ClientTabloPage.test.tsx b/apps/clients/src/pages/ClientTabloPage.test.tsx index 8380d98..4055037 100644 --- a/apps/clients/src/pages/ClientTabloPage.test.tsx +++ b/apps/clients/src/pages/ClientTabloPage.test.tsx @@ -102,9 +102,24 @@ describe("ClientTabloPage parity shell", () => { expect(screen.getByText("Client Project")).toBeInTheDocument(); expect(screen.getAllByRole("button", { name: "Discussion" })).toHaveLength(2); - expect(screen.getByText("Rôle :")).toBeInTheDocument(); - expect(screen.getByText("Créé le :")).toBeInTheDocument(); - expect(screen.getByText("Progression :")).toBeInTheDocument(); + expect(screen.getAllByText("Rôle").length).toBeGreaterThan(0); + expect(screen.getAllByText("Créé le").length).toBeGreaterThan(0); + expect(screen.getAllByText("Progression").length).toBeGreaterThan(0); + }); + + it("keeps the shared main-app header labels even when the client locale is english", () => { + renderWithProviders(, { + route: "/tablo/tablo-1", + path: "/tablo/:tabloId", + language: "en", + }); + + expect(screen.getAllByText("Rôle").length).toBeGreaterThan(0); + expect(screen.getAllByText("Créé le").length).toBeGreaterThan(0); + expect(screen.getAllByText("Progression").length).toBeGreaterThan(0); + expect(screen.queryByText("Role")).not.toBeInTheDocument(); + expect(screen.queryByText("Created on")).not.toBeInTheDocument(); + expect(screen.queryByText("Progress")).not.toBeInTheDocument(); }); it("keeps client restrictions by hiding invite and layout-edit controls", () => { diff --git a/apps/clients/src/pages/ClientTabloPage.tsx b/apps/clients/src/pages/ClientTabloPage.tsx index 0f536d4..aaeb3eb 100644 --- a/apps/clients/src/pages/ClientTabloPage.tsx +++ b/apps/clients/src/pages/ClientTabloPage.tsx @@ -4,31 +4,15 @@ import { buildApi } from "@xtablo/shared"; import { useSession } from "@xtablo/shared/contexts/SessionContext"; import type { Etape, KanbanTask, TabloFolder, UserTablo } from "@xtablo/shared-types"; import { - CalendarIcon, - Compass, - Flame, FolderIcon, - Gem, - Heart, - KanbanIcon, - LayoutDashboardIcon, - Leaf, - ListChecksIcon, - MapIcon, - MessageCircleIcon, - Sparkles, - Star, - Sun, - Waves, - Zap, } from "lucide-react"; import { useState } from "react"; -import { useTranslation } from "react-i18next"; import { useParams } from "react-router-dom"; import { EtapesSection, RoadmapSection, - TabloDetailsShell, + SingleTabloView, + type SingleTabloTabId, TabloDiscussionSection, TabloEventsSection, TabloFilesSection, @@ -158,43 +142,6 @@ function useClientTabloFolders(tabloId: string, accessToken: string | undefined) }); } -function getTabloIcon(color: string | null | undefined) { - switch (color) { - case "bg-blue-500": - return Zap; - case "bg-green-500": - return Leaf; - case "bg-purple-500": - return Gem; - case "bg-red-500": - return Flame; - case "bg-yellow-500": - return Star; - case "bg-indigo-500": - return Compass; - case "bg-pink-500": - return Heart; - case "bg-teal-500": - return Waves; - case "bg-orange-500": - return Sun; - case "bg-cyan-500": - return Sparkles; - default: - return FolderIcon; - } -} - -function getTabloIconColor(color: string | null | undefined): string { - switch (color) { - case "bg-yellow-500": - case "bg-cyan-500": - return "text-gray-700"; - default: - return "text-white"; - } -} - function getStatusConfig(status: string) { switch (status) { case "in_progress": @@ -238,27 +185,12 @@ function getEtapeProgressStats(etapes: Etape[]) { }; } -// ─── Tabs ───────────────────────────────────────────────────────────────────── - -type TabId = "overview" | "etapes" | "tasks" | "files" | "discussion" | "events" | "roadmap"; - -const TABS: { id: TabId; label: string; icon: React.ElementType }[] = [ - { id: "overview", label: "Aperçu", icon: LayoutDashboardIcon }, - { id: "etapes", label: "Étapes", icon: ListChecksIcon }, - { id: "tasks", label: "Tâches", icon: KanbanIcon }, - { id: "files", label: "Fichiers", icon: FolderIcon }, - { id: "discussion", label: "Discussion", icon: MessageCircleIcon }, - { id: "events", label: "Événements", icon: CalendarIcon }, - { id: "roadmap", label: "Roadmap", icon: MapIcon }, -]; - // ─── Page ───────────────────────────────────────────────────────────────────── export function ClientTabloPage() { - const { t } = useTranslation(["pages", "chat"]); const { tabloId } = useParams<{ tabloId: string }>(); const { session } = useSession(); - const [activeTab, setActiveTab] = useState("overview"); + const [activeTab, setActiveTab] = useState("overview"); const accessToken = session?.access_token; const currentUserId = session?.user.id ?? ""; @@ -293,93 +225,17 @@ export function ClientTabloPage() { const { label: statusLabel, badgeClass } = getStatusConfig(tablo.status); const progress = getEtapeProgressStats(etapes); - const isDiscussionView = activeTab === "discussion"; - const TabloIcon = getTabloIcon(tablo.color); - const iconColor = getTabloIconColor(tablo.color); - - const metadata = [ - { - key: "role", - label: t("pages:tablo.details.roleLabel"), - value: ( - {t("pages:tablo.role.guest")} - ), - }, - { - key: "created-at", - label: t("pages:tablo.details.createdAtLabel"), - value: ( - - {new Intl.DateTimeFormat("fr-FR", { - year: "numeric", - month: "short", - day: "2-digit", - }).format(new Date(tablo.created_at))} - - ), - }, - { - key: "status", - label: t("pages:tablo.details.statusLabel"), - value: {statusLabel}, - }, - { - key: "progress", - label: t("pages:tablo.details.progressLabel"), - value: ( - <> -
-
-
-
- {progress.donePercentage}% - - ), - }, - ]; - - const headerVisual = ( -
- {tablo.image ? ( - {tablo.name} - ) : ( - - )} -
- ); - - const headerActions = ( - - ); return ( - setActiveTab(tabId as TabId)} - isDiscussionView={isDiscussionView} + onTabChange={setActiveTab} + discussionAction={{ kind: "button", onClick: () => setActiveTab("discussion") }} > {activeTab === "overview" && (
@@ -464,7 +320,7 @@ export function ClientTabloPage() {
Rôle
-
{t("pages:tablo.role.guest")}
+
Invité
@@ -540,6 +396,6 @@ export function ClientTabloPage() { onTaskStatusChange={() => {}} /> )} - + ); } From 68ad61b5a9765b0a99853f747db371714f7abcbc Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sat, 18 Apr 2026 13:05:21 +0200 Subject: [PATCH 42/75] Fix css not wired in clients --- .../clients/src/components/ClientLayout.test.tsx | 16 ++++++++++++---- apps/clients/src/components/ClientLayout.tsx | 8 +++++--- apps/clients/src/main.css | 2 ++ apps/clients/src/mainCss.test.ts | 4 +++- 4 files changed, 22 insertions(+), 8 deletions(-) diff --git a/apps/clients/src/components/ClientLayout.test.tsx b/apps/clients/src/components/ClientLayout.test.tsx index 709a0c0..4578431 100644 --- a/apps/clients/src/components/ClientLayout.test.tsx +++ b/apps/clients/src/components/ClientLayout.test.tsx @@ -5,7 +5,7 @@ import { renderWithProviders } from "../test/testHelpers"; import { ClientLayout } from "./ClientLayout"; describe("ClientLayout", () => { - it("uses the main app style header shell and centered content container", () => { + it("uses the main app style header shell and scrolling main viewport", () => { const { container } = renderWithProviders(); const header = container.querySelector("header"); @@ -18,9 +18,17 @@ describe("ClientLayout", () => { expect(headerInner).toHaveClass("mx-auto"); const main = container.querySelector("main"); - expect(main).toHaveClass("w-full"); - expect(main).toHaveClass("max-w-7xl"); - expect(main).toHaveClass("mx-auto"); + expect(main).toHaveClass("flex-1"); + expect(main).toHaveClass("overflow-auto"); + expect(main).not.toHaveClass("max-w-7xl"); + expect(main).not.toHaveClass("mx-auto"); + + const contentWrapper = main?.firstElementChild; + expect(contentWrapper).toHaveClass("mx-auto"); + expect(contentWrapper).toHaveClass("w-full"); + expect(contentWrapper).toHaveClass("max-w-7xl"); + expect(contentWrapper).toHaveClass("px-4"); + expect(contentWrapper).toHaveClass("sm:px-6"); }); it("redirects unauthenticated client routes to the login page", async () => { diff --git a/apps/clients/src/components/ClientLayout.tsx b/apps/clients/src/components/ClientLayout.tsx index 5ef32f4..a2079db 100644 --- a/apps/clients/src/components/ClientLayout.tsx +++ b/apps/clients/src/components/ClientLayout.tsx @@ -24,7 +24,7 @@ export function ClientLayout() { }; return ( -
+
Xtablo @@ -42,8 +42,10 @@ export function ClientLayout() {
-
- +
+
+ +
); diff --git a/apps/clients/src/main.css b/apps/clients/src/main.css index 2782768..104b0b7 100644 --- a/apps/clients/src/main.css +++ b/apps/clients/src/main.css @@ -2,6 +2,8 @@ @import "tw-animate-css"; @source "../../../packages/chat-ui/src/**/*.{ts,tsx}"; +@source "../../../packages/tablo-views/src/**/*.{ts,tsx}"; +@source "../../../packages/auth-ui/src/**/*.{ts,tsx}"; @custom-variant dark (&:is(.dark *)); diff --git a/apps/clients/src/mainCss.test.ts b/apps/clients/src/mainCss.test.ts index c150cce..a7f2a5c 100644 --- a/apps/clients/src/mainCss.test.ts +++ b/apps/clients/src/mainCss.test.ts @@ -5,8 +5,10 @@ import { describe, expect, it } from "vitest"; const mainCss = readFileSync(resolve(process.cwd(), "src/main.css"), "utf8"); describe("clients main.css", () => { - it("keeps the chat source and theme tokens aligned with the main app", () => { + it("keeps shared package sources and theme tokens aligned with the main app", () => { expect(mainCss).toContain('@source "../../../packages/chat-ui/src/**/*.{ts,tsx}";'); + expect(mainCss).toContain('@source "../../../packages/tablo-views/src/**/*.{ts,tsx}";'); + expect(mainCss).toContain('@source "../../../packages/auth-ui/src/**/*.{ts,tsx}";'); expect(mainCss).toContain("--navbar-background: rgb(249, 250, 251);"); expect(mainCss).toContain("--color-navbar-background: var(--navbar-background);"); expect(mainCss).toContain("--str-chat__own-message-bubble-color: #804eec;"); From a37c4ddf258f74185c9525be4d3725ce29c7be04 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sat, 18 Apr 2026 23:15:01 +0200 Subject: [PATCH 43/75] fix: allow deleting tablos with etapes --- apps/api/src/__tests__/routes/tablo.test.ts | 47 +++++++++++++++++++++ apps/api/src/routers/tablo.ts | 22 ++-------- 2 files changed, 50 insertions(+), 19 deletions(-) diff --git a/apps/api/src/__tests__/routes/tablo.test.ts b/apps/api/src/__tests__/routes/tablo.test.ts index 923fa38..a8fa3ea 100644 --- a/apps/api/src/__tests__/routes/tablo.test.ts +++ b/apps/api/src/__tests__/routes/tablo.test.ts @@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { createConfig } from "../../config.js"; import { MiddlewareManager } from "../../middlewares/middleware.js"; import { getMainRouter } from "../../routers/index.js"; +import { TEST_USERS } from "../fixtures/testData.js"; import type { TestUserData } from "../helpers/dbSetup.js"; import { getTestUser } from "../helpers/dbSetup.js"; @@ -109,6 +110,23 @@ describe("Tablo Endpoint", () => { ); }; + const signInAsTestUser = async (email: string, password: string) => { + const userClient = createClient(config.SUPABASE_URL, config.SUPABASE_SERVICE_ROLE_KEY, { + auth: { + autoRefreshToken: false, + persistSession: false, + }, + }); + + const { data, error } = await userClient.auth.signInWithPassword({ email, password }); + + if (error || !data.session) { + throw new Error(`Failed to sign in ${email}: ${error?.message ?? "missing session"}`); + } + + return userClient; + }; + // Helper function to get tablo members // biome-ignore lint/suspicious/noExplicitAny: testClient requires any for dynamic route access const getTabloMembersRequest = async (user: TestUserData, client: any, tabloId: string) => { @@ -415,6 +433,35 @@ describe("Tablo Endpoint", () => { expect(res.status).toBe(403); }); + + it("should allow owner to delete a tablo that contains etapes", async () => { + const createRes = await createTabloRequest(ownerUser, client, { + name: "Delete With Etape", + status: "todo", + color: "#804EEC", + }); + + expect(createRes.status).toBe(200); + const createData = await createRes.json(); + const createdTabloId = createData.tablo.id as string; + createdTabloIds.push(createdTabloId); + + const ownerClient = await signInAsTestUser(TEST_USERS.owner.email, TEST_USERS.owner.password); + const { error: createEtapeError } = await ownerClient.from("tasks").insert({ + tablo_id: createdTabloId, + title: "Delete me", + is_parent: true, + status: "todo", + }); + + expect(createEtapeError).toBeNull(); + + const res = await deleteTabloRequest(ownerUser, client, createdTabloId); + + expect(res.status).toBe(200); + const data = await res.json(); + expect(data.message).toBe("Tablo deleted successfully"); + }); }); describe("GET /tablos/members/:tablo_id - Get Tablo Members", () => { diff --git a/apps/api/src/routers/tablo.ts b/apps/api/src/routers/tablo.ts index 5ce02b7..105e21c 100644 --- a/apps/api/src/routers/tablo.ts +++ b/apps/api/src/routers/tablo.ts @@ -126,26 +126,10 @@ const deleteTablo = factory.createHandlers(async (c) => { const deletedAt = new Date().toISOString(); - const { error: tasksSoftDeleteError } = await supabase - .from("tasks") - .update({ deleted_at: deletedAt }) - .eq("tablo_id", id) - .is("deleted_at", null); + const { error: tasksDeleteError } = await supabase.from("tasks").delete().eq("tablo_id", id); - if (tasksSoftDeleteError) { - // Backward compatibility for environments where tasks.deleted_at is not migrated yet. - const isMissingDeletedAtColumn = - tasksSoftDeleteError.code === "42703" || - tasksSoftDeleteError.message?.toLowerCase().includes("deleted_at"); - - if (isMissingDeletedAtColumn) { - const { error: tasksDeleteError } = await supabase.from("tasks").delete().eq("tablo_id", id); - if (tasksDeleteError) { - return c.json({ error: tasksDeleteError.message }, 500); - } - } else { - return c.json({ error: tasksSoftDeleteError.message }, 500); - } + if (tasksDeleteError) { + return c.json({ error: tasksDeleteError.message }, 500); } const { error } = await supabase.from("tablos").update({ deleted_at: deletedAt }).eq("id", id); From 515a875e889ce5df34abc5c9867f3fcbf4c29428 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sat, 18 Apr 2026 23:15:01 +0200 Subject: [PATCH 44/75] fix: allow deleting tablos with etapes --- apps/api/src/__tests__/routes/tablo.test.ts | 47 +++++++++++++++++++++ apps/api/src/routers/tablo.ts | 22 ++-------- 2 files changed, 50 insertions(+), 19 deletions(-) diff --git a/apps/api/src/__tests__/routes/tablo.test.ts b/apps/api/src/__tests__/routes/tablo.test.ts index 923fa38..a8fa3ea 100644 --- a/apps/api/src/__tests__/routes/tablo.test.ts +++ b/apps/api/src/__tests__/routes/tablo.test.ts @@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { createConfig } from "../../config.js"; import { MiddlewareManager } from "../../middlewares/middleware.js"; import { getMainRouter } from "../../routers/index.js"; +import { TEST_USERS } from "../fixtures/testData.js"; import type { TestUserData } from "../helpers/dbSetup.js"; import { getTestUser } from "../helpers/dbSetup.js"; @@ -109,6 +110,23 @@ describe("Tablo Endpoint", () => { ); }; + const signInAsTestUser = async (email: string, password: string) => { + const userClient = createClient(config.SUPABASE_URL, config.SUPABASE_SERVICE_ROLE_KEY, { + auth: { + autoRefreshToken: false, + persistSession: false, + }, + }); + + const { data, error } = await userClient.auth.signInWithPassword({ email, password }); + + if (error || !data.session) { + throw new Error(`Failed to sign in ${email}: ${error?.message ?? "missing session"}`); + } + + return userClient; + }; + // Helper function to get tablo members // biome-ignore lint/suspicious/noExplicitAny: testClient requires any for dynamic route access const getTabloMembersRequest = async (user: TestUserData, client: any, tabloId: string) => { @@ -415,6 +433,35 @@ describe("Tablo Endpoint", () => { expect(res.status).toBe(403); }); + + it("should allow owner to delete a tablo that contains etapes", async () => { + const createRes = await createTabloRequest(ownerUser, client, { + name: "Delete With Etape", + status: "todo", + color: "#804EEC", + }); + + expect(createRes.status).toBe(200); + const createData = await createRes.json(); + const createdTabloId = createData.tablo.id as string; + createdTabloIds.push(createdTabloId); + + const ownerClient = await signInAsTestUser(TEST_USERS.owner.email, TEST_USERS.owner.password); + const { error: createEtapeError } = await ownerClient.from("tasks").insert({ + tablo_id: createdTabloId, + title: "Delete me", + is_parent: true, + status: "todo", + }); + + expect(createEtapeError).toBeNull(); + + const res = await deleteTabloRequest(ownerUser, client, createdTabloId); + + expect(res.status).toBe(200); + const data = await res.json(); + expect(data.message).toBe("Tablo deleted successfully"); + }); }); describe("GET /tablos/members/:tablo_id - Get Tablo Members", () => { diff --git a/apps/api/src/routers/tablo.ts b/apps/api/src/routers/tablo.ts index 5ce02b7..105e21c 100644 --- a/apps/api/src/routers/tablo.ts +++ b/apps/api/src/routers/tablo.ts @@ -126,26 +126,10 @@ const deleteTablo = factory.createHandlers(async (c) => { const deletedAt = new Date().toISOString(); - const { error: tasksSoftDeleteError } = await supabase - .from("tasks") - .update({ deleted_at: deletedAt }) - .eq("tablo_id", id) - .is("deleted_at", null); + const { error: tasksDeleteError } = await supabase.from("tasks").delete().eq("tablo_id", id); - if (tasksSoftDeleteError) { - // Backward compatibility for environments where tasks.deleted_at is not migrated yet. - const isMissingDeletedAtColumn = - tasksSoftDeleteError.code === "42703" || - tasksSoftDeleteError.message?.toLowerCase().includes("deleted_at"); - - if (isMissingDeletedAtColumn) { - const { error: tasksDeleteError } = await supabase.from("tasks").delete().eq("tablo_id", id); - if (tasksDeleteError) { - return c.json({ error: tasksDeleteError.message }, 500); - } - } else { - return c.json({ error: tasksSoftDeleteError.message }, 500); - } + if (tasksDeleteError) { + return c.json({ error: tasksDeleteError.message }, 500); } const { error } = await supabase.from("tablos").update({ deleted_at: deletedAt }).eq("id", id); From 46d2eb027775870fc108df46d69b0668f99bce20 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sun, 19 Apr 2026 09:51:35 +0200 Subject: [PATCH 45/75] fix: wire client portal interactions --- apps/chat-worker/src/index.ts | 3 +- apps/clients/.env.production | 3 + apps/clients/src/envProduction.test.ts | 4 +- .../src/pages/ClientTabloPage.test.tsx | 472 +++++++++++++++++- apps/clients/src/pages/ClientTabloPage.tsx | 314 +++++++++++- packages/tablo-views/src/EtapesSection.tsx | 17 +- .../tablo-views/src/TabloFilesSection.tsx | 130 ++--- 7 files changed, 865 insertions(+), 78 deletions(-) diff --git a/apps/chat-worker/src/index.ts b/apps/chat-worker/src/index.ts index 5eb2a65..6f3adee 100644 --- a/apps/chat-worker/src/index.ts +++ b/apps/chat-worker/src/index.ts @@ -10,12 +10,13 @@ export { ChatRoom }; const app = new Hono<{ Bindings: Env }>(); -// CORS — allow the main app origins +// CORS — allow the web app origins that embed chat app.use("*", cors({ origin: [ "http://localhost:5173", "https://app.xtablo.com", "https://app-staging.xtablo.com", + "https://clients.xtablo.com", ], allowHeaders: ["Authorization", "Content-Type"], allowMethods: ["GET", "POST", "OPTIONS"], diff --git a/apps/clients/.env.production b/apps/clients/.env.production index 7f10812..7c3ba26 100644 --- a/apps/clients/.env.production +++ b/apps/clients/.env.production @@ -1,4 +1,7 @@ VITE_SUPABASE_URL=https://mhcafqvzbrrwvahpvvzd.supabase.co VITE_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im1oY2FmcXZ6YnJyd3ZhaHB2dnpkIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDEyNDEzMjEsImV4cCI6MjA1NjgxNzMyMX0.Otxn5BWCPD2ABlMM59hCgeur9Tf_Q7PndAbTkqXDPtM +VITE_CHAT_WS_URL=wss://chat.xtablo.com +VITE_CHAT_API_URL=https://chat.xtablo.com + VITE_API_URL=https://xablo-api-staging-636270553187.europe-west1.run.app diff --git a/apps/clients/src/envProduction.test.ts b/apps/clients/src/envProduction.test.ts index a2481d2..90f3834 100644 --- a/apps/clients/src/envProduction.test.ts +++ b/apps/clients/src/envProduction.test.ts @@ -5,9 +5,11 @@ import { describe, expect, it } from "vitest"; const productionEnv = readFileSync(resolve(process.cwd(), ".env.production"), "utf8"); describe("clients production env", () => { - it("points the API URL to staging while client portal testing is in progress", () => { + it("points the API URL to staging while client portal testing is in progress and keeps chat endpoints configured", () => { expect(productionEnv).toContain( "VITE_API_URL=https://xablo-api-staging-636270553187.europe-west1.run.app" ); + expect(productionEnv).toContain("VITE_CHAT_API_URL=https://chat.xtablo.com"); + expect(productionEnv).toContain("VITE_CHAT_WS_URL=wss://chat.xtablo.com"); }); }); diff --git a/apps/clients/src/pages/ClientTabloPage.test.tsx b/apps/clients/src/pages/ClientTabloPage.test.tsx index 4055037..2f0dc18 100644 --- a/apps/clients/src/pages/ClientTabloPage.test.tsx +++ b/apps/clients/src/pages/ClientTabloPage.test.tsx @@ -1,14 +1,114 @@ -import { screen } from "@testing-library/react"; -import { describe, expect, it, vi } from "vitest"; +import { screen, waitFor } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import { renderWithProviders } from "../test/testHelpers"; import { ClientTabloPage } from "./ClientTabloPage"; +const { + apiGetMock, + apiPostMock, + apiPutMock, + apiDeleteMock, + updateTaskMock, + insertTaskMock, + deleteTaskMock, + supabaseFromMock, +} = vi.hoisted(() => { + const apiGetMock = vi.fn(async (url: string) => { + if (url.endsWith("/brief.pdf")) { + return { + status: 200, + data: { content: "test file content", contentType: "application/pdf" }, + }; + } + + return { status: 200, data: { folders: [] } }; + }); + const apiPostMock = vi.fn(async () => ({ + status: 200, + data: { + message: "ok", + fileName: "brief.pdf", + tabloId: "tablo-1", + folder: { id: "folder-1", name: "Livrable", description: "" }, + }, + })); + const apiPutMock = vi.fn(async () => ({ + status: 200, + data: { folder: { id: "folder-1", name: "Livrable mis à jour", description: "Desc" } }, + })); + const apiDeleteMock = vi.fn(async () => ({ status: 200, data: { message: "ok" } })); + const createUpdateBuilder = () => { + const builder = { + error: null as null, + eq: vi.fn(() => builder), + select: vi.fn(() => ({ + single: async () => ({ data: { id: "task-1" }, error: null }), + })), + }; + return builder; + }; + const updateTaskMock = vi.fn(() => createUpdateBuilder()); + const insertTaskMock = vi.fn(() => ({ + select: () => ({ + single: async () => ({ data: { id: "task-created" }, error: null }), + }), + })); + const deleteTaskMock = vi.fn(() => ({ + eq: vi.fn(async () => ({ error: null })), + })); + const supabaseFromMock = vi.fn(() => ({ + insert: insertTaskMock, + update: updateTaskMock, + delete: deleteTaskMock, + })); + + return { + apiGetMock, + apiPostMock, + apiPutMock, + apiDeleteMock, + updateTaskMock, + insertTaskMock, + deleteTaskMock, + supabaseFromMock, + }; +}); +let latestTabloTasksSectionProps: Record | null = null; +let latestEtapesSectionProps: Record | null = null; +let latestRoadmapSectionProps: Record | null = null; +let latestTabloFilesSectionProps: Record | null = null; + +vi.mock("@xtablo/shared", async (importOriginal) => { + const actual = await importOriginal(); + + return { + ...actual, + buildApi: () => ({ + create: () => ({ + get: apiGetMock, + post: apiPostMock, + put: apiPutMock, + delete: apiDeleteMock, + }), + }), + }; +}); + +vi.mock("../lib/supabase", () => ({ + supabase: { + from: supabaseFromMock, + }, +})); + vi.mock("@tanstack/react-query", async (importOriginal) => { const actual = await importOriginal(); return { ...actual, - useQuery: ({ queryKey }: { queryKey: string[] }) => { + useQuery: ({ queryKey, queryFn }: { queryKey: string[]; queryFn?: () => Promise }) => { + if (queryKey[0] === "client-tablo-folders" && queryFn) { + void queryFn(); + } switch (queryKey[0]) { case "client-tablo": return { @@ -84,16 +184,321 @@ vi.mock("@xtablo/tablo-views", async (importOriginal) => { return { ...actual, - EtapesSection: () =>
Etapes section
, - RoadmapSection: () =>
Roadmap section
, + EtapesSection: (props: Record) => { + latestEtapesSectionProps = props; + return ( +
+
Etapes section
+ + +
+ ); + }, + RoadmapSection: (props: Record) => { + latestRoadmapSectionProps = props; + return ( +
+
Roadmap section
+ +
+ ); + }, TabloDiscussionSection: () =>
Discussion section
, TabloEventsSection: () =>
Events section
, - TabloFilesSection: () =>
Files section
, - TabloTasksSection: () =>
Tasks section
, + TabloFilesSection: (props: Record) => { + latestTabloFilesSectionProps = props; + return ( +
+
Files section
+ + + + + +
+ ); + }, + TabloTasksSection: (props: Record) => { + latestTabloTasksSectionProps = props; + return ( +
+
Tasks section
+ + + + +
+ ); + }, }; }); describe("ClientTabloPage parity shell", () => { + beforeEach(() => { + window.URL.createObjectURL = vi.fn(() => "blob:test"); + window.URL.revokeObjectURL = vi.fn(); + HTMLAnchorElement.prototype.click = vi.fn(); + apiGetMock.mockClear(); + apiPostMock.mockClear(); + apiPutMock.mockClear(); + apiDeleteMock.mockClear(); + updateTaskMock.mockClear(); + insertTaskMock.mockClear(); + deleteTaskMock.mockClear(); + supabaseFromMock.mockClear(); + latestTabloTasksSectionProps = null; + latestEtapesSectionProps = null; + latestRoadmapSectionProps = null; + latestTabloFilesSectionProps = null; + }); + + it("requests folders from the tablo-data API route", () => { + renderWithProviders(, { + route: "/tablo/tablo-1", + path: "/tablo/:tabloId", + }); + + expect(apiGetMock).toHaveBeenCalledWith("/api/v1/tablo-data/tablo-1/folders"); + }); + + it("wires real task mutation callbacks throughout the client task surfaces", async () => { + const { user } = renderWithProviders(, { + route: "/tablo/tablo-1", + path: "/tablo/:tabloId", + }); + + await user.click(screen.getByRole("button", { name: "Étapes" })); + + expect(latestEtapesSectionProps?.onCreateTask).toBeTypeOf("function"); + expect(latestEtapesSectionProps?.onTaskStatusChange).toBeTypeOf("function"); + + await user.click(screen.getByRole("button", { name: "Créer tâche d'étape test" })); + await user.click(screen.getByRole("button", { name: "Terminer tâche d'étape test" })); + + await user.click(screen.getByRole("button", { name: "Tâches" })); + + expect(latestTabloTasksSectionProps?.onCreateTask).toBeTypeOf("function"); + expect(latestTabloTasksSectionProps?.onUpdateTask).toBeTypeOf("function"); + expect(latestTabloTasksSectionProps?.onDeleteTask).toBeTypeOf("function"); + expect(latestTabloTasksSectionProps?.onUpdateTaskPositions).toBeTypeOf("function"); + + await user.click(screen.getByRole("button", { name: "Créer tâche test" })); + await user.click(screen.getByRole("button", { name: "Modifier tâche test" })); + await user.click(screen.getByRole("button", { name: "Supprimer tâche test" })); + await user.click(screen.getByRole("button", { name: "Déplacer la tâche test" })); + + await user.click(screen.getByRole("button", { name: "Roadmap" })); + + expect(latestRoadmapSectionProps?.onTaskStatusChange).toBeTypeOf("function"); + + await user.click(screen.getByRole("button", { name: "Changer statut roadmap test" })); + + await waitFor(() => { + expect(supabaseFromMock).toHaveBeenCalledWith("tasks"); + expect(insertTaskMock).toHaveBeenCalledTimes(2); + expect(insertTaskMock).toHaveBeenCalledWith( + expect.objectContaining({ + tablo_id: "tablo-1", + title: "Task from etape", + status: "todo", + assignee_id: null, + position: 0, + parent_task_id: "etape-1", + is_parent: false, + description: null, + due_date: null, + }) + ); + expect(updateTaskMock).toHaveBeenCalledWith({ title: "Updated task title" }); + expect(updateTaskMock).toHaveBeenCalledWith({ position: 7, status: "done" }); + expect(updateTaskMock).toHaveBeenCalledWith({ status: "done" }); + expect(deleteTaskMock).toHaveBeenCalledTimes(1); + }); + }); + it("renders the main-route style header metadata and discussion CTA", () => { renderWithProviders(, { route: "/tablo/tablo-1", @@ -143,4 +548,57 @@ describe("ClientTabloPage parity shell", () => { expect(screen.getByText("Informations")).toBeInTheDocument(); expect(screen.queryByRole("button", { name: "Ajouter" })).not.toBeInTheDocument(); }); + + it("lets the client quickly toggle a task from the overview card", async () => { + const { user } = renderWithProviders(, { + route: "/tablo/tablo-1", + path: "/tablo/:tabloId", + }); + + await user.click(screen.getByRole("button", { name: "Prepare proposal" })); + + await waitFor(() => { + expect(updateTaskMock).toHaveBeenCalledWith({ status: "done" }); + }); + }); + + it("wires file and folder actions in the client files tab while keeping file deletion disabled", async () => { + const { user } = renderWithProviders(, { + route: "/tablo/tablo-1", + path: "/tablo/:tabloId", + }); + + await user.click(screen.getByRole("button", { name: "Fichiers" })); + + expect(latestTabloFilesSectionProps?.isReadOnly).toBe(false); + expect(latestTabloFilesSectionProps?.onCreateFile).toBeTypeOf("function"); + expect(latestTabloFilesSectionProps?.onDownloadFile).toBeTypeOf("function"); + expect(latestTabloFilesSectionProps?.onCreateFolder).toBeTypeOf("function"); + expect(latestTabloFilesSectionProps?.onUpdateFolder).toBeTypeOf("function"); + expect(latestTabloFilesSectionProps?.onDeleteFolder).toBeTypeOf("function"); + expect(latestTabloFilesSectionProps?.onDeleteFile).toBeUndefined(); + + await user.click(screen.getByRole("button", { name: "Créer fichier test" })); + await user.click(screen.getByRole("button", { name: "Télécharger fichier test" })); + await user.click(screen.getByRole("button", { name: "Créer livrable test" })); + await user.click(screen.getByRole("button", { name: "Modifier livrable test" })); + await user.click(screen.getByRole("button", { name: "Supprimer livrable test" })); + + await waitFor(() => { + expect(apiPostMock).toHaveBeenCalledWith( + "/api/v1/tablo-data/tablo-1/file/brief.pdf", + { content: "data:application/pdf;base64,AAAA", contentType: "application/pdf" } + ); + expect(apiGetMock).toHaveBeenCalledWith("/api/v1/tablo-data/tablo-1/brief.pdf"); + expect(apiPostMock).toHaveBeenCalledWith("/api/v1/tablo-data/tablo-1/folders", { + name: "Livrable", + description: "Desc", + }); + expect(apiPutMock).toHaveBeenCalledWith("/api/v1/tablo-data/tablo-1/folders/folder-1", { + name: "Livrable mis à jour", + description: "Desc", + }); + expect(apiDeleteMock).toHaveBeenCalledWith("/api/v1/tablo-data/tablo-1/folders/folder-1"); + }); + }); }); diff --git a/apps/clients/src/pages/ClientTabloPage.tsx b/apps/clients/src/pages/ClientTabloPage.tsx index aaeb3eb..4be1e85 100644 --- a/apps/clients/src/pages/ClientTabloPage.tsx +++ b/apps/clients/src/pages/ClientTabloPage.tsx @@ -1,8 +1,15 @@ -import { useQuery } from "@tanstack/react-query"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { cn } from "@xtablo/shared"; import { buildApi } from "@xtablo/shared"; import { useSession } from "@xtablo/shared/contexts/SessionContext"; -import type { Etape, KanbanTask, TabloFolder, UserTablo } from "@xtablo/shared-types"; +import type { + Etape, + KanbanTask, + KanbanTaskUpdate, + TabloFolder, + TaskStatus, + UserTablo, +} from "@xtablo/shared-types"; import { FolderIcon, } from "lucide-react"; @@ -135,13 +142,254 @@ function useClientTabloFolders(tabloId: string, accessToken: string | undefined) return useQuery({ queryKey: ["client-tablo-folders", tabloId], queryFn: async () => { - const { data } = await api.get<{ folders: TabloFolder[] }>(`/api/v1/tablo-folders/${tabloId}`); + const { data } = await api.get<{ folders: TabloFolder[] }>( + `/api/v1/tablo-data/${tabloId}/folders` + ); return data.folders ?? []; }, enabled: !!tabloId && !!accessToken, }); } +const invalidateClientFileQueries = (queryClient: ReturnType, tabloId: string) => { + queryClient.invalidateQueries({ queryKey: ["client-tablo-files", tabloId] }); + queryClient.invalidateQueries({ queryKey: ["client-tablo-folders", tabloId] }); +}; + +function useClientCreateFile(tabloId: string, accessToken: string | undefined) { + const api = useAuthedApi(accessToken); + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async (params: { + tabloId: string; + fileName: string; + data: { content: string; contentType: string }; + }) => { + const response = await api.post(`/api/v1/tablo-data/${params.tabloId}/file/${params.fileName}`, params.data); + if (response.status !== 200) { + throw new Error("Failed to create file"); + } + return response.data; + }, + onSuccess: () => invalidateClientFileQueries(queryClient, tabloId), + }); +} + +function useClientDownloadFile(accessToken: string | undefined) { + const api = useAuthedApi(accessToken); + + return useMutation({ + mutationFn: async ({ tabloId, fileName }: { tabloId: string; fileName: string }) => { + const response = await api.get(`/api/v1/tablo-data/${tabloId}/${fileName}`); + if (response.status !== 200) { + throw new Error("Failed to download file"); + } + + const fileData = response.data as { content: string; contentType?: string }; + let blob: Blob; + + if (fileData.content.startsWith("data:")) { + const fileResponse = await fetch(fileData.content); + blob = await fileResponse.blob(); + } else { + blob = new Blob([fileData.content], { + type: fileData.contentType || "application/octet-stream", + }); + } + + const url = window.URL.createObjectURL(blob); + const link = document.createElement("a"); + link.href = url; + link.download = fileName; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + window.URL.revokeObjectURL(url); + }, + }); +} + +function useClientCreateFolder(tabloId: string, accessToken: string | undefined) { + const api = useAuthedApi(accessToken); + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async (params: { + tabloId: string; + name: string; + description: string; + createdBy: string; + }) => { + const response = await api.post(`/api/v1/tablo-data/${params.tabloId}/folders`, { + name: params.name, + description: params.description, + }); + if (response.status !== 200) { + throw new Error("Failed to create folder"); + } + return response.data; + }, + onSuccess: () => invalidateClientFileQueries(queryClient, tabloId), + }); +} + +function useClientUpdateFolder(tabloId: string, accessToken: string | undefined) { + const api = useAuthedApi(accessToken); + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async (params: { + tabloId: string; + folderId: string; + name: string; + description: string; + }) => { + const response = await api.put(`/api/v1/tablo-data/${params.tabloId}/folders/${params.folderId}`, { + name: params.name, + description: params.description, + }); + if (response.status !== 200) { + throw new Error("Failed to update folder"); + } + return response.data; + }, + onSuccess: () => invalidateClientFileQueries(queryClient, tabloId), + }); +} + +function useClientDeleteFolder(tabloId: string, accessToken: string | undefined) { + const api = useAuthedApi(accessToken); + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async (params: { + tabloId: string; + folderId: string; + folderName: string; + }) => { + const response = await api.delete(`/api/v1/tablo-data/${params.tabloId}/folders/${params.folderId}`); + if (response.status !== 200) { + throw new Error("Failed to delete folder"); + } + return response.data; + }, + onSuccess: () => invalidateClientFileQueries(queryClient, tabloId), + }); +} + +type ClientTaskCreateInput = { + tablo_id: string; + title: string; + status?: TaskStatus | string; + parent_task_id?: string | null; + is_parent?: boolean; + position?: number; + description?: string | null; + assignee_id?: string | null; + due_date?: string | null; +}; + +const invalidateClientTaskQueries = (queryClient: ReturnType, tabloId: string) => { + queryClient.invalidateQueries({ queryKey: ["client-tasks", tabloId] }); +}; + +function useClientCreateTask(tabloId: string) { + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async (task: ClientTaskCreateInput) => { + const { data, error } = await supabase + .from("tasks") + .insert({ + tablo_id: task.tablo_id, + title: task.title, + status: (task.status as TaskStatus | undefined) ?? "todo", + assignee_id: task.assignee_id ?? null, + position: task.position ?? 0, + parent_task_id: task.parent_task_id ?? null, + is_parent: task.is_parent ?? false, + description: task.description ?? null, + due_date: task.due_date ?? null, + }) + .select() + .single(); + + if (error) throw error; + return data; + }, + onSuccess: () => invalidateClientTaskQueries(queryClient, tabloId), + }); +} + +function useClientUpdateTask(tabloId: string) { + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async ({ id, tablo_id: _tabloId, ...updates }: KanbanTaskUpdate & { id: string; tablo_id?: string }) => { + const { data, error } = await supabase + .from("tasks") + .update(updates) + .eq("id", id) + .select() + .single(); + + if (error) throw error; + return data; + }, + onSuccess: () => invalidateClientTaskQueries(queryClient, tabloId), + }); +} + +function useClientDeleteTask(tabloId: string) { + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async (taskId: string) => { + const { error } = await supabase.from("tasks").delete().eq("id", taskId); + if (error) throw error; + return taskId; + }, + onSuccess: () => invalidateClientTaskQueries(queryClient, tabloId), + }); +} + +function useClientUpdateTaskPositions(tabloId: string) { + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async ( + updates: Array<{ + id: string; + position: number; + status?: TaskStatus; + parent_task_id?: string | null; + }> + ) => { + const results = await Promise.all( + updates.map(({ id, position, status, parent_task_id }) => + supabase + .from("tasks") + .update({ + position, + ...(status && { status }), + ...(parent_task_id !== undefined ? { parent_task_id } : {}), + }) + .eq("id", id) + ) + ); + + const errors = results.filter((result) => result.error); + if (errors.length > 0) { + throw new Error("Failed to update some task positions"); + } + + return updates; + }, + onSuccess: () => invalidateClientTaskQueries(queryClient, tabloId), + }); +} + function getStatusConfig(status: string) { switch (status) { case "in_progress": @@ -202,6 +450,15 @@ export function ClientTabloPage() { const { data: members = [] } = useClientTabloMembers(tabloId ?? "", accessToken); const { data: filesData, isLoading: filesLoading, error: filesError } = useClientTabloFiles(tabloId ?? "", accessToken); const { data: folders = [], isLoading: foldersLoading, error: foldersError } = useClientTabloFolders(tabloId ?? "", accessToken); + const { mutate: createTask } = useClientCreateTask(tabloId ?? ""); + const { mutate: updateTask } = useClientUpdateTask(tabloId ?? ""); + const { mutate: deleteTask } = useClientDeleteTask(tabloId ?? ""); + const { mutate: updateTaskPositions } = useClientUpdateTaskPositions(tabloId ?? ""); + const { mutateAsync: createFile } = useClientCreateFile(tabloId ?? "", accessToken); + const { mutateAsync: downloadFile } = useClientDownloadFile(accessToken); + const { mutateAsync: createFolder } = useClientCreateFolder(tabloId ?? "", accessToken); + const { mutateAsync: updateFolder } = useClientUpdateFolder(tabloId ?? "", accessToken); + const { mutateAsync: deleteFolder } = useClientDeleteFolder(tabloId ?? "", accessToken); const fileNames = (filesData?.fileNames ?? []).filter((f) => !f.startsWith(".")); @@ -263,12 +520,36 @@ export function ClientTabloPage() {
) : ( tasks.slice(0, 5).map((task) => ( -
-
-

+ )) )}

@@ -334,8 +615,9 @@ export function ClientTabloPage() { tabloTasks={tasks} tabloId={tablo.id} isAdmin={false} - onCreateTask={() => {}} + onCreateTask={(task) => createTask(task)} onCreateEtape={async () => {}} + onTaskStatusChange={(taskId, status) => updateTask({ id: taskId, status })} /> )} @@ -347,6 +629,10 @@ export function ClientTabloPage() { members={members} etapes={etapes} currentUser={currentUser} + onCreateTask={(task) => createTask(task)} + onUpdateTask={(task) => updateTask(task)} + onDeleteTask={(taskId) => deleteTask(taskId)} + onUpdateTaskPositions={(updates) => updateTaskPositions(updates)} /> )} @@ -354,7 +640,10 @@ export function ClientTabloPage() { createFile(params)} + onDownloadFile={(params) => downloadFile(params)} + onCreateFolder={(params) => createFolder(params)} + onUpdateFolder={(params) => updateFolder(params)} + onDeleteFolder={(params) => deleteFolder(params)} /> )} @@ -393,7 +687,7 @@ export function ClientTabloPage() { {}} - onTaskStatusChange={() => {}} + onTaskStatusChange={(taskId, status) => updateTask({ id: taskId, status })} /> )} diff --git a/packages/tablo-views/src/EtapesSection.tsx b/packages/tablo-views/src/EtapesSection.tsx index e1b22e8..4f5f3ee 100644 --- a/packages/tablo-views/src/EtapesSection.tsx +++ b/packages/tablo-views/src/EtapesSection.tsx @@ -1,5 +1,5 @@ import { cn } from "@xtablo/shared"; -import type { Etape, KanbanTask } from "@xtablo/shared-types"; +import type { Etape, KanbanTask, TaskStatus } from "@xtablo/shared-types"; import { Button } from "@xtablo/ui/components/button"; import { Input } from "@xtablo/ui/components/input"; import { @@ -30,6 +30,7 @@ interface EtapesSectionProps { position: number; }) => void; onCreateEtape: (params: { tabloId: string; title: string; position: number }) => Promise; + onTaskStatusChange?: (taskId: string, status: TaskStatus) => void; onUpdateEtape?: (params: { id: string; tabloId: string; title: string }) => Promise; onDeleteEtape?: (params: { id: string; tabloId: string }) => Promise; isCreatingEtape?: boolean; @@ -44,6 +45,7 @@ export function EtapesSection({ isAdmin, onCreateTask, onCreateEtape, + onTaskStatusChange, onUpdateEtape, onDeleteEtape, isCreatingEtape = false, @@ -381,7 +383,18 @@ export function EtapesSection({ {childTasks.map((task) => (
+ onTaskStatusChange?.( + task.id, + task.status === "done" ? "todo" : "done" + ) + } > {task.status === "done" ? ( diff --git a/packages/tablo-views/src/TabloFilesSection.tsx b/packages/tablo-views/src/TabloFilesSection.tsx index e6b93f2..a96df14 100644 --- a/packages/tablo-views/src/TabloFilesSection.tsx +++ b/packages/tablo-views/src/TabloFilesSection.tsx @@ -270,8 +270,9 @@ const FolderDialog = ({ const FolderSection = ({ folder, files, - isAdmin, - isReadOnly, + canManageFolders, + canUploadFiles, + canDeleteFiles, isOpen, onToggle, onEdit, @@ -285,8 +286,9 @@ const FolderSection = ({ }: { folder: TabloFolder; files: string[]; - isAdmin: boolean; - isReadOnly: boolean; + canManageFolders: boolean; + canUploadFiles: boolean; + canDeleteFiles: boolean; isOpen: boolean; onToggle: () => void; onEdit: () => void; @@ -341,7 +343,7 @@ const FolderSection = ({
- {isAdmin && !isReadOnly && ( + {canManageFolders && ( <> -
+ {canUploadFiles && ( +
+ + +
+ )} {/* Files List */} {files.length > 0 ? ( @@ -427,7 +431,7 @@ const FolderSection = ({ onDownloadFile(fileName)} onDelete={() => onDeleteFile(fileName)} isDownloading={downloadingFile === fileName} @@ -483,6 +487,9 @@ interface TabloFilesSectionProps { isCancellingInvite?: boolean; isCreatingFolder?: boolean; isUpdatingFolder?: boolean; + canUploadFiles?: boolean; + canManageFolders?: boolean; + canDeleteFiles?: boolean; onCreateFile?: (params: { tabloId: string; fileName: string; data: { content: string; contentType: string } }) => Promise; onDeleteFile?: (params: { tabloId: string; fileName: string }) => Promise; onDownloadFile?: (params: { tabloId: string; fileName: string }) => Promise; @@ -512,6 +519,9 @@ export const TabloFilesSection = ({ isCancellingInvite, isCreatingFolder = false, isUpdatingFolder = false, + canUploadFiles, + canManageFolders, + canDeleteFiles, onCreateFile, onDeleteFile, onDownloadFile, @@ -534,6 +544,9 @@ export const TabloFilesSection = ({ const fileInputRef = useRef(null); const folderIds = useMemo(() => new Set(folders.map((folder) => folder.id)), [folders]); + const allowUploadFiles = canUploadFiles ?? !isReadOnly; + const allowManageFolders = canManageFolders ?? (isAdmin && !isReadOnly); + const allowDeleteFiles = canDeleteFiles ?? true; // Organize files by folder const { filesInFolders, unorganizedFiles } = useMemo(() => { @@ -805,7 +818,7 @@ export const TabloFilesSection = ({ )} {/* Create Folder Button - Admin Only */} - {isAdmin && !isReadOnly && ( + {allowManageFolders && (
{/* File Upload Area */} - {!selectedFile ? ( + {allowUploadFiles && !selectedFile ? (
- ) : ( + ) : allowUploadFiles && selectedFile ? (
@@ -979,11 +993,13 @@ export const TabloFilesSection = ({
- )} + ) : null} -

- Taille maximale par fichier: 20MB -

+ {allowUploadFiles && ( +

+ Taille maximale par fichier: 20MB +

+ )} {/* Unorganized Files List */} {unorganizedFiles.length > 0 && ( @@ -992,7 +1008,7 @@ export const TabloFilesSection = ({ handleDownloadFile(fileName)} onDelete={() => handleDeleteFile(fileName)} isDownloading={downloadingFile === fileName} From cab790dd2a5d3ea2cad49c5ae517e3318a2a30f8 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sun, 19 Apr 2026 11:33:30 +0200 Subject: [PATCH 46/75] Redirect clients to the clients app --- .../components/AuthenticationGateway.test.tsx | 67 ++++++++++ .../src/components/AuthenticationGateway.tsx | 14 ++- .../components/AuthenticationGateway.unit.tsx | 116 +++++++++++++++--- .../src/components/ProtectedRoute.test.tsx | 45 +++++++ apps/main/src/components/ProtectedRoute.tsx | 19 ++- apps/main/src/lib/clientPortal.ts | 24 ++++ 6 files changed, 264 insertions(+), 21 deletions(-) create mode 100644 apps/main/src/components/AuthenticationGateway.test.tsx create mode 100644 apps/main/src/lib/clientPortal.ts diff --git a/apps/main/src/components/AuthenticationGateway.test.tsx b/apps/main/src/components/AuthenticationGateway.test.tsx new file mode 100644 index 0000000..655a495 --- /dev/null +++ b/apps/main/src/components/AuthenticationGateway.test.tsx @@ -0,0 +1,67 @@ +import { screen, waitFor } from "@testing-library/react"; +import { AuthenticationGateway } from "@ui/components/AuthenticationGateway"; +import { SessionTestProvider } from "@xtablo/shared/contexts/SessionContext"; +import { Route, Routes } from "react-router-dom"; +import { vi } from "vitest"; +import { TestUserStoreProvider } from "../providers/UserStoreProvider"; +import { renderWithRouter } from "../utils/testHelpers"; + +const { redirectClientUserToPortal } = vi.hoisted(() => ({ + redirectClientUserToPortal: vi.fn(), +})); + +vi.mock("../lib/clientPortal", () => ({ + redirectClientUserToPortal, +})); + +describe("AuthenticationGateway", () => { + it("redirects authenticated client users to the client portal instead of main auth pages", async () => { + renderWithRouter( + + + + }> + Login Page
} /> + + + + , + { route: "/login" } + ); + + await waitFor(() => { + expect(redirectClientUserToPortal).toHaveBeenCalledWith("/"); + }); + expect(screen.queryByText("Login Page")).not.toBeInTheDocument(); + }); +}); diff --git a/apps/main/src/components/AuthenticationGateway.tsx b/apps/main/src/components/AuthenticationGateway.tsx index 4c8e124..ba3a1b5 100644 --- a/apps/main/src/components/AuthenticationGateway.tsx +++ b/apps/main/src/components/AuthenticationGateway.tsx @@ -1,6 +1,7 @@ import { useEffect, useState } from "react"; import { Navigate, Outlet, useSearchParams } from "react-router-dom"; import { match } from "ts-pattern"; +import { redirectClientUserToPortal } from "../lib/clientPortal"; import { useMaybeUser } from "../providers/UserStoreProvider"; import { LoadingSpinner } from "./LoadingSpinner"; @@ -22,9 +23,11 @@ export const AuthenticationGateway = () => { return () => clearTimeout(timer); }, [user]); - let status: "loading" | "should-redirect" | "should-pass" = "loading"; + let status: "loading" | "should-redirect" | "should-redirect-client" | "should-pass" = "loading"; if (isLoading) { status = "loading"; + } else if (user?.is_client) { + status = "should-redirect-client"; } else if (user) { status = "should-redirect"; } else { @@ -34,6 +37,15 @@ export const AuthenticationGateway = () => { return match(status) .with("loading", () => ) .with("should-redirect", () => ) + .with("should-redirect-client", () => ) .with("should-pass", () => ) .exhaustive(); }; + +const ClientPortalRedirect = () => { + useEffect(() => { + redirectClientUserToPortal("/"); + }, []); + + return ; +}; diff --git a/apps/main/src/components/AuthenticationGateway.unit.tsx b/apps/main/src/components/AuthenticationGateway.unit.tsx index ee07143..77515e0 100644 --- a/apps/main/src/components/AuthenticationGateway.unit.tsx +++ b/apps/main/src/components/AuthenticationGateway.unit.tsx @@ -2,8 +2,18 @@ import { screen, waitFor } from "@testing-library/react"; import { AuthenticationGateway } from "@ui/components/AuthenticationGateway"; import { SessionTestProvider } from "@xtablo/shared/contexts/SessionContext"; import { Route, Routes } from "react-router-dom"; +import { vi } from "vitest"; +import { TestUserStoreProvider } from "../providers/UserStoreProvider"; import { renderWithRouter } from "../utils/testHelpers"; +const { redirectClientUserToPortal } = vi.hoisted(() => ({ + redirectClientUserToPortal: vi.fn(), +})); + +vi.mock("../lib/clientPortal", () => ({ + redirectClientUserToPortal, +})); + describe("PublicRoute", () => { it("shows loading state initially", () => { renderWithRouter( @@ -38,29 +48,47 @@ describe("PublicRoute", () => { it("redirect to home when user is authenticated", async () => { renderWithRouter( - - - }> - Login Page
} /> - - Home Page
} /> - - , + + + }> + Login Page
} /> +
+ Home Page
} /> + + + , { route: "/login" } ); @@ -70,6 +98,56 @@ describe("PublicRoute", () => { }); }); + it("redirects authenticated client users to the client portal instead of main auth pages", async () => { + renderWithRouter( + + + + }> + Login Page
} /> + + + + , + { route: "/login" } + ); + + await waitFor(() => { + expect(redirectClientUserToPortal).toHaveBeenCalledWith("/"); + }); + expect(screen.queryByText("Login Page")).not.toBeInTheDocument(); + }); + it("renders public content when user is not authenticated", async () => { renderWithRouter( diff --git a/apps/main/src/components/ProtectedRoute.test.tsx b/apps/main/src/components/ProtectedRoute.test.tsx index c7e6375..3a1de85 100644 --- a/apps/main/src/components/ProtectedRoute.test.tsx +++ b/apps/main/src/components/ProtectedRoute.test.tsx @@ -1,10 +1,19 @@ import { screen, waitFor } from "@testing-library/react"; +import { vi } from "vitest"; import { ProtectedRoute } from "@ui/components/ProtectedRoute"; import { SessionTestProvider } from "@xtablo/shared/contexts/SessionContext"; import { Route, Routes } from "react-router-dom"; import { TestUserStoreProvider } from "../providers/UserStoreProvider"; import { renderWithRouter } from "../utils/testHelpers"; +const { redirectClientUserToPortal } = vi.hoisted(() => ({ + redirectClientUserToPortal: vi.fn(), +})); + +vi.mock("../lib/clientPortal", () => ({ + redirectClientUserToPortal, +})); + describe("ProtectedRoute", () => { beforeEach(() => { localStorage.setItem("xtablo-has-seen-landing-page", "true"); @@ -127,4 +136,40 @@ describe("ProtectedRoute", () => { expect(screen.getByText("Custom Login Page")).toBeInTheDocument(); }); }); + + it("redirects client users to the client portal instead of rendering main app content", async () => { + renderWithRouter( + + + + }> + Protected Content
} /> + + + + , + { route: "/" } + ); + + await waitFor(() => { + expect(redirectClientUserToPortal).toHaveBeenCalledWith("/"); + }); + expect(screen.queryByText("Protected Content")).not.toBeInTheDocument(); + }); }); diff --git a/apps/main/src/components/ProtectedRoute.tsx b/apps/main/src/components/ProtectedRoute.tsx index adaeb24..c9c64a7 100644 --- a/apps/main/src/components/ProtectedRoute.tsx +++ b/apps/main/src/components/ProtectedRoute.tsx @@ -1,6 +1,7 @@ import { useEffect, useState } from "react"; import { Navigate, Outlet } from "react-router-dom"; import { match } from "ts-pattern"; +import { redirectClientUserToPortal } from "../lib/clientPortal"; import { useMaybeUser } from "../providers/UserStoreProvider"; import { LoadingSpinner } from "./LoadingSpinner"; @@ -28,7 +29,12 @@ export const ProtectedRoute = ({ return () => clearTimeout(timer); }, [user, fallback]); - let status: "loading" | "should-land-user" | "should-redirect" | "should-pass" = "loading"; + let status: + | "loading" + | "should-land-user" + | "should-redirect" + | "should-redirect-client" + | "should-pass" = "loading"; const isFirstTimeUser = localStorage.getItem("xtablo-has-seen-landing-page") === null; @@ -38,6 +44,8 @@ export const ProtectedRoute = ({ status = "should-land-user"; } else if (!user) { status = "should-redirect"; + } else if (user.is_client) { + status = "should-redirect-client"; } else if (onlyRegularUser && user.is_temporary) { status = "should-redirect"; } else { @@ -56,6 +64,15 @@ export const ProtectedRoute = ({ .with("loading", () => ) .with("should-land-user", () => ) .with("should-redirect", () => ) + .with("should-redirect-client", () => ) .with("should-pass", () => ) .exhaustive(); }; + +const ClientPortalRedirect = () => { + useEffect(() => { + redirectClientUserToPortal("/"); + }, []); + + return ; +}; diff --git a/apps/main/src/lib/clientPortal.ts b/apps/main/src/lib/clientPortal.ts new file mode 100644 index 0000000..9e026ca --- /dev/null +++ b/apps/main/src/lib/clientPortal.ts @@ -0,0 +1,24 @@ +const DEFAULT_CLIENTS_APP_URL = "https://clients.xtablo.com"; + +const trimTrailingSlash = (value: string) => value.replace(/\/+$/, ""); + +export function getClientPortalUrl(path = "/") { + const configuredUrl = import.meta.env.VITE_CLIENTS_APP_URL as string | undefined; + const normalizedPath = path.startsWith("/") ? path : `/${path}`; + + const baseUrl = configuredUrl + ? trimTrailingSlash(configuredUrl) + : window.location.hostname === "app.xtablo.com" + ? DEFAULT_CLIENTS_APP_URL + : window.location.hostname.startsWith("app.") + ? `${window.location.protocol}//clients.${window.location.hostname.slice(4)}${ + window.location.port ? `:${window.location.port}` : "" + }` + : DEFAULT_CLIENTS_APP_URL; + + return `${baseUrl}${normalizedPath}`; +} + +export function redirectClientUserToPortal(path = "/") { + window.location.replace(getClientPortalUrl(path)); +} From 46c7bb589e06ca5044fba23febea6fc7d6bcf6e3 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sun, 19 Apr 2026 13:51:54 +0200 Subject: [PATCH 47/75] Update title of webpage --- apps/clients/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/clients/index.html b/apps/clients/index.html index 9fb3e81..0c424af 100644 --- a/apps/clients/index.html +++ b/apps/clients/index.html @@ -3,7 +3,7 @@ - Xtablo — Client Portal + Xtablo — Portail client
From f43491052b5d32f3a20717b97a7ef16f4ff25493 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sun, 19 Apr 2026 17:28:11 +0200 Subject: [PATCH 48/75] Use github CI instead of circle ci --- .circleci/config.yml | 330 --------------------------------------- .dockerignore | 2 - .github/workflows/ci.yml | 54 +++++++ 3 files changed, 54 insertions(+), 332 deletions(-) delete mode 100644 .circleci/config.yml create mode 100644 .github/workflows/ci.yml diff --git a/.circleci/config.yml b/.circleci/config.yml deleted file mode 100644 index c40679e..0000000 --- a/.circleci/config.yml +++ /dev/null @@ -1,330 +0,0 @@ -version: 2.1 - -# Import the Node orb -orbs: - node: circleci/node@7.2.1 - -# Jobs -jobs: - # ============================================ - # TEST PHASE - # ============================================ - - test-lint: - executor: - name: node/default - resource_class: small - tag: 'lts' - steps: - - checkout - - node/install-packages: - pkg-manager: pnpm - - run: - name: Run linting - command: pnpm run lint - - test-typecheck: - executor: - name: node/default - resource_class: small - tag: 'lts' - steps: - - checkout - - node/install-packages: - pkg-manager: pnpm - cache-path: ~/.pnpm-store - - run: - name: Type check all packages - command: pnpm run typecheck - - test-unit: - executor: - name: node/default - resource_class: medium - tag: 'lts' - steps: - - checkout - - node/install-packages: - pkg-manager: pnpm - cache-path: ~/.pnpm-store - - run: - name: Run unit tests - command: pnpm --filter @xtablo/main run test - - test-api: - executor: - name: node/default - tag: 'lts' - resource_class: small - steps: - - checkout - - node/install-packages: - pkg-manager: pnpm - cache-path: ~/.pnpm-store - - run: - name: Run API checks - command: | - if [ "${RUN_API_INTEGRATION_TESTS:-0}" = "1" ]; then - pnpm --filter @xtablo/api run test - else - echo "Skipping API integration tests (set RUN_API_INTEGRATION_TESTS=1 to enable)." - pnpm --filter @xtablo/api run build - fi - - # ============================================ - # BUILD PHASE - # ============================================ - - build-apps: - docker: - - image: cimg/node:lts - resource_class: small - parameters: - environment: - type: string - default: "staging" - steps: - - checkout - - node/install-packages: - pkg-manager: pnpm - cache-path: ~/.pnpm-store - - run: - name: Build main app for << parameters.environment >> - command: | - cd apps/main - pnpm run build:<< parameters.environment >> - - run: - name: Build external app - command: | - cd apps/external - pnpm run build - - persist_to_workspace: - root: . - paths: - - apps/main/dist - - apps/external/dist - - store_artifacts: - path: apps/main/dist - destination: main-app-<< parameters.environment >> - - store_artifacts: - path: apps/external/dist - destination: external-app - - build-api: - docker: - - image: cimg/node:lts - resource_class: small - steps: - - checkout - - node/install-packages: - pkg-manager: pnpm - cache-path: ~/.pnpm-store - - run: - name: Build API - command: pnpm --filter @xtablo/api run build - - persist_to_workspace: - root: . - paths: - - apps/api/dist - - store_artifacts: - path: apps/api/dist - destination: api - - # ============================================ - # DOCKER BUILD PHASE - # ============================================ - - build-docker-api: - machine: - image: ubuntu-2204:current - resource_class: medium - steps: - - checkout - - attach_workspace: - at: . - - run: - name: Build API Docker image - command: docker build -f apps/api/Dockerfile -t xtablo-api:${CIRCLE_SHA1} -t xtablo-api:latest . - - run: - name: Save Docker image - command: | - mkdir -p /tmp/docker-images - docker save xtablo-api:${CIRCLE_SHA1} -o /tmp/docker-images/api.tar - - persist_to_workspace: - root: /tmp - paths: - - docker-images/api.tar - - # ============================================ - # DEPLOY PHASE - # ============================================ - - deploy-staging: - docker: - - image: cimg/node:lts - resource_class: small - steps: - - checkout - - attach_workspace: - at: . - - node/install-packages: - pkg-manager: pnpm - cache-path: ~/.pnpm-store - - run: - name: Deploy main app to staging - command: | - cd apps/main - echo "Deploying main app to staging environment..." - npx wrangler deploy --env staging - - run: - name: Deploy external app to staging - command: | - cd apps/external - echo "Deploying external app to staging..." - # Add external app staging deployment if needed - # npx wrangler deploy --env staging - - run: - name: Deploy API to staging - command: | - echo "Deploying API to staging environment..." - # Add your API deployment commands here - # Example for Google Cloud Run: - # gcloud run deploy xtablo-api-staging --image gcr.io/${GCP_PROJECT}/xtablo-api:${CIRCLE_SHA1} --region us-central1 - - deploy-production: - docker: - - image: cimg/node:lts - resource_class: small - steps: - - checkout - - attach_workspace: - at: . - - node/install-packages: - pkg-manager: pnpm - cache-path: ~/.pnpm-store - - run: - name: Deploy main app to production - command: | - cd apps/main - echo "Deploying main app to production environment..." - npx wrangler deploy --env production - - run: - name: Deploy external app to production - command: | - cd apps/external - echo "Deploying external app to production..." - # Add external app production deployment if needed - # npx wrangler deploy --env production - - run: - name: Deploy API to production - command: | - echo "Deploying API to production environment..." - # Add your production API deployment commands here - # Example for Google Cloud Run: - # gcloud run deploy xtablo-api --image gcr.io/${GCP_PROJECT}/xtablo-api:${CIRCLE_SHA1} --region us-central1 - -# Workflows -workflows: - version: 2 - - # Run on all branches (except main and develop) - test-and-build: - when: - and: - - not: - equal: [ main, << pipeline.git.branch >> ] - - not: - equal: [ develop, << pipeline.git.branch >> ] - jobs: - # Test phase - run in parallel - - test-lint - - test-typecheck - - test-unit - - test-api - - # Build phase - run after tests pass - - build-apps: - requires: - - test-lint - - test-typecheck - - test-unit - - - build-api: - requires: - - test-api - - - build-docker-api: - requires: - - build-api - - # Staging deployment workflow (develop branch) - deploy-to-staging: - when: - equal: [ develop, << pipeline.git.branch >> ] - jobs: - # Test phase - - test-lint - - test-typecheck - - test-unit - - test-api - - # Build phase for staging - - build-apps: - environment: "staging" - requires: - - test-lint - - test-typecheck - - test-unit - - - build-api: - requires: - - test-api - - - build-docker-api: - requires: - - build-api - - # Deploy to staging - - deploy-staging: - requires: - - build-apps - - build-docker-api - - # Production deployment workflow (main branch) - deploy-to-production: - when: - equal: [ main, << pipeline.git.branch >> ] - jobs: - # Test phase - - test-lint - - test-typecheck - - test-unit - - test-api - - # Build phase for production - - build-apps: - environment: "prod" - requires: - - test-lint - - test-typecheck - - test-unit - - - build-api: - requires: - - test-api - - - build-docker-api: - requires: - - build-api - - # Manual approval gate before production - - hold-for-approval: - type: approval - requires: - - build-apps - - build-docker-api - - # Deploy to production - - deploy-production: - requires: - - hold-for-approval diff --git a/.dockerignore b/.dockerignore index 30331cb..aaa32d1 100644 --- a/.dockerignore +++ b/.dockerignore @@ -38,7 +38,6 @@ node_modules # CI/CD .github **/cloudbuild.yaml -**/.circleci # Misc **/.turbo @@ -48,4 +47,3 @@ node_modules **/temp **/.next **/.nuxt - diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..e1b6548 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,54 @@ +name: CI + +on: + pull_request: + push: + branches: + - main + - develop + +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + checks: + name: Checks + runs-on: + - self-hosted + - linux + - x64 + timeout-minutes: 45 + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Setup pnpm + uses: pnpm/action-setup@v4 + with: + version: 10.19.0 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: 20 + cache: pnpm + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Lint + run: pnpm lint + + - name: Typecheck + run: pnpm typecheck + + - name: Test main app + run: pnpm --filter @xtablo/main test + + - name: Test clients app + run: pnpm --filter @xtablo/clients test + + - name: Typecheck API + run: pnpm --filter @xtablo/api typecheck From cc918407beef8acccde386e6229fcf847495405d Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sun, 19 Apr 2026 18:02:27 +0200 Subject: [PATCH 49/75] fix: stabilize lint and client portal flows --- .github/workflows/ci.yml | 4 +- .../__tests__/middlewares/middlewares.test.ts | 24 +- apps/api/src/__tests__/routes/tablo.test.ts | 2 +- apps/api/src/config.ts | 5 +- apps/api/src/helpers/helpers.ts | 5 +- apps/api/src/helpers/orgIcons.test.ts | 18 +- apps/api/src/routers/tablo.ts | 79 +- apps/api/src/routers/tablo_data.ts | 98 +-- apps/api/src/routers/user.ts | 1 - apps/clients/src/i18n.test.ts | 4 +- apps/clients/src/i18n.ts | 6 +- .../clients/src/pages/ClientTabloListPage.tsx | 6 +- .../src/pages/ClientTabloPage.test.tsx | 51 +- apps/clients/src/pages/ClientTabloPage.tsx | 439 +++++----- apps/clients/src/pages/ResetPasswordPage.tsx | 5 +- .../src/pages/SetPasswordPage.test.tsx | 9 +- apps/clients/src/setupTests.ts | 12 +- apps/clients/src/test/testHelpers.test.tsx | 2 +- apps/clients/src/test/testHelpers.tsx | 6 +- apps/clients/vite.config.ts | 6 +- .../src/components/ProtectedRoute.test.tsx | 2 +- .../src/components/SubscriptionCard.test.tsx | 17 +- apps/main/src/pages/tablo-details.tsx | 322 +++---- apps/main/src/pages/tasks.test.tsx | 2 +- biome.json | 12 + packages/auth-ui/src/AuthInfoBanner.tsx | 3 +- packages/chat-ui/src/chat-ui.css | 67 +- packages/chat-ui/src/components/chat.tsx | 789 +++++++++--------- packages/chat-ui/src/components/features.tsx | 284 ++++--- packages/chat-ui/src/components/layouts.tsx | 361 ++++---- packages/chat-ui/src/hooks.ts | 213 +++-- packages/chat-ui/src/index.ts | 174 ++-- packages/chat-ui/src/security.ts | 103 ++- packages/chat-ui/src/types.ts | 102 +-- packages/shared/package.json | 2 +- packages/tablo-views/src/ChatMessages.tsx | 27 +- packages/tablo-views/src/EtapesSection.tsx | 13 +- .../tablo-views/src/TabloDetailsShell.tsx | 7 +- .../src/TabloDiscussionSection.tsx | 2 +- .../tablo-views/src/TabloEventsSection.tsx | 6 +- .../tablo-views/src/TabloFilesSection.tsx | 32 +- .../tablo-views/src/TabloTasksSection.tsx | 15 +- .../src/components/kanban/TaskModal.tsx | 22 +- packages/tablo-views/src/hooks/useChat.ts | 126 +-- .../tablo-views/src/hooks/useChatUnread.ts | 2 +- packages/tablo-views/src/index.ts | 45 +- .../src/single-tablo/SingleTabloOverview.tsx | 21 +- 47 files changed, 1864 insertions(+), 1689 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e1b6548..3fcca40 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,4 +1,4 @@ -name: CI +name: xtablo-ci on: pull_request: @@ -18,6 +18,8 @@ jobs: - self-hosted - linux - x64 + - xtablo-runner + timeout-minutes: 45 steps: diff --git a/apps/api/src/__tests__/middlewares/middlewares.test.ts b/apps/api/src/__tests__/middlewares/middlewares.test.ts index 52a9b20..08390ab 100644 --- a/apps/api/src/__tests__/middlewares/middlewares.test.ts +++ b/apps/api/src/__tests__/middlewares/middlewares.test.ts @@ -24,9 +24,7 @@ describe("Middleware Tests", () => { }), }); - const createBillingStateSupabaseMock = (input: { - ownerPlan?: string | null; - }) => { + const createBillingStateSupabaseMock = (input: { ownerPlan?: string | null }) => { const ownerPlan = input.ownerPlan ?? "none"; return { @@ -325,10 +323,10 @@ describe("Middleware Tests", () => { createProfilesSupabaseMock({ data: { is_temporary: true }, error: null, - }) as any + }) ); // biome-ignore lint/suspicious/noExplicitAny: Test-only context injection - (c as any).set("user", { id: "temp-user" } as any); + (c as any).set("user", { id: "temp-user" }); await next(); }); app.use(middlewareManager.regularUserCheck); @@ -352,10 +350,10 @@ describe("Middleware Tests", () => { createProfilesSupabaseMock({ data: { is_temporary: false, is_client: true }, error: null, - }) as any + }) ); // biome-ignore lint/suspicious/noExplicitAny: Test-only context injection - (c as any).set("user", { id: "client-user" } as any); + (c as any).set("user", { id: "client-user" }); await next(); }); app.use(middlewareManager.regularUserCheck); @@ -381,10 +379,10 @@ describe("Middleware Tests", () => { createProfilesSupabaseMock({ data: { is_temporary: true }, error: null, - }) as any + }) ); // biome-ignore lint/suspicious/noExplicitAny: Test-only context injection - (c as any).set("user", { id: "temp-user" } as any); + (c as any).set("user", { id: "temp-user" }); await next(); }); app.use(middlewareManager.billingCheckoutAccess); @@ -409,10 +407,10 @@ describe("Middleware Tests", () => { "supabase", createBillingStateSupabaseMock({ ownerPlan: "none", - }) as any + }) ); // biome-ignore lint/suspicious/noExplicitAny: Test-only context injection - (c as any).set("user", { id: "owner-user" } as any); + (c as any).set("user", { id: "owner-user" }); await next(); }); app.use(middlewareManager.activePlanAccess); @@ -435,10 +433,10 @@ describe("Middleware Tests", () => { "supabase", createBillingStateSupabaseMock({ ownerPlan: "solo", - }) as any + }) ); // biome-ignore lint/suspicious/noExplicitAny: Test-only context injection - (c as any).set("user", { id: "owner-user" } as any); + (c as any).set("user", { id: "owner-user" }); await next(); }); app.use(middlewareManager.activePlanAccess); diff --git a/apps/api/src/__tests__/routes/tablo.test.ts b/apps/api/src/__tests__/routes/tablo.test.ts index a8fa3ea..3af1417 100644 --- a/apps/api/src/__tests__/routes/tablo.test.ts +++ b/apps/api/src/__tests__/routes/tablo.test.ts @@ -1,5 +1,5 @@ -import { createClient } from "@supabase/supabase-js"; import { randomUUID } from "node:crypto"; +import { createClient } from "@supabase/supabase-js"; import { testClient } from "hono/testing"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { createConfig } from "../../config.js"; diff --git a/apps/api/src/config.ts b/apps/api/src/config.ts index 38f74f0..0ed26af 100644 --- a/apps/api/src/config.ts +++ b/apps/api/src/config.ts @@ -85,10 +85,7 @@ export function createConfig(secrets?: Secrets): AppConfig { ? validateEnvVar("STRIPE_WEBHOOK_SECRET", process.env.STRIPE_WEBHOOK_SECRET) : getStripeWebhookSecretFromEnv() || getStripeWebhookSecret(isStagingMode), STRIPE_SOLO_PRICE_ID: validateEnvVar("STRIPE_SOLO_PRICE_ID", process.env.STRIPE_SOLO_PRICE_ID), - STRIPE_TEAM_PRICE_ID: validateEnvVar( - "STRIPE_TEAM_PRICE_ID", - process.env.STRIPE_TEAM_PRICE_ID - ), + STRIPE_TEAM_PRICE_ID: validateEnvVar("STRIPE_TEAM_PRICE_ID", process.env.STRIPE_TEAM_PRICE_ID), STRIPE_FOUNDER_PRICE_ID: validateEnvVar( "STRIPE_FOUNDER_PRICE_ID", process.env.STRIPE_FOUNDER_PRICE_ID diff --git a/apps/api/src/helpers/helpers.ts b/apps/api/src/helpers/helpers.ts index 99a3acb..298d6d2 100644 --- a/apps/api/src/helpers/helpers.ts +++ b/apps/api/src/helpers/helpers.ts @@ -413,7 +413,10 @@ export async function findOrCreateClientAccount( recipientEmail: string ): Promise { const normalizedEmail = recipientEmail.trim().toLowerCase(); - const { user: existingUser, error: lookupError } = await getAuthUserByEmail(supabase, normalizedEmail); + const { user: existingUser, error: lookupError } = await getAuthUserByEmail( + supabase, + normalizedEmail + ); if (lookupError) { return { success: false, error: lookupError }; diff --git a/apps/api/src/helpers/orgIcons.test.ts b/apps/api/src/helpers/orgIcons.test.ts index 6493d46..ef943dd 100644 --- a/apps/api/src/helpers/orgIcons.test.ts +++ b/apps/api/src/helpers/orgIcons.test.ts @@ -1,5 +1,5 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { resizeOrgIcon, buildOrgIconKey, ICON_SIZES, ORG_ICONS_BUCKET } from "./orgIcons.js"; +import { describe, expect, it } from "vitest"; +import { buildOrgIconKey, ICON_SIZES, resizeOrgIcon } from "./orgIcons.js"; describe("buildOrgIconKey", () => { it("builds the correct R2 key for a given org and size", () => { @@ -32,7 +32,12 @@ describe("resizeOrgIcon", () => { it("returns buffers for all required sizes from a valid PNG input", async () => { const sharp = (await import("sharp")).default; const input = await sharp({ - create: { width: 512, height: 512, channels: 4, background: { r: 255, g: 0, b: 0, alpha: 1 } }, + create: { + width: 512, + height: 512, + channels: 4, + background: { r: 255, g: 0, b: 0, alpha: 1 }, + }, }) .png() .toBuffer(); @@ -49,7 +54,12 @@ describe("resizeOrgIcon", () => { it("rejects images smaller than 512x512", async () => { const sharp = (await import("sharp")).default; const tooSmall = await sharp({ - create: { width: 256, height: 256, channels: 4, background: { r: 0, g: 0, b: 255, alpha: 1 } }, + create: { + width: 256, + height: 256, + channels: 4, + background: { r: 0, g: 0, b: 255, alpha: 1 }, + }, }) .png() .toBuffer(); diff --git a/apps/api/src/routers/tablo.ts b/apps/api/src/routers/tablo.ts index 105e21c..7b843ae 100644 --- a/apps/api/src/routers/tablo.ts +++ b/apps/api/src/routers/tablo.ts @@ -28,44 +28,44 @@ const createTablo = (middlewareManager: ReturnType; + const tabloData = insertedTablo as Tables<"tablos">; - if (typedPayload.events) { - const eventsToInsert = typedPayload.events.map((event) => ({ - ...event, - tablo_id: tabloData.id, - created_by: user.id, - })); + if (typedPayload.events) { + const eventsToInsert = typedPayload.events.map((event) => ({ + ...event, + tablo_id: tabloData.id, + created_by: user.id, + })); - await supabase.from("events").insert(eventsToInsert); - } + await supabase.from("events").insert(eventsToInsert); + } return c.json({ message: "Tablo created successfully", tablo: tabloData }); } ); @@ -90,12 +90,7 @@ const updateTablo = (middlewareManager: ReturnType { const postTabloFile = (middlewareManager: ReturnType) => factory.createHandlers(checkTabloMember, async (c) => { - const tabloId = c.req.param("tabloId"); - const user = c.get("user"); - // Get the file path - supports both wildcard (*) and named parameter (:fileName) - const filePath = c.req.param("path") || c.req.param("fileName"); + const tabloId = c.req.param("tabloId"); + const user = c.get("user"); + // Get the file path - supports both wildcard (*) and named parameter (:fileName) + const filePath = c.req.param("path") || c.req.param("fileName"); - if (!filePath) { - return c.json({ error: "File path is required" }, 400); - } - - const s3_client = c.get("s3_client"); - - try { - const body = await c.req.json(); - const { content, contentType = "text/plain" } = body; - - if (!content) { - return c.json({ error: "Content is required" }, 400); + if (!filePath) { + return c.json({ error: "File path is required" }, 400); } - await s3_client.send( - new PutObjectCommand({ - Bucket: "tablo-data", - Key: `${tabloId}/${filePath}`, - Body: content, - ContentType: contentType, - Metadata: { - "uploaded-by": user.id, - }, - }) - ); - fileNamesCache.delete(tabloId); + const s3_client = c.get("s3_client"); - return c.json({ - message: "File uploaded successfully", - fileName: filePath, - tabloId, - }); - } catch (error) { - console.error("Error uploading file:", error); - return c.json({ error: "Failed to upload file" }, 500); - } + try { + const body = await c.req.json(); + const { content, contentType = "text/plain" } = body; + + if (!content) { + return c.json({ error: "Content is required" }, 400); + } + + await s3_client.send( + new PutObjectCommand({ + Bucket: "tablo-data", + Key: `${tabloId}/${filePath}`, + Body: content, + ContentType: contentType, + Metadata: { + "uploaded-by": user.id, + }, + }) + ); + fileNamesCache.delete(tabloId); + + return c.json({ + message: "File uploaded successfully", + fileName: filePath, + tabloId, + }); + } catch (error) { + console.error("Error uploading file:", error); + return c.json({ error: "Failed to upload file" }, 500); + } }); const deleteTabloFile = (middlewareManager: ReturnType) => @@ -336,10 +336,7 @@ const getTabloFolders = factory.createHandlers(checkTabloMember, async (c) => { // POST /tablo-data/:tabloId/folders - Create a new folder (admin only) const createTabloFolder = (middlewareManager: ReturnType) => - factory.createHandlers( - middlewareManager.regularUserCheck, - checkTabloAdmin, - async (c) => { + factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { const tabloId = c.req.param("tabloId"); const s3_client = c.get("s3_client"); const user = c.get("user"); @@ -380,15 +377,11 @@ const createTabloFolder = (middlewareManager: ReturnType) => - factory.createHandlers( - middlewareManager.regularUserCheck, - checkTabloAdmin, - async (c) => { + factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { const tabloId = c.req.param("tabloId"); const folderId = c.req.param("folderId"); const s3_client = c.get("s3_client"); @@ -433,15 +426,11 @@ const updateTabloFolder = (middlewareManager: ReturnType) => - factory.createHandlers( - middlewareManager.regularUserCheck, - checkTabloAdmin, - async (c) => { + factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { const tabloId = c.req.param("tabloId"); const folderId = c.req.param("folderId"); const s3_client = c.get("s3_client"); @@ -469,8 +458,7 @@ const deleteTabloFolder = (middlewareManager: ReturnType { if (removeAccessError) { return c.json({ error: "Failed to revoke member tablo permissions" }, 500); } - } const { error: inviteCleanupError } = await supabase diff --git a/apps/clients/src/i18n.test.ts b/apps/clients/src/i18n.test.ts index 7ca4e6c..813951c 100644 --- a/apps/clients/src/i18n.test.ts +++ b/apps/clients/src/i18n.test.ts @@ -1,7 +1,5 @@ import i18n from "i18next"; import { initReactI18next } from "react-i18next"; -import bookingEn from "./locales/en/booking.json"; -import bookingFr from "./locales/fr/booking.json"; import authEn from "../../main/src/locales/en/auth.json"; import chatEn from "../../main/src/locales/en/chat.json"; import commonEn from "../../main/src/locales/en/common.json"; @@ -14,6 +12,8 @@ import commonFr from "../../main/src/locales/fr/common.json"; import componentsFr from "../../main/src/locales/fr/components.json"; import pagesFr from "../../main/src/locales/fr/pages.json"; import tabloFr from "../../main/src/locales/fr/tablo.json"; +import bookingEn from "./locales/en/booking.json"; +import bookingFr from "./locales/fr/booking.json"; i18n.use(initReactI18next).init({ resources: { diff --git a/apps/clients/src/i18n.ts b/apps/clients/src/i18n.ts index 92423b4..44c6469 100644 --- a/apps/clients/src/i18n.ts +++ b/apps/clients/src/i18n.ts @@ -1,9 +1,6 @@ import i18n from "i18next"; import LanguageDetector from "i18next-browser-languagedetector"; import { initReactI18next } from "react-i18next"; -import bookingEn from "./locales/en/booking.json"; -// Import translation files -import bookingFr from "./locales/fr/booking.json"; import authEn from "../../main/src/locales/en/auth.json"; import chatEn from "../../main/src/locales/en/chat.json"; import commonEn from "../../main/src/locales/en/common.json"; @@ -16,6 +13,9 @@ import commonFr from "../../main/src/locales/fr/common.json"; import componentsFr from "../../main/src/locales/fr/components.json"; import pagesFr from "../../main/src/locales/fr/pages.json"; import tabloFr from "../../main/src/locales/fr/tablo.json"; +import bookingEn from "./locales/en/booking.json"; +// Import translation files +import bookingFr from "./locales/fr/booking.json"; i18n .use(LanguageDetector) diff --git a/apps/clients/src/pages/ClientTabloListPage.tsx b/apps/clients/src/pages/ClientTabloListPage.tsx index e3ce7c6..bbfff3d 100644 --- a/apps/clients/src/pages/ClientTabloListPage.tsx +++ b/apps/clients/src/pages/ClientTabloListPage.tsx @@ -1,6 +1,6 @@ import { useQuery } from "@tanstack/react-query"; import type { UserTablo } from "@xtablo/shared-types"; -import { Navigate, Link } from "react-router-dom"; +import { Link, Navigate } from "react-router-dom"; import { supabase } from "../lib/supabase"; function useClientTablosList() { @@ -51,9 +51,7 @@ export function ClientTabloListPage() { to={`/tablo/${tablo.id}`} className="block p-5 rounded-lg border border-border bg-card hover:bg-muted/50 transition-colors space-y-2" > - {tablo.color && ( -
- )} + {tablo.color &&
}

{tablo.name}

))} diff --git a/apps/clients/src/pages/ClientTabloPage.test.tsx b/apps/clients/src/pages/ClientTabloPage.test.tsx index 2f0dc18..b687b51 100644 --- a/apps/clients/src/pages/ClientTabloPage.test.tsx +++ b/apps/clients/src/pages/ClientTabloPage.test.tsx @@ -219,9 +219,7 @@ vi.mock("@xtablo/tablo-views", async (importOriginal) => { type="button" onClick={() => ( - props.onTaskStatusChange as - | ((taskId: string, status: string) => void) - | undefined + props.onTaskStatusChange as ((taskId: string, status: string) => void) | undefined )?.("task-1", "done") } > @@ -239,9 +237,7 @@ vi.mock("@xtablo/tablo-views", async (importOriginal) => { type="button" onClick={() => ( - props.onTaskStatusChange as - | ((taskId: string, status: string) => void) - | undefined + props.onTaskStatusChange as ((taskId: string, status: string) => void) | undefined )?.("task-1", "done") } > @@ -271,7 +267,10 @@ vi.mock("@xtablo/tablo-views", async (importOriginal) => { )?.({ tabloId: "tablo-1", fileName: "brief.pdf", - data: { content: "data:application/pdf;base64,AAAA", contentType: "application/pdf" }, + data: { + content: "data:application/pdf;base64,AAAA", + contentType: "application/pdf", + }, }) } > @@ -338,11 +337,7 @@ vi.mock("@xtablo/tablo-views", async (importOriginal) => { onClick={() => ( props.onDeleteFolder as - | ((params: { - tabloId: string; - folderId: string; - folderName: string; - }) => void) + | ((params: { tabloId: string; folderId: string; folderName: string }) => void) | undefined )?.({ tabloId: "tablo-1", @@ -364,11 +359,7 @@ vi.mock("@xtablo/tablo-views", async (importOriginal) => { @@ -534,7 +527,9 @@ describe("ClientTabloPage parity shell", () => { }); expect(screen.queryByRole("button", { name: "Inviter" })).not.toBeInTheDocument(); - expect(screen.queryByRole("button", { name: "Modifier la mise en page" })).not.toBeInTheDocument(); + expect( + screen.queryByRole("button", { name: "Modifier la mise en page" }) + ).not.toBeInTheDocument(); }); it("renders a read-only overview matching the main route cards", () => { @@ -585,10 +580,10 @@ describe("ClientTabloPage parity shell", () => { await user.click(screen.getByRole("button", { name: "Supprimer livrable test" })); await waitFor(() => { - expect(apiPostMock).toHaveBeenCalledWith( - "/api/v1/tablo-data/tablo-1/file/brief.pdf", - { content: "data:application/pdf;base64,AAAA", contentType: "application/pdf" } - ); + expect(apiPostMock).toHaveBeenCalledWith("/api/v1/tablo-data/tablo-1/file/brief.pdf", { + content: "data:application/pdf;base64,AAAA", + contentType: "application/pdf", + }); expect(apiGetMock).toHaveBeenCalledWith("/api/v1/tablo-data/tablo-1/brief.pdf"); expect(apiPostMock).toHaveBeenCalledWith("/api/v1/tablo-data/tablo-1/folders", { name: "Livrable", diff --git a/apps/clients/src/pages/ClientTabloPage.tsx b/apps/clients/src/pages/ClientTabloPage.tsx index 4be1e85..2ff728d 100644 --- a/apps/clients/src/pages/ClientTabloPage.tsx +++ b/apps/clients/src/pages/ClientTabloPage.tsx @@ -1,6 +1,5 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { cn } from "@xtablo/shared"; -import { buildApi } from "@xtablo/shared"; +import { buildApi, cn } from "@xtablo/shared"; import { useSession } from "@xtablo/shared/contexts/SessionContext"; import type { Etape, @@ -10,21 +9,19 @@ import type { TaskStatus, UserTablo, } from "@xtablo/shared-types"; -import { - FolderIcon, -} from "lucide-react"; -import { useState } from "react"; -import { useParams } from "react-router-dom"; import { EtapesSection, RoadmapSection, - SingleTabloView, type SingleTabloTabId, + SingleTabloView, TabloDiscussionSection, TabloEventsSection, TabloFilesSection, TabloTasksSection, } from "@xtablo/tablo-views"; +import { FolderIcon } from "lucide-react"; +import { useState } from "react"; +import { useParams } from "react-router-dom"; import { supabase } from "../lib/supabase"; const API_URL = import.meta.env.VITE_API_URL as string; @@ -151,7 +148,10 @@ function useClientTabloFolders(tabloId: string, accessToken: string | undefined) }); } -const invalidateClientFileQueries = (queryClient: ReturnType, tabloId: string) => { +const invalidateClientFileQueries = ( + queryClient: ReturnType, + tabloId: string +) => { queryClient.invalidateQueries({ queryKey: ["client-tablo-files", tabloId] }); queryClient.invalidateQueries({ queryKey: ["client-tablo-folders", tabloId] }); }; @@ -166,7 +166,10 @@ function useClientCreateFile(tabloId: string, accessToken: string | undefined) { fileName: string; data: { content: string; contentType: string }; }) => { - const response = await api.post(`/api/v1/tablo-data/${params.tabloId}/file/${params.fileName}`, params.data); + const response = await api.post( + `/api/v1/tablo-data/${params.tabloId}/file/${params.fileName}`, + params.data + ); if (response.status !== 200) { throw new Error("Failed to create file"); } @@ -245,10 +248,13 @@ function useClientUpdateFolder(tabloId: string, accessToken: string | undefined) name: string; description: string; }) => { - const response = await api.put(`/api/v1/tablo-data/${params.tabloId}/folders/${params.folderId}`, { - name: params.name, - description: params.description, - }); + const response = await api.put( + `/api/v1/tablo-data/${params.tabloId}/folders/${params.folderId}`, + { + name: params.name, + description: params.description, + } + ); if (response.status !== 200) { throw new Error("Failed to update folder"); } @@ -263,12 +269,10 @@ function useClientDeleteFolder(tabloId: string, accessToken: string | undefined) const queryClient = useQueryClient(); return useMutation({ - mutationFn: async (params: { - tabloId: string; - folderId: string; - folderName: string; - }) => { - const response = await api.delete(`/api/v1/tablo-data/${params.tabloId}/folders/${params.folderId}`); + mutationFn: async (params: { tabloId: string; folderId: string; folderName: string }) => { + const response = await api.delete( + `/api/v1/tablo-data/${params.tabloId}/folders/${params.folderId}` + ); if (response.status !== 200) { throw new Error("Failed to delete folder"); } @@ -290,7 +294,10 @@ type ClientTaskCreateInput = { due_date?: string | null; }; -const invalidateClientTaskQueries = (queryClient: ReturnType, tabloId: string) => { +const invalidateClientTaskQueries = ( + queryClient: ReturnType, + tabloId: string +) => { queryClient.invalidateQueries({ queryKey: ["client-tasks", tabloId] }); }; @@ -326,7 +333,11 @@ function useClientUpdateTask(tabloId: string) { const queryClient = useQueryClient(); return useMutation({ - mutationFn: async ({ id, tablo_id: _tabloId, ...updates }: KanbanTaskUpdate & { id: string; tablo_id?: string }) => { + mutationFn: async ({ + id, + tablo_id: _tabloId, + ...updates + }: KanbanTaskUpdate & { id: string; tablo_id?: string }) => { const { data, error } = await supabase .from("tasks") .update(updates) @@ -446,10 +457,22 @@ export function ClientTabloPage() { const { data: tablo, isLoading: tabloLoading } = useClientTablo(tabloId ?? ""); const { data: tasks = [] } = useClientTabloTasks(tabloId ?? ""); const { data: etapes = [] } = useClientTabloEtapes(tabloId ?? ""); - const { data: events, isLoading: eventsLoading, error: eventsError } = useClientTabloEvents(tabloId ?? ""); + const { + data: events, + isLoading: eventsLoading, + error: eventsError, + } = useClientTabloEvents(tabloId ?? ""); const { data: members = [] } = useClientTabloMembers(tabloId ?? "", accessToken); - const { data: filesData, isLoading: filesLoading, error: filesError } = useClientTabloFiles(tabloId ?? "", accessToken); - const { data: folders = [], isLoading: foldersLoading, error: foldersError } = useClientTabloFolders(tabloId ?? "", accessToken); + const { + data: filesData, + isLoading: filesLoading, + error: filesError, + } = useClientTabloFiles(tabloId ?? "", accessToken); + const { + data: folders = [], + isLoading: foldersLoading, + error: foldersError, + } = useClientTabloFolders(tabloId ?? "", accessToken); const { mutate: createTask } = useClientCreateTask(tabloId ?? ""); const { mutate: updateTask } = useClientUpdateTask(tabloId ?? ""); const { mutate: deleteTask } = useClientDeleteTask(tabloId ?? ""); @@ -494,202 +517,200 @@ export function ClientTabloPage() { onTabChange={setActiveTab} discussionAction={{ kind: "button", onClick: () => setActiveTab("discussion") }} > - {activeTab === "overview" && ( -
-
-
-

- Description du projet -

-

- Ce projet regroupe les tâches, fichiers et événements associés. Utilisez les - onglets ci-dessus pour naviguer entre les différentes sections. -

-
- -
-
-

- Mes tâches -

-
-
- {tasks.length === 0 ? ( -
- Aucune tâche -
- ) : ( - tasks.slice(0, 5).map((task) => ( - - )) - )} -
-
+ {activeTab === "overview" && ( +
+
+
+

+ Description du projet +

+

+ Ce projet regroupe les tâches, fichiers et événements associés. Utilisez les onglets + ci-dessus pour naviguer entre les différentes sections. +

-
-
-
-

Fichiers

-
-
- {fileNames.length === 0 ? ( -

Aucun fichier

- ) : ( - fileNames.slice(0, 5).map((fileName) => ( -
-
- -
-
-

{fileName}

-
-
- )) - )} -
+
+
+

+ Mes tâches +

- -
-

Informations

-
-
-
Tâches
-
{tasks.length}
-
-
-
Fichiers
-
{fileNames.length}
-
-
-
Statut
-
- {statusLabel} -
-
-
-
Rôle
-
Invité
-
-
+
+ {tasks.length === 0 ? ( +
Aucune tâche
+ ) : ( + tasks.slice(0, 5).map((task) => ( + + )) + )}
- )} - {activeTab === "etapes" && ( - createTask(task)} - onCreateEtape={async () => {}} - onTaskStatusChange={(taskId, status) => updateTask({ id: taskId, status })} - /> - )} +
+
+
+

Fichiers

+
+
+ {fileNames.length === 0 ? ( +

Aucun fichier

+ ) : ( + fileNames.slice(0, 5).map((fileName) => ( +
+
+ +
+
+

{fileName}

+
+
+ )) + )} +
+
- {activeTab === "tasks" && ( - createTask(task)} - onUpdateTask={(task) => updateTask(task)} - onDeleteTask={(taskId) => deleteTask(taskId)} - onUpdateTaskPositions={(updates) => updateTaskPositions(updates)} - /> - )} +
+

Informations

+
+
+
Tâches
+
{tasks.length}
+
+
+
Fichiers
+
{fileNames.length}
+
+
+
Statut
+
+ {statusLabel} +
+
+
+
Rôle
+
Invité
+
+
+
+
+
+ )} - {activeTab === "files" && ( - createFile(params)} - onDownloadFile={(params) => downloadFile(params)} - onCreateFolder={(params) => createFolder(params)} - onUpdateFolder={(params) => updateFolder(params)} - onDeleteFolder={(params) => deleteFolder(params)} - /> - )} + {activeTab === "etapes" && ( + createTask(task)} + onCreateEtape={async () => undefined} + onTaskStatusChange={(taskId, status) => updateTask({ id: taskId, status })} + /> + )} - {activeTab === "discussion" && ( - - )} + {activeTab === "tasks" && ( + createTask(task)} + onUpdateTask={(task) => updateTask(task)} + onDeleteTask={(taskId) => deleteTask(taskId)} + onUpdateTaskPositions={(updates) => updateTaskPositions(updates)} + /> + )} - {activeTab === "events" && ( - [0]["events"]} - isLoading={eventsLoading} - error={eventsError instanceof Error ? eventsError : null} - currentUser={currentUser} - members={members} - /> - )} + {activeTab === "files" && ( + createFile(params)} + onDownloadFile={(params) => downloadFile(params)} + onCreateFolder={(params) => createFolder(params)} + onUpdateFolder={(params) => updateFolder(params)} + onDeleteFolder={(params) => deleteFolder(params)} + /> + )} - {activeTab === "roadmap" && ( - {}} - onTaskStatusChange={(taskId, status) => updateTask({ id: taskId, status })} - /> - )} + {activeTab === "discussion" && ( + + )} + + {activeTab === "events" && ( + [0]["events"]} + isLoading={eventsLoading} + error={eventsError instanceof Error ? eventsError : null} + currentUser={currentUser} + members={members} + /> + )} + + {activeTab === "roadmap" && ( + undefined} + onTaskStatusChange={(taskId, status) => updateTask({ id: taskId, status })} + /> + )} ); } diff --git a/apps/clients/src/pages/ResetPasswordPage.tsx b/apps/clients/src/pages/ResetPasswordPage.tsx index 85d591e..15031cd 100644 --- a/apps/clients/src/pages/ResetPasswordPage.tsx +++ b/apps/clients/src/pages/ResetPasswordPage.tsx @@ -34,7 +34,10 @@ export function ResetPasswordPage() { }; return ( - +
{error ? : null} {isSubmitted ? ( diff --git a/apps/clients/src/pages/SetPasswordPage.test.tsx b/apps/clients/src/pages/SetPasswordPage.test.tsx index 1cce2ee..250d2c6 100644 --- a/apps/clients/src/pages/SetPasswordPage.test.tsx +++ b/apps/clients/src/pages/SetPasswordPage.test.tsx @@ -58,9 +58,12 @@ describe("SetPasswordPage", () => { }) ) .mockResolvedValueOnce( - new Response(JSON.stringify({ success: true, email: "client@example.com", tabloId: "tablo-1" }), { - status: 200, - }) + new Response( + JSON.stringify({ success: true, email: "client@example.com", tabloId: "tablo-1" }), + { + status: 200, + } + ) ); renderWithProviders(, { diff --git a/apps/clients/src/setupTests.ts b/apps/clients/src/setupTests.ts index 23c7532..00791b7 100644 --- a/apps/clients/src/setupTests.ts +++ b/apps/clients/src/setupTests.ts @@ -8,9 +8,15 @@ afterEach(() => { }); global.ResizeObserver = class ResizeObserver { - observe() {} - unobserve() {} - disconnect() {} + observe() { + return undefined; + } + unobserve() { + return undefined; + } + disconnect() { + return undefined; + } }; Element.prototype.scrollIntoView = vi.fn(); diff --git a/apps/clients/src/test/testHelpers.test.tsx b/apps/clients/src/test/testHelpers.test.tsx index 435c9bc..b221b34 100644 --- a/apps/clients/src/test/testHelpers.test.tsx +++ b/apps/clients/src/test/testHelpers.test.tsx @@ -1,5 +1,5 @@ -import { describe, expect, it } from "vitest"; import { screen } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; import { renderWithProviders } from "./testHelpers"; describe("client test harness", () => { diff --git a/apps/clients/src/test/testHelpers.tsx b/apps/clients/src/test/testHelpers.tsx index ac7b2ab..51ae585 100644 --- a/apps/clients/src/test/testHelpers.tsx +++ b/apps/clients/src/test/testHelpers.tsx @@ -1,5 +1,5 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { render, type RenderResult } from "@testing-library/react"; +import { type RenderResult, render } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { SessionTestProvider } from "@xtablo/shared/contexts/SessionContext"; import { ThemeProvider } from "@xtablo/shared/contexts/ThemeContext"; @@ -31,9 +31,7 @@ export const renderWithProviders = ( options: RenderWithProvidersOptions = {} ): RenderResult & { user: ReturnType } => { const { route = "/", path, language = "fr" } = options; - const testUser = Object.prototype.hasOwnProperty.call(options, "testUser") - ? options.testUser - : defaultUser; + const testUser = Object.hasOwn(options, "testUser") ? options.testUser : defaultUser; testI18n.changeLanguage(language); diff --git a/apps/clients/vite.config.ts b/apps/clients/vite.config.ts index 7b36df3..8fbd39f 100644 --- a/apps/clients/vite.config.ts +++ b/apps/clients/vite.config.ts @@ -5,7 +5,11 @@ import { defineConfig, type PluginOption } from "vite"; import tsconfigPaths from "vite-tsconfig-paths"; export default defineConfig(({ mode }) => { - const plugins: PluginOption[] = [react(), tailwindcss(), tsconfigPaths({ ignoreConfigErrors: true })]; + const plugins: PluginOption[] = [ + react(), + tailwindcss(), + tsconfigPaths({ ignoreConfigErrors: true }), + ]; if (mode !== "test" && process.env.VITEST !== "true") { plugins.push(cloudflare({ inspectorPort: 9232 })); diff --git a/apps/main/src/components/ProtectedRoute.test.tsx b/apps/main/src/components/ProtectedRoute.test.tsx index 3a1de85..b07a8c1 100644 --- a/apps/main/src/components/ProtectedRoute.test.tsx +++ b/apps/main/src/components/ProtectedRoute.test.tsx @@ -1,8 +1,8 @@ import { screen, waitFor } from "@testing-library/react"; -import { vi } from "vitest"; import { ProtectedRoute } from "@ui/components/ProtectedRoute"; import { SessionTestProvider } from "@xtablo/shared/contexts/SessionContext"; import { Route, Routes } from "react-router-dom"; +import { vi } from "vitest"; import { TestUserStoreProvider } from "../providers/UserStoreProvider"; import { renderWithRouter } from "../utils/testHelpers"; diff --git a/apps/main/src/components/SubscriptionCard.test.tsx b/apps/main/src/components/SubscriptionCard.test.tsx index 7eebb0e..8c779a7 100644 --- a/apps/main/src/components/SubscriptionCard.test.tsx +++ b/apps/main/src/components/SubscriptionCard.test.tsx @@ -29,6 +29,7 @@ import { useSubscription } from "../hooks/stripe"; const mockUseOrganization = vi.mocked(useOrganization); const mockUseSubscription = vi.mocked(useSubscription); +type SubscriptionData = NonNullable["data"]>; const baseUser: User = { id: "user-1", @@ -147,8 +148,8 @@ describe("SubscriptionCard", () => { status: "active", current_period_end: Math.floor(Date.now() / 1000) + 86400 * 30, cancel_at_period_end: false, - }; - renderCard(baseUser, teamOrg, activeSubscription as any); + } satisfies SubscriptionData; + renderCard(baseUser, teamOrg, activeSubscription); expect(screen.getByText("Actif")).toBeInTheDocument(); expect(screen.getByText("Gérer l'abonnement")).toBeInTheDocument(); expect(screen.getByText("Annuler")).toBeInTheDocument(); @@ -164,8 +165,8 @@ describe("SubscriptionCard", () => { status: "trialing", current_period_end: Math.floor(Date.now() / 1000) + 86400 * 14, cancel_at_period_end: false, - }; - renderCard(baseUser, teamOrg, trialingSubscription as any); + } satisfies SubscriptionData; + renderCard(baseUser, teamOrg, trialingSubscription); expect(screen.getByText("Période d'essai")).toBeInTheDocument(); }); @@ -179,8 +180,8 @@ describe("SubscriptionCard", () => { status: "past_due", current_period_end: Math.floor(Date.now() / 1000) - 86400, cancel_at_period_end: false, - }; - renderCard(baseUser, teamOrg, pastDueSubscription as any); + } satisfies SubscriptionData; + renderCard(baseUser, teamOrg, pastDueSubscription); expect(screen.getByText("Paiement en retard")).toBeInTheDocument(); }); @@ -195,8 +196,8 @@ describe("SubscriptionCard", () => { status: "active", current_period_end: Math.floor(Date.now() / 1000) + 86400 * 15, cancel_at_period_end: true, - }; - renderCard(baseUser, teamOrg, canceledSubscription as any); + } satisfies SubscriptionData; + renderCard(baseUser, teamOrg, canceledSubscription); expect(screen.getByText(/Abonnement en cours d'annulation/)).toBeInTheDocument(); expect(screen.getByText("Réactiver l'abonnement")).toBeInTheDocument(); }); diff --git a/apps/main/src/pages/tablo-details.tsx b/apps/main/src/pages/tablo-details.tsx index a6db9de..f198ce3 100644 --- a/apps/main/src/pages/tablo-details.tsx +++ b/apps/main/src/pages/tablo-details.tsx @@ -5,20 +5,20 @@ import type { KanbanTask } from "@xtablo/shared-types"; import { DEFAULT_OVERVIEW_LAYOUT, EtapesSection, + getSingleTabloStatusConfig, + moveBetweenZones, + moveWithinZone, type OverviewLayoutV1, RoadmapSection, SingleTabloOverview, + type SingleTabloTabId, SingleTabloView, + sanitizeOverviewLayout, TabloDiscussionSection, TabloEventsSection, TabloFilesSection, TabloTasksSection, TaskModal, - getSingleTabloStatusConfig, - moveBetweenZones, - moveWithinZone, - sanitizeOverviewLayout, - type SingleTabloTabId, useChatUnread, } from "@xtablo/tablo-views"; import { Avatar, AvatarFallback, AvatarImage } from "@xtablo/ui/components/avatar"; @@ -336,166 +336,166 @@ export const TabloDetailsPage = () => { return ( <> setSearchParams({ section: tabId })} - hasUnreadDiscussion={hasUnreadDiscussion} - discussionAction={{ kind: "link", to: `/chat/${tabloId}` }} - canInviteMembers={isAdmin} - onOpenInviteDialog={() => setIsShareDialogOpen(true)} - > - {activeSection === "overview" && ( - setSearchParams({ section: "tasks" })} - onOpenFiles={() => setSearchParams({ section: "files" })} - onCreateTask={() => openTaskModal(undefined, currentUser.id)} - onToggleTaskDone={(taskId) => updateTask({ id: taskId, status: "done" })} - showAllTasks={showAllOverviewTasks} - onToggleShowAllTasks={() => setShowAllOverviewTasks((prev) => !prev)} - layout={overviewLayout} - canEditLayout={isAdmin} - isLayoutEditMode={isLayoutEditMode} - draggedBlock={draggedOverviewBlock} - onToggleLayoutEditMode={() => setIsLayoutEditMode((prev) => !prev)} - onResetLayout={handleResetOverviewLayout} - onBlockDragStart={handleOverviewBlockDragStart} - onBlockDragOver={handleOverviewBlockDragOver} - onBlockDrop={handleOverviewBlockDrop} - onBlockDragEnd={() => setDraggedOverviewBlock(null)} - /> - )} + tablo={tablo} + roleLabel={isAdmin ? "Admin" : "Invité"} + statusLabel={statusLabel} + statusBadgeClass={badgeClass} + progress={progress} + activeTab={activeSection} + onTabChange={(tabId) => setSearchParams({ section: tabId })} + hasUnreadDiscussion={hasUnreadDiscussion} + discussionAction={{ kind: "link", to: `/chat/${tabloId}` }} + canInviteMembers={isAdmin} + onOpenInviteDialog={() => setIsShareDialogOpen(true)} + > + {activeSection === "overview" && ( + setSearchParams({ section: "tasks" })} + onOpenFiles={() => setSearchParams({ section: "files" })} + onCreateTask={() => openTaskModal(undefined, currentUser.id)} + onToggleTaskDone={(taskId) => updateTask({ id: taskId, status: "done" })} + showAllTasks={showAllOverviewTasks} + onToggleShowAllTasks={() => setShowAllOverviewTasks((prev) => !prev)} + layout={overviewLayout} + canEditLayout={isAdmin} + isLayoutEditMode={isLayoutEditMode} + draggedBlock={draggedOverviewBlock} + onToggleLayoutEditMode={() => setIsLayoutEditMode((prev) => !prev)} + onResetLayout={handleResetOverviewLayout} + onBlockDragStart={handleOverviewBlockDragStart} + onBlockDragOver={handleOverviewBlockDragOver} + onBlockDrop={handleOverviewBlockDrop} + onBlockDragEnd={() => setDraggedOverviewBlock(null)} + /> + )} - {activeSection === "tasks" && ( - ({ ...inv, id: String(inv.id) }))} - isInvitingUser={isInvitingUser} - isCancellingInvite={isCancellingInvite} - onCreateTask={(task) => createTask(task)} - onUpdateTask={(task) => updateTask(task)} - onDeleteTask={(taskId) => deleteTask(taskId)} - onUpdateTaskPositions={(updates) => updateTaskPositions(updates)} - onUpdateTablo={(data) => - updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) - } - onInviteUser={inviteUser} - onCancelInvite={(params) => - cancelInvite({ ...params, inviteId: Number(params.inviteId) }) - } - /> - )} - {activeSection === "files" && ( - ({ ...inv, id: String(inv.id) }))} - isInvitingUser={isInvitingUser} - isCancellingInvite={isCancellingInvite} - isCreatingFolder={isCreatingFolder} - isUpdatingFolder={isUpdatingFolder} - onCreateFile={(params) => uploadFile(params).then(() => undefined)} - onDeleteFile={(params) => deleteFile(params).then(() => undefined)} - onDownloadFile={(params) => downloadFile(params).then(() => undefined)} - onCreateFolder={(params) => createFolder(params).then(() => undefined)} - onUpdateFolder={(params) => updateFolder(params).then(() => undefined)} - onDeleteFolder={(params) => deleteFolder(params).then(() => undefined)} - onUpdateTablo={(data) => - updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) - } - onInviteUser={inviteUser} - onCancelInvite={(params) => - cancelInvite({ ...params, inviteId: Number(params.inviteId) }) - } - /> - )} - {activeSection === "discussion" && ( -
- ({ ...inv, id: String(inv.id) }))} + isInvitingUser={isInvitingUser} + isCancellingInvite={isCancellingInvite} + onCreateTask={(task) => createTask(task)} + onUpdateTask={(task) => updateTask(task)} + onDeleteTask={(taskId) => deleteTask(taskId)} + onUpdateTaskPositions={(updates) => updateTaskPositions(updates)} + onUpdateTablo={(data) => + updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) + } + onInviteUser={inviteUser} + onCancelInvite={(params) => + cancelInvite({ ...params, inviteId: Number(params.inviteId) }) + } + /> + )} + {activeSection === "files" && ( + ({ ...inv, id: String(inv.id) }))} + isInvitingUser={isInvitingUser} + isCancellingInvite={isCancellingInvite} + isCreatingFolder={isCreatingFolder} + isUpdatingFolder={isUpdatingFolder} + onCreateFile={(params) => uploadFile(params).then(() => undefined)} + onDeleteFile={(params) => deleteFile(params).then(() => undefined)} + onDownloadFile={(params) => downloadFile(params).then(() => undefined)} + onCreateFolder={(params) => createFolder(params).then(() => undefined)} + onUpdateFolder={(params) => updateFolder(params).then(() => undefined)} + onDeleteFolder={(params) => deleteFolder(params).then(() => undefined)} + onUpdateTablo={(data) => + updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) + } + onInviteUser={inviteUser} + onCancelInvite={(params) => + cancelInvite({ ...params, inviteId: Number(params.inviteId) }) + } /> -
- )} - {activeSection === "events" && ( - ({ ...inv, id: String(inv.id) }))} - isInvitingUser={isInvitingUser} - isCancellingInvite={isCancellingInvite} - onCreateEvent={() => undefined} - onUpdateTablo={(data) => - updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) - } - onInviteUser={inviteUser} - onCancelInvite={(params) => - cancelInvite({ ...params, inviteId: Number(params.inviteId) }) - } - /> - )} + )} + {activeSection === "discussion" && ( +
+ +
+ )} + {activeSection === "events" && ( + ({ ...inv, id: String(inv.id) }))} + isInvitingUser={isInvitingUser} + isCancellingInvite={isCancellingInvite} + onCreateEvent={() => undefined} + onUpdateTablo={(data) => + updateTabloAsync({ ...data, name: data.name ?? undefined }).then(() => undefined) + } + onInviteUser={inviteUser} + onCancelInvite={(params) => + cancelInvite({ ...params, inviteId: Number(params.inviteId) }) + } + /> + )} - {activeSection === "etapes" && ( - - createTask({ - ...task, - status: task.status as "todo" | "in_progress" | "in_review" | "done", - }) - } - onCreateEtape={(params) => createEtape(params).then(() => undefined)} - onUpdateEtape={(params) => updateEtape(params).then(() => undefined)} - onDeleteEtape={(params) => deleteEtape(params).then(() => undefined)} - isCreatingEtape={isCreatingEtape} - isUpdatingEtape={isUpdatingEtape} - isDeletingEtape={isDeletingEtape} - /> - )} + {activeSection === "etapes" && ( + + createTask({ + ...task, + status: task.status as "todo" | "in_progress" | "in_review" | "done", + }) + } + onCreateEtape={(params) => createEtape(params).then(() => undefined)} + onUpdateEtape={(params) => updateEtape(params).then(() => undefined)} + onDeleteEtape={(params) => deleteEtape(params).then(() => undefined)} + isCreatingEtape={isCreatingEtape} + isUpdatingEtape={isUpdatingEtape} + isDeletingEtape={isDeletingEtape} + /> + )} - {activeSection === "roadmap" && ( - updateTask({ id: taskId, status })} - /> - )} + {activeSection === "roadmap" && ( + updateTask({ id: taskId, status })} + /> + )}
{/* Task Create Modal */} @@ -568,8 +568,8 @@ export const TabloDetailsPage = () => {

Accès client

- Le client recevra un email pour définir son mot de passe ou, s'il a déjà - un compte, une notification d'accès directe à ce tablo. + Le client recevra un email pour définir son mot de passe ou, s'il a déjà un + compte, une notification d'accès directe à ce tablo.

@@ -681,7 +681,9 @@ export const TabloDetailsPage = () => { ) : ( <>
-

Inviter un utilisateur

+

+ Inviter un utilisateur +

Utilisez le système d'invitation standard par email pour le moment

diff --git a/apps/main/src/pages/tasks.test.tsx b/apps/main/src/pages/tasks.test.tsx index e421f12..d5f3e5b 100644 --- a/apps/main/src/pages/tasks.test.tsx +++ b/apps/main/src/pages/tasks.test.tsx @@ -1,8 +1,8 @@ import { screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import { TasksPage } from "./tasks"; import { renderWithProviders } from "../utils/testHelpers"; +import { TasksPage } from "./tasks"; const mutateUpdateTask = vi.fn(); const mutateDeleteTask = vi.fn(); diff --git a/biome.json b/biome.json index ef80f8d..cc68d4e 100644 --- a/biome.json +++ b/biome.json @@ -13,6 +13,12 @@ "apps/api/*.{ts,tsx,js,jsx,json}", "packages/ui/src/**/*", "packages/ui/*.{ts,tsx,js,jsx,json}", + "packages/tablo-views/src/**/*", + "packages/tablo-views/*.{ts,tsx,js,jsx,json}", + "packages/auth-ui/src/**/*", + "packages/auth-ui/*.{ts,tsx,js,jsx,json}", + "packages/chat-ui/src/**/*", + "packages/chat-ui/*.{ts,tsx,js,jsx,json}", "packages/shared/src/**/*", "packages/shared/*.{ts,tsx,js,jsx,json}", "packages/shared-types/src/**/*", @@ -298,6 +304,12 @@ "apps/api/*.{ts,tsx}", "packages/ui/src/**/*.{ts,tsx}", "packages/ui/*.{ts,tsx}", + "packages/tablo-views/src/**/*.{ts,tsx}", + "packages/tablo-views/*.{ts,tsx}", + "packages/auth-ui/src/**/*.{ts,tsx}", + "packages/auth-ui/*.{ts,tsx}", + "packages/chat-ui/src/**/*.{ts,tsx}", + "packages/chat-ui/*.{ts,tsx}", "packages/shared/src/**/*.{ts,tsx}", "packages/shared/*.{ts,tsx}", "packages/shared-types/src/**/*.{ts,tsx}", diff --git a/packages/auth-ui/src/AuthInfoBanner.tsx b/packages/auth-ui/src/AuthInfoBanner.tsx index a5554d2..c7b7aff 100644 --- a/packages/auth-ui/src/AuthInfoBanner.tsx +++ b/packages/auth-ui/src/AuthInfoBanner.tsx @@ -7,7 +7,8 @@ type AuthInfoBannerProps = { }; const variantStyles: Record = { - error: "bg-red-50 text-red-800 border-red-200 dark:bg-red-950/20 dark:text-red-200 dark:border-red-800", + error: + "bg-red-50 text-red-800 border-red-200 dark:bg-red-950/20 dark:text-red-200 dark:border-red-800", info: "bg-blue-50 text-blue-800 border-blue-200 dark:bg-blue-950/20 dark:text-blue-200 dark:border-blue-800", success: "bg-green-50 text-green-800 border-green-200 dark:bg-green-950/20 dark:text-green-200 dark:border-green-800", diff --git a/packages/chat-ui/src/chat-ui.css b/packages/chat-ui/src/chat-ui.css index 0398317..eff81d9 100644 --- a/packages/chat-ui/src/chat-ui.css +++ b/packages/chat-ui/src/chat-ui.css @@ -2,45 +2,82 @@ /* ─── Message entry ─────────────────────────────────────────────── */ @keyframes chat-message-enter { - from { opacity: 0; transform: translateY(8px); } - to { opacity: 1; transform: translateY(0); } + from { + opacity: 0; + transform: translateY(8px); + } + to { + opacity: 1; + transform: translateY(0); + } } /* ─── Toolbar entrance ──────────────────────────────────────────── */ @keyframes chat-toolbar-enter { - from { opacity: 0; transform: scale(0.95) translateY(4px); } - to { opacity: 1; transform: scale(1) translateY(0); } + from { + opacity: 0; + transform: scale(0.95) translateY(4px); + } + to { + opacity: 1; + transform: scale(1) translateY(0); + } } /* ─── Reaction pop ──────────────────────────────────────────────── */ @keyframes chat-reaction-pop { - 0% { transform: scale(0); opacity: 0; } - 70% { transform: scale(1.1); } - 100% { transform: scale(1); opacity: 1; } + 0% { + transform: scale(0); + opacity: 0; + } + 70% { + transform: scale(1.1); + } + 100% { + transform: scale(1); + opacity: 1; + } } /* ─── Typing indicator dots ─────────────────────────────────────── */ @keyframes chat-typing-pulse { - 0%, 60%, 100% { opacity: 0.3; transform: translateY(0); } - 30% { opacity: 1; transform: translateY(-4px); } + 0%, + 60%, + 100% { + opacity: 0.3; + transform: translateY(0); + } + 30% { + opacity: 1; + transform: translateY(-4px); + } } /* ─── Cursor blink (streaming) ──────────────────────────────────── */ @keyframes chat-cursor-blink { - 0%, 100% { opacity: 1; } - 50% { opacity: 0; } + 0%, + 100% { + opacity: 1; + } + 50% { + opacity: 0; + } } /* ─── Read receipt status color transition ───────────────────────── */ @keyframes chat-status-read-in { - from { color: var(--color-muted-foreground); } - to { color: var(--color-primary); } + from { + color: var(--color-muted-foreground); + } + to { + color: var(--color-primary); + } } /* ─── Utility classes ───────────────────────────────────────────── */ @layer base { .chat-message { - animation: chat-message-enter 250ms cubic-bezier(0.25, 0.1, 0.25, 1.0); + animation: chat-message-enter 250ms cubic-bezier(0.25, 0.1, 0.25, 1); } .chat-typing-dot { @@ -56,7 +93,7 @@ } .chat-reaction-pop { - animation: chat-reaction-pop 200ms cubic-bezier(0.25, 0.1, 0.25, 1.0); + animation: chat-reaction-pop 200ms cubic-bezier(0.25, 0.1, 0.25, 1); } .chat-status-read { diff --git a/packages/chat-ui/src/components/chat.tsx b/packages/chat-ui/src/components/chat.tsx index a4e8549..4b58a8a 100644 --- a/packages/chat-ui/src/components/chat.tsx +++ b/packages/chat-ui/src/components/chat.tsx @@ -1,72 +1,71 @@ -import * as React from "react" -import { cn } from "@xtablo/shared" +import { cn } from "@xtablo/shared"; import { + AlertCircle, + ArrowUp, Check, CheckCheck, - ArrowUp, ChevronDown, Clock, - AlertCircle, + Mic, + MoreHorizontal, + Paperclip, + Pause, + Pencil, + Pin, + // Plus, + Play, Reply, SmilePlus, - MoreHorizontal, - Pin, - Pencil, Trash2, - X, - Paperclip, // Image as ImageIcon, // Smile, Upload, - // Plus, - Play, - Pause, - Mic, -} from "lucide-react" -import { createPortal } from "react-dom" + X, +} from "lucide-react"; +import * as React from "react"; +import { createPortal } from "react-dom"; +import { + formatTimestamp, + groupMessages, + useAutoResize, + useAutoScroll, + useTypingIndicator, +} from "../hooks"; import type { - ChatUser, ChatConfig, ChatLabels, ChatMessageData, + ChatUser, MessageGroup, TypingUser, -} from "../types" -import { - groupMessages, - useAutoScroll, - useAutoResize, - useTypingIndicator, - formatTimestamp, -} from "../hooks" +} from "../types"; // ─── Context ────────────────────────────────────────────────────────────────── -const ChatContext = React.createContext(null) +const ChatContext = React.createContext(null); function useChatContext() { - const ctx = React.useContext(ChatContext) - if (!ctx) - throw new Error("Chat components must be wrapped in ") - return ctx + const ctx = React.useContext(ChatContext); + if (!ctx) throw new Error("Chat components must be wrapped in "); + return ctx; } // ─── ChatProvider ───────────────────────────────────────────────────────────── interface ChatProviderProps { - currentUser: ChatUser - dateFormat?: "relative" | "absolute" | "time-only" - messageGroupingInterval?: number - labels?: ChatLabels - onReactionAdd?: (messageId: string, emoji: string) => void - onReactionRemove?: (messageId: string, emoji: string) => void - onReply?: (message: ChatMessageData) => void - onEdit?: (message: ChatMessageData) => void - onDelete?: (messageId: string) => void - onPin?: (messageId: string) => void - children: React.ReactNode - style?: React.CSSProperties - className?: string + currentUser: ChatUser; + dateFormat?: "relative" | "absolute" | "time-only"; + messageGroupingInterval?: number; + labels?: ChatLabels; + onReactionAdd?: (messageId: string, emoji: string) => void; + onReactionRemove?: (messageId: string, emoji: string) => void; + onReply?: (message: ChatMessageData) => void; + onEdit?: (message: ChatMessageData) => void; + onDelete?: (messageId: string) => void; + onPin?: (messageId: string) => void; + children: React.ReactNode; + style?: React.CSSProperties; + className?: string; } function ChatProvider({ @@ -97,8 +96,19 @@ function ChatProvider({ onDelete, onPin, }), - [currentUser, dateFormat, messageGroupingInterval, labels, onReactionAdd, onReactionRemove, onReply, onEdit, onDelete, onPin] - ) + [ + currentUser, + dateFormat, + messageGroupingInterval, + labels, + onReactionAdd, + onReactionRemove, + onReply, + onEdit, + onDelete, + onPin, + ] + ); return ( @@ -106,19 +116,26 @@ function ChatProvider({ {children}
- ) + ); } // ─── Quick emoji picker (6 common reactions) ────────────────────────────────── -const QUICK_REACTIONS = ["\u{1F44D}", "\u{2764}\u{FE0F}", "\u{1F602}", "\u{1F62E}", "\u{1F64F}", "\u{1F525}"] +const QUICK_REACTIONS = [ + "\u{1F44D}", + "\u{2764}\u{FE0F}", + "\u{1F602}", + "\u{1F62E}", + "\u{1F64F}", + "\u{1F525}", +]; function QuickReactionPicker({ onSelect, onClose, }: { - onSelect: (emoji: string) => void - onClose: () => void + onSelect: (emoji: string) => void; + onClose: () => void; }) { return (
{ - onSelect(emoji) - onClose() + onSelect(emoji); + onClose(); }} className="flex size-8 items-center justify-center rounded-lg text-lg transition-transform hover:scale-125 hover:bg-accent" aria-label={`React with ${emoji}`} @@ -139,20 +156,20 @@ function QuickReactionPicker({ ))}
- ) + ); } // ─── ChatMessageActions (hover toolbar) ─────────────────────────────────────── interface ChatMessageActionsProps { - message: ChatMessageData - isOutgoing: boolean + message: ChatMessageData; + isOutgoing: boolean; } function ChatMessageActions({ message, isOutgoing }: ChatMessageActionsProps) { - const { onReply, onReactionAdd, onEdit, onDelete, onPin } = useChatContext() - const [showReactions, setShowReactions] = React.useState(false) - const [showMore, setShowMore] = React.useState(false) + const { onReply, onReactionAdd, onEdit, onDelete, onPin } = useChatContext(); + const [showReactions, setShowReactions] = React.useState(false); + const [showMore, setShowMore] = React.useState(false); return (
- onReactionAdd?.(message.id, emoji) - } + onSelect={(emoji) => onReactionAdd?.(message.id, emoji)} onClose={() => setShowReactions(false)} />
@@ -211,8 +226,8 @@ function ChatMessageActions({ message, isOutgoing }: ChatMessageActionsProps) { {isOutgoing && (
- ) + ); } // ─── ChatMessageReply (quoted reply inside bubble) ──────────────────────────── @@ -255,8 +270,8 @@ function ChatMessageReply({ replyTo, isOutgoing, }: { - replyTo: NonNullable - isOutgoing: boolean + replyTo: NonNullable; + isOutgoing: boolean; }) { // Outgoing bubbles set text color via --chat-bubble-outgoing-text which may // be white (Lunar, Midnight) or dark (Aurora, Ember). Using `text-inherit` @@ -290,63 +305,70 @@ function ChatMessageReply({
- ) + ); } // ─── ChatMessage ────────────────────────────────────────────────────────────── interface ChatMessageProps { - message: ChatMessageData - isOutgoing: boolean - position: "solo" | "first" | "middle" | "last" - showSender?: boolean - showAvatar?: boolean - className?: string + message: ChatMessageData; + isOutgoing: boolean; + position: "solo" | "first" | "middle" | "last"; + showSender?: boolean; + showAvatar?: boolean; + className?: string; } // ─── Voice Message ───────────────────────────────────────────────────────── -function ChatVoiceMessage({ voice, isOutgoing }: { voice: NonNullable; isOutgoing: boolean }) { - const [playing, setPlaying] = React.useState(false) - const [progress, setProgress] = React.useState(0) - const progressRef = React.useRef(0) +function ChatVoiceMessage({ + voice, + isOutgoing, +}: { + voice: NonNullable; + isOutgoing: boolean; +}) { + const [playing, setPlaying] = React.useState(false); + const [progress, setProgress] = React.useState(0); + const progressRef = React.useRef(0); React.useEffect(() => { - progressRef.current = progress - }, [progress]) + progressRef.current = progress; + }, [progress]); - const totalMins = Math.floor(voice.duration / 60) - const totalSecs = Math.floor(voice.duration % 60) - const elapsed = progress * voice.duration - const elapsedMins = Math.floor(elapsed / 60) - const elapsedSecs = Math.floor(elapsed % 60) - const timeLabel = playing || progress > 0 - ? `${elapsedMins}:${elapsedSecs.toString().padStart(2, "0")}` - : `${totalMins}:${totalSecs.toString().padStart(2, "0")}` + const totalMins = Math.floor(voice.duration / 60); + const totalSecs = Math.floor(voice.duration % 60); + const elapsed = progress * voice.duration; + const elapsedMins = Math.floor(elapsed / 60); + const elapsedSecs = Math.floor(elapsed % 60); + const timeLabel = + playing || progress > 0 + ? `${elapsedMins}:${elapsedSecs.toString().padStart(2, "0")}` + : `${totalMins}:${totalSecs.toString().padStart(2, "0")}`; - const progressIndex = Math.floor(progress * voice.waveform.length) + const progressIndex = Math.floor(progress * voice.waveform.length); React.useEffect(() => { - if (!playing) return - const fps = 20 - const step = 1 / (voice.duration * fps) + if (!playing) return; + const fps = 20; + const step = 1 / (voice.duration * fps); const id = setInterval(() => { - const next = progressRef.current + step + const next = progressRef.current + step; if (next >= 1) { - setProgress(0) - setPlaying(false) - clearInterval(id) + setProgress(0); + setPlaying(false); + clearInterval(id); } else { - setProgress(next) + setProgress(next); } - }, 1000 / fps) - return () => clearInterval(id) - }, [playing, voice.duration]) + }, 1000 / fps); + return () => clearInterval(id); + }, [playing, voice.duration]); const toggle = () => { - if (!playing && progress === 0) setProgress(0) - setPlaying((p) => !p) - } + if (!playing && progress === 0) setProgress(0); + setPlaying((p) => !p); + }; return (
@@ -364,7 +386,7 @@ function ChatVoiceMessage({ voice, isOutgoing }: { voice: NonNullable
{voice.waveform.map((v, i) => { - const played = i < progressIndex + const played = i < progressIndex; return (
- ) + ); })}
{timeLabel}
- ) + ); } function ChatMessage({ @@ -392,10 +414,10 @@ function ChatMessage({ showAvatar = false, className, }: ChatMessageProps) { - const timestamp = new Date(message.timestamp) - const { currentUser } = useChatContext() - const radiusClass = getBubbleRadius(isOutgoing, position) - const [lightboxImage, setLightboxImage] = React.useState(null) + const timestamp = new Date(message.timestamp); + const { currentUser } = useChatContext(); + const radiusClass = getBubbleRadius(isOutgoing, position); + const [lightboxImage, setLightboxImage] = React.useState(null); return (
{/* Quoted reply */} {message.replyTo && ( - + )} {/* Text content */} @@ -463,7 +480,12 @@ function ChatMessage({ {/* Images */} {message.images && message.images.length > 0 && ( -
+
{message.images.map((img, idx) => (
-

{file.name}

-

{file.size < 1024 ? `${file.size} B` : file.size < 1048576 ? `${(file.size / 1024).toFixed(0)} KB` : `${(file.size / 1048576).toFixed(1)} MB`}

+

+ {file.name} +

+

+ {file.size < 1024 + ? `${file.size} B` + : file.size < 1048576 + ? `${(file.size / 1024).toFixed(0)} KB` + : `${(file.size / 1048576).toFixed(1)} MB`} +

))} @@ -524,20 +556,27 @@ function ChatMessage({ className="chat-content-card mt-1.5 block hover:opacity-90 transition-opacity" > {message.linkPreview.image && ( - + )}
-

{message.linkPreview.title}

-

{message.linkPreview.description}

+

+ {message.linkPreview.title} +

+

+ {message.linkPreview.description} +

{message.linkPreview.url}

)} {/* Voice message */} - {message.voice && ( - - )} + {message.voice && } {/* Inline timestamp + status + edited label */}
- {message.isEdited && ( - edited - )} + {message.isEdited && edited} - {isOutgoing && message.status && ( - - )} + {isOutgoing && message.status && }
@@ -578,37 +613,36 @@ function ChatMessage({ {/* Read receipts (group chat) — small stacked avatars */} {message.readBy && message.readBy.length > 0 && ( - + )}
{/* Image lightbox */} - {lightboxImage && typeof document !== "undefined" && createPortal( -
setLightboxImage(null)} - > - - e.stopPropagation()} - /> -
, - document.body - )} + + e.stopPropagation()} + /> +
, + document.body + )}
- ) + ); } // ─── Bubble radius helper ───────────────────────────────────────────────────── @@ -620,50 +654,42 @@ function getBubbleRadius( if (isOutgoing) { switch (position) { case "solo": - return "rounded-[18px_18px_4px_18px]" + return "rounded-[18px_18px_4px_18px]"; case "first": - return "rounded-[18px_18px_4px_18px]" + return "rounded-[18px_18px_4px_18px]"; case "middle": - return "rounded-[18px_4px_4px_18px]" + return "rounded-[18px_4px_4px_18px]"; case "last": - return "rounded-[18px_4px_18px_18px]" + return "rounded-[18px_4px_18px_18px]"; } } else { switch (position) { case "solo": - return "rounded-[18px_18px_18px_4px]" + return "rounded-[18px_18px_18px_4px]"; case "first": - return "rounded-[18px_18px_18px_4px]" + return "rounded-[18px_18px_18px_4px]"; case "middle": - return "rounded-[4px_18px_18px_4px]" + return "rounded-[4px_18px_18px_4px]"; case "last": - return "rounded-[4px_18px_18px_18px]" + return "rounded-[4px_18px_18px_18px]"; } } } // ─── ChatMessageStatus ──────────────────────────────────────────────────────── -function ChatMessageStatus({ - status, -}: { - status: NonNullable -}) { +function ChatMessageStatus({ status }: { status: NonNullable }) { switch (status) { case "sending": - return + return ; case "sent": - return + return ; case "delivered": - return + return ; case "read": - return ( - - ) + return ; case "failed": - return ( - - ) + return ; } } @@ -675,37 +701,30 @@ function ChatMessageReactions({ isOutgoing, currentUserId, }: { - messageId: string - reactions: NonNullable - isOutgoing: boolean - currentUserId: string + messageId: string; + reactions: NonNullable; + isOutgoing: boolean; + currentUserId: string; }) { - const { onReactionAdd, onReactionRemove } = useChatContext() + const { onReactionAdd, onReactionRemove } = useChatContext(); return ( -
+
{reactions.map((r) => { - const hasReacted = r.userIds.includes(currentUserId) + const hasReacted = r.userIds.includes(currentUserId); return ( - ) + ); })} {/* Add reaction button — visible on hover */}
- ) + ); } // ─── ChatReadReceipts (group chat — stacked mini avatars) ───────────────────── @@ -744,20 +761,15 @@ function ChatReadReceipts({ readBy, isOutgoing, }: { - readBy: NonNullable - isOutgoing: boolean + readBy: NonNullable; + isOutgoing: boolean; }) { - const maxVisible = 3 - const visible = readBy.slice(0, maxVisible) - const overflow = readBy.length - maxVisible + const maxVisible = 3; + const visible = readBy.slice(0, maxVisible); + const overflow = readBy.length - maxVisible; return ( -
+
{visible.map((user) => (
{overflow > 0 && ( - - +{overflow} - + +{overflow} )}
- ) + ); } // ─── ChatMessageGroup ───────────────────────────────────────────────────────── interface ChatMessageGroupProps { - group: MessageGroup - className?: string + group: MessageGroup; + className?: string; } function ChatMessageGroup({ group, className }: ChatMessageGroupProps) { - const len = group.messages.length + const len = group.messages.length; return (
{group.messages.map((msg, i) => { const position: "solo" | "first" | "middle" | "last" = - len === 1 - ? "solo" - : i === 0 - ? "first" - : i === len - 1 - ? "last" - : "middle" + len === 1 ? "solo" : i === 0 ? "first" : i === len - 1 ? "last" : "middle"; return ( - ) + ); })}
- ) + ); } // ─── ChatDateSeparator ──────────────────────────────────────────────────────── interface ChatDateSeparatorProps { - label: string - className?: string + label: string; + className?: string; } function ChatDateSeparator({ label, className }: ChatDateSeparatorProps) { return ( -
+
{label}
- ) + ); } // ─── ChatSystemMessage ──────────────────────────────────────────────────────── interface ChatSystemMessageProps { - message: ChatMessageData - className?: string + message: ChatMessageData; + className?: string; } function ChatSystemMessage({ message, className }: ChatSystemMessageProps) { return ( -
+
{message.text || message.systemEvent}
- ) + ); } // ─── ChatTypingIndicator ────────────────────────────────────────────────────── interface ChatTypingIndicatorProps { - users: TypingUser[] - className?: string + users: TypingUser[]; + className?: string; } function ChatTypingIndicator({ users, className }: ChatTypingIndicatorProps) { - const { labels } = useChatContext() - if (users.length === 0) return null + const { labels } = useChatContext(); + if (users.length === 0) return null; const label = users.length === 1 ? (labels?.typingOne?.replace("{{name}}", users[0]!.name) ?? `${users[0]!.name} is typing`) : users.length === 2 - ? (labels?.typingTwo?.replace("{{name1}}", users[0]!.name).replace("{{name2}}", users[1]!.name) ?? `${users[0]!.name} and ${users[1]!.name} are typing`) - : (labels?.typingMany ?? "Several people are typing") + ? (labels?.typingTwo + ?.replace("{{name1}}", users[0]!.name) + .replace("{{name2}}", users[1]!.name) ?? + `${users[0]!.name} and ${users[1]!.name} are typing`) + : (labels?.typingMany ?? "Several people are typing"); return ( -
+
{/* Avatar */}
{users[0]!.avatar ? ( @@ -915,9 +907,7 @@ function ChatTypingIndicator({ users, className }: ChatTypingIndicatorProps) {
{/* Label */} - - {label} - + {label} {/* Dots bubble */}
@@ -936,37 +926,28 @@ function ChatTypingIndicator({ users, className }: ChatTypingIndicatorProps) {
- ) + ); } // ─── ChatReplyPreview (bar above composer) ──────────────────────────────────── interface ChatReplyPreviewProps { - replyingTo: ChatMessageData - onCancel: () => void - className?: string + replyingTo: ChatMessageData; + onCancel: () => void; + className?: string; } -function ChatReplyPreview({ - replyingTo, - onCancel, - className, -}: ChatReplyPreviewProps) { +function ChatReplyPreview({ replyingTo, onCancel, className }: ChatReplyPreviewProps) { return (
{replyingTo.senderName} - - {replyingTo.text} - + {replyingTo.text}
- ) + ); } // ─── ChatMessages (scroll container) ────────────────────────────────────────── interface ChatMessagesProps { - messages: ChatMessageData[] - typingUsers?: TypingUser[] - className?: string - onLoadMore?: () => Promise - hasMore?: boolean + messages: ChatMessageData[]; + typingUsers?: TypingUser[]; + className?: string; + onLoadMore?: () => Promise; + hasMore?: boolean; } -function ChatMessages({ - messages, - typingUsers = [], - className, -}: ChatMessagesProps) { - const { currentUser, messageGroupingInterval, labels } = useChatContext() - const { containerRef, scrollToBottom, isAtBottom, unseenCount } = - useAutoScroll(messages) +function ChatMessages({ messages, typingUsers = [], className }: ChatMessagesProps) { + const { currentUser, messageGroupingInterval, labels } = useChatContext(); + const { containerRef, scrollToBottom, isAtBottom, unseenCount } = useAutoScroll(messages); const items = React.useMemo( () => groupMessages(messages, currentUser.id, messageGroupingInterval), [messages, currentUser.id, messageGroupingInterval] - ) + ); return ( -
+
{/* Scrollable area */}
{ switch (item.type) { case "date": - return ( - - ) + return ; case "system": - return ( - - ) + return ; case "group": return ( - ) + ); } })} {/* Typing indicator at the bottom */} - {typingUsers.length > 0 && ( - - )} + {typingUsers.length > 0 && }
@@ -1056,12 +1015,9 @@ function ChatMessages({ onClick={() => scrollToBottom("smooth")} className={cn( "absolute bottom-4 right-4 z-5 flex size-10 items-center justify-center rounded-full border border-border bg-background shadow-md transition-all duration-200", - isAtBottom - ? "pointer-events-none translate-y-2 opacity-0" - : "translate-y-0 opacity-100" + isAtBottom ? "pointer-events-none translate-y-2 opacity-0" : "translate-y-0 opacity-100" )} - aria-label={labels?.scrollToBottom ?? "Scroll to bottom" - } + aria-label={labels?.scrollToBottom ?? "Scroll to bottom"} > {/* Unread badge */} @@ -1072,26 +1028,20 @@ function ChatMessages({ )}
- ) + ); } // ─── File preview item ──────────────────────────────────────────────────────── interface FilePreviewItem { - file: File - id: string - preview?: string // data URL for images - progress?: number // 0-100 + file: File; + id: string; + preview?: string; // data URL for images + progress?: number; // 0-100 } -function ChatFilePreview({ - item, - onRemove, -}: { - item: FilePreviewItem - onRemove: () => void -}) { - const isImage = item.file.type.startsWith("image/") +function ChatFilePreview({ item, onRemove }: { item: FilePreviewItem; onRemove: () => void }) { + const isImage = item.file.type.startsWith("image/"); return (
@@ -1105,15 +1055,22 @@ function ChatFilePreview({
-

{item.file.name}

-

{(item.file.size / 1024).toFixed(0)} KB

+

+ {item.file.name} +

+

+ {(item.file.size / 1024).toFixed(0)} KB +

)} {/* Progress bar */} {item.progress !== undefined && item.progress < 100 && (
-
+
)} {/* Remove button */} @@ -1125,21 +1082,21 @@ function ChatFilePreview({
- ) + ); } // ─── ChatComposer ───────────────────────────────────────────────────────────── interface ChatComposerProps { - onSend?: (text: string) => void - onTyping?: (isTyping: boolean) => void - onFileUpload?: (files: File[]) => void - onVoiceRecord?: () => void - placeholder?: string - disabled?: boolean - replyingTo?: ChatMessageData | null - onCancelReply?: () => void - className?: string + onSend?: (text: string) => void; + onTyping?: (isTyping: boolean) => void; + onFileUpload?: (files: File[]) => void; + onVoiceRecord?: () => void; + placeholder?: string; + disabled?: boolean; + replyingTo?: ChatMessageData | null; + onCancelReply?: () => void; + className?: string; } function ChatComposer({ @@ -1153,103 +1110,112 @@ function ChatComposer({ onCancelReply, className, }: ChatComposerProps) { - const [value, setValue] = React.useState("") - const [files, setFiles] = React.useState([]) - const [isDragging, setIsDragging] = React.useState(false) + const [value, setValue] = React.useState(""); + const [files, setFiles] = React.useState([]); + const [isDragging, setIsDragging] = React.useState(false); // const [showAttachMenu, setShowAttachMenu] = React.useState(false) - const { textareaRef, resize } = useAutoResize({ maxRows: 6 }) - const { handleKeyDown: handleTypingKeyDown, stopTyping } = - useTypingIndicator({ onTypingChange: onTyping }) + const { textareaRef, resize } = useAutoResize({ maxRows: 6 }); + const { handleKeyDown: handleTypingKeyDown, stopTyping } = useTypingIndicator({ + onTypingChange: onTyping, + }); // const fileInputRef = React.useRef(null) // const imageInputRef = React.useRef(null) - const hasContent = value.trim().length > 0 || files.length > 0 + const hasContent = value.trim().length > 0 || files.length > 0; - const addFiles = React.useCallback((newFiles: FileList | File[]) => { - const arr = Array.from(newFiles) - const items: FilePreviewItem[] = arr.map((f) => ({ - file: f, - id: `${f.name}-${Date.now()}-${Math.random()}`, - progress: undefined, - })) + const addFiles = React.useCallback( + (newFiles: FileList | File[]) => { + const arr = Array.from(newFiles); + const items: FilePreviewItem[] = arr.map((f) => ({ + file: f, + id: `${f.name}-${Date.now()}-${Math.random()}`, + progress: undefined, + })); - // Generate image previews - items.forEach((item) => { - if (item.file.type.startsWith("image/")) { - const reader = new FileReader() - reader.onload = (e) => { - setFiles((prev) => - prev.map((f) => f.id === item.id ? { ...f, preview: e.target?.result as string } : f) - ) + // Generate image previews + items.forEach((item) => { + if (item.file.type.startsWith("image/")) { + const reader = new FileReader(); + reader.onload = (e) => { + setFiles((prev) => + prev.map((f) => + f.id === item.id ? { ...f, preview: e.target?.result as string } : f + ) + ); + }; + reader.readAsDataURL(item.file); } - reader.readAsDataURL(item.file) - } - }) + }); - setFiles((prev) => [...prev, ...items]) - onFileUpload?.(arr) - }, [onFileUpload]) + setFiles((prev) => [...prev, ...items]); + onFileUpload?.(arr); + }, + [onFileUpload] + ); const removeFile = React.useCallback((id: string) => { - setFiles((prev) => prev.filter((f) => f.id !== id)) - }, []) + setFiles((prev) => prev.filter((f) => f.id !== id)); + }, []); const handleSend = React.useCallback(() => { - const trimmed = value.trim() - if ((!trimmed && files.length === 0) || disabled) return - if (trimmed) onSend?.(trimmed) - setValue("") - setFiles([]) - stopTyping() - if (textareaRef.current) textareaRef.current.style.height = "auto" - }, [value, files, disabled, onSend, textareaRef, stopTyping]) + const trimmed = value.trim(); + if ((!trimmed && files.length === 0) || disabled) return; + if (trimmed) onSend?.(trimmed); + setValue(""); + setFiles([]); + stopTyping(); + if (textareaRef.current) textareaRef.current.style.height = "auto"; + }, [value, files, disabled, onSend, textareaRef, stopTyping]); const handleKeyDown = React.useCallback( (e: React.KeyboardEvent) => { - handleTypingKeyDown() - if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); handleSend() } - if (e.key === "Escape" && replyingTo) onCancelReply?.() + handleTypingKeyDown(); + if (e.key === "Enter" && !e.shiftKey) { + e.preventDefault(); + handleSend(); + } + if (e.key === "Escape" && replyingTo) onCancelReply?.(); }, [handleSend, handleTypingKeyDown, replyingTo, onCancelReply] - ) + ); // Paste upload const handlePaste = React.useCallback( (e: React.ClipboardEvent) => { - const items = e.clipboardData?.items - if (!items) return - const imageFiles: File[] = [] + const items = e.clipboardData?.items; + if (!items) return; + const imageFiles: File[] = []; for (const item of Array.from(items)) { if (item.type.startsWith("image/")) { - const file = item.getAsFile() - if (file) imageFiles.push(file) + const file = item.getAsFile(); + if (file) imageFiles.push(file); } } if (imageFiles.length > 0) { - addFiles(imageFiles) + addFiles(imageFiles); } }, [addFiles] - ) + ); // Drag-and-drop handlers (on the composer container) const handleDragOver = React.useCallback((e: React.DragEvent) => { - e.preventDefault() - setIsDragging(true) - }, []) + e.preventDefault(); + setIsDragging(true); + }, []); const handleDragLeave = React.useCallback((e: React.DragEvent) => { - e.preventDefault() - setIsDragging(false) - }, []) + e.preventDefault(); + setIsDragging(false); + }, []); const handleDrop = React.useCallback( (e: React.DragEvent) => { - e.preventDefault() - setIsDragging(false) + e.preventDefault(); + setIsDragging(false); if (e.dataTransfer.files.length > 0) { - addFiles(e.dataTransfer.files) + addFiles(e.dataTransfer.files); } }, [addFiles] - ) + ); return (
{ setValue(e.target.value); resize() }} + onChange={(e) => { + setValue(e.target.value); + resize(); + }} onKeyDown={handleKeyDown} onPaste={handlePaste} placeholder={placeholder} @@ -1374,7 +1343,7 @@ function ChatComposer({
- ) + ); } // ─── Exports ────────────────────────────────────────────────────────────────── @@ -1394,7 +1363,7 @@ export { ChatTypingIndicator, ChatReplyPreview, ChatReadReceipts, -} +}; export type { ChatProviderProps, ChatMessageProps, @@ -1406,4 +1375,4 @@ export type { ChatMessageActionsProps, ChatTypingIndicatorProps, ChatReplyPreviewProps, -} +}; diff --git a/packages/chat-ui/src/components/features.tsx b/packages/chat-ui/src/components/features.tsx index b3589db..c058aed 100644 --- a/packages/chat-ui/src/components/features.tsx +++ b/packages/chat-ui/src/components/features.tsx @@ -1,33 +1,33 @@ -import * as React from "react" -import { cn } from "@xtablo/shared" +import { cn } from "@xtablo/shared"; import { - X, - Search, - Pin, + ArrowDown, + ArrowUp, + Check, ChevronDown, ChevronRight, - ArrowUp, - ArrowDown, + Pin, + Search, Trash2, - Check, -} from "lucide-react" -import type { ChatMessageData } from "../types" -import { formatTimestamp } from "../hooks" + X, +} from "lucide-react"; +import * as React from "react"; +import { formatTimestamp } from "../hooks"; +import type { ChatMessageData } from "../types"; // ─── ChatForwardDialog ──────────────────────────────────────────────────────── interface Conversation { - id: string - title: string - avatar?: string + id: string; + title: string; + avatar?: string; } interface ChatForwardDialogProps { - message: ChatMessageData - conversations: Conversation[] - onForward: (targetIds: string[]) => void - onCancel: () => void - className?: string + message: ChatMessageData; + conversations: Conversation[]; + onForward: (targetIds: string[]) => void; + onCancel: () => void; + className?: string; } function ChatForwardDialog({ @@ -37,24 +37,24 @@ function ChatForwardDialog({ onCancel, className, }: ChatForwardDialogProps) { - const [query, setQuery] = React.useState("") - const [selected, setSelected] = React.useState>(new Set()) + const [query, setQuery] = React.useState(""); + const [selected, setSelected] = React.useState>(new Set()); - const filtered = conversations.filter((c) => - c.title.toLowerCase().includes(query.toLowerCase()) - ) + const filtered = conversations.filter((c) => c.title.toLowerCase().includes(query.toLowerCase())); const toggle = (id: string) => { setSelected((prev) => { - const next = new Set(prev) - if (next.has(id)) next.delete(id) - else next.add(id) - return next - }) - } + const next = new Set(prev); + if (next.has(id)) next.delete(id); + else next.add(id); + return next; + }); + }; return ( -
+
{/* Header */}
@@ -66,7 +66,9 @@ function ChatForwardDialog({ {/* Preview */}
- {message.senderName} + + {message.senderName} +

{message.text}

@@ -106,7 +108,10 @@ function ChatForwardDialog({ {/* Actions */}
-
- ) + ); } // ─── ChatEditComposer (inline edit mode) ────────────────────────────────────── interface ChatEditComposerProps { - message: ChatMessageData - onSave: (messageId: string, newText: string) => void - onCancel: () => void - className?: string + message: ChatMessageData; + onSave: (messageId: string, newText: string) => void; + onCancel: () => void; + className?: string; } -function ChatEditComposer({ - message, - onSave, - onCancel, - className, -}: ChatEditComposerProps) { - const [value, setValue] = React.useState(message.text || "") +function ChatEditComposer({ message, onSave, onCancel, className }: ChatEditComposerProps) { + const [value, setValue] = React.useState(message.text || ""); return (
{/* Edit bar */}
Editing message -
@@ -153,8 +156,11 @@ function ChatEditComposer({ value={value} onChange={(e) => setValue(e.target.value)} onKeyDown={(e) => { - if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); onSave(message.id, value.trim()) } - if (e.key === "Escape") onCancel() + if (e.key === "Enter" && !e.shiftKey) { + e.preventDefault(); + onSave(message.id, value.trim()); + } + if (e.key === "Escape") onCancel(); }} rows={1} autoFocus @@ -169,14 +175,14 @@ function ChatEditComposer({
- ) + ); } // ─── ChatDeletedMessage (placeholder) ───────────────────────────────────────── interface ChatDeletedMessageProps { - deletedBy?: string - className?: string + deletedBy?: string; + className?: string; } function ChatDeletedMessage({ deletedBy, className }: ChatDeletedMessageProps) { @@ -187,17 +193,17 @@ function ChatDeletedMessage({ deletedBy, className }: ChatDeletedMessageProps) { {deletedBy ? `${deletedBy} deleted this message` : "This message was deleted"}
- ) + ); } // ─── ChatPinnedPanel ────────────────────────────────────────────────────────── interface ChatPinnedPanelProps { - pinnedMessages: ChatMessageData[] - onUnpin: (messageId: string) => void - onJumpTo: (messageId: string) => void - onClose: () => void - className?: string + pinnedMessages: ChatMessageData[]; + onUnpin: (messageId: string) => void; + onJumpTo: (messageId: string) => void; + onClose: () => void; + className?: string; } function ChatPinnedPanel({ @@ -227,17 +233,25 @@ function ChatPinnedPanel({ className="border-b border-border px-4 py-3 transition-colors hover:bg-accent" >
- {msg.senderName} + + {msg.senderName} + {formatTimestamp(new Date(msg.timestamp))}

{msg.text}

- -
@@ -250,27 +264,27 @@ function ChatPinnedPanel({ )}
- ) + ); } // ─── ChatNestedThread ───────────────────────────────────────────────────────── interface ThreadedMessage extends ChatMessageData { - parentId: string | null - children: ThreadedMessage[] - depth: number - votes?: number - userVote?: "up" | "down" | null - isCollapsed?: boolean + parentId: string | null; + children: ThreadedMessage[]; + depth: number; + votes?: number; + userVote?: "up" | "down" | null; + isCollapsed?: boolean; } interface ChatNestedThreadProps { - messages: ThreadedMessage[] - maxDepth?: number - onReply?: (parentId: string) => void - onVote?: (messageId: string, direction: "up" | "down") => void - showVotes?: boolean - className?: string + messages: ThreadedMessage[]; + maxDepth?: number; + onReply?: (parentId: string) => void; + onVote?: (messageId: string, direction: "up" | "down") => void; + showVotes?: boolean; + className?: string; } function ChatNestedThread({ @@ -294,7 +308,7 @@ function ChatNestedThread({ /> ))}
- ) + ); } function ThreadMessage({ @@ -304,29 +318,30 @@ function ThreadMessage({ onVote, showVotes, }: { - message: ThreadedMessage - maxDepth: number - onReply?: (parentId: string) => void - onVote?: (messageId: string, direction: "up" | "down") => void - showVotes: boolean + message: ThreadedMessage; + maxDepth: number; + onReply?: (parentId: string) => void; + onVote?: (messageId: string, direction: "up" | "down") => void; + showVotes: boolean; }) { - const [collapsed, setCollapsed] = React.useState(message.isCollapsed ?? false) - const atMaxDepth = message.depth >= maxDepth + const [collapsed, setCollapsed] = React.useState(message.isCollapsed ?? false); + const atMaxDepth = message.depth >= maxDepth; return (
{/* Thread connector line */} - {message.depth > 0 && ( -
- )} + {message.depth > 0 &&
} {/* Vote buttons */} {showVotes && (
@@ -335,7 +350,10 @@ function ThreadMessage({ @@ -353,7 +371,10 @@ function ThreadMessage({

{message.text}

{!atMaxDepth && ( - )} @@ -362,7 +383,11 @@ function ThreadMessage({ onClick={() => setCollapsed(!collapsed)} className="flex items-center gap-0.5 text-[11px] font-medium text-muted-foreground hover:text-foreground" > - {collapsed ? : } + {collapsed ? ( + + ) : ( + + )} {message.children.length} {message.children.length === 1 ? "reply" : "replies"} )} @@ -392,53 +417,63 @@ function ThreadMessage({ )}
- ) + ); } // ─── ChatSearch ─────────────────────────────────────────────────────────────── interface SearchResult { - messageId: string - conversationId?: string - conversationName?: string - senderName: string - snippet: string - timestamp: Date | number + messageId: string; + conversationId?: string; + conversationName?: string; + senderName: string; + snippet: string; + timestamp: Date | number; } interface ChatSearchProps { - onSearch: (query: string) => SearchResult[] | Promise - onSelect: (result: SearchResult) => void - onClose: () => void - className?: string + onSearch: (query: string) => SearchResult[] | Promise; + onSelect: (result: SearchResult) => void; + onClose: () => void; + className?: string; } function ChatSearch({ onSearch, onSelect, onClose, className }: ChatSearchProps) { - const [query, setQuery] = React.useState("") - const [results, setResults] = React.useState([]) - const inputRef = React.useRef(null) + const [query, setQuery] = React.useState(""); + const [results, setResults] = React.useState([]); + const inputRef = React.useRef(null); React.useEffect(() => { - inputRef.current?.focus() - }, []) + inputRef.current?.focus(); + }, []); React.useEffect(() => { - if (!query.trim()) { setResults([]); return } + if (!query.trim()) { + setResults([]); + return; + } const timeout = setTimeout(async () => { - const r = await onSearch(query) - setResults(r) - }, 200) - return () => clearTimeout(timeout) - }, [query, onSearch]) + const r = await onSearch(query); + setResults(r); + }, 200); + return () => clearTimeout(timeout); + }, [query, onSearch]); React.useEffect(() => { - const handler = (e: KeyboardEvent) => { if (e.key === "Escape") onClose() } - document.addEventListener("keydown", handler) - return () => document.removeEventListener("keydown", handler) - }, [onClose]) + const handler = (e: KeyboardEvent) => { + if (e.key === "Escape") onClose(); + }; + document.addEventListener("keydown", handler); + return () => document.removeEventListener("keydown", handler); + }, [onClose]); return ( -
+
{/* Search input */}
@@ -451,7 +486,9 @@ function ChatSearch({ onSearch, onSelect, onClose, className }: ChatSearchProps) placeholder="Search messages..." className="flex-1 bg-transparent text-[15px] text-foreground placeholder:text-muted-foreground/60 outline-none" /> - ESC + + ESC +
{/* Results */} @@ -459,13 +496,18 @@ function ChatSearch({ onSearch, onSelect, onClose, className }: ChatSearchProps) {results.map((r) => (
- ) + ); } // ─── Exports ────────────────────────────────────────────────────────────────── @@ -494,7 +536,7 @@ export { ChatPinnedPanel, ChatNestedThread, ChatSearch, -} +}; export type { Conversation, ChatForwardDialogProps, @@ -505,4 +547,4 @@ export type { ChatNestedThreadProps, SearchResult, ChatSearchProps, -} +}; diff --git a/packages/chat-ui/src/components/layouts.tsx b/packages/chat-ui/src/components/layouts.tsx index abc5ff5..d12e6e8 100644 --- a/packages/chat-ui/src/components/layouts.tsx +++ b/packages/chat-ui/src/components/layouts.tsx @@ -1,38 +1,43 @@ -import * as React from "react" -import { cn } from "@xtablo/shared" +import { cn } from "@xtablo/shared"; import { - MessageSquare, - Search, - Phone, - X, - ChevronLeft, - Plus, - Minimize2, - Pin, - Ticket, - Clock, AlertCircle, CheckCircle2, + ChevronLeft, Circle, + Clock, + MessageSquare, + Minimize2, + Phone, + Pin, + Plus, + Search, + Ticket, User, -} from "lucide-react" -import type { ChatMessageData, ChatUser, TypingUser } from "../types" -import { ChatProvider, ChatMessages, ChatComposer } from "./chat" + X, +} from "lucide-react"; +import * as React from "react"; +import type { ChatMessageData, ChatUser, TypingUser } from "../types"; +import { ChatComposer, ChatMessages, ChatProvider } from "./chat"; // ─── Shared: ChatHeader ─────────────────────────────────────────────────────── interface ChatHeaderProps { - title: string - subtitle?: string - avatar?: React.ReactNode - actions?: React.ReactNode - onBack?: () => void - className?: string + title: string; + subtitle?: string; + avatar?: React.ReactNode; + actions?: React.ReactNode; + onBack?: () => void; + className?: string; } function ChatHeader({ title, subtitle, avatar, actions, onBack, className }: ChatHeaderProps) { return ( -
+
{onBack && (
- ) + ); } // ─── Shared: Sidebar conversation item ──────────────────────────────────────── interface SidebarConversation { - id: string - title: string - avatar?: string - lastMessage?: string - lastMessageTime?: string - unreadCount?: number - presence?: "online" | "away" | "offline" - isGroup?: boolean + id: string; + title: string; + avatar?: string; + lastMessage?: string; + lastMessageTime?: string; + unreadCount?: number; + presence?: "online" | "away" | "offline"; + isGroup?: boolean; } function ConversationItem({ @@ -66,9 +73,9 @@ function ConversationItem({ isActive, onClick, }: { - convo: SidebarConversation - isActive: boolean - onClick: () => void + convo: SidebarConversation; + isActive: boolean; + onClick: () => void; }) { return (
@@ -103,7 +112,7 @@ function ConversationItem({
- ) + ); } // ═══════════════════════════════════════════════════════════════════════════════ @@ -111,16 +120,16 @@ function ConversationItem({ // ═══════════════════════════════════════════════════════════════════════════════ interface FullMessengerProps { - currentUser: ChatUser - conversations: SidebarConversation[] - activeConversationId?: string - onSelectConversation: (id: string) => void - messages: ChatMessageData[] - typingUsers?: TypingUser[] - onSend: (text: string) => void - title?: string - subtitle?: string - className?: string + currentUser: ChatUser; + conversations: SidebarConversation[]; + activeConversationId?: string; + onSelectConversation: (id: string) => void; + messages: ChatMessageData[]; + typingUsers?: TypingUser[]; + onSend: (text: string) => void; + title?: string; + subtitle?: string; + className?: string; } function FullMessenger({ @@ -135,8 +144,8 @@ function FullMessenger({ subtitle, className, }: FullMessengerProps) { - const activeConvo = conversations.find((c) => c.id === activeConversationId) - const showingConvo = !!activeConvo + const activeConvo = conversations.find((c) => c.id === activeConversationId); + const showingConvo = !!activeConvo; return ( - - - + + +
} /> @@ -227,14 +242,16 @@ function FullMessenger({
-

Select a conversation

+

+ Select a conversation +

)}
- ) + ); } // ═══════════════════════════════════════════════════════════════════════════════ @@ -242,14 +259,14 @@ function FullMessenger({ // ═══════════════════════════════════════════════════════════════════════════════ interface ChatWidgetProps { - currentUser: ChatUser - messages: ChatMessageData[] - onSend: (text: string) => void - title?: string - subtitle?: string - greeting?: string - position?: "bottom-right" | "bottom-left" - className?: string + currentUser: ChatUser; + messages: ChatMessageData[]; + onSend: (text: string) => void; + title?: string; + subtitle?: string; + greeting?: string; + position?: "bottom-right" | "bottom-left"; + className?: string; } function ChatWidget({ @@ -261,11 +278,17 @@ function ChatWidget({ position = "bottom-right", className, }: ChatWidgetProps) { - const [isOpen, setIsOpen] = React.useState(false) + const [isOpen, setIsOpen] = React.useState(false); return ( -
+
{/* Chat window */} {isOpen && (
@@ -278,7 +301,10 @@ function ChatWidget({
} actions={ - } @@ -298,7 +324,7 @@ function ChatWidget({
- ) + ); } // ═══════════════════════════════════════════════════════════════════════════════ @@ -306,12 +332,12 @@ function ChatWidget({ // ═══════════════════════════════════════════════════════════════════════════════ interface InlineChatProps { - currentUser: ChatUser - messages: ChatMessageData[] - onSend: (text: string) => void - placeholder?: string - maxHeight?: number - className?: string + currentUser: ChatUser; + messages: ChatMessageData[]; + onSend: (text: string) => void; + placeholder?: string; + maxHeight?: number; + className?: string; } function InlineChat({ @@ -324,12 +350,18 @@ function InlineChat({ }: InlineChatProps) { return ( -
+
- ) + ); } // ═══════════════════════════════════════════════════════════════════════════════ @@ -337,23 +369,23 @@ function InlineChat({ // ═══════════════════════════════════════════════════════════════════════════════ interface Topic { - id: string - title: string - author: string - replyCount: number - lastActivity: string - isPinned?: boolean - tags?: string[] + id: string; + title: string; + author: string; + replyCount: number; + lastActivity: string; + isPinned?: boolean; + tags?: string[]; } interface ChatBoardProps { - currentUser: ChatUser - topics: Topic[] - activeTopic?: Topic - onSelectTopic: (id: string) => void - onBack?: () => void - children?: React.ReactNode - className?: string + currentUser: ChatUser; + topics: Topic[]; + activeTopic?: Topic; + onSelectTopic: (id: string) => void; + onBack?: () => void; + children?: React.ReactNode; + className?: string; } function ChatBoard({ @@ -370,16 +402,25 @@ function ChatBoard({
{activeTopic ? ( <> - +
{children}
) : ( <> - - } /> + + + + } + />
{topics.map((t) => (
- ) + ); } // ═══════════════════════════════════════════════════════════════════════════════ @@ -420,12 +466,12 @@ function ChatBoard({ // ═══════════════════════════════════════════════════════════════════════════════ interface LiveChatProps { - currentUser: ChatUser - messages: ChatMessageData[] - onSend: (text: string) => void - title?: string - viewerCount?: number - className?: string + currentUser: ChatUser; + messages: ChatMessageData[]; + onSend: (text: string) => void; + title?: string; + viewerCount?: number; + className?: string; } function LiveChat({ @@ -452,64 +498,67 @@ function LiveChat({
- ) + ); } // ═══════════════════════════════════════════════════════════════════════════════ // LAYOUT 7: SupportTickets (Help desk / ticket queue) // ═══════════════════════════════════════════════════════════════════════════════ -type TicketStatus = "open" | "in-progress" | "resolved" -type TicketPriority = "low" | "medium" | "high" | "urgent" +type TicketStatus = "open" | "in-progress" | "resolved"; +type TicketPriority = "low" | "medium" | "high" | "urgent"; interface SupportTicket { - id: string - subject: string - customerName: string - customerAvatar?: string - status: TicketStatus - priority: TicketPriority - category?: string - tags?: string[] - createdAt: string - updatedAt?: string - lastMessage?: string - unreadCount?: number - assignee?: string + id: string; + subject: string; + customerName: string; + customerAvatar?: string; + status: TicketStatus; + priority: TicketPriority; + category?: string; + tags?: string[]; + createdAt: string; + updatedAt?: string; + lastMessage?: string; + unreadCount?: number; + assignee?: string; } interface SupportTicketsProps { - currentUser: ChatUser - tickets: SupportTicket[] - activeTicketId?: string - onSelectTicket: (id: string) => void - messages: ChatMessageData[] - typingUsers?: TypingUser[] - onSend: (text: string) => void - statusFilter?: TicketStatus | "all" - onStatusFilterChange?: (status: TicketStatus | "all") => void - title?: string - className?: string + currentUser: ChatUser; + tickets: SupportTicket[]; + activeTicketId?: string; + onSelectTicket: (id: string) => void; + messages: ChatMessageData[]; + typingUsers?: TypingUser[]; + onSend: (text: string) => void; + statusFilter?: TicketStatus | "all"; + onStatusFilterChange?: (status: TicketStatus | "all") => void; + title?: string; + className?: string; } // ─── Internal helpers ──────────────────────────────────────────────────────── -const ticketStatusConfig: Record = { +const ticketStatusConfig: Record< + TicketStatus, + { icon: typeof Circle; label: string; color: string } +> = { open: { icon: Circle, label: "Open", color: "var(--color-chart-4)" }, "in-progress": { icon: Clock, label: "In Progress", color: "var(--color-primary)" }, resolved: { icon: CheckCircle2, label: "Resolved", color: "#22c55e" }, -} +}; const ticketPriorityColors: Record = { urgent: "var(--color-destructive)", high: "var(--color-chart-4)", medium: "var(--color-primary)", low: "var(--color-muted-foreground)", -} +}; function TicketStatusBadge({ status }: { status: TicketStatus }) { - const cfg = ticketStatusConfig[status] - const Icon = cfg.icon + const cfg = ticketStatusConfig[status]; + const Icon = cfg.icon; return ( {cfg.label} - ) + ); } function TicketPriorityBadge({ priority }: { priority: TicketPriority }) { - const color = ticketPriorityColors[priority] + const color = ticketPriorityColors[priority]; return ( {priority} - ) + ); } function TicketFilterTabs({ value, onChange, }: { - value: TicketStatus | "all" - onChange: (v: TicketStatus | "all") => void + value: TicketStatus | "all"; + onChange: (v: TicketStatus | "all") => void; }) { const tabs: { key: TicketStatus | "all"; label: string }[] = [ { key: "all", label: "All" }, { key: "open", label: "Open" }, { key: "in-progress", label: "Active" }, { key: "resolved", label: "Resolved" }, - ] + ]; return (
{tabs.map((t) => ( @@ -569,7 +618,7 @@ function TicketFilterTabs({ ))}
- ) + ); } function TicketItem({ @@ -577,11 +626,11 @@ function TicketItem({ isActive, onClick, }: { - ticket: SupportTicket - isActive: boolean - onClick: () => void + ticket: SupportTicket; + isActive: boolean; + onClick: () => void; }) { - const StatusIcon = ticketStatusConfig[ticket.status].icon + const StatusIcon = ticketStatusConfig[ticket.status].icon; return ( - ) + ); } // ─── Main component ────────────────────────────────────────────────────────── @@ -644,17 +693,17 @@ function SupportTickets({ title = "Support Tickets", className, }: SupportTicketsProps) { - const [internalFilter, setInternalFilter] = React.useState("all") - const filter = controlledFilter ?? internalFilter - const setFilter = onStatusFilterChange ?? setInternalFilter + const [internalFilter, setInternalFilter] = React.useState("all"); + const filter = controlledFilter ?? internalFilter; + const setFilter = onStatusFilterChange ?? setInternalFilter; - const filteredTickets = filter === "all" ? tickets : tickets.filter((t) => t.status === filter) - const activeTicket = tickets.find((t) => t.id === activeTicketId) + const filteredTickets = filter === "all" ? tickets : tickets.filter((t) => t.status === filter); + const activeTicket = tickets.find((t) => t.id === activeTicketId); - const openCount = tickets.filter((t) => t.status === "open").length - const activeCount = tickets.filter((t) => t.status === "in-progress").length + const openCount = tickets.filter((t) => t.status === "open").length; + const activeCount = tickets.filter((t) => t.status === "in-progress").length; - const showingTicket = !!activeTicket + const showingTicket = !!activeTicket; return (
- ) + ); } // ─── Exports ────────────────────────────────────────────────────────────────── -const ChatConversationItem = ConversationItem +const ChatConversationItem = ConversationItem; export { ChatHeader, @@ -787,7 +836,7 @@ export { TicketStatusBadge, TicketPriorityBadge, TicketFilterTabs, -} +}; export type { ChatHeaderProps, SidebarConversation, @@ -801,4 +850,4 @@ export type { TicketPriority, SupportTicket, SupportTicketsProps, -} +}; diff --git a/packages/chat-ui/src/hooks.ts b/packages/chat-ui/src/hooks.ts index 467abc4..89238b8 100644 --- a/packages/chat-ui/src/hooks.ts +++ b/packages/chat-ui/src/hooks.ts @@ -1,35 +1,21 @@ -import { - useRef, - useEffect, - useCallback, - useState, -} from "react" -import { - isToday, - isYesterday, - format, - isSameDay, - differenceInSeconds, -} from "date-fns" -import type { ChatMessageData, MessageListItem, MessageGroup } from "./types" +import { differenceInSeconds, format, isSameDay, isToday, isYesterday } from "date-fns"; +import { useCallback, useEffect, useRef, useState } from "react"; +import type { ChatMessageData, MessageGroup, MessageListItem } from "./types"; // ─── Date formatting ────────────────────────────────────────────────────────── export function formatDateLabel(date: Date): string { - if (isToday(date)) return "Today" - if (isYesterday(date)) return "Yesterday" - const now = new Date() - const diffDays = Math.floor( - (now.getTime() - date.getTime()) / (1000 * 60 * 60 * 24) - ) - if (diffDays < 7) return format(date, "EEEE") // "Tuesday" - if (date.getFullYear() === now.getFullYear()) - return format(date, "MMMM d") // "March 18" - return format(date, "MMMM d, yyyy") // "March 18, 2026" + if (isToday(date)) return "Today"; + if (isYesterday(date)) return "Yesterday"; + const now = new Date(); + const diffDays = Math.floor((now.getTime() - date.getTime()) / (1000 * 60 * 60 * 24)); + if (diffDays < 7) return format(date, "EEEE"); // "Tuesday" + if (date.getFullYear() === now.getFullYear()) return format(date, "MMMM d"); // "March 18" + return format(date, "MMMM d, yyyy"); // "March 18, 2026" } export function formatTimestamp(date: Date): string { - return format(date, "h:mm a") // "10:42 AM" + return format(date, "h:mm a"); // "10:42 AM" } // ─── Message grouping ───────────────────────────────────────────────────────── @@ -39,40 +25,40 @@ export function groupMessages( currentUserId: string, intervalSeconds: number = 120 ): MessageListItem[] { - if (messages.length === 0) return [] + if (messages.length === 0) return []; - const items: MessageListItem[] = [] - let currentGroup: MessageGroup | null = null - let lastDate: Date | null = null + const items: MessageListItem[] = []; + let currentGroup: MessageGroup | null = null; + let lastDate: Date | null = null; for (const msg of messages) { - const msgDate = new Date(msg.timestamp) + const msgDate = new Date(msg.timestamp); // System messages break groups if (msg.isSystem) { if (currentGroup) { - items.push({ type: "group", group: currentGroup }) - currentGroup = null + items.push({ type: "group", group: currentGroup }); + currentGroup = null; } // Insert date separator if needed if (!lastDate || !isSameDay(lastDate, msgDate)) { - items.push({ type: "date", date: msgDate, label: formatDateLabel(msgDate) }) - lastDate = msgDate + items.push({ type: "date", date: msgDate, label: formatDateLabel(msgDate) }); + lastDate = msgDate; } - items.push({ type: "system", message: msg }) - continue + items.push({ type: "system", message: msg }); + continue; } // Insert date separator if needed if (!lastDate || !isSameDay(lastDate, msgDate)) { if (currentGroup) { - items.push({ type: "group", group: currentGroup }) - currentGroup = null + items.push({ type: "group", group: currentGroup }); + currentGroup = null; } - items.push({ type: "date", date: msgDate, label: formatDateLabel(msgDate) }) - lastDate = msgDate + items.push({ type: "date", date: msgDate, label: formatDateLabel(msgDate) }); + lastDate = msgDate; } // Check if message should continue the current group @@ -82,16 +68,14 @@ export function groupMessages( currentGroup.messages.length > 0 && differenceInSeconds( msgDate, - new Date( - currentGroup.messages[currentGroup.messages.length - 1]!.timestamp - ) - ) <= intervalSeconds + new Date(currentGroup.messages[currentGroup.messages.length - 1]!.timestamp) + ) <= intervalSeconds; if (shouldGroup && currentGroup) { - currentGroup.messages.push(msg) + currentGroup.messages.push(msg); } else { if (currentGroup) { - items.push({ type: "group", group: currentGroup }) + items.push({ type: "group", group: currentGroup }); } currentGroup = { senderId: msg.senderId, @@ -99,133 +83,126 @@ export function groupMessages( senderAvatar: msg.senderAvatar, messages: [msg], isOutgoing: msg.senderId === currentUserId, - } + }; } } if (currentGroup) { - items.push({ type: "group", group: currentGroup }) + items.push({ type: "group", group: currentGroup }); } - return items + return items; } // ─── Auto-scroll hook ───────────────────────────────────────────────────────── -export function useAutoScroll( - messages: ChatMessageData[], - opts?: { threshold?: number } -) { - const containerRef = useRef(null) - const [isAtBottom, setIsAtBottom] = useState(true) - const [unseenCount, setUnseenCount] = useState(0) - const prevLengthRef = useRef(messages.length) - const threshold = opts?.threshold ?? 100 +export function useAutoScroll(messages: ChatMessageData[], opts?: { threshold?: number }) { + const containerRef = useRef(null); + const [isAtBottom, setIsAtBottom] = useState(true); + const [unseenCount, setUnseenCount] = useState(0); + const prevLengthRef = useRef(messages.length); + const threshold = opts?.threshold ?? 100; - const scrollToBottom = useCallback( - (behavior: ScrollBehavior = "smooth") => { - const el = containerRef.current - if (!el) return - el.scrollTo({ top: el.scrollHeight, behavior }) - setUnseenCount(0) - }, - [] - ) + const scrollToBottom = useCallback((behavior: ScrollBehavior = "smooth") => { + const el = containerRef.current; + if (!el) return; + el.scrollTo({ top: el.scrollHeight, behavior }); + setUnseenCount(0); + }, []); // Track scroll position useEffect(() => { - const el = containerRef.current - if (!el) return + const el = containerRef.current; + if (!el) return; const handleScroll = () => { - const distanceFromBottom = - el.scrollHeight - el.scrollTop - el.clientHeight - const atBottom = distanceFromBottom <= threshold - setIsAtBottom(atBottom) - if (atBottom) setUnseenCount(0) - } + const distanceFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight; + const atBottom = distanceFromBottom <= threshold; + setIsAtBottom(atBottom); + if (atBottom) setUnseenCount(0); + }; - el.addEventListener("scroll", handleScroll, { passive: true }) - return () => el.removeEventListener("scroll", handleScroll) - }, [threshold]) + el.addEventListener("scroll", handleScroll, { passive: true }); + return () => el.removeEventListener("scroll", handleScroll); + }, [threshold]); // Auto-scroll when new messages arrive and user is at bottom useEffect(() => { - const newCount = messages.length - prevLengthRef.current - prevLengthRef.current = messages.length + const newCount = messages.length - prevLengthRef.current; + prevLengthRef.current = messages.length; - if (newCount <= 0) return + if (newCount <= 0) return; if (isAtBottom) { - scrollToBottom("smooth") + scrollToBottom("smooth"); } else { - setUnseenCount((c) => c + newCount) + setUnseenCount((c) => c + newCount); } // eslint-disable-next-line react-hooks/exhaustive-deps - }, [messages.length]) + }, [messages.length]); // Scroll to bottom on mount useEffect(() => { - scrollToBottom("instant") + scrollToBottom("instant"); // eslint-disable-next-line react-hooks/exhaustive-deps - }, []) + }, []); - return { containerRef, scrollToBottom, isAtBottom, unseenCount } as const + return { containerRef, scrollToBottom, isAtBottom, unseenCount } as const; } // ─── Auto-resize textarea hook ──────────────────────────────────────────────── export function useAutoResize(opts?: { maxRows?: number }) { - const textareaRef = useRef(null) - const maxRows = opts?.maxRows ?? 6 + const textareaRef = useRef(null); + const maxRows = opts?.maxRows ?? 6; const resize = useCallback(() => { - const el = textareaRef.current - if (!el) return - el.style.height = "auto" - const lineHeight = parseInt(getComputedStyle(el).lineHeight) || 22 - const maxHeight = lineHeight * maxRows - el.style.height = `${Math.min(el.scrollHeight, maxHeight)}px` - el.style.overflowY = el.scrollHeight > maxHeight ? "auto" : "hidden" - }, [maxRows]) + const el = textareaRef.current; + if (!el) return; + el.style.height = "auto"; + const lineHeight = parseInt(getComputedStyle(el).lineHeight) || 22; + const maxHeight = lineHeight * maxRows; + el.style.height = `${Math.min(el.scrollHeight, maxHeight)}px`; + el.style.overflowY = el.scrollHeight > maxHeight ? "auto" : "hidden"; + }, [maxRows]); - return { textareaRef, resize } as const + return { textareaRef, resize } as const; } // ─── Typing indicator hook ──────────────────────────────────────────────────── export function useTypingIndicator(opts?: { - onTypingChange?: (isTyping: boolean) => void - debounceMs?: number + onTypingChange?: (isTyping: boolean) => void; + debounceMs?: number; }) { - const [isTyping, setIsTyping] = useState(false) - const timeoutRef = useRef | null>(null) - const debounceMs = opts?.debounceMs ?? 2000 + const [isTyping, setIsTyping] = useState(false); + const timeoutRef = useRef | null>(null); + const debounceMs = opts?.debounceMs ?? 2000; const handleKeyDown = useCallback(() => { if (!isTyping) { - setIsTyping(true) - opts?.onTypingChange?.(true) + setIsTyping(true); + opts?.onTypingChange?.(true); } - if (timeoutRef.current) clearTimeout(timeoutRef.current) + if (timeoutRef.current) clearTimeout(timeoutRef.current); timeoutRef.current = setTimeout(() => { - setIsTyping(false) - opts?.onTypingChange?.(false) - }, debounceMs) - }, [isTyping, debounceMs, opts]) + setIsTyping(false); + opts?.onTypingChange?.(false); + }, debounceMs); + }, [isTyping, debounceMs, opts]); const stopTyping = useCallback(() => { - if (timeoutRef.current) clearTimeout(timeoutRef.current) - setIsTyping(false) - opts?.onTypingChange?.(false) - }, [opts]) + if (timeoutRef.current) clearTimeout(timeoutRef.current); + setIsTyping(false); + opts?.onTypingChange?.(false); + }, [opts]); useEffect(() => { return () => { - if (timeoutRef.current) clearTimeout(timeoutRef.current) - } - }, []) + if (timeoutRef.current) clearTimeout(timeoutRef.current); + }; + }, []); - return { isTyping, handleKeyDown, stopTyping } as const + return { isTyping, handleKeyDown, stopTyping } as const; } diff --git a/packages/chat-ui/src/index.ts b/packages/chat-ui/src/index.ts index 2ea8fee..24721f7 100644 --- a/packages/chat-ui/src/index.ts +++ b/packages/chat-ui/src/index.ts @@ -1,114 +1,110 @@ // Core components -export { - ChatProvider, - ChatMessage, - ChatMessageGroup, - ChatDateSeparator, - ChatSystemMessage, - ChatMessages, - ChatComposer, - ChatMessageStatus, - ChatMessageReactions, - ChatMessageActions, - ChatMessageReply, - ChatTypingIndicator, - ChatReplyPreview, - ChatReadReceipts, -} from "./components/chat" -export type { - ChatProviderProps, - ChatMessageProps, - ChatMessageGroupProps, - ChatDateSeparatorProps, - ChatSystemMessageProps, - ChatMessagesProps, - ChatComposerProps, - ChatMessageActionsProps, - ChatTypingIndicatorProps, - ChatReplyPreviewProps, -} from "./components/chat" +export type { + ChatComposerProps, + ChatDateSeparatorProps, + ChatMessageActionsProps, + ChatMessageGroupProps, + ChatMessageProps, + ChatMessagesProps, + ChatProviderProps, + ChatReplyPreviewProps, + ChatSystemMessageProps, + ChatTypingIndicatorProps, +} from "./components/chat"; +export { + ChatComposer, + ChatDateSeparator, + ChatMessage, + ChatMessageActions, + ChatMessageGroup, + ChatMessageReactions, + ChatMessageReply, + ChatMessageStatus, + ChatMessages, + ChatProvider, + ChatReadReceipts, + ChatReplyPreview, + ChatSystemMessage, + ChatTypingIndicator, +} from "./components/chat"; +export type { + ChatDeletedMessageProps, + ChatEditComposerProps, + ChatForwardDialogProps, + ChatNestedThreadProps, + ChatPinnedPanelProps, + ChatSearchProps, + Conversation, + SearchResult, + ThreadedMessage, +} from "./components/features"; // Feature components export { - ChatForwardDialog, - ChatEditComposer, ChatDeletedMessage, - ChatPinnedPanel, + ChatEditComposer, + ChatForwardDialog, ChatNestedThread, + ChatPinnedPanel, ChatSearch, -} from "./components/features" +} from "./components/features"; export type { - Conversation, - ChatForwardDialogProps, - ChatEditComposerProps, - ChatDeletedMessageProps, - ChatPinnedPanelProps, - ThreadedMessage, - ChatNestedThreadProps, - SearchResult, - ChatSearchProps, -} from "./components/features" - -// Pre-built layouts -export { - ChatHeader, - ChatConversationItem, - FullMessenger, - ChatWidget, - InlineChat, - ChatBoard, - LiveChat, - SupportTickets, - TicketStatusBadge, - TicketPriorityBadge, - TicketFilterTabs, -} from "./components/layouts" -export type { - ChatHeaderProps, - SidebarConversation, - FullMessengerProps, - ChatWidgetProps, - InlineChatProps, - Topic, ChatBoardProps, + ChatHeaderProps, + ChatWidgetProps, + FullMessengerProps, + InlineChatProps, LiveChatProps, - TicketStatus, - TicketPriority, + SidebarConversation, SupportTicket, SupportTicketsProps, -} from "./components/layouts" - + TicketPriority, + TicketStatus, + Topic, +} from "./components/layouts"; +// Pre-built layouts +export { + ChatBoard, + ChatConversationItem, + ChatHeader, + ChatWidget, + FullMessenger, + InlineChat, + LiveChat, + SupportTickets, + TicketFilterTabs, + TicketPriorityBadge, + TicketStatusBadge, +} from "./components/layouts"; +// Hooks +export { + formatDateLabel, + formatTimestamp, + groupMessages, + useAutoResize, + useAutoScroll, + useTypingIndicator, +} from "./hooks"; +export type { FileValidationResult } from "./security"; // Security utilities export { - sanitizeUrl, displayHostname, + formatReactionCount, + isValidEmoji, + sanitizeFileName, + sanitizeSenderName, + sanitizeUrl, stripBidiOverrides, truncateMessage, - sanitizeSenderName, validateFile, - sanitizeFileName, - isValidEmoji, - formatReactionCount, -} from "./security" -export type { FileValidationResult } from "./security" - +} from "./security"; // Types export type { - ChatUser, + ChatConfig, ChatLabels, ChatMessageData, - ChatConfig, + ChatUser, MessageGroup, MessageListItem, TypingUser, -} from "./types" - -// Hooks -export { - groupMessages, - useAutoScroll, - useAutoResize, - useTypingIndicator, - formatTimestamp, - formatDateLabel, -} from "./hooks" +} from "./types"; diff --git a/packages/chat-ui/src/security.ts b/packages/chat-ui/src/security.ts index 40bab72..902e5f3 100644 --- a/packages/chat-ui/src/security.ts +++ b/packages/chat-ui/src/security.ts @@ -5,22 +5,22 @@ // ─── URL Sanitization ───────────────────────────────────────────────────────── -const ALLOWED_URL_PROTOCOL = /^(https?:\/\/|mailto:)/i +const ALLOWED_URL_PROTOCOL = /^(https?:\/\/|mailto:)/i; /** Sanitize a URL — only allow http, https, and mailto. Blocks javascript:, data:, etc. */ export function sanitizeUrl(url: string | undefined | null): string { - if (!url) return "#" - const trimmed = url.trim() - if (!ALLOWED_URL_PROTOCOL.test(trimmed)) return "#" - return trimmed + if (!url) return "#"; + const trimmed = url.trim(); + if (!ALLOWED_URL_PROTOCOL.test(trimmed)) return "#"; + return trimmed; } /** Extract hostname from a URL for display (prevents misleading long URLs) */ export function displayHostname(url: string): string { try { - return new URL(url).hostname + return new URL(url).hostname; } catch { - return url + return url; } } @@ -29,7 +29,7 @@ export function displayHostname(url: string): string { /** Strip bidi override characters that can disguise malicious content (RLO attacks) */ export function stripBidiOverrides(text: string): string { // Remove LRO, RLO, LRE, RLE, PDF, LRI, RLI, FSI, PDI - return text.replace(/[\u202A-\u202E\u2066-\u2069]/g, "") + return text.replace(/[\u202A-\u202E\u2066-\u2069]/g, ""); } /** Truncate message text to prevent rendering DoS */ @@ -37,80 +37,97 @@ export function truncateMessage( text: string, maxLength: number = 10_000 ): { text: string; truncated: boolean } { - if (text.length <= maxLength) return { text, truncated: false } - return { text: text.slice(0, maxLength) + "\u2026", truncated: true } + if (text.length <= maxLength) return { text, truncated: false }; + return { text: `${text.slice(0, maxLength)}\u2026`, truncated: true }; } /** Sanitize sender name — strip bidi, truncate */ export function sanitizeSenderName(name: string): string { - return stripBidiOverrides(name).slice(0, 100) + return stripBidiOverrides(name).slice(0, 100); } // ─── File Validation ────────────────────────────────────────────────────────── const BLOCKED_EXTENSIONS = new Set([ - ".exe", ".bat", ".cmd", ".scr", ".pif", ".com", - ".js", ".jsx", ".ts", ".tsx", ".mjs", - ".html", ".htm", ".xhtml", + ".exe", + ".bat", + ".cmd", + ".scr", + ".pif", + ".com", + ".js", + ".jsx", + ".ts", + ".tsx", + ".mjs", + ".html", + ".htm", + ".xhtml", ".svg", - ".xml", ".xsl", ".xslt", - ".hta", ".vbs", ".vbe", ".wsf", ".wsh", - ".ps1", ".psm1", - ".sh", ".bash", -]) + ".xml", + ".xsl", + ".xslt", + ".hta", + ".vbs", + ".vbe", + ".wsf", + ".wsh", + ".ps1", + ".psm1", + ".sh", + ".bash", +]); -const DEFAULT_MAX_FILE_SIZE = 25 * 1024 * 1024 // 25MB +const DEFAULT_MAX_FILE_SIZE = 25 * 1024 * 1024; // 25MB export interface FileValidationResult { - valid: boolean - error?: string + valid: boolean; + error?: string; } -export function validateFile( - file: File, - opts?: { maxSize?: number } -): FileValidationResult { - const maxSize = opts?.maxSize ?? DEFAULT_MAX_FILE_SIZE +export function validateFile(file: File, opts?: { maxSize?: number }): FileValidationResult { + const maxSize = opts?.maxSize ?? DEFAULT_MAX_FILE_SIZE; // Check extension - const parts = file.name.split(".") - const ext = parts.length > 1 ? "." + parts[parts.length - 1]!.toLowerCase() : "" + const parts = file.name.split("."); + const ext = parts.length > 1 ? `.${parts[parts.length - 1]!.toLowerCase()}` : ""; if (BLOCKED_EXTENSIONS.has(ext)) { - return { valid: false, error: `File type ${ext} is not allowed` } + return { valid: false, error: `File type ${ext} is not allowed` }; } // Check size if (file.size > maxSize) { - const mbLimit = Math.round(maxSize / (1024 * 1024)) - return { valid: false, error: `File exceeds maximum size of ${mbLimit}MB` } + const mbLimit = Math.round(maxSize / (1024 * 1024)); + return { valid: false, error: `File exceeds maximum size of ${mbLimit}MB` }; } - return { valid: true } + return { valid: true }; } /** Sanitize a file name for display */ export function sanitizeFileName(name: string): string { - let clean = name.replace(/[/\\]/g, "_") // Remove path traversal - clean = clean.replace(/\0/g, "") // Remove null bytes - clean = stripBidiOverrides(clean) // Remove bidi overrides - if (clean.length > 100) clean = clean.slice(0, 97) + "..." - return clean + let clean = name.replace(/[/\\]/g, "_"); // Remove path traversal + clean = clean.replace(/\0/g, ""); // Remove null bytes + clean = stripBidiOverrides(clean); // Remove bidi overrides + if (clean.length > 100) clean = `${clean.slice(0, 97)}...`; + return clean; } // ─── Emoji Validation ───────────────────────────────────────────────────────── -const EMOJI_REGEX = /^(\p{Emoji_Presentation}|\p{Emoji}\uFE0F)(\u200D(\p{Emoji_Presentation}|\p{Emoji}\uFE0F))*$/u +const EMOJI_REGEX = + /^(\p{Emoji_Presentation}|\p{Emoji}\uFE0F)(\u200D(\p{Emoji_Presentation}|\p{Emoji}\uFE0F))*$/u; /** Validate that a string is a valid emoji (not arbitrary text) */ export function isValidEmoji(str: string): boolean { - return EMOJI_REGEX.test(str) && str.length <= 20 + return EMOJI_REGEX.test(str) && str.length <= 20; } // ─── Reaction Count Safety ──────────────────────────────────────────────────── /** Format reaction count for display (cap at 999+, floor at 0) */ export function formatReactionCount(count: number): string { - if (count <= 0) return "0" - if (count > 999) return "999+" - return String(count) + if (count <= 0) return "0"; + if (count > 999) return "999+"; + return String(count); } diff --git a/packages/chat-ui/src/types.ts b/packages/chat-ui/src/types.ts index 1a7da7e..201eb7b 100644 --- a/packages/chat-ui/src/types.ts +++ b/packages/chat-ui/src/types.ts @@ -1,84 +1,84 @@ export interface ChatUser { - id: string - name: string - avatar?: string - status?: "online" | "away" | "dnd" | "offline" + id: string; + name: string; + avatar?: string; + status?: "online" | "away" | "dnd" | "offline"; } export interface ChatMessageData { - id: string - senderId: string - senderName: string - senderAvatar?: string + id: string; + senderId: string; + senderName: string; + senderAvatar?: string; // Content - text?: string - images?: { url: string; width: number; height: number; alt?: string }[] - files?: { name: string; size: number; type: string; url: string }[] - voice?: { url: string; duration: number; waveform: number[] } + text?: string; + images?: { url: string; width: number; height: number; alt?: string }[]; + files?: { name: string; size: number; type: string; url: string }[]; + voice?: { url: string; duration: number; waveform: number[] }; linkPreview?: { - url: string - title: string - description: string - image?: string - } - code?: { language: string; code: string } + url: string; + title: string; + description: string; + image?: string; + }; + code?: { language: string; code: string }; // Metadata - timestamp: Date | number - status?: "sending" | "sent" | "delivered" | "read" | "failed" - replyTo?: { id: string; senderName: string; text: string } - reactions?: { emoji: string; userIds: string[]; count: number }[] - isEdited?: boolean - isPinned?: boolean - isSystem?: boolean - systemEvent?: string + timestamp: Date | number; + status?: "sending" | "sent" | "delivered" | "read" | "failed"; + replyTo?: { id: string; senderName: string; text: string }; + reactions?: { emoji: string; userIds: string[]; count: number }[]; + isEdited?: boolean; + isPinned?: boolean; + isSystem?: boolean; + systemEvent?: string; // Read receipts (group chat) — list of users who have read up to this message - readBy?: { userId: string; name: string; avatar?: string }[] + readBy?: { userId: string; name: string; avatar?: string }[]; } export interface ChatLabels { - composerPlaceholder?: string - typingOne?: string // e.g. "{{name}} is typing" - typingTwo?: string // e.g. "{{name1}} and {{name2}} are typing" - typingMany?: string // e.g. "Several people are typing" - scrollToBottom?: string + composerPlaceholder?: string; + typingOne?: string; // e.g. "{{name}} is typing" + typingTwo?: string; // e.g. "{{name1}} and {{name2}} are typing" + typingMany?: string; // e.g. "Several people are typing" + scrollToBottom?: string; } export interface ChatConfig { - currentUser: ChatUser - dateFormat?: "relative" | "absolute" | "time-only" - messageGroupingInterval?: number // seconds, default 120 - labels?: ChatLabels + currentUser: ChatUser; + dateFormat?: "relative" | "absolute" | "time-only"; + messageGroupingInterval?: number; // seconds, default 120 + labels?: ChatLabels; // Callbacks - onReactionAdd?: (messageId: string, emoji: string) => void - onReactionRemove?: (messageId: string, emoji: string) => void - onReply?: (message: ChatMessageData) => void - onEdit?: (message: ChatMessageData) => void - onDelete?: (messageId: string) => void - onPin?: (messageId: string) => void + onReactionAdd?: (messageId: string, emoji: string) => void; + onReactionRemove?: (messageId: string, emoji: string) => void; + onReply?: (message: ChatMessageData) => void; + onEdit?: (message: ChatMessageData) => void; + onDelete?: (messageId: string) => void; + onPin?: (messageId: string) => void; } /** A group of consecutive messages from the same sender within the grouping interval */ export interface MessageGroup { - senderId: string - senderName: string - senderAvatar?: string - messages: ChatMessageData[] - isOutgoing: boolean + senderId: string; + senderName: string; + senderAvatar?: string; + messages: ChatMessageData[]; + isOutgoing: boolean; } /** Items that can appear in the message list */ export type MessageListItem = | { type: "group"; group: MessageGroup } | { type: "date"; date: Date; label: string } - | { type: "system"; message: ChatMessageData } + | { type: "system"; message: ChatMessageData }; /** Typing state for one or more users */ export interface TypingUser { - id: string - name: string - avatar?: string + id: string; + name: string; + avatar?: string; } diff --git a/packages/shared/package.json b/packages/shared/package.json index 2c58350..61dce73 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -35,7 +35,7 @@ "react-dom": "19.0.0", "react-router-dom": "^7.9.4", "sonner": "^2.0.7", -"tailwind-merge": "^3.0.2", + "tailwind-merge": "^3.0.2", "ts-pattern": "^5.6.2", "zustand": "^5.0.5" }, diff --git a/packages/tablo-views/src/ChatMessages.tsx b/packages/tablo-views/src/ChatMessages.tsx index 896e34c..319a233 100644 --- a/packages/tablo-views/src/ChatMessages.tsx +++ b/packages/tablo-views/src/ChatMessages.tsx @@ -1,11 +1,7 @@ +import type { ChatLabels, ChatMessageData, ChatUser, TypingUser } from "@xtablo/chat-ui"; +import { ChatComposer, ChatMessages as ChatMessageList, ChatProvider } from "@xtablo/chat-ui"; import { useMemo } from "react"; import { useTranslation } from "react-i18next"; -import { - ChatProvider, - ChatMessages as ChatMessageList, - ChatComposer, -} from "@xtablo/chat-ui"; -import type { ChatLabels, ChatMessageData, ChatUser, TypingUser } from "@xtablo/chat-ui"; interface ChatMessage { id: string; @@ -60,7 +56,7 @@ export function ChatMessages({ name: membersById.get(currentUserId)?.name ?? t("currentUserName"), avatar: membersById.get(currentUserId)?.avatar_url ?? undefined, }), - [currentUserId, membersById, t], + [currentUserId, membersById, t] ); const chatMessages = useMemo( @@ -77,7 +73,7 @@ export function ChatMessages({ status: msg.optimistic ? "sending" : undefined, }; }), - [messages, membersById, t], + [messages, membersById, t] ); const chatTypingUsers = useMemo( @@ -87,7 +83,7 @@ export function ChatMessages({ name: membersById.get(userId)?.name ?? t("defaultUserName"), avatar: membersById.get(userId)?.avatar_url ?? undefined, })), - [typingUsers, membersById, t], + [typingUsers, membersById, t] ); const chatLabels = useMemo( @@ -98,19 +94,12 @@ export function ChatMessages({ typingMany: t("typingMany"), scrollToBottom: t("scrollToBottom"), }), - [t], + [t] ); return ( - - + + { diff --git a/packages/tablo-views/src/EtapesSection.tsx b/packages/tablo-views/src/EtapesSection.tsx index 4f5f3ee..a8e190f 100644 --- a/packages/tablo-views/src/EtapesSection.tsx +++ b/packages/tablo-views/src/EtapesSection.tsx @@ -8,8 +8,8 @@ import { ChevronDownIcon, ChevronRightIcon, CircleCheckIcon, - PencilIcon, ListChecksIcon, + PencilIcon, PlusIcon, Trash2Icon, XIcon, @@ -178,11 +178,7 @@ export function EtapesSection({ required className="h-11 sm:h-9 sm:w-80" /> - @@ -390,10 +386,7 @@ export function EtapesSection({ : "hover:bg-gray-50 dark:hover:bg-gray-800" )} onClick={() => - onTaskStatusChange?.( - task.id, - task.status === "done" ? "todo" : "done" - ) + onTaskStatusChange?.(task.id, task.status === "done" ? "todo" : "done") } > {task.status === "done" ? ( diff --git a/packages/tablo-views/src/TabloDetailsShell.tsx b/packages/tablo-views/src/TabloDetailsShell.tsx index b0eae62..d9e2d91 100644 --- a/packages/tablo-views/src/TabloDetailsShell.tsx +++ b/packages/tablo-views/src/TabloDetailsShell.tsx @@ -49,7 +49,9 @@ export function TabloDetailsShell({

{tablo.name}

- {headerActions &&
{headerActions}
} + {headerActions && ( +
{headerActions}
+ )}
@@ -58,7 +60,8 @@ export function TabloDetailsShell({ key={item.key} className={cn( "flex items-center gap-2", - index < metadata.length - 1 && "sm:border-r border-[#D0D5DD] dark:border-gray-600 sm:pr-4" + index < metadata.length - 1 && + "sm:border-r border-[#D0D5DD] dark:border-gray-600 sm:pr-4" )} > {item.label} diff --git a/packages/tablo-views/src/TabloDiscussionSection.tsx b/packages/tablo-views/src/TabloDiscussionSection.tsx index 8973a7f..422d9ce 100644 --- a/packages/tablo-views/src/TabloDiscussionSection.tsx +++ b/packages/tablo-views/src/TabloDiscussionSection.tsx @@ -1,7 +1,7 @@ import type { UserTablo } from "@xtablo/shared/types/tablos.types"; import { useEffect } from "react"; -import { useChat } from "./hooks/useChat"; import { ChatMessages } from "./ChatMessages"; +import { useChat } from "./hooks/useChat"; interface Member { id: string; diff --git a/packages/tablo-views/src/TabloEventsSection.tsx b/packages/tablo-views/src/TabloEventsSection.tsx index 2781805..74e1686 100644 --- a/packages/tablo-views/src/TabloEventsSection.tsx +++ b/packages/tablo-views/src/TabloEventsSection.tsx @@ -46,7 +46,11 @@ interface TabloEventsSectionProps { isInvitingUser?: boolean; isCancellingInvite?: boolean; onCreateEvent?: () => void; - onUpdateTablo?: (data: { id: string; name?: string | null; color?: string | null }) => Promise; + onUpdateTablo?: (data: { + id: string; + name?: string | null; + color?: string | null; + }) => Promise; onInviteUser?: (params: { email: string; tablo_id: string }) => void; onCancelInvite?: (params: { tabloId: string; inviteId: string }) => void; } diff --git a/packages/tablo-views/src/TabloFilesSection.tsx b/packages/tablo-views/src/TabloFilesSection.tsx index a96df14..7312d2f 100644 --- a/packages/tablo-views/src/TabloFilesSection.tsx +++ b/packages/tablo-views/src/TabloFilesSection.tsx @@ -490,13 +490,35 @@ interface TabloFilesSectionProps { canUploadFiles?: boolean; canManageFolders?: boolean; canDeleteFiles?: boolean; - onCreateFile?: (params: { tabloId: string; fileName: string; data: { content: string; contentType: string } }) => Promise; + onCreateFile?: (params: { + tabloId: string; + fileName: string; + data: { content: string; contentType: string }; + }) => Promise; onDeleteFile?: (params: { tabloId: string; fileName: string }) => Promise; onDownloadFile?: (params: { tabloId: string; fileName: string }) => Promise; - onCreateFolder?: (params: { tabloId: string; name: string; description: string; createdBy: string }) => Promise; - onUpdateFolder?: (params: { tabloId: string; folderId: string; name: string; description: string }) => Promise; - onDeleteFolder?: (params: { tabloId: string; folderId: string; folderName: string }) => Promise; - onUpdateTablo?: (data: { id: string; name?: string | null; color?: string | null }) => Promise; + onCreateFolder?: (params: { + tabloId: string; + name: string; + description: string; + createdBy: string; + }) => Promise; + onUpdateFolder?: (params: { + tabloId: string; + folderId: string; + name: string; + description: string; + }) => Promise; + onDeleteFolder?: (params: { + tabloId: string; + folderId: string; + folderName: string; + }) => Promise; + onUpdateTablo?: (data: { + id: string; + name?: string | null; + color?: string | null; + }) => Promise; onInviteUser?: (params: { email: string; tablo_id: string }) => void; onCancelInvite?: (params: { tabloId: string; inviteId: string }) => void; } diff --git a/packages/tablo-views/src/TabloTasksSection.tsx b/packages/tablo-views/src/TabloTasksSection.tsx index 1839fe9..1ec3a4d 100644 --- a/packages/tablo-views/src/TabloTasksSection.tsx +++ b/packages/tablo-views/src/TabloTasksSection.tsx @@ -12,8 +12,8 @@ import { TypographyH3, TypographyMuted } from "@xtablo/ui/components/typography" import { AlertTriangle, ListChecks } from "lucide-react"; import { useCallback, useEffect, useMemo, useState } from "react"; import { KanbanBoard } from "./components/kanban/KanbanBoard"; -import type { TabloMember } from "./components/kanban/types"; import { TaskModal } from "./components/kanban/TaskModal"; +import type { TabloMember } from "./components/kanban/types"; import { TabloHeaderActions } from "./TabloHeaderActions"; interface CurrentUser { @@ -39,8 +39,14 @@ interface TabloTasksSectionProps { onCreateTask?: (task: KanbanTaskInsert) => void; onUpdateTask?: (task: KanbanTaskUpdate & { id: string; tablo_id: string }) => void; onDeleteTask?: (taskId: string) => void; - onUpdateTaskPositions?: (updates: Array<{ id: string; position: number; status: TaskStatus }>) => void; - onUpdateTablo?: (data: { id: string; name?: string | null; color?: string | null }) => Promise; + onUpdateTaskPositions?: ( + updates: Array<{ id: string; position: number; status: TaskStatus }> + ) => void; + onUpdateTablo?: (data: { + id: string; + name?: string | null; + color?: string | null; + }) => Promise; onInviteUser?: (params: { email: string; tablo_id: string }) => void; onCancelInvite?: (params: { tabloId: string; inviteId: string }) => void; } @@ -245,7 +251,8 @@ export const TabloTasksSection = ({ {orphanedTasks.length} {pluralize("tâche", orphanedTasks.length)} sans Étape

- Associez {orphanedTasks.length > 1 ? "ces" : "cette"} {pluralize("tâche", orphanedTasks.length)} à une étape. + Associez {orphanedTasks.length > 1 ? "ces" : "cette"}{" "} + {pluralize("tâche", orphanedTasks.length)} à une étape.

diff --git a/packages/tablo-views/src/components/kanban/TaskModal.tsx b/packages/tablo-views/src/components/kanban/TaskModal.tsx index df1dd2b..9594934 100644 --- a/packages/tablo-views/src/components/kanban/TaskModal.tsx +++ b/packages/tablo-views/src/components/kanban/TaskModal.tsx @@ -1,4 +1,10 @@ -import type { Etape, KanbanTask, KanbanTaskInsert, KanbanTaskUpdate, TaskStatus } from "@xtablo/shared-types"; +import type { + Etape, + KanbanTask, + KanbanTaskInsert, + KanbanTaskUpdate, + TaskStatus, +} from "@xtablo/shared-types"; import { Button } from "@xtablo/ui/components/button"; import { DatePicker } from "@xtablo/ui/components/date-picker"; import { Input } from "@xtablo/ui/components/input"; @@ -74,11 +80,11 @@ export const TaskModal = ({ const selectedAssigneeLabel = assigneeId === "unassigned" ? "Non assigné" - : providedMembers.find((member) => member.id === assigneeId)?.name ?? "Non assigné"; + : (providedMembers.find((member) => member.id === assigneeId)?.name ?? "Non assigné"); const selectedEtapeLabel = etapeId === "none" ? "Aucune Étape" - : providedEtapes.find((etape) => etape.id === etapeId)?.title ?? "Aucune Étape"; + : (providedEtapes.find((etape) => etape.id === etapeId)?.title ?? "Aucune Étape"); useEffect(() => { if (!isOpen) { @@ -104,7 +110,15 @@ export const TaskModal = ({ setSelectedTabloId(tablos[0].id); } } - }, [isOpen, task, initialTabloId, allowTabloSelection, tablos, initialDueDate, defaultAssigneeId]); + }, [ + isOpen, + task, + initialTabloId, + allowTabloSelection, + tablos, + initialDueDate, + defaultAssigneeId, + ]); // Format Date to YYYY-MM-DD string for database storage const formatDateForDb = (date: Date | undefined): string | null => { diff --git a/packages/tablo-views/src/hooks/useChat.ts b/packages/tablo-views/src/hooks/useChat.ts index 1ff345f..3b0e455 100644 --- a/packages/tablo-views/src/hooks/useChat.ts +++ b/packages/tablo-views/src/hooks/useChat.ts @@ -1,5 +1,5 @@ -import { useCallback, useEffect, useRef, useState } from "react"; import { useSession } from "@xtablo/shared/contexts/SessionContext"; +import { useCallback, useEffect, useRef, useState } from "react"; interface ChatMessage { id: string; @@ -31,7 +31,14 @@ function normalizeMessage(raw: RawApiMessage): ChatMessage { } type ServerMessage = - | { type: "message.new"; id: string; userId: string; text: string; createdAt: string; clientId: string } + | { + type: "message.new"; + id: string; + userId: string; + text: string; + createdAt: string; + clientId: string; + } | { type: "typing"; userId: string; isTyping: boolean } | { type: "presence.update"; userId: string; status: "online" | "offline" } | { type: "error"; code: string; message: string }; @@ -56,30 +63,33 @@ export function useChat(channelId: string | undefined) { const isTypingRef = useRef(false); // Fetch message history from REST endpoint - const fetchHistory = useCallback(async (before?: string) => { - if (!channelId || !token) return; + const fetchHistory = useCallback( + async (before?: string) => { + if (!channelId || !token) return; - const params = new URLSearchParams({ limit: "50" }); - if (before) params.set("before", before); + const params = new URLSearchParams({ limit: "50" }); + if (before) params.set("before", before); - const res = await fetch(`${CHAT_API_BASE}/chat/channels/${channelId}/messages?${params}`, { - headers: { Authorization: `Bearer ${token}` }, - }); + const res = await fetch(`${CHAT_API_BASE}/chat/channels/${channelId}/messages?${params}`, { + headers: { Authorization: `Bearer ${token}` }, + }); - if (!res.ok) return; + if (!res.ok) return; - const data = await res.json() as { messages: RawApiMessage[]; hasMore: boolean }; - const normalized = data.messages.map(normalizeMessage); - setHasMoreMessages(data.hasMore); + const data = (await res.json()) as { messages: RawApiMessage[]; hasMore: boolean }; + const normalized = data.messages.map(normalizeMessage); + setHasMoreMessages(data.hasMore); - if (before) { - // Prepend older messages - setMessages((prev) => [...normalized, ...prev]); - } else { - // Initial load - setMessages(normalized); - } - }, [channelId, token]); + if (before) { + // Prepend older messages + setMessages((prev) => [...normalized, ...prev]); + } else { + // Initial load + setMessages(normalized); + } + }, + [channelId, token] + ); // Load more (pagination) const loadMoreMessages = useCallback(() => { @@ -116,13 +126,16 @@ export function useChat(channelId: string | undefined) { if (withoutOptimistic.some((m) => m.id === msg.id)) { return withoutOptimistic; } - return [...withoutOptimistic, { - id: msg.id, - userId: msg.userId, - text: msg.text, - createdAt: msg.createdAt, - clientId: msg.clientId, - }]; + return [ + ...withoutOptimistic, + { + id: msg.id, + userId: msg.userId, + text: msg.text, + createdAt: msg.createdAt, + clientId: msg.clientId, + }, + ]; }); break; @@ -130,7 +143,9 @@ export function useChat(channelId: string | undefined) { if (msg.userId === session?.user?.id) break; setTypingUsers((prev) => msg.isTyping - ? prev.includes(msg.userId) ? prev : [...prev, msg.userId] + ? prev.includes(msg.userId) + ? prev + : [...prev, msg.userId] : prev.filter((id) => id !== msg.userId) ); break; @@ -138,7 +153,9 @@ export function useChat(channelId: string | undefined) { case "presence.update": setOnlineUsers((prev) => msg.status === "online" - ? prev.includes(msg.userId) ? prev : [...prev, msg.userId] + ? prev.includes(msg.userId) + ? prev + : [...prev, msg.userId] : prev.filter((id) => id !== msg.userId) ); break; @@ -182,33 +199,36 @@ export function useChat(channelId: string | undefined) { }, [channelId, token, fetchHistory]); // Send message - const sendMessage = useCallback((text: string) => { - if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) return; + const sendMessage = useCallback( + (text: string) => { + if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) return; - const clientId = crypto.randomUUID(); + const clientId = crypto.randomUUID(); - // Optimistic update - setMessages((prev) => [ - ...prev, - { - id: `optimistic-${clientId}`, - userId: session?.user?.id ?? "", - text, - createdAt: new Date().toISOString(), - clientId, - optimistic: true, - }, - ]); + // Optimistic update + setMessages((prev) => [ + ...prev, + { + id: `optimistic-${clientId}`, + userId: session?.user?.id ?? "", + text, + createdAt: new Date().toISOString(), + clientId, + optimistic: true, + }, + ]); - wsRef.current.send(JSON.stringify({ type: "message.send", text, clientId })); + wsRef.current.send(JSON.stringify({ type: "message.send", text, clientId })); - // Stop typing when sending - if (isTypingRef.current) { - wsRef.current.send(JSON.stringify({ type: "typing.stop" })); - isTypingRef.current = false; - clearTimeout(typingTimerRef.current); - } - }, [session?.user?.id]); + // Stop typing when sending + if (isTypingRef.current) { + wsRef.current.send(JSON.stringify({ type: "typing.stop" })); + isTypingRef.current = false; + clearTimeout(typingTimerRef.current); + } + }, + [session?.user?.id] + ); // Typing indicator const sendTyping = useCallback(() => { diff --git a/packages/tablo-views/src/hooks/useChatUnread.ts b/packages/tablo-views/src/hooks/useChatUnread.ts index ff7f806..0f3a2c8 100644 --- a/packages/tablo-views/src/hooks/useChatUnread.ts +++ b/packages/tablo-views/src/hooks/useChatUnread.ts @@ -19,7 +19,7 @@ export function useChatUnread() { headers: { Authorization: `Bearer ${token}` }, }); if (!res.ok) return []; - const json = await res.json() as { unread: UnreadCount[] }; + const json = (await res.json()) as { unread: UnreadCount[] }; return json.unread; }, enabled: !!token, diff --git a/packages/tablo-views/src/index.ts b/packages/tablo-views/src/index.ts index ab47c35..6e5a8f2 100644 --- a/packages/tablo-views/src/index.ts +++ b/packages/tablo-views/src/index.ts @@ -1,32 +1,29 @@ -export { TabloTasksSection } from "./TabloTasksSection"; -export { TabloFilesSection } from "./TabloFilesSection"; -export { TabloDiscussionSection } from "./TabloDiscussionSection"; -export { TabloEventsSection } from "./TabloEventsSection"; -export { EtapesSection } from "./EtapesSection"; -export { RoadmapSection } from "./RoadmapSection"; -export { TabloHeaderActions } from "./TabloHeaderActions"; export { ChatMessages } from "./ChatMessages"; -export { TabloDetailsShell } from "./TabloDetailsShell"; -export { SingleTabloOverview } from "./single-tablo/SingleTabloOverview"; -export { SingleTabloView } from "./single-tablo/SingleTabloView"; +// Sub-components +export { GanttChart } from "./components/gantt/GanttChart"; +export { KanbanBoard } from "./components/kanban/KanbanBoard"; +export { TaskModal } from "./components/kanban/TaskModal"; +// Types +export type { TabloMember } from "./components/kanban/types"; +export { EtapesSection } from "./EtapesSection"; +// Hooks +export { useChat } from "./hooks/useChat"; +export { useChatUnread } from "./hooks/useChatUnread"; +export { RoadmapSection } from "./RoadmapSection"; +export type { OverviewBlockId, OverviewLayoutV1 } from "./single-tablo/overviewLayout"; export { DEFAULT_OVERVIEW_LAYOUT, sanitizeOverviewLayout, } from "./single-tablo/overviewLayout"; -export type { OverviewBlockId, OverviewLayoutV1 } from "./single-tablo/overviewLayout"; export { moveBetweenZones, moveWithinZone } from "./single-tablo/overviewReorder"; -export { getSingleTabloStatusConfig } from "./single-tablo/shared"; +export { SingleTabloOverview } from "./single-tablo/SingleTabloOverview"; +export { SingleTabloView } from "./single-tablo/SingleTabloView"; export type { SingleTabloTabId } from "./single-tablo/shared"; - -// Sub-components -export { GanttChart } from "./components/gantt/GanttChart"; -export { TaskModal } from "./components/kanban/TaskModal"; -export { KanbanBoard } from "./components/kanban/KanbanBoard"; - -// Hooks -export { useChat } from "./hooks/useChat"; -export { useChatUnread } from "./hooks/useChatUnread"; - -// Types -export type { TabloMember } from "./components/kanban/types"; +export { getSingleTabloStatusConfig } from "./single-tablo/shared"; export type { TabloDetailsShellMetadataItem, TabloDetailsShellTab } from "./TabloDetailsShell"; +export { TabloDetailsShell } from "./TabloDetailsShell"; +export { TabloDiscussionSection } from "./TabloDiscussionSection"; +export { TabloEventsSection } from "./TabloEventsSection"; +export { TabloFilesSection } from "./TabloFilesSection"; +export { TabloHeaderActions } from "./TabloHeaderActions"; +export { TabloTasksSection } from "./TabloTasksSection"; diff --git a/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx b/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx index a5646a9..e78262a 100644 --- a/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx +++ b/packages/tablo-views/src/single-tablo/SingleTabloOverview.tsx @@ -1,7 +1,13 @@ import { cn } from "@xtablo/shared"; import type { KanbanTask } from "@xtablo/shared-types"; import { Button } from "@xtablo/ui/components/button"; -import { FileIcon, GripVerticalIcon, LayoutPanelTopIcon, ListChecksIcon, RotateCcwIcon } from "lucide-react"; +import { + FileIcon, + GripVerticalIcon, + LayoutPanelTopIcon, + ListChecksIcon, + RotateCcwIcon, +} from "lucide-react"; import type { OverviewBlockId, OverviewLayoutV1 } from "./overviewLayout"; interface DraggedBlock { @@ -170,7 +176,12 @@ export function SingleTabloOverview({ )) )} {personalTaskCount > 5 && ( - )} @@ -231,11 +242,7 @@ export function SingleTabloOverview({ const block = renderBlockContent(blockId); return ( -
onBlockDrop(zone, index)} - > +
onBlockDrop(zone, index)}> Date: Sun, 19 Apr 2026 18:07:24 +0200 Subject: [PATCH 50/75] Remove label --- .github/workflows/ci.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3fcca40..0ab814a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,7 +18,6 @@ jobs: - self-hosted - linux - x64 - - xtablo-runner timeout-minutes: 45 From dd71653ad5ef28e42ad58279c5366ab1b94de18f Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sun, 19 Apr 2026 18:31:13 +0200 Subject: [PATCH 51/75] ci: reduce workflow parallelism for self-hosted runner --- .github/workflows/ci.yml | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0ab814a..d917eb5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,33 +23,33 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup pnpm - uses: pnpm/action-setup@v4 + uses: pnpm/action-setup@v5 with: version: 10.19.0 - name: Setup Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@v6 with: node-version: 20 cache: pnpm - name: Install dependencies - run: pnpm install --frozen-lockfile + run: pnpm install --frozen-lockfile --child-concurrency=2 - name: Lint - run: pnpm lint + run: pnpm turbo run lint --concurrency=2 - name: Typecheck - run: pnpm typecheck + run: pnpm turbo run typecheck --concurrency=1 - name: Test main app - run: pnpm --filter @xtablo/main test + run: pnpm --filter @xtablo/main test -- --maxWorkers=1 --no-file-parallelism - name: Test clients app - run: pnpm --filter @xtablo/clients test + run: pnpm --filter @xtablo/clients test -- --maxWorkers=1 --no-file-parallelism - name: Typecheck API run: pnpm --filter @xtablo/api typecheck From 901c54169c12cef5351fc4f0d26da16bb5da4e10 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sun, 19 Apr 2026 18:50:27 +0200 Subject: [PATCH 52/75] fix: keep client test helpers compatible with es2020 --- apps/clients/src/test/testHelpers.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/clients/src/test/testHelpers.tsx b/apps/clients/src/test/testHelpers.tsx index 51ae585..fbbcf44 100644 --- a/apps/clients/src/test/testHelpers.tsx +++ b/apps/clients/src/test/testHelpers.tsx @@ -31,7 +31,7 @@ export const renderWithProviders = ( options: RenderWithProvidersOptions = {} ): RenderResult & { user: ReturnType } => { const { route = "/", path, language = "fr" } = options; - const testUser = Object.hasOwn(options, "testUser") ? options.testUser : defaultUser; + const testUser = Object.prototype.hasOwnProperty.call(options, "testUser") ? options.testUser : defaultUser; testI18n.changeLanguage(language); From 5d7dbc95fc461b45cbe984b6d448821424668a13 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sun, 19 Apr 2026 19:24:47 +0200 Subject: [PATCH 53/75] Use ES2022 in apps/clients --- apps/clients/src/test/testHelpers.tsx | 2 +- apps/clients/tsconfig.json | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/clients/src/test/testHelpers.tsx b/apps/clients/src/test/testHelpers.tsx index fbbcf44..51ae585 100644 --- a/apps/clients/src/test/testHelpers.tsx +++ b/apps/clients/src/test/testHelpers.tsx @@ -31,7 +31,7 @@ export const renderWithProviders = ( options: RenderWithProvidersOptions = {} ): RenderResult & { user: ReturnType } => { const { route = "/", path, language = "fr" } = options; - const testUser = Object.prototype.hasOwnProperty.call(options, "testUser") ? options.testUser : defaultUser; + const testUser = Object.hasOwn(options, "testUser") ? options.testUser : defaultUser; testI18n.changeLanguage(language); diff --git a/apps/clients/tsconfig.json b/apps/clients/tsconfig.json index 2431c00..f763816 100644 --- a/apps/clients/tsconfig.json +++ b/apps/clients/tsconfig.json @@ -1,8 +1,8 @@ { "compilerOptions": { - "target": "ES2020", + "target": "ES2022", "useDefineForClassFields": true, - "lib": ["ES2020", "DOM", "DOM.Iterable"], + "lib": ["ES2022", "DOM", "DOM.Iterable"], "types": ["vite/client"], "module": "ESNext", "skipLibCheck": true, From 246755d7c4dbd4c756d62ddb60ed794d28ee8f15 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 22 Apr 2026 21:35:42 +0200 Subject: [PATCH 54/75] Fix react rendering issue --- apps/api/README.md | 51 +++ apps/main/src/pages/planning.test.tsx | 145 ++++++++ apps/main/src/pages/planning.tsx | 466 +++++++++++++------------- 3 files changed, 433 insertions(+), 229 deletions(-) create mode 100644 apps/main/src/pages/planning.test.tsx diff --git a/apps/api/README.md b/apps/api/README.md index cfb930a..124ccb9 100644 --- a/apps/api/README.md +++ b/apps/api/README.md @@ -88,3 +88,54 @@ See `.env.example` for required environment variables. ## Deployment The API is deployed to Google Cloud Run. See `cloudbuild.yaml` for deployment configuration. + +## Dokploy Deployment + +Prefer a Dokploy `Application` instead of a Compose service. + +Dokploy supports Dockerfile-based applications directly, which fits this API better than maintaining a dedicated compose wrapper. Configure the application like this: + +- Build Type: `Dockerfile` +- Dockerfile Path: `apps/api/Dockerfile` +- Docker Context Path: `.` +- Docker Build Stage: `final` +- Port: `8080` +- Run Command: leave empty and use the image `CMD` + +Set these Dokploy environment variables: + +- `NODE_ENV` +- `DD_SERVICE=xtablo-api` +- `DD_ENV` +- `DD_VERSION` +- `DD_LOGS_INJECTION=true` +- `SUPABASE_URL` +- `SUPABASE_SERVICE_ROLE_KEY` +- `SUPABASE_CONNECTION_STRING` +- `SUPABASE_CA_CERT` +- `STRIPE_SECRET_KEY` +- `STRIPE_WEBHOOK_SECRET` +- `STRIPE_SOLO_PRICE_ID` +- `STRIPE_TEAM_PRICE_ID` +- `STRIPE_FOUNDER_PRICE_ID` +- `EMAIL_USER` +- `EMAIL_CLIENT_ID` +- `EMAIL_CLIENT_SECRET` +- `EMAIL_REFRESH_TOKEN` +- `R2_ACCOUNT_ID` +- `R2_ACCESS_KEY_ID` +- `R2_SECRET_ACCESS_KEY` +- `TASKS_SECRET` + +For Datadog logs, the Dokploy host should already run a Datadog Agent with Docker log collection enabled. Then add these Docker Swarm labels in Dokploy `Advanced Settings -> Swarm Settings -> Labels`: + +- `com.datadoghq.tags.service=xtablo-api` +- `com.datadoghq.tags.env=${DD_ENV}` +- `com.datadoghq.tags.version=${DD_VERSION}` +- `com.datadoghq.ad.logs=[{"source":"nodejs","service":"xtablo-api"}]` + +This gives you: + +- container logs in Datadog with `source: nodejs` +- service tagging as `xtablo-api` +- APM/log correlation via `dd-trace` plus `DD_LOGS_INJECTION=true` diff --git a/apps/main/src/pages/planning.test.tsx b/apps/main/src/pages/planning.test.tsx new file mode 100644 index 0000000..d4bf8f6 --- /dev/null +++ b/apps/main/src/pages/planning.test.tsx @@ -0,0 +1,145 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { act, render, screen, waitFor } from "@testing-library/react"; +import { SessionTestProvider } from "@xtablo/shared/contexts/SessionContext"; +import { ThemeProvider } from "@xtablo/shared/contexts/ThemeContext"; +import { I18nextProvider } from "react-i18next"; +import { createMemoryRouter, RouterProvider } from "react-router-dom"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import testI18n from "../i18n.test"; +import { TestUserStoreProvider, type User } from "../providers/UserStoreProvider"; +import { PlanningPage } from "./planning"; + +vi.mock("../hooks/events", () => ({ + useDeleteEvent: () => ({ mutate: vi.fn(), isPending: false }), + useEventsByTablo: () => ({ + data: [ + { + event_id: "event-1", + tablo_id: "tablo-1", + tablo_name: "Tablo Alpha", + tablo_color: "bg-blue-500", + start_date: "2026-04-22", + start_time: "09:00:00", + end_time: "10:00:00", + title: "Kickoff", + description: "Planning event", + }, + ], + isLoading: false, + }), +})); + +vi.mock("../hooks/tablos", () => ({ + useGetAllTabloAccess: () => ({ + data: [{ tablo_id: "tablo-1", is_admin: true }], + }), + useTablosList: () => ({ + data: [{ id: "tablo-1", name: "Tablo Alpha" }], + isLoading: false, + }), +})); + +vi.mock("../providers/UserStoreProvider", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + useIsReadOnlyUser: () => false, + }; +}); + +vi.mock("../components/EventModal", () => ({ + EventModal: () =>
, +})); + +const testUser: User = { + id: "user-1", + short_user_id: "u1", + name: "John Doe", + first_name: "John", + last_name: "Doe", + email: "john@example.com", + avatar_url: null, + is_temporary: false, + is_client: false, + client_onboarded_at: null, + last_signed_in: null, + plan: "none", + created_at: new Date("2026-01-01").toISOString(), +}; + +const createTestRouter = (initialEntry: string) => + createMemoryRouter( + [ + { + path: "/planning", + element: , + }, + { + path: "/tasks", + element:
Tasks page
, + }, + ], + { initialEntries: [initialEntry] } + ); + +const renderPlanningRouter = (initialEntry: string) => { + const queryClient = new QueryClient({ + defaultOptions: { + queries: { + retry: false, + staleTime: Infinity, + }, + }, + }); + const router = createTestRouter(initialEntry); + + return { + router, + ...render( + + + + + + + + + + + + ), + }; +}; + +describe("PlanningPage", () => { + beforeEach(() => { + testI18n.changeLanguage("fr"); + }); + + it("does not throw when leaving the planning page from the events tab", async () => { + const { router } = renderPlanningRouter("/planning?tab=events"); + + expect(screen.getByText("Événements")).toBeInTheDocument(); + + await act(async () => { + await expect(router.navigate("/tasks")).resolves.toBeUndefined(); + }); + + await waitFor(() => { + expect(screen.getByText("Tasks page")).toBeInTheDocument(); + }); + }); +}); diff --git a/apps/main/src/pages/planning.tsx b/apps/main/src/pages/planning.tsx index 58ea4f4..e5e7d38 100644 --- a/apps/main/src/pages/planning.tsx +++ b/apps/main/src/pages/planning.tsx @@ -1055,254 +1055,262 @@ export const PlanningPage = () => { ); }; - if (currentTab === "events") { - return ( -
- {renderEventsView()} - setIsCreateEventOpen(false)} - defaultTabloId={selectedTabloId !== "all" ? selectedTabloId : undefined} - defaultDate={currentDate} - /> - -
- ); - } - return (
-
- {/* Sidebar */} -
-
- {/* Tablo Selector */} -
- setSelectedTabloId(value)} + disabled={tablosLoading} + > + + + + + {t("planning:allTablos")} + {tablos?.map((tablo) => ( + + {tablo.name} + + ))} + + +
+ + + + + +
- - - - - -
- - {/* Mini Calendar */} -
-
- {monthNames[currentDate.getMonth()]} {currentDate.getFullYear()} -
-
- {dayNamesShort.map((day) => ( -
- {day.slice(0, 1)} -
- ))} - {getDaysInMonth(currentDate).map((day, index) => ( -
{ - if (day) { - navigateToCreateEvent(day, selectedTabloId); - } - }} - > - {day ? day.getDate() : ""} -
- ))} -
-
-
- - {/* Main Content */} -
- {/* Header */} -
-
-
- {t("planning:title")} - -
- - -
- {getViewTitle()} + {/* Mini Calendar */} +
+
+ {monthNames[currentDate.getMonth()]} {currentDate.getFullYear()}
+
+ {dayNamesShort.map((day) => ( +
+ {day.slice(0, 1)} +
+ ))} + {getDaysInMonth(currentDate).map((day, index) => ( +
{ + if (day) { + navigateToCreateEvent(day, selectedTabloId); + } + }} + > + {day ? day.getDate() : ""} +
+ ))} +
+
+
-
- -
- {(["month", "week", "day"] as ViewType[]).map((view) => ( - +
+ - ))} + +
+ {getViewTitle()} +
+ +
+ +
+ {(["month", "week", "day"] as ViewType[]).map((view) => ( + + ))} +
-
- {/* Calendar Views */} -
- {tabloEventsLoading ? ( -
- Loading... - {t("planning:loadingEvents")} -
- ) : ( - <> - {currentView === "month" && renderMonthView()} - {currentView === "week" && renderWeekView()} - {currentView === "day" && renderDayView()} - - )} + {/* Calendar Views */} +
+ {tabloEventsLoading ? ( +
+ Loading... + {t("planning:loadingEvents")} +
+ ) : ( + <> + {currentView === "month" && renderMonthView()} + {currentView === "week" && renderWeekView()} + {currentView === "day" && renderDayView()} + + )} +
-
+ )} + + setIsCreateEventOpen(false)} + defaultTabloId={selectedTabloId !== "all" ? selectedTabloId : undefined} + defaultDate={currentDate} + /> {isImportModalOpen && setIsImportModalOpen(false)} />} - + {isWebcalModalOpen && ( + + )}
); }; From fd5137e91e1ecf1ae455feeaa676faa8cae4ab2d Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 22 Apr 2026 21:35:42 +0200 Subject: [PATCH 55/75] Fix react rendering issue --- apps/api/README.md | 51 +++ apps/main/src/pages/planning.test.tsx | 145 ++++++++ apps/main/src/pages/planning.tsx | 466 +++++++++++++------------- 3 files changed, 433 insertions(+), 229 deletions(-) create mode 100644 apps/main/src/pages/planning.test.tsx diff --git a/apps/api/README.md b/apps/api/README.md index cfb930a..124ccb9 100644 --- a/apps/api/README.md +++ b/apps/api/README.md @@ -88,3 +88,54 @@ See `.env.example` for required environment variables. ## Deployment The API is deployed to Google Cloud Run. See `cloudbuild.yaml` for deployment configuration. + +## Dokploy Deployment + +Prefer a Dokploy `Application` instead of a Compose service. + +Dokploy supports Dockerfile-based applications directly, which fits this API better than maintaining a dedicated compose wrapper. Configure the application like this: + +- Build Type: `Dockerfile` +- Dockerfile Path: `apps/api/Dockerfile` +- Docker Context Path: `.` +- Docker Build Stage: `final` +- Port: `8080` +- Run Command: leave empty and use the image `CMD` + +Set these Dokploy environment variables: + +- `NODE_ENV` +- `DD_SERVICE=xtablo-api` +- `DD_ENV` +- `DD_VERSION` +- `DD_LOGS_INJECTION=true` +- `SUPABASE_URL` +- `SUPABASE_SERVICE_ROLE_KEY` +- `SUPABASE_CONNECTION_STRING` +- `SUPABASE_CA_CERT` +- `STRIPE_SECRET_KEY` +- `STRIPE_WEBHOOK_SECRET` +- `STRIPE_SOLO_PRICE_ID` +- `STRIPE_TEAM_PRICE_ID` +- `STRIPE_FOUNDER_PRICE_ID` +- `EMAIL_USER` +- `EMAIL_CLIENT_ID` +- `EMAIL_CLIENT_SECRET` +- `EMAIL_REFRESH_TOKEN` +- `R2_ACCOUNT_ID` +- `R2_ACCESS_KEY_ID` +- `R2_SECRET_ACCESS_KEY` +- `TASKS_SECRET` + +For Datadog logs, the Dokploy host should already run a Datadog Agent with Docker log collection enabled. Then add these Docker Swarm labels in Dokploy `Advanced Settings -> Swarm Settings -> Labels`: + +- `com.datadoghq.tags.service=xtablo-api` +- `com.datadoghq.tags.env=${DD_ENV}` +- `com.datadoghq.tags.version=${DD_VERSION}` +- `com.datadoghq.ad.logs=[{"source":"nodejs","service":"xtablo-api"}]` + +This gives you: + +- container logs in Datadog with `source: nodejs` +- service tagging as `xtablo-api` +- APM/log correlation via `dd-trace` plus `DD_LOGS_INJECTION=true` diff --git a/apps/main/src/pages/planning.test.tsx b/apps/main/src/pages/planning.test.tsx new file mode 100644 index 0000000..d4bf8f6 --- /dev/null +++ b/apps/main/src/pages/planning.test.tsx @@ -0,0 +1,145 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { act, render, screen, waitFor } from "@testing-library/react"; +import { SessionTestProvider } from "@xtablo/shared/contexts/SessionContext"; +import { ThemeProvider } from "@xtablo/shared/contexts/ThemeContext"; +import { I18nextProvider } from "react-i18next"; +import { createMemoryRouter, RouterProvider } from "react-router-dom"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import testI18n from "../i18n.test"; +import { TestUserStoreProvider, type User } from "../providers/UserStoreProvider"; +import { PlanningPage } from "./planning"; + +vi.mock("../hooks/events", () => ({ + useDeleteEvent: () => ({ mutate: vi.fn(), isPending: false }), + useEventsByTablo: () => ({ + data: [ + { + event_id: "event-1", + tablo_id: "tablo-1", + tablo_name: "Tablo Alpha", + tablo_color: "bg-blue-500", + start_date: "2026-04-22", + start_time: "09:00:00", + end_time: "10:00:00", + title: "Kickoff", + description: "Planning event", + }, + ], + isLoading: false, + }), +})); + +vi.mock("../hooks/tablos", () => ({ + useGetAllTabloAccess: () => ({ + data: [{ tablo_id: "tablo-1", is_admin: true }], + }), + useTablosList: () => ({ + data: [{ id: "tablo-1", name: "Tablo Alpha" }], + isLoading: false, + }), +})); + +vi.mock("../providers/UserStoreProvider", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + useIsReadOnlyUser: () => false, + }; +}); + +vi.mock("../components/EventModal", () => ({ + EventModal: () =>
, +})); + +const testUser: User = { + id: "user-1", + short_user_id: "u1", + name: "John Doe", + first_name: "John", + last_name: "Doe", + email: "john@example.com", + avatar_url: null, + is_temporary: false, + is_client: false, + client_onboarded_at: null, + last_signed_in: null, + plan: "none", + created_at: new Date("2026-01-01").toISOString(), +}; + +const createTestRouter = (initialEntry: string) => + createMemoryRouter( + [ + { + path: "/planning", + element: , + }, + { + path: "/tasks", + element:
Tasks page
, + }, + ], + { initialEntries: [initialEntry] } + ); + +const renderPlanningRouter = (initialEntry: string) => { + const queryClient = new QueryClient({ + defaultOptions: { + queries: { + retry: false, + staleTime: Infinity, + }, + }, + }); + const router = createTestRouter(initialEntry); + + return { + router, + ...render( + + + + + + + + + + + + ), + }; +}; + +describe("PlanningPage", () => { + beforeEach(() => { + testI18n.changeLanguage("fr"); + }); + + it("does not throw when leaving the planning page from the events tab", async () => { + const { router } = renderPlanningRouter("/planning?tab=events"); + + expect(screen.getByText("Événements")).toBeInTheDocument(); + + await act(async () => { + await expect(router.navigate("/tasks")).resolves.toBeUndefined(); + }); + + await waitFor(() => { + expect(screen.getByText("Tasks page")).toBeInTheDocument(); + }); + }); +}); diff --git a/apps/main/src/pages/planning.tsx b/apps/main/src/pages/planning.tsx index 58ea4f4..e5e7d38 100644 --- a/apps/main/src/pages/planning.tsx +++ b/apps/main/src/pages/planning.tsx @@ -1055,254 +1055,262 @@ export const PlanningPage = () => { ); }; - if (currentTab === "events") { - return ( -
- {renderEventsView()} - setIsCreateEventOpen(false)} - defaultTabloId={selectedTabloId !== "all" ? selectedTabloId : undefined} - defaultDate={currentDate} - /> - -
- ); - } - return (
-
- {/* Sidebar */} -
-
- {/* Tablo Selector */} -
- setSelectedTabloId(value)} + disabled={tablosLoading} + > + + + + + {t("planning:allTablos")} + {tablos?.map((tablo) => ( + + {tablo.name} + + ))} + + +
+ + + + + +
- - - - - -
- - {/* Mini Calendar */} -
-
- {monthNames[currentDate.getMonth()]} {currentDate.getFullYear()} -
-
- {dayNamesShort.map((day) => ( -
- {day.slice(0, 1)} -
- ))} - {getDaysInMonth(currentDate).map((day, index) => ( -
{ - if (day) { - navigateToCreateEvent(day, selectedTabloId); - } - }} - > - {day ? day.getDate() : ""} -
- ))} -
-
-
- - {/* Main Content */} -
- {/* Header */} -
-
-
- {t("planning:title")} - -
- - -
- {getViewTitle()} + {/* Mini Calendar */} +
+
+ {monthNames[currentDate.getMonth()]} {currentDate.getFullYear()}
+
+ {dayNamesShort.map((day) => ( +
+ {day.slice(0, 1)} +
+ ))} + {getDaysInMonth(currentDate).map((day, index) => ( +
{ + if (day) { + navigateToCreateEvent(day, selectedTabloId); + } + }} + > + {day ? day.getDate() : ""} +
+ ))} +
+
+
-
- -
- {(["month", "week", "day"] as ViewType[]).map((view) => ( - +
+ - ))} + +
+ {getViewTitle()} +
+ +
+ +
+ {(["month", "week", "day"] as ViewType[]).map((view) => ( + + ))} +
-
- {/* Calendar Views */} -
- {tabloEventsLoading ? ( -
- Loading... - {t("planning:loadingEvents")} -
- ) : ( - <> - {currentView === "month" && renderMonthView()} - {currentView === "week" && renderWeekView()} - {currentView === "day" && renderDayView()} - - )} + {/* Calendar Views */} +
+ {tabloEventsLoading ? ( +
+ Loading... + {t("planning:loadingEvents")} +
+ ) : ( + <> + {currentView === "month" && renderMonthView()} + {currentView === "week" && renderWeekView()} + {currentView === "day" && renderDayView()} + + )} +
-
+ )} + + setIsCreateEventOpen(false)} + defaultTabloId={selectedTabloId !== "all" ? selectedTabloId : undefined} + defaultDate={currentDate} + /> {isImportModalOpen && setIsImportModalOpen(false)} />} - + {isWebcalModalOpen && ( + + )}
); }; From 3c90ba232cea8b9d51fbfdc23b4de9931a6e83ae Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 22 Apr 2026 21:39:13 +0200 Subject: [PATCH 56/75] fix test --- apps/main/src/pages/planning.test.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/apps/main/src/pages/planning.test.tsx b/apps/main/src/pages/planning.test.tsx index d4bf8f6..c3ba6c0 100644 --- a/apps/main/src/pages/planning.test.tsx +++ b/apps/main/src/pages/planning.test.tsx @@ -61,7 +61,6 @@ const testUser: User = { avatar_url: null, is_temporary: false, is_client: false, - client_onboarded_at: null, last_signed_in: null, plan: "none", created_at: new Date("2026-01-01").toISOString(), From 222c61339f51fb573b199fa73543755fadcb9e60 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 22 Apr 2026 22:13:30 +0200 Subject: [PATCH 57/75] feat: add datadog frontend sourcemap uploads --- .github/workflows/frontend-sourcemaps.yml | 74 +++ apps/clients/src/setupTests.ts | 34 +- apps/clients/src/vite-env.d.ts | 9 + apps/clients/src/viteConfig.test.ts | 13 + apps/clients/vite.config.ts | 3 + apps/external/package.json | 1 + apps/external/src/setupTests.ts | 1 + apps/external/src/vite-env.d.ts | 8 + apps/external/src/viteConfig.test.ts | 13 + apps/external/vite.config.ts | 7 +- apps/main/src/lib/rum.test.ts | 35 ++ apps/main/src/lib/rum.ts | 3 +- apps/main/src/setupTests.ts | 36 +- apps/main/src/vite-env.d.ts | 8 + apps/main/src/viteConfig.test.ts | 13 + apps/main/vite.config.ts | 3 + ...026-04-22-datadog-rum-sourcemaps-via-ci.md | 467 ++++++++++++++++ ...22-datadog-rum-sourcemaps-via-ci-design.md | 99 ++++ package.json | 1 + pnpm-lock.yaml | 502 +++++++++++++++++- 20 files changed, 1290 insertions(+), 40 deletions(-) create mode 100644 .github/workflows/frontend-sourcemaps.yml create mode 100644 apps/clients/src/vite-env.d.ts create mode 100644 apps/clients/src/viteConfig.test.ts create mode 100644 apps/external/src/setupTests.ts create mode 100644 apps/external/src/viteConfig.test.ts create mode 100644 apps/main/src/lib/rum.test.ts create mode 100644 apps/main/src/viteConfig.test.ts create mode 100644 docs/superpowers/plans/2026-04-22-datadog-rum-sourcemaps-via-ci.md create mode 100644 docs/superpowers/specs/2026-04-22-datadog-rum-sourcemaps-via-ci-design.md diff --git a/.github/workflows/frontend-sourcemaps.yml b/.github/workflows/frontend-sourcemaps.yml new file mode 100644 index 0000000..38247ee --- /dev/null +++ b/.github/workflows/frontend-sourcemaps.yml @@ -0,0 +1,74 @@ +name: Frontend Sourcemaps + +on: + workflow_dispatch: + push: + branches: + - main + - develop + +jobs: + upload-sourcemaps: + runs-on: + - self-hosted + - linux + - x64 + env: + DATADOG_API_KEY: ${{ secrets.DATADOG_API_KEY }} + DATADOG_SITE: ${{ secrets.DATADOG_SITE }} + RELEASE_VERSION: ${{ github.sha }} + steps: + - name: Check out repository + uses: actions/checkout@v6 + + - name: Set up pnpm + uses: pnpm/action-setup@v5 + with: + version: 10.19.0 + + - name: Set up Node.js + uses: actions/setup-node@v6 + with: + node-version: 22 + cache: pnpm + + - name: Validate Datadog secrets + run: | + test -n "$DATADOG_API_KEY" + test -n "$DATADOG_SITE" + + - name: Install dependencies + run: pnpm install --frozen-lockfile --child-concurrency=2 + + - name: Build main + run: pnpm --filter @xtablo/main build:prod + env: + VITE_APP_VERSION: ${{ env.RELEASE_VERSION }} + + - name: Upload main sourcemaps + run: pnpm exec datadog-ci sourcemaps upload apps/main/dist --service xtablo-ui --release-version "$RELEASE_VERSION" --minified-path-prefix https://app.xtablo.com/assets + + - name: Remove main sourcemaps + run: find apps/main/dist -name '*.map' -delete + + - name: Build clients + run: pnpm --filter @xtablo/clients build:prod + env: + VITE_APP_VERSION: ${{ env.RELEASE_VERSION }} + + - name: Upload clients sourcemaps + run: pnpm exec datadog-ci sourcemaps upload apps/clients/dist --service xtablo-clients --release-version "$RELEASE_VERSION" --minified-path-prefix https://clients.xtablo.com/assets + + - name: Remove clients sourcemaps + run: find apps/clients/dist -name '*.map' -delete + + - name: Build external + run: pnpm --filter @xtablo/external build + env: + VITE_APP_VERSION: ${{ env.RELEASE_VERSION }} + + - name: Upload external sourcemaps + run: pnpm exec datadog-ci sourcemaps upload apps/external/dist --service xtablo-external --release-version "$RELEASE_VERSION" --minified-path-prefix https://embed.xtablo.com/assets + + - name: Remove external sourcemaps + run: find apps/external/dist -name '*.map' -delete diff --git a/apps/clients/src/setupTests.ts b/apps/clients/src/setupTests.ts index 23c7532..bfff6cc 100644 --- a/apps/clients/src/setupTests.ts +++ b/apps/clients/src/setupTests.ts @@ -13,19 +13,23 @@ global.ResizeObserver = class ResizeObserver { disconnect() {} }; -Element.prototype.scrollIntoView = vi.fn(); -Element.prototype.scrollTo = vi.fn(); +if (typeof Element !== "undefined") { + Element.prototype.scrollIntoView = vi.fn(); + Element.prototype.scrollTo = vi.fn(); +} -Object.defineProperty(window, "matchMedia", { - writable: true, - value: vi.fn().mockImplementation((query) => ({ - matches: false, - media: query, - onchange: null, - addListener: vi.fn(), - removeListener: vi.fn(), - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - dispatchEvent: vi.fn(), - })), -}); +if (typeof window !== "undefined") { + Object.defineProperty(window, "matchMedia", { + writable: true, + value: vi.fn().mockImplementation((query) => ({ + matches: false, + media: query, + onchange: null, + addListener: vi.fn(), + removeListener: vi.fn(), + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + dispatchEvent: vi.fn(), + })), + }); +} diff --git a/apps/clients/src/vite-env.d.ts b/apps/clients/src/vite-env.d.ts new file mode 100644 index 0000000..f9164af --- /dev/null +++ b/apps/clients/src/vite-env.d.ts @@ -0,0 +1,9 @@ +/// + +interface ImportMetaEnv { + readonly VITE_APP_VERSION: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} diff --git a/apps/clients/src/viteConfig.test.ts b/apps/clients/src/viteConfig.test.ts new file mode 100644 index 0000000..5583270 --- /dev/null +++ b/apps/clients/src/viteConfig.test.ts @@ -0,0 +1,13 @@ +// @vitest-environment node + +import { describe, expect, it } from "vitest"; + +import configFactory from "../vite.config"; + +describe("clients vite config", () => { + it("uses hidden sourcemaps for production builds", () => { + const config = configFactory({ mode: "production", command: "build", isSsrBuild: false, isPreview: false }); + + expect(config.build?.sourcemap).toBe("hidden"); + }); +}); diff --git a/apps/clients/vite.config.ts b/apps/clients/vite.config.ts index 7b36df3..8d83ea9 100644 --- a/apps/clients/vite.config.ts +++ b/apps/clients/vite.config.ts @@ -13,6 +13,9 @@ export default defineConfig(({ mode }) => { return { plugins, + build: { + sourcemap: mode === "test" ? false : "hidden", + }, server: { cors: false }, define: process.env.VITEST ? { diff --git a/apps/external/package.json b/apps/external/package.json index b93d5b1..fa37897 100644 --- a/apps/external/package.json +++ b/apps/external/package.json @@ -27,6 +27,7 @@ "typescript": "^5.7.0", "vite": "^6.2.2", "vite-tsconfig-paths": "^5.1.4", + "vitest": "^3.2.4", "wrangler": "^4.24.3" }, "dependencies": { diff --git a/apps/external/src/setupTests.ts b/apps/external/src/setupTests.ts new file mode 100644 index 0000000..3115856 --- /dev/null +++ b/apps/external/src/setupTests.ts @@ -0,0 +1 @@ +// Intentionally minimal test setup so Vitest can honor the configured setupFiles path. diff --git a/apps/external/src/vite-env.d.ts b/apps/external/src/vite-env.d.ts index 11f02fe..f9164af 100644 --- a/apps/external/src/vite-env.d.ts +++ b/apps/external/src/vite-env.d.ts @@ -1 +1,9 @@ /// + +interface ImportMetaEnv { + readonly VITE_APP_VERSION: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} diff --git a/apps/external/src/viteConfig.test.ts b/apps/external/src/viteConfig.test.ts new file mode 100644 index 0000000..b3831b7 --- /dev/null +++ b/apps/external/src/viteConfig.test.ts @@ -0,0 +1,13 @@ +// @vitest-environment node + +import { describe, expect, it } from "vitest"; + +import configFactory from "../vite.config"; + +describe("external vite config", () => { + it("uses hidden sourcemaps for production builds", () => { + const config = configFactory({ mode: "production", command: "build", isSsrBuild: false, isPreview: false }); + + expect(config.build?.sourcemap).toBe("hidden"); + }); +}); diff --git a/apps/external/vite.config.ts b/apps/external/vite.config.ts index 8bd72da..c4f1e6b 100644 --- a/apps/external/vite.config.ts +++ b/apps/external/vite.config.ts @@ -3,13 +3,9 @@ import { cloudflare } from "@cloudflare/vite-plugin"; import tailwindcss from "@tailwindcss/vite"; import react from "@vitejs/plugin-react"; -import { dirname } from "path"; -import { fileURLToPath } from "url"; import { defineConfig, PluginOption } from "vite"; import tsconfigPaths from "vite-tsconfig-paths"; -const __dirname = dirname(fileURLToPath(import.meta.url)); - // https://vitejs.dev/config/ export default defineConfig(({ mode }) => { const plugins: PluginOption[] = [ @@ -26,6 +22,9 @@ export default defineConfig(({ mode }) => { return { plugins, + build: { + sourcemap: mode === "test" ? false : "hidden", + }, server: { cors: false, }, diff --git a/apps/main/src/lib/rum.test.ts b/apps/main/src/lib/rum.test.ts new file mode 100644 index 0000000..f468c19 --- /dev/null +++ b/apps/main/src/lib/rum.test.ts @@ -0,0 +1,35 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const init = vi.fn(); + +vi.mock("@datadog/browser-rum", () => ({ + datadogRum: { + init, + }, +})); + +vi.mock("@datadog/browser-rum-react", () => ({ + reactPlugin: () => "react-plugin", +})); + +describe("rum config", () => { + beforeEach(() => { + init.mockReset(); + vi.resetModules(); + }); + + it("sets the Datadog release version from VITE_APP_VERSION", async () => { + vi.stubEnv("VITE_APP_VERSION", "test-sha"); + vi.stubEnv("MODE", "production"); + + await import("./rum"); + + expect(init).toHaveBeenCalledWith( + expect.objectContaining({ + service: "xtablo-ui", + env: "production", + version: "test-sha", + }) + ); + }); +}); diff --git a/apps/main/src/lib/rum.ts b/apps/main/src/lib/rum.ts index 948e6f2..e2a49ca 100644 --- a/apps/main/src/lib/rum.ts +++ b/apps/main/src/lib/rum.ts @@ -13,9 +13,8 @@ datadogRum.init({ site: "datadoghq.com", service: "xtablo-ui", env: import.meta.env.MODE, + version: import.meta.env.VITE_APP_VERSION, - // Specify a version number to identify the deployed version of your application in Datadog - // version: '1.0.0', sessionSampleRate: 100, sessionReplaySampleRate: 80, defaultPrivacyLevel: "mask-user-input", diff --git a/apps/main/src/setupTests.ts b/apps/main/src/setupTests.ts index 1fa4e83..36149d2 100644 --- a/apps/main/src/setupTests.ts +++ b/apps/main/src/setupTests.ts @@ -21,20 +21,24 @@ global.ResizeObserver = class ResizeObserver { } }; -// Mock scrollIntoView for Radix UI components -Element.prototype.scrollIntoView = vi.fn(); -Element.prototype.scrollTo = vi.fn(); +// Mock scroll APIs for DOM-oriented tests without breaking node-environment suites. +if (typeof Element !== "undefined") { + Element.prototype.scrollIntoView = vi.fn(); + Element.prototype.scrollTo = vi.fn(); +} -Object.defineProperty(window, "matchMedia", { - writable: true, - value: vi.fn().mockImplementation((query) => ({ - matches: false, - media: query, - onchange: null, - addListener: vi.fn(), // deprecated - removeListener: vi.fn(), // deprecated - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - dispatchEvent: vi.fn(), - })), -}); +if (typeof window !== "undefined") { + Object.defineProperty(window, "matchMedia", { + writable: true, + value: vi.fn().mockImplementation((query) => ({ + matches: false, + media: query, + onchange: null, + addListener: vi.fn(), // deprecated + removeListener: vi.fn(), // deprecated + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + dispatchEvent: vi.fn(), + })), + }); +} diff --git a/apps/main/src/vite-env.d.ts b/apps/main/src/vite-env.d.ts index 11f02fe..f9164af 100644 --- a/apps/main/src/vite-env.d.ts +++ b/apps/main/src/vite-env.d.ts @@ -1 +1,9 @@ /// + +interface ImportMetaEnv { + readonly VITE_APP_VERSION: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} diff --git a/apps/main/src/viteConfig.test.ts b/apps/main/src/viteConfig.test.ts new file mode 100644 index 0000000..3a15668 --- /dev/null +++ b/apps/main/src/viteConfig.test.ts @@ -0,0 +1,13 @@ +// @vitest-environment node + +import { describe, expect, it } from "vitest"; + +import configFactory from "../vite.config"; + +describe("main vite config", () => { + it("uses hidden sourcemaps for production builds", () => { + const config = configFactory({ mode: "production", command: "build", isSsrBuild: false, isPreview: false }); + + expect(config.build?.sourcemap).toBe("hidden"); + }); +}); diff --git a/apps/main/vite.config.ts b/apps/main/vite.config.ts index 59e1e45..10802fc 100644 --- a/apps/main/vite.config.ts +++ b/apps/main/vite.config.ts @@ -43,6 +43,9 @@ export default defineConfig(({ mode }) => { return { plugins, + build: { + sourcemap: mode === "test" ? false : "hidden", + }, server: { cors: false, }, diff --git a/docs/superpowers/plans/2026-04-22-datadog-rum-sourcemaps-via-ci.md b/docs/superpowers/plans/2026-04-22-datadog-rum-sourcemaps-via-ci.md new file mode 100644 index 0000000..ac7edbd --- /dev/null +++ b/docs/superpowers/plans/2026-04-22-datadog-rum-sourcemaps-via-ci.md @@ -0,0 +1,467 @@ +# Datadog RUM Sourcemaps Via CI Implementation Plan + +> **For agentic workers:** REQUIRED: Use superpowers:subagent-driven-development (if subagents available) or superpowers:executing-plans to implement this plan. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Generate private frontend sourcemaps for Datadog RUM/Error Tracking, upload them from GitHub Actions, and keep `.map` files out of deployed frontend assets. + +**Architecture:** Add an explicit release-version contract to the main app’s RUM init, enable hidden sourcemaps in all Vite frontends, and create a frontend CI workflow that builds each app, uploads sourcemaps with matching Datadog metadata, and removes `.map` files before any deploy step consumes the build output. + +**Tech Stack:** React 19, Vite 6, Vitest, GitHub Actions, Datadog CI CLI, Cloudflare/Wrangler deploy targets, pnpm workspaces. + +**Spec:** `docs/superpowers/specs/2026-04-22-datadog-rum-sourcemaps-via-ci-design.md` + +--- + +## File Structure + +### New files + +- `.github/workflows/frontend-sourcemaps.yml` — GitHub Actions workflow that builds the frontend apps on a self-hosted runner and uploads sourcemaps to Datadog. +- `apps/clients/src/vite-env.d.ts` — Vite env typings for client-specific build variables, including `VITE_APP_VERSION`. +- `apps/main/src/lib/rum.test.ts` — regression test for Datadog RUM init config. +- `apps/main/vite.config.test.ts` — production sourcemap config test for `apps/main`. +- `apps/clients/vite.config.test.ts` — production sourcemap config test for `apps/clients`. +- `apps/external/vite.config.test.ts` — production sourcemap config test for `apps/external`. + +### Modified files + +- `package.json` — add `@datadog/datadog-ci` to root dev dependencies. +- `apps/main/src/lib/rum.ts` — add `version: import.meta.env.VITE_APP_VERSION`. +- `apps/main/src/vite-env.d.ts` — add `VITE_APP_VERSION` typing. +- `apps/external/src/vite-env.d.ts` — add `VITE_APP_VERSION` typing. +- `apps/main/vite.config.ts` — enable hidden sourcemaps for non-test builds. +- `apps/clients/vite.config.ts` — enable hidden sourcemaps for non-test builds. +- `apps/external/vite.config.ts` — enable hidden sourcemaps for non-test builds. + +--- + +## Chunk 1: Runtime Release Metadata + +### Task 1: Wire Datadog RUM version in `apps/main` + +**Files:** +- Create: `apps/main/src/lib/rum.test.ts` +- Modify: `apps/main/src/lib/rum.ts` +- Modify: `apps/main/src/vite-env.d.ts` + +- [ ] **Step 1: Write the failing RUM init test** + +Create `apps/main/src/lib/rum.test.ts`: + +```typescript +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const init = vi.fn(); + +vi.mock("@datadog/browser-rum", () => ({ + datadogRum: { + init, + }, +})); + +vi.mock("@datadog/browser-rum-react", () => ({ + reactPlugin: () => "react-plugin", +})); + +describe("rum config", () => { + beforeEach(() => { + init.mockReset(); + vi.resetModules(); + }); + + it("sets the Datadog release version from VITE_APP_VERSION", async () => { + vi.stubEnv("VITE_APP_VERSION", "test-sha"); + vi.stubEnv("MODE", "production"); + + await import("./rum"); + + expect(init).toHaveBeenCalledWith( + expect.objectContaining({ + service: "xtablo-ui", + env: "production", + version: "test-sha", + }) + ); + }); +}); +``` + +- [ ] **Step 2: Run the test to verify it fails** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run src/lib/rum.test.ts --mode dev +``` + +Expected: FAIL because `version` is not set in `datadogRum.init`. + +- [ ] **Step 3: Add the runtime version** + +Update `apps/main/src/lib/rum.ts`: + +```typescript + service: "xtablo-ui", + env: import.meta.env.MODE, + version: import.meta.env.VITE_APP_VERSION, +``` + +Update `apps/main/src/vite-env.d.ts`: + +```typescript +/// + +interface ImportMetaEnv { + readonly VITE_APP_VERSION: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} +``` + +- [ ] **Step 4: Run the test to verify it passes** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run src/lib/rum.test.ts --mode dev +pnpm --filter @xtablo/main typecheck +``` + +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add apps/main/src/lib/rum.ts apps/main/src/lib/rum.test.ts apps/main/src/vite-env.d.ts +git commit -m "feat: add Datadog release version to main rum config" +``` + +--- + +## Chunk 2: Hidden Sourcemaps In All Vite Frontends + +### Task 2: Add production sourcemap config tests + +**Files:** +- Create: `apps/main/vite.config.test.ts` +- Create: `apps/clients/vite.config.test.ts` +- Create: `apps/external/vite.config.test.ts` + +- [ ] **Step 1: Write the failing config test for `apps/main`** + +Create `apps/main/vite.config.test.ts`: + +```typescript +import { describe, expect, it } from "vitest"; +import configFactory from "./vite.config"; + +describe("main vite config", () => { + it("uses hidden sourcemaps for production builds", () => { + const config = configFactory({ mode: "production" }); + expect(config.build?.sourcemap).toBe("hidden"); + }); +}); +``` + +- [ ] **Step 2: Write the failing config test for `apps/clients`** + +Create `apps/clients/vite.config.test.ts`: + +```typescript +import { describe, expect, it } from "vitest"; +import configFactory from "./vite.config"; + +describe("clients vite config", () => { + it("uses hidden sourcemaps for production builds", () => { + const config = configFactory({ mode: "production" }); + expect(config.build?.sourcemap).toBe("hidden"); + }); +}); +``` + +- [ ] **Step 3: Write the failing config test for `apps/external`** + +Create `apps/external/vite.config.test.ts`: + +```typescript +import { describe, expect, it } from "vitest"; +import configFactory from "./vite.config"; + +describe("external vite config", () => { + it("uses hidden sourcemaps for production builds", () => { + const config = configFactory({ mode: "production" }); + expect(config.build?.sourcemap).toBe("hidden"); + }); +}); +``` + +- [ ] **Step 4: Run the tests to verify they fail** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run vite.config.test.ts --mode dev +pnpm --filter @xtablo/clients exec vitest run vite.config.test.ts --mode test +pnpm --filter @xtablo/external exec vitest run vite.config.test.ts --mode test +``` + +Expected: FAIL because `build.sourcemap` is not configured. + +- [ ] **Step 5: Implement hidden sourcemaps in all three Vite configs** + +Update: +- `apps/main/vite.config.ts` +- `apps/clients/vite.config.ts` +- `apps/external/vite.config.ts` + +Add the same build section in each returned config: + +```typescript + build: { + sourcemap: mode === "test" ? false : "hidden", + }, +``` + +Keep it alongside the existing `plugins`, `server`, `define`, and `test` sections. + +- [ ] **Step 6: Add env typing for the remaining apps** + +Create `apps/clients/src/vite-env.d.ts`: + +```typescript +/// + +interface ImportMetaEnv { + readonly VITE_APP_VERSION: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} +``` + +Update `apps/external/src/vite-env.d.ts`: + +```typescript +/// + +interface ImportMetaEnv { + readonly VITE_APP_VERSION: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} +``` + +- [ ] **Step 7: Run the tests and typechecks** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run vite.config.test.ts --mode dev +pnpm --filter @xtablo/clients exec vitest run vite.config.test.ts --mode test +pnpm --filter @xtablo/external exec vitest run vite.config.test.ts --mode test +pnpm --filter @xtablo/main typecheck +pnpm --filter @xtablo/clients typecheck +pnpm --filter @xtablo/external typecheck +``` + +Expected: PASS. + +- [ ] **Step 8: Commit** + +```bash +git add apps/main/vite.config.ts apps/main/vite.config.test.ts apps/clients/vite.config.ts apps/clients/vite.config.test.ts apps/clients/src/vite-env.d.ts apps/external/vite.config.ts apps/external/vite.config.test.ts apps/external/src/vite-env.d.ts +git commit -m "build: enable hidden sourcemaps for frontend apps" +``` + +--- + +## Chunk 3: Datadog CI Upload Workflow + +### Task 3: Add pinned Datadog CLI and frontend sourcemap workflow + +**Files:** +- Create: `.github/workflows/frontend-sourcemaps.yml` +- Modify: `package.json` + +- [ ] **Step 1: Add the Datadog CLI dependency** + +Update root `package.json`: + +```json + "devDependencies": { + "@biomejs/biome": "2.2.5", + "@datadog/datadog-ci": "^3.21.0", + "turbo": "^2.5.8", + "typescript": "^5.7.0" + } +``` + +- [ ] **Step 2: Install dependencies and verify lockfile changes** + +Run: + +```bash +pnpm install +``` + +Expected: `pnpm-lock.yaml` updates with `@datadog/datadog-ci`. + +- [ ] **Step 3: Create the workflow** + +Create `.github/workflows/frontend-sourcemaps.yml`: + +```yaml +name: Frontend Sourcemaps + +on: + workflow_dispatch: + push: + branches: + - main + - develop + +jobs: + upload-sourcemaps: + runs-on: + - self-hosted + - linux + - x64 + env: + DATADOG_API_KEY: ${{ secrets.DATADOG_API_KEY }} + DATADOG_SITE: ${{ secrets.DATADOG_SITE }} + RELEASE_VERSION: ${{ github.sha }} + steps: + - uses: actions/checkout@v6 + + - uses: pnpm/action-setup@v5 + with: + version: 10.19.0 + + - uses: actions/setup-node@v6 + with: + node-version: 22 + cache: pnpm + + - name: Install dependencies + run: pnpm install --frozen-lockfile --child-concurrency=2 + + - name: Build main + run: pnpm --filter @xtablo/main build:prod + env: + VITE_APP_VERSION: ${{ env.RELEASE_VERSION }} + + - name: Upload main sourcemaps + run: pnpm exec datadog-ci sourcemaps upload apps/main/dist --service xtablo-ui --release-version "$RELEASE_VERSION" --minified-path-prefix https://app.xtablo.com/assets + + - name: Remove main sourcemaps + run: find apps/main/dist -name '*.map' -delete + + - name: Build clients + run: pnpm --filter @xtablo/clients build:prod + env: + VITE_APP_VERSION: ${{ env.RELEASE_VERSION }} + + - name: Upload clients sourcemaps + run: pnpm exec datadog-ci sourcemaps upload apps/clients/dist --service xtablo-clients --release-version "$RELEASE_VERSION" --minified-path-prefix https://clients.xtablo.com/assets + + - name: Remove clients sourcemaps + run: find apps/clients/dist -name '*.map' -delete + + - name: Build external + run: pnpm --filter @xtablo/external build + env: + VITE_APP_VERSION: ${{ env.RELEASE_VERSION }} + + - name: Upload external sourcemaps + run: pnpm exec datadog-ci sourcemaps upload apps/external/dist --service xtablo-external --release-version "$RELEASE_VERSION" --minified-path-prefix https://embed.xtablo.com/assets + + - name: Remove external sourcemaps + run: find apps/external/dist -name '*.map' -delete +``` + +- [ ] **Step 4: Validate the workflow file structure** + +Run: + +```bash +rg -n "datadog-ci sourcemaps upload|RELEASE_VERSION|find .*\\.map" .github/workflows/frontend-sourcemaps.yml +``` + +Expected: one upload and one cleanup step for each frontend app. + +- [ ] **Step 5: Commit** + +```bash +git add package.json pnpm-lock.yaml .github/workflows/frontend-sourcemaps.yml +git commit -m "ci: upload frontend sourcemaps to Datadog" +``` + +--- + +## Chunk 4: End-To-End Verification + +### Task 4: Prove builds emit hidden sourcemaps and cleanup works + +**Files:** +- No new source files + +- [ ] **Step 1: Build each frontend locally with a release version** + +Run: + +```bash +VITE_APP_VERSION=test-sha pnpm --filter @xtablo/main build:prod +VITE_APP_VERSION=test-sha pnpm --filter @xtablo/clients build:prod +VITE_APP_VERSION=test-sha pnpm --filter @xtablo/external build +``` + +Expected: each `dist/` contains built assets and `.map` files, but the generated JS bundles do not include public `sourceMappingURL` comments. + +- [ ] **Step 2: Verify `.map` files exist before cleanup** + +Run: + +```bash +find apps/main/dist apps/clients/dist apps/external/dist -name '*.map' | sort +``` + +Expected: at least one sourcemap per app. + +- [ ] **Step 3: Simulate CI cleanup locally** + +Run: + +```bash +find apps/main/dist apps/clients/dist apps/external/dist -name '*.map' -delete +find apps/main/dist apps/clients/dist apps/external/dist -name '*.map' | sort +``` + +Expected: no output from the second command. + +- [ ] **Step 4: Run the targeted regression suite** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run src/lib/rum.test.ts vite.config.test.ts --mode dev +pnpm --filter @xtablo/clients exec vitest run vite.config.test.ts --mode test +pnpm --filter @xtablo/external exec vitest run vite.config.test.ts --mode test +pnpm --filter @xtablo/main typecheck +pnpm --filter @xtablo/clients typecheck +pnpm --filter @xtablo/external typecheck +``` + +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git status --short +``` + +Expected: clean worktree before opening the implementation PR. diff --git a/docs/superpowers/specs/2026-04-22-datadog-rum-sourcemaps-via-ci-design.md b/docs/superpowers/specs/2026-04-22-datadog-rum-sourcemaps-via-ci-design.md new file mode 100644 index 0000000..6e247b0 --- /dev/null +++ b/docs/superpowers/specs/2026-04-22-datadog-rum-sourcemaps-via-ci-design.md @@ -0,0 +1,99 @@ +# Datadog RUM Sourcemaps Via CI Design + +**Goal:** Deobfuscate frontend RUM and Error Tracking stack traces in Datadog for the Xtablo frontends by generating sourcemaps during build, uploading them in CI, and keeping `.map` files off the public CDN. + +## Current State + +- `apps/main` initializes Datadog RUM in [apps/main/src/lib/rum.ts](/Users/arthur.belleville/Documents/perso/projects/xtablo-source/apps/main/src/lib/rum.ts) with `service: "xtablo-ui"` and `env: import.meta.env.MODE`, but no explicit release version. +- `apps/main`, `apps/clients`, and `apps/external` are Vite frontends with production Cloudflare deployments. +- None of the three Vite configs currently emit production sourcemaps. +- On this branch there is no tracked GitHub Actions workflow yet, so CI wiring must be introduced as part of the implementation. + +## Decision + +Use Datadog’s recommended CI upload flow: + +1. Build each frontend with Vite `build.sourcemap: "hidden"`. +2. Upload generated sourcemaps from CI with `datadog-ci sourcemaps upload`. +3. Use a release version derived from the CI commit SHA. +4. Remove all `.map` files from `dist/` before deploy packaging so they are never publicly served. + +This keeps sourcemaps private while still enabling unminified stack traces in Datadog. + +Sources: +- Datadog CI sourcemap upload guide: https://docs.datadoghq.com/real_user_monitoring/guide/upload-javascript-source-maps/?tab=vite +- Vite `build.sourcemap` docs: https://vite.dev/config/build-options.html + +## Runtime Contract + +Datadog matches sourcemaps against browser events by `service` and `version`. + +- `apps/main` must emit `version: import.meta.env.VITE_APP_VERSION` in its RUM initialization. +- CI must upload sourcemaps for `apps/main` using: + - `service=xtablo-ui` + - `release-version=$GITHUB_SHA` +- `apps/clients` and `apps/external` should use the same CI release version convention now, even though they do not currently emit RUM events. This keeps the deployment contract consistent and avoids another pipeline change when browser monitoring is enabled there. + +## Public Asset Prefixes + +The Datadog upload command must use the real production asset prefixes: + +- `apps/main`: `https://app.xtablo.com/assets` +- `apps/clients`: `https://clients.xtablo.com/assets` +- `apps/external`: `https://embed.xtablo.com/assets` + +These prefixes must match the actual URLs used by the deployed JS bundles. + +## Implementation Shape + +### Frontend code + +- `apps/main/src/lib/rum.ts` + - add `version: import.meta.env.VITE_APP_VERSION` +- `apps/main/src/vite-env.d.ts` + - declare `VITE_APP_VERSION` +- `apps/clients/src/vite-env.d.ts` + - create and declare `VITE_APP_VERSION` +- `apps/external/src/vite-env.d.ts` + - declare `VITE_APP_VERSION` + +### Build config + +- `apps/main/vite.config.ts` +- `apps/clients/vite.config.ts` +- `apps/external/vite.config.ts` + +Each should emit hidden sourcemaps for non-test builds. + +### CI + +- Add GitHub Actions workflow for frontend builds on self-hosted runners. +- Add `@datadog/datadog-ci` as a root dev dependency so the workflow can run a pinned CLI version from the repo. +- After each frontend build: + - upload sourcemaps to Datadog + - delete `dist/**/*.map` + +## Secrets And CI Inputs + +The workflow needs: + +- `DATADOG_API_KEY` +- `DATADOG_SITE` +- release version from `github.sha` + +The workflow should fail fast if Datadog secrets are missing on the deployment path where sourcemap upload is required. + +## Verification + +- Unit test for `apps/main` RUM init to assert `version` is wired from env. +- Vite config tests or config assertions for all three apps to verify production builds use `sourcemap: "hidden"`. +- CI workflow smoke verification: + - build the apps + - run sourcemap upload + - confirm `.map` files are removed from `dist` + +## Non-Goals + +- Enabling Datadog RUM in `apps/clients` or `apps/external` right now. +- Serving sourcemaps publicly. +- Changing app deployment hosts or CDN paths. diff --git a/package.json b/package.json index 5366d4f..5dd27ce 100644 --- a/package.json +++ b/package.json @@ -33,6 +33,7 @@ }, "devDependencies": { "@biomejs/biome": "2.2.5", + "@datadog/datadog-ci": "^4.3.0", "turbo": "^2.5.8", "typescript": "^5.7.0" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e797dbd..68d2284 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -17,6 +17,9 @@ importers: '@biomejs/biome': specifier: 2.2.5 version: 2.2.5 + '@datadog/datadog-ci': + specifier: ^4.3.0 + version: 4.4.0(@types/node@22.18.12) turbo: specifier: ^2.5.8 version: 2.5.8 @@ -89,7 +92,7 @@ importers: version: 2.2.5 '@datadog/datadog-ci-base': specifier: ^4.0.2 - version: 4.1.2(@datadog/datadog-ci-plugin-cloud-run@4.1.2)(@types/node@20.19.23) + version: 4.1.2(@datadog/datadog-ci-plugin-cloud-run@4.1.2)(@datadog/datadog-ci-plugin-deployment@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-dora@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-gate@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-sarif@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-sbom@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-synthetics@4.4.0(@datadog/datadog-ci-base@4.4.0))(@types/node@20.19.23) '@datadog/datadog-ci-plugin-cloud-run': specifier: ^4.0.2 version: 4.1.2(@datadog/datadog-ci-base@4.1.2)(@types/node@20.19.23) @@ -318,6 +321,9 @@ importers: vite-tsconfig-paths: specifier: ^5.1.4 version: 5.1.4(typescript@5.9.3)(vite@6.4.1(@types/node@22.18.12)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6)) + vitest: + specifier: ^3.2.4 + version: 3.2.4(@types/debug@4.1.12)(@types/node@22.18.12)(happy-dom@20.0.7)(jiti@2.6.1)(jsdom@20.0.3)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6) wrangler: specifier: ^4.24.3 version: 4.44.0(@cloudflare/workers-types@4.20260411.1) @@ -1944,11 +1950,84 @@ packages: '@datadog/datadog-ci-plugin-synthetics': optional: true + '@datadog/datadog-ci-base@4.4.0': + resolution: {integrity: sha512-sFssfj3EQKBiD9SkVYzhkzHZEQqmnsMGXKYKoLLTFcTmRbaePItx/1Sa3KzFVIWBhZQSpYoJt3VZ7+cagCShLA==} + peerDependencies: + '@datadog/datadog-ci-plugin-aas': 4.4.0 + '@datadog/datadog-ci-plugin-cloud-run': 4.4.0 + '@datadog/datadog-ci-plugin-container-app': 4.4.0 + '@datadog/datadog-ci-plugin-deployment': 4.4.0 + '@datadog/datadog-ci-plugin-dora': 4.4.0 + '@datadog/datadog-ci-plugin-gate': 4.4.0 + '@datadog/datadog-ci-plugin-lambda': 4.4.0 + '@datadog/datadog-ci-plugin-sarif': 4.4.0 + '@datadog/datadog-ci-plugin-sbom': 4.4.0 + '@datadog/datadog-ci-plugin-stepfunctions': 4.4.0 + '@datadog/datadog-ci-plugin-synthetics': 4.4.0 + peerDependenciesMeta: + '@datadog/datadog-ci-plugin-aas': + optional: true + '@datadog/datadog-ci-plugin-cloud-run': + optional: true + '@datadog/datadog-ci-plugin-container-app': + optional: true + '@datadog/datadog-ci-plugin-deployment': + optional: true + '@datadog/datadog-ci-plugin-dora': + optional: true + '@datadog/datadog-ci-plugin-gate': + optional: true + '@datadog/datadog-ci-plugin-lambda': + optional: true + '@datadog/datadog-ci-plugin-sarif': + optional: true + '@datadog/datadog-ci-plugin-sbom': + optional: true + '@datadog/datadog-ci-plugin-stepfunctions': + optional: true + '@datadog/datadog-ci-plugin-synthetics': + optional: true + '@datadog/datadog-ci-plugin-cloud-run@4.1.2': resolution: {integrity: sha512-HKVZ7SSjzskdVqIrf16bqmgeRrxscoRkgh9ILfni3D/GoXpG3DFaZPs7pXJR6igjBeZMclLjtolqMyyWy7DCLQ==} peerDependencies: '@datadog/datadog-ci-base': 4.1.2 + '@datadog/datadog-ci-plugin-deployment@4.4.0': + resolution: {integrity: sha512-u9FtFw2TKRF74wwcuM8tWseWTrLKZZ/Lwq1Fz+LtAGHTJ5675WuIhGNnSxbrKU4f2VsaFp+eUIsetcqbuUerXw==} + peerDependencies: + '@datadog/datadog-ci-base': 4.4.0 + + '@datadog/datadog-ci-plugin-dora@4.4.0': + resolution: {integrity: sha512-DuyKfiwxZoNu5dlMPZNq6DYlafR/3kpaqS0q9KfGStnu1LwS5YTREuZgssNkyYWnF6qZN80x1l7E/ubaAFVYOg==} + peerDependencies: + '@datadog/datadog-ci-base': 4.4.0 + + '@datadog/datadog-ci-plugin-gate@4.4.0': + resolution: {integrity: sha512-bR5AY5p5/5jQuZtcuEPJrEpL1WhJiXhfPwuc9OhGN0ny4/98S3Hg02aQ9aoloFipsBgEN3W5XhrWH6Pn1jSI5w==} + peerDependencies: + '@datadog/datadog-ci-base': 4.4.0 + + '@datadog/datadog-ci-plugin-sarif@4.4.0': + resolution: {integrity: sha512-kgExnC/ReiGKr9R6SxaXr62lp2fYJQ4i8c9x4/GqDpNbLENQdsqBmxs6h1/N3xkdt3/p3RZlMcAhIytLYDkBAA==} + peerDependencies: + '@datadog/datadog-ci-base': 4.4.0 + + '@datadog/datadog-ci-plugin-sbom@4.4.0': + resolution: {integrity: sha512-bBsgIBBT0KsWqLcIMuf692PGjMNjG6OKNUjuPZOWbuToyKKnpRRkMDrX9KvUWVXuMKfDEp7i2PYw/2fQm5DXHg==} + peerDependencies: + '@datadog/datadog-ci-base': 4.4.0 + + '@datadog/datadog-ci-plugin-synthetics@4.4.0': + resolution: {integrity: sha512-SpGdOZUSjEVZZD/hopPKuXnOP6ZRl0nnZ8i5ffVIxohlMwn5y0vMWjjkDohk24M+2QBDUnMe4sNXW4YP1aeSWg==} + peerDependencies: + '@datadog/datadog-ci-base': 4.4.0 + + '@datadog/datadog-ci@4.4.0': + resolution: {integrity: sha512-vpQPcz+FRgDhPoHg9aXtTeaVe6Dhky6q1vG9TmOWDX39Pjf/Wz1LEY94uWvK6miC8orHf6RtIGOSxsycRNde7g==} + engines: {node: '>=18'} + hasBin: true + '@datadog/flagging-core@0.1.0-preview.13': resolution: {integrity: sha512-DfQYeBgGvCerKx6coRiXMt0aXWJB8kRIsJhfdTKyejS9rfp6ZBjWc6dctKzhwMAQdpBiN42MEVXNt4Pdcmj1WA==} peerDependencies: @@ -4999,6 +5078,9 @@ packages: '@types/use-sync-external-store@0.0.6': resolution: {integrity: sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==} + '@types/uuid@9.0.8': + resolution: {integrity: sha512-jg+97EGIcY9AGHJJRaaPVgetKDsrTgbRjQ5Msgjh/DQKEFl0DtyRr/VCOyD1T2R1MNeWPK/u7JoGhlDZnKBAfA==} + '@types/whatwg-mimetype@3.0.2': resolution: {integrity: sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==} @@ -5298,6 +5380,14 @@ packages: resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==} engines: {node: '>= 14'} + ajv-formats@2.1.1: + resolution: {integrity: sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==} + peerDependencies: + ajv: ^8.0.0 + peerDependenciesMeta: + ajv: + optional: true + ajv@6.12.6: resolution: {integrity: sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==} @@ -5391,6 +5481,13 @@ packages: resolution: {integrity: sha512-3duEwti880xqi4eAMN8AyR4a0ByT90zoYdLlevfrvU43vb0YZwZVfxOgxWrLXXXpyugL0hNZc9G6BiB5B3nUug==} engines: {node: '>=8'} + asn1@0.2.6: + resolution: {integrity: sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==} + + assert-plus@1.0.0: + resolution: {integrity: sha512-NfJ4UzBCcQGLDlQq7nHxH+tv3kyZ0hHQqF5BO6J7tNJeP5do1llPr8dZ8zHonfhAu0PHAdMkSo+8o0wxg9lZWw==} + engines: {node: '>=0.8'} + assertion-error@2.0.1: resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} engines: {node: '>=12'} @@ -5496,6 +5593,9 @@ packages: resolution: {integrity: sha512-4Bcg1P8xhUuqcii/S0Z9wiHIrQVPMermM1any+MX5GeGD7faD3/msQUDGLol9wOcz4/jbg/WJnGqoJF6LiBdtg==} engines: {node: '>=10.0.0'} + bcrypt-pbkdf@1.0.2: + resolution: {integrity: sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==} + bignumber.js@9.3.1: resolution: {integrity: sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==} @@ -5540,6 +5640,10 @@ packages: buffer@5.7.1: resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==} + buildcheck@0.0.7: + resolution: {integrity: sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA==} + engines: {node: '>=10.0.0'} + busboy@1.6.0: resolution: {integrity: sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==} engines: {node: '>=10.16.0'} @@ -5737,6 +5841,10 @@ packages: resolution: {integrity: sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==} engines: {node: '>= 0.10'} + cpu-features@0.0.10: + resolution: {integrity: sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA==} + engines: {node: '>=10.0.0'} + create-jest@29.7.0: resolution: {integrity: sha512-Adz2bdH0Vq3F53KEMJOoftQFutWCukm6J24wbPWRO4k1kMY7gS7ds/uoJkNuV8wDCtWWnuwGcJwpWcih+zEW1Q==} engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} @@ -5778,6 +5886,10 @@ packages: csstype@3.1.3: resolution: {integrity: sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==} + dashdash@1.14.1: + resolution: {integrity: sha512-jRFi8UDGo6j+odZiEpjazZaWqEal3w/basFjQHQEwVtZJGDpxbH1MeYluwCS8Xq5wmLJooDlMgvVarmWfGM44g==} + engines: {node: '>=0.10'} + data-uri-to-buffer@4.0.1: resolution: {integrity: sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==} engines: {node: '>= 12'} @@ -5974,6 +6086,9 @@ packages: eastasianwidth@0.2.0: resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==} + ecc-jsbn@0.1.2: + resolution: {integrity: sha512-eh9O+hwRHNbG4BLTjEl3nw044CkGm5X6LoaCf7LPp7UU8Qrt47JYNi6nPX8xjW97TKGKm1ouctg0QSpZe9qrnw==} + ecdsa-sig-formatter@1.0.11: resolution: {integrity: sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==} @@ -6207,6 +6322,9 @@ packages: fast-levenshtein@2.0.6: resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} + fast-levenshtein@3.0.0: + resolution: {integrity: sha512-hKKNajm46uNmTlhHSyZkmToAc56uZJwYq7yrciZjqOxnlfQwERDQJmHPUp7m1m9wx8vgOe8IaCKZ5Kv2k1DdCQ==} + fast-png@6.4.0: resolution: {integrity: sha512-kAqZq1TlgBjZcLr5mcN6NP5Rv4V2f22z00c3g8vRrwkcqjerx7BEhPbOnWCPqaHUl2XWQBJQvOT/FQhdMT7X/Q==} @@ -6221,6 +6339,10 @@ packages: resolution: {integrity: sha512-pfX9uG9Ki0yekDHx2SiuRIyFdyAr1kMIMitPvb0YBo8SUfKvia7w7FIyd/l6av85pFYRhZscS75MwMnbvY+hcQ==} hasBin: true + fastest-levenshtein@1.0.16: + resolution: {integrity: sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==} + engines: {node: '>= 4.9.1'} + fastq@1.19.1: resolution: {integrity: sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==} @@ -6386,6 +6508,12 @@ packages: resolution: {integrity: sha512-b1O07XYq8eRuVzBNgJLstU6FYc1tS6wnMtF1I1D9lE8LxZSOGZ7LhxN54yPP6mGw5f2CkXY2BQUL9Fx41qvcIg==} engines: {node: '>= 14'} + get-value@4.0.1: + resolution: {integrity: sha512-QTDzwunK3V+VlJJlL0BlCzebAaE8OSlUC+UVd80PiekTw1gpzQSb3cfEQB2LYFWr1lbWfbdqL4pjAoJDPCLxhQ==} + + getpass@0.1.7: + resolution: {integrity: sha512-0fzj9JxOLfJ+XGLhR8ze3unN0KZCgZwiSSDz168VERjK8Wl8kVSdcu2kspd4s4wtAa1y/qrVRiAA0WclVsu0ng==} + glob-parent@5.1.2: resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==} engines: {node: '>= 6'} @@ -6402,6 +6530,11 @@ packages: deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me hasBin: true + glob@10.5.0: + resolution: {integrity: sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==} + deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me + hasBin: true + glob@11.0.3: resolution: {integrity: sha512-2Nim7dha1KVkaiF4q6Dj+ngPPMdfvLJEOpZk/jKiUAkqKebpGAWQXAq9z1xu9HKu5lWfqw/FASuccEjyznjPaA==} engines: {node: 20 || >=22} @@ -6804,9 +6937,17 @@ packages: resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==} engines: {node: '>=12'} + is-plain-object@2.0.4: + resolution: {integrity: sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==} + engines: {node: '>=0.10.0'} + is-potential-custom-element-name@1.0.1: resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==} + is-primitive@3.0.1: + resolution: {integrity: sha512-GljRxhWvlCNRfZyORiH77FwdFwGcMO620o37EOYC0ORWdq+WYNVqW0w2Juzew4M+L81l6/QS3t5gkkihyRqv9w==} + engines: {node: '>=0.10.0'} + is-regex@1.2.1: resolution: {integrity: sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==} engines: {node: '>= 0.4'} @@ -6868,6 +7009,10 @@ packages: isexe@2.0.0: resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + isobject@3.0.1: + resolution: {integrity: sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==} + engines: {node: '>=0.10.0'} + isomorphic.js@0.2.5: resolution: {integrity: sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==} @@ -7074,6 +7219,13 @@ packages: resolution: {integrity: sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==} hasBin: true + js-yaml@4.1.1: + resolution: {integrity: sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==} + hasBin: true + + jsbn@0.1.1: + resolution: {integrity: sha512-UVU9dibq2JcFWxQPA6KCqj5O42VOmAY3zQUfEKxU0KpTGXwNoCjkX1e13eHNvw/xPynt6pU0rZ1htjWTNTSXsg==} + jsdom@20.0.3: resolution: {integrity: sha512-SYhBvTh89tTfCD/CRdSOm13mOBa42iTaTyfyEWBdKcGdPxPtLFBXuHR8XHb33YNYaP+lLbmSvBTsnoesCNJEsQ==} engines: {node: '>=14'} @@ -7573,6 +7725,9 @@ packages: mutexify@1.4.0: resolution: {integrity: sha512-pbYSsOrSB/AKN5h/WzzLRMFgZhClWccf2XIB4RSMC8JbquiB0e0/SH5AIfdQMdyHmYtv4seU7yV/TvAwPLJ1Yg==} + nan@2.26.2: + resolution: {integrity: sha512-0tTvBTYkt3tdGw22nrAy50x7gpbGCCFH3AFcyS5WiUu7Eu4vWlri1woE6qHBSfy11vksDqkiwjOnlR7WV8G1Hw==} + nanoid@3.3.11: resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} @@ -7754,6 +7909,9 @@ packages: package-manager-detector@1.5.0: resolution: {integrity: sha512-uBj69dVlYe/+wxj8JOpr97XfsxH/eumMt6HqjNTmJDf/6NO9s+0uxeOneIz3AsPt2m6y9PqzDzd3ATcU17MNfw==} + packageurl-js@2.0.1: + resolution: {integrity: sha512-N5ixXjzTy4QDQH0Q9YFjqIWd6zH6936Djpl2m9QNFmDv5Fum8q8BjkpAcHNMzOFE0IwQrFhJWex3AN6kS0OSwg==} + pako@1.0.11: resolution: {integrity: sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==} @@ -8527,6 +8685,10 @@ packages: safer-buffer@2.1.2: resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} + sax@1.6.0: + resolution: {integrity: sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA==} + engines: {node: '>=11.0.0'} + saxes@6.0.0: resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==} engines: {node: '>=v12.22.7'} @@ -8564,6 +8726,10 @@ packages: resolution: {integrity: sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==} engines: {node: '>= 0.4'} + set-value@4.1.0: + resolution: {integrity: sha512-zTEg4HL0RwVrqcWs3ztF+x1vkxfm0lP+MQQFPiMJTKVceBwEV0A569Ou8l9IYQG8jOZdMVI1hGsc0tmeD2o/Lw==} + engines: {node: '>=11.0'} + setimmediate@1.0.5: resolution: {integrity: sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==} @@ -8702,6 +8868,15 @@ packages: resolution: {integrity: sha512-UXhXR2869FQaD+GMly8jAMCRZ94nU5KcrFetZfWEMd+LVVG6y0ExgHAhatEcKZ/wk8YcKPdi+hiD2wm75lq3/Q==} engines: {node: '>=4.0.0'} + ssh2@1.17.0: + resolution: {integrity: sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ==} + engines: {node: '>=10.16.0'} + + sshpk@1.16.1: + resolution: {integrity: sha512-HXXqVUq7+pcKeLqqZj6mHFUMvXtOJt1uoUx09pFW6011inTMxqI8BA8PM95myrIyyKwdnzjdFjLiE6KBPVtJIg==} + engines: {node: '>=0.10.0'} + hasBin: true + stack-utils@2.0.6: resolution: {integrity: sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==} engines: {node: '>=10'} @@ -9074,6 +9249,9 @@ packages: tw-animate-css@1.4.0: resolution: {integrity: sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ==} + tweetnacl@0.14.5: + resolution: {integrity: sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==} + typanion@3.14.0: resolution: {integrity: sha512-ZW/lVMRabETuYCd9O9ZvMhAh8GslSqaUjxmK/JLPCh6l73CvLBiuXswj/+7LdnWOgYsQ130FqLzFz5aGT4I3Ug==} @@ -9617,6 +9795,18 @@ packages: resolution: {integrity: sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==} engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} + ws@7.5.10: + resolution: {integrity: sha512-+dbF1tHwZpXcbOJdVOkzLDxZP1ailvSxM6ZweXTegylPny803bFhA+vqBYw4s31NSAk4S2Qz+AKXK9a4wkdjcQ==} + engines: {node: '>=8.3.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: ^5.0.2 + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + ws@8.18.0: resolution: {integrity: sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==} engines: {node: '>=10.0.0'} @@ -9645,6 +9835,14 @@ packages: resolution: {integrity: sha512-ICP2e+jsHvAj2E2lIHxa5tjXRlKDJo4IdvPvCXbXQGdzSfmSpNVyIKMvoZHjDY9DP0zV17iI85o90vRFXNccRw==} engines: {node: '>=12'} + xml2js@0.5.0: + resolution: {integrity: sha512-drPFnkQJik/O+uPKpqSgr22mpuFHqKdbS835iAQrUC73L2F5WkboIRd63ai/2Yg6I1jzifPFKH2NTK+cfglkIA==} + engines: {node: '>=4.0.0'} + + xmlbuilder@11.0.1: + resolution: {integrity: sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==} + engines: {node: '>=4.0'} + xmlchars@2.2.0: resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==} @@ -9675,6 +9873,9 @@ packages: yallist@3.1.1: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} + yamux-js@0.1.2: + resolution: {integrity: sha512-bhsPlPZ9xB4Dawyf6nkS58u4F3IvGCaybkEKGnneUeepcI7MPoG3Tt6SaKCU5x/kP2/2w20Qm/GqbpwAM16vYw==} + yargs-parser@21.1.1: resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==} engines: {node: '>=12'} @@ -11283,7 +11484,7 @@ snapshots: '@datadog/browser-core': 6.22.0 '@datadog/browser-rum-core': 6.22.0 - '@datadog/datadog-ci-base@4.1.2(@datadog/datadog-ci-plugin-cloud-run@4.1.2)(@types/node@20.19.23)': + '@datadog/datadog-ci-base@4.1.2(@datadog/datadog-ci-plugin-cloud-run@4.1.2)(@datadog/datadog-ci-plugin-deployment@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-dora@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-gate@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-sarif@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-sbom@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-synthetics@4.4.0(@datadog/datadog-ci-base@4.4.0))(@types/node@20.19.23)': dependencies: '@antfu/install-pkg': 1.1.0 '@types/datadog-metrics': 0.6.1 @@ -11308,13 +11509,54 @@ snapshots: upath: 2.0.1 optionalDependencies: '@datadog/datadog-ci-plugin-cloud-run': 4.1.2(@datadog/datadog-ci-base@4.1.2)(@types/node@20.19.23) + '@datadog/datadog-ci-plugin-deployment': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-dora': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-gate': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-sarif': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-sbom': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-synthetics': 4.4.0(@datadog/datadog-ci-base@4.4.0) + transitivePeerDependencies: + - '@types/node' + - supports-color + + '@datadog/datadog-ci-base@4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12)': + dependencies: + '@antfu/install-pkg': 1.1.0 + '@types/datadog-metrics': 0.6.1 + async-retry: 1.3.1 + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + clipanion: 3.2.1(typanion@3.14.0) + datadog-metrics: 0.9.3 + debug: 4.4.3 + deep-extend: 0.6.0 + fast-xml-parser: 4.5.3 + form-data: 4.0.4 + glob: 10.5.0 + inquirer: 8.2.7(@types/node@22.18.12) + jest-diff: 30.2.0 + jszip: 3.10.1 + proxy-agent: 6.5.0 + semver: 7.7.3 + simple-git: 3.16.0 + terminal-link: 2.1.1 + tiny-async-pool: 2.1.0 + typanion: 3.14.0 + upath: 2.0.1 + optionalDependencies: + '@datadog/datadog-ci-plugin-deployment': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-dora': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-gate': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-sarif': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-sbom': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-synthetics': 4.4.0(@datadog/datadog-ci-base@4.4.0) transitivePeerDependencies: - '@types/node' - supports-color '@datadog/datadog-ci-plugin-cloud-run@4.1.2(@datadog/datadog-ci-base@4.1.2)(@types/node@20.19.23)': dependencies: - '@datadog/datadog-ci-base': 4.1.2(@datadog/datadog-ci-plugin-cloud-run@4.1.2)(@types/node@20.19.23) + '@datadog/datadog-ci-base': 4.1.2(@datadog/datadog-ci-plugin-cloud-run@4.1.2)(@datadog/datadog-ci-plugin-deployment@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-dora@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-gate@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-sarif@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-sbom@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-synthetics@4.4.0(@datadog/datadog-ci-base@4.4.0))(@types/node@20.19.23) '@google-cloud/logging': 11.2.1 '@google-cloud/run': 3.0.1 chalk: 3.0.0 @@ -11329,6 +11571,119 @@ snapshots: - encoding - supports-color + '@datadog/datadog-ci-plugin-deployment@4.4.0(@datadog/datadog-ci-base@4.4.0)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + simple-git: 3.16.0 + transitivePeerDependencies: + - debug + - supports-color + + '@datadog/datadog-ci-plugin-dora@4.4.0(@datadog/datadog-ci-base@4.4.0)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + simple-git: 3.16.0 + transitivePeerDependencies: + - debug + - supports-color + + '@datadog/datadog-ci-plugin-gate@4.4.0(@datadog/datadog-ci-base@4.4.0)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + '@types/uuid': 9.0.8 + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + uuid: 9.0.1 + transitivePeerDependencies: + - debug + + '@datadog/datadog-ci-plugin-sarif@4.4.0(@datadog/datadog-ci-base@4.4.0)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + ajv: 8.18.0 + ajv-formats: 2.1.1(ajv@8.18.0) + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + form-data: 4.0.4 + simple-git: 3.16.0 + upath: 2.0.1 + uuid: 9.0.1 + transitivePeerDependencies: + - debug + - supports-color + + '@datadog/datadog-ci-plugin-sbom@4.4.0(@datadog/datadog-ci-base@4.4.0)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + ajv: 8.18.0 + ajv-formats: 2.1.1(ajv@8.18.0) + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + packageurl-js: 2.0.1 + simple-git: 3.16.0 + upath: 2.0.1 + transitivePeerDependencies: + - debug + - supports-color + + '@datadog/datadog-ci-plugin-synthetics@4.4.0(@datadog/datadog-ci-base@4.4.0)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + debug: 4.4.3 + deep-extend: 0.6.0 + fast-levenshtein: 3.0.0 + get-value: 4.0.1 + ora: 5.4.1 + set-value: 4.1.0 + ssh2: 1.17.0 + sshpk: 1.16.1 + upath: 2.0.1 + ws: 7.5.10 + xml2js: 0.5.0 + yamux-js: 0.1.2 + transitivePeerDependencies: + - bufferutil + - supports-color + - utf-8-validate + + '@datadog/datadog-ci@4.4.0(@types/node@22.18.12)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + '@datadog/datadog-ci-plugin-deployment': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-dora': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-gate': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-sarif': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-sbom': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-synthetics': 4.4.0(@datadog/datadog-ci-base@4.4.0) + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + clipanion: 3.2.1(typanion@3.14.0) + fast-xml-parser: 4.5.3 + form-data: 4.0.4 + js-yaml: 4.1.1 + semver: 7.7.3 + simple-git: 3.16.0 + typanion: 3.14.0 + upath: 2.0.1 + uuid: 9.0.1 + transitivePeerDependencies: + - '@datadog/datadog-ci-plugin-aas' + - '@datadog/datadog-ci-plugin-cloud-run' + - '@datadog/datadog-ci-plugin-container-app' + - '@datadog/datadog-ci-plugin-lambda' + - '@datadog/datadog-ci-plugin-stepfunctions' + - '@types/node' + - bufferutil + - debug + - supports-color + - utf-8-validate + '@datadog/flagging-core@0.1.0-preview.13(@openfeature/core@1.9.1)': dependencies: '@openfeature/core': 1.9.1 @@ -11912,6 +12267,13 @@ snapshots: optionalDependencies: '@types/node': 20.19.23 + '@inquirer/external-editor@1.0.2(@types/node@22.18.12)': + dependencies: + chardet: 2.1.1 + iconv-lite: 0.7.0 + optionalDependencies: + '@types/node': 22.18.12 + '@internationalized/date@3.10.0': dependencies: '@swc/helpers': 0.5.17 @@ -14885,6 +15247,8 @@ snapshots: '@types/use-sync-external-store@0.0.6': {} + '@types/uuid@9.0.8': {} + '@types/whatwg-mimetype@3.0.2': {} '@types/ws@8.18.1': @@ -15258,6 +15622,10 @@ snapshots: agent-base@7.1.4: {} + ajv-formats@2.1.1(ajv@8.18.0): + optionalDependencies: + ajv: 8.18.0 + ajv@6.12.6: dependencies: fast-deep-equal: 3.1.3 @@ -15374,6 +15742,12 @@ snapshots: arrify@2.0.1: {} + asn1@0.2.6: + dependencies: + safer-buffer: 2.1.2 + + assert-plus@1.0.0: {} + assertion-error@2.0.1: {} ast-types@0.13.4: @@ -15506,6 +15880,10 @@ snapshots: basic-ftp@5.0.5: {} + bcrypt-pbkdf@1.0.2: + dependencies: + tweetnacl: 0.14.5 + bignumber.js@9.3.1: {} bl@4.1.0: @@ -15560,6 +15938,9 @@ snapshots: base64-js: 1.5.1 ieee754: 1.2.1 + buildcheck@0.0.7: + optional: true + busboy@1.6.0: dependencies: streamsearch: 1.1.0 @@ -15730,6 +16111,12 @@ snapshots: object-assign: 4.1.1 vary: 1.1.2 + cpu-features@0.0.10: + dependencies: + buildcheck: 0.0.7 + nan: 2.26.2 + optional: true + create-jest@29.7.0(@types/node@22.18.12)(ts-node@10.9.2(@types/node@22.18.12)(typescript@5.9.3)): dependencies: '@jest/types': 29.6.3 @@ -15776,6 +16163,10 @@ snapshots: csstype@3.1.3: {} + dashdash@1.14.1: + dependencies: + assert-plus: 1.0.0 + data-uri-to-buffer@4.0.1: {} data-uri-to-buffer@6.0.2: {} @@ -15984,6 +16375,11 @@ snapshots: eastasianwidth@0.2.0: {} + ecc-jsbn@0.1.2: + dependencies: + jsbn: 0.1.1 + safer-buffer: 2.1.2 + ecdsa-sig-formatter@1.0.11: dependencies: safe-buffer: 5.2.1 @@ -16355,6 +16751,10 @@ snapshots: fast-levenshtein@2.0.6: {} + fast-levenshtein@3.0.0: + dependencies: + fastest-levenshtein: 1.0.16 + fast-png@6.4.0: dependencies: '@types/pako': 2.0.4 @@ -16371,6 +16771,8 @@ snapshots: dependencies: strnum: 2.1.1 + fastest-levenshtein@1.0.16: {} + fastq@1.19.1: dependencies: reusify: 1.1.0 @@ -16562,6 +16964,12 @@ snapshots: transitivePeerDependencies: - supports-color + get-value@4.0.1: {} + + getpass@0.1.7: + dependencies: + assert-plus: 1.0.0 + glob-parent@5.1.2: dependencies: is-glob: 4.0.3 @@ -16581,6 +16989,15 @@ snapshots: package-json-from-dist: 1.0.1 path-scurry: 1.11.1 + glob@10.5.0: + dependencies: + foreground-child: 3.3.1 + jackspeak: 3.4.3 + minimatch: 9.0.5 + minipass: 7.1.2 + package-json-from-dist: 1.0.1 + path-scurry: 1.11.1 + glob@11.0.3: dependencies: foreground-child: 3.3.1 @@ -17017,6 +17434,26 @@ snapshots: transitivePeerDependencies: - '@types/node' + inquirer@8.2.7(@types/node@22.18.12): + dependencies: + '@inquirer/external-editor': 1.0.2(@types/node@22.18.12) + ansi-escapes: 4.3.2 + chalk: 4.1.2 + cli-cursor: 3.1.0 + cli-width: 3.0.0 + figures: 3.2.0 + lodash: 4.17.21 + mute-stream: 0.0.8 + ora: 5.4.1 + run-async: 2.4.1 + rxjs: 7.8.2 + string-width: 4.2.3 + strip-ansi: 6.0.1 + through: 2.3.8 + wrap-ansi: 6.2.0 + transitivePeerDependencies: + - '@types/node' + internal-slot@1.1.0: dependencies: es-errors: 1.3.0 @@ -17125,8 +17562,14 @@ snapshots: is-plain-obj@4.1.0: {} + is-plain-object@2.0.4: + dependencies: + isobject: 3.0.1 + is-potential-custom-element-name@1.0.1: {} + is-primitive@3.0.1: {} + is-regex@1.2.1: dependencies: call-bound: 1.0.4 @@ -17182,6 +17625,8 @@ snapshots: isexe@2.0.0: {} + isobject@3.0.1: {} + isomorphic.js@0.2.5: {} istanbul-lib-coverage@3.2.2: {} @@ -17598,6 +18043,12 @@ snapshots: dependencies: argparse: 2.0.1 + js-yaml@4.1.1: + dependencies: + argparse: 2.0.1 + + jsbn@0.1.1: {} + jsdom@20.0.3: dependencies: abab: 2.0.6 @@ -18271,6 +18722,9 @@ snapshots: dependencies: queue-tick: 1.0.1 + nan@2.26.2: + optional: true + nanoid@3.3.11: {} natural-compare@1.4.0: {} @@ -18454,6 +18908,8 @@ snapshots: package-manager-detector@1.5.0: {} + packageurl-js@2.0.1: {} + pako@1.0.11: {} pako@2.1.0: {} @@ -19343,6 +19799,8 @@ snapshots: safer-buffer@2.1.2: {} + sax@1.6.0: {} + saxes@6.0.0: dependencies: xmlchars: 2.2.0 @@ -19383,6 +19841,11 @@ snapshots: es-errors: 1.3.0 es-object-atoms: 1.1.1 + set-value@4.1.0: + dependencies: + is-plain-object: 2.0.4 + is-primitive: 3.0.1 + setimmediate@1.0.5: {} sharp@0.33.5: @@ -19573,6 +20036,26 @@ snapshots: sql-template-strings@2.2.2: {} + ssh2@1.17.0: + dependencies: + asn1: 0.2.6 + bcrypt-pbkdf: 1.0.2 + optionalDependencies: + cpu-features: 0.0.10 + nan: 2.26.2 + + sshpk@1.16.1: + dependencies: + asn1: 0.2.6 + assert-plus: 1.0.0 + bcrypt-pbkdf: 1.0.2 + dashdash: 1.14.1 + ecc-jsbn: 0.1.2 + getpass: 0.1.7 + jsbn: 0.1.1 + safer-buffer: 2.1.2 + tweetnacl: 0.14.5 + stack-utils@2.0.6: dependencies: escape-string-regexp: 2.0.0 @@ -19958,6 +20441,8 @@ snapshots: tw-animate-css@1.4.0: {} + tweetnacl@0.14.5: {} + typanion@3.14.0: {} type-check@0.4.0: @@ -20634,12 +21119,21 @@ snapshots: imurmurhash: 0.1.4 signal-exit: 3.0.7 + ws@7.5.10: {} + ws@8.18.0: {} ws@8.18.3: {} xml-name-validator@4.0.0: {} + xml2js@0.5.0: + dependencies: + sax: 1.6.0 + xmlbuilder: 11.0.1 + + xmlbuilder@11.0.1: {} + xmlchars@2.2.0: {} xtend@4.0.2: {} @@ -20662,6 +21156,8 @@ snapshots: yallist@3.1.1: {} + yamux-js@0.1.2: {} + yargs-parser@21.1.1: {} yargs@17.7.2: From 0b0c3800802fb432e6017209b2b8773b400309e1 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Wed, 22 Apr 2026 22:20:13 +0200 Subject: [PATCH 58/75] feat: add datadog frontend sourcemap uploads --- .github/workflows/frontend-sourcemaps.yml | 74 +++ apps/clients/src/setupTests.ts | 34 +- apps/clients/src/vite-env.d.ts | 9 + apps/clients/src/viteConfig.test.ts | 13 + apps/clients/vite.config.ts | 3 + apps/external/package.json | 1 + apps/external/src/setupTests.ts | 1 + apps/external/src/vite-env.d.ts | 8 + apps/external/src/viteConfig.test.ts | 13 + apps/external/vite.config.ts | 7 +- apps/main/src/lib/rum.test.ts | 35 ++ apps/main/src/lib/rum.ts | 3 +- apps/main/src/setupTests.ts | 36 +- apps/main/src/vite-env.d.ts | 8 + apps/main/src/viteConfig.test.ts | 13 + apps/main/vite.config.ts | 3 + ...026-04-22-datadog-rum-sourcemaps-via-ci.md | 467 ++++++++++++++++ ...22-datadog-rum-sourcemaps-via-ci-design.md | 99 ++++ package.json | 1 + pnpm-lock.yaml | 502 +++++++++++++++++- 20 files changed, 1290 insertions(+), 40 deletions(-) create mode 100644 .github/workflows/frontend-sourcemaps.yml create mode 100644 apps/clients/src/vite-env.d.ts create mode 100644 apps/clients/src/viteConfig.test.ts create mode 100644 apps/external/src/setupTests.ts create mode 100644 apps/external/src/viteConfig.test.ts create mode 100644 apps/main/src/lib/rum.test.ts create mode 100644 apps/main/src/viteConfig.test.ts create mode 100644 docs/superpowers/plans/2026-04-22-datadog-rum-sourcemaps-via-ci.md create mode 100644 docs/superpowers/specs/2026-04-22-datadog-rum-sourcemaps-via-ci-design.md diff --git a/.github/workflows/frontend-sourcemaps.yml b/.github/workflows/frontend-sourcemaps.yml new file mode 100644 index 0000000..38247ee --- /dev/null +++ b/.github/workflows/frontend-sourcemaps.yml @@ -0,0 +1,74 @@ +name: Frontend Sourcemaps + +on: + workflow_dispatch: + push: + branches: + - main + - develop + +jobs: + upload-sourcemaps: + runs-on: + - self-hosted + - linux + - x64 + env: + DATADOG_API_KEY: ${{ secrets.DATADOG_API_KEY }} + DATADOG_SITE: ${{ secrets.DATADOG_SITE }} + RELEASE_VERSION: ${{ github.sha }} + steps: + - name: Check out repository + uses: actions/checkout@v6 + + - name: Set up pnpm + uses: pnpm/action-setup@v5 + with: + version: 10.19.0 + + - name: Set up Node.js + uses: actions/setup-node@v6 + with: + node-version: 22 + cache: pnpm + + - name: Validate Datadog secrets + run: | + test -n "$DATADOG_API_KEY" + test -n "$DATADOG_SITE" + + - name: Install dependencies + run: pnpm install --frozen-lockfile --child-concurrency=2 + + - name: Build main + run: pnpm --filter @xtablo/main build:prod + env: + VITE_APP_VERSION: ${{ env.RELEASE_VERSION }} + + - name: Upload main sourcemaps + run: pnpm exec datadog-ci sourcemaps upload apps/main/dist --service xtablo-ui --release-version "$RELEASE_VERSION" --minified-path-prefix https://app.xtablo.com/assets + + - name: Remove main sourcemaps + run: find apps/main/dist -name '*.map' -delete + + - name: Build clients + run: pnpm --filter @xtablo/clients build:prod + env: + VITE_APP_VERSION: ${{ env.RELEASE_VERSION }} + + - name: Upload clients sourcemaps + run: pnpm exec datadog-ci sourcemaps upload apps/clients/dist --service xtablo-clients --release-version "$RELEASE_VERSION" --minified-path-prefix https://clients.xtablo.com/assets + + - name: Remove clients sourcemaps + run: find apps/clients/dist -name '*.map' -delete + + - name: Build external + run: pnpm --filter @xtablo/external build + env: + VITE_APP_VERSION: ${{ env.RELEASE_VERSION }} + + - name: Upload external sourcemaps + run: pnpm exec datadog-ci sourcemaps upload apps/external/dist --service xtablo-external --release-version "$RELEASE_VERSION" --minified-path-prefix https://embed.xtablo.com/assets + + - name: Remove external sourcemaps + run: find apps/external/dist -name '*.map' -delete diff --git a/apps/clients/src/setupTests.ts b/apps/clients/src/setupTests.ts index 00791b7..d54e5d0 100644 --- a/apps/clients/src/setupTests.ts +++ b/apps/clients/src/setupTests.ts @@ -19,19 +19,23 @@ global.ResizeObserver = class ResizeObserver { } }; -Element.prototype.scrollIntoView = vi.fn(); -Element.prototype.scrollTo = vi.fn(); +if (typeof Element !== "undefined") { + Element.prototype.scrollIntoView = vi.fn(); + Element.prototype.scrollTo = vi.fn(); +} -Object.defineProperty(window, "matchMedia", { - writable: true, - value: vi.fn().mockImplementation((query) => ({ - matches: false, - media: query, - onchange: null, - addListener: vi.fn(), - removeListener: vi.fn(), - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - dispatchEvent: vi.fn(), - })), -}); +if (typeof window !== "undefined") { + Object.defineProperty(window, "matchMedia", { + writable: true, + value: vi.fn().mockImplementation((query) => ({ + matches: false, + media: query, + onchange: null, + addListener: vi.fn(), + removeListener: vi.fn(), + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + dispatchEvent: vi.fn(), + })), + }); +} diff --git a/apps/clients/src/vite-env.d.ts b/apps/clients/src/vite-env.d.ts new file mode 100644 index 0000000..f9164af --- /dev/null +++ b/apps/clients/src/vite-env.d.ts @@ -0,0 +1,9 @@ +/// + +interface ImportMetaEnv { + readonly VITE_APP_VERSION: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} diff --git a/apps/clients/src/viteConfig.test.ts b/apps/clients/src/viteConfig.test.ts new file mode 100644 index 0000000..5583270 --- /dev/null +++ b/apps/clients/src/viteConfig.test.ts @@ -0,0 +1,13 @@ +// @vitest-environment node + +import { describe, expect, it } from "vitest"; + +import configFactory from "../vite.config"; + +describe("clients vite config", () => { + it("uses hidden sourcemaps for production builds", () => { + const config = configFactory({ mode: "production", command: "build", isSsrBuild: false, isPreview: false }); + + expect(config.build?.sourcemap).toBe("hidden"); + }); +}); diff --git a/apps/clients/vite.config.ts b/apps/clients/vite.config.ts index 8fbd39f..db6ef09 100644 --- a/apps/clients/vite.config.ts +++ b/apps/clients/vite.config.ts @@ -17,6 +17,9 @@ export default defineConfig(({ mode }) => { return { plugins, + build: { + sourcemap: mode === "test" ? false : "hidden", + }, server: { cors: false }, define: process.env.VITEST ? { diff --git a/apps/external/package.json b/apps/external/package.json index b93d5b1..fa37897 100644 --- a/apps/external/package.json +++ b/apps/external/package.json @@ -27,6 +27,7 @@ "typescript": "^5.7.0", "vite": "^6.2.2", "vite-tsconfig-paths": "^5.1.4", + "vitest": "^3.2.4", "wrangler": "^4.24.3" }, "dependencies": { diff --git a/apps/external/src/setupTests.ts b/apps/external/src/setupTests.ts new file mode 100644 index 0000000..3115856 --- /dev/null +++ b/apps/external/src/setupTests.ts @@ -0,0 +1 @@ +// Intentionally minimal test setup so Vitest can honor the configured setupFiles path. diff --git a/apps/external/src/vite-env.d.ts b/apps/external/src/vite-env.d.ts index 11f02fe..f9164af 100644 --- a/apps/external/src/vite-env.d.ts +++ b/apps/external/src/vite-env.d.ts @@ -1 +1,9 @@ /// + +interface ImportMetaEnv { + readonly VITE_APP_VERSION: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} diff --git a/apps/external/src/viteConfig.test.ts b/apps/external/src/viteConfig.test.ts new file mode 100644 index 0000000..b3831b7 --- /dev/null +++ b/apps/external/src/viteConfig.test.ts @@ -0,0 +1,13 @@ +// @vitest-environment node + +import { describe, expect, it } from "vitest"; + +import configFactory from "../vite.config"; + +describe("external vite config", () => { + it("uses hidden sourcemaps for production builds", () => { + const config = configFactory({ mode: "production", command: "build", isSsrBuild: false, isPreview: false }); + + expect(config.build?.sourcemap).toBe("hidden"); + }); +}); diff --git a/apps/external/vite.config.ts b/apps/external/vite.config.ts index 8bd72da..c4f1e6b 100644 --- a/apps/external/vite.config.ts +++ b/apps/external/vite.config.ts @@ -3,13 +3,9 @@ import { cloudflare } from "@cloudflare/vite-plugin"; import tailwindcss from "@tailwindcss/vite"; import react from "@vitejs/plugin-react"; -import { dirname } from "path"; -import { fileURLToPath } from "url"; import { defineConfig, PluginOption } from "vite"; import tsconfigPaths from "vite-tsconfig-paths"; -const __dirname = dirname(fileURLToPath(import.meta.url)); - // https://vitejs.dev/config/ export default defineConfig(({ mode }) => { const plugins: PluginOption[] = [ @@ -26,6 +22,9 @@ export default defineConfig(({ mode }) => { return { plugins, + build: { + sourcemap: mode === "test" ? false : "hidden", + }, server: { cors: false, }, diff --git a/apps/main/src/lib/rum.test.ts b/apps/main/src/lib/rum.test.ts new file mode 100644 index 0000000..f468c19 --- /dev/null +++ b/apps/main/src/lib/rum.test.ts @@ -0,0 +1,35 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const init = vi.fn(); + +vi.mock("@datadog/browser-rum", () => ({ + datadogRum: { + init, + }, +})); + +vi.mock("@datadog/browser-rum-react", () => ({ + reactPlugin: () => "react-plugin", +})); + +describe("rum config", () => { + beforeEach(() => { + init.mockReset(); + vi.resetModules(); + }); + + it("sets the Datadog release version from VITE_APP_VERSION", async () => { + vi.stubEnv("VITE_APP_VERSION", "test-sha"); + vi.stubEnv("MODE", "production"); + + await import("./rum"); + + expect(init).toHaveBeenCalledWith( + expect.objectContaining({ + service: "xtablo-ui", + env: "production", + version: "test-sha", + }) + ); + }); +}); diff --git a/apps/main/src/lib/rum.ts b/apps/main/src/lib/rum.ts index 948e6f2..e2a49ca 100644 --- a/apps/main/src/lib/rum.ts +++ b/apps/main/src/lib/rum.ts @@ -13,9 +13,8 @@ datadogRum.init({ site: "datadoghq.com", service: "xtablo-ui", env: import.meta.env.MODE, + version: import.meta.env.VITE_APP_VERSION, - // Specify a version number to identify the deployed version of your application in Datadog - // version: '1.0.0', sessionSampleRate: 100, sessionReplaySampleRate: 80, defaultPrivacyLevel: "mask-user-input", diff --git a/apps/main/src/setupTests.ts b/apps/main/src/setupTests.ts index 1fa4e83..36149d2 100644 --- a/apps/main/src/setupTests.ts +++ b/apps/main/src/setupTests.ts @@ -21,20 +21,24 @@ global.ResizeObserver = class ResizeObserver { } }; -// Mock scrollIntoView for Radix UI components -Element.prototype.scrollIntoView = vi.fn(); -Element.prototype.scrollTo = vi.fn(); +// Mock scroll APIs for DOM-oriented tests without breaking node-environment suites. +if (typeof Element !== "undefined") { + Element.prototype.scrollIntoView = vi.fn(); + Element.prototype.scrollTo = vi.fn(); +} -Object.defineProperty(window, "matchMedia", { - writable: true, - value: vi.fn().mockImplementation((query) => ({ - matches: false, - media: query, - onchange: null, - addListener: vi.fn(), // deprecated - removeListener: vi.fn(), // deprecated - addEventListener: vi.fn(), - removeEventListener: vi.fn(), - dispatchEvent: vi.fn(), - })), -}); +if (typeof window !== "undefined") { + Object.defineProperty(window, "matchMedia", { + writable: true, + value: vi.fn().mockImplementation((query) => ({ + matches: false, + media: query, + onchange: null, + addListener: vi.fn(), // deprecated + removeListener: vi.fn(), // deprecated + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + dispatchEvent: vi.fn(), + })), + }); +} diff --git a/apps/main/src/vite-env.d.ts b/apps/main/src/vite-env.d.ts index 11f02fe..f9164af 100644 --- a/apps/main/src/vite-env.d.ts +++ b/apps/main/src/vite-env.d.ts @@ -1 +1,9 @@ /// + +interface ImportMetaEnv { + readonly VITE_APP_VERSION: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} diff --git a/apps/main/src/viteConfig.test.ts b/apps/main/src/viteConfig.test.ts new file mode 100644 index 0000000..3a15668 --- /dev/null +++ b/apps/main/src/viteConfig.test.ts @@ -0,0 +1,13 @@ +// @vitest-environment node + +import { describe, expect, it } from "vitest"; + +import configFactory from "../vite.config"; + +describe("main vite config", () => { + it("uses hidden sourcemaps for production builds", () => { + const config = configFactory({ mode: "production", command: "build", isSsrBuild: false, isPreview: false }); + + expect(config.build?.sourcemap).toBe("hidden"); + }); +}); diff --git a/apps/main/vite.config.ts b/apps/main/vite.config.ts index 59e1e45..10802fc 100644 --- a/apps/main/vite.config.ts +++ b/apps/main/vite.config.ts @@ -43,6 +43,9 @@ export default defineConfig(({ mode }) => { return { plugins, + build: { + sourcemap: mode === "test" ? false : "hidden", + }, server: { cors: false, }, diff --git a/docs/superpowers/plans/2026-04-22-datadog-rum-sourcemaps-via-ci.md b/docs/superpowers/plans/2026-04-22-datadog-rum-sourcemaps-via-ci.md new file mode 100644 index 0000000..ac7edbd --- /dev/null +++ b/docs/superpowers/plans/2026-04-22-datadog-rum-sourcemaps-via-ci.md @@ -0,0 +1,467 @@ +# Datadog RUM Sourcemaps Via CI Implementation Plan + +> **For agentic workers:** REQUIRED: Use superpowers:subagent-driven-development (if subagents available) or superpowers:executing-plans to implement this plan. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Generate private frontend sourcemaps for Datadog RUM/Error Tracking, upload them from GitHub Actions, and keep `.map` files out of deployed frontend assets. + +**Architecture:** Add an explicit release-version contract to the main app’s RUM init, enable hidden sourcemaps in all Vite frontends, and create a frontend CI workflow that builds each app, uploads sourcemaps with matching Datadog metadata, and removes `.map` files before any deploy step consumes the build output. + +**Tech Stack:** React 19, Vite 6, Vitest, GitHub Actions, Datadog CI CLI, Cloudflare/Wrangler deploy targets, pnpm workspaces. + +**Spec:** `docs/superpowers/specs/2026-04-22-datadog-rum-sourcemaps-via-ci-design.md` + +--- + +## File Structure + +### New files + +- `.github/workflows/frontend-sourcemaps.yml` — GitHub Actions workflow that builds the frontend apps on a self-hosted runner and uploads sourcemaps to Datadog. +- `apps/clients/src/vite-env.d.ts` — Vite env typings for client-specific build variables, including `VITE_APP_VERSION`. +- `apps/main/src/lib/rum.test.ts` — regression test for Datadog RUM init config. +- `apps/main/vite.config.test.ts` — production sourcemap config test for `apps/main`. +- `apps/clients/vite.config.test.ts` — production sourcemap config test for `apps/clients`. +- `apps/external/vite.config.test.ts` — production sourcemap config test for `apps/external`. + +### Modified files + +- `package.json` — add `@datadog/datadog-ci` to root dev dependencies. +- `apps/main/src/lib/rum.ts` — add `version: import.meta.env.VITE_APP_VERSION`. +- `apps/main/src/vite-env.d.ts` — add `VITE_APP_VERSION` typing. +- `apps/external/src/vite-env.d.ts` — add `VITE_APP_VERSION` typing. +- `apps/main/vite.config.ts` — enable hidden sourcemaps for non-test builds. +- `apps/clients/vite.config.ts` — enable hidden sourcemaps for non-test builds. +- `apps/external/vite.config.ts` — enable hidden sourcemaps for non-test builds. + +--- + +## Chunk 1: Runtime Release Metadata + +### Task 1: Wire Datadog RUM version in `apps/main` + +**Files:** +- Create: `apps/main/src/lib/rum.test.ts` +- Modify: `apps/main/src/lib/rum.ts` +- Modify: `apps/main/src/vite-env.d.ts` + +- [ ] **Step 1: Write the failing RUM init test** + +Create `apps/main/src/lib/rum.test.ts`: + +```typescript +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const init = vi.fn(); + +vi.mock("@datadog/browser-rum", () => ({ + datadogRum: { + init, + }, +})); + +vi.mock("@datadog/browser-rum-react", () => ({ + reactPlugin: () => "react-plugin", +})); + +describe("rum config", () => { + beforeEach(() => { + init.mockReset(); + vi.resetModules(); + }); + + it("sets the Datadog release version from VITE_APP_VERSION", async () => { + vi.stubEnv("VITE_APP_VERSION", "test-sha"); + vi.stubEnv("MODE", "production"); + + await import("./rum"); + + expect(init).toHaveBeenCalledWith( + expect.objectContaining({ + service: "xtablo-ui", + env: "production", + version: "test-sha", + }) + ); + }); +}); +``` + +- [ ] **Step 2: Run the test to verify it fails** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run src/lib/rum.test.ts --mode dev +``` + +Expected: FAIL because `version` is not set in `datadogRum.init`. + +- [ ] **Step 3: Add the runtime version** + +Update `apps/main/src/lib/rum.ts`: + +```typescript + service: "xtablo-ui", + env: import.meta.env.MODE, + version: import.meta.env.VITE_APP_VERSION, +``` + +Update `apps/main/src/vite-env.d.ts`: + +```typescript +/// + +interface ImportMetaEnv { + readonly VITE_APP_VERSION: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} +``` + +- [ ] **Step 4: Run the test to verify it passes** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run src/lib/rum.test.ts --mode dev +pnpm --filter @xtablo/main typecheck +``` + +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add apps/main/src/lib/rum.ts apps/main/src/lib/rum.test.ts apps/main/src/vite-env.d.ts +git commit -m "feat: add Datadog release version to main rum config" +``` + +--- + +## Chunk 2: Hidden Sourcemaps In All Vite Frontends + +### Task 2: Add production sourcemap config tests + +**Files:** +- Create: `apps/main/vite.config.test.ts` +- Create: `apps/clients/vite.config.test.ts` +- Create: `apps/external/vite.config.test.ts` + +- [ ] **Step 1: Write the failing config test for `apps/main`** + +Create `apps/main/vite.config.test.ts`: + +```typescript +import { describe, expect, it } from "vitest"; +import configFactory from "./vite.config"; + +describe("main vite config", () => { + it("uses hidden sourcemaps for production builds", () => { + const config = configFactory({ mode: "production" }); + expect(config.build?.sourcemap).toBe("hidden"); + }); +}); +``` + +- [ ] **Step 2: Write the failing config test for `apps/clients`** + +Create `apps/clients/vite.config.test.ts`: + +```typescript +import { describe, expect, it } from "vitest"; +import configFactory from "./vite.config"; + +describe("clients vite config", () => { + it("uses hidden sourcemaps for production builds", () => { + const config = configFactory({ mode: "production" }); + expect(config.build?.sourcemap).toBe("hidden"); + }); +}); +``` + +- [ ] **Step 3: Write the failing config test for `apps/external`** + +Create `apps/external/vite.config.test.ts`: + +```typescript +import { describe, expect, it } from "vitest"; +import configFactory from "./vite.config"; + +describe("external vite config", () => { + it("uses hidden sourcemaps for production builds", () => { + const config = configFactory({ mode: "production" }); + expect(config.build?.sourcemap).toBe("hidden"); + }); +}); +``` + +- [ ] **Step 4: Run the tests to verify they fail** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run vite.config.test.ts --mode dev +pnpm --filter @xtablo/clients exec vitest run vite.config.test.ts --mode test +pnpm --filter @xtablo/external exec vitest run vite.config.test.ts --mode test +``` + +Expected: FAIL because `build.sourcemap` is not configured. + +- [ ] **Step 5: Implement hidden sourcemaps in all three Vite configs** + +Update: +- `apps/main/vite.config.ts` +- `apps/clients/vite.config.ts` +- `apps/external/vite.config.ts` + +Add the same build section in each returned config: + +```typescript + build: { + sourcemap: mode === "test" ? false : "hidden", + }, +``` + +Keep it alongside the existing `plugins`, `server`, `define`, and `test` sections. + +- [ ] **Step 6: Add env typing for the remaining apps** + +Create `apps/clients/src/vite-env.d.ts`: + +```typescript +/// + +interface ImportMetaEnv { + readonly VITE_APP_VERSION: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} +``` + +Update `apps/external/src/vite-env.d.ts`: + +```typescript +/// + +interface ImportMetaEnv { + readonly VITE_APP_VERSION: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} +``` + +- [ ] **Step 7: Run the tests and typechecks** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run vite.config.test.ts --mode dev +pnpm --filter @xtablo/clients exec vitest run vite.config.test.ts --mode test +pnpm --filter @xtablo/external exec vitest run vite.config.test.ts --mode test +pnpm --filter @xtablo/main typecheck +pnpm --filter @xtablo/clients typecheck +pnpm --filter @xtablo/external typecheck +``` + +Expected: PASS. + +- [ ] **Step 8: Commit** + +```bash +git add apps/main/vite.config.ts apps/main/vite.config.test.ts apps/clients/vite.config.ts apps/clients/vite.config.test.ts apps/clients/src/vite-env.d.ts apps/external/vite.config.ts apps/external/vite.config.test.ts apps/external/src/vite-env.d.ts +git commit -m "build: enable hidden sourcemaps for frontend apps" +``` + +--- + +## Chunk 3: Datadog CI Upload Workflow + +### Task 3: Add pinned Datadog CLI and frontend sourcemap workflow + +**Files:** +- Create: `.github/workflows/frontend-sourcemaps.yml` +- Modify: `package.json` + +- [ ] **Step 1: Add the Datadog CLI dependency** + +Update root `package.json`: + +```json + "devDependencies": { + "@biomejs/biome": "2.2.5", + "@datadog/datadog-ci": "^3.21.0", + "turbo": "^2.5.8", + "typescript": "^5.7.0" + } +``` + +- [ ] **Step 2: Install dependencies and verify lockfile changes** + +Run: + +```bash +pnpm install +``` + +Expected: `pnpm-lock.yaml` updates with `@datadog/datadog-ci`. + +- [ ] **Step 3: Create the workflow** + +Create `.github/workflows/frontend-sourcemaps.yml`: + +```yaml +name: Frontend Sourcemaps + +on: + workflow_dispatch: + push: + branches: + - main + - develop + +jobs: + upload-sourcemaps: + runs-on: + - self-hosted + - linux + - x64 + env: + DATADOG_API_KEY: ${{ secrets.DATADOG_API_KEY }} + DATADOG_SITE: ${{ secrets.DATADOG_SITE }} + RELEASE_VERSION: ${{ github.sha }} + steps: + - uses: actions/checkout@v6 + + - uses: pnpm/action-setup@v5 + with: + version: 10.19.0 + + - uses: actions/setup-node@v6 + with: + node-version: 22 + cache: pnpm + + - name: Install dependencies + run: pnpm install --frozen-lockfile --child-concurrency=2 + + - name: Build main + run: pnpm --filter @xtablo/main build:prod + env: + VITE_APP_VERSION: ${{ env.RELEASE_VERSION }} + + - name: Upload main sourcemaps + run: pnpm exec datadog-ci sourcemaps upload apps/main/dist --service xtablo-ui --release-version "$RELEASE_VERSION" --minified-path-prefix https://app.xtablo.com/assets + + - name: Remove main sourcemaps + run: find apps/main/dist -name '*.map' -delete + + - name: Build clients + run: pnpm --filter @xtablo/clients build:prod + env: + VITE_APP_VERSION: ${{ env.RELEASE_VERSION }} + + - name: Upload clients sourcemaps + run: pnpm exec datadog-ci sourcemaps upload apps/clients/dist --service xtablo-clients --release-version "$RELEASE_VERSION" --minified-path-prefix https://clients.xtablo.com/assets + + - name: Remove clients sourcemaps + run: find apps/clients/dist -name '*.map' -delete + + - name: Build external + run: pnpm --filter @xtablo/external build + env: + VITE_APP_VERSION: ${{ env.RELEASE_VERSION }} + + - name: Upload external sourcemaps + run: pnpm exec datadog-ci sourcemaps upload apps/external/dist --service xtablo-external --release-version "$RELEASE_VERSION" --minified-path-prefix https://embed.xtablo.com/assets + + - name: Remove external sourcemaps + run: find apps/external/dist -name '*.map' -delete +``` + +- [ ] **Step 4: Validate the workflow file structure** + +Run: + +```bash +rg -n "datadog-ci sourcemaps upload|RELEASE_VERSION|find .*\\.map" .github/workflows/frontend-sourcemaps.yml +``` + +Expected: one upload and one cleanup step for each frontend app. + +- [ ] **Step 5: Commit** + +```bash +git add package.json pnpm-lock.yaml .github/workflows/frontend-sourcemaps.yml +git commit -m "ci: upload frontend sourcemaps to Datadog" +``` + +--- + +## Chunk 4: End-To-End Verification + +### Task 4: Prove builds emit hidden sourcemaps and cleanup works + +**Files:** +- No new source files + +- [ ] **Step 1: Build each frontend locally with a release version** + +Run: + +```bash +VITE_APP_VERSION=test-sha pnpm --filter @xtablo/main build:prod +VITE_APP_VERSION=test-sha pnpm --filter @xtablo/clients build:prod +VITE_APP_VERSION=test-sha pnpm --filter @xtablo/external build +``` + +Expected: each `dist/` contains built assets and `.map` files, but the generated JS bundles do not include public `sourceMappingURL` comments. + +- [ ] **Step 2: Verify `.map` files exist before cleanup** + +Run: + +```bash +find apps/main/dist apps/clients/dist apps/external/dist -name '*.map' | sort +``` + +Expected: at least one sourcemap per app. + +- [ ] **Step 3: Simulate CI cleanup locally** + +Run: + +```bash +find apps/main/dist apps/clients/dist apps/external/dist -name '*.map' -delete +find apps/main/dist apps/clients/dist apps/external/dist -name '*.map' | sort +``` + +Expected: no output from the second command. + +- [ ] **Step 4: Run the targeted regression suite** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run src/lib/rum.test.ts vite.config.test.ts --mode dev +pnpm --filter @xtablo/clients exec vitest run vite.config.test.ts --mode test +pnpm --filter @xtablo/external exec vitest run vite.config.test.ts --mode test +pnpm --filter @xtablo/main typecheck +pnpm --filter @xtablo/clients typecheck +pnpm --filter @xtablo/external typecheck +``` + +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git status --short +``` + +Expected: clean worktree before opening the implementation PR. diff --git a/docs/superpowers/specs/2026-04-22-datadog-rum-sourcemaps-via-ci-design.md b/docs/superpowers/specs/2026-04-22-datadog-rum-sourcemaps-via-ci-design.md new file mode 100644 index 0000000..6e247b0 --- /dev/null +++ b/docs/superpowers/specs/2026-04-22-datadog-rum-sourcemaps-via-ci-design.md @@ -0,0 +1,99 @@ +# Datadog RUM Sourcemaps Via CI Design + +**Goal:** Deobfuscate frontend RUM and Error Tracking stack traces in Datadog for the Xtablo frontends by generating sourcemaps during build, uploading them in CI, and keeping `.map` files off the public CDN. + +## Current State + +- `apps/main` initializes Datadog RUM in [apps/main/src/lib/rum.ts](/Users/arthur.belleville/Documents/perso/projects/xtablo-source/apps/main/src/lib/rum.ts) with `service: "xtablo-ui"` and `env: import.meta.env.MODE`, but no explicit release version. +- `apps/main`, `apps/clients`, and `apps/external` are Vite frontends with production Cloudflare deployments. +- None of the three Vite configs currently emit production sourcemaps. +- On this branch there is no tracked GitHub Actions workflow yet, so CI wiring must be introduced as part of the implementation. + +## Decision + +Use Datadog’s recommended CI upload flow: + +1. Build each frontend with Vite `build.sourcemap: "hidden"`. +2. Upload generated sourcemaps from CI with `datadog-ci sourcemaps upload`. +3. Use a release version derived from the CI commit SHA. +4. Remove all `.map` files from `dist/` before deploy packaging so they are never publicly served. + +This keeps sourcemaps private while still enabling unminified stack traces in Datadog. + +Sources: +- Datadog CI sourcemap upload guide: https://docs.datadoghq.com/real_user_monitoring/guide/upload-javascript-source-maps/?tab=vite +- Vite `build.sourcemap` docs: https://vite.dev/config/build-options.html + +## Runtime Contract + +Datadog matches sourcemaps against browser events by `service` and `version`. + +- `apps/main` must emit `version: import.meta.env.VITE_APP_VERSION` in its RUM initialization. +- CI must upload sourcemaps for `apps/main` using: + - `service=xtablo-ui` + - `release-version=$GITHUB_SHA` +- `apps/clients` and `apps/external` should use the same CI release version convention now, even though they do not currently emit RUM events. This keeps the deployment contract consistent and avoids another pipeline change when browser monitoring is enabled there. + +## Public Asset Prefixes + +The Datadog upload command must use the real production asset prefixes: + +- `apps/main`: `https://app.xtablo.com/assets` +- `apps/clients`: `https://clients.xtablo.com/assets` +- `apps/external`: `https://embed.xtablo.com/assets` + +These prefixes must match the actual URLs used by the deployed JS bundles. + +## Implementation Shape + +### Frontend code + +- `apps/main/src/lib/rum.ts` + - add `version: import.meta.env.VITE_APP_VERSION` +- `apps/main/src/vite-env.d.ts` + - declare `VITE_APP_VERSION` +- `apps/clients/src/vite-env.d.ts` + - create and declare `VITE_APP_VERSION` +- `apps/external/src/vite-env.d.ts` + - declare `VITE_APP_VERSION` + +### Build config + +- `apps/main/vite.config.ts` +- `apps/clients/vite.config.ts` +- `apps/external/vite.config.ts` + +Each should emit hidden sourcemaps for non-test builds. + +### CI + +- Add GitHub Actions workflow for frontend builds on self-hosted runners. +- Add `@datadog/datadog-ci` as a root dev dependency so the workflow can run a pinned CLI version from the repo. +- After each frontend build: + - upload sourcemaps to Datadog + - delete `dist/**/*.map` + +## Secrets And CI Inputs + +The workflow needs: + +- `DATADOG_API_KEY` +- `DATADOG_SITE` +- release version from `github.sha` + +The workflow should fail fast if Datadog secrets are missing on the deployment path where sourcemap upload is required. + +## Verification + +- Unit test for `apps/main` RUM init to assert `version` is wired from env. +- Vite config tests or config assertions for all three apps to verify production builds use `sourcemap: "hidden"`. +- CI workflow smoke verification: + - build the apps + - run sourcemap upload + - confirm `.map` files are removed from `dist` + +## Non-Goals + +- Enabling Datadog RUM in `apps/clients` or `apps/external` right now. +- Serving sourcemaps publicly. +- Changing app deployment hosts or CDN paths. diff --git a/package.json b/package.json index 5366d4f..5dd27ce 100644 --- a/package.json +++ b/package.json @@ -33,6 +33,7 @@ }, "devDependencies": { "@biomejs/biome": "2.2.5", + "@datadog/datadog-ci": "^4.3.0", "turbo": "^2.5.8", "typescript": "^5.7.0" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 240d4f4..6337b4e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -17,6 +17,9 @@ importers: '@biomejs/biome': specifier: 2.2.5 version: 2.2.5 + '@datadog/datadog-ci': + specifier: ^4.3.0 + version: 4.4.0(@types/node@22.18.12) turbo: specifier: ^2.5.8 version: 2.5.8 @@ -89,7 +92,7 @@ importers: version: 2.2.5 '@datadog/datadog-ci-base': specifier: ^4.0.2 - version: 4.1.2(@datadog/datadog-ci-plugin-cloud-run@4.1.2)(@types/node@20.19.23) + version: 4.1.2(@datadog/datadog-ci-plugin-cloud-run@4.1.2)(@datadog/datadog-ci-plugin-deployment@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-dora@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-gate@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-sarif@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-sbom@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-synthetics@4.4.0(@datadog/datadog-ci-base@4.4.0))(@types/node@20.19.23) '@datadog/datadog-ci-plugin-cloud-run': specifier: ^4.0.2 version: 4.1.2(@datadog/datadog-ci-base@4.1.2)(@types/node@20.19.23) @@ -321,6 +324,9 @@ importers: vite-tsconfig-paths: specifier: ^5.1.4 version: 5.1.4(typescript@5.9.3)(vite@6.4.1(@types/node@22.18.12)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6)) + vitest: + specifier: ^3.2.4 + version: 3.2.4(@types/debug@4.1.12)(@types/node@22.18.12)(happy-dom@20.0.7)(jiti@2.6.1)(jsdom@20.0.3)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6) wrangler: specifier: ^4.24.3 version: 4.44.0(@cloudflare/workers-types@4.20260411.1) @@ -1987,11 +1993,84 @@ packages: '@datadog/datadog-ci-plugin-synthetics': optional: true + '@datadog/datadog-ci-base@4.4.0': + resolution: {integrity: sha512-sFssfj3EQKBiD9SkVYzhkzHZEQqmnsMGXKYKoLLTFcTmRbaePItx/1Sa3KzFVIWBhZQSpYoJt3VZ7+cagCShLA==} + peerDependencies: + '@datadog/datadog-ci-plugin-aas': 4.4.0 + '@datadog/datadog-ci-plugin-cloud-run': 4.4.0 + '@datadog/datadog-ci-plugin-container-app': 4.4.0 + '@datadog/datadog-ci-plugin-deployment': 4.4.0 + '@datadog/datadog-ci-plugin-dora': 4.4.0 + '@datadog/datadog-ci-plugin-gate': 4.4.0 + '@datadog/datadog-ci-plugin-lambda': 4.4.0 + '@datadog/datadog-ci-plugin-sarif': 4.4.0 + '@datadog/datadog-ci-plugin-sbom': 4.4.0 + '@datadog/datadog-ci-plugin-stepfunctions': 4.4.0 + '@datadog/datadog-ci-plugin-synthetics': 4.4.0 + peerDependenciesMeta: + '@datadog/datadog-ci-plugin-aas': + optional: true + '@datadog/datadog-ci-plugin-cloud-run': + optional: true + '@datadog/datadog-ci-plugin-container-app': + optional: true + '@datadog/datadog-ci-plugin-deployment': + optional: true + '@datadog/datadog-ci-plugin-dora': + optional: true + '@datadog/datadog-ci-plugin-gate': + optional: true + '@datadog/datadog-ci-plugin-lambda': + optional: true + '@datadog/datadog-ci-plugin-sarif': + optional: true + '@datadog/datadog-ci-plugin-sbom': + optional: true + '@datadog/datadog-ci-plugin-stepfunctions': + optional: true + '@datadog/datadog-ci-plugin-synthetics': + optional: true + '@datadog/datadog-ci-plugin-cloud-run@4.1.2': resolution: {integrity: sha512-HKVZ7SSjzskdVqIrf16bqmgeRrxscoRkgh9ILfni3D/GoXpG3DFaZPs7pXJR6igjBeZMclLjtolqMyyWy7DCLQ==} peerDependencies: '@datadog/datadog-ci-base': 4.1.2 + '@datadog/datadog-ci-plugin-deployment@4.4.0': + resolution: {integrity: sha512-u9FtFw2TKRF74wwcuM8tWseWTrLKZZ/Lwq1Fz+LtAGHTJ5675WuIhGNnSxbrKU4f2VsaFp+eUIsetcqbuUerXw==} + peerDependencies: + '@datadog/datadog-ci-base': 4.4.0 + + '@datadog/datadog-ci-plugin-dora@4.4.0': + resolution: {integrity: sha512-DuyKfiwxZoNu5dlMPZNq6DYlafR/3kpaqS0q9KfGStnu1LwS5YTREuZgssNkyYWnF6qZN80x1l7E/ubaAFVYOg==} + peerDependencies: + '@datadog/datadog-ci-base': 4.4.0 + + '@datadog/datadog-ci-plugin-gate@4.4.0': + resolution: {integrity: sha512-bR5AY5p5/5jQuZtcuEPJrEpL1WhJiXhfPwuc9OhGN0ny4/98S3Hg02aQ9aoloFipsBgEN3W5XhrWH6Pn1jSI5w==} + peerDependencies: + '@datadog/datadog-ci-base': 4.4.0 + + '@datadog/datadog-ci-plugin-sarif@4.4.0': + resolution: {integrity: sha512-kgExnC/ReiGKr9R6SxaXr62lp2fYJQ4i8c9x4/GqDpNbLENQdsqBmxs6h1/N3xkdt3/p3RZlMcAhIytLYDkBAA==} + peerDependencies: + '@datadog/datadog-ci-base': 4.4.0 + + '@datadog/datadog-ci-plugin-sbom@4.4.0': + resolution: {integrity: sha512-bBsgIBBT0KsWqLcIMuf692PGjMNjG6OKNUjuPZOWbuToyKKnpRRkMDrX9KvUWVXuMKfDEp7i2PYw/2fQm5DXHg==} + peerDependencies: + '@datadog/datadog-ci-base': 4.4.0 + + '@datadog/datadog-ci-plugin-synthetics@4.4.0': + resolution: {integrity: sha512-SpGdOZUSjEVZZD/hopPKuXnOP6ZRl0nnZ8i5ffVIxohlMwn5y0vMWjjkDohk24M+2QBDUnMe4sNXW4YP1aeSWg==} + peerDependencies: + '@datadog/datadog-ci-base': 4.4.0 + + '@datadog/datadog-ci@4.4.0': + resolution: {integrity: sha512-vpQPcz+FRgDhPoHg9aXtTeaVe6Dhky6q1vG9TmOWDX39Pjf/Wz1LEY94uWvK6miC8orHf6RtIGOSxsycRNde7g==} + engines: {node: '>=18'} + hasBin: true + '@datadog/flagging-core@0.1.0-preview.13': resolution: {integrity: sha512-DfQYeBgGvCerKx6coRiXMt0aXWJB8kRIsJhfdTKyejS9rfp6ZBjWc6dctKzhwMAQdpBiN42MEVXNt4Pdcmj1WA==} peerDependencies: @@ -5042,6 +5121,9 @@ packages: '@types/use-sync-external-store@0.0.6': resolution: {integrity: sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==} + '@types/uuid@9.0.8': + resolution: {integrity: sha512-jg+97EGIcY9AGHJJRaaPVgetKDsrTgbRjQ5Msgjh/DQKEFl0DtyRr/VCOyD1T2R1MNeWPK/u7JoGhlDZnKBAfA==} + '@types/whatwg-mimetype@3.0.2': resolution: {integrity: sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==} @@ -5341,6 +5423,14 @@ packages: resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==} engines: {node: '>= 14'} + ajv-formats@2.1.1: + resolution: {integrity: sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==} + peerDependencies: + ajv: ^8.0.0 + peerDependenciesMeta: + ajv: + optional: true + ajv@6.12.6: resolution: {integrity: sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==} @@ -5434,6 +5524,13 @@ packages: resolution: {integrity: sha512-3duEwti880xqi4eAMN8AyR4a0ByT90zoYdLlevfrvU43vb0YZwZVfxOgxWrLXXXpyugL0hNZc9G6BiB5B3nUug==} engines: {node: '>=8'} + asn1@0.2.6: + resolution: {integrity: sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==} + + assert-plus@1.0.0: + resolution: {integrity: sha512-NfJ4UzBCcQGLDlQq7nHxH+tv3kyZ0hHQqF5BO6J7tNJeP5do1llPr8dZ8zHonfhAu0PHAdMkSo+8o0wxg9lZWw==} + engines: {node: '>=0.8'} + assertion-error@2.0.1: resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} engines: {node: '>=12'} @@ -5539,6 +5636,9 @@ packages: resolution: {integrity: sha512-4Bcg1P8xhUuqcii/S0Z9wiHIrQVPMermM1any+MX5GeGD7faD3/msQUDGLol9wOcz4/jbg/WJnGqoJF6LiBdtg==} engines: {node: '>=10.0.0'} + bcrypt-pbkdf@1.0.2: + resolution: {integrity: sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==} + bignumber.js@9.3.1: resolution: {integrity: sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==} @@ -5583,6 +5683,10 @@ packages: buffer@5.7.1: resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==} + buildcheck@0.0.7: + resolution: {integrity: sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA==} + engines: {node: '>=10.0.0'} + busboy@1.6.0: resolution: {integrity: sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==} engines: {node: '>=10.16.0'} @@ -5780,6 +5884,10 @@ packages: resolution: {integrity: sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==} engines: {node: '>= 0.10'} + cpu-features@0.0.10: + resolution: {integrity: sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA==} + engines: {node: '>=10.0.0'} + create-jest@29.7.0: resolution: {integrity: sha512-Adz2bdH0Vq3F53KEMJOoftQFutWCukm6J24wbPWRO4k1kMY7gS7ds/uoJkNuV8wDCtWWnuwGcJwpWcih+zEW1Q==} engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} @@ -5821,6 +5929,10 @@ packages: csstype@3.1.3: resolution: {integrity: sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==} + dashdash@1.14.1: + resolution: {integrity: sha512-jRFi8UDGo6j+odZiEpjazZaWqEal3w/basFjQHQEwVtZJGDpxbH1MeYluwCS8Xq5wmLJooDlMgvVarmWfGM44g==} + engines: {node: '>=0.10'} + data-uri-to-buffer@4.0.1: resolution: {integrity: sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==} engines: {node: '>= 12'} @@ -6017,6 +6129,9 @@ packages: eastasianwidth@0.2.0: resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==} + ecc-jsbn@0.1.2: + resolution: {integrity: sha512-eh9O+hwRHNbG4BLTjEl3nw044CkGm5X6LoaCf7LPp7UU8Qrt47JYNi6nPX8xjW97TKGKm1ouctg0QSpZe9qrnw==} + ecdsa-sig-formatter@1.0.11: resolution: {integrity: sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==} @@ -6250,6 +6365,9 @@ packages: fast-levenshtein@2.0.6: resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} + fast-levenshtein@3.0.0: + resolution: {integrity: sha512-hKKNajm46uNmTlhHSyZkmToAc56uZJwYq7yrciZjqOxnlfQwERDQJmHPUp7m1m9wx8vgOe8IaCKZ5Kv2k1DdCQ==} + fast-png@6.4.0: resolution: {integrity: sha512-kAqZq1TlgBjZcLr5mcN6NP5Rv4V2f22z00c3g8vRrwkcqjerx7BEhPbOnWCPqaHUl2XWQBJQvOT/FQhdMT7X/Q==} @@ -6264,6 +6382,10 @@ packages: resolution: {integrity: sha512-pfX9uG9Ki0yekDHx2SiuRIyFdyAr1kMIMitPvb0YBo8SUfKvia7w7FIyd/l6av85pFYRhZscS75MwMnbvY+hcQ==} hasBin: true + fastest-levenshtein@1.0.16: + resolution: {integrity: sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==} + engines: {node: '>= 4.9.1'} + fastq@1.19.1: resolution: {integrity: sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==} @@ -6429,6 +6551,12 @@ packages: resolution: {integrity: sha512-b1O07XYq8eRuVzBNgJLstU6FYc1tS6wnMtF1I1D9lE8LxZSOGZ7LhxN54yPP6mGw5f2CkXY2BQUL9Fx41qvcIg==} engines: {node: '>= 14'} + get-value@4.0.1: + resolution: {integrity: sha512-QTDzwunK3V+VlJJlL0BlCzebAaE8OSlUC+UVd80PiekTw1gpzQSb3cfEQB2LYFWr1lbWfbdqL4pjAoJDPCLxhQ==} + + getpass@0.1.7: + resolution: {integrity: sha512-0fzj9JxOLfJ+XGLhR8ze3unN0KZCgZwiSSDz168VERjK8Wl8kVSdcu2kspd4s4wtAa1y/qrVRiAA0WclVsu0ng==} + glob-parent@5.1.2: resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==} engines: {node: '>= 6'} @@ -6445,6 +6573,11 @@ packages: deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me hasBin: true + glob@10.5.0: + resolution: {integrity: sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==} + deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me + hasBin: true + glob@11.0.3: resolution: {integrity: sha512-2Nim7dha1KVkaiF4q6Dj+ngPPMdfvLJEOpZk/jKiUAkqKebpGAWQXAq9z1xu9HKu5lWfqw/FASuccEjyznjPaA==} engines: {node: 20 || >=22} @@ -6847,9 +6980,17 @@ packages: resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==} engines: {node: '>=12'} + is-plain-object@2.0.4: + resolution: {integrity: sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==} + engines: {node: '>=0.10.0'} + is-potential-custom-element-name@1.0.1: resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==} + is-primitive@3.0.1: + resolution: {integrity: sha512-GljRxhWvlCNRfZyORiH77FwdFwGcMO620o37EOYC0ORWdq+WYNVqW0w2Juzew4M+L81l6/QS3t5gkkihyRqv9w==} + engines: {node: '>=0.10.0'} + is-regex@1.2.1: resolution: {integrity: sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==} engines: {node: '>= 0.4'} @@ -6911,6 +7052,10 @@ packages: isexe@2.0.0: resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + isobject@3.0.1: + resolution: {integrity: sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==} + engines: {node: '>=0.10.0'} + isomorphic.js@0.2.5: resolution: {integrity: sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==} @@ -7117,6 +7262,13 @@ packages: resolution: {integrity: sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==} hasBin: true + js-yaml@4.1.1: + resolution: {integrity: sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==} + hasBin: true + + jsbn@0.1.1: + resolution: {integrity: sha512-UVU9dibq2JcFWxQPA6KCqj5O42VOmAY3zQUfEKxU0KpTGXwNoCjkX1e13eHNvw/xPynt6pU0rZ1htjWTNTSXsg==} + jsdom@20.0.3: resolution: {integrity: sha512-SYhBvTh89tTfCD/CRdSOm13mOBa42iTaTyfyEWBdKcGdPxPtLFBXuHR8XHb33YNYaP+lLbmSvBTsnoesCNJEsQ==} engines: {node: '>=14'} @@ -7616,6 +7768,9 @@ packages: mutexify@1.4.0: resolution: {integrity: sha512-pbYSsOrSB/AKN5h/WzzLRMFgZhClWccf2XIB4RSMC8JbquiB0e0/SH5AIfdQMdyHmYtv4seU7yV/TvAwPLJ1Yg==} + nan@2.26.2: + resolution: {integrity: sha512-0tTvBTYkt3tdGw22nrAy50x7gpbGCCFH3AFcyS5WiUu7Eu4vWlri1woE6qHBSfy11vksDqkiwjOnlR7WV8G1Hw==} + nanoid@3.3.11: resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} @@ -7797,6 +7952,9 @@ packages: package-manager-detector@1.5.0: resolution: {integrity: sha512-uBj69dVlYe/+wxj8JOpr97XfsxH/eumMt6HqjNTmJDf/6NO9s+0uxeOneIz3AsPt2m6y9PqzDzd3ATcU17MNfw==} + packageurl-js@2.0.1: + resolution: {integrity: sha512-N5ixXjzTy4QDQH0Q9YFjqIWd6zH6936Djpl2m9QNFmDv5Fum8q8BjkpAcHNMzOFE0IwQrFhJWex3AN6kS0OSwg==} + pako@1.0.11: resolution: {integrity: sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==} @@ -8570,6 +8728,10 @@ packages: safer-buffer@2.1.2: resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} + sax@1.6.0: + resolution: {integrity: sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA==} + engines: {node: '>=11.0.0'} + saxes@6.0.0: resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==} engines: {node: '>=v12.22.7'} @@ -8607,6 +8769,10 @@ packages: resolution: {integrity: sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==} engines: {node: '>= 0.4'} + set-value@4.1.0: + resolution: {integrity: sha512-zTEg4HL0RwVrqcWs3ztF+x1vkxfm0lP+MQQFPiMJTKVceBwEV0A569Ou8l9IYQG8jOZdMVI1hGsc0tmeD2o/Lw==} + engines: {node: '>=11.0'} + setimmediate@1.0.5: resolution: {integrity: sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==} @@ -8745,6 +8911,15 @@ packages: resolution: {integrity: sha512-UXhXR2869FQaD+GMly8jAMCRZ94nU5KcrFetZfWEMd+LVVG6y0ExgHAhatEcKZ/wk8YcKPdi+hiD2wm75lq3/Q==} engines: {node: '>=4.0.0'} + ssh2@1.17.0: + resolution: {integrity: sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ==} + engines: {node: '>=10.16.0'} + + sshpk@1.16.1: + resolution: {integrity: sha512-HXXqVUq7+pcKeLqqZj6mHFUMvXtOJt1uoUx09pFW6011inTMxqI8BA8PM95myrIyyKwdnzjdFjLiE6KBPVtJIg==} + engines: {node: '>=0.10.0'} + hasBin: true + stack-utils@2.0.6: resolution: {integrity: sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==} engines: {node: '>=10'} @@ -9117,6 +9292,9 @@ packages: tw-animate-css@1.4.0: resolution: {integrity: sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ==} + tweetnacl@0.14.5: + resolution: {integrity: sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==} + typanion@3.14.0: resolution: {integrity: sha512-ZW/lVMRabETuYCd9O9ZvMhAh8GslSqaUjxmK/JLPCh6l73CvLBiuXswj/+7LdnWOgYsQ130FqLzFz5aGT4I3Ug==} @@ -9660,6 +9838,18 @@ packages: resolution: {integrity: sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==} engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} + ws@7.5.10: + resolution: {integrity: sha512-+dbF1tHwZpXcbOJdVOkzLDxZP1ailvSxM6ZweXTegylPny803bFhA+vqBYw4s31NSAk4S2Qz+AKXK9a4wkdjcQ==} + engines: {node: '>=8.3.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: ^5.0.2 + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + ws@8.18.0: resolution: {integrity: sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==} engines: {node: '>=10.0.0'} @@ -9688,6 +9878,14 @@ packages: resolution: {integrity: sha512-ICP2e+jsHvAj2E2lIHxa5tjXRlKDJo4IdvPvCXbXQGdzSfmSpNVyIKMvoZHjDY9DP0zV17iI85o90vRFXNccRw==} engines: {node: '>=12'} + xml2js@0.5.0: + resolution: {integrity: sha512-drPFnkQJik/O+uPKpqSgr22mpuFHqKdbS835iAQrUC73L2F5WkboIRd63ai/2Yg6I1jzifPFKH2NTK+cfglkIA==} + engines: {node: '>=4.0.0'} + + xmlbuilder@11.0.1: + resolution: {integrity: sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==} + engines: {node: '>=4.0'} + xmlchars@2.2.0: resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==} @@ -9718,6 +9916,9 @@ packages: yallist@3.1.1: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} + yamux-js@0.1.2: + resolution: {integrity: sha512-bhsPlPZ9xB4Dawyf6nkS58u4F3IvGCaybkEKGnneUeepcI7MPoG3Tt6SaKCU5x/kP2/2w20Qm/GqbpwAM16vYw==} + yargs-parser@21.1.1: resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==} engines: {node: '>=12'} @@ -11326,7 +11527,7 @@ snapshots: '@datadog/browser-core': 6.22.0 '@datadog/browser-rum-core': 6.22.0 - '@datadog/datadog-ci-base@4.1.2(@datadog/datadog-ci-plugin-cloud-run@4.1.2)(@types/node@20.19.23)': + '@datadog/datadog-ci-base@4.1.2(@datadog/datadog-ci-plugin-cloud-run@4.1.2)(@datadog/datadog-ci-plugin-deployment@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-dora@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-gate@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-sarif@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-sbom@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-synthetics@4.4.0(@datadog/datadog-ci-base@4.4.0))(@types/node@20.19.23)': dependencies: '@antfu/install-pkg': 1.1.0 '@types/datadog-metrics': 0.6.1 @@ -11351,13 +11552,54 @@ snapshots: upath: 2.0.1 optionalDependencies: '@datadog/datadog-ci-plugin-cloud-run': 4.1.2(@datadog/datadog-ci-base@4.1.2)(@types/node@20.19.23) + '@datadog/datadog-ci-plugin-deployment': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-dora': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-gate': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-sarif': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-sbom': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-synthetics': 4.4.0(@datadog/datadog-ci-base@4.4.0) + transitivePeerDependencies: + - '@types/node' + - supports-color + + '@datadog/datadog-ci-base@4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12)': + dependencies: + '@antfu/install-pkg': 1.1.0 + '@types/datadog-metrics': 0.6.1 + async-retry: 1.3.1 + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + clipanion: 3.2.1(typanion@3.14.0) + datadog-metrics: 0.9.3 + debug: 4.4.3 + deep-extend: 0.6.0 + fast-xml-parser: 4.5.3 + form-data: 4.0.4 + glob: 10.5.0 + inquirer: 8.2.7(@types/node@22.18.12) + jest-diff: 30.2.0 + jszip: 3.10.1 + proxy-agent: 6.5.0 + semver: 7.7.3 + simple-git: 3.16.0 + terminal-link: 2.1.1 + tiny-async-pool: 2.1.0 + typanion: 3.14.0 + upath: 2.0.1 + optionalDependencies: + '@datadog/datadog-ci-plugin-deployment': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-dora': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-gate': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-sarif': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-sbom': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-synthetics': 4.4.0(@datadog/datadog-ci-base@4.4.0) transitivePeerDependencies: - '@types/node' - supports-color '@datadog/datadog-ci-plugin-cloud-run@4.1.2(@datadog/datadog-ci-base@4.1.2)(@types/node@20.19.23)': dependencies: - '@datadog/datadog-ci-base': 4.1.2(@datadog/datadog-ci-plugin-cloud-run@4.1.2)(@types/node@20.19.23) + '@datadog/datadog-ci-base': 4.1.2(@datadog/datadog-ci-plugin-cloud-run@4.1.2)(@datadog/datadog-ci-plugin-deployment@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-dora@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-gate@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-sarif@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-sbom@4.4.0(@datadog/datadog-ci-base@4.4.0))(@datadog/datadog-ci-plugin-synthetics@4.4.0(@datadog/datadog-ci-base@4.4.0))(@types/node@20.19.23) '@google-cloud/logging': 11.2.1 '@google-cloud/run': 3.0.1 chalk: 3.0.0 @@ -11372,6 +11614,119 @@ snapshots: - encoding - supports-color + '@datadog/datadog-ci-plugin-deployment@4.4.0(@datadog/datadog-ci-base@4.4.0)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + simple-git: 3.16.0 + transitivePeerDependencies: + - debug + - supports-color + + '@datadog/datadog-ci-plugin-dora@4.4.0(@datadog/datadog-ci-base@4.4.0)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + simple-git: 3.16.0 + transitivePeerDependencies: + - debug + - supports-color + + '@datadog/datadog-ci-plugin-gate@4.4.0(@datadog/datadog-ci-base@4.4.0)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + '@types/uuid': 9.0.8 + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + uuid: 9.0.1 + transitivePeerDependencies: + - debug + + '@datadog/datadog-ci-plugin-sarif@4.4.0(@datadog/datadog-ci-base@4.4.0)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + ajv: 8.18.0 + ajv-formats: 2.1.1(ajv@8.18.0) + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + form-data: 4.0.4 + simple-git: 3.16.0 + upath: 2.0.1 + uuid: 9.0.1 + transitivePeerDependencies: + - debug + - supports-color + + '@datadog/datadog-ci-plugin-sbom@4.4.0(@datadog/datadog-ci-base@4.4.0)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + ajv: 8.18.0 + ajv-formats: 2.1.1(ajv@8.18.0) + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + packageurl-js: 2.0.1 + simple-git: 3.16.0 + upath: 2.0.1 + transitivePeerDependencies: + - debug + - supports-color + + '@datadog/datadog-ci-plugin-synthetics@4.4.0(@datadog/datadog-ci-base@4.4.0)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + debug: 4.4.3 + deep-extend: 0.6.0 + fast-levenshtein: 3.0.0 + get-value: 4.0.1 + ora: 5.4.1 + set-value: 4.1.0 + ssh2: 1.17.0 + sshpk: 1.16.1 + upath: 2.0.1 + ws: 7.5.10 + xml2js: 0.5.0 + yamux-js: 0.1.2 + transitivePeerDependencies: + - bufferutil + - supports-color + - utf-8-validate + + '@datadog/datadog-ci@4.4.0(@types/node@22.18.12)': + dependencies: + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + '@datadog/datadog-ci-plugin-deployment': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-dora': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-gate': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-sarif': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-sbom': 4.4.0(@datadog/datadog-ci-base@4.4.0) + '@datadog/datadog-ci-plugin-synthetics': 4.4.0(@datadog/datadog-ci-base@4.4.0) + axios: 1.12.2(debug@4.4.3) + chalk: 3.0.0 + clipanion: 3.2.1(typanion@3.14.0) + fast-xml-parser: 4.5.3 + form-data: 4.0.4 + js-yaml: 4.1.1 + semver: 7.7.3 + simple-git: 3.16.0 + typanion: 3.14.0 + upath: 2.0.1 + uuid: 9.0.1 + transitivePeerDependencies: + - '@datadog/datadog-ci-plugin-aas' + - '@datadog/datadog-ci-plugin-cloud-run' + - '@datadog/datadog-ci-plugin-container-app' + - '@datadog/datadog-ci-plugin-lambda' + - '@datadog/datadog-ci-plugin-stepfunctions' + - '@types/node' + - bufferutil + - debug + - supports-color + - utf-8-validate + '@datadog/flagging-core@0.1.0-preview.13(@openfeature/core@1.9.1)': dependencies: '@openfeature/core': 1.9.1 @@ -11955,6 +12310,13 @@ snapshots: optionalDependencies: '@types/node': 20.19.23 + '@inquirer/external-editor@1.0.2(@types/node@22.18.12)': + dependencies: + chardet: 2.1.1 + iconv-lite: 0.7.0 + optionalDependencies: + '@types/node': 22.18.12 + '@internationalized/date@3.10.0': dependencies: '@swc/helpers': 0.5.17 @@ -14928,6 +15290,8 @@ snapshots: '@types/use-sync-external-store@0.0.6': {} + '@types/uuid@9.0.8': {} + '@types/whatwg-mimetype@3.0.2': {} '@types/ws@8.18.1': @@ -15301,6 +15665,10 @@ snapshots: agent-base@7.1.4: {} + ajv-formats@2.1.1(ajv@8.18.0): + optionalDependencies: + ajv: 8.18.0 + ajv@6.12.6: dependencies: fast-deep-equal: 3.1.3 @@ -15417,6 +15785,12 @@ snapshots: arrify@2.0.1: {} + asn1@0.2.6: + dependencies: + safer-buffer: 2.1.2 + + assert-plus@1.0.0: {} + assertion-error@2.0.1: {} ast-types@0.13.4: @@ -15549,6 +15923,10 @@ snapshots: basic-ftp@5.0.5: {} + bcrypt-pbkdf@1.0.2: + dependencies: + tweetnacl: 0.14.5 + bignumber.js@9.3.1: {} bl@4.1.0: @@ -15603,6 +15981,9 @@ snapshots: base64-js: 1.5.1 ieee754: 1.2.1 + buildcheck@0.0.7: + optional: true + busboy@1.6.0: dependencies: streamsearch: 1.1.0 @@ -15773,6 +16154,12 @@ snapshots: object-assign: 4.1.1 vary: 1.1.2 + cpu-features@0.0.10: + dependencies: + buildcheck: 0.0.7 + nan: 2.26.2 + optional: true + create-jest@29.7.0(@types/node@22.18.12)(ts-node@10.9.2(@types/node@22.18.12)(typescript@5.9.3)): dependencies: '@jest/types': 29.6.3 @@ -15819,6 +16206,10 @@ snapshots: csstype@3.1.3: {} + dashdash@1.14.1: + dependencies: + assert-plus: 1.0.0 + data-uri-to-buffer@4.0.1: {} data-uri-to-buffer@6.0.2: {} @@ -16027,6 +16418,11 @@ snapshots: eastasianwidth@0.2.0: {} + ecc-jsbn@0.1.2: + dependencies: + jsbn: 0.1.1 + safer-buffer: 2.1.2 + ecdsa-sig-formatter@1.0.11: dependencies: safe-buffer: 5.2.1 @@ -16398,6 +16794,10 @@ snapshots: fast-levenshtein@2.0.6: {} + fast-levenshtein@3.0.0: + dependencies: + fastest-levenshtein: 1.0.16 + fast-png@6.4.0: dependencies: '@types/pako': 2.0.4 @@ -16414,6 +16814,8 @@ snapshots: dependencies: strnum: 2.1.1 + fastest-levenshtein@1.0.16: {} + fastq@1.19.1: dependencies: reusify: 1.1.0 @@ -16605,6 +17007,12 @@ snapshots: transitivePeerDependencies: - supports-color + get-value@4.0.1: {} + + getpass@0.1.7: + dependencies: + assert-plus: 1.0.0 + glob-parent@5.1.2: dependencies: is-glob: 4.0.3 @@ -16624,6 +17032,15 @@ snapshots: package-json-from-dist: 1.0.1 path-scurry: 1.11.1 + glob@10.5.0: + dependencies: + foreground-child: 3.3.1 + jackspeak: 3.4.3 + minimatch: 9.0.5 + minipass: 7.1.2 + package-json-from-dist: 1.0.1 + path-scurry: 1.11.1 + glob@11.0.3: dependencies: foreground-child: 3.3.1 @@ -17060,6 +17477,26 @@ snapshots: transitivePeerDependencies: - '@types/node' + inquirer@8.2.7(@types/node@22.18.12): + dependencies: + '@inquirer/external-editor': 1.0.2(@types/node@22.18.12) + ansi-escapes: 4.3.2 + chalk: 4.1.2 + cli-cursor: 3.1.0 + cli-width: 3.0.0 + figures: 3.2.0 + lodash: 4.17.21 + mute-stream: 0.0.8 + ora: 5.4.1 + run-async: 2.4.1 + rxjs: 7.8.2 + string-width: 4.2.3 + strip-ansi: 6.0.1 + through: 2.3.8 + wrap-ansi: 6.2.0 + transitivePeerDependencies: + - '@types/node' + internal-slot@1.1.0: dependencies: es-errors: 1.3.0 @@ -17168,8 +17605,14 @@ snapshots: is-plain-obj@4.1.0: {} + is-plain-object@2.0.4: + dependencies: + isobject: 3.0.1 + is-potential-custom-element-name@1.0.1: {} + is-primitive@3.0.1: {} + is-regex@1.2.1: dependencies: call-bound: 1.0.4 @@ -17225,6 +17668,8 @@ snapshots: isexe@2.0.0: {} + isobject@3.0.1: {} + isomorphic.js@0.2.5: {} istanbul-lib-coverage@3.2.2: {} @@ -17641,6 +18086,12 @@ snapshots: dependencies: argparse: 2.0.1 + js-yaml@4.1.1: + dependencies: + argparse: 2.0.1 + + jsbn@0.1.1: {} + jsdom@20.0.3: dependencies: abab: 2.0.6 @@ -18314,6 +18765,9 @@ snapshots: dependencies: queue-tick: 1.0.1 + nan@2.26.2: + optional: true + nanoid@3.3.11: {} natural-compare@1.4.0: {} @@ -18497,6 +18951,8 @@ snapshots: package-manager-detector@1.5.0: {} + packageurl-js@2.0.1: {} + pako@1.0.11: {} pako@2.1.0: {} @@ -19386,6 +19842,8 @@ snapshots: safer-buffer@2.1.2: {} + sax@1.6.0: {} + saxes@6.0.0: dependencies: xmlchars: 2.2.0 @@ -19426,6 +19884,11 @@ snapshots: es-errors: 1.3.0 es-object-atoms: 1.1.1 + set-value@4.1.0: + dependencies: + is-plain-object: 2.0.4 + is-primitive: 3.0.1 + setimmediate@1.0.5: {} sharp@0.33.5: @@ -19616,6 +20079,26 @@ snapshots: sql-template-strings@2.2.2: {} + ssh2@1.17.0: + dependencies: + asn1: 0.2.6 + bcrypt-pbkdf: 1.0.2 + optionalDependencies: + cpu-features: 0.0.10 + nan: 2.26.2 + + sshpk@1.16.1: + dependencies: + asn1: 0.2.6 + assert-plus: 1.0.0 + bcrypt-pbkdf: 1.0.2 + dashdash: 1.14.1 + ecc-jsbn: 0.1.2 + getpass: 0.1.7 + jsbn: 0.1.1 + safer-buffer: 2.1.2 + tweetnacl: 0.14.5 + stack-utils@2.0.6: dependencies: escape-string-regexp: 2.0.0 @@ -20001,6 +20484,8 @@ snapshots: tw-animate-css@1.4.0: {} + tweetnacl@0.14.5: {} + typanion@3.14.0: {} type-check@0.4.0: @@ -20677,12 +21162,21 @@ snapshots: imurmurhash: 0.1.4 signal-exit: 3.0.7 + ws@7.5.10: {} + ws@8.18.0: {} ws@8.18.3: {} xml-name-validator@4.0.0: {} + xml2js@0.5.0: + dependencies: + sax: 1.6.0 + xmlbuilder: 11.0.1 + + xmlbuilder@11.0.1: {} + xmlchars@2.2.0: {} xtend@4.0.2: {} @@ -20705,6 +21199,8 @@ snapshots: yallist@3.1.1: {} + yamux-js@0.1.2: {} + yargs-parser@21.1.1: {} yargs@17.7.2: From 38a471e98a9b15659ceeb8a2e191589d56cf659e Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Thu, 23 Apr 2026 19:29:12 +0200 Subject: [PATCH 59/75] Set site --- .github/workflows/frontend-sourcemaps.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/frontend-sourcemaps.yml b/.github/workflows/frontend-sourcemaps.yml index 38247ee..70ab116 100644 --- a/.github/workflows/frontend-sourcemaps.yml +++ b/.github/workflows/frontend-sourcemaps.yml @@ -15,7 +15,7 @@ jobs: - x64 env: DATADOG_API_KEY: ${{ secrets.DATADOG_API_KEY }} - DATADOG_SITE: ${{ secrets.DATADOG_SITE }} + DATADOG_SITE: datadoghq.com RELEASE_VERSION: ${{ github.sha }} steps: - name: Check out repository From e4576b6363aeca9312f76f932f5c940649ae4de4 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Thu, 23 Apr 2026 19:32:58 +0200 Subject: [PATCH 60/75] Fix lint --- apps/clients/src/viteConfig.test.ts | 7 ++++++- apps/external/src/viteConfig.test.ts | 7 ++++++- apps/main/src/viteConfig.test.ts | 7 ++++++- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/apps/clients/src/viteConfig.test.ts b/apps/clients/src/viteConfig.test.ts index 5583270..dad6799 100644 --- a/apps/clients/src/viteConfig.test.ts +++ b/apps/clients/src/viteConfig.test.ts @@ -6,7 +6,12 @@ import configFactory from "../vite.config"; describe("clients vite config", () => { it("uses hidden sourcemaps for production builds", () => { - const config = configFactory({ mode: "production", command: "build", isSsrBuild: false, isPreview: false }); + const config = configFactory({ + mode: "production", + command: "build", + isSsrBuild: false, + isPreview: false, + }); expect(config.build?.sourcemap).toBe("hidden"); }); diff --git a/apps/external/src/viteConfig.test.ts b/apps/external/src/viteConfig.test.ts index b3831b7..1c95586 100644 --- a/apps/external/src/viteConfig.test.ts +++ b/apps/external/src/viteConfig.test.ts @@ -6,7 +6,12 @@ import configFactory from "../vite.config"; describe("external vite config", () => { it("uses hidden sourcemaps for production builds", () => { - const config = configFactory({ mode: "production", command: "build", isSsrBuild: false, isPreview: false }); + const config = configFactory({ + mode: "production", + command: "build", + isSsrBuild: false, + isPreview: false, + }); expect(config.build?.sourcemap).toBe("hidden"); }); diff --git a/apps/main/src/viteConfig.test.ts b/apps/main/src/viteConfig.test.ts index 3a15668..7242369 100644 --- a/apps/main/src/viteConfig.test.ts +++ b/apps/main/src/viteConfig.test.ts @@ -6,7 +6,12 @@ import configFactory from "../vite.config"; describe("main vite config", () => { it("uses hidden sourcemaps for production builds", () => { - const config = configFactory({ mode: "production", command: "build", isSsrBuild: false, isPreview: false }); + const config = configFactory({ + mode: "production", + command: "build", + isSsrBuild: false, + isPreview: false, + }); expect(config.build?.sourcemap).toBe("hidden"); }); From d796960cc0b69d169ed2206c63d4a226dd620213 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Fri, 24 Apr 2026 14:16:42 +0200 Subject: [PATCH 61/75] docs: add supabase admin dashboard design spec --- ...6-04-24-supabase-admin-dashboard-design.md | 428 ++++++++++++++++++ 1 file changed, 428 insertions(+) create mode 100644 docs/superpowers/specs/2026-04-24-supabase-admin-dashboard-design.md diff --git a/docs/superpowers/specs/2026-04-24-supabase-admin-dashboard-design.md b/docs/superpowers/specs/2026-04-24-supabase-admin-dashboard-design.md new file mode 100644 index 0000000..5ff700d --- /dev/null +++ b/docs/superpowers/specs/2026-04-24-supabase-admin-dashboard-design.md @@ -0,0 +1,428 @@ +# Supabase Admin Dashboard — Design Spec + +## Overview + +Add a new internal-only app alongside `apps/main`, implemented as `apps/admin`, to operate the production Supabase database through a polished operations dashboard. The app is not customer-facing. Its primary purpose is operational data inspection and repair, with analytics and charting as supporting capabilities for investigation and monitoring. + +The product shape is: + +- an internal operations console for browsing and editing approved production data +- a guarded action center for high-impact business workflows +- a semi-flexible analytics studio for charting curated datasets and saving dashboards + +This should feel closer to a premium internal instrument than a generic admin template. + +## Goals + +- Give internal operators a fast way to inspect, filter, and modify approved production rows +- Support business-safe admin actions that should not be performed as ad hoc table edits +- Provide chart-based analytics over curated datasets for investigation and monitoring +- Keep the app visually strong, dense, and pleasant to operate for power users +- Make production access intentionally hard to misuse through layered security and auditability + +## Non-Goals + +- Building a full Tableau, Metabase, or Power BI replacement in v1 +- Exposing this app to regular product users or customer organization admins +- Allowing arbitrary SQL execution from the browser in v1 +- Making every database table directly editable +- Reusing `apps/main` navigation and UX constraints for internal operations work + +## Recommended App Shape + +Create a dedicated app at `apps/admin` rather than extending `apps/main`. + +Reasons: + +- Internal operations workflows have different navigation, information density, and safety needs than the main product +- The app should remain isolated from customer-facing code paths and feature assumptions +- A separate app can share the existing monorepo stack without inheriting the product shell + +## Technical Foundation + +The app should reuse the current workspace patterns: + +- React 19 +- Vite +- React Router +- TanStack React Query +- Tailwind +- `@xtablo/ui` +- shared Supabase and type packages where appropriate + +Specialized libraries are acceptable where they materially improve operator workflows: + +- `ag-grid-react` or the existing AG Grid dependency for dense table exploration +- a charting library suited for composable dashboards and interactive filters +- lightweight schema/form helpers for registry-driven edit UIs + +This keeps the app consistent with the repo while allowing purpose-built admin and analytics ergonomics. + +Unlike `apps/main`, this app should not rely on normal browser-side Supabase access as its primary trust boundary. Privileged access should be enforced through backend-verified admin sessions and server-mediated data operations. + +## Internal-Only Access Model + +This app must be firewalled and internal only. + +Access should be enforced in layers: + +### Layer 1: Network / edge boundary + +The app should be hosted behind an internal boundary rather than a public route. The preferred model is a private hostname or protected subdomain with an edge access control layer such as: + +- Cloudflare Access +- VPN-only reachability +- IP allowlist for office/VPN egress + +At least one network-level gate should exist before the app is reachable. + +### Layer 2: Special admin access token + +Reaching the app is not sufficient. Operators must also present a dedicated admin access token that is separate from normal product authentication. + +Properties of this token: + +- not the regular Supabase session token used by `apps/main` +- issued only to approved internal operators +- short-lived +- bound to operator identity and role claims +- verified server-side before the app shell can load protected data + +Recommended model: + +1. Operator reaches the private app endpoint +2. Operator enters or redeems a privileged access token +3. Backend verifies the token and exchanges it for a short-lived admin session +4. The app stores only the short-lived admin session artifacts needed for operation + +The token exchange endpoint should be the only way to unlock privileged access. Public frontend credentials alone must never be enough to talk to admin-capable data paths. + +Normal product users must not be able to access this app by logging in with standard app credentials alone. + +### Layer 3: In-app roles + +After the privileged token gate, the app should still tier capabilities: + +- `viewer`: inspect data and dashboards +- `operator`: edit approved rows and use standard tools +- `superadmin`: use destructive or high-impact actions + +### Layer 4: Action-specific friction + +High-risk workflows should require stronger confirmation than read or low-risk edit paths: + +- confirmation modals with exact record identity +- diff previews before sensitive changes +- explicit typing for destructive actions where appropriate +- bulk-action result summaries +- audit logging for every consequential mutation + +## Product Modules + +The app should have four top-level modules. + +### 1. Operations Home + +The landing screen is a command deck for operators, not a blank dashboard shell. + +It should surface: + +- key health cards +- recent operational anomalies +- recent signups and organizations +- billing or subscription exceptions +- pinned saved views +- quick links into frequent tables and admin actions + +This page should optimize for “what needs attention now?” rather than for abstract BI storytelling. + +### 2. Data Explorer + +This is the primary workspace for day-to-day operations. It should behave like a polished spreadsheet-database hybrid. + +Capabilities: + +- table group navigation +- dense data grid with filtering, sorting, resizing, pinning, and saved views +- column selection and per-table presets +- row selection and bulk action support +- row detail drawer with linked records, history, and edit tools +- schema-aware editing for enums, booleans, dates, JSON, nullable fields, and foreign keys + +Not every table should appear. Only approved tables defined in a registry should be exposed. + +### 3. Analytics Studio + +This is a semi-flexible analytics layer, not an open query workbench. + +Capabilities: + +- choose a curated dataset or view +- apply filters and date ranges +- pick dimensions, metrics, and grouping +- render charts and summary tables +- save charts into reusable dashboards + +Supported visual shapes in v1 should be the practical set: + +- KPI cards +- bar charts +- line charts +- stacked comparisons +- pie or donut only where the dataset justifies it +- tabular breakdowns + +The focus is fast investigative charting over approved datasets, not raw BI authoring. + +### 4. Action Center + +This module isolates high-impact business operations from routine browsing. + +Examples: + +- repair a broken organization membership +- merge duplicate records +- trigger a re-sync or backfill +- re-run a workflow cleanup +- repair broken references after a partial failure + +Each action should have: + +- a typed input form +- explicit eligibility checks +- confirmation copy describing impact +- structured result output +- audit-log emission + +## Data Access Architecture + +Use three backend access layers with different trust levels. + +All privileged data access should be mediated by backend-verified admin sessions. The app should not expose broad direct production table access purely through a public browser Supabase client. + +### Read layer + +Prefer curated Postgres views or RPC-backed read models for dashboards and analytics. This yields: + +- stable schemas for charts +- human-readable labels +- better performance characteristics +- fewer accidental joins in the frontend + +Direct table reads should still be modeled as approved explorer resources, but they should preferably flow through admin APIs or narrowly scoped RPC wrappers that enforce the privileged token and table registry. Analytics should primarily be dataset-driven. + +### Edit layer + +Use structured mutations for simple edits on approved tables and safe fields. These edits should be governed by a table registry that declares: + +- table visibility +- editable columns +- field widgets +- validation rules +- read-only or computed fields +- related-record links + +Sensitive tables or writes with cross-table invariants should not mutate directly from the browser. They should route through API endpoints or database functions with explicit validation, and even low-risk edits should pass through an admin-aware boundary instead of depending on the main product's client auth model. + +### Action layer + +High-impact admin workflows should live behind narrow APIs or RPCs with: + +- validation +- authorization +- idempotency where needed +- audit logging +- structured success and failure payloads + +This layer is how the app avoids solving every problem as a raw row edit. + +## Registry-Driven Configuration + +The app should be intentionally configured rather than schema-introspective by default. + +Introduce three registries: + +### Table registry + +Defines: + +- which tables are exposed +- labels and groupings +- visible columns +- editable columns +- per-column rendering rules +- row detail sections +- allowed bulk actions + +### Dataset registry + +Defines: + +- which analytics datasets exist +- metrics and dimensions available +- supported filters +- supported chart types +- default aggregations +- dashboard-friendly naming + +### Action registry + +Defines: + +- which admin actions exist +- required permissions +- input schemas +- confirmation copy +- expected result payloads + +This registry approach is what makes the app feel curated and safe rather than like a generic database browser. + +## Production Safety Model + +This app operates on production from day one, so the interface should continuously communicate context without becoming noisy. + +Recommended safety affordances: + +- persistent production environment indicator +- visible operator identity in the shell +- visible “last modified by” and “last modified at” metadata in row details where possible +- change history in row drawers for tracked entities +- limited inline edits to low-risk fields +- full-form edits with diff preview for sensitive records +- destructive actions kept out of casual explorer flows + +Bulk operations should never resolve to a single toast. Operators need a result screen that distinguishes: + +- succeeded rows +- failed rows +- skipped rows +- next actions + +## Visual Design Direction + +The visual system should avoid generic white-label admin aesthetics. + +Recommended direction: + +- deep ink or navy structure colors +- warm neutrals for surfaces +- one disciplined accent family for actions and focus states +- crisp, expressive typography with clear density hierarchy +- subtle layered backgrounds and panel contrast rather than flat gray cards +- charts with strong contrast and restrained but deliberate color semantics + +The overall tone should be “serious internal operations instrument”: + +- information-dense +- elegant +- calm under pressure +- visually credible for long sessions + +## Error Handling + +Errors should be explicit and categorized so operators know whether to retry, escalate, or correct input. + +Primary categories: + +- validation errors +- concurrency conflicts +- permission failures +- system or connectivity failures + +Patterns: + +- field-level validation on forms +- diff conflict messaging when a row changed concurrently +- structured action results instead of generic error banners +- partial failure summaries for bulk operations + +## Testing Strategy + +Testing should mirror the architecture. + +### Unit tests + +- table, dataset, and action registries +- column renderers and formatter helpers +- chart config builders +- edit reducers and validation logic + +### Component tests + +- explorer grid behaviors +- row detail drawers +- edit forms +- action forms +- dashboard widgets + +### Integration tests + +- internal token gate +- role restrictions +- safe edit flows +- audit-log emission +- failure handling for partial bulk actions + +### API or RPC tests + +- every high-impact admin action +- guarded write paths +- authorization boundaries for privileged tokens + +## Delivery Phases + +### Phase 1: App shell and access control + +- create `apps/admin` +- implement internal-only deployment boundary +- add privileged token gate +- establish app shell, navigation, and visual system + +### Phase 2: Data Explorer foundation + +- implement table registry +- ship explorer for a small set of core tables +- add row detail drawers and safe field editing + +### Phase 3: Audit and guarded writes + +- add audit logging +- add diff previews and sensitive edit flows +- add bulk action result handling + +### Phase 4: Operations Home + +- add curated operational cards +- add pinned saved views and shortcuts + +### Phase 5: Analytics Studio + +- implement dataset registry +- add chart builder for curated datasets +- add saved dashboards + +### Phase 6: Action Center + +- implement first high-value admin workflows +- add structured action results and stronger confirmation patterns + +## Initial Implementation Recommendation + +For v1, start with a deliberately small surface: + +- 3 to 5 core tables in the explorer +- 2 to 3 dashboards +- 2 to 4 high-value admin actions + +This keeps the first release useful without pretending the system is fully modeled from day one. + +## Open Design Decisions For Planning + +These should be resolved during implementation planning: + +- exact privileged token issuance flow and storage model +- whether the edge boundary is Cloudflare Access, VPN-only reachability, or a hybrid +- initial list of exposed tables +- first analytics datasets to support +- first custom admin actions to build +- audit log storage location and retention model From 41720147d71820f8dabe8319e3c47db49b05fd5a Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Fri, 24 Apr 2026 14:22:22 +0200 Subject: [PATCH 62/75] docs: add admin dashboard implementation plan --- .../2026-04-24-supabase-admin-dashboard.md | 1009 +++++++++++++++++ 1 file changed, 1009 insertions(+) create mode 100644 docs/superpowers/plans/2026-04-24-supabase-admin-dashboard.md diff --git a/docs/superpowers/plans/2026-04-24-supabase-admin-dashboard.md b/docs/superpowers/plans/2026-04-24-supabase-admin-dashboard.md new file mode 100644 index 0000000..aea8956 --- /dev/null +++ b/docs/superpowers/plans/2026-04-24-supabase-admin-dashboard.md @@ -0,0 +1,1009 @@ +# Supabase Admin Dashboard Implementation Plan + +> **For agentic workers:** REQUIRED: Use superpowers:subagent-driven-development (if subagents available) or superpowers:executing-plans to implement this plan. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Build an internal-only `apps/admin` operations console for production Supabase data with privileged token-gated access, safe row editing, curated analytics, and audited admin actions. + +**Architecture:** Add a standalone React app in `apps/admin`, but keep privileged trust on the server by introducing admin-only API routes, short-lived admin sessions, and registry-driven table, dataset, and action definitions. Deliver the product in slices: access foundation first, then explorer and auditability, then operations home, analytics, and custom actions. + +**Tech Stack:** React 19, Vite, React Router, TanStack Query, Tailwind, `@xtablo/ui`, Hono, Supabase, Zod, AG Grid, Recharts, Vitest, React Testing Library + +--- + +## File Map + +### New app + +- Create: `apps/admin/package.json` +- Create: `apps/admin/tsconfig.json` +- Create: `apps/admin/vite.config.ts` +- Create: `apps/admin/wrangler.toml` +- Create: `apps/admin/index.html` +- Create: `apps/admin/worker/index.ts` +- Create: `apps/admin/src/main.tsx` +- Create: `apps/admin/src/App.tsx` +- Create: `apps/admin/src/routes.tsx` +- Create: `apps/admin/src/main.css` +- Create: `apps/admin/src/lib/api.ts` +- Create: `apps/admin/src/lib/adminSession.ts` +- Create: `apps/admin/src/hooks/useAdminSession.ts` +- Create: `apps/admin/src/hooks/useAdminTables.ts` +- Create: `apps/admin/src/hooks/useAdminDatasets.ts` +- Create: `apps/admin/src/hooks/useAdminActions.ts` +- Create: `apps/admin/src/components/AdminLayout.tsx` +- Create: `apps/admin/src/components/AdminNavigation.tsx` +- Create: `apps/admin/src/components/ProductionBadge.tsx` +- Create: `apps/admin/src/components/PrivilegedGate.tsx` +- Create: `apps/admin/src/components/data-explorer/AdminGrid.tsx` +- Create: `apps/admin/src/components/data-explorer/RowDetailDrawer.tsx` +- Create: `apps/admin/src/components/data-explorer/RowEditForm.tsx` +- Create: `apps/admin/src/components/analytics/ChartBuilder.tsx` +- Create: `apps/admin/src/components/analytics/SavedDashboardList.tsx` +- Create: `apps/admin/src/components/actions/ActionRunner.tsx` +- Create: `apps/admin/src/pages/OperationsHomePage.tsx` +- Create: `apps/admin/src/pages/DataExplorerPage.tsx` +- Create: `apps/admin/src/pages/AnalyticsStudioPage.tsx` +- Create: `apps/admin/src/pages/ActionCenterPage.tsx` +- Create: `apps/admin/src/registry/tables.ts` +- Create: `apps/admin/src/registry/datasets.ts` +- Create: `apps/admin/src/registry/actions.ts` +- Test: `apps/admin/src/routes.test.tsx` +- Test: `apps/admin/src/components/PrivilegedGate.test.tsx` +- Test: `apps/admin/src/pages/DataExplorerPage.test.tsx` +- Test: `apps/admin/src/pages/AnalyticsStudioPage.test.tsx` +- Test: `apps/admin/src/pages/ActionCenterPage.test.tsx` + +### Shared types and docs + +- Create: `packages/shared-types/src/admin.types.ts` +- Modify: `packages/shared-types/src/index.ts` +- Create: `docs/ADMIN_APP_ACCESS_SETUP.md` + +### API and auth + +- Create: `apps/api/src/helpers/adminTokens.ts` +- Create: `apps/api/src/helpers/adminAudit.ts` +- Create: `apps/api/src/helpers/adminRegistry.ts` +- Create: `apps/api/src/routers/adminAuth.ts` +- Create: `apps/api/src/routers/adminTables.ts` +- Create: `apps/api/src/routers/adminDatasets.ts` +- Create: `apps/api/src/routers/adminActions.ts` +- Create: `apps/api/src/routers/admin.ts` +- Modify: `apps/api/src/config.ts` +- Modify: `apps/api/src/index.ts` +- Modify: `apps/api/src/routers/index.ts` +- Modify: `apps/api/src/middlewares/middleware.ts` +- Test: `apps/api/src/__tests__/routes/adminAuth.test.ts` +- Test: `apps/api/src/__tests__/routes/adminTables.test.ts` +- Test: `apps/api/src/__tests__/routes/adminDatasets.test.ts` +- Test: `apps/api/src/__tests__/routes/adminActions.test.ts` +- Test: `apps/api/src/__tests__/middlewares/adminAuth.test.ts` + +### Database + +- Create: `supabase/migrations/20260424110000_create_admin_audit_log.sql` +- Create: `supabase/migrations/20260424111000_create_admin_dataset_views.sql` + +### Workspace wiring + +- Modify: `package.json` +- Modify: `turbo.json` only if new task inputs or outputs are needed + +## Chunk 1: Access Foundation And App Scaffolding + +### Task 1: Scaffold `apps/admin` and workspace wiring + +**Files:** +- Create: `apps/admin/package.json` +- Create: `apps/admin/tsconfig.json` +- Create: `apps/admin/vite.config.ts` +- Create: `apps/admin/wrangler.toml` +- Create: `apps/admin/index.html` +- Create: `apps/admin/worker/index.ts` +- Create: `apps/admin/src/main.tsx` +- Create: `apps/admin/src/App.tsx` +- Create: `apps/admin/src/routes.tsx` +- Create: `apps/admin/src/main.css` +- Create: `apps/admin/src/routes.test.tsx` +- Modify: `package.json` + +- [ ] **Step 1: Write the failing route smoke test** + +```tsx +import { MemoryRouter } from "react-router-dom"; +import { render, screen } from "@testing-library/react"; +import AppRoutes from "./routes"; + +it("renders the privileged gate on the root route", () => { + render( + + + + ); + + expect(screen.getByText(/admin access token/i)).toBeInTheDocument(); +}); +``` + +- [ ] **Step 2: Run the new app test and verify it fails** + +Run: `pnpm --filter @xtablo/admin test -- src/routes.test.tsx` +Expected: FAIL because `@xtablo/admin` and `src/routes.tsx` do not exist yet + +- [ ] **Step 3: Copy the standalone app structure from `apps/clients`** + +Create a minimal app shell modeled on: + +- `apps/clients/package.json` +- `apps/clients/vite.config.ts` +- `apps/clients/wrangler.toml` +- `apps/clients/src/main.tsx` +- `apps/clients/src/App.tsx` + +Use: + +- package name `@xtablo/admin` +- dev port `5176` +- Cloudflare worker name `xtablo-admin` +- private hostname route placeholders in `wrangler.toml` + +- [ ] **Step 4: Add root workspace scripts** + +Add scripts to `package.json`: + +```json +{ + "dev:admin": "turbo dev --filter=@xtablo/admin", + "deploy:admin": "turbo deploy --filter=@xtablo/admin" +} +``` + +- [ ] **Step 5: Add a minimal gate screen so the test passes** + +Stub the root route to render: + +```tsx +export function PrivilegedGatePlaceholder() { + return
Admin access token required
; +} +``` + +- [ ] **Step 6: Re-run the route smoke test** + +Run: `pnpm --filter @xtablo/admin test -- src/routes.test.tsx` +Expected: PASS + +- [ ] **Step 7: Verify the app typechecks** + +Run: `pnpm --filter @xtablo/admin typecheck` +Expected: PASS + +- [ ] **Step 8: Commit the scaffold** + +```bash +git add package.json apps/admin +git commit -m "feat(admin): scaffold internal admin app" +``` + +### Task 2: Add privileged token exchange and admin session verification in the API + +**Files:** +- Create: `apps/api/src/helpers/adminTokens.ts` +- Create: `apps/api/src/routers/adminAuth.ts` +- Create: `apps/api/src/routers/admin.ts` +- Create: `apps/api/src/__tests__/routes/adminAuth.test.ts` +- Create: `apps/api/src/__tests__/middlewares/adminAuth.test.ts` +- Modify: `apps/api/src/config.ts` +- Modify: `apps/api/src/index.ts` +- Modify: `apps/api/src/routers/index.ts` +- Modify: `apps/api/src/middlewares/middleware.ts` +- Create: `packages/shared-types/src/admin.types.ts` +- Modify: `packages/shared-types/src/index.ts` + +- [ ] **Step 1: Write failing tests for token exchange and protected-session rejection** + +```ts +it("rejects requests without a valid privileged token", async () => { + const res = await app.request("/api/v1/admin/auth/exchange", { + method: "POST", + body: JSON.stringify({ accessToken: "bad-token" }), + headers: { "Content-Type": "application/json" }, + }); + + expect(res.status).toBe(401); +}); + +it("rejects admin routes without an admin session", async () => { + const res = await app.request("/api/v1/admin/tables/profiles"); + expect(res.status).toBe(401); +}); +``` + +- [ ] **Step 2: Run the targeted API tests and verify failure** + +Run: `pnpm --filter @xtablo/api test -- src/__tests__/routes/adminAuth.test.ts src/__tests__/middlewares/adminAuth.test.ts` +Expected: FAIL because the admin auth router and middleware do not exist + +- [ ] **Step 3: Extend config for privileged token validation** + +Add to `apps/api/src/config.ts`: + +```ts +ADMIN_TOKEN_SIGNING_SECRET: string; +ADMIN_TOKEN_AUDIENCE: string; +ADMIN_APP_URL: string; +``` + +Load them from env or secrets and fail fast if missing outside test mode. + +- [ ] **Step 4: Add admin token helper and session payload types** + +In `apps/api/src/helpers/adminTokens.ts`, implement helpers shaped like: + +```ts +export type AdminSessionClaims = { + sub: string; + role: "viewer" | "operator" | "superadmin"; + aud: string; + exp: number; +}; + +export async function exchangePrivilegedToken(input: string, config: AppConfig) { + // verify privileged token, then issue short-lived admin session +} + +export async function verifyAdminSession(token: string, config: AppConfig) { + // decode and validate admin session claims +} +``` + +- [ ] **Step 5: Add admin auth middleware** + +Extend `apps/api/src/middlewares/middleware.ts` with a dedicated admin middleware that: + +- reads `Authorization: Bearer ` +- verifies session claims +- attaches `adminSession` to the Hono context +- never falls back to normal product auth + +- [ ] **Step 6: Add `/api/v1/admin/auth/exchange` and `/api/v1/admin/auth/session`** + +`adminAuth.ts` should expose: + +- `POST /auth/exchange` +- `GET /auth/session` +- `POST /auth/logout` + +Use `zod` request validation and structured error responses. + +- [ ] **Step 7: Register the new admin router** + +Mount it under `/api/v1/admin` without reusing the normal authenticated router chain. + +- [ ] **Step 8: Add shared admin types** + +Export common types like: + +```ts +export type AdminRole = "viewer" | "operator" | "superadmin"; + +export type AdminSessionResponse = { + sessionToken: string; + expiresAt: string; + role: AdminRole; + operatorEmail: string; +}; +``` + +- [ ] **Step 9: Re-run API tests** + +Run: `pnpm --filter @xtablo/api test -- src/__tests__/routes/adminAuth.test.ts src/__tests__/middlewares/adminAuth.test.ts` +Expected: PASS + +- [ ] **Step 10: Commit the access backend** + +```bash +git add apps/api/src/config.ts apps/api/src/index.ts apps/api/src/routers/index.ts apps/api/src/middlewares/middleware.ts apps/api/src/helpers/adminTokens.ts apps/api/src/routers/adminAuth.ts apps/api/src/routers/admin.ts apps/api/src/__tests__/routes/adminAuth.test.ts apps/api/src/__tests__/middlewares/adminAuth.test.ts packages/shared-types/src/admin.types.ts packages/shared-types/src/index.ts +git commit -m "feat(admin): add privileged admin session exchange" +``` + +### Task 3: Build the privileged gate and admin session client in `apps/admin` + +**Files:** +- Create: `apps/admin/src/lib/api.ts` +- Create: `apps/admin/src/lib/adminSession.ts` +- Create: `apps/admin/src/hooks/useAdminSession.ts` +- Create: `apps/admin/src/components/PrivilegedGate.tsx` +- Create: `apps/admin/src/components/PrivilegedGate.test.tsx` +- Modify: `apps/admin/src/routes.tsx` +- Modify: `apps/admin/src/main.tsx` + +- [ ] **Step 1: Write the failing component test for exchanging a privileged token** + +```tsx +it("exchanges a privileged token and enters the admin shell", async () => { + render(); + + await userEvent.type(screen.getByLabelText(/access token/i), "valid-token"); + await userEvent.click(screen.getByRole("button", { name: /unlock admin/i })); + + expect(await screen.findByText(/operations home/i)).toBeInTheDocument(); +}); +``` + +- [ ] **Step 2: Run the test to confirm it fails** + +Run: `pnpm --filter @xtablo/admin test -- src/components/PrivilegedGate.test.tsx` +Expected: FAIL because no session client or gate exists + +- [ ] **Step 3: Create an admin-only API client** + +Implement `apps/admin/src/lib/api.ts` with: + +```ts +export const adminApi = buildApi(import.meta.env.VITE_API_URL); + +adminApi.interceptors.request.use((config) => { + const token = getAdminSessionToken(); + if (token) config.headers.Authorization = `Bearer ${token}`; + return config; +}); +``` + +- [ ] **Step 4: Create local admin session storage helpers** + +In `apps/admin/src/lib/adminSession.ts`, keep the stored shape minimal: + +```ts +type StoredAdminSession = { + token: string; + expiresAt: string; + role: AdminRole; + operatorEmail: string; +}; +``` + +- [ ] **Step 5: Add `useAdminSession`** + +The hook should: + +- exchange privileged tokens +- fetch current session metadata +- clear expired sessions +- expose `isAuthenticated`, `role`, `operatorEmail`, `unlock`, and `logout` + +- [ ] **Step 6: Build the gate screen** + +`PrivilegedGate.tsx` should: + +- explain that normal Xtablo login is not sufficient +- accept the special token +- handle loading and invalid-token states +- redirect authenticated operators into the shell + +- [ ] **Step 7: Wire root routing through the gate** + +Root route behavior: + +- no admin session: gate +- active admin session: `AdminLayout` + +- [ ] **Step 8: Re-run admin frontend tests and typecheck** + +Run: `pnpm --filter @xtablo/admin test -- src/components/PrivilegedGate.test.tsx src/routes.test.tsx` +Expected: PASS + +Run: `pnpm --filter @xtablo/admin typecheck` +Expected: PASS + +- [ ] **Step 9: Commit the gate flow** + +```bash +git add apps/admin/src/lib/api.ts apps/admin/src/lib/adminSession.ts apps/admin/src/hooks/useAdminSession.ts apps/admin/src/components/PrivilegedGate.tsx apps/admin/src/components/PrivilegedGate.test.tsx apps/admin/src/routes.tsx apps/admin/src/main.tsx +git commit -m "feat(admin): add privileged token gate" +``` + +## Chunk 2: Explorer, Guarded Mutations, And Auditability + +### Task 4: Build the admin shell and visual system + +**Files:** +- Create: `apps/admin/src/components/AdminLayout.tsx` +- Create: `apps/admin/src/components/AdminNavigation.tsx` +- Create: `apps/admin/src/components/ProductionBadge.tsx` +- Create: `apps/admin/src/pages/OperationsHomePage.tsx` +- Modify: `apps/admin/src/App.tsx` +- Modify: `apps/admin/src/routes.tsx` +- Modify: `apps/admin/src/main.css` +- Test: `apps/admin/src/components/AdminLayout.test.tsx` + +- [ ] **Step 1: Write a failing shell test for navigation and production context** + +```tsx +it("shows the production badge and admin sections", () => { + render(); + + expect(screen.getByText(/production/i)).toBeInTheDocument(); + expect(screen.getByRole("link", { name: /data explorer/i })).toBeInTheDocument(); + expect(screen.getByRole("link", { name: /analytics studio/i })).toBeInTheDocument(); +}); +``` + +- [ ] **Step 2: Run the shell test and verify failure** + +Run: `pnpm --filter @xtablo/admin test -- src/components/AdminLayout.test.tsx` +Expected: FAIL because the admin shell does not exist + +- [ ] **Step 3: Build the navigation and shell** + +The shell should include: + +- top-level nav for `Operations Home`, `Data Explorer`, `Analytics Studio`, `Action Center` +- persistent operator identity +- prominent but tasteful production badge +- strong visual hierarchy using the design spec colors and spacing + +- [ ] **Step 4: Replace the placeholder route target with the real shell** + +Route structure: + +```tsx +}> + } /> + } /> + } /> + } /> + +``` + +- [ ] **Step 5: Re-run the shell test** + +Run: `pnpm --filter @xtablo/admin test -- src/components/AdminLayout.test.tsx` +Expected: PASS + +- [ ] **Step 6: Commit the shell** + +```bash +git add apps/admin/src/components/AdminLayout.tsx apps/admin/src/components/AdminNavigation.tsx apps/admin/src/components/ProductionBadge.tsx apps/admin/src/pages/OperationsHomePage.tsx apps/admin/src/App.tsx apps/admin/src/routes.tsx apps/admin/src/main.css +git commit -m "feat(admin): add admin shell and visual system" +``` + +### Task 5: Add registry-driven table exploration and approved read endpoints + +**Files:** +- Create: `apps/admin/src/registry/tables.ts` +- Create: `apps/admin/src/hooks/useAdminTables.ts` +- Create: `apps/admin/src/pages/DataExplorerPage.tsx` +- Create: `apps/admin/src/components/data-explorer/AdminGrid.tsx` +- Create: `apps/admin/src/components/data-explorer/RowDetailDrawer.tsx` +- Create: `apps/admin/src/pages/DataExplorerPage.test.tsx` +- Create: `apps/api/src/helpers/adminRegistry.ts` +- Create: `apps/api/src/routers/adminTables.ts` +- Create: `apps/api/src/__tests__/routes/adminTables.test.ts` + +- [ ] **Step 1: Write failing API tests for approved-table reads** + +```ts +it("returns table metadata for an approved table", async () => { + const res = await authedAdminRequest("/api/v1/admin/tables/profiles/meta"); + expect(res.status).toBe(200); +}); + +it("rejects a table that is not in the registry", async () => { + const res = await authedAdminRequest("/api/v1/admin/tables/secrets/rows"); + expect(res.status).toBe(404); +}); +``` + +- [ ] **Step 2: Write a failing frontend test for switching tables** + +```tsx +it("loads rows for the selected table", async () => { + render(); + + await userEvent.click(screen.getByRole("button", { name: /profiles/i })); + + expect(await screen.findByText(/email/i)).toBeInTheDocument(); +}); +``` + +- [ ] **Step 3: Run API and frontend tests to verify failure** + +Run: `pnpm --filter @xtablo/api test -- src/__tests__/routes/adminTables.test.ts` +Expected: FAIL + +Run: `pnpm --filter @xtablo/admin test -- src/pages/DataExplorerPage.test.tsx` +Expected: FAIL + +- [ ] **Step 4: Define the table registry** + +Seed the registry with 3 to 5 core resources only: + +```ts +export const adminTables = { + profiles: { + label: "Users", + source: "profiles", + editableColumns: ["first_name", "last_name", "plan"], + }, + organizations: { + label: "Organizations", + source: "organizations", + editableColumns: ["name"], + }, + tablo_access: { + label: "Tablo Access", + source: "tablo_access", + editableColumns: ["is_active", "is_admin"], + }, +}; +``` + +- [ ] **Step 5: Add the admin tables API** + +Endpoints: + +- `GET /api/v1/admin/tables` +- `GET /api/v1/admin/tables/:tableId/meta` +- `GET /api/v1/admin/tables/:tableId/rows` +- `GET /api/v1/admin/tables/:tableId/rows/:rowId` + +Keep all queries registry-driven. Do not allow arbitrary table names. + +- [ ] **Step 6: Build the explorer UI** + +Implement: + +- left rail of table groups +- AG Grid-based row list +- row detail drawer with linked values and metadata +- saved filter state scoped per table + +- [ ] **Step 7: Re-run table API and explorer tests** + +Run: `pnpm --filter @xtablo/api test -- src/__tests__/routes/adminTables.test.ts` +Expected: PASS + +Run: `pnpm --filter @xtablo/admin test -- src/pages/DataExplorerPage.test.tsx` +Expected: PASS + +- [ ] **Step 8: Commit approved reads** + +```bash +git add apps/admin/src/registry/tables.ts apps/admin/src/hooks/useAdminTables.ts apps/admin/src/pages/DataExplorerPage.tsx apps/admin/src/components/data-explorer/AdminGrid.tsx apps/admin/src/components/data-explorer/RowDetailDrawer.tsx apps/admin/src/pages/DataExplorerPage.test.tsx apps/api/src/helpers/adminRegistry.ts apps/api/src/routers/adminTables.ts apps/api/src/__tests__/routes/adminTables.test.ts +git commit -m "feat(admin): add registry-driven data explorer reads" +``` + +### Task 6: Add guarded row updates and audit logging + +**Files:** +- Create: `supabase/migrations/20260424110000_create_admin_audit_log.sql` +- Create: `apps/api/src/helpers/adminAudit.ts` +- Modify: `apps/api/src/routers/adminTables.ts` +- Create: `apps/admin/src/components/data-explorer/RowEditForm.tsx` +- Modify: `apps/admin/src/components/data-explorer/RowDetailDrawer.tsx` +- Create: `apps/api/src/__tests__/routes/adminTableEdits.test.ts` +- Create: `apps/admin/src/components/data-explorer/RowEditForm.test.tsx` + +- [ ] **Step 1: Write failing tests for guarded edits and audit emission** + +```ts +it("writes an audit log entry for a successful update", async () => { + const res = await authedOperatorRequest("/api/v1/admin/tables/profiles/rows/user-1", { + method: "PATCH", + body: JSON.stringify({ first_name: "Ada" }), + }); + + expect(res.status).toBe(200); + expect(mockInsertAuditLog).toHaveBeenCalled(); +}); +``` + +```tsx +it("shows a diff preview before saving a sensitive record", async () => { + render(); + + await userEvent.type(screen.getByLabelText(/plan/i), "team"); + await userEvent.click(screen.getByRole("button", { name: /review changes/i })); + + expect(screen.getByText(/before/i)).toBeInTheDocument(); + expect(screen.getByText(/after/i)).toBeInTheDocument(); +}); +``` + +- [ ] **Step 2: Run the edit tests and verify failure** + +Run: `pnpm --filter @xtablo/api test -- src/__tests__/routes/adminTableEdits.test.ts` +Expected: FAIL + +Run: `pnpm --filter @xtablo/admin test -- src/components/data-explorer/RowEditForm.test.tsx` +Expected: FAIL + +- [ ] **Step 3: Add the audit log migration** + +Create a migration like: + +```sql +create table public.admin_audit_log ( + id bigserial primary key, + operator_id text not null, + operator_email text not null, + role text not null, + action text not null, + target_type text not null, + target_id text not null, + before jsonb, + after jsonb, + created_at timestamptz not null default now() +); +``` + +- [ ] **Step 4: Implement audit helper** + +In `apps/api/src/helpers/adminAudit.ts`: + +```ts +export async function recordAdminAuditLog(args: { + operatorId: string; + operatorEmail: string; + role: string; + action: string; + targetType: string; + targetId: string; + before?: unknown; + after?: unknown; +}) { + // insert into admin_audit_log +} +``` + +- [ ] **Step 5: Add PATCH support to `adminTables.ts`** + +Rules: + +- only registry-approved columns may change +- role-aware permissions enforce `viewer` vs `operator` vs `superadmin` +- sensitive fields return a diff payload before final confirmation +- every successful write records an audit entry + +- [ ] **Step 6: Add the row edit form and diff preview** + +Support typed editors for: + +- text +- booleans +- enums +- nullable values +- timestamps rendered read-only + +- [ ] **Step 7: Re-run edit tests** + +Run: `pnpm --filter @xtablo/api test -- src/__tests__/routes/adminTableEdits.test.ts` +Expected: PASS + +Run: `pnpm --filter @xtablo/admin test -- src/components/data-explorer/RowEditForm.test.tsx` +Expected: PASS + +- [ ] **Step 8: Commit guarded edits** + +```bash +git add supabase/migrations/20260424110000_create_admin_audit_log.sql apps/api/src/helpers/adminAudit.ts apps/api/src/routers/adminTables.ts apps/api/src/__tests__/routes/adminTableEdits.test.ts apps/admin/src/components/data-explorer/RowEditForm.tsx apps/admin/src/components/data-explorer/RowEditForm.test.tsx apps/admin/src/components/data-explorer/RowDetailDrawer.tsx +git commit -m "feat(admin): add guarded row edits with audit logging" +``` + +## Chunk 3: Operations Views, Analytics, Actions, And Rollout + +### Task 7: Build `Operations Home` with curated operational cards + +**Files:** +- Modify: `apps/admin/src/pages/OperationsHomePage.tsx` +- Create: `apps/api/src/routers/adminOverview.ts` +- Create: `apps/api/src/__tests__/routes/adminOverview.test.ts` +- Create: `apps/admin/src/pages/OperationsHomePage.test.tsx` +- Modify: `apps/api/src/routers/admin.ts` + +- [ ] **Step 1: Write failing tests for overview cards** + +```ts +it("returns overview sections for the operations home", async () => { + const res = await authedAdminRequest("/api/v1/admin/overview"); + expect(res.status).toBe(200); +}); +``` + +```tsx +it("renders anomaly and recent-signup cards", async () => { + render(); + expect(await screen.findByText(/recent signups/i)).toBeInTheDocument(); + expect(await screen.findByText(/operational anomalies/i)).toBeInTheDocument(); +}); +``` + +- [ ] **Step 2: Run the overview tests and confirm failure** + +Run: `pnpm --filter @xtablo/api test -- src/__tests__/routes/adminOverview.test.ts` +Expected: FAIL + +Run: `pnpm --filter @xtablo/admin test -- src/pages/OperationsHomePage.test.tsx` +Expected: FAIL + +- [ ] **Step 3: Add the overview endpoint** + +Return a small curated payload: + +- recent signups +- recent organizations +- subscription exceptions +- pinned saved explorer views +- anomaly counts + +- [ ] **Step 4: Build the home page cards** + +Make the first screen useful even if analytics is unfinished. + +- [ ] **Step 5: Re-run overview tests** + +Run: `pnpm --filter @xtablo/api test -- src/__tests__/routes/adminOverview.test.ts` +Expected: PASS + +Run: `pnpm --filter @xtablo/admin test -- src/pages/OperationsHomePage.test.tsx` +Expected: PASS + +- [ ] **Step 6: Commit operations home** + +```bash +git add apps/api/src/routers/adminOverview.ts apps/api/src/__tests__/routes/adminOverview.test.ts apps/api/src/routers/admin.ts apps/admin/src/pages/OperationsHomePage.tsx apps/admin/src/pages/OperationsHomePage.test.tsx +git commit -m "feat(admin): add operations home dashboard" +``` + +### Task 8: Add curated analytics datasets and dashboard building + +**Files:** +- Create: `supabase/migrations/20260424111000_create_admin_dataset_views.sql` +- Create: `apps/api/src/routers/adminDatasets.ts` +- Create: `apps/api/src/__tests__/routes/adminDatasets.test.ts` +- Create: `apps/admin/src/registry/datasets.ts` +- Create: `apps/admin/src/hooks/useAdminDatasets.ts` +- Create: `apps/admin/src/pages/AnalyticsStudioPage.tsx` +- Create: `apps/admin/src/components/analytics/ChartBuilder.tsx` +- Create: `apps/admin/src/components/analytics/SavedDashboardList.tsx` +- Create: `apps/admin/src/pages/AnalyticsStudioPage.test.tsx` + +- [ ] **Step 1: Write failing analytics dataset tests** + +```ts +it("lists curated datasets only", async () => { + const res = await authedAdminRequest("/api/v1/admin/datasets"); + expect(res.status).toBe(200); + expect(await res.json()).toMatchObject({ + datasets: expect.arrayContaining([expect.objectContaining({ id: "signups" })]), + }); +}); +``` + +```tsx +it("builds a chart from a curated dataset", async () => { + render(); + + await userEvent.selectOptions(screen.getByLabelText(/dataset/i), "signups"); + await userEvent.selectOptions(screen.getByLabelText(/metric/i), "count"); + + expect(await screen.findByRole("img", { name: /signups chart/i })).toBeInTheDocument(); +}); +``` + +- [ ] **Step 2: Run the analytics tests and confirm failure** + +Run: `pnpm --filter @xtablo/api test -- src/__tests__/routes/adminDatasets.test.ts` +Expected: FAIL + +Run: `pnpm --filter @xtablo/admin test -- src/pages/AnalyticsStudioPage.test.tsx` +Expected: FAIL + +- [ ] **Step 3: Create dataset views** + +Back them with curated views such as: + +- `admin_signups_daily` +- `admin_organizations_daily` +- `admin_subscription_exceptions` + +- [ ] **Step 4: Add dataset registry and API** + +Expose: + +- `GET /api/v1/admin/datasets` +- `GET /api/v1/admin/datasets/:datasetId/query` + +Only allow registry-defined dimensions, metrics, and grains. + +- [ ] **Step 5: Build Analytics Studio** + +Implement: + +- dataset picker +- metric and dimension controls +- date-range filters +- chart type picker +- saved dashboard list + +Use `recharts` and accessible titles for chart containers. + +- [ ] **Step 6: Re-run analytics tests** + +Run: `pnpm --filter @xtablo/api test -- src/__tests__/routes/adminDatasets.test.ts` +Expected: PASS + +Run: `pnpm --filter @xtablo/admin test -- src/pages/AnalyticsStudioPage.test.tsx` +Expected: PASS + +- [ ] **Step 7: Commit analytics** + +```bash +git add supabase/migrations/20260424111000_create_admin_dataset_views.sql apps/api/src/routers/adminDatasets.ts apps/api/src/__tests__/routes/adminDatasets.test.ts apps/admin/src/registry/datasets.ts apps/admin/src/hooks/useAdminDatasets.ts apps/admin/src/pages/AnalyticsStudioPage.tsx apps/admin/src/components/analytics/ChartBuilder.tsx apps/admin/src/components/analytics/SavedDashboardList.tsx apps/admin/src/pages/AnalyticsStudioPage.test.tsx +git commit -m "feat(admin): add curated analytics studio" +``` + +### Task 9: Add `Action Center` and first custom admin workflows + +**Files:** +- Create: `apps/admin/src/registry/actions.ts` +- Create: `apps/admin/src/hooks/useAdminActions.ts` +- Create: `apps/admin/src/pages/ActionCenterPage.tsx` +- Create: `apps/admin/src/components/actions/ActionRunner.tsx` +- Create: `apps/admin/src/pages/ActionCenterPage.test.tsx` +- Create: `apps/api/src/routers/adminActions.ts` +- Create: `apps/api/src/__tests__/routes/adminActions.test.ts` +- Modify: `apps/api/src/routers/admin.ts` + +- [ ] **Step 1: Write failing tests for action discovery and execution** + +```ts +it("executes a registry-defined admin action", async () => { + const res = await authedSuperadminRequest("/api/v1/admin/actions/repair-membership", { + method: "POST", + body: JSON.stringify({ userId: "user-1", organizationId: "org-1" }), + }); + + expect(res.status).toBe(200); +}); +``` + +```tsx +it("shows structured action results", async () => { + render(); + await userEvent.click(screen.getByRole("button", { name: /repair membership/i })); + expect(await screen.findByText(/result/i)).toBeInTheDocument(); +}); +``` + +- [ ] **Step 2: Run the action tests and confirm failure** + +Run: `pnpm --filter @xtablo/api test -- src/__tests__/routes/adminActions.test.ts` +Expected: FAIL + +Run: `pnpm --filter @xtablo/admin test -- src/pages/ActionCenterPage.test.tsx` +Expected: FAIL + +- [ ] **Step 3: Define the action registry** + +Start with 2 to 4 actions only: + +- `repair-membership` +- `resync-subscription` +- `merge-duplicate-profile` + +Each entry must define: + +- role requirement +- form schema +- confirmation copy +- handler route + +- [ ] **Step 4: Add admin action endpoints** + +Pattern: + +```ts +adminActions.post("/:actionId", async (c) => { + // load registry entry + // validate input + // execute handler + // write audit log + // return structured result +}); +``` + +- [ ] **Step 5: Build the Action Center UI** + +Include: + +- action catalog +- permission-aware disabled states +- typed form rendering +- confirmation step +- structured success and partial-failure results + +- [ ] **Step 6: Re-run action tests** + +Run: `pnpm --filter @xtablo/api test -- src/__tests__/routes/adminActions.test.ts` +Expected: PASS + +Run: `pnpm --filter @xtablo/admin test -- src/pages/ActionCenterPage.test.tsx` +Expected: PASS + +- [ ] **Step 7: Commit custom actions** + +```bash +git add apps/admin/src/registry/actions.ts apps/admin/src/hooks/useAdminActions.ts apps/admin/src/pages/ActionCenterPage.tsx apps/admin/src/components/actions/ActionRunner.tsx apps/admin/src/pages/ActionCenterPage.test.tsx apps/api/src/routers/adminActions.ts apps/api/src/__tests__/routes/adminActions.test.ts apps/api/src/routers/admin.ts +git commit -m "feat(admin): add audited action center workflows" +``` + +### Task 10: Deployment hardening, access docs, and final verification + +**Files:** +- Create: `docs/ADMIN_APP_ACCESS_SETUP.md` +- Modify: `apps/admin/wrangler.toml` +- Modify: `apps/api/src/config.ts` if any env names changed during implementation + +- [ ] **Step 1: Write the failing docs checklist** + +Create a checklist in `docs/ADMIN_APP_ACCESS_SETUP.md` covering: + +- private hostname or protected subdomain +- Cloudflare Access or VPN requirements +- privileged token issuance and rotation +- required env vars +- rollback path + +- [ ] **Step 2: Add private-route deployment details** + +Document placeholders like: + +```toml +[env.production] +route = { pattern = "admin.internal.xtablo.com", custom_domain = true } +``` + +Also document that public DNS alone is not sufficient; edge access policy must be enabled. + +- [ ] **Step 3: Run focused verification** + +Run: + +```bash +pnpm --filter @xtablo/api test -- src/__tests__/routes/adminAuth.test.ts src/__tests__/routes/adminTables.test.ts src/__tests__/routes/adminDatasets.test.ts src/__tests__/routes/adminActions.test.ts +pnpm --filter @xtablo/admin test -- src/routes.test.tsx src/components/PrivilegedGate.test.tsx src/pages/DataExplorerPage.test.tsx src/pages/AnalyticsStudioPage.test.tsx src/pages/ActionCenterPage.test.tsx +pnpm --filter @xtablo/api typecheck +pnpm --filter @xtablo/admin typecheck +``` + +Expected: all PASS + +- [ ] **Step 4: Run broader workspace checks before merge** + +Run: + +```bash +pnpm lint +pnpm typecheck +``` + +Expected: PASS, or only pre-existing unrelated failures clearly identified + +- [ ] **Step 5: Commit docs and hardening** + +```bash +git add docs/ADMIN_APP_ACCESS_SETUP.md apps/admin/wrangler.toml apps/api/src/config.ts +git commit -m "docs(admin): add deployment and access runbook" +``` + +## Notes For Execution + +- Do not bypass the privileged token model by reusing `apps/main/src/lib/supabase.ts` directly in the admin app. +- Keep the initial registry intentionally small; expand after the guarded end-to-end slice is working. +- Prefer API-mediated reads and writes for admin resources even where direct browser Supabase access would be faster to code. +- When a task touches both API and frontend, land the contract tests first, then the server, then the UI. +- If the private edge boundary cannot be fully provisioned in code, keep the repo changes ready and document the exact manual platform steps in `docs/ADMIN_APP_ACCESS_SETUP.md`. + +Plan complete and saved to `docs/superpowers/plans/2026-04-24-supabase-admin-dashboard.md`. Ready to execute? From ce462b4d657e65041a8f1c04d61dd00c2a168898 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Fri, 24 Apr 2026 15:10:44 +0200 Subject: [PATCH 63/75] feat(admin): scaffold internal admin app --- apps/admin/index.html | 12 +++++++++ apps/admin/package.json | 46 ++++++++++++++++++++++++++++++++++ apps/admin/src/App.tsx | 9 +++++++ apps/admin/src/main.css | 30 ++++++++++++++++++++++ apps/admin/src/main.tsx | 15 +++++++++++ apps/admin/src/routes.test.tsx | 13 ++++++++++ apps/admin/src/routes.tsx | 19 ++++++++++++++ apps/admin/src/setupTests.ts | 6 +++++ apps/admin/tsconfig.json | 31 +++++++++++++++++++++++ apps/admin/vite.config.ts | 29 +++++++++++++++++++++ apps/admin/worker/index.ts | 9 +++++++ apps/admin/wrangler.toml | 16 ++++++++++++ package.json | 2 ++ 13 files changed, 237 insertions(+) create mode 100644 apps/admin/index.html create mode 100644 apps/admin/package.json create mode 100644 apps/admin/src/App.tsx create mode 100644 apps/admin/src/main.css create mode 100644 apps/admin/src/main.tsx create mode 100644 apps/admin/src/routes.test.tsx create mode 100644 apps/admin/src/routes.tsx create mode 100644 apps/admin/src/setupTests.ts create mode 100644 apps/admin/tsconfig.json create mode 100644 apps/admin/vite.config.ts create mode 100644 apps/admin/worker/index.ts create mode 100644 apps/admin/wrangler.toml diff --git a/apps/admin/index.html b/apps/admin/index.html new file mode 100644 index 0000000..49d4ec8 --- /dev/null +++ b/apps/admin/index.html @@ -0,0 +1,12 @@ + + + + + + XTablo Admin + + +
+ + + diff --git a/apps/admin/package.json b/apps/admin/package.json new file mode 100644 index 0000000..c431f5f --- /dev/null +++ b/apps/admin/package.json @@ -0,0 +1,46 @@ +{ + "name": "@xtablo/admin", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite dev --port 5176", + "build": "tsc -b && vite build --mode production", + "deploy": "wrangler deploy", + "typecheck": "tsc -b", + "lint": "biome check .", + "lint:fix": "biome check --write .", + "format": "biome format --write .", + "preview": "vite preview", + "test": "vitest run --mode test --passWithNoTests", + "test:watch": "vitest watch --mode test --passWithNoTests", + "clean": "rm -rf dist .vite tsconfig.tsbuildinfo node_modules/.vite" + }, + "devDependencies": { + "@biomejs/biome": "2.2.5", + "@cloudflare/vite-plugin": "^1.9.4", + "@tailwindcss/vite": "^4.0.14", + "@testing-library/jest-dom": "^6.6.3", + "@testing-library/react": "^16.3.0", + "@types/react": "19.0.10", + "@types/react-dom": "19.0.4", + "@vitejs/plugin-react": "^4.3.4", + "happy-dom": "^20.0.0", + "tailwindcss": "^4.0.14", + "tw-animate-css": "^1.4.0", + "typescript": "^5.7.0", + "vite": "^6.2.2", + "vite-tsconfig-paths": "^5.1.4", + "vitest": "^3.2.4", + "wrangler": "^4.24.3" + }, + "dependencies": { + "@tanstack/react-query": "^5.69.0", + "@xtablo/shared": "workspace:*", + "@xtablo/shared-types": "workspace:*", + "@xtablo/ui": "workspace:*", + "react": "19.0.0", + "react-dom": "19.0.0", + "react-router-dom": "^7.9.4" + } +} diff --git a/apps/admin/src/App.tsx b/apps/admin/src/App.tsx new file mode 100644 index 0000000..d723e06 --- /dev/null +++ b/apps/admin/src/App.tsx @@ -0,0 +1,9 @@ +import AppRoutes from "./routes"; + +export default function App() { + return ( +
+ +
+ ); +} diff --git a/apps/admin/src/main.css b/apps/admin/src/main.css new file mode 100644 index 0000000..70631d1 --- /dev/null +++ b/apps/admin/src/main.css @@ -0,0 +1,30 @@ +@import "tailwindcss"; +@import "tw-animate-css"; + +@custom-variant dark (&:is(.dark *)); + +:root { + --background: oklch(0.97 0.01 95); + --foreground: oklch(0.2 0.02 255); + --card: oklch(0.995 0.002 95); + --card-foreground: oklch(0.2 0.02 255); + --border: oklch(0.88 0.01 95); +} + +@theme inline { + --color-background: var(--background); + --color-foreground: var(--foreground); + --color-card: var(--card); + --color-card-foreground: var(--card-foreground); + --color-border: var(--border); +} + +@layer base { + * { + @apply border-border; + } + + body { + @apply bg-background text-foreground antialiased; + } +} diff --git a/apps/admin/src/main.tsx b/apps/admin/src/main.tsx new file mode 100644 index 0000000..6781fde --- /dev/null +++ b/apps/admin/src/main.tsx @@ -0,0 +1,15 @@ +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import { BrowserRouter } from "react-router-dom"; +import App from "./App"; + +import "@xtablo/ui/globals.css"; +import "./main.css"; + +createRoot(document.getElementById("admin-root")!).render( + + + + + +); diff --git a/apps/admin/src/routes.test.tsx b/apps/admin/src/routes.test.tsx new file mode 100644 index 0000000..418cc42 --- /dev/null +++ b/apps/admin/src/routes.test.tsx @@ -0,0 +1,13 @@ +import { render, screen } from "@testing-library/react"; +import { MemoryRouter } from "react-router-dom"; +import AppRoutes from "./routes"; + +it("renders the privileged gate on the root route", () => { + render( + + + + ); + + expect(screen.getByText(/admin access token/i)).toBeInTheDocument(); +}); diff --git a/apps/admin/src/routes.tsx b/apps/admin/src/routes.tsx new file mode 100644 index 0000000..3e30c96 --- /dev/null +++ b/apps/admin/src/routes.tsx @@ -0,0 +1,19 @@ +import { Route, Routes } from "react-router-dom"; + +function PrivilegedGatePlaceholder() { + return ( +
+
+

Admin access token required

+
+
+ ); +} + +export default function AppRoutes() { + return ( + + } /> + + ); +} diff --git a/apps/admin/src/setupTests.ts b/apps/admin/src/setupTests.ts new file mode 100644 index 0000000..b403818 --- /dev/null +++ b/apps/admin/src/setupTests.ts @@ -0,0 +1,6 @@ +import "@testing-library/jest-dom"; +import { cleanup } from "@testing-library/react"; + +afterEach(() => { + cleanup(); +}); diff --git a/apps/admin/tsconfig.json b/apps/admin/tsconfig.json new file mode 100644 index 0000000..586e2a9 --- /dev/null +++ b/apps/admin/tsconfig.json @@ -0,0 +1,31 @@ +{ + "compilerOptions": { + "target": "ES2020", + "useDefineForClassFields": true, + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "types": ["vite/client", "vitest/globals"], + "module": "ESNext", + "skipLibCheck": true, + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "jsx": "react-jsx", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "baseUrl": ".", + "paths": { + "@xtablo/ui": ["../../packages/ui/src"], + "@xtablo/ui/*": ["../../packages/ui/src/*"], + "@xtablo/shared": ["../../packages/shared/src"], + "@xtablo/shared/*": ["../../packages/shared/src/*"], + "@xtablo/shared-types": ["../../packages/shared-types/src"], + "@xtablo/shared-types/*": ["../../packages/shared-types/src/*"] + } + }, + "include": ["src"], + "references": [] +} diff --git a/apps/admin/vite.config.ts b/apps/admin/vite.config.ts new file mode 100644 index 0000000..b80495d --- /dev/null +++ b/apps/admin/vite.config.ts @@ -0,0 +1,29 @@ +/// + +import { cloudflare } from "@cloudflare/vite-plugin"; +import tailwindcss from "@tailwindcss/vite"; +import react from "@vitejs/plugin-react"; +import { defineConfig, type PluginOption } from "vite"; +import tsconfigPaths from "vite-tsconfig-paths"; + +export default defineConfig(({ mode }) => { + const plugins: PluginOption[] = [ + react(), + tailwindcss(), + tsconfigPaths({ ignoreConfigErrors: true }), + ]; + + if (mode !== "test" && process.env.VITEST !== "true") { + plugins.push(cloudflare({ inspectorPort: 9233 })); + } + + return { + plugins, + server: { cors: false }, + test: { + globals: true, + environment: "happy-dom", + setupFiles: "./src/setupTests.ts", + }, + }; +}); diff --git a/apps/admin/worker/index.ts b/apps/admin/worker/index.ts new file mode 100644 index 0000000..bee9dbb --- /dev/null +++ b/apps/admin/worker/index.ts @@ -0,0 +1,9 @@ +export default { + fetch(request: Request) { + const url = new URL(request.url); + if (url.pathname.startsWith("/api/")) { + return Response.json({ name: "XTablo Admin Worker" }); + } + return new Response(null, { status: 404 }); + }, +}; diff --git a/apps/admin/wrangler.toml b/apps/admin/wrangler.toml new file mode 100644 index 0000000..8083093 --- /dev/null +++ b/apps/admin/wrangler.toml @@ -0,0 +1,16 @@ +name = "xtablo-admin" +main = "worker/index.ts" +compatibility_date = "2025-07-09" + +[assets] +directory = "./dist/" +not_found_handling = "single-page-application" + +[observability] +enabled = true + +[env.staging] +route = { pattern = "admin-staging.internal.xtablo.com", custom_domain = true } + +[env.production] +route = { pattern = "admin.internal.xtablo.com", custom_domain = true } diff --git a/package.json b/package.json index bf99826..6c383b5 100644 --- a/package.json +++ b/package.json @@ -14,11 +14,13 @@ "build:prod": "turbo build:prod --filter=@xtablo/main", "dev": "turbo dev", "dev:main": "turbo dev --filter=@xtablo/main", + "dev:admin": "turbo dev --filter=@xtablo/admin", "dev:external": "turbo dev --filter=@xtablo/external", "dev:clients": "turbo dev --filter=@xtablo/clients", "dev:api": "turbo dev --filter=@xtablo/api", "deploy:main:staging": "turbo deploy:staging --filter=@xtablo/main", "deploy:main:prod": "turbo deploy:prod --filter=@xtablo/main", + "deploy:admin": "turbo deploy --filter=@xtablo/admin", "deploy:chat": "turbo deploy --filter=@xtablo/chat-worker", "deploy:external": "turbo deploy --filter=@xtablo/external", "lint": "turbo lint", From 1c97113c67f4976b5eda19427cdedc6fd601afc3 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Fri, 24 Apr 2026 15:31:34 +0200 Subject: [PATCH 64/75] feat(admin): add privileged admin session exchange --- .../__tests__/config/stripe-config.test.ts | 1 + .../__tests__/helpers/adminTokenTestUtils.ts | 24 +++ .../__tests__/middlewares/adminAuth.test.ts | 55 +++++ .../src/__tests__/routes/adminAuth.test.ts | 64 ++++++ apps/api/src/config.ts | 13 +- apps/api/src/helpers/adminTokens.ts | 201 ++++++++++++++++++ apps/api/src/middlewares/middleware.ts | 45 ++++ apps/api/src/routers/admin.ts | 18 ++ apps/api/src/routers/adminAuth.ts | 55 +++++ apps/api/src/routers/adminTables.ts | 19 ++ apps/api/src/routers/index.ts | 4 + apps/api/src/secrets.ts | 2 + apps/api/src/types/app.types.ts | 2 + packages/shared-types/src/admin.types.ts | 17 ++ packages/shared-types/src/index.ts | 4 + 15 files changed, 520 insertions(+), 4 deletions(-) create mode 100644 apps/api/src/__tests__/helpers/adminTokenTestUtils.ts create mode 100644 apps/api/src/__tests__/middlewares/adminAuth.test.ts create mode 100644 apps/api/src/__tests__/routes/adminAuth.test.ts create mode 100644 apps/api/src/helpers/adminTokens.ts create mode 100644 apps/api/src/routers/admin.ts create mode 100644 apps/api/src/routers/adminAuth.ts create mode 100644 apps/api/src/routers/adminTables.ts create mode 100644 packages/shared-types/src/admin.types.ts diff --git a/apps/api/src/__tests__/config/stripe-config.test.ts b/apps/api/src/__tests__/config/stripe-config.test.ts index fdc130b..0a29917 100644 --- a/apps/api/src/__tests__/config/stripe-config.test.ts +++ b/apps/api/src/__tests__/config/stripe-config.test.ts @@ -3,6 +3,7 @@ import { createConfig } from "../../config.js"; import type { Secrets } from "../../secrets.js"; const baseSecrets: Secrets = { + adminTokenSigningSecret: "admin-token-signing-secret", supabaseServiceRoleKey: "service-role-from-secret-manager", supabaseConnectionString: "postgres://secret-manager", supabaseCaCert: "ca-cert", diff --git a/apps/api/src/__tests__/helpers/adminTokenTestUtils.ts b/apps/api/src/__tests__/helpers/adminTokenTestUtils.ts new file mode 100644 index 0000000..4b024d0 --- /dev/null +++ b/apps/api/src/__tests__/helpers/adminTokenTestUtils.ts @@ -0,0 +1,24 @@ +import { createHmac } from "node:crypto"; + +type TestAdminTokenClaims = { + aud: string; + email: string; + exp: number; + role: "viewer" | "operator" | "superadmin"; + sub: string; + type: "admin_access" | "admin_session"; +}; + +function encodeSegment(value: unknown) { + return Buffer.from(JSON.stringify(value)).toString("base64url"); +} + +export function createSignedAdminToken(claims: TestAdminTokenClaims, secret: string) { + const header = encodeSegment({ alg: "HS256", typ: "JWT" }); + const payload = encodeSegment(claims); + const signature = createHmac("sha256", secret) + .update(`${header}.${payload}`) + .digest("base64url"); + + return `${header}.${payload}.${signature}`; +} diff --git a/apps/api/src/__tests__/middlewares/adminAuth.test.ts b/apps/api/src/__tests__/middlewares/adminAuth.test.ts new file mode 100644 index 0000000..1bc0393 --- /dev/null +++ b/apps/api/src/__tests__/middlewares/adminAuth.test.ts @@ -0,0 +1,55 @@ +import { createSignedAdminToken } from "../helpers/adminTokenTestUtils.js"; +import { describe, expect, it } from "vitest"; +import { createConfig } from "../../config.js"; +import { MiddlewareManager } from "../../middlewares/middleware.js"; +import { getMainRouter } from "../../routers/index.js"; + +const ADMIN_TOKEN_SIGNING_SECRET = "admin-test-secret"; +const ADMIN_TOKEN_AUDIENCE = "xtablo-admin"; + +describe("Admin Auth Middleware", () => { + process.env.ADMIN_TOKEN_SIGNING_SECRET = ADMIN_TOKEN_SIGNING_SECRET; + process.env.ADMIN_TOKEN_AUDIENCE = ADMIN_TOKEN_AUDIENCE; + process.env.ADMIN_APP_URL = "http://localhost:5176"; + + const config = createConfig(); + MiddlewareManager.initialize(config); + const app = getMainRouter(config); + + it("rejects admin routes without an admin session", async () => { + const res = await app.request("/admin/tables/profiles"); + + expect(res.status).toBe(401); + await expect(res.json()).resolves.toMatchObject({ + error: "Admin session required", + code: "ADMIN_SESSION_REQUIRED", + }); + }); + + it("returns the current admin session for a valid admin session token", async () => { + const sessionToken = createSignedAdminToken( + { + aud: ADMIN_TOKEN_AUDIENCE, + email: "ops@xtablo.com", + exp: Math.floor(Date.now() / 1000) + 900, + role: "operator", + sub: "operator-1", + type: "admin_session", + }, + ADMIN_TOKEN_SIGNING_SECRET + ); + + const res = await app.request("/admin/auth/session", { + headers: { + Authorization: `Bearer ${sessionToken}`, + }, + }); + + expect(res.status).toBe(200); + await expect(res.json()).resolves.toMatchObject({ + role: "operator", + operatorEmail: "ops@xtablo.com", + operatorId: "operator-1", + }); + }); +}); diff --git a/apps/api/src/__tests__/routes/adminAuth.test.ts b/apps/api/src/__tests__/routes/adminAuth.test.ts new file mode 100644 index 0000000..0ff3585 --- /dev/null +++ b/apps/api/src/__tests__/routes/adminAuth.test.ts @@ -0,0 +1,64 @@ +import { createSignedAdminToken } from "../helpers/adminTokenTestUtils.js"; +import { describe, expect, it } from "vitest"; +import { createConfig } from "../../config.js"; +import { MiddlewareManager } from "../../middlewares/middleware.js"; +import { getMainRouter } from "../../routers/index.js"; + +const ADMIN_TOKEN_SIGNING_SECRET = "admin-test-secret"; +const ADMIN_TOKEN_AUDIENCE = "xtablo-admin"; + +describe("Admin Auth Router", () => { + process.env.ADMIN_TOKEN_SIGNING_SECRET = ADMIN_TOKEN_SIGNING_SECRET; + process.env.ADMIN_TOKEN_AUDIENCE = ADMIN_TOKEN_AUDIENCE; + process.env.ADMIN_APP_URL = "http://localhost:5176"; + + const config = createConfig(); + MiddlewareManager.initialize(config); + const app = getMainRouter(config); + + it("rejects requests without a valid privileged token", async () => { + const res = await app.request("/admin/auth/exchange", { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ accessToken: "bad-token" }), + }); + + expect(res.status).toBe(401); + await expect(res.json()).resolves.toMatchObject({ + error: "Invalid privileged access token", + code: "INVALID_ADMIN_ACCESS_TOKEN", + }); + }); + + it("exchanges a valid privileged token for an admin session", async () => { + const accessToken = createSignedAdminToken( + { + aud: ADMIN_TOKEN_AUDIENCE, + email: "ops@xtablo.com", + exp: Math.floor(Date.now() / 1000) + 3600, + role: "operator", + sub: "operator-1", + type: "admin_access", + }, + ADMIN_TOKEN_SIGNING_SECRET + ); + + const res = await app.request("/admin/auth/exchange", { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ accessToken }), + }); + + expect(res.status).toBe(200); + await expect(res.json()).resolves.toMatchObject({ + role: "operator", + operatorEmail: "ops@xtablo.com", + sessionToken: expect.any(String), + expiresAt: expect.any(String), + }); + }); +}); diff --git a/apps/api/src/config.ts b/apps/api/src/config.ts index 38f74f0..a6a4134 100644 --- a/apps/api/src/config.ts +++ b/apps/api/src/config.ts @@ -23,6 +23,9 @@ export interface AppConfig { R2_SECRET_ACCESS_KEY: string; LOG_LEVEL: "debug" | "info" | "warn" | "error"; TASKS_SECRET: string; + ADMIN_TOKEN_SIGNING_SECRET: string; + ADMIN_TOKEN_AUDIENCE: string; + ADMIN_APP_URL: string; /** * Test user @@ -85,10 +88,7 @@ export function createConfig(secrets?: Secrets): AppConfig { ? validateEnvVar("STRIPE_WEBHOOK_SECRET", process.env.STRIPE_WEBHOOK_SECRET) : getStripeWebhookSecretFromEnv() || getStripeWebhookSecret(isStagingMode), STRIPE_SOLO_PRICE_ID: validateEnvVar("STRIPE_SOLO_PRICE_ID", process.env.STRIPE_SOLO_PRICE_ID), - STRIPE_TEAM_PRICE_ID: validateEnvVar( - "STRIPE_TEAM_PRICE_ID", - process.env.STRIPE_TEAM_PRICE_ID - ), + STRIPE_TEAM_PRICE_ID: validateEnvVar("STRIPE_TEAM_PRICE_ID", process.env.STRIPE_TEAM_PRICE_ID), STRIPE_FOUNDER_PRICE_ID: validateEnvVar( "STRIPE_FOUNDER_PRICE_ID", process.env.STRIPE_FOUNDER_PRICE_ID @@ -110,6 +110,11 @@ export function createConfig(secrets?: Secrets): AppConfig { ? validateEnvVar("R2_SECRET_ACCESS_KEY", process.env.R2_SECRET_ACCESS_KEY) : secrets!.r2SecretAccessKey, TASKS_SECRET: process.env.TASKS_SECRET || "", + ADMIN_TOKEN_SIGNING_SECRET: isTestMode + ? validateEnvVar("ADMIN_TOKEN_SIGNING_SECRET", process.env.ADMIN_TOKEN_SIGNING_SECRET) + : secrets!.adminTokenSigningSecret, + ADMIN_TOKEN_AUDIENCE: process.env.ADMIN_TOKEN_AUDIENCE || "xtablo-admin", + ADMIN_APP_URL: process.env.ADMIN_APP_URL || "http://localhost:5176", LOG_LEVEL: "info", TEST_USER_DATA: { id: "test", diff --git a/apps/api/src/helpers/adminTokens.ts b/apps/api/src/helpers/adminTokens.ts new file mode 100644 index 0000000..b382e23 --- /dev/null +++ b/apps/api/src/helpers/adminTokens.ts @@ -0,0 +1,201 @@ +import { createHmac, timingSafeEqual } from "node:crypto"; +import type { AppConfig } from "../config.js"; + +export type AdminRole = "viewer" | "operator" | "superadmin"; + +type TokenKind = "admin_access" | "admin_session"; + +type AdminTokenClaims = { + aud: string; + email: string; + exp: number; + role: AdminRole; + sub: string; + type: TokenKind; +}; + +export type AdminSessionClaims = { + aud: string; + exp: number; + operatorEmail: string; + operatorId: string; + role: AdminRole; +}; + +type AdminTokenErrorCode = + | "ADMIN_SESSION_REQUIRED" + | "INVALID_ADMIN_ACCESS_TOKEN" + | "INVALID_ADMIN_SESSION"; + +type AdminTokenFailure = { + code: AdminTokenErrorCode; + error: string; + statusCode: 401; + success: false; +}; + +type AdminTokenSuccess = { + success: true; + value: T; +}; + +export type AdminTokenResult = AdminTokenFailure | AdminTokenSuccess; + +type ExchangeResult = { + expiresAt: string; + operatorEmail: string; + operatorId: string; + role: AdminRole; + sessionToken: string; +}; + +function encodeSegment(value: unknown) { + return Buffer.from(JSON.stringify(value)).toString("base64url"); +} + +function decodeSegment(segment: string): T | null { + try { + return JSON.parse(Buffer.from(segment, "base64url").toString("utf8")) as T; + } catch { + return null; + } +} + +function signToken(claims: AdminTokenClaims, secret: string) { + const header = encodeSegment({ alg: "HS256", typ: "JWT" }); + const payload = encodeSegment(claims); + const signature = createHmac("sha256", secret).update(`${header}.${payload}`).digest("base64url"); + + return `${header}.${payload}.${signature}`; +} + +function invalidToken(error: string, code: AdminTokenErrorCode): AdminTokenFailure { + return { + code, + error, + statusCode: 401, + success: false, + }; +} + +function isFailure(result: AdminTokenResult): result is AdminTokenFailure { + return !result.success; +} + +function verifyToken( + token: string, + config: AppConfig, + expectedType: TokenKind +): AdminTokenResult { + const segments = token.split("."); + if (segments.length !== 3) { + return invalidToken( + expectedType === "admin_access" ? "Invalid privileged access token" : "Invalid admin session", + expectedType === "admin_access" ? "INVALID_ADMIN_ACCESS_TOKEN" : "INVALID_ADMIN_SESSION" + ); + } + + const [header, payload, signature] = segments; + const expectedSignature = createHmac("sha256", config.ADMIN_TOKEN_SIGNING_SECRET) + .update(`${header}.${payload}`) + .digest(); + const receivedSignature = Buffer.from(signature, "base64url"); + + if ( + expectedSignature.length !== receivedSignature.length || + !timingSafeEqual(expectedSignature, receivedSignature) + ) { + return invalidToken( + expectedType === "admin_access" ? "Invalid privileged access token" : "Invalid admin session", + expectedType === "admin_access" ? "INVALID_ADMIN_ACCESS_TOKEN" : "INVALID_ADMIN_SESSION" + ); + } + + const claims = decodeSegment(payload); + if (!claims) { + return invalidToken( + expectedType === "admin_access" ? "Invalid privileged access token" : "Invalid admin session", + expectedType === "admin_access" ? "INVALID_ADMIN_ACCESS_TOKEN" : "INVALID_ADMIN_SESSION" + ); + } + + if (claims.type !== expectedType || claims.aud !== config.ADMIN_TOKEN_AUDIENCE) { + return invalidToken( + expectedType === "admin_access" ? "Invalid privileged access token" : "Invalid admin session", + expectedType === "admin_access" ? "INVALID_ADMIN_ACCESS_TOKEN" : "INVALID_ADMIN_SESSION" + ); + } + + if (claims.exp <= Math.floor(Date.now() / 1000)) { + return invalidToken( + expectedType === "admin_access" ? "Invalid privileged access token" : "Invalid admin session", + expectedType === "admin_access" ? "INVALID_ADMIN_ACCESS_TOKEN" : "INVALID_ADMIN_SESSION" + ); + } + + return { success: true, value: claims }; +} + +export function exchangePrivilegedToken( + token: string, + config: AppConfig +): AdminTokenResult { + const verifiedAccessToken = verifyToken(token, config, "admin_access"); + if (isFailure(verifiedAccessToken)) { + return verifiedAccessToken; + } + + const accessClaims = verifiedAccessToken.value; + const sessionExpiry = Math.floor(Date.now() / 1000) + 15 * 60; + const sessionToken = signToken( + { + aud: config.ADMIN_TOKEN_AUDIENCE, + email: accessClaims.email, + exp: sessionExpiry, + role: accessClaims.role, + sub: accessClaims.sub, + type: "admin_session", + }, + config.ADMIN_TOKEN_SIGNING_SECRET + ); + + return { + success: true, + value: { + expiresAt: new Date(sessionExpiry * 1000).toISOString(), + operatorEmail: accessClaims.email, + operatorId: accessClaims.sub, + role: accessClaims.role, + sessionToken, + }, + }; +} + +export function verifyAdminSession( + token: string | undefined, + config: AppConfig +): AdminTokenResult { + if (!token) { + return invalidToken("Admin session required", "ADMIN_SESSION_REQUIRED"); + } + + const verifiedSession = verifyToken(token, config, "admin_session"); + if (isFailure(verifiedSession)) { + return { + ...verifiedSession, + code: "ADMIN_SESSION_REQUIRED", + error: "Admin session required", + }; + } + + return { + success: true, + value: { + aud: verifiedSession.value.aud, + exp: verifiedSession.value.exp, + operatorEmail: verifiedSession.value.email, + operatorId: verifiedSession.value.sub, + role: verifiedSession.value.role, + }, + }; +} diff --git a/apps/api/src/middlewares/middleware.ts b/apps/api/src/middlewares/middleware.ts index 7c153e6..b53c15b 100644 --- a/apps/api/src/middlewares/middleware.ts +++ b/apps/api/src/middlewares/middleware.ts @@ -6,6 +6,7 @@ import { createMiddleware } from "hono/factory"; import type { Transporter } from "nodemailer"; import { Stripe } from "stripe"; import { type AppConfig } from "../config.js"; +import { type AdminTokenResult, verifyAdminSession } from "../helpers/adminTokens.js"; import { authenticateFromHeader } from "../helpers/auth.js"; import { createStripeSync } from "./stripeSync.js"; import { createTransporter } from "./transporter.js"; @@ -24,6 +25,9 @@ export type Middlewares = { Variables: { supabase: SupabaseClient; user: User }; Bindings: { user: User }; }>; + adminAuthMiddleware: MiddlewareHandler<{ + Variables: { adminSession: import("../helpers/adminTokens.js").AdminSessionClaims }; + }>; r2Middleware: MiddlewareHandler<{ Variables: { s3_client: S3Client }; }>; @@ -74,6 +78,10 @@ export class MiddlewareManager { } private initializeMiddlewares(config: AppConfig): Middlewares { + const isAdminTokenFailure = ( + result: AdminTokenResult + ): result is Extract, { success: false }> => !result.success; + const createProfileAccessMiddleware = (allowTemporaryUsers: boolean) => createMiddleware<{ Variables: { supabase: SupabaseClient; user: User }; @@ -141,6 +149,38 @@ export class MiddlewareManager { await next(); }); + const adminAuthMiddleware = createMiddleware<{ + Variables: { adminSession: import("../helpers/adminTokens.js").AdminSessionClaims }; + }>(async (c, next) => { + const authHeader = c.req.header("Authorization"); + + if (!authHeader || !authHeader.startsWith("Bearer ")) { + return c.json( + { + code: "ADMIN_SESSION_REQUIRED", + error: "Admin session required", + }, + 401 + ); + } + + const sessionToken = authHeader.substring(7); + const verifiedSession = verifyAdminSession(sessionToken, config); + + if (isAdminTokenFailure(verifiedSession)) { + return c.json( + { + code: verifiedSession.code, + error: verifiedSession.error, + }, + verifiedSession.statusCode + ); + } + + c.set("adminSession", verifiedSession.value); + await next(); + }); + const maybeAuthenticatedMiddleware = createMiddleware<{ Variables: { supabase: SupabaseClient; user: User | null }; }>(async (c, next) => { @@ -241,6 +281,7 @@ export class MiddlewareManager { supabaseMiddleware, basicAuthMiddleware, authMiddleware, + adminAuthMiddleware, maybeAuthenticatedMiddleware, r2Middleware, regularUserCheckMiddleware, @@ -264,6 +305,10 @@ export class MiddlewareManager { return this.middlewares.authMiddleware; } + get adminAuth() { + return this.middlewares.adminAuthMiddleware; + } + get maybeAuthenticated() { return this.middlewares.maybeAuthenticatedMiddleware; } diff --git a/apps/api/src/routers/admin.ts b/apps/api/src/routers/admin.ts new file mode 100644 index 0000000..1eb8f8b --- /dev/null +++ b/apps/api/src/routers/admin.ts @@ -0,0 +1,18 @@ +import { Hono } from "hono"; +import type { AppConfig } from "../config.js"; +import { MiddlewareManager } from "../middlewares/middleware.js"; +import type { BaseEnv } from "../types/app.types.js"; +import { getAdminAuthRouter } from "./adminAuth.js"; +import { getAdminTablesRouter } from "./adminTables.js"; + +export const getAdminRouter = (config: AppConfig) => { + const adminRouter = new Hono(); + const middlewareManager = MiddlewareManager.getInstance(); + + adminRouter.route("/auth", getAdminAuthRouter(config)); + + adminRouter.use("/tables/*", middlewareManager.adminAuth); + adminRouter.route("/tables", getAdminTablesRouter()); + + return adminRouter; +}; diff --git a/apps/api/src/routers/adminAuth.ts b/apps/api/src/routers/adminAuth.ts new file mode 100644 index 0000000..065d284 --- /dev/null +++ b/apps/api/src/routers/adminAuth.ts @@ -0,0 +1,55 @@ +import { Hono } from "hono"; +import type { AppConfig } from "../config.js"; +import { type AdminTokenResult, exchangePrivilegedToken } from "../helpers/adminTokens.js"; +import { MiddlewareManager } from "../middlewares/middleware.js"; +import type { BaseEnv } from "../types/app.types.js"; + +export const getAdminAuthRouter = (config: AppConfig) => { + const adminAuthRouter = new Hono(); + const middlewareManager = MiddlewareManager.getInstance(); + const isAdminTokenFailure = ( + result: AdminTokenResult + ): result is Extract, { success: false }> => !result.success; + + adminAuthRouter.post("/exchange", async (c) => { + const body = await c.req.json().catch(() => null); + const accessToken = + body && typeof body === "object" && "accessToken" in body ? body.accessToken : undefined; + + if (typeof accessToken !== "string" || accessToken.length === 0) { + return c.json( + { + code: "INVALID_ADMIN_ACCESS_TOKEN", + error: "Invalid privileged access token", + }, + 401 + ); + } + + const exchangeResult = exchangePrivilegedToken(accessToken, config); + + if (isAdminTokenFailure(exchangeResult)) { + return c.json( + { + code: exchangeResult.code, + error: exchangeResult.error, + }, + exchangeResult.statusCode + ); + } + + return c.json(exchangeResult.value, 200); + }); + + adminAuthRouter.use("/session", middlewareManager.adminAuth); + + adminAuthRouter.get("/session", async (c) => { + const adminSession = c.get("adminSession"); + + return c.json(adminSession, 200); + }); + + adminAuthRouter.post("/logout", async (c) => c.json({ success: true }, 200)); + + return adminAuthRouter; +}; diff --git a/apps/api/src/routers/adminTables.ts b/apps/api/src/routers/adminTables.ts new file mode 100644 index 0000000..29709f0 --- /dev/null +++ b/apps/api/src/routers/adminTables.ts @@ -0,0 +1,19 @@ +import { Hono } from "hono"; +import type { BaseEnv } from "../types/app.types.js"; + +export const getAdminTablesRouter = () => { + const adminTablesRouter = new Hono(); + + adminTablesRouter.get("/:tableId", async (c) => { + const tableId = c.req.param("tableId"); + + return c.json( + { + error: `Admin table '${tableId}' is not implemented yet`, + }, + 501 + ); + }); + + return adminTablesRouter; +}; diff --git a/apps/api/src/routers/index.ts b/apps/api/src/routers/index.ts index 1ca996e..93ccd34 100644 --- a/apps/api/src/routers/index.ts +++ b/apps/api/src/routers/index.ts @@ -1,6 +1,7 @@ import { Hono } from "hono"; import type { AppConfig } from "../config.js"; import { MiddlewareManager } from "../middlewares/middleware.js"; +import { getAdminRouter } from "./admin.js"; import type { BaseEnv } from "../types/app.types.js"; import { getAuthenticatedRouter } from "./authRouter.js"; import { getMaybeAuthenticatedRouter } from "./maybeAuthRouter.js"; @@ -31,6 +32,9 @@ export const getMainRouter = (config: AppConfig) => { // webhooks mainRouter.route("/stripe-webhook", getStripeWebhookRouter()); + // admin routes + mainRouter.route("/admin", getAdminRouter(config)); + // maybe authenticated routes (checked first to allow unauthenticated booking) mainRouter.route("/", getMaybeAuthenticatedRouter()); diff --git a/apps/api/src/secrets.ts b/apps/api/src/secrets.ts index 2126133..f3e917d 100644 --- a/apps/api/src/secrets.ts +++ b/apps/api/src/secrets.ts @@ -21,6 +21,7 @@ export type Secrets = { supabaseServiceRoleKey: string; supabaseConnectionString: string; supabaseCaCert: string; + adminTokenSigningSecret: string; emailClientSecret: string; emailRefreshToken: string; r2AccessKeyId: string; @@ -42,6 +43,7 @@ export async function loadSecrets(): Promise { supabaseServiceRoleKey: await fetchSecret("supabase-service-role-key"), supabaseConnectionString: await fetchSecret("supabase-connection-string"), supabaseCaCert: await fetchSecret("supabase-ca-cert"), + adminTokenSigningSecret: await fetchSecret("admin-token-signing-secret"), emailClientSecret: await fetchSecret("email-client-secret"), emailRefreshToken: await fetchSecret("email-refresh-token"), r2AccessKeyId: await fetchSecret("r2-access-key-id"), diff --git a/apps/api/src/types/app.types.ts b/apps/api/src/types/app.types.ts index 1f14da7..df9b18a 100644 --- a/apps/api/src/types/app.types.ts +++ b/apps/api/src/types/app.types.ts @@ -1,4 +1,5 @@ import type { S3Client } from "@aws-sdk/client-s3"; +import type { AdminSessionClaims } from "../helpers/adminTokens.js"; import type { StripeSync } from "@supabase/stripe-sync-engine"; import type { SupabaseClient, User } from "@supabase/supabase-js"; import type { Hono } from "hono"; @@ -10,6 +11,7 @@ import type Stripe from "stripe"; */ export type BaseEnv = { Variables: { + adminSession: AdminSessionClaims; supabase: SupabaseClient; s3_client: S3Client; transporter: Transporter; diff --git a/packages/shared-types/src/admin.types.ts b/packages/shared-types/src/admin.types.ts new file mode 100644 index 0000000..1a8859b --- /dev/null +++ b/packages/shared-types/src/admin.types.ts @@ -0,0 +1,17 @@ +export type AdminRole = "viewer" | "operator" | "superadmin"; + +export type AdminSessionResponse = { + expiresAt: string; + operatorEmail: string; + operatorId: string; + role: AdminRole; + sessionToken: string; +}; + +export type AdminSessionInfo = { + aud: string; + exp: number; + operatorEmail: string; + operatorId: string; + role: AdminRole; +}; diff --git a/packages/shared-types/src/index.ts b/packages/shared-types/src/index.ts index fd57e3a..78db254 100644 --- a/packages/shared-types/src/index.ts +++ b/packages/shared-types/src/index.ts @@ -1,4 +1,8 @@ // ============================================================================ +// Admin Types +// ============================================================================ +export type { AdminRole, AdminSessionInfo, AdminSessionResponse } from "./admin.types.js"; +// ============================================================================ // Database Types // ============================================================================ export type { Database, Json } from "./database.types.js"; From 49cdd3b7550f70b4cbba8d563942893386e8bc6d Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Fri, 24 Apr 2026 15:33:13 +0200 Subject: [PATCH 65/75] feat(admin): add privileged token gate --- .../src/components/PrivilegedGate.test.tsx | 49 +++++++++++++ apps/admin/src/components/PrivilegedGate.tsx | 55 ++++++++++++++ apps/admin/src/hooks/useAdminSession.ts | 57 +++++++++++++++ apps/admin/src/lib/adminSession.ts | 38 ++++++++++ apps/admin/src/lib/api.ts | 5 ++ apps/admin/src/routes.tsx | 26 ++++--- pnpm-lock.yaml | 73 +++++++++++++++++++ 7 files changed, 294 insertions(+), 9 deletions(-) create mode 100644 apps/admin/src/components/PrivilegedGate.test.tsx create mode 100644 apps/admin/src/components/PrivilegedGate.tsx create mode 100644 apps/admin/src/hooks/useAdminSession.ts create mode 100644 apps/admin/src/lib/adminSession.ts create mode 100644 apps/admin/src/lib/api.ts diff --git a/apps/admin/src/components/PrivilegedGate.test.tsx b/apps/admin/src/components/PrivilegedGate.test.tsx new file mode 100644 index 0000000..cdd72a5 --- /dev/null +++ b/apps/admin/src/components/PrivilegedGate.test.tsx @@ -0,0 +1,49 @@ +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { MemoryRouter } from "react-router-dom"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import AppRoutes from "../routes"; +import { adminApi } from "../lib/api"; + +vi.mock("../lib/api", () => ({ + adminApi: { + post: vi.fn(), + }, +})); + +describe("PrivilegedGate", () => { + beforeEach(() => { + localStorage.clear(); + vi.clearAllMocks(); + }); + + it("exchanges a privileged token and enters the admin shell", async () => { + vi.mocked(adminApi.post).mockResolvedValue({ + data: { + expiresAt: new Date(Date.now() + 15 * 60 * 1000).toISOString(), + operatorEmail: "ops@xtablo.com", + operatorId: "operator-1", + role: "operator", + sessionToken: "admin-session-token", + }, + }); + + render( + + + + ); + + fireEvent.change(screen.getByLabelText(/access token/i), { + target: { value: "valid-access-token" }, + }); + fireEvent.click(screen.getByRole("button", { name: /unlock admin/i })); + + await waitFor(() => { + expect(adminApi.post).toHaveBeenCalledWith("/admin/auth/exchange", { + accessToken: "valid-access-token", + }); + }); + + expect(await screen.findByText(/operations home/i)).toBeInTheDocument(); + }); +}); diff --git a/apps/admin/src/components/PrivilegedGate.tsx b/apps/admin/src/components/PrivilegedGate.tsx new file mode 100644 index 0000000..c22168f --- /dev/null +++ b/apps/admin/src/components/PrivilegedGate.tsx @@ -0,0 +1,55 @@ +import { FormEvent, useState } from "react"; + +type PrivilegedGateProps = { + error?: string | null; + isPending?: boolean; + onUnlock: (accessToken: string) => Promise; +}; + +export function PrivilegedGate({ + error = null, + isPending = false, + onUnlock, +}: PrivilegedGateProps) { + const [accessToken, setAccessToken] = useState(""); + + const handleSubmit = async (event: FormEvent) => { + event.preventDefault(); + await onUnlock(accessToken); + }; + + return ( +
+
+

Internal Only

+

Admin access token required

+

+ Normal XTablo login is not sufficient. Enter a privileged access token to unlock the + internal admin dashboard. +

+ +
+ + setAccessToken(event.target.value)} + value={accessToken} + /> + + {error ?

{error}

: null} + + +
+
+
+ ); +} diff --git a/apps/admin/src/hooks/useAdminSession.ts b/apps/admin/src/hooks/useAdminSession.ts new file mode 100644 index 0000000..d52845e --- /dev/null +++ b/apps/admin/src/hooks/useAdminSession.ts @@ -0,0 +1,57 @@ +import type { AdminSessionResponse } from "@xtablo/shared-types"; +import { useEffect, useState } from "react"; +import { adminApi } from "../lib/api"; +import { + clearStoredAdminSession, + getStoredAdminSession, + storeAdminSession, + type StoredAdminSession, +} from "../lib/adminSession"; + +export function useAdminSession() { + const [session, setSession] = useState(() => getStoredAdminSession()); + const [isPending, setIsPending] = useState(false); + const [error, setError] = useState(null); + + useEffect(() => { + setSession(getStoredAdminSession()); + }, []); + + const unlock = async (accessToken: string) => { + setIsPending(true); + setError(null); + + try { + const response = await adminApi.post("/admin/auth/exchange", { + accessToken, + }); + + storeAdminSession(response.data); + setSession(response.data); + return response.data; + } catch { + clearStoredAdminSession(); + setSession(null); + setError("Invalid privileged access token"); + return null; + } finally { + setIsPending(false); + } + }; + + const logout = () => { + clearStoredAdminSession(); + setSession(null); + }; + + return { + error, + isAuthenticated: session !== null, + isPending, + logout, + operatorEmail: session?.operatorEmail ?? null, + role: session?.role ?? null, + session, + unlock, + }; +} diff --git a/apps/admin/src/lib/adminSession.ts b/apps/admin/src/lib/adminSession.ts new file mode 100644 index 0000000..5eab8e1 --- /dev/null +++ b/apps/admin/src/lib/adminSession.ts @@ -0,0 +1,38 @@ +import type { AdminRole } from "@xtablo/shared-types"; + +const ADMIN_SESSION_STORAGE_KEY = "xtablo-admin-session"; + +export type StoredAdminSession = { + expiresAt: string; + operatorEmail: string; + operatorId: string; + role: AdminRole; + sessionToken: string; +}; + +export function getStoredAdminSession() { + const rawSession = localStorage.getItem(ADMIN_SESSION_STORAGE_KEY); + if (!rawSession) { + return null; + } + + try { + const parsedSession = JSON.parse(rawSession) as StoredAdminSession; + if (new Date(parsedSession.expiresAt).getTime() <= Date.now()) { + localStorage.removeItem(ADMIN_SESSION_STORAGE_KEY); + return null; + } + return parsedSession; + } catch { + localStorage.removeItem(ADMIN_SESSION_STORAGE_KEY); + return null; + } +} + +export function storeAdminSession(session: StoredAdminSession) { + localStorage.setItem(ADMIN_SESSION_STORAGE_KEY, JSON.stringify(session)); +} + +export function clearStoredAdminSession() { + localStorage.removeItem(ADMIN_SESSION_STORAGE_KEY); +} diff --git a/apps/admin/src/lib/api.ts b/apps/admin/src/lib/api.ts new file mode 100644 index 0000000..b562524 --- /dev/null +++ b/apps/admin/src/lib/api.ts @@ -0,0 +1,5 @@ +import { buildApi } from "@xtablo/shared"; + +const apiBaseUrl = import.meta.env.VITE_API_URL || "http://localhost:8080/api/v1"; + +export const adminApi = buildApi(apiBaseUrl); diff --git a/apps/admin/src/routes.tsx b/apps/admin/src/routes.tsx index 3e30c96..a37f488 100644 --- a/apps/admin/src/routes.tsx +++ b/apps/admin/src/routes.tsx @@ -1,19 +1,27 @@ import { Route, Routes } from "react-router-dom"; +import { PrivilegedGate } from "./components/PrivilegedGate"; +import { useAdminSession } from "./hooks/useAdminSession"; -function PrivilegedGatePlaceholder() { - return ( -
-
-

Admin access token required

-
-
- ); +function AdminEntry() { + const { error, isAuthenticated, isPending, unlock } = useAdminSession(); + + if (isAuthenticated) { + return ( +
+
+

Operations Home

+
+
+ ); + } + + return ; } export default function AppRoutes() { return ( - } /> + } /> ); } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ecad098..74a775a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -24,6 +24,79 @@ importers: specifier: ^5.7.0 version: 5.9.3 + apps/admin: + dependencies: + '@tanstack/react-query': + specifier: ^5.69.0 + version: 5.90.5(react@19.0.0) + '@xtablo/shared': + specifier: workspace:* + version: link:../../packages/shared + '@xtablo/shared-types': + specifier: workspace:* + version: link:../../packages/shared-types + '@xtablo/ui': + specifier: workspace:* + version: link:../../packages/ui + react: + specifier: 19.0.0 + version: 19.0.0 + react-dom: + specifier: 19.0.0 + version: 19.0.0(react@19.0.0) + react-router-dom: + specifier: ^7.9.4 + version: 7.9.4(react-dom@19.0.0(react@19.0.0))(react@19.0.0) + devDependencies: + '@biomejs/biome': + specifier: 2.2.5 + version: 2.2.5 + '@cloudflare/vite-plugin': + specifier: ^1.9.4 + version: 1.13.14(vite@6.4.1(@types/node@22.18.12)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6))(workerd@1.20251011.0)(wrangler@4.44.0(@cloudflare/workers-types@4.20260411.1)) + '@tailwindcss/vite': + specifier: ^4.0.14 + version: 4.1.15(vite@6.4.1(@types/node@22.18.12)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6)) + '@testing-library/jest-dom': + specifier: ^6.6.3 + version: 6.9.1 + '@testing-library/react': + specifier: ^16.3.0 + version: 16.3.0(@testing-library/dom@10.4.1)(@types/react-dom@19.0.4(@types/react@19.0.10))(@types/react@19.0.10)(react-dom@19.0.0(react@19.0.0))(react@19.0.0) + '@types/react': + specifier: 19.0.10 + version: 19.0.10 + '@types/react-dom': + specifier: 19.0.4 + version: 19.0.4(@types/react@19.0.10) + '@vitejs/plugin-react': + specifier: ^4.3.4 + version: 4.7.0(vite@6.4.1(@types/node@22.18.12)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6)) + happy-dom: + specifier: ^20.0.0 + version: 20.0.7 + tailwindcss: + specifier: ^4.0.14 + version: 4.1.15 + tw-animate-css: + specifier: ^1.4.0 + version: 1.4.0 + typescript: + specifier: ^5.7.0 + version: 5.9.3 + vite: + specifier: ^6.2.2 + version: 6.4.1(@types/node@22.18.12)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6) + vite-tsconfig-paths: + specifier: ^5.1.4 + version: 5.1.4(typescript@5.9.3)(vite@6.4.1(@types/node@22.18.12)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6)) + vitest: + specifier: ^3.2.4 + version: 3.2.4(@types/debug@4.1.12)(@types/node@22.18.12)(happy-dom@20.0.7)(jiti@2.6.1)(jsdom@20.0.3)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6) + wrangler: + specifier: ^4.24.3 + version: 4.44.0(@cloudflare/workers-types@4.20260411.1) + apps/api: dependencies: '@aws-sdk/client-s3': From 4f71c52e145b89f6ca3a7f148ad73c4dd6877a1a Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Fri, 24 Apr 2026 15:39:03 +0200 Subject: [PATCH 66/75] feat(admin): add explorer shell and registry reads --- .../admin/src/components/AdminLayout.test.tsx | 33 +++++++ apps/admin/src/components/AdminLayout.tsx | 29 ++++++ apps/admin/src/components/AdminNavigation.tsx | 30 ++++++ .../src/components/PrivilegedGate.test.tsx | 2 +- apps/admin/src/components/ProductionBadge.tsx | 7 ++ .../components/data-explorer/AdminGrid.tsx | 39 ++++++++ apps/admin/src/hooks/useAdminTables.ts | 94 ++++++++++++++++++ apps/admin/src/lib/api.ts | 11 +++ apps/admin/src/pages/ActionCenterPage.tsx | 11 +++ apps/admin/src/pages/AnalyticsStudioPage.tsx | 11 +++ .../admin/src/pages/DataExplorerPage.test.tsx | 71 ++++++++++++++ apps/admin/src/pages/DataExplorerPage.tsx | 43 ++++++++ apps/admin/src/pages/OperationsHomePage.tsx | 13 +++ apps/admin/src/routes.tsx | 24 +++-- .../src/__tests__/routes/adminTables.test.ts | 98 +++++++++++++++++++ apps/api/src/helpers/adminRegistry.ts | 53 ++++++++++ apps/api/src/routers/admin.ts | 1 + apps/api/src/routers/adminTables.ts | 54 +++++++++- packages/shared-types/src/admin.types.ts | 16 +++ packages/shared-types/src/index.ts | 9 +- 20 files changed, 635 insertions(+), 14 deletions(-) create mode 100644 apps/admin/src/components/AdminLayout.test.tsx create mode 100644 apps/admin/src/components/AdminLayout.tsx create mode 100644 apps/admin/src/components/AdminNavigation.tsx create mode 100644 apps/admin/src/components/ProductionBadge.tsx create mode 100644 apps/admin/src/components/data-explorer/AdminGrid.tsx create mode 100644 apps/admin/src/hooks/useAdminTables.ts create mode 100644 apps/admin/src/pages/ActionCenterPage.tsx create mode 100644 apps/admin/src/pages/AnalyticsStudioPage.tsx create mode 100644 apps/admin/src/pages/DataExplorerPage.test.tsx create mode 100644 apps/admin/src/pages/DataExplorerPage.tsx create mode 100644 apps/admin/src/pages/OperationsHomePage.tsx create mode 100644 apps/api/src/__tests__/routes/adminTables.test.ts create mode 100644 apps/api/src/helpers/adminRegistry.ts diff --git a/apps/admin/src/components/AdminLayout.test.tsx b/apps/admin/src/components/AdminLayout.test.tsx new file mode 100644 index 0000000..dc014f8 --- /dev/null +++ b/apps/admin/src/components/AdminLayout.test.tsx @@ -0,0 +1,33 @@ +import { render, screen } from "@testing-library/react"; +import { MemoryRouter } from "react-router-dom"; +import { beforeEach, describe, expect, it } from "vitest"; +import AppRoutes from "../routes"; +import { storeAdminSession } from "../lib/adminSession"; + +describe("AdminLayout", () => { + beforeEach(() => { + localStorage.clear(); + storeAdminSession({ + expiresAt: new Date(Date.now() + 15 * 60 * 1000).toISOString(), + operatorEmail: "ops@xtablo.com", + operatorId: "operator-1", + role: "operator", + sessionToken: "admin-session-token", + }); + }); + + it("shows the production badge and admin sections", async () => { + render( + + + + ); + + expect(await screen.findByText(/^production$/i)).toBeInTheDocument(); + expect(screen.getByRole("heading", { name: /operations home/i })).toBeInTheDocument(); + expect(screen.getByRole("link", { name: /operations home/i })).toBeInTheDocument(); + expect(screen.getByRole("link", { name: /data explorer/i })).toBeInTheDocument(); + expect(screen.getByRole("link", { name: /analytics studio/i })).toBeInTheDocument(); + expect(screen.getByRole("link", { name: /action center/i })).toBeInTheDocument(); + }); +}); diff --git a/apps/admin/src/components/AdminLayout.tsx b/apps/admin/src/components/AdminLayout.tsx new file mode 100644 index 0000000..4133974 --- /dev/null +++ b/apps/admin/src/components/AdminLayout.tsx @@ -0,0 +1,29 @@ +import { Outlet } from "react-router-dom"; +import { useAdminSession } from "../hooks/useAdminSession"; +import { AdminNavigation } from "./AdminNavigation"; +import { ProductionBadge } from "./ProductionBadge"; + +export function AdminLayout() { + const { operatorEmail } = useAdminSession(); + + return ( +
+
+ + +
+ +
+
+
+ ); +} diff --git a/apps/admin/src/components/AdminNavigation.tsx b/apps/admin/src/components/AdminNavigation.tsx new file mode 100644 index 0000000..c004fe8 --- /dev/null +++ b/apps/admin/src/components/AdminNavigation.tsx @@ -0,0 +1,30 @@ +import { NavLink } from "react-router-dom"; + +const navItems = [ + { label: "Operations Home", to: "/" }, + { label: "Data Explorer", to: "/explorer" }, + { label: "Analytics Studio", to: "/analytics" }, + { label: "Action Center", to: "/actions" }, +]; + +export function AdminNavigation() { + return ( + + ); +} diff --git a/apps/admin/src/components/PrivilegedGate.test.tsx b/apps/admin/src/components/PrivilegedGate.test.tsx index cdd72a5..04aa323 100644 --- a/apps/admin/src/components/PrivilegedGate.test.tsx +++ b/apps/admin/src/components/PrivilegedGate.test.tsx @@ -44,6 +44,6 @@ describe("PrivilegedGate", () => { }); }); - expect(await screen.findByText(/operations home/i)).toBeInTheDocument(); + expect(await screen.findByRole("heading", { name: /operations home/i })).toBeInTheDocument(); }); }); diff --git a/apps/admin/src/components/ProductionBadge.tsx b/apps/admin/src/components/ProductionBadge.tsx new file mode 100644 index 0000000..7583812 --- /dev/null +++ b/apps/admin/src/components/ProductionBadge.tsx @@ -0,0 +1,7 @@ +export function ProductionBadge() { + return ( +
+ Production +
+ ); +} diff --git a/apps/admin/src/components/data-explorer/AdminGrid.tsx b/apps/admin/src/components/data-explorer/AdminGrid.tsx new file mode 100644 index 0000000..9c8f46e --- /dev/null +++ b/apps/admin/src/components/data-explorer/AdminGrid.tsx @@ -0,0 +1,39 @@ +import type { AdminTableMeta } from "@xtablo/shared-types"; + +type AdminGridProps = { + meta: AdminTableMeta | null; + rows: Record[]; +}; + +export function AdminGrid({ meta, rows }: AdminGridProps) { + if (!meta) { + return null; + } + + return ( +
+ + + + {meta.columns.map((column) => ( + + ))} + + + + {rows.map((row, index) => ( + + {meta.columns.map((column) => ( + + ))} + + ))} + +
+ {column.label} +
+ {String(row[column.id] ?? "")} +
+
+ ); +} diff --git a/apps/admin/src/hooks/useAdminTables.ts b/apps/admin/src/hooks/useAdminTables.ts new file mode 100644 index 0000000..cf21114 --- /dev/null +++ b/apps/admin/src/hooks/useAdminTables.ts @@ -0,0 +1,94 @@ +import type { AdminTableMeta, AdminTableSummary } from "@xtablo/shared-types"; +import { useEffect, useState } from "react"; +import { adminApi } from "../lib/api"; + +type AdminRow = Record; + +export function useAdminTables() { + const [tables, setTables] = useState([]); + const [selectedTableId, setSelectedTableId] = useState(null); + const [meta, setMeta] = useState(null); + const [rows, setRows] = useState([]); + const [isLoading, setIsLoading] = useState(true); + const [error, setError] = useState(null); + + useEffect(() => { + let isMounted = true; + + const loadTables = async () => { + try { + const response = await adminApi.get<{ tables: AdminTableSummary[] }>("/admin/tables"); + if (!isMounted) { + return; + } + + setTables(response.data.tables); + setSelectedTableId((currentValue) => currentValue ?? response.data.tables[0]?.id ?? null); + } catch { + if (isMounted) { + setError("Failed to load admin tables"); + } + } + }; + + void loadTables(); + + return () => { + isMounted = false; + }; + }, []); + + useEffect(() => { + let isMounted = true; + + const loadTableData = async () => { + if (!selectedTableId) { + setIsLoading(false); + return; + } + + setIsLoading(true); + setError(null); + + try { + const [metaResponse, rowsResponse] = await Promise.all([ + adminApi.get(`/admin/tables/${selectedTableId}/meta`), + adminApi.get<{ rows: AdminRow[] }>(`/admin/tables/${selectedTableId}/rows`), + ]); + + if (!isMounted) { + return; + } + + setMeta(metaResponse.data); + setRows(rowsResponse.data.rows); + } catch { + if (isMounted) { + setError("Failed to load admin table data"); + setMeta(null); + setRows([]); + } + } finally { + if (isMounted) { + setIsLoading(false); + } + } + }; + + void loadTableData(); + + return () => { + isMounted = false; + }; + }, [selectedTableId]); + + return { + error, + isLoading, + meta, + rows, + selectedTableId, + setSelectedTableId, + tables, + }; +} diff --git a/apps/admin/src/lib/api.ts b/apps/admin/src/lib/api.ts index b562524..7db3ca1 100644 --- a/apps/admin/src/lib/api.ts +++ b/apps/admin/src/lib/api.ts @@ -1,5 +1,16 @@ import { buildApi } from "@xtablo/shared"; +import { getStoredAdminSession } from "./adminSession"; const apiBaseUrl = import.meta.env.VITE_API_URL || "http://localhost:8080/api/v1"; export const adminApi = buildApi(apiBaseUrl); + +adminApi.interceptors.request.use((config) => { + const adminSession = getStoredAdminSession(); + + if (adminSession) { + config.headers.Authorization = `Bearer ${adminSession.sessionToken}`; + } + + return config; +}); diff --git a/apps/admin/src/pages/ActionCenterPage.tsx b/apps/admin/src/pages/ActionCenterPage.tsx new file mode 100644 index 0000000..19107ca --- /dev/null +++ b/apps/admin/src/pages/ActionCenterPage.tsx @@ -0,0 +1,11 @@ +export function ActionCenterPage() { + return ( +
+

Actions

+

Action Center

+

+ High-impact repair and resync workflows will run from this controlled surface. +

+
+ ); +} diff --git a/apps/admin/src/pages/AnalyticsStudioPage.tsx b/apps/admin/src/pages/AnalyticsStudioPage.tsx new file mode 100644 index 0000000..7ef381a --- /dev/null +++ b/apps/admin/src/pages/AnalyticsStudioPage.tsx @@ -0,0 +1,11 @@ +export function AnalyticsStudioPage() { + return ( +
+

Analytics

+

Analytics Studio

+

+ Curated operational datasets and chart building land here next. +

+
+ ); +} diff --git a/apps/admin/src/pages/DataExplorerPage.test.tsx b/apps/admin/src/pages/DataExplorerPage.test.tsx new file mode 100644 index 0000000..0337663 --- /dev/null +++ b/apps/admin/src/pages/DataExplorerPage.test.tsx @@ -0,0 +1,71 @@ +import { render, screen } from "@testing-library/react"; +import { MemoryRouter } from "react-router-dom"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { adminApi } from "../lib/api"; +import { DataExplorerPage } from "./DataExplorerPage"; + +vi.mock("../lib/api", () => ({ + adminApi: { + get: vi.fn(), + }, +})); + +describe("DataExplorerPage", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("loads rows for the selected table", async () => { + vi.mocked(adminApi.get).mockImplementation(async (path: string) => { + if (path === "/admin/tables") { + return { + data: { + tables: [ + { id: "profiles", label: "Users" }, + { id: "tablo_access", label: "Tablo Access" }, + ], + }, + }; + } + + if (path === "/admin/tables/profiles/meta") { + return { + data: { + columns: [ + { id: "email", label: "Email" }, + { id: "first_name", label: "First name" }, + ], + id: "profiles", + label: "Users", + }, + }; + } + + if (path === "/admin/tables/profiles/rows") { + return { + data: { + rows: [ + { + email: "test_owner@example.com", + first_name: "Test", + id: "user-1", + }, + ], + }, + }; + } + + throw new Error(`Unexpected path: ${path}`); + }); + + render( + + + + ); + + expect(await screen.findByRole("button", { name: /users/i })).toBeInTheDocument(); + expect(await screen.findByText(/email/i)).toBeInTheDocument(); + expect(await screen.findByText(/test_owner@example.com/i)).toBeInTheDocument(); + }); +}); diff --git a/apps/admin/src/pages/DataExplorerPage.tsx b/apps/admin/src/pages/DataExplorerPage.tsx new file mode 100644 index 0000000..d928f12 --- /dev/null +++ b/apps/admin/src/pages/DataExplorerPage.tsx @@ -0,0 +1,43 @@ +import { AdminGrid } from "../components/data-explorer/AdminGrid"; +import { useAdminTables } from "../hooks/useAdminTables"; + +export function DataExplorerPage() { + const { error, isLoading, meta, rows, selectedTableId, setSelectedTableId, tables } = + useAdminTables(); + + return ( +
+
+ + +
+
+

{meta?.label ?? "Explorer"}

+

+ Approved production tables exposed through the internal admin registry. +

+
+ + {isLoading ?

Loading explorer...

: null} + {error ?

{error}

: null} + {!isLoading && !error ? : null} +
+
+
+ ); +} diff --git a/apps/admin/src/pages/OperationsHomePage.tsx b/apps/admin/src/pages/OperationsHomePage.tsx new file mode 100644 index 0000000..8caeb92 --- /dev/null +++ b/apps/admin/src/pages/OperationsHomePage.tsx @@ -0,0 +1,13 @@ +export function OperationsHomePage() { + return ( +
+
+

Operations

+

Operations Home

+
+

+ Internal production oversight, anomaly checks, and shortcuts into the admin workflows. +

+
+ ); +} diff --git a/apps/admin/src/routes.tsx b/apps/admin/src/routes.tsx index a37f488..b637b3b 100644 --- a/apps/admin/src/routes.tsx +++ b/apps/admin/src/routes.tsx @@ -1,4 +1,9 @@ -import { Route, Routes } from "react-router-dom"; +import { Outlet, Route, Routes } from "react-router-dom"; +import { ActionCenterPage } from "./pages/ActionCenterPage"; +import { AnalyticsStudioPage } from "./pages/AnalyticsStudioPage"; +import { DataExplorerPage } from "./pages/DataExplorerPage"; +import { OperationsHomePage } from "./pages/OperationsHomePage"; +import { AdminLayout } from "./components/AdminLayout"; import { PrivilegedGate } from "./components/PrivilegedGate"; import { useAdminSession } from "./hooks/useAdminSession"; @@ -6,13 +11,7 @@ function AdminEntry() { const { error, isAuthenticated, isPending, unlock } = useAdminSession(); if (isAuthenticated) { - return ( -
-
-

Operations Home

-
-
- ); + return ; } return ; @@ -21,7 +20,14 @@ function AdminEntry() { export default function AppRoutes() { return ( - } /> + }> + }> + } /> + } /> + } /> + } /> + + ); } diff --git a/apps/api/src/__tests__/routes/adminTables.test.ts b/apps/api/src/__tests__/routes/adminTables.test.ts new file mode 100644 index 0000000..f3d7603 --- /dev/null +++ b/apps/api/src/__tests__/routes/adminTables.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it } from "vitest"; +import { createSignedAdminToken } from "../helpers/adminTokenTestUtils.js"; +import { createConfig } from "../../config.js"; +import { MiddlewareManager } from "../../middlewares/middleware.js"; +import { getMainRouter } from "../../routers/index.js"; + +const ADMIN_TOKEN_SIGNING_SECRET = "admin-test-secret"; +const ADMIN_TOKEN_AUDIENCE = "xtablo-admin"; + +describe("Admin Tables Router", () => { + process.env.ADMIN_TOKEN_SIGNING_SECRET = ADMIN_TOKEN_SIGNING_SECRET; + process.env.ADMIN_TOKEN_AUDIENCE = ADMIN_TOKEN_AUDIENCE; + process.env.ADMIN_APP_URL = "http://localhost:5176"; + + const config = createConfig(); + MiddlewareManager.initialize(config); + const app = getMainRouter(config); + + const sessionToken = createSignedAdminToken( + { + aud: ADMIN_TOKEN_AUDIENCE, + email: "ops@xtablo.com", + exp: Math.floor(Date.now() / 1000) + 900, + role: "operator", + sub: "operator-1", + type: "admin_session", + }, + ADMIN_TOKEN_SIGNING_SECRET + ); + + it("lists only approved admin tables", async () => { + const res = await app.request("/admin/tables", { + headers: { + Authorization: `Bearer ${sessionToken}`, + }, + }); + + expect(res.status).toBe(200); + await expect(res.json()).resolves.toMatchObject({ + tables: expect.arrayContaining([ + expect.objectContaining({ + id: "profiles", + label: "Users", + }), + ]), + }); + }); + + it("returns metadata for an approved table", async () => { + const res = await app.request("/admin/tables/profiles/meta", { + headers: { + Authorization: `Bearer ${sessionToken}`, + }, + }); + + expect(res.status).toBe(200); + await expect(res.json()).resolves.toMatchObject({ + id: "profiles", + label: "Users", + columns: expect.arrayContaining([ + expect.objectContaining({ + id: "email", + label: "Email", + }), + ]), + }); + }); + + it("returns rows for an approved table", async () => { + const res = await app.request("/admin/tables/profiles/rows", { + headers: { + Authorization: `Bearer ${sessionToken}`, + }, + }); + + expect(res.status).toBe(200); + await expect(res.json()).resolves.toMatchObject({ + rows: expect.arrayContaining([ + expect.objectContaining({ + email: "test_owner@example.com", + }), + ]), + }); + }); + + it("rejects tables that are not in the registry", async () => { + const res = await app.request("/admin/tables/secrets/meta", { + headers: { + Authorization: `Bearer ${sessionToken}`, + }, + }); + + expect(res.status).toBe(404); + await expect(res.json()).resolves.toMatchObject({ + error: "Admin table 'secrets' is not registered", + }); + }); +}); diff --git a/apps/api/src/helpers/adminRegistry.ts b/apps/api/src/helpers/adminRegistry.ts new file mode 100644 index 0000000..bf2b52f --- /dev/null +++ b/apps/api/src/helpers/adminRegistry.ts @@ -0,0 +1,53 @@ +import type { Database } from "@xtablo/shared-types"; + +type AdminTableColumn = { + id: string; + label: string; +}; + +type AdminTableDefinition = { + columns: AdminTableColumn[]; + id: string; + label: string; + select: string; + source: keyof Database["public"]["Tables"]; +}; + +export const adminTableRegistry: Record = { + profiles: { + columns: [ + { id: "id", label: "ID" }, + { id: "email", label: "Email" }, + { id: "first_name", label: "First name" }, + { id: "last_name", label: "Last name" }, + ], + id: "profiles", + label: "Users", + select: "id,email,first_name,last_name", + source: "profiles", + }, + tablo_access: { + columns: [ + { id: "tablo_id", label: "Tablo ID" }, + { id: "user_id", label: "User ID" }, + { id: "is_active", label: "Active" }, + { id: "is_admin", label: "Admin" }, + ], + id: "tablo_access", + label: "Tablo Access", + select: "tablo_id,user_id,is_active,is_admin", + source: "tablo_access", + }, +}; + +export function getAdminTableDefinition(tableId: string) { + return adminTableRegistry[tableId] ?? null; +} + +export function listAdminTables() { + return Object.values(adminTableRegistry).map(({ id, label }) => ({ id, label })); +} + +export function normalizeAdminRows(rows: unknown[]) { + return rows as Record[]; +} diff --git a/apps/api/src/routers/admin.ts b/apps/api/src/routers/admin.ts index 1eb8f8b..c1eb040 100644 --- a/apps/api/src/routers/admin.ts +++ b/apps/api/src/routers/admin.ts @@ -11,6 +11,7 @@ export const getAdminRouter = (config: AppConfig) => { adminRouter.route("/auth", getAdminAuthRouter(config)); + adminRouter.use("/tables", middlewareManager.adminAuth); adminRouter.use("/tables/*", middlewareManager.adminAuth); adminRouter.route("/tables", getAdminTablesRouter()); diff --git a/apps/api/src/routers/adminTables.ts b/apps/api/src/routers/adminTables.ts index 29709f0..02ec6ea 100644 --- a/apps/api/src/routers/adminTables.ts +++ b/apps/api/src/routers/adminTables.ts @@ -1,19 +1,67 @@ import { Hono } from "hono"; +import { getAdminTableDefinition, listAdminTables, normalizeAdminRows } from "../helpers/adminRegistry.js"; import type { BaseEnv } from "../types/app.types.js"; export const getAdminTablesRouter = () => { const adminTablesRouter = new Hono(); - adminTablesRouter.get("/:tableId", async (c) => { + adminTablesRouter.get("/", async (c) => { + return c.json({ tables: listAdminTables() }, 200); + }); + + adminTablesRouter.get("/:tableId/meta", async (c) => { const tableId = c.req.param("tableId"); + const tableDefinition = getAdminTableDefinition(tableId); + + if (!tableDefinition) { + return c.json( + { + error: `Admin table '${tableId}' is not registered`, + }, + 404 + ); + } return c.json( { - error: `Admin table '${tableId}' is not implemented yet`, + columns: tableDefinition.columns, + id: tableDefinition.id, + label: tableDefinition.label, }, - 501 + 200 ); }); + adminTablesRouter.get("/:tableId/rows", async (c) => { + const supabase = c.get("supabase"); + const tableId = c.req.param("tableId"); + const tableDefinition = getAdminTableDefinition(tableId); + + if (!tableDefinition) { + return c.json( + { + error: `Admin table '${tableId}' is not registered`, + }, + 404 + ); + } + + const { data, error } = await supabase + .from(tableDefinition.source) + .select(tableDefinition.select) + .limit(50); + + if (error) { + return c.json( + { + error: `Failed to load admin table '${tableId}'`, + }, + 500 + ); + } + + return c.json({ rows: normalizeAdminRows(data ?? []) }, 200); + }); + return adminTablesRouter; }; diff --git a/packages/shared-types/src/admin.types.ts b/packages/shared-types/src/admin.types.ts index 1a8859b..2859ec8 100644 --- a/packages/shared-types/src/admin.types.ts +++ b/packages/shared-types/src/admin.types.ts @@ -15,3 +15,19 @@ export type AdminSessionInfo = { operatorId: string; role: AdminRole; }; + +export type AdminTableSummary = { + id: string; + label: string; +}; + +export type AdminTableColumn = { + id: string; + label: string; +}; + +export type AdminTableMeta = { + columns: AdminTableColumn[]; + id: string; + label: string; +}; diff --git a/packages/shared-types/src/index.ts b/packages/shared-types/src/index.ts index 78db254..11a7446 100644 --- a/packages/shared-types/src/index.ts +++ b/packages/shared-types/src/index.ts @@ -1,7 +1,14 @@ // ============================================================================ // Admin Types // ============================================================================ -export type { AdminRole, AdminSessionInfo, AdminSessionResponse } from "./admin.types.js"; +export type { + AdminRole, + AdminSessionInfo, + AdminSessionResponse, + AdminTableColumn, + AdminTableMeta, + AdminTableSummary, +} from "./admin.types.js"; // ============================================================================ // Database Types // ============================================================================ From 85d44af57e06585e26dd1954cac2ba2cad529415 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Fri, 24 Apr 2026 15:55:56 +0200 Subject: [PATCH 67/75] feat(admin): add dashboard explorer analytics and actions --- .../admin/src/components/AdminLayout.test.tsx | 21 ++- .../src/components/PrivilegedGate.test.tsx | 14 +- .../src/components/actions/ActionRunner.tsx | 133 ++++++++++++++ .../src/components/analytics/ChartBuilder.tsx | 173 ++++++++++++++++++ .../analytics/SavedDashboardList.tsx | 35 ++++ .../components/data-explorer/AdminGrid.tsx | 12 +- .../data-explorer/RowEditForm.test.tsx | 43 +++++ .../components/data-explorer/RowEditForm.tsx | 115 ++++++++++++ apps/admin/src/hooks/useAdminActions.ts | 98 ++++++++++ apps/admin/src/hooks/useAdminDatasets.ts | 105 +++++++++++ apps/admin/src/hooks/useAdminOverview.ts | 44 +++++ apps/admin/src/hooks/useAdminTables.ts | 53 +++++- .../admin/src/pages/ActionCenterPage.test.tsx | 69 +++++++ apps/admin/src/pages/ActionCenterPage.tsx | 48 ++++- .../src/pages/AnalyticsStudioPage.test.tsx | 87 +++++++++ apps/admin/src/pages/AnalyticsStudioPage.tsx | 39 +++- .../admin/src/pages/DataExplorerPage.test.tsx | 31 +++- apps/admin/src/pages/DataExplorerPage.tsx | 125 ++++++++++++- apps/admin/src/pages/OperationsHomePage.tsx | 95 +++++++++- apps/admin/src/registry/actions.ts | 10 + apps/admin/src/registry/datasets.ts | 20 ++ .../src/__tests__/routes/adminActions.test.ts | 64 +++++++ .../__tests__/routes/adminDatasets.test.ts | 64 +++++++ .../__tests__/routes/adminTableEdits.test.ts | 72 ++++++++ .../src/__tests__/routes/adminTables.test.ts | 2 + apps/api/src/helpers/adminAudit.ts | 42 +++++ apps/api/src/helpers/adminRegistry.ts | 93 ++++++++++ apps/api/src/routers/admin.ts | 13 ++ apps/api/src/routers/adminActions.ts | 109 +++++++++++ apps/api/src/routers/adminDatasets.ts | 155 ++++++++++++++++ apps/api/src/routers/adminOverview.ts | 144 +++++++++++++++ apps/api/src/routers/adminTables.ts | 74 +++++++- docs/ADMIN_APP_ACCESS_SETUP.md | 56 ++++++ packages/shared-types/src/admin.types.ts | 67 +++++++ packages/shared-types/src/index.ts | 11 ++ .../20260424110000_create_admin_audit_log.sql | 12 ++ 36 files changed, 2313 insertions(+), 35 deletions(-) create mode 100644 apps/admin/src/components/actions/ActionRunner.tsx create mode 100644 apps/admin/src/components/analytics/ChartBuilder.tsx create mode 100644 apps/admin/src/components/analytics/SavedDashboardList.tsx create mode 100644 apps/admin/src/components/data-explorer/RowEditForm.test.tsx create mode 100644 apps/admin/src/components/data-explorer/RowEditForm.tsx create mode 100644 apps/admin/src/hooks/useAdminActions.ts create mode 100644 apps/admin/src/hooks/useAdminDatasets.ts create mode 100644 apps/admin/src/hooks/useAdminOverview.ts create mode 100644 apps/admin/src/pages/ActionCenterPage.test.tsx create mode 100644 apps/admin/src/pages/AnalyticsStudioPage.test.tsx create mode 100644 apps/admin/src/registry/actions.ts create mode 100644 apps/admin/src/registry/datasets.ts create mode 100644 apps/api/src/__tests__/routes/adminActions.test.ts create mode 100644 apps/api/src/__tests__/routes/adminDatasets.test.ts create mode 100644 apps/api/src/__tests__/routes/adminTableEdits.test.ts create mode 100644 apps/api/src/helpers/adminAudit.ts create mode 100644 apps/api/src/routers/adminActions.ts create mode 100644 apps/api/src/routers/adminDatasets.ts create mode 100644 apps/api/src/routers/adminOverview.ts create mode 100644 docs/ADMIN_APP_ACCESS_SETUP.md create mode 100644 supabase/migrations/20260424110000_create_admin_audit_log.sql diff --git a/apps/admin/src/components/AdminLayout.test.tsx b/apps/admin/src/components/AdminLayout.test.tsx index dc014f8..b9c5998 100644 --- a/apps/admin/src/components/AdminLayout.test.tsx +++ b/apps/admin/src/components/AdminLayout.test.tsx @@ -1,12 +1,20 @@ import { render, screen } from "@testing-library/react"; import { MemoryRouter } from "react-router-dom"; -import { beforeEach, describe, expect, it } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import AppRoutes from "../routes"; +import { adminApi } from "../lib/api"; import { storeAdminSession } from "../lib/adminSession"; +vi.mock("../lib/api", () => ({ + adminApi: { + get: vi.fn(), + }, +})); + describe("AdminLayout", () => { beforeEach(() => { localStorage.clear(); + vi.clearAllMocks(); storeAdminSession({ expiresAt: new Date(Date.now() + 15 * 60 * 1000).toISOString(), operatorEmail: "ops@xtablo.com", @@ -14,6 +22,13 @@ describe("AdminLayout", () => { role: "operator", sessionToken: "admin-session-token", }); + vi.mocked(adminApi.get).mockResolvedValue({ + data: { + alerts: [], + metrics: [], + shortcuts: [], + }, + }); }); it("shows the production badge and admin sections", async () => { @@ -24,7 +39,9 @@ describe("AdminLayout", () => { ); expect(await screen.findByText(/^production$/i)).toBeInTheDocument(); - expect(screen.getByRole("heading", { name: /operations home/i })).toBeInTheDocument(); + expect( + screen.getByRole("heading", { name: /production command deck for privileged supabase operations/i }) + ).toBeInTheDocument(); expect(screen.getByRole("link", { name: /operations home/i })).toBeInTheDocument(); expect(screen.getByRole("link", { name: /data explorer/i })).toBeInTheDocument(); expect(screen.getByRole("link", { name: /analytics studio/i })).toBeInTheDocument(); diff --git a/apps/admin/src/components/PrivilegedGate.test.tsx b/apps/admin/src/components/PrivilegedGate.test.tsx index 04aa323..60c1687 100644 --- a/apps/admin/src/components/PrivilegedGate.test.tsx +++ b/apps/admin/src/components/PrivilegedGate.test.tsx @@ -6,6 +6,7 @@ import { adminApi } from "../lib/api"; vi.mock("../lib/api", () => ({ adminApi: { + get: vi.fn(), post: vi.fn(), }, })); @@ -14,6 +15,13 @@ describe("PrivilegedGate", () => { beforeEach(() => { localStorage.clear(); vi.clearAllMocks(); + vi.mocked(adminApi.get).mockResolvedValue({ + data: { + alerts: [], + metrics: [], + shortcuts: [], + }, + }); }); it("exchanges a privileged token and enters the admin shell", async () => { @@ -44,6 +52,10 @@ describe("PrivilegedGate", () => { }); }); - expect(await screen.findByRole("heading", { name: /operations home/i })).toBeInTheDocument(); + expect( + await screen.findByRole("heading", { + name: /production command deck for privileged supabase operations/i, + }) + ).toBeInTheDocument(); }); }); diff --git a/apps/admin/src/components/actions/ActionRunner.tsx b/apps/admin/src/components/actions/ActionRunner.tsx new file mode 100644 index 0000000..a656aec --- /dev/null +++ b/apps/admin/src/components/actions/ActionRunner.tsx @@ -0,0 +1,133 @@ +import type { AdminActionSummary } from "@xtablo/shared-types"; +import { useEffect, useMemo, useState } from "react"; +import { actionSeverityCopy } from "../../registry/actions"; + +type ActionRunnerProps = { + actions: AdminActionSummary[]; + error: string | null; + isRunning: boolean; + onRun: (payload: Record) => Promise; + onSelectActionId: (actionId: string) => void; + resultMessage: string | null; + selectedActionId: string | null; +}; + +export function ActionRunner({ + actions, + error, + isRunning, + onRun, + onSelectActionId, + resultMessage, + selectedActionId, +}: ActionRunnerProps) { + const selectedAction = useMemo( + () => actions.find((action) => action.id === selectedActionId) ?? null, + [actions, selectedActionId] + ); + const [values, setValues] = useState>({}); + + useEffect(() => { + if (!selectedAction) { + return; + } + + setValues( + Object.fromEntries(selectedAction.fields.map((field) => [field.id, ""])) + ); + }, [selectedAction]); + + const tone = selectedAction ? actionSeverityCopy[selectedAction.id as keyof typeof actionSeverityCopy] : null; + + return ( +
+ + +
+ {selectedAction ? ( +
{ + event.preventDefault(); + void onRun(values); + }} + > +
+
+

Action

+

{selectedAction.label}

+

+ {selectedAction.description} +

+
+ {tone ? ( + + {tone.badge} + + ) : null} +
+ +
+ {selectedAction.fields.map((field) => ( + + ))} +
+ + {error ?

{error}

: null} + {resultMessage ?

{resultMessage}

: null} + + +
+ ) : ( +

Select an action to begin.

+ )} +
+
+ ); +} diff --git a/apps/admin/src/components/analytics/ChartBuilder.tsx b/apps/admin/src/components/analytics/ChartBuilder.tsx new file mode 100644 index 0000000..9a60cad --- /dev/null +++ b/apps/admin/src/components/analytics/ChartBuilder.tsx @@ -0,0 +1,173 @@ +import type { AdminDatasetPoint, AdminDatasetResult, AdminDatasetSummary } from "@xtablo/shared-types"; + +type ChartBuilderProps = { + dataset: AdminDatasetResult | null; + datasets: AdminDatasetSummary[]; + onSelectDatasetId: (datasetId: string) => void; + selectedDatasetId: string | null; +}; + +function BarChart({ points }: { points: AdminDatasetPoint[] }) { + const maxValue = Math.max(...points.map((point) => point.value), 1); + + return ( +
+ {points.map((point) => ( +
+
+
+

{point.value}

+

+ {point.label} +

+
+
+ ))} +
+ ); +} + +function LineChart({ points }: { points: AdminDatasetPoint[] }) { + const width = 560; + const height = 220; + const maxValue = Math.max(...points.map((point) => point.value), 1); + const polyline = points + .map((point, index) => { + const x = points.length === 1 ? width / 2 : (index / (points.length - 1)) * width; + const y = height - (point.value / maxValue) * (height - 24) - 12; + return `${x},${y}`; + }) + .join(" "); + + return ( +
+ + + {points.map((point, index) => { + const x = points.length === 1 ? width / 2 : (index / (points.length - 1)) * width; + const y = height - (point.value / maxValue) * (height - 24) - 12; + + return ; + })} + +
+ {points.map((point) => ( +
+

{point.label}

+

{point.value}

+
+ ))} +
+
+ ); +} + +function DonutChart({ points }: { points: AdminDatasetPoint[] }) { + const total = points.reduce((sum, point) => sum + point.value, 0) || 1; + const palette = ["#172554", "#0f766e", "#b45309", "#7c2d12", "#475569"]; + let currentStop = 0; + const gradientStops = points + .map((point, index) => { + const start = currentStop; + currentStop += (point.value / total) * 100; + return `${palette[index % palette.length]} ${start}% ${currentStop}%`; + }) + .join(", "); + + return ( +
+
+
+
+

Total

+

{total}

+
+
+
+
+ {points.map((point, index) => ( +
+
+ +

{point.label}

+
+

{point.value}

+
+ ))} +
+
+ ); +} + +export function ChartBuilder({ + dataset, + datasets, + onSelectDatasetId, + selectedDatasetId, +}: ChartBuilderProps) { + return ( +
+
+ {datasets.map((entry) => ( + + ))} +
+ + {dataset ? ( +
+
+
+

Dataset

+

{dataset.label}

+

{dataset.description}

+
+
+

+ {dataset.dimensionLabel} x {dataset.metricLabel} +

+

+ {dataset.points.reduce((sum, point) => sum + point.value, 0)} +

+
+
+ + {dataset.chartType === "line" ? : null} + {dataset.chartType === "bar" ? : null} + {dataset.chartType === "donut" ? : null} +
+ ) : null} +
+ ); +} diff --git a/apps/admin/src/components/analytics/SavedDashboardList.tsx b/apps/admin/src/components/analytics/SavedDashboardList.tsx new file mode 100644 index 0000000..a76fa65 --- /dev/null +++ b/apps/admin/src/components/analytics/SavedDashboardList.tsx @@ -0,0 +1,35 @@ +type SavedDashboard = { + datasetId: string; + description: string; + id: string; + label: string; +}; + +type SavedDashboardListProps = { + dashboards: readonly SavedDashboard[]; + onOpen: (datasetId: string) => void; +}; + +export function SavedDashboardList({ dashboards, onOpen }: SavedDashboardListProps) { + return ( +
+
+

Saved Views

+

Operator Dashboards

+
+
+ {dashboards.map((dashboard) => ( + + ))} +
+
+ ); +} diff --git a/apps/admin/src/components/data-explorer/AdminGrid.tsx b/apps/admin/src/components/data-explorer/AdminGrid.tsx index 9c8f46e..db49c90 100644 --- a/apps/admin/src/components/data-explorer/AdminGrid.tsx +++ b/apps/admin/src/components/data-explorer/AdminGrid.tsx @@ -2,10 +2,12 @@ import type { AdminTableMeta } from "@xtablo/shared-types"; type AdminGridProps = { meta: AdminTableMeta | null; + onSelectRow: (row: Record) => void; rows: Record[]; + selectedRowId: string | null; }; -export function AdminGrid({ meta, rows }: AdminGridProps) { +export function AdminGrid({ meta, onSelectRow, rows, selectedRowId }: AdminGridProps) { if (!meta) { return null; } @@ -24,7 +26,13 @@ export function AdminGrid({ meta, rows }: AdminGridProps) { {rows.map((row, index) => ( - + onSelectRow(row)} + > {meta.columns.map((column) => ( {String(row[column.id] ?? "")} diff --git a/apps/admin/src/components/data-explorer/RowEditForm.test.tsx b/apps/admin/src/components/data-explorer/RowEditForm.test.tsx new file mode 100644 index 0000000..26892f7 --- /dev/null +++ b/apps/admin/src/components/data-explorer/RowEditForm.test.tsx @@ -0,0 +1,43 @@ +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; +import { RowEditForm } from "./RowEditForm"; + +describe("RowEditForm", () => { + it("shows a diff preview before saving a sensitive record", async () => { + const onSave = vi.fn().mockResolvedValue(undefined); + + render( + + ); + + fireEvent.change(screen.getByLabelText(/first name/i), { + target: { value: "Ada" }, + }); + fireEvent.click(screen.getByRole("button", { name: /review changes/i })); + + expect(await screen.findByText(/before/i)).toBeInTheDocument(); + expect(screen.getByText(/after/i)).toBeInTheDocument(); + expect(screen.getByText(/first name:\s*test/i)).toBeInTheDocument(); + expect(screen.getByText(/first name:\s*ada/i)).toBeInTheDocument(); + + fireEvent.click(screen.getByRole("button", { name: /confirm update/i })); + + await waitFor(() => + expect(onSave).toHaveBeenCalledWith({ + first_name: "Ada", + }) + ); + }); +}); diff --git a/apps/admin/src/components/data-explorer/RowEditForm.tsx b/apps/admin/src/components/data-explorer/RowEditForm.tsx new file mode 100644 index 0000000..4ae738e --- /dev/null +++ b/apps/admin/src/components/data-explorer/RowEditForm.tsx @@ -0,0 +1,115 @@ +import type { AdminTableColumn } from "@xtablo/shared-types"; +import { FormEvent, useEffect, useMemo, useState } from "react"; + +type RowEditFormProps = { + columns: AdminTableColumn[]; + editableFields: string[]; + isSaving?: boolean; + onSave: (changes: Record) => Promise; + record: Record; +}; + +export function RowEditForm({ + columns, + editableFields, + isSaving = false, + onSave, + record, +}: RowEditFormProps) { + const [draft, setDraft] = useState(record); + const [showDiff, setShowDiff] = useState(false); + + useEffect(() => { + setDraft(record); + setShowDiff(false); + }, [record]); + + const editableColumns = useMemo( + () => columns.filter((column) => editableFields.includes(column.id)), + [columns, editableFields] + ); + + const changedFields = editableColumns.filter((column) => draft[column.id] !== record[column.id]); + const hasChanges = changedFields.length > 0; + + const handleSubmit = (event: FormEvent) => { + event.preventDefault(); + setShowDiff(true); + }; + + const handleSave = async () => { + if (!hasChanges) { + return; + } + + await onSave( + Object.fromEntries(changedFields.map((column) => [column.id, draft[column.id] ?? null])) + ); + setShowDiff(false); + }; + + return ( +
+ {editableColumns.map((column) => ( + + ))} + + + + {showDiff ? ( +
+

Before

+ {changedFields.map((column) => ( +

+ {column.label}: {String(record[column.id] ?? "")} +

+ ))} +

After

+ {changedFields.map((column) => ( +

+ {column.label}: {String(draft[column.id] ?? "")} +

+ ))} + {!hasChanges ? ( +

No changes to save yet.

+ ) : null} +
+ + +
+
+ ) : null} +
+ ); +} diff --git a/apps/admin/src/hooks/useAdminActions.ts b/apps/admin/src/hooks/useAdminActions.ts new file mode 100644 index 0000000..4256922 --- /dev/null +++ b/apps/admin/src/hooks/useAdminActions.ts @@ -0,0 +1,98 @@ +import type { AdminActionRunResponse, AdminActionSummary } from "@xtablo/shared-types"; +import { useEffect, useState } from "react"; +import { adminApi } from "../lib/api"; + +function getErrorMessage(error: unknown, fallbackMessage: string) { + if (typeof error === "object" && error !== null && "response" in error) { + const response = error.response; + if ( + typeof response === "object" && + response !== null && + "data" in response && + typeof response.data === "object" && + response.data !== null && + "error" in response.data && + typeof response.data.error === "string" + ) { + return response.data.error; + } + } + + return fallbackMessage; +} + +export function useAdminActions() { + const [actions, setActions] = useState([]); + const [selectedActionId, setSelectedActionId] = useState(null); + const [isLoading, setIsLoading] = useState(true); + const [isRunning, setIsRunning] = useState(false); + const [error, setError] = useState(null); + const [resultMessage, setResultMessage] = useState(null); + + useEffect(() => { + let isMounted = true; + + const loadActions = async () => { + try { + const response = await adminApi.get<{ actions: AdminActionSummary[] }>("/admin/actions"); + if (!isMounted) { + return; + } + + setActions(response.data.actions); + setSelectedActionId((currentValue) => currentValue ?? response.data.actions[0]?.id ?? null); + } catch (error) { + if (isMounted) { + setError(getErrorMessage(error, "Failed to load admin actions")); + } + } finally { + if (isMounted) { + setIsLoading(false); + } + } + }; + + void loadActions(); + + return () => { + isMounted = false; + }; + }, []); + + const runAction = async (payload: Record) => { + if (!selectedActionId) { + return; + } + + setIsRunning(true); + setError(null); + setResultMessage(null); + + try { + const response = await adminApi.post( + `/admin/actions/${selectedActionId}/run`, + payload + ); + setResultMessage(response.data.message); + } catch (error) { + const message = getErrorMessage(error, "Failed to run admin action"); + setError(message); + throw new Error(message); + } finally { + setIsRunning(false); + } + }; + + return { + actions, + error, + isLoading, + isRunning, + resultMessage, + runAction, + selectedActionId, + setError, + setResultMessage, + setSelectedActionId, + }; +} diff --git a/apps/admin/src/hooks/useAdminDatasets.ts b/apps/admin/src/hooks/useAdminDatasets.ts new file mode 100644 index 0000000..12907dd --- /dev/null +++ b/apps/admin/src/hooks/useAdminDatasets.ts @@ -0,0 +1,105 @@ +import type { AdminDatasetResult, AdminDatasetSummary } from "@xtablo/shared-types"; +import { useEffect, useState } from "react"; +import { adminApi } from "../lib/api"; + +function getErrorMessage(error: unknown, fallbackMessage: string) { + if (typeof error === "object" && error !== null && "response" in error) { + const response = error.response; + if ( + typeof response === "object" && + response !== null && + "data" in response && + typeof response.data === "object" && + response.data !== null && + "error" in response.data && + typeof response.data.error === "string" + ) { + return response.data.error; + } + } + + return fallbackMessage; +} + +export function useAdminDatasets() { + const [datasets, setDatasets] = useState([]); + const [selectedDatasetId, setSelectedDatasetId] = useState(null); + const [dataset, setDataset] = useState(null); + const [isLoading, setIsLoading] = useState(true); + const [error, setError] = useState(null); + + useEffect(() => { + let isMounted = true; + + const loadDatasets = async () => { + try { + const response = await adminApi.get<{ datasets: AdminDatasetSummary[] }>("/admin/datasets"); + if (!isMounted) { + return; + } + + setDatasets(response.data.datasets); + setSelectedDatasetId((currentValue) => currentValue ?? response.data.datasets[0]?.id ?? null); + } catch (error) { + if (isMounted) { + setError(getErrorMessage(error, "Failed to load admin datasets")); + setIsLoading(false); + } + } + }; + + void loadDatasets(); + + return () => { + isMounted = false; + }; + }, []); + + useEffect(() => { + let isMounted = true; + + const loadDataset = async () => { + if (!selectedDatasetId) { + setIsLoading(false); + return; + } + + setIsLoading(true); + setError(null); + + try { + const response = await adminApi.get(`/admin/datasets/${selectedDatasetId}`); + + if (!isMounted) { + return; + } + + setDataset(response.data); + } catch (error) { + if (isMounted) { + setError(getErrorMessage(error, "Failed to load admin dataset")); + setDataset(null); + } + } finally { + if (isMounted) { + setIsLoading(false); + } + } + }; + + void loadDataset(); + + return () => { + isMounted = false; + }; + }, [selectedDatasetId]); + + return { + dataset, + datasets, + error, + isLoading, + selectedDatasetId, + setSelectedDatasetId, + }; +} diff --git a/apps/admin/src/hooks/useAdminOverview.ts b/apps/admin/src/hooks/useAdminOverview.ts new file mode 100644 index 0000000..f33df94 --- /dev/null +++ b/apps/admin/src/hooks/useAdminOverview.ts @@ -0,0 +1,44 @@ +import type { AdminOverviewResponse } from "@xtablo/shared-types"; +import { useEffect, useState } from "react"; +import { adminApi } from "../lib/api"; + +export function useAdminOverview() { + const [overview, setOverview] = useState(null); + const [isLoading, setIsLoading] = useState(true); + const [error, setError] = useState(null); + + useEffect(() => { + let isMounted = true; + + const loadOverview = async () => { + try { + const response = await adminApi.get("/admin/overview"); + if (!isMounted) { + return; + } + + setOverview(response.data); + } catch { + if (isMounted) { + setError("Failed to load admin overview"); + } + } finally { + if (isMounted) { + setIsLoading(false); + } + } + }; + + void loadOverview(); + + return () => { + isMounted = false; + }; + }, []); + + return { + error, + isLoading, + overview, + }; +} diff --git a/apps/admin/src/hooks/useAdminTables.ts b/apps/admin/src/hooks/useAdminTables.ts index cf21114..3335d6e 100644 --- a/apps/admin/src/hooks/useAdminTables.ts +++ b/apps/admin/src/hooks/useAdminTables.ts @@ -2,7 +2,26 @@ import type { AdminTableMeta, AdminTableSummary } from "@xtablo/shared-types"; import { useEffect, useState } from "react"; import { adminApi } from "../lib/api"; -type AdminRow = Record; +export type AdminRow = Record; + +function getErrorMessage(error: unknown, fallbackMessage: string) { + if (typeof error === "object" && error !== null && "response" in error) { + const response = error.response; + if ( + typeof response === "object" && + response !== null && + "data" in response && + typeof response.data === "object" && + response.data !== null && + "error" in response.data && + typeof response.data.error === "string" + ) { + return response.data.error; + } + } + + return fallbackMessage; +} export function useAdminTables() { const [tables, setTables] = useState([]); @@ -82,6 +101,37 @@ export function useAdminTables() { }; }, [selectedTableId]); + const updateRow = async (rowId: string, changes: Partial) => { + if (!selectedTableId) { + throw new Error("No admin table selected"); + } + + try { + const response = await adminApi.patch<{ row: AdminRow }>( + `/admin/tables/${selectedTableId}/rows/${rowId}`, + changes + ); + const updatedRow = response.data.row; + + setRows((currentRows) => + currentRows.map((row) => { + if (String(row[meta?.primaryKey ?? "id"] ?? "") !== rowId) { + return row; + } + + return updatedRow; + }) + ); + setError(null); + + return updatedRow; + } catch (error) { + const message = getErrorMessage(error, "Failed to update admin row"); + setError(message); + throw new Error(message); + } + }; + return { error, isLoading, @@ -90,5 +140,6 @@ export function useAdminTables() { selectedTableId, setSelectedTableId, tables, + updateRow, }; } diff --git a/apps/admin/src/pages/ActionCenterPage.test.tsx b/apps/admin/src/pages/ActionCenterPage.test.tsx new file mode 100644 index 0000000..e7ce473 --- /dev/null +++ b/apps/admin/src/pages/ActionCenterPage.test.tsx @@ -0,0 +1,69 @@ +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { adminApi } from "../lib/api"; +import { ActionCenterPage } from "./ActionCenterPage"; + +vi.mock("../lib/api", () => ({ + adminApi: { + get: vi.fn(), + post: vi.fn(), + }, +})); + +describe("ActionCenterPage", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("loads actions and runs a guarded workflow", async () => { + vi.mocked(adminApi.get).mockResolvedValue({ + data: { + actions: [ + { + description: "Disable a user's access to a tablo.", + fields: [ + { id: "tabloId", label: "Tablo ID", required: true }, + { id: "userId", label: "User ID", required: true }, + { id: "reason", label: "Reason", required: true }, + ], + id: "deactivate_tablo_access", + label: "Deactivate Tablo Access", + }, + ], + }, + }); + vi.mocked(adminApi.post).mockResolvedValue({ + data: { + message: "Tablo access deactivated and logged.", + success: true, + }, + }); + + render(); + + expect(await screen.findByText(/action center/i)).toBeInTheDocument(); + + fireEvent.change(screen.getByLabelText(/tablo id/i), { + target: { value: "tablo-1" }, + }); + fireEvent.change(screen.getByLabelText(/user id/i), { + target: { value: "user-1" }, + }); + fireEvent.change(screen.getByLabelText(/reason/i), { + target: { value: "manual cleanup" }, + }); + fireEvent.click(screen.getByRole("button", { name: /run action/i })); + + await waitFor(() => + expect(adminApi.post).toHaveBeenCalledWith( + "/admin/actions/deactivate_tablo_access/run", + { + reason: "manual cleanup", + tabloId: "tablo-1", + userId: "user-1", + } + ) + ); + expect(await screen.findByText(/deactivated and logged/i)).toBeInTheDocument(); + }); +}); diff --git a/apps/admin/src/pages/ActionCenterPage.tsx b/apps/admin/src/pages/ActionCenterPage.tsx index 19107ca..b4330bf 100644 --- a/apps/admin/src/pages/ActionCenterPage.tsx +++ b/apps/admin/src/pages/ActionCenterPage.tsx @@ -1,11 +1,47 @@ +import { ActionRunner } from "../components/actions/ActionRunner"; +import { useAdminActions } from "../hooks/useAdminActions"; + export function ActionCenterPage() { + const { + actions, + error, + isLoading, + isRunning, + resultMessage, + runAction, + selectedActionId, + setError, + setResultMessage, + setSelectedActionId, + } = useAdminActions(); + return ( -
-

Actions

-

Action Center

-

- High-impact repair and resync workflows will run from this controlled surface. -

+
+
+

Actions

+

Action Center

+

+ Run guarded production actions with explicit operator input and audit logging. +

+
+ + {isLoading ?

Loading actions...

: null} + + {!isLoading ? ( + { + setSelectedActionId(actionId); + setError(null); + setResultMessage(null); + }} + resultMessage={resultMessage} + selectedActionId={selectedActionId} + /> + ) : null}
); } diff --git a/apps/admin/src/pages/AnalyticsStudioPage.test.tsx b/apps/admin/src/pages/AnalyticsStudioPage.test.tsx new file mode 100644 index 0000000..e6b710c --- /dev/null +++ b/apps/admin/src/pages/AnalyticsStudioPage.test.tsx @@ -0,0 +1,87 @@ +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { adminApi } from "../lib/api"; +import { AnalyticsStudioPage } from "./AnalyticsStudioPage"; + +vi.mock("../lib/api", () => ({ + adminApi: { + get: vi.fn(), + }, +})); + +describe("AnalyticsStudioPage", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("loads curated datasets and switches charts", async () => { + vi.mocked(adminApi.get).mockImplementation(async (path: string) => { + if (path === "/admin/datasets") { + return { + data: { + datasets: [ + { + description: "New users over time.", + id: "profile_growth", + label: "User Growth", + }, + { + description: "Users by plan.", + id: "plan_mix", + label: "Plan Mix", + }, + ], + }, + }; + } + + if (path === "/admin/datasets/profile_growth") { + return { + data: { + chartType: "line", + description: "New users over time.", + dimensionLabel: "Created Day", + id: "profile_growth", + label: "User Growth", + metricLabel: "Users Created", + points: [ + { label: "2026-04-20", value: 2 }, + { label: "2026-04-21", value: 4 }, + ], + }, + }; + } + + if (path === "/admin/datasets/plan_mix") { + return { + data: { + chartType: "donut", + description: "Users by plan.", + dimensionLabel: "Plan", + id: "plan_mix", + label: "Plan Mix", + metricLabel: "Users", + points: [ + { label: "solo", value: 6 }, + { label: "team", value: 3 }, + ], + }, + }; + } + + throw new Error(`Unexpected path: ${path}`); + }); + + render(); + + expect(await screen.findByText(/analytics studio/i)).toBeInTheDocument(); + expect(await screen.findByText(/user growth/i)).toBeInTheDocument(); + + fireEvent.click(screen.getByRole("button", { name: /plan mix/i })); + + await waitFor(() => + expect(adminApi.get).toHaveBeenCalledWith("/admin/datasets/plan_mix") + ); + expect(await screen.findByText(/total/i)).toBeInTheDocument(); + }); +}); diff --git a/apps/admin/src/pages/AnalyticsStudioPage.tsx b/apps/admin/src/pages/AnalyticsStudioPage.tsx index 7ef381a..7cbbe8b 100644 --- a/apps/admin/src/pages/AnalyticsStudioPage.tsx +++ b/apps/admin/src/pages/AnalyticsStudioPage.tsx @@ -1,11 +1,38 @@ +import { ChartBuilder } from "../components/analytics/ChartBuilder"; +import { SavedDashboardList } from "../components/analytics/SavedDashboardList"; +import { useAdminDatasets } from "../hooks/useAdminDatasets"; +import { savedDashboardPresets } from "../registry/datasets"; + export function AnalyticsStudioPage() { + const { dataset, datasets, error, isLoading, selectedDatasetId, setSelectedDatasetId } = + useAdminDatasets(); + return ( -
-

Analytics

-

Analytics Studio

-

- Curated operational datasets and chart building land here next. -

+
+
+

Analytics

+

Analytics Studio

+

+ Curated production datasets for operators who need charted context before they take + action in the explorer or action center. +

+
+ + {isLoading ?

Loading analytics...

: null} + {error ?

{error}

: null} + +
+ + setSelectedDatasetId(datasetId)} + /> +
); } diff --git a/apps/admin/src/pages/DataExplorerPage.test.tsx b/apps/admin/src/pages/DataExplorerPage.test.tsx index 0337663..944d5c3 100644 --- a/apps/admin/src/pages/DataExplorerPage.test.tsx +++ b/apps/admin/src/pages/DataExplorerPage.test.tsx @@ -1,4 +1,4 @@ -import { render, screen } from "@testing-library/react"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import { MemoryRouter } from "react-router-dom"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { adminApi } from "../lib/api"; @@ -7,6 +7,7 @@ import { DataExplorerPage } from "./DataExplorerPage"; vi.mock("../lib/api", () => ({ adminApi: { get: vi.fn(), + patch: vi.fn(), }, })); @@ -15,7 +16,7 @@ describe("DataExplorerPage", () => { vi.clearAllMocks(); }); - it("loads rows for the selected table", async () => { + it("loads rows for the selected table and saves approved edits", async () => { vi.mocked(adminApi.get).mockImplementation(async (path: string) => { if (path === "/admin/tables") { return { @@ -32,11 +33,14 @@ describe("DataExplorerPage", () => { return { data: { columns: [ + { id: "id", label: "ID" }, { id: "email", label: "Email" }, { id: "first_name", label: "First name" }, ], + editableFields: ["first_name"], id: "profiles", label: "Users", + primaryKey: "id", }, }; } @@ -57,6 +61,15 @@ describe("DataExplorerPage", () => { throw new Error(`Unexpected path: ${path}`); }); + vi.mocked(adminApi.patch).mockResolvedValue({ + data: { + row: { + email: "test_owner@example.com", + first_name: "Ada", + id: "user-1", + }, + }, + }); render( @@ -67,5 +80,19 @@ describe("DataExplorerPage", () => { expect(await screen.findByRole("button", { name: /users/i })).toBeInTheDocument(); expect(await screen.findByText(/email/i)).toBeInTheDocument(); expect(await screen.findByText(/test_owner@example.com/i)).toBeInTheDocument(); + + fireEvent.click(screen.getByText(/test_owner@example.com/i)); + fireEvent.change(screen.getByLabelText(/first name/i), { + target: { value: "Ada" }, + }); + fireEvent.click(screen.getByRole("button", { name: /review changes/i })); + fireEvent.click(screen.getByRole("button", { name: /confirm update/i })); + + await waitFor(() => + expect(adminApi.patch).toHaveBeenCalledWith("/admin/tables/profiles/rows/user-1", { + first_name: "Ada", + }) + ); + expect(await screen.findByText(/row updated and logged/i)).toBeInTheDocument(); }); }); diff --git a/apps/admin/src/pages/DataExplorerPage.tsx b/apps/admin/src/pages/DataExplorerPage.tsx index d928f12..f448f6f 100644 --- a/apps/admin/src/pages/DataExplorerPage.tsx +++ b/apps/admin/src/pages/DataExplorerPage.tsx @@ -1,25 +1,72 @@ +import { useEffect, useMemo, useState } from "react"; import { AdminGrid } from "../components/data-explorer/AdminGrid"; +import { RowEditForm } from "../components/data-explorer/RowEditForm"; import { useAdminTables } from "../hooks/useAdminTables"; export function DataExplorerPage() { - const { error, isLoading, meta, rows, selectedTableId, setSelectedTableId, tables } = - useAdminTables(); + const { + error, + isLoading, + meta, + rows, + selectedTableId, + setSelectedTableId, + tables, + updateRow, + } = useAdminTables(); + const [selectedRowId, setSelectedRowId] = useState(null); + const [isSaving, setIsSaving] = useState(false); + const [saveMessage, setSaveMessage] = useState(null); + + useEffect(() => { + setSelectedRowId(null); + setSaveMessage(null); + }, [selectedTableId]); + + const selectedRow = useMemo(() => { + if (!meta || !selectedRowId) { + return null; + } + + return ( + rows.find((row) => String(row[meta.primaryKey] ?? "") === selectedRowId) ?? null + ); + }, [meta, rows, selectedRowId]); + + const handleSave = async (changes: Record) => { + if (!selectedRowId) { + return; + } + + setIsSaving(true); + setSaveMessage(null); + + try { + await updateRow(selectedRowId, changes); + setSaveMessage("Row updated and logged."); + } finally { + setIsSaving(false); + } + }; return (
-
+
); diff --git a/apps/admin/src/pages/OperationsHomePage.tsx b/apps/admin/src/pages/OperationsHomePage.tsx index 8caeb92..6260c83 100644 --- a/apps/admin/src/pages/OperationsHomePage.tsx +++ b/apps/admin/src/pages/OperationsHomePage.tsx @@ -1,13 +1,92 @@ +import { Link } from "react-router-dom"; +import { useAdminOverview } from "../hooks/useAdminOverview"; + export function OperationsHomePage() { + const { error, isLoading, overview } = useAdminOverview(); + return ( -
-
-

Operations

-

Operations Home

-
-

- Internal production oversight, anomaly checks, and shortcuts into the admin workflows. -

+
+
+

Operations

+

+ Production command deck for privileged Supabase operations. +

+

+ Monitor the current state of users, access grants, and tablos before drilling into + explorer edits, analytics, or controlled admin actions. +

+
+ + {isLoading ?

Loading operations overview...

: null} + {error ?

{error}

: null} + + {overview ? ( + <> +
+ {overview.metrics.map((metric) => ( +
+

+ {metric.label} +

+

{metric.value}

+

{metric.changeLabel}

+
+ ))} +
+ +
+
+
+

Alerts

+

Operational Watchlist

+
+
+ {overview.alerts.map((alert) => ( +
+
+ + {alert.severity} + +

{alert.title}

+
+

{alert.description}

+
+ ))} +
+
+ +
+

Shortcuts

+

Common Paths

+
+ {overview.shortcuts.map((shortcut) => ( + + {shortcut.label} + + ))} +
+
+
+ + ) : null}
); } diff --git a/apps/admin/src/registry/actions.ts b/apps/admin/src/registry/actions.ts new file mode 100644 index 0000000..d159b57 --- /dev/null +++ b/apps/admin/src/registry/actions.ts @@ -0,0 +1,10 @@ +export const actionSeverityCopy = { + deactivate_tablo_access: { + badge: "Restriction", + tone: "warning", + }, + grant_tablo_admin: { + badge: "Privilege", + tone: "critical", + }, +} as const; diff --git a/apps/admin/src/registry/datasets.ts b/apps/admin/src/registry/datasets.ts new file mode 100644 index 0000000..8fa262e --- /dev/null +++ b/apps/admin/src/registry/datasets.ts @@ -0,0 +1,20 @@ +export const savedDashboardPresets = [ + { + datasetId: "profile_growth", + description: "Track production user creation velocity.", + id: "growth", + label: "Growth Watch", + }, + { + datasetId: "plan_mix", + description: "Review monetization mix across the current user base.", + id: "plans", + label: "Plan Pulse", + }, + { + datasetId: "tablo_access_mix", + description: "Spot access drift and admin-heavy tablos.", + id: "access", + label: "Access Posture", + }, +] as const; diff --git a/apps/api/src/__tests__/routes/adminActions.test.ts b/apps/api/src/__tests__/routes/adminActions.test.ts new file mode 100644 index 0000000..f16423f --- /dev/null +++ b/apps/api/src/__tests__/routes/adminActions.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it } from "vitest"; +import { createSignedAdminToken } from "../helpers/adminTokenTestUtils.js"; +import { createConfig } from "../../config.js"; +import { MiddlewareManager } from "../../middlewares/middleware.js"; +import { getMainRouter } from "../../routers/index.js"; + +const ADMIN_TOKEN_SIGNING_SECRET = "admin-test-secret"; +const ADMIN_TOKEN_AUDIENCE = "xtablo-admin"; + +describe("Admin Actions Router", () => { + process.env.ADMIN_TOKEN_SIGNING_SECRET = ADMIN_TOKEN_SIGNING_SECRET; + process.env.ADMIN_TOKEN_AUDIENCE = ADMIN_TOKEN_AUDIENCE; + process.env.ADMIN_APP_URL = "http://localhost:5176"; + + const config = createConfig(); + MiddlewareManager.initialize(config); + const app = getMainRouter(config); + + const sessionToken = createSignedAdminToken( + { + aud: ADMIN_TOKEN_AUDIENCE, + email: "ops@xtablo.com", + exp: Math.floor(Date.now() / 1000) + 900, + role: "operator", + sub: "operator-1", + type: "admin_session", + }, + ADMIN_TOKEN_SIGNING_SECRET + ); + + it("lists curated admin actions", async () => { + const res = await app.request("/admin/actions", { + headers: { + Authorization: `Bearer ${sessionToken}`, + }, + }); + + expect(res.status).toBe(200); + await expect(res.json()).resolves.toMatchObject({ + actions: expect.arrayContaining([ + expect.objectContaining({ + id: "deactivate_tablo_access", + label: "Deactivate Tablo Access", + }), + ]), + }); + }); + + it("validates required input before running an action", async () => { + const res = await app.request("/admin/actions/deactivate_tablo_access/run", { + body: JSON.stringify({ tabloId: "tablo-1" }), + headers: { + Authorization: `Bearer ${sessionToken}`, + "Content-Type": "application/json", + }, + method: "POST", + }); + + expect(res.status).toBe(400); + await expect(res.json()).resolves.toMatchObject({ + error: "tabloId, userId, and reason are required", + }); + }); +}); diff --git a/apps/api/src/__tests__/routes/adminDatasets.test.ts b/apps/api/src/__tests__/routes/adminDatasets.test.ts new file mode 100644 index 0000000..b233560 --- /dev/null +++ b/apps/api/src/__tests__/routes/adminDatasets.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it } from "vitest"; +import { createSignedAdminToken } from "../helpers/adminTokenTestUtils.js"; +import { createConfig } from "../../config.js"; +import { MiddlewareManager } from "../../middlewares/middleware.js"; +import { getMainRouter } from "../../routers/index.js"; + +const ADMIN_TOKEN_SIGNING_SECRET = "admin-test-secret"; +const ADMIN_TOKEN_AUDIENCE = "xtablo-admin"; + +describe("Admin Datasets Router", () => { + process.env.ADMIN_TOKEN_SIGNING_SECRET = ADMIN_TOKEN_SIGNING_SECRET; + process.env.ADMIN_TOKEN_AUDIENCE = ADMIN_TOKEN_AUDIENCE; + process.env.ADMIN_APP_URL = "http://localhost:5176"; + + const config = createConfig(); + MiddlewareManager.initialize(config); + const app = getMainRouter(config); + + const sessionToken = createSignedAdminToken( + { + aud: ADMIN_TOKEN_AUDIENCE, + email: "ops@xtablo.com", + exp: Math.floor(Date.now() / 1000) + 900, + role: "operator", + sub: "operator-1", + type: "admin_session", + }, + ADMIN_TOKEN_SIGNING_SECRET + ); + + it("lists curated admin datasets", async () => { + const res = await app.request("/admin/datasets", { + headers: { + Authorization: `Bearer ${sessionToken}`, + }, + }); + + expect(res.status).toBe(200); + await expect(res.json()).resolves.toMatchObject({ + datasets: expect.arrayContaining([ + expect.objectContaining({ + id: "profile_growth", + label: "User Growth", + }), + ]), + }); + }); + + it("returns chart-ready data for a registered dataset", async () => { + const res = await app.request("/admin/datasets/plan_mix", { + headers: { + Authorization: `Bearer ${sessionToken}`, + }, + }); + + expect(res.status).toBe(200); + await expect(res.json()).resolves.toMatchObject({ + chartType: "donut", + id: "plan_mix", + metricLabel: "Users", + points: expect.any(Array), + }); + }); +}); diff --git a/apps/api/src/__tests__/routes/adminTableEdits.test.ts b/apps/api/src/__tests__/routes/adminTableEdits.test.ts new file mode 100644 index 0000000..58d6110 --- /dev/null +++ b/apps/api/src/__tests__/routes/adminTableEdits.test.ts @@ -0,0 +1,72 @@ +import { createClient } from "@supabase/supabase-js"; +import { describe, expect, it } from "vitest"; +import { createSignedAdminToken } from "../helpers/adminTokenTestUtils.js"; +import { getTestData } from "../helpers/dbSetup.js"; +import { createConfig } from "../../config.js"; +import { MiddlewareManager } from "../../middlewares/middleware.js"; +import { getMainRouter } from "../../routers/index.js"; + +const ADMIN_TOKEN_SIGNING_SECRET = "admin-test-secret"; +const ADMIN_TOKEN_AUDIENCE = "xtablo-admin"; + +describe("Admin Table Edit Router", () => { + process.env.ADMIN_TOKEN_SIGNING_SECRET = ADMIN_TOKEN_SIGNING_SECRET; + process.env.ADMIN_TOKEN_AUDIENCE = ADMIN_TOKEN_AUDIENCE; + process.env.ADMIN_APP_URL = "http://localhost:5176"; + + const config = createConfig(); + MiddlewareManager.initialize(config); + const app = getMainRouter(config); + + const sessionToken = createSignedAdminToken( + { + aud: ADMIN_TOKEN_AUDIENCE, + email: "ops@xtablo.com", + exp: Math.floor(Date.now() / 1000) + 900, + role: "operator", + sub: "operator-1", + type: "admin_session", + }, + ADMIN_TOKEN_SIGNING_SECRET + ); + + it("writes an audit log entry for a successful update", async () => { + const ownerUserId = getTestData().users.owner.userId; + + const res = await app.request(`/admin/tables/profiles/rows/${ownerUserId}`, { + method: "PATCH", + headers: { + Authorization: `Bearer ${sessionToken}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ first_name: "Ada" }), + }); + + expect(res.status).toBe(200); + await expect(res.json()).resolves.toMatchObject({ + row: expect.objectContaining({ + first_name: "Ada", + id: ownerUserId, + }), + }); + + const auditClient = createClient(config.SUPABASE_URL, config.SUPABASE_SERVICE_ROLE_KEY, { + auth: { autoRefreshToken: false, persistSession: false }, + }); + + const { data: auditRows, error } = await auditClient + .from("admin_audit_log") + .select("*") + .eq("target_id", ownerUserId) + .eq("action", "update") + .order("created_at", { ascending: false }) + .limit(1); + + expect(error).toBeNull(); + expect(auditRows).toHaveLength(1); + expect(auditRows?.[0]).toMatchObject({ + operator_email: "ops@xtablo.com", + target_type: "profiles", + }); + }); +}); diff --git a/apps/api/src/__tests__/routes/adminTables.test.ts b/apps/api/src/__tests__/routes/adminTables.test.ts index f3d7603..443d1db 100644 --- a/apps/api/src/__tests__/routes/adminTables.test.ts +++ b/apps/api/src/__tests__/routes/adminTables.test.ts @@ -57,6 +57,8 @@ describe("Admin Tables Router", () => { await expect(res.json()).resolves.toMatchObject({ id: "profiles", label: "Users", + editableFields: ["first_name", "last_name"], + primaryKey: "id", columns: expect.arrayContaining([ expect.objectContaining({ id: "email", diff --git a/apps/api/src/helpers/adminAudit.ts b/apps/api/src/helpers/adminAudit.ts new file mode 100644 index 0000000..3abf933 --- /dev/null +++ b/apps/api/src/helpers/adminAudit.ts @@ -0,0 +1,42 @@ +import type { SupabaseClient } from "@supabase/supabase-js"; + +type AdminAuditArgs = { + action: string; + after?: unknown; + before?: unknown; + operatorEmail: string; + operatorId: string; + role: string; + supabase: SupabaseClient; + targetId: string; + targetType: string; +}; + +export async function recordAdminAuditLog({ + action, + after, + before, + operatorEmail, + operatorId, + role, + supabase, + targetId, + targetType, +}: AdminAuditArgs) { + const { error } = await (supabase as SupabaseClient) + .from("admin_audit_log") + .insert({ + action, + after, + before, + operator_email: operatorEmail, + operator_id: operatorId, + role, + target_id: targetId, + target_type: targetType, + }); + + if (error) { + throw new Error(`Failed to write admin audit log: ${error.message}`); + } +} diff --git a/apps/api/src/helpers/adminRegistry.ts b/apps/api/src/helpers/adminRegistry.ts index bf2b52f..8f17c22 100644 --- a/apps/api/src/helpers/adminRegistry.ts +++ b/apps/api/src/helpers/adminRegistry.ts @@ -7,8 +7,10 @@ type AdminTableColumn = { type AdminTableDefinition = { columns: AdminTableColumn[]; + editableColumns?: string[]; id: string; label: string; + primaryKey: string; select: string; source: keyof Database["public"]["Tables"]; }; @@ -21,8 +23,10 @@ export const adminTableRegistry: Record = { { id: "first_name", label: "First name" }, { id: "last_name", label: "Last name" }, ], + editableColumns: ["first_name", "last_name"], id: "profiles", label: "Users", + primaryKey: "id", select: "id,email,first_name,last_name", source: "profiles", }, @@ -33,13 +37,86 @@ export const adminTableRegistry: Record = { { id: "is_active", label: "Active" }, { id: "is_admin", label: "Admin" }, ], + editableColumns: [], id: "tablo_access", label: "Tablo Access", + primaryKey: "user_id", select: "tablo_id,user_id,is_active,is_admin", source: "tablo_access", }, }; +type AdminDatasetDefinition = { + description: string; + id: string; + label: string; +}; + +type AdminActionFieldDefinition = { + id: string; + label: string; + placeholder?: string; + required?: boolean; +}; + +type AdminActionDefinition = { + description: string; + fields: AdminActionFieldDefinition[]; + id: string; + label: string; +}; + +export const adminDatasetRegistry: Record = { + profile_growth: { + description: "New user creation trend over time.", + id: "profile_growth", + label: "User Growth", + }, + plan_mix: { + description: "Production users by current subscription plan.", + id: "plan_mix", + label: "Plan Mix", + }, + tablo_access_mix: { + description: "Current active, inactive, and admin access posture.", + id: "tablo_access_mix", + label: "Tablo Access Mix", + }, +}; + +export const adminActionRegistry: Record = { + deactivate_tablo_access: { + description: "Disable a user's access to a tablo and log the operator reason.", + fields: [ + { id: "tabloId", label: "Tablo ID", placeholder: "tablo_123", required: true }, + { id: "userId", label: "User ID", placeholder: "user_123", required: true }, + { + id: "reason", + label: "Reason", + placeholder: "Explain why this access is being removed", + required: true, + }, + ], + id: "deactivate_tablo_access", + label: "Deactivate Tablo Access", + }, + grant_tablo_admin: { + description: "Promote an existing tablo member to admin and force active access.", + fields: [ + { id: "tabloId", label: "Tablo ID", placeholder: "tablo_123", required: true }, + { id: "userId", label: "User ID", placeholder: "user_123", required: true }, + { + id: "reason", + label: "Reason", + placeholder: "Explain why admin access is being granted", + required: true, + }, + ], + id: "grant_tablo_admin", + label: "Grant Tablo Admin", + }, +}; + export function getAdminTableDefinition(tableId: string) { return adminTableRegistry[tableId] ?? null; } @@ -48,6 +125,22 @@ export function listAdminTables() { return Object.values(adminTableRegistry).map(({ id, label }) => ({ id, label })); } +export function getAdminDatasetDefinition(datasetId: string) { + return adminDatasetRegistry[datasetId] ?? null; +} + +export function listAdminDatasets() { + return Object.values(adminDatasetRegistry); +} + +export function getAdminActionDefinition(actionId: string) { + return adminActionRegistry[actionId] ?? null; +} + +export function listAdminActions() { + return Object.values(adminActionRegistry); +} + export function normalizeAdminRows(rows: unknown[]) { return rows as Record[]; } diff --git a/apps/api/src/routers/admin.ts b/apps/api/src/routers/admin.ts index c1eb040..00aa5b1 100644 --- a/apps/api/src/routers/admin.ts +++ b/apps/api/src/routers/admin.ts @@ -2,7 +2,10 @@ import { Hono } from "hono"; import type { AppConfig } from "../config.js"; import { MiddlewareManager } from "../middlewares/middleware.js"; import type { BaseEnv } from "../types/app.types.js"; +import { getAdminActionsRouter } from "./adminActions.js"; import { getAdminAuthRouter } from "./adminAuth.js"; +import { getAdminDatasetsRouter } from "./adminDatasets.js"; +import { getAdminOverviewRouter } from "./adminOverview.js"; import { getAdminTablesRouter } from "./adminTables.js"; export const getAdminRouter = (config: AppConfig) => { @@ -11,9 +14,19 @@ export const getAdminRouter = (config: AppConfig) => { adminRouter.route("/auth", getAdminAuthRouter(config)); + adminRouter.use("/overview", middlewareManager.adminAuth); + adminRouter.use("/overview/*", middlewareManager.adminAuth); adminRouter.use("/tables", middlewareManager.adminAuth); adminRouter.use("/tables/*", middlewareManager.adminAuth); + adminRouter.use("/datasets", middlewareManager.adminAuth); + adminRouter.use("/datasets/*", middlewareManager.adminAuth); + adminRouter.use("/actions", middlewareManager.adminAuth); + adminRouter.use("/actions/*", middlewareManager.adminAuth); + + adminRouter.route("/overview", getAdminOverviewRouter()); adminRouter.route("/tables", getAdminTablesRouter()); + adminRouter.route("/datasets", getAdminDatasetsRouter()); + adminRouter.route("/actions", getAdminActionsRouter()); return adminRouter; }; diff --git a/apps/api/src/routers/adminActions.ts b/apps/api/src/routers/adminActions.ts new file mode 100644 index 0000000..0aea6fe --- /dev/null +++ b/apps/api/src/routers/adminActions.ts @@ -0,0 +1,109 @@ +import { Hono } from "hono"; +import type { AdminActionRunResponse } from "@xtablo/shared-types"; +import { recordAdminAuditLog } from "../helpers/adminAudit.js"; +import { + getAdminActionDefinition, + listAdminActions, +} from "../helpers/adminRegistry.js"; +import type { BaseEnv } from "../types/app.types.js"; + +type ActionInput = { + reason?: string; + tabloId?: string; + userId?: string; +}; + +function getActionInput(body: unknown): ActionInput { + if (!body || typeof body !== "object") { + return {}; + } + + const input = body as Record; + + return { + reason: typeof input.reason === "string" ? input.reason : undefined, + tabloId: typeof input.tabloId === "string" ? input.tabloId : undefined, + userId: typeof input.userId === "string" ? input.userId : undefined, + }; +} + +export const getAdminActionsRouter = () => { + const adminActionsRouter = new Hono(); + + adminActionsRouter.get("/", async (c) => { + return c.json({ actions: listAdminActions() }, 200); + }); + + adminActionsRouter.post("/:actionId/run", async (c) => { + const supabase = c.get("supabase"); + const adminSession = c.get("adminSession"); + const actionId = c.req.param("actionId"); + const definition = getAdminActionDefinition(actionId); + + if (!definition) { + return c.json({ error: `Admin action '${actionId}' is not registered` }, 404); + } + + const { reason, tabloId, userId } = getActionInput(await c.req.json().catch(() => null)); + + if (!tabloId || !userId || !reason) { + return c.json({ error: "tabloId, userId, and reason are required" }, 400); + } + + const { data: before, error: beforeError } = await supabase + .from("tablo_access") + .select("id,tablo_id,user_id,is_active,is_admin") + .eq("tablo_id", tabloId) + .eq("user_id", userId) + .maybeSingle(); + + if (beforeError) { + return c.json({ error: `Failed to load tablo access for action '${actionId}'` }, 500); + } + + if (!before) { + return c.json({ error: "Target tablo access row was not found" }, 404); + } + + const changes = + actionId === "grant_tablo_admin" + ? { is_active: true, is_admin: true } + : { is_active: false }; + + const { data: after, error: updateError } = await supabase + .from("tablo_access") + .update(changes) + .eq("id", before.id) + .select("id,tablo_id,user_id,is_active,is_admin") + .single(); + + if (updateError || !after) { + return c.json({ error: `Failed to run admin action '${actionId}'` }, 500); + } + + await recordAdminAuditLog({ + action: `${actionId}:${reason}`, + after, + before, + operatorEmail: adminSession.operatorEmail, + operatorId: adminSession.operatorId, + role: adminSession.role, + supabase, + targetId: `${tabloId}:${userId}`, + targetType: "tablo_access", + }); + + return c.json( + { + message: + actionId === "grant_tablo_admin" + ? "Tablo admin access granted and logged." + : "Tablo access deactivated and logged.", + success: true, + } satisfies AdminActionRunResponse, + 200 + ); + }); + + return adminActionsRouter; +}; diff --git a/apps/api/src/routers/adminDatasets.ts b/apps/api/src/routers/adminDatasets.ts new file mode 100644 index 0000000..7b8206a --- /dev/null +++ b/apps/api/src/routers/adminDatasets.ts @@ -0,0 +1,155 @@ +import { Hono } from "hono"; +import type { AdminDatasetResult } from "@xtablo/shared-types"; +import { + getAdminDatasetDefinition, + listAdminDatasets, +} from "../helpers/adminRegistry.js"; +import type { BaseEnv } from "../types/app.types.js"; + +function bucketByDay(values: Array) { + const counts = new Map(); + + values.forEach((value) => { + if (!value) { + return; + } + + const bucket = value.slice(0, 10); + counts.set(bucket, (counts.get(bucket) ?? 0) + 1); + }); + + return Array.from(counts.entries()) + .sort(([left], [right]) => left.localeCompare(right)) + .map(([label, value]) => ({ label, value })); +} + +function bucketByValue(values: Array, emptyLabel: string) { + const counts = new Map(); + + values.forEach((value) => { + const bucket = value?.trim() || emptyLabel; + counts.set(bucket, (counts.get(bucket) ?? 0) + 1); + }); + + return Array.from(counts.entries()) + .sort(([left], [right]) => left.localeCompare(right)) + .map(([label, value]) => ({ label, value })); +} + +function bucketTabloAccess(rows: Array<{ is_active: boolean | null; is_admin: boolean | null }>) { + const counts = new Map([ + ["Active Member", 0], + ["Active Admin", 0], + ["Inactive", 0], + ]); + + rows.forEach((row) => { + if (row.is_active) { + const label = row.is_admin ? "Active Admin" : "Active Member"; + counts.set(label, (counts.get(label) ?? 0) + 1); + return; + } + + counts.set("Inactive", (counts.get("Inactive") ?? 0) + 1); + }); + + return Array.from(counts.entries()).map(([label, value]) => ({ label, value })); +} + +type AdminDatasetPayload = Pick< + AdminDatasetResult, + "chartType" | "dimensionLabel" | "metricLabel" | "points" +>; + +async function getDatasetPoints( + datasetId: string, + supabase: BaseEnv["Variables"]["supabase"] +): Promise { + switch (datasetId) { + case "profile_growth": { + const { data, error } = await supabase + .from("profiles") + .select("created_at") + .order("created_at", { ascending: true }) + .limit(365); + + if (error) { + throw new Error(error.message); + } + + return { + chartType: "line", + dimensionLabel: "Created Day", + metricLabel: "Users Created", + points: bucketByDay((data ?? []).map((row) => row.created_at)), + }; + } + case "plan_mix": { + const { data, error } = await supabase.from("profiles").select("plan").limit(500); + + if (error) { + throw new Error(error.message); + } + + return { + chartType: "donut", + dimensionLabel: "Plan", + metricLabel: "Users", + points: bucketByValue((data ?? []).map((row) => row.plan), "No Plan"), + }; + } + case "tablo_access_mix": { + const { data, error } = await supabase + .from("tablo_access") + .select("is_active,is_admin") + .limit(500); + + if (error) { + throw new Error(error.message); + } + + return { + chartType: "bar", + dimensionLabel: "Access Type", + metricLabel: "Rows", + points: bucketTabloAccess(data ?? []), + }; + } + default: + throw new Error(`Unknown admin dataset '${datasetId}'`); + } +} + +export const getAdminDatasetsRouter = () => { + const adminDatasetsRouter = new Hono(); + + adminDatasetsRouter.get("/", async (c) => { + return c.json({ datasets: listAdminDatasets() }, 200); + }); + + adminDatasetsRouter.get("/:datasetId", async (c) => { + const supabase = c.get("supabase"); + const datasetId = c.req.param("datasetId"); + const definition = getAdminDatasetDefinition(datasetId); + + if (!definition) { + return c.json({ error: `Admin dataset '${datasetId}' is not registered` }, 404); + } + + try { + const dataset = await getDatasetPoints(datasetId, supabase); + + return c.json( + { + ...definition, + ...dataset, + } satisfies AdminDatasetResult, + 200 + ); + } catch { + return c.json({ error: `Failed to load admin dataset '${datasetId}'` }, 500); + } + }); + + return adminDatasetsRouter; +}; diff --git a/apps/api/src/routers/adminOverview.ts b/apps/api/src/routers/adminOverview.ts new file mode 100644 index 0000000..fc5b3f1 --- /dev/null +++ b/apps/api/src/routers/adminOverview.ts @@ -0,0 +1,144 @@ +import { Hono } from "hono"; +import type { AdminOverviewResponse } from "@xtablo/shared-types"; +import type { BaseEnv } from "../types/app.types.js"; + +function startOfRecentWindow(days: number) { + const date = new Date(); + date.setUTCDate(date.getUTCDate() - days); + return date.toISOString(); +} + +async function countRows( + query: PromiseLike<{ count: number | null; error: { message: string } | null }> +) { + const { count, error } = await query; + + if (error) { + throw new Error(error.message); + } + + return count ?? 0; +} + +export const getAdminOverviewRouter = () => { + const adminOverviewRouter = new Hono(); + + adminOverviewRouter.get("/", async (c) => { + const supabase = c.get("supabase"); + const sevenDaysAgo = startOfRecentWindow(7); + + try { + const [ + totalUsers, + recentUsers, + totalTablos, + recentTablos, + activeAccess, + adminAccess, + temporaryUsers, + inactiveAccess, + ] = await Promise.all([ + countRows(supabase.from("profiles").select("*", { count: "exact", head: true })), + countRows( + supabase + .from("profiles") + .select("*", { count: "exact", head: true }) + .gte("created_at", sevenDaysAgo) + ), + countRows( + supabase + .from("tablos") + .select("*", { count: "exact", head: true }) + .is("deleted_at", null) + ), + countRows( + supabase + .from("tablos") + .select("*", { count: "exact", head: true }) + .is("deleted_at", null) + .gte("created_at", sevenDaysAgo) + ), + countRows( + supabase + .from("tablo_access") + .select("*", { count: "exact", head: true }) + .eq("is_active", true) + ), + countRows( + supabase + .from("tablo_access") + .select("*", { count: "exact", head: true }) + .eq("is_active", true) + .eq("is_admin", true) + ), + countRows( + supabase + .from("profiles") + .select("*", { count: "exact", head: true }) + .eq("is_temporary", true) + ), + countRows( + supabase + .from("tablo_access") + .select("*", { count: "exact", head: true }) + .eq("is_active", false) + ), + ]); + + const response: AdminOverviewResponse = { + alerts: [ + { + description: `${temporaryUsers} temporary users still exist in production.`, + id: "temporary-users", + severity: temporaryUsers > 0 ? "warning" : "info", + title: "Temporary Accounts", + }, + { + description: `${inactiveAccess} tablo access rows are inactive and may need review.`, + id: "inactive-access", + severity: inactiveAccess > 10 ? "critical" : "warning", + title: "Inactive Access Drift", + }, + ], + metrics: [ + { + changeLabel: `+${recentUsers} last 7d`, + id: "total-users", + label: "Total Users", + value: totalUsers.toLocaleString(), + }, + { + changeLabel: `+${recentTablos} last 7d`, + id: "total-tablos", + label: "Active Tablos", + value: totalTablos.toLocaleString(), + }, + { + changeLabel: `${adminAccess} admin grants`, + id: "active-access", + label: "Active Access", + value: activeAccess.toLocaleString(), + }, + { + changeLabel: `${temporaryUsers} temporary`, + id: "admin-access", + label: "Admin Grants", + value: adminAccess.toLocaleString(), + }, + ], + shortcuts: [ + { href: "/explorer", id: "profiles", label: "Inspect Users" }, + { href: "/explorer", id: "access", label: "Review Tablo Access" }, + { href: "/analytics", id: "growth", label: "Open Growth Analytics" }, + { href: "/actions", id: "actions", label: "Run Admin Actions" }, + ], + }; + + return c.json(response, 200); + } catch { + return c.json({ error: "Failed to load admin overview" }, 500); + } + }); + + return adminOverviewRouter; +}; diff --git a/apps/api/src/routers/adminTables.ts b/apps/api/src/routers/adminTables.ts index 02ec6ea..7f2b9da 100644 --- a/apps/api/src/routers/adminTables.ts +++ b/apps/api/src/routers/adminTables.ts @@ -1,5 +1,10 @@ import { Hono } from "hono"; -import { getAdminTableDefinition, listAdminTables, normalizeAdminRows } from "../helpers/adminRegistry.js"; +import { recordAdminAuditLog } from "../helpers/adminAudit.js"; +import { + getAdminTableDefinition, + listAdminTables, + normalizeAdminRows, +} from "../helpers/adminRegistry.js"; import type { BaseEnv } from "../types/app.types.js"; export const getAdminTablesRouter = () => { @@ -25,8 +30,10 @@ export const getAdminTablesRouter = () => { return c.json( { columns: tableDefinition.columns, + editableFields: tableDefinition.editableColumns ?? [], id: tableDefinition.id, label: tableDefinition.label, + primaryKey: tableDefinition.primaryKey, }, 200 ); @@ -63,5 +70,70 @@ export const getAdminTablesRouter = () => { return c.json({ rows: normalizeAdminRows(data ?? []) }, 200); }); + adminTablesRouter.patch("/:tableId/rows/:rowId", async (c) => { + const supabase = c.get("supabase"); + const adminSession = c.get("adminSession"); + const tableId = c.req.param("tableId"); + const rowId = c.req.param("rowId"); + const tableDefinition = getAdminTableDefinition(tableId); + + if (!tableDefinition) { + return c.json( + { + error: `Admin table '${tableId}' is not registered`, + }, + 404 + ); + } + + const body = await c.req.json().catch(() => null); + if (!body || typeof body !== "object") { + return c.json({ error: "Invalid update payload" }, 400); + } + + const requestedChanges = Object.fromEntries( + Object.entries(body).filter(([key]) => tableDefinition.editableColumns?.includes(key)) + ); + + if (Object.keys(requestedChanges).length === 0) { + return c.json({ error: "No editable fields provided" }, 400); + } + + const { data: existingRow, error: existingRowError } = await supabase + .from(tableDefinition.source) + .select(tableDefinition.select) + .eq(tableDefinition.primaryKey, rowId) + .single(); + + if (existingRowError || !existingRow) { + return c.json({ error: `Admin row '${rowId}' was not found` }, 404); + } + + const { data: updatedRow, error: updateError } = await supabase + .from(tableDefinition.source) + .update(requestedChanges) + .eq(tableDefinition.primaryKey, rowId) + .select(tableDefinition.select) + .single(); + + if (updateError || !updatedRow) { + return c.json({ error: `Failed to update admin table '${tableId}'` }, 500); + } + + await recordAdminAuditLog({ + action: "update", + after: updatedRow, + before: existingRow, + operatorEmail: adminSession.operatorEmail, + operatorId: adminSession.operatorId, + role: adminSession.role, + supabase, + targetId: rowId, + targetType: tableId, + }); + + return c.json({ row: updatedRow }, 200); + }); + return adminTablesRouter; }; diff --git a/docs/ADMIN_APP_ACCESS_SETUP.md b/docs/ADMIN_APP_ACCESS_SETUP.md new file mode 100644 index 0000000..0e27441 --- /dev/null +++ b/docs/ADMIN_APP_ACCESS_SETUP.md @@ -0,0 +1,56 @@ +# Admin App Access Setup + +The admin app is designed to be internal-only and requires a separate privileged token flow. + +## Required API configuration + +Set these values for `apps/api`: + +- `ADMIN_TOKEN_SIGNING_SECRET` +- `ADMIN_TOKEN_AUDIENCE` +- `ADMIN_APP_URL` + +`ADMIN_TOKEN_SIGNING_SECRET` signs short-lived admin session tokens. +`ADMIN_TOKEN_AUDIENCE` scopes privileged access to the admin app only. +`ADMIN_APP_URL` is the allowed frontend origin for the internal admin surface. + +## Access model + +1. The operator reaches the private `apps/admin` deployment from the internal network boundary. +2. The operator pastes a privileged access token into the admin gate. +3. `POST /admin/auth/exchange` validates that token and returns a short-lived `admin_session`. +4. The admin app stores that session locally and attaches it as a bearer token for admin routes. +5. All privileged data and mutations go through `/admin/*` API routes guarded by admin middleware. + +Normal product auth is not sufficient for admin access. + +## Current guarded routes + +- `GET /admin/overview` +- `GET /admin/tables` +- `GET /admin/tables/:tableId/meta` +- `GET /admin/tables/:tableId/rows` +- `PATCH /admin/tables/:tableId/rows/:rowId` +- `GET /admin/datasets` +- `GET /admin/datasets/:datasetId` +- `GET /admin/actions` +- `POST /admin/actions/:actionId/run` + +All write paths emit admin audit log entries. + +## Local development + +- Run the API and local Supabase stack. +- Start the admin app with `pnpm dev:admin`. +- Use a valid privileged access token compatible with `ADMIN_TOKEN_SIGNING_SECRET` and `ADMIN_TOKEN_AUDIENCE`. + +## Initial action coverage + +- `deactivate_tablo_access` +- `grant_tablo_admin` + +## Initial analytics coverage + +- `profile_growth` +- `plan_mix` +- `tablo_access_mix` diff --git a/packages/shared-types/src/admin.types.ts b/packages/shared-types/src/admin.types.ts index 2859ec8..bc85f9c 100644 --- a/packages/shared-types/src/admin.types.ts +++ b/packages/shared-types/src/admin.types.ts @@ -28,6 +28,73 @@ export type AdminTableColumn = { export type AdminTableMeta = { columns: AdminTableColumn[]; + editableFields: string[]; + id: string; + label: string; + primaryKey: string; +}; + +export type AdminOverviewMetric = { + changeLabel: string; + id: string; + label: string; + value: string; +}; + +export type AdminOverviewAlert = { + description: string; + id: string; + severity: "info" | "warning" | "critical"; + title: string; +}; + +export type AdminOverviewShortcut = { + href: string; id: string; label: string; }; + +export type AdminOverviewResponse = { + alerts: AdminOverviewAlert[]; + metrics: AdminOverviewMetric[]; + shortcuts: AdminOverviewShortcut[]; +}; + +export type AdminDatasetChartType = "bar" | "line" | "donut"; + +export type AdminDatasetSummary = { + description: string; + id: string; + label: string; +}; + +export type AdminDatasetPoint = { + label: string; + value: number; +}; + +export type AdminDatasetResult = AdminDatasetSummary & { + chartType: AdminDatasetChartType; + dimensionLabel: string; + metricLabel: string; + points: AdminDatasetPoint[]; +}; + +export type AdminActionField = { + id: string; + label: string; + placeholder?: string; + required?: boolean; +}; + +export type AdminActionSummary = { + description: string; + fields: AdminActionField[]; + id: string; + label: string; +}; + +export type AdminActionRunResponse = { + message: string; + success: boolean; +}; diff --git a/packages/shared-types/src/index.ts b/packages/shared-types/src/index.ts index 11a7446..8c42acc 100644 --- a/packages/shared-types/src/index.ts +++ b/packages/shared-types/src/index.ts @@ -2,6 +2,17 @@ // Admin Types // ============================================================================ export type { + AdminActionField, + AdminActionRunResponse, + AdminActionSummary, + AdminDatasetChartType, + AdminDatasetPoint, + AdminDatasetResult, + AdminDatasetSummary, + AdminOverviewAlert, + AdminOverviewMetric, + AdminOverviewResponse, + AdminOverviewShortcut, AdminRole, AdminSessionInfo, AdminSessionResponse, diff --git a/supabase/migrations/20260424110000_create_admin_audit_log.sql b/supabase/migrations/20260424110000_create_admin_audit_log.sql new file mode 100644 index 0000000..45d8ebc --- /dev/null +++ b/supabase/migrations/20260424110000_create_admin_audit_log.sql @@ -0,0 +1,12 @@ +create table if not exists public.admin_audit_log ( + id bigserial primary key, + operator_id text not null, + operator_email text not null, + role text not null, + action text not null, + target_type text not null, + target_id text not null, + before jsonb, + after jsonb, + created_at timestamptz not null default now() +); From 9aff7e1bed5ded79d8992789461488dce4db3471 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Fri, 24 Apr 2026 16:15:55 +0200 Subject: [PATCH 68/75] feat(admin): harden app access at the worker edge --- .../admin/src/components/AdminLayout.test.tsx | 16 +- apps/admin/src/components/AdminLayout.tsx | 11 +- .../src/pages/AnalyticsStudioPage.test.tsx | 2 +- apps/admin/tsconfig.json | 2 +- apps/admin/worker/index.test.ts | 88 ++++++ apps/admin/worker/index.ts | 279 +++++++++++++++++- docs/ADMIN_APP_ACCESS_SETUP.md | 24 +- 7 files changed, 409 insertions(+), 13 deletions(-) create mode 100644 apps/admin/worker/index.test.ts diff --git a/apps/admin/src/components/AdminLayout.test.tsx b/apps/admin/src/components/AdminLayout.test.tsx index b9c5998..92fcc5c 100644 --- a/apps/admin/src/components/AdminLayout.test.tsx +++ b/apps/admin/src/components/AdminLayout.test.tsx @@ -1,4 +1,4 @@ -import { render, screen } from "@testing-library/react"; +import { fireEvent, render, screen } from "@testing-library/react"; import { MemoryRouter } from "react-router-dom"; import { beforeEach, describe, expect, it, vi } from "vitest"; import AppRoutes from "../routes"; @@ -46,5 +46,19 @@ describe("AdminLayout", () => { expect(screen.getByRole("link", { name: /data explorer/i })).toBeInTheDocument(); expect(screen.getByRole("link", { name: /analytics studio/i })).toBeInTheDocument(); expect(screen.getByRole("link", { name: /action center/i })).toBeInTheDocument(); + expect(screen.getByRole("button", { name: /lock admin app/i })).toBeInTheDocument(); + }); + + it("clears the stored admin session when locking the app", async () => { + render( + + + + ); + + const button = await screen.findByRole("button", { name: /lock admin app/i }); + fireEvent.click(button); + + expect(localStorage.getItem("xtablo-admin-session")).toBeNull(); }); }); diff --git a/apps/admin/src/components/AdminLayout.tsx b/apps/admin/src/components/AdminLayout.tsx index 4133974..257aa04 100644 --- a/apps/admin/src/components/AdminLayout.tsx +++ b/apps/admin/src/components/AdminLayout.tsx @@ -4,7 +4,7 @@ import { AdminNavigation } from "./AdminNavigation"; import { ProductionBadge } from "./ProductionBadge"; export function AdminLayout() { - const { operatorEmail } = useAdminSession(); + const { logout, operatorEmail } = useAdminSession(); return (
@@ -17,6 +17,15 @@ export function AdminLayout() {

{operatorEmail ?? "Unknown operator"}

+
+ +
diff --git a/apps/admin/src/pages/AnalyticsStudioPage.test.tsx b/apps/admin/src/pages/AnalyticsStudioPage.test.tsx index e6b710c..d9dc2c4 100644 --- a/apps/admin/src/pages/AnalyticsStudioPage.test.tsx +++ b/apps/admin/src/pages/AnalyticsStudioPage.test.tsx @@ -75,7 +75,7 @@ describe("AnalyticsStudioPage", () => { render(); expect(await screen.findByText(/analytics studio/i)).toBeInTheDocument(); - expect(await screen.findByText(/user growth/i)).toBeInTheDocument(); + expect(await screen.findByRole("button", { name: /user growth/i })).toBeInTheDocument(); fireEvent.click(screen.getByRole("button", { name: /plan mix/i })); diff --git a/apps/admin/tsconfig.json b/apps/admin/tsconfig.json index 586e2a9..4a98594 100644 --- a/apps/admin/tsconfig.json +++ b/apps/admin/tsconfig.json @@ -26,6 +26,6 @@ "@xtablo/shared-types/*": ["../../packages/shared-types/src/*"] } }, - "include": ["src"], + "include": ["src", "worker"], "references": [] } diff --git a/apps/admin/worker/index.test.ts b/apps/admin/worker/index.test.ts new file mode 100644 index 0000000..87124e8 --- /dev/null +++ b/apps/admin/worker/index.test.ts @@ -0,0 +1,88 @@ +// @vitest-environment node + +import { beforeEach, describe, expect, it, vi } from "vitest"; +import worker, { + ADMIN_APP_SESSION_COOKIE, + buildAccessDeniedHtml, + createSignedAdminAppSession, +} from "./index"; + +const env = { + ADMIN_APP_ACCESS_TOKEN: "super-secret-admin-app-token", + ADMIN_APP_SESSION_SECRET: "worker-session-secret", + ASSETS: { + fetch: vi.fn(async () => new Response("app", { status: 200 })), + }, +}; + +describe("admin worker firewall", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("serves the admin access gate when no session cookie is present", async () => { + const response = await worker.fetch( + new Request("https://admin.internal.xtablo.com/", { + headers: { + accept: "text/html", + }, + }), + env + ); + + expect(response.status).toBe(401); + await expect(response.text()).resolves.toContain("Internal Admin Access"); + }); + + it("creates a signed app session cookie from a valid access token", async () => { + const request = new Request("https://admin.internal.xtablo.com/__admin/access", { + body: new URLSearchParams({ accessToken: env.ADMIN_APP_ACCESS_TOKEN }), + headers: { + "Content-Type": "application/x-www-form-urlencoded", + }, + method: "POST", + }); + + const response = await worker.fetch(request, env); + + expect(response.status).toBe(302); + expect(response.headers.get("location")).toBe("https://admin.internal.xtablo.com/"); + expect(response.headers.get("set-cookie")).toContain(`${ADMIN_APP_SESSION_COOKIE}=`); + }); + + it("allows authenticated requests through to static assets", async () => { + const session = await createSignedAdminAppSession(env.ADMIN_APP_SESSION_SECRET); + const request = new Request("https://admin.internal.xtablo.com/", { + headers: { + cookie: `${ADMIN_APP_SESSION_COOKIE}=${session}`, + }, + }); + + const response = await worker.fetch(request, env); + + expect(response.status).toBe(200); + expect(env.ASSETS.fetch).toHaveBeenCalledOnce(); + }); + + it("rejects invalid access tokens", async () => { + const request = new Request("https://admin.internal.xtablo.com/__admin/access", { + body: new URLSearchParams({ accessToken: "wrong-token" }), + headers: { + accept: "text/html", + "Content-Type": "application/x-www-form-urlencoded", + }, + method: "POST", + }); + + const response = await worker.fetch(request, env); + + expect(response.status).toBe(401); + await expect(response.text()).resolves.toContain("Invalid app access token"); + }); +}); + +describe("buildAccessDeniedHtml", () => { + it("renders the access error when provided", () => { + expect(buildAccessDeniedHtml("Bad token")).toContain("Bad token"); + }); +}); diff --git a/apps/admin/worker/index.ts b/apps/admin/worker/index.ts index bee9dbb..32af99f 100644 --- a/apps/admin/worker/index.ts +++ b/apps/admin/worker/index.ts @@ -1,9 +1,280 @@ +export const ADMIN_APP_SESSION_COOKIE = "xtablo-admin-app-session"; +const ADMIN_ACCESS_PATH = "/__admin/access"; +const ADMIN_LOGOUT_PATH = "/__admin/logout"; +const SESSION_TTL_SECONDS = 60 * 60 * 12; + +type WorkerEnv = { + ADMIN_APP_ACCESS_TOKEN: string; + ADMIN_APP_SESSION_SECRET: string; + ASSETS: { + fetch: (request: Request) => Promise; + }; +}; + +function base64UrlEncode(bytes: Uint8Array) { + return btoa(String.fromCharCode(...bytes)) + .replace(/\+/g, "-") + .replace(/\//g, "_") + .replace(/=/g, ""); +} + +function base64UrlDecode(value: string) { + const normalized = value.replace(/-/g, "+").replace(/_/g, "/"); + const padding = normalized.length % 4 === 0 ? "" : "=".repeat(4 - (normalized.length % 4)); + const binary = atob(`${normalized}${padding}`); + + return Uint8Array.from(binary, (character) => character.charCodeAt(0)); +} + +async function importSigningKey(secret: string) { + return crypto.subtle.importKey( + "raw", + new TextEncoder().encode(secret), + { name: "HMAC", hash: "SHA-256" }, + false, + ["sign", "verify"] + ); +} + +async function signValue(value: string, secret: string) { + const key = await importSigningKey(secret); + const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(value)); + + return base64UrlEncode(new Uint8Array(signature)); +} + +async function verifyValueSignature(value: string, signature: string, secret: string) { + const key = await importSigningKey(secret); + + return crypto.subtle.verify( + "HMAC", + key, + base64UrlDecode(signature), + new TextEncoder().encode(value) + ); +} + +function parseCookie(cookieHeader: string | null, cookieName: string) { + if (!cookieHeader) { + return null; + } + + const match = cookieHeader.match(new RegExp(`(?:^|;\\s*)${cookieName}=([^;]+)`)); + return match?.[1] ?? null; +} + +export async function createSignedAdminAppSession(secret: string, now = Date.now()) { + const expiresAt = Math.floor(now / 1000) + SESSION_TTL_SECONDS; + const payload = `${expiresAt}`; + const signature = await signValue(payload, secret); + + return `${payload}.${signature}`; +} + +export async function hasValidAdminAppSession(request: Request, secret: string, now = Date.now()) { + const sessionCookie = parseCookie(request.headers.get("cookie"), ADMIN_APP_SESSION_COOKIE); + if (!sessionCookie) { + return false; + } + + const [expiresAtValue, signature] = sessionCookie.split("."); + if (!expiresAtValue || !signature) { + return false; + } + + const expiresAt = Number.parseInt(expiresAtValue, 10); + if (Number.isNaN(expiresAt) || expiresAt <= Math.floor(now / 1000)) { + return false; + } + + return verifyValueSignature(expiresAtValue, signature, secret); +} + +function isHtmlRequest(request: Request) { + const accept = request.headers.get("accept") ?? ""; + return accept.includes("text/html") || accept.includes("*/*"); +} + +function buildSessionCookie(session: string) { + return `${ADMIN_APP_SESSION_COOKIE}=${session}; HttpOnly; Path=/; SameSite=Strict; Secure; Max-Age=${SESSION_TTL_SECONDS}`; +} + +function buildExpiredSessionCookie() { + return `${ADMIN_APP_SESSION_COOKIE}=; HttpOnly; Path=/; SameSite=Strict; Secure; Max-Age=0`; +} + +export function buildAccessDeniedHtml(error?: string) { + return ` + + + + + XTablo Admin Access + + + +
+
Internal Only
+

Internal Admin Access

+

+ This app is firewalled behind a dedicated app-access token before any admin session + can be established. +

+
+ + + +
+ ${error ? `
${error}
` : ""} +

A second privileged token is still required inside the admin shell.

+
+ +`; +} + +function respondUnauthorized(request: Request, error?: string) { + if (isHtmlRequest(request)) { + return new Response(buildAccessDeniedHtml(error), { + headers: { + "Content-Type": "text/html; charset=utf-8", + "Cache-Control": "no-store", + }, + status: 401, + }); + } + + return new Response("Unauthorized", { status: 401 }); +} + +async function handleAccessRequest(request: Request, env: WorkerEnv) { + const formData = await request.formData().catch(() => null); + const accessToken = formData?.get("accessToken"); + + if (accessToken !== env.ADMIN_APP_ACCESS_TOKEN) { + return respondUnauthorized(request, "Invalid app access token"); + } + + const session = await createSignedAdminAppSession(env.ADMIN_APP_SESSION_SECRET); + const location = new URL("/", request.url).toString(); + + return new Response(null, { + headers: { + Location: location, + "Set-Cookie": buildSessionCookie(session), + "Cache-Control": "no-store", + }, + status: 302, + }); +} + +async function handleLogoutRequest(request: Request) { + return new Response(null, { + headers: { + Location: new URL("/", request.url).toString(), + "Set-Cookie": buildExpiredSessionCookie(), + "Cache-Control": "no-store", + }, + status: 302, + }); +} + export default { - fetch(request: Request) { + async fetch(request: Request, env: WorkerEnv) { const url = new URL(request.url); - if (url.pathname.startsWith("/api/")) { - return Response.json({ name: "XTablo Admin Worker" }); + + if (request.method === "POST" && url.pathname === ADMIN_ACCESS_PATH) { + return handleAccessRequest(request, env); } - return new Response(null, { status: 404 }); + + if (request.method === "POST" && url.pathname === ADMIN_LOGOUT_PATH) { + return handleLogoutRequest(request); + } + + const hasSession = await hasValidAdminAppSession(request, env.ADMIN_APP_SESSION_SECRET); + if (!hasSession) { + return respondUnauthorized(request); + } + + return env.ASSETS.fetch(request); }, }; diff --git a/docs/ADMIN_APP_ACCESS_SETUP.md b/docs/ADMIN_APP_ACCESS_SETUP.md index 0e27441..8734cca 100644 --- a/docs/ADMIN_APP_ACCESS_SETUP.md +++ b/docs/ADMIN_APP_ACCESS_SETUP.md @@ -2,6 +2,16 @@ The admin app is designed to be internal-only and requires a separate privileged token flow. +## Required admin worker configuration + +Set these values for `apps/admin`: + +- `ADMIN_APP_ACCESS_TOKEN` +- `ADMIN_APP_SESSION_SECRET` + +`ADMIN_APP_ACCESS_TOKEN` is the first-layer token required before the admin SPA will be served. +`ADMIN_APP_SESSION_SECRET` signs the worker-issued app session cookie after that token is accepted. + ## Required API configuration Set these values for `apps/api`: @@ -17,10 +27,13 @@ Set these values for `apps/api`: ## Access model 1. The operator reaches the private `apps/admin` deployment from the internal network boundary. -2. The operator pastes a privileged access token into the admin gate. -3. `POST /admin/auth/exchange` validates that token and returns a short-lived `admin_session`. -4. The admin app stores that session locally and attaches it as a bearer token for admin routes. -5. All privileged data and mutations go through `/admin/*` API routes guarded by admin middleware. +2. The admin worker presents a dedicated app-access gate before any SPA asset is served. +3. The operator submits the app access token, and the worker issues a signed session cookie. +4. Only then does the browser load the React admin shell. +5. Inside the shell, the operator pastes a separate privileged admin API token. +6. `POST /admin/auth/exchange` validates that token and returns a short-lived `admin_session`. +7. The admin app stores that session locally and attaches it as a bearer token for admin routes. +8. All privileged data and mutations go through `/admin/*` API routes guarded by admin middleware. Normal product auth is not sufficient for admin access. @@ -42,7 +55,8 @@ All write paths emit admin audit log entries. - Run the API and local Supabase stack. - Start the admin app with `pnpm dev:admin`. -- Use a valid privileged access token compatible with `ADMIN_TOKEN_SIGNING_SECRET` and `ADMIN_TOKEN_AUDIENCE`. +- Configure worker env for `ADMIN_APP_ACCESS_TOKEN` and `ADMIN_APP_SESSION_SECRET`. +- Use the app-access token at the worker gate, then use a valid privileged API token compatible with `ADMIN_TOKEN_SIGNING_SECRET` and `ADMIN_TOKEN_AUDIENCE`. ## Initial action coverage From 657ebc44b9419dfff44f5bdfd040e5aa323139d5 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Fri, 24 Apr 2026 16:22:51 +0200 Subject: [PATCH 69/75] chore(admin): align domain and deploy command --- apps/admin/worker/index.test.ts | 10 +++++----- apps/admin/wrangler.toml | 6 +----- docs/ADMIN_APP_ACCESS_SETUP.md | 18 +++++++++++++++++- package.json | 2 +- 4 files changed, 24 insertions(+), 12 deletions(-) diff --git a/apps/admin/worker/index.test.ts b/apps/admin/worker/index.test.ts index 87124e8..41bc176 100644 --- a/apps/admin/worker/index.test.ts +++ b/apps/admin/worker/index.test.ts @@ -22,7 +22,7 @@ describe("admin worker firewall", () => { it("serves the admin access gate when no session cookie is present", async () => { const response = await worker.fetch( - new Request("https://admin.internal.xtablo.com/", { + new Request("https://admin-panel.xtablo.com/", { headers: { accept: "text/html", }, @@ -35,7 +35,7 @@ describe("admin worker firewall", () => { }); it("creates a signed app session cookie from a valid access token", async () => { - const request = new Request("https://admin.internal.xtablo.com/__admin/access", { + const request = new Request("https://admin-panel.xtablo.com/__admin/access", { body: new URLSearchParams({ accessToken: env.ADMIN_APP_ACCESS_TOKEN }), headers: { "Content-Type": "application/x-www-form-urlencoded", @@ -46,13 +46,13 @@ describe("admin worker firewall", () => { const response = await worker.fetch(request, env); expect(response.status).toBe(302); - expect(response.headers.get("location")).toBe("https://admin.internal.xtablo.com/"); + expect(response.headers.get("location")).toBe("https://admin-panel.xtablo.com/"); expect(response.headers.get("set-cookie")).toContain(`${ADMIN_APP_SESSION_COOKIE}=`); }); it("allows authenticated requests through to static assets", async () => { const session = await createSignedAdminAppSession(env.ADMIN_APP_SESSION_SECRET); - const request = new Request("https://admin.internal.xtablo.com/", { + const request = new Request("https://admin-panel.xtablo.com/", { headers: { cookie: `${ADMIN_APP_SESSION_COOKIE}=${session}`, }, @@ -65,7 +65,7 @@ describe("admin worker firewall", () => { }); it("rejects invalid access tokens", async () => { - const request = new Request("https://admin.internal.xtablo.com/__admin/access", { + const request = new Request("https://admin-panel.xtablo.com/__admin/access", { body: new URLSearchParams({ accessToken: "wrong-token" }), headers: { accept: "text/html", diff --git a/apps/admin/wrangler.toml b/apps/admin/wrangler.toml index 8083093..2786105 100644 --- a/apps/admin/wrangler.toml +++ b/apps/admin/wrangler.toml @@ -9,8 +9,4 @@ not_found_handling = "single-page-application" [observability] enabled = true -[env.staging] -route = { pattern = "admin-staging.internal.xtablo.com", custom_domain = true } - -[env.production] -route = { pattern = "admin.internal.xtablo.com", custom_domain = true } +route = { pattern = "admin-panel.xtablo.com", custom_domain = true } diff --git a/docs/ADMIN_APP_ACCESS_SETUP.md b/docs/ADMIN_APP_ACCESS_SETUP.md index 8734cca..764575a 100644 --- a/docs/ADMIN_APP_ACCESS_SETUP.md +++ b/docs/ADMIN_APP_ACCESS_SETUP.md @@ -12,6 +12,22 @@ Set these values for `apps/admin`: `ADMIN_APP_ACCESS_TOKEN` is the first-layer token required before the admin SPA will be served. `ADMIN_APP_SESSION_SECRET` signs the worker-issued app session cookie after that token is accepted. +Production domain: `https://admin-panel.xtablo.com` + +## Deploy commands + +Use the root command: + +```bash +pnpm deploy:admin +``` + +Or directly from the app package: + +```bash +pnpm --filter @xtablo/admin deploy +``` + ## Required API configuration Set these values for `apps/api`: @@ -22,7 +38,7 @@ Set these values for `apps/api`: `ADMIN_TOKEN_SIGNING_SECRET` signs short-lived admin session tokens. `ADMIN_TOKEN_AUDIENCE` scopes privileged access to the admin app only. -`ADMIN_APP_URL` is the allowed frontend origin for the internal admin surface. +`ADMIN_APP_URL` is the allowed frontend origin for the admin surface, for example `https://admin-panel.xtablo.com`. ## Access model diff --git a/package.json b/package.json index 6c383b5..9885577 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,7 @@ "dev:api": "turbo dev --filter=@xtablo/api", "deploy:main:staging": "turbo deploy:staging --filter=@xtablo/main", "deploy:main:prod": "turbo deploy:prod --filter=@xtablo/main", - "deploy:admin": "turbo deploy --filter=@xtablo/admin", + "deploy:admin": "pnpm --filter @xtablo/admin deploy", "deploy:chat": "turbo deploy --filter=@xtablo/chat-worker", "deploy:external": "turbo deploy --filter=@xtablo/external", "lint": "turbo lint", From 13af8f66c0af937c8d143bab10d8503e2703b2b3 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Fri, 24 Apr 2026 16:25:38 +0200 Subject: [PATCH 70/75] chore(admin): run deploy through turbo --- docs/ADMIN_APP_ACCESS_SETUP.md | 2 +- package.json | 2 +- turbo.json | 6 +++++- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/ADMIN_APP_ACCESS_SETUP.md b/docs/ADMIN_APP_ACCESS_SETUP.md index 764575a..b4f09a1 100644 --- a/docs/ADMIN_APP_ACCESS_SETUP.md +++ b/docs/ADMIN_APP_ACCESS_SETUP.md @@ -25,7 +25,7 @@ pnpm deploy:admin Or directly from the app package: ```bash -pnpm --filter @xtablo/admin deploy +pnpm --filter @xtablo/admin run deploy ``` ## Required API configuration diff --git a/package.json b/package.json index 9885577..6c383b5 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,7 @@ "dev:api": "turbo dev --filter=@xtablo/api", "deploy:main:staging": "turbo deploy:staging --filter=@xtablo/main", "deploy:main:prod": "turbo deploy:prod --filter=@xtablo/main", - "deploy:admin": "pnpm --filter @xtablo/admin deploy", + "deploy:admin": "turbo deploy --filter=@xtablo/admin", "deploy:chat": "turbo deploy --filter=@xtablo/chat-worker", "deploy:external": "turbo deploy --filter=@xtablo/external", "lint": "turbo lint", diff --git a/turbo.json b/turbo.json index 48afb1d..b9e2ebe 100644 --- a/turbo.json +++ b/turbo.json @@ -18,6 +18,11 @@ "cache": false, "persistent": true }, + "deploy": { + "cache": false, + "dependsOn": ["build"], + "outputLogs": "new-only" + }, "lint": { "inputs": ["src/**", "biome.json", "package.json"], "outputLogs": "new-only" @@ -48,4 +53,3 @@ } } } - From 4be99b990070161142c95229be397d1c131b8573 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Fri, 24 Apr 2026 16:43:00 +0200 Subject: [PATCH 71/75] lint --- .../admin/src/components/AdminLayout.test.tsx | 8 +- .../src/components/PrivilegedGate.test.tsx | 2 +- apps/admin/src/components/PrivilegedGate.tsx | 6 +- .../src/components/actions/ActionRunner.tsx | 8 +- .../src/components/analytics/ChartBuilder.tsx | 16 +- .../components/data-explorer/RowEditForm.tsx | 5 +- apps/admin/src/hooks/useAdminDatasets.ts | 8 +- apps/admin/src/hooks/useAdminSession.ts | 4 +- .../admin/src/pages/ActionCenterPage.test.tsx | 13 +- .../src/pages/AnalyticsStudioPage.test.tsx | 4 +- apps/admin/src/pages/AnalyticsStudioPage.tsx | 4 +- apps/admin/src/pages/DataExplorerPage.tsx | 21 +- apps/admin/src/routes.tsx | 6 +- apps/admin/tsconfig.tsbuildinfo | 1 + apps/admin/wrangler.toml | 4 +- .../__tests__/helpers/adminTokenTestUtils.ts | 4 +- .../__tests__/middlewares/adminAuth.test.ts | 2 +- .../__tests__/middlewares/middlewares.test.ts | 14 +- .../src/__tests__/routes/adminActions.test.ts | 2 +- .../src/__tests__/routes/adminAuth.test.ts | 2 +- .../__tests__/routes/adminDatasets.test.ts | 2 +- .../__tests__/routes/adminTableEdits.test.ts | 6 +- .../src/__tests__/routes/adminTables.test.ts | 2 +- apps/api/src/__tests__/routes/tablo.test.ts | 2 +- apps/api/src/helpers/adminAudit.ts | 22 +- apps/api/src/helpers/orgIcons.test.ts | 18 +- apps/api/src/routers/adminActions.ts | 11 +- apps/api/src/routers/adminDatasets.ts | 12 +- apps/api/src/routers/adminOverview.ts | 7 +- apps/api/src/routers/index.ts | 2 +- apps/api/src/routers/tablo.ts | 79 +- apps/api/src/routers/tablo_data.ts | 98 +- apps/api/src/routers/user.ts | 1 - apps/api/src/types/app.types.ts | 2 +- apps/clients/index.html | 2 +- apps/clients/src/pages/AuthCallback.tsx | 4 +- .../clients/src/pages/ClientTabloListPage.tsx | 6 +- apps/clients/src/pages/ClientTabloPage.tsx | 41 +- apps/clients/tsconfig.tsbuildinfo | 1 + apps/clients/vite.config.ts | 6 +- apps/clients/worker-configuration.d.ts | 8376 +++++++++++++++++ apps/clients/wrangler.toml | 9 +- biome.json | 6 + packages/shared/package.json | 2 +- prompts/rework_temporary_users.txt | 20 + 45 files changed, 8632 insertions(+), 239 deletions(-) create mode 100644 apps/admin/tsconfig.tsbuildinfo create mode 100644 apps/clients/tsconfig.tsbuildinfo create mode 100644 apps/clients/worker-configuration.d.ts create mode 100644 prompts/rework_temporary_users.txt diff --git a/apps/admin/src/components/AdminLayout.test.tsx b/apps/admin/src/components/AdminLayout.test.tsx index 92fcc5c..469d6af 100644 --- a/apps/admin/src/components/AdminLayout.test.tsx +++ b/apps/admin/src/components/AdminLayout.test.tsx @@ -1,9 +1,9 @@ import { fireEvent, render, screen } from "@testing-library/react"; import { MemoryRouter } from "react-router-dom"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import AppRoutes from "../routes"; -import { adminApi } from "../lib/api"; import { storeAdminSession } from "../lib/adminSession"; +import { adminApi } from "../lib/api"; +import AppRoutes from "../routes"; vi.mock("../lib/api", () => ({ adminApi: { @@ -40,7 +40,9 @@ describe("AdminLayout", () => { expect(await screen.findByText(/^production$/i)).toBeInTheDocument(); expect( - screen.getByRole("heading", { name: /production command deck for privileged supabase operations/i }) + screen.getByRole("heading", { + name: /production command deck for privileged supabase operations/i, + }) ).toBeInTheDocument(); expect(screen.getByRole("link", { name: /operations home/i })).toBeInTheDocument(); expect(screen.getByRole("link", { name: /data explorer/i })).toBeInTheDocument(); diff --git a/apps/admin/src/components/PrivilegedGate.test.tsx b/apps/admin/src/components/PrivilegedGate.test.tsx index 60c1687..72e19dd 100644 --- a/apps/admin/src/components/PrivilegedGate.test.tsx +++ b/apps/admin/src/components/PrivilegedGate.test.tsx @@ -1,8 +1,8 @@ import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import { MemoryRouter } from "react-router-dom"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import AppRoutes from "../routes"; import { adminApi } from "../lib/api"; +import AppRoutes from "../routes"; vi.mock("../lib/api", () => ({ adminApi: { diff --git a/apps/admin/src/components/PrivilegedGate.tsx b/apps/admin/src/components/PrivilegedGate.tsx index c22168f..3bdfa36 100644 --- a/apps/admin/src/components/PrivilegedGate.tsx +++ b/apps/admin/src/components/PrivilegedGate.tsx @@ -6,11 +6,7 @@ type PrivilegedGateProps = { onUnlock: (accessToken: string) => Promise; }; -export function PrivilegedGate({ - error = null, - isPending = false, - onUnlock, -}: PrivilegedGateProps) { +export function PrivilegedGate({ error = null, isPending = false, onUnlock }: PrivilegedGateProps) { const [accessToken, setAccessToken] = useState(""); const handleSubmit = async (event: FormEvent) => { diff --git a/apps/admin/src/components/actions/ActionRunner.tsx b/apps/admin/src/components/actions/ActionRunner.tsx index a656aec..6d0bf05 100644 --- a/apps/admin/src/components/actions/ActionRunner.tsx +++ b/apps/admin/src/components/actions/ActionRunner.tsx @@ -32,12 +32,12 @@ export function ActionRunner({ return; } - setValues( - Object.fromEntries(selectedAction.fields.map((field) => [field.id, ""])) - ); + setValues(Object.fromEntries(selectedAction.fields.map((field) => [field.id, ""]))); }, [selectedAction]); - const tone = selectedAction ? actionSeverityCopy[selectedAction.id as keyof typeof actionSeverityCopy] : null; + const tone = selectedAction + ? actionSeverityCopy[selectedAction.id as keyof typeof actionSeverityCopy] + : null; return (
diff --git a/apps/admin/src/components/analytics/ChartBuilder.tsx b/apps/admin/src/components/analytics/ChartBuilder.tsx index 9a60cad..9bc80b4 100644 --- a/apps/admin/src/components/analytics/ChartBuilder.tsx +++ b/apps/admin/src/components/analytics/ChartBuilder.tsx @@ -1,4 +1,8 @@ -import type { AdminDatasetPoint, AdminDatasetResult, AdminDatasetSummary } from "@xtablo/shared-types"; +import type { + AdminDatasetPoint, + AdminDatasetResult, + AdminDatasetSummary, +} from "@xtablo/shared-types"; type ChartBuilderProps = { dataset: AdminDatasetResult | null; @@ -65,7 +69,10 @@ function LineChart({ points }: { points: AdminDatasetPoint[] }) {
{points.map((point) => ( -
+

{point.label}

{point.value}

@@ -104,7 +111,10 @@ function DonutChart({ points }: { points: AdminDatasetPoint[] }) {
{points.map((point, index) => ( -
+
))} - diff --git a/apps/admin/src/hooks/useAdminDatasets.ts b/apps/admin/src/hooks/useAdminDatasets.ts index 12907dd..b74bd4d 100644 --- a/apps/admin/src/hooks/useAdminDatasets.ts +++ b/apps/admin/src/hooks/useAdminDatasets.ts @@ -39,7 +39,9 @@ export function useAdminDatasets() { } setDatasets(response.data.datasets); - setSelectedDatasetId((currentValue) => currentValue ?? response.data.datasets[0]?.id ?? null); + setSelectedDatasetId( + (currentValue) => currentValue ?? response.data.datasets[0]?.id ?? null + ); } catch (error) { if (isMounted) { setError(getErrorMessage(error, "Failed to load admin datasets")); @@ -68,7 +70,9 @@ export function useAdminDatasets() { setError(null); try { - const response = await adminApi.get(`/admin/datasets/${selectedDatasetId}`); + const response = await adminApi.get( + `/admin/datasets/${selectedDatasetId}` + ); if (!isMounted) { return; diff --git a/apps/admin/src/hooks/useAdminSession.ts b/apps/admin/src/hooks/useAdminSession.ts index d52845e..0f25690 100644 --- a/apps/admin/src/hooks/useAdminSession.ts +++ b/apps/admin/src/hooks/useAdminSession.ts @@ -1,12 +1,12 @@ import type { AdminSessionResponse } from "@xtablo/shared-types"; import { useEffect, useState } from "react"; -import { adminApi } from "../lib/api"; import { clearStoredAdminSession, getStoredAdminSession, - storeAdminSession, type StoredAdminSession, + storeAdminSession, } from "../lib/adminSession"; +import { adminApi } from "../lib/api"; export function useAdminSession() { const [session, setSession] = useState(() => getStoredAdminSession()); diff --git a/apps/admin/src/pages/ActionCenterPage.test.tsx b/apps/admin/src/pages/ActionCenterPage.test.tsx index e7ce473..6ffa003 100644 --- a/apps/admin/src/pages/ActionCenterPage.test.tsx +++ b/apps/admin/src/pages/ActionCenterPage.test.tsx @@ -55,14 +55,11 @@ describe("ActionCenterPage", () => { fireEvent.click(screen.getByRole("button", { name: /run action/i })); await waitFor(() => - expect(adminApi.post).toHaveBeenCalledWith( - "/admin/actions/deactivate_tablo_access/run", - { - reason: "manual cleanup", - tabloId: "tablo-1", - userId: "user-1", - } - ) + expect(adminApi.post).toHaveBeenCalledWith("/admin/actions/deactivate_tablo_access/run", { + reason: "manual cleanup", + tabloId: "tablo-1", + userId: "user-1", + }) ); expect(await screen.findByText(/deactivated and logged/i)).toBeInTheDocument(); }); diff --git a/apps/admin/src/pages/AnalyticsStudioPage.test.tsx b/apps/admin/src/pages/AnalyticsStudioPage.test.tsx index d9dc2c4..f55d574 100644 --- a/apps/admin/src/pages/AnalyticsStudioPage.test.tsx +++ b/apps/admin/src/pages/AnalyticsStudioPage.test.tsx @@ -79,9 +79,7 @@ describe("AnalyticsStudioPage", () => { fireEvent.click(screen.getByRole("button", { name: /plan mix/i })); - await waitFor(() => - expect(adminApi.get).toHaveBeenCalledWith("/admin/datasets/plan_mix") - ); + await waitFor(() => expect(adminApi.get).toHaveBeenCalledWith("/admin/datasets/plan_mix")); expect(await screen.findByText(/total/i)).toBeInTheDocument(); }); }); diff --git a/apps/admin/src/pages/AnalyticsStudioPage.tsx b/apps/admin/src/pages/AnalyticsStudioPage.tsx index 7cbbe8b..1f696f6 100644 --- a/apps/admin/src/pages/AnalyticsStudioPage.tsx +++ b/apps/admin/src/pages/AnalyticsStudioPage.tsx @@ -13,8 +13,8 @@ export function AnalyticsStudioPage() {

Analytics

Analytics Studio

- Curated production datasets for operators who need charted context before they take - action in the explorer or action center. + Curated production datasets for operators who need charted context before they take action + in the explorer or action center.

diff --git a/apps/admin/src/pages/DataExplorerPage.tsx b/apps/admin/src/pages/DataExplorerPage.tsx index f448f6f..a7e35e8 100644 --- a/apps/admin/src/pages/DataExplorerPage.tsx +++ b/apps/admin/src/pages/DataExplorerPage.tsx @@ -4,16 +4,8 @@ import { RowEditForm } from "../components/data-explorer/RowEditForm"; import { useAdminTables } from "../hooks/useAdminTables"; export function DataExplorerPage() { - const { - error, - isLoading, - meta, - rows, - selectedTableId, - setSelectedTableId, - tables, - updateRow, - } = useAdminTables(); + const { error, isLoading, meta, rows, selectedTableId, setSelectedTableId, tables, updateRow } = + useAdminTables(); const [selectedRowId, setSelectedRowId] = useState(null); const [isSaving, setIsSaving] = useState(false); const [saveMessage, setSaveMessage] = useState(null); @@ -28,9 +20,7 @@ export function DataExplorerPage() { return null; } - return ( - rows.find((row) => String(row[meta.primaryKey] ?? "") === selectedRowId) ?? null - ); + return rows.find((row) => String(row[meta.primaryKey] ?? "") === selectedRowId) ?? null; }, [meta, rows, selectedRowId]); const handleSave = async (changes: Record) => { @@ -111,10 +101,7 @@ export function DataExplorerPage() {
{meta.columns.map((column) => ( -
+

{column.label}

diff --git a/apps/admin/src/routes.tsx b/apps/admin/src/routes.tsx index b637b3b..d3ddd57 100644 --- a/apps/admin/src/routes.tsx +++ b/apps/admin/src/routes.tsx @@ -1,11 +1,11 @@ import { Outlet, Route, Routes } from "react-router-dom"; +import { AdminLayout } from "./components/AdminLayout"; +import { PrivilegedGate } from "./components/PrivilegedGate"; +import { useAdminSession } from "./hooks/useAdminSession"; import { ActionCenterPage } from "./pages/ActionCenterPage"; import { AnalyticsStudioPage } from "./pages/AnalyticsStudioPage"; import { DataExplorerPage } from "./pages/DataExplorerPage"; import { OperationsHomePage } from "./pages/OperationsHomePage"; -import { AdminLayout } from "./components/AdminLayout"; -import { PrivilegedGate } from "./components/PrivilegedGate"; -import { useAdminSession } from "./hooks/useAdminSession"; function AdminEntry() { const { error, isAuthenticated, isPending, unlock } = useAdminSession(); diff --git a/apps/admin/tsconfig.tsbuildinfo b/apps/admin/tsconfig.tsbuildinfo new file mode 100644 index 0000000..bbb6911 --- /dev/null +++ b/apps/admin/tsconfig.tsbuildinfo @@ -0,0 +1 @@ +{"root":["./src/app.tsx","./src/main.tsx","./src/routes.test.tsx","./src/routes.tsx","./src/setuptests.ts","./src/components/adminlayout.test.tsx","./src/components/adminlayout.tsx","./src/components/adminnavigation.tsx","./src/components/privilegedgate.test.tsx","./src/components/privilegedgate.tsx","./src/components/productionbadge.tsx","./src/components/actions/actionrunner.tsx","./src/components/analytics/chartbuilder.tsx","./src/components/analytics/saveddashboardlist.tsx","./src/components/data-explorer/admingrid.tsx","./src/components/data-explorer/roweditform.test.tsx","./src/components/data-explorer/roweditform.tsx","./src/hooks/useadminactions.ts","./src/hooks/useadmindatasets.ts","./src/hooks/useadminoverview.ts","./src/hooks/useadminsession.ts","./src/hooks/useadmintables.ts","./src/lib/adminsession.ts","./src/lib/api.ts","./src/pages/actioncenterpage.test.tsx","./src/pages/actioncenterpage.tsx","./src/pages/analyticsstudiopage.test.tsx","./src/pages/analyticsstudiopage.tsx","./src/pages/dataexplorerpage.test.tsx","./src/pages/dataexplorerpage.tsx","./src/pages/operationshomepage.tsx","./src/registry/actions.ts","./src/registry/datasets.ts","./worker/index.test.ts","./worker/index.ts"],"version":"5.9.3"} \ No newline at end of file diff --git a/apps/admin/wrangler.toml b/apps/admin/wrangler.toml index 2786105..8889e95 100644 --- a/apps/admin/wrangler.toml +++ b/apps/admin/wrangler.toml @@ -9,4 +9,6 @@ not_found_handling = "single-page-application" [observability] enabled = true -route = { pattern = "admin-panel.xtablo.com", custom_domain = true } +[[routes]] +pattern = "admin-panel.xtablo.com" +custom_domain = true diff --git a/apps/api/src/__tests__/helpers/adminTokenTestUtils.ts b/apps/api/src/__tests__/helpers/adminTokenTestUtils.ts index 4b024d0..859816e 100644 --- a/apps/api/src/__tests__/helpers/adminTokenTestUtils.ts +++ b/apps/api/src/__tests__/helpers/adminTokenTestUtils.ts @@ -16,9 +16,7 @@ function encodeSegment(value: unknown) { export function createSignedAdminToken(claims: TestAdminTokenClaims, secret: string) { const header = encodeSegment({ alg: "HS256", typ: "JWT" }); const payload = encodeSegment(claims); - const signature = createHmac("sha256", secret) - .update(`${header}.${payload}`) - .digest("base64url"); + const signature = createHmac("sha256", secret).update(`${header}.${payload}`).digest("base64url"); return `${header}.${payload}.${signature}`; } diff --git a/apps/api/src/__tests__/middlewares/adminAuth.test.ts b/apps/api/src/__tests__/middlewares/adminAuth.test.ts index 1bc0393..a595103 100644 --- a/apps/api/src/__tests__/middlewares/adminAuth.test.ts +++ b/apps/api/src/__tests__/middlewares/adminAuth.test.ts @@ -1,8 +1,8 @@ -import { createSignedAdminToken } from "../helpers/adminTokenTestUtils.js"; import { describe, expect, it } from "vitest"; import { createConfig } from "../../config.js"; import { MiddlewareManager } from "../../middlewares/middleware.js"; import { getMainRouter } from "../../routers/index.js"; +import { createSignedAdminToken } from "../helpers/adminTokenTestUtils.js"; const ADMIN_TOKEN_SIGNING_SECRET = "admin-test-secret"; const ADMIN_TOKEN_AUDIENCE = "xtablo-admin"; diff --git a/apps/api/src/__tests__/middlewares/middlewares.test.ts b/apps/api/src/__tests__/middlewares/middlewares.test.ts index 52a9b20..e9c6646 100644 --- a/apps/api/src/__tests__/middlewares/middlewares.test.ts +++ b/apps/api/src/__tests__/middlewares/middlewares.test.ts @@ -24,9 +24,7 @@ describe("Middleware Tests", () => { }), }); - const createBillingStateSupabaseMock = (input: { - ownerPlan?: string | null; - }) => { + const createBillingStateSupabaseMock = (input: { ownerPlan?: string | null }) => { const ownerPlan = input.ownerPlan ?? "none"; return { @@ -325,7 +323,7 @@ describe("Middleware Tests", () => { createProfilesSupabaseMock({ data: { is_temporary: true }, error: null, - }) as any + }) ); // biome-ignore lint/suspicious/noExplicitAny: Test-only context injection (c as any).set("user", { id: "temp-user" } as any); @@ -352,7 +350,7 @@ describe("Middleware Tests", () => { createProfilesSupabaseMock({ data: { is_temporary: false, is_client: true }, error: null, - }) as any + }) ); // biome-ignore lint/suspicious/noExplicitAny: Test-only context injection (c as any).set("user", { id: "client-user" } as any); @@ -381,7 +379,7 @@ describe("Middleware Tests", () => { createProfilesSupabaseMock({ data: { is_temporary: true }, error: null, - }) as any + }) ); // biome-ignore lint/suspicious/noExplicitAny: Test-only context injection (c as any).set("user", { id: "temp-user" } as any); @@ -409,7 +407,7 @@ describe("Middleware Tests", () => { "supabase", createBillingStateSupabaseMock({ ownerPlan: "none", - }) as any + }) ); // biome-ignore lint/suspicious/noExplicitAny: Test-only context injection (c as any).set("user", { id: "owner-user" } as any); @@ -435,7 +433,7 @@ describe("Middleware Tests", () => { "supabase", createBillingStateSupabaseMock({ ownerPlan: "solo", - }) as any + }) ); // biome-ignore lint/suspicious/noExplicitAny: Test-only context injection (c as any).set("user", { id: "owner-user" } as any); diff --git a/apps/api/src/__tests__/routes/adminActions.test.ts b/apps/api/src/__tests__/routes/adminActions.test.ts index f16423f..65a13de 100644 --- a/apps/api/src/__tests__/routes/adminActions.test.ts +++ b/apps/api/src/__tests__/routes/adminActions.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from "vitest"; -import { createSignedAdminToken } from "../helpers/adminTokenTestUtils.js"; import { createConfig } from "../../config.js"; import { MiddlewareManager } from "../../middlewares/middleware.js"; import { getMainRouter } from "../../routers/index.js"; +import { createSignedAdminToken } from "../helpers/adminTokenTestUtils.js"; const ADMIN_TOKEN_SIGNING_SECRET = "admin-test-secret"; const ADMIN_TOKEN_AUDIENCE = "xtablo-admin"; diff --git a/apps/api/src/__tests__/routes/adminAuth.test.ts b/apps/api/src/__tests__/routes/adminAuth.test.ts index 0ff3585..18dd43a 100644 --- a/apps/api/src/__tests__/routes/adminAuth.test.ts +++ b/apps/api/src/__tests__/routes/adminAuth.test.ts @@ -1,8 +1,8 @@ -import { createSignedAdminToken } from "../helpers/adminTokenTestUtils.js"; import { describe, expect, it } from "vitest"; import { createConfig } from "../../config.js"; import { MiddlewareManager } from "../../middlewares/middleware.js"; import { getMainRouter } from "../../routers/index.js"; +import { createSignedAdminToken } from "../helpers/adminTokenTestUtils.js"; const ADMIN_TOKEN_SIGNING_SECRET = "admin-test-secret"; const ADMIN_TOKEN_AUDIENCE = "xtablo-admin"; diff --git a/apps/api/src/__tests__/routes/adminDatasets.test.ts b/apps/api/src/__tests__/routes/adminDatasets.test.ts index b233560..59c8b6d 100644 --- a/apps/api/src/__tests__/routes/adminDatasets.test.ts +++ b/apps/api/src/__tests__/routes/adminDatasets.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from "vitest"; -import { createSignedAdminToken } from "../helpers/adminTokenTestUtils.js"; import { createConfig } from "../../config.js"; import { MiddlewareManager } from "../../middlewares/middleware.js"; import { getMainRouter } from "../../routers/index.js"; +import { createSignedAdminToken } from "../helpers/adminTokenTestUtils.js"; const ADMIN_TOKEN_SIGNING_SECRET = "admin-test-secret"; const ADMIN_TOKEN_AUDIENCE = "xtablo-admin"; diff --git a/apps/api/src/__tests__/routes/adminTableEdits.test.ts b/apps/api/src/__tests__/routes/adminTableEdits.test.ts index 58d6110..f997acf 100644 --- a/apps/api/src/__tests__/routes/adminTableEdits.test.ts +++ b/apps/api/src/__tests__/routes/adminTableEdits.test.ts @@ -1,10 +1,10 @@ import { createClient } from "@supabase/supabase-js"; import { describe, expect, it } from "vitest"; -import { createSignedAdminToken } from "../helpers/adminTokenTestUtils.js"; -import { getTestData } from "../helpers/dbSetup.js"; import { createConfig } from "../../config.js"; import { MiddlewareManager } from "../../middlewares/middleware.js"; import { getMainRouter } from "../../routers/index.js"; +import { createSignedAdminToken } from "../helpers/adminTokenTestUtils.js"; +import { getTestData } from "../helpers/dbSetup.js"; const ADMIN_TOKEN_SIGNING_SECRET = "admin-test-secret"; const ADMIN_TOKEN_AUDIENCE = "xtablo-admin"; @@ -50,7 +50,7 @@ describe("Admin Table Edit Router", () => { }), }); - const auditClient = createClient(config.SUPABASE_URL, config.SUPABASE_SERVICE_ROLE_KEY, { + const auditClient = createClient(config.SUPABASE_URL, config.SUPABASE_SERVICE_ROLE_KEY, { auth: { autoRefreshToken: false, persistSession: false }, }); diff --git a/apps/api/src/__tests__/routes/adminTables.test.ts b/apps/api/src/__tests__/routes/adminTables.test.ts index 443d1db..6e591a7 100644 --- a/apps/api/src/__tests__/routes/adminTables.test.ts +++ b/apps/api/src/__tests__/routes/adminTables.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from "vitest"; -import { createSignedAdminToken } from "../helpers/adminTokenTestUtils.js"; import { createConfig } from "../../config.js"; import { MiddlewareManager } from "../../middlewares/middleware.js"; import { getMainRouter } from "../../routers/index.js"; +import { createSignedAdminToken } from "../helpers/adminTokenTestUtils.js"; const ADMIN_TOKEN_SIGNING_SECRET = "admin-test-secret"; const ADMIN_TOKEN_AUDIENCE = "xtablo-admin"; diff --git a/apps/api/src/__tests__/routes/tablo.test.ts b/apps/api/src/__tests__/routes/tablo.test.ts index b445c90..073d754 100644 --- a/apps/api/src/__tests__/routes/tablo.test.ts +++ b/apps/api/src/__tests__/routes/tablo.test.ts @@ -1,5 +1,5 @@ -import { createClient } from "@supabase/supabase-js"; import { randomUUID } from "node:crypto"; +import { createClient } from "@supabase/supabase-js"; import { testClient } from "hono/testing"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { createConfig } from "../../config.js"; diff --git a/apps/api/src/helpers/adminAudit.ts b/apps/api/src/helpers/adminAudit.ts index 3abf933..2489688 100644 --- a/apps/api/src/helpers/adminAudit.ts +++ b/apps/api/src/helpers/adminAudit.ts @@ -23,18 +23,16 @@ export async function recordAdminAuditLog({ targetId, targetType, }: AdminAuditArgs) { - const { error } = await (supabase as SupabaseClient) - .from("admin_audit_log") - .insert({ - action, - after, - before, - operator_email: operatorEmail, - operator_id: operatorId, - role, - target_id: targetId, - target_type: targetType, - }); + const { error } = await supabase.from("admin_audit_log").insert({ + action, + after, + before, + operator_email: operatorEmail, + operator_id: operatorId, + role, + target_id: targetId, + target_type: targetType, + }); if (error) { throw new Error(`Failed to write admin audit log: ${error.message}`); diff --git a/apps/api/src/helpers/orgIcons.test.ts b/apps/api/src/helpers/orgIcons.test.ts index 6493d46..ef943dd 100644 --- a/apps/api/src/helpers/orgIcons.test.ts +++ b/apps/api/src/helpers/orgIcons.test.ts @@ -1,5 +1,5 @@ -import { describe, it, expect, vi, beforeEach } from "vitest"; -import { resizeOrgIcon, buildOrgIconKey, ICON_SIZES, ORG_ICONS_BUCKET } from "./orgIcons.js"; +import { describe, expect, it } from "vitest"; +import { buildOrgIconKey, ICON_SIZES, resizeOrgIcon } from "./orgIcons.js"; describe("buildOrgIconKey", () => { it("builds the correct R2 key for a given org and size", () => { @@ -32,7 +32,12 @@ describe("resizeOrgIcon", () => { it("returns buffers for all required sizes from a valid PNG input", async () => { const sharp = (await import("sharp")).default; const input = await sharp({ - create: { width: 512, height: 512, channels: 4, background: { r: 255, g: 0, b: 0, alpha: 1 } }, + create: { + width: 512, + height: 512, + channels: 4, + background: { r: 255, g: 0, b: 0, alpha: 1 }, + }, }) .png() .toBuffer(); @@ -49,7 +54,12 @@ describe("resizeOrgIcon", () => { it("rejects images smaller than 512x512", async () => { const sharp = (await import("sharp")).default; const tooSmall = await sharp({ - create: { width: 256, height: 256, channels: 4, background: { r: 0, g: 0, b: 255, alpha: 1 } }, + create: { + width: 256, + height: 256, + channels: 4, + background: { r: 0, g: 0, b: 255, alpha: 1 }, + }, }) .png() .toBuffer(); diff --git a/apps/api/src/routers/adminActions.ts b/apps/api/src/routers/adminActions.ts index 0aea6fe..3431786 100644 --- a/apps/api/src/routers/adminActions.ts +++ b/apps/api/src/routers/adminActions.ts @@ -1,10 +1,7 @@ -import { Hono } from "hono"; import type { AdminActionRunResponse } from "@xtablo/shared-types"; +import { Hono } from "hono"; import { recordAdminAuditLog } from "../helpers/adminAudit.js"; -import { - getAdminActionDefinition, - listAdminActions, -} from "../helpers/adminRegistry.js"; +import { getAdminActionDefinition, listAdminActions } from "../helpers/adminRegistry.js"; import type { BaseEnv } from "../types/app.types.js"; type ActionInput = { @@ -66,9 +63,7 @@ export const getAdminActionsRouter = () => { } const changes = - actionId === "grant_tablo_admin" - ? { is_active: true, is_admin: true } - : { is_active: false }; + actionId === "grant_tablo_admin" ? { is_active: true, is_admin: true } : { is_active: false }; const { data: after, error: updateError } = await supabase .from("tablo_access") diff --git a/apps/api/src/routers/adminDatasets.ts b/apps/api/src/routers/adminDatasets.ts index 7b8206a..3c6444d 100644 --- a/apps/api/src/routers/adminDatasets.ts +++ b/apps/api/src/routers/adminDatasets.ts @@ -1,9 +1,6 @@ -import { Hono } from "hono"; import type { AdminDatasetResult } from "@xtablo/shared-types"; -import { - getAdminDatasetDefinition, - listAdminDatasets, -} from "../helpers/adminRegistry.js"; +import { Hono } from "hono"; +import { getAdminDatasetDefinition, listAdminDatasets } from "../helpers/adminRegistry.js"; import type { BaseEnv } from "../types/app.types.js"; function bucketByDay(values: Array) { @@ -95,7 +92,10 @@ async function getDatasetPoints( chartType: "donut", dimensionLabel: "Plan", metricLabel: "Users", - points: bucketByValue((data ?? []).map((row) => row.plan), "No Plan"), + points: bucketByValue( + (data ?? []).map((row) => row.plan), + "No Plan" + ), }; } case "tablo_access_mix": { diff --git a/apps/api/src/routers/adminOverview.ts b/apps/api/src/routers/adminOverview.ts index fc5b3f1..22671d7 100644 --- a/apps/api/src/routers/adminOverview.ts +++ b/apps/api/src/routers/adminOverview.ts @@ -1,5 +1,5 @@ -import { Hono } from "hono"; import type { AdminOverviewResponse } from "@xtablo/shared-types"; +import { Hono } from "hono"; import type { BaseEnv } from "../types/app.types.js"; function startOfRecentWindow(days: number) { @@ -46,10 +46,7 @@ export const getAdminOverviewRouter = () => { .gte("created_at", sevenDaysAgo) ), countRows( - supabase - .from("tablos") - .select("*", { count: "exact", head: true }) - .is("deleted_at", null) + supabase.from("tablos").select("*", { count: "exact", head: true }).is("deleted_at", null) ), countRows( supabase diff --git a/apps/api/src/routers/index.ts b/apps/api/src/routers/index.ts index 93ccd34..c372bcf 100644 --- a/apps/api/src/routers/index.ts +++ b/apps/api/src/routers/index.ts @@ -1,8 +1,8 @@ import { Hono } from "hono"; import type { AppConfig } from "../config.js"; import { MiddlewareManager } from "../middlewares/middleware.js"; -import { getAdminRouter } from "./admin.js"; import type { BaseEnv } from "../types/app.types.js"; +import { getAdminRouter } from "./admin.js"; import { getAuthenticatedRouter } from "./authRouter.js"; import { getMaybeAuthenticatedRouter } from "./maybeAuthRouter.js"; import { getPublicRouter } from "./public.js"; diff --git a/apps/api/src/routers/tablo.ts b/apps/api/src/routers/tablo.ts index 5ce02b7..769524c 100644 --- a/apps/api/src/routers/tablo.ts +++ b/apps/api/src/routers/tablo.ts @@ -28,44 +28,44 @@ const createTablo = (middlewareManager: ReturnType; + const tabloData = insertedTablo as Tables<"tablos">; - if (typedPayload.events) { - const eventsToInsert = typedPayload.events.map((event) => ({ - ...event, - tablo_id: tabloData.id, - created_by: user.id, - })); + if (typedPayload.events) { + const eventsToInsert = typedPayload.events.map((event) => ({ + ...event, + tablo_id: tabloData.id, + created_by: user.id, + })); - await supabase.from("events").insert(eventsToInsert); - } + await supabase.from("events").insert(eventsToInsert); + } return c.json({ message: "Tablo created successfully", tablo: tabloData }); } ); @@ -90,12 +90,7 @@ const updateTablo = (middlewareManager: ReturnType { const postTabloFile = (middlewareManager: ReturnType) => factory.createHandlers(checkTabloMember, async (c) => { - const tabloId = c.req.param("tabloId"); - const user = c.get("user"); - // Get the file path - supports both wildcard (*) and named parameter (:fileName) - const filePath = c.req.param("path") || c.req.param("fileName"); + const tabloId = c.req.param("tabloId"); + const user = c.get("user"); + // Get the file path - supports both wildcard (*) and named parameter (:fileName) + const filePath = c.req.param("path") || c.req.param("fileName"); - if (!filePath) { - return c.json({ error: "File path is required" }, 400); - } - - const s3_client = c.get("s3_client"); - - try { - const body = await c.req.json(); - const { content, contentType = "text/plain" } = body; - - if (!content) { - return c.json({ error: "Content is required" }, 400); + if (!filePath) { + return c.json({ error: "File path is required" }, 400); } - await s3_client.send( - new PutObjectCommand({ - Bucket: "tablo-data", - Key: `${tabloId}/${filePath}`, - Body: content, - ContentType: contentType, - Metadata: { - "uploaded-by": user.id, - }, - }) - ); - fileNamesCache.delete(tabloId); + const s3_client = c.get("s3_client"); - return c.json({ - message: "File uploaded successfully", - fileName: filePath, - tabloId, - }); - } catch (error) { - console.error("Error uploading file:", error); - return c.json({ error: "Failed to upload file" }, 500); - } + try { + const body = await c.req.json(); + const { content, contentType = "text/plain" } = body; + + if (!content) { + return c.json({ error: "Content is required" }, 400); + } + + await s3_client.send( + new PutObjectCommand({ + Bucket: "tablo-data", + Key: `${tabloId}/${filePath}`, + Body: content, + ContentType: contentType, + Metadata: { + "uploaded-by": user.id, + }, + }) + ); + fileNamesCache.delete(tabloId); + + return c.json({ + message: "File uploaded successfully", + fileName: filePath, + tabloId, + }); + } catch (error) { + console.error("Error uploading file:", error); + return c.json({ error: "Failed to upload file" }, 500); + } }); const deleteTabloFile = (middlewareManager: ReturnType) => @@ -336,10 +336,7 @@ const getTabloFolders = factory.createHandlers(checkTabloMember, async (c) => { // POST /tablo-data/:tabloId/folders - Create a new folder (admin only) const createTabloFolder = (middlewareManager: ReturnType) => - factory.createHandlers( - middlewareManager.regularUserCheck, - checkTabloAdmin, - async (c) => { + factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { const tabloId = c.req.param("tabloId"); const s3_client = c.get("s3_client"); const user = c.get("user"); @@ -380,15 +377,11 @@ const createTabloFolder = (middlewareManager: ReturnType) => - factory.createHandlers( - middlewareManager.regularUserCheck, - checkTabloAdmin, - async (c) => { + factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { const tabloId = c.req.param("tabloId"); const folderId = c.req.param("folderId"); const s3_client = c.get("s3_client"); @@ -433,15 +426,11 @@ const updateTabloFolder = (middlewareManager: ReturnType) => - factory.createHandlers( - middlewareManager.regularUserCheck, - checkTabloAdmin, - async (c) => { + factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { const tabloId = c.req.param("tabloId"); const folderId = c.req.param("folderId"); const s3_client = c.get("s3_client"); @@ -469,8 +458,7 @@ const deleteTabloFolder = (middlewareManager: ReturnType { if (removeAccessError) { return c.json({ error: "Failed to revoke member tablo permissions" }, 500); } - } const { error: inviteCleanupError } = await supabase diff --git a/apps/api/src/types/app.types.ts b/apps/api/src/types/app.types.ts index df9b18a..5c1f28e 100644 --- a/apps/api/src/types/app.types.ts +++ b/apps/api/src/types/app.types.ts @@ -1,10 +1,10 @@ import type { S3Client } from "@aws-sdk/client-s3"; -import type { AdminSessionClaims } from "../helpers/adminTokens.js"; import type { StripeSync } from "@supabase/stripe-sync-engine"; import type { SupabaseClient, User } from "@supabase/supabase-js"; import type { Hono } from "hono"; import type { Transporter } from "nodemailer"; import type Stripe from "stripe"; +import type { AdminSessionClaims } from "../helpers/adminTokens.js"; /** * Base environment variables available across all routes diff --git a/apps/clients/index.html b/apps/clients/index.html index 9fb3e81..e0bb97a 100644 --- a/apps/clients/index.html +++ b/apps/clients/index.html @@ -3,7 +3,7 @@ - Xtablo — Client Portal + XTablo -- Portail Clients
diff --git a/apps/clients/src/pages/AuthCallback.tsx b/apps/clients/src/pages/AuthCallback.tsx index b34427b..ff3f50e 100644 --- a/apps/clients/src/pages/AuthCallback.tsx +++ b/apps/clients/src/pages/AuthCallback.tsx @@ -29,7 +29,9 @@ export function AuthCallback() { .then(async (res) => { if (!res.ok) { const body = await res.json().catch(() => ({})); - throw new Error((body as { message?: string }).message ?? "Erreur lors de l'acceptation de l'invitation"); + throw new Error( + (body as { message?: string }).message ?? "Erreur lors de l'acceptation de l'invitation" + ); } return res.json() as Promise<{ tabloId: string }>; }) diff --git a/apps/clients/src/pages/ClientTabloListPage.tsx b/apps/clients/src/pages/ClientTabloListPage.tsx index e3ce7c6..bbfff3d 100644 --- a/apps/clients/src/pages/ClientTabloListPage.tsx +++ b/apps/clients/src/pages/ClientTabloListPage.tsx @@ -1,6 +1,6 @@ import { useQuery } from "@tanstack/react-query"; import type { UserTablo } from "@xtablo/shared-types"; -import { Navigate, Link } from "react-router-dom"; +import { Link, Navigate } from "react-router-dom"; import { supabase } from "../lib/supabase"; function useClientTablosList() { @@ -51,9 +51,7 @@ export function ClientTabloListPage() { to={`/tablo/${tablo.id}`} className="block p-5 rounded-lg border border-border bg-card hover:bg-muted/50 transition-colors space-y-2" > - {tablo.color && ( -
- )} + {tablo.color &&
}

{tablo.name}

))} diff --git a/apps/clients/src/pages/ClientTabloPage.tsx b/apps/clients/src/pages/ClientTabloPage.tsx index 3da9be0..7693243 100644 --- a/apps/clients/src/pages/ClientTabloPage.tsx +++ b/apps/clients/src/pages/ClientTabloPage.tsx @@ -2,9 +2,6 @@ import { useQuery } from "@tanstack/react-query"; import { buildApi } from "@xtablo/shared"; import { useSession } from "@xtablo/shared/contexts/SessionContext"; import type { Etape, KanbanTask, TabloFolder, UserTablo } from "@xtablo/shared-types"; -import { CalendarIcon, FolderIcon, KanbanIcon, ListChecksIcon, MapIcon, MessageCircleIcon } from "lucide-react"; -import { useState } from "react"; -import { useParams } from "react-router-dom"; import { EtapesSection, RoadmapSection, @@ -13,6 +10,16 @@ import { TabloFilesSection, TabloTasksSection, } from "@xtablo/tablo-views"; +import { + CalendarIcon, + FolderIcon, + KanbanIcon, + ListChecksIcon, + MapIcon, + MessageCircleIcon, +} from "lucide-react"; +import { useState } from "react"; +import { useParams } from "react-router-dom"; import { supabase } from "../lib/supabase"; const API_URL = import.meta.env.VITE_API_URL as string; @@ -130,7 +137,9 @@ function useClientTabloFolders(tabloId: string, accessToken: string | undefined) return useQuery({ queryKey: ["client-tablo-folders", tabloId], queryFn: async () => { - const { data } = await api.get<{ folders: TabloFolder[] }>(`/api/v1/tablo-folders/${tabloId}`); + const { data } = await api.get<{ folders: TabloFolder[] }>( + `/api/v1/tablo-folders/${tabloId}` + ); return data.folders ?? []; }, enabled: !!tabloId && !!accessToken, @@ -164,10 +173,22 @@ export function ClientTabloPage() { const { data: tablo, isLoading: tabloLoading } = useClientTablo(tabloId ?? ""); const { data: tasks = [] } = useClientTabloTasks(tabloId ?? ""); const { data: etapes = [] } = useClientTabloEtapes(tabloId ?? ""); - const { data: events, isLoading: eventsLoading, error: eventsError } = useClientTabloEvents(tabloId ?? ""); + const { + data: events, + isLoading: eventsLoading, + error: eventsError, + } = useClientTabloEvents(tabloId ?? ""); const { data: members = [] } = useClientTabloMembers(tabloId ?? "", accessToken); - const { data: filesData, isLoading: filesLoading, error: filesError } = useClientTabloFiles(tabloId ?? "", accessToken); - const { data: folders = [], isLoading: foldersLoading, error: foldersError } = useClientTabloFolders(tabloId ?? "", accessToken); + const { + data: filesData, + isLoading: filesLoading, + error: filesError, + } = useClientTabloFiles(tabloId ?? "", accessToken); + const { + data: folders = [], + isLoading: foldersLoading, + error: foldersError, + } = useClientTabloFolders(tabloId ?? "", accessToken); const fileNames = (filesData?.fileNames ?? []).filter((f) => !f.startsWith(".")); @@ -298,11 +319,7 @@ export function ClientTabloPage() { )} {activeTab === "roadmap" && ( - {}} - onTaskStatusChange={() => {}} - /> + {}} onTaskStatusChange={() => {}} /> )}
diff --git a/apps/clients/tsconfig.tsbuildinfo b/apps/clients/tsconfig.tsbuildinfo new file mode 100644 index 0000000..a7db947 --- /dev/null +++ b/apps/clients/tsconfig.tsbuildinfo @@ -0,0 +1 @@ +{"root":["./src/app.tsx","./src/i18n.ts","./src/main.tsx","./src/routes.tsx","./src/components/clientlayout.tsx","./src/lib/supabase.ts","./src/pages/authcallback.tsx","./src/pages/clienttablolistpage.tsx","./src/pages/clienttablopage.tsx"],"version":"5.9.3"} \ No newline at end of file diff --git a/apps/clients/vite.config.ts b/apps/clients/vite.config.ts index dfed7ff..8660ed9 100644 --- a/apps/clients/vite.config.ts +++ b/apps/clients/vite.config.ts @@ -5,7 +5,11 @@ import { defineConfig, type PluginOption } from "vite"; import tsconfigPaths from "vite-tsconfig-paths"; export default defineConfig(({ mode }) => { - const plugins: PluginOption[] = [react(), tailwindcss(), tsconfigPaths({ ignoreConfigErrors: true })]; + const plugins: PluginOption[] = [ + react(), + tailwindcss(), + tsconfigPaths({ ignoreConfigErrors: true }), + ]; if (mode !== "test" && process.env.VITEST !== "true") { plugins.push(cloudflare({ inspectorPort: 9232 })); diff --git a/apps/clients/worker-configuration.d.ts b/apps/clients/worker-configuration.d.ts new file mode 100644 index 0000000..8d33658 --- /dev/null +++ b/apps/clients/worker-configuration.d.ts @@ -0,0 +1,8376 @@ +/* eslint-disable */ +// Generated by Wrangler by running `wrangler types` (hash: cde5d6bbbb8f5d59a6f6313ce6d7b38b) +// Runtime types generated with workerd@1.20251011.0 2025-07-09 +declare namespace Cloudflare { + interface GlobalProps { + mainModule: typeof import("./worker/index"); + } + interface Env { + } +} +interface Env extends Cloudflare.Env {} + +// Begin runtime types +/*! ***************************************************************************** +Copyright (c) Cloudflare. All rights reserved. +Copyright (c) Microsoft Corporation. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* eslint-disable */ +// noinspection JSUnusedGlobalSymbols +declare var onmessage: never; +/** + * An abnormal event (called an exception) which occurs as a result of calling a method or accessing a property of a web API. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException) + */ +declare class DOMException extends Error { + constructor(message?: string, name?: string); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + static readonly INDEX_SIZE_ERR: number; + static readonly DOMSTRING_SIZE_ERR: number; + static readonly HIERARCHY_REQUEST_ERR: number; + static readonly WRONG_DOCUMENT_ERR: number; + static readonly INVALID_CHARACTER_ERR: number; + static readonly NO_DATA_ALLOWED_ERR: number; + static readonly NO_MODIFICATION_ALLOWED_ERR: number; + static readonly NOT_FOUND_ERR: number; + static readonly NOT_SUPPORTED_ERR: number; + static readonly INUSE_ATTRIBUTE_ERR: number; + static readonly INVALID_STATE_ERR: number; + static readonly SYNTAX_ERR: number; + static readonly INVALID_MODIFICATION_ERR: number; + static readonly NAMESPACE_ERR: number; + static readonly INVALID_ACCESS_ERR: number; + static readonly VALIDATION_ERR: number; + static readonly TYPE_MISMATCH_ERR: number; + static readonly SECURITY_ERR: number; + static readonly NETWORK_ERR: number; + static readonly ABORT_ERR: number; + static readonly URL_MISMATCH_ERR: number; + static readonly QUOTA_EXCEEDED_ERR: number; + static readonly TIMEOUT_ERR: number; + static readonly INVALID_NODE_TYPE_ERR: number; + static readonly DATA_CLONE_ERR: number; + get stack(): any; + set stack(value: any); +} +type WorkerGlobalScopeEventMap = { + fetch: FetchEvent; + scheduled: ScheduledEvent; + queue: QueueEvent; + unhandledrejection: PromiseRejectionEvent; + rejectionhandled: PromiseRejectionEvent; +}; +declare abstract class WorkerGlobalScope extends EventTarget { + EventTarget: typeof EventTarget; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) */ +interface Console { + "assert"(condition?: boolean, ...data: any[]): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) */ + clear(): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ + count(label?: string): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ + countReset(label?: string): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ + debug(...data: any[]): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) */ + dir(item?: any, options?: any): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) */ + dirxml(...data: any[]): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) */ + error(...data: any[]): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ + group(...data: any[]): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ + groupCollapsed(...data: any[]): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ + groupEnd(): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ + info(...data: any[]): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) */ + log(...data: any[]): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) */ + table(tabularData?: any, properties?: string[]): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ + time(label?: string): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ + timeEnd(label?: string): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ + timeLog(label?: string, ...data: any[]): void; + timeStamp(label?: string): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ + trace(...data: any[]): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) */ + warn(...data: any[]): void; +} +declare const console: Console; +type BufferSource = ArrayBufferView | ArrayBuffer; +type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array; +declare namespace WebAssembly { + class CompileError extends Error { + constructor(message?: string); + } + class RuntimeError extends Error { + constructor(message?: string); + } + type ValueType = "anyfunc" | "externref" | "f32" | "f64" | "i32" | "i64" | "v128"; + interface GlobalDescriptor { + value: ValueType; + mutable?: boolean; + } + class Global { + constructor(descriptor: GlobalDescriptor, value?: any); + value: any; + valueOf(): any; + } + type ImportValue = ExportValue | number; + type ModuleImports = Record; + type Imports = Record; + type ExportValue = Function | Global | Memory | Table; + type Exports = Record; + class Instance { + constructor(module: Module, imports?: Imports); + readonly exports: Exports; + } + interface MemoryDescriptor { + initial: number; + maximum?: number; + shared?: boolean; + } + class Memory { + constructor(descriptor: MemoryDescriptor); + readonly buffer: ArrayBuffer; + grow(delta: number): number; + } + type ImportExportKind = "function" | "global" | "memory" | "table"; + interface ModuleExportDescriptor { + kind: ImportExportKind; + name: string; + } + interface ModuleImportDescriptor { + kind: ImportExportKind; + module: string; + name: string; + } + abstract class Module { + static customSections(module: Module, sectionName: string): ArrayBuffer[]; + static exports(module: Module): ModuleExportDescriptor[]; + static imports(module: Module): ModuleImportDescriptor[]; + } + type TableKind = "anyfunc" | "externref"; + interface TableDescriptor { + element: TableKind; + initial: number; + maximum?: number; + } + class Table { + constructor(descriptor: TableDescriptor, value?: any); + readonly length: number; + get(index: number): any; + grow(delta: number, value?: any): number; + set(index: number, value?: any): void; + } + function instantiate(module: Module, imports?: Imports): Promise; + function validate(bytes: BufferSource): boolean; +} +/** + * This ServiceWorker API interface represents the global execution context of a service worker. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) + */ +interface ServiceWorkerGlobalScope extends WorkerGlobalScope { + DOMException: typeof DOMException; + WorkerGlobalScope: typeof WorkerGlobalScope; + btoa(data: string): string; + atob(data: string): string; + setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; + setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; + clearTimeout(timeoutId: number | null): void; + setInterval(callback: (...args: any[]) => void, msDelay?: number): number; + setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; + clearInterval(timeoutId: number | null): void; + queueMicrotask(task: Function): void; + structuredClone(value: T, options?: StructuredSerializeOptions): T; + reportError(error: any): void; + fetch(input: RequestInfo | URL, init?: RequestInit): Promise; + self: ServiceWorkerGlobalScope; + crypto: Crypto; + caches: CacheStorage; + scheduler: Scheduler; + performance: Performance; + Cloudflare: Cloudflare; + readonly origin: string; + Event: typeof Event; + ExtendableEvent: typeof ExtendableEvent; + CustomEvent: typeof CustomEvent; + PromiseRejectionEvent: typeof PromiseRejectionEvent; + FetchEvent: typeof FetchEvent; + TailEvent: typeof TailEvent; + TraceEvent: typeof TailEvent; + ScheduledEvent: typeof ScheduledEvent; + MessageEvent: typeof MessageEvent; + CloseEvent: typeof CloseEvent; + ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; + ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; + ReadableStream: typeof ReadableStream; + WritableStream: typeof WritableStream; + WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; + TransformStream: typeof TransformStream; + ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; + CountQueuingStrategy: typeof CountQueuingStrategy; + ErrorEvent: typeof ErrorEvent; + EventSource: typeof EventSource; + ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; + ReadableStreamDefaultController: typeof ReadableStreamDefaultController; + ReadableByteStreamController: typeof ReadableByteStreamController; + WritableStreamDefaultController: typeof WritableStreamDefaultController; + TransformStreamDefaultController: typeof TransformStreamDefaultController; + CompressionStream: typeof CompressionStream; + DecompressionStream: typeof DecompressionStream; + TextEncoderStream: typeof TextEncoderStream; + TextDecoderStream: typeof TextDecoderStream; + Headers: typeof Headers; + Body: typeof Body; + Request: typeof Request; + Response: typeof Response; + WebSocket: typeof WebSocket; + WebSocketPair: typeof WebSocketPair; + WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; + AbortController: typeof AbortController; + AbortSignal: typeof AbortSignal; + TextDecoder: typeof TextDecoder; + TextEncoder: typeof TextEncoder; + navigator: Navigator; + Navigator: typeof Navigator; + URL: typeof URL; + URLSearchParams: typeof URLSearchParams; + URLPattern: typeof URLPattern; + Blob: typeof Blob; + File: typeof File; + FormData: typeof FormData; + Crypto: typeof Crypto; + SubtleCrypto: typeof SubtleCrypto; + CryptoKey: typeof CryptoKey; + CacheStorage: typeof CacheStorage; + Cache: typeof Cache; + FixedLengthStream: typeof FixedLengthStream; + IdentityTransformStream: typeof IdentityTransformStream; + HTMLRewriter: typeof HTMLRewriter; +} +declare function addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; +declare function removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean): void; +/** + * Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ +declare function dispatchEvent(event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap]): boolean; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/btoa) */ +declare function btoa(data: string): string; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/atob) */ +declare function atob(data: string): string; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ +declare function setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ +declare function setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearTimeout) */ +declare function clearTimeout(timeoutId: number | null): void; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ +declare function setInterval(callback: (...args: any[]) => void, msDelay?: number): number; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ +declare function setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearInterval) */ +declare function clearInterval(timeoutId: number | null): void; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/queueMicrotask) */ +declare function queueMicrotask(task: Function): void; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */ +declare function structuredClone(value: T, options?: StructuredSerializeOptions): T; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/reportError) */ +declare function reportError(error: any): void; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */ +declare function fetch(input: RequestInfo | URL, init?: RequestInit): Promise; +declare const self: ServiceWorkerGlobalScope; +/** +* The Web Crypto API provides a set of low-level functions for common cryptographic tasks. +* The Workers runtime implements the full surface of this API, but with some differences in +* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) +* compared to those implemented in most browsers. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) +*/ +declare const crypto: Crypto; +/** +* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) +*/ +declare const caches: CacheStorage; +declare const scheduler: Scheduler; +/** +* The Workers runtime supports a subset of the Performance API, used to measure timing and performance, +* as well as timing of subrequests and other operations. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) +*/ +declare const performance: Performance; +declare const Cloudflare: Cloudflare; +declare const origin: string; +declare const navigator: Navigator; +interface TestController { +} +interface ExecutionContext { + waitUntil(promise: Promise): void; + passThroughOnException(): void; + readonly props: Props; +} +type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | Promise; +type ExportedHandlerTailHandler = (events: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTraceHandler = (traces: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTailStreamHandler = (event: TailStream.TailEvent, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise; +type ExportedHandlerScheduledHandler = (controller: ScheduledController, env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerQueueHandler = (batch: MessageBatch, env: Env, ctx: ExecutionContext) => void | Promise; +type ExportedHandlerTestHandler = (controller: TestController, env: Env, ctx: ExecutionContext) => void | Promise; +interface ExportedHandler { + fetch?: ExportedHandlerFetchHandler; + tail?: ExportedHandlerTailHandler; + trace?: ExportedHandlerTraceHandler; + tailStream?: ExportedHandlerTailStreamHandler; + scheduled?: ExportedHandlerScheduledHandler; + test?: ExportedHandlerTestHandler; + email?: EmailExportedHandler; + queue?: ExportedHandlerQueueHandler; +} +interface StructuredSerializeOptions { + transfer?: any[]; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent) */ +declare abstract class PromiseRejectionEvent extends Event { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) */ + readonly promise: Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) */ + readonly reason: any; +} +declare abstract class Navigator { + sendBeacon(url: string, body?: (ReadableStream | string | (ArrayBuffer | ArrayBufferView) | Blob | FormData | URLSearchParams | URLSearchParams)): boolean; + readonly userAgent: string; + readonly hardwareConcurrency: number; + readonly language: string; + readonly languages: string[]; +} +interface AlarmInvocationInfo { + readonly isRetry: boolean; + readonly retryCount: number; +} +interface Cloudflare { + readonly compatibilityFlags: Record; +} +interface DurableObject { + fetch(request: Request): Response | Promise; + alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; + webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; + webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; +} +type DurableObjectStub = Fetcher & { + readonly id: DurableObjectId; + readonly name?: string; +}; +interface DurableObjectId { + toString(): string; + equals(other: DurableObjectId): boolean; + readonly name?: string; +} +declare abstract class DurableObjectNamespace { + newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId; + idFromName(name: string): DurableObjectId; + idFromString(id: string): DurableObjectId; + get(id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; + getByName(name: string, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; + jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; +} +type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high"; +interface DurableObjectNamespaceNewUniqueIdOptions { + jurisdiction?: DurableObjectJurisdiction; +} +type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "oc" | "afr" | "me"; +interface DurableObjectNamespaceGetDurableObjectOptions { + locationHint?: DurableObjectLocationHint; +} +interface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> { +} +interface DurableObjectState { + waitUntil(promise: Promise): void; + readonly props: Props; + readonly id: DurableObjectId; + readonly storage: DurableObjectStorage; + container?: Container; + blockConcurrencyWhile(callback: () => Promise): Promise; + acceptWebSocket(ws: WebSocket, tags?: string[]): void; + getWebSockets(tag?: string): WebSocket[]; + setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; + getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; + getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; + setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; + getHibernatableWebSocketEventTimeout(): number | null; + getTags(ws: WebSocket): string[]; + abort(reason?: string): void; +} +interface DurableObjectTransaction { + get(key: string, options?: DurableObjectGetOptions): Promise; + get(keys: string[], options?: DurableObjectGetOptions): Promise>; + list(options?: DurableObjectListOptions): Promise>; + put(key: string, value: T, options?: DurableObjectPutOptions): Promise; + put(entries: Record, options?: DurableObjectPutOptions): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + rollback(): void; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; +} +interface DurableObjectStorage { + get(key: string, options?: DurableObjectGetOptions): Promise; + get(keys: string[], options?: DurableObjectGetOptions): Promise>; + list(options?: DurableObjectListOptions): Promise>; + put(key: string, value: T, options?: DurableObjectPutOptions): Promise; + put(entries: Record, options?: DurableObjectPutOptions): Promise; + delete(key: string, options?: DurableObjectPutOptions): Promise; + delete(keys: string[], options?: DurableObjectPutOptions): Promise; + deleteAll(options?: DurableObjectPutOptions): Promise; + transaction(closure: (txn: DurableObjectTransaction) => Promise): Promise; + getAlarm(options?: DurableObjectGetAlarmOptions): Promise; + setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; + deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; + sync(): Promise; + sql: SqlStorage; + kv: SyncKvStorage; + transactionSync(closure: () => T): T; + getCurrentBookmark(): Promise; + getBookmarkForTime(timestamp: number | Date): Promise; + onNextSessionRestoreBookmark(bookmark: string): Promise; +} +interface DurableObjectListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; + allowConcurrency?: boolean; + noCache?: boolean; +} +interface DurableObjectGetOptions { + allowConcurrency?: boolean; + noCache?: boolean; +} +interface DurableObjectGetAlarmOptions { + allowConcurrency?: boolean; +} +interface DurableObjectPutOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; + noCache?: boolean; +} +interface DurableObjectSetAlarmOptions { + allowConcurrency?: boolean; + allowUnconfirmed?: boolean; +} +declare class WebSocketRequestResponsePair { + constructor(request: string, response: string); + get request(): string; + get response(): string; +} +interface AnalyticsEngineDataset { + writeDataPoint(event?: AnalyticsEngineDataPoint): void; +} +interface AnalyticsEngineDataPoint { + indexes?: ((ArrayBuffer | string) | null)[]; + doubles?: number[]; + blobs?: ((ArrayBuffer | string) | null)[]; +} +/** + * An event which takes place in the DOM. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event) + */ +declare class Event { + constructor(type: string, init?: EventInit); + /** + * Returns the type of event, e.g. "click", "hashchange", or "submit". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) + */ + get type(): string; + /** + * Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) + */ + get eventPhase(): number; + /** + * Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) + */ + get composed(): boolean; + /** + * Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) + */ + get bubbles(): boolean; + /** + * Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) + */ + get cancelable(): boolean; + /** + * Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) + */ + get defaultPrevented(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) + */ + get returnValue(): boolean; + /** + * Returns the object whose event listener's callback is currently being invoked. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) + */ + get currentTarget(): EventTarget | undefined; + /** + * Returns the object to which event is dispatched (its target). + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target) + */ + get target(): EventTarget | undefined; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) + */ + get srcElement(): EventTarget | undefined; + /** + * Returns the event's timestamp as the number of milliseconds measured relative to the time origin. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) + */ + get timeStamp(): number; + /** + * Returns true if event was dispatched by the user agent, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) + */ + get isTrusted(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + get cancelBubble(): boolean; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) + */ + set cancelBubble(value: boolean); + /** + * Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) + */ + stopImmediatePropagation(): void; + /** + * If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) + */ + preventDefault(): void; + /** + * When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) + */ + stopPropagation(): void; + /** + * Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) + */ + composedPath(): EventTarget[]; + static readonly NONE: number; + static readonly CAPTURING_PHASE: number; + static readonly AT_TARGET: number; + static readonly BUBBLING_PHASE: number; +} +interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} +type EventListener = (event: EventType) => void; +interface EventListenerObject { + handleEvent(event: EventType): void; +} +type EventListenerOrEventListenerObject = EventListener | EventListenerObject; +/** + * EventTarget is a DOM interface implemented by objects that can receive events and may have listeners for them. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget) + */ +declare class EventTarget = Record> { + constructor(); + /** + * Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched. + * + * The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture. + * + * When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET. + * + * When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners. + * + * When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed. + * + * If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted. + * + * The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) + */ + addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; + /** + * Removes the event listener in target's event listener list with the same type, callback, and options. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) + */ + removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean): void; + /** + * Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) + */ + dispatchEvent(event: EventMap[keyof EventMap]): boolean; +} +interface EventTargetEventListenerOptions { + capture?: boolean; +} +interface EventTargetAddEventListenerOptions { + capture?: boolean; + passive?: boolean; + once?: boolean; + signal?: AbortSignal; +} +interface EventTargetHandlerObject { + handleEvent: (event: Event) => any | undefined; +} +/** + * A controller object that allows you to abort one or more DOM requests as and when desired. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController) + */ +declare class AbortController { + constructor(); + /** + * Returns the AbortSignal object associated with this object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) + */ + get signal(): AbortSignal; + /** + * Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) + */ + abort(reason?: any): void; +} +/** + * A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal) + */ +declare abstract class AbortSignal extends EventTarget { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) */ + static abort(reason?: any): AbortSignal; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) */ + static timeout(delay: number): AbortSignal; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static) */ + static any(signals: AbortSignal[]): AbortSignal; + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) + */ + get aborted(): boolean; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) */ + get reason(): any; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + get onabort(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ + set onabort(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) */ + throwIfAborted(): void; +} +interface Scheduler { + wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; +} +interface SchedulerWaitOptions { + signal?: AbortSignal; +} +/** + * Extends the lifetime of the install and activate events dispatched on the global scope as part of the service worker lifecycle. This ensures that any functional events (like FetchEvent) are not dispatched until it upgrades database schemas and deletes the outdated cache entries. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent) + */ +declare abstract class ExtendableEvent extends Event { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) */ + waitUntil(promise: Promise): void; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent) */ +declare class CustomEvent extends Event { + constructor(type: string, init?: CustomEventCustomEventInit); + /** + * Returns any custom data event was created with. Typically used for synthetic events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) + */ + get detail(): T; +} +interface CustomEventCustomEventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; + detail?: any; +} +/** + * A file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob) + */ +declare class Blob { + constructor(type?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], options?: BlobOptions); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ + get size(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ + get type(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ + slice(start?: number, end?: number, type?: string): Blob; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) */ + arrayBuffer(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes) */ + bytes(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ + text(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) */ + stream(): ReadableStream; +} +interface BlobOptions { + type?: string; +} +/** + * Provides information about files and allows JavaScript in a web page to access their content. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File) + */ +declare class File extends Blob { + constructor(bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, name: string, options?: FileOptions); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ + get name(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ + get lastModified(): number; +} +interface FileOptions { + type?: string; + lastModified?: number; +} +/** +* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) +*/ +declare abstract class CacheStorage { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) */ + open(cacheName: string): Promise; + readonly default: Cache; +} +/** +* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) +*/ +declare abstract class Cache { + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */ + delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */ + match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */ + put(request: RequestInfo | URL, response: Response): Promise; +} +interface CacheQueryOptions { + ignoreMethod?: boolean; +} +/** +* The Web Crypto API provides a set of low-level functions for common cryptographic tasks. +* The Workers runtime implements the full surface of this API, but with some differences in +* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) +* compared to those implemented in most browsers. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) +*/ +declare abstract class Crypto { + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) + */ + get subtle(): SubtleCrypto; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */ + getRandomValues(buffer: T): T; + /** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) + */ + randomUUID(): string; + DigestStream: typeof DigestStream; +} +/** + * This Web Crypto API interface provides a number of low-level cryptographic functions. It is accessed via the Crypto.subtle properties available in a window context (via Window.crypto). + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto) + */ +declare abstract class SubtleCrypto { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt) */ + encrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, plainText: ArrayBuffer | ArrayBufferView): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) */ + decrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, cipherText: ArrayBuffer | ArrayBufferView): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign) */ + sign(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, data: ArrayBuffer | ArrayBufferView): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify) */ + verify(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, signature: ArrayBuffer | ArrayBufferView, data: ArrayBuffer | ArrayBufferView): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) */ + digest(algorithm: string | SubtleCryptoHashAlgorithm, data: ArrayBuffer | ArrayBufferView): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) */ + generateKey(algorithm: string | SubtleCryptoGenerateKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ + deriveKey(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) */ + deriveBits(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, length?: number | null): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) */ + importKey(format: string, keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, algorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey) */ + exportKey(format: string, key: CryptoKey): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey) */ + wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) */ + unwrapKey(format: string, wrappedKey: ArrayBuffer | ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; + timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean; +} +/** + * The CryptoKey dictionary of the Web Crypto API represents a cryptographic key. + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey) + */ +declare abstract class CryptoKey { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */ + readonly type: string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */ + readonly extractable: boolean; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */ + readonly algorithm: CryptoKeyKeyAlgorithm | CryptoKeyAesKeyAlgorithm | CryptoKeyHmacKeyAlgorithm | CryptoKeyRsaKeyAlgorithm | CryptoKeyEllipticKeyAlgorithm | CryptoKeyArbitraryKeyAlgorithm; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */ + readonly usages: string[]; +} +interface CryptoKeyPair { + publicKey: CryptoKey; + privateKey: CryptoKey; +} +interface JsonWebKey { + kty: string; + use?: string; + key_ops?: string[]; + alg?: string; + ext?: boolean; + crv?: string; + x?: string; + y?: string; + d?: string; + n?: string; + e?: string; + p?: string; + q?: string; + dp?: string; + dq?: string; + qi?: string; + oth?: RsaOtherPrimesInfo[]; + k?: string; +} +interface RsaOtherPrimesInfo { + r?: string; + d?: string; + t?: string; +} +interface SubtleCryptoDeriveKeyAlgorithm { + name: string; + salt?: (ArrayBuffer | ArrayBufferView); + iterations?: number; + hash?: (string | SubtleCryptoHashAlgorithm); + $public?: CryptoKey; + info?: (ArrayBuffer | ArrayBufferView); +} +interface SubtleCryptoEncryptAlgorithm { + name: string; + iv?: (ArrayBuffer | ArrayBufferView); + additionalData?: (ArrayBuffer | ArrayBufferView); + tagLength?: number; + counter?: (ArrayBuffer | ArrayBufferView); + length?: number; + label?: (ArrayBuffer | ArrayBufferView); +} +interface SubtleCryptoGenerateKeyAlgorithm { + name: string; + hash?: (string | SubtleCryptoHashAlgorithm); + modulusLength?: number; + publicExponent?: (ArrayBuffer | ArrayBufferView); + length?: number; + namedCurve?: string; +} +interface SubtleCryptoHashAlgorithm { + name: string; +} +interface SubtleCryptoImportKeyAlgorithm { + name: string; + hash?: (string | SubtleCryptoHashAlgorithm); + length?: number; + namedCurve?: string; + compressed?: boolean; +} +interface SubtleCryptoSignAlgorithm { + name: string; + hash?: (string | SubtleCryptoHashAlgorithm); + dataLength?: number; + saltLength?: number; +} +interface CryptoKeyKeyAlgorithm { + name: string; +} +interface CryptoKeyAesKeyAlgorithm { + name: string; + length: number; +} +interface CryptoKeyHmacKeyAlgorithm { + name: string; + hash: CryptoKeyKeyAlgorithm; + length: number; +} +interface CryptoKeyRsaKeyAlgorithm { + name: string; + modulusLength: number; + publicExponent: ArrayBuffer | ArrayBufferView; + hash?: CryptoKeyKeyAlgorithm; +} +interface CryptoKeyEllipticKeyAlgorithm { + name: string; + namedCurve: string; +} +interface CryptoKeyArbitraryKeyAlgorithm { + name: string; + hash?: CryptoKeyKeyAlgorithm; + namedCurve?: string; + length?: number; +} +declare class DigestStream extends WritableStream { + constructor(algorithm: string | SubtleCryptoHashAlgorithm); + readonly digest: Promise; + get bytesWritten(): number | bigint; +} +/** + * A decoder for a specific method, that is a specific character encoding, like utf-8, iso-8859-2, koi8, cp1261, gbk, etc. A decoder takes a stream of bytes as input and emits a stream of code points. For a more scalable, non-native library, see StringView – a C-like representation of strings based on typed arrays. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder) + */ +declare class TextDecoder { + constructor(label?: string, options?: TextDecoderConstructorOptions); + /** + * Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments. + * + * ``` + * var string = "", decoder = new TextDecoder(encoding), buffer; + * while(buffer = next_chunk()) { + * string += decoder.decode(buffer, {stream:true}); + * } + * string += decoder.decode(); // end-of-queue + * ``` + * + * If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) + */ + decode(input?: (ArrayBuffer | ArrayBufferView), options?: TextDecoderDecodeOptions): string; + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +/** + * TextEncoder takes a stream of code points as input and emits a stream of bytes. For a more scalable, non-native library, see StringView – a C-like representation of strings based on typed arrays. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder) + */ +declare class TextEncoder { + constructor(); + /** + * Returns the result of running UTF-8's encoder. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) + */ + encode(input?: string): Uint8Array; + /** + * Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) + */ + encodeInto(input: string, buffer: ArrayBuffer | ArrayBufferView): TextEncoderEncodeIntoResult; + get encoding(): string; +} +interface TextDecoderConstructorOptions { + fatal: boolean; + ignoreBOM: boolean; +} +interface TextDecoderDecodeOptions { + stream: boolean; +} +interface TextEncoderEncodeIntoResult { + read: number; + written: number; +} +/** + * Events providing information related to errors in scripts or in files. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent) + */ +declare class ErrorEvent extends Event { + constructor(type: string, init?: ErrorEventErrorEventInit); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) */ + get filename(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) */ + get message(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) */ + get lineno(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) */ + get colno(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) */ + get error(): any; +} +interface ErrorEventErrorEventInit { + message?: string; + filename?: string; + lineno?: number; + colno?: number; + error?: any; +} +/** + * A message received by a target object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent) + */ +declare class MessageEvent extends Event { + constructor(type: string, initializer: MessageEventInit); + /** + * Returns the data of the message. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data) + */ + readonly data: any; + /** + * Returns the origin of the message, for server-sent events and cross-document messaging. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin) + */ + readonly origin: string | null; + /** + * Returns the last event ID string, for server-sent events. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId) + */ + readonly lastEventId: string; + /** + * Returns the WindowProxy of the source window, for cross-document messaging, and the MessagePort being attached, in the connect event fired at SharedWorkerGlobalScope objects. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source) + */ + readonly source: MessagePort | null; + /** + * Returns the MessagePort array sent with the message, for cross-document messaging and channel messaging. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports) + */ + readonly ports: MessagePort[]; +} +interface MessageEventInit { + data: ArrayBuffer | string; +} +/** + * Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData) + */ +declare class FormData { + constructor(); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) */ + append(name: string, value: string): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) */ + append(name: string, value: Blob, filename?: string): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete) */ + delete(name: string): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get) */ + get(name: string): (File | string) | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll) */ + getAll(name: string): (File | string)[]; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) */ + has(name: string): boolean; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) */ + set(name: string, value: string): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) */ + set(name: string, value: Blob, filename?: string): void; + /* Returns an array of key, value pairs for every entry in the list. */ + entries(): IterableIterator<[ + key: string, + value: File | string + ]>; + /* Returns a list of keys in the list. */ + keys(): IterableIterator; + /* Returns a list of values in the list. */ + values(): IterableIterator<(File | string)>; + forEach(callback: (this: This, value: File | string, key: string, parent: FormData) => void, thisArg?: This): void; + [Symbol.iterator](): IterableIterator<[ + key: string, + value: File | string + ]>; +} +interface ContentOptions { + html?: boolean; +} +declare class HTMLRewriter { + constructor(); + on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter; + onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; + transform(response: Response): Response; +} +interface HTMLRewriterElementContentHandlers { + element?(element: Element): void | Promise; + comments?(comment: Comment): void | Promise; + text?(element: Text): void | Promise; +} +interface HTMLRewriterDocumentContentHandlers { + doctype?(doctype: Doctype): void | Promise; + comments?(comment: Comment): void | Promise; + text?(text: Text): void | Promise; + end?(end: DocumentEnd): void | Promise; +} +interface Doctype { + readonly name: string | null; + readonly publicId: string | null; + readonly systemId: string | null; +} +interface Element { + tagName: string; + readonly attributes: IterableIterator; + readonly removed: boolean; + readonly namespaceURI: string; + getAttribute(name: string): string | null; + hasAttribute(name: string): boolean; + setAttribute(name: string, value: string): Element; + removeAttribute(name: string): Element; + before(content: string | ReadableStream | Response, options?: ContentOptions): Element; + after(content: string | ReadableStream | Response, options?: ContentOptions): Element; + prepend(content: string | ReadableStream | Response, options?: ContentOptions): Element; + append(content: string | ReadableStream | Response, options?: ContentOptions): Element; + replace(content: string | ReadableStream | Response, options?: ContentOptions): Element; + remove(): Element; + removeAndKeepContent(): Element; + setInnerContent(content: string | ReadableStream | Response, options?: ContentOptions): Element; + onEndTag(handler: (tag: EndTag) => void | Promise): void; +} +interface EndTag { + name: string; + before(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; + after(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; + remove(): EndTag; +} +interface Comment { + text: string; + readonly removed: boolean; + before(content: string, options?: ContentOptions): Comment; + after(content: string, options?: ContentOptions): Comment; + replace(content: string, options?: ContentOptions): Comment; + remove(): Comment; +} +interface Text { + readonly text: string; + readonly lastInTextNode: boolean; + readonly removed: boolean; + before(content: string | ReadableStream | Response, options?: ContentOptions): Text; + after(content: string | ReadableStream | Response, options?: ContentOptions): Text; + replace(content: string | ReadableStream | Response, options?: ContentOptions): Text; + remove(): Text; +} +interface DocumentEnd { + append(content: string, options?: ContentOptions): DocumentEnd; +} +/** + * This is the event type for fetch events dispatched on the service worker global scope. It contains information about the fetch, including the request and how the receiver will treat the response. It provides the event.respondWith() method, which allows us to provide a response to this fetch. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent) + */ +declare abstract class FetchEvent extends ExtendableEvent { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) */ + readonly request: Request; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) */ + respondWith(promise: Response | Promise): void; + passThroughOnException(): void; +} +type HeadersInit = Headers | Iterable> | Record; +/** + * This Fetch API interface allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing. A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs.  You can add to this using methods like append() (see Examples.) In all methods of this interface, header names are matched by case-insensitive byte sequence. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers) + */ +declare class Headers { + constructor(init?: HeadersInit); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get) */ + get(name: string): string | null; + getAll(name: string): string[]; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie) */ + getSetCookie(): string[]; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has) */ + has(name: string): boolean; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set) */ + set(name: string, value: string): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append) */ + append(name: string, value: string): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete) */ + delete(name: string): void; + forEach(callback: (this: This, value: string, key: string, parent: Headers) => void, thisArg?: This): void; + /* Returns an iterator allowing to go through all key/value pairs contained in this object. */ + entries(): IterableIterator<[ + key: string, + value: string + ]>; + /* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ + keys(): IterableIterator; + /* Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[ + key: string, + value: string + ]>; +} +type BodyInit = ReadableStream | string | ArrayBuffer | ArrayBufferView | Blob | URLSearchParams | FormData; +declare abstract class Body { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */ + get body(): ReadableStream | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */ + get bodyUsed(): boolean; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */ + arrayBuffer(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */ + bytes(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */ + text(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */ + json(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */ + formData(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */ + blob(): Promise; +} +/** + * This Fetch API interface represents the response to a request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) + */ +declare var Response: { + prototype: Response; + new (body?: BodyInit | null, init?: ResponseInit): Response; + error(): Response; + redirect(url: string, status?: number): Response; + json(any: any, maybeInit?: (ResponseInit | Response)): Response; +}; +/** + * This Fetch API interface represents the response to a request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) + */ +interface Response extends Body { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) */ + clone(): Response; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) */ + status: number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) */ + statusText: string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) */ + headers: Headers; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) */ + ok: boolean; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) */ + redirected: boolean; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) */ + url: string; + webSocket: WebSocket | null; + cf: any | undefined; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type) */ + type: "default" | "error"; +} +interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; + cf?: any; + webSocket?: (WebSocket | null); + encodeBody?: "automatic" | "manual"; +} +type RequestInfo> = Request | string; +/** + * This Fetch API interface represents a resource request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) + */ +declare var Request: { + prototype: Request; + new >(input: RequestInfo | URL, init?: RequestInit): Request; +}; +/** + * This Fetch API interface represents a resource request. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) + */ +interface Request> extends Body { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) */ + clone(): Request; + /** + * Returns request's HTTP method, which is "GET" by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) + */ + method: string; + /** + * Returns the URL of request as a string. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) + */ + url: string; + /** + * Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) + */ + headers: Headers; + /** + * Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) + */ + redirect: string; + fetcher: Fetcher | null; + /** + * Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) + */ + signal: AbortSignal; + cf: Cf | undefined; + /** + * Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) + */ + integrity: string; + /** + * Returns a boolean indicating whether or not request can outlive the global in which it was created. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) + */ + keepalive: boolean; + /** + * Returns the cache mode associated with request, which is a string indicating how the request will interact with the browser's cache when fetching. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache) + */ + cache?: "no-store"; +} +interface RequestInit { + /* A string to set request's method. */ + method?: string; + /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ + headers?: HeadersInit; + /* A BodyInit object or null to set request's body. */ + body?: BodyInit | null; + /* A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ + redirect?: string; + fetcher?: (Fetcher | null); + cf?: Cf; + /* A string indicating how the request will interact with the browser's cache to set request's cache. */ + cache?: "no-store"; + /* A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ + integrity?: string; + /* An AbortSignal to set request's signal. */ + signal?: (AbortSignal | null); + encodeResponseBody?: "automatic" | "manual"; +} +type Service Rpc.WorkerEntrypointBranded) | Rpc.WorkerEntrypointBranded | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? Fetcher> : T extends Rpc.WorkerEntrypointBranded ? Fetcher : T extends Exclude ? never : Fetcher; +type Fetcher = (T extends Rpc.EntrypointBranded ? Rpc.Provider : unknown) & { + fetch(input: RequestInfo | URL, init?: RequestInit): Promise; + connect(address: SocketAddress | string, options?: SocketOptions): Socket; +}; +interface KVNamespaceListKey { + name: Key; + expiration?: number; + metadata?: Metadata; +} +type KVNamespaceListResult = { + list_complete: false; + keys: KVNamespaceListKey[]; + cursor: string; + cacheStatus: string | null; +} | { + list_complete: true; + keys: KVNamespaceListKey[]; + cacheStatus: string | null; +}; +interface KVNamespace { + get(key: Key, options?: Partial>): Promise; + get(key: Key, type: "text"): Promise; + get(key: Key, type: "json"): Promise; + get(key: Key, type: "arrayBuffer"): Promise; + get(key: Key, type: "stream"): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"text">): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"json">): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"arrayBuffer">): Promise; + get(key: Key, options?: KVNamespaceGetOptions<"stream">): Promise; + get(key: Array, type: "text"): Promise>; + get(key: Array, type: "json"): Promise>; + get(key: Array, options?: Partial>): Promise>; + get(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>; + get(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>; + list(options?: KVNamespaceListOptions): Promise>; + put(key: Key, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVNamespacePutOptions): Promise; + getWithMetadata(key: Key, options?: Partial>): Promise>; + getWithMetadata(key: Key, type: "text"): Promise>; + getWithMetadata(key: Key, type: "json"): Promise>; + getWithMetadata(key: Key, type: "arrayBuffer"): Promise>; + getWithMetadata(key: Key, type: "stream"): Promise>; + getWithMetadata(key: Key, options: KVNamespaceGetOptions<"text">): Promise>; + getWithMetadata(key: Key, options: KVNamespaceGetOptions<"json">): Promise>; + getWithMetadata(key: Key, options: KVNamespaceGetOptions<"arrayBuffer">): Promise>; + getWithMetadata(key: Key, options: KVNamespaceGetOptions<"stream">): Promise>; + getWithMetadata(key: Array, type: "text"): Promise>>; + getWithMetadata(key: Array, type: "json"): Promise>>; + getWithMetadata(key: Array, options?: Partial>): Promise>>; + getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>>; + getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>>; + delete(key: Key): Promise; +} +interface KVNamespaceListOptions { + limit?: number; + prefix?: (string | null); + cursor?: (string | null); +} +interface KVNamespaceGetOptions { + type: Type; + cacheTtl?: number; +} +interface KVNamespacePutOptions { + expiration?: number; + expirationTtl?: number; + metadata?: (any | null); +} +interface KVNamespaceGetWithMetadataResult { + value: Value | null; + metadata: Metadata | null; + cacheStatus: string | null; +} +type QueueContentType = "text" | "bytes" | "json" | "v8"; +interface Queue { + send(message: Body, options?: QueueSendOptions): Promise; + sendBatch(messages: Iterable>, options?: QueueSendBatchOptions): Promise; +} +interface QueueSendOptions { + contentType?: QueueContentType; + delaySeconds?: number; +} +interface QueueSendBatchOptions { + delaySeconds?: number; +} +interface MessageSendRequest { + body: Body; + contentType?: QueueContentType; + delaySeconds?: number; +} +interface QueueRetryOptions { + delaySeconds?: number; +} +interface Message { + readonly id: string; + readonly timestamp: Date; + readonly body: Body; + readonly attempts: number; + retry(options?: QueueRetryOptions): void; + ack(): void; +} +interface QueueEvent extends ExtendableEvent { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +interface MessageBatch { + readonly messages: readonly Message[]; + readonly queue: string; + retryAll(options?: QueueRetryOptions): void; + ackAll(): void; +} +interface R2Error extends Error { + readonly name: string; + readonly code: number; + readonly message: string; + readonly action: string; + readonly stack: any; +} +interface R2ListOptions { + limit?: number; + prefix?: string; + cursor?: string; + delimiter?: string; + startAfter?: string; + include?: ("httpMetadata" | "customMetadata")[]; +} +declare abstract class R2Bucket { + head(key: string): Promise; + get(key: string, options: R2GetOptions & { + onlyIf: R2Conditional | Headers; + }): Promise; + get(key: string, options?: R2GetOptions): Promise; + put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions & { + onlyIf: R2Conditional | Headers; + }): Promise; + put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions): Promise; + createMultipartUpload(key: string, options?: R2MultipartOptions): Promise; + resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; + delete(keys: string | string[]): Promise; + list(options?: R2ListOptions): Promise; +} +interface R2MultipartUpload { + readonly key: string; + readonly uploadId: string; + uploadPart(partNumber: number, value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, options?: R2UploadPartOptions): Promise; + abort(): Promise; + complete(uploadedParts: R2UploadedPart[]): Promise; +} +interface R2UploadedPart { + partNumber: number; + etag: string; +} +declare abstract class R2Object { + readonly key: string; + readonly version: string; + readonly size: number; + readonly etag: string; + readonly httpEtag: string; + readonly checksums: R2Checksums; + readonly uploaded: Date; + readonly httpMetadata?: R2HTTPMetadata; + readonly customMetadata?: Record; + readonly range?: R2Range; + readonly storageClass: string; + readonly ssecKeyMd5?: string; + writeHttpMetadata(headers: Headers): void; +} +interface R2ObjectBody extends R2Object { + get body(): ReadableStream; + get bodyUsed(): boolean; + arrayBuffer(): Promise; + bytes(): Promise; + text(): Promise; + json(): Promise; + blob(): Promise; +} +type R2Range = { + offset: number; + length?: number; +} | { + offset?: number; + length: number; +} | { + suffix: number; +}; +interface R2Conditional { + etagMatches?: string; + etagDoesNotMatch?: string; + uploadedBefore?: Date; + uploadedAfter?: Date; + secondsGranularity?: boolean; +} +interface R2GetOptions { + onlyIf?: (R2Conditional | Headers); + range?: (R2Range | Headers); + ssecKey?: (ArrayBuffer | string); +} +interface R2PutOptions { + onlyIf?: (R2Conditional | Headers); + httpMetadata?: (R2HTTPMetadata | Headers); + customMetadata?: Record; + md5?: ((ArrayBuffer | ArrayBufferView) | string); + sha1?: ((ArrayBuffer | ArrayBufferView) | string); + sha256?: ((ArrayBuffer | ArrayBufferView) | string); + sha384?: ((ArrayBuffer | ArrayBufferView) | string); + sha512?: ((ArrayBuffer | ArrayBufferView) | string); + storageClass?: string; + ssecKey?: (ArrayBuffer | string); +} +interface R2MultipartOptions { + httpMetadata?: (R2HTTPMetadata | Headers); + customMetadata?: Record; + storageClass?: string; + ssecKey?: (ArrayBuffer | string); +} +interface R2Checksums { + readonly md5?: ArrayBuffer; + readonly sha1?: ArrayBuffer; + readonly sha256?: ArrayBuffer; + readonly sha384?: ArrayBuffer; + readonly sha512?: ArrayBuffer; + toJSON(): R2StringChecksums; +} +interface R2StringChecksums { + md5?: string; + sha1?: string; + sha256?: string; + sha384?: string; + sha512?: string; +} +interface R2HTTPMetadata { + contentType?: string; + contentLanguage?: string; + contentDisposition?: string; + contentEncoding?: string; + cacheControl?: string; + cacheExpiry?: Date; +} +type R2Objects = { + objects: R2Object[]; + delimitedPrefixes: string[]; +} & ({ + truncated: true; + cursor: string; +} | { + truncated: false; +}); +interface R2UploadPartOptions { + ssecKey?: (ArrayBuffer | string); +} +declare abstract class ScheduledEvent extends ExtendableEvent { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +interface ScheduledController { + readonly scheduledTime: number; + readonly cron: string; + noRetry(): void; +} +interface QueuingStrategy { + highWaterMark?: (number | bigint); + size?: (chunk: T) => number | bigint; +} +interface UnderlyingSink { + type?: string; + start?: (controller: WritableStreamDefaultController) => void | Promise; + write?: (chunk: W, controller: WritableStreamDefaultController) => void | Promise; + abort?: (reason: any) => void | Promise; + close?: () => void | Promise; +} +interface UnderlyingByteSource { + type: "bytes"; + autoAllocateChunkSize?: number; + start?: (controller: ReadableByteStreamController) => void | Promise; + pull?: (controller: ReadableByteStreamController) => void | Promise; + cancel?: (reason: any) => void | Promise; +} +interface UnderlyingSource { + type?: "" | undefined; + start?: (controller: ReadableStreamDefaultController) => void | Promise; + pull?: (controller: ReadableStreamDefaultController) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: (number | bigint); +} +interface Transformer { + readableType?: string; + writableType?: string; + start?: (controller: TransformStreamDefaultController) => void | Promise; + transform?: (chunk: I, controller: TransformStreamDefaultController) => void | Promise; + flush?: (controller: TransformStreamDefaultController) => void | Promise; + cancel?: (reason: any) => void | Promise; + expectedLength?: number; +} +interface StreamPipeOptions { + /** + * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate as follows: + * + * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. + * + * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. + * + * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. + * + * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. + * + * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. + */ + preventClose?: boolean; + preventAbort?: boolean; + preventCancel?: boolean; + signal?: AbortSignal; +} +type ReadableStreamReadResult = { + done: false; + value: R; +} | { + done: true; + value?: undefined; +}; +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +interface ReadableStream { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) */ + get locked(): boolean; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) */ + cancel(reason?: any): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(): ReadableStreamDefaultReader; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) */ + getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) */ + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) */ + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) */ + tee(): [ + ReadableStream, + ReadableStream + ]; + values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; + [Symbol.asyncIterator](options?: ReadableStreamValuesOptions): AsyncIterableIterator; +} +/** + * This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) + */ +declare const ReadableStream: { + prototype: ReadableStream; + new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new (underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; +}; +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader) */ +declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) */ + read(): Promise>; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) */ + releaseLock(): void; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) */ +declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + get closed(): Promise; + cancel(reason?: any): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) */ + read(view: T): Promise>; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) */ + releaseLock(): void; + readAtLeast(minElements: number, view: T): Promise>; +} +interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { + min?: number; +} +interface ReadableStreamGetReaderOptions { + /** + * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. + * + * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. + */ + mode: "byob"; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ +declare abstract class ReadableStreamBYOBRequest { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) */ + get view(): Uint8Array | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) */ + respond(bytesWritten: number): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) */ + respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; + get atLeast(): number | null; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) */ +declare abstract class ReadableStreamDefaultController { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) */ + close(): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) */ + enqueue(chunk?: R): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) */ + error(reason: any): void; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) */ +declare abstract class ReadableByteStreamController { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) */ + get desiredSize(): number | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) */ + close(): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) */ + enqueue(chunk: ArrayBuffer | ArrayBufferView): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) */ + error(reason: any): void; +} +/** + * This Streams API interface represents a controller allowing control of a WritableStream's state. When constructing a WritableStream, the underlying sink is given a corresponding WritableStreamDefaultController instance to manipulate. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) + */ +declare abstract class WritableStreamDefaultController { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) */ + get signal(): AbortSignal; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) */ + error(reason?: any): void; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) */ +declare abstract class TransformStreamDefaultController { + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) */ + get desiredSize(): number | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) */ + enqueue(chunk?: O): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) */ + error(reason: any): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) */ + terminate(): void; +} +interface ReadableWritablePair { + /** + * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. + */ + writable: WritableStream; + readable: ReadableStream; +} +/** + * This Streams API interface provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream) + */ +declare class WritableStream { + constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) */ + get locked(): boolean; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) */ + abort(reason?: any): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) */ + close(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) */ + getWriter(): WritableStreamDefaultWriter; +} +/** + * This Streams API interface is the object returned by WritableStream.getWriter() and once created locks the < writer to the WritableStream ensuring that no other streams can write to the underlying sink. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter) + */ +declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) */ + get closed(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) */ + get ready(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) */ + get desiredSize(): number | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) */ + abort(reason?: any): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) */ + close(): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) */ + write(chunk?: W): Promise; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) */ + releaseLock(): void; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream) */ +declare class TransformStream { + constructor(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) */ + get readable(): ReadableStream; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) */ + get writable(): WritableStream; +} +declare class FixedLengthStream extends IdentityTransformStream { + constructor(expectedLength: number | bigint, queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +declare class IdentityTransformStream extends TransformStream { + constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); +} +interface IdentityTransformStreamQueuingStrategy { + highWaterMark?: (number | bigint); +} +interface ReadableStreamValuesOptions { + preventCancel?: boolean; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) */ +declare class CompressionStream extends TransformStream { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream) */ +declare class DecompressionStream extends TransformStream { + constructor(format: "gzip" | "deflate" | "deflate-raw"); +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream) */ +declare class TextEncoderStream extends TransformStream { + constructor(); + get encoding(): string; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream) */ +declare class TextDecoderStream extends TransformStream { + constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); + get encoding(): string; + get fatal(): boolean; + get ignoreBOM(): boolean; +} +interface TextDecoderStreamTextDecoderStreamInit { + fatal?: boolean; + ignoreBOM?: boolean; +} +/** + * This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy) + */ +declare class ByteLengthQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +/** + * This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy) + */ +declare class CountQueuingStrategy implements QueuingStrategy { + constructor(init: QueuingStrategyInit); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) */ + get highWaterMark(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ + get size(): (chunk?: any) => number; +} +interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water mark. + * + * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. + */ + highWaterMark: number; +} +interface ScriptVersion { + id?: string; + tag?: string; + message?: string; +} +declare abstract class TailEvent extends ExtendableEvent { + readonly events: TraceItem[]; + readonly traces: TraceItem[]; +} +interface TraceItem { + readonly event: (TraceItemFetchEventInfo | TraceItemJsRpcEventInfo | TraceItemScheduledEventInfo | TraceItemAlarmEventInfo | TraceItemQueueEventInfo | TraceItemEmailEventInfo | TraceItemTailEventInfo | TraceItemCustomEventInfo | TraceItemHibernatableWebSocketEventInfo) | null; + readonly eventTimestamp: number | null; + readonly logs: TraceLog[]; + readonly exceptions: TraceException[]; + readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; + readonly scriptName: string | null; + readonly entrypoint?: string; + readonly scriptVersion?: ScriptVersion; + readonly dispatchNamespace?: string; + readonly scriptTags?: string[]; + readonly durableObjectId?: string; + readonly outcome: string; + readonly executionModel: string; + readonly truncated: boolean; + readonly cpuTime: number; + readonly wallTime: number; +} +interface TraceItemAlarmEventInfo { + readonly scheduledTime: Date; +} +interface TraceItemCustomEventInfo { +} +interface TraceItemScheduledEventInfo { + readonly scheduledTime: number; + readonly cron: string; +} +interface TraceItemQueueEventInfo { + readonly queue: string; + readonly batchSize: number; +} +interface TraceItemEmailEventInfo { + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; +} +interface TraceItemTailEventInfo { + readonly consumedEvents: TraceItemTailEventInfoTailItem[]; +} +interface TraceItemTailEventInfoTailItem { + readonly scriptName: string | null; +} +interface TraceItemFetchEventInfo { + readonly response?: TraceItemFetchEventInfoResponse; + readonly request: TraceItemFetchEventInfoRequest; +} +interface TraceItemFetchEventInfoRequest { + readonly cf?: any; + readonly headers: Record; + readonly method: string; + readonly url: string; + getUnredacted(): TraceItemFetchEventInfoRequest; +} +interface TraceItemFetchEventInfoResponse { + readonly status: number; +} +interface TraceItemJsRpcEventInfo { + readonly rpcMethod: string; +} +interface TraceItemHibernatableWebSocketEventInfo { + readonly getWebSocketEvent: TraceItemHibernatableWebSocketEventInfoMessage | TraceItemHibernatableWebSocketEventInfoClose | TraceItemHibernatableWebSocketEventInfoError; +} +interface TraceItemHibernatableWebSocketEventInfoMessage { + readonly webSocketEventType: string; +} +interface TraceItemHibernatableWebSocketEventInfoClose { + readonly webSocketEventType: string; + readonly code: number; + readonly wasClean: boolean; +} +interface TraceItemHibernatableWebSocketEventInfoError { + readonly webSocketEventType: string; +} +interface TraceLog { + readonly timestamp: number; + readonly level: string; + readonly message: any; +} +interface TraceException { + readonly timestamp: number; + readonly message: string; + readonly name: string; + readonly stack?: string; +} +interface TraceDiagnosticChannelEvent { + readonly timestamp: number; + readonly channel: string; + readonly message: any; +} +interface TraceMetrics { + readonly cpuTime: number; + readonly wallTime: number; +} +interface UnsafeTraceMetrics { + fromTrace(item: TraceItem): TraceMetrics; +} +/** + * The URL interface represents an object providing static methods used for creating object URLs. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL) + */ +declare class URL { + constructor(url: string | URL, base?: string | URL); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + get origin(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + get href(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + set href(value: string); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + get protocol(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + set protocol(value: string); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + get username(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + set username(value: string); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + get password(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + set password(value: string); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + get host(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + set host(value: string); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + get hostname(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + set hostname(value: string); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + get port(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + set port(value: string); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + get pathname(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + set pathname(value: string); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + get search(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + set search(value: string); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + get hash(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + set hash(value: string); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + get searchParams(): URLSearchParams; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; + /*function toString() { [native code] }*/ + toString(): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) */ + static canParse(url: string, base?: string): boolean; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static) */ + static parse(url: string, base?: string): URL | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static) */ + static createObjectURL(object: File | Blob): string; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static) */ + static revokeObjectURL(object_url: string): void; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams) */ +declare class URLSearchParams { + constructor(init?: (Iterable> | Record | string)); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size) */ + get size(): number; + /** + * Appends a specified key/value pair as a new search parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append) + */ + append(name: string, value: string): void; + /** + * Deletes the given search parameter, and its associated value, from the list of all search parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete) + */ + delete(name: string, value?: string): void; + /** + * Returns the first value associated to the given search parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get) + */ + get(name: string): string | null; + /** + * Returns all the values association with a given search parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll) + */ + getAll(name: string): string[]; + /** + * Returns a Boolean indicating if such a search parameter exists. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has) + */ + has(name: string, value?: string): boolean; + /** + * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set) + */ + set(name: string, value: string): void; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort) */ + sort(): void; + /* Returns an array of key, value pairs for every entry in the search params. */ + entries(): IterableIterator<[ + key: string, + value: string + ]>; + /* Returns a list of keys in the search params. */ + keys(): IterableIterator; + /* Returns a list of values in the search params. */ + values(): IterableIterator; + forEach(callback: (this: This, value: string, key: string, parent: URLSearchParams) => void, thisArg?: This): void; + /*function toString() { [native code] } Returns a string containing a query string suitable for use in a URL. Does not include the question mark. */ + toString(): string; + [Symbol.iterator](): IterableIterator<[ + key: string, + value: string + ]>; +} +declare class URLPattern { + constructor(input?: (string | URLPatternInit), baseURL?: (string | URLPatternOptions), patternOptions?: URLPatternOptions); + get protocol(): string; + get username(): string; + get password(): string; + get hostname(): string; + get port(): string; + get pathname(): string; + get search(): string; + get hash(): string; + get hasRegExpGroups(): boolean; + test(input?: (string | URLPatternInit), baseURL?: string): boolean; + exec(input?: (string | URLPatternInit), baseURL?: string): URLPatternResult | null; +} +interface URLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} +interface URLPatternComponentResult { + input: string; + groups: Record; +} +interface URLPatternResult { + inputs: (string | URLPatternInit)[]; + protocol: URLPatternComponentResult; + username: URLPatternComponentResult; + password: URLPatternComponentResult; + hostname: URLPatternComponentResult; + port: URLPatternComponentResult; + pathname: URLPatternComponentResult; + search: URLPatternComponentResult; + hash: URLPatternComponentResult; +} +interface URLPatternOptions { + ignoreCase?: boolean; +} +/** + * A CloseEvent is sent to clients using WebSockets when the connection is closed. This is delivered to the listener indicated by the WebSocket object's onclose attribute. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent) + */ +declare class CloseEvent extends Event { + constructor(type: string, initializer?: CloseEventInit); + /** + * Returns the WebSocket connection close code provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) + */ + readonly code: number; + /** + * Returns the WebSocket connection close reason provided by the server. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) + */ + readonly reason: string; + /** + * Returns true if the connection closed cleanly; false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) + */ + readonly wasClean: boolean; +} +interface CloseEventInit { + code?: number; + reason?: string; + wasClean?: boolean; +} +type WebSocketEventMap = { + close: CloseEvent; + message: MessageEvent; + open: Event; + error: ErrorEvent; +}; +/** + * Provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) + */ +declare var WebSocket: { + prototype: WebSocket; + new (url: string, protocols?: (string[] | string)): WebSocket; + readonly READY_STATE_CONNECTING: number; + readonly CONNECTING: number; + readonly READY_STATE_OPEN: number; + readonly OPEN: number; + readonly READY_STATE_CLOSING: number; + readonly CLOSING: number; + readonly READY_STATE_CLOSED: number; + readonly CLOSED: number; +}; +/** + * Provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) + */ +interface WebSocket extends EventTarget { + accept(): void; + /** + * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) + */ + send(message: (ArrayBuffer | ArrayBufferView) | string): void; + /** + * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) + */ + close(code?: number, reason?: string): void; + serializeAttachment(attachment: any): void; + deserializeAttachment(): any | null; + /** + * Returns the state of the WebSocket object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) + */ + readyState: number; + /** + * Returns the URL that was used to establish the WebSocket connection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) + */ + url: string | null; + /** + * Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) + */ + protocol: string | null; + /** + * Returns the extensions selected by the server, if any. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) + */ + extensions: string | null; +} +declare const WebSocketPair: { + new (): { + 0: WebSocket; + 1: WebSocket; + }; +}; +interface SqlStorage { + exec>(query: string, ...bindings: any[]): SqlStorageCursor; + get databaseSize(): number; + Cursor: typeof SqlStorageCursor; + Statement: typeof SqlStorageStatement; +} +declare abstract class SqlStorageStatement { +} +type SqlStorageValue = ArrayBuffer | string | number | null; +declare abstract class SqlStorageCursor> { + next(): { + done?: false; + value: T; + } | { + done: true; + value?: never; + }; + toArray(): T[]; + one(): T; + raw(): IterableIterator; + columnNames: string[]; + get rowsRead(): number; + get rowsWritten(): number; + [Symbol.iterator](): IterableIterator; +} +interface Socket { + get readable(): ReadableStream; + get writable(): WritableStream; + get closed(): Promise; + get opened(): Promise; + get upgraded(): boolean; + get secureTransport(): "on" | "off" | "starttls"; + close(): Promise; + startTls(options?: TlsOptions): Socket; +} +interface SocketOptions { + secureTransport?: string; + allowHalfOpen: boolean; + highWaterMark?: (number | bigint); +} +interface SocketAddress { + hostname: string; + port: number; +} +interface TlsOptions { + expectedServerHostname?: string; +} +interface SocketInfo { + remoteAddress?: string; + localAddress?: string; +} +/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) */ +declare class EventSource extends EventTarget { + constructor(url: string, init?: EventSourceEventSourceInit); + /** + * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) + */ + close(): void; + /** + * Returns the URL providing the event stream. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) + */ + get url(): string; + /** + * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) + */ + get withCredentials(): boolean; + /** + * Returns the state of this EventSource object's connection. It can have the values described below. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) + */ + get readyState(): number; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + get onopen(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ + set onopen(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + get onmessage(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ + set onmessage(value: any | null); + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + get onerror(): any | null; + /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ + set onerror(value: any | null); + static readonly CONNECTING: number; + static readonly OPEN: number; + static readonly CLOSED: number; + static from(stream: ReadableStream): EventSource; +} +interface EventSourceEventSourceInit { + withCredentials?: boolean; + fetcher?: Fetcher; +} +interface Container { + get running(): boolean; + start(options?: ContainerStartupOptions): void; + monitor(): Promise; + destroy(error?: any): Promise; + signal(signo: number): void; + getTcpPort(port: number): Fetcher; +} +interface ContainerStartupOptions { + entrypoint?: string[]; + enableInternet: boolean; + env?: Record; +} +/** + * This Channel Messaging API interface represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort) + */ +interface MessagePort extends EventTarget { + /** + * Posts a message through the channel. Objects listed in transfer are transferred, not just cloned, meaning that they are no longer usable on the sending side. + * + * Throws a "DataCloneError" DOMException if transfer contains duplicate objects or port, or if message could not be cloned. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage) + */ + postMessage(data?: any, options?: (any[] | MessagePortPostMessageOptions)): void; + /** + * Disconnects the port, so that it is no longer active. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close) + */ + close(): void; + /** + * Begins dispatching messages received on the port. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start) + */ + start(): void; + get onmessage(): any | null; + set onmessage(value: any | null); +} +interface MessagePortPostMessageOptions { + transfer?: any[]; +} +type LoopbackForExport Rpc.EntrypointBranded) | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? LoopbackServiceStub> : T extends new (...args: any[]) => Rpc.DurableObjectBranded ? LoopbackDurableObjectClass> : T extends ExportedHandler ? LoopbackServiceStub : undefined; +type LoopbackServiceStub = Fetcher & (T extends CloudflareWorkersModule.WorkerEntrypoint ? (opts: { + props?: Props; +}) => Fetcher : (opts: { + props?: any; +}) => Fetcher); +type LoopbackDurableObjectClass = DurableObjectClass & (T extends CloudflareWorkersModule.DurableObject ? (opts: { + props?: Props; +}) => DurableObjectClass : (opts: { + props?: any; +}) => DurableObjectClass); +interface SyncKvStorage { + get(key: string): T | undefined; + list(options?: SyncKvListOptions): Iterable<[ + string, + T + ]>; + put(key: string, value: T): void; + delete(key: string): boolean; +} +interface SyncKvListOptions { + start?: string; + startAfter?: string; + end?: string; + prefix?: string; + reverse?: boolean; + limit?: number; +} +interface WorkerStub { + getEntrypoint(name?: string, options?: WorkerStubEntrypointOptions): Fetcher; +} +interface WorkerStubEntrypointOptions { + props?: any; +} +interface WorkerLoader { + get(name: string, getCode: () => WorkerLoaderWorkerCode | Promise): WorkerStub; +} +interface WorkerLoaderModule { + js?: string; + cjs?: string; + text?: string; + data?: ArrayBuffer; + json?: any; + py?: string; +} +interface WorkerLoaderWorkerCode { + compatibilityDate: string; + compatibilityFlags?: string[]; + allowExperimental?: boolean; + mainModule: string; + modules: Record; + env?: any; + globalOutbound?: (Fetcher | null); + tails?: Fetcher[]; + streamingTails?: Fetcher[]; +} +/** +* The Workers runtime supports a subset of the Performance API, used to measure timing and performance, +* as well as timing of subrequests and other operations. +* +* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) +*/ +declare abstract class Performance { + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */ + get timeOrigin(): number; + /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */ + now(): number; +} +type AiImageClassificationInput = { + image: number[]; +}; +type AiImageClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiImageClassification { + inputs: AiImageClassificationInput; + postProcessedOutputs: AiImageClassificationOutput; +} +type AiImageToTextInput = { + image: number[]; + prompt?: string; + max_tokens?: number; + temperature?: number; + top_p?: number; + top_k?: number; + seed?: number; + repetition_penalty?: number; + frequency_penalty?: number; + presence_penalty?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +type AiImageToTextOutput = { + description: string; +}; +declare abstract class BaseAiImageToText { + inputs: AiImageToTextInput; + postProcessedOutputs: AiImageToTextOutput; +} +type AiImageTextToTextInput = { + image: string; + prompt?: string; + max_tokens?: number; + temperature?: number; + ignore_eos?: boolean; + top_p?: number; + top_k?: number; + seed?: number; + repetition_penalty?: number; + frequency_penalty?: number; + presence_penalty?: number; + raw?: boolean; + messages?: RoleScopedChatInput[]; +}; +type AiImageTextToTextOutput = { + description: string; +}; +declare abstract class BaseAiImageTextToText { + inputs: AiImageTextToTextInput; + postProcessedOutputs: AiImageTextToTextOutput; +} +type AiMultimodalEmbeddingsInput = { + image: string; + text: string[]; +}; +type AiIMultimodalEmbeddingsOutput = { + data: number[][]; + shape: number[]; +}; +declare abstract class BaseAiMultimodalEmbeddings { + inputs: AiImageTextToTextInput; + postProcessedOutputs: AiImageTextToTextOutput; +} +type AiObjectDetectionInput = { + image: number[]; +}; +type AiObjectDetectionOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiObjectDetection { + inputs: AiObjectDetectionInput; + postProcessedOutputs: AiObjectDetectionOutput; +} +type AiSentenceSimilarityInput = { + source: string; + sentences: string[]; +}; +type AiSentenceSimilarityOutput = number[]; +declare abstract class BaseAiSentenceSimilarity { + inputs: AiSentenceSimilarityInput; + postProcessedOutputs: AiSentenceSimilarityOutput; +} +type AiAutomaticSpeechRecognitionInput = { + audio: number[]; +}; +type AiAutomaticSpeechRecognitionOutput = { + text?: string; + words?: { + word: string; + start: number; + end: number; + }[]; + vtt?: string; +}; +declare abstract class BaseAiAutomaticSpeechRecognition { + inputs: AiAutomaticSpeechRecognitionInput; + postProcessedOutputs: AiAutomaticSpeechRecognitionOutput; +} +type AiSummarizationInput = { + input_text: string; + max_length?: number; +}; +type AiSummarizationOutput = { + summary: string; +}; +declare abstract class BaseAiSummarization { + inputs: AiSummarizationInput; + postProcessedOutputs: AiSummarizationOutput; +} +type AiTextClassificationInput = { + text: string; +}; +type AiTextClassificationOutput = { + score?: number; + label?: string; +}[]; +declare abstract class BaseAiTextClassification { + inputs: AiTextClassificationInput; + postProcessedOutputs: AiTextClassificationOutput; +} +type AiTextEmbeddingsInput = { + text: string | string[]; +}; +type AiTextEmbeddingsOutput = { + shape: number[]; + data: number[][]; +}; +declare abstract class BaseAiTextEmbeddings { + inputs: AiTextEmbeddingsInput; + postProcessedOutputs: AiTextEmbeddingsOutput; +} +type RoleScopedChatInput = { + role: "user" | "assistant" | "system" | "tool" | (string & NonNullable); + content: string; + name?: string; +}; +type AiTextGenerationToolLegacyInput = { + name: string; + description: string; + parameters?: { + type: "object" | (string & NonNullable); + properties: { + [key: string]: { + type: string; + description?: string; + }; + }; + required: string[]; + }; +}; +type AiTextGenerationToolInput = { + type: "function" | (string & NonNullable); + function: { + name: string; + description: string; + parameters?: { + type: "object" | (string & NonNullable); + properties: { + [key: string]: { + type: string; + description?: string; + }; + }; + required: string[]; + }; + }; +}; +type AiTextGenerationFunctionsInput = { + name: string; + code: string; +}; +type AiTextGenerationResponseFormat = { + type: string; + json_schema?: any; +}; +type AiTextGenerationInput = { + prompt?: string; + raw?: boolean; + stream?: boolean; + max_tokens?: number; + temperature?: number; + top_p?: number; + top_k?: number; + seed?: number; + repetition_penalty?: number; + frequency_penalty?: number; + presence_penalty?: number; + messages?: RoleScopedChatInput[]; + response_format?: AiTextGenerationResponseFormat; + tools?: AiTextGenerationToolInput[] | AiTextGenerationToolLegacyInput[] | (object & NonNullable); + functions?: AiTextGenerationFunctionsInput[]; +}; +type AiTextGenerationToolLegacyOutput = { + name: string; + arguments: unknown; +}; +type AiTextGenerationToolOutput = { + id: string; + type: "function"; + function: { + name: string; + arguments: string; + }; +}; +type UsageTags = { + prompt_tokens: number; + completion_tokens: number; + total_tokens: number; +}; +type AiTextGenerationOutput = { + response?: string; + tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[]; + usage?: UsageTags; +}; +declare abstract class BaseAiTextGeneration { + inputs: AiTextGenerationInput; + postProcessedOutputs: AiTextGenerationOutput; +} +type AiTextToSpeechInput = { + prompt: string; + lang?: string; +}; +type AiTextToSpeechOutput = Uint8Array | { + audio: string; +}; +declare abstract class BaseAiTextToSpeech { + inputs: AiTextToSpeechInput; + postProcessedOutputs: AiTextToSpeechOutput; +} +type AiTextToImageInput = { + prompt: string; + negative_prompt?: string; + height?: number; + width?: number; + image?: number[]; + image_b64?: string; + mask?: number[]; + num_steps?: number; + strength?: number; + guidance?: number; + seed?: number; +}; +type AiTextToImageOutput = ReadableStream; +declare abstract class BaseAiTextToImage { + inputs: AiTextToImageInput; + postProcessedOutputs: AiTextToImageOutput; +} +type AiTranslationInput = { + text: string; + target_lang: string; + source_lang?: string; +}; +type AiTranslationOutput = { + translated_text?: string; +}; +declare abstract class BaseAiTranslation { + inputs: AiTranslationInput; + postProcessedOutputs: AiTranslationOutput; +} +type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; +} | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; + }[]; +}; +type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} | AsyncResponse; +interface AsyncResponse { + /** + * The async request id that can be used to obtain the results. + */ + request_id?: string; +} +declare abstract class Base_Ai_Cf_Baai_Bge_Base_En_V1_5 { + inputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Output; +} +type Ai_Cf_Openai_Whisper_Input = string | { + /** + * An array of integers that represent the audio data constrained to 8-bit unsigned integer values + */ + audio: number[]; +}; +interface Ai_Cf_Openai_Whisper_Output { + /** + * The transcription + */ + text: string; + word_count?: number; + words?: { + word?: string; + /** + * The second this word begins in the recording + */ + start?: number; + /** + * The ending second when the word completes + */ + end?: number; + }[]; + vtt?: string; +} +declare abstract class Base_Ai_Cf_Openai_Whisper { + inputs: Ai_Cf_Openai_Whisper_Input; + postProcessedOutputs: Ai_Cf_Openai_Whisper_Output; +} +type Ai_Cf_Meta_M2M100_1_2B_Input = { + /** + * The text to be translated + */ + text: string; + /** + * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified + */ + source_lang?: string; + /** + * The language code to translate the text into (e.g., 'es' for Spanish) + */ + target_lang: string; +} | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + /** + * The text to be translated + */ + text: string; + /** + * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified + */ + source_lang?: string; + /** + * The language code to translate the text into (e.g., 'es' for Spanish) + */ + target_lang: string; + }[]; +}; +type Ai_Cf_Meta_M2M100_1_2B_Output = { + /** + * The translated text in the target language + */ + translated_text?: string; +} | AsyncResponse; +declare abstract class Base_Ai_Cf_Meta_M2M100_1_2B { + inputs: Ai_Cf_Meta_M2M100_1_2B_Input; + postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output; +} +type Ai_Cf_Baai_Bge_Small_En_V1_5_Input = { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; +} | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; + }[]; +}; +type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} | AsyncResponse; +declare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 { + inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output; +} +type Ai_Cf_Baai_Bge_Large_En_V1_5_Input = { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; +} | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: { + text: string | string[]; + /** + * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. + */ + pooling?: "mean" | "cls"; + }[]; +}; +type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} | AsyncResponse; +declare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 { + inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output; +} +type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = string | { + /** + * The input text prompt for the model to generate a response. + */ + prompt?: string; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; + image: number[] | (string & NonNullable); + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; +}; +interface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output { + description?: string; +} +declare abstract class Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M { + inputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input; + postProcessedOutputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output; +} +type Ai_Cf_Openai_Whisper_Tiny_En_Input = string | { + /** + * An array of integers that represent the audio data constrained to 8-bit unsigned integer values + */ + audio: number[]; +}; +interface Ai_Cf_Openai_Whisper_Tiny_En_Output { + /** + * The transcription + */ + text: string; + word_count?: number; + words?: { + word?: string; + /** + * The second this word begins in the recording + */ + start?: number; + /** + * The ending second when the word completes + */ + end?: number; + }[]; + vtt?: string; +} +declare abstract class Base_Ai_Cf_Openai_Whisper_Tiny_En { + inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input; + postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output; +} +interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input { + /** + * Base64 encoded value of the audio data. + */ + audio: string; + /** + * Supported tasks are 'translate' or 'transcribe'. + */ + task?: string; + /** + * The language of the audio being transcribed or translated. + */ + language?: string; + /** + * Preprocess the audio with a voice activity detection model. + */ + vad_filter?: boolean; + /** + * A text prompt to help provide context to the model on the contents of the audio. + */ + initial_prompt?: string; + /** + * The prefix it appended the the beginning of the output of the transcription and can guide the transcription result. + */ + prefix?: string; +} +interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output { + transcription_info?: { + /** + * The language of the audio being transcribed or translated. + */ + language?: string; + /** + * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1. + */ + language_probability?: number; + /** + * The total duration of the original audio file, in seconds. + */ + duration?: number; + /** + * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds. + */ + duration_after_vad?: number; + }; + /** + * The complete transcription of the audio. + */ + text: string; + /** + * The total number of words in the transcription. + */ + word_count?: number; + segments?: { + /** + * The starting time of the segment within the audio, in seconds. + */ + start?: number; + /** + * The ending time of the segment within the audio, in seconds. + */ + end?: number; + /** + * The transcription of the segment. + */ + text?: string; + /** + * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs. + */ + temperature?: number; + /** + * The average log probability of the predictions for the words in this segment, indicating overall confidence. + */ + avg_logprob?: number; + /** + * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process. + */ + compression_ratio?: number; + /** + * The probability that the segment contains no speech, represented as a decimal between 0 and 1. + */ + no_speech_prob?: number; + words?: { + /** + * The individual word transcribed from the audio. + */ + word?: string; + /** + * The starting time of the word within the audio, in seconds. + */ + start?: number; + /** + * The ending time of the word within the audio, in seconds. + */ + end?: number; + }[]; + }[]; + /** + * The transcription in WebVTT format, which includes timing and text information for use in subtitles. + */ + vtt?: string; +} +declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo { + inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input; + postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output; +} +type Ai_Cf_Baai_Bge_M3_Input = BGEM3InputQueryAndContexts | BGEM3InputEmbedding | { + /** + * Batch of the embeddings requests to run using async-queue + */ + requests: (BGEM3InputQueryAndContexts1 | BGEM3InputEmbedding1)[]; +}; +interface BGEM3InputQueryAndContexts { + /** + * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts + */ + query?: string; + /** + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. + */ + contexts: { + /** + * One of the provided context content + */ + text?: string; + }[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +interface BGEM3InputEmbedding { + text: string | string[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +interface BGEM3InputQueryAndContexts1 { + /** + * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts + */ + query?: string; + /** + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. + */ + contexts: { + /** + * One of the provided context content + */ + text?: string; + }[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +interface BGEM3InputEmbedding1 { + text: string | string[]; + /** + * When provided with too long context should the model error out or truncate the context to fit? + */ + truncate_inputs?: boolean; +} +type Ai_Cf_Baai_Bge_M3_Output = BGEM3OuputQuery | BGEM3OutputEmbeddingForContexts | BGEM3OuputEmbedding | AsyncResponse; +interface BGEM3OuputQuery { + response?: { + /** + * Index of the context in the request + */ + id?: number; + /** + * Score of the context under the index. + */ + score?: number; + }[]; +} +interface BGEM3OutputEmbeddingForContexts { + response?: number[][]; + shape?: number[]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} +interface BGEM3OuputEmbedding { + shape?: number[]; + /** + * Embeddings of the requested text values + */ + data?: number[][]; + /** + * The pooling method used in the embedding process. + */ + pooling?: "mean" | "cls"; +} +declare abstract class Base_Ai_Cf_Baai_Bge_M3 { + inputs: Ai_Cf_Baai_Bge_M3_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output; +} +interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input { + /** + * A text description of the image you want to generate. + */ + prompt: string; + /** + * The number of diffusion steps; higher values can improve quality but take longer. + */ + steps?: number; +} +interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output { + /** + * The generated image in Base64 format. + */ + image?: string; +} +declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell { + inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input; + postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output; +} +type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Prompt | Messages; +interface Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + image?: number[] | (string & NonNullable); + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; +} +interface Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + image?: number[] | (string & NonNullable); + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + /** + * If true, the response will be streamed back incrementally. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = { + /** + * The generated text response from the model + */ + response?: string; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct { + inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output; +} +type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt | Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages | AsyncBatch; +interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: JSONMode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface JSONMode { + type?: "json_object" | "json_schema"; + json_schema?: unknown; +} +interface Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: JSONMode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface AsyncBatch { + requests?: { + /** + * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique. + */ + external_reference?: string; + /** + * Prompt for the text generation model + */ + prompt?: string; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; + response_format?: JSONMode; + }[]; +} +type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +} | string | AsyncResponse; +declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast { + inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output; +} +interface Ai_Cf_Meta_Llama_Guard_3_8B_Input { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender must alternate between 'user' and 'assistant'. + */ + role: "user" | "assistant"; + /** + * The content of the message as a string. + */ + content: string; + }[]; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Dictate the output format of the generated response. + */ + response_format?: { + /** + * Set to json_object to process and output generated text as JSON. + */ + type?: string; + }; +} +interface Ai_Cf_Meta_Llama_Guard_3_8B_Output { + response?: string | { + /** + * Whether the conversation is safe or not. + */ + safe?: boolean; + /** + * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe. + */ + categories?: string[]; + }; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; +} +declare abstract class Base_Ai_Cf_Meta_Llama_Guard_3_8B { + inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output; +} +interface Ai_Cf_Baai_Bge_Reranker_Base_Input { + /** + * A query you wish to perform against the provided contexts. + */ + /** + * Number of returned results starting with the best score. + */ + top_k?: number; + /** + * List of provided contexts. Note that the index in this array is important, as the response will refer to it. + */ + contexts: { + /** + * One of the provided context content + */ + text?: string; + }[]; +} +interface Ai_Cf_Baai_Bge_Reranker_Base_Output { + response?: { + /** + * Index of the context in the request + */ + id?: number; + /** + * Score of the context under the index. + */ + score?: number; + }[]; +} +declare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base { + inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input; + postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output; +} +type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = Qwen2_5_Coder_32B_Instruct_Prompt | Qwen2_5_Coder_32B_Instruct_Messages; +interface Qwen2_5_Coder_32B_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. + */ + lora?: string; + response_format?: JSONMode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Qwen2_5_Coder_32B_Instruct_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role: string; + /** + * The content of the message as a string. + */ + content: string; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: JSONMode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct { + inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output; +} +type Ai_Cf_Qwen_Qwq_32B_Input = Qwen_Qwq_32B_Prompt | Qwen_Qwq_32B_Messages; +interface Qwen_Qwq_32B_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Qwen_Qwq_32B_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + /** + * JSON schema that should be fufilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Qwen_Qwq_32B_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Qwen_Qwq_32B { + inputs: Ai_Cf_Qwen_Qwq_32B_Input; + postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output; +} +type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = Mistral_Small_3_1_24B_Instruct_Prompt | Mistral_Small_3_1_24B_Instruct_Messages; +interface Mistral_Small_3_1_24B_Instruct_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Mistral_Small_3_1_24B_Instruct_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + /** + * JSON schema that should be fufilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct { + inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input; + postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output; +} +type Ai_Cf_Google_Gemma_3_12B_It_Input = Google_Gemma_3_12B_It_Prompt | Google_Gemma_3_12B_It_Messages; +interface Google_Gemma_3_12B_It_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fufilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Google_Gemma_3_12B_It_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + /** + * JSON schema that should be fufilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Google_Gemma_3_12B_It_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + /** + * The name of the tool to be called + */ + name?: string; + }[]; +}; +declare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It { + inputs: Ai_Cf_Google_Gemma_3_12B_It_Input; + postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output; +} +type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = Ai_Cf_Meta_Llama_4_Prompt | Ai_Cf_Meta_Llama_4_Messages | Ai_Cf_Meta_Llama_4_Async_Batch; +interface Ai_Cf_Meta_Llama_4_Prompt { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + response_format?: JSONMode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_4_Messages { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: JSONMode; + /** + * JSON schema that should be fufilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_4_Async_Batch { + requests: (Ai_Cf_Meta_Llama_4_Prompt_Inner | Ai_Cf_Meta_Llama_4_Messages_Inner)[]; +} +interface Ai_Cf_Meta_Llama_4_Prompt_Inner { + /** + * The input text prompt for the model to generate a response. + */ + prompt: string; + /** + * JSON schema that should be fulfilled for the response. + */ + guided_json?: object; + response_format?: JSONMode; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +interface Ai_Cf_Meta_Llama_4_Messages_Inner { + /** + * An array of message objects representing the conversation history. + */ + messages: { + /** + * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). + */ + role?: string; + /** + * The tool call id. If you don't know what to put here you can fall back to 000000001 + */ + tool_call_id?: string; + content?: string | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }[] | { + /** + * Type of the content provided + */ + type?: string; + text?: string; + image_url?: { + /** + * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted + */ + url?: string; + }; + }; + }[]; + functions?: { + name: string; + code: string; + }[]; + /** + * A list of tools available for the assistant to use. + */ + tools?: ({ + /** + * The name of the tool. More descriptive the better. + */ + name: string; + /** + * A brief description of what the tool does. + */ + description: string; + /** + * Schema defining the parameters accepted by the tool. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + } | { + /** + * Specifies the type of tool (e.g., 'function'). + */ + type: string; + /** + * Details of the function tool. + */ + function: { + /** + * The name of the function. + */ + name: string; + /** + * A brief description of what the function does. + */ + description: string; + /** + * Schema defining the parameters accepted by the function. + */ + parameters: { + /** + * The type of the parameters object (usually 'object'). + */ + type: string; + /** + * List of required parameter names. + */ + required?: string[]; + /** + * Definitions of each parameter. + */ + properties: { + [k: string]: { + /** + * The data type of the parameter. + */ + type: string; + /** + * A description of the expected parameter. + */ + description: string; + }; + }; + }; + }; + })[]; + response_format?: JSONMode; + /** + * JSON schema that should be fufilled for the response. + */ + guided_json?: object; + /** + * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. + */ + raw?: boolean; + /** + * If true, the response will be streamed back incrementally using SSE, Server Sent Events. + */ + stream?: boolean; + /** + * The maximum number of tokens to generate in the response. + */ + max_tokens?: number; + /** + * Controls the randomness of the output; higher values produce more random results. + */ + temperature?: number; + /** + * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. + */ + top_p?: number; + /** + * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. + */ + top_k?: number; + /** + * Random seed for reproducibility of the generation. + */ + seed?: number; + /** + * Penalty for repeated tokens; higher values discourage repetition. + */ + repetition_penalty?: number; + /** + * Decreases the likelihood of the model repeating the same lines verbatim. + */ + frequency_penalty?: number; + /** + * Increases the likelihood of the model introducing new topics. + */ + presence_penalty?: number; +} +type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = { + /** + * The generated text response from the model + */ + response: string; + /** + * Usage statistics for the inference request + */ + usage?: { + /** + * Total number of tokens in input + */ + prompt_tokens?: number; + /** + * Total number of tokens in output + */ + completion_tokens?: number; + /** + * Total number of input and output tokens + */ + total_tokens?: number; + }; + /** + * An array of tool calls requests made during the response generation + */ + tool_calls?: { + /** + * The tool call id. + */ + id?: string; + /** + * Specifies the type of tool (e.g., 'function'). + */ + type?: string; + /** + * Details of the function tool. + */ + function?: { + /** + * The name of the tool to be called + */ + name?: string; + /** + * The arguments passed to be passed to the tool call request + */ + arguments?: object; + }; + }[]; +}; +declare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct { + inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input; + postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output; +} +interface Ai_Cf_Deepgram_Nova_3_Input { + audio: { + body: object; + contentType: string; + }; + /** + * Sets how the model will interpret strings submitted to the custom_topic param. When strict, the model will only return topics submitted using the custom_topic param. When extended, the model will return its own detected topics in addition to those submitted using the custom_topic param. + */ + custom_topic_mode?: "extended" | "strict"; + /** + * Custom topics you want the model to detect within your input audio or text if present Submit up to 100 + */ + custom_topic?: string; + /** + * Sets how the model will interpret intents submitted to the custom_intent param. When strict, the model will only return intents submitted using the custom_intent param. When extended, the model will return its own detected intents in addition those submitted using the custom_intents param + */ + custom_intent_mode?: "extended" | "strict"; + /** + * Custom intents you want the model to detect within your input audio if present + */ + custom_intent?: string; + /** + * Identifies and extracts key entities from content in submitted audio + */ + detect_entities?: boolean; + /** + * Identifies the dominant language spoken in submitted audio + */ + detect_language?: boolean; + /** + * Recognize speaker changes. Each word in the transcript will be assigned a speaker number starting at 0 + */ + diarize?: boolean; + /** + * Identify and extract key entities from content in submitted audio + */ + dictation?: boolean; + /** + * Specify the expected encoding of your submitted audio + */ + encoding?: "linear16" | "flac" | "mulaw" | "amr-nb" | "amr-wb" | "opus" | "speex" | "g729"; + /** + * Arbitrary key-value pairs that are attached to the API response for usage in downstream processing + */ + extra?: string; + /** + * Filler Words can help transcribe interruptions in your audio, like 'uh' and 'um' + */ + filler_words?: boolean; + /** + * Key term prompting can boost or suppress specialized terminology and brands. + */ + keyterm?: string; + /** + * Keywords can boost or suppress specialized terminology and brands. + */ + keywords?: string; + /** + * The BCP-47 language tag that hints at the primary spoken language. Depending on the Model and API endpoint you choose only certain languages are available. + */ + language?: string; + /** + * Spoken measurements will be converted to their corresponding abbreviations. + */ + measurements?: boolean; + /** + * Opts out requests from the Deepgram Model Improvement Program. Refer to our Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip. + */ + mip_opt_out?: boolean; + /** + * Mode of operation for the model representing broad area of topic that will be talked about in the supplied audio + */ + mode?: "general" | "medical" | "finance"; + /** + * Transcribe each audio channel independently. + */ + multichannel?: boolean; + /** + * Numerals converts numbers from written format to numerical format. + */ + numerals?: boolean; + /** + * Splits audio into paragraphs to improve transcript readability. + */ + paragraphs?: boolean; + /** + * Profanity Filter looks for recognized profanity and converts it to the nearest recognized non-profane word or removes it from the transcript completely. + */ + profanity_filter?: boolean; + /** + * Add punctuation and capitalization to the transcript. + */ + punctuate?: boolean; + /** + * Redaction removes sensitive information from your transcripts. + */ + redact?: string; + /** + * Search for terms or phrases in submitted audio and replaces them. + */ + replace?: string; + /** + * Search for terms or phrases in submitted audio. + */ + search?: string; + /** + * Recognizes the sentiment throughout a transcript or text. + */ + sentiment?: boolean; + /** + * Apply formatting to transcript output. When set to true, additional formatting will be applied to transcripts to improve readability. + */ + smart_format?: boolean; + /** + * Detect topics throughout a transcript or text. + */ + topics?: boolean; + /** + * Segments speech into meaningful semantic units. + */ + utterances?: boolean; + /** + * Seconds to wait before detecting a pause between words in submitted audio. + */ + utt_split?: number; + /** + * The number of channels in the submitted audio + */ + channels?: number; + /** + * Specifies whether the streaming endpoint should provide ongoing transcription updates as more audio is received. When set to true, the endpoint sends continuous updates, meaning transcription results may evolve over time. Note: Supported only for webosockets. + */ + interim_results?: boolean; + /** + * Indicates how long model will wait to detect whether a speaker has finished speaking or pauses for a significant period of time. When set to a value, the streaming endpoint immediately finalizes the transcription for the processed time range and returns the transcript with a speech_final parameter set to true. Can also be set to false to disable endpointing + */ + endpointing?: string; + /** + * Indicates that speech has started. You'll begin receiving Speech Started messages upon speech starting. Note: Supported only for webosockets. + */ + vad_events?: boolean; + /** + * Indicates how long model will wait to send an UtteranceEnd message after a word has been transcribed. Use with interim_results. Note: Supported only for webosockets. + */ + utterance_end_ms?: boolean; +} +interface Ai_Cf_Deepgram_Nova_3_Output { + results?: { + channels?: { + alternatives?: { + confidence?: number; + transcript?: string; + words?: { + confidence?: number; + end?: number; + start?: number; + word?: string; + }[]; + }[]; + }[]; + summary?: { + result?: string; + short?: string; + }; + sentiments?: { + segments?: { + text?: string; + start_word?: number; + end_word?: number; + sentiment?: string; + sentiment_score?: number; + }[]; + average?: { + sentiment?: string; + sentiment_score?: number; + }; + }; + }; +} +declare abstract class Base_Ai_Cf_Deepgram_Nova_3 { + inputs: Ai_Cf_Deepgram_Nova_3_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output; +} +type Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = { + /** + * readable stream with audio data and content-type specified for that data + */ + audio: { + body: object; + contentType: string; + }; + /** + * type of data PCM data that's sent to the inference server as raw array + */ + dtype?: "uint8" | "float32" | "float64"; +} | { + /** + * base64 encoded audio data + */ + audio: string; + /** + * type of data PCM data that's sent to the inference server as raw array + */ + dtype?: "uint8" | "float32" | "float64"; +}; +interface Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output { + /** + * if true, end-of-turn was detected + */ + is_complete?: boolean; + /** + * probability of the end-of-turn detection + */ + probability?: number; +} +declare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 { + inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input; + postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output; +} +type Ai_Cf_Openai_Gpt_Oss_120B_Input = GPT_OSS_120B_Responses | GPT_OSS_120B_Responses_Async; +interface GPT_OSS_120B_Responses { + /** + * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types + */ + input: string | unknown[]; + reasoning?: { + /** + * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. + */ + effort?: "low" | "medium" | "high"; + /** + * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. + */ + summary?: "auto" | "concise" | "detailed"; + }; +} +interface GPT_OSS_120B_Responses_Async { + requests: { + /** + * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types + */ + input: string | unknown[]; + reasoning?: { + /** + * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. + */ + effort?: "low" | "medium" | "high"; + /** + * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. + */ + summary?: "auto" | "concise" | "detailed"; + }; + }[]; +} +type Ai_Cf_Openai_Gpt_Oss_120B_Output = {} | (string & NonNullable); +declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B { + inputs: Ai_Cf_Openai_Gpt_Oss_120B_Input; + postProcessedOutputs: Ai_Cf_Openai_Gpt_Oss_120B_Output; +} +type Ai_Cf_Openai_Gpt_Oss_20B_Input = GPT_OSS_20B_Responses | GPT_OSS_20B_Responses_Async; +interface GPT_OSS_20B_Responses { + /** + * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types + */ + input: string | unknown[]; + reasoning?: { + /** + * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. + */ + effort?: "low" | "medium" | "high"; + /** + * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. + */ + summary?: "auto" | "concise" | "detailed"; + }; +} +interface GPT_OSS_20B_Responses_Async { + requests: { + /** + * Responses API Input messages. Refer to OpenAI Responses API docs to learn more about supported content types + */ + input: string | unknown[]; + reasoning?: { + /** + * Constrains effort on reasoning for reasoning models. Currently supported values are low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. + */ + effort?: "low" | "medium" | "high"; + /** + * A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of auto, concise, or detailed. + */ + summary?: "auto" | "concise" | "detailed"; + }; + }[]; +} +type Ai_Cf_Openai_Gpt_Oss_20B_Output = {} | (string & NonNullable); +declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B { + inputs: Ai_Cf_Openai_Gpt_Oss_20B_Input; + postProcessedOutputs: Ai_Cf_Openai_Gpt_Oss_20B_Output; +} +interface Ai_Cf_Leonardo_Phoenix_1_0_Input { + /** + * A text description of the image you want to generate. + */ + prompt: string; + /** + * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt + */ + guidance?: number; + /** + * Random seed for reproducibility of the image generation + */ + seed?: number; + /** + * The height of the generated image in pixels + */ + height?: number; + /** + * The width of the generated image in pixels + */ + width?: number; + /** + * The number of diffusion steps; higher values can improve quality but take longer + */ + num_steps?: number; + /** + * Specify what to exclude from the generated images + */ + negative_prompt?: string; +} +/** + * The generated image in JPEG format + */ +type Ai_Cf_Leonardo_Phoenix_1_0_Output = string; +declare abstract class Base_Ai_Cf_Leonardo_Phoenix_1_0 { + inputs: Ai_Cf_Leonardo_Phoenix_1_0_Input; + postProcessedOutputs: Ai_Cf_Leonardo_Phoenix_1_0_Output; +} +interface Ai_Cf_Leonardo_Lucid_Origin_Input { + /** + * A text description of the image you want to generate. + */ + prompt: string; + /** + * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt + */ + guidance?: number; + /** + * Random seed for reproducibility of the image generation + */ + seed?: number; + /** + * The height of the generated image in pixels + */ + height?: number; + /** + * The width of the generated image in pixels + */ + width?: number; + /** + * The number of diffusion steps; higher values can improve quality but take longer + */ + num_steps?: number; + /** + * The number of diffusion steps; higher values can improve quality but take longer + */ + steps?: number; +} +interface Ai_Cf_Leonardo_Lucid_Origin_Output { + /** + * The generated image in Base64 format. + */ + image?: string; +} +declare abstract class Base_Ai_Cf_Leonardo_Lucid_Origin { + inputs: Ai_Cf_Leonardo_Lucid_Origin_Input; + postProcessedOutputs: Ai_Cf_Leonardo_Lucid_Origin_Output; +} +interface Ai_Cf_Deepgram_Aura_1_Input { + /** + * Speaker used to produce the audio. + */ + speaker?: "angus" | "asteria" | "arcas" | "orion" | "orpheus" | "athena" | "luna" | "zeus" | "perseus" | "helios" | "hera" | "stella"; + /** + * Encoding of the output audio. + */ + encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; + /** + * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. + */ + container?: "none" | "wav" | "ogg"; + /** + * The text content to be converted to speech + */ + text: string; + /** + * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable + */ + sample_rate?: number; + /** + * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. + */ + bit_rate?: number; +} +/** + * The generated audio in MP3 format + */ +type Ai_Cf_Deepgram_Aura_1_Output = string; +declare abstract class Base_Ai_Cf_Deepgram_Aura_1 { + inputs: Ai_Cf_Deepgram_Aura_1_Input; + postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output; +} +interface AiModels { + "@cf/huggingface/distilbert-sst-2-int8": BaseAiTextClassification; + "@cf/stabilityai/stable-diffusion-xl-base-1.0": BaseAiTextToImage; + "@cf/runwayml/stable-diffusion-v1-5-inpainting": BaseAiTextToImage; + "@cf/runwayml/stable-diffusion-v1-5-img2img": BaseAiTextToImage; + "@cf/lykon/dreamshaper-8-lcm": BaseAiTextToImage; + "@cf/bytedance/stable-diffusion-xl-lightning": BaseAiTextToImage; + "@cf/myshell-ai/melotts": BaseAiTextToSpeech; + "@cf/google/embeddinggemma-300m": BaseAiTextEmbeddings; + "@cf/microsoft/resnet-50": BaseAiImageClassification; + "@cf/meta/llama-2-7b-chat-int8": BaseAiTextGeneration; + "@cf/mistral/mistral-7b-instruct-v0.1": BaseAiTextGeneration; + "@cf/meta/llama-2-7b-chat-fp16": BaseAiTextGeneration; + "@hf/thebloke/llama-2-13b-chat-awq": BaseAiTextGeneration; + "@hf/thebloke/mistral-7b-instruct-v0.1-awq": BaseAiTextGeneration; + "@hf/thebloke/zephyr-7b-beta-awq": BaseAiTextGeneration; + "@hf/thebloke/openhermes-2.5-mistral-7b-awq": BaseAiTextGeneration; + "@hf/thebloke/neural-chat-7b-v3-1-awq": BaseAiTextGeneration; + "@hf/thebloke/llamaguard-7b-awq": BaseAiTextGeneration; + "@hf/thebloke/deepseek-coder-6.7b-base-awq": BaseAiTextGeneration; + "@hf/thebloke/deepseek-coder-6.7b-instruct-awq": BaseAiTextGeneration; + "@cf/deepseek-ai/deepseek-math-7b-instruct": BaseAiTextGeneration; + "@cf/defog/sqlcoder-7b-2": BaseAiTextGeneration; + "@cf/openchat/openchat-3.5-0106": BaseAiTextGeneration; + "@cf/tiiuae/falcon-7b-instruct": BaseAiTextGeneration; + "@cf/thebloke/discolm-german-7b-v1-awq": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-0.5b-chat": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-7b-chat-awq": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-14b-chat-awq": BaseAiTextGeneration; + "@cf/tinyllama/tinyllama-1.1b-chat-v1.0": BaseAiTextGeneration; + "@cf/microsoft/phi-2": BaseAiTextGeneration; + "@cf/qwen/qwen1.5-1.8b-chat": BaseAiTextGeneration; + "@cf/mistral/mistral-7b-instruct-v0.2-lora": BaseAiTextGeneration; + "@hf/nousresearch/hermes-2-pro-mistral-7b": BaseAiTextGeneration; + "@hf/nexusflow/starling-lm-7b-beta": BaseAiTextGeneration; + "@hf/google/gemma-7b-it": BaseAiTextGeneration; + "@cf/meta-llama/llama-2-7b-chat-hf-lora": BaseAiTextGeneration; + "@cf/google/gemma-2b-it-lora": BaseAiTextGeneration; + "@cf/google/gemma-7b-it-lora": BaseAiTextGeneration; + "@hf/mistral/mistral-7b-instruct-v0.2": BaseAiTextGeneration; + "@cf/meta/llama-3-8b-instruct": BaseAiTextGeneration; + "@cf/fblgit/una-cybertron-7b-v2-bf16": BaseAiTextGeneration; + "@cf/meta/llama-3-8b-instruct-awq": BaseAiTextGeneration; + "@hf/meta-llama/meta-llama-3-8b-instruct": BaseAiTextGeneration; + "@cf/meta/llama-3.1-8b-instruct-fp8": BaseAiTextGeneration; + "@cf/meta/llama-3.1-8b-instruct-awq": BaseAiTextGeneration; + "@cf/meta/llama-3.2-3b-instruct": BaseAiTextGeneration; + "@cf/meta/llama-3.2-1b-instruct": BaseAiTextGeneration; + "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b": BaseAiTextGeneration; + "@cf/facebook/bart-large-cnn": BaseAiSummarization; + "@cf/llava-hf/llava-1.5-7b-hf": BaseAiImageToText; + "@cf/baai/bge-base-en-v1.5": Base_Ai_Cf_Baai_Bge_Base_En_V1_5; + "@cf/openai/whisper": Base_Ai_Cf_Openai_Whisper; + "@cf/meta/m2m100-1.2b": Base_Ai_Cf_Meta_M2M100_1_2B; + "@cf/baai/bge-small-en-v1.5": Base_Ai_Cf_Baai_Bge_Small_En_V1_5; + "@cf/baai/bge-large-en-v1.5": Base_Ai_Cf_Baai_Bge_Large_En_V1_5; + "@cf/unum/uform-gen2-qwen-500m": Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M; + "@cf/openai/whisper-tiny-en": Base_Ai_Cf_Openai_Whisper_Tiny_En; + "@cf/openai/whisper-large-v3-turbo": Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo; + "@cf/baai/bge-m3": Base_Ai_Cf_Baai_Bge_M3; + "@cf/black-forest-labs/flux-1-schnell": Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell; + "@cf/meta/llama-3.2-11b-vision-instruct": Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct; + "@cf/meta/llama-3.3-70b-instruct-fp8-fast": Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast; + "@cf/meta/llama-guard-3-8b": Base_Ai_Cf_Meta_Llama_Guard_3_8B; + "@cf/baai/bge-reranker-base": Base_Ai_Cf_Baai_Bge_Reranker_Base; + "@cf/qwen/qwen2.5-coder-32b-instruct": Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct; + "@cf/qwen/qwq-32b": Base_Ai_Cf_Qwen_Qwq_32B; + "@cf/mistralai/mistral-small-3.1-24b-instruct": Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct; + "@cf/google/gemma-3-12b-it": Base_Ai_Cf_Google_Gemma_3_12B_It; + "@cf/meta/llama-4-scout-17b-16e-instruct": Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct; + "@cf/deepgram/nova-3": Base_Ai_Cf_Deepgram_Nova_3; + "@cf/pipecat-ai/smart-turn-v2": Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2; + "@cf/openai/gpt-oss-120b": Base_Ai_Cf_Openai_Gpt_Oss_120B; + "@cf/openai/gpt-oss-20b": Base_Ai_Cf_Openai_Gpt_Oss_20B; + "@cf/leonardo/phoenix-1.0": Base_Ai_Cf_Leonardo_Phoenix_1_0; + "@cf/leonardo/lucid-origin": Base_Ai_Cf_Leonardo_Lucid_Origin; + "@cf/deepgram/aura-1": Base_Ai_Cf_Deepgram_Aura_1; +} +type AiOptions = { + /** + * Send requests as an asynchronous batch job, only works for supported models + * https://developers.cloudflare.com/workers-ai/features/batch-api + */ + queueRequest?: boolean; + /** + * Establish websocket connections, only works for supported models + */ + websocket?: boolean; + gateway?: GatewayOptions; + returnRawResponse?: boolean; + prefix?: string; + extraHeaders?: object; +}; +type AiModelsSearchParams = { + author?: string; + hide_experimental?: boolean; + page?: number; + per_page?: number; + search?: string; + source?: number; + task?: string; +}; +type AiModelsSearchObject = { + id: string; + source: number; + name: string; + description: string; + task: { + id: string; + name: string; + description: string; + }; + tags: string[]; + properties: { + property_id: string; + value: string; + }[]; +}; +interface InferenceUpstreamError extends Error { +} +interface AiInternalError extends Error { +} +type AiModelListType = Record; +declare abstract class Ai { + aiGatewayLogId: string | null; + gateway(gatewayId: string): AiGateway; + autorag(autoragId: string): AutoRAG; + run(model: Name, inputs: InputOptions, options?: Options): Promise; + models(params?: AiModelsSearchParams): Promise; + toMarkdown(): ToMarkdownService; + toMarkdown(files: { + name: string; + blob: Blob; + }[], options?: { + gateway?: GatewayOptions; + extraHeaders?: object; + }): Promise; + toMarkdown(files: { + name: string; + blob: Blob; + }, options?: { + gateway?: GatewayOptions; + extraHeaders?: object; + }): Promise; +} +type GatewayRetries = { + maxAttempts?: 1 | 2 | 3 | 4 | 5; + retryDelayMs?: number; + backoff?: 'constant' | 'linear' | 'exponential'; +}; +type GatewayOptions = { + id: string; + cacheKey?: string; + cacheTtl?: number; + skipCache?: boolean; + metadata?: Record; + collectLog?: boolean; + eventId?: string; + requestTimeoutMs?: number; + retries?: GatewayRetries; +}; +type UniversalGatewayOptions = Exclude & { + /** + ** @deprecated + */ + id?: string; +}; +type AiGatewayPatchLog = { + score?: number | null; + feedback?: -1 | 1 | null; + metadata?: Record | null; +}; +type AiGatewayLog = { + id: string; + provider: string; + model: string; + model_type?: string; + path: string; + duration: number; + request_type?: string; + request_content_type?: string; + status_code: number; + response_content_type?: string; + success: boolean; + cached: boolean; + tokens_in?: number; + tokens_out?: number; + metadata?: Record; + step?: number; + cost?: number; + custom_cost?: boolean; + request_size: number; + request_head?: string; + request_head_complete: boolean; + response_size: number; + response_head?: string; + response_head_complete: boolean; + created_at: Date; +}; +type AIGatewayProviders = 'workers-ai' | 'anthropic' | 'aws-bedrock' | 'azure-openai' | 'google-vertex-ai' | 'huggingface' | 'openai' | 'perplexity-ai' | 'replicate' | 'groq' | 'cohere' | 'google-ai-studio' | 'mistral' | 'grok' | 'openrouter' | 'deepseek' | 'cerebras' | 'cartesia' | 'elevenlabs' | 'adobe-firefly'; +type AIGatewayHeaders = { + 'cf-aig-metadata': Record | string; + 'cf-aig-custom-cost': { + per_token_in?: number; + per_token_out?: number; + } | { + total_cost?: number; + } | string; + 'cf-aig-cache-ttl': number | string; + 'cf-aig-skip-cache': boolean | string; + 'cf-aig-cache-key': string; + 'cf-aig-event-id': string; + 'cf-aig-request-timeout': number | string; + 'cf-aig-max-attempts': number | string; + 'cf-aig-retry-delay': number | string; + 'cf-aig-backoff': string; + 'cf-aig-collect-log': boolean | string; + Authorization: string; + 'Content-Type': string; + [key: string]: string | number | boolean | object; +}; +type AIGatewayUniversalRequest = { + provider: AIGatewayProviders | string; // eslint-disable-line + endpoint: string; + headers: Partial; + query: unknown; +}; +interface AiGatewayInternalError extends Error { +} +interface AiGatewayLogNotFound extends Error { +} +declare abstract class AiGateway { + patchLog(logId: string, data: AiGatewayPatchLog): Promise; + getLog(logId: string): Promise; + run(data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], options?: { + gateway?: UniversalGatewayOptions; + extraHeaders?: object; + }): Promise; + getUrl(provider?: AIGatewayProviders | string): Promise; // eslint-disable-line +} +interface AutoRAGInternalError extends Error { +} +interface AutoRAGNotFoundError extends Error { +} +interface AutoRAGUnauthorizedError extends Error { +} +interface AutoRAGNameNotSetError extends Error { +} +type ComparisonFilter = { + key: string; + type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte'; + value: string | number | boolean; +}; +type CompoundFilter = { + type: 'and' | 'or'; + filters: ComparisonFilter[]; +}; +type AutoRagSearchRequest = { + query: string; + filters?: CompoundFilter | ComparisonFilter; + max_num_results?: number; + ranking_options?: { + ranker?: string; + score_threshold?: number; + }; + rewrite_query?: boolean; +}; +type AutoRagAiSearchRequest = AutoRagSearchRequest & { + stream?: boolean; + system_prompt?: string; +}; +type AutoRagAiSearchRequestStreaming = Omit & { + stream: true; +}; +type AutoRagSearchResponse = { + object: 'vector_store.search_results.page'; + search_query: string; + data: { + file_id: string; + filename: string; + score: number; + attributes: Record; + content: { + type: 'text'; + text: string; + }[]; + }[]; + has_more: boolean; + next_page: string | null; +}; +type AutoRagListResponse = { + id: string; + enable: boolean; + type: string; + source: string; + vectorize_name: string; + paused: boolean; + status: string; +}[]; +type AutoRagAiSearchResponse = AutoRagSearchResponse & { + response: string; +}; +declare abstract class AutoRAG { + list(): Promise; + search(params: AutoRagSearchRequest): Promise; + aiSearch(params: AutoRagAiSearchRequestStreaming): Promise; + aiSearch(params: AutoRagAiSearchRequest): Promise; + aiSearch(params: AutoRagAiSearchRequest): Promise; +} +interface BasicImageTransformations { + /** + * Maximum width in image pixels. The value must be an integer. + */ + width?: number; + /** + * Maximum height in image pixels. The value must be an integer. + */ + height?: number; + /** + * Resizing mode as a string. It affects interpretation of width and height + * options: + * - scale-down: Similar to contain, but the image is never enlarged. If + * the image is larger than given width or height, it will be resized. + * Otherwise its original size will be kept. + * - contain: Resizes to maximum size that fits within the given width and + * height. If only a single dimension is given (e.g. only width), the + * image will be shrunk or enlarged to exactly match that dimension. + * Aspect ratio is always preserved. + * - cover: Resizes (shrinks or enlarges) to fill the entire area of width + * and height. If the image has an aspect ratio different from the ratio + * of width and height, it will be cropped to fit. + * - crop: The image will be shrunk and cropped to fit within the area + * specified by width and height. The image will not be enlarged. For images + * smaller than the given dimensions it's the same as scale-down. For + * images larger than the given dimensions, it's the same as cover. + * See also trim. + * - pad: Resizes to the maximum size that fits within the given width and + * height, and then fills the remaining area with a background color + * (white by default). Use of this mode is not recommended, as the same + * effect can be more efficiently achieved with the contain mode and the + * CSS object-fit: contain property. + * - squeeze: Stretches and deforms to the width and height given, even if it + * breaks aspect ratio + */ + fit?: "scale-down" | "contain" | "cover" | "crop" | "pad" | "squeeze"; + /** + * Image segmentation using artificial intelligence models. Sets pixels not + * within selected segment area to transparent e.g "foreground" sets every + * background pixel as transparent. + */ + segment?: "foreground"; + /** + * When cropping with fit: "cover", this defines the side or point that should + * be left uncropped. The value is either a string + * "left", "right", "top", "bottom", "auto", or "center" (the default), + * or an object {x, y} containing focal point coordinates in the original + * image expressed as fractions ranging from 0.0 (top or left) to 1.0 + * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will + * crop bottom or left and right sides as necessary, but won’t crop anything + * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to + * preserve as much as possible around a point at 20% of the height of the + * source image. + */ + gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | BasicImageTransformationsGravityCoordinates; + /** + * Background color to add underneath the image. Applies only to images with + * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), + * hsl(…), etc.) + */ + background?: string; + /** + * Number of degrees (90, 180, 270) to rotate the image by. width and height + * options refer to axes after rotation. + */ + rotate?: 0 | 90 | 180 | 270 | 360; +} +interface BasicImageTransformationsGravityCoordinates { + x?: number; + y?: number; + mode?: 'remainder' | 'box-center'; +} +/** + * In addition to the properties you can set in the RequestInit dict + * that you pass as an argument to the Request constructor, you can + * set certain properties of a `cf` object to control how Cloudflare + * features are applied to that new Request. + * + * Note: Currently, these properties cannot be tested in the + * playground. + */ +interface RequestInitCfProperties extends Record { + cacheEverything?: boolean; + /** + * A request's cache key is what determines if two requests are + * "the same" for caching purposes. If a request has the same cache key + * as some previous request, then we can serve the same cached response for + * both. (e.g. 'some-key') + * + * Only available for Enterprise customers. + */ + cacheKey?: string; + /** + * This allows you to append additional Cache-Tag response headers + * to the origin response without modifications to the origin server. + * This will allow for greater control over the Purge by Cache Tag feature + * utilizing changes only in the Workers process. + * + * Only available for Enterprise customers. + */ + cacheTags?: string[]; + /** + * Force response to be cached for a given number of seconds. (e.g. 300) + */ + cacheTtl?: number; + /** + * Force response to be cached for a given number of seconds based on the Origin status code. + * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) + */ + cacheTtlByStatus?: Record; + scrapeShield?: boolean; + apps?: boolean; + image?: RequestInitCfPropertiesImage; + minify?: RequestInitCfPropertiesImageMinify; + mirage?: boolean; + polish?: "lossy" | "lossless" | "off"; + r2?: RequestInitCfPropertiesR2; + /** + * Redirects the request to an alternate origin server. You can use this, + * for example, to implement load balancing across several origins. + * (e.g.us-east.example.com) + * + * Note - For security reasons, the hostname set in resolveOverride must + * be proxied on the same Cloudflare zone of the incoming request. + * Otherwise, the setting is ignored. CNAME hosts are allowed, so to + * resolve to a host under a different domain or a DNS only domain first + * declare a CNAME record within your own zone’s DNS mapping to the + * external hostname, set proxy on Cloudflare, then set resolveOverride + * to point to that CNAME record. + */ + resolveOverride?: string; +} +interface RequestInitCfPropertiesImageDraw extends BasicImageTransformations { + /** + * Absolute URL of the image file to use for the drawing. It can be any of + * the supported file formats. For drawing of watermarks or non-rectangular + * overlays we recommend using PNG or WebP images. + */ + url: string; + /** + * Floating-point number between 0 (transparent) and 1 (opaque). + * For example, opacity: 0.5 makes overlay semitransparent. + */ + opacity?: number; + /** + * - If set to true, the overlay image will be tiled to cover the entire + * area. This is useful for stock-photo-like watermarks. + * - If set to "x", the overlay image will be tiled horizontally only + * (form a line). + * - If set to "y", the overlay image will be tiled vertically only + * (form a line). + */ + repeat?: true | "x" | "y"; + /** + * Position of the overlay image relative to a given edge. Each property is + * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 + * positions left side of the overlay 10 pixels from the left edge of the + * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom + * of the background image. + * + * Setting both left & right, or both top & bottom is an error. + * + * If no position is specified, the image will be centered. + */ + top?: number; + left?: number; + bottom?: number; + right?: number; +} +interface RequestInitCfPropertiesImage extends BasicImageTransformations { + /** + * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it + * easier to specify higher-DPI sizes in . + */ + dpr?: number; + /** + * Allows you to trim your image. Takes dpr into account and is performed before + * resizing or rotation. + * + * It can be used as: + * - left, top, right, bottom - it will specify the number of pixels to cut + * off each side + * - width, height - the width/height you'd like to end up with - can be used + * in combination with the properties above + * - border - this will automatically trim the surroundings of an image based on + * it's color. It consists of three properties: + * - color: rgb or hex representation of the color you wish to trim (todo: verify the rgba bit) + * - tolerance: difference from color to treat as color + * - keep: the number of pixels of border to keep + */ + trim?: "border" | { + top?: number; + bottom?: number; + left?: number; + right?: number; + width?: number; + height?: number; + border?: boolean | { + color?: string; + tolerance?: number; + keep?: number; + }; + }; + /** + * Quality setting from 1-100 (useful values are in 60-90 range). Lower values + * make images look worse, but load faster. The default is 85. It applies only + * to JPEG and WebP images. It doesn’t have any effect on PNG. + */ + quality?: number | "low" | "medium-low" | "medium-high" | "high"; + /** + * Output format to generate. It can be: + * - avif: generate images in AVIF format. + * - webp: generate images in Google WebP format. Set quality to 100 to get + * the WebP-lossless format. + * - json: instead of generating an image, outputs information about the + * image, in JSON format. The JSON object will contain image size + * (before and after resizing), source image’s MIME type, file size, etc. + * - jpeg: generate images in JPEG format. + * - png: generate images in PNG format. + */ + format?: "avif" | "webp" | "json" | "jpeg" | "png" | "baseline-jpeg" | "png-force" | "svg"; + /** + * Whether to preserve animation frames from input files. Default is true. + * Setting it to false reduces animations to still images. This setting is + * recommended when enlarging images or processing arbitrary user content, + * because large GIF animations can weigh tens or even hundreds of megabytes. + * It is also useful to set anim:false when using format:"json" to get the + * response quicker without the number of frames. + */ + anim?: boolean; + /** + * What EXIF data should be preserved in the output image. Note that EXIF + * rotation and embedded color profiles are always applied ("baked in" into + * the image), and aren't affected by this option. Note that if the Polish + * feature is enabled, all metadata may have been removed already and this + * option may have no effect. + * - keep: Preserve most of EXIF metadata, including GPS location if there's + * any. + * - copyright: Only keep the copyright tag, and discard everything else. + * This is the default behavior for JPEG files. + * - none: Discard all invisible EXIF metadata. Currently WebP and PNG + * output formats always discard metadata. + */ + metadata?: "keep" | "copyright" | "none"; + /** + * Strength of sharpening filter to apply to the image. Floating-point + * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a + * recommended value for downscaled images. + */ + sharpen?: number; + /** + * Radius of a blur filter (approximate gaussian). Maximum supported radius + * is 250. + */ + blur?: number; + /** + * Overlays are drawn in the order they appear in the array (last array + * entry is the topmost layer). + */ + draw?: RequestInitCfPropertiesImageDraw[]; + /** + * Fetching image from authenticated origin. Setting this property will + * pass authentication headers (Authorization, Cookie, etc.) through to + * the origin. + */ + "origin-auth"?: "share-publicly"; + /** + * Adds a border around the image. The border is added after resizing. Border + * width takes dpr into account, and can be specified either using a single + * width property, or individually for each side. + */ + border?: { + color: string; + width: number; + } | { + color: string; + top: number; + right: number; + bottom: number; + left: number; + }; + /** + * Increase brightness by a factor. A value of 1.0 equals no change, a value + * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. + * 0 is ignored. + */ + brightness?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + contrast?: number; + /** + * Increase exposure by a factor. A value of 1.0 equals no change, a value of + * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. + */ + gamma?: number; + /** + * Increase contrast by a factor. A value of 1.0 equals no change, a value of + * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is + * ignored. + */ + saturation?: number; + /** + * Flips the images horizontally, vertically, or both. Flipping is applied before + * rotation, so if you apply flip=h,rotate=90 then the image will be flipped + * horizontally, then rotated by 90 degrees. + */ + flip?: 'h' | 'v' | 'hv'; + /** + * Slightly reduces latency on a cache miss by selecting a + * quickest-to-compress file format, at a cost of increased file size and + * lower image quality. It will usually override the format option and choose + * JPEG over WebP or AVIF. We do not recommend using this option, except in + * unusual circumstances like resizing uncacheable dynamically-generated + * images. + */ + compression?: "fast"; +} +interface RequestInitCfPropertiesImageMinify { + javascript?: boolean; + css?: boolean; + html?: boolean; +} +interface RequestInitCfPropertiesR2 { + /** + * Colo id of bucket that an object is stored in + */ + bucketColoId?: number; +} +/** + * Request metadata provided by Cloudflare's edge. + */ +type IncomingRequestCfProperties = IncomingRequestCfPropertiesBase & IncomingRequestCfPropertiesBotManagementEnterprise & IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & IncomingRequestCfPropertiesGeographicInformation & IncomingRequestCfPropertiesCloudflareAccessOrApiShield; +interface IncomingRequestCfPropertiesBase extends Record { + /** + * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. + * + * @example 395747 + */ + asn?: number; + /** + * The organization which owns the ASN of the incoming request. + * + * @example "Google Cloud" + */ + asOrganization?: string; + /** + * The original value of the `Accept-Encoding` header if Cloudflare modified it. + * + * @example "gzip, deflate, br" + */ + clientAcceptEncoding?: string; + /** + * The number of milliseconds it took for the request to reach your worker. + * + * @example 22 + */ + clientTcpRtt?: number; + /** + * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) + * airport code of the data center that the request hit. + * + * @example "DFW" + */ + colo: string; + /** + * Represents the upstream's response to a + * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) + * from cloudflare. + * + * For workers with no upstream, this will always be `1`. + * + * @example 3 + */ + edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; + /** + * The HTTP Protocol the request used. + * + * @example "HTTP/2" + */ + httpProtocol: string; + /** + * The browser-requested prioritization information in the request object. + * + * If no information was set, defaults to the empty string `""` + * + * @example "weight=192;exclusive=0;group=3;group-weight=127" + * @default "" + */ + requestPriority: string; + /** + * The TLS version of the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "TLSv1.3" + */ + tlsVersion: string; + /** + * The cipher for the connection to Cloudflare. + * In requests served over plaintext (without TLS), this property is the empty string `""`. + * + * @example "AEAD-AES128-GCM-SHA256" + */ + tlsCipher: string; + /** + * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. + * + * If the incoming request was served over plaintext (without TLS) this field is undefined. + */ + tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; +} +interface IncomingRequestCfPropertiesBotManagementBase { + /** + * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, + * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). + * + * @example 54 + */ + score: number; + /** + * A boolean value that is true if the request comes from a good bot, like Google or Bing. + * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). + */ + verifiedBot: boolean; + /** + * A boolean value that is true if the request originates from a + * Cloudflare-verified proxy service. + */ + corporateProxy: boolean; + /** + * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. + */ + staticResource: boolean; + /** + * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). + */ + detectionIds: number[]; +} +interface IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase; + /** + * Duplicate of `botManagement.score`. + * + * @deprecated + */ + clientTrustScore: number; +} +interface IncomingRequestCfPropertiesBotManagementEnterprise extends IncomingRequestCfPropertiesBotManagement { + /** + * Results of Cloudflare's Bot Management analysis + */ + botManagement: IncomingRequestCfPropertiesBotManagementBase & { + /** + * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients + * across different destination IPs, Ports, and X509 certificates. + */ + ja3Hash: string; + }; +} +interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise { + /** + * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). + * + * This field is only present if you have Cloudflare for SaaS enabled on your account + * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). + */ + hostMetadata?: HostMetadata; +} +interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { + /** + * Information about the client certificate presented to Cloudflare. + * + * This is populated when the incoming request is served over TLS using + * either Cloudflare Access or API Shield (mTLS) + * and the presented SSL certificate has a valid + * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) + * (i.e., not `null` or `""`). + * + * Otherwise, a set of placeholder values are used. + * + * The property `certPresented` will be set to `"1"` when + * the object is populated (i.e. the above conditions were met). + */ + tlsClientAuth: IncomingRequestCfPropertiesTLSClientAuth | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; +} +/** + * Metadata about the request's TLS handshake + */ +interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { + /** + * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + clientHandshake: string; + /** + * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal + * + * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" + */ + serverHandshake: string; + /** + * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + clientFinished: string; + /** + * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal + * + * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" + */ + serverFinished: string; +} +/** + * Geographic data about the request's origin. + */ +interface IncomingRequestCfPropertiesGeographicInformation { + /** + * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. + * + * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. + * + * If Cloudflare is unable to determine where the request originated this property is omitted. + * + * The country code `"T1"` is used for requests originating on TOR. + * + * @example "GB" + */ + country?: Iso3166Alpha2Code | "T1"; + /** + * If present, this property indicates that the request originated in the EU + * + * @example "1" + */ + isEUCountry?: "1"; + /** + * A two-letter code indicating the continent the request originated from. + * + * @example "AN" + */ + continent?: ContinentCode; + /** + * The city the request originated from + * + * @example "Austin" + */ + city?: string; + /** + * Postal code of the incoming request + * + * @example "78701" + */ + postalCode?: string; + /** + * Latitude of the incoming request + * + * @example "30.27130" + */ + latitude?: string; + /** + * Longitude of the incoming request + * + * @example "-97.74260" + */ + longitude?: string; + /** + * Timezone of the incoming request + * + * @example "America/Chicago" + */ + timezone?: string; + /** + * If known, the ISO 3166-2 name for the first level region associated with + * the IP address of the incoming request + * + * @example "Texas" + */ + region?: string; + /** + * If known, the ISO 3166-2 code for the first-level region associated with + * the IP address of the incoming request + * + * @example "TX" + */ + regionCode?: string; + /** + * Metro code (DMA) of the incoming request + * + * @example "635" + */ + metroCode?: string; +} +/** Data about the incoming request's TLS certificate */ +interface IncomingRequestCfPropertiesTLSClientAuth { + /** Always `"1"`, indicating that the certificate was presented */ + certPresented: "1"; + /** + * Result of certificate verification. + * + * @example "FAILED:self signed certificate" + */ + certVerified: Exclude; + /** The presented certificate's revokation status. + * + * - A value of `"1"` indicates the certificate has been revoked + * - A value of `"0"` indicates the certificate has not been revoked + */ + certRevoked: "1" | "0"; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDN: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDN: string; + /** + * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certIssuerDNRFC2253: string; + /** + * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) + * + * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" + */ + certSubjectDNRFC2253: string; + /** The certificate issuer's distinguished name (legacy policies) */ + certIssuerDNLegacy: string; + /** The certificate subject's distinguished name (legacy policies) */ + certSubjectDNLegacy: string; + /** + * The certificate's serial number + * + * @example "00936EACBE07F201DF" + */ + certSerial: string; + /** + * The certificate issuer's serial number + * + * @example "2489002934BDFEA34" + */ + certIssuerSerial: string; + /** + * The certificate's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certSKI: string; + /** + * The certificate issuer's Subject Key Identifier + * + * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" + */ + certIssuerSKI: string; + /** + * The certificate's SHA-1 fingerprint + * + * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" + */ + certFingerprintSHA1: string; + /** + * The certificate's SHA-256 fingerprint + * + * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" + */ + certFingerprintSHA256: string; + /** + * The effective starting date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotBefore: string; + /** + * The effective expiration date of the certificate + * + * @example "Dec 22 19:39:00 2018 GMT" + */ + certNotAfter: string; +} +/** Placeholder values for TLS Client Authorization */ +interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { + certPresented: "0"; + certVerified: "NONE"; + certRevoked: "0"; + certIssuerDN: ""; + certSubjectDN: ""; + certIssuerDNRFC2253: ""; + certSubjectDNRFC2253: ""; + certIssuerDNLegacy: ""; + certSubjectDNLegacy: ""; + certSerial: ""; + certIssuerSerial: ""; + certSKI: ""; + certIssuerSKI: ""; + certFingerprintSHA1: ""; + certFingerprintSHA256: ""; + certNotBefore: ""; + certNotAfter: ""; +} +/** Possible outcomes of TLS verification */ +declare type CertVerificationStatus = +/** Authentication succeeded */ +"SUCCESS" +/** No certificate was presented */ + | "NONE" +/** Failed because the certificate was self-signed */ + | "FAILED:self signed certificate" +/** Failed because the certificate failed a trust chain check */ + | "FAILED:unable to verify the first certificate" +/** Failed because the certificate not yet valid */ + | "FAILED:certificate is not yet valid" +/** Failed because the certificate is expired */ + | "FAILED:certificate has expired" +/** Failed for another unspecified reason */ + | "FAILED"; +/** + * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. + */ +declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = 0 /** Unknown */ | 1 /** no keepalives (not found) */ | 2 /** no connection re-use, opening keepalive connection failed */ | 3 /** no connection re-use, keepalive accepted and saved */ | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ | 5; /** connection re-use, accepted by the origin server */ +/** ISO 3166-1 Alpha-2 codes */ +declare type Iso3166Alpha2Code = "AD" | "AE" | "AF" | "AG" | "AI" | "AL" | "AM" | "AO" | "AQ" | "AR" | "AS" | "AT" | "AU" | "AW" | "AX" | "AZ" | "BA" | "BB" | "BD" | "BE" | "BF" | "BG" | "BH" | "BI" | "BJ" | "BL" | "BM" | "BN" | "BO" | "BQ" | "BR" | "BS" | "BT" | "BV" | "BW" | "BY" | "BZ" | "CA" | "CC" | "CD" | "CF" | "CG" | "CH" | "CI" | "CK" | "CL" | "CM" | "CN" | "CO" | "CR" | "CU" | "CV" | "CW" | "CX" | "CY" | "CZ" | "DE" | "DJ" | "DK" | "DM" | "DO" | "DZ" | "EC" | "EE" | "EG" | "EH" | "ER" | "ES" | "ET" | "FI" | "FJ" | "FK" | "FM" | "FO" | "FR" | "GA" | "GB" | "GD" | "GE" | "GF" | "GG" | "GH" | "GI" | "GL" | "GM" | "GN" | "GP" | "GQ" | "GR" | "GS" | "GT" | "GU" | "GW" | "GY" | "HK" | "HM" | "HN" | "HR" | "HT" | "HU" | "ID" | "IE" | "IL" | "IM" | "IN" | "IO" | "IQ" | "IR" | "IS" | "IT" | "JE" | "JM" | "JO" | "JP" | "KE" | "KG" | "KH" | "KI" | "KM" | "KN" | "KP" | "KR" | "KW" | "KY" | "KZ" | "LA" | "LB" | "LC" | "LI" | "LK" | "LR" | "LS" | "LT" | "LU" | "LV" | "LY" | "MA" | "MC" | "MD" | "ME" | "MF" | "MG" | "MH" | "MK" | "ML" | "MM" | "MN" | "MO" | "MP" | "MQ" | "MR" | "MS" | "MT" | "MU" | "MV" | "MW" | "MX" | "MY" | "MZ" | "NA" | "NC" | "NE" | "NF" | "NG" | "NI" | "NL" | "NO" | "NP" | "NR" | "NU" | "NZ" | "OM" | "PA" | "PE" | "PF" | "PG" | "PH" | "PK" | "PL" | "PM" | "PN" | "PR" | "PS" | "PT" | "PW" | "PY" | "QA" | "RE" | "RO" | "RS" | "RU" | "RW" | "SA" | "SB" | "SC" | "SD" | "SE" | "SG" | "SH" | "SI" | "SJ" | "SK" | "SL" | "SM" | "SN" | "SO" | "SR" | "SS" | "ST" | "SV" | "SX" | "SY" | "SZ" | "TC" | "TD" | "TF" | "TG" | "TH" | "TJ" | "TK" | "TL" | "TM" | "TN" | "TO" | "TR" | "TT" | "TV" | "TW" | "TZ" | "UA" | "UG" | "UM" | "US" | "UY" | "UZ" | "VA" | "VC" | "VE" | "VG" | "VI" | "VN" | "VU" | "WF" | "WS" | "YE" | "YT" | "ZA" | "ZM" | "ZW"; +/** The 2-letter continent codes Cloudflare uses */ +declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; +type CfProperties = IncomingRequestCfProperties | RequestInitCfProperties; +interface D1Meta { + duration: number; + size_after: number; + rows_read: number; + rows_written: number; + last_row_id: number; + changed_db: boolean; + changes: number; + /** + * The region of the database instance that executed the query. + */ + served_by_region?: string; + /** + * True if-and-only-if the database instance that executed the query was the primary. + */ + served_by_primary?: boolean; + timings?: { + /** + * The duration of the SQL query execution by the database instance. It doesn't include any network time. + */ + sql_duration_ms: number; + }; + /** + * Number of total attempts to execute the query, due to automatic retries. + * Note: All other fields in the response like `timings` only apply to the last attempt. + */ + total_attempts?: number; +} +interface D1Response { + success: true; + meta: D1Meta & Record; + error?: never; +} +type D1Result = D1Response & { + results: T[]; +}; +interface D1ExecResult { + count: number; + duration: number; +} +type D1SessionConstraint = +// Indicates that the first query should go to the primary, and the rest queries +// using the same D1DatabaseSession will go to any replica that is consistent with +// the bookmark maintained by the session (returned by the first query). +'first-primary' +// Indicates that the first query can go anywhere (primary or replica), and the rest queries +// using the same D1DatabaseSession will go to any replica that is consistent with +// the bookmark maintained by the session (returned by the first query). + | 'first-unconstrained'; +type D1SessionBookmark = string; +declare abstract class D1Database { + prepare(query: string): D1PreparedStatement; + batch(statements: D1PreparedStatement[]): Promise[]>; + exec(query: string): Promise; + /** + * Creates a new D1 Session anchored at the given constraint or the bookmark. + * All queries executed using the created session will have sequential consistency, + * meaning that all writes done through the session will be visible in subsequent reads. + * + * @param constraintOrBookmark Either the session constraint or the explicit bookmark to anchor the created session. + */ + withSession(constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint): D1DatabaseSession; + /** + * @deprecated dump() will be removed soon, only applies to deprecated alpha v1 databases. + */ + dump(): Promise; +} +declare abstract class D1DatabaseSession { + prepare(query: string): D1PreparedStatement; + batch(statements: D1PreparedStatement[]): Promise[]>; + /** + * @returns The latest session bookmark across all executed queries on the session. + * If no query has been executed yet, `null` is returned. + */ + getBookmark(): D1SessionBookmark | null; +} +declare abstract class D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + first(colName: string): Promise; + first>(): Promise; + run>(): Promise>; + all>(): Promise>; + raw(options: { + columnNames: true; + }): Promise<[ + string[], + ...T[] + ]>; + raw(options?: { + columnNames?: false; + }): Promise; +} +// `Disposable` was added to TypeScript's standard lib types in version 5.2. +// To support older TypeScript versions, define an empty `Disposable` interface. +// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, +// but this will ensure type checking on older versions still passes. +// TypeScript's interface merging will ensure our empty interface is effectively +// ignored when `Disposable` is included in the standard lib. +interface Disposable { +} +/** + * An email message that can be sent from a Worker. + */ +interface EmailMessage { + /** + * Envelope From attribute of the email message. + */ + readonly from: string; + /** + * Envelope To attribute of the email message. + */ + readonly to: string; +} +/** + * An email message that is sent to a consumer Worker and can be rejected/forwarded. + */ +interface ForwardableEmailMessage extends EmailMessage { + /** + * Stream of the email message content. + */ + readonly raw: ReadableStream; + /** + * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + */ + readonly headers: Headers; + /** + * Size of the email message content. + */ + readonly rawSize: number; + /** + * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. + * @param reason The reject reason. + * @returns void + */ + setReject(reason: string): void; + /** + * Forward this email message to a verified destination address of the account. + * @param rcptTo Verified destination address. + * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). + * @returns A promise that resolves when the email message is forwarded. + */ + forward(rcptTo: string, headers?: Headers): Promise; + /** + * Reply to the sender of this email message with a new EmailMessage object. + * @param message The reply message. + * @returns A promise that resolves when the email message is replied. + */ + reply(message: EmailMessage): Promise; +} +/** + * A binding that allows a Worker to send email messages. + */ +interface SendEmail { + send(message: EmailMessage): Promise; +} +declare abstract class EmailEvent extends ExtendableEvent { + readonly message: ForwardableEmailMessage; +} +declare type EmailExportedHandler = (message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext) => void | Promise; +declare module "cloudflare:email" { + let _EmailMessage: { + prototype: EmailMessage; + new (from: string, to: string, raw: ReadableStream | string): EmailMessage; + }; + export { _EmailMessage as EmailMessage }; +} +/** + * Hello World binding to serve as an explanatory example. DO NOT USE + */ +interface HelloWorldBinding { + /** + * Retrieve the current stored value + */ + get(): Promise<{ + value: string; + ms?: number; + }>; + /** + * Set a new stored value + */ + set(value: string): Promise; +} +interface Hyperdrive { + /** + * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. + * + * Calling this method returns an idential socket to if you call + * `connect("host:port")` using the `host` and `port` fields from this object. + * Pick whichever approach works better with your preferred DB client library. + * + * Note that this socket is not yet authenticated -- it's expected that your + * code (or preferably, the client library of your choice) will authenticate + * using the information in this class's readonly fields. + */ + connect(): Socket; + /** + * A valid DB connection string that can be passed straight into the typical + * client library/driver/ORM. This will typically be the easiest way to use + * Hyperdrive. + */ + readonly connectionString: string; + /* + * A randomly generated hostname that is only valid within the context of the + * currently running Worker which, when passed into `connect()` function from + * the "cloudflare:sockets" module, will connect to the Hyperdrive instance + * for your database. + */ + readonly host: string; + /* + * The port that must be paired the the host field when connecting. + */ + readonly port: number; + /* + * The username to use when authenticating to your database via Hyperdrive. + * Unlike the host and password, this will be the same every time + */ + readonly user: string; + /* + * The randomly generated password to use when authenticating to your + * database via Hyperdrive. Like the host field, this password is only valid + * within the context of the currently running Worker instance from which + * it's read. + */ + readonly password: string; + /* + * The name of the database to connect to. + */ + readonly database: string; +} +// Copyright (c) 2024 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +type ImageInfoResponse = { + format: 'image/svg+xml'; +} | { + format: string; + fileSize: number; + width: number; + height: number; +}; +type ImageTransform = { + width?: number; + height?: number; + background?: string; + blur?: number; + border?: { + color?: string; + width?: number; + } | { + top?: number; + bottom?: number; + left?: number; + right?: number; + }; + brightness?: number; + contrast?: number; + fit?: 'scale-down' | 'contain' | 'pad' | 'squeeze' | 'cover' | 'crop'; + flip?: 'h' | 'v' | 'hv'; + gamma?: number; + segment?: 'foreground'; + gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | { + x?: number; + y?: number; + mode: 'remainder' | 'box-center'; + }; + rotate?: 0 | 90 | 180 | 270; + saturation?: number; + sharpen?: number; + trim?: 'border' | { + top?: number; + bottom?: number; + left?: number; + right?: number; + width?: number; + height?: number; + border?: boolean | { + color?: string; + tolerance?: number; + keep?: number; + }; + }; +}; +type ImageDrawOptions = { + opacity?: number; + repeat?: boolean | string; + top?: number; + left?: number; + bottom?: number; + right?: number; +}; +type ImageInputOptions = { + encoding?: 'base64'; +}; +type ImageOutputOptions = { + format: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'image/avif' | 'rgb' | 'rgba'; + quality?: number; + background?: string; + anim?: boolean; +}; +interface ImagesBinding { + /** + * Get image metadata (type, width and height) + * @throws {@link ImagesError} with code 9412 if input is not an image + * @param stream The image bytes + */ + info(stream: ReadableStream, options?: ImageInputOptions): Promise; + /** + * Begin applying a series of transformations to an image + * @param stream The image bytes + * @returns A transform handle + */ + input(stream: ReadableStream, options?: ImageInputOptions): ImageTransformer; +} +interface ImageTransformer { + /** + * Apply transform next, returning a transform handle. + * You can then apply more transformations, draw, or retrieve the output. + * @param transform + */ + transform(transform: ImageTransform): ImageTransformer; + /** + * Draw an image on this transformer, returning a transform handle. + * You can then apply more transformations, draw, or retrieve the output. + * @param image The image (or transformer that will give the image) to draw + * @param options The options configuring how to draw the image + */ + draw(image: ReadableStream | ImageTransformer, options?: ImageDrawOptions): ImageTransformer; + /** + * Retrieve the image that results from applying the transforms to the + * provided input + * @param options Options that apply to the output e.g. output format + */ + output(options: ImageOutputOptions): Promise; +} +type ImageTransformationOutputOptions = { + encoding?: 'base64'; +}; +interface ImageTransformationResult { + /** + * The image as a response, ready to store in cache or return to users + */ + response(): Response; + /** + * The content type of the returned image + */ + contentType(): string; + /** + * The bytes of the response + */ + image(options?: ImageTransformationOutputOptions): ReadableStream; +} +interface ImagesError extends Error { + readonly code: number; + readonly message: string; + readonly stack?: string; +} +/** + * Media binding for transforming media streams. + * Provides the entry point for media transformation operations. + */ +interface MediaBinding { + /** + * Creates a media transformer from an input stream. + * @param media - The input media bytes + * @returns A MediaTransformer instance for applying transformations + */ + input(media: ReadableStream): MediaTransformer; +} +/** + * Media transformer for applying transformation operations to media content. + * Handles sizing, fitting, and other input transformation parameters. + */ +interface MediaTransformer { + /** + * Applies transformation options to the media content. + * @param transform - Configuration for how the media should be transformed + * @returns A generator for producing the transformed media output + */ + transform(transform: MediaTransformationInputOptions): MediaTransformationGenerator; +} +/** + * Generator for producing media transformation results. + * Configures the output format and parameters for the transformed media. + */ +interface MediaTransformationGenerator { + /** + * Generates the final media output with specified options. + * @param output - Configuration for the output format and parameters + * @returns The final transformation result containing the transformed media + */ + output(output: MediaTransformationOutputOptions): MediaTransformationResult; +} +/** + * Result of a media transformation operation. + * Provides multiple ways to access the transformed media content. + */ +interface MediaTransformationResult { + /** + * Returns the transformed media as a readable stream of bytes. + * @returns A stream containing the transformed media data + */ + media(): ReadableStream; + /** + * Returns the transformed media as an HTTP response object. + * @returns The transformed media as a Response, ready to store in cache or return to users + */ + response(): Response; + /** + * Returns the MIME type of the transformed media. + * @returns The content type string (e.g., 'image/jpeg', 'video/mp4') + */ + contentType(): string; +} +/** + * Configuration options for transforming media input. + * Controls how the media should be resized and fitted. + */ +type MediaTransformationInputOptions = { + /** How the media should be resized to fit the specified dimensions */ + fit?: 'contain' | 'cover' | 'scale-down'; + /** Target width in pixels */ + width?: number; + /** Target height in pixels */ + height?: number; +}; +/** + * Configuration options for Media Transformations output. + * Controls the format, timing, and type of the generated output. + */ +type MediaTransformationOutputOptions = { + /** + * Output mode determining the type of media to generate + */ + mode?: 'video' | 'spritesheet' | 'frame' | 'audio'; + /** Whether to include audio in the output */ + audio?: boolean; + /** + * Starting timestamp for frame extraction or start time for clips. (e.g. '2s'). + */ + time?: string; + /** + * Duration for video clips, audio extraction, and spritesheet generation (e.g. '5s'). + */ + duration?: string; + /** + * Number of frames in the spritesheet. + */ + imageCount?: number; + /** + * Output format for the generated media. + */ + format?: 'jpg' | 'png' | 'm4a'; +}; +/** + * Error object for media transformation operations. + * Extends the standard Error interface with additional media-specific information. + */ +interface MediaError extends Error { + readonly code: number; + readonly message: string; + readonly stack?: string; +} +declare module 'cloudflare:node' { + interface NodeStyleServer { + listen(...args: unknown[]): this; + address(): { + port?: number | null | undefined; + }; + } + export function httpServerHandler(port: number): ExportedHandler; + export function httpServerHandler(options: { + port: number; + }): ExportedHandler; + export function httpServerHandler(server: NodeStyleServer): ExportedHandler; +} +type Params

= Record; +type EventContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; +}; +type PagesFunction = Record> = (context: EventContext) => Response | Promise; +type EventPluginContext = { + request: Request>; + functionPath: string; + waitUntil: (promise: Promise) => void; + passThroughOnException: () => void; + next: (input?: Request | string, init?: RequestInit) => Promise; + env: Env & { + ASSETS: { + fetch: typeof fetch; + }; + }; + params: Params

; + data: Data; + pluginArgs: PluginArgs; +}; +type PagesPluginFunction = Record, PluginArgs = unknown> = (context: EventPluginContext) => Response | Promise; +declare module "assets:*" { + export const onRequest: PagesFunction; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +declare module "cloudflare:pipelines" { + export abstract class PipelineTransformationEntrypoint { + protected env: Env; + protected ctx: ExecutionContext; + constructor(ctx: ExecutionContext, env: Env); + /** + * run recieves an array of PipelineRecord which can be + * transformed and returned to the pipeline + * @param records Incoming records from the pipeline to be transformed + * @param metadata Information about the specific pipeline calling the transformation entrypoint + * @returns A promise containing the transformed PipelineRecord array + */ + public run(records: I[], metadata: PipelineBatchMetadata): Promise; + } + export type PipelineRecord = Record; + export type PipelineBatchMetadata = { + pipelineId: string; + pipelineName: string; + }; + export interface Pipeline { + /** + * The Pipeline interface represents the type of a binding to a Pipeline + * + * @param records The records to send to the pipeline + */ + send(records: T[]): Promise; + } +} +// PubSubMessage represents an incoming PubSub message. +// The message includes metadata about the broker, the client, and the payload +// itself. +// https://developers.cloudflare.com/pub-sub/ +interface PubSubMessage { + // Message ID + readonly mid: number; + // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT + readonly broker: string; + // The MQTT topic the message was sent on. + readonly topic: string; + // The client ID of the client that published this message. + readonly clientId: string; + // The unique identifier (JWT ID) used by the client to authenticate, if token + // auth was used. + readonly jti?: string; + // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker + // received the message from the client. + readonly receivedAt: number; + // An (optional) string with the MIME type of the payload, if set by the + // client. + readonly contentType: string; + // Set to 1 when the payload is a UTF-8 string + // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 + readonly payloadFormatIndicator: number; + // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. + // You can use payloadFormatIndicator to inspect this before decoding. + payload: string | Uint8Array; +} +// JsonWebKey extended by kid parameter +interface JsonWebKeyWithKid extends JsonWebKey { + // Key Identifier of the JWK + readonly kid: string; +} +interface RateLimitOptions { + key: string; +} +interface RateLimitOutcome { + success: boolean; +} +interface RateLimit { + /** + * Rate limit a request based on the provided options. + * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/ + * @returns A promise that resolves with the outcome of the rate limit. + */ + limit(options: RateLimitOptions): Promise; +} +// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need +// to referenced by `Fetcher`. This is included in the "importable" version of the types which +// strips all `module` blocks. +declare namespace Rpc { + // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. + // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. + // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to + // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) + export const __RPC_STUB_BRAND: '__RPC_STUB_BRAND'; + export const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND'; + export const __WORKER_ENTRYPOINT_BRAND: '__WORKER_ENTRYPOINT_BRAND'; + export const __DURABLE_OBJECT_BRAND: '__DURABLE_OBJECT_BRAND'; + export const __WORKFLOW_ENTRYPOINT_BRAND: '__WORKFLOW_ENTRYPOINT_BRAND'; + export interface RpcTargetBranded { + [__RPC_TARGET_BRAND]: never; + } + export interface WorkerEntrypointBranded { + [__WORKER_ENTRYPOINT_BRAND]: never; + } + export interface DurableObjectBranded { + [__DURABLE_OBJECT_BRAND]: never; + } + export interface WorkflowEntrypointBranded { + [__WORKFLOW_ENTRYPOINT_BRAND]: never; + } + export type EntrypointBranded = WorkerEntrypointBranded | DurableObjectBranded | WorkflowEntrypointBranded; + // Types that can be used through `Stub`s + export type Stubable = RpcTargetBranded | ((...args: any[]) => any); + // Types that can be passed over RPC + // The reason for using a generic type here is to build a serializable subset of structured + // cloneable composite types. This allows types defined with the "interface" keyword to pass the + // serializable check as well. Otherwise, only types defined with the "type" keyword would pass. + type Serializable = + // Structured cloneables + BaseType + // Structured cloneable composites + | Map ? Serializable : never, T extends Map ? Serializable : never> | Set ? Serializable : never> | ReadonlyArray ? Serializable : never> | { + [K in keyof T]: K extends number | string ? Serializable : never; + } + // Special types + | Stub + // Serialized as stubs, see `Stubify` + | Stubable; + // Base type for all RPC stubs, including common memory management methods. + // `T` is used as a marker type for unwrapping `Stub`s later. + interface StubBase extends Disposable { + [__RPC_STUB_BRAND]: T; + dup(): this; + } + export type Stub = Provider & StubBase; + // This represents all the types that can be sent as-is over an RPC boundary + type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | ReadableStream | WritableStream | Request | Response | Headers; + // Recursively rewrite all `Stubable` types with `Stub`s + // prettier-ignore + type Stubify = T extends Stubable ? Stub : T extends Map ? Map, Stubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { + [key: string | number]: any; + } ? { + [K in keyof T]: Stubify; + } : T; + // Recursively rewrite all `Stub`s with the corresponding `T`s. + // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: + // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. + // prettier-ignore + type Unstubify = T extends StubBase ? V : T extends Map ? Map, Unstubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { + [key: string | number]: unknown; + } ? { + [K in keyof T]: Unstubify; + } : T; + type UnstubifyAll = { + [I in keyof A]: Unstubify; + }; + // Utility type for adding `Provider`/`Disposable`s to `object` types only. + // Note `unknown & T` is equivalent to `T`. + type MaybeProvider = T extends object ? Provider : unknown; + type MaybeDisposable = T extends object ? Disposable : unknown; + // Type for method return or property on an RPC interface. + // - Stubable types are replaced by stubs. + // - Serializable types are passed by value, with stubable types replaced by stubs + // and a top-level `Disposer`. + // Everything else can't be passed over PRC. + // Technically, we use custom thenables here, but they quack like `Promise`s. + // Intersecting with `(Maybe)Provider` allows pipelining. + // prettier-ignore + type Result = R extends Stubable ? Promise> & Provider : R extends Serializable ? Promise & MaybeDisposable> & MaybeProvider : never; + // Type for method or property on an RPC interface. + // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. + // Unwrapping `Stub`s allows calling with `Stubable` arguments. + // For properties, rewrite types to be `Result`s. + // In each case, unwrap `Promise`s. + type MethodOrProperty = V extends (...args: infer P) => infer R ? (...args: UnstubifyAll

) => Result> : Result>; + // Type for the callable part of an `Provider` if `T` is callable. + // This is intersected with methods/properties. + type MaybeCallableProvider = T extends (...args: any[]) => any ? MethodOrProperty : unknown; + // Base type for all other types providing RPC-like interfaces. + // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. + // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. + export type Provider = MaybeCallableProvider & { + [K in Exclude>]: MethodOrProperty; + }; +} +declare namespace Cloudflare { + // Type of `env`. + // + // The specific project can extend `Env` by redeclaring it in project-specific files. Typescript + // will merge all declarations. + // + // You can use `wrangler types` to generate the `Env` type automatically. + interface Env { + } + // Project-specific parameters used to inform types. + // + // This interface is, again, intended to be declared in project-specific files, and then that + // declaration will be merged with this one. + // + // A project should have a declaration like this: + // + // interface GlobalProps { + // // Declares the main module's exports. Used to populate Cloudflare.Exports aka the type + // // of `ctx.exports`. + // mainModule: typeof import("my-main-module"); + // + // // Declares which of the main module's exports are configured with durable storage, and + // // thus should behave as Durable Object namsepace bindings. + // durableNamespaces: "MyDurableObject" | "AnotherDurableObject"; + // } + // + // You can use `wrangler types` to generate `GlobalProps` automatically. + interface GlobalProps { + } + // Evaluates to the type of a property in GlobalProps, defaulting to `Default` if it is not + // present. + type GlobalProp = K extends keyof GlobalProps ? GlobalProps[K] : Default; + // The type of the program's main module exports, if known. Requires `GlobalProps` to declare the + // `mainModule` property. + type MainModule = GlobalProp<"mainModule", {}>; + // The type of ctx.exports, which contains loopback bindings for all top-level exports. + type Exports = { + [K in keyof MainModule]: LoopbackForExport + // If the export is listed in `durableNamespaces`, then it is also a + // DurableObjectNamespace. + & (K extends GlobalProp<"durableNamespaces", never> ? MainModule[K] extends new (...args: any[]) => infer DoInstance ? DoInstance extends Rpc.DurableObjectBranded ? DurableObjectNamespace : DurableObjectNamespace : DurableObjectNamespace : {}); + }; +} +declare namespace CloudflareWorkersModule { + export type RpcStub = Rpc.Stub; + export const RpcStub: { + new (value: T): Rpc.Stub; + }; + export abstract class RpcTarget implements Rpc.RpcTargetBranded { + [Rpc.__RPC_TARGET_BRAND]: never; + } + // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC + export abstract class WorkerEntrypoint implements Rpc.WorkerEntrypointBranded { + [Rpc.__WORKER_ENTRYPOINT_BRAND]: never; + protected ctx: ExecutionContext; + protected env: Env; + constructor(ctx: ExecutionContext, env: Env); + fetch?(request: Request): Response | Promise; + tail?(events: TraceItem[]): void | Promise; + trace?(traces: TraceItem[]): void | Promise; + scheduled?(controller: ScheduledController): void | Promise; + queue?(batch: MessageBatch): void | Promise; + test?(controller: TestController): void | Promise; + } + export abstract class DurableObject implements Rpc.DurableObjectBranded { + [Rpc.__DURABLE_OBJECT_BRAND]: never; + protected ctx: DurableObjectState; + protected env: Env; + constructor(ctx: DurableObjectState, env: Env); + fetch?(request: Request): Response | Promise; + alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; + webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; + webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; + webSocketError?(ws: WebSocket, error: unknown): void | Promise; + } + export type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; + export type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number; + export type WorkflowDelayDuration = WorkflowSleepDuration; + export type WorkflowTimeoutDuration = WorkflowSleepDuration; + export type WorkflowRetentionDuration = WorkflowSleepDuration; + export type WorkflowBackoff = 'constant' | 'linear' | 'exponential'; + export type WorkflowStepConfig = { + retries?: { + limit: number; + delay: WorkflowDelayDuration | number; + backoff?: WorkflowBackoff; + }; + timeout?: WorkflowTimeoutDuration | number; + }; + export type WorkflowEvent = { + payload: Readonly; + timestamp: Date; + instanceId: string; + }; + export type WorkflowStepEvent = { + payload: Readonly; + timestamp: Date; + type: string; + }; + export abstract class WorkflowStep { + do>(name: string, callback: () => Promise): Promise; + do>(name: string, config: WorkflowStepConfig, callback: () => Promise): Promise; + sleep: (name: string, duration: WorkflowSleepDuration) => Promise; + sleepUntil: (name: string, timestamp: Date | number) => Promise; + waitForEvent>(name: string, options: { + type: string; + timeout?: WorkflowTimeoutDuration | number; + }): Promise>; + } + export abstract class WorkflowEntrypoint | unknown = unknown> implements Rpc.WorkflowEntrypointBranded { + [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never; + protected ctx: ExecutionContext; + protected env: Env; + constructor(ctx: ExecutionContext, env: Env); + run(event: Readonly>, step: WorkflowStep): Promise; + } + export function waitUntil(promise: Promise): void; + export const env: Cloudflare.Env; +} +declare module 'cloudflare:workers' { + export = CloudflareWorkersModule; +} +interface SecretsStoreSecret { + /** + * Get a secret from the Secrets Store, returning a string of the secret value + * if it exists, or throws an error if it does not exist + */ + get(): Promise; +} +declare module "cloudflare:sockets" { + function _connect(address: string | SocketAddress, options?: SocketOptions): Socket; + export { _connect as connect }; +} +type ConversionResponse = { + name: string; + mimeType: string; +} & ({ + format: "markdown"; + tokens: number; + data: string; +} | { + format: "error"; + error: string; +}); +type SupportedFileFormat = { + mimeType: string; + extension: string; +}; +declare abstract class ToMarkdownService { + transform(files: { + name: string; + blob: Blob; + }[], options?: { + gateway?: GatewayOptions; + extraHeaders?: object; + }): Promise; + transform(files: { + name: string; + blob: Blob; + }, options?: { + gateway?: GatewayOptions; + extraHeaders?: object; + }): Promise; + supported(): Promise; +} +declare namespace TailStream { + interface Header { + readonly name: string; + readonly value: string; + } + interface FetchEventInfo { + readonly type: "fetch"; + readonly method: string; + readonly url: string; + readonly cfJson?: object; + readonly headers: Header[]; + } + interface JsRpcEventInfo { + readonly type: "jsrpc"; + } + interface ScheduledEventInfo { + readonly type: "scheduled"; + readonly scheduledTime: Date; + readonly cron: string; + } + interface AlarmEventInfo { + readonly type: "alarm"; + readonly scheduledTime: Date; + } + interface QueueEventInfo { + readonly type: "queue"; + readonly queueName: string; + readonly batchSize: number; + } + interface EmailEventInfo { + readonly type: "email"; + readonly mailFrom: string; + readonly rcptTo: string; + readonly rawSize: number; + } + interface TraceEventInfo { + readonly type: "trace"; + readonly traces: (string | null)[]; + } + interface HibernatableWebSocketEventInfoMessage { + readonly type: "message"; + } + interface HibernatableWebSocketEventInfoError { + readonly type: "error"; + } + interface HibernatableWebSocketEventInfoClose { + readonly type: "close"; + readonly code: number; + readonly wasClean: boolean; + } + interface HibernatableWebSocketEventInfo { + readonly type: "hibernatableWebSocket"; + readonly info: HibernatableWebSocketEventInfoClose | HibernatableWebSocketEventInfoError | HibernatableWebSocketEventInfoMessage; + } + interface CustomEventInfo { + readonly type: "custom"; + } + interface FetchResponseInfo { + readonly type: "fetch"; + readonly statusCode: number; + } + type EventOutcome = "ok" | "canceled" | "exception" | "unknown" | "killSwitch" | "daemonDown" | "exceededCpu" | "exceededMemory" | "loadShed" | "responseStreamDisconnected" | "scriptNotFound"; + interface ScriptVersion { + readonly id: string; + readonly tag?: string; + readonly message?: string; + } + interface Onset { + readonly type: "onset"; + readonly attributes: Attribute[]; + // id for the span being opened by this Onset event. + readonly spanId: string; + readonly dispatchNamespace?: string; + readonly entrypoint?: string; + readonly executionModel: string; + readonly scriptName?: string; + readonly scriptTags?: string[]; + readonly scriptVersion?: ScriptVersion; + readonly info: FetchEventInfo | JsRpcEventInfo | ScheduledEventInfo | AlarmEventInfo | QueueEventInfo | EmailEventInfo | TraceEventInfo | HibernatableWebSocketEventInfo | CustomEventInfo; + } + interface Outcome { + readonly type: "outcome"; + readonly outcome: EventOutcome; + readonly cpuTime: number; + readonly wallTime: number; + } + interface SpanOpen { + readonly type: "spanOpen"; + readonly name: string; + // id for the span being opened by this SpanOpen event. + readonly spanId: string; + readonly info?: FetchEventInfo | JsRpcEventInfo | Attributes; + } + interface SpanClose { + readonly type: "spanClose"; + readonly outcome: EventOutcome; + } + interface DiagnosticChannelEvent { + readonly type: "diagnosticChannel"; + readonly channel: string; + readonly message: any; + } + interface Exception { + readonly type: "exception"; + readonly name: string; + readonly message: string; + readonly stack?: string; + } + interface Log { + readonly type: "log"; + readonly level: "debug" | "error" | "info" | "log" | "warn"; + readonly message: object; + } + // This marks the worker handler return information. + // This is separate from Outcome because the worker invocation can live for a long time after + // returning. For example - Websockets that return an http upgrade response but then continue + // streaming information or SSE http connections. + interface Return { + readonly type: "return"; + readonly info?: FetchResponseInfo; + } + interface Attribute { + readonly name: string; + readonly value: string | string[] | boolean | boolean[] | number | number[] | bigint | bigint[]; + } + interface Attributes { + readonly type: "attributes"; + readonly info: Attribute[]; + } + type EventType = Onset | Outcome | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | Return | Attributes; + // Context in which this trace event lives. + interface SpanContext { + // Single id for the entire top-level invocation + // This should be a new traceId for the first worker stage invoked in the eyeball request and then + // same-account service-bindings should reuse the same traceId but cross-account service-bindings + // should use a new traceId. + readonly traceId: string; + // spanId in which this event is handled + // for Onset and SpanOpen events this would be the parent span id + // for Outcome and SpanClose these this would be the span id of the opening Onset and SpanOpen events + // For Hibernate and Mark this would be the span under which they were emitted. + // spanId is not set ONLY if: + // 1. This is an Onset event + // 2. We are not inherting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation) + readonly spanId?: string; + } + interface TailEvent { + // invocation id of the currently invoked worker stage. + // invocation id will always be unique to every Onset event and will be the same until the Outcome event. + readonly invocationId: string; + // Inherited spanContext for this event. + readonly spanContext: SpanContext; + readonly timestamp: Date; + readonly sequence: number; + readonly event: Event; + } + type TailEventHandler = (event: TailEvent) => void | Promise; + type TailEventHandlerObject = { + outcome?: TailEventHandler; + spanOpen?: TailEventHandler; + spanClose?: TailEventHandler; + diagnosticChannel?: TailEventHandler; + exception?: TailEventHandler; + log?: TailEventHandler; + return?: TailEventHandler; + attributes?: TailEventHandler; + }; + type TailEventHandlerType = TailEventHandler | TailEventHandlerObject; +} +// Copyright (c) 2022-2023 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 +/** + * Data types supported for holding vector metadata. + */ +type VectorizeVectorMetadataValue = string | number | boolean | string[]; +/** + * Additional information to associate with a vector. + */ +type VectorizeVectorMetadata = VectorizeVectorMetadataValue | Record; +type VectorFloatArray = Float32Array | Float64Array; +interface VectorizeError { + code?: number; + error: string; +} +/** + * Comparison logic/operation to use for metadata filtering. + * + * This list is expected to grow as support for more operations are released. + */ +type VectorizeVectorMetadataFilterOp = "$eq" | "$ne"; +/** + * Filter criteria for vector metadata used to limit the retrieved query result set. + */ +type VectorizeVectorMetadataFilter = { + [field: string]: Exclude | null | { + [Op in VectorizeVectorMetadataFilterOp]?: Exclude | null; + }; +}; +/** + * Supported distance metrics for an index. + * Distance metrics determine how other "similar" vectors are determined. + */ +type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; +/** + * Metadata return levels for a Vectorize query. + * + * Default to "none". + * + * @property all Full metadata for the vector return set, including all fields (including those un-indexed) without truncation. This is a more expensive retrieval, as it requires additional fetching & reading of un-indexed data. + * @property indexed Return all metadata fields configured for indexing in the vector return set. This level of retrieval is "free" in that no additional overhead is incurred returning this data. However, note that indexed metadata is subject to truncation (especially for larger strings). + * @property none No indexed metadata will be returned. + */ +type VectorizeMetadataRetrievalLevel = "all" | "indexed" | "none"; +interface VectorizeQueryOptions { + topK?: number; + namespace?: string; + returnValues?: boolean; + returnMetadata?: boolean | VectorizeMetadataRetrievalLevel; + filter?: VectorizeVectorMetadataFilter; +} +/** + * Information about the configuration of an index. + */ +type VectorizeIndexConfig = { + dimensions: number; + metric: VectorizeDistanceMetric; +} | { + preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity +}; +/** + * Metadata about an existing index. + * + * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released. + * See {@link VectorizeIndexInfo} for its post-beta equivalent. + */ +interface VectorizeIndexDetails { + /** The unique ID of the index */ + readonly id: string; + /** The name of the index. */ + name: string; + /** (optional) A human readable description for the index. */ + description?: string; + /** The index configuration, including the dimension size and distance metric. */ + config: VectorizeIndexConfig; + /** The number of records containing vectors within the index. */ + vectorsCount: number; +} +/** + * Metadata about an existing index. + */ +interface VectorizeIndexInfo { + /** The number of records containing vectors within the index. */ + vectorCount: number; + /** Number of dimensions the index has been configured for. */ + dimensions: number; + /** ISO 8601 datetime of the last processed mutation on in the index. All changes before this mutation will be reflected in the index state. */ + processedUpToDatetime: number; + /** UUIDv4 of the last mutation processed by the index. All changes before this mutation will be reflected in the index state. */ + processedUpToMutation: number; +} +/** + * Represents a single vector value set along with its associated metadata. + */ +interface VectorizeVector { + /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ + id: string; + /** The vector values */ + values: VectorFloatArray | number[]; + /** The namespace this vector belongs to. */ + namespace?: string; + /** Metadata associated with the vector. Includes the values of other fields and potentially additional details. */ + metadata?: Record; +} +/** + * Represents a matched vector for a query along with its score and (if specified) the matching vector information. + */ +type VectorizeMatch = Pick, "values"> & Omit & { + /** The score or rank for similarity, when returned as a result */ + score: number; +}; +/** + * A set of matching {@link VectorizeMatch} for a particular query. + */ +interface VectorizeMatches { + matches: VectorizeMatch[]; + count: number; +} +/** + * Results of an operation that performed a mutation on a set of vectors. + * Here, `ids` is a list of vectors that were successfully processed. + * + * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released. + * See {@link VectorizeAsyncMutation} for its post-beta equivalent. + */ +interface VectorizeVectorMutation { + /* List of ids of vectors that were successfully processed. */ + ids: string[]; + /* Total count of the number of processed vectors. */ + count: number; +} +/** + * Result type indicating a mutation on the Vectorize Index. + * Actual mutations are processed async where the `mutationId` is the unique identifier for the operation. + */ +interface VectorizeAsyncMutation { + /** The unique identifier for the async mutation operation containing the changeset. */ + mutationId: string; +} +/** + * A Vectorize Vector Search Index for querying vectors/embeddings. + * + * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released. + * See {@link Vectorize} for its new implementation. + */ +declare abstract class VectorizeIndex { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with the ids & count of records that were successfully processed. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * A Vectorize Vector Search Index for querying vectors/embeddings. + * + * Mutations in this version are async, returning a mutation id. + */ +declare abstract class Vectorize { + /** + * Get information about the currently bound index. + * @returns A promise that resolves with information about the current index. + */ + public describe(): Promise; + /** + * Use the provided vector to perform a similarity search across the index. + * @param vector Input vector that will be used to drive the similarity search. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise; + /** + * Use the provided vector-id to perform a similarity search across the index. + * @param vectorId Id for a vector in the index against which the index should be queried. + * @param options Configuration options to massage the returned data. + * @returns A promise that resolves with matched and scored vectors. + */ + public queryById(vectorId: string, options?: VectorizeQueryOptions): Promise; + /** + * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. + * @param vectors List of vectors that will be inserted. + * @returns A promise that resolves with a unique identifier of a mutation containing the insert changeset. + */ + public insert(vectors: VectorizeVector[]): Promise; + /** + * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. + * @param vectors List of vectors that will be upserted. + * @returns A promise that resolves with a unique identifier of a mutation containing the upsert changeset. + */ + public upsert(vectors: VectorizeVector[]): Promise; + /** + * Delete a list of vectors with a matching id. + * @param ids List of vector ids that should be deleted. + * @returns A promise that resolves with a unique identifier of a mutation containing the delete changeset. + */ + public deleteByIds(ids: string[]): Promise; + /** + * Get a list of vectors with a matching id. + * @param ids List of vector ids that should be returned. + * @returns A promise that resolves with the raw unscored vectors matching the id set. + */ + public getByIds(ids: string[]): Promise; +} +/** + * The interface for "version_metadata" binding + * providing metadata about the Worker Version using this binding. + */ +type WorkerVersionMetadata = { + /** The ID of the Worker Version using this binding */ + id: string; + /** The tag of the Worker Version using this binding */ + tag: string; + /** The timestamp of when the Worker Version was uploaded */ + timestamp: string; +}; +interface DynamicDispatchLimits { + /** + * Limit CPU time in milliseconds. + */ + cpuMs?: number; + /** + * Limit number of subrequests. + */ + subRequests?: number; +} +interface DynamicDispatchOptions { + /** + * Limit resources of invoked Worker script. + */ + limits?: DynamicDispatchLimits; + /** + * Arguments for outbound Worker script, if configured. + */ + outbound?: { + [key: string]: any; + }; +} +interface DispatchNamespace { + /** + * @param name Name of the Worker script. + * @param args Arguments to Worker script. + * @param options Options for Dynamic Dispatch invocation. + * @returns A Fetcher object that allows you to send requests to the Worker script. + * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. + */ + get(name: string, args?: { + [key: string]: any; + }, options?: DynamicDispatchOptions): Fetcher; +} +declare module 'cloudflare:workflows' { + /** + * NonRetryableError allows for a user to throw a fatal error + * that makes a Workflow instance fail immediately without triggering a retry + */ + export class NonRetryableError extends Error { + public constructor(message: string, name?: string); + } +} +declare abstract class Workflow { + /** + * Get a handle to an existing instance of the Workflow. + * @param id Id for the instance of this Workflow + * @returns A promise that resolves with a handle for the Instance + */ + public get(id: string): Promise; + /** + * Create a new instance and return a handle to it. If a provided id exists, an error will be thrown. + * @param options Options when creating an instance including id and params + * @returns A promise that resolves with a handle for the Instance + */ + public create(options?: WorkflowInstanceCreateOptions): Promise; + /** + * Create a batch of instances and return handle for all of them. If a provided id exists, an error will be thrown. + * `createBatch` is limited at 100 instances at a time or when the RPC limit for the batch (1MiB) is reached. + * @param batch List of Options when creating an instance including name and params + * @returns A promise that resolves with a list of handles for the created instances. + */ + public createBatch(batch: WorkflowInstanceCreateOptions[]): Promise; +} +type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; +type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number; +type WorkflowRetentionDuration = WorkflowSleepDuration; +interface WorkflowInstanceCreateOptions { + /** + * An id for your Workflow instance. Must be unique within the Workflow. + */ + id?: string; + /** + * The event payload the Workflow instance is triggered with + */ + params?: PARAMS; + /** + * The retention policy for Workflow instance. + * Defaults to the maximum retention period available for the owner's account. + */ + retention?: { + successRetention?: WorkflowRetentionDuration; + errorRetention?: WorkflowRetentionDuration; + }; +} +type InstanceStatus = { + status: 'queued' // means that instance is waiting to be started (see concurrency limits) + | 'running' | 'paused' | 'errored' | 'terminated' // user terminated the instance while it was running + | 'complete' | 'waiting' // instance is hibernating and waiting for sleep or event to finish + | 'waitingForPause' // instance is finishing the current work to pause + | 'unknown'; + error?: string; + output?: object; +}; +interface WorkflowError { + code?: number; + message: string; +} +declare abstract class WorkflowInstance { + public id: string; + /** + * Pause the instance. + */ + public pause(): Promise; + /** + * Resume the instance. If it is already running, an error will be thrown. + */ + public resume(): Promise; + /** + * Terminate the instance. If it is errored, terminated or complete, an error will be thrown. + */ + public terminate(): Promise; + /** + * Restart the instance. + */ + public restart(): Promise; + /** + * Returns the current status of the instance. + */ + public status(): Promise; + /** + * Send an event to this instance. + */ + public sendEvent({ type, payload, }: { + type: string; + payload: unknown; + }): Promise; +} diff --git a/apps/clients/wrangler.toml b/apps/clients/wrangler.toml index 13aff9a..01912cd 100644 --- a/apps/clients/wrangler.toml +++ b/apps/clients/wrangler.toml @@ -9,8 +9,9 @@ not_found_handling = "single-page-application" [observability] enabled = true -[env.staging] -route = { pattern = "clients-staging.xtablo.com", custom_domain = true } +[[routes]] +pattern = "clients.xtablo.com" +custom_domain = true -[env.production] -route = { pattern = "clients.xtablo.com", custom_domain = true } +[secrets] +required = [ "ADMIN_APP_ACCESS_TOKEN" ] diff --git a/biome.json b/biome.json index ef80f8d..141034a 100644 --- a/biome.json +++ b/biome.json @@ -9,6 +9,9 @@ "apps/external/src/**/*", "apps/external/worker/**/*", "apps/external/*.{ts,tsx,js,jsx,json}", + "apps/admin/src/**/*", + "apps/admin/worker/**/*", + "apps/admin/*.{ts,tsx,js,jsx,json}", "apps/api/src/**/*", "apps/api/*.{ts,tsx,js,jsx,json}", "packages/ui/src/**/*", @@ -294,6 +297,9 @@ "apps/external/src/**/*.{ts,tsx}", "apps/external/worker/**/*.{ts,tsx}", "apps/external/*.{ts,tsx}", + "apps/admin/src/**/*.{ts,tsx}", + "apps/admin/worker/**/*.{ts,tsx}", + "apps/admin/*.{ts,tsx}", "apps/api/src/**/*.{ts,tsx}", "apps/api/*.{ts,tsx}", "packages/ui/src/**/*.{ts,tsx}", diff --git a/packages/shared/package.json b/packages/shared/package.json index 2c58350..61dce73 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -35,7 +35,7 @@ "react-dom": "19.0.0", "react-router-dom": "^7.9.4", "sonner": "^2.0.7", -"tailwind-merge": "^3.0.2", + "tailwind-merge": "^3.0.2", "ts-pattern": "^5.6.2", "zustand": "^5.0.5" }, diff --git a/prompts/rework_temporary_users.txt b/prompts/rework_temporary_users.txt new file mode 100644 index 0000000..94d3b95 --- /dev/null +++ b/prompts/rework_temporary_users.txt @@ -0,0 +1,20 @@ +/superpowers:brainstorming + +You are going to rework the is_temporary feature that was brought earlier to the project. The idea is that a tablo can be accessed by the organization members, +as admin of the tablo, but also by temporary users that are invited to the tablo. + +Although this is a good pitch, it brings up a lot of issues since a temporary user is a special user in our systems, and doesn't have the same privileges. + +For instance, a temporary user is not forced to have a paid plan to be on xtablo. It also implies more complex permission checks in the backend api. + +We are going to remove this type of user, and instead rework the invitations into magic links. + +The idea is that the tablo has a magic link access, which is outside of the domain: currently it will be clients.xtablo.com. This allows the members to send an invite to the tablo via a magic link, and allow their +clients to access their portal at this url, and interact. + +This means: create a new package called at apps/clients that is React-based, with a wrangler.toml since it will be a new worker on Cloudlfare. This package will share some code with apps/main since the tablo logic +is to be remimplemented there. This new website will not have the left navigation bar, and instead contain only the scoped view to the tablo. + +Temporary users can stay for now, since we need to talk to our clients and let them upgrade to magic links before removing all temporary users. + +With magic links, you still need to create a user that will be impersonated when accessing the link, so that discussions work. From 5390028a5c629a750a658ca4a8068c077ba96401 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Fri, 24 Apr 2026 20:12:51 +0200 Subject: [PATCH 72/75] Target production from admin --- apps/admin/src/lib/api.test.ts | 15 +++++++++++++++ apps/admin/src/lib/api.ts | 13 ++++++++++++- apps/admin/tsconfig.tsbuildinfo | 2 +- 3 files changed, 28 insertions(+), 2 deletions(-) create mode 100644 apps/admin/src/lib/api.test.ts diff --git a/apps/admin/src/lib/api.test.ts b/apps/admin/src/lib/api.test.ts new file mode 100644 index 0000000..7ed9724 --- /dev/null +++ b/apps/admin/src/lib/api.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from "vitest"; +import { resolveAdminApiBaseUrl } from "./api"; + +describe("resolveAdminApiBaseUrl", () => { + it("pins the deployed admin panel to the production api", () => { + expect(resolveAdminApiBaseUrl("production", "https://api-staging.xtablo.com/api/v1")).toBe( + "https://api.xtablo.com/api/v1" + ); + expect(resolveAdminApiBaseUrl("production")).toBe("https://api.xtablo.com/api/v1"); + }); + + it("keeps localhost for local development", () => { + expect(resolveAdminApiBaseUrl("development")).toBe("http://localhost:8080/api/v1"); + }); +}); diff --git a/apps/admin/src/lib/api.ts b/apps/admin/src/lib/api.ts index 7db3ca1..5ddfcdb 100644 --- a/apps/admin/src/lib/api.ts +++ b/apps/admin/src/lib/api.ts @@ -1,7 +1,18 @@ import { buildApi } from "@xtablo/shared"; import { getStoredAdminSession } from "./adminSession"; -const apiBaseUrl = import.meta.env.VITE_API_URL || "http://localhost:8080/api/v1"; +const LOCAL_ADMIN_API_BASE_URL = "http://localhost:8080/api/v1"; +const PRODUCTION_ADMIN_API_BASE_URL = "https://api.xtablo.com/api/v1"; + +export function resolveAdminApiBaseUrl(mode = import.meta.env.MODE, _envApiUrl?: string) { + if (mode === "development") { + return LOCAL_ADMIN_API_BASE_URL; + } + + return PRODUCTION_ADMIN_API_BASE_URL; +} + +const apiBaseUrl = resolveAdminApiBaseUrl(); export const adminApi = buildApi(apiBaseUrl); diff --git a/apps/admin/tsconfig.tsbuildinfo b/apps/admin/tsconfig.tsbuildinfo index bbb6911..2e651c2 100644 --- a/apps/admin/tsconfig.tsbuildinfo +++ b/apps/admin/tsconfig.tsbuildinfo @@ -1 +1 @@ -{"root":["./src/app.tsx","./src/main.tsx","./src/routes.test.tsx","./src/routes.tsx","./src/setuptests.ts","./src/components/adminlayout.test.tsx","./src/components/adminlayout.tsx","./src/components/adminnavigation.tsx","./src/components/privilegedgate.test.tsx","./src/components/privilegedgate.tsx","./src/components/productionbadge.tsx","./src/components/actions/actionrunner.tsx","./src/components/analytics/chartbuilder.tsx","./src/components/analytics/saveddashboardlist.tsx","./src/components/data-explorer/admingrid.tsx","./src/components/data-explorer/roweditform.test.tsx","./src/components/data-explorer/roweditform.tsx","./src/hooks/useadminactions.ts","./src/hooks/useadmindatasets.ts","./src/hooks/useadminoverview.ts","./src/hooks/useadminsession.ts","./src/hooks/useadmintables.ts","./src/lib/adminsession.ts","./src/lib/api.ts","./src/pages/actioncenterpage.test.tsx","./src/pages/actioncenterpage.tsx","./src/pages/analyticsstudiopage.test.tsx","./src/pages/analyticsstudiopage.tsx","./src/pages/dataexplorerpage.test.tsx","./src/pages/dataexplorerpage.tsx","./src/pages/operationshomepage.tsx","./src/registry/actions.ts","./src/registry/datasets.ts","./worker/index.test.ts","./worker/index.ts"],"version":"5.9.3"} \ No newline at end of file +{"root":["./src/app.tsx","./src/main.tsx","./src/routes.test.tsx","./src/routes.tsx","./src/setuptests.ts","./src/components/adminlayout.test.tsx","./src/components/adminlayout.tsx","./src/components/adminnavigation.tsx","./src/components/privilegedgate.test.tsx","./src/components/privilegedgate.tsx","./src/components/productionbadge.tsx","./src/components/actions/actionrunner.tsx","./src/components/analytics/chartbuilder.tsx","./src/components/analytics/saveddashboardlist.tsx","./src/components/data-explorer/admingrid.tsx","./src/components/data-explorer/roweditform.test.tsx","./src/components/data-explorer/roweditform.tsx","./src/hooks/useadminactions.ts","./src/hooks/useadmindatasets.ts","./src/hooks/useadminoverview.ts","./src/hooks/useadminsession.ts","./src/hooks/useadmintables.ts","./src/lib/adminsession.ts","./src/lib/api.test.ts","./src/lib/api.ts","./src/pages/actioncenterpage.test.tsx","./src/pages/actioncenterpage.tsx","./src/pages/analyticsstudiopage.test.tsx","./src/pages/analyticsstudiopage.tsx","./src/pages/dataexplorerpage.test.tsx","./src/pages/dataexplorerpage.tsx","./src/pages/operationshomepage.tsx","./src/registry/actions.ts","./src/registry/datasets.ts","./worker/index.test.ts","./worker/index.ts"],"version":"5.9.3"} \ No newline at end of file From 3fd0f3dcdee163441a4219834d65f09e906d3c07 Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sat, 25 Apr 2026 09:39:36 +0200 Subject: [PATCH 73/75] Add rum + fix icon in clients.xtablo.com --- apps/clients/index.html | 1 + apps/clients/package.json | 2 ++ apps/clients/public/icon.jpg | Bin 0 -> 43486 bytes apps/clients/src/lib/rum.ts | 23 +++++++++++++++ apps/clients/src/main.tsx | 1 + pnpm-lock.yaml | 55 +++++++++++------------------------ 6 files changed, 44 insertions(+), 38 deletions(-) create mode 100644 apps/clients/public/icon.jpg create mode 100644 apps/clients/src/lib/rum.ts diff --git a/apps/clients/index.html b/apps/clients/index.html index 0c424af..ba3e01b 100644 --- a/apps/clients/index.html +++ b/apps/clients/index.html @@ -2,6 +2,7 @@ + Xtablo — Portail client diff --git a/apps/clients/package.json b/apps/clients/package.json index 699fa82..bae1419 100644 --- a/apps/clients/package.json +++ b/apps/clients/package.json @@ -38,6 +38,8 @@ "wrangler": "^4.24.3" }, "dependencies": { + "@datadog/browser-rum": "^6.13.0", + "@datadog/browser-rum-react": "^6.13.0", "@tanstack/react-query": "^5.69.0", "@xtablo/auth-ui": "workspace:*", "@xtablo/shared": "workspace:*", diff --git a/apps/clients/public/icon.jpg b/apps/clients/public/icon.jpg new file mode 100644 index 0000000000000000000000000000000000000000..026425ee2f33c0c373dfa9f9f5d9078cc80e4241 GIT binary patch literal 43486 zcmdSBc_5Ts|37}&i)>}dI)#cAxV--5mO{2WS=ZEq3m1Ms7y#m_FWjeQ1&J3 z43g|Ksxg=u-!m=ueLtV)zMt>&{r&a(9Ilx&GuLv?xz79je!X7jJ+t|76A$s6)z;O9 z7#JYv4ETdKCnQ(2khZrWNM9e?4?)lth?QYG!~|*#;16ODhFE^oA?ON&$RBlc2I*h> zFhUUHjz9Mgw1t>|?GMfg)q)LNg?^@A&umc;#0Fk5AC{Lt@|fXgoq>@Fdhz@HBZm*a zVEB2)%}oe;!T9@(j1OKg{aJs>`s=FTWIqZk1Jkc}SpV8?2ChHb%^>hE?PmCWHU@FV zKdvIt_UnBA((cWVnzKE85x47=MqUOcUWUy^hE&jPmLCnI5BHA( z+6fxQwq+|j2M@%^z{JGJ%)|oP3-~h1%l6$zG+1{S-ei+-;*f`zl+R(1iwokGHU_U@CG*?&~=n3A%}am~|O+B#=+&l+92e8u?cH51EQR=2Hf zZ11?Zy19EG?|b?`d=wBE6dV#A6B`$w@FX!QHSJ~ktBlO7*M&vJC8cHM6_xc3jZMuh z?^@e>di(kZ20soBPfSjIn*KcVWp<9Z^7Y$y(kgjv9n6BC-2spP)*oKbA4Xvj!8wwq2nB;`Qc$;5QsE+j-@>_@T|nyS#2zBOOFw$_ z-*w3E|5K0t=+Gbi*&K$pF)@G}#>5N3AsS6OH3a&(#rU4&(Biwm@aOhin!)Df`o*r_ zZ?SE5{XU@P4mB5U7x@5}zglbWND8N>xs`u|bJ{pfKcVzqKZl#kvA4jtJIRPxhI@Wj zzVKeuVx*7(ZHFGl;o%E#0?d?}hPD}VP~&be5jB0@`9ZPqJ>1RSUXax^_{@l?-C$O| zpU&FlO{h*Ej<3O$$x-;2rohV}%Dzde<3vlt#-Z!nP;!b|G zYJoW&e!xx%%}cMl!LNAV!QvCz97oWUBdfSfu`M(ax!Osdn~~F7GYFB%dUHXmO4l<@8nVm4b35BWNL_4O>9yhB>FiuEtK5*Eyjy)mz z+AU{(UcT+`&p_LfrO&Vsm4d5O@K`Pc65F&&S~rhNA8B>Ff8R}_fu)Kk>;9g2o!y4K z8V4F5K&_M54{|h)m`#Z70Ob}nt43nn8v-MUCZ`z@jO)jQb^PpI&c*AA={0W88tw^> zxkVzWT1dyHoy~9^yCO|CAS=t!xV8~t6h4kd4=^B+3n@NM=@h=6nIRANw<(y$-uj{K zZOXUuwHaRc=3nz zaPC9XTXV>ErhR*>I63b1Ue$B%5wVMf$;U~k94Xb3WI^}qkPN8VG-lceoY56NtUz)Z zlo<3rlG{`%vtv4bt1;E8q|xkV@{W~O5ohjmSFEQ!)vhp$SQXReHYDpVUZ-2)EXx$7%V$( zUwCO}Z4Ngnl=`gXUCHvc`2vTC(`#0KVCG-5cM-g5{g6_qJ?h`PUjwdV+@WYMlxe8N z_h7S|Zj~`FUT`O2?J&bLc%_9C1d$&Ww)oS+?%!6n&AokdBir<9x%}u^?T=H4toneP zw6idRF@`KV*a9A4Edj)ga1(v*+9c6vor%b8I(xs|O>t12EqD~aa+&Evf~ZepJtRA@ z2?2v77|Dgh2p70VFikW8B0r^+29cd|=7eDZu9x=Q2tV-I&Q|W$`EVCk%klT4sr=!n z%QJ-Lnx{;@mj)F^o6kw-eX*u(o!^95duTW~!O&o6S(}P0CTWuMgm+u(f)NIxT3nT-EYJ%S%1S`dsZ^)jz@te0f|_^}(0FUP9Vs`gr#J z+n4nYr^`5}tcaI@UXams_2Rpzz9m#R=?pa|Z>EpNF=w=pkM-&4oJgE@FoW9FlNVf$ z?%x{p`D%d2OU!K3L?mgNfREN@u=pS zm8kqxNzSg59}k_3H+&wv1B=IZ0^@B&6E47bakMsA;iK=(2?V3FZxYZ);*y#E40~#Sa-g-6BFv)y`i~!ZG6XEbWbN1fFZ_i=6 zWf47XZ9R$sgqYXKOyF@2csIYR z6b0&&Z^1`lY-CJ*sroMe^IpNZX{E_}Pv5Gf1?UAvBMv+@+$%O>>&z;6Cvs*STLvSm z`PViWP*YK?-e*T57ah6oRNh`jENqm&YMCJ62CzYM-|k&>h&A1v_I-o4g}Mo`_>vdF z^^(X7H3tZZ31(z;Zo4oN)4;v=WA3E6dbcAcUgVuI_4<PB6jz5-2uQ zzfH)2KEK&C`u0?ieTYhCy~W(TUvl+M;v5p~Z`K6E{U-Zga#q|&HfTF{;#()HhX>|hE3=wjI828+hRrJCfz1uCoyDcgN5%_dkYBd%_gyxn4p6% z&b7a|V_fK%q;q-R(n&!;7h)82lzAY2&GC}}cHF;FT)fNM^u;*Yxaru1J0`c&nd8gc z6Aa(v8!*4VcqTo(&RFN- zIdxWI^K<*`FT>Tv@g4(8kKYWe3VfB(m55hjF%#3>_VPxAETsmG#~YB9zBVBU=kxf@ zQN5c`5$E&fJc8!ciuVPaz1NX6bSi29} z2u^UsP((H+<;c*SYf#qX>a%zJgr2PInE??mFXSaDCoN$pGw8+s*AJkb{9T6EvEkl! z6Wjqbo<0hCih6!TyXzYWk#c!?QdjL4b0#jX=pBeSl`0VyjbyB`lC&g02g5!@**=J6 zrZIYJUz$2M@V)vdHe)0w#|qpLsSfoxnx`UlAG)pq#IG$_d={MVfciFXp0Z;YHVT{1 z!RACKRjWfKp^E`K&=O^b>m?7AcHdBMwvO3WuZ(>vygtgQ#C}%(NR%;24ovrUbltX^ z-KZ{@ptmgOkq|X?;bk{X3<m`szalMXdMp_F0olDXC8zdr#y1_dW|dBIVC&vCZk3!%bRZ z(%#@Sq_uW2VJ7h4?%r=y^_`13_V#I4Qv!CzN;$RsF>nw=$k(E6Xv$k(!{96}KH~rz z^k(l*cOnb>!yTCZCwCCWTemYOM4E|GkHt^G$Vz4ARDZ=qO;RQGvFqA*Ie+0W+U=B# zmda}sg`+w3WmkOEK2FMp%VouqLN@pNb}hI+ix>bgNVYt81*!Qr6J~h-_b9t zdP)JejR z$Jxq~DW4;bx5(-(JM&gpQ!DMP`eqK@KKq!KK?5wszXFYqLh)Ifv2H?5HG77-W-BGN zMP^B}_VDY*GuDe{0Br=(ny|bm4rJK`x*i;X+DjBo-qn-)tv|34H$*DsCOt`#`xb;x zCML^0J@A0DVY+QblJf0Ks*n|bPGAQ=?KOg6s}tTC0s?cSu(+S82SrkR-{8?&_}kCt z%RX*GtyMHd+T{{jAevx}TeK!A_`GL*Lh7?vLmU5EBYfT_Nl=rg!5wxMKp{R@_<*e)4+R7qU2{85c* zcKSqg_fFQ*Qb$`W@!O3L|9X(be>~`_!|#Iv*B-qg2%-03)i$AB0NmsNaFa&koE<c)GG2!-(XIbhU1(fIM_cBJWn zV%!KfsiF6FFOAFg>sHt5Ll?UBCv8(5>tfDp?~K;)KfbXl`BJm9+g?>^ z;_Vq%>Is8@6LzMiHUrW(0`_bbb!z?%XCTO;;Qf(JXl02hOsnggnqb56gBgLUO14~> z3|m5ry`7!CaML!P#uUj2GD=*_<0fpmTM>* zmm|7;uSrO^bzdFX$cF1<4~*c5&}OK5eMsAS|wiQV>3X zdz$>@o)`ayd&*K8f8t7oMg-s-09UpGPUu5fN7U&bnzEXnbO=E2FyL@H06-S=%_qBd z32oWlrcfY(AS)~UqLEBLXe4?8gH{J7N`x8G zMY0SLJ`wrw8;1K>VBUv`m-fdxM9fM(1mskY;VLeRU%K7(q>GSfU*6ieMlxOx1+E*9 z;@X5BCeXGjTIasLMfPeru10cNJsrOqkM6*;Z$gJc=G*sd#L7J4r-h-5bSOeIAo#Bk zGwKoBytRmBO?iUI+IbWEoYfIkHK$j@wh8LqdixUXYdYpMIjleJy?A!AW)mXlP=xKk zagKx(qg=9Oqxs&EzB?x0NAIsw9}c6QWX9X+v+brC6&r7CC0o)s$AGaNMxN~(w#6_M z+s4IaDV2G~&EE*SH>l*y+t)#v}TWy?pZiz?bD1WtR z?{t~S4mRa*be=gxa-gGy?HY|nVjJRiDT$|?r$3%&vjlFM&f3&>QT-Huu(n*epR8@o zU2yqlJZOI*WZgRyar@z|Mi(i~<+M#GgDp^12hgycNK{Kx@{VeMqn_`|l9feoOCDSK zA@}?Vp5=-r^*5 zi-`Cv1AIO!x~{H9f{LYR`E2Y%wGOTdBkIf!`6MI+R|-+|RSz~sa|s>beQ@~XNqL?< zvDOw^;BM8m0~CS@!j{0A4fxP?a1>UrSr$}-=l?p=TJylwK=-dBKmgd-f9oD!B1#d#!C=PGc0d-l5@xVcE_ym@F zSl26aPOxyxi!#66@g9~RT_NZ55Ob95bo4Pe4~Tj*d0f|!p|mZ}iN3klw(F}Ei@ei| zQb&G&%fHLILfeW7$4}GwP6d0`A+h*MG!Gn~h1v0R!lORxkSom3T)6UJy6uN2pZhZ+ z_bZBg7b9YdYLSo58!U5Ju8rqq*Isa)U3u4hj+O?;<8WkU?j|(hJevO+?LE49db*>4 z05`5^bQb#wo!4>?##$wR__$PFX0Gu*Kb+23w)`Dq5&I8}1x;{VrZW~Sov|#!ZyO9d zEd3-blPbRmi&d`u@9P*wxg3y0eR~RIh_7CR{qkSXS@tf;a)iJ~s9i`vS>z&I0cFt| zI7p`~RewWSbn(kOkw%k(kB;KRkUI=Z2acLq49m8Q%&Q34d4=AO{X-|&g%6pPo%z7M z0$79p1G)}?<44!2P>ek`^l9(iJ&w23aazpCpH|X$0*>J+hyA_LqM^59rK_Cplmm>g zmLDh;gBxwghPrV+@}miTo!aE%z4j&Hf>%qUJJy?5_9Tr@j$6q{U2Mi@r)BNR+9`o; zFQRd60e*^!97)?+G5HoVY)5h^dwPis%Qbr>ts6hpkYLRDu(%x9wvJ`#Fn)z=ckJ@V zuRg4Z$j{W#RRH(IuoMv-FgP|K=`a&H1L?j2@xwRF{Pqp+M_YFaS?9Z}B=LWiKUc7A zSr^{>v>{m%NWEdIKiqrUyQZKeH0Go#)AG4!z1QI1lcgWonj^up_E$yv}m;m!* zeW^VZHPz+BVzKii{V1IsN|cK09d+W8zB{ltOc>>oM?s8$EN-;;9RQ6lE;(r!?guEzLu3Zf#>C5Io_ty|ckwxG2z|x0ozhT2fLPZV|A>;=)fG7MQ|L*S8ben=lWhm4=nY3R*c_@kNd5MoGpC(ld!>l z6EqVRd)52bG?P_Fye)5Hkw1!~2s zq#E)3@&LUQTlwpne9>cLW=iozI-*bX9~K@uFVBsC#DA}@C$ussmwy9bJNk?`QX`KV z$CMfS)AraVc@JQ?P=fRE!plK!2^aGn^Wz+HzL8DIONY!AFJ`}Y5{Q~&7ios$fobZ% zBM^iujuDy-@-Lce+t%{khb^QK{8n+2q zp?xt09wJaQ(XOYI^dOwU>`8EEgbAl?X*GFXgzM z7)?Wgj*X7%V~z16Pl|9S}jmg0UEU2$#IRZnyLrC z>PW0)e2hYcrY5=fGtgAfgsYBZ$<7u7vQ%e_(FA%&u-kHA(zil*fa>|jld_o!n4;^8 zYd5POp$Bxj13O`D_pp&}v}sI<$3i+mmNY=-&qZ}$ip>KBswcud4@Lu+a3HD;-hbV+ zbu}efU@h(OeWQgl@M*A!#c~wPXK$=S=SR7z%QSz&a^3JU*gde!IiXus>&5I>#11A{ zya?I;qIPMy#!Bfl@4Ne9kK+(&b+_5|;=K~jszug$(n_%SaST~0!-QH<@?443K+XR) zR18j>1URIe-rsV_>SYQ~1C2A0T(NPAa;lJ;3c_RRIDelij4-3~cwZ5rBWuUd-0_9> zuloU1OB!x;!XkC|!uCTi%QqoiPHxR^?<1*0WXA^gsM&RQ%r^Id($elX7wWd1-L5

-#hUi&&IMgN4_g=Ec4orabg7Utqx`OJd#;_S zV`H|!eu(_BhROQD+k*N`U1A*71>n^(`<%G~+3wAmucKraz2IfHgRGWck2;-vno&^* zU-|IZY?A2~M*5lvuJ*Rz>RxMU5=eyp;)*?y_LY z`R>mrkewe$re+Oy%L?;G4c-dVRtypts-M!f2GT8(Hi|3DXb$C+o%Hbkj(fBTaoO+T z&O!Q{<;T}+vRk?edkgA{i~>`+?Dr&Xqeq-kX&pmrhZlC%;y$+E-2*pHpgJn~)M11g zU+x5EUgs5+&$=^Fl%7sm@18TG1*BU3i1&QP2UvCnZyZ3i!JDuR4pErj<&d(&n zM_o-##D$9n+Pdeoek21iyaTfcB;`Pmy@RXsMV(W-Kw`%(HvG>lAo^!FEnV)>pZ~d# z27cuEK)nb5d7pp$Wa}*}7fbLd0c=vv;Nl=fg%8yEtbf*}>2-^rbya%Z!}Xpk*yjSh z?tJN@CaB*6b!qFr)Ghu}x4h>}-#-lOqiTQGjeae9p(mDXvvRm>1fI8mO%!s0E4d{62H1aUuvpwiAi-}`e+?%j00`Qvo- z{3yoTAUkR$1A;iOLC}sa2x2$=@fmpdhqmnkABlo?If6fH=q_Xh?Sgb62gnjS1Zwio zVdw~SY;zG(zF_0%>gZzQcyE`&p~H~!DP4Vfx(~hlsPFkv<>?a(8;XPqnP(qteX>A4 zh5C_E#Q1>m!Cy0qAQ%{*f6ge{Y=lbw7iJZKX2bqtW)Zz#{~NQ5Mj%ZHWTk-ulGB)2 zKx*30oHW)gKT^`Ru>VL#+rs{3_|3qEb>rq@n*GZ%mtA{|nmK{lB1%J^u^Z*!$nNF>f~+OYEHRs6}&>h1ST}<=d2= zjtjoNl;pv5Vt0`D63Rbh7ZbX%3HSh7e?e# z0Xu+wN|@S&7MX~Gq$sk#2a#!V&uo(IRz1^8Ql>*ApW*`e7ua0-Bc%qlj-NOAw!?a! ztrup0Ea&*3P}H<`1nBtI-pU(?h*>Auct{P6Zr7=>MDoh$CE0suHBfDy7*3UXx5 z$_i45!goy#CQ*(9Sb3Y=?`Jt)djS;cAg>zq-6$e=;ztf5&bc${ZLlDPKA(h zBz0ZJAjJ`I=-q6c5%pcF{%E z|9;B@Ni%nsM^4ls3ekS&B8;vOb6*}{|3r&_sn#8^GIwO~bDbeJo#1qZ9o!<6Y-lxcqvf8ulOtP2buj%f-jJ(?A zdRpT_h%#i%Vjd=~C5H^??6tw-b1)?hV@}9zNal?*4>R+fJETM(T9SHRm`)=Dx*SjoDi_OYf zVzF)>U(#?;#-hr`dCGBWf+~Yj7{v~bx$jh|c0xZWved*(q2UF_SHBpxAvjCO+@xF&GS`?tPM)hLS*d zYmxntRu$!Y>~k()iiS-6R~p!pLrx^WaW*g^o|Vqimx_A~@^g*oVU4M~hR^#d5m#p* zW{crf7rWzZ>)D*R%gRbc*NB{&=&9-;FJ{0DGq+psq(-9e!Wd}-;%u~@o==hbMDr(^ zmB0oz-d&H_6RKLpfQYg+a#LR z-QB{XfAeBe^jDb^u+bcTV&?*S;|3W<$|vZMlAl=idS8Ae!D*^1m*5*Ie)rn+gv;}s zk(8OdkNwldy+zU>_4p)xCGr2hA$U_$@&GtcJymn%9fZ4PS{y#Po55KFDyc zeZ!p+<@XvXbrcwu+#+Vf2Dy)9K(IN~Jy&zAzq>ghohhb;b#e;k%%?o>zk5Ol<_h(@`gr;`UW zA}K5`y}Y=q??A4jeGz>MCn;T4mZ;huqQCb|Eo}g6%?Y@^1X|QFSxqNt3%g1sz z%%-4%>2t`16CT=MrXG)SzsM#(r#?s9c(ybwiu27 z#)6nO`~UCOlb3|G?Hu-)zyZUdp@ongcs(EGTfMFyKl-GudoP-FKO^2bLVw)LoQW3AFscQhy?pf&<#yaeYdw(jgp|k_V|IeGi61; z4J}LcS<+9_DL&1@XLyb=MEb?=ja!FoNHlGMv3R?^0vEfVS^D&iZB87pARg+MmxxIn zQGP|LHL3+y%IycY<7Rx7@#=05#rRdT|CJuSB^yLayyyy{Vk4)|nk^aIa@kX^J~E_6 znJhb1tuQIqFs7}qaIFXDd_1P~w5sYwIi2tp76aD&EPdVkvCkuy%tOe7BvooYg&v#u z6~&Zu6DP+MFT2_A8JP)Qzu%2U3C?9?su;a%-Pm7Mn&fT;T7Twu%m4ma7Pznx9a0y; zdLad0)OKh5SbtP*LV5s2z1wMQx50-FXsNBoeu!b;V#l`ZaLUu>qf*-+9YRLBnmbbH+^xv`ILUiVvVy!B07fa(u!=I^vj+*@3|N0fg-I& zjMfY1&Z+Xii@dnb0s@8P;xVP2ts$2wBqeRp2=Y2RHn?+WkQ71=1lp)(326I+L-({L zstcnqMdKsZ2l?9Iha2KlBhm9{k|Q`DjMj?)fyWDP7bR8Sg1)i9+4QJG-6ox>%+(=G zMcn^=wn5z3T@&lBSVJwBus^><@$ag~=D>e8n!F^m?Ir{)2AFIKVZ~7x*@h@a7*rlq z(hsjqCQXU%kDSox$L%y+I=OH0#D)Pyl^S0IYoCG%>(Ah>vjTu8A-O16L;b6L7>>)68H zCh{tAev*4ph{y#p=Ne@j6#MIB?e9LMCU=Y(v~Sz*DZS(w6MbKCvd_>w^-4DnxM7F? z4i2daP8c+y#VGv5jzl8ZU0gf}4B^@>sKV|a*+U|RFk?mmJ>-u#IllYA?f z^<8_tucfCR%6=J7{dBG&IJHxb>DffUJ>*?cYw|*#7Wp!;M+8gNujo^g@MbnwNbJ6@ zAUW;v@#D()tT|cs*uI2B-H){CFL@DgOWX(tSbZr8^kYqb_2e5)z}D$Se{u90@+$Fj zBext=a`?!D`^~79yo0ZvCu(T%UHk_^NcJLiQH!fYHujNKGi}@uqH|pZJ>OE-l&7_t zYKhjk$kXPe6T$bWY>nMNj@^cv0Ts4k8=Lh8$`OR-}yg z?LX~Ndj41ZIShN^@cNz>QjssoK%0$Jw4p@n1`FK4c?Y`Js1x=y5AF;BCa2zQ>CE4~Zu;u>?Z_baWOV}PklC9oABzRl2Os-q#qxQ-BGB@}#KsvA zfHKr!byIl^*C%@KdXTn9{R}{_K|m8#{^Y^*K1;W076c%=p#P5$j%jo7pKT~F32wVQ z95^wvP=ViCg_t_==;?)WV||5l;eo?)4$#CUG&|Ez5N5h@0o4cN21^duKo4yQLlk33FBHmS-turj0gtx+4Fp+Q`EC{p4SYCAr^QWP2{R_v(whEBk=TKK~ zA|?!zt94sd_EyUDID2?)EkLPKJjuZuT9lJjS9AL+RC zC7;(vR`VIZiu?DN^FKW|w-!KL#?4^Kpz22u^2w|LK`6Y!%%ELDX*@)WCgoITG=O~r zmc~{|^#q+oOZ=t2Z(T`<(4+6V?hG5+f8hA`_2#|=-_9{LZTIB+@D?*qIEX{z%4C_J zap=QYeTAza4i&}}(&JFxk2u7(@@Bu$MRTj`v}v2Xa5S(Z?jLsK+k2rm(G}QHP?D8{n3Rs;0~fdG&=d`W(;C`Y2acCzHW|Pv+j}L(;TZlH4*m819A$ zQdjG{)$dkqVRYc@8JC4j5T2yj0sVnw1M)6DSLFY!c~gt;%H$uOtiaCB&BsaXd90k1 z>U)04aJ{z*?vS&-D~gRE7mC`0%sx*r@GY(=33t34tLbPDwJRt&d+v`&4~DiypUj)X zlBB7RRCzZJk?)8(UN0*fpzTI9s*hwA2AbM8JoPeb_@wov<8Y716k}nQp%&L5JWdQ< zi&7yx<26HOG*m`}Z`*|C#z{SPZs^r>AunkBAos>&62U?CXgk}8kf#J)wbACvw@~pKH%Gl#>&9o{Q=f~8xHqB$!2+p*gM?A z=vr9eU_-07^^}m-2Ws<|;;~~&j9w#Q_p+&dVrIlg;-45XC2WgYgs&tMGFmB2)kh#yY~`(UEKLh|pDy?#LEu7|`l7g3w1~JVY@^(;<4N?HSr<>AyG#wC^TV?D{$K9PxIdFxt+RWra{M)$vf= zoXxRvbZWQhGwX%dE5o)!u^>wQQc?hY0R}&!Q->`?`v<*0o)@8L^JLb<5apFwUe4}u zfW3BIXv_W#KTX}TTa2h-SZRVE@Y>w04>|?1r+iG5Xze||ty7Tznl7CR6uWmzb)PmM zbHF=1o-znE2j0Pl$aE>ec;LJ3xgvd;+2o+mZeF%6^b`XY7%xo<**iHH<^~g|ob3D5 zUy^fCQ>yojr{{j@2_7!Suz&In^QxS9G(Sa`Xr72iGusx<4G$E^*V#L=$KSRbU6&Tx z6A3ZuLKn$`wKcNjgvl|5+VL&D>HTgw<~KP@sw5A*_l)`Sf>Bo$+Nwx3p#kSu!2Jkq zWw0eT{q=nlY$K=15o$^%%i0a2&Y_&5cUrW)^Sg!cH@3aLWN2=A2JtbFw2OdQ$eJ)% z)Hi7Fr=YW&vBSc?7p}0hP`pgh?uSud-CPDAKpUS!WLxda+^-sctp)+)O}BR*jG{c) zfA7%Ik+<%SMtp5k-|ot!)bYCYiJD9T+*5&J4RB9pGP^>O6W-2iHP)Hq&8hi%u^uo8|cCHsXx5?F9{F6`8V=)ULqR!iBNzc$^dB-eF6^ixh1JD{xoDpzj+w6PY`+L|Yn8uG2Duy7Y38#n$P@LkEd z>*$DSFDi=$MB=TmAUx^?d$BP(-CLTRlB=u_t3O^crDU+b*}d~q$y}w}g3HDwq`z%X zjR4Z`vO^e2UK_L8=c_Y+@l(PDb-UD>rEWMr307KK-eyU5B^j0(zwJA)YvlWt@~?2I zJi9J59xQ2>TzSo3Vy4;PxgS$iCfNIK>dUUOSlGr=%rn7@Z%{^thynCwD z4y8{l^M5hmUKUuG_hLy;<`jB$-Rp(1P;afSJ zA9C7uPKOU>?%IUZ150?HnZG~a(r2i3ZTGL}#g^*5pPV&?_M@rvq9nZ4`Vjg9uFazn z8Pl$CPZ{Gh$q4r35;|GOl)?a6hcUiN&sgZ8n7+~mWIfa>6_xBNwL(zY$jIy%n2Djd z52kv{kh7;E{l-u9&?G2oeVB6tt{L?6J?7@-3+J5`k{3RTdy9`^0wO$M}16Y zqh?dsDs8f|5}cKpOh?d;OP@7Z&Y!0RxDfquaU zlFGtMZb|C()Gc>79D-LcqVC>fBgzLKTX+Dsmjm)K4#>w(Xv3Id1t^U zBCas2tU4bHqvIj(Gr;4?g_NVh19ByU^8Mo{__ z9ktTYQQXb4QeO`R1rN12or{eRSao+9e|OyAMKy|Vr^cxsP_);V=&#u|*Ol3)DC%&P z5C7EeF13$sS&8)&D-zna|A)teTX28$ug4VTJ)G)yyX=3N{OEN(Yg*>(rK?Ogp4wSx zpT6T%Q7+FL(+q9Qg~+zkT^^7R9>}g3(>P$MB0yIPJw0G~y)EK?(P z-(O?ZvG`0A9-xp}JnZXho=oBsw93Ydj06z%fosTgFw++A8Ao%u4J@g zPYS^7hS?UBw;XA!dG3CAg3hQk2Z`_vWmLDiDm6)c&sB;hL3P8Am;ZZc0gw4`LA&Np zp->Ve{aIkPpk$DUDdUE4wn<0-X?a`E?}Z&9jgGg}H)XlI^te2_%0zvH0h&G{j1Zd8MyThU{SvdEp9eGd_4H;`r{D zC|(;J;q-h_8Erc(n3$0_L=wj|qo8fpv)dXw-l% zkqhJw_Li6EK}pyi;k9)?d3D*+u&Jc=8*S>lQQbRLR8Y76vFBZ|dbv>VJ(C8E2~i#mD)*_wS}rBj+o&-_J~j}32eAzsta>R69C{~Gv$2MOcq|>{V%x6FdUnJpXt>$SFCsskf3e}g zmcqP^3eAkm3)7s-*iv3tIe*P_w($1;88`tc#>0RMano z8u0H3^+_*0yK@8%R8M1|dUjW*_IulBYXg_yc|k?h32;iEcNeB|w*@}@(u9tQ42Ey_ zwj;VUdtxGKyXK3+Mw0KT`zoJ7k(-vpFDv>pqbqOnoGcMf8bHD@QStB;YAFEg_+F!Tuw?G86* zh1%MkmoihUnxjySumZM+06N3j(YA9IYKWHgDmwr(`B`pUN4J!ety%)FdyRV^z>R-( zqVxbD`x!Q(qbV*)ja8SOedVPfBB=@6nxvtS$h*`ld z9&*%PV7J$+a_x1|~lcU!Lmw&$*-NlNW&6k3T4bW|O69huPx+k|Qh zt_~Rc%fNc4`3%i<|6sKMAFyry`|3K=+BC55PKs3DU5X_h8y zR6GjO>az&4T)e=w7;#IZ>r-Sbk&-s3F@fMm27;{p-YT<+6Kk&3!0Znlbhv2|ttBDq zw}ocb!XJ0`&Y72Jk67awr3J|i52P0`%Tjtd5e$xUh}Y!&c$$gKBCqp76b(_Ke3 zYij8ml{YoX{=^ITLjb8Y8^;-mhf?t1%Tu#GvnI`P3Yso-FEZ*TK2aXsVLd?GHMVOSmzd68%jX9^ku;v9FLpLr8~kAN(b2Q9~&6jDDYo>>c5*w z6=LPzFP-udR=~XgZrqS@z3uC{R@NLM$K{8dI))q-H#q(5bAp9ofnxDzLfhWX=1wR#TXWx#J0b zV<|5`^VQSyU$`gUPR`WB#VFjw&l!Z7$wNu&4tcNCdv>ChY(|#!Ib4yW&O3dSclmyf zqeh?xv4t>Sv>i7?Yuelk+hpn9$4_Jj15JuQ=?%2&!)<&)@?i z73BiqJl|$|OMDb-ZfFc0uwUI1j*U=a+8tOvw*|;YJO==S4JMG;Zrlmqot1$D@^wF2l`ItoJR-JW1D_iH6mfr6WaR>}H)Ew>ihBz(p;mowpSRc)r@9%y8Mkc? z<-9V>6AkWzIpDwT@{=9NFx0&t-Twok=>AJL{*ZNU(`B7M0`$MgI_IG`;T)R%-ugKo zksg|5cGWsY$tUcP7p#)6?cATa9xc1xMh(DP7;vK6Xxk!<2euzHnB*$pIUY_BGIjHY z6^_KbJN;#G;1meVLLe{)M1e3)*K;x!GA7`Q`sZ}A!ME0p!_mcxj4$4B0Jb}T8w*44 zaC2$JL+b0PAuFc#V}F~61doK1r2|5#z8lsQ!-A2r4_LotaqQjVfEoDO_8PgoUhun4 zfq~cp^j(e*dbe?lRKasK9qObeuXCHwry4jrr8&>yX_X=U=5|H>#p0m6n`A+P99RhkJa15E*jrzm^eRyjzckS^@tn+c=17hjXK?A_KdSdi93Xyh|0Ae2gx|olIVt5=~bB zbVrx>#g`+|AL5lSy-s~oCaj6J!VK9>tS%G~)?r(b+AQV$4t}k#=OVDPf<;qV@CISm z)1nNW2d+i-9W^vJwSQY!A0qvd;kUB=0|Wd+zCvCU+O8A$4qQo~Z$#vqyS=IguhO3H zyRx-n@ssMBGlL%x1?DkMAAEeYjt+aAM04TYs{_vP_W?`_zYLYpC^ zY@;X@QX&y1A|we}vQ34Aq?C+p#*!>yEKvwWBGP2fI@Ts3`@ZklGDF5NOYe8cIi2&I z^SsYr@B4?(Oq!gdEY8Pw~;V4NEX7Oq|t?K z@cPu5wJY^X`3;fGBHg_H2zl*k@FW2VV5*8!L!;#W}^)x3R2TOPnUBO4A$%P4XAzo z7715^Ph;Z;&`bn%=!zUgQ1@aE>HQmrjt(PW*PZAvVjqAJ`+kQJ?Q|HyKAA zH4OAk{56C8VUpsb$D+5HX_xOl)7@@uX1=ymB|mX;x^2~%;Pl8-XBf8IUWkJb7Jn+@ z-SmAKxl@H~`kDg}kc&7g1%j8~w(G0O+z0Knz3{I9Vg8OL9qL5CaX=NotI1x5%(yLu zu7@GI3WJ?j55QJhgK1^rq%o?`GGbp6^un4>aG1rrP_w26Ltqt@d9g&8z6T{<$vth^PFbY7JUPXm2Qxu8jWd|v^J z-H^DG9ShQJ>Mnb`O4B~EWF}1>sw1r)p3?*-;5}9&b4X5ni1_^s%iGVcbO{3m?s$YAg*4o40ra_xO#pdIG<6>aYz=3b52T}pgclA!v0El9N%kEW@79CMIiBXoK zz|K>{pw0KVx|h#pTHr-;A{K^S(Jrt680Ui?nE|+t*X!fdenL`_j1-s`e!l+W7oebZ zCFO|upzId_pm1QYOB7oN6nc!2gO|awduLe zV0+`MZEF(wO!ATf<1VV1S`16LX8Zgac$}MoK$E!*)$_i4(>OgXMx=HlAT`BkKMFjp zKGlKmVv`f-DxOBla}4`JCVve)Y>)$}4>&OJfbE0@Daz0X9uLy7EyubYwY!@^8(e1z zu*A{_LNkH#j#OPGbPx{-%7?Nds&$`fcRq-X+mUJa%mH`6g|+Xa5}R=FvK>eX`Bw2@ zk*co>upGpinvfqgvVev`T)ZDr<1O2Qlzr0FU|+F?cUAWBP=pY!1`1+d>{+l{TrbOd*Ua96S{9ol^UOC zh7Q0&?%Zfc9<=8exqL(O$Hxf)-P7N!aVI``#eQnA`6O8)EJ*f54w*vddQx=oph=d- zz4g>=e|hH0_0iU`dp?S^9M>>qQvEe6SpDNNjDzLjPK>Ae=$RfDNnO3@siLBUhRAyH z7r7^ev<^M15fbiFG|n0%Mb#9x*}K0<71z0c|4b|}`;?bxa66Pe+X;pqy9Yq&&H58p z5g`B-C<8yKB#w8=0u=eS-tTMkg*qphg!2laNVlQn1CW|XZl-Z2kXZx?%*00|KP&vy zNXHY4p#jguFDi?Uj+Km430QwFk;HLt>5Y^D%fVI;^}t6cLR|Q#aEFff(NM#VgO|n1 zJ~BtqYOY0!s5Dz0jF-3zcI#K~=o@npjj1upLbQ4)Y(Fm_;e)CmX3nTTP44P$0 zf=&2O2_h;L0*kfJsp{%H69s)G|H?&0{Wtmvy(nM+paXz{s{#uE1$*ebM{S-7v;`~;-q$j%f0u)$u3WDx7iIaQsg|%NE%~JzCsG^%0iy%ZSj{neoR)gUv$PL z#hAdM3d+)uMR^|3h@fe}LkjARwO?RHSvlOpr6J;Vj2*>|4I2u+S3mC$v*Z-zVfUvqN2H|r6u=@O7)edsDA8cI?J!+HKJGrNq@Hqf<(;BL$WvQ2GRj@+a0Ia>#E-`;k z6TBUq^G7vH1P;y9@*Ua~Ej~w=iGP-P*)?(4MM~)PkYJ#a}~-%*$XXvG*@S3HL>t zJqfYb|B1APsn;bPNt%lvk$M7WTgHaODMgwhhALwmA9kJa&T_T7EvL;rG`Kj{{}~q% z^58V4y_n=m+rER4Ta9AH-h}Tpvv<{dpEcUIBa~maK-4WtY3}B}y;2t0pBfrGuDN%H z7e{`8ewGAdrpo8*r_Ge3oD%qncUo*oDEu121scQ`VzMJb z)ZP3Ntn1>L&l(^joP$2|qZA|jYWRkNmrE9QBO-|w+E?1&xP8BK^Twh!i1HIkI&zj> z`AOWf#)BdRp1I<%w6_lPP8k0N|Iq^@$T`~qYfx!#*sfYb(lmWcn*Q?L~;DR@FTtIXY)U3Z9>ike6lAEhe zH0lSH+c>80&fJIO;3Iz!O*aXrzaAO?jYmQc^3AV}<^i%kco1z_PVc%zIQ8P)+NF1X zD+PNJo{gove52VMenMa=lSMJ{CDqoP*-_vju#!Pym z3%qCZx8-G7X~)_Y6cy431?vODT_}U04^8v)Bf7l~XZ@;_k0%Q9k18i|aP{W0jkWWf z-$^W*@hG*5{(9axZPCwIh6?s3T4jFvt>3M4OA4+Lbap%+*AU!yRepm2+)f7jsFmZxs)hs65A=Oefm$pl8iL<&$lZ9m>M}vhZNO@!$c&JH5x1 zeNK&jq+t%cN7?4+aG#Sdez|;O>ot4eAoC`OGwEvQyW0l@Ek`F0KU=!VLs6d@;w=}S zt;H6U+P)k7K642B(S;K7{5{L)eD(2j&BCn!3m)#dMwq3nBCfCtG*gzeqV z@}s0118wiDjPfJ(026I2BIyT)rwcax8gMl3_%;e)IbW4VpdPn=Ar3=RUh~5UGqiKJ zGEH3ijbU#c9cbI<$p@!Po?Y^CGQ8egd5u$dOd=3U5rA2FH%1QiUeUo_f92fPivdHB@nz>64va!0KZOBie}_&K=6z)j9GK0jrK- z_;E6Ipbq+!0BOYv-O9Lft$1rw%Md53(g=3D?4E^$qQ>=C?_xneCwQzonzgzAU5(fM zIFc=HXg5$a=yySDk~m9MJVqsTNGAsyT656qP1}{cnLY-KtFvWA>{sVDTn`50W#EFc zC8ZOakFs)t^n4$nMy1a@{7Cyg-S`Q%C^ZZJB8$=nK3?Y&9OhBEO+k4&J+#KI*PiZP z$!txuI`jOlVtp9=R&wytg^ey1(*W;VAd*^Ow!3zZjVx66J(nLdIa4bc*c7Dx%2 z65RQG@^n+~@xG9cwSeS98w9zpGl(pAYspiQgpzQ7R^xSnEB`#md~$oabi3;YPg8Tc z_ckq#y`L>^3R;dI;vfZsTxQU2WB2}!?S0XlFH;f?xJa!uhc#N^Xqo*=4N|oHnLZFq znL5PB_SZ?|$k*Mps*{ZX+ba9R>!fr0%`rTK@dtoJ_}7t$|8+VN@w0?mB(z;r*&KIp z(#IXrnp>4wDI5f#o?|7j{2Gh2AEUXY3J3lNVz~pR9XYsl#PWlVSWp157;YjKoEW-@ zFH-H6!cOa4n=mjC&XfepntJHwKTzhvzhIg*F5Yn{GvhOuceJfVQBI_(0le}e`zGvi zi@KZ6kP&^~{co9!{(Z)OV!CW*vELst5hw>t4=+G3C?EEqtVeC7T4^E)V#Zen4(5fN z%qIBailZvSsU@3HT7G+Dq5FpjH*fH|?f}$O>M2FC#pA4TnLTwPz z5!8KPa61l4HT*diROqD?T4S7I5~Liey(g8xuOB#Ut!Qd~>2%z^L9k_v`J+T{rIurz zLN`k^5g{uT#P{^t(Qz%IXI$vzw)ENk(3vsVg3xJLeOjQRN)`!YR!$HLlCo*f*STPu zI5~L}_;MH3pX6$vjI!)`C8byJ0|Jt2}g}wW3-p(p}y>E3Yfv}j& z?h)0(D9TKAM1BG8i#U4w4j)-W=vG}$?aXq`(J{XAfN2y|-KLH1okfe>P&1~Vj81PA z+!*~~ZFCvL9+iq>Z+A#BDZkD5>?2l|z^X6ZCvq_%V%&erqLwIC1wipreI@jP%g z(I!Cp>m%wPC=Gv9>EG{f`g2SK%mEATae8wiiggkc=h^ZUPf`?gY%F5R~i$}u3kGkhod=!yPeFk`p&V44j0(OJ^<%nu?69?WSRx%KDtm{QRDC_B?mmI)4 zwQmP)yBEH1r0dawq74WFa~^jM(p1V2V((Ifm3ShkQ&Cf5BBzxyUU#@a~o? zv=BGHl1yvt1s;wNWvH%DDge2U=9wXTqWMF%y_vIF5I{Y-2e!M%+`pH+BPCreBR~S3 zY}#Fv&Kt!|PP$5KOT2e(XmAsadsv2skv;jI30!3pw%O=Z8&0?<+R?ij*%gqW$cU~ zN4yn1|6RO_ea=2tiAs=CX$0mPl#Wsd5XN`!=%F{PdgMHGDVI>r)J)N zfx^|UbM(U)pomO536};)xUTEk%dI6zQbvS=Os-wx+PlJZp|?Kb#J3A18H?Qdq%F1R zLJ$Y~u<~PwE(4O!*!%`Xf9X(clS&I+`n8vBT^?p!gWl(9PI&*8z>HgaTKv8+^NUT~ z)l2t!^jOu@_FmDeU|`(TQ<{DJOB`4PczZIB0y9RMWLxR3VI64;xLJn{r-~C>-3|9h z-R&uFt-M(ep&1dZwSWr&xPB!5ia7e#HuFNZSzncOgRZ`=`ek_uO*&cEc-e)#8(Cus zp*}4=LVe{f(oyP_S(T#So*f0a`6#W}FGJoxZfioOtavH3wL=TfUOS@P1W$ zjA1-7+EN0DuOmDQhf2{+IlijWHwqu?Mno$(+0!?jOdhdo8QGl`fWjze+iX=&R!E0vUF%18AWI zEYH7vInZeHAZZ|m^=LQo^ZOg+W1wb5e6vyk26_k0lDC9Sj((cg+`Eeyzr)Q0u$nIR ztgw^|U@VVKpZv=-cXJNJOT@rwJJ|z1pX33!kOM?wi5OPw=OIWoN^TMV5(- z$kiqZdhR9+#u9i(2Gb4!=`gzJsuq1cI!f0gpFWD9oR#&zV6WX^m(-uiL%_{>k*}|_ zffQy;t&YWxmYpz^wKxLwk3Siv-ob}JQ2H19Mc?LZ>RzS`i2tWbL9Zmhs`%eEM1QRo zq-P*1ay|C}<=63&=lO8HnQZyiykx4bu(>&ds{~thHxPb_MAC&{kiL_|CcrXE7;aw7 zbH{|b+!`WFUDy@*kTBKnI3aBCy*-47u6E3|hnbB<2d`W29H3 z)RPs7TifVlP*c5KrJOrsl)4jxUs?k~Ct#;r&}x#h<><5_DOSnJR}=PwN*&42Uej=R zjIbM7w!n>3j3F_HGm@byWRt52??zWabJ8AdoyVh%3Ewe$6~dCws|lk?!~)u!L;v#q zNJJI7^j30dL7yvq{HqC>z<}eKz#ht)2AG(=!q*&-(6;xvGkR|THtRirm7FC;(RLW7 zP?JVis^>lKC=Vp-I+b+IbsYroI|5}&F~e9UeozD5{KgRWFM#h~03p!!(v|E=f4 zscg*AU=&ib>ym}BS;vHQqfEelPzwY(Ij-xS2kuVh2mdaer*}5S*N3GTz(FCXCl3~w z5nLDPa*nHNMnrr_jAVOM%N2I*-3$V8PCkmPqYFXh5^bKlhAoacTA6jEf)f>9Su`{Z z)P2ifJ%(dED;mBPWsJ?1n$sEvpjEdD)yw-tC~Iuq@*rPKN@)G=WpGa;=gv~cDxDb> zw=#p#lJWCaNOwH(AUsT6VVI0~!fW^+Pa1FNF;=El1m-ltRS}!~OCTifBz;+ilyv z`ryDytTEdCsl_mzMO(aW{VI!pgZRL6Rz3~&!VKbdNqQqavU?@jc;#}6`+6!%Ub>AR zEy4DfXHPM74X%k%IFpFsrQ6qrf=XrIWV&2QoEhnw*;*_$-Vy(nC&k8u5}1sA@W6?5 zz%|Is0pU05pX{FXK0(ClThn2h;VhpVh0}QC-5E1WQc%VKXUFw|#|L3S681`YOt_^i zb<|}A@PY-RX?AaK77_dQ_{^^Hdq>v%17KP11y4XlET=ws;G8ArGtoZaF58*vi8>+h zIgP+`tW*`ZsHcvyE#{pwBOfB&KHP@nLO81??CN-A{0J#`;GAV`vZo};X5?i`bs}f0 zOjen4-E}7xtF)BFo1nj{c>T)4&?3FRx)xjWr`Gzi1x}=i&~n z!UiXvCP|HDNsWqCH?H$^U$ch=Og#A3a-mE}ZXbJ^@2*YJ!%1~dE3zQ6yPOS(9(GE- z+b7e+J8hqtF)e{a3_)jKH4XWYgTFe^>}zO&vc_6 zi)#%;c8@iE?E9jc_RZXvH-(e(0{DJBqx*iGY%fIt>fL&7*%_s?f7t!N;gMfbu_MTX zl#2vR?E;^@G7xLOt;?7-O?eh$e0uwt15#>g0$T+b%?1A@b3qvqg`=nt87w1-|I#y~ z&gGy-r#cBcb5A;J(Pmz5O#oUkT_!XGiM4i!i(>Hxh{lR<7Z(7KdH@)SN8(DjTCVH_ z^h3t=Vhqog^M`?2oHhCKMhC?!^E@msp9j?9yU0ezL^Z8XW`6tk3GX~ym8#A&Df5_C zgUyCMLfOFB=p3s0PDPK*^Xw^adG`8iLcetmbjp5rFRD|#t}*!FKUp)ZlTs9(lJm4S zYB)xUX?)uBYr?&xvkhP(Kd%D+GLM48@cO$rX0h2$HJK0gMRxXnoxh~u6-V4g2c1V9 zR#`B*?9^5;nBr-r&(;{JxwOWi?WJe%@ZqFKo?Ayg>z|&>BR~8Y&CPtzMf7@FY~YMV zo#KzZf|&yjOT4sgjiB;ajiptGij2U6oOZX3viiSEDL@>&ed?9N?N>&l2aro!c1&U} ztK11dw`CB(F8QX9I`@_Tn1UHkq2{~DI}rCl^WH;{dK@DuHhL(EbI&u|i7?{v(*;G! zN&UzS#JCVl?Qq5u`bJI!QBq|of)@*Nkzyqk120vR)|(z4nRZX#MSKp}!nx+x9KvZn zfw~GSgwIKW6*anA8WCUBQl09l(VF~|L9OI^&Y6v6GW6*kJ;yC27;?8F&1Z&2;yZ-0*WHgVMK-e!B+zYEwyAZ8cg)t2TuYg-c*}LkLW< zMy3Uf`=ZcCe@OWcahKl1JACQ|&2K|H9|88XM)1)v!*AcleA9f_eG~w9z9>U{ zOsac|_z7=3Z!;X>VLM@GdAvkhf#Y@GZ)c?;>>hd zu1JUF2PeW0WsO-Fo#Hck3f(6*K~}F6c*o}KWgeQcPXb$qt7!^Co}|ML-BDij@;=~E zVie`sCO>j^M2{6Tp^O>~+m#P_(u4aa1HXL|N4c=Q^GtCk2Jrr0%WsE0maz;BJf5E7 z&A{|gVfjd#o~8Br^2=Fu6Iqr({^&5%5TL`f?gbVNUk>;Vaz@syh~hI8Vni9_|G5nX zXBUxF7YY&#t(|L)~caPaZ^WeM^k$cV_Iknyd^eS zI~1svTyOXMh&yzSGE2G~DHnV`_^e@b^feEj8S&=oxtdQP-n-AzcwY!x{jaFIuOCGvITW)Eci>Rtf)-W z_r+k!B=r&Y&H_6UY}Mi05b1!9dcHN8WwM(i8~%w^?iA>#&x;v~(TQpMFh{l0ZqhTA z@ZaZ*JgaTwhsdgO0q_asq=G3&b}HD`gdSy*JQm3I?3>?#-f>z)(S%mzssi$fp5Y!k zF-;vX$x5|{bvb8*I0?uC$5F`#BgmH}}8)46@5!jyTB|0&fo;U9PBFR$LggR#0Hl~Cy zzyNv;8me{U1tA}N;V3$^d>3NsA}I(@*7E{xLrD*ukE~wR-Nhdk5(e7s19VOJ5V01o z3pC+2WqEz6i0X@>=d)5z`dR@&Bx`2HRJi-wGrDJW2@{t7;QgM3(!l#^gZEo8h@$gh zm~jW7(Op1g{>x8{uPRmc;H3V;^}GS;9wXxLF!0_!Zq{{g5Lj(P3*!q`OXr7{dIhK? zc=k-1Fi~u7?Qeqc-_!-`J&IGe!iNvf1*SYw6F890!01EoW)fvVTG7$K{bb;fm6x?}xZ=F{Wr|V5 zTK!wPpLdG4xZgiIOU!z18+PKRTp%E$hjq7hE2m}68f2B_ms%Zsv7#Kzq9x|dDCT1x zjqFEN@=*4_oKaRH1&x_??{+jhpPiGR_mCm)2x2id)@#S=g(AU1_Q~8AMOJrVfW&(P z-W>%R?`Myc`@AM*Xo?+Uta|OiA*yVDE%ksPd(N>W_v}CHz8Nhi_sf=k_{rdP6?Gz* zwikKOPUjUk+2>O5m&@Jug&!P6_AXAj(4whdW=#DPqtXWKi$gNOnOIznGGVG28hkM~ zMez&_FS_ungeSG9Eaga;F$nK8mN50szN_#uxmL8{Gm1my{hadL#U=N{$t8j7tqr)y z3XmOiiU=Dx`68HdFuf_&e$BjIHovjtY0QyzipT=IgLm#A8G&#jzQR+G90cnKI_Ko$ zIrF}|5ksH+SVsGXN;lc>`G2tAftko2lE&ru3mrd-VjLWv?|ls_xG!W$kZrir@W|W! zZ&0oejHjf)JG&xWi7)Zv${d6Tc)O(C4?f>_u|L6Q&*m2&fBna#Chjnu%<{v&^zET_ z&dC*TdRzMYm+_Rw`~Wzz$OC-9F$AV6nNBs0;v`G9Fj`?l*d^cV(w+dAAfHU=EsP`-gOqSreK zSj0Dt17)Tz+!2x{Q|Vw59{y|C#oS!JhhhNKbV>ZcLINoWoHI?o#tJ`(aMLiSw0sT- z&=62aWLq~oLlsDYxtjxI3$>tfw3Px+O-9*IZ!JdzZP+}>SB}431vU?)1&k``DnSD#yN?Mi&XX8UKMYvNl@@S#?iadMlB*jrz`WXJIFcl2mQ4wH6igdZE7s zc1}iq;^o6{?(bC#Pm9fc`PXsCKg#*ndxmzI9tdw07SU<&@{gsHC@;@kg#6ovl+DTcRhKnnU? zTdHO#s9cs*Ipzh9tf>(M(+<;)RB0UvFzvv90uB@`Jlxk97A zwr_1usttPK_TqOi7>it`h#$?s+lZ_sfH(h4XSDq~+!+&(g4RhVmylGl$~FOxs2!q1Ij%iqdPB*)M(} zlOwER)~xiG()(t=b7O|>KN)N>zOEBLIG@Wln(nD6yM}ZydnoYy{0R|M{iQ25@=i7G z3QOwlAAEyzPJ-~y`+Xz9{0dOMC>sU-7(RNVz~}b%SJhgF0Tm2%QUM&Kbp`ezV7_kz zjN<~TBLK$0u+xPwPpF4_G))#pRemx+PYu(xFo7rY7L^TfiyjuNz~6rqx@Dc?;x9GP zy6kn-`eS~PPp}qupz~g!t+4@?l|aSsrjB%`Rly5UbYdGs>QSjl3rI3~&wYvtwn(@? zvX?I^fUZd^XSQ1l!Omya*{x#+?my_!o4;W3B{XpXwEn=K4e`)vFG6+igQg$_YtU(o zaOs7z?&%VHKN+@>3NNiEtT_JotIe+?Gy}p_XkLKU z2ZMJk%ny-SL8eMLw5`Gk;LwV5!%ZA; za6+!TXRjsZ%|*O48VMLp zfq2y|mNQr^mfOXTIS`01K_p(8_$G;5|p#QJ|W(J|sYdbdRLzeS|c9tKW%_xN2 zNESb%->1_tUV4sW!PnU&EO;*wGxlsWsaA@ga+C1&ErDy4{qVR z2QQB9tL`;BJ|_P;0(X%|U>se^q$MvV+N>oeIvyw9@rc_n;yL)CUaqI8zbSbEm#h?U z$+jRKSJx))Zntf92|Z>5XyOB3v_YKFMQ7{8QB)!7F>qpn;6Nk1M|;mR0#y4EfBc=@ zN~$t@<@O9x$3vWBKd%B2TSqg(xEA!`Fd$;PIwGkGsIIM(K*V;9&P{tDjBfu^#5Sl0 ze}MvNVF=Vo4SX@9qbUFR*6+aV0sy;~P=Rm5~VJ74$kU|#V^r}` zjq2IS4;^`L4RMG!Xqe(jDFROT%f}yz9CtN{=g5klj`UH@EFvnGqE$!o0T0jb zr&ja?b5(V{Lf9eq{NObSNCJSFw4;_k8EzrS!})Wy^QMPg>bb=N2lkp-SW)rK0;n8a z_i@aQ_ctQQ%i!L7@%z2U_zx>)=2cyA8|J9HKfBrY{U@Tq_97}$U@ulf2>wvW>;?3*ovJd$P*kNFZKL5t2U8#e0DGDM6x9s zoJ|s6Cr-v%z7tM<7g7Z-{U0S;yt8~eAa3}9%8u)VvX}FB^EX~t_Hh%4_U#o2ZM!sl zs^;S2U9E47qT5|7rF>x=s9TUgK2$X(fX}V0-N|I%L8q7Vb#hOrKR_0(-5dmh@o!-F-$jyiLbq+`T-r-5QNr76VTm; zsM35uubc4cJzrFD>1uv7Wyi{epA1S|BwZ0d+#T`0+M! zv~v>3UG(>VzNWD%OPA0C_1iMfDh|vq28D#E>57Wwy9o~KZG1AzXg^1`J!kslXtz5U zTxqUh^r97!Va8F1^L`D%dH9RZr}q2nwMTi2Gm&ctdD;x)FL&O~QeBqrKmVN4>#d+5 zUX!2Ht4;L8e+NZB$Wriwc)L!9*?vk$^jPl#gH$xr0BK1>Fb({FdwABZ$7@* z;au1Z$xX*JWC1>V2U*AtRD|4R9V@fGwmEm}ppt1~3hS)pxpyEJ-704>yF;tM8(~pl ziEaf2P1Gfc?#wIWYg?Oo6vXkmrr>_=*$>Y1WLv3P#14>+Qc9KMFyoWD-x#i6>!)_8>(NP9sv)C{EAwgxj-DZ*CbGnAb%zh9@UvA961Z z^;hYSfLHrB%)8u^tY>&*baVfC2GJ>|@)YVTK(-x1!}5kAYzQKzYAudt4FTF8&~u&I zVkzclF^jt_f+OE?N(AKv<4Q7_nG`18^)_0=8R8{-uAT@MV>M=3$}Qv^A6uN`D9U_rzQ zy9o_ENrK`Y_Pq?xi{X28mKsMKQq7$0fuktw>F| zKz$X0smvIm3#~T;!S!fh3Kj?HiMAb--K}i7B&F+KVA$WW)-;y+`oz$X+POnf{9%T= z=bSYFN|(Tiz1aS-wyuW}ocp$Q54b%3=kNu6dZc}L%OBcf{Ev>$xIdNHK7DKKd5TC@ z9V>>C%Sxug;(MmzX55b5u}F7>==1#_#pu>_6NkWb}9C0>q@%dh<_?! z?Z6=ovA6rrYcUiKKdXd6kh(l)qXPkF%aciw}%pR|Mc9?vz+S9L65)Jy*A zk1RkJ3)lL|pg6uRIruTNu1wrUSH|&|AEW$|2cX!2Z4ly60kA z>65F}e3-*7lq>OBt%YaivI$0L3k<)v0Mc51E%}+K@mVDiV^ST#!SY6LQ>biwmHTSp zQUQuEGlFr^(baQY^Y8D{>5~5Z6=iVcaK;A!d;cSR=ph7d{BNL$J|kL@o{;rC&jwT` zvK21A8#%fblX{qbtbM)^rlRJyLAz0)HZvg{M$mpTP7Da;_N(94c=8?=w1jD@?d`{voTw8k zI`k3d4QD_KA-}>P^U6?)Vm60a4fBBc2k5P`kDvJL;)|35)CIP$Y+uZ1pG2x3yauKL zyL~sqfFA$Y=Y34#{R#h=J#$|4bc7NC zrk_c3Jp>5&`2+3`I|-V`_{1jZwsQi1>8z!i2&iRzS4QG4lmpK&HV-zp0>rz~BsVww z3a+y!bm?H~xV>_VjWcV#j0EbCWr*}fetXmc4#R`1B3qMkoob*xPevuXyeaqYSng?v z;U&D?v(ni!s@a6Gwah>$1+9Kx&u)LeJdo*n8rw)#Jh(IgrY#9MYw)0BRcOu0!oqt% zByk7RnL#-X63<}=OIu&sA%t5WRejn2i&S2O<~tOj1Jm!mm_fPSvX$F-0!HEH2Z`|m zH7Tzi?T^}VN2H7tkglrMc4TLq+NIME1$T}MBqt^zh^%{of`P@B!hMpqeVZL#?ots+ z9sigpj)4w-GWtG!;(#6JX-a4v>x99IhNvwQHa32Cc0ivvrr(|xIrDwG_v)MICv~D> z>zvj|pt;m*cUlfr9W(5>V_i~O5|J8bXHpuexgl?mZ#2M|g3NZXLye z!TBp5_FXY5=PZAlp#XBBHLFmnl@9KPwSV1=me`E_VT@$KK+p9}B_Exhjp^ZE7f`~o zW%G5;)Wq4Ju~YbPw$)5?sDd;x;>@z#^l`GhWJ6Q+_$LE^kDeaDbjcLx?*e=8+x3>e zsNr0p8z|&dkygjRW}R-0r@qXZHut`#GG!OHpQ61|);0A~={5+Uu!Ia(WCmgi-|6#(;{9hOv%$3+%sGbFIY>612xHPhY&N?URllYau?Unpx3M$c@ z{T&wMe*Cj6B^=p`%C)V5^#qIx;(Qccoyx@qB>gF8fphH8>D_9&=X%-~)9_+s6ATOW z70ebBkd&8HO~x>Q^GbJ%uy~xQVV*x_ytk@x$3x}JmH?LGBklLvUdF+KzKDO*1&H}J zNWmvORX*b7(2|8}6R$sDL!h~qeN#-DO;&C0iC6F*TuTG)c5mL(w-3)j%2;2QK~t0P z7g4<)Rq))VTB`O1QjjY(VFbI^4CiogjL9m$C}?SCz1w1WC>~S8HXQudJ)G=36Gq^5K z(LmSAg-W*toNT>5`eZSm?T<7v=o2bcO6BpaYNaGceDRu~@u=(%M}EbNIkm4dAmsMGiCu*&whvmvJ)dabJ-<4I3=E2> zo6*#ZJS#~O!E1vRR~}>oC%w}dOmSV(5@Fh3;G+pqoMZhG6w%~-cAw~WS|QBFsmBZ$ zY!`a($0zx7%@>!oip<2l3*6(-Q!ze968Q`M0kpavGom55BgH+H{i+hVA6d-GZNi`2 zzrvr_|3-aZWhItU!ztkS2n4$h|5f$2Qk^t$<*3X9G~ytfKBgJ+UsFg*uVm=zYB$hH zd%%hxA$W}NhS69NEBd7S1g=X_mpbw~D|bSkDQavQKY4_`^qDl=&|8c7VC_K(Ru0PA z3WVHgpMU`Ki_h!AXXzS(mb@^p``?c{tcsIL@Ms*Ixzr78b4fvI1qqqcji2RDG;(p} z+%hAz;O}bu=KDm~a{S5G{jCmf0Eu-lF%9WK6R(3)1oS8XOO$W(uC`$`ZqGlWLRN|{ zQY;agbL;ktQSRA)DzbzTbyEryN8WiY0t<92>6jEa7iu1q4I6#OxvaX%n;WlF4%`_;o9IDrS@1@Wh65PIs8i`vFcU{fMI{fb2O1#)?t2H>)OLcgY<~ndg1Bw_4{6VA2a!zZ75>@5=; zfG;Yb99eR&0J?}6Ht#XF+99E{CY`wVt`{~E+N(jl1G=XZlyk*+sjw`qN4ZM=Ye&dR z%jL+c2b?y+h2d~gp2pnLI=FCkrGtx-=%s@RbJsuu8i&M~Jf~eO+iMNgYq^y2WRXjQ zprr1#mEJrJaiDI(0t+pf2#rOEFmUR8sAge#K~ue`MprJzP*JFcLbi;v%S;B>=goiS zbD+twEWv9G2LKt#4jd6oW(2yuFqccOSw}Ax5I;=qlKIZ;s5XNT{lO5q^$d_n12#82 z4_YG#16E3*ii7aM57G@o5_`gr0BP0QQQ@if7hAS|W?k#1Mq_Q90)V^H`Ikdc|}(jeu_f{J!oD4A%!g~j0iYUBv1hd-AtsX9J(MRQB2U@`gF8T)-pbe=T>VFWVGgrbu zM2&$OERJ7X0*D=*rNX{%Zb46jZnVDGxD7^H{BgY!Gww%>pvEKj(;DC$-xarwm3R@# zZ9ZTFq2T-@P$+{I=q1>%J89m&l#3WZO`r)OTd|P$rCSM1&C=mbHtxa7ZC3X}Bt8_< z9+mCA>yVtF!F$K|7ELT2^AdFn!0nPzsku4=%UDIZaz3?hj|cy^O0w*HIU@4Z@^qQ* zQG` zB%`h`bc-Sih_Y0&N%!$HK$OLclF2!KfZv4Pm{)kF#|o^7GJ@kcX73YCsL>QgP-$RK zsuH=-^KtpTDKo{OGI{)2na*hFU(%uzCv86dtu%3g(!_fKlQENXcxl0Qfi|wyDkH!k z?L6_Es_`$Rsy|1`8&{8KQEc9Ye1HT2eLHvYp@JuAh-bP+K>n%@peME;wNOPB1m|FS zJIodzjdHlciXS8Rjj)E%SP*1=(mew2C9g9^ZSf?Z#i^k3@#aEsNXvPlVE{m%cM(;{ z=Csd)TdA3)Oua${yq5^a62pMcSRkLao$h`C7lip35bSceVa9WTu2xDA=xV>G;Ack< z(KUx@a>C;{8MTBc)gc`J@GzO~6Ogds6Ce%x#J{ejxs3sEgUn$GT*TKTABbNmFQaeO zK=iWYh0Dk$8)l)aXoCE{Zofz`7EPVk?<>Gas>cu5#%U3lq*zGOQUJ8hN9nhx>Vvqm z3T;G}PK5``i#0Q8EEnRrhUL6rw(x)g7&{Hx6X=*#;SnFhOfNaBZ(;+CloJ?+?_DB6 z@Vvm5e;!Y38d<5X-&&aO%~JI78pwyr$J;Iq)!-JHeQG^y{+D2)Umn!|sEKB-z}`al zbZwR?IESMg)5RELP^P;3t(Z*Ae%L4;A12}!&yh8eV0i@g@i%n?p8;RPfww32*nYsO z!)(h7o9ZPTXWQI?Ni$~tPU#L}FbFCrvK5@pN`oSZefx6{M*mT$f+(>7C@ZHVM{Drf zW=opW4j%?#We4r49)*B@V9#uYr9z?PzJ>z1mi0b()g~m7n&AHSvvS(h%#Su5i{0SI z+c=bK8ML=hW|}Y#XnJWXtnQ{99MRl8Wn9{KEHk5+@t%kBnZ(T9 z&LSZKJEK-&gQ~JXI2CD`!+WfVCSWp_g{OKR9O345PyH6AV{qlc4yCzo?AvCHWcmk9 zf3<@^Tt{yQRW{o}fE4~?N%#Br=!*5E9%w}p7+b+UEZ45Li<)$!y<#&v0q2csb&>da z+_>w?pAe80jbtIsUIz9!&`awZ3_ri(BPrl2Nuj|xtA4BA&cHsMe1Q5MW$na3>lkEm zgqR1({AAc|Hv(+HT2Nk&`=R$fPmCbtUX6JJgAZ)vPzaQ@)C(_#D}Dx?e|sIKdkbES zTQ6}FP+OW|AYO&hfYh@oT7TB^2M83O2G)i|OTx;$4uKuYO1f~Upv^J3{_V`2N0qiL z?ollXt8B4#$`#@9S{6RMbCqN%Pc`aWW#K;3xysH)mUw3I8PoVzWTmJ3CZ7K|c3xF@ zJn41>)seyq&ZSr(-Y0q4;#Wo*0}Jy5AouQ)6yn$jk&ccAXg^^Cx5F0lIm*t<&-2v$6kF$6n z|FDbyw`;hL0+ZHjmL&fBdd+fF+4)a3E1nohjirgw8kCjdE0M~1jisqz#&pAgX!eb9 zWX!7nUK!-5J5h{mh&fG)#ixu+eUjSQI06ZB=P4*ly>NfR{MbdO5U0@c#Z%i>pZZyF z&wO0lj>C7Tqt3$i!G=Tl9G59;ms{H7aX;L}1vQdg5MB5N`5=|{?Jjmf<5kJW?N=TO ztLiGAu0_^+ih%YDJ8b;;SrvB2gB@P%HN*82A@yf`LYFk1zYdOf8oYm2wMVg!Uf*cz z23Nzt;OaWBY3-LxP~U=;TRdR*X*G7Or*RDI^m+ySt)~8)zt!LC*5;pi7Ue+w5OzjCWe;I1Bgn9Tnd23FYm>ot^s%!bO`5WoAo;x@;G zB|DO1?|wr*#_}smf+m?)%DUqq7L1;s>wh{Io!w=1m*BA@)5UA7d9ROP9p*ew8!0H8 zB&UwdJqM&n&eSyP;^SKHNY00GTBbA3X?Tv4$mnHEr4&g-_t6jS^ko!UNF2qfXw8{s zx4pBoW@YJ^D0LQXV}dT4HdSc0P{oZy=8DKiJu;Fpp1n+gbA$rEwX-( zvfrOW{$UaSZxQ$Z>-+y`-JJY?$?pG;|NehE*7pDLXZri~`fo$HzrXhX*Poex_WU0+ CiV&j! literal 0 HcmV?d00001 diff --git a/apps/clients/src/lib/rum.ts b/apps/clients/src/lib/rum.ts new file mode 100644 index 0000000..4a512ab --- /dev/null +++ b/apps/clients/src/lib/rum.ts @@ -0,0 +1,23 @@ +import { datadogRum } from "@datadog/browser-rum"; +import { reactPlugin } from "@datadog/browser-rum-react"; + +datadogRum.init({ + applicationId: "8e268e1a-1be0-44c6-b12a-978530d497c7", + clientToken: "pub1761af09ab04e215cc90d34da6ac576b", + site: "datadoghq.com", + service: "xtablo-clients-ui", + env: import.meta.env.MODE, + version: import.meta.env.VITE_APP_VERSION, + + sessionSampleRate: 100, + sessionReplaySampleRate: 80, + defaultPrivacyLevel: "mask-user-input", + plugins: [reactPlugin({ router: true })], + trackViewsManually: true, + trackUserInteractions: true, + trackResources: true, + trackingConsent: "granted", + startSessionReplayRecordingManually: false, +}); + +export default datadogRum; diff --git a/apps/clients/src/main.tsx b/apps/clients/src/main.tsx index 073fb40..6d41477 100644 --- a/apps/clients/src/main.tsx +++ b/apps/clients/src/main.tsx @@ -13,6 +13,7 @@ import "@xtablo/ui/styles/globals.css"; import "@xtablo/tablo-views/styles/tablo-details-shell.css"; import "./main.css"; import "./i18n"; +import "./lib/rum"; createRoot(document.getElementById("client-root")!).render( diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ef82179..5b8c7a5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -19,7 +19,7 @@ importers: version: 2.2.5 '@datadog/datadog-ci': specifier: ^4.3.0 - version: 4.4.0(@types/node@22.18.12) + version: 4.4.0 turbo: specifier: ^2.5.8 version: 2.5.8 @@ -218,6 +218,12 @@ importers: apps/clients: dependencies: + '@datadog/browser-rum': + specifier: ^6.13.0 + version: 6.22.0 + '@datadog/browser-rum-react': + specifier: ^6.13.0 + version: 6.22.0(@datadog/browser-rum@6.22.0)(react-router-dom@7.9.4(react-dom@19.0.0(react@19.0.0))(react@19.0.0))(react-router@7.9.4(react-dom@19.0.0(react@19.0.0))(react@19.0.0))(react@19.0.0) '@tanstack/react-query': specifier: ^5.69.0 version: 5.90.5(react@19.0.0) @@ -11635,7 +11641,7 @@ snapshots: - '@types/node' - supports-color - '@datadog/datadog-ci-base@4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12)': + '@datadog/datadog-ci-base@4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)': dependencies: '@antfu/install-pkg': 1.1.0 '@types/datadog-metrics': 0.6.1 @@ -11649,7 +11655,7 @@ snapshots: fast-xml-parser: 4.5.3 form-data: 4.0.4 glob: 10.5.0 - inquirer: 8.2.7(@types/node@22.18.12) + inquirer: 8.2.7(@types/node@20.19.23) jest-diff: 30.2.0 jszip: 3.10.1 proxy-agent: 6.5.0 @@ -11689,7 +11695,7 @@ snapshots: '@datadog/datadog-ci-plugin-deployment@4.4.0(@datadog/datadog-ci-base@4.4.0)': dependencies: - '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0) axios: 1.12.2(debug@4.4.3) chalk: 3.0.0 simple-git: 3.16.0 @@ -11699,7 +11705,7 @@ snapshots: '@datadog/datadog-ci-plugin-dora@4.4.0(@datadog/datadog-ci-base@4.4.0)': dependencies: - '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0) axios: 1.12.2(debug@4.4.3) chalk: 3.0.0 simple-git: 3.16.0 @@ -11709,7 +11715,7 @@ snapshots: '@datadog/datadog-ci-plugin-gate@4.4.0(@datadog/datadog-ci-base@4.4.0)': dependencies: - '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0) '@types/uuid': 9.0.8 axios: 1.12.2(debug@4.4.3) chalk: 3.0.0 @@ -11719,7 +11725,7 @@ snapshots: '@datadog/datadog-ci-plugin-sarif@4.4.0(@datadog/datadog-ci-base@4.4.0)': dependencies: - '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0) ajv: 8.18.0 ajv-formats: 2.1.1(ajv@8.18.0) axios: 1.12.2(debug@4.4.3) @@ -11734,7 +11740,7 @@ snapshots: '@datadog/datadog-ci-plugin-sbom@4.4.0(@datadog/datadog-ci-base@4.4.0)': dependencies: - '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0) ajv: 8.18.0 ajv-formats: 2.1.1(ajv@8.18.0) axios: 1.12.2(debug@4.4.3) @@ -11748,7 +11754,7 @@ snapshots: '@datadog/datadog-ci-plugin-synthetics@4.4.0(@datadog/datadog-ci-base@4.4.0)': dependencies: - '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0) axios: 1.12.2(debug@4.4.3) chalk: 3.0.0 debug: 4.4.3 @@ -11768,9 +11774,9 @@ snapshots: - supports-color - utf-8-validate - '@datadog/datadog-ci@4.4.0(@types/node@22.18.12)': + '@datadog/datadog-ci@4.4.0': dependencies: - '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0)(@types/node@22.18.12) + '@datadog/datadog-ci-base': 4.4.0(@datadog/datadog-ci-plugin-deployment@4.4.0)(@datadog/datadog-ci-plugin-dora@4.4.0)(@datadog/datadog-ci-plugin-gate@4.4.0)(@datadog/datadog-ci-plugin-sarif@4.4.0)(@datadog/datadog-ci-plugin-sbom@4.4.0)(@datadog/datadog-ci-plugin-synthetics@4.4.0) '@datadog/datadog-ci-plugin-deployment': 4.4.0(@datadog/datadog-ci-base@4.4.0) '@datadog/datadog-ci-plugin-dora': 4.4.0(@datadog/datadog-ci-base@4.4.0) '@datadog/datadog-ci-plugin-gate': 4.4.0(@datadog/datadog-ci-base@4.4.0) @@ -12383,13 +12389,6 @@ snapshots: optionalDependencies: '@types/node': 20.19.23 - '@inquirer/external-editor@1.0.2(@types/node@22.18.12)': - dependencies: - chardet: 2.1.1 - iconv-lite: 0.7.0 - optionalDependencies: - '@types/node': 22.18.12 - '@internationalized/date@3.10.0': dependencies: '@swc/helpers': 0.5.17 @@ -17550,26 +17549,6 @@ snapshots: transitivePeerDependencies: - '@types/node' - inquirer@8.2.7(@types/node@22.18.12): - dependencies: - '@inquirer/external-editor': 1.0.2(@types/node@22.18.12) - ansi-escapes: 4.3.2 - chalk: 4.1.2 - cli-cursor: 3.1.0 - cli-width: 3.0.0 - figures: 3.2.0 - lodash: 4.17.21 - mute-stream: 0.0.8 - ora: 5.4.1 - run-async: 2.4.1 - rxjs: 7.8.2 - string-width: 4.2.3 - strip-ansi: 6.0.1 - through: 2.3.8 - wrap-ansi: 6.2.0 - transitivePeerDependencies: - - '@types/node' - internal-slot@1.1.0: dependencies: es-errors: 1.3.0 From 0476a87afd0f86845697cc5e566831c3e82fbe8e Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Sat, 25 Apr 2026 10:28:29 +0200 Subject: [PATCH 74/75] fix onboarding modal --- apps/clients/tsconfig.tsbuildinfo | 2 +- apps/main/src/components/Layout.test.tsx | 70 +++++++++++++++++++++++- apps/main/src/components/Layout.tsx | 12 +++- 3 files changed, 79 insertions(+), 5 deletions(-) diff --git a/apps/clients/tsconfig.tsbuildinfo b/apps/clients/tsconfig.tsbuildinfo index f2629d6..0266a11 100644 --- a/apps/clients/tsconfig.tsbuildinfo +++ b/apps/clients/tsconfig.tsbuildinfo @@ -1 +1 @@ -{"root":["./src/app.tsx","./src/envproduction.test.ts","./src/i18n.test.ts","./src/i18n.ts","./src/main.tsx","./src/maincss.test.ts","./src/routes.tsx","./src/setuptests.ts","./src/vite-env.d.ts","./src/viteconfig.test.ts","./src/components/clientauthgate.tsx","./src/components/clientlayout.test.tsx","./src/components/clientlayout.tsx","./src/lib/supabase.ts","./src/pages/authcallback.tsx","./src/pages/clienttablolistpage.tsx","./src/pages/clienttablopage.test.tsx","./src/pages/clienttablopage.tsx","./src/pages/loginpage.test.tsx","./src/pages/loginpage.tsx","./src/pages/resetpasswordpage.test.tsx","./src/pages/resetpasswordpage.tsx","./src/pages/setpasswordpage.test.tsx","./src/pages/setpasswordpage.tsx","./src/test/testhelpers.test.tsx","./src/test/testhelpers.tsx"],"version":"5.9.3"} \ No newline at end of file +{"root":["./src/app.tsx","./src/envproduction.test.ts","./src/i18n.test.ts","./src/i18n.ts","./src/main.tsx","./src/maincss.test.ts","./src/routes.tsx","./src/setuptests.ts","./src/vite-env.d.ts","./src/viteconfig.test.ts","./src/components/clientauthgate.tsx","./src/components/clientlayout.test.tsx","./src/components/clientlayout.tsx","./src/lib/rum.ts","./src/lib/supabase.ts","./src/pages/authcallback.tsx","./src/pages/clienttablolistpage.tsx","./src/pages/clienttablopage.test.tsx","./src/pages/clienttablopage.tsx","./src/pages/loginpage.test.tsx","./src/pages/loginpage.tsx","./src/pages/resetpasswordpage.test.tsx","./src/pages/resetpasswordpage.tsx","./src/pages/setpasswordpage.test.tsx","./src/pages/setpasswordpage.tsx","./src/test/testhelpers.test.tsx","./src/test/testhelpers.tsx"],"version":"5.9.3"} \ No newline at end of file diff --git a/apps/main/src/components/Layout.test.tsx b/apps/main/src/components/Layout.test.tsx index 7dcf293..c8298dc 100644 --- a/apps/main/src/components/Layout.test.tsx +++ b/apps/main/src/components/Layout.test.tsx @@ -1,11 +1,55 @@ import { fireEvent, screen } from "@testing-library/react"; import { Layout } from "@ui/components/Layout"; -import { beforeEach } from "vitest"; +import { beforeEach, vi } from "vitest"; import { renderWithProviders } from "../utils/testHelpers"; +vi.mock("../hooks/organization", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + useOrganization: vi.fn(), + }; +}); + +vi.mock("./OnboardingModal", () => ({ + OnboardingModal: ({ open }: { open: boolean }) => ( +

+ ), +})); + +import { useOrganization } from "../hooks/organization"; + +const mockUseOrganization = vi.mocked(useOrganization); + +const baseOrganizationData = { + organization: { + id: 1, + name: "Org", + plan: "none", + member_count: 1, + tablo_count: 0, + logo_url: null, + }, + members: [], + invites_sent: [], + trial_starts_at: "2026-01-01", + trial_ends_at: "2026-02-01", + is_trial_expired: false, + required_plan: "solo" as const, + required_team_quantity: 1, + active_subscription_plan: null, + active_subscription_quantity: 0, + is_billing_owner: true, +}; + describe("Layout", () => { beforeEach(() => { localStorage.setItem("xtablo-onboarding-completed", "true"); + mockUseOrganization.mockReturnValue({ + data: baseOrganizationData, + isLoading: false, + error: null, + } as ReturnType); }); it("renders the layout with children", () => { @@ -80,4 +124,28 @@ describe("Layout", () => { // Should have transition and mobile/desktop behavior expect(navParent).toHaveClass("fixed", "md:relative", "transition-transform"); }); + + it("keeps onboarding closed when there is no paid plan", () => { + localStorage.removeItem("xtablo-onboarding-completed"); + + renderWithProviders(); + + expect(screen.getByTestId("onboarding-modal")).toHaveTextContent("closed"); + }); + + it("opens onboarding when there is an active paid plan and onboarding is incomplete", () => { + localStorage.removeItem("xtablo-onboarding-completed"); + mockUseOrganization.mockReturnValue({ + data: { + ...baseOrganizationData, + active_subscription_plan: "solo", + }, + isLoading: false, + error: null, + } as ReturnType); + + renderWithProviders(); + + expect(screen.getByTestId("onboarding-modal")).toHaveTextContent("open"); + }); }); diff --git a/apps/main/src/components/Layout.tsx b/apps/main/src/components/Layout.tsx index cf96f1b..a8fe0fe 100644 --- a/apps/main/src/components/Layout.tsx +++ b/apps/main/src/components/Layout.tsx @@ -3,6 +3,7 @@ import { MenuIcon, XIcon } from "lucide-react"; import { useCallback, useEffect, useState } from "react"; import { Outlet, useLocation } from "react-router-dom"; import { twMerge } from "tailwind-merge"; +import { useOrganization } from "../hooks/organization"; import { SideNavigation } from "./NavigationBar"; import { OnboardingModal } from "./OnboardingModal"; import { TopBar } from "./TopBar"; @@ -13,14 +14,19 @@ export function Layout() { const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false); const [showOnboarding, setShowOnboarding] = useState(false); const location = useLocation(); + const { data: organizationData } = useOrganization(); useEffect(() => { - // Check if user has completed onboarding const hasCompletedOnboarding = localStorage.getItem(ONBOARDING_STORAGE_KEY); - if (!hasCompletedOnboarding) { + const hasPaidPlan = Boolean(organizationData?.active_subscription_plan); + + if (!hasCompletedOnboarding && hasPaidPlan) { setShowOnboarding(true); + return; } - }, []); + + setShowOnboarding(false); + }, [organizationData?.active_subscription_plan]); // Close mobile menu on route change useEffect(() => { From 1eace2291b3bf6d8bad251b835249790c9a921fe Mon Sep 17 00:00:00 2001 From: Arthur Belleville Date: Tue, 28 Apr 2026 22:35:15 +0200 Subject: [PATCH 75/75] Remove is_temporary invite flow in favor of is_client client invites MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The USE_CLIENT_PASSWORD_INVITES flag was hardcoded true. This removes the dead else-branch (old is_temporary flow sending users to app.xtablo.com/login) and always shows the Accès client form that routes new clients through clients.xtablo.com/set-password with is_client: true. Co-Authored-By: Claude Sonnet 4.6 (1M context) --- apps/main/src/pages/tablo-details.tsx | 313 +++++++++----------------- 1 file changed, 106 insertions(+), 207 deletions(-) diff --git a/apps/main/src/pages/tablo-details.tsx b/apps/main/src/pages/tablo-details.tsx index f198ce3..006720d 100644 --- a/apps/main/src/pages/tablo-details.tsx +++ b/apps/main/src/pages/tablo-details.tsx @@ -86,8 +86,6 @@ const TAB_SECTIONS: TabSection[] = [ "roadmap", ]; -const USE_CLIENT_PASSWORD_INVITES = true; - // ─── Page ───────────────────────────────────────────────────────────────────── export const TabloDetailsPage = () => { @@ -107,7 +105,6 @@ export const TabloDetailsPage = () => { ); const [showAllOverviewTasks, setShowAllOverviewTasks] = useState(false); const [isShareDialogOpen, setIsShareDialogOpen] = useState(false); - const [inviteEmail, setInviteEmail] = useState(""); const [clientInviteEmail, setClientInviteEmail] = useState(""); const [isLayoutEditMode, setIsLayoutEditMode] = useState(false); const [draggedOverviewBlock, setDraggedOverviewBlock] = useState<{ @@ -164,13 +161,6 @@ export const TabloDetailsPage = () => { (member) => !pendingInvites?.some((invite) => invite.invited_email === member.email) ); - const handleSendInvite = () => { - if (!tabloId || !inviteEmail.trim()) return; - - inviteUser({ email: inviteEmail, tablo_id: tabloId }); - setInviteEmail(""); - }; - const openTaskModal = (dueDate?: Date, defaultAssigneeId?: string) => { setTaskModalInitialDueDate(dueDate ? new Date(dueDate) : undefined); setTaskModalDefaultAssigneeId(defaultAssigneeId); @@ -563,208 +553,117 @@ export const TabloDetailsPage = () => { {/* Separator */}
- {USE_CLIENT_PASSWORD_INVITES ? ( - <> -
-

Accès client

-

- Le client recevra un email pour définir son mot de passe ou, s'il a déjà un - compte, une notification d'accès directe à ce tablo. -

-
+
+

Accès client

+

+ Le client recevra un email pour définir son mot de passe ou, s'il a déjà un + compte, une notification d'accès directe à ce tablo. +

+
-
- setClientInviteEmail(e.target.value)} - placeholder="Email du client" - className="flex-1 min-h-[44px]" - /> - {isCreatingClientInvite ? ( -
-
-
- ) : ( - - )} +
+ setClientInviteEmail(e.target.value)} + placeholder="Email du client" + className="flex-1 min-h-[44px]" + /> + {isCreatingClientInvite ? ( +
+
+ ) : ( + + )} +
- {pendingClientInvites && pendingClientInvites.length > 0 && ( -
-

- Invitations client en attente ({pendingClientInvites.length}) -

-
- {pendingClientInvites.map((invite) => { - const daysUntilExpiry = Math.ceil( - (new Date(invite.expires_at).getTime() - Date.now()) / - (1000 * 60 * 60 * 24) - ); - const isExpiringSoon = daysUntilExpiry < 5; - return ( -
0 && ( +
+

+ Invitations client en attente ({pendingClientInvites.length}) +

+
+ {pendingClientInvites.map((invite) => { + const daysUntilExpiry = Math.ceil( + (new Date(invite.expires_at).getTime() - Date.now()) / + (1000 * 60 * 60 * 24) + ); + const isExpiringSoon = daysUntilExpiry < 5; + return ( +
+
+ -
- - - -
-
- - {invite.invited_email} - - - {isExpiringSoon && "⚠ "} - Expire dans {daysUntilExpiry} jour - {daysUntilExpiry !== 1 ? "s" : ""} - -
- {isExpiringSoon && ( - - Bientôt expiré - - )} - -
- ); - })} -
-
- )} - - ) : ( - <> -
-

- Inviter un utilisateur -

-

- Utilisez le système d'invitation standard par email pour le moment -

-
- -
- setInviteEmail(e.target.value)} - placeholder="Email de l'utilisateur à inviter" - className="flex-1 min-h-[44px]" - /> - {isInvitingUser ? ( -
-
-
- ) : ( - - )} -
- - {pendingInvites && pendingInvites.length > 0 && ( -
-

- Invitations en attente ({pendingInvites.length}) -

-
- {pendingInvites.map((invite) => ( -
-
- - - -
-
- - {invite.invited_email} - - (En attente) -
- + +
- ))} -
-
- )} - +
+ + {invite.invited_email} + + + {isExpiringSoon && "⚠ "} + Expire dans {daysUntilExpiry} jour + {daysUntilExpiry !== 1 ? "s" : ""} + +
+ {isExpiringSoon && ( + + Bientôt expiré + + )} + +
+ ); + })} +
+
)}