Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

style: apply writing standards across all project files

spacesdrive31124caeb7b9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 465e89a..8c53750 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,64 +13,64 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
---
-## [1.0.0] — 2025 (Initial Production Release)
+## [1.0.0] - 2025 (Initial Production Release)
### Added
**Backend (Cloudflare Worker + Hono)**
-- `GET /api/health` — public health check endpoint
-- `POST /api/accounts` — add YouTube channel by URL or handle
-- `POST /api/accounts/instagram` — add Instagram account via access token
-- `GET /api/accounts` — list all user accounts
-- `DELETE /api/accounts/:id` — remove account and invalidate Redis cache
-- `POST /api/accounts/refresh-all` — batch refresh all account stats
-- `POST /api/accounts/:id/refresh` — refresh single account stats
-- `POST /api/accounts/:id/refresh-ig-token` — extend Instagram long-lived token
-- `GET /api/accounts/:id/analytics` — full YouTube analytics with video-level computation
-- `GET /api/accounts/:id/videos` — YouTube video list (cached in Redis)
-- `GET /api/accounts/:id/ig-analytics` — Instagram analytics with engagement computation
-- `GET /api/accounts/:id/ig-media` — Instagram media list (cached in Redis)
-- `GET /api/comparison` — cross-account comparison data
-- `GET /api/auth/instagram/url` — generate HMAC-signed Instagram OAuth URL
-- `GET /api/auth/instagram/callback` — OAuth code exchange, account creation, redirect
-- `GET /api/resolve-channel` — resolve YouTube URL/handle to channel ID
-- `GET /api/keys` — return configuration status for all required API keys
-- `GET /api/cloudinary-config` — return Cloudinary cloud name and upload preset
-- `POST /api/accounts/:id/ig-publish` — create Instagram media container
-- `GET /api/ig-container/:id/status` — poll container processing status
-- `POST /api/accounts/:id/ig-media-publish` — publish container to Instagram
-- `GET /api/accounts/:id/ig-publishing-limit` — check daily publishing quota
-- `GET/POST /api/scheduled-posts` — list and create scheduled posts
-- `PUT/DELETE /api/scheduled-posts/:id` — edit and delete individual posts
-- `DELETE /api/scheduled-posts` — clear all non-publishing posts
-- `GET/POST /api/process-scheduled` — manual scheduler trigger
-- `GET/PUT /api/settings/github` — GitHub PAT and repo settings
+- `GET /api/health` - public health check endpoint
+- `POST /api/accounts` - add YouTube channel by URL or handle
+- `POST /api/accounts/instagram` - add Instagram account via access token
+- `GET /api/accounts` - list all user accounts
+- `DELETE /api/accounts/:id` - remove account and invalidate Redis cache
+- `POST /api/accounts/refresh-all` - batch refresh all account stats
+- `POST /api/accounts/:id/refresh` - refresh single account stats
+- `POST /api/accounts/:id/refresh-ig-token` - extend Instagram long-lived token
+- `GET /api/accounts/:id/analytics` - full YouTube analytics with video-level computation
+- `GET /api/accounts/:id/videos` - YouTube video list (cached in Redis)
+- `GET /api/accounts/:id/ig-analytics` - Instagram analytics with engagement computation
+- `GET /api/accounts/:id/ig-media` - Instagram media list (cached in Redis)
+- `GET /api/comparison` - cross-account comparison data
+- `GET /api/auth/instagram/url` - generate HMAC-signed Instagram OAuth URL
+- `GET /api/auth/instagram/callback` - OAuth code exchange, account creation, redirect
+- `GET /api/resolve-channel` - resolve YouTube URL/handle to channel ID
+- `GET /api/keys` - return configuration status for all required API keys
+- `GET /api/cloudinary-config` - return Cloudinary cloud name and upload preset
+- `POST /api/accounts/:id/ig-publish` - create Instagram media container
+- `GET /api/ig-container/:id/status` - poll container processing status
+- `POST /api/accounts/:id/ig-media-publish` - publish container to Instagram
+- `GET /api/accounts/:id/ig-publishing-limit` - check daily publishing quota
+- `GET/POST /api/scheduled-posts` - list and create scheduled posts
+- `PUT/DELETE /api/scheduled-posts/:id` - edit and delete individual posts
+- `DELETE /api/scheduled-posts` - clear all non-publishing posts
+- `GET/POST /api/process-scheduled` - manual scheduler trigger
+- `GET/PUT /api/settings/github` - GitHub PAT and repo settings
**Cron triggers (wrangler.toml)**
-- `*/15 * * * *` → `processScheduledPosts()` publishes due Instagram posts
-- `0 0 * * *` → `autoRefreshInstagramTokens()` refreshes tokens expiring within 15 days
+- `*/15 * * * *` -> `processScheduledPosts()` publishes due Instagram posts
+- `0 0 * * *` -> `autoRefreshInstagramTokens()` refreshes tokens expiring within 15 days
**Database (Supabase)**
-- `accounts` table — `id, user_id, platform, data jsonb`
-- `settings` table — `user_id, key, value jsonb` (PK: user_id + key)
-- `scheduled_posts` table — `id, user_id, account_id, status, scheduled_at, data jsonb`
+- `accounts` table - `id, user_id, platform, data jsonb`
+- `settings` table - `user_id, key, value jsonb` (PK: user_id + key)
+- `scheduled_posts` table - `id, user_id, account_id, status, scheduled_at, data jsonb`
**Frontend (React 19 + Vite)**
-- `/login` — email/password authentication via Supabase Auth
-- `/` — Overview dashboard: KPI cards, area chart, pie chart, leaderboard tables
-- `/channel/:id` — Deep YouTube channel analytics
-- `/instagram/:id` — Deep Instagram profile analytics
-- `/videos` — Cross-account YouTube video explorer
-- `/shorts` — Shorts-filtered video explorer
-- `/reels` — Instagram reels/media explorer
-- `/upload` — Instagram publishing UI + scheduled post queue
-- `/accounts` — Account management: add, remove, refresh, Instagram OAuth
-- `/settings` — API key status + GitHub PAT configuration
+- `/login` - email/password authentication via Supabase Auth
+- `/` - Overview dashboard: KPI cards, area chart, pie chart, leaderboard tables
+- `/channel/:id` - Deep YouTube channel analytics
+- `/instagram/:id` - Deep Instagram profile analytics
+- `/videos` - Cross-account YouTube video explorer
+- `/shorts` - Shorts-filtered video explorer
+- `/reels` - Instagram reels/media explorer
+- `/upload` - Instagram publishing UI + scheduled post queue
+- `/accounts` - Account management: add, remove, refresh, Instagram OAuth
+- `/settings` - API key status + GitHub PAT configuration
**GitHub Actions**
-- `deploy-backend.yml` — deploy Worker on push to `main` (paths: `backend/**`)
-- `deploy-frontend.yml` — build and deploy Pages on push to `main` (paths: `frontend/**`)
-- `publish-scheduled.yml` — run scheduled publisher every 15 minutes via cron
+- `deploy-backend.yml` - deploy Worker on push to `main` (paths: `backend/**`)
+- `deploy-frontend.yml` - build and deploy Pages on push to `main` (paths: `frontend/**`)
+- `publish-scheduled.yml` - run scheduled publisher every 15 minutes via cron
**Infrastructure**
- HMAC-signed OAuth state (no Redis dependency for auth flows)
diff --git a/DECISIONS.md b/DECISIONS.md
index 7a89cba..8685c3a 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -1,6 +1,6 @@
# Architecture Decision Log
-Records every significant architectural decision, the alternatives considered, and the reasoning. Append new entries — never modify or delete existing ones.
+Records every significant architectural decision, the alternatives considered, and the reasoning. Append new entries - never modify or delete existing ones.
---
@@ -20,7 +20,7 @@ Records every significant architectural decision, the alternatives considered, a
- Zero cold starts at the edge
- Global distribution at no extra cost
- Free tier includes built-in cron triggers
-- Native `crypto.subtle` API for HMAC — no dependency needed
+- Native `crypto.subtle` API for HMAC - no dependency needed
- `wrangler` CLI makes local dev and deploy identical
**Trade-offs:**
@@ -46,7 +46,7 @@ Records every significant architectural decision, the alternatives considered, a
**Reasoning:**
- First-class Cloudflare Workers support
- Type-safe context (`c.set()` / `c.get()`)
-- Middleware composability matches the auth → route pattern
+- Middleware composability matches the auth -> route pattern
- `app.route()` enables clean sub-application isolation
- Active maintenance and large community
@@ -79,7 +79,7 @@ Records every significant architectural decision, the alternatives considered, a
**Trade-offs:**
- External service dependency
- jsonb data column means no column-level DB constraints on account fields
-- RLS is bypassed by the backend — application-layer isolation is the security model
+- RLS is bypassed by the backend - application-layer isolation is the security model
---
@@ -88,21 +88,21 @@ Records every significant architectural decision, the alternatives considered, a
**Date:** 2024 (initial)
**Status:** Accepted
-**Decision:** YouTube API key, Instagram App ID/Secret, Cloudinary credentials are all stored as Cloudflare Worker secrets — shared across all users of the instance.
+**Decision:** YouTube API key, Instagram App ID/Secret, Cloudinary credentials are all stored as Cloudflare Worker secrets - shared across all users of the instance.
**Alternatives considered:**
- Per-user API key storage in Supabase `settings` table
- User-provided keys stored encrypted in DB
**Reasoning:**
-- The app is self-hosted — there is one admin and a small team
+- The app is self-hosted - there is one admin and a small team
- Per-user keys add UI complexity with marginal security benefit at this scale
- Worker secrets are encrypted at rest and never exposed in API responses
**Trade-offs:**
- All users share the YouTube API daily quota
- Changing credentials requires a Worker redeploy
-- `GET /api/keys` only returns `{configured: true/false}` — the frontend can see what is configured but never the values
+- `GET /api/keys` only returns `{configured: true/false}` - the frontend can see what is configured but never the values
---
@@ -125,7 +125,7 @@ Records every significant architectural decision, the alternatives considered, a
**Trade-offs:**
- No column-level DB constraints on data fields
- Queries cannot use index-accelerated filters on data sub-fields without JSON indexing
-- `accessToken` lives inside `data.accessToken` — must be consistently stripped by `safeAccount()`
+- `accessToken` lives inside `data.accessToken` - must be consistently stripped by `safeAccount()`
---
@@ -146,10 +146,10 @@ Records every significant architectural decision, the alternatives considered, a
**Reasoning:**
- The app must function without Redis configured
- HMAC is cryptographically equivalent to a signed opaque token
-- `crypto.subtle` is natively available in Workers — no dependency needed
+- `crypto.subtle` is natively available in Workers - no dependency needed
**Trade-offs:**
-- State cannot be invalidated early (e.g., on logout) — only expires by time
+- State cannot be invalidated early (e.g., on logout) - only expires by time
- If `INSTAGRAM_APP_SECRET` is compromised, historical state tokens can be forged
---
@@ -169,11 +169,11 @@ Records every significant architectural decision, the alternatives considered, a
**Reasoning:**
- GitHub Actions is free on public repos (unlimited minutes)
- Provides redundancy if the Worker cron fails or is paused
-- `scripts/publish-scheduled.js` can run without any npm install — it uses native fetch only
+- `scripts/publish-scheduled.js` can run without any npm install - it uses native fetch only
- The same Supabase table is the source of truth for both systems
**Trade-offs:**
-- There is a risk of double-publishing if both run at exactly the same moment. Mitigated by the `publishing` status lock — the first scheduler to claim a post sets it to `publishing`, so the second will skip it.
+- There is a risk of double-publishing if both run at exactly the same moment. Mitigated by the `publishing` status lock - the first scheduler to claim a post sets it to `publishing`, so the second will skip it.
- `SUPABASE_URL` and `SUPABASE_SERVICE_KEY` must be set as GitHub Actions secrets separately from Worker secrets
---
@@ -192,12 +192,12 @@ Records every significant architectural decision, the alternatives considered, a
**Reasoning:**
- Self-hosted users may not want to create an Upstash account
-- YouTube and Instagram API quotas are the real constraint — caching is an optimization
+- YouTube and Instagram API quotas are the real constraint - caching is an optimization
- Silent fallback means Redis can be added or removed without code changes
**Trade-offs:**
- Without Redis, every analytics page load fetches 500+ videos/media items from external APIs
-- Cache TTL is not set — cached data persists until the account is deleted or explicitly invalidated
+- Cache TTL is not set - cached data persists until the account is deleted or explicitly invalidated
---
@@ -216,13 +216,13 @@ Records every significant architectural decision, the alternatives considered, a
**Reasoning:**
- Instagram's Graph API requires a publicly accessible, stable URL
- Cloudinary provides immediate CDN distribution
-- The unsigned upload preset lets the browser upload directly — the backend never handles binary file streams
+- The unsigned upload preset lets the browser upload directly - the backend never handles binary file streams
- Cloudinary's transformation URLs can generate thumbnails and previews
**Trade-offs:**
- Requires a Cloudinary account and upload preset configuration
-- Media stays in Cloudinary after posting — could accumulate cost if not cleaned up
-- `GET /api/cloudinary-config` exposes the cloud name and unsigned preset to the frontend (acceptable — unsigned presets are intentionally public)
+- Media stays in Cloudinary after posting - could accumulate cost if not cleaned up
+- `GET /api/cloudinary-config` exposes the cloud name and unsigned preset to the frontend (acceptable - unsigned presets are intentionally public)
---
@@ -239,7 +239,7 @@ Records every significant architectural decision, the alternatives considered, a
- JSDoc annotations for IDE assistance
**Reasoning:**
-- Reduced build complexity — no tsc step in Workers or Vite
+- Reduced build complexity - no tsc step in Workers or Vite
- The project is small enough that naming conventions and documentation provide adequate clarity
- Worker bundles avoid a TS compilation step
@@ -264,7 +264,7 @@ Records every significant architectural decision, the alternatives considered, a
**Reasoning:**
- Service-role key simplifies cron handlers (scheduler, token refresh) which need to query across all users
- Having a single key avoids key-switching logic in `lib/db.js`
-- The security boundary is the `requireAuth` middleware — once the JWT is verified, `userId` is trusted
+- The security boundary is the `requireAuth` middleware - once the JWT is verified, `userId` is trusted
**Trade-offs:**
- A bug that accidentally omits `.eq('user_id', userId)` could expose another user's data
@@ -283,5 +283,5 @@ Records every significant architectural decision, the alternatives considered, a
**Status:** The settings table and API routes exist. The GitHub push feature is planned but not yet implemented.
**Trade-offs:**
-- GitHub PAT is stored in plaintext in Supabase jsonb — acceptable for a self-hosted deployment where the admin trusts the storage layer
+- GitHub PAT is stored in plaintext in Supabase jsonb - acceptable for a self-hosted deployment where the admin trusts the storage layer
- The `settings` table design (user_id + key + jsonb value) is generic enough to hold any future per-user configuration
diff --git a/ROADMAP.md b/ROADMAP.md
index 332df62..c8ddff3 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -1,6 +1,6 @@
# Roadmap
-Planned features, improvements, and known gaps. Items within each section are roughly prioritized — top items first.
+Planned features, improvements, and known gaps. Items within each section are roughly prioritized - top items first.
Update this file whenever a feature ships (move to CHANGELOG.md) or when priorities change.
@@ -8,7 +8,7 @@ Update this file whenever a feature ships (move to CHANGELOG.md) or when priorit
## In Progress
-- **BOM-stripping fix for GitHub Actions publisher** — Hardening `scripts/publish-scheduled.js` against PowerShell-injected BOM characters in secrets
+- **BOM-stripping fix for GitHub Actions publisher** - Hardening `scripts/publish-scheduled.js` against PowerShell-injected BOM characters in secrets
---
@@ -21,22 +21,22 @@ Add Reddit as a connected platform for analytics.
**Approach:** Cookie-based authentication (no OAuth required)
- User logs into Reddit in a browser popup
- Session cookies (`token_v2`, `reddit_session`) are captured and stored in `accounts.data`
-- Cookies are auto-refreshed: Reddit rotates `Set-Cookie` on every authenticated response — save the updated cookie on each API call
+- Cookies are auto-refreshed: Reddit rotates `Set-Cookie` on every authenticated response - save the updated cookie on each API call
- Endpoints to fetch: `GET /user/{username}/submitted.json`, `/user/{username}/about.json`
**Files to add:**
-- `backend/services/reddit.js` — cookie-based fetch wrapper, token refresh, analytics computation
-- `backend/routes/reddit.js` — analytics routes (analytics, posts, comments)
-- `frontend/src/features/analytics/reddit/RedditAnalytics.jsx` — analytics page
-- `frontend/src/features/accounts/components/RedditConnect.jsx` — login popup + cookie capture
+- `backend/services/reddit.js` - cookie-based fetch wrapper, token refresh, analytics computation
+- `backend/routes/reddit.js` - analytics routes (analytics, posts, comments)
+- `frontend/src/features/analytics/reddit/RedditAnalytics.jsx` - analytics page
+- `frontend/src/features/accounts/components/RedditConnect.jsx` - login popup + cookie capture
**Files to modify:**
-- `backend/server.js` — mount Reddit routes
-- `backend/lib/db.js` — no changes needed (platform='reddit' works with existing schema)
-- `backend/lib/cache.js` — add `getRedditCache`, `setRedditCache`, `deleteRedditCache`
-- `frontend/src/App.jsx` — add `/reddit/:id` route
-- `frontend/src/layout/Sidebar.jsx` — add Reddit nav links
-- `docs/architecture/data-flows/` — add `REDDIT.md`
+- `backend/server.js` - mount Reddit routes
+- `backend/lib/db.js` - no changes needed (platform='reddit' works with existing schema)
+- `backend/lib/cache.js` - add `getRedditCache`, `setRedditCache`, `deleteRedditCache`
+- `frontend/src/App.jsx` - add `/reddit/:id` route
+- `frontend/src/layout/Sidebar.jsx` - add Reddit nav links
+- `docs/architecture/data-flows/` - add `REDDIT.md`
---
@@ -77,7 +77,7 @@ The `settings` table already stores GitHub PAT and repo config. Build the actual
Allow users to upload a CSV file to schedule multiple Instagram posts at once.
**Current:** Bulk scheduling UI exists in `UploadContent.jsx` but only via manual row entry.
-**Goal:** CSV upload → parse → preview → schedule all rows
+**Goal:** CSV upload -> parse -> preview -> schedule all rows
---
@@ -111,7 +111,7 @@ TikTok's API requires a business account and app review. Lower priority until th
### YouTube Publishing
-YouTube's upload API requires OAuth with `youtube.upload` scope. Architecture would mirror Instagram publishing — add a media pipeline with Cloudinary → YouTube upload → status polling.
+YouTube's upload API requires OAuth with `youtube.upload` scope. Architecture would mirror Instagram publishing - add a media pipeline with Cloudinary -> YouTube upload -> status polling.
### Multi-User Teams
@@ -125,9 +125,9 @@ React Native app using the same Cloudflare Worker backend.
## Known Issues / Tech Debt
-- Redis cache TTL is never set — cached analytics data persists indefinitely until account deletion. Should add a TTL (e.g., 24 hours for video lists).
-- `public/` directory at repo root contains a legacy Express prototype — should be removed once it is confirmed unused.
-- Root `package.json` and `node_modules/` belong to the legacy prototype — can be removed.
-- `wrangler.toml` has no `vars` section for non-secret configuration — any non-sensitive config currently requires a redeploy to change.
-- No error monitoring (Sentry, Cloudflare Analytics, etc.) — failures are only visible in Cloudflare Worker logs.
-- The `scripts/publish-scheduled.js` scheduler has no rate limiting — if 100 posts are due at the same time, it will attempt to publish all 100 concurrently within a single GitHub Actions run.
+- Redis cache TTL is never set - cached analytics data persists indefinitely until account deletion. Should add a TTL (e.g., 24 hours for video lists).
+- `public/` directory at repo root contains a legacy Express prototype - should be removed once it is confirmed unused.
+- Root `package.json` and `node_modules/` belong to the legacy prototype - can be removed.
+- `wrangler.toml` has no `vars` section for non-secret configuration - any non-sensitive config currently requires a redeploy to change.
+- No error monitoring (Sentry, Cloudflare Analytics, etc.) - failures are only visible in Cloudflare Worker logs.
+- The `scripts/publish-scheduled.js` scheduler has no rate limiting - if 100 posts are due at the same time, it will attempt to publish all 100 concurrently within a single GitHub Actions run.
diff --git a/backend/lib/cache.js b/backend/lib/cache.js
index 7be4b4e..eaa8b35 100644
--- a/backend/lib/cache.js
+++ b/backend/lib/cache.js
@@ -1,6 +1,6 @@
// All functions accept `redis` as first argument.
// If redis is null (Upstash not configured) or the call fails, all operations
-// are silent no-ops — cache failures must never break the main request.
+// are silent no-ops - cache failures must never break the main request.
export async function getVideosCache(redis, userId, accountId) {
if (!redis) return null;
diff --git a/backend/lib/db.js b/backend/lib/db.js
index 8216af0..5d90cd8 100644
--- a/backend/lib/db.js
+++ b/backend/lib/db.js
@@ -1,4 +1,4 @@
-// All functions accept `supabase` as first argument so they work both in
+// All functions accept `supabase` as first argument so they work both in
// request handlers (where supabase comes from context) and in cron handlers
// (where supabase is created from env). userId=null means service-level
// (no user filter) - used by the scheduler and token refresh cron.
diff --git a/backend/lib/supabase.js b/backend/lib/supabase.js
index 4bdbcec..f4328d4 100644
--- a/backend/lib/supabase.js
+++ b/backend/lib/supabase.js
@@ -1,4 +1,4 @@
-import { createClient } from '@supabase/supabase-js';
+import { createClient } from '@supabase/supabase-js';
function clean(s) {
return s?.replace(/^/, '').trim();
diff --git a/backend/routes/instagramAuth.js b/backend/routes/instagramAuth.js
index 2f9838e..a61e3bc 100644
--- a/backend/routes/instagramAuth.js
+++ b/backend/routes/instagramAuth.js
@@ -1,4 +1,4 @@
-import { createOAuthState, verifyOAuthState } from '../lib/cache.js';
+import { createOAuthState, verifyOAuthState } from '../lib/cache.js';
import { createAccount, getAccounts } from '../lib/db.js';
import { fetchInstagramProfile } from '../services/instagram.js';
diff --git a/backend/server.js b/backend/server.js
index 061906f..864b48e 100644
--- a/backend/server.js
+++ b/backend/server.js
@@ -1,4 +1,4 @@
-import { Hono } from 'hono';
+import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { getSupabase } from './lib/supabase.js';
import { getRedis } from './lib/redis.js';
diff --git a/backend/services/instagram.js b/backend/services/instagram.js
index 447af3a..cbcae87 100644
--- a/backend/services/instagram.js
+++ b/backend/services/instagram.js
@@ -1,4 +1,4 @@
-// fetch is a global in Cloudflare Workers - no import needed.
+// fetch is a global in Cloudflare Workers - no import needed.
import { getAccounts, updateAccount } from '../lib/db.js';
const IG_GRAPH_URL = 'https://graph.instagram.com';
diff --git a/backend/services/youtube.js b/backend/services/youtube.js
index 1c827d5..f5f615a 100644
--- a/backend/services/youtube.js
+++ b/backend/services/youtube.js
@@ -1,4 +1,4 @@
-// fetch is a global in Cloudflare Workers - no import needed.
+// fetch is a global in Cloudflare Workers - no import needed.
async function ytFetch(endpoint, params, apiKey) {
const url = new URL(`https://www.googleapis.com/youtube/v3/${endpoint}`);
diff --git a/docs/architecture/OVERVIEW.md b/docs/architecture/OVERVIEW.md
index 7bab312..14e908b 100644
--- a/docs/architecture/OVERVIEW.md
+++ b/docs/architecture/OVERVIEW.md
@@ -5,23 +5,23 @@
```
┌─────────────────────────────────────────────────────────────────┐
│ Browser (User) │
-│ React SPA — Cloudflare Pages │
+│ React SPA - Cloudflare Pages │
│ https://twiligent.pages.dev │
└────────────────────────┬────────────────────────────────────────┘
│ HTTPS + Bearer JWT
▼
┌─────────────────────────────────────────────────────────────────┐
-│ Cloudflare Worker — "twiligent" │
+│ Cloudflare Worker - "twiligent" │
│ https://twiligent.ujjwalkrai.workers.dev/api │
│ │
│ Hono v4 app │
│ ├── Global middleware: CORS, Supabase client, Redis client │
│ ├── Public: GET /api/health, GET /api/auth/instagram/callback │
-│ └── Protected (/api/*): requireAuth → routes │
+│ └── Protected (/api/*): requireAuth -> routes │
│ │
│ Cron handlers (wrangler.toml triggers): │
-│ ├── */15 * * * * → processScheduledPosts() │
-│ └── 0 0 * * * → autoRefreshInstagramTokens() │
+│ ├── */15 * * * * -> processScheduledPosts() │
+│ └── 0 0 * * * -> autoRefreshInstagramTokens() │
└──────┬──────────┬──────────────┬────────────────────────────────┘
│ │ │
▼ ▼ ▼
@@ -55,38 +55,38 @@
```
Browser
- → fetch(`${VITE_API_URL}/accounts`, { Authorization: Bearer <jwt> })
+ -> fetch(`${VITE_API_URL}/accounts`, { Authorization: Bearer <jwt> })
↓
Cloudflare Worker edge node (nearest to user)
- → CORS middleware (checks origin)
- → Client injection middleware (creates Supabase + Redis clients from env)
- → requireAuth middleware
- → extracts Bearer token from Authorization header
- → supabaseAuth.auth.getUser(token) → Supabase validates JWT
- → sets c.userId, c.userEmail on Hono context
- → route handler (e.g., accounts router)
- → db.getAccounts(supabase, userId) [lib/db.js]
- → supabase.from('accounts').select(...).eq('user_id', userId)
- → normalizes rows
- → returns JSON response
+ -> CORS middleware (checks origin)
+ -> Client injection middleware (creates Supabase + Redis clients from env)
+ -> requireAuth middleware
+ -> extracts Bearer token from Authorization header
+ -> supabaseAuth.auth.getUser(token) -> Supabase validates JWT
+ -> sets c.userId, c.userEmail on Hono context
+ -> route handler (e.g., accounts router)
+ -> db.getAccounts(supabase, userId) [lib/db.js]
+ -> supabase.from('accounts').select(...).eq('user_id', userId)
+ -> normalizes rows
+ -> returns JSON response
```
## Cron Lifecycle
```
Cloudflare scheduler fires cron trigger
- → Worker.scheduled(event, env, ctx)
- → getSupabase(env) [creates service-role client]
- → if event.cron === '*/15 * * * *':
+ -> Worker.scheduled(event, env, ctx)
+ -> getSupabase(env) [creates service-role client]
+ -> if event.cron === '*/15 * * * *':
ctx.waitUntil(processScheduledPosts(supabase))
- → db.getDuePosts(supabase) [no userId filter — scans all users]
- → for each post: publishToInstagram(post, account)
- → db.updatePost(supabase, id, { status: 'published' })
- → if event.cron === '0 0 * * *':
+ -> db.getDuePosts(supabase) [no userId filter - scans all users]
+ -> for each post: publishToInstagram(post, account)
+ -> db.updatePost(supabase, id, { status: 'published' })
+ -> if event.cron === '0 0 * * *':
ctx.waitUntil(autoRefreshInstagramTokens(supabase))
- → db.getAccounts(supabase) [all users, platform='instagram']
- → for each expiring token: igFetch refresh endpoint
- → db.updateAccount(supabase, id, { accessToken: newToken })
+ -> db.getAccounts(supabase) [all users, platform='instagram']
+ -> for each expiring token: igFetch refresh endpoint
+ -> db.updateAccount(supabase, id, { accessToken: newToken })
```
## Data Storage Strategy
@@ -117,6 +117,6 @@ Frontend env vars are documented in `docs/architecture/cloudflare/PAGES.md`.
4. **`safeAccount()` is the only place access tokens are stripped.** Any route that returns account data must pass through this function before responding.
-5. **`db.js` is the only file that contains Supabase queries.** Route handlers import and call db functions — they never call `supabase.from()` directly.
+5. **`db.js` is the only file that contains Supabase queries.** Route handlers import and call db functions - they never call `supabase.from()` directly.
-6. **`api.js` is the only file that calls `fetch()` in the frontend.** Components call `api.methodName()` — they never construct fetch calls.
+6. **`api.js` is the only file that calls `fetch()` in the frontend.** Components call `api.methodName()` - they never construct fetch calls.
diff --git a/docs/architecture/backend/CACHING.md b/docs/architecture/backend/CACHING.md
index 9c41a1b..6fe4156 100644
--- a/docs/architecture/backend/CACHING.md
+++ b/docs/architecture/backend/CACHING.md
@@ -2,14 +2,14 @@
## Overview
-Caching is implemented via Upstash Redis (REST API) using the `@upstash/redis` SDK. It is **entirely optional** — if `UPSTASH_REDIS_REST_URL` is not set, `getRedis()` returns `null` and all cache functions in `lib/cache.js` silently no-op.
+Caching is implemented via Upstash Redis (REST API) using the `@upstash/redis` SDK. It is **entirely optional** - if `UPSTASH_REDIS_REST_URL` is not set, `getRedis()` returns `null` and all cache functions in `lib/cache.js` silently no-op.
## Cache Layer: `backend/lib/cache.js`
All cache operations follow this contract:
- Accept `redis` as the first argument
- If `redis` is `null`, return immediately (no-op)
-- Wrap all `redis` calls in `try/catch` — a Redis failure must never break the main request
+- Wrap all `redis` calls in `try/catch` - a Redis failure must never break the main request
```js
export async function getVideosCache(redis, userId, accountId) {
@@ -71,4 +71,4 @@ Expiry: 10 minutes (checked by comparing embedded timestamp to Date.now())
Secret: INSTAGRAM_APP_SECRET
```
-These functions are in `cache.js` for historical reasons — they started as Redis-backed and were migrated to HMAC. They could logically live in `lib/auth.js` but remain in `cache.js` for stability.
+These functions are in `cache.js` for historical reasons - they started as Redis-backed and were migrated to HMAC. They could logically live in `lib/auth.js` but remain in `cache.js` for stability.
diff --git a/docs/architecture/backend/CRON.md b/docs/architecture/backend/CRON.md
index c860e78..1e79777 100644
--- a/docs/architecture/backend/CRON.md
+++ b/docs/architecture/backend/CRON.md
@@ -11,7 +11,7 @@ Both cron triggers invoke the `scheduled` export from `backend/server.js`.
## Cron Handlers
-### `*/15 * * * *` — Instagram Scheduled Post Publisher
+### `*/15 * * * *` - Instagram Scheduled Post Publisher
**Function:** `processScheduledPosts(supabase)` in `backend/utils/scheduler.js`
@@ -24,11 +24,11 @@ Both cron triggers invoke the `scheduled` export from `backend/server.js`.
- On success: sets status to `'published'`, stores `publishedMediaId` and `publishedAt` in `data`
- On failure: sets status to `'failed'`, stores `error` message in `data`
-**No userId filter** — the scheduler operates across all users. It uses the service-role Supabase client.
+**No userId filter** - the scheduler operates across all users. It uses the service-role Supabase client.
**Concurrency safety:** The `'publishing'` status acts as a mutex. If the Worker cron and GitHub Actions cron overlap, the second one to claim a post will find it already in `'publishing'` state and skip it (it won't appear in the `status=pending` query).
-### `0 0 * * *` — Instagram Token Auto-Refresh
+### `0 0 * * *` - Instagram Token Auto-Refresh
**Function:** `autoRefreshInstagramTokens(supabase)` in `backend/services/instagram.js`
diff --git a/docs/architecture/backend/HONO.md b/docs/architecture/backend/HONO.md
index 701c2e6..1ef652d 100644
--- a/docs/architecture/backend/HONO.md
+++ b/docs/architecture/backend/HONO.md
@@ -1,4 +1,4 @@
-# Backend — Hono Application Structure
+# Backend - Hono Application Structure
## Entry Point: `backend/server.js`
@@ -117,7 +117,7 @@ app.onError((err, c) => {
});
```
-Route handlers should catch their own errors and return descriptive messages. Do not throw from route handlers — catch and return JSON error responses with appropriate status codes.
+Route handlers should catch their own errors and return descriptive messages. Do not throw from route handlers - catch and return JSON error responses with appropriate status codes.
## Environment Access
diff --git a/docs/architecture/backend/MIDDLEWARE.md b/docs/architecture/backend/MIDDLEWARE.md
index 3306c5c..fe19e54 100644
--- a/docs/architecture/backend/MIDDLEWARE.md
+++ b/docs/architecture/backend/MIDDLEWARE.md
@@ -12,7 +12,7 @@ Request arrives
2. Client injection app.use('*', clientInjectionMiddleware)
│
▼
-3. requireAuth api.use('*', requireAuth) ← protected routes only
+3. requireAuth api.use('*', requireAuth) <- protected routes only
│
▼
Route handler
@@ -25,7 +25,7 @@ Route handler
**Source:** `hono/cors` (Hono built-in)
**Applied to:** Every request
-Configured with defaults — allows all origins in development. For production, the Worker's CORS behavior should be tightened to only allow `FRONTEND_URL`.
+Configured with defaults - allows all origins in development. For production, the Worker's CORS behavior should be tightened to only allow `FRONTEND_URL`.
**Current config:** `cors()` with no options (allows all origins). This is acceptable for a self-hosted deployment where the Worker URL is not publicly advertised.
@@ -36,7 +36,7 @@ Configured with defaults — allows all origins in development. For production,
**Source:** Inline in `backend/server.js`
**Applied to:** Every request
-Creates per-request Supabase and Redis client instances and sets them on the Hono context. This is the correct pattern for Cloudflare Workers — clients must be created fresh per request because there is no persistent process memory.
+Creates per-request Supabase and Redis client instances and sets them on the Hono context. This is the correct pattern for Cloudflare Workers - clients must be created fresh per request because there is no persistent process memory.
```js
app.use('*', async (c, next) => {
@@ -46,8 +46,8 @@ app.use('*', async (c, next) => {
});
```
-**`getSupabase(env)`** — creates a Supabase client with the service-role key. Used for all DB operations.
-**`getRedis(env)`** — creates an Upstash Redis client if `UPSTASH_REDIS_REST_URL` is set, otherwise returns `null`. All cache functions in `lib/cache.js` handle `null` silently.
+**`getSupabase(env)`** - creates a Supabase client with the service-role key. Used for all DB operations.
+**`getRedis(env)`** - creates an Upstash Redis client if `UPSTASH_REDIS_REST_URL` is set, otherwise returns `null`. All cache functions in `lib/cache.js` handle `null` silently.
---
@@ -72,11 +72,11 @@ export async function requireAuth(c, next) {
**What it does:**
1. Extracts `Authorization: Bearer <token>` header
2. Creates a Supabase **anon** client (not service-role) to verify the JWT
-3. Calls `supabaseAuth.auth.getUser(token)` — Supabase validates the token signature
+3. Calls `supabaseAuth.auth.getUser(token)` - Supabase validates the token signature
4. Sets `userId` (UUID) and `userEmail` (string) on the Hono context
5. Returns 401 JSON if token is missing, invalid, or expired
-**Critical:** `userId` from this middleware is the only trusted source of user identity. Route handlers must use `c.get('userId')` — never accept a userId from request body or query params.
+**Critical:** `userId` from this middleware is the only trusted source of user identity. Route handlers must use `c.get('userId')` - never accept a userId from request body or query params.
---
diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.md
index 4edfa47..bc0e55c 100644
--- a/docs/architecture/backend/ROUTES.md
+++ b/docs/architecture/backend/ROUTES.md
@@ -14,13 +14,13 @@ All routes live under `/api`. Routes under the `api` sub-app require a valid Sup
### Keys
| Method | Path | File | Purpose |
|---|---|---|---|
-| GET | `/api/keys` | `routes/keys.js` | Returns `{ youtube: bool, instagram: bool, cloudinary: bool }` — whether each API key is configured |
+| GET | `/api/keys` | `routes/keys.js` | Returns `{ youtube: bool, instagram: bool, cloudinary: bool }` - whether each API key is configured |
### Accounts
| Method | Path | File | Purpose |
|---|---|---|---|
| GET | `/api/accounts` | `routes/accounts.js` | List all user accounts (tokens stripped via `safeAccount()`) |
-| POST | `/api/accounts` | `routes/accounts.js` | Add YouTube channel — resolves URL/handle to channel ID, fetches stats |
+| POST | `/api/accounts` | `routes/accounts.js` | Add YouTube channel - resolves URL/handle to channel ID, fetches stats |
| DELETE | `/api/accounts/:id` | `routes/accounts.js` | Remove account + invalidate Redis cache for that account |
| POST | `/api/accounts/refresh-all` | `routes/accounts.js` | Refresh stats for every account; returns updated accounts list |
| POST | `/api/accounts/:id/refresh` | `routes/accounts.js` | Refresh a single account's stats |
@@ -30,9 +30,9 @@ All routes live under `/api`. Routes under the `api` sub-app require a valid Sup
### Analytics
| Method | Path | File | Purpose |
|---|---|---|---|
-| GET | `/api/accounts/:id/analytics` | `routes/analytics.js` | Full YouTube analytics — fetches up to 500 videos, runs `computeVideoAnalytics()`, returns 50+ metrics |
+| GET | `/api/accounts/:id/analytics` | `routes/analytics.js` | Full YouTube analytics - fetches up to 500 videos, runs `computeVideoAnalytics()`, returns 50+ metrics |
| GET | `/api/accounts/:id/videos` | `routes/analytics.js` | Returns cached video list (from Redis if available) |
-| GET | `/api/accounts/:id/ig-analytics` | `routes/analytics.js` | Instagram analytics — fetches up to 500 media, runs `computeInstagramAnalytics()` |
+| GET | `/api/accounts/:id/ig-analytics` | `routes/analytics.js` | Instagram analytics - fetches up to 500 media, runs `computeInstagramAnalytics()` |
| GET | `/api/accounts/:id/ig-media` | `routes/analytics.js` | Returns cached Instagram media list |
| GET | `/api/comparison` | `routes/analytics.js` | Cross-account comparison data for the Overview dashboard |
@@ -58,7 +58,7 @@ All routes live under `/api`. Routes under the `api` sub-app require a valid Sup
| PUT | `/api/scheduled-posts/:id` | `routes/scheduledPosts.js` | Edit a pending post (caption, scheduled time, media, etc.) |
| DELETE | `/api/scheduled-posts/:id` | `routes/scheduledPosts.js` | Delete a single post |
| DELETE | `/api/scheduled-posts` | `routes/scheduledPosts.js` | Delete all posts except those with `status: 'publishing'` |
-| GET | `/api/process-scheduled` | `routes/scheduledPosts.js` | Manual trigger — runs `processScheduledPosts()` immediately (dev/test) |
+| GET | `/api/process-scheduled` | `routes/scheduledPosts.js` | Manual trigger - runs `processScheduledPosts()` immediately (dev/test) |
| POST | `/api/process-scheduled` | `routes/scheduledPosts.js` | Same as above |
### Settings
diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.md
index 7e0962c..e144eaa 100644
--- a/docs/architecture/backend/SERVICES.md
+++ b/docs/architecture/backend/SERVICES.md
@@ -25,12 +25,12 @@ async function igFetch(path, token, options = {}) {
| Function | Purpose |
|---|---|
-| `exchangeCodeForToken(code, env)` | Short-lived code → short-lived token (Instagram OAuth step 1) |
-| `exchangeForLongLivedToken(shortToken, env)` | Short-lived → 60-day long-lived token (Instagram OAuth step 2) |
+| `exchangeCodeForToken(code, env)` | Short-lived code -> short-lived token (Instagram OAuth step 1) |
+| `exchangeForLongLivedToken(shortToken, env)` | Short-lived -> 60-day long-lived token (Instagram OAuth step 2) |
| `getIGProfile(accessToken)` | Fetches `id, username, account_type, media_count` for the token |
| `getIGMedia(accessToken, limit)` | Paginates media items up to `limit` (default 500) |
| `refreshLongLivedToken(accessToken)` | Extends a long-lived token; call before expiry |
-| `autoRefreshInstagramTokens(supabase)` | Cron handler — refreshes all tokens expiring within 15 days |
+| `autoRefreshInstagramTokens(supabase)` | Cron handler - refreshes all tokens expiring within 15 days |
| `computeInstagramAnalytics(media, profile)` | Computes engagement rates, hashtag analysis, timing patterns, monthly breakdown |
| `publishIGContainer(igUserId, params, token)` | Creates a media container via Graph API |
| `publishIGMedia(igUserId, containerId, token)` | Publishes a container; returns `mediaId` |
diff --git a/docs/architecture/cloudflare/CI_CD.md b/docs/architecture/cloudflare/CI_CD.md
index 62b267f..be2d04c 100644
--- a/docs/architecture/cloudflare/CI_CD.md
+++ b/docs/architecture/cloudflare/CI_CD.md
@@ -1,4 +1,4 @@
-# CI/CD — GitHub Actions
+# CI/CD - GitHub Actions
## Workflows
@@ -11,8 +11,8 @@
2. Run `wrangler deploy` via `cloudflare/wrangler-action@v4`
**Required GitHub secrets:**
-- `CLOUDFLARE_API_TOKEN` — API token with Worker deploy permission
-- `CLOUDFLARE_ACCOUNT_ID` — your Cloudflare account ID
+- `CLOUDFLARE_API_TOKEN` - API token with Worker deploy permission
+- `CLOUDFLARE_ACCOUNT_ID` - your Cloudflare account ID
**Does not** redeploy on frontend-only changes, documentation changes, or script changes.
@@ -25,15 +25,15 @@
**What it does:**
1. Checkout repo
2. `npm ci` (in `frontend/`)
-3. `npm run build` — Vite builds to `frontend/dist/`
+3. `npm run build` - Vite builds to `frontend/dist/`
4. Deploy `dist/` to Cloudflare Pages via `wrangler pages deploy`
**Required GitHub secrets:**
- `CLOUDFLARE_API_TOKEN`
- `CLOUDFLARE_ACCOUNT_ID`
-- `VITE_SUPABASE_URL` — injected at build time
-- `VITE_SUPABASE_ANON_KEY` — injected at build time
-- `VITE_API_URL` — injected at build time (the Worker URL)
+- `VITE_SUPABASE_URL` - injected at build time
+- `VITE_SUPABASE_ANON_KEY` - injected at build time
+- `VITE_API_URL` - injected at build time (the Worker URL)
**Note:** `VITE_*` variables are baked into the built JS bundle at build time. They are not runtime environment variables.
@@ -42,8 +42,8 @@
### `publish-scheduled.yml`
**Trigger:**
-- `schedule: cron('*/15 * * * *')` — every 15 minutes
-- `workflow_dispatch` — manual trigger from GitHub Actions UI
+- `schedule: cron('*/15 * * * *')` - every 15 minutes
+- `workflow_dispatch` - manual trigger from GitHub Actions UI
**What it does:**
1. Checkout repo
@@ -51,8 +51,8 @@
3. `node scripts/publish-scheduled.js`
**Required GitHub secrets:**
-- `SUPABASE_URL` — the Supabase project URL
-- `SUPABASE_SERVICE_KEY` — service-role key (needed to query all users' posts)
+- `SUPABASE_URL` - the Supabase project URL
+- `SUPABASE_SERVICE_KEY` - service-role key (needed to query all users' posts)
**This is the GitHub Actions fallback for the Worker cron.** Both this workflow and the Worker cron (`*/15`) run the same publishing logic against the same Supabase table. The `publishing` status mutex prevents double-publishing.
@@ -61,11 +61,11 @@
## Path Filtering
GitHub Actions path filters mean:
-- Editing `frontend/` only → triggers `deploy-frontend.yml`, not `deploy-backend.yml`
-- Editing `backend/` only → triggers `deploy-backend.yml`, not `deploy-frontend.yml`
-- Editing `scripts/` → triggers neither deploy workflow (only `publish-scheduled.yml` on its cron)
-- Editing `docs/` → triggers nothing
-- Editing `CLAUDE.md`, `DECISIONS.md`, etc. → triggers nothing
+- Editing `frontend/` only -> triggers `deploy-frontend.yml`, not `deploy-backend.yml`
+- Editing `backend/` only -> triggers `deploy-backend.yml`, not `deploy-frontend.yml`
+- Editing `scripts/` -> triggers neither deploy workflow (only `publish-scheduled.yml` on its cron)
+- Editing `docs/` -> triggers nothing
+- Editing `CLAUDE.md`, `DECISIONS.md`, etc. -> triggers nothing
## Deployment Verification
@@ -78,14 +78,14 @@ curl https://twiligent.ujjwalkrai.workers.dev/api/health
```
**Frontend:**
-Open `https://twiligent.pages.dev` — verify login page loads, accounts load after auth.
+Open `https://twiligent.pages.dev` - verify login page loads, accounts load after auth.
**Publisher:**
-Trigger `publish-scheduled.yml` manually via GitHub Actions UI → Actions → "Instagram Scheduled Publisher" → "Run workflow" → check the run log for expected output.
+Trigger `publish-scheduled.yml` manually via GitHub Actions UI -> Actions -> "Instagram Scheduled Publisher" -> "Run workflow" -> check the run log for expected output.
## Adding a New Workflow
1. Create `.github/workflows/my-workflow.yml`
2. Add appropriate path filters to avoid unnecessary runs
3. Document it in `docs/architecture/cloudflare/CI_CD.md` (this file)
-4. Add any required secrets via GitHub repo → Settings → Secrets → Actions
+4. Add any required secrets via GitHub repo -> Settings -> Secrets -> Actions
diff --git a/docs/architecture/cloudflare/PAGES.md b/docs/architecture/cloudflare/PAGES.md
index 930b023..b2841e5 100644
--- a/docs/architecture/cloudflare/PAGES.md
+++ b/docs/architecture/cloudflare/PAGES.md
@@ -2,7 +2,7 @@
## Overview
-The React frontend is deployed to Cloudflare Pages. It is a static SPA — all routing is client-side (React Router), and the Cloudflare Pages `_redirects` file handles the SPA fallback.
+The React frontend is deployed to Cloudflare Pages. It is a static SPA - all routing is client-side (React Router), and the Cloudflare Pages `_redirects` file handles the SPA fallback.
## Build Configuration
@@ -36,11 +36,11 @@ The frontend accesses environment variables at **build time** via Vite's `VITE_`
| Variable | Purpose | Where set |
|---|---|---|
-| `VITE_SUPABASE_URL` | Supabase project URL (public) | Cloudflare Pages → Settings → Environment Variables |
-| `VITE_SUPABASE_ANON_KEY` | Supabase anon key (public) | Cloudflare Pages → Settings → Environment Variables |
-| `VITE_API_URL` | Backend Worker URL | Cloudflare Pages → Settings → Environment Variables |
+| `VITE_SUPABASE_URL` | Supabase project URL (public) | Cloudflare Pages -> Settings -> Environment Variables |
+| `VITE_SUPABASE_ANON_KEY` | Supabase anon key (public) | Cloudflare Pages -> Settings -> Environment Variables |
+| `VITE_API_URL` | Backend Worker URL | Cloudflare Pages -> Settings -> Environment Variables |
-**These are public values** — they are baked into the JavaScript bundle. Do not add the service role key here. Do not add any private API credentials here.
+**These are public values** - they are baked into the JavaScript bundle. Do not add the service role key here. Do not add any private API credentials here.
Vite exposes them at runtime as `import.meta.env.VITE_*`.
@@ -61,7 +61,7 @@ npx wrangler pages deploy dist --project-name=twiligent
The app is accessible at both:
- `twiligent.pages.dev` (Cloudflare Pages default)
-- Custom domain configured in Cloudflare Pages → Custom domains
+- Custom domain configured in Cloudflare Pages -> Custom domains
## Local Development
diff --git a/docs/architecture/cloudflare/WORKERS.md b/docs/architecture/cloudflare/WORKERS.md
index 2289e51..44b7a51 100644
--- a/docs/architecture/cloudflare/WORKERS.md
+++ b/docs/architecture/cloudflare/WORKERS.md
@@ -11,10 +11,10 @@ compatibility_date = "2025-01-01"
crons = ["*/15 * * * *", "0 0 * * *"]
```
-- `name` — the Worker name as deployed on Cloudflare; also determines the default URL
-- `main` — entry point file (ES module)
-- `compatibility_date` — pins the Workers runtime API version
-- `crons` — cron trigger schedules (see `docs/architecture/backend/CRON.md`)
+- `name` - the Worker name as deployed on Cloudflare; also determines the default URL
+- `main` - entry point file (ES module)
+- `compatibility_date` - pins the Workers runtime API version
+- `crons` - cron trigger schedules (see `docs/architecture/backend/CRON.md`)
## Worker Export Format
@@ -24,9 +24,9 @@ The Worker exports two handlers:
export default {
fetch: app.fetch, // handles HTTP requests (the Hono app)
async scheduled(event, env, ctx) { // handles cron triggers
- // event.cron — the cron expression that fired
- // env — Worker environment bindings (secrets + vars)
- // ctx.waitUntil(promise) — keeps Worker alive for background work
+ // event.cron - the cron expression that fired
+ // env - Worker environment bindings (secrets + vars)
+ // ctx.waitUntil(promise) - keeps Worker alive for background work
}
};
```
@@ -38,8 +38,8 @@ All secrets are set via `wrangler secret put <NAME>`. They are available at runt
| Secret | Required | Purpose |
|---|---|---|
| `SUPABASE_URL` | Yes | Supabase project URL |
-| `SUPABASE_SERVICE_KEY` | Yes | Service-role key — bypasses RLS, all DB operations |
-| `SUPABASE_ANON_KEY` | Yes | Anon key — used only for JWT verification in `requireAuth` |
+| `SUPABASE_SERVICE_KEY` | Yes | Service-role key - bypasses RLS, all DB operations |
+| `SUPABASE_ANON_KEY` | Yes | Anon key - used only for JWT verification in `requireAuth` |
| `YOUTUBE_API_KEY` | Yes | Shared YouTube Data API v3 key (all users share quota) |
| `INSTAGRAM_APP_ID` | Yes | Meta/Facebook App ID for OAuth |
| `INSTAGRAM_APP_SECRET` | Yes | Used for OAuth token exchange + HMAC state signing |
@@ -55,7 +55,7 @@ All secrets are set via `wrangler secret put <NAME>`. They are available at runt
```bash
wrangler secret put SUPABASE_URL
wrangler secret put SUPABASE_SERVICE_KEY
-# (paste value when prompted — no echo)
+# (paste value when prompted - no echo)
```
### Local development (`.dev.vars`)
@@ -85,7 +85,7 @@ These are hard constraints imposed by the Cloudflare Workers runtime. Violating
1. **No Node.js APIs.** No `fs`, `Buffer`, `path`, `process.env` (use `c.env`), `require()`. Everything must be ESM `import`.
-2. **No binary file handling.** The Worker cannot efficiently stream large binary files. Never add routes that accept file uploads — Cloudinary handles that directly from the browser.
+2. **No binary file handling.** The Worker cannot efficiently stream large binary files. Never add routes that accept file uploads - Cloudinary handles that directly from the browser.
3. **No persistent state between requests.** The Worker isolate may be a fresh instance on every request. Do not rely on module-level variables to persist state across requests. All state must come from Supabase, Redis, or Worker KV.
diff --git a/docs/architecture/data-flows/ANALYTICS.md b/docs/architecture/data-flows/ANALYTICS.md
index 725db1a..20c9f67 100644
--- a/docs/architecture/data-flows/ANALYTICS.md
+++ b/docs/architecture/data-flows/ANALYTICS.md
@@ -1,4 +1,4 @@
-# Data Flow — Analytics
+# Data Flow - Analytics
## YouTube Analytics Flow
@@ -6,26 +6,26 @@
User navigates to /channel/:id
│
▼
-ChannelAnalytics.jsx mounts → api.getAnalytics(id)
- → GET /api/accounts/:id/analytics
+ChannelAnalytics.jsx mounts -> api.getAnalytics(id)
+ -> GET /api/accounts/:id/analytics
│
▼
Worker: analyticsRouter
- 1. getAccountById(supabase, id, userId) — verify ownership
+ 1. getAccountById(supabase, id, userId) - verify ownership
2. redis cache check: getVideosCache(redis, userId, id)
- → cache hit: return cached data immediately
- → cache miss: continue
+ -> cache hit: return cached data immediately
+ -> cache miss: continue
3. Fetch from YouTube Data API:
a. GET /channels?part=snippet,statistics,contentDetails&id={channelId}
- → channel metadata + subscriber/view/video counts + uploadPlaylistId
+ -> channel metadata + subscriber/view/video counts + uploadPlaylistId
b. Paginate /playlistItems?part=contentDetails&playlistId={uploadPlaylistId}
- → up to 10 pages × 50 items = 500 video IDs
+ -> up to 10 pages × 50 items = 500 video IDs
c. Batch /videos?part=snippet,statistics&id={id1,id2,...}
- → 50 videos per batch request → statistics (views, likes, comments, duration)
+ -> 50 videos per batch request -> statistics (views, likes, comments, duration)
4. computeVideoAnalytics(videos, channel)
- → 50+ computed metrics
+ -> 50+ computed metrics
5. setVideosCache(redis, userId, id, result)
- → cache result for future requests
+ -> cache result for future requests
6. Return JSON
```
@@ -67,23 +67,23 @@ ChannelAnalytics.jsx mounts → api.getAnalytics(id)
User navigates to /instagram/:id
│
▼
-InstagramAnalytics.jsx mounts → api.getIGAnalytics(id)
- → GET /api/accounts/:id/ig-analytics
+InstagramAnalytics.jsx mounts -> api.getIGAnalytics(id)
+ -> GET /api/accounts/:id/ig-analytics
│
▼
Worker: analyticsRouter
- 1. getAccountById(supabase, id, userId) — verify ownership + get accessToken
+ 1. getAccountById(supabase, id, userId) - verify ownership + get accessToken
2. redis cache check: getIGCache(redis, userId, id)
- → cache hit: return immediately
- → cache miss: continue
+ -> cache hit: return immediately
+ -> cache miss: continue
3. Fetch from Instagram Graph API:
a. GET /me?fields=id,username,account_type,media_count,followers_count
- → profile data
+ -> profile data
b. Paginate /me/media?fields=id,media_type,timestamp,like_count,comments_count,
caption,permalink,thumbnail_url,media_url
- → up to 500 media items (10 pages × 50)
+ -> up to 500 media items (10 pages × 50)
4. computeInstagramAnalytics(media, profile)
- → engagement metrics
+ -> engagement metrics
5. setIGCache(redis, userId, id, result)
6. Return JSON
```
@@ -130,9 +130,9 @@ User navigates to /
│
▼
Overview.jsx uses accounts from AppContext
- → Combined totals computed from account.subscriberCount, viewCount, etc.
- → api.getComparison() → GET /api/comparison
- → returns all accounts sorted by view count, subscriber count
+ -> Combined totals computed from account.subscriberCount, viewCount, etc.
+ -> api.getComparison() -> GET /api/comparison
+ -> returns all accounts sorted by view count, subscriber count
```
-The Overview doesn't fetch fresh analytics — it uses the cached account metadata (subscriber counts, view counts) already in `AppContext.accounts`. Deep per-account analytics (video lists, engagement rates) are only fetched when the user navigates to a specific account page.
+The Overview doesn't fetch fresh analytics - it uses the cached account metadata (subscriber counts, view counts) already in `AppContext.accounts`. Deep per-account analytics (video lists, engagement rates) are only fetched when the user navigates to a specific account page.
diff --git a/docs/architecture/data-flows/AUTHENTICATION.md b/docs/architecture/data-flows/AUTHENTICATION.md
index fe5a8e3..8ebd83e 100644
--- a/docs/architecture/data-flows/AUTHENTICATION.md
+++ b/docs/architecture/data-flows/AUTHENTICATION.md
@@ -1,4 +1,4 @@
-# Data Flow — Authentication
+# Data Flow - Authentication
## Login Flow
@@ -6,26 +6,26 @@
User visits the app
│
▼
-React Router: no session → ProtectedRoute redirects to /login
+React Router: no session -> ProtectedRoute redirects to /login
│
▼
Login.jsx renders email/password form
│
▼
-User submits → AuthContext.signIn(email, password)
- → supabase.auth.signInWithPassword({ email, password })
- → Supabase validates credentials
- → Returns { session: { access_token, user: { id, email } } }
- → AuthProvider.setSession(session)
- → onAuthStateChange fires, React re-renders
+User submits -> AuthContext.signIn(email, password)
+ -> supabase.auth.signInWithPassword({ email, password })
+ -> Supabase validates credentials
+ -> Returns { session: { access_token, user: { id, email } } }
+ -> AuthProvider.setSession(session)
+ -> onAuthStateChange fires, React re-renders
│
▼
-ProtectedRoute sees session is now set → renders children (app)
+ProtectedRoute sees session is now set -> renders children (app)
│
▼
-AppProvider mounts → loadAccounts() fires
- → api.getAccounts() → GET /api/accounts (with JWT)
- → accounts[] populated
+AppProvider mounts -> loadAccounts() fires
+ -> api.getAccounts() -> GET /api/accounts (with JWT)
+ -> accounts[] populated
│
▼
User sees Overview dashboard
@@ -43,12 +43,12 @@ Supabase JWT stored in browser (localStorage by default)
On app load: supabase.auth.getSession() checks stored token
- If valid: session is set immediately (no network request)
- If expired: Supabase attempts to refresh via refresh_token
- - If refresh fails: session is null → redirect to /login
+ - If refresh fails: session is null -> redirect to /login
│
▼
supabase.auth.onAuthStateChange watches for:
- TOKEN_REFRESHED: updates session with new access_token
- - SIGNED_OUT: clears session → ProtectedRoute redirects to /login
+ - SIGNED_OUT: clears session -> ProtectedRoute redirects to /login
- USER_UPDATED: updates user in session
```
@@ -59,30 +59,30 @@ API call arrives at Worker with Authorization: Bearer <token>
│
▼
requireAuth middleware
- → extracts token from header
- → getSupabaseAuth(env) — creates Supabase client with ANON key
- → supabaseAuth.auth.getUser(token)
- → Supabase validates:
+ -> extracts token from header
+ -> getSupabaseAuth(env) - creates Supabase client with ANON key
+ -> supabaseAuth.auth.getUser(token)
+ -> Supabase validates:
1. JWT signature (signed with Supabase project secret)
2. Token expiry (exp claim)
3. Token not invalidated (Supabase can invalidate on signOut)
- → On success: { user: { id, email } }
- → c.set('userId', user.id)
- → c.set('userEmail', user.email)
- → await next() → route handler executes
+ -> On success: { user: { id, email } }
+ -> c.set('userId', user.id)
+ -> c.set('userEmail', user.email)
+ -> await next() -> route handler executes
```
## Sign Out Flow
```
User clicks Sign Out (Header.jsx)
- → AuthContext.signOut()
- → supabase.auth.signOut()
- → Supabase invalidates refresh token server-side
- → Local session cleared from browser storage
- → onAuthStateChange fires with SIGNED_OUT
- → session = null
- → ProtectedRoute → redirect to /login
+ -> AuthContext.signOut()
+ -> supabase.auth.signOut()
+ -> Supabase invalidates refresh token server-side
+ -> Local session cleared from browser storage
+ -> onAuthStateChange fires with SIGNED_OUT
+ -> session = null
+ -> ProtectedRoute -> redirect to /login
```
## Token Refresh
@@ -93,6 +93,6 @@ No manual refresh logic is needed in the frontend.
## Instagram OAuth (Separate Flow)
-Instagram OAuth is not user authentication — it is account connection. The flow is documented in the system overview under "Instagram OAuth" and does not use Supabase Auth.
+Instagram OAuth is not user authentication - it is account connection. The flow is documented in the system overview under "Instagram OAuth" and does not use Supabase Auth.
The Instagram OAuth state is secured via HMAC (see `docs/architecture/backend/CACHING.md`) and the flow ends by creating a row in the `accounts` table, not a Supabase Auth user.
diff --git a/docs/architecture/data-flows/PUBLISHING.md b/docs/architecture/data-flows/PUBLISHING.md
index a93a8eb..a51106d 100644
--- a/docs/architecture/data-flows/PUBLISHING.md
+++ b/docs/architecture/data-flows/PUBLISHING.md
@@ -1,4 +1,4 @@
-# Data Flow — Instagram Publishing
+# Data Flow - Instagram Publishing
## Immediate Publishing
@@ -7,38 +7,38 @@ User selects account + uploads media + fills caption
│
▼
1. Frontend: Upload media to Cloudinary
- api.getCloudinaryConfig() → GET /api/cloudinary-config
- → returns { cloudName, uploadPreset }
+ api.getCloudinaryConfig() -> GET /api/cloudinary-config
+ -> returns { cloudName, uploadPreset }
Browser uploads directly to Cloudinary using unsigned preset
- → Cloudinary returns public URL (e.g., https://res.cloudinary.com/cloud/image/upload/...)
+ -> Cloudinary returns public URL (e.g., https://res.cloudinary.com/cloud/image/upload/...)
│
▼
2. Frontend: Create media container
api.createIGContainer(accountId, { mediaUrl, caption, mediaType, ... })
- → POST /api/accounts/:id/ig-publish
- → Backend: calls Instagram Graph API
+ -> POST /api/accounts/:id/ig-publish
+ -> Backend: calls Instagram Graph API
POST https://graph.instagram.com/v25.0/{igUserId}/media
params: { image_url|video_url, caption, media_type, access_token }
- → Returns { containerId }
+ -> Returns { containerId }
│
▼
3. For REELS or STORIES: poll container status (images skip this step)
api.getIGContainerStatus(containerId, accountId)
- → GET /api/ig-container/:containerId/status?accountId=:id
- → Backend: GET https://graph.instagram.com/v25.0/{containerId}?fields=status_code,status
- → Poll every 3 seconds, timeout at 3 minutes
- → Wait for status_code = 'FINISHED'
- → ERROR → throw error, mark as failed
- → EXPIRED → throw error
+ -> GET /api/ig-container/:containerId/status?accountId=:id
+ -> Backend: GET https://graph.instagram.com/v25.0/{containerId}?fields=status_code,status
+ -> Poll every 3 seconds, timeout at 3 minutes
+ -> Wait for status_code = 'FINISHED'
+ -> ERROR -> throw error, mark as failed
+ -> EXPIRED -> throw error
│
▼
4. Frontend: Publish the container
api.publishIGContainer(accountId, containerId)
- → POST /api/accounts/:id/ig-media-publish
- → Backend: POST https://graph.instagram.com/v25.0/{igUserId}/media_publish
+ -> POST /api/accounts/:id/ig-media-publish
+ -> Backend: POST https://graph.instagram.com/v25.0/{igUserId}/media_publish
body: { creation_id: containerId, access_token }
- → Returns { mediaId }
+ -> Returns { mediaId }
│
▼
5. Frontend: Show success toast with mediaId
@@ -51,14 +51,14 @@ User creates a scheduled post
│
▼
1. Frontend: api.createScheduledPost({ accountId, scheduledAt, mediaUrl, caption, ... })
- → POST /api/scheduled-posts
- → Backend: db.createPost(supabase, post, userId)
+ -> POST /api/scheduled-posts
+ -> Backend: db.createPost(supabase, post, userId)
INSERT INTO scheduled_posts (id, user_id, account_id, status='pending', scheduled_at, data)
│
▼
2. Every 15 minutes, one of two schedulers fires:
- A. Cloudflare Worker cron → processScheduledPosts(supabase)
- B. GitHub Actions → node scripts/publish-scheduled.js → direct Supabase REST calls
+ A. Cloudflare Worker cron -> processScheduledPosts(supabase)
+ B. GitHub Actions -> node scripts/publish-scheduled.js -> direct Supabase REST calls
│
▼
3. Scheduler queries due posts:
@@ -67,7 +67,7 @@ User creates a scheduled post
▼
4. For each due post:
a. UPDATE scheduled_posts SET status='publishing' WHERE id=:id AND status='pending'
- (This is the mutex — prevents double-publish if both schedulers fire simultaneously)
+ (This is the mutex - prevents double-publish if both schedulers fire simultaneously)
b. SELECT account WHERE id=:accountId
(Gets the accessToken from accounts.data)
diff --git a/docs/architecture/data-flows/SCHEDULING.md b/docs/architecture/data-flows/SCHEDULING.md
index 1b05819..e7b91ba 100644
--- a/docs/architecture/data-flows/SCHEDULING.md
+++ b/docs/architecture/data-flows/SCHEDULING.md
@@ -1,4 +1,4 @@
-# Data Flow — Scheduled Publishing (Dual Scheduler)
+# Data Flow - Scheduled Publishing (Dual Scheduler)
## Overview
@@ -7,12 +7,12 @@ Two independent systems check for due posts every 15 minutes. Both target the sa
## System A: Cloudflare Worker Cron
**Trigger:** `*/15 * * * *` cron in `wrangler.toml`
-**Handler:** `backend/utils/scheduler.js` → `processScheduledPosts(supabase)`
+**Handler:** `backend/utils/scheduler.js` -> `processScheduledPosts(supabase)`
**Supabase client:** service-role (created from Worker env)
## System B: GitHub Actions
-**Trigger:** `publish-scheduled.yml` workflow → `schedule: cron('*/15 * * * *')`
+**Trigger:** `publish-scheduled.yml` workflow -> `schedule: cron('*/15 * * * *')`
**Handler:** `scripts/publish-scheduled.js` (standalone Node.js, zero npm deps)
**Supabase client:** direct REST API calls using `SUPABASE_URL` + `SUPABASE_SERVICE_KEY` GitHub secrets
@@ -42,13 +42,13 @@ The `AND status = 'pending'` condition means only one scheduler can successfully
pending The post is waiting to be published
│
▼ scheduler picks it up
-publishing Claimed by a scheduler — in-flight
+publishing Claimed by a scheduler - in-flight
│
- ├─ Instagram API succeeds ──→ published
+ ├─ Instagram API succeeds ──-> published
│ + data.publishedMediaId
│ + data.publishedAt
│
- └─ Instagram API fails ─────→ failed
+ └─ Instagram API fails ─────-> failed
+ data.error (error message)
```
@@ -69,10 +69,10 @@ Both schedulers implement the same logic:
## Configuration Requirements
### For Worker Cron (System A)
-- Worker secrets: `SUPABASE_URL`, `SUPABASE_SERVICE_KEY`, `INSTAGRAM_APP_ID` (not used by scheduler directly — the account's stored `accessToken` is used)
+- Worker secrets: `SUPABASE_URL`, `SUPABASE_SERVICE_KEY`, `INSTAGRAM_APP_ID` (not used by scheduler directly - the account's stored `accessToken` is used)
- No additional setup beyond deploying the Worker
### For GitHub Actions (System B)
- GitHub repo secrets: `SUPABASE_URL`, `SUPABASE_SERVICE_KEY`
- The `publish-scheduled.yml` workflow must be enabled
-- Note: These GitHub secrets are only required for System B — the main deploy workflows (`deploy-backend.yml`, `deploy-frontend.yml`) do not need them
+- Note: These GitHub secrets are only required for System B - the main deploy workflows (`deploy-backend.yml`, `deploy-frontend.yml`) do not need them
diff --git a/docs/architecture/database/SCHEMA.md b/docs/architecture/database/SCHEMA.md
index 4c8989c..a97b21c 100644
--- a/docs/architecture/database/SCHEMA.md
+++ b/docs/architecture/database/SCHEMA.md
@@ -4,7 +4,7 @@
Supabase (PostgreSQL) with three application tables. All tables include `user_id` (UUID) referencing `auth.users` to scope data per user.
-The backend uses the **service-role key** (bypasses Row Level Security) but enforces isolation by always appending `.eq('user_id', userId)` on user-scoped queries. The `userId` comes exclusively from the verified JWT — never from request input.
+The backend uses the **service-role key** (bypasses Row Level Security) but enforces isolation by always appending `.eq('user_id', userId)` on user-scoped queries. The `userId` comes exclusively from the verified JWT - never from request input.
Cron handlers (`processScheduledPosts`, `autoRefreshInstagramTokens`) intentionally omit the `userId` filter to operate across all users.
@@ -17,7 +17,7 @@ Stores connected YouTube channels and Instagram accounts.
| Column | Type | Nullable | Description |
|---|---|---|---|
| `id` | text | NOT NULL | PK. Client-generated: `Date.now().toString(36) + Math.random().toString(36).slice(2)` |
-| `user_id` | uuid | NOT NULL | FK → `auth.users.id`. All user-scoped queries filter on this. |
+| `user_id` | uuid | NOT NULL | FK -> `auth.users.id`. All user-scoped queries filter on this. |
| `platform` | text | NOT NULL | `'youtube'` or `'instagram'` |
| `data` | jsonb | NOT NULL | All platform-specific fields (see below) |
@@ -59,8 +59,8 @@ Stores connected YouTube channels and Instagram accounts.
### Indexes recommended
-- `accounts(user_id)` — speeds up all user-scoped queries
-- `accounts(platform)` — speeds up cross-user platform queries in cron handlers
+- `accounts(user_id)` - speeds up all user-scoped queries
+- `accounts(platform)` - speeds up cross-user platform queries in cron handlers
---
@@ -70,9 +70,9 @@ Per-user key-value configuration store.
| Column | Type | Nullable | Description |
|---|---|---|---|
-| `user_id` | uuid | NOT NULL | PK (composite). FK → `auth.users.id` |
+| `user_id` | uuid | NOT NULL | PK (composite). FK -> `auth.users.id` |
| `key` | text | NOT NULL | PK (composite). Currently only `'api_keys'` |
-| `value` | jsonb | — | Configuration payload |
+| `value` | jsonb | - | Configuration payload |
### Primary key: `(user_id, key)`
@@ -98,20 +98,20 @@ Stores Instagram posts queued for future publishing.
| Column | Type | Nullable | Description |
|---|---|---|---|
| `id` | text | NOT NULL | PK. Client-generated: same pattern as `accounts.id` |
-| `user_id` | uuid | NOT NULL | FK → `auth.users.id` |
-| `account_id` | text | NOT NULL | FK → `accounts.id` |
+| `user_id` | uuid | NOT NULL | FK -> `auth.users.id` |
+| `account_id` | text | NOT NULL | FK -> `accounts.id` |
| `status` | text | NOT NULL | `'pending'`, `'publishing'`, `'published'`, `'failed'` |
| `scheduled_at` | timestamptz | NOT NULL | UTC timestamp when the post should be published |
-| `data` | jsonb | — | Post content and result data (see below) |
+| `data` | jsonb | - | Post content and result data (see below) |
### Status lifecycle
```
-pending → publishing → published
+pending -> publishing -> published
↘ failed
```
-The `publishing` status is a mutex — it prevents double-publishing when both the Worker cron and GitHub Actions scheduler fire at the same time.
+The `publishing` status is a mutex - it prevents double-publishing when both the Worker cron and GitHub Actions scheduler fire at the same time.
### `data` jsonb shape
@@ -136,14 +136,14 @@ The `publishing` status is a mutex — it prevents double-publishing when both t
### Indexes recommended
-- `scheduled_posts(user_id)` — user-scoped queries
-- `scheduled_posts(status, scheduled_at)` — the cron scheduler query: `status=pending AND scheduled_at <= now()`
+- `scheduled_posts(user_id)` - user-scoped queries
+- `scheduled_posts(status, scheduled_at)` - the cron scheduler query: `status=pending AND scheduled_at <= now()`
---
-## `lib/db.js` — Query Layer
+## `lib/db.js` - Query Layer
-All SQL operations are centralized in `backend/lib/db.js`. Route handlers and cron handlers import named functions from this file — they never call `supabase.from()` directly.
+All SQL operations are centralized in `backend/lib/db.js`. Route handlers and cron handlers import named functions from this file - they never call `supabase.from()` directly.
### Available functions
@@ -162,7 +162,7 @@ saveSettings(supabase, keys, userId)
// Scheduled Posts
getPosts(supabase, userId?)
getPostById(supabase, id, userId?)
-getDuePosts(supabase) // for cron — no userId filter, selects pending+overdue
+getDuePosts(supabase) // for cron - no userId filter, selects pending+overdue
createPost(supabase, post, userId)
updatePost(supabase, id, updates, userId?)
deletePost(supabase, id, userId?)
diff --git a/docs/architecture/database/SECURITY.md b/docs/architecture/database/SECURITY.md
index 6fdee45..ed7e60f 100644
--- a/docs/architecture/database/SECURITY.md
+++ b/docs/architecture/database/SECURITY.md
@@ -4,16 +4,16 @@
The backend uses the **service-role key** for all database operations. This key bypasses Row Level Security (RLS). Data isolation is enforced by the application:
-1. `requireAuth` middleware verifies the JWT and sets `c.userId` from Supabase's response — this is the only trusted source of `userId`
+1. `requireAuth` middleware verifies the JWT and sets `c.userId` from Supabase's response - this is the only trusted source of `userId`
2. Every user-scoped query in `lib/db.js` appends `.eq('user_id', userId)` using this verified value
3. `userId` is never accepted from request body, query params, or any other user-controlled input
-**This means a missing `.eq('user_id', userId)` call is a security bug.** The centralization of all queries in `lib/db.js` makes this auditable — every public function signature documents whether it accepts a userId.
+**This means a missing `.eq('user_id', userId)` call is a security bug.** The centralization of all queries in `lib/db.js` makes this auditable - every public function signature documents whether it accepts a userId.
## Why Not Use RLS?
See `DECISIONS.md` ADR-011 for the full reasoning. Summary:
-- Cron handlers (scheduler, token refresh) need to query across all users — they cannot be scoped to a single JWT
+- Cron handlers (scheduler, token refresh) need to query across all users - they cannot be scoped to a single JWT
- Using the service-role key with application-layer filtering achieves the same isolation with less complexity
## Key Hierarchy
@@ -21,7 +21,7 @@ See `DECISIONS.md` ADR-011 for the full reasoning. Summary:
| Key | Where used | What it can do |
|---|---|---|
| `SUPABASE_SERVICE_KEY` | Cloudflare Worker (server-side only) | All operations, bypasses RLS |
-| `SUPABASE_ANON_KEY` | Cloudflare Worker (`requireAuth` only) | Only `getUser(token)` — JWT verification |
+| `SUPABASE_ANON_KEY` | Cloudflare Worker (`requireAuth` only) | Only `getUser(token)` - JWT verification |
| `VITE_SUPABASE_ANON_KEY` | Frontend browser | Supabase Auth (sign in, sign up, sign out, session management) |
The anon key has no meaningful permissions beyond what Supabase Auth allows. It cannot read or write application tables unless RLS policies explicitly permit it.
@@ -39,11 +39,11 @@ The Instagram `accessToken` stored in `accounts.data.accessToken` is a long-live
**Protection mechanisms:**
1. Stored only in the Supabase `accounts` table (server-side)
-2. Never returned in API responses — `safeAccount()` strips it
+2. Never returned in API responses - `safeAccount()` strips it
3. Only used by: `services/instagram.js` (for API calls) and `utils/scheduler.js` (for cron publishing)
4. The `GET /api/accounts` endpoint passes all accounts through `safeAccount()` before returning
-**If you add a new route that returns account data, you must call `safeAccount()`.** There is no automatic stripping — it is an explicit step in route handlers.
+**If you add a new route that returns account data, you must call `safeAccount()`.** There is no automatic stripping - it is an explicit step in route handlers.
## GitHub PAT Security
@@ -55,7 +55,7 @@ The GitHub Personal Access Token stored in `settings.value.githubPat` is stored
## Audit Points
When reviewing security, check these files:
-- `backend/middleware/auth.js` — JWT verification
-- `backend/lib/db.js` — every function that accepts an optional `userId` should either: require it explicitly, or have a documented reason for omitting it (cron use case)
-- `backend/services/instagram.js` — `safeAccount()` definition and usage
-- All route files in `backend/routes/` — verify `safeAccount()` is called on every account response
+- `backend/middleware/auth.js` - JWT verification
+- `backend/lib/db.js` - every function that accepts an optional `userId` should either: require it explicitly, or have a documented reason for omitting it (cron use case)
+- `backend/services/instagram.js` - `safeAccount()` definition and usage
+- All route files in `backend/routes/` - verify `safeAccount()` is called on every account response
diff --git a/docs/architecture/frontend/API_LAYER.md b/docs/architecture/frontend/API_LAYER.md
index 9520463..d76ef89 100644
--- a/docs/architecture/frontend/API_LAYER.md
+++ b/docs/architecture/frontend/API_LAYER.md
@@ -89,7 +89,7 @@ async function handleAction() {
## Authentication
-The `request()` function automatically attaches the JWT. Components do not need to handle auth tokens — the API layer manages this transparently. If the user is not logged in, the token will be absent and the backend will return 401, which `request()` will throw as an error.
+The `request()` function automatically attaches the JWT. Components do not need to handle auth tokens - the API layer manages this transparently. If the user is not logged in, the token will be absent and the backend will return 401, which `request()` will throw as an error.
## Base URL
diff --git a/docs/architecture/frontend/CONTEXTS.md b/docs/architecture/frontend/CONTEXTS.md
index 60ff930..3b7b71b 100644
--- a/docs/architecture/frontend/CONTEXTS.md
+++ b/docs/architecture/frontend/CONTEXTS.md
@@ -36,10 +36,10 @@ useEffect(() => {
### Where to use it
-- `ProtectedRoute` — reads `session` to decide whether to redirect to `/login`
-- `Login.jsx` — calls `signIn()` and `signUp()`
-- `Header.jsx` — calls `signOut()`, shows `user.email`
-- Do **not** use in page/feature components — they should never need auth state directly
+- `ProtectedRoute` - reads `session` to decide whether to redirect to `/login`
+- `Login.jsx` - calls `signIn()` and `signUp()`
+- `Header.jsx` - calls `signOut()`, shows `user.email`
+- Do **not** use in page/feature components - they should never need auth state directly
---
@@ -64,15 +64,15 @@ const { accounts, setAccounts, loading, showToast, loadAccounts, refreshAll } =
### Loading behavior
-`loadAccounts()` is called automatically on mount. It does not set `loading = true` — it's a background load. Only `refreshAll()` sets `loading = true` (used to show a spinner in the Header).
+`loadAccounts()` is called automatically on mount. It does not set `loading = true` - it's a background load. Only `refreshAll()` sets `loading = true` (used to show a spinner in the Header).
### Where to use it
All feature pages and layout components use `useAppContext()`:
-- `Sidebar.jsx` — generates per-account nav links from `accounts`
-- `Overview.jsx` — renders the all-accounts dashboard
-- `AccountManager.jsx` — calls `loadAccounts()` after add/delete
-- `ChannelAnalytics.jsx` — finds the account by `params.id`
+- `Sidebar.jsx` - generates per-account nav links from `accounts`
+- `Overview.jsx` - renders the all-accounts dashboard
+- `AccountManager.jsx` - calls `loadAccounts()` after add/delete
+- `ChannelAnalytics.jsx` - finds the account by `params.id`
- All pages that show toast notifications call `showToast()`
### Account shape after `normalizeAccount()`
@@ -94,7 +94,7 @@ All feature pages and layout components use `useAppContext()`:
username: '...',
followersCount: 5000,
mediaCount: 200,
- // Note: accessToken is NEVER present — stripped by safeAccount() on the backend
+ // Note: accessToken is NEVER present - stripped by safeAccount() on the backend
}
```
@@ -102,8 +102,8 @@ All feature pages and layout components use `useAppContext()`:
## Context Rules
-1. Never use `AuthContext` in feature pages — they should not care about auth state
+1. Never use `AuthContext` in feature pages - they should not care about auth state
2. Never use `AppContext` in `AuthContext` or vice versa
3. `AppProvider` must be inside `ProtectedRoute` (it makes authenticated API calls on mount)
-4. All toast notifications go through `showToast()` — never call `toast()` from sonner directly in pages
+4. All toast notifications go through `showToast()` - never call `toast()` from sonner directly in pages
5. Do not add new global state to `AppContext` unless it truly needs to be shared across multiple unrelated pages. Prefer local component state.
diff --git a/docs/architecture/frontend/FEATURES.md b/docs/architecture/frontend/FEATURES.md
index 6d11870..4212f73 100644
--- a/docs/architecture/frontend/FEATURES.md
+++ b/docs/architecture/frontend/FEATURES.md
@@ -7,21 +7,21 @@ frontend/src/
├── features/
│ ├── analytics/
│ │ ├── channel/
-│ │ │ └── ChannelAnalytics.jsx ← YouTube channel analytics
+│ │ │ └── ChannelAnalytics.jsx <- YouTube channel analytics
│ │ ├── instagram/
-│ │ │ └── InstagramAnalytics.jsx ← Instagram account analytics
+│ │ │ └── InstagramAnalytics.jsx <- Instagram account analytics
│ │ └── overview/
-│ │ └── Overview.jsx ← Cross-platform aggregate dashboard
+│ │ └── Overview.jsx <- Cross-platform aggregate dashboard
│ ├── accounts/
-│ │ └── Accounts.jsx ← Add/remove connected accounts
+│ │ └── Accounts.jsx <- Add/remove connected accounts
│ ├── publish/
-│ │ └── Publish.jsx ← Instagram immediate publish
+│ │ └── Publish.jsx <- Instagram immediate publish
│ ├── schedule/
-│ │ └── Schedule.jsx ← Instagram scheduled posts queue
+│ │ └── Schedule.jsx <- Instagram scheduled posts queue
│ ├── settings/
-│ │ └── Settings.jsx ← GitHub PAT and other settings
+│ │ └── Settings.jsx <- GitHub PAT and other settings
│ └── videos/
-│ └── VideoExplorer.jsx ← YouTube video library with filtering
+│ └── VideoExplorer.jsx <- YouTube video library with filtering
```
## Feature Conventions
@@ -31,8 +31,8 @@ frontend/src/
Each top-level directory under `features/` represents a product area. Sub-directories represent per-platform views within that area.
```
-features/analytics/youtube/ ← correct
-features/ChannelAnalytics.jsx ← wrong (flat, not grouped)
+features/analytics/youtube/ <- correct
+features/ChannelAnalytics.jsx <- wrong (flat, not grouped)
```
### One page component per file
@@ -41,9 +41,9 @@ Each `.jsx` file in `features/` is a routable page. It is lazy-imported in `App.
```
features/analytics/channel/
- ChannelAnalytics.jsx ← page (exported as default)
- VideoCard.jsx ← sub-component used only here
- useChannelData.js ← hook used only here
+ ChannelAnalytics.jsx <- page (exported as default)
+ VideoCard.jsx <- sub-component used only here
+ useChannelData.js <- hook used only here
```
Shared components used across multiple features go in `components/` (shadcn UI pieces) or `components/shared/` (custom cross-feature pieces).
@@ -54,14 +54,14 @@ Pages are entry points from the router. They get their context from `useAppConte
### Feature state is local
-Each page manages its own loading/data/error state. Pages do not write to `AppContext` — the context is for account list and toast only. If you need shared state between two pages, it belongs in the URL (query params or route params), not in context.
+Each page manages its own loading/data/error state. Pages do not write to `AppContext` - the context is for account list and toast only. If you need shared state between two pages, it belongs in the URL (query params or route params), not in context.
### Naming
-- Page files: `PascalCase.jsx` matching the feature name — `ChannelAnalytics.jsx`, `Schedule.jsx`
-- Sub-components: `PascalCase.jsx` named for what they render — `VideoCard.jsx`, `StatRow.jsx`
-- Hooks: `camelCase.js` with `use` prefix — `useChannelData.js`
-- Directories: `camelCase` matching the feature — `analytics/channel/`, `publish/`
+- Page files: `PascalCase.jsx` matching the feature name - `ChannelAnalytics.jsx`, `Schedule.jsx`
+- Sub-components: `PascalCase.jsx` named for what they render - `VideoCard.jsx`, `StatRow.jsx`
+- Hooks: `camelCase.js` with `use` prefix - `useChannelData.js`
+- Directories: `camelCase` matching the feature - `analytics/channel/`, `publish/`
## Current Features
diff --git a/docs/architecture/frontend/REACT_ARCHITECTURE.md b/docs/architecture/frontend/REACT_ARCHITECTURE.md
index 8ca53f5..9f4123a 100644
--- a/docs/architecture/frontend/REACT_ARCHITECTURE.md
+++ b/docs/architecture/frontend/REACT_ARCHITECTURE.md
@@ -7,12 +7,12 @@
| Framework | React | 19 |
| Router | React Router | 7 |
| Build tool | Vite | 7 |
-| UI components | shadcn/ui (base-nova style) | — |
+| UI components | shadcn/ui (base-nova style) | - |
| Styling | Tailwind CSS | 4 |
| Charts | Recharts | 3 |
-| Theming | next-themes | — |
-| Toasts | Sonner | — |
-| Icons | Lucide React | — |
+| Theming | next-themes | - |
+| Toasts | Sonner | - |
+| Icons | Lucide React | - |
## Entry: `frontend/src/main.jsx`
@@ -31,18 +31,18 @@ Defines the router, provider tree, and lazy-loaded page imports.
## Provider Tree
```
-ThemeProvider (next-themes) ← OS/user theme preference
- TooltipProvider (shadcn) ← global tooltip context
- AuthProvider (AuthContext.jsx) ← Supabase session
+ThemeProvider (next-themes) <- OS/user theme preference
+ TooltipProvider (shadcn) <- global tooltip context
+ AuthProvider (AuthContext.jsx) <- Supabase session
Suspense (fallback=null)
RouterProvider
- /login → Login (no protection)
- /* →
- ProtectedRoute ← redirects to /login if no session
- AppProvider ← accounts[], loading, showToast
- MainLayout ← sidebar + header + <Outlet />
+ /login -> Login (no protection)
+ /* ->
+ ProtectedRoute <- redirects to /login if no session
+ AppProvider <- accounts[], loading, showToast
+ MainLayout <- sidebar + header + <Outlet />
(lazy page)
- Toaster (Sonner, bottom-right) ← toast notifications
+ Toaster (Sonner, bottom-right) <- toast notifications
```
**Why `AppProvider` is inside `ProtectedRoute`:** `AppProvider` calls `api.getAccounts()` on mount. This request requires a valid JWT. If `AppProvider` were outside `ProtectedRoute`, it would fire before auth is confirmed and fail with 401.
@@ -78,12 +78,12 @@ frontend/src/
Login.jsx Auth page (not lazy-loaded, always small)
features/
analytics/
- overview/ Overview.jsx — all-accounts dashboard
- channel/ ChannelAnalytics.jsx — per-channel YouTube
- instagram/ InstagramAnalytics.jsx — per-account Instagram
- videos/ VideoExplorer.jsx — all videos table
- shorts/ ShortsExplorer.jsx — shorts-filtered table
- reels/ ReelsExplorer.jsx — Instagram media grid
+ overview/ Overview.jsx - all-accounts dashboard
+ channel/ ChannelAnalytics.jsx - per-channel YouTube
+ instagram/ InstagramAnalytics.jsx - per-account Instagram
+ videos/ VideoExplorer.jsx - all videos table
+ shorts/ ShortsExplorer.jsx - shorts-filtered table
+ reels/ ReelsExplorer.jsx - Instagram media grid
publishing/
UploadContent.jsx Instagram publishing + schedule queue
accounts/
diff --git a/docs/architecture/frontend/ROUTING.md b/docs/architecture/frontend/ROUTING.md
index e4de809..a829631 100644
--- a/docs/architecture/frontend/ROUTING.md
+++ b/docs/architecture/frontend/ROUTING.md
@@ -8,8 +8,8 @@ The app uses React Router v6 in `frontend/src/App.jsx`. The router uses `Browser
| Path | Component | Notes |
|---|---|---|
-| `/login` | `Login.jsx` | Public — redirects to `/` if already authenticated |
-| `/` (layout) | `AppLayout` (inline) | Protected — redirects to `/login` if unauthenticated |
+| `/login` | `Login.jsx` | Public - redirects to `/` if already authenticated |
+| `/` (layout) | `AppLayout` (inline) | Protected - redirects to `/login` if unauthenticated |
| `/` (index) | `Overview.jsx` | Default page after login |
| `/accounts` | `Accounts.jsx` | Connect/disconnect accounts |
| `/channel/:id` | `ChannelAnalytics.jsx` | `:id` = account.id for YouTube accounts |
@@ -67,14 +67,14 @@ All lazy components are wrapped in `<Suspense>` with a shared fallback.
## URL Parameters
-The `:id` param in per-account routes always refers to `account.id` — the primary key of the `accounts` table. Pages look up the account from `AppContext`:
+The `:id` param in per-account routes always refers to `account.id` - the primary key of the `accounts` table. Pages look up the account from `AppContext`:
```js
const { id } = useParams();
const account = accounts.find(a => a.id === id);
```
-If `account` is undefined (invalid ID or account deleted), the page renders an empty state — it does not redirect.
+If `account` is undefined (invalid ID or account deleted), the page renders an empty state - it does not redirect.
## Navigation
diff --git a/docs/features/NEW_ANALYTICS_PAGE.md b/docs/features/NEW_ANALYTICS_PAGE.md
index f9ec32d..a3f4bd6 100644
--- a/docs/features/NEW_ANALYTICS_PAGE.md
+++ b/docs/features/NEW_ANALYTICS_PAGE.md
@@ -10,7 +10,7 @@ Adding a platform analytics page touches all layers:
|---|---|
| **Backend service** | New service file with platform API client, data fetcher, analytics computation |
| **Backend cache** | New cache key functions in `lib/cache.js` |
-| **Backend db** | No schema change needed — `platform='reddit'` works with existing `accounts` table |
+| **Backend db** | No schema change needed - `platform='reddit'` works with existing `accounts` table |
| **Backend routes** | New analytics routes (`/accounts/:id/platform-analytics`, `/accounts/:id/platform-media`) |
| **Backend server** | Mount new router in `server.js` |
| **Frontend api** | New methods in `api.js` |
@@ -24,9 +24,9 @@ Adding a platform analytics page touches all layers:
```
backend/
services/
- reddit.js ← API client + analytics computation
+ reddit.js <- API client + analytics computation
routes/
- reddit.js ← analytics routes
+ reddit.js <- analytics routes
frontend/src/
features/
@@ -133,7 +133,7 @@ api.route('/', redditRouter);
```
```js
-// backend/routes/accounts.js — in the delete handler
+// backend/routes/accounts.js - in the delete handler
await deleteRedditCache(redis, userId, id); // add alongside existing cache deletes
```
@@ -162,14 +162,14 @@ getRedditAnalytics: (id) => request(`/accounts/${id}/reddit-analytics`),
```
```jsx
-// Sidebar.jsx — in per-account link generation for Reddit accounts
+// Sidebar.jsx - in per-account link generation for Reddit accounts
{ title: 'Reddit', url: `/reddit/${account.id}`, icon: RedditIcon }
```
## Step 7: Update Documentation
-- `docs/architecture/backend/ROUTES.md` — new routes
-- `docs/architecture/backend/CACHING.md` — new cache keys
-- `docs/architecture/backend/SERVICES.md` — Reddit service
-- `docs/architecture/data-flows/` — create `REDDIT.md` for the analytics flow
-- `CHANGELOG.md` — feature entry
+- `docs/architecture/backend/ROUTES.md` - new routes
+- `docs/architecture/backend/CACHING.md` - new cache keys
+- `docs/architecture/backend/SERVICES.md` - Reddit service
+- `docs/architecture/data-flows/` - create `REDDIT.md` for the analytics flow
+- `CHANGELOG.md` - feature entry
diff --git a/docs/features/NEW_API_ENDPOINT.md b/docs/features/NEW_API_ENDPOINT.md
index afaed59..46af7ae 100644
--- a/docs/features/NEW_API_ENDPOINT.md
+++ b/docs/features/NEW_API_ENDPOINT.md
@@ -108,7 +108,7 @@ Add the new routes to `docs/architecture/backend/ROUTES.md`.
## Security Checklist
- [ ] Route is mounted under `api` (protected by `requireAuth`)
-- [ ] Route handler reads `userId` from `c.get('userId')` — not from request body
+- [ ] Route handler reads `userId` from `c.get('userId')` - not from request body
- [ ] All DB queries include `.eq('user_id', userId)` for user-scoped data
- [ ] Any account data in the response passes through `safeAccount()` if it contains tokens
- [ ] Input validation returns 400 for missing required fields
diff --git a/docs/features/NEW_DATABASE_TABLE.md b/docs/features/NEW_DATABASE_TABLE.md
index 80daf23..b23d4d8 100644
--- a/docs/features/NEW_DATABASE_TABLE.md
+++ b/docs/features/NEW_DATABASE_TABLE.md
@@ -3,9 +3,9 @@
## When You Need a New Table
Before creating a new table, consider whether the data fits the existing jsonb pattern:
-- If it's platform-specific configuration for an account → add fields to `accounts.data` jsonb
-- If it's per-user settings → use the `settings` table with a new `key`
-- If it's a new entity with its own lifecycle and queryable status → new table
+- If it's platform-specific configuration for an account -> add fields to `accounts.data` jsonb
+- If it's per-user settings -> use the `settings` table with a new `key`
+- If it's a new entity with its own lifecycle and queryable status -> new table
## Steps
@@ -36,9 +36,9 @@ CREATE INDEX content_drafts_status_idx ON content_drafts(status);
### Step 2: Create the Table in Supabase
-Option A: Supabase Dashboard → SQL Editor → paste and run the SQL above
+Option A: Supabase Dashboard -> SQL Editor -> paste and run the SQL above
-Option B: Supabase Dashboard → Table Editor → create visually
+Option B: Supabase Dashboard -> Table Editor -> create visually
There is currently no migration tool configured. SQL is applied directly. **Document the SQL in this guide for future reference** if it needs to be recreated.
@@ -133,13 +133,13 @@ Update `docs/architecture/database/SCHEMA.md` with:
### Step 6: Wire Up the Feature
Follow the guides for:
-- `docs/features/NEW_API_ENDPOINT.md` — add backend routes
-- `docs/features/NEW_REACT_PAGE.md` — add frontend page
-- `docs/features/NEW_API_ENDPOINT.md` — add frontend api.js methods
+- `docs/features/NEW_API_ENDPOINT.md` - add backend routes
+- `docs/features/NEW_REACT_PAGE.md` - add frontend page
+- `docs/features/NEW_API_ENDPOINT.md` - add frontend api.js methods
## Naming Conventions for New Tables
-- Table names: `snake_case`, plural — `content_drafts`, `webhook_configs`
+- Table names: `snake_case`, plural - `content_drafts`, `webhook_configs`
- All tables must have `user_id uuid NOT NULL`
- If table relates to an account: also include `account_id text NOT NULL`
- Status columns: text, with documented enum values
diff --git a/docs/features/NEW_INTEGRATION.md b/docs/features/NEW_INTEGRATION.md
index 00c884b..f1dd8af 100644
--- a/docs/features/NEW_INTEGRATION.md
+++ b/docs/features/NEW_INTEGRATION.md
@@ -73,7 +73,7 @@ export async function getTwitterTweets(userId, accessToken) {
return data || [];
}
-// Analytics computation (pure function — easy to test)
+// Analytics computation (pure function - easy to test)
export function computeTwitterAnalytics(tweets, profile) {
const totalLikes = tweets.reduce((sum, t) => sum + (t.public_metrics?.like_count || 0), 0);
const totalRetweets = tweets.reduce((sum, t) => sum + (t.public_metrics?.retweet_count || 0), 0);
@@ -208,7 +208,7 @@ await deleteTwitterCache(redis, userId, id);
```toml
# wrangler.toml
[vars]
-# (no vars for platform-specific secrets — use secrets)
+# (no vars for platform-specific secrets - use secrets)
```
```bash
@@ -249,13 +249,13 @@ Follow `docs/features/NEW_REACT_PAGE.md` and `docs/features/NEW_ANALYTICS_PAGE.m
If the platform uses OAuth:
- Backend: add `GET /auth/{platform}/start` and `GET /auth/{platform}/callback` routes
- Use the HMAC-signed state pattern (see `docs/architecture/backend/CACHING.md` and `ADR-006` in `DECISIONS.md`)
-- Store tokens in `accounts.data` — never in a separate table
+- Store tokens in `accounts.data` - never in a separate table
- Delete cache on every token refresh
## Security Checklist
- [ ] Access token never returned in any API response (use `safeTwitterAccount()` or equivalent)
-- [ ] Access token read from `account.accessToken` on the backend — never passed from frontend
+- [ ] Access token read from `account.accessToken` on the backend - never passed from frontend
- [ ] OAuth callback validates HMAC state before accepting code
-- [ ] New Worker secrets added with `wrangler secret put` — not stored in `wrangler.toml` plaintext
+- [ ] New Worker secrets added with `wrangler secret put` - not stored in `wrangler.toml` plaintext
- [ ] New secrets added to GitHub Actions repository secrets if needed by CI
diff --git a/docs/features/NEW_REACT_PAGE.md b/docs/features/NEW_REACT_PAGE.md
index 7b4eedf..c030504 100644
--- a/docs/features/NEW_REACT_PAGE.md
+++ b/docs/features/NEW_REACT_PAGE.md
@@ -108,9 +108,9 @@ getMyData: (id) => request(`/accounts/${id}/my-data`),
## Conventions
-- Use `useAppContext()` — don't re-fetch the accounts list, use what's in context
+- Use `useAppContext()` - don't re-fetch the accounts list, use what's in context
- Always handle loading and error states
-- Use `Skeleton` components for loading state (not spinners — shadcn's Skeleton matches the page layout)
+- Use `Skeleton` components for loading state (not spinners - shadcn's Skeleton matches the page layout)
- Use semantic HTML for the page structure
- Wrap content in `className="p-6"` padding (matches existing pages)
- Use `space-y-6` or `space-y-4` for vertical rhythm between sections
@@ -122,7 +122,7 @@ For pages that show aggregate data across all accounts (like Overview):
```jsx
export default function MyAggregatePage() {
const { accounts, loading: accountsLoading } = useAppContext();
- // accounts is already loaded — no need to fetch
+ // accounts is already loaded - no need to fetch
const summary = useMemo(() => {
return accounts.reduce((sum, a) => sum + (a.viewCount || 0), 0);
diff --git a/docs/features/NEW_SCHEDULED_TASK.md b/docs/features/NEW_SCHEDULED_TASK.md
index 1804d04..21ad41f 100644
--- a/docs/features/NEW_SCHEDULED_TASK.md
+++ b/docs/features/NEW_SCHEDULED_TASK.md
@@ -70,7 +70,7 @@ export default {
};
```
-Or match by the cron expression string — the `event.cron` property contains the exact cron string from `wrangler.toml`.
+Or match by the cron expression string - the `event.cron` property contains the exact cron string from `wrangler.toml`.
### Step 4: Test Locally
@@ -86,7 +86,7 @@ curl "http://localhost:8787/__scheduled?cron=30+3+*+*+*"
cd backend && wrangler deploy
```
-Cron triggers deploy with the Worker. Verify in the Cloudflare dashboard → Workers → Triggers → Cron.
+Cron triggers deploy with the Worker. Verify in the Cloudflare dashboard -> Workers -> Triggers -> Cron.
---
@@ -152,13 +152,13 @@ jobs:
If the task requires secrets not already in GitHub Actions:
-1. GitHub → Settings → Secrets and variables → Actions
+1. GitHub -> Settings -> Secrets and variables -> Actions
2. Add `New repository secret`
3. Name must match what the workflow references
### Step 4: Test
-GitHub → Actions → "My Scheduled Task" → "Run workflow" → watch the logs.
+GitHub -> Actions -> "My Scheduled Task" -> "Run workflow" -> watch the logs.
---
diff --git a/docs/guidelines/API_CONVENTIONS.md b/docs/guidelines/API_CONVENTIONS.md
index 05bb645..799e2b1 100644
--- a/docs/guidelines/API_CONVENTIONS.md
+++ b/docs/guidelines/API_CONVENTIONS.md
@@ -37,7 +37,7 @@ The `request()` function in `frontend/src/services/api.js` reads `data.error` an
|---|---|
| `200` | Successful GET, PUT, DELETE |
| `201` | Successful POST that creates a resource |
-| `400` | Bad request — missing fields, invalid input |
+| `400` | Bad request - missing fields, invalid input |
| `401` | Authentication required or token invalid (returned by `requireAuth`) |
| `403` | Authenticated but not authorized (wrong user for this resource) |
| `404` | Resource not found |
@@ -89,11 +89,11 @@ The backend extracts and verifies it in `requireAuth`. Route handlers access the
## Route Naming
-- Resource collections: plural noun — `/accounts`, `/scheduled-posts`
-- Single resources: `/:id` suffix — `/accounts/:id`
-- Sub-resources: nested — `/accounts/:id/analytics`, `/accounts/:id/ig-media`
-- Actions on resources: verb-noun — `/accounts/refresh-all`, `/accounts/:id/refresh`
-- Non-resource actions: verb noun — `/resolve-channel`, `/process-scheduled`
+- Resource collections: plural noun - `/accounts`, `/scheduled-posts`
+- Single resources: `/:id` suffix - `/accounts/:id`
+- Sub-resources: nested - `/accounts/:id/analytics`, `/accounts/:id/ig-media`
+- Actions on resources: verb-noun - `/accounts/refresh-all`, `/accounts/:id/refresh`
+- Non-resource actions: verb noun - `/resolve-channel`, `/process-scheduled`
## Frontend `api.js` Conventions
diff --git a/docs/guidelines/CLOUDFLARE_WORKERS.md b/docs/guidelines/CLOUDFLARE_WORKERS.md
index 572b7f4..01fc32b 100644
--- a/docs/guidelines/CLOUDFLARE_WORKERS.md
+++ b/docs/guidelines/CLOUDFLARE_WORKERS.md
@@ -2,7 +2,7 @@
## Environment Access
-Access environment variables and secrets via `c.env` (in Hono handlers) or `env` (in the `scheduled` cron handler). Never use `process.env` — it does not exist in the Workers runtime.
+Access environment variables and secrets via `c.env` (in Hono handlers) or `env` (in the `scheduled` cron handler). Never use `process.env` - it does not exist in the Workers runtime.
```js
// In a Hono handler or middleware:
@@ -20,20 +20,20 @@ export default {
## No Node.js APIs
The Workers runtime does not have Node.js built-ins. These are unavailable:
-- `fs` — no file system
-- `Buffer` — use `Uint8Array`, `TextEncoder`, `TextDecoder`
-- `path` — no file system paths
-- `process` — no `process.env`, `process.exit`, etc.
-- `crypto` module — use Web Crypto API (`crypto.subtle`)
-- `require()` — use ESM `import`
+- `fs` - no file system
+- `Buffer` - use `Uint8Array`, `TextEncoder`, `TextDecoder`
+- `path` - no file system paths
+- `process` - no `process.env`, `process.exit`, etc.
+- `crypto` module - use Web Crypto API (`crypto.subtle`)
+- `require()` - use ESM `import`
**Web APIs available in Workers:**
-- `fetch()` — for HTTP calls
-- `crypto.subtle` — for HMAC, hashing
-- `TextEncoder` / `TextDecoder` — for string/buffer conversion
-- `URL`, `URLSearchParams` — for URL construction
-- `btoa()` / `atob()` — for base64
-- `ReadableStream`, `WritableStream` — for streaming
+- `fetch()` - for HTTP calls
+- `crypto.subtle` - for HMAC, hashing
+- `TextEncoder` / `TextDecoder` - for string/buffer conversion
+- `URL`, `URLSearchParams` - for URL construction
+- `btoa()` / `atob()` - for base64
+- `ReadableStream`, `WritableStream` - for streaming
## `ctx.waitUntil()`
@@ -47,14 +47,14 @@ async scheduled(event, env, ctx) {
Without `ctx.waitUntil()`, the Worker isolate may terminate before the promise resolves.
-Do not use `ctx.waitUntil()` in HTTP request handlers — just `await` the work normally.
+Do not use `ctx.waitUntil()` in HTTP request handlers - just `await` the work normally.
## Stateless Requests
The Workers runtime does not guarantee a persistent process between requests. Do not rely on module-level variables to persist state:
```js
-// BAD — will not work reliably
+// BAD - will not work reliably
let cachedData = null;
export default { fetch: async (request, env) => {
if (cachedData) return Response.json(cachedData); // unreliable
@@ -62,7 +62,7 @@ export default { fetch: async (request, env) => {
return Response.json(cachedData);
}};
-// GOOD — use Redis or Supabase for persistence
+// GOOD - use Redis or Supabase for persistence
const cached = await redis.get('my-key');
if (cached) return c.json(cached);
const fresh = await fetchData(env);
@@ -74,9 +74,9 @@ return c.json(fresh);
The Worker is bundled as a single ESM file by Wrangler. Large dependencies increase cold-start time and may exceed Workers bundle size limits. The current backend has minimal dependencies:
-- `hono` — ~15KB gzipped
-- `@supabase/supabase-js` — larger; mostly used for auth.getUser()
-- `@upstash/redis` — small REST client
+- `hono` - ~15KB gzipped
+- `@supabase/supabase-js` - larger; mostly used for auth.getUser()
+- `@upstash/redis` - small REST client
Avoid adding large dependencies. If a library is only needed for one small utility, consider implementing that utility directly.
@@ -117,7 +117,7 @@ cd backend
wrangler deploy
```
-Or push to `main` with changes in `backend/` — GitHub Actions deploys automatically via `deploy-backend.yml`.
+Or push to `main` with changes in `backend/` - GitHub Actions deploys automatically via `deploy-backend.yml`.
## CORS
@@ -131,4 +131,4 @@ app.use('*', cors({
}));
```
-This change would need to be applied carefully — it would break requests from local development (`localhost:5173`) unless the allowed origin list includes it.
+This change would need to be applied carefully - it would break requests from local development (`localhost:5173`) unless the allowed origin list includes it.
diff --git a/docs/guidelines/ERROR_HANDLING.md b/docs/guidelines/ERROR_HANDLING.md
index dff47d6..a57cddc 100644
--- a/docs/guidelines/ERROR_HANDLING.md
+++ b/docs/guidelines/ERROR_HANDLING.md
@@ -29,7 +29,7 @@ Supabase errors are objects with `message`, `code`, and `details`. Throwing the
### Cache Operations (lib/cache.js)
-Always catch and silently ignore — cache failures must never surface to users:
+Always catch and silently ignore - cache failures must never surface to users:
```js
try {
@@ -39,7 +39,7 @@ try {
}
```
-The empty `catch` block is intentional. Do not log cache errors — they create noise for transient Redis connection issues.
+The empty `catch` block is intentional. Do not log cache errors - they create noise for transient Redis connection issues.
### Route Handlers (routes/)
@@ -63,11 +63,11 @@ router.get('/accounts/:id/analytics', async (c) => {
```
**Status codes:**
-- `400` — bad request (missing required fields, invalid input)
-- `401` — unauthorized (handled by `requireAuth`, not route handlers)
-- `403` — forbidden (account belongs to another user)
-- `404` — resource not found
-- `500` — unexpected server error
+- `400` - bad request (missing required fields, invalid input)
+- `401` - unauthorized (handled by `requireAuth`, not route handlers)
+- `403` - forbidden (account belongs to another user)
+- `404` - resource not found
+- `500` - unexpected server error
### Frontend API Calls
@@ -107,9 +107,9 @@ This is the last resort. Route handlers should not rely on it.
## Logging
-Use `console.error()` for errors in route handlers — Cloudflare Workers captures these in the dashboard logs.
+Use `console.error()` for errors in route handlers - Cloudflare Workers captures these in the dashboard logs.
-Format: `console.error('METHOD /path:', err.message)` — includes the route for easy filtering.
+Format: `console.error('METHOD /path:', err.message)` - includes the route for easy filtering.
Do not log sensitive values: access tokens, API keys, user emails, Supabase URLs.
diff --git a/docs/guidelines/HONO.md b/docs/guidelines/HONO.md
index e38694b..67ad965 100644
--- a/docs/guidelines/HONO.md
+++ b/docs/guidelines/HONO.md
@@ -8,7 +8,7 @@ Every route handler follows this exact shape:
router.METHOD('/path', async (c) => {
const userId = c.get('userId'); // from requireAuth middleware
const supabase = c.get('supabase'); // from client injection middleware
- const redis = c.get('redis'); // may be null — always guard
+ const redis = c.get('redis'); // may be null - always guard
// 1. Read inputs
const id = c.req.param('id');
@@ -30,7 +30,7 @@ router.METHOD('/path', async (c) => {
## Context Values
-Access these via `c.get()` — never reconstruct them inside handlers:
+Access these via `c.get()` - never reconstruct them inside handlers:
| Key | Type | Notes |
|---|---|---|
@@ -55,7 +55,7 @@ const body = await c.req.json();
const auth = c.req.header('Authorization');
```
-Never destructure `c.req` directly — always call the method.
+Never destructure `c.req` directly - always call the method.
## Returning Responses
@@ -114,15 +114,15 @@ app.use('/api/*', async (c, next) => {
## Error Handling Rules
- Always wrap external calls (Supabase, platform APIs) in try/catch
-- Log with `console.error('VERB /path:', err.message)` — include the route in the log
-- Never throw from a route handler — catch and return `c.json({ error }, status)`
+- Log with `console.error('VERB /path:', err.message)` - include the route in the log
+- Never throw from a route handler - catch and return `c.json({ error }, status)`
- 400 for client errors (missing fields, invalid format, resource not found)
- 500 for server errors (DB failures, external API failures)
- Never expose stack traces in the response body
## What Not To Do
-- Do not import `env` directly — access it via `c.env` or via the middleware-injected clients
-- Do not use `c.env` directly in route handlers — always use `c.get('supabase')` / `c.get('redis')`
-- Do not build Supabase clients inside route handlers — the middleware does this once per request
-- Do not use `app.use()` for business logic — that is for cross-cutting middleware only
+- Do not import `env` directly - access it via `c.env` or via the middleware-injected clients
+- Do not use `c.env` directly in route handlers - always use `c.get('supabase')` / `c.get('redis')`
+- Do not build Supabase clients inside route handlers - the middleware does this once per request
+- Do not use `app.use()` for business logic - that is for cross-cutting middleware only
diff --git a/docs/guidelines/JAVASCRIPT.md b/docs/guidelines/JAVASCRIPT.md
index 0363df3..17576b4 100644
--- a/docs/guidelines/JAVASCRIPT.md
+++ b/docs/guidelines/JAVASCRIPT.md
@@ -1,6 +1,6 @@
# JavaScript Standards
-This project is plain JavaScript — no TypeScript, no Babel transpilation beyond what Vite handles. These rules apply to both the backend (Cloudflare Worker) and the frontend (Vite + React).
+This project is plain JavaScript - no TypeScript, no Babel transpilation beyond what Vite handles. These rules apply to both the backend (Cloudflare Worker) and the frontend (Vite + React).
## Module System
@@ -10,10 +10,10 @@ This project is plain JavaScript — no TypeScript, no Babel transpilation beyon
## File Conventions
-- **Backend files:** `camelCase.js` — `server.js`, `auth.js`, `instagram.js`, `db.js`
-- **Frontend utility/service files:** `camelCase.js` — `api.js`, `formatters.js`
-- **Frontend React files:** `PascalCase.jsx` — `Overview.jsx`, `AppContext.jsx`
-- **shadcn generated files:** `kebab-case.jsx` — do not rename these
+- **Backend files:** `camelCase.js` - `server.js`, `auth.js`, `instagram.js`, `db.js`
+- **Frontend utility/service files:** `camelCase.js` - `api.js`, `formatters.js`
+- **Frontend React files:** `PascalCase.jsx` - `Overview.jsx`, `AppContext.jsx`
+- **shadcn generated files:** `kebab-case.jsx` - do not rename these
## Comments Policy
@@ -27,18 +27,18 @@ Write no comments by default. Add a comment only when the WHY is non-obvious and
**Do write (sparingly):**
```js
-// userId=null means service-level — used by cron handlers that scan all users
+// userId=null means service-level - used by cron handlers that scan all users
export async function getAccounts(supabase, userId = null) { ... }
-// Redis HMAC state: base64url(userId:timestamp).HMAC-SHA256-sig — see cache.js
+// Redis HMAC state: base64url(userId:timestamp).HMAC-SHA256-sig - see cache.js
```
## Naming
-- Functions: `camelCase` — `getAccounts`, `computeVideoAnalytics`, `publishToInstagram`
-- Variables: `camelCase` — `accountId`, `scheduledAt`, `accessToken`
+- Functions: `camelCase` - `getAccounts`, `computeVideoAnalytics`, `publishToInstagram`
+- Variables: `camelCase` - `accountId`, `scheduledAt`, `accessToken`
- Constants: `SCREAMING_SNAKE_CASE` only for true global constants (rare)
-- React components: `PascalCase` — `ChannelAnalytics`, `AppProvider`
+- React components: `PascalCase` - `ChannelAnalytics`, `AppProvider`
Prefer names that describe intent, not implementation:
- `getVideosCache` not `redisGetVideos`
@@ -58,12 +58,12 @@ try {
}
```
-In **service functions**, throw descriptive errors — let the caller decide how to handle:
+In **service functions**, throw descriptive errors - let the caller decide how to handle:
```js
if (data.error) throw new Error(data.error.message);
```
-In **cache functions**, always catch and silently ignore — cache failures must never bubble up:
+In **cache functions**, always catch and silently ignore - cache failures must never bubble up:
```js
try { return await redis.get(key); } catch { return null; }
```
diff --git a/docs/guidelines/NAMING.md b/docs/guidelines/NAMING.md
index b5007f0..179afcb 100644
--- a/docs/guidelines/NAMING.md
+++ b/docs/guidelines/NAMING.md
@@ -14,50 +14,50 @@
| Frontend layout | `PascalCase.jsx` or `index.jsx` | `Sidebar.jsx`, `Header.jsx`, `index.jsx` |
| Frontend hooks | `use-kebab-case.js` | `use-mobile.js` |
| Frontend utilities | `camelCase.js` | `formatters.js`, `api.js`, `utils.js` |
-| shadcn components | `kebab-case.jsx` | `button.jsx`, `card.jsx` (generated — do not rename) |
+| shadcn components | `kebab-case.jsx` | `button.jsx`, `card.jsx` (generated - do not rename) |
| Documentation | `SCREAMING_SNAKE_CASE.md` | `OVERVIEW.md`, `JAVASCRIPT.md`, `SCHEMA.md` |
## Functions
-- Backend route handlers: `camelCase` verb + noun — `getAnalytics(c)`, `createAccount(c)`, `deletePost(c)`
-- Backend service functions: `camelCase` verb + noun — `fetchChannelData()`, `computeVideoAnalytics()`, `publishIGContainer()`
-- Backend db functions: `camelCase` verb + noun — `getAccounts()`, `createPost()`, `updateAccount()`, `deletePost()`
-- Frontend API methods: `camelCase` verb + noun — `getAnalytics()`, `createScheduledPost()`, `deleteAccount()`
-- React event handlers: `handle` + PascalCase noun/event — `handleSubmit()`, `handleDeleteClick()`, `handleInputChange()`
-- React custom hooks: `use` + PascalCase noun — `useAppContext()`, `useIsMobile()`
+- Backend route handlers: `camelCase` verb + noun - `getAnalytics(c)`, `createAccount(c)`, `deletePost(c)`
+- Backend service functions: `camelCase` verb + noun - `fetchChannelData()`, `computeVideoAnalytics()`, `publishIGContainer()`
+- Backend db functions: `camelCase` verb + noun - `getAccounts()`, `createPost()`, `updateAccount()`, `deletePost()`
+- Frontend API methods: `camelCase` verb + noun - `getAnalytics()`, `createScheduledPost()`, `deleteAccount()`
+- React event handlers: `handle` + PascalCase noun/event - `handleSubmit()`, `handleDeleteClick()`, `handleInputChange()`
+- React custom hooks: `use` + PascalCase noun - `useAppContext()`, `useIsMobile()`
## Variables
-- `camelCase` throughout — `accountId`, `scheduledAt`, `accessToken`, `uploadPlaylistId`
-- Boolean variables: `is`/`has`/`can` prefix — `isLoading`, `hasError`, `canPublish`
-- IDs: always `{entity}Id` suffix — `accountId`, `userId`, `containerId`, `mediaId`
-- Timestamps: `{action}At` suffix — `scheduledAt`, `publishedAt`, `createdAt`
-- Counts: `{entity}Count` suffix — `subscriberCount`, `viewCount`, `mediaCount`
-- Collections/arrays: plural noun — `accounts`, `videos`, `posts`, `hashtags`
+- `camelCase` throughout - `accountId`, `scheduledAt`, `accessToken`, `uploadPlaylistId`
+- Boolean variables: `is`/`has`/`can` prefix - `isLoading`, `hasError`, `canPublish`
+- IDs: always `{entity}Id` suffix - `accountId`, `userId`, `containerId`, `mediaId`
+- Timestamps: `{action}At` suffix - `scheduledAt`, `publishedAt`, `createdAt`
+- Counts: `{entity}Count` suffix - `subscriberCount`, `viewCount`, `mediaCount`
+- Collections/arrays: plural noun - `accounts`, `videos`, `posts`, `hashtags`
## Constants
-- True global constants: `SCREAMING_SNAKE_CASE` — `API`, `DEFAULT_KEYS`
+- True global constants: `SCREAMING_SNAKE_CASE` - `API`, `DEFAULT_KEYS`
- Environment-derived values at module top: `SUPABASE_URL`, `SUPABASE_SERVICE_KEY` (from env)
- Named groupings: prefer an object over multiple constants
## Database
-- Table names: `snake_case`, plural — `accounts`, `settings`, `scheduled_posts`
-- Column names: `snake_case` — `user_id`, `account_id`, `scheduled_at`, `access_token` (inside jsonb)
-- jsonb field names: `camelCase` — these are JavaScript objects embedded in JSON, so they follow JS conventions: `accessToken`, `subscriberCount`, `publishedAt`
+- Table names: `snake_case`, plural - `accounts`, `settings`, `scheduled_posts`
+- Column names: `snake_case` - `user_id`, `account_id`, `scheduled_at`, `access_token` (inside jsonb)
+- jsonb field names: `camelCase` - these are JavaScript objects embedded in JSON, so they follow JS conventions: `accessToken`, `subscriberCount`, `publishedAt`
## Routes
-- REST convention: noun-first, plural — `/accounts`, `/scheduled-posts`
+- REST convention: noun-first, plural - `/accounts`, `/scheduled-posts`
- Resource nesting: `/accounts/:id/ig-analytics` (not `/ig-analytics/:accountId`)
-- Kebab-case multi-word paths — `/refresh-all`, `/ig-publish`, `/process-scheduled`
+- Kebab-case multi-word paths - `/refresh-all`, `/ig-publish`, `/process-scheduled`
## Supabase Cache Keys
-`{entity}:{userId}:{accountId}` — `videos:abc-123:def-456`, `ig:abc-123:def-456`
+`{entity}:{userId}:{accountId}` - `videos:abc-123:def-456`, `ig:abc-123:def-456`
## Environment Variables
-- Backend Worker secrets: `SCREAMING_SNAKE_CASE` — `SUPABASE_URL`, `YOUTUBE_API_KEY`
-- Frontend Vite variables: `VITE_` prefix + `SCREAMING_SNAKE_CASE` — `VITE_API_URL`, `VITE_SUPABASE_URL`
+- Backend Worker secrets: `SCREAMING_SNAKE_CASE` - `SUPABASE_URL`, `YOUTUBE_API_KEY`
+- Frontend Vite variables: `VITE_` prefix + `SCREAMING_SNAKE_CASE` - `VITE_API_URL`, `VITE_SUPABASE_URL`
diff --git a/docs/guidelines/REACT.md b/docs/guidelines/REACT.md
index 21f7807..6cc9e95 100644
--- a/docs/guidelines/REACT.md
+++ b/docs/guidelines/REACT.md
@@ -102,7 +102,7 @@ function handleInputChange(e) { ... }
## Lazy Loading
-All pages are lazy-loaded via `React.lazy()` in `App.jsx`. Do not import pages directly — always use lazy imports for new pages.
+All pages are lazy-loaded via `React.lazy()` in `App.jsx`. Do not import pages directly - always use lazy imports for new pages.
```jsx
const MyNewPage = lazy(() => import('./features/myFeature/MyNewPage'));
@@ -114,10 +114,10 @@ const MyNewPage = lazy(() => import('./features/myFeature/MyNewPage'));
- `<button>` for actions, `<a>` for navigation
- Images need `alt` attributes (empty string for decorative images)
- Use semantic HTML: `<main>`, `<nav>`, `<section>`, `<article>` where appropriate
-- shadcn components handle most ARIA attributes automatically — use them as provided
+- shadcn components handle most ARIA attributes automatically - use them as provided
## Performance
-- Avoid large computations in render — move to `useMemo` if expensive
-- Avoid re-creating functions in render that are passed as props — use `useCallback`
+- Avoid large computations in render - move to `useMemo` if expensive
+- Avoid re-creating functions in render that are passed as props - use `useCallback`
- The analytics computation functions (`computeVideoAnalytics`) run on the backend, not the frontend
diff --git a/docs/guidelines/SHADCN.md b/docs/guidelines/SHADCN.md
index 17f64e9..49ffefa 100644
--- a/docs/guidelines/SHADCN.md
+++ b/docs/guidelines/SHADCN.md
@@ -25,7 +25,7 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
```
-Never import from `shadcn/ui` directly — the components are copied into the project.
+Never import from `shadcn/ui` directly - the components are copied into the project.
## Adding a New Component
@@ -76,7 +76,7 @@ shadcn components are composed using their named export variants. Read the compo
## `cn()` Utility
-Always use `cn()` from `@/lib/utils` to combine class names — it handles conditional classes and tailwind-merge conflicts:
+Always use `cn()` from `@/lib/utils` to combine class names - it handles conditional classes and tailwind-merge conflicts:
```jsx
import { cn } from '@/lib/utils';
@@ -103,4 +103,4 @@ import StatCard from '@/components/ui/StatCard';
The project uses `next-themes` with `attribute="class"`. Dark mode is applied by adding the `dark` class to `<html>`. All shadcn components respond to this automatically via CSS variables defined in `frontend/src/index.css`.
-Do not hardcode colors in components — use Tailwind semantic classes (`text-muted-foreground`, `bg-card`, `border-border`, etc.) that reference CSS variables.
+Do not hardcode colors in components - use Tailwind semantic classes (`text-muted-foreground`, `bg-card`, `border-border`, etc.) that reference CSS variables.
diff --git a/docs/guidelines/STATE_MANAGEMENT.md b/docs/guidelines/STATE_MANAGEMENT.md
index 3a3a2f6..78bf58d 100644
--- a/docs/guidelines/STATE_MANAGEMENT.md
+++ b/docs/guidelines/STATE_MANAGEMENT.md
@@ -4,16 +4,16 @@
```
Is the data needed by only one component?
- → useState in that component
+ -> useState in that component
Is the data needed by a few sibling/child components?
- → useState in the closest common ancestor, passed as props
+ -> useState in the closest common ancestor, passed as props
Is the data needed across many unrelated pages?
- → AppContext (accounts, showToast)
+ -> AppContext (accounts, showToast)
Is the data auth-related (session, user)?
- → AuthContext
+ -> AuthContext
```
## Component-Level State (`useState`)
@@ -30,7 +30,7 @@ const [loading, setLoading] = useState(true);
const [selectedTab, setSelectedTab] = useState('overview');
```
-## AppContext — What Belongs Here
+## AppContext - What Belongs Here
`AppContext` currently provides:
@@ -38,29 +38,29 @@ const [selectedTab, setSelectedTab] = useState('overview');
|---|---|---|
| `accounts` | `Account[]` | Needed by Sidebar (nav links), Overview (dashboard), all analytics pages (lookup by ID), AccountManager (CRUD), Header (refresh button) |
| `loading` | `boolean` | The global refresh spinner in Header |
-| `showToast` | `function` | Toast notifications from anywhere — avoids threading Sonner's `toast` import everywhere |
+| `showToast` | `function` | Toast notifications from anywhere - avoids threading Sonner's `toast` import everywhere |
**Do not add** page-specific data to `AppContext`. If only one or two pages need a piece of data, keep it local.
-## AuthContext — What Belongs Here
+## AuthContext - What Belongs Here
Only auth state:
-- `session` — the Supabase session object
-- `user` — shorthand for `session.user`
-- `signIn`, `signUp`, `signOut` — auth actions
+- `session` - the Supabase session object
+- `user` - shorthand for `session.user`
+- `signIn`, `signUp`, `signOut` - auth actions
-Feature pages should not need to read `AuthContext`. If a feature page needs the user's email or ID, reconsider — in most cases, the backend handles user scoping via the JWT, so the frontend doesn't need to know the userId.
+Feature pages should not need to read `AuthContext`. If a feature page needs the user's email or ID, reconsider - in most cases, the backend handles user scoping via the JWT, so the frontend doesn't need to know the userId.
## Derived State
Prefer computing derived values at render time rather than storing them in state:
```jsx
-// Good — derive from existing state
+// Good - derive from existing state
const youtubeAccounts = accounts.filter(a => a.platform === 'youtube');
const totalViews = accounts.reduce((sum, a) => sum + (a.viewCount || 0), 0);
-// Bad — storing derived data in extra state
+// Bad - storing derived data in extra state
const [youtubeAccounts, setYoutubeAccounts] = useState([]);
useEffect(() => {
setYoutubeAccounts(accounts.filter(a => a.platform === 'youtube'));
@@ -86,7 +86,7 @@ Use `useRef` for:
- Referencing DOM elements (`ref={inputRef}; inputRef.current.focus()`)
- Storing mutable values that should not trigger re-renders (e.g., a timer ID, a cancelled flag)
-Do not use `useRef` as a workaround for stale closures — fix the closure instead.
+Do not use `useRef` as a workaround for stale closures - fix the closure instead.
## No External State Library
diff --git a/docs/guidelines/SUPABASE.md b/docs/guidelines/SUPABASE.md
index 16d3eb1..a3bfde1 100644
--- a/docs/guidelines/SUPABASE.md
+++ b/docs/guidelines/SUPABASE.md
@@ -6,7 +6,7 @@
|---|---|---|---|
| Service client | `SUPABASE_SERVICE_KEY` | `getSupabase(env)` in `lib/supabase.js` | All DB operations (bypasses RLS) |
| Auth client | `SUPABASE_ANON_KEY` | `getSupabaseAuth(env)` in `lib/supabase.js` | JWT verification only (`auth.getUser(token)`) |
-| Frontend client | `VITE_SUPABASE_ANON_KEY` | `lib/supabase.js` in frontend | Supabase Auth (sign in/out, session) — no DB queries |
+| Frontend client | `VITE_SUPABASE_ANON_KEY` | `lib/supabase.js` in frontend | Supabase Auth (sign in/out, session) - no DB queries |
**Rule:** The service client is the only client used for database queries. The auth client is used exclusively in `requireAuth` middleware. The frontend client is used only for Supabase Auth, never for database access.
@@ -75,7 +75,7 @@ await supabase.from('accounts').update({
}).eq('id', id);
```
-**Never replace the entire `data` object** without first reading the current value — you'll lose fields that aren't in the update.
+**Never replace the entire `data` object** without first reading the current value - you'll lose fields that aren't in the update.
## Row Isolation
@@ -83,7 +83,7 @@ Every user-scoped query must include `.eq('user_id', userId)`. Functions that in
```js
export async function getDuePosts(supabase) {
- // No userId filter — used by cron scheduler to process all users' posts
+ // No userId filter - used by cron scheduler to process all users' posts
const { data, error } = await supabase
.from('scheduled_posts')
.select(...)
@@ -95,7 +95,7 @@ export async function getDuePosts(supabase) {
## Client Lifecycle
-Supabase clients are created fresh per request in the Worker — they are stateless HTTP clients and safe to create on each request. Do not cache client instances in module-level variables; they would hold references to a specific request's `env` bindings.
+Supabase clients are created fresh per request in the Worker - they are stateless HTTP clients and safe to create on each request. Do not cache client instances in module-level variables; they would hold references to a specific request's `env` bindings.
```js
// lib/supabase.js
@@ -104,7 +104,7 @@ export function getSupabase(env) {
}
```
-## Frontend — No DB Access
+## Frontend - No DB Access
The frontend's Supabase client (`frontend/src/lib/supabase.js`) is used only for:
- `supabase.auth.signInWithPassword()`
diff --git a/docs/guidelines/TAILWIND.md b/docs/guidelines/TAILWIND.md
index c8725c6..0cbfaef 100644
--- a/docs/guidelines/TAILWIND.md
+++ b/docs/guidelines/TAILWIND.md
@@ -4,21 +4,21 @@
This project uses **Tailwind CSS v4**. The v4 API is substantially different from v3:
- Configuration is done via CSS `@theme` instead of `tailwind.config.js`
-- No `tailwind.config.js` exists — do not create one
+- No `tailwind.config.js` exists - do not create one
- Use `@import "tailwindcss"` in the main CSS entry point
- Utility classes are the same as v3 in most cases
## Token References
-Design tokens are defined in the CSS file (check `frontend/src/index.css` or `frontend/src/app.css` for the `@theme` block). Use these tokens via their utility class names — never use hardcoded hex values in class names.
+Design tokens are defined in the CSS file (check `frontend/src/index.css` or `frontend/src/app.css` for the `@theme` block). Use these tokens via their utility class names - never use hardcoded hex values in class names.
Common token utilities:
-- `bg-background` / `text-foreground` — page background and main text
-- `bg-card` / `text-card-foreground` — card surfaces
-- `bg-muted` / `text-muted-foreground` — subdued backgrounds and secondary text
-- `border-border` — default border color
-- `bg-primary` / `text-primary-foreground` — primary action color
-- `bg-destructive` / `text-destructive-foreground` — error/delete actions
+- `bg-background` / `text-foreground` - page background and main text
+- `bg-card` / `text-card-foreground` - card surfaces
+- `bg-muted` / `text-muted-foreground` - subdued backgrounds and secondary text
+- `border-border` - default border color
+- `bg-primary` / `text-primary-foreground` - primary action color
+- `bg-destructive` / `text-destructive-foreground` - error/delete actions
## Layout
@@ -49,13 +49,13 @@ Common token utilities:
## Spacing System
Use the spacing scale consistently. Common patterns in this project:
-- `p-6` — standard page padding
-- `p-4` — card inner padding
-- `gap-4` — grid column gap
-- `gap-2` — inline icon+label gap
-- `space-y-6` — vertical rhythm between major sections
-- `space-y-4` — vertical rhythm within a card
-- `mb-4` / `mb-6` — heading bottom margin
+- `p-6` - standard page padding
+- `p-4` - card inner padding
+- `gap-4` - grid column gap
+- `gap-2` - inline icon+label gap
+- `space-y-6` - vertical rhythm between major sections
+- `space-y-4` - vertical rhythm within a card
+- `mb-4` / `mb-6` - heading bottom margin
## Typography
@@ -76,7 +76,7 @@ Mobile-first. Most pages in this app are designed primarily for desktop (analyti
## Dark Mode
-This project uses shadcn's theme system, which manages light/dark via CSS custom properties — not Tailwind's `dark:` variant. Do not use `dark:` variants. Use token-based colors (`bg-card`, `text-muted-foreground`) which automatically respond to the theme.
+This project uses shadcn's theme system, which manages light/dark via CSS custom properties - not Tailwind's `dark:` variant. Do not use `dark:` variants. Use token-based colors (`bg-card`, `text-muted-foreground`) which automatically respond to the theme.
If you need to add a custom dark-mode variant for non-token colors, add a CSS custom property to the `@theme` block instead.
@@ -94,12 +94,12 @@ import { cn } from '@/lib/utils';
)} />
```
-Never use template literals for conditional classes — they won't be properly merged and can produce duplicate or conflicting utilities.
+Never use template literals for conditional classes - they won't be properly merged and can produce duplicate or conflicting utilities.
## What Not To Do
- Do not use `style={{}}` for values that can be expressed as Tailwind utilities
-- Do not hardcode colors in class names (`text-[#ff0000]`) — use design token utilities
+- Do not hardcode colors in class names (`text-[#ff0000]`) - use design token utilities
- Do not use `!important` (`!text-red-500`) unless debugging a specificity conflict
-- Do not create a `tailwind.config.js` — configuration lives in the CSS `@theme` block in v4
-- Do not use `dark:` prefix variants — theme is token-based, not class-based
+- Do not create a `tailwind.config.js` - configuration lives in the CSS `@theme` block in v4
+- Do not use `dark:` prefix variants - theme is token-based, not class-based
diff --git a/docs/mcp/CONTEXT7.md b/docs/mcp/CONTEXT7.md
index a53180c..b7403d9 100644
--- a/docs/mcp/CONTEXT7.md
+++ b/docs/mcp/CONTEXT7.md
@@ -1,4 +1,4 @@
-# MCP: Context7 — Library Documentation
+# MCP: Context7 - Library Documentation
## Purpose
@@ -12,15 +12,15 @@ Context7 fetches current, version-accurate documentation for libraries and APIs.
## When to Use
✅ **Use Context7 for:**
-- Instagram Graph API — container creation params, field names, error codes
-- YouTube Data API v3 — endpoint params, quota costs, response shapes
-- Hono v4 — middleware API, context methods, routing
-- Supabase JS — client methods, query builder, auth API
-- Cloudflare Workers — runtime APIs, `ctx.waitUntil()`, env bindings
-- Recharts v3 — component props, data shapes, chart configuration
-- shadcn/ui components — available props, slot composition
-- React 19 — hooks API, new features
-- React Router v7 — `createBrowserRouter`, `Outlet`, nested routes
+- Instagram Graph API - container creation params, field names, error codes
+- YouTube Data API v3 - endpoint params, quota costs, response shapes
+- Hono v4 - middleware API, context methods, routing
+- Supabase JS - client methods, query builder, auth API
+- Cloudflare Workers - runtime APIs, `ctx.waitUntil()`, env bindings
+- Recharts v3 - component props, data shapes, chart configuration
+- shadcn/ui components - available props, slot composition
+- React 19 - hooks API, new features
+- React Router v7 - `createBrowserRouter`, `Outlet`, nested routes
❌ **Do not use Context7 for:**
- Debugging business logic (read the code instead)
@@ -31,7 +31,7 @@ Context7 fetches current, version-accurate documentation for libraries and APIs.
## Workflow
1. `resolve-library-id` with the library name and your specific question
-2. Review results — pick the ID with the most relevant description and highest score
+2. Review results - pick the ID with the most relevant description and highest score
3. `query-docs` with the selected ID and your full question
4. Apply the documentation to the implementation
@@ -70,7 +70,7 @@ query-docs: "How do I create an AreaChart with multiple data series,
## Tips
-- Be specific in your query — include the exact method name or concept
+- Be specific in your query - include the exact method name or concept
- If the first result doesn't match, try alternate names (e.g., "next.js" not "nextjs", "hono.js" not "honojs")
- Use version-specific IDs when the project is on a specific version and the API has changed recently
-- The Supabase library has multiple IDs — prefer the one specifically for the JavaScript client
+- The Supabase library has multiple IDs - prefer the one specifically for the JavaScript client
diff --git a/docs/mcp/FILESYSTEM.md b/docs/mcp/FILESYSTEM.md
index 00e33b2..6f502cd 100644
--- a/docs/mcp/FILESYSTEM.md
+++ b/docs/mcp/FILESYSTEM.md
@@ -1,4 +1,4 @@
-# MCP: Filesystem — Codebase Navigation
+# MCP: Filesystem - Codebase Navigation
## Purpose
@@ -28,7 +28,7 @@ pattern: "safeAccount"
path: backend/
```
-Better: Use the built-in Grep tool for this — it's faster for string search.
+Better: Use the built-in Grep tool for this - it's faster for string search.
### Get directory structure
@@ -56,9 +56,9 @@ path: frontend/src/
The built-in Grep and Glob tools are faster for most search tasks:
-- `Grep pattern="useAppContext"` — faster than filesystem search for string patterns
-- `Glob pattern="backend/routes/*.js"` — faster than filesystem for file patterns
-- `Read file_path="..."` — faster than filesystem for single file reads
+- `Grep pattern="useAppContext"` - faster than filesystem search for string patterns
+- `Glob pattern="backend/routes/*.js"` - faster than filesystem for file patterns
+- `Read file_path="..."` - faster than filesystem for single file reads
Use Filesystem MCP when you need its specific features: recursive directory trees, multi-file reads in one call, or file move operations.
@@ -71,6 +71,6 @@ When renaming a function or moving a file:
3. Verify with Grep that no old references remain
Example: renaming `safeAccount` to `stripSensitiveFields`:
-1. `search_files pattern="safeAccount" path="backend/"` → list of files
+1. `search_files pattern="safeAccount" path="backend/"` -> list of files
2. Edit each file
-3. `Grep pattern="safeAccount"` → should return empty
+3. `Grep pattern="safeAccount"` -> should return empty
diff --git a/docs/mcp/OVERVIEW.md b/docs/mcp/OVERVIEW.md
index 32bf606..2a3650d 100644
--- a/docs/mcp/OVERVIEW.md
+++ b/docs/mcp/OVERVIEW.md
@@ -1,4 +1,4 @@
-# MCP Usage — Decision Guide
+# MCP Usage - Decision Guide
Four MCP servers are available. Each has a specific purpose. Using the wrong one wastes time and produces worse results than using the right one.
@@ -6,16 +6,16 @@ Four MCP servers are available. Each has a specific purpose. Using the wrong one
```
Need API docs, library reference, or framework docs?
- → Context7
+ -> Context7
Need to find a file, symbol, or understand the codebase?
- → Filesystem (or direct Grep/Glob tools first)
+ -> Filesystem (or direct Grep/Glob tools first)
Need to plan a complex feature, debug a hard problem, or think through architecture?
- → Sequential Thinking
+ -> Sequential Thinking
Need to research UX patterns, browser compat, competing products, or best practices?
- → Parallel Search
+ -> Parallel Search
```
## When Each MCP is the Right Choice
@@ -31,30 +31,30 @@ Need to research UX patterns, browser compat, competing products, or best practi
### Adding Instagram Reels support to the publisher
-1. **Sequential Thinking** — plan the full implementation (backend params, frontend UI changes, DB schema changes if any)
-2. **Context7** — look up Instagram Graph API Reels container params (`media_type=REELS`, required fields)
-3. **Parallel Search** — research UX patterns for Reels upload interfaces
+1. **Sequential Thinking** - plan the full implementation (backend params, frontend UI changes, DB schema changes if any)
+2. **Context7** - look up Instagram Graph API Reels container params (`media_type=REELS`, required fields)
+3. **Parallel Search** - research UX patterns for Reels upload interfaces
4. Implement
### Debugging a Supabase query that returns wrong data
-1. **Filesystem** — find all callers of the function to understand the context
-2. **Context7** — look up Supabase `select()`, `eq()`, `single()` semantics if the issue might be a library API misunderstanding
-3. **Sequential Thinking** — if the root cause is still unclear, walk through the data flow step by step
+1. **Filesystem** - find all callers of the function to understand the context
+2. **Context7** - look up Supabase `select()`, `eq()`, `single()` semantics if the issue might be a library API misunderstanding
+3. **Sequential Thinking** - if the root cause is still unclear, walk through the data flow step by step
### Adding a new shadcn component
-1. **Context7** — get the exact props and composition for the component
-2. Direct implementation — no other MCP needed
+1. **Context7** - get the exact props and composition for the component
+2. Direct implementation - no other MCP needed
### Deciding whether to add a new npm dependency
-1. **Sequential Thinking** — analyze the trade-offs (bundle size, alternatives, maintenance)
-2. **Parallel Search** — check if there is a lightweight alternative or a Web API equivalent
+1. **Sequential Thinking** - analyze the trade-offs (bundle size, alternatives, maintenance)
+2. **Parallel Search** - check if there is a lightweight alternative or a Web API equivalent
## Detailed Docs
-- `docs/mcp/CONTEXT7.md` — when, how, and example queries
-- `docs/mcp/FILESYSTEM.md` — file search, symbol location, refactoring
-- `docs/mcp/SEQUENTIAL_THINKING.md` — planning and debugging
-- `docs/mcp/PARALLEL_SEARCH.md` — research workflows
+- `docs/mcp/CONTEXT7.md` - when, how, and example queries
+- `docs/mcp/FILESYSTEM.md` - file search, symbol location, refactoring
+- `docs/mcp/SEQUENTIAL_THINKING.md` - planning and debugging
+- `docs/mcp/PARALLEL_SEARCH.md` - research workflows
diff --git a/docs/mcp/PARALLEL_SEARCH.md b/docs/mcp/PARALLEL_SEARCH.md
index ffb53f8..e372be8 100644
--- a/docs/mcp/PARALLEL_SEARCH.md
+++ b/docs/mcp/PARALLEL_SEARCH.md
@@ -1,4 +1,4 @@
-# MCP: Parallel Search — Research
+# MCP: Parallel Search - Research
## Purpose
@@ -30,7 +30,7 @@ Parallel Search fetches current web content for research tasks: UX patterns, bro
- "how Hootsuite implements scheduling calendar"
- "time slot selection UI accessibility"
3. Extract the patterns relevant to this project's constraints (mobile-first, React)
-4. Apply the patterns — document sources in a code comment if the pattern is non-obvious
+4. Apply the patterns - document sources in a code comment if the pattern is non-obvious
### API Behavior Research
@@ -44,9 +44,9 @@ When Instagram/YouTube API behavior is unclear or seems different from Context7
Before building any interactive feature:
-1. Search "WCAG 2.1 {feature type}" — e.g., "WCAG 2.1 date picker accessibility"
+1. Search "WCAG 2.1 {feature type}" - e.g., "WCAG 2.1 date picker accessibility"
2. Check MDN for the correct ARIA roles and attributes
-3. Apply what you find — shadcn components already include correct ARIA in most cases
+3. Apply what you find - shadcn components already include correct ARIA in most cases
## Multiple Search Queries
diff --git a/docs/mcp/SEQUENTIAL_THINKING.md b/docs/mcp/SEQUENTIAL_THINKING.md
index af8b50f..56101a9 100644
--- a/docs/mcp/SEQUENTIAL_THINKING.md
+++ b/docs/mcp/SEQUENTIAL_THINKING.md
@@ -1,8 +1,8 @@
-# MCP: Sequential Thinking — Planning and Debugging
+# MCP: Sequential Thinking - Planning and Debugging
## Purpose
-Sequential Thinking enables structured, step-by-step reasoning for complex problems. Use it before implementing anything non-trivial to produce a verified plan — not a list of guesses.
+Sequential Thinking enables structured, step-by-step reasoning for complex problems. Use it before implementing anything non-trivial to produce a verified plan - not a list of guesses.
## When to Use
@@ -74,8 +74,8 @@ Sequential Thinking would work through:
### Debugging double-publishing
Sequential Thinking would walk through:
-- The `getDuePosts()` query — what exactly does it return?
-- The `status = 'publishing'` update — is it atomic?
+- The `getDuePosts()` query - what exactly does it return?
+- The `status = 'publishing'` update - is it atomic?
- The race condition window between SELECT and UPDATE
- Whether Supabase/PostgreSQL guarantees isolation at the right level
- Whether the GitHub Actions workflow and Worker cron can actually overlap
diff --git a/docs/philosophy/ARCHITECTURE.md b/docs/philosophy/ARCHITECTURE.md
index df26386..93ff034 100644
--- a/docs/philosophy/ARCHITECTURE.md
+++ b/docs/philosophy/ARCHITECTURE.md
@@ -4,13 +4,13 @@
### 1. Fetch at the edge, not in the client
-The Cloudflare Worker sits at the edge, close to the user. All data fetching — from Supabase, from external platform APIs, from Redis — happens in the Worker. The React client fetches from the Worker only. The client never talks to Supabase or platform APIs directly.
+The Cloudflare Worker sits at the edge, close to the user. All data fetching - from Supabase, from external platform APIs, from Redis - happens in the Worker. The React client fetches from the Worker only. The client never talks to Supabase or platform APIs directly.
**Why:** Keeps credentials server-side. Enables caching at the edge. Single point of auth enforcement.
### 2. One source of auth truth
-Authentication is Supabase JWTs. The Worker verifies the JWT on every protected request. `userId` derived from the verified JWT is the only identity that matters. No session state. No cookies. The JWT is verified by checking its signature against the Supabase JWT secret — not by calling Supabase on every request.
+Authentication is Supabase JWTs. The Worker verifies the JWT on every protected request. `userId` derived from the verified JWT is the only identity that matters. No session state. No cookies. The JWT is verified by checking its signature against the Supabase JWT secret - not by calling Supabase on every request.
**Why:** Stateless auth scales to zero infrastructure. JWTs are self-verifying.
@@ -30,7 +30,7 @@ Redis is optional infrastructure. The cache layer always catches errors and retu
### 5. Credentials stay in the Worker
-Platform API credentials (Instagram app secret, YouTube API key) are Worker secrets — not in code, not in the database, not in the frontend. The only credential that goes near the frontend is the Supabase anon key, which is public by design.
+Platform API credentials (Instagram app secret, YouTube API key) are Worker secrets - not in code, not in the database, not in the frontend. The only credential that goes near the frontend is the Supabase anon key, which is public by design.
User-specific tokens (Instagram access tokens, GitHub PATs) live in `accounts.data` in the database. They are read by the Worker and never returned to the frontend. See `ADR-004`.
@@ -48,7 +48,7 @@ This is a deliberate constraint, not an oversight. See `ADR-010` and `docs/guide
**Not a real-time system.** There are no WebSockets, no Server-Sent Events. Analytics pages refresh on load. Scheduled post status updates on poll.
-**Not a multi-tenant platform.** Every user has their own credentials, their own accounts. There is no concept of organizations, teams, or shared accounts at the data layer. (This is a known constraint — see ROADMAP.md.)
+**Not a multi-tenant platform.** Every user has their own credentials, their own accounts. There is no concept of organizations, teams, or shared accounts at the data layer. (This is a known constraint - see ROADMAP.md.)
## When to Break These Rules
diff --git a/docs/philosophy/PERFORMANCE.md b/docs/philosophy/PERFORMANCE.md
index 1042441..6c3b5f8 100644
--- a/docs/philosophy/PERFORMANCE.md
+++ b/docs/philosophy/PERFORMANCE.md
@@ -6,21 +6,21 @@
```
Request
- → Redis (hot cache, ~1ms) ← check first
+ -> Redis (hot cache, ~1ms) <- check first
hit: return immediately
miss: fall through
- → Platform API / Supabase ← cold path
- → populate Redis
- → return result
+ -> Platform API / Supabase <- cold path
+ -> populate Redis
+ -> return result
```
### Cache keys and TTLs
| Resource | Cache key | TTL | Note |
|---|---|---|---|
-| YouTube analytics | `videos:{userId}:{accountId}` | None set (bug — see ROADMAP) | Should be 1 hour |
-| Instagram analytics | `ig:{userId}:{accountId}` | None set (bug — see ROADMAP) | Should be 1 hour |
-| OAuth state | `oauth_ig:{state}` | 10 minutes | Security-critical — do not extend |
+| YouTube analytics | `videos:{userId}:{accountId}` | None set (bug - see ROADMAP) | Should be 1 hour |
+| Instagram analytics | `ig:{userId}:{accountId}` | None set (bug - see ROADMAP) | Should be 1 hour |
+| OAuth state | `oauth_ig:{state}` | 10 minutes | Security-critical - do not extend |
Cache invalidation happens on:
- Account deletion (explicit `redis.del()`)
@@ -39,10 +39,10 @@ await redis.set(key, data, { ex: 3600 }); // expire after 1 hour
## Edge Deployment
-The Cloudflare Worker runs at the edge — in a data center close to the user. This means:
+The Cloudflare Worker runs at the edge - in a data center close to the user. This means:
- Low first-byte latency for API responses
- Supabase queries go from the Worker (edge) to Supabase (centralized), so DB round-trips are fast but not zero
-- Platform API calls (Instagram, YouTube) happen from the Worker — not from the user's browser — eliminating client-side rate limit attribution
+- Platform API calls (Instagram, YouTube) happen from the Worker - not from the user's browser - eliminating client-side rate limit attribution
## Bundle Size
@@ -61,13 +61,13 @@ Analytics libraries (Recharts) and heavy page components are loaded on demand wh
Cloudflare Workers have a CPU time limit of 50ms per request (on the free tier; up to 30 seconds on paid). Expensive operations to be aware of:
- HMAC computation: negligible
- Multiple sequential Supabase queries: watch for N+1 patterns
-- Large JSON serialization: analytics response objects can be large — profile them
+- Large JSON serialization: analytics response objects can be large - profile them
If a route feels slow, add Redis caching first before optimizing the underlying query.
## What We Don't Optimize (Yet)
- **Database indexes:** The `accounts` and `scheduled_posts` tables have only a primary key index. If query performance degrades as the table grows, add an index on `user_id`. See ROADMAP.
-- **Response compression:** Cloudflare automatically compresses Worker responses with gzip/brotli — no code needed.
+- **Response compression:** Cloudflare automatically compresses Worker responses with gzip/brotli - no code needed.
- **Image optimization:** Cloudinary handles image resizing and format conversion for Instagram posts. No custom image optimization in the app layer.
- **Frontend rendering performance:** The app is not a high-frequency update scenario. No virtualization, no memoization beyond standard React patterns. If analytics tables get large (1000+ rows), add pagination.
diff --git a/docs/philosophy/SECURITY.md b/docs/philosophy/SECURITY.md
index d995eb0..a86b7aa 100644
--- a/docs/philosophy/SECURITY.md
+++ b/docs/philosophy/SECURITY.md
@@ -4,7 +4,7 @@
| Credential | Where stored | Who reads it | Exposed to client? |
|---|---|---|---|
-| Supabase anon key | `VITE_SUPABASE_ANON_KEY` (env var in frontend build) | Frontend (Supabase JS auth) | **Yes — intentionally public** |
+| Supabase anon key | `VITE_SUPABASE_ANON_KEY` (env var in frontend build) | Frontend (Supabase JS auth) | **Yes - intentionally public** |
| Supabase service role key | Worker secret | Worker only | **Never** |
| Instagram App ID | Worker secret | Worker only | **Never** |
| Instagram App Secret | Worker secret | Worker only | **Never** |
@@ -23,16 +23,16 @@ The service role key bypasses Supabase Row-Level Security and has full read/writ
- Never referenced in frontend code
- Never returned in any API response
- Never logged
-- The `.dev.vars` file must remain in `.gitignore` — verify before every commit that touches the backend
+- The `.dev.vars` file must remain in `.gitignore` - verify before every commit that touches the backend
## User Access Token Protection
Instagram access tokens grant posting authority on behalf of users. They must be treated with the same care as passwords.
**Rules:**
-- Stored in `accounts.data.accessToken` (jsonb field, not a dedicated column — intentional)
+- Stored in `accounts.data.accessToken` (jsonb field, not a dedicated column - intentional)
- Never selected and returned to the frontend. The `safeAccount()` function strips them before responses
-- When updating an account, the token field must survive the jsonb merge — never replace the whole `data` object with a subset
+- When updating an account, the token field must survive the jsonb merge - never replace the whole `data` object with a subset
- When deleting an account, the token becomes inaccessible because the row is deleted
## User Row Isolation
@@ -50,8 +50,8 @@ const userId = c.get('userId');
const { data } = await supabase
.from('accounts')
.select('*')
- .eq('user_id', userId) // ← always present
- .eq('id', accountId); // ← narrows to specific account
+ .eq('user_id', userId) // <- always present
+ .eq('id', accountId); // <- narrows to specific account
// Wrong: no user_id filter
const { data } = await supabase.from('accounts').select('*').eq('id', accountId);
@@ -93,9 +93,9 @@ The frontend must never:
If a credential is compromised:
1. Worker secrets: `wrangler secret put SECRET_NAME` then `wrangler deploy`
-2. GitHub Actions secrets: update in repository Settings → Secrets
+2. GitHub Actions secrets: update in repository Settings -> Secrets
3. Instagram App Secret: rotate in Meta Developer dashboard, then update Worker secret
-4. Supabase service role key: rotate in Supabase project Settings → API
+4. Supabase service role key: rotate in Supabase project Settings -> API
5. User Instagram tokens: user must reconnect their account via the OAuth flow
There is no automated secrets rotation. This is a known gap.
diff --git a/docs/workflows/DEPLOYMENT.md b/docs/workflows/DEPLOYMENT.md
index ed1ce69..48b024a 100644
--- a/docs/workflows/DEPLOYMENT.md
+++ b/docs/workflows/DEPLOYMENT.md
@@ -2,7 +2,7 @@
## Automatic Deployment (Normal Path)
-Push to `main` → GitHub Actions deploys automatically.
+Push to `main` -> GitHub Actions deploys automatically.
| What changed | Workflow that runs | What it deploys |
|---|---|---|
@@ -53,13 +53,13 @@ wrangler secret put UPSTASH_REDIS_REST_URL # optional
wrangler secret put UPSTASH_REDIS_REST_TOKEN # optional
```
-Each command prompts for the value (no echo — the value is not shown).
+Each command prompts for the value (no echo - the value is not shown).
## Setting GitHub Actions Secrets
Required for `deploy-frontend.yml` and `publish-scheduled.yml`:
-1. GitHub → repository → Settings → Secrets and variables → Actions
+1. GitHub -> repository -> Settings -> Secrets and variables -> Actions
2. Click "New repository secret" for each:
**For frontend deploy:**
@@ -88,10 +88,10 @@ curl https://twiligent.ujjwalkrai.workers.dev/api/health
```
**Frontend:**
-Open `https://twiligent.pages.dev` → verify login page loads → sign in → verify accounts load.
+Open `https://twiligent.pages.dev` -> verify login page loads -> sign in -> verify accounts load.
**Scheduled publisher:**
-GitHub Actions → "Instagram Scheduled Publisher" → "Run workflow" → check run output.
+GitHub Actions -> "Instagram Scheduled Publisher" -> "Run workflow" -> check run output.
## Rollback
@@ -104,7 +104,7 @@ wrangler deployments list
wrangler rollback <deployment-id>
```
-**Frontend:** Cloudflare Pages → deployments list → "Rollback to this deployment" on a previous build.
+**Frontend:** Cloudflare Pages -> deployments list -> "Rollback to this deployment" on a previous build.
## First-Time Setup
diff --git a/docs/workflows/FEATURE_DEVELOPMENT.md b/docs/workflows/FEATURE_DEVELOPMENT.md
index f6efb7b..d2570d9 100644
--- a/docs/workflows/FEATURE_DEVELOPMENT.md
+++ b/docs/workflows/FEATURE_DEVELOPMENT.md
@@ -1,25 +1,25 @@
# Feature Development Workflow
-Every feature — large or small — follows this sequence. Steps that don't apply to a specific feature can be skipped, but must be consciously skipped (not forgotten).
+Every feature - large or small - follows this sequence. Steps that don't apply to a specific feature can be skipped, but must be consciously skipped (not forgotten).
---
## Phase 1: Understand
-**Step 1 — Read CLAUDE.md**
+**Step 1 - Read CLAUDE.md**
Confirm you have the project context and know which docs to load.
-**Step 2 — Load relevant documentation**
+**Step 2 - Load relevant documentation**
Based on what the feature touches:
-- Backend change → read `docs/architecture/backend/`
-- Frontend change → read `docs/architecture/frontend/`
-- DB change → read `docs/architecture/database/SCHEMA.md`
-- New integration → read `docs/guidelines/API_CONVENTIONS.md`, relevant data flow doc
+- Backend change -> read `docs/architecture/backend/`
+- Frontend change -> read `docs/architecture/frontend/`
+- DB change -> read `docs/architecture/database/SCHEMA.md`
+- New integration -> read `docs/guidelines/API_CONVENTIONS.md`, relevant data flow doc
-**Step 3 — Read the existing code in the affected area**
+**Step 3 - Read the existing code in the affected area**
Read every file you will modify. Read sibling files to understand the established pattern. Do not start implementing until you understand the code you are about to change.
-**Step 4 — Search for existing implementations**
+**Step 4 - Search for existing implementations**
Is there already something that does part of what you need?
- `Grep` for relevant function names, component names, or patterns
- Look for a similar feature in the codebase to use as a template
@@ -28,34 +28,34 @@ Is there already something that does part of what you need?
## Phase 2: Research
-**Step 5 — Look up official API documentation (Context7)**
+**Step 5 - Look up official API documentation (Context7)**
For any external API you'll call (Instagram, YouTube, Supabase, Cloudflare), use Context7 to confirm:
- Required parameters
- Response field names and types
- Error codes and their meanings
- Rate limits or quotas
-**Step 6 — Research UX patterns (Parallel Search)**
+**Step 6 - Research UX patterns (Parallel Search)**
For user-facing features:
- How do established tools handle this interaction?
- What are the accessibility requirements?
- What edge cases do users encounter?
-**Step 7 — Research accessibility requirements**
+**Step 7 - Research accessibility requirements**
Any new interactive UI must be keyboard-accessible and screen-reader compatible:
- Buttons trigger on Enter/Space
- Modals trap focus
- Dynamic content updates are announced via ARIA live regions
- shadcn components handle most of this automatically
-**Step 8 — Plan with Sequential Thinking**
+**Step 8 - Plan with Sequential Thinking**
For features touching more than one layer (backend + frontend, DB + backend), use Sequential Thinking to produce an ordered plan before writing any code.
---
## Phase 3: Design
-**Step 9 — Design the implementation**
+**Step 9 - Design the implementation**
Determine:
- Which files will be created or modified
- What new DB columns or tables are needed
@@ -63,7 +63,7 @@ Determine:
- What new frontend pages or components are needed
- What security implications exist
-**Step 10 — Identify reuse opportunities**
+**Step 10 - Identify reuse opportunities**
Before creating new patterns, check:
- Is there a db.js function that almost does what you need? Extend it.
- Is there a service function you can call? Use it.
@@ -74,8 +74,8 @@ Before creating new patterns, check:
## Phase 4: Implement
-**Step 11 — Implement in this order:**
-1. DB schema changes (if any) — see `docs/features/NEW_DATABASE_TABLE.md`
+**Step 11 - Implement in this order:**
+1. DB schema changes (if any) - see `docs/features/NEW_DATABASE_TABLE.md`
2. Backend: `lib/db.js` additions (new query functions)
3. Backend: `services/` additions (new external API calls)
4. Backend: `routes/` additions (new route handlers)
@@ -85,14 +85,14 @@ Before creating new patterns, check:
8. Frontend: `App.jsx` routing (if new page)
9. Frontend: `Sidebar.jsx` navigation (if new page needs nav entry)
-**Step 12 — Eliminate duplication**
+**Step 12 - Eliminate duplication**
After implementing, look for logic that duplicates something that already existed. Extract it into the appropriate shared location (`lib/db.js`, `services/`, `utils/formatters.js`, shared components).
---
## Phase 5: Verify
-**Step 13 — Build verification**
+**Step 13 - Build verification**
```bash
# Backend
cd backend && wrangler dev # should start without errors
@@ -102,63 +102,63 @@ cd frontend && npm run build # should build without errors
cd frontend && npm run dev # should start without errors
```
-**Step 14 — Lint**
+**Step 14 - Lint**
```bash
cd frontend && npm run lint
```
-**Step 15 — Manual testing — golden path**
+**Step 15 - Manual testing - golden path**
Test the main success case end-to-end:
- Backend routes: verify with `curl` or the frontend
- Frontend pages: navigate to the page, perform the action, verify the result
-**Step 16 — Manual testing — edge cases**
+**Step 16 - Manual testing - edge cases**
- Empty state (no accounts, no data)
- Error state (backend unavailable, API error)
- Loading state (spinner shows during async operations)
- Invalid input (missing required fields)
- Unauthorized access (try accessing another user's resource ID)
-**Step 17 — Accessibility verification**
-- Tab through the new UI — all interactive elements must be reachable
+**Step 17 - Accessibility verification**
+- Tab through the new UI - all interactive elements must be reachable
- Activate buttons with Enter key
- Verify focus is visible on all interactive elements
-- Open Chrome DevTools → Accessibility tree — verify structure makes sense
+- Open Chrome DevTools -> Accessibility tree - verify structure makes sense
-**Step 18 — Responsive layout verification**
+**Step 18 - Responsive layout verification**
Test at 375px (mobile), 768px (tablet), 1280px (desktop):
- Content doesn't overflow horizontally
- Tables scroll within their container (not the page)
- Touch targets are large enough on mobile
-**Step 19 — Performance check**
+**Step 19 - Performance check**
- Does the new page load in reasonable time?
- Are API responses cached where appropriate?
- Is there unnecessary re-fetching on every render?
-**Step 20 — Console error check**
-Open browser DevTools → Console. Verify no errors or warnings during normal usage.
+**Step 20 - Console error check**
+Open browser DevTools -> Console. Verify no errors or warnings during normal usage.
---
## Phase 6: Document and Commit
-**Step 21 — Update documentation**
+**Step 21 - Update documentation**
Based on what changed (see `claude.md` Documentation Maintenance Policy):
-- New route → `docs/architecture/backend/ROUTES.md`
-- New DB column/table → `docs/architecture/database/SCHEMA.md`
-- New env var → `docs/architecture/cloudflare/WORKERS.md`
-- New page → `docs/architecture/frontend/REACT_ARCHITECTURE.md`
-- Architecture decision → `DECISIONS.md`
+- New route -> `docs/architecture/backend/ROUTES.md`
+- New DB column/table -> `docs/architecture/database/SCHEMA.md`
+- New env var -> `docs/architecture/cloudflare/WORKERS.md`
+- New page -> `docs/architecture/frontend/REACT_ARCHITECTURE.md`
+- Architecture decision -> `DECISIONS.md`
-**Step 22 — Update CHANGELOG.md**
+**Step 22 - Update CHANGELOG.md**
Add an entry under `[Unreleased]` describing what was added, changed, or fixed.
-**Step 23 — Update ROADMAP.md**
+**Step 23 - Update ROADMAP.md**
If the feature was on the roadmap, move it to the completed list. If it opened new follow-up work, add that.
-**Step 24 — Commit**
+**Step 24 - Commit**
Follow the Git workflow in `docs/workflows/GIT.md`.
-**Step 25 — Deploy (if ready)**
+**Step 25 - Deploy (if ready)**
Follow `docs/workflows/DEPLOYMENT.md`.
diff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.md
index cab5e1a..16622da 100644
--- a/docs/workflows/TESTING.md
+++ b/docs/workflows/TESTING.md
@@ -2,7 +2,7 @@
## Current State
-This project has no automated test suite. Testing is currently manual. This is a known gap — see ROADMAP.md.
+This project has no automated test suite. Testing is currently manual. This is a known gap - see ROADMAP.md.
The testing workflow documented here describes what should run before shipping any change.
@@ -54,14 +54,14 @@ cd backend && wrangler dev
Open the app in a browser. For each changed area, test:
**Authentication:**
-- [ ] Login with valid credentials → lands on Overview
-- [ ] Login with invalid credentials → error message shown
-- [ ] Sign out → redirects to login
+- [ ] Login with valid credentials -> lands on Overview
+- [ ] Login with invalid credentials -> error message shown
+- [ ] Sign out -> redirects to login
**Accounts:**
-- [ ] Add a YouTube channel by URL → appears in sidebar
-- [ ] Delete an account → removed from sidebar
-- [ ] Connect Instagram via OAuth → OAuth popup, returns to accounts page
+- [ ] Add a YouTube channel by URL -> appears in sidebar
+- [ ] Delete an account -> removed from sidebar
+- [ ] Connect Instagram via OAuth -> OAuth popup, returns to accounts page
**Analytics:**
- [ ] Overview page loads with correct totals
@@ -73,10 +73,10 @@ Open the app in a browser. For each changed area, test:
- [ ] Upload to Cloudinary works
- [ ] Container creation succeeds
- [ ] Status polling shows progress for video
-- [ ] Publish succeeds → media ID shown
+- [ ] Publish succeeds -> media ID shown
**Scheduling (if changed):**
-- [ ] Create a scheduled post → appears in queue
+- [ ] Create a scheduled post -> appears in queue
- [ ] Manual trigger processes due posts correctly
- [ ] Failed posts show error in UI
@@ -89,7 +89,7 @@ Open the app in a browser. For each changed area, test:
### 6. Console Error Verification
-Open browser DevTools → Console. Navigate through all changed pages.
+Open browser DevTools -> Console. Navigate through all changed pages.
- No JavaScript errors
- No failed network requests (red in Network tab)
- No React warnings about missing keys, prop types, etc.
@@ -97,16 +97,16 @@ Open browser DevTools → Console. Navigate through all changed pages.
### 7. Accessibility Verification
For any new UI:
-- Tab through all interactive elements — all must be reachable
-- Press Enter on buttons — they should activate
-- Press Space on buttons and checkboxes — they should activate
+- Tab through all interactive elements - all must be reachable
+- Press Enter on buttons - they should activate
+- Press Space on buttons and checkboxes - they should activate
- Check for visible focus ring on focused elements
-- Use Chrome's built-in Accessibility tab (DevTools → Elements → Accessibility) to verify ARIA structure
+- Use Chrome's built-in Accessibility tab (DevTools -> Elements -> Accessibility) to verify ARIA structure
### 8. Responsive Layout Verification
Resize the browser to test at:
-- 375px (iPhone SE — smallest common mobile)
+- 375px (iPhone SE - smallest common mobile)
- 768px (tablet)
- 1280px (laptop)
- 1920px (desktop)
@@ -121,7 +121,7 @@ Verify:
After any change to `scripts/publish-scheduled.js` or `publish-scheduled.yml`:
-1. GitHub Actions → "Instagram Scheduled Publisher" → "Run workflow"
+1. GitHub Actions -> "Instagram Scheduled Publisher" -> "Run workflow"
2. Watch the run output
3. Verify: "No posts due for publishing" (if no scheduled posts) or successful publish
@@ -131,7 +131,7 @@ If you have a test post scheduled in the near future, use `GET /api/process-sche
When automated tests are added, this document will be updated. Priority order for adding tests:
-1. **Unit tests for `computeVideoAnalytics()` and `computeInstagramAnalytics()`** — pure functions with complex logic, easy to test
-2. **Unit tests for `lib/db.js` functions** — using a Supabase test project
-3. **Integration tests for backend routes** — using `miniflare` or similar Workers test runner
-4. **End-to-end tests** — Playwright for the full login → view analytics → publish flow
+1. **Unit tests for `computeVideoAnalytics()` and `computeInstagramAnalytics()`** - pure functions with complex logic, easy to test
+2. **Unit tests for `lib/db.js` functions** - using a Supabase test project
+3. **Integration tests for backend routes** - using `miniflare` or similar Workers test runner
+4. **End-to-end tests** - Playwright for the full login -> view analytics -> publish flow
diff --git a/frontend/src/features/accounts/AccountManager.jsx b/frontend/src/features/accounts/AccountManager.jsx
index b5d2fc0..e237032 100644
--- a/frontend/src/features/accounts/AccountManager.jsx
+++ b/frontend/src/features/accounts/AccountManager.jsx
@@ -1,4 +1,4 @@
-import React, { useState, useEffect } from 'react';
+import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
diff --git a/frontend/src/features/analytics/reels/ReelsExplorer.jsx b/frontend/src/features/analytics/reels/ReelsExplorer.jsx
index 6796b9e..f2a6958 100644
--- a/frontend/src/features/analytics/reels/ReelsExplorer.jsx
+++ b/frontend/src/features/analytics/reels/ReelsExplorer.jsx
@@ -35,8 +35,8 @@ const MEDIA_TYPE_META = {
const PERFORMANCE_TIERS = [
{ label: 'All', value: 'all' },
{ label: 'Viral (>100K)', value: 'viral', min: 100000 },
- { label: 'High (10K–100K)', value: 'high', min: 10000, max: 100000 },
- { label: 'Medium (1K–10K)', value: 'medium', min: 1000, max: 10000 },
+ { label: 'High (10K-100K)', value: 'high', min: 10000, max: 100000 },
+ { label: 'Medium (1K-10K)', value: 'medium', min: 1000, max: 10000 },
{ label: 'Low (<1K)', value: 'low', max: 1000 },
];
diff --git a/frontend/src/features/analytics/shorts/ShortsExplorer.jsx b/frontend/src/features/analytics/shorts/ShortsExplorer.jsx
index affa444..1b0caa8 100644
--- a/frontend/src/features/analytics/shorts/ShortsExplorer.jsx
+++ b/frontend/src/features/analytics/shorts/ShortsExplorer.jsx
@@ -27,8 +27,8 @@ function parseDurationToSeconds(iso) {
const PERFORMANCE_TIERS = [
{ label: 'All', value: 'all' },
{ label: 'Viral (>1M)', value: 'viral', min: 1000000 },
- { label: 'High (100K–1M)', value: 'high', min: 100000, max: 1000000 },
- { label: 'Medium (10K–100K)', value: 'medium', min: 10000, max: 100000 },
+ { label: 'High (100K-1M)', value: 'high', min: 100000, max: 1000000 },
+ { label: 'Medium (10K-100K)', value: 'medium', min: 10000, max: 100000 },
{ label: 'Low (<10K)', value: 'low', max: 10000 },
];
diff --git a/frontend/src/features/analytics/videos/VideoExplorer.jsx b/frontend/src/features/analytics/videos/VideoExplorer.jsx
index 919401b..ec0f31b 100644
--- a/frontend/src/features/analytics/videos/VideoExplorer.jsx
+++ b/frontend/src/features/analytics/videos/VideoExplorer.jsx
@@ -35,8 +35,8 @@ function parseDurationToSeconds(iso) {
const PERFORMANCE_TIERS = [
{ label: 'All', value: 'all' },
{ label: 'Viral (>1M)', value: 'viral', min: 1000000 },
- { label: 'High (100K–1M)', value: 'high', min: 100000, max: 1000000 },
- { label: 'Medium (10K–100K)', value: 'medium', min: 10000, max: 100000 },
+ { label: 'High (100K-1M)', value: 'high', min: 100000, max: 1000000 },
+ { label: 'Medium (10K-100K)', value: 'medium', min: 10000, max: 100000 },
{ label: 'Low (<10K)', value: 'low', max: 10000 },
];
diff --git a/frontend/src/features/publishing/UploadContent.jsx b/frontend/src/features/publishing/UploadContent.jsx
index 252828a..8ea8ad0 100644
--- a/frontend/src/features/publishing/UploadContent.jsx
+++ b/frontend/src/features/publishing/UploadContent.jsx
@@ -1,4 +1,4 @@
-import React, { useState, useEffect, useRef } from 'react';
+import React, { useState, useEffect, useRef } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
@@ -43,7 +43,7 @@ const BULK_INTERVAL_OPTIONS = [
const CONTENT_TYPES = [
{ value: 'IMAGE', label: 'Photo', icon: ImageIcon, color: '#F58529', accept: 'image/jpeg', desc: 'JPEG, 4:5 to 1.91:1, max 8MB' },
- { value: 'REELS', label: 'Reel', icon: Film, color: '#DD2A7B', accept: 'video/mp4,video/quicktime', desc: 'MP4/MOV 9:16, 3s–15min, max 300MB' },
+ { value: 'REELS', label: 'Reel', icon: Film, color: '#DD2A7B', accept: 'video/mp4,video/quicktime', desc: 'MP4/MOV 9:16, 3s-15min, max 300MB' },
{ value: 'STORIES', label: 'Story', icon: BookOpen, color: '#8134AF', accept: 'image/jpeg,video/mp4,video/quicktime', desc: 'Image or video, 9:16, max 60s' },
];
diff --git a/frontend/src/services/api.js b/frontend/src/services/api.js
index 6745048..992642f 100644
--- a/frontend/src/services/api.js
+++ b/frontend/src/services/api.js
@@ -1,4 +1,4 @@
-import { supabase } from '../lib/supabase';
+import { supabase } from '../lib/supabase';
const API = import.meta.env.VITE_API_URL || 'http://localhost:8787/api';