diff --git a/CLAUDE.md b/CLAUDE.md index 8a74d65..1e4675b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -105,17 +105,19 @@ v41 Iris turns the current design, the Interactive Tour, or the Before / After c - **Ownership** is stateless: the key is `base64url(HMAC-SHA256(SHARE_SIGNING_SECRET, 'own:' + id))`. The editor keeps it in `glint_shares` ("Your links"), and a manage link (`/s/#key=...`) lets the viewer page delete the share. - **Viewer.** `s/index.html` (Vite input `share`, entry `src/share/viewer.js`, also a knip entry) is the page. On Vercel, `vercel.json` rewrites `/s/` to `api/share.js?op=page` (`api/_share-page.js`), which fills `` (Open Graph tags, poster) and `` (the manifest as inline JSON) and sends a strict content security policy. Under `vite`, a dev middleware serves the static page and the viewer fetches `/api/share-manifest` itself. `?embed=1` hides the chrome. The service worker's navigation fallback skips `/s/` and `/api/` (`navigateFallbackDenylist`), or a returning visitor would get the cached homepage. - **Players are shared with the exports.** The Tour player (`src/share/tour-player.js`) and the Before / After slider (`src/share/compare-player.js`) have no imports; the viewer imports them, and `tour-export.js` / `compare-export.js` inline their raw text (`?raw`) into the downloaded .html files. Edit the player modules, never the export templates. A test checks they stay import-free. -- **One function for all share routes.** The Vercel Hobby plan allows 12 serverless functions per deployment and every non-underscore file in `api/` is one (10 today). So `api/share.js` is the only deployed share function: `vercel.json` rewrites `/api/share-` and `/s/` to it with `?op=`, and it dispatches to the route modules `api/_share-.js` (underscore files are not deployed on their own). **Add new server routes the same way, not as new `api/` files**, or the deployment fails with `exceeded_serverless_functions_per_deployment`. +- **One function for all share routes.** The Vercel Hobby plan allows 12 serverless functions per deployment and every non-underscore file in `api/` is one (11 today, with `api/account.js`). So `api/share.js` is the only deployed share function: `vercel.json` rewrites `/api/share-` and `/s/` to it with `?op=`, and it dispatches to the route modules `api/_share-.js` (underscore files are not deployed on their own). **Add new server routes the same way, not as new `api/` files**, or the deployment fails with `exceeded_serverless_functions_per_deployment`. - **Tests and local runs.** `SHARE_STORE=memory` swaps Blob for an in-process store (still minting real client tokens), so `scripts/regression-tests.mjs` runs every route. Under plain `npm run dev` there is no `/api`, so `shareStatus()` is false and the Share panel says links are not set up; downloads still work. -### Glint Pro waitlist and usage analytics -Not a versioned release; groundwork for a paid plan (Glint Pro: hosted AI, lasting share links, sync). The studio itself stays free, and site copy must keep saying so. +### Glint Pro groundwork: waitlist, analytics, accounts and AI credits +Not a versioned release; groundwork for a paid plan (Glint Pro: hosted AI, lasting share links, sync). The studio itself stays free, and site copy must keep saying so. Glint Pro itself will be a later numbered release (v42 Junction shipped separately). + +- **Accounts and hosted AI credits (Clerk + Neon; Supabase is gone).** Supabase was removed entirely, and cloud project and template sync, the community gallery (`gallery.js`) and live collaboration (`collab.js`) went with it; projects now live only in the browser. Sign-in is Clerk: `src/features/auth.js` loads Clerk's two browser bundles from the Clerk instance's own Frontend API (host decoded from the publishable key), so there is no Clerk package in the build; without a key no sign-in UI shows and nothing loads. It exports `getToken()`, `getUser()`, `onAuthChange()`, `openSignIn()`, `isConfigured()`; the header pill is a Sign in button or Clerk's own user button. The key is read at build time from `VITE_CLERK_PUBLISHABLE_KEY` or `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` (the name Clerk's Vercel Marketplace install adds; `vite.config.js` `envPrefix` lets it through). Server side, `api/_account.js` verifies the Clerk session token with `@clerk/backend` `verifyToken` (`CLERK_SECRET_KEY`, or `CLERK_JWT_KEY` for a networkless check) and keeps plans and credit counts in Neon Postgres through `@neondatabase/serverless` (`DATABASE_URL` or `POSTGRES_URL`). The schema is `api/_account-schema.js` (`subscriptions`, `ai_usage`, and the atomic `glint_use_credits(user, cost, free_limit, pro_limit)` function, keyed by Clerk's text user id); **the server installs it itself** the first time a query fails with a missing function or table, so there is no SQL to run by hand. `metered(kind, handler)` wraps the six hosted AI routes, spends credits before the model call (`CREDIT_COSTS`: 1 for text / vision / enhance / agent, 5 for an image) and refunds them when the route answers with an error. It answers `401 { code: 'sign_in' }` or `402 { code: 'no_credits' }`; a Clerk or database failure answers 503 (closed, not free). **Metering is on only when the deployment has a Clerk key and a database URL**; without them the routes behave as before. Limits default to 20 free and 500 Pro credits a month (`AI_FREE_CREDITS`, `AI_PRO_CREDITS`). `api/account.js` is one function for every account route (`?op=me` today; checkout, portal and the payment webhook go here, not in new files). In the editor, `src/features/account.js` `hostedFetch(path, body)` is the only way to call a hosted AI route: it adds the token, turns a sign-in or out-of-credits answer into a 501 (which every caller already treats as "use the person's own key") and shows why in a toast unless the person has their own key; the `#ai-credits` header chip shows credits left. **A new hosted AI route must be wrapped in `metered()` and called through `hostedFetch()`.** Tests use `ACCOUNT_STORE=memory` and sign throwaway Clerk-shaped tokens. Still to build: checkout + webhook (a merchant of record such as Lemon Squeezy), an account panel, share link perks, real prices. - **Waitlist.** The pricing page's Pro card (`pricing/index.html`, `#pro`) has a `form[data-waitlist]` that `public/site.js` (0a) posts to `/api/waitlist`. `api/_waitlist.js` holds both routes as ops of the one share function (`vercel.json` rewrites `/api/waitlist` and `/api/waitlist-export` to `api/share.js`). The Blob store is public, so entries are stored unreadable: the file name is an HMAC of the email (which also de-duplicates) and the body is AES-256-GCM encrypted, both keyed from `SHARE_SIGNING_SECRET`. Changing that secret orphans the list. The join route answers the same whether or not the email was already there. Read the list with `curl -H "Authorization: Bearer $CRON_SECRET" https:///api/waitlist-export?format=csv`. -- **Analytics.** Vercel Web Analytics, no cookies. Marketing pages load it from `public/site.js` (0) (skipped on localhost) and send `open_studio` and `waitlist_join`. The editor uses `src/features/analytics.js` (`bindAnalytics()`, `track(name, data)`): `section_used` once per sidebar section per visit (a capture listener, so new sections are covered for free), `export`, `share_link`, `roll_develop`. **Events carry feature names and choices only, never images, file names, colors or typed text;** if you add an event, list it on the privacy page. +- **Analytics.** Vercel Web Analytics, no cookies. Marketing pages load it from `public/site.js` (0) (skipped on localhost) and send `open_studio` and `waitlist_join`. The editor uses `src/features/analytics.js` (`bindAnalytics()`, `track(name, data)`): `section_used` once per sidebar section per visit (a capture listener, so new sections are covered for free), `export`, `share_link`, `roll_develop`, `ai_blocked` (sign-in needed or out of credits). **Events carry feature names and choices only, never images, file names, colors or typed text;** if you add an event, list it on the privacy page. ### Persistence -User data (templates, brand kits, projects, onboarding flags) is stored in `localStorage` under `glint_*` keys, each feature managing its own. `src/state/serialize.js` handles project save/load (`SERIALIZED_FIELDS` for the lean payload, `PROJECT_FIELDS` for heavier fields like dataURLs). Cloud sync (optional) goes through Supabase. The Campaign folder lives in its own `glint_campaigns_v1` localStorage store (optional Supabase mirror ships but is unwired) and is never snapshotted. Projects (`glint_projects_v12`) are stored in IndexedDB (`src/state/project-db.js`, db `glint`, store `kv`) with a localStorage fallback (used when IndexedDB is unavailable or does not load within 8s); any project store found in localStorage is merged into IndexedDB on every healthy load (not one-time) and then removed, and the `glint_projects_idb` flag records that IndexedDB was used before, so a later load failure retries once and warns the user. The projects status line shows "Saved" only after the IndexedDB write commits. Share links (v41) keep each link's record and owner key in `glint_shares` (newest first, max 50, thumbnails dropped first on quota errors); the shares themselves live in Vercel Blob, not in the project. Since v40 the Projects panel's "History" button (whole-project versions) is labeled "Project timeline", so it is not confused with the History panel. +User data (templates, brand kits, projects, onboarding flags) is stored in `localStorage` under `glint_*` keys, each feature managing its own. `src/state/serialize.js` handles project save/load (`SERIALIZED_FIELDS` for the lean payload, `PROJECT_FIELDS` for heavier fields like dataURLs). There is no cloud sync (it left with Supabase). The Campaign folder lives in its own `glint_campaigns_v1` localStorage store and is never snapshotted. Projects (`glint_projects_v12`) are stored in IndexedDB (`src/state/project-db.js`, db `glint`, store `kv`) with a localStorage fallback (used when IndexedDB is unavailable or does not load within 8s); any project store found in localStorage is merged into IndexedDB on every healthy load (not one-time) and then removed, and the `glint_projects_idb` flag records that IndexedDB was used before, so a later load failure retries once and warns the user. The projects status line shows "Saved" only after the IndexedDB write commits. Share links (v41) keep each link's record and owner key in `glint_shares` (newest first, max 50, thumbnails dropped first on quota errors); the shares themselves live in Vercel Blob, not in the project. Since v40 the Projects panel's "History" button (whole-project versions) is labeled "Project timeline", so it is not confused with the History panel. ### Brand & identifiers (v36 Glint rename) The app was called SnapShotPro through v35. Since v36 every identifier uses the Glint name: localStorage keys use the `glint_` prefix, the IndexedDB db is `glint` (store `kv`, project store key `glint_projects_v12`), the projects BroadcastChannel is `glint-projects`, and the extension handoff messages are `glint-capture` / `glint-capture-ack` (`ext-receiver.js` still accepts `snapshotpro-capture` and acks it as `snapshotpro-capture-ack`, so extension builds already installed keep working). **New storage keys use the `glint_` prefix.** @@ -218,7 +220,7 @@ Current `SCHEMA_VERSION` is 26 (v42 Junction: tour hotspot targets, Bokeh tilt-s ## Backlog (unbuilt) - **From v42:** CMYK conversion and real TrimBox / BleedBox entries for the print PDF; a true high-resolution re-render for print (today it is the design's own pixels plus a smooth upscale); tour links in the board's PNG export; an on-canvas handle for the tilt-shift band; Design Agent tools for tours. -- **From v41:** view counts; a hosted "Your links" that follows the person across browsers (today the owner keys live in one browser's `glint_shares`). Retiring Supabase entirely (sign-in, cloud project and template sync, the community gallery, live collaboration) was proposed for v41.1 and needs a decision first. +- **From v41:** view counts; a hosted "Your links" that follows the person across browsers (today the owner keys live in one browser's `glint_shares`). Supabase was retired (see the Glint Pro groundwork section); cloud project sync, a community gallery or live collaboration would have to be rebuilt on Neon. - **Still open from the v39 options list:** the extension's element picker. From v39 itself: per-frame flips on video. (Raised cards in dark mode shipped in v41.0.1: `flipLightness` folds the top of the range so a white card lands above a light-gray page; the light direction still saturates everything below the surface to white.) - **From v40:** nothing left; Look chip previews with temperature / tint and scaled blur, the shared Light / Dark scene record, clearing history on page switch and normalizing Roll grade overrides on load all shipped in v41.0.1. - **New creative outputs:** AI Storyboard / multi-panel generator. (Tour branching shipped in v42.) @@ -226,7 +228,7 @@ Current `SCHEMA_VERSION` is 26 (v42 Junction: tour hotspot targets, Bokeh tilt-s - **Automation & scale:** public REST API + CLI (headless generation). - **More capture surfaces:** element-pick + Firefox/Edge port for the extension (deferred v26 stretch); mobile camera capture. - **Collab & platform:** async review / approvals (pinned threaded comments, sign-off; distinct from live cursors); template marketplace + creator monetization; plugin / extension SDK. -- **Deferred from shipped releases:** a `look` kind in the community gallery (v38); Roll per-shot focal point and a Roll-aware Merge Studio (v37); Motion Studio full per-property keyframing + bottom-dock timeline (v29); Supabase campaign mirror wiring, in-place multi-language re-render, open-ended Producer autonomy (v30). +- **Deferred from shipped releases:** Roll per-shot focal point and a Roll-aware Merge Studio (v37); Motion Studio full per-property keyframing + bottom-dock timeline (v29); in-place multi-language re-render, open-ended Producer autonomy (v30). ## Things that look like project rules but aren't diff --git a/DEPLOY.md b/DEPLOY.md index e5639aa..d310283 100644 --- a/DEPLOY.md +++ b/DEPLOY.md @@ -69,7 +69,7 @@ In the Vercel project dashboard → Settings → Domains → add your domain. Ve The app still works without these values for offline editing, local analysis, PWA install, and bring-your-own-key AI. Add them when you want hosted AI, -accounts, cloud sync, or share links. +accounts, or share links. ### Hosted AI backend @@ -85,45 +85,22 @@ This enables the serverless routes in `api/` so visitors can use AI features without pasting their own key. If `OPENAI_API_KEY` is missing, those routes return `501` and the editor falls back to the existing browser-key flow. -### Supabase (for accounts + cloud project sync) +### Accounts and hosted AI credits (Clerk + Neon) -Create a free Supabase project at https://supabase.com/, then in the Vercel project → Settings → Environment Variables, add: +Sign-in is Clerk and the credit counts live in a Neon Postgres database. Add +both from the Vercel project's **Storage / Marketplace** tab; each one adds its +own environment variables, so there is nothing to copy by hand: -| Name | Value | -|------|-------| -| `VITE_SUPABASE_URL` | from Supabase project Settings → API | -| `VITE_SUPABASE_ANON_KEY` | from Supabase project Settings → API (the **anon public** key, safe to ship to browsers) | - -Both must start with `VITE_` so Vite exposes them to the client bundle. - -Then in your Supabase project, create the schema (SQL Editor → New Query): - -```sql -create table if not exists public.templates ( - user_id uuid not null references auth.users(id) on delete cascade, - name text not null, - payload jsonb not null, - updated_at timestamptz default now(), - primary key (user_id, name) -); -alter table public.templates enable row level security; -create policy "users own templates" on public.templates - for all using (auth.uid() = user_id) with check (auth.uid() = user_id); - -create table if not exists public.projects ( - id uuid primary key default gen_random_uuid(), - user_id uuid not null references auth.users(id) on delete cascade, - name text not null, - payload jsonb not null, - updated_at timestamptz default now(), - unique (user_id, name) -); -alter table public.projects enable row level security; -create policy "users own projects" on public.projects - for all using (auth.uid() = user_id) with check (auth.uid() = user_id); -``` +| Added by | Name | Used for | +|------|-------|-------| +| Clerk | `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` | The browser's sign-in (the build reads this name; `VITE_CLERK_PUBLISHABLE_KEY` also works) | +| Clerk | `CLERK_SECRET_KEY` | The server checks session tokens with it | +| Neon | `DATABASE_URL` | Plans and monthly credit counts | -In Supabase → Authentication → Providers, enable Email (default) and optionally Google/GitHub. For Google/GitHub, set the redirect URL to your Vercel domain. +Redeploy after adding them. The server creates its two tables and one function +in the database the first time it is used. Once both are present, hosted AI +needs a signed-in account and spends credits (20 a month by default; see +`docs/BACKEND.md`). Without them, hosted AI works for everyone as before. ### AI cloud features @@ -137,7 +114,7 @@ See `docs/BACKEND.md` for the route list and what the backend adds. ### Bundle size & lazy loading -v5 dependencies (Supabase SDK, OpenAI/Anthropic SDKs, Tesseract.js, @imgly/background-removal) are split into separate chunks via Vite's `manualChunks` and dynamically `import()`-ed only when the related feature is first used. Initial JS payload stays roughly the same as v4 (~30KB gzipped main bundle + small chunks). +v5 dependencies (OpenAI/Anthropic SDKs, Tesseract.js, @imgly/background-removal) are split into separate chunks via Vite's `manualChunks` and dynamically `import()`-ed only when the related feature is first used. Initial JS payload stays roughly the same as v4 (~30KB gzipped main bundle + small chunks). The 23 MB `ort.wasm` (background-removal model) in `dist/` is **not loaded by default** — it's only fetched when the user clicks "Remove Background." Vercel serves it as a static asset like any other. diff --git a/MIGRATION.md b/MIGRATION.md index 776efb2..77bc41d 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -69,18 +69,10 @@ npm run build Should produce a `dist/` folder with `index.html` plus hashed JS and CSS bundles. That's what Vercel deploys. -## Supabase schema (cloud features) +## Accounts database -The copyable SQL lives in `src/features/auth.js` (the setup modal's "Copy SQL" -button) — paste it into the Supabase SQL Editor. Tables and their RLS: - -- `templates` — per-user named template payloads. PK `(user_id, name)`. RLS: - owner-only (`auth.uid() = user_id`). -- `projects` — per-user named full-project snapshots. RLS: owner-only. -- `gallery` (v11.3) — public community gallery of templates + brand kits. - Columns: `id, author_id, kind('template'|'brandkit'), name, payload jsonb, - preview_url, likes, created_at`. RLS: **public read** (`select using (true)`), - insert/delete restricted to the author (`auth.uid() = author_id`). - -Storage buckets (created on demand by the client, public): -- `shares` (share links), `gallery` (v11.3 thumbnails). +Supabase is gone (cloud project and template sync, the community gallery and +live collaboration went with it). Sign-in is Clerk, and a Neon Postgres database +holds two tables, `subscriptions` and `ai_usage`, plus the `glint_use_credits` +function. The schema lives in `api/_account-schema.js` and the server installs +it on first use. diff --git a/README.md b/README.md index e35a5ab..0f67891 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ you see is exactly what you download. - **AI (optional)** — a design agent that composes a look from a sentence, background generation, subject isolation, OCR, vision, outpaint, and magic eraser. - **Motion** — Ken Burns, per-element animation, a timeline, in-browser screen recording, and GIF or MP4 export. - **Output** — PNG, JPEG, WebP, GIF, MP4, multi-page PDF decks, and ZIP for batches and App Store sets at every store size. -- **Projects** — save, version history, and optional cloud sync. A Cmd-K command palette ties it together. +- **Projects** — save and version history, kept in your browser. A Cmd-K command palette ties it together. See the full list at [snapshotpro.xyz/features](https://snapshotpro.xyz/features/). @@ -72,8 +72,8 @@ npm run preview # serve the built dist/ Vanilla JavaScript and Vite, no framework. The editor lives at `/editor/`; the marketing and info pages are separate Vite inputs (see `rollupOptions.input` in `vite.config.js`). 3D mockups -use three.js, optional AI runs through Vercel serverless functions in `api/`, and cloud sync -is optional via Supabase. Architecture notes are in [`CLAUDE.md`](CLAUDE.md); deployment is in +use three.js, optional AI runs through Vercel serverless functions in `api/`, and optional +sign-in (Clerk) with a small Postgres database (Neon) counts hosted AI credits. Architecture notes are in [`CLAUDE.md`](CLAUDE.md); deployment is in [`DEPLOY.md`](DEPLOY.md). ## Contributing diff --git a/ai/index.html b/ai/index.html index 65d864b..869c403 100644 --- a/ai/index.html +++ b/ai/index.html @@ -197,7 +197,7 @@

Works hosted, or with your own key

Hosted

Nothing to set up

-

On the live site, AI features work out of the box. We proxy the request so you can try everything without an account or an API key.

+

On the live site, AI features work without an API key. We proxy the request, and a free account keeps count of your monthly credits.

Bring your own key diff --git a/api/_account-schema.js b/api/_account-schema.js new file mode 100644 index 0000000..a949dc8 --- /dev/null +++ b/api/_account-schema.js @@ -0,0 +1,77 @@ +// Glint Pro groundwork: the Postgres schema for plans and hosted AI credits. +// The server installs it by itself the first time it finds the database empty +// (api/_account.js), so there is no SQL to run by hand. Every statement is safe +// to run again. Nothing in the browser talks to this database. +// +// user_id is the sign-in provider's user id (Clerk: "user_..."). + +export const SCHEMA = [ + `create table if not exists subscriptions ( + user_id text primary key, + plan text not null default 'pro', + status text not null default 'active', + current_period_end timestamptz, + provider text, + provider_customer_id text, + provider_subscription_id text, + updated_at timestamptz not null default now() + )`, + `create table if not exists ai_usage ( + user_id text not null, + month date not null, + used integer not null default 0 check (used >= 0), + updated_at timestamptz not null default now(), + primary key (user_id, month) + )`, + // One atomic step: work out the plan, then spend (cost > 0), refund + // (cost < 0) or just read (cost = 0) this month's credits. A spend that + // would pass the limit changes nothing and comes back with allowed = false. + // status: active | trialing | past_due | canceled; a canceled plan still + // counts until current_period_end (what was paid for). + `create or replace function glint_use_credits( + p_user text, p_cost integer, p_free_limit integer, p_pro_limit integer + ) returns json + language plpgsql + as $fn$ + declare + v_month date := date_trunc('month', timezone('utc', now()))::date; + v_plan text := 'free'; + v_limit integer; + v_used integer; + v_allowed boolean := true; + begin + if exists ( + select 1 from subscriptions s + where s.user_id = p_user and s.plan = 'pro' + and (s.status in ('active', 'trialing') + or (s.current_period_end is not null and s.current_period_end > now())) + ) then + v_plan := 'pro'; + end if; + v_limit := case when v_plan = 'pro' then p_pro_limit else p_free_limit end; + + insert into ai_usage (user_id, month) values (p_user, v_month) + on conflict (user_id, month) do nothing; + + if p_cost > 0 then + update ai_usage set used = used + p_cost, updated_at = now() + where user_id = p_user and month = v_month and used + p_cost <= v_limit + returning used into v_used; + if not found then + v_allowed := false; + select used into v_used from ai_usage where user_id = p_user and month = v_month; + end if; + elsif p_cost < 0 then + update ai_usage set used = greatest(0, used + p_cost), updated_at = now() + where user_id = p_user and month = v_month + returning used into v_used; + else + select used into v_used from ai_usage where user_id = p_user and month = v_month; + end if; + + return json_build_object('allowed', v_allowed, 'used', v_used, 'limit', v_limit, 'plan', v_plan); + end; + $fn$`, +]; + +export const USE_CREDITS = 'select glint_use_credits($1::text, $2::int, $3::int, $4::int) as r'; diff --git a/api/_account.js b/api/_account.js new file mode 100644 index 0000000..953b9e5 --- /dev/null +++ b/api/_account.js @@ -0,0 +1,211 @@ +// Glint Pro groundwork: accounts and hosted AI credits. +// +// Sign-in is Clerk; plans and credit counts live in Postgres (Neon). This +// module is the server side: it verifies the caller's Clerk session token, +// then spends credits through one atomic Postgres function +// (api/_account-schema.js), which also works out the plan. Nothing here +// trusts the browser. +// +// Metering is on only when the deployment has a Clerk key and a database URL +// (both arrive when Clerk and Neon are added from the Vercel Marketplace). +// Without them every hosted AI route behaves as it did before. + +import { verifyToken } from '@clerk/backend'; +import { neon } from '@neondatabase/serverless'; +import { ApiError, serverOpenAIKey } from './_shared.js'; +import { SCHEMA, USE_CREDITS } from './_account-schema.js'; + +// What one call costs. Image models cost far more to run than text ones. +export const CREDIT_COSTS = { text: 1, vision: 1, enhance: 1, agent: 1, image: 5 }; + +const posInt = (value, fallback) => { + const n = Math.floor(Number(value)); + return Number.isFinite(n) && n > 0 ? n : fallback; +}; + +export function accountConfig() { + const memory = process.env.ACCOUNT_STORE === 'memory'; // tests only + const secretKey = process.env.CLERK_SECRET_KEY || ''; + const jwtKey = process.env.CLERK_JWT_KEY || ''; // optional: verify without a network call + const databaseUrl = process.env.DATABASE_URL || process.env.POSTGRES_URL || ''; + return { + enabled: Boolean((secretKey || jwtKey) && (memory || databaseUrl)), + memory, + secretKey, + jwtKey, + databaseUrl, + freeCredits: posInt(process.env.AI_FREE_CREDITS, 20), + proCredits: posInt(process.env.AI_PRO_CREDITS, 500), + }; +} + +// An error the editor can act on: `code` says what to offer the person. +export class MeterError extends ApiError { + constructor(status, code, message, extra = {}) { + super(status, message); + this.code = code; + this.extra = extra; + } +} + +export function readBearer(req) { + const h = (req.headers && (req.headers.authorization || req.headers.Authorization)) || ''; + const m = /^Bearer\s+([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)$/.exec(String(h)); + return m && m[1].length < 4096 ? m[1] : ''; +} + +const unavailable = () => new ApiError(503, 'Hosted AI could not check your account just now. Try again in a moment.'); + +// Who does this Clerk session token belong to? Null means not signed in: no +// token, an expired one, or one this Clerk instance did not sign. +export async function userFromToken(cfg, token) { + if (!token) return null; + try { + const claims = await verifyToken(token, cfg.jwtKey ? { jwtKey: cfg.jwtKey } : { secretKey: cfg.secretKey }); + const id = claims && typeof claims.sub === 'string' ? claims.sub : ''; + return /^[A-Za-z0-9_-]{1,128}$/.test(id) ? { id } : null; + } catch (e) { + // "token-..." reasons are about the token itself. Anything else (a wrong + // secret key, Clerk's key service unreachable) is our side failing. + if (typeof e.reason === 'string' && e.reason.startsWith('token-')) return null; + console.error('[account] could not verify a session token:', e.reason || e.message); + throw unavailable(); + } +} + +// ── credit stores ──────────────────────────────────────────────────────────── + +// Tests: the same rules as the Postgres function, in memory. +const memoryUsage = new Map(); +const memoryPro = new Set(); +export function memoryAccounts() { return { usage: memoryUsage, pro: memoryPro }; } +function memoryUse(user, cost, freeLimit, proLimit) { + const plan = memoryPro.has(user) ? 'pro' : 'free'; + const limit = plan === 'pro' ? proLimit : freeLimit; + const now = memoryUsage.get(user) || 0; + let allowed = true; + if (cost > 0) { if (now + cost <= limit) memoryUsage.set(user, now + cost); else allowed = false; } + else if (cost < 0) memoryUsage.set(user, Math.max(0, now + cost)); + return { allowed, used: memoryUsage.get(user) || 0, limit, plan }; +} + +let sqlClient = null, sqlUrl = ''; +function db(cfg) { + if (!sqlClient || sqlUrl !== cfg.databaseUrl) { sqlClient = neon(cfg.databaseUrl); sqlUrl = cfg.databaseUrl; } + return sqlClient; +} + +// 42883: the function is missing; 42P01: a table is missing. Either way the +// database has not been set up yet, which the server does itself, once. +const needsSchema = (e) => e && (e.code === '42883' || e.code === '42P01'); + +async function postgresUse(cfg, args) { + const sql = db(cfg); + try { + return (await sql.query(USE_CREDITS, args))[0].r; + } catch (e) { + if (!needsSchema(e)) throw e; + for (const statement of SCHEMA) await sql.query(statement); + return (await sql.query(USE_CREDITS, args))[0].r; + } +} + +// cost > 0 spends, cost < 0 refunds, 0 only reads. +export async function useCredits(cfg, userId, cost) { + let out; + try { + out = cfg.memory + ? memoryUse(userId, cost, cfg.freeCredits, cfg.proCredits) + : await postgresUse(cfg, [userId, cost, cfg.freeCredits, cfg.proCredits]); + } catch (e) { + console.error('[account] credits query failed:', e.code || '', e.message); + throw unavailable(); + } + if (!out || typeof out.used !== 'number' || typeof out.limit !== 'number') throw unavailable(); + return { allowed: out.allowed !== false, used: out.used, limit: out.limit, plan: out.plan === 'pro' ? 'pro' : 'free' }; +} + +// First day of next month, UTC: when the monthly credits start over. +export function resetsAt(now = new Date()) { + return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1)).toISOString(); +} + +// Spend `cost` credits for this request. Returns null when the call is not +// metered at all, otherwise { usage, refund }. Throws a MeterError when the +// person has to sign in or is out of credits. +export async function meter(req, cost) { + const cfg = accountConfig(); + // No server key: the route answers 501 itself and the editor uses the + // person's own key, so there is nothing to charge for. + if (!cfg.enabled || req.method !== 'POST' || !serverOpenAIKey()) return null; + const user = await userFromToken(cfg, readBearer(req)); + if (!user) { + throw new MeterError(401, 'sign_in', `Sign in to use Glint's hosted AI (${cfg.freeCredits} free credits a month), or add your own API key.`, { limit: cfg.freeCredits }); + } + const usage = await useCredits(cfg, user.id, cost); + if (!usage.allowed) { + const left = Math.max(0, usage.limit - usage.used); + const message = left > 0 + ? `This needs ${cost} hosted AI credits and you have ${left} left this month. Your own API key still works.` + : `You have used all ${usage.limit} hosted AI credits for this month. Your own API key still works.`; + throw new MeterError(402, 'no_credits', message, { used: usage.used, limit: usage.limit, plan: usage.plan, resets: resetsAt() }); + } + let refunded = false; + return { + usage, + async refund() { + if (refunded) return; + refunded = true; + try { await useCredits(cfg, user.id, -cost); } catch (e) { console.error('[account] refund failed', e.message); } + }, + }; +} + +// Wrap a hosted AI route. The credits are spent before the model is called (so +// two requests at once cannot both slip under the limit) and handed back when +// the route answers with an error. +export function metered(kind, handler) { + const cost = CREDIT_COSTS[kind]; + return async function meteredHandler(req, res) { + let ticket; + try { + ticket = await meter(req, cost); + } catch (e) { + const status = e instanceof ApiError ? e.status : 500; + res.setHeader('Cache-Control', 'no-store'); + res.status(status).json({ error: e instanceof ApiError ? e.message : 'Something went wrong. Try again.', ...(e.code ? { code: e.code, ...e.extra } : {}) }); + return; + } + if (!ticket) return handler(req, res); + res.setHeader('X-Glint-Credits', `${ticket.usage.used}/${ticket.usage.limit}`); + let code = 200; + const status = res.status.bind(res); + res.status = (c) => { code = c; return status(c); }; + try { + await handler(req, res); + } catch (e) { + code = 500; + throw e; + } finally { + if (code >= 400) await ticket.refund(); + } + }; +} + +// GET /api/account?op=me: what the editor shows as "credits left". +export async function me(req, res) { + res.setHeader('Cache-Control', 'no-store'); + try { + if (req.method !== 'GET') throw new ApiError(405, 'Method not allowed'); + const cfg = accountConfig(); + if (!cfg.enabled) { res.status(200).json({ enabled: false }); return; } + const base = { enabled: true, hosted: Boolean(serverOpenAIKey()), costs: CREDIT_COSTS, freeCredits: cfg.freeCredits }; + const user = await userFromToken(cfg, readBearer(req)); + if (!user) { res.status(200).json({ ...base, signedIn: false }); return; } + const usage = await useCredits(cfg, user.id, 0); + res.status(200).json({ ...base, signedIn: true, plan: usage.plan, used: usage.used, limit: usage.limit, resets: resetsAt() }); + } catch (e) { + if (!(e instanceof ApiError)) console.error('[account]', e); + res.status(e instanceof ApiError ? e.status : 500).json({ error: e instanceof ApiError ? e.message : 'Something went wrong. Try again.' }); + } +} diff --git a/api/account.js b/api/account.js new file mode 100644 index 0000000..e178890 --- /dev/null +++ b/api/account.js @@ -0,0 +1,18 @@ +// Glint Pro groundwork: one serverless function for every account route, +// dispatched on ?op= like api/share.js (the Hobby plan allows 12 functions). +// Today that is `me`; checkout, the billing portal and the payment webhook +// join it when billing is built. +import { me } from './_account.js'; + +const ROUTES = { me }; + +export default async function handler(req, res) { + const raw = req.query && req.query.op; + const op = Array.isArray(raw) ? raw[0] : raw; + const route = typeof op === 'string' && Object.prototype.hasOwnProperty.call(ROUTES, op) ? ROUTES[op] : null; + if (!route) { + res.status(404).json({ error: 'Not found' }); + return; + } + return route(req, res); +} diff --git a/api/ai-agent.js b/api/ai-agent.js index 36c211c..6bc9808 100644 --- a/api/ai-agent.js +++ b/api/ai-agent.js @@ -10,13 +10,16 @@ // Response (200 JSON): { text: string, toolCalls: [{ id, name, args }] } import { requirePost, parseBody, ApiError, openAIChat } from './_shared.js'; +import { metered } from './_account.js'; // Only allow known tool-capable chat models (the client sends AGENT_MODELS.openai). // v30 model policy: gpt-5.5 for agent reasoning. Override with OPENAI_TEXT_MODEL. const DEFAULT_AGENT_MODEL = process.env.OPENAI_TEXT_MODEL || 'gpt-5.5'; const ALLOWED_MODELS = [DEFAULT_AGENT_MODEL, 'gpt-5.5', 'gpt-4o', 'gpt-4o-mini']; -export default async function handler(req, res) { +export default metered('agent', handler); + +async function handler(req, res) { if (!requirePost(req, res)) return; try { const { messages, tools, model, max_tokens } = parseBody(req); diff --git a/api/ai-enhance.js b/api/ai-enhance.js index b75152e..e6268fa 100644 --- a/api/ai-enhance.js +++ b/api/ai-enhance.js @@ -8,6 +8,7 @@ import { requirePost, textFromChat } from './_shared.js'; +import { metered } from './_account.js'; export const config = { api: { bodyParser: { sizeLimit: '8mb' } } }; @@ -27,7 +28,9 @@ function parseFilters(text) { } } -export default async function handler(req, res) { +export default metered('enhance', handler); + +async function handler(req, res) { if (!requirePost(req, res)) return; try { diff --git a/api/ai-text.js b/api/ai-text.js index 8a2684a..b4325e9 100644 --- a/api/ai-text.js +++ b/api/ai-text.js @@ -7,8 +7,11 @@ // Response (200 JSON): { text: string } import { requirePost, parseBody, ApiError, openAIChat } from './_shared.js'; +import { metered } from './_account.js'; -export default async function handler(req, res) { +export default metered('text', handler); + +async function handler(req, res) { if (!requirePost(req, res)) return; try { const { prompt, json = false, system } = parseBody(req); diff --git a/api/ai-vision.js b/api/ai-vision.js index 915e86d..e6a4cda 100644 --- a/api/ai-vision.js +++ b/api/ai-vision.js @@ -7,10 +7,13 @@ import { requirePost, textFromChat } from './_shared.js'; +import { metered } from './_account.js'; export const config = { api: { bodyParser: { sizeLimit: '8mb' } } }; -export default async function handler(req, res) { +export default metered('vision', handler); + +async function handler(req, res) { if (!requirePost(req, res)) return; try { diff --git a/api/image-edit.js b/api/image-edit.js index ec4b3fd..f7f4b64 100644 --- a/api/image-edit.js +++ b/api/image-edit.js @@ -9,6 +9,8 @@ // // Returns 501 when no server key is set so the client falls back to BYOK. +import { metered } from './_account.js'; + export const config = { api: { bodyParser: { sizeLimit: '12mb' } } }; function b64ToBlob(b64, type = 'image/png') { @@ -16,7 +18,9 @@ function b64ToBlob(b64, type = 'image/png') { return new Blob([buf], { type }); } -export default async function handler(req, res) { +export default metered('image', handler); + +async function handler(req, res) { if (req.method !== 'POST') { res.status(405).json({ error: 'Method not allowed' }); return; } const key = process.env.OPENAI_API_KEY; if (!key) { res.status(501).json({ error: 'No server key configured' }); return; } diff --git a/api/image-generate.js b/api/image-generate.js index 69ca462..f6b3658 100644 --- a/api/image-generate.js +++ b/api/image-generate.js @@ -7,7 +7,11 @@ // Request (POST JSON): { prompt: string, size?: '1024x1024'|'1536x1024'|'1024x1536' } // Response (200 JSON): { b64: string } // base64 PNG, no data: prefix -export default async function handler(req, res) { +import { metered } from './_account.js'; + +export default metered('image', handler); + +async function handler(req, res) { if (req.method !== 'POST') { res.status(405).json({ error: 'Method not allowed' }); return; diff --git a/docs/BACKEND.md b/docs/BACKEND.md index 4df775e..f345da6 100644 --- a/docs/BACKEND.md +++ b/docs/BACKEND.md @@ -25,6 +25,7 @@ the Vite frontend. | `POST /api/ai-enhance` | Suggests CSS filter values. Returns `{ filters }`. | | `POST /api/image-generate` | Generates a PNG. Returns `{ b64 }`. | | `POST /api/image-edit` | Inpaints/outpaints a PNG. Returns `{ b64 }`. | +| `GET /api/account?op=me` | Accounts. With a Clerk session token: `{ plan, used, limit, resets }` for this month's hosted AI credits. `{ enabled: false }` when metering is not set up. | | `GET /api/share-status` | v41 share links. Returns `{ enabled }`. | | `POST /api/share-create` | Reserves a share id; returns the owner key and the planned file paths. | | `POST /api/share-upload` | The Blob client's upload handshake: a presigned PUT for one planned file. | @@ -51,13 +52,32 @@ every file in `api/` without a leading underscore counts as one. | `BLOB_STORE_ID` or `BLOB_READ_WRITE_TOKEN` | Yes for share links | Added by Vercel when a Blob store is connected to the project. Newer stores add `BLOB_STORE_ID` (the SDK signs in with the deployment's OIDC token); older ones add `BLOB_READ_WRITE_TOKEN`. Either works. | | `SHARE_SIGNING_SECRET` | Yes for share links | 32+ random bytes (base64). Signs the owner key that lets someone delete their link. Changing it orphans every existing key. | | `SHARE_REPORT_EMAIL` | No | Shows a "Report this link" mailto on shared pages. | -| `CRON_SECRET` | Set by Vercel | Authorizes the daily `/api/share-sweep` run. | +| `CRON_SECRET` | Yes for the sweep and the waitlist export | A long random string you add yourself; Vercel then sends it with cron requests. Authorizes the daily `/api/share-sweep` run and `/api/waitlist-export`. Without it both answer 401. | | `SHARE_STORE` | Tests only | `memory` swaps Blob for an in-process store. | +| `CLERK_SECRET_KEY` | Yes for AI credits | Added by the Clerk Marketplace install. The server verifies session tokens with it. | +| `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` | Yes for sign-in | Added by Clerk. Read at build time by the editor (`VITE_CLERK_PUBLISHABLE_KEY` also works). | +| `CLERK_JWT_KEY` | No | Clerk's PEM public key. Lets the server verify tokens without a network call. | +| `DATABASE_URL` | Yes for AI credits | Added by the Neon Marketplace install (`POSTGRES_URL` also works). Clerk plus a database turns metering on. | +| `ACCOUNT_STORE` | Tests only | `memory` keeps credit counts in the process. | +| `AI_FREE_CREDITS` / `AI_PRO_CREDITS` | No | Monthly hosted AI credits per account. Default 20 and 500. | + +## Accounts and hosted AI credits + +Sign-in is Clerk; plans and credit counts live in Neon Postgres. Add both from +the Vercel Marketplace and redeploy. From then on the six hosted AI routes +(`ai-text`, `ai-vision`, `ai-enhance`, `ai-agent`, `image-generate`, +`image-edit`) verify the caller's Clerk session token and spend credits through +the `glint_use_credits` Postgres function: 1 per text, vision, enhance or agent +call, 5 per image. A call that fails gets its credits back. Without a token the +route answers `401 { code: 'sign_in' }`, over the limit `402 { code: +'no_credits' }`, and the editor falls back to the visitor's own API key. The +schema (`api/_account-schema.js`) installs itself the first time the database +is used. To give an account Pro by hand, insert a row into `subscriptions` with +its Clerk user id (`user_...`). Remove the Clerk or database variables to turn +metering off again. Share links (v41) are stored in Vercel Blob under `shares//`: the rendered images, a `poster.webp` for link previews, and a `manifest.json` that names its images by file name only. Shared files are cached for an hour, so a deleted link can take up to an hour to disappear from the CDN. -Supabase is still used separately for accounts, cloud projects, templates, -the community gallery, and live collaboration. diff --git a/editor/index.html b/editor/index.html index b704c3d..82b95b7 100644 --- a/editor/index.html +++ b/editor/index.html @@ -29,6 +29,7 @@ Glint v42 · Junction
+
@@ -1414,22 +1415,11 @@

Share

Your links
-
- -

Start a session and share the link; edits and cursors sync live. Requires cloud setup.

- - -

@@ -92,13 +92,14 @@

Share links

You can delete a link from Your links in the editor, or from its manage link. Deleting removes the files from storage; copies cached along the way can take up to an hour to clear.

Accounts

-

The core editor needs no account, and neither do share links. When you save a cloud project, the project is uploaded to our storage so it can sync; that only happens when you take the action. Sign-in (optional) exists solely to sync your projects across devices.

+

The core editor needs no account, and neither do share links. Your projects stay in your browser and are not uploaded. Sign-in is optional and exists to count hosted AI use. It is run by Clerk, which stores your email address and login details, and the editor loads Clerk's sign-in script when it opens; Glint's own database holds only an account id, never your email or password.

+

When you use the hosted AI while signed in, we keep one number per account per month: how many credits were used. We do not store your prompts or images. If you later subscribe to Glint Pro, we will also keep the status of that subscription; card details stay with the payment provider.

Browser extension

The Glint Capture extension reads a tab only when you click its toolbar button and pick a capture (the activeTab permission); it has no standing access to your browsing and runs no tracking or analytics. The screenshot it takes is handed to the Glint studio and nowhere else: it is held in the extension's local storage for a moment in transit, then cleared once the editor loads it. The extension contains no remote code, and like the rest of the project its source is public.

Analytics

-

We use privacy-friendly, aggregate analytics (Vercel Analytics) to understand traffic and which parts of Glint get used. It sets no cookies. Along with page views, the site and the editor record a few named events: opening the studio from a page, joining the waitlist, the first time a sidebar section is used in a visit, an export (its format), and creating a share link (its kind). Events never include your images, file names, colors or anything you type. There are no advertising trackers and no cross-site profiling. We do not sell data.

+

We use privacy-friendly, aggregate analytics (Vercel Analytics) to understand traffic and which parts of Glint get used. It sets no cookies. Along with page views, the site and the editor record a few named events: opening the studio from a page, joining the waitlist, the first time a sidebar section is used in a visit, an export (its format), creating a share link (its kind), and reaching the hosted AI limit. Events never include your images, file names, colors or anything you type. There are no advertising trackers and no cross-site profiling. We do not sell data.

Glint Pro waitlist

If you join the waitlist on the pricing page, we store your email address, the date, and the page you joined from. It is kept encrypted in Glint's storage on Vercel and used for one thing: telling you when Glint Pro opens. That email will include a way to leave the list. To leave sooner, contact us through GitHub.

diff --git a/scripts/regression-tests.mjs b/scripts/regression-tests.mjs index 332afa4..7068c16 100644 --- a/scripts/regression-tests.mjs +++ b/scripts/regression-tests.mjs @@ -29,6 +29,11 @@ import shareSweepRoute from '../api/_share-sweep.js'; import { shareMeta, fillTemplate } from '../api/_share-page.js'; import shareRouter from '../api/share.js'; import shareUploadRoute from '../api/_share-upload.js'; +import accountRouter from '../api/account.js'; +import { CREDIT_COSTS, resetsAt, memoryAccounts } from '../api/_account.js'; +import { generateKeyPairSync, createSign } from 'node:crypto'; +import aiTextRoute from '../api/ai-text.js'; +import imageGenerateRoute from '../api/image-generate.js'; import { join as waitlistJoin, exportList as waitlistExport, cleanEmail, WAITLIST_PREFIX } from '../api/_waitlist.js'; import { LIMITS, newShareId, isShareId, isAssetName, shareKey, verifyKey, base64url, normalizeManifest, manifestAssets, describeShare, planUploads, isExpired, EXPIRY } from '../src/share/share-core.js'; @@ -115,20 +120,6 @@ async function testFailedProjectImageDecodeClearsPreviousImage() { } } -function testGalleryTemplateApplySnapshotsHistory() { - const source = fs.readFileSync('src/features/gallery.js', 'utf8'); - assert.match(source, /import\s+\{\s*saveStateToHistory\s*\}\s+from\s+['"]\.\.\/state\/history\.js['"]/); - assert.match( - source, - /else\s*\{[\s\S]*saveStateToHistory\(\);[\s\S]*Object\.assign\(state,\s*payload\)/, - 'gallery template apply should snapshot before mutating state' - ); - // v40 — a gallery row never sets pins (their thumbnails go into innerHTML). - assert.match(source, /delete payload\.versions;[\s\S]*Object\.assign\(state,\s*payload\)/); - const collab = fs.readFileSync('src/features/collab.js', 'utf8'); - assert.match(collab, /delete next\.versions;[\s\S]*Object\.assign\(state,\s*next\)/, 'nor does a collab update'); -} - // v35 — Before / After Compare: migration + geometry. function testCompareMigratesAndPersists() { // A pre-v35 design gets a full default block (no Before image leaks in). @@ -1296,12 +1287,143 @@ async function testWaitlistRoutes() { } } +// Glint Pro groundwork: hosted AI spends credits per signed-in account. Clerk +// session tokens are signed here with a throwaway key (CLERK_JWT_KEY makes the +// check networkless), credits use the in-memory store that mirrors the Postgres +// function in api/_account-schema.js, and OpenAI is faked at fetch. +async function testHostedAiIsMetered() { + const saved = { ...process.env }; + const realFetch = globalThis.fetch; + const KEYS = ['CLERK_SECRET_KEY', 'CLERK_JWT_KEY', 'DATABASE_URL', 'POSTGRES_URL', 'ACCOUNT_STORE', 'OPENAI_API_KEY', 'AI_FREE_CREDITS', 'AI_PRO_CREDITS']; + for (const k of KEYS) delete process.env[k]; + const { usage, pro } = memoryAccounts(); + usage.clear(); pro.clear(); + const USER = 'user_2abcDEF123'; + const { publicKey, privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 }); + const stranger = generateKeyPairSync('rsa', { modulusLength: 2048 }); + const part = (o) => Buffer.from(JSON.stringify(o)).toString('base64url'); + const now = Math.floor(Date.now() / 1000); + const sign = (claims, key = privateKey) => { + // "cat" marks a Clerk session token; the library refuses anything else. + const head = part({ alg: 'RS256', typ: 'JWT', kid: 'ins_test', cat: 'cl_B7d4PD111AAA' }); + const body = part({ sid: 'sess_1', iss: 'https://clerk.glint.test', iat: now, nbf: now - 5, exp: now + 300, ...claims }); + return `${head}.${body}.${createSign('RSA-SHA256').update(`${head}.${body}`).sign(key).toString('base64url')}`; + }; + const good = sign({ sub: USER }); + let openaiCalls = 0, openaiFails = false; + const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); + globalThis.fetch = async (url) => { + const u = String(url); + if (u.startsWith('https://api.openai.com/')) { + openaiCalls++; + if (openaiFails) return json(500, { error: { message: 'upstream broke' } }); + return u.includes('/images/') ? json(200, { data: [{ b64_json: 'AAAA' }] }) : json(200, { choices: [{ message: { content: 'hello' } }] }); + } + throw new Error('network down: ' + u); + }; + const post = (body, token) => shareReq('POST', body, token ? { headers: { authorization: `Bearer ${token}` } } : {}); + try { + assert.deepEqual(CREDIT_COSTS, { text: 1, vision: 1, enhance: 1, agent: 1, image: 5 }); + assert.equal(resetsAt(new Date('2026-12-31T23:59:59Z')), '2027-01-01T00:00:00.000Z'); + + // Not set up: hosted AI works as before, for anyone, uncounted. + process.env.OPENAI_API_KEY = 'sk-test'; + const open = await callRoute(aiTextRoute, post({ prompt: 'hi' })); + assert.equal(open.statusCode, 200); + assert.equal(open.headers['x-glint-credits'], undefined); + assert.deepEqual((await callRoute(accountRouter, shareReq('GET', null, { query: { op: 'me' } }))).body, { enabled: false }); + // Sign-in alone, with nowhere to keep the count, is not enough to meter. + process.env.CLERK_JWT_KEY = publicKey.export({ type: 'spki', format: 'pem' }); + assert.equal((await callRoute(aiTextRoute, post({ prompt: 'hi' }))).statusCode, 200); + + process.env.ACCOUNT_STORE = 'memory'; + process.env.AI_FREE_CREDITS = '3'; + process.env.AI_PRO_CREDITS = '40'; + openaiCalls = 0; + + // No account, an expired session, another signer's token, junk: asked to + // sign in, nothing spent, the model never called. + const bad = [undefined, 'not-a-jwt', sign({ sub: USER, iat: now - 900, nbf: now - 900, exp: now - 600 }), sign({ sub: USER }, stranger.privateKey)]; + for (const token of bad) { + const r = await callRoute(aiTextRoute, post({ prompt: 'hi' }, token)); + assert.equal(r.statusCode, 401); + assert.equal(r.body.code, 'sign_in'); + } + assert.equal(openaiCalls, 0); + assert.equal(usage.size, 0); + // Other methods are the route's own business. + assert.equal((await callRoute(aiTextRoute, shareReq('GET'))).statusCode, 405); + + const one = await callRoute(aiTextRoute, post({ prompt: 'hi' }, good)); + assert.equal(one.statusCode, 200); + assert.equal(one.body.text, 'hello'); + assert.equal(one.headers['x-glint-credits'], '1/3'); + + // A failed call (bad input, or the model erroring) hands the credit back. + assert.equal((await callRoute(aiTextRoute, post({}, good))).statusCode, 400); + assert.equal(usage.get(USER), 1); + openaiFails = true; + assert.equal((await callRoute(aiTextRoute, post({ prompt: 'hi' }, good))).statusCode, 500); + assert.equal(usage.get(USER), 1); + openaiFails = false; + + // An image costs 5, more than the 2 left: refused, with the count. + const img = await callRoute(imageGenerateRoute, post({ prompt: 'a cat' }, good)); + assert.equal(img.statusCode, 402); + assert.equal(img.body.code, 'no_credits'); + assert.match(img.body.error, /needs 5 .* you have 2 left/); + assert.equal(usage.get(USER), 1); + + await callRoute(aiTextRoute, post({ prompt: 'hi' }, good)); + await callRoute(aiTextRoute, post({ prompt: 'hi' }, good)); + const calls = openaiCalls; + const out = await callRoute(aiTextRoute, post({ prompt: 'hi' }, good)); + assert.equal(out.statusCode, 402); + assert.match(out.body.error, /used all 3 hosted AI credits/); + assert.equal(out.body.limit, 3); + assert.ok(out.body.resets.endsWith('T00:00:00.000Z')); + assert.equal(openaiCalls, calls); + // One person's count is their own. + assert.equal((await callRoute(aiTextRoute, post({ prompt: 'hi' }, sign({ sub: 'user_other' })))).headers['x-glint-credits'], '1/3'); + + const me = await callRoute(accountRouter, shareReq('GET', null, { query: { op: 'me' }, headers: { authorization: `Bearer ${good}` } })); + assert.equal(me.body.signedIn, true); + assert.deepEqual([me.body.plan, me.body.used, me.body.limit], ['free', 3, 3]); + assert.equal((await callRoute(accountRouter, shareReq('GET', null, { query: { op: 'me' } }))).body.signedIn, false); + assert.equal((await callRoute(accountRouter, shareReq('GET', null, { query: { op: 'constructor' } }))).statusCode, 404); + + // A Pro subscription raises the limit, so the image goes through. + pro.add(USER); + const paid = await callRoute(imageGenerateRoute, post({ prompt: 'a cat' }, good)); + assert.equal(paid.statusCode, 200); + assert.equal(paid.headers['x-glint-credits'], '8/40'); + + // Clerk's key service unreachable (no local key to fall back on): closed, not free. + delete process.env.CLERK_JWT_KEY; + process.env.CLERK_SECRET_KEY = 'sk_test_unreachable'; + const errors = console.error; + console.error = () => {}; + try { + assert.equal((await callRoute(aiTextRoute, post({ prompt: 'hi' }, good))).statusCode, 503); + } finally { console.error = errors; } + assert.equal(usage.get(USER), 8); + + // No server AI key: the route says 501 without asking anyone to sign in, + // so the editor falls back to the person's own key. + delete process.env.OPENAI_API_KEY; + assert.equal((await callRoute(imageGenerateRoute, post({ prompt: 'a cat' }))).statusCode, 501); + } finally { + globalThis.fetch = realFetch; + usage.clear(); pro.clear(); + for (const k of KEYS) { if (k in saved) process.env[k] = saved[k]; else delete process.env[k]; } + } +} + const tests = [ testFetchUrlRejectsPrivateHostsBeforeFetch, testFetchUrlUsesManualRedirects, testColorMapPersistsInProjects, testFailedProjectImageDecodeClearsPreviousImage, - testGalleryTemplateApplySnapshotsHistory, testCompareMigratesAndPersists, testCompareGeometry, testBrandMigrateCopiesOnce, @@ -1330,7 +1452,8 @@ const tests = [ testShareCoreManifest, testSharePlayersInlineCleanly, testShareRoutesRoundTrip, - testWaitlistRoutes + testWaitlistRoutes, + testHostedAiIsMetered ]; for (const test of tests) { diff --git a/src/features/account.js b/src/features/account.js new file mode 100644 index 0000000..c8ed05d --- /dev/null +++ b/src/features/account.js @@ -0,0 +1,106 @@ +// Glint Pro groundwork: the editor's side of accounts and hosted AI credits. +// Every call to a hosted AI route goes through hostedFetch(), which adds the +// signed-in person's token so the server can count credits. When the server +// says "sign in" or "out of credits" this explains why, and otherwise stays +// out of the way: a person with their own API key never sees any of it. +import { getToken, onAuthChange, isConfigured, openSignIn } from './auth.js'; +import { getKey } from './api-keys.js'; +import { showNotification } from '../ui/notification.js'; +import { track } from './analytics.js'; + +let usage = null; // { used, limit, plan, resets } once known +let lastBlock = null; // { message, at } for the Design Agent's reply + +const token = () => getToken(); + +const hasOwnKey = () => Boolean(getKey('openai') || getKey('anthropic')); + +function resetDay(iso) { + const d = new Date(iso); + if (Number.isNaN(d.getTime())) return ''; + return d.toLocaleDateString(undefined, { day: 'numeric', month: 'long', timeZone: 'UTC' }); +} + +function renderChip() { + const chip = document.getElementById('ai-credits'); + if (!chip) return; + if (!usage) { chip.style.display = 'none'; return; } + const left = Math.max(0, usage.limit - usage.used); + chip.style.display = ''; + chip.textContent = `${left} AI credit${left === 1 ? '' : 's'}`; + const day = usage.resets ? resetDay(usage.resets) : ''; + chip.title = `${left} of ${usage.limit} hosted AI credits left this month${usage.plan === 'pro' ? ' (Glint Pro)' : ''}.${day ? ` They start over on ${day}.` : ''} Your own API key does not use credits.`; +} + +function setUsage(next) { + usage = next; + renderChip(); +} + +let refreshing = null; +export function refreshAccount() { + if (!refreshing) refreshing = loadAccount().finally(() => { refreshing = null; }); + return refreshing; +} + +async function loadAccount() { + const t = await token(); + if (!t) { setUsage(null); return; } + try { + const r = await fetch('/api/account?op=me', { headers: { Authorization: `Bearer ${t}` }, cache: 'no-store' }); + const type = r.headers.get('content-type') || ''; + const data = r.ok && type.includes('json') ? await r.json() : null; + if (data && data.enabled && data.hosted && data.signedIn) setUsage({ used: data.used, limit: data.limit, plan: data.plan, resets: data.resets }); + else setUsage(null); + } catch (e) { + setUsage(null); + } +} + +function explain(data) { + let message = data.error || 'Hosted AI is not available for this account.'; + let action = null; + if (data.code === 'sign_in') { + if (isConfigured()) action = { label: 'Sign in', run: openSignIn }; + } else { + const day = data.resets ? resetDay(data.resets) : ''; + if (day) message = message.replace(' Your own API key', ` They start over on ${day}. Your own API key`); + action = { label: 'Glint Pro', run: () => window.open('/pricing/#pro', '_blank', 'noopener') }; + } + lastBlock = { message, at: Date.now() }; + return { message, action }; +} + +// The reason hosted AI just said no, if it did in the last few seconds. +export function recentMeterBlock() { + return lastBlock && Date.now() - lastBlock.at < 8000 ? lastBlock.message : ''; +} + +// POST to a hosted AI route. Returns the Response. A "sign in" or "out of +// credits" answer comes back as a 501, which every caller already treats as +// "no hosted AI here" and so falls back to the person's own key. +export async function hostedFetch(path, body, { quiet = false } = {}) { + const t = await token(); + const r = await fetch(path, { + method: 'POST', + headers: { 'Content-Type': 'application/json', ...(t ? { Authorization: `Bearer ${t}` } : {}) }, + body: JSON.stringify(body), + }); + const credits = /^(\d+)\/(\d+)$/.exec(r.headers.get('X-Glint-Credits') || ''); + if (credits && r.ok) setUsage({ ...(usage || {}), used: Number(credits[1]), limit: Number(credits[2]) }); + if (r.status !== 401 && r.status !== 402) return r; + const data = await r.clone().json().catch(() => ({})); + if (data.code !== 'sign_in' && data.code !== 'no_credits') return r; + track('ai_blocked', { reason: data.code }); + if (data.code === 'no_credits' && typeof data.used === 'number') setUsage({ ...(usage || {}), used: data.used, limit: data.limit, plan: data.plan, resets: data.resets }); + const { message, action } = explain(data); + // The caller falls back to the person's own key. Without one it shows its + // generic "add a key" message; this lands just after and says why. + if (!quiet && !hasOwnKey()) setTimeout(() => showNotification(message, 'info', { action, duration: 9000 }), 80); + return new Response(JSON.stringify({ error: message }), { status: 501, headers: { 'Content-Type': 'application/json' } }); +} + +export function bindAccount() { + // bindAuth() announces the first sign-in state once Clerk has loaded. + onAuthChange(() => { refreshAccount(); }); +} diff --git a/src/features/ai-agent.js b/src/features/ai-agent.js index 7339de4..37c9e13 100644 --- a/src/features/ai-agent.js +++ b/src/features/ai-agent.js @@ -10,6 +10,7 @@ import { TOOLS, runTool, consumeChips } from './agent-tools.js'; import { loadChat, saveChat, loadMemory } from './agent-memory.js'; import { getPageMeta } from './pages.js'; import { revealSection } from './studio-nav.js'; +import { recentMeterBlock } from './account.js'; const MAX_ITERS = 8; let messages = []; // neutral history @@ -113,7 +114,7 @@ async function send() { } } catch (e) { if (e && e.code === 'NO_KEY') { - addLine('assistant', 'Add an OpenAI or Claude key in AI settings to use the Design Agent.'); + addLine('assistant', recentMeterBlock() || 'Add an OpenAI or Claude key in AI settings to use the Design Agent.'); const d = el('api-keys-details'); if (d) { revealSection(d); d.open = true; d.scrollIntoView({ behavior: 'smooth', block: 'center' }); } } else { console.error(e); diff --git a/src/features/ai-cloud.js b/src/features/ai-cloud.js index b66ddae..9def1a7 100644 --- a/src/features/ai-cloud.js +++ b/src/features/ai-cloud.js @@ -2,6 +2,7 @@ import { state } from '../state/state.js'; import { showNotification } from '../ui/notification.js'; import { getKey } from './api-keys.js'; import { revealSection } from './studio-nav.js'; +import { hostedFetch } from './account.js'; function imageToDataUrl(img) { const c = document.createElement('canvas'); @@ -42,11 +43,7 @@ function promptForKey() { async function tryHostedJson(path, body) { try { - const r = await fetch(path, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(body) - }); + const r = await hostedFetch(path, body); if (r.status === 404 || r.status === 501) return { fellThrough: true }; const data = await r.json().catch(() => ({})); if (!r.ok) throw new Error(data.error || `Backend error ${r.status}`); diff --git a/src/features/ai-enhance.js b/src/features/ai-enhance.js index 5f23a60..29ca1a8 100644 --- a/src/features/ai-enhance.js +++ b/src/features/ai-enhance.js @@ -3,6 +3,7 @@ import { el } from '../ui/elements.js'; import { showNotification } from '../ui/notification.js'; import { render } from '../render/render.js'; import { saveStateToHistory } from '../state/history.js'; +import { hostedFetch } from './account.js'; const STYLE_PRESETS = { watercolor: { brightness: 110, contrast: 90, saturation: 130, blur: 1, grayscale: 0, sepia: 15 }, @@ -54,14 +55,11 @@ function dataUrlToBase64(url) { async function tryHostedEnhance(dataUrl) { try { - const r = await fetch('/api/ai-enhance', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - image: dataUrlToBase64(dataUrl), - mimeType: 'image/jpeg' - }) - }); + // Quiet: without hosted AI this falls back to a local enhance, which works. + const r = await hostedFetch('/api/ai-enhance', { + image: dataUrlToBase64(dataUrl), + mimeType: 'image/jpeg' + }, { quiet: true }); if (r.status === 404 || r.status === 501) return null; const data = await r.json().catch(() => ({})); if (!r.ok) throw new Error(data.error || `Backend error ${r.status}`); diff --git a/src/features/ai-image-edit.js b/src/features/ai-image-edit.js index e5743c5..5f93062 100644 --- a/src/features/ai-image-edit.js +++ b/src/features/ai-image-edit.js @@ -12,6 +12,7 @@ import { showNotification } from '../ui/notification.js'; import { getKey } from './api-keys.js'; import { imageToDataUrl, loadImage, canvasToBlob, blobToBase64, nearestGptImageSize } from './ai-shared.js'; import { revealSection } from './studio-nav.js'; +import { hostedFetch } from './account.js'; function setStatus(msg) { const s = document.getElementById('ai-edit-status'); @@ -27,11 +28,7 @@ function needKeyHint() { async function tryProxy(path, body) { try { - const r = await fetch(path, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(body) - }); + const r = await hostedFetch(path, body); if (r.status === 501 || r.status === 404) return { fell_through: true }; const data = await r.json().catch(() => ({})); if (!r.ok) throw new Error(data.error || `Proxy error ${r.status}`); diff --git a/src/features/auth.js b/src/features/auth.js index 0919466..a16bc56 100644 --- a/src/features/auth.js +++ b/src/features/auth.js @@ -1,271 +1,140 @@ -import { showNotification } from '../ui/notification.js'; -import { askConfirm } from '../ui/dialog.js'; - -const CFG_KEY = 'glint_supabase_cfg'; - -let supabaseClient = null; -let currentUser = null; +// Sign-in, through Clerk. Glint works without an account; signing in is how +// the hosted AI counts its free monthly credits (see features/account.js). +// +// Clerk's browser bundles are loaded from the Clerk instance itself (its +// "Frontend API", whose host is encoded in the publishable key), so nothing +// is added to Glint's own build and a copy of Glint without a key loads +// nothing and shows no sign-in at all. + +const PUBLISHABLE_KEY = (import.meta.env + && (import.meta.env.VITE_CLERK_PUBLISHABLE_KEY || import.meta.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY)) || ''; + +let clerk = null; +let loading = null; +let failed = false; +let currentUserId = null; const listeners = []; export function onAuthChange(fn) { listeners.push(fn); } -function emit() { listeners.forEach(fn => fn(currentUser)); } - -function loadLocalConfig() { - try { return JSON.parse(localStorage.getItem(CFG_KEY)) || null; } - catch (e) { return null; } -} -function saveLocalConfig(cfg) { - try { localStorage.setItem(CFG_KEY, JSON.stringify(cfg)); } - catch (e) {} -} -function clearLocalConfig() { - try { localStorage.removeItem(CFG_KEY); } - catch (e) {} -} - -function getConfig() { - const local = loadLocalConfig(); - if (local && local.url && local.anonKey) return local; - const envUrl = import.meta.env.VITE_SUPABASE_URL; - const envKey = import.meta.env.VITE_SUPABASE_ANON_KEY; - if (envUrl && envKey) return { url: envUrl, anonKey: envKey, source: 'env' }; - return null; +function emit() { listeners.forEach((fn) => { try { fn(getUser()); } catch (e) { console.error(e); } }); } + +// The Frontend API host: the key is pk__. +export function frontendApiHost(key) { + const m = /^pk_(?:test|live)_([A-Za-z0-9+/=_-]+)$/.exec(String(key || '')); + if (!m) return ''; + try { + const host = atob(m[1].replace(/-/g, '+').replace(/_/g, '/')).replace(/\$$/, ''); + return /^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/i.test(host) && host.includes('.') ? host : ''; + } catch (e) { + return ''; + } } export function isConfigured() { - return Boolean(getConfig()); + return Boolean(frontendApiHost(PUBLISHABLE_KEY)); +} + +export function getUser() { + const u = clerk && clerk.user; + if (!u) return null; + const email = (u.primaryEmailAddress && u.primaryEmailAddress.emailAddress) || ''; + return { id: u.id, email, name: u.fullName || u.username || email || 'You' }; +} + +function addScript(src, attrs = {}) { + return new Promise((resolve, reject) => { + const s = document.createElement('script'); + s.src = src; + s.async = true; + s.crossOrigin = 'anonymous'; + Object.entries(attrs).forEach(([k, v]) => s.setAttribute(k, v)); + s.onload = resolve; + s.onerror = () => { s.remove(); reject(new Error('Could not load ' + src)); }; + document.head.appendChild(s); + }); } -export function getUser() { return currentUser; } - -export async function getClient() { - if (supabaseClient) return supabaseClient; - const cfg = getConfig(); - if (!cfg) return null; - const { createClient } = await import('@supabase/supabase-js'); - supabaseClient = createClient( - cfg.url, - cfg.anonKey, - { auth: { persistSession: true, autoRefreshToken: true } } - ); - const { data: { session } } = await supabaseClient.auth.getSession(); - currentUser = session?.user || null; - supabaseClient.auth.onAuthStateChange((_event, sess) => { - currentUser = sess?.user || null; +async function loadClerk() { + const host = frontendApiHost(PUBLISHABLE_KEY); + // The UI bundle first, then the SDK, which finds its key on its own tag. + await addScript(`https://${host}/npm/@clerk/ui@1/dist/ui.browser.js`); + await addScript(`https://${host}/npm/@clerk/clerk-js@6/dist/clerk.browser.js`, { 'data-clerk-publishable-key': PUBLISHABLE_KEY }); + const instance = window.Clerk; + if (!instance) throw new Error('Clerk did not start'); + await instance.load({ ui: { ClerkUI: window.__internal_ClerkUICtor } }); + clerk = instance; + currentUserId = clerk.user ? clerk.user.id : null; + // Clerk calls this on every refresh of the session; only a change of person matters here. + clerk.addListener(({ user }) => { + const id = user ? user.id : null; + if (id === currentUserId) return; + currentUserId = id; renderAuthPill(); emit(); }); - return supabaseClient; -} - -function openModal() { - const m = document.getElementById('auth-modal'); - if (m) m.classList.add('visible'); -} -function closeModal() { - const m = document.getElementById('auth-modal'); - if (m) m.classList.remove('visible'); -} - -function openSetupModal() { - const m = document.getElementById('cloud-setup-modal'); - if (m) { - m.classList.add('visible'); - const cfg = loadLocalConfig(); - const urlInp = document.getElementById('cloud-setup-url'); - const keyInp = document.getElementById('cloud-setup-key'); - if (urlInp && cfg) urlInp.value = cfg.url || ''; - if (keyInp && cfg) keyInp.value = cfg.anonKey || ''; + return clerk; +} + +// Resolves to the Clerk instance, or null when sign-in is not set up or could +// not load (offline, blocked). A later call tries again. +export function ready() { + if (!isConfigured()) return Promise.resolve(null); + if (clerk) return Promise.resolve(clerk); + if (!loading) { + loading = loadClerk() + .then((c) => { failed = false; return c; }) + .catch((e) => { failed = true; console.warn('[auth]', e.message); return null; }) + .finally(() => { loading = null; }); } + return loading; } -function closeSetupModal() { - const m = document.getElementById('cloud-setup-modal'); - if (m) m.classList.remove('visible'); + +// The signed-in person's session token for our own API, or '' when signed out. +export async function getToken() { + const c = await ready(); + if (!c || !c.session) return ''; + try { return (await c.session.getToken()) || ''; } catch (e) { return ''; } } -async function saveCloudConfig() { - const url = document.getElementById('cloud-setup-url').value.trim(); - const anonKey = document.getElementById('cloud-setup-key').value.trim(); - if (!url || !anonKey) { showNotification('Both URL and anon key are required.', 'error'); return; } - if (!url.startsWith('https://') || !url.includes('.supabase.co')) { - showNotification('URL should look like https://xxx.supabase.co', 'error'); +export async function openSignIn() { + const c = await ready(); + if (!c) { + const { showNotification } = await import('../ui/notification.js'); + showNotification('Sign-in could not load. Check your connection and try again.', 'error'); + renderAuthPill(); return; } - saveLocalConfig({ url, anonKey }); - supabaseClient = null; - currentUser = null; - await getClient(); - renderAuthPill(); - closeSetupModal(); - showNotification('Cloud configured. You can now sign in.', 'success'); - openModal(); -} - -async function disconnectCloud() { - if (!await askConfirm('Disconnect cloud sync?', { message: 'Your local data stays, but sync will stop.', okLabel: 'Disconnect', danger: true })) return; - clearLocalConfig(); - supabaseClient = null; - currentUser = null; - renderAuthPill(); - closeSetupModal(); - showNotification('Cloud disconnected.', 'success'); -} - -async function signUp() { - const c = await getClient(); - if (!c) return; - const email = document.getElementById('auth-email').value.trim(); - const password = document.getElementById('auth-password').value; - if (!email || !password) { showNotification('Enter email and password.', 'error'); return; } - const { error } = await c.auth.signUp({ email, password }); - if (error) showNotification(error.message, 'error'); - else { showNotification('Check your email to confirm your account.', 'success'); closeModal(); } -} - -async function signIn() { - const c = await getClient(); - if (!c) return; - const email = document.getElementById('auth-email').value.trim(); - const password = document.getElementById('auth-password').value; - if (!email || !password) { showNotification('Enter email and password.', 'error'); return; } - const { error } = await c.auth.signInWithPassword({ email, password }); - if (error) showNotification(error.message, 'error'); - else { showNotification('Signed in.', 'success'); closeModal(); } -} - -async function signInWithProvider(provider) { - const c = await getClient(); - if (!c) return; - const { error } = await c.auth.signInWithOAuth({ provider, options: { redirectTo: window.location.origin } }); - if (error) showNotification(error.message, 'error'); -} - -async function signOut() { - const c = await getClient(); - if (!c) return; - await c.auth.signOut(); - showNotification('Signed out.', 'success'); + if (c.user) return; + c.openSignIn(); } function renderAuthPill() { const pill = document.getElementById('auth-pill'); if (!pill) return; - if (!isConfigured()) { - pill.innerHTML = ''; - document.getElementById('cloud-setup-btn').addEventListener('click', openSetupModal); + if (!isConfigured()) { pill.replaceChildren(); return; } + if (clerk && clerk.user) { + // Clerk's own account button: avatar, manage account, sign out. + const holder = document.createElement('span'); + holder.id = 'auth-user-button'; + holder.style.display = 'inline-flex'; + pill.replaceChildren(holder); + clerk.mountUserButton(holder); return; } - if (currentUser) { - const name = currentUser.email || currentUser.user_metadata?.full_name || 'You'; - pill.innerHTML = ` - - - `; - document.getElementById('auth-signout-btn').addEventListener('click', signOut); - } else { - pill.innerHTML = ` - - - `; - document.getElementById('auth-signin-btn').addEventListener('click', openModal); - document.getElementById('cloud-reconfigure-btn').addEventListener('click', openSetupModal); - } + const btn = document.createElement('button'); + btn.type = 'button'; + btn.className = 'btn btn-secondary'; + btn.id = 'auth-signin-btn'; + btn.title = failed ? 'Sign-in could not load. Click to try again.' : 'Sign in for free hosted AI credits'; + btn.textContent = 'Sign in'; + btn.addEventListener('click', openSignIn); + pill.replaceChildren(btn); } export async function bindAuth() { - // Auth modal buttons - const signUpBtn = document.getElementById('auth-signup-btn'); - const signInBtn = document.getElementById('auth-signin-modal-btn'); - const googleBtn = document.getElementById('auth-google-btn'); - const githubBtn = document.getElementById('auth-github-btn'); - const closeBtn = document.getElementById('auth-modal-close'); - const overlay = document.getElementById('auth-modal'); - if (signUpBtn) signUpBtn.addEventListener('click', signUp); - if (signInBtn) signInBtn.addEventListener('click', signIn); - if (googleBtn) googleBtn.addEventListener('click', () => signInWithProvider('google')); - if (githubBtn) githubBtn.addEventListener('click', () => signInWithProvider('github')); - if (closeBtn) closeBtn.addEventListener('click', closeModal); - if (overlay) overlay.addEventListener('click', (e) => { if (e.target === overlay) closeModal(); }); - - // Cloud-setup modal buttons - const setupSaveBtn = document.getElementById('cloud-setup-save-btn'); - const setupCloseBtn = document.getElementById('cloud-setup-close'); - const setupDisconnectBtn = document.getElementById('cloud-setup-disconnect-btn'); - const setupOverlay = document.getElementById('cloud-setup-modal'); - const setupCopySqlBtn = document.getElementById('cloud-setup-copy-sql'); - if (setupSaveBtn) setupSaveBtn.addEventListener('click', saveCloudConfig); - if (setupCloseBtn) setupCloseBtn.addEventListener('click', closeSetupModal); - if (setupDisconnectBtn) setupDisconnectBtn.addEventListener('click', disconnectCloud); - if (setupOverlay) setupOverlay.addEventListener('click', (e) => { if (e.target === setupOverlay) closeSetupModal(); }); - if (setupCopySqlBtn) setupCopySqlBtn.addEventListener('click', async () => { - const sql = `create table if not exists public.templates ( - user_id uuid not null references auth.users(id) on delete cascade, - name text not null, - payload jsonb not null, - updated_at timestamptz default now(), - primary key (user_id, name) -); -alter table public.templates enable row level security; -create policy "users own templates" on public.templates - for all using (auth.uid() = user_id) with check (auth.uid() = user_id); - -create table if not exists public.projects ( - id uuid primary key default gen_random_uuid(), - user_id uuid not null references auth.users(id) on delete cascade, - name text not null, - payload jsonb not null, - updated_at timestamptz default now() -); --- v12 — projects are keyed by id (not name); carry a thumbnail + created_at. -alter table public.projects add column if not exists thumbnail text; -alter table public.projects add column if not exists created_at timestamptz default now(); -alter table public.projects drop constraint if exists projects_user_id_name_key; -alter table public.projects enable row level security; -create policy "users own projects" on public.projects - for all using (auth.uid() = user_id) with check (auth.uid() = user_id); - --- v12 — version history snapshots for each project. -create table if not exists public.project_versions ( - id uuid primary key default gen_random_uuid(), - project_id uuid not null references public.projects(id) on delete cascade, - user_id uuid not null references auth.users(id) on delete cascade, - label text, - payload jsonb not null, - thumbnail text, - created_at timestamptz default now() -); -alter table public.project_versions enable row level security; -create policy "users own project versions" on public.project_versions - for all using (auth.uid() = user_id) with check (auth.uid() = user_id); - --- v11.3 — public community gallery (templates + brand kits) -create table if not exists public.gallery ( - id uuid primary key default gen_random_uuid(), - author_id uuid not null references auth.users(id) on delete cascade, - kind text not null check (kind in ('template','brandkit')), - name text not null, - payload jsonb not null, - preview_url text, - likes int default 0, - created_at timestamptz default now() -); -alter table public.gallery enable row level security; -create policy "gallery is publicly readable" on public.gallery - for select using (true); -create policy "authors insert their gallery items" on public.gallery - for insert with check (auth.uid() = author_id); -create policy "authors delete their gallery items" on public.gallery - for delete using (auth.uid() = author_id);`; - try { - await navigator.clipboard.writeText(sql); - showNotification('SQL copied — paste into Supabase SQL Editor.', 'success'); - } catch (e) { - showNotification('Copy failed — see DEPLOY.md for the SQL.', 'error'); - } - }); - - if (isConfigured()) { - await getClient(); - } renderAuthPill(); + if (!isConfigured()) return; + await ready(); + renderAuthPill(); + emit(); } diff --git a/src/features/campaigns.js b/src/features/campaigns.js index 705916d..12eb4c5 100644 --- a/src/features/campaigns.js +++ b/src/features/campaigns.js @@ -5,7 +5,6 @@ import { showNotification } from '../ui/notification.js'; import { askConfirm } from '../ui/dialog.js'; -import { getClient, getUser } from './auth.js'; const KEY = 'glint_campaigns_v1'; @@ -97,102 +96,6 @@ async function downloadCampaign(id) { await downloadZip(files, `${(record.name || 'campaign').replace(/\s+/g, '-').toLowerCase()}-${Date.now()}.zip`); } -// --------------------------------------------------------------------------- -// v30 — Optional Supabase mirror (additive, inert when unconfigured / signed out) -// Mirrors gallery.js's client/user accessor + guard pattern against a `campaigns` -// table: { user_id, name, config, preview_url, created_at }. -// localStorage is always the offline source of truth; these are purely additive. -// --------------------------------------------------------------------------- - -const CAMPAIGNS_BUCKET = 'campaigns'; - -async function ensureCampaignsBucket(client) { - const { data } = await client.storage.getBucket(CAMPAIGNS_BUCKET); - if (!data) { - await client.storage.createBucket(CAMPAIGNS_BUCKET, { public: true, fileSizeLimit: 5242880 }); - } -} - -/** - * Publish a saved campaign to the Supabase `campaigns` table. - * Uploads the hero thumbnail (first thumb) to Storage; inserts a row with - * { user_id, name, config: record, preview_url }. - * Silently returns if Supabase is not configured or the user is not signed in. - */ -export async function publishCampaign(id) { - const client = await getClient(); - const user = getUser(); - if (!client || !user) return; // inert — no notification, just skip - - const record = getCampaign(id); - if (!record) return; - - try { - await ensureCampaignsBucket(client); - - // Upload hero thumbnail if present - let preview_url = null; - const heroThumb = (record.thumbs || [])[0]; - if (heroThumb?.dataUrl) { - // Convert data URL → Blob for upload - const res = await fetch(heroThumb.dataUrl); - const blob = await res.blob(); - const path = `${user.id}/${record.id}.png`; - const { error: upErr } = await client.storage - .from(CAMPAIGNS_BUCKET) - .upload(path, blob, { contentType: 'image/png', upsert: true }); - if (!upErr) { - const { data: urlData } = client.storage.from(CAMPAIGNS_BUCKET).getPublicUrl(path); - preview_url = urlData?.publicUrl || null; - } - } - - const { error: insErr } = await client.from('campaigns').insert({ - user_id: user.id, - name: record.name || 'Campaign', - config: record, - preview_url - }); - if (insErr) throw insErr; - } catch (e) { - // Additive mirror — log but don't surface errors to avoid spam on offline/unconfigured - console.warn('[campaigns] Supabase publish skipped:', e?.message || e); - } -} - -/** - * Pull campaigns owned by the signed-in user from Supabase and merge them - * into the local store (via saveCampaign). Remote rows supplement but do not - * overwrite local edits — local record wins if both have the same id. - * Silently returns if Supabase is not configured or the user is not signed in. - */ -export async function pullCampaigns() { - const client = await getClient(); - const user = getUser(); - if (!client || !user) return; // inert — no notification, just skip - - try { - const { data, error } = await client - .from('campaigns') - .select('id, name, config, preview_url, created_at') - .eq('user_id', user.id) - .order('created_at', { ascending: false }); - if (error) throw error; - - const local = loadCampaigns(); - for (const row of data || []) { - // `config` holds the full campaign record; fall back to a minimal stub - const remote = row.config || { id: row.id, name: row.name, createdAt: Date.parse(row.created_at) }; - // Prefer local record — it may have been edited since the last publish - if (!local[remote.id]) { - saveCampaign(remote); - } - } - } catch (e) { - console.warn('[campaigns] Supabase pull skipped:', e?.message || e); - } -} - function escapeHtml(s) { return String(s == null ? '' : s) .replace(/&/g, '&') diff --git a/src/features/cloud-sync.js b/src/features/cloud-sync.js deleted file mode 100644 index 7057ce3..0000000 --- a/src/features/cloud-sync.js +++ /dev/null @@ -1,60 +0,0 @@ -// Template cloud sync. (v12: full project sync + version history moved to -// features/projects.js, which owns the `projects`/`project_versions` tables.) -import { showNotification } from '../ui/notification.js'; -import { getClient, getUser, onAuthChange } from './auth.js'; - -const TEMPLATES_KEY = 'glint_templates'; - -function loadLocalTemplates() { - try { return JSON.parse(localStorage.getItem(TEMPLATES_KEY)) || {}; } - catch (e) { return {}; } -} -function saveLocalTemplates(obj) { - try { localStorage.setItem(TEMPLATES_KEY, JSON.stringify(obj)); } - catch (e) {} -} - -export async function pushTemplates() { - const user = getUser(); - const c = await getClient(); - if (!user || !c) return; - const all = loadLocalTemplates(); - const names = Object.keys(all); - if (names.length === 0) return; - const rows = names.map(name => ({ - user_id: user.id, - name, - payload: all[name], - updated_at: new Date().toISOString() - })); - const { error } = await c.from('templates').upsert(rows, { onConflict: 'user_id,name' }); - if (error) console.warn('template sync push failed', error); -} - -export async function pullTemplates() { - const user = getUser(); - const c = await getClient(); - if (!user || !c) return; - const { data, error } = await c.from('templates').select('name, payload').eq('user_id', user.id); - if (error) { console.warn('template sync pull failed', error); return; } - const local = loadLocalTemplates(); - let added = 0; - data.forEach(row => { - if (!local[row.name]) { local[row.name] = row.payload; added++; } - }); - if (added > 0) { - saveLocalTemplates(local); - showNotification(`Synced ${added} template${added === 1 ? '' : 's'} from cloud.`, 'success'); - if (typeof window.__refreshTemplateList === 'function') window.__refreshTemplateList(); - } -} - -async function syncOnSignIn(user) { - if (!user) return; - await pullTemplates(); - await pushTemplates(); -} - -export function bindCloudSync() { - onAuthChange(syncOnSignIn); -} diff --git a/src/features/collab.js b/src/features/collab.js deleted file mode 100644 index 844f9b7..0000000 --- a/src/features/collab.js +++ /dev/null @@ -1,207 +0,0 @@ -// v11.4 — Live collaboration over Supabase Realtime. -// -// A session is an id carried in a ?collab= link. Everyone who joins -// subscribes to the channel `project:` and shares: -// - presence + live cursors (rendered as fixed overlay divs above the canvas, -// never on it, so they never enter exports), and -// - design state: on each local commit we broadcast snapshotProject() (the -// shared serializer); on receive we Object.assign + render + refresh UI. -// -// Sync is last-write-wins (documented; no CRDT). We broadcast only on commits — -// saveStateToHistory() fires onHistoryChange, our broadcast trigger — and we -// suppress re-broadcast while applying a remote update, so there's no echo and -// remote updates never pollute local undo history (they don't call -// saveStateToHistory at all). - -import { state } from '../state/state.js'; -import { el } from '../ui/elements.js'; -import { render } from '../render/render.js'; -import { showNotification } from '../ui/notification.js'; -import { getClient, getUser } from './auth.js'; -import { snapshotProject } from '../state/serialize.js'; -import { onHistoryChange } from '../state/history.js'; - -let channel = null; -let applyingRemote = false; -let selfKey = null; -let sessionId = null; -let lastStateSend = 0; -let lastCursorSend = 0; -const cursors = {}; // key -> { name, color, xFrac, yFrac } - -const PALETTE = ['#ff3b30', '#34c759', '#007aff', '#ff9500', '#af52de', '#ff2d55', '#5ac8fa']; -const me = { - name: 'Guest ' + Math.floor(Math.random() * 900 + 100), - color: PALETTE[Math.floor(Math.random() * PALETTE.length)] -}; - -function rand() { - return (crypto.randomUUID ? crypto.randomUUID() : String(Math.random()).slice(2)) ; -} - -// ---- cursor overlay ------------------------------------------------------- - -let overlay = null; -function ensureOverlay() { - if (overlay) return overlay; - overlay = document.createElement('div'); - overlay.id = 'collab-cursors'; - overlay.style.cssText = 'position:fixed;inset:0;pointer-events:none;z-index:9000;'; - document.body.appendChild(overlay); - return overlay; -} - -function renderCursors() { - const box = ensureOverlay(); - const canvas = el.previewCanvas; - if (!canvas) return; - const rect = canvas.getBoundingClientRect(); - box.innerHTML = Object.entries(cursors).map(([key, c]) => { - if (key === selfKey) return ''; - const x = rect.left + (c.xFrac || 0) * rect.width; - const y = rect.top + (c.yFrac || 0) * rect.height; - return `
- - ${escape(c.name || 'Guest')} -
`; - }).join(''); -} - -function escape(s) { const d = document.createElement('div'); d.textContent = String(s); return d.innerHTML; } - -function clearCursors() { - if (overlay) overlay.innerHTML = ''; -} - -// ---- state sync ----------------------------------------------------------- - -function applyRemoteState(payload) { - applyingRemote = true; - try { - // v40 — pins are per-page project data and never travel in collab - // updates; a peer's payload is not trusted to set them. - const next = { ...(payload || {}) }; - delete next.versions; - Object.assign(state, next); - render(); - if (typeof window.__updateUIFromState === 'function') window.__updateUIFromState(); - } finally { - applyingRemote = false; - } -} - -function broadcastState() { - if (!channel || applyingRemote) return; - const now = Date.now(); - if (now - lastStateSend < 100) return; // ~10/s cap - lastStateSend = now; - channel.send({ type: 'broadcast', event: 'state', payload: snapshotProject() }); -} - -function onPointerMove(e) { - if (!channel) return; - const canvas = el.previewCanvas; - if (!canvas) return; - const now = Date.now(); - if (now - lastCursorSend < 50) return; // ~20/s - lastCursorSend = now; - const rect = canvas.getBoundingClientRect(); - const xFrac = (e.clientX - rect.left) / rect.width; - const yFrac = (e.clientY - rect.top) / rect.height; - channel.send({ type: 'broadcast', event: 'cursor', payload: { key: selfKey, name: me.name, color: me.color, xFrac, yFrac } }); -} - -// ---- session lifecycle ---------------------------------------------------- - -export async function joinSession(id) { - const client = await getClient(); - if (!client) { showNotification('Connect Supabase to collaborate.', 'error'); return false; } - - if (channel) await leaveSession(); - sessionId = id; - selfKey = rand(); - const user = getUser(); - if (user?.email) me.name = user.email.split('@')[0]; - - channel = client.channel(`project:${id}`, { config: { presence: { key: selfKey } } }); - - channel - .on('broadcast', { event: 'state' }, ({ payload }) => applyRemoteState(payload)) - .on('broadcast', { event: 'cursor' }, ({ payload }) => { - if (!payload || payload.key === selfKey) return; - cursors[payload.key] = payload; - renderCursors(); - }) - .on('presence', { event: 'sync' }, () => { - const stateP = channel.presenceState(); - const live = new Set(Object.keys(stateP)); - for (const k of Object.keys(cursors)) if (!live.has(k)) delete cursors[k]; - renderCursors(); - }) - .subscribe((status) => { - if (status === 'SUBSCRIBED') { - channel.track({ name: me.name, color: me.color }); - broadcastState(); // share current design with whoever's already here - } - }); - - document.addEventListener('pointermove', onPointerMove, true); - updateCollabUI(true); - showNotification('Live session started. Share the link to collaborate.', 'success'); - return true; -} - -export async function leaveSession() { - document.removeEventListener('pointermove', onPointerMove, true); - if (channel) { try { await channel.unsubscribe(); } catch (_) {} channel = null; } - sessionId = null; - for (const k of Object.keys(cursors)) delete cursors[k]; - clearCursors(); - updateCollabUI(false); -} - -function shareLink() { - const url = new URL(window.location.href); - url.searchParams.set('collab', sessionId); - return url.toString(); -} - -function updateCollabUI(active) { - const start = document.getElementById('collab-start-btn'); - const linkBox = document.getElementById('collab-link-box'); - const linkInput = document.getElementById('collab-link'); - const status = document.getElementById('collab-status'); - if (start) start.textContent = active ? '⏹ Leave session' : '👥 Start live session'; - if (linkBox) linkBox.style.display = active ? 'block' : 'none'; - if (active && linkInput) linkInput.value = shareLink(); - if (status) status.textContent = active ? 'Live. Others can join via the link.' : ''; -} - -// ---- bind ----------------------------------------------------------------- - -export function bindCollab() { - // Broadcast on every local commit (saveStateToHistory → onHistoryChange). - onHistoryChange(() => broadcastState()); - - const startBtn = document.getElementById('collab-start-btn'); - if (startBtn) startBtn.addEventListener('click', () => { - if (channel) leaveSession(); - else joinSession(rand()); - }); - - const copyBtn = document.getElementById('collab-copy-btn'); - if (copyBtn) copyBtn.addEventListener('click', async () => { - const input = document.getElementById('collab-link'); - if (input && input.value) { - try { await navigator.clipboard.writeText(input.value); showNotification('Collaboration link copied.', 'success'); } catch (_) {} - } - }); - - // Reposition cursors when the canvas moves (zoom/pan/scroll/resize). - window.addEventListener('scroll', renderCursors, true); - window.addEventListener('resize', renderCursors); - - // Auto-join from a ?collab= link. - const id = new URLSearchParams(window.location.search).get('collab'); - if (id) joinSession(id); -} diff --git a/src/features/gallery.js b/src/features/gallery.js deleted file mode 100644 index 7bf27dc..0000000 --- a/src/features/gallery.js +++ /dev/null @@ -1,169 +0,0 @@ -// v11.3 — Community template & Brand Kit gallery. -// -// Publish the current design (or Brand Kit) to a public Supabase `gallery` -// table with a rendered thumbnail in Storage; browse everyone's submissions and -// apply one in a click. Built entirely on the existing cloud layer: -// - serialize.js snapshotProject() for template payloads -// - brand-kit.js captureKitObject()/applyKitObject() for brand-kit payloads -// - share.js-style Storage upload for thumbnails -// - the loadProject() apply path (Object.assign → render → __updateUIFromState) -// -// Public read is open (RLS: select using true); insert/delete are restricted to -// the author (auth.uid() = author_id), so signed-out users can browse but not -// publish — enforced in the DB and gated in the UI. - -import { state } from '../state/state.js'; -import { el } from '../ui/elements.js'; -import { render } from '../render/render.js'; -import { showNotification } from '../ui/notification.js'; -import { saveStateToHistory } from '../state/history.js'; -import { getClient, getUser } from './auth.js'; -import { snapshotProject } from '../state/serialize.js'; -import { applyKitObject, captureKitObject } from './brand-kit.js'; -import { escapeHTML } from '../utils/dom.js'; -import { revealSection } from './studio-nav.js'; -import { normalizeColorTools } from '../render/curves-core.js'; -import { normalizeModeFlip } from '../render/mode-flip-core.js'; - -const GALLERY_BUCKET = 'gallery'; - -async function ensureBucket(client) { - const { data } = await client.storage.getBucket(GALLERY_BUCKET); - if (!data) { - await client.storage.createBucket(GALLERY_BUCKET, { public: true, fileSizeLimit: 5242880 }); - } -} - -function thumbnailBlob() { - // Reuse the export render so the thumbnail matches what ships. - render(true); - return new Promise((resolve) => el.previewCanvas.toBlob((blob) => { render(); resolve(blob); }, 'image/png')); -} - -// ---- publish -------------------------------------------------------------- - -async function publish(kind) { - const client = await getClient(); - const user = getUser(); - if (!client || !user) { showNotification('Sign in to publish to the gallery.', 'error'); return; } - - const nameInput = document.getElementById('gallery-name'); - const name = (nameInput?.value || '').trim(); - if (!name) { showNotification('Name your submission first.', 'error'); return; } - if (kind === 'template' && !state.image) { showNotification('Load a screenshot first.', 'error'); return; } - - setGalleryStatus('Publishing…'); - try { - await ensureBucket(client); - const blob = await thumbnailBlob(); - const path = `${user.id}/${Date.now()}.png`; - const { error: upErr } = await client.storage - .from(GALLERY_BUCKET) - .upload(path, blob, { contentType: 'image/png', upsert: true }); - if (upErr) throw upErr; - const { data: urlData } = client.storage.from(GALLERY_BUCKET).getPublicUrl(path); - - const payload = kind === 'brandkit' ? captureKitObject() : snapshotProject(); - const { error: insErr } = await client.from('gallery').insert({ - author_id: user.id, - kind, - name, - payload, - preview_url: urlData.publicUrl - }); - if (insErr) throw insErr; - - if (nameInput) nameInput.value = ''; - setGalleryStatus('Published!'); - showNotification('Published to the community gallery.', 'success'); - await browse(); - } catch (e) { - console.error(e); - setGalleryStatus('Failed.'); - showNotification('Publish failed: ' + (e.message || e), 'error'); - } -} - -// ---- browse + apply ------------------------------------------------------- - -let lastItems = []; - -async function browse() { - const client = await getClient(); - const listEl = document.getElementById('gallery-list'); - if (!listEl) return; - if (!client) { listEl.innerHTML = '

Connect Supabase to browse the gallery.

'; return; } - - setGalleryStatus('Loading…'); - const search = (document.getElementById('gallery-search')?.value || '').trim(); - let query = client.from('gallery').select('id, kind, name, preview_url, author_id, created_at') - .order('created_at', { ascending: false }).limit(60); - if (search) query = query.ilike('name', `%${search}%`); - const { data, error } = await query; - if (error) { setGalleryStatus('Failed.'); listEl.innerHTML = `

${escapeHTML(error.message)}

`; return; } - - lastItems = data || []; - setGalleryStatus(''); - if (!lastItems.length) { listEl.innerHTML = '

Nothing published yet. Be the first!

'; return; } - - listEl.innerHTML = lastItems.map((it) => ` - `).join(''); - - listEl.querySelectorAll('.gallery-card').forEach((card) => { - card.addEventListener('click', () => applyItem(card.dataset.id)); - }); -} - -async function applyItem(id) { - const client = await getClient(); - if (!client) return; - const meta = lastItems.find((x) => String(x.id) === String(id)); - const { data, error } = await client.from('gallery').select('kind, payload').eq('id', id).single(); - if (error) { showNotification('Could not load that item.', 'error'); return; } - - if ((data.kind || meta?.kind) === 'brandkit') { - applyKitObject(data.payload); - } else { - saveStateToHistory(); - // v40 — pins are per-page project data and never travel in a gallery - // item; a row carrying them is not trusted to set them. - const payload = { ...(data.payload || {}) }; - delete payload.versions; - Object.assign(state, payload); - state.colorTools = normalizeColorTools(data.payload && data.payload.colorTools); // v38: older items carry no curves - state.modeFlip = normalizeModeFlip(data.payload && data.payload.modeFlip); // v39: or no flip - render(); - if (typeof window.__updateUIFromState === 'function') window.__updateUIFromState(); - } - showNotification(`Applied "${meta?.name || 'item'}". Undo if needed.`, 'success'); -} - -function setGalleryStatus(msg) { - const s = document.getElementById('gallery-status'); - if (s) s.textContent = msg || ''; -} - -// ---- bind ----------------------------------------------------------------- - -export function openGalleryBrowse() { - const panel = document.getElementById('gallery-panel'); - if (panel) { - revealSection(panel); // v35 — switches to the Project tab, even in Simple mode - panel.scrollIntoView({ behavior: 'smooth', block: 'center' }); - } - browse(); -} - -export function bindGallery() { - document.getElementById('gallery-publish-template')?.addEventListener('click', () => publish('template')); - document.getElementById('gallery-publish-brandkit')?.addEventListener('click', () => publish('brandkit')); - document.getElementById('gallery-browse-btn')?.addEventListener('click', browse); - const search = document.getElementById('gallery-search'); - if (search) search.addEventListener('input', () => { clearTimeout(search._t); search._t = setTimeout(browse, 300); }); -} diff --git a/src/features/palette.js b/src/features/palette.js index 543e9d7..482c950 100644 --- a/src/features/palette.js +++ b/src/features/palette.js @@ -32,7 +32,6 @@ import { addPage, pageCount } from './pages.js'; import { toggleBoardMode, enterBoardMode } from './board.js'; import { setGroup, revealSection } from './studio-nav.js'; import { seedFromUrl } from './seed.js'; -import { openGalleryBrowse } from './gallery.js'; import { exportVideoMp4, exportVideoGif } from './video-export.js'; import { resetOnboarding } from './welcome.js'; import { canInstallApp, installApp } from './install-app.js'; @@ -299,9 +298,6 @@ export function registerCommands() { { id: 'video-play', label: 'Video: Play/Pause clip', icon: '🎬', run: togglePlay }, { id: 'video-mp4', label: 'Video: Export MP4', icon: '⬇', run: exportVideoMp4 }, { id: 'video-gif', label: 'Video: Export GIF', icon: '⬇', run: exportVideoGif }, - { id: 'gallery-browse', label: 'Browse community gallery', icon: '🌐', run: openGalleryBrowse }, - { id: 'gallery-publish', label: 'Publish design to gallery', icon: '⬆', run: () => document.getElementById('gallery-publish-template')?.click() }, - { id: 'collab-start', label: 'Live collaboration: Start/leave session', icon: '👥', run: () => document.getElementById('collab-start-btn')?.click() }, { id: 'reset-onboarding', label: 'Reset onboarding tour', icon: '🧭', run: () => { resetOnboarding(); showStatus('Onboarding reset'); } }, { id: 'brand-brain-apply', label: 'Apply Brand', icon: '🎨', run: () => import('./brand-brain.js').then(m => m.applyBrand()), when: () => !!state.brand?.enabled }, // v33 — Aperture QoL diff --git a/src/features/projects.js b/src/features/projects.js index 7548dd1..6e44035 100644 --- a/src/features/projects.js +++ b/src/features/projects.js @@ -2,7 +2,7 @@ // // Turns the editor from a single ephemeral canvas into a project workspace: // • Local-first store so "never lose a design" works offline and without a -// Supabase account; cloud sync layers on when signed in. v34: projects live +// an account. v34: projects live // in IndexedDB (src/state/project-db.js) because a large photo plus its // versions overflows phone localStorage; the whole store is kept in memory // (`cache`) so call sites stay synchronous. On every healthy load, any @@ -18,7 +18,7 @@ // // v13: a project's `payload` is now a *document* (multiple pages). Serialization // is delegated to pages.js (serializeDocument / applyDocument); this module owns -// persistence, the dashboard, version history, and cloud sync. +// persistence, the dashboard and version history. import { state } from '../state/state.js'; import { showNotification } from '../ui/notification.js'; @@ -27,7 +27,6 @@ import { escapeHTML } from '../utils/dom.js'; import { onHistoryChange } from '../state/history.js'; import { makeThumb, uid } from './document.js'; import { serializeDocument, applyDocument, onDocumentChange, pageCount } from './pages.js'; -import { getClient, getUser, onAuthChange } from './auth.js'; import { idbAvailable, idbGet, idbUpdate, idbReset } from '../state/project-db.js'; const STORE_KEY = 'glint_projects_v12'; @@ -425,7 +424,6 @@ function newProject(name) { activeId = id; setActiveKey(id); writeStore(store); - pushProjectToCloud(store[id]); // v30 — Brand Brain enforcement: a new project starts on-brand. if (state.brand && state.brand.enforce && state.brand.enabled) { import('./brand-brain.js').then(m => m.applyBrand()); @@ -471,16 +469,13 @@ function saveActive({ versionLabel } = {}) { createdAt: Date.now(), auto: !named }); - const justAdded = p.versions[0]; // Keep all named versions; cap auto versions. const namedV = p.versions.filter(v => !v.auto); const autoV = p.versions.filter(v => v.auto).slice(0, MAX_AUTO_VERSIONS); p.versions = [...namedV, ...autoV].sort((a, b) => b.createdAt - a.createdAt); - pushVersionToCloud(p.id, justAdded); } const res = writeStore(store); - pushProjectToCloud(p); reportWrite(res, p.updatedAt); return p; } @@ -548,7 +543,6 @@ function restoreVersion(versionId) { p.payload = v.payload; // shared: stored payloads are never mutated touch(p); writeStore(store); - pushProjectToCloud(p); applyDocument(cloneDoc(v.payload)); closeVersionsModal(); renderPanel(); @@ -571,7 +565,6 @@ function forkVersion(versionId) { activeId = id; setActiveKey(id); writeStore(store); - pushProjectToCloud(store[id]); applyDocument(cloneDoc(v.payload)); closeVersionsModal(); renderPanel(); @@ -590,7 +583,6 @@ async function renameProject(id) { p.name = name.trim() || p.name; touch(p); writeStore(store); - pushProjectToCloud(p); renderPanel(); } @@ -606,7 +598,6 @@ function duplicateProject(id) { }; markDirty(nid); writeStore(store); - pushProjectToCloud(store[nid]); renderPanel(); showNotification(`Duplicated "${p.name}".`, 'success'); } @@ -623,75 +614,10 @@ async function deleteProject(id) { dirtyIds.delete(id); writeStore(store); if (activeId === id) { activeId = null; setActiveKey(null); } - deleteProjectFromCloud(id); renderPanel(); showNotification('Project deleted.', 'success'); } -// ── Cloud sync (best-effort; local stays the source of truth) ──────────────── -async function pushProjectToCloud(p) { - try { - const user = getUser(); const c = await getClient(); - if (!user || !c || !p) return; - await c.from('projects').upsert({ - id: p.id, user_id: user.id, name: p.name, - payload: p.payload, thumbnail: p.thumbnail, - updated_at: new Date(p.updatedAt).toISOString() - }, { onConflict: 'id' }); - } catch (e) { /* offline / not configured — local copy is safe */ } -} -async function pushVersionToCloud(projectId, v) { - try { - const user = getUser(); const c = await getClient(); - if (!user || !c || !v) return; - await c.from('project_versions').upsert({ - id: v.id, project_id: projectId, user_id: user.id, - label: v.label, payload: v.payload, thumbnail: v.thumbnail, - created_at: new Date(v.createdAt).toISOString() - }, { onConflict: 'id' }); - } catch (e) { /* best-effort */ } -} -async function deleteProjectFromCloud(id) { - try { - const user = getUser(); const c = await getClient(); - if (!user || !c) return; - await c.from('projects').delete().eq('id', id).eq('user_id', user.id); - } catch (e) { /* best-effort */ } -} -async function pullCloud() { - try { - await readyP; - const user = getUser(); const c = await getClient(); - if (!user || !c) return; - const { data: projs } = await c.from('projects') - .select('id, name, payload, thumbnail, updated_at').eq('user_id', user.id); - if (!projs) return; - const { data: vers } = await c.from('project_versions') - .select('id, project_id, label, payload, thumbnail, created_at').eq('user_id', user.id); - const store = loadStore(); - let added = 0; - projs.forEach(row => { - const cloudUpdated = new Date(row.updated_at).getTime(); - const local = store[row.id]; - if (!local || cloudUpdated > local.updatedAt) { - store[row.id] = { - id: row.id, name: row.name, payload: row.payload, thumbnail: row.thumbnail, - createdAt: local ? local.createdAt : cloudUpdated, updatedAt: cloudUpdated, - versions: (vers || []).filter(v => v.project_id === row.id).map(v => ({ - id: v.id, label: v.label, payload: v.payload, thumbnail: v.thumbnail, - createdAt: new Date(v.created_at).getTime(), auto: !v.label - })).sort((a, b) => b.createdAt - a.createdAt) - }; - markDirty(row.id); - if (!local) added++; - } - }); - writeStore(store); - if (added > 0) showNotification(`Synced ${added} project${added === 1 ? '' : 's'} from cloud.`, 'success'); - renderPanel(); - } catch (e) { /* best-effort */ } -} - // ── UI: sidebar panel ──────────────────────────────────────────────────────── // IndexedDB: the write is async, so show "Saving…" now; persistIdb sets "Saved" // or "Not saved" once it settles. localStorage: synchronous, as before v34. @@ -819,9 +745,6 @@ export function bindProjects() { if (closeBtn) closeBtn.addEventListener('click', closeVersionsModal); if (overlay) overlay.addEventListener('click', (e) => { if (e.target === overlay) closeVersionsModal(); }); - // Pull cloud projects whenever a user signs in. - onAuthChange(u => { if (u) pullCloud(); }); - // v34: flush a pending autosave when the page is hidden or unloaded. document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') flushPendingSave(); diff --git a/src/main.js b/src/main.js index 071ce35..2ac4b8f 100644 --- a/src/main.js +++ b/src/main.js @@ -60,7 +60,7 @@ import { bindAiArtDirector } from './features/ai-art-director.js'; import { bindAiImageEdit } from './features/ai-image-edit.js'; import { bindScreenshotEditor } from './features/ai-screenshot-editor.js'; import { bindAuth } from './features/auth.js'; -import { bindCloudSync } from './features/cloud-sync.js'; +import { bindAccount } from './features/account.js'; import { bindProjects } from './features/projects.js'; import { bindCampaigns } from './features/campaigns.js'; import { bindPages } from './features/pages.js'; @@ -69,13 +69,11 @@ import { bindSeed } from './features/seed.js'; import { bindA11y } from './ui/a11y.js'; import { bindStaleBuildReload } from './ui/stale-build.js'; import { bindTours } from './features/tours.js'; -import { bindGallery } from './features/gallery.js'; import { bindCrop } from './features/crop.js'; import { bindResetButton } from './features/reset.js'; import { bindShare } from './features/share.js'; import { bindShareLinks } from './features/share-links.js'; import { bindPrintPdf } from './features/print-pdf.js'; // v42 -import { bindCollab } from './features/collab.js'; import { bindAiEnhance } from './features/ai-enhance.js'; import { bindAnimation } from './features/animation.js'; import { bindKenBurns } from './features/ken-burns.js'; @@ -177,8 +175,8 @@ function init() { bindAiArtDirector(); bindAiImageEdit(); bindScreenshotEditor(); // v30 — Magic Edit panel + bindAccount(); // before bindAuth, so it hears the first sign-in state bindAuth(); - bindCloudSync(); bindPages(); bindBoard(); // v32 — Open Canvas board surface bindSeed(); // v32 — Seed: URL -> board cards @@ -187,13 +185,11 @@ function init() { bindTours(); bindProjects(); bindCampaigns(); - bindGallery(); bindCrop(); bindResetButton(); bindShare(); bindShareLinks(); bindPrintPdf(); // v42 — Junction: print-ready PDF - bindCollab(); bindAiEnhance(); bindAnimation(); bindKenBurns(); diff --git a/terms/index.html b/terms/index.html index 1f32c15..a7ad08e 100644 --- a/terms/index.html +++ b/terms/index.html @@ -38,7 +38,7 @@

The deal, in plain language.

Using Glint

-

By using Glint you agree to these terms. The tool is provided free of charge for personal and commercial use. You do not need an account to use the editor; an optional account exists only to sync your projects across devices.

+

By using Glint you agree to these terms. The tool is provided free of charge for personal and commercial use. You do not need an account to use the editor; an optional free account exists only so the hosted AI can count its monthly credits.

What you create is yours

You keep all rights to the screenshots, images, and designs you make. We do not claim ownership of your content, and because editing happens in your browser, we do not receive a copy of it unless you choose a cloud feature. You are responsible for making sure you have the rights to any image you bring in.

@@ -47,7 +47,7 @@

Acceptable use

Use the tool for lawful purposes. Do not use Glint to create or distribute content that is illegal, infringes someone else's rights, or is designed to deceive or harm. Do not attempt to disrupt the service or abuse any hosted feature, including the optional AI backend.

Optional AI and third-party services

-

Some features are optional and connect to third parties. Cloud AI sends your current image and prompt to an AI provider when you click the button. Sharing and cloud projects upload content to storage so it can be linked or synced. When you use these, you also accept the terms and policies of those providers. Anything generated by an AI model may also be subject to that provider's usage terms.

+

Some features are optional and connect to third parties. Cloud AI sends your current image and prompt to an AI provider when you click the button. Share links upload the rendered images to storage so they can be opened by link. Sign-in is provided by Clerk. When you use these, you also accept the terms and policies of those providers. Anything generated by an AI model may also be subject to that provider's usage terms.

Open-source license

Glint is open source. Your use of the source code is governed by the license published in the project repository on GitHub. These terms cover your use of the hosted app and site.

diff --git a/vite.config.js b/vite.config.js index 5e15b36..b84ebd0 100644 --- a/vite.config.js +++ b/vite.config.js @@ -123,6 +123,9 @@ function shareRoutes() { } export default defineConfig({ + // Clerk's Marketplace install names its browser key NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY + // whatever the framework, so let the build read it (src/features/auth.js). + envPrefix: ['VITE_', 'NEXT_PUBLIC_CLERK_'], root: '.', build: { outDir: 'dist', @@ -163,7 +166,6 @@ export default defineConfig({ }, output: { manualChunks: { - 'vendor-supabase': ['@supabase/supabase-js'], 'vendor-openai': ['openai'], 'vendor-anthropic': ['@anthropic-ai/sdk'], 'vendor-three': ['three'],