Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.
TypeScript canva-alternativecanvasdesigndesign-tooldrag-and-dropeditorgraphic-designkonvanextjsopen-sourcereactself-hostedtemplatestypescript
docs(v0.12): ops runbook — tested backup/restore drill, upgrade & rollback guide, media orphan GC with drill (H6) (#15)
Ashiq Hussain Mirca487d4c30f2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2fbafa5..8caec4e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,42 @@All notable changes to Canvix will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).+## [0.12.4] — 2026-11-02++### Added++- **Docs & ops runbook (H6).** Self-hosters get the two guides the+ roadmap research called the missing floor of the operations story:+ - **`docs/BACKUP-AND-RESTORE.md`** — one-command `pg_dump` backup+ (custom format) with the notes that actually matter in practice:+ the **bytea media travels inside the dump** (size implications,+ 32 MB/file cap), the Supabase session-vs-transaction-pooler+ pitfall for pg_dump, and cross-owner restore flags. The core is a+ **restore drill executed and verified end-to-end**, documented+ step-by-step with its real output: dump (753 KB, 167 designs,+ 110 templates, 30 media) → scratch database → `pg_restore+ --no-owner --no-privileges` → count-and-byte verification+ (identical, including `SUM(size)` on media) → **booting the app+ against the restored database** (`/api/health` green, designs+ served) → teardown. Plus real-recovery steps and a scheduled-+ backup cron example.+ - **`docs/UPGRADING.md`** — the routine upgrade path (snapshot →+ pull → `npm ci` → `db:migrate:deploy` → rebuild → health check),+ jumping minors (cumulative migrations, one command, what to read+ in the CHANGELOG), and rollback guidance with the honest caveat:+ Prisma migrations are forward-only, so the safe path is+ restore-forward from the pre-upgrade snapshot — and the note that+ 0.9–0.12 migrations are additive, so code-only rollbacks can+ leave the schema migrated.+ - **`scripts/media-gc.ts`** — media orphan GC: reports (default) or+ prunes (`--prune`, `GRACE_DAYS`) never-finalized uploads older+ than 24 h and finalized uploads no live design references anymore+ (elements reference media as `/api/media/<id>`; deleting a design+ intentionally keeps its media for version snapshots). Verified by+ a drill (`scripts/media-gc-drill.ts`) that plants one orphan and+ one referenced row and asserts exactly the orphan is pruned.+- **README pointers** to both guides from the Deploy section.+## [0.12.3] — 2026-11-02### Addeddiff --git a/README.md b/README.mdindex b955eb2..c7d9c72 100644--- a/README.md+++ b/README.md@@ -463,6 +463,15 @@ Canvix runs on **any Node host** and — since v0.9.3 — on **CloudflareWorkers** too, and — since v0.9.4 — on **Netlify**. Same codebase, samedatabase, zero config divergence.+**Running it long-term?** Two operations guides shipped with v0.12.4:+[`docs/BACKUP-AND-RESTORE.md`](docs/BACKUP-AND-RESTORE.md) — the+one-command `pg_dump` backup, a restore drill executed and verified+step-by-step (counts + bytea sizes + booting the app against the+restored database), scheduled-backup cron, and the media orphan GC —+and [`docs/UPGRADING.md`](docs/UPGRADING.md) — the routine upgrade+path, jumping minors, and rollback guidance including the honest+forward-only-migrations caveat.+### Vercel (or any Node host)1. Import the repo, set `DATABASE_URL` (the **transaction pooler** URL —@@ -846,6 +855,12 @@ tool descriptions so agents pick the right format.at 6 concurrent connections per IP, a load-probe script that provesboth caps on a live instance, and an honest “multi-instance fleets”section in the README *(v0.12.3)*+- [x] Docs & ops runbook — `docs/BACKUP-AND-RESTORE.md` (pg_dump backup+ with the bytea note, a restore drill executed + verified end-to-end:+ counts, media bytes, booting the app on the restored database,+ scheduled-backup cron) and `docs/UPGRADING.md` (routine upgrades,+ jumping minors, rollback with the forward-only-migrations caveat),+ plus a media orphan GC script with its own verified drill *(v0.12.4)*- [ ] Plugin system (external, installable apps) — sandboxed-iframe MVPper `research/PLUGIN-SYSTEM.md`: manifest + permission model, iframesandbox with postMessage bridge, an “Apps” panel store, and 2–3diff --git a/docs/BACKUP-AND-RESTORE.md b/docs/BACKUP-AND-RESTORE.mdnew file mode 100644index 0000000..b305fff--- /dev/null+++ b/docs/BACKUP-AND-RESTORE.md@@ -0,0 +1,170 @@+# Backup & restore — the tested drill++Canvix keeps **everything** in one Postgres database: designs (jsonb+pages), accounts and sessions, comments, version snapshots, the+template library — and **uploaded audio/video, as `bytea`**. One+`pg_dump` therefore captures the entire instance. There is no object+storage, no secondary state, nothing else to back up (unless you count+`.env`, which you should also keep a copy of — it holds your+`DATABASE_URL` and any AI/MCP keys).++This guide documents a restore drill **actually executed and verified**+(the output below is real, not illustrative): dump → scratch database →+restore → row/byte-level count verification → boot the app against the+restored database. The drill ran against PostgreSQL 18 on a development+instance; on a hosted database (Supabase, Neon, RDS…) only the+connection flags change — the steps and the verification are identical.++> **When to read this:** before your first production-ish deployment,+> and every time you change backup schedules. A backup that has never+> been restored is a hope, not a backup.++---++## 1. Back up++```bash+# custom format: compressed, pg_restore-able, selective restore possible+pg_dump "$DATABASE_URL" -Fc -f canvix-backup-$(date +%Y%m%d).dump+```++Notes that matter:++- **The `bytea` media travels inside the dump.** A design-heavy or+ media-heavy instance produces a proportionally large dump — media is+ capped at 32 MB per file by default (`CANVIX_MAX_MEDIA_MB`), but+ hundreds of uploads add up. Check the dump size before assuming a+ schedule is fine; a daily full dump is the right cadence for a+ single-instance self-host.+- **Supabase**: use the **session/direct connection** for `pg_dump`,+ not the transaction pooler port 6543 (pg_dump needs session-level+ features the pooler does not pass through). The direct port is+ 5432, or the *session* pooler (`:5432`-style `pooler.supabase.com`+ URL with `pgbouncer=false`). Plain `pg_dump` with the connection+ string from the dashboard works when the host has an IPv6 route;+ otherwise use the session pooler.+- Verify a dump non-destructively any time:++ ```bash+ pg_restore --list canvix-backup-20261101.dump | head+ ```++## 2. Restore into a scratch database (the drill)++Never test a restore over your live database. The drill, exactly as+executed:++```bash+# 1. dump the source+pg_dump -h localhost -p 5433 -U canvix -Fc -f canvix-backup-20261101.dump canvix+# → 753 KB for a dev instance (167 designs, 110 templates, 30 media)++# 2. create the scratch target+createdb -h localhost -p 5433 -U canvix canvix_restore_drill++# 3. restore — cross-owner safe flags+pg_restore -h localhost -p 5433 -U canvix -d canvix_restore_drill \+ --no-owner --no-privileges canvix-backup-20261101.dump+# → exit 0+```++`--no-owner --no-privileges` matter when the restoring role differs+from the dumping role (typical when moving between hosts: dump as+`postgres`, restore as `postgres` on Supabase).++## 3. Verify (counts + bytes)++```sql+-- run against BOTH databases; every line must match+SELECT 'designs=' || COUNT(*) FROM "Design" UNION ALL+SELECT 'users=' || COUNT(*) FROM "User" UNION ALL+SELECT 'templates=' || COUNT(*) FROM "Template" UNION ALL+SELECT 'media=' || COUNT(*) || ' (' || COALESCE(SUM(size),0)/1024 || ' KB)' FROM "Media" UNION ALL+SELECT 'events=' || COUNT(*) FROM "DesignEvent" UNION ALL+SELECT 'comments=' || COUNT(*) FROM "Comment";+```++Drill output (source vs restored — identical, including media bytes):++```+[canvix] [canvix_restore_drill]+ designs=167 designs=167+ users=0 users=0+ templates=110 templates=110+ media=30 (3756 KB) media=30 (3756 KB)+ events=13 events=13+ comments=0 comments=0+```++The `Media` line is the one to watch: `SUM(size)` proves the bytea+payloads restored at full length, not just the row count.++## 4. Boot the app against the restored database++```bash+DATABASE_URL=postgresql://…canvix_restore_drill npm run dev # or your prod start+curl -s localhost:3000/api/health+```++Drill output — the app declares the restored database healthy and+serves its designs:++```json+{+ "ok": true,+ "database": { "kind": "local", "host": "localhost", "database": "canvix_restore_drill" },+ "templates": 110+}+```++```+GET /api/designs → 60 designs on page 1 (keyset pagination), first:+"v0110 browser smoke"+```++Then drop the scratch database (`dropdb … canvix_restore_drill`) — or,+in a real recovery, point production at the restored database instead.++## 5. Restoring over the live database (actual recovery)++1. Stop the app (or put it behind a maintenance page).+2. Back up the current database first (`pg_dump` again) — you want the+ pre-recovery state for forensics.+3. Restore. Two options:+ - **Same database**: `psql "$DATABASE_URL" -c 'DROP SCHEMA public CASCADE; CREATE SCHEMA public;'` then `pg_restore --no-owner --no-privileges -d "$DATABASE_URL" backup.dump`.+ (Supabase: do NOT drop the schema you are connected through the+ dashboard — use a connection to `postgres` or a fresh database.)+ - **Fresh database** (safer, zero-downtime-ish): `createdb`, restore,+ then repoint `DATABASE_URL` and restart the app. Verified above.+4. `curl -s your-host/api/health` until `ok: true`.+5. Spot-check a design, a media element (play an uploaded video), and a+ login.++## 6. Scheduled backups (example)++```cron+# /etc/cron.d/canvix-backup — daily 03:15, keep 14 days+15 3 * * * canvix pg_dump "$DATABASE_URL" -Fc -f /var/backups/canvix/canvix-$(date +\%Y\%m\%d).dump+25 3 * * * canvix find /var/backups/canvix -name 'canvix-*.dump' -mtime +14 -delete+```++Offsite: sync the dump directory to any object storage (`rclone`,+`aws s3 sync`). Because everything is one dump file, a restore needs+nothing but the newest file and a fresh database.++## 7. Media orphan GC (companion)++Deleted designs leave their uploaded media behind (deletes remove the+element JSON, not the media row — intentional, media may be shared by+version snapshots). Reclaim space periodically:++```bash+DATABASE_URL=… npx tsx scripts/media-gc.ts # report only+DATABASE_URL=… npx tsx scripts/media-gc.ts --prune # actually delete+GRACE_DAYS=30 npx tsx scripts/media-gc.ts --prune # keep 30d of orphans+```++The script removes never-finalized uploads older than 24 h and+finalized uploads past the grace period whose id no design references+(verified by a drill that plants one orphan + one referenced row and+asserts exactly the orphan is pruned). Cron it next to the backup.diff --git a/docs/UPGRADING.md b/docs/UPGRADING.mdnew file mode 100644index 0000000..53fe04a--- /dev/null+++ b/docs/UPGRADING.md@@ -0,0 +1,113 @@+# Upgrading & rolling back a self-hosted Canvix++Canvix ships as one Next.js app plus one Postgres database, and every+release is designed to upgrade with **one migration command**. This+guide covers the routine path, jumping minors, and — the part most+guides skip — how to roll back, with the honest database caveat.++## How releases work++- Versions are semver-ish patch streams (`0.11.0 → 0.11.8 → 0.12.0 …`);+ every change lands on `main` through a PR and is documented in+ `CHANGELOG.md` with the version it shipped in.+- Database changes ship as **forward-only Prisma migrations**+ (`prisma/migrations/…`). They are cumulative: a fresh checkout of any+ version can build the complete schema from zero (`npm run db:setup`).+- The app never reads a schema that is older than its migrations, and+ migrations never drop user data (additive columns are nullable, data+ backfills live inside the migration SQL).++## The routine upgrade (any version → next)++```bash+# 1. snapshot first — see docs/BACKUP-AND-RESTORE.md+pg_dump "$DATABASE_URL" -Fc -f /var/backups/canvix/pre-upgrade-$(date +%Y%m%d).dump++# 2. fetch the new code (however you deploy: git pull, new image, new checkout)+git pull --ff-only++# 3. dependencies (postinstall runs prisma generate + the wasm patch)+npm ci++# 4. apply migrations — idempotent, skips already-applied ones+npm run db:migrate:deploy++# 5. rebuild + restart (Node standalone shown; same idea on every host)+npm run build && npm start++# 6. verify+curl -s your-host/api/health # → {"ok": true, ...}+```++Downtime = the restart (seconds). The migration step is safe to run+while the old app is still serving: pending migrations are additive,+so the old version keeps working against the migrated schema.++## Jumping minors (e.g. 0.11.8 → 0.12.x)++Same six steps — nothing extra. Things worth knowing:++- **You do not need to stop at intermediate versions.** Migrations are+ cumulative; `db:migrate:deploy` takes you from whatever you have to+ the checkout's schema, applying only the missing ones.+- **Read the CHANGELOG entries you are crossing** for env-var+ additions (they are always optional-with-defaults — e.g. v0.12.3's+ rate limits work with zero configuration) and deploy-size notes+ (v0.9.4 shrank the traced bundle; if you ship to Netlify's 50 MB+ limit, crossing that version changes your artifact size for the+ better).+- **`npm run db:setup` is for fresh databases** (migrate + seed the+ 110 templates). On an existing database use `db:migrate:deploy` —+ setup would also re-seed templates that already exist (harmless but+ noisy).+- The template library ships as code; upgrading may add new templates+ via the seed. Existing designs are never touched by an upgrade.++## Rolling back++**App rollback is easy:** redeploy the previous build (git checkout+the previous commit, `npm ci && npm run build && npm start`, or point+your platform at the previous deployment). The previous version runs+fine against a *not-newer* schema.++**The honest database caveat:** Prisma migrations are forward-only —+there is no generated `down`. Two rollback situations:++1. **You upgraded the code but migrations have not run yet** (step 4+ pending): just redeploy the old build. Nothing changed in the DB.+2. **Migrations ran**: the safe path is *restore-forward*, not+ schema-revert:+ ```bash+ # restore the pre-upgrade backup into a FRESH database (tested+ # procedure: docs/BACKUP-AND-RESTORE.md)+ createdb "$RESTORE_TARGET" && pg_restore --no-owner --no-privileges \+ -d "$RESTORE_TARGET" /var/backups/canvix/pre-upgrade-YYYYMMDD.dump+ # repoint DATABASE_URL at it, restart the old build+ ```+ You lose writes made between the backup and the rollback — that is+ the RPO of your backup schedule, stated plainly. If the failing+ change is confined to code (most are), roll the code back and leave+ the migrated schema alone: migrations in the 0.9–0.12 range are+ additive (nullable columns, new tables), so older code simply+ ignores them.++Never hand-edit the schema or the `_prisma_migrations` table to+"un-migrate" — a hand-crafted reverse migration is the one move that+can actually lose data.++## Choosing what to run++| Deployment | Notes |+|---|---|+| Node standalone (`output: "standalone"`) | `npm run build && npm start` — the reference target |+| Vercel / Netlify / Cloudflare Workers | Platform rebuilds from the repo; set `DATABASE_URL`, run `db:migrate:deploy` once per upgrade from anywhere with DB access (CI step, your laptop) |+| Docker | Rebuild the image; run the migration as a one-off container before swapping |++## Quick reference++```bash+npm run db:migrate:deploy # apply pending migrations (idempotent)+npm run db:setup # fresh database only: migrate + seed templates+pg_dump "$DATABASE_URL" -Fc -f backup.dump # pre-upgrade snapshot+npx tsx scripts/media-gc.ts # space check (report only)+```diff --git a/package.json b/package.jsonindex 9df73c7..565ade5 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "canvix",- "version": "0.12.3",+ "version": "0.12.4","private": false,"description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.","scripts": {diff --git a/scripts/media-gc-drill.ts b/scripts/media-gc-drill.tsnew file mode 100644index 0000000..546eeb8--- /dev/null+++ b/scripts/media-gc-drill.ts@@ -0,0 +1,101 @@+// one-off drill for scripts/media-gc.ts (v0.12.4, H6): plants+// (a) an old ORPHAN media row, and+// (b) an old media row REFERENCED by a live design's pages,+// runs the GC in report + prune mode, and asserts that exactly the+// orphan is flagged and deleted while the referenced one survives.+// Restores the design's pages afterwards. Safe to re-run.+// Usage: DATABASE_URL=... npx tsx scripts/media-gc-drill.ts+import { createScriptClient } from '../src/lib/db-script'++const db = createScriptClient()+const OLD = new Date(Date.now() - 30 * 24 * 3600 * 1000)+const bytes = new Uint8Array([1, 2, 3, 4])++interface PageShape {+ id?: string+ elements?: Array<Record<string, unknown>>+ [k: string]: unknown+}++function asPages(raw: unknown): PageShape[] {+ const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw+ return Array.isArray(parsed) ? (parsed as PageShape[]) : []+}++async function main() {+ // a live design with at least one page to anchor the "referenced" probe+ const designs = await db.design.findMany({+ where: { deletedAt: null },+ orderBy: { updatedAt: 'desc' },+ take: 20,+ select: { id: true, pages: true },+ })+ const design = designs.find((d) => {+ const pages = asPages(d.pages)+ return pages.length > 0 && Array.isArray(pages[0].elements)+ })+ if (!design) throw new Error('need at least one live design with a page for the drill')++ const originalPages = design.pages+ const pages = asPages(design.pages)++ const orphan = await db.media.create({+ data: { mime: 'audio/mp4', size: 4, bytes, finalizedAt: OLD, createdAt: OLD },+ select: { id: true },+ })+ const kept = await db.media.create({+ data: { mime: 'video/webm', size: 4, bytes, finalizedAt: OLD, createdAt: OLD },+ select: { id: true },+ })+ const probeElement = {+ type: 'video',+ src: `/api/media/${kept.id}`,+ x: 0,+ y: 0,+ w: 10,+ h: 10,+ }+ pages[0].elements!.push(probeElement)+ await db.design.update({ where: { id: design.id }, data: { pages: pages as never } })+ console.log(`planted orphan=${orphan.id} referenced=${kept.id} (in design ${design.id})`)++ try {+ const { execSync } = await import('node:child_process')+ const out = execSync('npx tsx scripts/media-gc.ts', {+ env: { ...process.env },+ encoding: 'utf8',+ })+ const flagsOrphan = out.includes(orphan.id)+ const flagsKept = out.includes(kept.id)+ console.log(`report flags orphan: ${flagsOrphan}, flags referenced: ${flagsKept}`)++ const prune = execSync('npx tsx scripts/media-gc.ts --prune', {+ env: { ...process.env },+ encoding: 'utf8',+ })+ const prunedOrphan = prune.includes(orphan.id)+ const orphanGone = !(await db.media.findUnique({ where: { id: orphan.id } }))+ const keptAlive = !!(await db.media.findUnique({ where: { id: kept.id } }))+ console.log(+ `prune lists orphan: ${prunedOrphan}; orphan deleted: ${orphanGone}; referenced kept: ${keptAlive}`,+ )++ const pass = flagsOrphan && !flagsKept && prunedOrphan && orphanGone && keptAlive+ console.log(pass ? 'MEDIA GC DRILL: PASS' : 'MEDIA GC DRILL: FAIL')+ process.exitCode = pass ? 0 : 1+ } finally {+ // restore the design's pages + drop the probe media row+ await db.design+ .update({ where: { id: design.id }, data: { pages: originalPages as never } })+ .catch(() => {})+ await db.media.delete({ where: { id: kept.id } }).catch(() => {})+ console.log('drill cleaned up')+ }+}++main()+ .catch((e) => {+ console.error('drill failed:', e)+ process.exitCode = 1+ })+ .finally(() => db.$disconnect())diff --git a/scripts/media-gc.ts b/scripts/media-gc.tsnew file mode 100644index 0000000..e9a3fd3--- /dev/null+++ b/scripts/media-gc.ts@@ -0,0 +1,130 @@+// scripts/media-gc.ts — media orphan GC (v0.12.4, roadmap H6).+//+// The media store keeps finalized uploads (audio/video, up to 32 MB+// each as bytea) until someone deletes them; deleting the design+// that used them (permanent delete) removes the element JSON but+// never the media row. This script finds and (with --prune) removes:+//+// 1. never-finalized uploads older than 24 h — the same rule the+// upload-init route applies lazily, applied deterministically+// 2. finalized uploads older than the grace period (default 14 d)+// whose id is not referenced by ANY live design's pages — an+// element references its media as `/api/media/<id>` in src+//+// Default mode REPORTS only; --prune actually deletes. The grace+// period exists because a freshly uploaded file can legitimately be+// referenced only by an UNSAVED design (autosave 1.6 s debounce, an+// offline tab, or a design that was never saved at all).+//+// Usage:+// DATABASE_URL=... npx tsx scripts/media-gc.ts # report+// DATABASE_URL=... npx tsx scripts/media-gc.ts --prune # delete+// GRACE_DAYS=30 npx tsx scripts/media-gc.ts --prune # custom grace+import { createScriptClient } from '../src/lib/db-script'++const db = createScriptClient()++const PRUNE = process.argv.includes('--prune')+const GRACE_DAYS = Math.max(1, Number(process.env.GRACE_DAYS ?? 14))+const ABANDON_MS = 24 * 3600 * 1000+const GRACE_MS = GRACE_DAYS * 24 * 3600 * 1000++/** every `/api/media/<id>` referenced by any page of this design */+function referencedMediaIds(pages: unknown): Set<string> {+ const ids = new Set<string>()+ const walk = (value: unknown): void => {+ if (typeof value === 'string') {+ // element src — also catches src in exports/settings mirrors+ const m = value.match(/\/api\/media\/([a-zA-Z0-9_-]+)/g)+ if (m) for (const hit of m) ids.add(hit.slice('/api/media/'.length))+ return+ }+ if (Array.isArray(value)) {+ value.forEach(walk)+ return+ }+ if (value && typeof value === 'object') {+ Object.values(value).forEach(walk)+ }+ }+ walk(pages)+ return ids+}++async function main() {+ const now = Date.now()+ console.log('════ CANVIX MEDIA ORPHAN GC ════')+ console.log(`run at: ${new Date().toISOString()}`)+ console.log(`mode: ${PRUNE ? 'PRUNE (deletes!)' : 'report only'}`)+ console.log(`grace: ${GRACE_DAYS} days for finalized orphans`)++ // 1. abandoned (never finalized) uploads+ const abandoned = await db.media.findMany({+ where: { finalizedAt: null, createdAt: { lt: new Date(now - ABANDON_MS) } },+ select: { id: true, size: true, createdAt: true },+ })+ const abandonedBytes = abandoned.reduce((n, m) => n + m.size, 0)+ console.log(`\nabandoned uploads (>24 h, never finalized): ${abandoned.length}`)+ console.log(` reclaimable: ${(abandonedBytes / 1024 / 1024).toFixed(2)} MB`)+ if (PRUNE && abandoned.length) {+ await db.media.deleteMany({+ where: { finalizedAt: null, createdAt: { lt: new Date(now - ABANDON_MS) } },+ })+ console.log(' → deleted')+ }++ // 2. finalized orphans past the grace period+ const candidates = await db.media.findMany({+ where: { finalizedAt: { not: null }, createdAt: { lt: new Date(now - GRACE_MS) } },+ select: { id: true, size: true, createdAt: true },+ })+ console.log(+ `\nfinalized uploads older than ${GRACE_DAYS} d: ${candidates.length}` ++ ` (${(candidates.reduce((n, m) => n + m.size, 0) / 1024 / 1024).toFixed(2)} MB)`,+ )++ // referenced set — scan live (non-trashed) designs in batches+ const referenced = new Set<string>()+ let cursor: string | undefined+ let scanned = 0+ for (;;) {+ const batch = await db.design.findMany({+ where: { deletedAt: null, ...(cursor ? { id: { gt: cursor } } : {}) },+ orderBy: { id: 'asc' },+ take: 100,+ select: { id: true, pages: true },+ })+ if (!batch.length) break+ cursor = batch[batch.length - 1].id+ scanned += batch.length+ for (const d of batch) {+ for (const id of referencedMediaIds(d.pages)) referenced.add(id)+ }+ }+ console.log(`live designs scanned for references: ${scanned}`)++ const orphans = candidates.filter((m) => !referenced.has(m.id))+ const orphanBytes = orphans.reduce((n, m) => n + m.size, 0)+ console.log(`\norphaned finalized media: ${orphans.length}`)+ console.log(` reclaimable: ${(orphanBytes / 1024 / 1024).toFixed(2)} MB`)+ for (const m of orphans.slice(0, 20)) {+ console.log(` ${m.id} ${(m.size / 1024 / 1024).toFixed(2)} MB ${m.createdAt.toISOString()}`)+ }+ if (orphans.length > 20) console.log(` … and ${orphans.length - 20} more`)+ if (PRUNE && orphans.length) {+ await db.media.deleteMany({ where: { id: { in: orphans.map((m) => m.id) } } })+ console.log(' → deleted')+ }++ if (!PRUNE) {+ console.log('\n(report only — re-run with --prune to delete)')+ }+ console.log(`\n${PRUNE ? 'PRUNED' : 'REPORTED'} — done.`)+}++main()+ .catch((e) => {+ console.error('media-gc failed:', e)+ process.exitCode = 1+ })+ .finally(() => db.$disconnect())