Compare commits
24
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f49a2e0a0a | ||
|
|
2aad665096 | ||
|
|
08645699f3 | ||
|
|
f5e8d25fe2 | ||
|
|
b2fcc57d19 | ||
|
|
91744aeaef | ||
|
|
0ab72867b0 | ||
|
|
7d85d56e53 | ||
|
|
3baed783b1 | ||
|
|
ed1fa39cff | ||
|
|
40eac1a0cb | ||
|
|
d277a018ee | ||
|
|
163fcb475e | ||
|
|
903267cf3c | ||
|
|
18f0641595 | ||
|
|
be18c0a412 | ||
|
|
94fde6e660 | ||
|
|
c81f3925c6 | ||
|
|
921dba0bf1 | ||
|
|
34f85f6e57 | ||
|
|
0e0a8d6bad | ||
|
|
0785b29462 | ||
|
|
344e83376b | ||
|
|
150702d33f |
No files matched your search
@@ -4,8 +4,8 @@
|
||||
When making database schema changes, you must ensure that generated migrations are resilient against environmental discrepancies.
|
||||
|
||||
- **Review Generated SQL**: Always review the `.sql` files generated by `npx prisma migrate dev`.
|
||||
- **Add "IF EXISTS" clauses**: SQLite and Prisma can sometimes produce brittle drop statements (`DROP INDEX "my_index"`). To prevent migrations from crashing if a state desynchronization occurs (e.g., the index was already dropped or never created), manually edit the migration file to use `DROP INDEX IF EXISTS "my_index";` or `DROP TABLE IF EXISTS "table_name";`.
|
||||
- **Data Preservation**: When dropping columns or renaming, SQLite does not cleanly support it and requires table recreation. Carefully review the `INSERT INTO "new_table" SELECT ...` clauses to ensure data is correctly mapped.
|
||||
- **Add "IF EXISTS" clauses**: Prisma can sometimes produce brittle drop statements (`DROP INDEX "my_index"`). To prevent migrations from crashing if a state desynchronization occurs, manually edit the migration file to use `DROP INDEX IF EXISTS "my_index";` or `DROP TABLE IF EXISTS "table_name";`.
|
||||
- **Data Preservation**: When dropping columns or renaming, carefully review the migration to ensure data is correctly mapped. In PostgreSQL, ensure that cascaded drops don't accidentally remove required data.
|
||||
|
||||
## 2. Managing Failed Migrations
|
||||
If a migration fails in production:
|
||||
@@ -13,4 +13,4 @@ If a migration fails in production:
|
||||
- If you use `resolve --applied`, Prisma will permanently skip that migration in the future, leaving your database structurally out of sync with your Prisma Client.
|
||||
|
||||
## 3. Backups Before DDL
|
||||
Never perform direct DDL operations (ALTER, DROP, CREATE) on a production database (via Prisma or direct SQLite access) without first confirming an automated backup exists, or manually taking a backup of the `wwv.db` file.
|
||||
Never perform direct DDL operations (ALTER, DROP, CREATE) on a production database without first confirming an automated backup exists, or manually taking a `pg_dump` backup of the database.
|
||||
@@ -1,4 +1,13 @@
|
||||
DATABASE_URL=file:./data/wwv.db
|
||||
# PostgreSQL connection string.
|
||||
# For local dev: The platform will automatically spin up PostgreSQL via Docker Compose.
|
||||
# Set DATABASE_URL to: postgresql://postgres:postgres@localhost:5432/worldwideview?schema=public
|
||||
#
|
||||
# For cloud/production: Provide your external Postgres connection string (e.g. Supabase)
|
||||
# and set WWV_SKIP_LOCAL_DB=true to prevent Docker from spinning up a local database instance.
|
||||
# DATABASE_URL=postgresql://postgres:postgres@localhost:5432/worldwideview?schema=public
|
||||
|
||||
# Set this to true in production to prevent docker-compose or pnpm run dev from starting the local database.
|
||||
# WWV_SKIP_LOCAL_DB=false
|
||||
|
||||
# Default plugins enabled on boot for demo edition
|
||||
# Comma-separated list of plugin IDs
|
||||
|
||||
@@ -11,8 +11,6 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
@@ -27,8 +25,6 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
@@ -42,14 +38,12 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [typecheck, test]
|
||||
env:
|
||||
DATABASE_URL: file:./data/wwv.db
|
||||
DATABASE_URL: postgresql://ci:ci@localhost:5432/ci
|
||||
AUTH_SECRET: ci-placeholder-secret-not-used-in-tests
|
||||
NEXT_PUBLIC_WWV_EDITION: local
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
|
||||
@@ -19,7 +19,7 @@ Our primary design, feature-set, and operational layout goal is to mimic the str
|
||||
| State | Zustand (slice-based: globe, layers, timeline, UI, filters, data, config, favorites, geojson) |
|
||||
| Event Bus | Custom typed `DataBus` (pub/sub singleton) |
|
||||
| Styling | Vanilla CSS — **no Tailwind** |
|
||||
| Database | SQLite via Prisma (local), PostgreSQL (cloud) |
|
||||
| Database | PostgreSQL via Prisma 7 (local and cloud) |
|
||||
| Auth | NextAuth v5 beta (Credentials provider, JWT sessions) |
|
||||
| Package Manager | pnpm (monorepo with `pnpm-workspace.yaml`) |
|
||||
| Testing | Vitest + jsdom + React Testing Library |
|
||||
@@ -77,7 +77,7 @@ worldwideview/
|
||||
├── prisma/ # schema.prisma, migrations/
|
||||
├── public/ # Static assets, Cesium workers, plugin GeoJSON data
|
||||
├── scripts/ # Build scripts (copy-cesium, scaffold-osm-plugin, setup)
|
||||
├── data/ # SQLite database (gitignored, Docker volume)
|
||||
├── data/ # PostgreSQL data volume (gitignored)
|
||||
├── Dockerfile # Multi-stage production build
|
||||
├── docker-compose.yml # Main app + microservice backends
|
||||
└── .agents/ # Agent documentation, rules, skills, workflows
|
||||
@@ -102,7 +102,7 @@ Visibility Toggle → DataBusSubscriber subscribes to layer via WsClient
|
||||
```
|
||||
|
||||
Four plugin architectures exist (All-Bundle Model):
|
||||
1. **Data Engine Seeder** — Standalone Fastify container with SQLite microservice or unified seeders (e.g., `iranwarlive-backend`).
|
||||
1. **Data Engine Seeder** — Standalone Fastify container with PostgreSQL microservice or unified seeders (e.g., `iranwarlive-backend`).
|
||||
2. **Dynamic CDN Loaded (Bundle)** — Externally developed plugins dynamically imported at runtime via ES module CDNs (e.g., `unpkg.com` version-pinned URLs).
|
||||
3. **Static Compiled (Bundle)** — Static GeoJSON data wrapped into JS bundles via `wwvStaticCompiler` during build/sync (previously `StaticDataPlugin`).
|
||||
4. **Active Proxied (Bundle)** — Next.js API routes bundled to provide frontend interactions (previously `DeclarativePlugin`).
|
||||
@@ -213,6 +213,7 @@ Built-in plugins are instantiated in `AppShell.tsx` and registered via `PluginRe
|
||||
> - **MUST**: You MUST update Semantic Versioning numbering inside the relevant `package.json` file prior to executing any code commits, adhering strictly to the `[/commit]` workflow rules (`feat:` -> Minor, `fix/refactor/perf:` -> Patch).
|
||||
> - **MUST Detail Commit Levels & Bumps**: On description changes or release notes, you must detail the level of commit (Major/Minor/Fix) for *each* individual change. If there are multiple accumulated changes, you MUST EITHER commit them individually and bump the version each time, OR commit them all at once and bump the version multiple times.
|
||||
> - **MUST Explain Complex Concepts Simply**: Whenever providing a complicated technical explanation to the user, you MUST include a simple explanation below it. Use an analogy with reference to the correct terminology, comparing the concept to something from everyday life to ensure the user easily understands it.
|
||||
> - **MUST Be Transparent & Narrate Actions**: You MUST always be transparent about what you are doing. Narrate your goals, your current step in the process, and exactly what actions you are taking or tools you are executing **before** or **while** you do them, not after they are done. Do not work in silence or lock all your reasoning behind hidden "thought" blocks. Use visible chat messages to bring the user along the journey by describing your plan as it unfolds. **Crucially, keep this narration conversational and natural.** Avoid stiff, robotic templates (e.g., "My Goal: X. My Step: Y."). Just occasionally drop a brief, casual note about what you are checking or doing next so the user isn't left in the dark.
|
||||
|
||||
### 5.8 Workspace Hygiene
|
||||
Whenever agents generate temporary debugging scripts, test REST endpoints via `.mjs`, or dump traces/JSON outputs, they **MUST** save these exclusively inside `/local-scripts/`. The root directory is strictly for production configuration files.
|
||||
@@ -223,7 +224,7 @@ Whenever agents generate temporary debugging scripts, test REST endpoints via `.
|
||||
|
||||
| Variable | Required | Description |
|
||||
|---|---|---|
|
||||
| `DATABASE_URL` | Yes | SQLite: `file:./data/wwv.db` |
|
||||
| `DATABASE_URL` | Yes | PostgreSQL connection string |
|
||||
| `AUTH_SECRET` | Yes | JWT signing secret (generate with `openssl rand -hex 32`) |
|
||||
| `NEXT_PUBLIC_CESIUM_ION_TOKEN` | No | Cesium Ion access token |
|
||||
| `NEXT_PUBLIC_BING_MAPS_KEY` | No | Bing Maps imagery |
|
||||
@@ -249,9 +250,9 @@ pnpm dev:all # Frontend + wwv-data-engine concurrently (normal developm
|
||||
pnpm dev:backends # Run only the data engine in dev mode
|
||||
pnpm build # Production build
|
||||
pnpm test # Run all Vitest tests (scoped to src/lib, src/core, src/plugins)
|
||||
pnpm db:reset # Reset and re-migrate the frontend SQLite database (destructive)
|
||||
pnpm db:reset # Reset and re-migrate the frontend database (destructive)
|
||||
pnpm start:backends # Start all plugin microservice backends in parallel
|
||||
pnpm clean:backends # Wipe all plugin SQLite databases
|
||||
pnpm clean:backends # Wipe all plugin database records
|
||||
pnpm run scaffold-osm-plugin <name> # Generate a new plugin from scaffold
|
||||
```
|
||||
|
||||
@@ -266,8 +267,8 @@ Frontend runs at `http://localhost:3000`.
|
||||
- **Cesium assets**: Copied to `public/cesium/` via `scripts/copy-cesium.mjs` at build time, excluded from output tracing.
|
||||
- **Prisma Configuration**: `prisma.config.ts` must export a native javascript object instead of dynamically importing CLI wrapper binaries (`prisma/config` or `dotenv`). The standalone Next.js tracer strips CLI devDependencies during the build, which will cause fatal runtime container crashes if imported.
|
||||
- **Microservices**: Separate containers defined in `docker-compose.yml`, proxied via `next.config.ts` rewrites.
|
||||
- **Coolify**: Deployed via Dockerfile builder natively mapping environment variables continuously into the container shell. Persistent storage mount required at `/app/data` for the SQLite root node database.
|
||||
- **Docker volumes**: Mount `/app/data` (frontend SQLite), `/app/packages/wwv-data-engine/data` (data engine SQLite), `/data` (Redis)
|
||||
- **Coolify**: Deployed via Dockerfile builder natively mapping environment variables continuously into the container shell.
|
||||
- **Docker volumes**: Ensure PostgreSQL data and Redis volumes are mounted for persistence.
|
||||
|
||||
---
|
||||
|
||||
@@ -314,7 +315,7 @@ Read the relevant rule file when working in that domain:
|
||||
| `plugin-architecture` | Creating/modifying plugins, lifecycle, registration | `.agents/rules/plugin-architecture.md` |
|
||||
| `cesium-rendering` | Globe rendering, entity types, primitives, LOD, culling | `.agents/rules/cesium-rendering.md` |
|
||||
| `state-management` | Zustand slices, store access, plugin settings | `.agents/rules/state-management.md` |
|
||||
| `database-migrations` | Prisma schema changes, migrations, SQLite/Postgres | `.agents/rules/database-migrations.md` |
|
||||
| `database-migrations` | Prisma schema changes, migrations, PostgreSQL | `.agents/rules/database-migrations.md` |
|
||||
| `continuous-improvement` | When to create/update rules, skills, or workflows | `.agents/rules/continuous-improvement.md` |
|
||||
| `context-and-memory` | How to orient and maintain project context between sessions | `.agents/rules/context-and-memory.md` |
|
||||
|
||||
@@ -361,3 +362,21 @@ Refer to these skill documents for specialized tasks:
|
||||
### Global Skills
|
||||
|
||||
52 skills are available across all projects. See `.agents/global-skills-index.md` for the full list and invocation paths.
|
||||
|
||||
---
|
||||
|
||||
## 15. Pull Request & Commit Guidelines
|
||||
|
||||
- **Commit Format**: We strictly enforce Conventional Commits (`feat:`, `fix:`, `refactor:`, `perf:`).
|
||||
- **Workflow**: You **MUST** use the `/commit` workflow before every git commit to ensure proper semantic versioning bumps.
|
||||
- **Required Checks**: Ensure `pnpm test` and `pnpm build` complete successfully before proposing a merge.
|
||||
- **Review Process**: Use `/pr-review` to conduct a comprehensive multi-role review on any pull request.
|
||||
|
||||
---
|
||||
|
||||
## 16. Debugging and Troubleshooting
|
||||
|
||||
- **Prisma & PostgreSQL Sync Issues**: If the local database state falls out of sync with Prisma schema, do not manually drop tables. Instead, run `pnpm db:reset` to cleanly wipe and re-apply all migrations.
|
||||
- **Cesium Entity Clipping**: If `billboard` entities are clipping or failing to render correctly, verify that you are not mixing `point` primitive properties (like `size` or `outlineWidth`) into the `billboard` options.
|
||||
- **Build Exhaustion (Docker)**: Multi-stage pnpm builds generate massive cache layers. If a Coolify deployment fails silently or PostgreSQL crashes abruptly, check host disk space and run `docker builder prune -a -f`.
|
||||
- **Next.js Typechecking Failures**: If backend-only `scripts/` fail during Next.js build, verify that the scripts directory is properly listed in the `exclude` array of `tsconfig.json`.
|
||||
+14
-8
@@ -8,7 +8,7 @@ RUN find . -type f \! -name 'package.json' \! -name 'pnpm-workspace.yaml' \! -na
|
||||
# Stage 1: Install ALL dependencies (needed for build)
|
||||
FROM node:22-alpine AS deps
|
||||
RUN npm install -g [email protected]
|
||||
RUN apk add --no-cache python3 make g++
|
||||
# python3/make/g++ no longer needed — removed better-sqlite3 native compilation
|
||||
WORKDIR /app
|
||||
# Copy only the extracted package.jsons
|
||||
COPY --from=extractor /app ./
|
||||
@@ -31,16 +31,18 @@ ARG NEXT_PUBLIC_SUPABASE_URL
|
||||
ARG NEXT_PUBLIC_SUPABASE_ANON_KEY
|
||||
|
||||
# Run our pregenerate schema swap script and then generate Prisma client
|
||||
RUN npx prisma generate
|
||||
RUN NEXT_PUBLIC_WWV_EDITION=$NEXT_PUBLIC_WWV_EDITION pnpm run generate
|
||||
|
||||
# Create an empty SQLite database with all tables applied ONLY IF NOT CLOUD
|
||||
# (For cloud, we'll run migrations against Postgres at runtime)
|
||||
RUN if [ "$NEXT_PUBLIC_WWV_EDITION" != "cloud" ]; then mkdir -p ./data && DATABASE_URL=file:./data/wwv.db npx prisma migrate deploy; fi
|
||||
# Database migrations run at container startup via docker-entrypoint.sh
|
||||
# DATABASE_URL must be set to a PostgreSQL connection string
|
||||
|
||||
# Run Next.js build with Webpack cache mounted
|
||||
RUN --mount=type=cache,target=/app/.next/cache NODE_OPTIONS="--max_old_space_size=3072" pnpm run build
|
||||
RUN node scripts/copy-cesium.mjs
|
||||
|
||||
# Deploy flattened production dependencies
|
||||
RUN pnpm --filter worldwideview deploy --prod /app/prod
|
||||
|
||||
# Stage 4: Production runner
|
||||
FROM node:22-alpine AS runner
|
||||
WORKDIR /app
|
||||
@@ -50,7 +52,8 @@ RUN apk add --no-cache openssl
|
||||
ENV NODE_ENV=production
|
||||
ENV HOSTNAME=0.0.0.0
|
||||
ENV PORT=3000
|
||||
ENV DATABASE_URL=file:./data/wwv.db
|
||||
# DATABASE_URL must be provided via environment variable (no default)
|
||||
# Example: postgresql://user:pass@host:5432/dbname
|
||||
ENV AUTH_TRUST_HOST=true
|
||||
|
||||
# Copy Prisma schema + migrations for runtime DB init
|
||||
@@ -63,6 +66,9 @@ COPY --from=builder /app/src/generated ./src/generated
|
||||
# Copy standalone server output
|
||||
COPY --from=builder /app/.next/standalone ./
|
||||
|
||||
# Copy deployed production node_modules
|
||||
COPY --from=builder /app/prod/node_modules ./node_modules
|
||||
|
||||
# We no longer copy proddeps/node_modules. Next.js standalone output
|
||||
# already traces and copies all the exact node_modules needed for production.
|
||||
|
||||
@@ -71,13 +77,13 @@ COPY --from=builder /app/.next/static ./.next/static
|
||||
COPY --from=builder /app/public ./public
|
||||
COPY --from=builder /app/scripts/https-proxy.mjs ./scripts/https-proxy.mjs
|
||||
|
||||
|
||||
# Entrypoint: migrate DB on first run, then start server
|
||||
COPY docker-entrypoint.sh ./docker-entrypoint.sh
|
||||
RUN sed -i 's/\r$//' ./docker-entrypoint.sh
|
||||
RUN chmod +x ./docker-entrypoint.sh
|
||||
|
||||
# Declare /app/data as a persistent volume mount point.
|
||||
VOLUME ["/app/data"]
|
||||
|
||||
|
||||
EXPOSE 3000 3001
|
||||
|
||||
|
||||
Binary file not shown.
@@ -21,7 +21,7 @@ WorldWideView is a real-time geospatial engine visualizing live global data on a
|
||||
- **3D Engine:** CesiumJS + Resium (Google Photorealistic 3D Tiles)
|
||||
- **State Management:** Zustand
|
||||
- **Event Bus:** Custom typed `DataBus` for high-frequency WebSocket updates
|
||||
- **Database:** SQLite via Prisma (local), PostgreSQL (cloud)
|
||||
- **Database:** PostgreSQL via Prisma 7
|
||||
- **Deployment:** Docker multi-stage build, Coolify
|
||||
|
||||
## Quick Start (Self-Hosting)
|
||||
@@ -41,7 +41,7 @@ Invoke-WebRequest -Uri https://raw.githubusercontent.com/silvertakana/worldwidev
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> Ensure you mount the `/app/data` volume to persist the SQLite database across container restarts.
|
||||
> Ensure you connect a PostgreSQL database via the `DATABASE_URL` environment variable for production deployments.
|
||||
|
||||
## Quick Start (Local Development)
|
||||
|
||||
|
||||
+3
-3
@@ -26,11 +26,11 @@ Each stage is **self-contained and demo-able**. Any stage can be shipped indepen
|
||||
---
|
||||
|
||||
## Stage 3: Prisma ORM & Local Database ✅
|
||||
**Demo:** "Run `pnpm run dev` on a fresh clone. SQLite auto-creates. App works with zero config."
|
||||
**Demo:** "Run `pnpm run dev` on a fresh clone with a valid DATABASE_URL. App works seamlessly."
|
||||
|
||||
- [x] Prisma (`prisma` + `@prisma/client`)
|
||||
- [x] Schema: `InstalledPlugin`, `Setting`, `User`, `AviationHistory`, `NpmCache`
|
||||
- [x] SQLite default: `DATABASE_URL=file:./data/wwv.db`
|
||||
- [x] PostgreSQL default: `DATABASE_URL` required
|
||||
- [x] `predev` script: `prisma migrate deploy`
|
||||
- [x] DB auto-creates on first run — zero manual setup
|
||||
|
||||
@@ -142,7 +142,7 @@ Each stage is **self-contained and demo-able**. Any stage can be shipped indepen
|
||||
| **License** | EL2.0 for WorldWideView core; Open Source for marketplace |
|
||||
| **Shared types** | `@worldwideview/plugin-sdk` npm package (MIT) |
|
||||
| **Hosting** | Coolify (ThinkPad T480s). Landing page on Vercel (static export) |
|
||||
| **Database** | Supabase PostgreSQL (cloud), SQLite (local), Prisma ORM |
|
||||
| **Database** | PostgreSQL, Prisma ORM |
|
||||
| **Tenant isolation** | Row-Level Security (RLS) in shared PostgreSQL |
|
||||
| **User settings** | Runtime settings store in DB, not `.env` |
|
||||
| **Bot prevention** | Email verification + Cloudflare Turnstile + rate limiting |
|
||||
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -0,0 +1,7 @@
|
||||
SUPABASE_PG_URL=postgresql://postgres:[email protected]:5432/postgres
|
||||
SUPABASE_URL=https://xyz.supabase.co
|
||||
SUPABASE_ANON_KEY=eyJ...
|
||||
SUPABASE_SERVICE_ROLE_KEY=eyJ...
|
||||
ACME_EMAIL=[email protected]
|
||||
STRIPE_SECRET_KEY=sk_test_...
|
||||
STRIPE_WEBHOOK_SECRET=whsec_...
|
||||
@@ -0,0 +1,47 @@
|
||||
services:
|
||||
db:
|
||||
image: postgres:15-alpine
|
||||
environment:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: password
|
||||
POSTGRES_DB: postgres
|
||||
ports:
|
||||
- "5432:5432"
|
||||
|
||||
wwv-cloud:
|
||||
build:
|
||||
context: ../..
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
- NEXT_PUBLIC_WWV_EDITION=cloud
|
||||
restart: always
|
||||
environment:
|
||||
NEXT_PUBLIC_WWV_EDITION: cloud
|
||||
DATABASE_URL: postgresql://postgres:password@db:5432/postgres
|
||||
NEXT_PUBLIC_SUPABASE_URL: ${SUPABASE_URL:-http://dummy}
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY: ${SUPABASE_ANON_KEY:-dummy}
|
||||
SUPABASE_SERVICE_ROLE_KEY: ${SUPABASE_SERVICE_ROLE_KEY:-dummy}
|
||||
AUTH_SECRET: ${AUTH_SECRET:-dummy_secret_for_local_testing_only_1234567890}
|
||||
ports:
|
||||
- "3001:3000"
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
- "traefik.http.routers.wwv.rule=HostRegexp(`{user:[a-z0-9-]+}.app.worldwideview.dev`) || Host(`app.worldwideview.dev`) || Host(`localhost`) || HostRegexp(`{user:[a-z0-9-]+}.localhost`)"
|
||||
- "traefik.http.routers.wwv.entrypoints=web,websecure"
|
||||
# - "traefik.http.routers.wwv.tls.certresolver=letsencrypt"
|
||||
- "traefik.http.services.wwv.loadbalancer.server.port=3000"
|
||||
depends_on:
|
||||
- db
|
||||
|
||||
traefik:
|
||||
image: traefik:v3.0
|
||||
command:
|
||||
- "--api.insecure=true"
|
||||
- "--providers.docker=true"
|
||||
- "--entrypoints.web.address=:80"
|
||||
- "--entrypoints.websecure.address=:443"
|
||||
ports:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
volumes:
|
||||
- "/var/run/docker.sock:/var/run/docker.sock:ro"
|
||||
@@ -12,9 +12,28 @@ services:
|
||||
- "AUTH_SECRET=${AUTH_SECRET:-default_secret_for_local_dev}"
|
||||
- "WWV_DEMO_ADMIN_SECRET=${WWV_DEMO_ADMIN_SECRET:-}"
|
||||
- "WWV_BRIDGE_TOKEN=${WWV_BRIDGE_TOKEN:-}"
|
||||
- "DATABASE_URL=${DATABASE_URL:-postgresql://postgres:postgres@db:5432/worldwideview?schema=public}"
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_started
|
||||
|
||||
db:
|
||||
image: postgres:15-alpine
|
||||
restart: always
|
||||
environment:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
POSTGRES_DB: worldwideview
|
||||
ports:
|
||||
- "5432:5432"
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql/data
|
||||
profiles:
|
||||
- "${WWV_SKIP_LOCAL_DB:-}"
|
||||
|
||||
volumes:
|
||||
wwv-data:
|
||||
postgres-data:
|
||||
|
||||
networks:
|
||||
coolify:
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
#!/bin/sh
|
||||
# ─── Docker Entrypoint ───────────────────────────────────────
|
||||
# Ensures the SQLite database exists and is migrated before
|
||||
# starting the application. On first run with a fresh volume
|
||||
# the DB file won't exist yet, so we run prisma migrate deploy.
|
||||
# Ensures the PostgreSQL database is migrated before starting
|
||||
# the application. DATABASE_URL must point to a PostgreSQL
|
||||
# instance (Supabase, self-hosted, etc).
|
||||
|
||||
set -e
|
||||
|
||||
mkdir -p ./data
|
||||
echo "[entrypoint] Running database migrations..."
|
||||
npx -y prisma migrate deploy
|
||||
echo "[entrypoint] Migrations complete."
|
||||
|
||||
|
||||
|
||||
# Generate self-signed SSL certificates for local HTTPS bridging if they don't exist
|
||||
if [ ! -f "./data/localhost.crt" ] || [ ! -f "./data/localhost.key" ]; then
|
||||
echo "[entrypoint] Generating self-signed SSL certificates for port 3001..."
|
||||
|
||||
@@ -12,7 +12,7 @@ The core design philosophy is the "All-Bundle Model," where plugins are dynamica
|
||||
- **State Management:** Zustand slice-based architecture (in `src/core/state/`).
|
||||
- **Data Pipeline:** Custom event bus (`DataBus`) and WebSocket clients (`DataBusSubscriber`) routing live data to state (in `src/core/data/`).
|
||||
- **Plugin System:** Registration, lifecycle management, and ES module loaders (in `src/core/plugins/`).
|
||||
- **Database Layer:** Prisma ORM connecting to local SQLite or cloud PostgreSQL (in `prisma/`).
|
||||
- **Database Layer:** Prisma ORM connecting to PostgreSQL (in `prisma/`).
|
||||
|
||||
## Key Files
|
||||
- `src/core/plugins/PluginManager.ts` - The PluginManager class. Core registry that instantiates plugins, calls `initialize()`, and handles lifecycle events.
|
||||
|
||||
@@ -20,7 +20,7 @@ The core build configuration resides in `package.json` and `next.config.ts`. A c
|
||||
|
||||
## Platform Setup
|
||||
|
||||
- **Database Migrations:** Prisma schema is located at `prisma/schema.prisma`. During development, `pnpm dev` triggers a `predev` hook running `npx prisma migrate deploy` to ensure SQLite tables exist in `data/wwv.db`.
|
||||
- **Database Migrations:** Prisma schema is located at `prisma/schema.prisma`. During development, `pnpm dev` triggers a `predev` hook running `npx prisma migrate deploy` to ensure PostgreSQL tables are initialized.
|
||||
- **Microservices:** Data engine seeders and standalone Fastify backend plugins (like `wwv-plugin-iranwarlive/backend`) are started via `pnpm start:backends` and managed locally inside `packages/*/backend`.
|
||||
- **Plugin Packages:** Internal plugin packages must be properly listed in `tsconfig.json` paths and `next.config.ts`'s `transpilePackages` array.
|
||||
|
||||
|
||||
+3
-3
@@ -18,7 +18,7 @@ WorldWideView utilizes a containerized deployment strategy based on Docker's mul
|
||||
### Coolify Integration
|
||||
WorldWideView deploys optimally to Coolify using a Dockerfile builder.
|
||||
- **Environment Variables:** Must be explicitly mapped in the Coolify UI (e.g., `DATABASE_URL`, `AUTH_SECRET`).
|
||||
- **Persistent Storage:** SQLite requires a persistent volume mounted to `/app/data` to ensure the frontend registry (installed plugins, user configs) survives container rebuilds.
|
||||
- **Persistent Storage:** PostgreSQL databases must be hosted externally or mounted via persistent volumes to ensure the frontend registry (installed plugins, user configs) survives container rebuilds.
|
||||
- **Microservices Deployment:** The `wwv-data-engine-internal` and associated plugin seeders are deployed as separate Coolify services communicating over private internal networks.
|
||||
|
||||
### Docker Structure
|
||||
@@ -29,6 +29,6 @@ WorldWideView deploys optimally to Coolify using a Dockerfile builder.
|
||||
- **Standalone Config:** `next.config.ts` (sets `output: "standalone"`).
|
||||
- **Prisma Export:** `prisma.config.ts` ensures no CLI wrappers are invoked inside the standalone container, preventing fatal `MODULE_NOT_FOUND` runtime crashes.
|
||||
- **Docker Mounts:**
|
||||
- Main App: `/app/data` (SQLite DB)
|
||||
- Data Engine: `/app/packages/wwv-data-engine/data` (SQLite DB)
|
||||
- Main App: PostgreSQL data volume (if running in-cluster)
|
||||
- Data Engine: PostgreSQL data volume (if running in-cluster)
|
||||
- Cache: `/data` (Redis)
|
||||
+1
-1
@@ -24,7 +24,7 @@ The system is highly modularized to separate React UI rendering from heavy Cesiu
|
||||
- `docker-compose.yml` - Defines the orchestration of the frontend, Redis cache, and all local plugin microservice backends (`wwv-data-engine`).
|
||||
|
||||
## Configuration
|
||||
- `prisma/schema.prisma` - Local SQLite and cloud PostgreSQL database schema for storing user settings and installed plugin manifests.
|
||||
- `prisma/schema.prisma` - PostgreSQL database schema for storing user settings and installed plugin manifests.
|
||||
- `scripts/copy-cesium.mjs` - Crucial build-time script that extracts and copies CesiumJS static web workers to `public/cesium/`.
|
||||
- `public/` - Static assets, plugin icons, and compiled Cesium workers.
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ The core value proposition of WorldWideView is mapping diverse, decoupled intell
|
||||
- **3D Engine:** CesiumJS + Resium (Google Photorealistic 3D Tiles) — `src/core/globe/GlobeView.tsx`
|
||||
- **State Management:** Zustand — `src/core/state/` (slice-based store)
|
||||
- **Event Bus:** Custom typed `DataBus` — `src/core/data/DataBus.ts`
|
||||
- **Database:** SQLite via Prisma (local), PostgreSQL (cloud) — `prisma/schema.prisma`
|
||||
- **Database:** PostgreSQL via Prisma 7 — `prisma/schema.prisma`
|
||||
- **Styling:** Vanilla CSS (no Tailwind) — `src/app/globals.css`
|
||||
|
||||
## Platform Support
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
# Persistent Custom OSM Tags Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Allow users to persistently save custom OSM tags to local storage so they remain available across sessions, and track their usage via Umami analytics.
|
||||
|
||||
**Architecture:** We will use `useState` and `useEffect` in the `OSMSidebar` component to sync `customTags` to the browser's `localStorage`. When the user enters a custom tag, we'll store it, render it with a small delete button (so the list doesn't get cluttered over time), and fire an event to `window.umami.track`.
|
||||
|
||||
**Tech Stack:** React Hooks, `localStorage`, Umami Analytics
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Add Custom Tag State and Persistence
|
||||
|
||||
**Files:**
|
||||
- Modify: `c:\dev\worldwideview-plugins\packages\wwv-plugin-osm-search\src\components\OSMSidebar.tsx`
|
||||
|
||||
- [ ] **Step 1: Add customTags state and persistence effects**
|
||||
|
||||
In `OSMSidebar.tsx`, below the existing `const [activeTags, setActiveTags] = useState<string[]>([]);` line, add:
|
||||
|
||||
```tsx
|
||||
const [customTags, setCustomTags] = useState<string[]>([]);
|
||||
|
||||
React.useEffect(() => {
|
||||
try {
|
||||
const saved = localStorage.getItem("wwv_osm_custom_tags");
|
||||
if (saved) setCustomTags(JSON.parse(saved));
|
||||
} catch {}
|
||||
}, []);
|
||||
|
||||
React.useEffect(() => {
|
||||
localStorage.setItem("wwv_osm_custom_tags", JSON.stringify(customTags));
|
||||
}, [customTags]);
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Include customTags in the rendered list**
|
||||
|
||||
Replace `const customTagMatch = searchText.includes("=") ? [searchText.trim()] : [];` and `const renderedTags = ...` with:
|
||||
|
||||
```tsx
|
||||
const renderedTags = Array.from(new Set([...filteredCommon, ...dynamicTags, ...customTags]));
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Update Enter key handler to save tags and track**
|
||||
|
||||
Inside the `input`'s `onKeyDown` handler:
|
||||
|
||||
```tsx
|
||||
onKeyDown={e => {
|
||||
if (e.key === "Enter" && searchText.includes("=")) {
|
||||
const tag = searchText.trim();
|
||||
if (!activeTags.includes(tag)) {
|
||||
setActiveTags(prev => [...prev, tag]);
|
||||
}
|
||||
if (!customTags.includes(tag)) {
|
||||
setCustomTags(prev => [...prev, tag]);
|
||||
try {
|
||||
(window as any).umami?.track("osm-search-custom-tag", { tag });
|
||||
} catch {}
|
||||
}
|
||||
setSearchText("");
|
||||
}
|
||||
}}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Add a delete button to custom tags**
|
||||
|
||||
Inside the `.map(tag => {` block, update the `button` contents to include a delete span if it's a custom tag:
|
||||
|
||||
```tsx
|
||||
<button
|
||||
key={tag}
|
||||
style={{
|
||||
background: isActive ? "var(--accent-blue)" : "rgba(255,255,255,0.05)",
|
||||
color: isActive ? "#fff" : "var(--text-secondary)",
|
||||
padding: "4px 10px",
|
||||
borderRadius: "14px",
|
||||
border: `1px solid ${isActive ? "transparent" : "rgba(255,255,255,0.1)"}`,
|
||||
fontSize: "11px",
|
||||
cursor: "pointer",
|
||||
transition: "all 0.2s",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "4px"
|
||||
}}
|
||||
onClick={() => setActiveTags(prev => prev.includes(tag) ? prev.filter(t=>t!==tag) : [...prev, tag])}
|
||||
>
|
||||
{tag.replace("=", ": ")}
|
||||
{customTags.includes(tag) && (
|
||||
<span
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setCustomTags(prev => prev.filter(t => t !== tag));
|
||||
setActiveTags(prev => prev.filter(t => t !== tag));
|
||||
}}
|
||||
style={{
|
||||
marginLeft: "2px",
|
||||
padding: "0 4px",
|
||||
borderRadius: "50%",
|
||||
background: "rgba(255,255,255,0.15)",
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
alignItems: "center"
|
||||
}}
|
||||
>
|
||||
×
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Commit changes**
|
||||
|
||||
```bash
|
||||
git add packages/wwv-plugin-osm-search/src/components/OSMSidebar.tsx
|
||||
git commit -m "feat(osm-search): persist custom tags and track via umami"
|
||||
```
|
||||
@@ -0,0 +1,132 @@
|
||||
# Robust Plugin Linking Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Ensure that when developers link local plugins using `wwv-cli link`, the main engine's database is automatically updated to prioritize the local code instead of accidentally loading the published version from the cloud CDN.
|
||||
|
||||
**Architecture:** We will implement a dedicated development API route in the main app (`/api/plugins/dev-link`) that allows the `wwv-cli` to safely push local plugin manifests directly into the `InstalledPlugin` database table without requiring Marketplace authentication. The CLI will be updated to make this request immediately after copying the bundle.
|
||||
|
||||
**Tech Stack:** Next.js API Routes, Prisma, Node.js `fetch`
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Create the Dev-Link API Route
|
||||
|
||||
**Files:**
|
||||
- Create: `c:\dev\worldwideview\src\app\api\plugins\dev-link\route.ts`
|
||||
|
||||
- [ ] **Step 1: Write the API Route**
|
||||
|
||||
```typescript
|
||||
import { NextResponse } from "next/server";
|
||||
import { upsertPlugin } from "@/lib/marketplace/repository";
|
||||
import { validateManifest } from "@/core/plugins/validateManifest";
|
||||
import { isPluginInstallEnabled } from "@/core/edition";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
// 1. Security Check: Only allow in development mode or local editions
|
||||
if (process.env.NODE_ENV !== "development" && !isPluginInstallEnabled) {
|
||||
return NextResponse.json({ error: "Dev-link is only available in development environments" }, { status: 403 });
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { manifest } = body;
|
||||
|
||||
if (!manifest || !manifest.id) {
|
||||
return NextResponse.json({ error: "Invalid payload. 'manifest' with an 'id' is required." }, { status: 400 });
|
||||
}
|
||||
|
||||
// 2. Validate the manifest
|
||||
const validation = validateManifest(manifest);
|
||||
if (!validation.valid) {
|
||||
console.error(`[Dev-Link] Invalid manifest for ${manifest.id}:`, validation.errors);
|
||||
return NextResponse.json({ error: "Invalid manifest", details: validation.errors }, { status: 400 });
|
||||
}
|
||||
|
||||
// 3. Upsert into database
|
||||
const config = JSON.stringify(manifest);
|
||||
const record = await upsertPlugin(manifest.id, manifest.version || "1.0.0", config);
|
||||
|
||||
console.log(`[Dev-Link] Successfully synced local plugin config for: ${manifest.id}`);
|
||||
|
||||
return NextResponse.json({ success: true, pluginId: record.pluginId });
|
||||
} catch (err) {
|
||||
console.error("[Dev-Link] Server Error:", err);
|
||||
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Commit API Route**
|
||||
|
||||
```bash
|
||||
git add src/app/api/plugins/dev-link/route.ts
|
||||
git commit -m "feat(api): add dev-link route to sync local plugin manifests"
|
||||
```
|
||||
|
||||
### Task 2: Update the CLI Link Command
|
||||
|
||||
**Files:**
|
||||
- Modify: `c:\dev\worldwideview-plugins\packages\wwv-cli\src\commands\link.ts`
|
||||
|
||||
- [ ] **Step 1: Add the sync request to linkCommand**
|
||||
|
||||
Find the `linkCommand` function. Below the `fs.writeFileSync` that writes `plugin.json` (around line 67), add a network request to sync the database.
|
||||
|
||||
```typescript
|
||||
fs.writeFileSync(path.join(finalDestDir, 'plugin.json'), JSON.stringify(manifest, null, 2));
|
||||
console.log(green(`✅ Proxy manifest injected to WWV instance: ${pluginId}`));
|
||||
|
||||
// --- NEW CODE: Sync with database ---
|
||||
fetch('http://localhost:3000/api/plugins/dev-link', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ manifest })
|
||||
})
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
console.log(green(`✅ Database successfully synced to point to local files.`));
|
||||
} else {
|
||||
console.log(red(`⚠️ Warning: Database sync failed: ${data.error}`));
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
console.log(red(`⚠️ Warning: Could not reach dev server to sync DB. Is localhost:3000 running?`));
|
||||
});
|
||||
// --- END NEW CODE ---
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Rebuild the CLI**
|
||||
|
||||
```bash
|
||||
cd packages/wwv-cli
|
||||
pnpm build
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Commit CLI Update**
|
||||
|
||||
```bash
|
||||
git add packages/wwv-cli/src/commands/link.ts
|
||||
git commit -m "feat(cli): auto-sync local plugin manifests with engine database during link"
|
||||
```
|
||||
|
||||
### Task 3: Test the Integration
|
||||
|
||||
- [ ] **Step 1: Run the Sync Command**
|
||||
|
||||
Run the updated sync command in the plugins repo to verify it pushes the manifest properly to the API.
|
||||
|
||||
```bash
|
||||
cd c:\dev\worldwideview-plugins
|
||||
pnpm run sync:all
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Verify Output**
|
||||
|
||||
Expected output in the plugins terminal should include:
|
||||
`[wwv-plugin-osm-search] ✅ Database successfully synced to point to local files.`
|
||||
|
||||
Expected output in the main WorldWideView terminal should include:
|
||||
`[Dev-Link] Successfully synced local plugin config for: osm-search`
|
||||
@@ -0,0 +1,105 @@
|
||||
# Phase 1: Database Adapter Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Modify Prisma schema and client initialization to support both SQLite (local/demo) and PostgreSQL (cloud).
|
||||
|
||||
**Architecture:** We use a pre-generation script to swap the Prisma provider based on `NEXT_PUBLIC_WWV_EDITION`. Abstract `src/lib/db.ts` to inject the correct adapter (better-sqlite3 vs pg) based on the edition.
|
||||
|
||||
**Tech Stack:** Prisma, PostgreSQL, SQLite.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Create Schema Swap Script
|
||||
|
||||
**Files:**
|
||||
- Create: `scripts/prepare-schema.mjs`
|
||||
- Modify: `package.json`
|
||||
|
||||
- [ ] **Step 1: Create a schema swap script**
|
||||
|
||||
```javascript
|
||||
// scripts/prepare-schema.mjs
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
const schemaPath = path.join(process.cwd(), 'prisma', 'schema.prisma');
|
||||
let schema = fs.readFileSync(schemaPath, 'utf-8');
|
||||
|
||||
if (process.env.NEXT_PUBLIC_WWV_EDITION === 'cloud') {
|
||||
schema = schema.replace(/provider\s*=\s*"sqlite"/, 'provider = "postgresql"');
|
||||
console.log("Swapped Prisma provider to PostgreSQL for cloud edition.");
|
||||
} else {
|
||||
// Revert back to sqlite just in case it was swapped
|
||||
schema = schema.replace(/provider\s*=\s*"postgresql"/, 'provider = "sqlite"');
|
||||
}
|
||||
|
||||
fs.writeFileSync(schemaPath, schema);
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Update package.json scripts**
|
||||
|
||||
Modify `package.json` to run the prepare script before prisma generate:
|
||||
```json
|
||||
"pregenerate": "node scripts/prepare-schema.mjs",
|
||||
"generate": "prisma generate"
|
||||
```
|
||||
|
||||
### Task 2: Create DB Adapter Factory
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/lib/db.ts`
|
||||
- Create: `src/core/adapters/db.ts`
|
||||
|
||||
- [ ] **Step 1: Create the adapter factory**
|
||||
|
||||
```typescript
|
||||
// src/core/adapters/db.ts
|
||||
import { isCloud } from "@/core/edition";
|
||||
import { PrismaClient } from "../../generated/prisma/client";
|
||||
|
||||
export function createPrismaClient(): PrismaClient {
|
||||
if (isCloud) {
|
||||
// Cloud uses native pg driver or connection pool via standard url
|
||||
return new PrismaClient({
|
||||
datasources: {
|
||||
db: {
|
||||
url: process.env.DATABASE_URL,
|
||||
},
|
||||
},
|
||||
});
|
||||
} else {
|
||||
// Local uses better-sqlite3 adapter (already set up)
|
||||
const { PrismaBetterSqlite3 } = require("@prisma/adapter-better-sqlite3");
|
||||
const adapter = new PrismaBetterSqlite3({
|
||||
url: process.env.DATABASE_URL || "file:./data/wwv.db",
|
||||
});
|
||||
return new PrismaClient({ adapter });
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Refactor `src/lib/db.ts`**
|
||||
|
||||
```typescript
|
||||
// src/lib/db.ts
|
||||
import { PrismaClient } from "../generated/prisma/client";
|
||||
import { createPrismaClient } from "@/core/adapters/db";
|
||||
|
||||
const globalForPrisma = globalThis as unknown as {
|
||||
prisma: PrismaClient | undefined;
|
||||
};
|
||||
|
||||
export const prisma = globalForPrisma.prisma ?? createPrismaClient();
|
||||
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
globalForPrisma.prisma = prisma;
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add package.json scripts/ src/lib/ src/core/adapters/
|
||||
git commit -m "feat: multi-provider database adapter for cloud"
|
||||
```
|
||||
@@ -0,0 +1,152 @@
|
||||
# Phase 2: Tenant System Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Implement single-container multi-tenancy using PostgreSQL Row-Level Security (RLS) and Next.js middleware to resolve subdomains.
|
||||
|
||||
**Architecture:** Middleware extracts the subdomain (e.g., `acme.app.worldwideview.dev`) and sets an `x-tenant-id` header. Prisma extension wraps all queries to `SET LOCAL app.tenant_id = '...'` to enforce RLS in PostgreSQL.
|
||||
|
||||
**Tech Stack:** Next.js Middleware, Prisma Client Extensions, PostgreSQL RLS.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Database Schema Tenant Column
|
||||
|
||||
**Files:**
|
||||
- Modify: `prisma/schema.prisma`
|
||||
|
||||
- [ ] **Step 1: Add tenant columns to models**
|
||||
|
||||
Add `tenantId String?` to all relevant models (`InstalledPlugin`, `Favorite`, `Setting`).
|
||||
For local SQLite, `tenantId` is ignored (null). For cloud, it's enforced via RLS.
|
||||
|
||||
```prisma
|
||||
model InstalledPlugin {
|
||||
id String @id @default(uuid())
|
||||
tenantId String? // NULL for local, UUID for cloud
|
||||
pluginId String
|
||||
version String
|
||||
config String @default("{}")
|
||||
enabled Boolean @default(true)
|
||||
installedAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([tenantId, pluginId]) // Replaces @@unique([pluginId])
|
||||
@@map("installed_plugins")
|
||||
}
|
||||
|
||||
model Setting {
|
||||
id String @id @default(uuid())
|
||||
tenantId String?
|
||||
key String
|
||||
value String
|
||||
|
||||
@@unique([tenantId, key])
|
||||
@@map("settings")
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Update primary keys if needed**
|
||||
|
||||
Ensure `Setting` uses `id` as `@id` instead of `key` since `key` is no longer globally unique (it's unique per tenant).
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add prisma/schema.prisma
|
||||
git commit -m "feat: add tenantId columns to schema"
|
||||
```
|
||||
|
||||
### Task 2: Subdomain Middleware
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/middleware.ts` (or create if doesn't exist)
|
||||
|
||||
- [ ] **Step 1: Create Next.js middleware**
|
||||
|
||||
```typescript
|
||||
// src/middleware.ts
|
||||
import { NextResponse } from "next/server";
|
||||
import type { NextRequest } from "next/server";
|
||||
|
||||
export function middleware(req: NextRequest) {
|
||||
const hostname = req.headers.get("host") || "";
|
||||
|
||||
// Extract subdomain if on cloud
|
||||
if (process.env.NEXT_PUBLIC_WWV_EDITION === "cloud") {
|
||||
const isApp = hostname.includes(".app.worldwideview.dev");
|
||||
if (isApp) {
|
||||
const subdomain = hostname.replace(".app.worldwideview.dev", "");
|
||||
if (subdomain && subdomain !== "app") {
|
||||
const res = NextResponse.next();
|
||||
res.headers.set("x-tenant-subdomain", subdomain);
|
||||
return res;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: ["/((?!api/auth|_next/static|_next/image|favicon.ico).*)"],
|
||||
};
|
||||
```
|
||||
|
||||
### Task 3: Prisma RLS Extension
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/core/adapters/db.ts`
|
||||
|
||||
- [ ] **Step 1: Wrap Prisma with RLS extension for Cloud**
|
||||
|
||||
Modify `createPrismaClient` to wrap the client if in cloud mode:
|
||||
|
||||
```typescript
|
||||
// src/core/adapters/db.ts
|
||||
import { isCloud } from "@/core/edition";
|
||||
import { PrismaClient } from "../../generated/prisma/client";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
export function createPrismaClient() {
|
||||
if (isCloud) {
|
||||
const client = new PrismaClient({
|
||||
datasources: { db: { url: process.env.DATABASE_URL } },
|
||||
});
|
||||
|
||||
// Use Prisma Client Extension to inject RLS
|
||||
return client.$extends({
|
||||
query: {
|
||||
$allModels: {
|
||||
async $allOperations({ args, query }) {
|
||||
const headersList = await headers();
|
||||
const tenantSubdomain = headersList.get("x-tenant-subdomain");
|
||||
|
||||
if (tenantSubdomain) {
|
||||
const [, result] = await client.$transaction([
|
||||
client.$executeRaw`SELECT set_config('app.tenant_id', ${tenantSubdomain}, TRUE)`,
|
||||
query(args),
|
||||
]);
|
||||
return result;
|
||||
}
|
||||
return query(args);
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const { PrismaBetterSqlite3 } = require("@prisma/adapter-better-sqlite3");
|
||||
const adapter = new PrismaBetterSqlite3({
|
||||
url: process.env.DATABASE_URL || "file:./data/wwv.db",
|
||||
});
|
||||
return new PrismaClient({ adapter });
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Commit**
|
||||
|
||||
```bash
|
||||
git add src/middleware.ts src/core/adapters/db.ts
|
||||
git commit -m "feat: multi-tenant middleware and RLS prisma extension"
|
||||
```
|
||||
@@ -0,0 +1,117 @@
|
||||
# Phase 3: Auth Upgrade Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Integrate Supabase Auth for the cloud edition while maintaining the existing Credentials provider for the local edition.
|
||||
|
||||
**Architecture:** Use the NextAuth adapter pattern. Modify `src/lib/auth.ts` to dynamically include the Supabase provider and Supabase Adapter if `isCloud` is true.
|
||||
|
||||
**Tech Stack:** NextAuth v5, Supabase Auth.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Supabase Adapter Integration
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/lib/auth.ts`
|
||||
- Modify: `package.json`
|
||||
|
||||
- [ ] **Step 1: Install Supabase NextAuth Adapter**
|
||||
|
||||
Run: `pnpm add @auth/supabase-adapter`
|
||||
|
||||
- [ ] **Step 2: Update `src/lib/auth.ts` to branch providers**
|
||||
|
||||
```typescript
|
||||
// src/lib/auth.ts
|
||||
import NextAuth from "next-auth";
|
||||
import Credentials from "next-auth/providers/credentials";
|
||||
import { compareSync } from "bcryptjs";
|
||||
import { timingSafeEqual } from "crypto";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { isDemo, isCloud, getDemoAdminSecret, DEMO_ADMIN_ROLE } from "@/core/edition";
|
||||
import { authConfig } from "@/lib/auth.config";
|
||||
import { SupabaseAdapter } from "@auth/supabase-adapter";
|
||||
|
||||
// Extract local credentials logic to a helper
|
||||
const localCredentialsProvider = Credentials({
|
||||
credentials: {
|
||||
email: { label: "Email", type: "email" },
|
||||
password: { label: "Password", type: "password" },
|
||||
},
|
||||
async authorize(credentials) {
|
||||
// ... existing credentials logic ...
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
...authConfig,
|
||||
session: { strategy: "jwt" },
|
||||
adapter: isCloud ? SupabaseAdapter({
|
||||
url: process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
||||
secret: process.env.SUPABASE_SERVICE_ROLE_KEY!,
|
||||
}) : undefined,
|
||||
providers: isCloud
|
||||
? [] // If using standard GoTrue via custom logic, or add providers here if using NextAuth OAuth
|
||||
: [localCredentialsProvider],
|
||||
callbacks: {
|
||||
...authConfig.callbacks,
|
||||
// ... existing callbacks ...
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Task 2: Login Form Cloud Adaptation
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/app/login/page.tsx`
|
||||
- Modify: `src/app/login/actions.ts`
|
||||
|
||||
- [ ] **Step 1: Update Login Form for Cloud Mode**
|
||||
|
||||
```typescript
|
||||
// src/app/login/actions.ts
|
||||
import { signIn } from "@/lib/auth";
|
||||
import { isCloud } from "@/core/edition";
|
||||
import { createClient } from "@supabase/supabase-js";
|
||||
|
||||
export async function loginAction(formData: FormData) {
|
||||
const email = formData.get("email") as string;
|
||||
const password = formData.get("password") as string;
|
||||
|
||||
if (isCloud) {
|
||||
// Use Supabase GoTrue
|
||||
const supabase = createClient(
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
|
||||
);
|
||||
const { data, error } = await supabase.auth.signInWithPassword({
|
||||
email,
|
||||
password,
|
||||
});
|
||||
|
||||
if (error) return { success: false, error: error.message };
|
||||
return { success: true };
|
||||
} else {
|
||||
// Use NextAuth Credentials
|
||||
try {
|
||||
await signIn("credentials", {
|
||||
email,
|
||||
password,
|
||||
redirect: false,
|
||||
});
|
||||
return { success: true };
|
||||
} catch (error: any) {
|
||||
return { success: false, error: "Invalid credentials" };
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Commit**
|
||||
|
||||
```bash
|
||||
git add package.json pnpm-lock.yaml src/lib/auth.ts src/app/login/actions.ts
|
||||
git commit -m "feat: supabase auth adapter for cloud edition"
|
||||
```
|
||||
@@ -0,0 +1,99 @@
|
||||
# Phase 4: License Keys & Tiers Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Implement RSA-signed JWT license keys to gate Pro and Enterprise features on both Local and Cloud editions.
|
||||
|
||||
**Architecture:** A hardcoded public key verifies the JWT. The JWT payload dictates the tier (`free`, `pro`, `enterprise`) and expiration. The `uiSlice` state provides easy access to the active tier.
|
||||
|
||||
**Tech Stack:** `jose` for JWT verification.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: License Verification Module
|
||||
|
||||
**Files:**
|
||||
- Create: `src/core/license/verifyLicense.ts`
|
||||
- Create: `src/core/license/tiers.ts`
|
||||
|
||||
- [ ] **Step 1: Create Tier Definitions**
|
||||
|
||||
```typescript
|
||||
// src/core/license/tiers.ts
|
||||
export type LicenseTier = "free" | "pro" | "team" | "enterprise";
|
||||
|
||||
export interface TierFeatures {
|
||||
maxUsers: number;
|
||||
storageQuotaBytes: number;
|
||||
historyEnabled: boolean;
|
||||
snapshotCapture: boolean;
|
||||
customDomains: boolean;
|
||||
}
|
||||
|
||||
export const TIER_FEATURES: Record<LicenseTier, TierFeatures> = {
|
||||
free: { maxUsers: 3, storageQuotaBytes: 500 * 1024 * 1024, historyEnabled: false, snapshotCapture: false, customDomains: false },
|
||||
pro: { maxUsers: 20, storageQuotaBytes: 5 * 1024 * 1024 * 1024, historyEnabled: true, snapshotCapture: true, customDomains: false },
|
||||
team: { maxUsers: -1, storageQuotaBytes: -1, historyEnabled: true, snapshotCapture: true, customDomains: false },
|
||||
enterprise: { maxUsers: -1, storageQuotaBytes: -1, historyEnabled: true, snapshotCapture: true, customDomains: true },
|
||||
};
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Create JWT Verification**
|
||||
|
||||
```typescript
|
||||
// src/core/license/verifyLicense.ts
|
||||
import * as jose from "jose";
|
||||
|
||||
// Public key is safe to hardcode/ship to client
|
||||
const PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
|
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu... (generate real one)
|
||||
-----END PUBLIC KEY-----`;
|
||||
|
||||
export interface LicensePayload {
|
||||
tier: "pro" | "team" | "enterprise";
|
||||
exp: number;
|
||||
org: string;
|
||||
}
|
||||
|
||||
export async function verifyLicenseKey(token: string): Promise<LicensePayload | null> {
|
||||
try {
|
||||
const publicKey = await jose.importSPKI(PUBLIC_KEY_PEM, "RS256");
|
||||
const { payload } = await jose.jwtVerify(token, publicKey);
|
||||
return payload as unknown as LicensePayload;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Task 2: State Integration
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/core/state/configSlice.ts`
|
||||
- Modify: `src/components/panels/SettingsPanel.tsx`
|
||||
|
||||
- [ ] **Step 1: Add license to configSlice**
|
||||
|
||||
```typescript
|
||||
// src/core/state/configSlice.ts
|
||||
// Add to DataConfig:
|
||||
export interface DataConfig {
|
||||
// ... existing ...
|
||||
licenseKey: string | null;
|
||||
activeTier: "free" | "pro" | "team" | "enterprise";
|
||||
}
|
||||
|
||||
// Add to initial state:
|
||||
// licenseKey: null, activeTier: "free"
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add License input UI**
|
||||
|
||||
Add a text input in `SettingsPanel` for users to paste their license key, dispatching an action to verify and save it to the DB and Zustand store.
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add src/core/license/ src/core/state/configSlice.ts src/components/panels/
|
||||
git commit -m "feat: rsa jwt license key verification"
|
||||
```
|
||||
@@ -0,0 +1,76 @@
|
||||
# Phase 5: Cloud Deployment Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Create the Docker Compose configuration and routing layer necessary to run the multi-tenant cloud application.
|
||||
|
||||
**Architecture:** Use Traefik or nginx to route wildcard subdomains to the Next.js container. Provide environment variable overrides.
|
||||
|
||||
**Tech Stack:** Docker Compose, Traefik.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Docker Compose Setup
|
||||
|
||||
**Files:**
|
||||
- Create: `deploy/cloud/docker-compose.yml`
|
||||
- Create: `deploy/cloud/.env.example`
|
||||
|
||||
- [ ] **Step 1: Create compose file**
|
||||
|
||||
```yaml
|
||||
# deploy/cloud/docker-compose.yml
|
||||
services:
|
||||
wwv-cloud:
|
||||
image: ghcr.io/silvertakana/worldwideview:latest
|
||||
restart: always
|
||||
environment:
|
||||
NEXT_PUBLIC_WWV_EDITION: cloud
|
||||
DATABASE_URL: ${SUPABASE_PG_URL}
|
||||
NEXT_PUBLIC_SUPABASE_URL: ${SUPABASE_URL}
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY: ${SUPABASE_ANON_KEY}
|
||||
SUPABASE_SERVICE_ROLE_KEY: ${SUPABASE_SERVICE_ROLE_KEY}
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
- "traefik.http.routers.wwv.rule=HostRegexp(`{user:[a-z0-9-]+}.app.worldwideview.dev`) || Host(`app.worldwideview.dev`)"
|
||||
- "traefik.http.routers.wwv.entrypoints=websecure"
|
||||
- "traefik.http.routers.wwv.tls.certresolver=letsencrypt"
|
||||
|
||||
traefik:
|
||||
image: traefik:v3.0
|
||||
command:
|
||||
- "--api.insecure=true"
|
||||
- "--providers.docker=true"
|
||||
- "--entrypoints.web.address=:80"
|
||||
- "--entrypoints.websecure.address=:443"
|
||||
- "--certificatesresolvers.letsencrypt.acme.tlschallenge=true"
|
||||
- "--certificatesresolvers.letsencrypt.acme.email=${ACME_EMAIL}"
|
||||
- "--certificatesresolvers.letsencrypt.acme.storage=/letsencrypt/acme.json"
|
||||
ports:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
volumes:
|
||||
- "/var/run/docker.sock:/var/run/docker.sock:ro"
|
||||
- "letsencrypt:/letsencrypt"
|
||||
|
||||
volumes:
|
||||
letsencrypt:
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Create example env file**
|
||||
|
||||
```env
|
||||
# deploy/cloud/.env.example
|
||||
SUPABASE_PG_URL=postgresql://postgres:[email protected]:5432/postgres
|
||||
SUPABASE_URL=https://xyz.supabase.co
|
||||
SUPABASE_ANON_KEY=eyJ...
|
||||
SUPABASE_SERVICE_ROLE_KEY=eyJ...
|
||||
ACME_EMAIL=[email protected]
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add deploy/
|
||||
git commit -m "chore: add cloud deployment compose configuration"
|
||||
```
|
||||
@@ -0,0 +1,77 @@
|
||||
# Phase 6: Stripe Billing Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Implement Stripe subscriptions for the cloud edition, generating license keys upon payment.
|
||||
|
||||
**Architecture:** Use Stripe Checkout Sessions for upgrades. Use Stripe Webhooks to listen for `checkout.session.completed` and `customer.subscription.updated` to update the user's tier in the database and generate their JWT license key.
|
||||
|
||||
**Tech Stack:** Stripe Node SDK, Next.js API Routes.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Stripe Integration
|
||||
|
||||
**Files:**
|
||||
- Modify: `package.json`
|
||||
- Create: `src/lib/stripe/client.ts`
|
||||
- Create: `src/app/api/billing/webhook/route.ts`
|
||||
- Create: `src/app/api/billing/checkout/route.ts`
|
||||
|
||||
- [ ] **Step 1: Install SDK**
|
||||
|
||||
Run: `pnpm add stripe`
|
||||
|
||||
- [ ] **Step 2: Create Stripe Client**
|
||||
|
||||
```typescript
|
||||
// src/lib/stripe/client.ts
|
||||
import Stripe from "stripe";
|
||||
|
||||
export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
|
||||
apiVersion: "2024-04-10",
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Create Checkout Route**
|
||||
|
||||
```typescript
|
||||
// src/app/api/billing/checkout/route.ts
|
||||
import { stripe } from "@/lib/stripe/client";
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "@/lib/auth";
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const session = await auth();
|
||||
if (!session?.user) return new NextResponse("Unauthorized", { status: 401 });
|
||||
|
||||
const { priceId } = await req.json();
|
||||
|
||||
const checkoutSession = await stripe.checkout.sessions.create({
|
||||
mode: "subscription",
|
||||
payment_method_types: ["card"],
|
||||
line_items: [{ price: priceId, quantity: 1 }],
|
||||
success_url: `${process.env.NEXT_PUBLIC_APP_URL}/settings?success=true`,
|
||||
cancel_url: `${process.env.NEXT_PUBLIC_APP_URL}/settings?canceled=true`,
|
||||
client_reference_id: session.user.id,
|
||||
});
|
||||
|
||||
return NextResponse.json({ url: checkoutSession.url });
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Create Webhook Handler**
|
||||
|
||||
```typescript
|
||||
// src/app/api/billing/webhook/route.ts
|
||||
import { stripe } from "@/lib/stripe/client";
|
||||
import { NextResponse } from "next/server";
|
||||
// ... basic webhook payload verification and logging ...
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add package.json pnpm-lock.yaml src/lib/stripe/ src/app/api/billing/
|
||||
git commit -m "feat: stripe checkout and webhook integration"
|
||||
```
|
||||
@@ -0,0 +1,51 @@
|
||||
# Cloud Hosting & Plans — Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Transform WorldWideView from a local-only SQLite app into a multi-tenant cloud platform with `[user].app.worldwideview.dev` subdomains, PostgreSQL RLS isolation, Supabase Auth, cryptographic license keys, and Stripe billing.
|
||||
|
||||
**Architecture:** Single Docker container serves all tenants. nginx wildcard routes `*.app.worldwideview.dev` → Next.js. Middleware reads subdomain → sets `tenant_id` → PostgreSQL RLS scopes all queries. Same codebase, three editions (`local`/`cloud`/`demo`), adapter pattern for DB/auth/storage/tenant.
|
||||
|
||||
**Tech Stack:** Next.js 16, Prisma (multi-provider), PostgreSQL + RLS, Supabase Auth, Supabase Storage, RSA-signed JWTs (license keys), Stripe Checkout + Webhooks, nginx wildcard SSL.
|
||||
|
||||
---
|
||||
|
||||
## Current State Summary
|
||||
|
||||
| Component | Status |
|
||||
|---|---|
|
||||
| Edition system (`edition.ts`) | ✅ `local`/`cloud`/`demo` flags exist |
|
||||
| Auth (`src/lib/auth.ts`) | ✅ Credentials provider (bcrypt + SQLite) |
|
||||
| Database (`src/lib/db.ts`) | ⚠️ Hardcoded to `better-sqlite3` adapter |
|
||||
| Prisma schema | ⚠️ `provider = "sqlite"` only |
|
||||
| Tenant isolation | ❌ Not implemented |
|
||||
| Cloud auth (Supabase) | ❌ Not implemented |
|
||||
| License keys | ❌ Not implemented |
|
||||
| Storage adapter | ❌ Not implemented |
|
||||
| Stripe billing | ❌ Not implemented |
|
||||
| Cloud deployment repo | ❌ Not created |
|
||||
|
||||
---
|
||||
|
||||
## Phase Breakdown
|
||||
|
||||
Each phase is a self-contained deliverable. Phases 1–3 are foundational. Phases 4–6 add monetization.
|
||||
|
||||
| Phase | File | What It Builds | Depends On |
|
||||
|---|---|---|---|
|
||||
| 1 | [01-database-adapter.md](./01-database-adapter.md) | Prisma multi-provider (SQLite + PostgreSQL) | Nothing |
|
||||
| 2 | [02-tenant-system.md](./02-tenant-system.md) | RLS isolation, middleware, tenant context | Phase 1 |
|
||||
| 3 | [03-auth-upgrade.md](./03-auth-upgrade.md) | Supabase Auth provider for cloud edition | Phase 1 |
|
||||
| 4 | [04-license-keys.md](./04-license-keys.md) | RSA-signed JWT license keys, tier gating | Phase 1 |
|
||||
| 5 | [05-cloud-deployment.md](./05-cloud-deployment.md) | `worldwideview-cloud` repo, nginx, Docker Compose | Phases 1–3 |
|
||||
| 6 | [06-stripe-billing.md](./06-stripe-billing.md) | Stripe Checkout, webhooks, subscription management | Phases 3–4 |
|
||||
|
||||
---
|
||||
|
||||
## Key Design Decisions
|
||||
|
||||
1. **Adapter pattern** — Three thin files (`src/core/adapters/db.ts`, `auth.ts`, `storage.ts`, `tenant.ts`) branch on `edition`. Everything else is edition-unaware.
|
||||
2. **Prisma multi-provider** — Use a build-time script to swap the provider in `schema.prisma` before generating the client if building for cloud. One schema, two providers.
|
||||
3. **RLS over application-level filtering** — PostgreSQL physically refuses cross-tenant data. Even bugs can't leak.
|
||||
4. **License keys are RSA JWTs** — Marketplace signs with private key; app verifies with hardcoded public key. No phone-home required.
|
||||
5. **Stripe is the only payment processor** — Checkout Sessions for signup, Webhooks for lifecycle events.
|
||||
@@ -0,0 +1,533 @@
|
||||
# WorldWideView CLI Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Build `@worldwideview/cli`, a standalone CLI tool that scaffolds, hot-reloads, and packages WWV plugins using the Chrome Extension model, completely decoupled from the main monorepo build pipeline.
|
||||
|
||||
**Architecture:** A Node.js CLI built with `commander`. It uses `vite` programmatically to serve and build plugins. For dev mode, it attaches a `ws` WebSocket server to the Vite dev server to broadcast hot-reload events to the running WWV web app, and communicates with `/api/dev/load-unpacked` to inject the plugin. Publishing creates a `.wwvpkg` ZIP archive via `archiver`.
|
||||
|
||||
**Tech Stack:** Node.js, TypeScript, Commander, Vite, WebSocket (`ws`), Archiver, Vitest.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Initialize Package & CLI Entry Point
|
||||
|
||||
**Files:**
|
||||
- Create: `packages/wwv-cli/package.json`
|
||||
- Create: `packages/wwv-cli/tsconfig.json`
|
||||
- Create: `packages/wwv-cli/bin/wwv.js`
|
||||
- Create: `packages/wwv-cli/src/index.ts`
|
||||
- Create: `packages/wwv-cli/tests/index.test.ts`
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```typescript
|
||||
// packages/wwv-cli/tests/index.test.ts
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { execSync } from "child_process";
|
||||
import path from "path";
|
||||
|
||||
describe("wwv cli", () => {
|
||||
it("should print help information", () => {
|
||||
const binPath = path.resolve(__dirname, "../bin/wwv.js");
|
||||
const output = execSync(`node ${binPath} --help`).toString();
|
||||
expect(output).toContain("Usage: wwv [options] [command]");
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
Run: `cd packages/wwv-cli && pnpm test`
|
||||
Expected: FAIL (File not found or missing package.json setup)
|
||||
|
||||
- [ ] **Step 3: Write minimal implementation**
|
||||
|
||||
```json
|
||||
// packages/wwv-cli/package.json
|
||||
{
|
||||
"name": "@worldwideview/cli",
|
||||
"version": "1.0.0",
|
||||
"bin": { "wwv": "./bin/wwv.js" },
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"commander": "^11.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.0.0",
|
||||
"vitest": "^1.0.0",
|
||||
"@types/node": "^20.0.0"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```json
|
||||
// packages/wwv-cli/tsconfig.json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "CommonJS",
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
// packages/wwv-cli/bin/wwv.js
|
||||
#!/usr/bin/env node
|
||||
require('../dist/index.js');
|
||||
```
|
||||
|
||||
```typescript
|
||||
// packages/wwv-cli/src/index.ts
|
||||
import { Command } from "commander";
|
||||
|
||||
const program = new Command();
|
||||
|
||||
program
|
||||
.name("wwv")
|
||||
.description("WorldWideView Plugin CLI")
|
||||
.version("1.0.0");
|
||||
|
||||
program.parse();
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run test to verify it passes**
|
||||
|
||||
Run: `cd packages/wwv-cli && pnpm install && pnpm run build && pnpm test`
|
||||
Expected: PASS
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add packages/wwv-cli
|
||||
git commit -m "feat(wwv-cli): initialize cli package and entry point"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Implement `wwv create` (Scaffolding)
|
||||
|
||||
**Files:**
|
||||
- Create: `packages/wwv-cli/src/commands/create.ts`
|
||||
- Create: `packages/wwv-cli/tests/create.test.ts`
|
||||
- Modify: `packages/wwv-cli/src/index.ts:10-15`
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```typescript
|
||||
// packages/wwv-cli/tests/create.test.ts
|
||||
import { describe, it, expect, afterEach } from "vitest";
|
||||
import { createPlugin } from "../src/commands/create";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
describe("create command", () => {
|
||||
const testDir = path.join(__dirname, "test-plugin");
|
||||
|
||||
afterEach(() => {
|
||||
if (fs.existsSync(testDir)) fs.rmSync(testDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("should scaffold a new plugin folder with manifest and index.ts", async () => {
|
||||
await createPlugin("test-plugin", __dirname);
|
||||
expect(fs.existsSync(path.join(testDir, "wwv-manifest.json"))).toBe(true);
|
||||
expect(fs.existsSync(path.join(testDir, "src", "index.ts"))).toBe(true);
|
||||
|
||||
const manifest = JSON.parse(fs.readFileSync(path.join(testDir, "wwv-manifest.json"), "utf-8"));
|
||||
expect(manifest.id).toBe("test-plugin");
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
Run: `cd packages/wwv-cli && pnpm test tests/create.test.ts`
|
||||
Expected: FAIL ("createPlugin is not defined")
|
||||
|
||||
- [ ] **Step 3: Write minimal implementation**
|
||||
|
||||
```typescript
|
||||
// packages/wwv-cli/src/commands/create.ts
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
export async function createPlugin(name: string, basePath: string = process.cwd()) {
|
||||
const targetDir = path.join(basePath, name);
|
||||
if (fs.existsSync(targetDir)) {
|
||||
throw new Error(`Directory ${name} already exists`);
|
||||
}
|
||||
|
||||
fs.mkdirSync(targetDir, { recursive: true });
|
||||
fs.mkdirSync(path.join(targetDir, "src"), { recursive: true });
|
||||
|
||||
const manifest = {
|
||||
manifest_version: 1,
|
||||
id: name,
|
||||
name: name,
|
||||
version: "1.0.0",
|
||||
description: "A WorldWideView plugin",
|
||||
type: "data-layer",
|
||||
category: "custom",
|
||||
icon: "Box",
|
||||
capabilities: ["data:own"],
|
||||
entry: "dist/frontend.mjs",
|
||||
dev_entry: "src/index.ts"
|
||||
};
|
||||
|
||||
fs.writeFileSync(
|
||||
path.join(targetDir, "wwv-manifest.json"),
|
||||
JSON.stringify(manifest, null, 2)
|
||||
);
|
||||
|
||||
const indexContent = `export default class MyPlugin {
|
||||
id = "${name}";
|
||||
name = "${name}";
|
||||
version = "1.0.0";
|
||||
category = "custom";
|
||||
icon = "Box";
|
||||
|
||||
async initialize(ctx) {
|
||||
console.log("Initialized", this.id);
|
||||
}
|
||||
|
||||
destroy() {}
|
||||
|
||||
async fetch(timeRange) {
|
||||
return [];
|
||||
}
|
||||
|
||||
getPollingInterval() {
|
||||
return 5000;
|
||||
}
|
||||
|
||||
getLayerConfig() {
|
||||
return { color: "#3b82f6", clusterEnabled: true, clusterDistance: 50 };
|
||||
}
|
||||
|
||||
renderEntity(entity) {
|
||||
return { type: "point", color: "#3b82f6", size: 6 };
|
||||
}
|
||||
}
|
||||
`;
|
||||
fs.writeFileSync(path.join(targetDir, "src", "index.ts"), indexContent);
|
||||
console.log(`Plugin ${name} scaffolded successfully in ./${name}`);
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// Modify packages/wwv-cli/src/index.ts (add this before program.parse())
|
||||
import { createPlugin } from "./commands/create";
|
||||
|
||||
program
|
||||
.command("create <name>")
|
||||
.description("Scaffold a new WorldWideView plugin")
|
||||
.action(async (name) => {
|
||||
try {
|
||||
await createPlugin(name);
|
||||
} catch (err: any) {
|
||||
console.error("Error:", err.message);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run test to verify it passes**
|
||||
|
||||
Run: `cd packages/wwv-cli && pnpm run build && pnpm test`
|
||||
Expected: PASS
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add packages/wwv-cli
|
||||
git commit -m "feat(wwv-cli): implement create command for scaffolding"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Implement `wwv dev` (Vite Server + WebSocket)
|
||||
|
||||
**Files:**
|
||||
- Create: `packages/wwv-cli/src/commands/dev.ts`
|
||||
- Create: `packages/wwv-cli/tests/dev.test.ts`
|
||||
- Modify: `packages/wwv-cli/src/index.ts:25-30`
|
||||
- Modify: `packages/wwv-cli/package.json:13-15` (Add vite, ws)
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```typescript
|
||||
// packages/wwv-cli/tests/dev.test.ts
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { startDevServer } from "../src/commands/dev";
|
||||
|
||||
// Mock vite and ws
|
||||
vi.mock("vite", () => ({
|
||||
createServer: vi.fn().mockResolvedValue({
|
||||
listen: vi.fn(),
|
||||
httpServer: { on: vi.fn() },
|
||||
ws: { on: vi.fn() }
|
||||
})
|
||||
}));
|
||||
|
||||
describe("dev command", () => {
|
||||
it("should export startDevServer function", () => {
|
||||
expect(typeof startDevServer).toBe("function");
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
Run: `cd packages/wwv-cli && pnpm test tests/dev.test.ts`
|
||||
Expected: FAIL ("startDevServer is not defined")
|
||||
|
||||
- [ ] **Step 3: Write minimal implementation**
|
||||
|
||||
Add `vite` and `ws` to dependencies in `packages/wwv-cli/package.json` and run `pnpm install`:
|
||||
```json
|
||||
"dependencies": {
|
||||
"commander": "^11.1.0",
|
||||
"vite": "^5.0.0",
|
||||
"ws": "^8.16.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/ws": "^8.5.10"
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// packages/wwv-cli/src/commands/dev.ts
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { createServer } from "vite";
|
||||
import { WebSocketServer } from "ws";
|
||||
|
||||
export async function startDevServer(targetUrl: string = "http://localhost:3000") {
|
||||
const cwd = process.cwd();
|
||||
const manifestPath = path.join(cwd, "wwv-manifest.json");
|
||||
|
||||
if (!fs.existsSync(manifestPath)) {
|
||||
throw new Error("No wwv-manifest.json found in current directory");
|
||||
}
|
||||
|
||||
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
|
||||
const port = 24601;
|
||||
|
||||
// Start Vite Dev Server
|
||||
const vite = await createServer({
|
||||
root: cwd,
|
||||
server: { port, cors: true, hmr: false }, // We handle HMR via custom WS
|
||||
plugins: [{
|
||||
name: 'wwv-hmr',
|
||||
handleHotUpdate({ server }) {
|
||||
// When Vite detects file changes, broadcast to our custom WS
|
||||
wss.clients.forEach(client => {
|
||||
client.send(JSON.stringify({ type: "plugin:updated", pluginId: manifest.id }));
|
||||
});
|
||||
return []; // Prevent default Vite HMR
|
||||
}
|
||||
}]
|
||||
});
|
||||
|
||||
await vite.listen();
|
||||
|
||||
// Attach custom WebSocket server for WWV DevModeSubscriber
|
||||
const wss = new WebSocketServer({ server: vite.httpServer as any, path: "/__wwv_dev__" });
|
||||
|
||||
wss.on("connection", (ws) => {
|
||||
console.log(`[WWV CLI] Connected to WorldWideView instance`);
|
||||
ws.send(JSON.stringify({ type: "plugin:added", manifest }));
|
||||
});
|
||||
|
||||
// Notify WorldWideView via API
|
||||
try {
|
||||
const fetch = (await import('node-fetch')).default || globalThis.fetch;
|
||||
await fetch(`${targetUrl}/api/dev/load-unpacked`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
...manifest,
|
||||
entry: `http://localhost:${port}/${manifest.dev_entry || "src/index.ts"}`
|
||||
})
|
||||
});
|
||||
console.log(`[WWV CLI] Registered with WorldWideView at ${targetUrl}`);
|
||||
} catch (err: any) {
|
||||
console.error(`[WWV CLI] Failed to connect to ${targetUrl}: ${err.message}`);
|
||||
console.log(`Waiting for WorldWideView to connect via WebSocket...`);
|
||||
}
|
||||
|
||||
console.log(`\n🚀 Dev server running on http://localhost:${port}`);
|
||||
console.log(`Watching for file changes in ${cwd}...\n`);
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// Modify packages/wwv-cli/src/index.ts (add this before program.parse())
|
||||
import { startDevServer } from "./commands/dev";
|
||||
|
||||
program
|
||||
.command("dev")
|
||||
.description("Start the plugin development server with hot-reload")
|
||||
.option("-t, --target <url>", "Target WorldWideView URL", "http://localhost:3000")
|
||||
.action(async (options) => {
|
||||
try {
|
||||
await startDevServer(options.target);
|
||||
} catch (err: any) {
|
||||
console.error("Error:", err.message);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run test to verify it passes**
|
||||
|
||||
Run: `cd packages/wwv-cli && pnpm run build && pnpm test`
|
||||
Expected: PASS
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add packages/wwv-cli
|
||||
git commit -m "feat(wwv-cli): implement dev command with vite and websockets"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Implement `wwv publish` (.wwvpkg creation)
|
||||
|
||||
**Files:**
|
||||
- Create: `packages/wwv-cli/src/commands/publish.ts`
|
||||
- Create: `packages/wwv-cli/tests/publish.test.ts`
|
||||
- Modify: `packages/wwv-cli/src/index.ts:40-45`
|
||||
- Modify: `packages/wwv-cli/package.json:16-17` (Add archiver)
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```typescript
|
||||
// packages/wwv-cli/tests/publish.test.ts
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { buildPackage } from "../src/commands/publish";
|
||||
|
||||
describe("publish command", () => {
|
||||
it("should export buildPackage function", () => {
|
||||
expect(typeof buildPackage).toBe("function");
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
Run: `cd packages/wwv-cli && pnpm test tests/publish.test.ts`
|
||||
Expected: FAIL ("buildPackage is not defined")
|
||||
|
||||
- [ ] **Step 3: Write minimal implementation**
|
||||
|
||||
Add `archiver` to dependencies in `packages/wwv-cli/package.json` and run `pnpm install`:
|
||||
```json
|
||||
"dependencies": {
|
||||
"archiver": "^7.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/archiver": "^6.0.2"
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// packages/wwv-cli/src/commands/publish.ts
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { build } from "vite";
|
||||
import archiver from "archiver";
|
||||
|
||||
export async function buildPackage() {
|
||||
const cwd = process.cwd();
|
||||
const manifestPath = path.join(cwd, "wwv-manifest.json");
|
||||
|
||||
if (!fs.existsSync(manifestPath)) {
|
||||
throw new Error("No wwv-manifest.json found in current directory");
|
||||
}
|
||||
|
||||
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
|
||||
|
||||
console.log(`[WWV CLI] Building production bundle...`);
|
||||
await build({
|
||||
root: cwd,
|
||||
build: {
|
||||
lib: {
|
||||
entry: path.resolve(cwd, manifest.dev_entry || "src/index.ts"),
|
||||
name: 'WWVPlugin',
|
||||
formats: ['es'],
|
||||
fileName: () => 'frontend.mjs'
|
||||
},
|
||||
outDir: 'dist',
|
||||
emptyOutDir: true
|
||||
}
|
||||
});
|
||||
|
||||
const pkgName = `${manifest.id}-${manifest.version}.wwvpkg`;
|
||||
const outputPath = path.join(cwd, pkgName);
|
||||
|
||||
console.log(`[WWV CLI] Creating archive ${pkgName}...`);
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const output = fs.createWriteStream(outputPath);
|
||||
const archive = archiver("zip", { zlib: { level: 9 } });
|
||||
|
||||
output.on("close", () => resolve());
|
||||
archive.on("error", (err) => reject(err));
|
||||
|
||||
archive.pipe(output);
|
||||
|
||||
archive.file(manifestPath, { name: "wwv-manifest.json" });
|
||||
archive.directory(path.join(cwd, "dist"), "dist");
|
||||
|
||||
if (fs.existsSync(path.join(cwd, "data"))) {
|
||||
archive.directory(path.join(cwd, "data"), "data");
|
||||
}
|
||||
|
||||
archive.finalize();
|
||||
});
|
||||
|
||||
console.log(`\n🎉 Success! Package created at ${outputPath}`);
|
||||
console.log(`You can now upload this file to the WorldWideView Marketplace.`);
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// Modify packages/wwv-cli/src/index.ts (add this before program.parse())
|
||||
import { buildPackage } from "./commands/publish";
|
||||
|
||||
program
|
||||
.command("publish")
|
||||
.description("Build and package the plugin into a .wwvpkg file")
|
||||
.action(async () => {
|
||||
try {
|
||||
await buildPackage();
|
||||
} catch (err: any) {
|
||||
console.error("Error:", err.message);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run test to verify it passes**
|
||||
|
||||
Run: `cd packages/wwv-cli && pnpm run build && pnpm test`
|
||||
Expected: PASS
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add packages/wwv-cli
|
||||
git commit -m "feat(wwv-cli): implement publish command for wwvpkg creation"
|
||||
```
|
||||
@@ -0,0 +1,323 @@
|
||||
# Split CLI Publish into Package and Publish Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Split the CLI publish command into `package` (for local .wwvpkg zip creation) and `publish` (for NPM distribution and marketplace registry updates).
|
||||
|
||||
**Architecture:**
|
||||
The current `publish` command creates a `.wwvpkg` file. We will rename this functionality to the `package` command. Then, we will create a true `publish` command that handles building the plugin, automatically generating a valid `package.json` from the `wwv-manifest.json`, running `npm publish` via a child process, and finally notifying the marketplace of the new release.
|
||||
|
||||
**Tech Stack:** TypeScript, Vite, Node.js `child_process`, Node.js `fs`.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Rename current publish to package
|
||||
|
||||
We will rename the file and its internal function from `buildPackage` to `packagePlugin`.
|
||||
|
||||
**Files:**
|
||||
- Modify: `packages/wwv-cli/src/commands/publish.ts` -> rename to `packages/wwv-cli/src/commands/package.ts`
|
||||
- Modify: `packages/wwv-cli/tests/publish.test.ts` -> rename to `packages/wwv-cli/tests/package.test.ts`
|
||||
|
||||
- [ ] **Step 1: Rename the command file and update function name**
|
||||
|
||||
```typescript
|
||||
// packages/wwv-cli/src/commands/package.ts
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { build } from "vite";
|
||||
import archiver from "archiver";
|
||||
|
||||
export async function packagePlugin() {
|
||||
const cwd = process.cwd();
|
||||
const manifestPath = path.join(cwd, "wwv-manifest.json");
|
||||
|
||||
if (!fs.existsSync(manifestPath)) {
|
||||
throw new Error("No wwv-manifest.json found in current directory");
|
||||
}
|
||||
|
||||
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
|
||||
|
||||
console.log(`[WWV CLI] Building production bundle...`);
|
||||
await build({
|
||||
root: cwd,
|
||||
build: {
|
||||
lib: {
|
||||
entry: path.resolve(cwd, manifest.dev_entry || "src/index.ts"),
|
||||
name: 'WWVPlugin',
|
||||
formats: ['es'],
|
||||
fileName: () => 'frontend.mjs'
|
||||
},
|
||||
outDir: 'dist',
|
||||
emptyOutDir: true
|
||||
}
|
||||
});
|
||||
|
||||
const pkgName = `${manifest.id}-${manifest.version}.wwvpkg`;
|
||||
const outputPath = path.join(cwd, pkgName);
|
||||
|
||||
console.log(`[WWV CLI] Creating archive ${pkgName}...`);
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const output = fs.createWriteStream(outputPath);
|
||||
const archive = archiver("zip", { zlib: { level: 9 } });
|
||||
|
||||
output.on("close", () => resolve());
|
||||
archive.on("error", (err) => reject(err));
|
||||
|
||||
archive.pipe(output);
|
||||
|
||||
archive.file(manifestPath, { name: "wwv-manifest.json" });
|
||||
archive.directory(path.join(cwd, "dist"), "dist");
|
||||
|
||||
if (fs.existsSync(path.join(cwd, "data"))) {
|
||||
archive.directory(path.join(cwd, "data"), "data");
|
||||
}
|
||||
|
||||
archive.finalize();
|
||||
});
|
||||
|
||||
console.log(`\n🎉 Success! Package created at ${outputPath}`);
|
||||
console.log(`You can use this file to sideload the plugin into your WWV instance.`);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Rename and update the test**
|
||||
|
||||
```typescript
|
||||
// packages/wwv-cli/tests/package.test.ts
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { packagePlugin } from "../src/commands/package";
|
||||
|
||||
describe("package command", () => {
|
||||
it("should export packagePlugin function", () => {
|
||||
expect(typeof packagePlugin).toBe("function");
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Remove old files**
|
||||
|
||||
Run: `git rm packages/wwv-cli/src/commands/publish.ts packages/wwv-cli/tests/publish.test.ts`
|
||||
Expected: Files deleted.
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add packages/wwv-cli/src/commands/package.ts packages/wwv-cli/tests/package.test.ts
|
||||
git commit -m "refactor(wwv-cli): rename publish to package for wwvpkg creation"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Implement true NPM Publish command
|
||||
|
||||
**Files:**
|
||||
- Create: `packages/wwv-cli/src/commands/publish.ts`
|
||||
- Create: `packages/wwv-cli/tests/publish.test.ts`
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```typescript
|
||||
// packages/wwv-cli/tests/publish.test.ts
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { publishToNpm } from "../src/commands/publish";
|
||||
|
||||
vi.mock("child_process", () => ({
|
||||
execSync: vi.fn()
|
||||
}));
|
||||
vi.mock("vite", () => ({
|
||||
build: vi.fn().mockResolvedValue({})
|
||||
}));
|
||||
|
||||
describe("publish command", () => {
|
||||
it("should export publishToNpm function", () => {
|
||||
expect(typeof publishToNpm).toBe("function");
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
Run: `pnpm test tests/publish.test.ts` inside `packages/wwv-cli`
|
||||
Expected: FAIL because `publishToNpm` does not exist.
|
||||
|
||||
- [ ] **Step 3: Write the publish implementation**
|
||||
|
||||
```typescript
|
||||
// packages/wwv-cli/src/commands/publish.ts
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { build } from "vite";
|
||||
import { execSync } from "child_process";
|
||||
|
||||
export async function publishToNpm() {
|
||||
const cwd = process.cwd();
|
||||
const manifestPath = path.join(cwd, "wwv-manifest.json");
|
||||
|
||||
if (!fs.existsSync(manifestPath)) {
|
||||
throw new Error("No wwv-manifest.json found in current directory");
|
||||
}
|
||||
|
||||
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
|
||||
|
||||
console.log(`[WWV CLI] Compiling bundle for NPM...`);
|
||||
await build({
|
||||
root: cwd,
|
||||
build: {
|
||||
lib: {
|
||||
entry: path.resolve(cwd, manifest.dev_entry || "src/index.ts"),
|
||||
name: 'WWVPlugin',
|
||||
formats: ['es'],
|
||||
fileName: () => 'frontend.mjs'
|
||||
},
|
||||
outDir: 'dist',
|
||||
emptyOutDir: true
|
||||
}
|
||||
});
|
||||
|
||||
console.log(`[WWV CLI] Generating package.json...`);
|
||||
// Create a temporary package.json required for NPM publish
|
||||
const packageJsonPath = path.join(cwd, "package.json");
|
||||
const packageJson = {
|
||||
name: manifest.id, // e.g. @username/my-plugin
|
||||
version: manifest.version,
|
||||
description: manifest.description,
|
||||
main: "dist/frontend.mjs",
|
||||
type: "module",
|
||||
files: ["dist", "wwv-manifest.json", "data"],
|
||||
keywords: ["worldwideview", "plugin", manifest.category],
|
||||
author: manifest.author || ""
|
||||
};
|
||||
|
||||
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
|
||||
|
||||
console.log(`[WWV CLI] Publishing to NPM...`);
|
||||
try {
|
||||
execSync(`npm publish --access public`, { stdio: "inherit", cwd });
|
||||
} catch (err) {
|
||||
console.error(`[WWV CLI] NPM publish failed. Please ensure you are logged in via 'npm login'.`);
|
||||
throw err;
|
||||
} finally {
|
||||
// Clean up the generated package.json so it doesn't clutter the dev's repo
|
||||
fs.unlinkSync(packageJsonPath);
|
||||
}
|
||||
|
||||
console.log(`[WWV CLI] Notifying WorldWideView Marketplace...`);
|
||||
try {
|
||||
const targetUrl = process.env.WWV_MARKETPLACE_URL || "https://marketplace.worldwideview.dev";
|
||||
await fetch(`${targetUrl}/api/webhooks/npm-publish`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ pluginId: manifest.id, version: manifest.version })
|
||||
});
|
||||
console.log(`[WWV CLI] Marketplace notified.`);
|
||||
} catch (err: any) {
|
||||
console.warn(`[WWV CLI] Could not notify marketplace: ${err.message}. It will be indexed on the next sweep.`);
|
||||
}
|
||||
|
||||
console.log(`\n🚀 Success! Version ${manifest.version} published globally to NPM.`);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run test to verify it passes**
|
||||
|
||||
Run: `pnpm test tests/publish.test.ts` inside `packages/wwv-cli`
|
||||
Expected: PASS
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add packages/wwv-cli/src/commands/publish.ts packages/wwv-cli/tests/publish.test.ts
|
||||
git commit -m "feat(wwv-cli): implement npm publish and marketplace webhook ping"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Update CLI Entry Point
|
||||
|
||||
**Files:**
|
||||
- Modify: `packages/wwv-cli/src/index.ts:36-50`
|
||||
|
||||
- [ ] **Step 1: Write the updated entry point logic**
|
||||
|
||||
Replace the existing `publish` command logic with both `package` and `publish`:
|
||||
|
||||
```typescript
|
||||
// Edit packages/wwv-cli/src/index.ts
|
||||
import { Command } from "commander";
|
||||
import { createPlugin } from "./commands/create";
|
||||
import { startDevServer } from "./commands/dev";
|
||||
import { packagePlugin } from "./commands/package";
|
||||
import { publishToNpm } from "./commands/publish";
|
||||
|
||||
const program = new Command();
|
||||
|
||||
program
|
||||
.name("wwv")
|
||||
.description("WorldWideView Plugin CLI")
|
||||
.version("1.0.0");
|
||||
|
||||
program
|
||||
.command("create <name>")
|
||||
.description("Scaffold a new WorldWideView plugin")
|
||||
.action(async (name) => {
|
||||
try {
|
||||
await createPlugin(name);
|
||||
} catch (err: any) {
|
||||
console.error("Error:", err.message);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
program
|
||||
.command("dev")
|
||||
.description("Start the plugin development server with hot-reload")
|
||||
.option("-t, --target <url>", "Target WorldWideView URL", "http://localhost:3000")
|
||||
.action(async (options) => {
|
||||
try {
|
||||
await startDevServer(options.target);
|
||||
} catch (err: any) {
|
||||
console.error("Error:", err.message);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
program
|
||||
.command("package")
|
||||
.description("Build and package the plugin into a .wwvpkg file for sideloading")
|
||||
.action(async () => {
|
||||
try {
|
||||
await packagePlugin();
|
||||
} catch (err: any) {
|
||||
console.error("Error:", err.message);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
program
|
||||
.command("publish")
|
||||
.description("Publish the plugin to NPM and notify the WWV Marketplace")
|
||||
.action(async () => {
|
||||
try {
|
||||
await publishToNpm();
|
||||
} catch (err: any) {
|
||||
console.error("Error:", err.message);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
program.parse();
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Build to verify no TypeScript errors**
|
||||
|
||||
Run: `pnpm run build` inside `packages/wwv-cli`
|
||||
Expected: Clean build.
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add packages/wwv-cli/src/index.ts
|
||||
git commit -m "feat(wwv-cli): register package and npm publish commands"
|
||||
```
|
||||
@@ -0,0 +1,53 @@
|
||||
# Prisma 7 Setup Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Finalize the Prisma 7 adapter architecture by removing legacy `url` parameters from the schema, syncing the local database, and validating the end-to-end connection.
|
||||
|
||||
**Architecture:** Prisma 7 strictly separates connection logic from the schema. The schema only defines the provider (`postgresql`), while connection strings for CLI commands like `db push` are handled by `prisma.config.ts`, and runtime connections are handled by the explicit `@prisma/adapter-pg` driver instance passed to the `PrismaClient` constructor.
|
||||
|
||||
**Tech Stack:** Prisma 7, PostgreSQL, Next.js, Node.js
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Update Prisma Schema
|
||||
|
||||
**Files:**
|
||||
- Modify: `prisma/schema.prisma:5-8`
|
||||
|
||||
- [ ] **Step 1: Remove the legacy `url` property from the datasource block**
|
||||
|
||||
```prisma
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
}
|
||||
```
|
||||
|
||||
### Task 2: Push Schema to Local Database
|
||||
|
||||
- [ ] **Step 1: Execute Prisma db push to create the tables in the newly running Docker Postgres container**
|
||||
|
||||
Run: `npx dotenv-cli -e .env.local -- npx prisma db push`
|
||||
Expected: PASS with "Your database is now in sync with your schema."
|
||||
|
||||
### Task 3: Generate Prisma Client
|
||||
|
||||
- [ ] **Step 1: Regenerate the Prisma Client types to ensure they match the schema**
|
||||
|
||||
Run: `npx dotenv-cli -e .env.local -- npx prisma generate`
|
||||
Expected: PASS with "Generated Prisma Client"
|
||||
|
||||
### Task 4: Verify End-to-End Connection
|
||||
|
||||
- [ ] **Step 1: Run the user management script to prove the `adapter-pg` runtime can connect and query the new tables**
|
||||
|
||||
Run: `npx tsx --env-file=.env.local scripts/manage-users.ts list`
|
||||
Expected: PASS with no errors (it should just exit silently if there are no users, rather than throwing a `P2021 TableDoesNotExist` or `P1001` error).
|
||||
|
||||
### Task 5: Restart the Development Server
|
||||
|
||||
- [ ] **Step 1: Restart the Next.js dev server**
|
||||
Because the server has been running while we were debugging the `PrismaClientInitializationError`, Webpack may have cached the broken client. We need to kill the current `pnpm run dev` and start it fresh so we can test the API routes in the browser.
|
||||
|
||||
Run: Terminate the current `pnpm run dev` terminal, then run: `pnpm run dev`
|
||||
Expected: Next.js starts successfully without any Prisma instantiation crashes.
|
||||
@@ -0,0 +1,618 @@
|
||||
# Unify Database Adapter (PostgreSQL-Only) Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [x]`) syntax for tracking.
|
||||
|
||||
**Goal:** Replace the dual SQLite/PostgreSQL database system with a single PostgreSQL adapter, using Prisma's built-in `prisma dev` for zero-install local development.
|
||||
|
||||
**Architecture:** The app currently has two database paths — `@prisma/adapter-better-sqlite3` for local and `@prisma/adapter-pg` for cloud — which causes constant migration conflicts and config drift. We unify to `@prisma/adapter-pg` everywhere. Local developers use `npx prisma dev` (PGLite-backed local Postgres managed by Prisma CLI) or their own Postgres instance. Production connects to Supabase via the same adapter and connection string swap.
|
||||
|
||||
**Tech Stack:** Prisma 7, `@prisma/adapter-pg`, `pg`, PostgreSQL, Next.js 16
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
| Action | File | Responsibility |
|
||||
|---|---|---|
|
||||
| Modify | `prisma/schema.prisma` | Change provider to `postgresql` |
|
||||
| **Rewrite** | `src/lib/db.ts` | Single PostgreSQL adapter factory |
|
||||
| Delete | `src/core/adapters/db.ts` | Remove cloud-branch adapter factory (merge into `db.ts`) |
|
||||
| Modify | `package.json` | Remove `better-sqlite3` + adapter deps, add `pg` |
|
||||
| Modify | `next.config.ts` | Remove `better-sqlite3` from `serverExternalPackages` |
|
||||
| Modify | `docker-entrypoint.sh` | Update comments, remove SQLite references |
|
||||
| Modify | `Dockerfile` | Remove SQLite build step, update env defaults |
|
||||
| Modify | `local-dev.ps1` | Add `prisma dev` startup guidance |
|
||||
| Modify | `.env` | Change default `DATABASE_URL` to local PostgreSQL |
|
||||
| Modify | `prisma.config.ts` | No changes needed (already reads `DATABASE_URL`) |
|
||||
| Modify | `scripts/cleanup-plugins.ts` | Use shared `db.ts` instead of hardcoded SQLite |
|
||||
| Modify | `scripts/manage-users.ts` | Use shared `db.ts` instead of hardcoded SQLite |
|
||||
| Keep | `scripts/migrate-aviation-history.ts` | This is a one-off Supabase-to-SQLite migration tool. Leave as-is but mark deprecated |
|
||||
| **Delete** | `prisma/migrations/` | Remove old SQLite migrations (will regenerate for PostgreSQL) |
|
||||
| **Create** | `prisma/migrations/` | Fresh PostgreSQL init migration |
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Update Prisma Schema Provider
|
||||
|
||||
**Files:**
|
||||
- Modify: `prisma/schema.prisma:1-6`
|
||||
|
||||
- [x] **Step 1: Change the datasource provider from SQLite to PostgreSQL**
|
||||
|
||||
Open `prisma/schema.prisma` and replace the datasource block:
|
||||
|
||||
```prisma
|
||||
// Prisma schema — PostgreSQL for all environments.
|
||||
// Local dev: use `npx prisma dev` for a zero-install local PGLite instance.
|
||||
// Cloud/Production: set DATABASE_URL to your Supabase/Postgres connection string.
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
}
|
||||
```
|
||||
|
||||
Leave the `generator` block and all models unchanged.
|
||||
|
||||
- [x] **Step 2: Verify the schema is valid**
|
||||
|
||||
Run:
|
||||
```powershell
|
||||
npx prisma validate
|
||||
```
|
||||
|
||||
Expected: `The schema at prisma/schema.prisma is valid.`
|
||||
|
||||
- [x] **Step 3: Commit**
|
||||
|
||||
```powershell
|
||||
git add prisma/schema.prisma
|
||||
git commit -m "refactor(db): switch schema provider from sqlite to postgresql"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Remove SQLite Dependencies
|
||||
|
||||
**Files:**
|
||||
- Modify: `package.json:22-80`
|
||||
- Modify: `next.config.ts:5`
|
||||
|
||||
- [x] **Step 1: Remove better-sqlite3 packages from package.json**
|
||||
|
||||
In `package.json`, remove these lines from `dependencies`:
|
||||
```diff
|
||||
- "@prisma/adapter-better-sqlite3": "^7.5.0",
|
||||
```
|
||||
|
||||
Remove from `pnpm.onlyBuiltDependencies`:
|
||||
```diff
|
||||
- "better-sqlite3",
|
||||
```
|
||||
|
||||
Ensure `@prisma/adapter-pg` and `pg` remain (they're already present):
|
||||
```json
|
||||
"@prisma/adapter-pg": "^7.8.0",
|
||||
"pg": "^8.20.0",
|
||||
```
|
||||
|
||||
- [x] **Step 2: Update serverExternalPackages in next.config.ts**
|
||||
|
||||
In `next.config.ts` line 5, replace:
|
||||
```typescript
|
||||
serverExternalPackages: ["better-sqlite3", "@prisma/adapter-better-sqlite3", "@prisma/client", "prisma"],
|
||||
```
|
||||
|
||||
With:
|
||||
```typescript
|
||||
serverExternalPackages: ["@prisma/client", "prisma", "pg"],
|
||||
```
|
||||
|
||||
- [x] **Step 3: Install to update lockfile**
|
||||
|
||||
Run:
|
||||
```powershell
|
||||
pnpm install
|
||||
```
|
||||
|
||||
Expected: Clean install with no `better-sqlite3` compilation step.
|
||||
|
||||
- [x] **Step 4: Commit**
|
||||
|
||||
```powershell
|
||||
git add package.json next.config.ts pnpm-lock.yaml
|
||||
git commit -m "refactor(db): remove better-sqlite3 dependencies"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Rewrite the Database Adapter Factory
|
||||
|
||||
**Files:**
|
||||
- Rewrite: `src/lib/db.ts`
|
||||
|
||||
- [x] **Step 1: Replace db.ts with a unified PostgreSQL adapter**
|
||||
|
||||
Replace the entire contents of `src/lib/db.ts` with:
|
||||
|
||||
```typescript
|
||||
import { PrismaClient } from "../generated/prisma";
|
||||
import { PrismaPg } from "@prisma/adapter-pg";
|
||||
import { Pool } from "pg";
|
||||
|
||||
/**
|
||||
* Prisma client singleton — PostgreSQL only.
|
||||
*
|
||||
* Local dev: Run `npx prisma dev` for a zero-install local Postgres.
|
||||
* Production: Set DATABASE_URL to your Supabase/Postgres connection string.
|
||||
*
|
||||
* Uses globalThis to survive Next.js HMR in development.
|
||||
*/
|
||||
|
||||
const globalForPrisma = globalThis as unknown as {
|
||||
prisma: PrismaClient | undefined;
|
||||
};
|
||||
|
||||
function createPrismaClient(): PrismaClient {
|
||||
const connectionString = process.env.DATABASE_URL;
|
||||
|
||||
if (!connectionString) {
|
||||
throw new Error(
|
||||
"[db] DATABASE_URL is not set. " +
|
||||
"Run `npx prisma dev` for local development, " +
|
||||
"or set DATABASE_URL to your PostgreSQL connection string."
|
||||
);
|
||||
}
|
||||
|
||||
const pool = new Pool({ connectionString });
|
||||
const adapter = new PrismaPg(pool);
|
||||
|
||||
return new PrismaClient({ adapter } as any);
|
||||
}
|
||||
|
||||
export const prisma = globalForPrisma.prisma ?? createPrismaClient();
|
||||
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
globalForPrisma.prisma = prisma;
|
||||
}
|
||||
```
|
||||
|
||||
> **Note:** The `feature/cloud-hosting-core` branch has a more complex version at `src/core/adapters/db.ts` with tenant isolation via `applyTenantIsolation()`. When merging that branch later, the tenant isolation extension should be layered on top of this unified base — it does NOT need a separate SQLite path.
|
||||
|
||||
- [x] **Step 2: Verify TypeScript compilation**
|
||||
|
||||
Run:
|
||||
```powershell
|
||||
npx tsc --noEmit --pretty 2>&1 | Select-String "db.ts"
|
||||
```
|
||||
|
||||
Expected: No errors related to `db.ts`.
|
||||
|
||||
- [x] **Step 3: Commit**
|
||||
|
||||
```powershell
|
||||
git add src/lib/db.ts
|
||||
git commit -m "refactor(db): unify adapter to postgresql-only via PrismaPg"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Update Utility Scripts
|
||||
|
||||
**Files:**
|
||||
- Modify: `scripts/cleanup-plugins.ts`
|
||||
- Modify: `scripts/manage-users.ts`
|
||||
|
||||
- [x] **Step 1: Rewrite cleanup-plugins.ts to use shared db**
|
||||
|
||||
Replace the entire contents of `scripts/cleanup-plugins.ts`:
|
||||
|
||||
```typescript
|
||||
import { PrismaClient } from "../src/generated/prisma/index.js";
|
||||
import { PrismaPg } from "@prisma/adapter-pg";
|
||||
import { Pool } from "pg";
|
||||
|
||||
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
||||
const adapter = new PrismaPg(pool);
|
||||
const prisma = new PrismaClient({ adapter } as any);
|
||||
|
||||
async function main() {
|
||||
const plugins = await prisma.installedPlugin.findMany();
|
||||
console.log("Installed plugins:");
|
||||
plugins.forEach((p) => console.log(` ${p.pluginId} | config: ${p.config.substring(0, 60)}`));
|
||||
|
||||
const geojson = plugins.find((p) => p.pluginId === "geojson");
|
||||
if (geojson) {
|
||||
await prisma.installedPlugin.delete({ where: { id: geojson.id } });
|
||||
console.log("\nDeleted orphaned 'geojson' record.");
|
||||
} else {
|
||||
console.log("\nNo orphaned 'geojson' record found.");
|
||||
}
|
||||
|
||||
const remaining = await prisma.installedPlugin.findMany();
|
||||
console.log("\nRemaining plugins:");
|
||||
remaining.forEach((p) => console.log(` ${p.pluginId}`));
|
||||
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
|
||||
- [x] **Step 2: Rewrite manage-users.ts to use shared db**
|
||||
|
||||
Replace the entire contents of `scripts/manage-users.ts`:
|
||||
|
||||
```typescript
|
||||
import { PrismaClient } from "../src/generated/prisma/index.js";
|
||||
import { PrismaPg } from "@prisma/adapter-pg";
|
||||
import { Pool } from "pg";
|
||||
import { hashSync } from "bcryptjs";
|
||||
|
||||
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
||||
const adapter = new PrismaPg(pool);
|
||||
const prisma = new PrismaClient({ adapter } as any);
|
||||
|
||||
async function main() {
|
||||
const action = process.argv[2];
|
||||
|
||||
if (action === "list") {
|
||||
const users = await prisma.user.findMany();
|
||||
if (users.length === 0) {
|
||||
console.log("No users found — visit /setup to create one.");
|
||||
} else {
|
||||
users.forEach((u) =>
|
||||
console.log(` ${u.email} | ${u.name} | ${u.role} | ${u.createdAt}`)
|
||||
);
|
||||
}
|
||||
} else if (action === "reset") {
|
||||
const email = process.argv[3];
|
||||
const newPass = process.argv[4];
|
||||
if (!email || !newPass) {
|
||||
console.log("Usage: tsx scripts/manage-users.ts reset <email> <password>");
|
||||
return;
|
||||
}
|
||||
const hashed = hashSync(newPass, 12);
|
||||
await prisma.user.update({
|
||||
where: { email },
|
||||
data: { hashedPassword: hashed },
|
||||
});
|
||||
console.log(`Password reset for ${email}`);
|
||||
} else if (action === "delete-all") {
|
||||
await prisma.user.deleteMany();
|
||||
console.log("All users deleted — visit /setup to create a new admin.");
|
||||
} else {
|
||||
console.log("Usage: tsx scripts/manage-users.ts <list|reset|delete-all>");
|
||||
}
|
||||
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
|
||||
- [x] **Step 3: Add deprecation notice to migrate-aviation-history.ts**
|
||||
|
||||
Add this comment at the top of `scripts/migrate-aviation-history.ts`:
|
||||
|
||||
```typescript
|
||||
/**
|
||||
* @deprecated This script uses better-sqlite3 directly to migrate data
|
||||
* from Supabase into the legacy data engine's SQLite database.
|
||||
* It is NOT part of the main application's database layer.
|
||||
* It will be removed once the data engine migration is complete.
|
||||
*/
|
||||
```
|
||||
|
||||
- [x] **Step 4: Commit**
|
||||
|
||||
```powershell
|
||||
git add scripts/cleanup-plugins.ts scripts/manage-users.ts scripts/migrate-aviation-history.ts
|
||||
git commit -m "refactor(scripts): update utility scripts to use postgresql adapter"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Create Fresh PostgreSQL Migration
|
||||
|
||||
**Files:**
|
||||
- Delete: `prisma/migrations/` (entire directory)
|
||||
- Create: `prisma/migrations/YYYYMMDD_init/migration.sql` (generated by Prisma)
|
||||
|
||||
- [x] **Step 1: Delete old SQLite migrations**
|
||||
|
||||
```powershell
|
||||
Remove-Item -Recurse -Force prisma/migrations
|
||||
```
|
||||
|
||||
- [x] **Step 2: Ensure a local PostgreSQL is available**
|
||||
|
||||
Either:
|
||||
- Run `npx prisma dev` in a separate terminal, OR
|
||||
- Use your existing local PostgreSQL at `127.0.0.1:5432`
|
||||
|
||||
Verify the connection string in `.env.local` points to a reachable PostgreSQL instance:
|
||||
```
|
||||
DATABASE_URL="postgresql://postgres:[email protected]:5432/postgres?schema=public"
|
||||
```
|
||||
|
||||
- [x] **Step 3: Reset and create initial migration**
|
||||
|
||||
```powershell
|
||||
npx prisma migrate reset --force
|
||||
npx prisma migrate dev --name init
|
||||
```
|
||||
|
||||
Expected output:
|
||||
```
|
||||
Applying migration `YYYYMMDDHHMMSS_init`
|
||||
The following migration(s) have been created and applied...
|
||||
```
|
||||
|
||||
- [x] **Step 4: Verify migration_lock.toml says postgresql**
|
||||
|
||||
```powershell
|
||||
Get-Content prisma/migrations/migration_lock.toml
|
||||
```
|
||||
|
||||
Expected:
|
||||
```
|
||||
provider = "postgresql"
|
||||
```
|
||||
|
||||
- [x] **Step 5: Commit**
|
||||
|
||||
```powershell
|
||||
git add prisma/migrations
|
||||
git commit -m "feat(db): create initial postgresql migration"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Update Dockerfile and Entrypoint
|
||||
|
||||
**Files:**
|
||||
- Modify: `Dockerfile:11,36-38,49,54`
|
||||
- Modify: `docker-entrypoint.sh:3-5`
|
||||
|
||||
- [x] **Step 1: Update Dockerfile**
|
||||
|
||||
Make these changes to `Dockerfile`:
|
||||
|
||||
**Line 11** — Remove `python3 make g++` (no longer need to compile better-sqlite3 native bindings):
|
||||
```dockerfile
|
||||
RUN apk add --no-cache python3 make g++
|
||||
```
|
||||
Replace with:
|
||||
```dockerfile
|
||||
# python3/make/g++ no longer needed — removed better-sqlite3 native compilation
|
||||
```
|
||||
|
||||
**Lines 36-38** — Remove the conditional SQLite build step entirely:
|
||||
```dockerfile
|
||||
# Create an empty SQLite database with all tables applied ONLY IF NOT CLOUD
|
||||
# (For cloud, we'll run migrations against Postgres at runtime)
|
||||
RUN if [ "$NEXT_PUBLIC_WWV_EDITION" != "cloud" ]; then mkdir -p ./data && DATABASE_URL=file:./data/wwv.db npx prisma migrate deploy; fi
|
||||
```
|
||||
Replace with:
|
||||
```dockerfile
|
||||
# Database migrations run at container startup via docker-entrypoint.sh
|
||||
# DATABASE_URL must be set to a PostgreSQL connection string
|
||||
```
|
||||
|
||||
**Line 49** — Keep `prisma` global install (needed for `migrate deploy` at runtime).
|
||||
|
||||
**Line 54** — Remove the SQLite default DATABASE_URL:
|
||||
```dockerfile
|
||||
ENV DATABASE_URL=file:./data/wwv.db
|
||||
```
|
||||
Replace with:
|
||||
```dockerfile
|
||||
# DATABASE_URL must be provided via environment variable (no default)
|
||||
# Example: postgresql://user:pass@host:5432/dbname
|
||||
```
|
||||
|
||||
- [x] **Step 2: Update docker-entrypoint.sh comments**
|
||||
|
||||
Replace lines 2-5 of `docker-entrypoint.sh`:
|
||||
```bash
|
||||
# ─── Docker Entrypoint ───────────────────────────────────────
|
||||
# Ensures the SQLite database exists and is migrated before
|
||||
# starting the application. On first run with a fresh volume
|
||||
# the DB file won't exist yet, so we run prisma migrate deploy.
|
||||
```
|
||||
|
||||
With:
|
||||
```bash
|
||||
# ─── Docker Entrypoint ───────────────────────────────────────
|
||||
# Ensures the PostgreSQL database is migrated before starting
|
||||
# the application. DATABASE_URL must point to a PostgreSQL
|
||||
# instance (Supabase, self-hosted, etc).
|
||||
```
|
||||
|
||||
Remove `mkdir -p ./data` from line 9 (no longer creating a local SQLite file):
|
||||
```bash
|
||||
set -e
|
||||
|
||||
echo "[entrypoint] Running database migrations..."
|
||||
prisma migrate deploy
|
||||
echo "[entrypoint] Migrations complete."
|
||||
```
|
||||
|
||||
- [x] **Step 3: Commit**
|
||||
|
||||
```powershell
|
||||
git add Dockerfile docker-entrypoint.sh
|
||||
git commit -m "refactor(docker): remove sqlite from build and runtime"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 7: Update Environment Defaults and Dev Scripts
|
||||
|
||||
**Files:**
|
||||
- Modify: `.env:1`
|
||||
- Modify: `package.json:13` (predev script)
|
||||
- Modify: `local-dev.ps1`
|
||||
|
||||
- [x] **Step 1: Update .env default DATABASE_URL**
|
||||
|
||||
Replace line 1 of `.env`:
|
||||
```
|
||||
DATABASE_URL=file:./data/wwv.db
|
||||
```
|
||||
|
||||
With:
|
||||
```
|
||||
# PostgreSQL connection string.
|
||||
# For local dev: run `npx prisma dev` and use the URL it prints.
|
||||
# For production: set to your Supabase/Postgres connection string.
|
||||
# DATABASE_URL=postgresql://postgres:[email protected]:5432/worldwideview
|
||||
```
|
||||
|
||||
> **Important:** The default is now commented out. The `.env.local` file (or `npx prisma dev`) must provide the actual value. This forces contributors to explicitly set up their database rather than silently falling back to a potentially broken SQLite path.
|
||||
|
||||
- [x] **Step 2: Simplify the predev script**
|
||||
|
||||
In `package.json`, the `predev` script currently runs `npx prisma migrate deploy`. This will fail if no Postgres is running. Change it to only copy Cesium assets and generate the Prisma client:
|
||||
|
||||
```json
|
||||
"predev": "npx prisma generate && node scripts/copy-cesium.mjs",
|
||||
```
|
||||
|
||||
> **Rationale:** `prisma migrate deploy` should only run in production (Docker entrypoint) or explicitly by the developer. During local dev, `npx prisma dev` handles migrations automatically.
|
||||
|
||||
- [x] **Step 3: Update local-dev.ps1**
|
||||
|
||||
Replace the entire contents of `local-dev.ps1`:
|
||||
|
||||
```powershell
|
||||
Write-Host "[*] Setting up WorldWideView for Local Development..."
|
||||
|
||||
# Check for pnpm
|
||||
try {
|
||||
$null = Get-Command pnpm -ErrorAction Stop
|
||||
} catch {
|
||||
Write-Host "[Error] pnpm is not installed or not in PATH."
|
||||
Write-Host "Please install it first: https://pnpm.io/installation"
|
||||
exit 1
|
||||
}
|
||||
|
||||
Write-Host "[*] Installing dependencies..."
|
||||
pnpm install
|
||||
|
||||
Write-Host "[*] Running initial setup (generating secrets)..."
|
||||
pnpm run setup
|
||||
|
||||
Write-Host "[*] Generating Prisma client..."
|
||||
npx prisma generate
|
||||
|
||||
# Check for the sibling Data Engine repository
|
||||
if (-not (Test-Path "../wwv-data-engine")) {
|
||||
Write-Host ""
|
||||
Write-Host "=====================================================================" -ForegroundColor Yellow
|
||||
Write-Host "[!] NOTICE: Local Data Engine not found at ../wwv-data-engine" -ForegroundColor Yellow
|
||||
Write-Host ""
|
||||
Write-Host "Frontend-Only Mode: You are developing the frontend UI." -ForegroundColor Green
|
||||
Write-Host "WorldWideView will automatically stream data from the Cloud Engine." -ForegroundColor Green
|
||||
Write-Host ""
|
||||
Write-Host "Full-Stack Mode: If you want to develop backend data seeders, you" -ForegroundColor Cyan
|
||||
Write-Host "must clone the open-source data engine as a sibling directory:" -ForegroundColor Cyan
|
||||
Write-Host " cd ..; git clone https://github.com/silvertakana/wwv-data-engine"
|
||||
Write-Host " cd wwv-data-engine; pnpm install"
|
||||
Write-Host "=====================================================================" -ForegroundColor Yellow
|
||||
Write-Host ""
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "=====================================================================" -ForegroundColor Cyan
|
||||
Write-Host "[!] DATABASE SETUP REQUIRED" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
Write-Host "WorldWideView uses PostgreSQL. Choose one option:" -ForegroundColor White
|
||||
Write-Host ""
|
||||
Write-Host " Option A (Easiest): Run Prisma's built-in local database:" -ForegroundColor Green
|
||||
Write-Host " npx prisma dev" -ForegroundColor Yellow
|
||||
Write-Host " (Copy the DATABASE_URL it prints into your .env.local file)" -ForegroundColor Gray
|
||||
Write-Host ""
|
||||
Write-Host " Option B: Use your own PostgreSQL or Supabase instance:" -ForegroundColor Green
|
||||
Write-Host " Set DATABASE_URL in .env.local to your connection string" -ForegroundColor Gray
|
||||
Write-Host "=====================================================================" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
|
||||
Write-Host "[*] Starting local Next.js frontend server..."
|
||||
Write-Host " (To run the data engine backends concurrently, run: pnpm dev:all)"
|
||||
pnpm run dev
|
||||
```
|
||||
|
||||
- [x] **Step 4: Commit**
|
||||
|
||||
```powershell
|
||||
git add .env package.json local-dev.ps1
|
||||
git commit -m "refactor(dev): update env defaults and dev scripts for postgresql"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 8: Run Tests and Validate
|
||||
|
||||
**Files:**
|
||||
- No file changes — validation only
|
||||
|
||||
- [x] **Step 1: Generate Prisma client**
|
||||
|
||||
```powershell
|
||||
npx prisma generate
|
||||
```
|
||||
|
||||
Expected: `Generated Prisma Client to ./src/generated/prisma`
|
||||
|
||||
- [x] **Step 2: Run the test suite**
|
||||
|
||||
```powershell
|
||||
pnpm test
|
||||
```
|
||||
|
||||
Expected: All tests pass. The repository tests mock `db.ts`, so the adapter change should be transparent to them.
|
||||
|
||||
- [x] **Step 3: Start the dev server**
|
||||
|
||||
Ensure your `.env.local` has a valid `DATABASE_URL` pointing to PostgreSQL, then:
|
||||
|
||||
```powershell
|
||||
pnpm run dev
|
||||
```
|
||||
|
||||
Expected: Server starts at `http://localhost:3000` without `P3005` or `P3018` errors.
|
||||
|
||||
- [x] **Step 4: Verify database operations work**
|
||||
|
||||
1. Navigate to `http://localhost:3000/setup` — create a test user
|
||||
2. Log in
|
||||
3. Open the Plugins panel — verify installed plugins load
|
||||
4. Star a favorite entity — verify it persists across reload
|
||||
|
||||
- [x] **Step 5: Final commit**
|
||||
|
||||
```powershell
|
||||
git add -A
|
||||
git commit -m "test(db): verify postgresql-only adapter works end-to-end"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Post-Implementation Notes
|
||||
|
||||
### For the `feature/cloud-hosting-core` merge
|
||||
|
||||
When merging the cloud-hosting-core branch back into main, the `src/core/adapters/db.ts` file with `applyTenantIsolation()` should be integrated into `src/lib/db.ts` as a wrapper around the single `PrismaPg` adapter. The conditional SQLite path in that file can be completely removed.
|
||||
|
||||
### For self-hosted Docker users
|
||||
|
||||
Add a note to the release changelog:
|
||||
|
||||
> **Breaking Change:** WorldWideView now requires a PostgreSQL database. SQLite is no longer supported.
|
||||
> Self-hosted users must provide a `DATABASE_URL` environment variable pointing to a PostgreSQL instance.
|
||||
> The easiest option is a free Supabase project, or run `docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=pass postgres:17-alpine` alongside your WWV container.
|
||||
|
||||
### For the migrate-aviation-history.ts script
|
||||
|
||||
This script uses `better-sqlite3` directly to talk to the data engine's separate SQLite database (not the platform database). It is unrelated to this migration and can remain as-is. If `better-sqlite3` is needed for this script, install it as a `devDependency` only, or move the script to the data engine repo where it belongs.
|
||||
@@ -15,6 +15,9 @@ pnpm install
|
||||
Write-Host "[*] Running initial setup (generating secrets)..."
|
||||
pnpm run setup
|
||||
|
||||
Write-Host "[*] Generating Prisma client..."
|
||||
npx prisma generate
|
||||
|
||||
# Check for the sibling Data Engine repository
|
||||
if (-not (Test-Path "../wwv-data-engine")) {
|
||||
Write-Host ""
|
||||
@@ -32,6 +35,21 @@ if (-not (Test-Path "../wwv-data-engine")) {
|
||||
Write-Host ""
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "=====================================================================" -ForegroundColor Cyan
|
||||
Write-Host "[!] DATABASE SETUP REQUIRED" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
Write-Host "WorldWideView uses PostgreSQL. Choose one option:" -ForegroundColor White
|
||||
Write-Host ""
|
||||
Write-Host " Option A (Easiest): Run Prisma's built-in local database:" -ForegroundColor Green
|
||||
Write-Host " npx prisma dev" -ForegroundColor Yellow
|
||||
Write-Host " (Copy the DATABASE_URL it prints into your .env.local file)" -ForegroundColor Gray
|
||||
Write-Host ""
|
||||
Write-Host " Option B: Use your own PostgreSQL or Supabase instance:" -ForegroundColor Green
|
||||
Write-Host " Set DATABASE_URL in .env.local to your connection string" -ForegroundColor Gray
|
||||
Write-Host "=====================================================================" -ForegroundColor Cyan
|
||||
Write-Host ""
|
||||
|
||||
Write-Host "[*] Starting local Next.js frontend server..."
|
||||
Write-Host " (To run the data engine backends concurrently, run: pnpm dev:all)"
|
||||
pnpm run dev
|
||||
+7
-6
@@ -2,7 +2,7 @@ import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
output: "standalone",
|
||||
serverExternalPackages: ["better-sqlite3", "@prisma/adapter-better-sqlite3", "@prisma/client", "prisma"],
|
||||
serverExternalPackages: ["@prisma/client", "prisma"],
|
||||
transpilePackages: ["@worldwideview/wwv-plugin-sdk", "resium", "react-player", "satellite.js"],
|
||||
allowedDevOrigins: process.env.ALLOWED_DEV_ORIGIN ? [process.env.ALLOWED_DEV_ORIGIN] : undefined,
|
||||
experimental: {
|
||||
@@ -10,6 +10,9 @@ const nextConfig: NextConfig = {
|
||||
cpus: 2,
|
||||
optimizePackageImports: ["lucide-react"],
|
||||
},
|
||||
outputFileTracingIncludes: {
|
||||
"/*": ["./scripts/**/*"],
|
||||
},
|
||||
typescript: {
|
||||
ignoreBuildErrors: true,
|
||||
},
|
||||
@@ -18,10 +21,6 @@ const nextConfig: NextConfig = {
|
||||
{
|
||||
source: "/(.*)",
|
||||
headers: [
|
||||
{ key: "Access-Control-Allow-Origin", value: "*" },
|
||||
{ key: "Access-Control-Allow-Methods", value: "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
|
||||
{ key: "Access-Control-Allow-Headers", value: "*" },
|
||||
{ key: "Access-Control-Allow-Private-Network", value: "true" },
|
||||
{
|
||||
key: "Content-Security-Policy",
|
||||
value: [
|
||||
@@ -56,7 +55,9 @@ const nextConfig: NextConfig = {
|
||||
},
|
||||
|
||||
outputFileTracingExcludes: {
|
||||
"*": ["./public/cesium/**"],
|
||||
"*": [
|
||||
"./public/cesium/**"
|
||||
],
|
||||
},
|
||||
env: {
|
||||
CESIUM_BASE_URL: "/cesium",
|
||||
|
||||
+15
-9
@@ -1,7 +1,8 @@
|
||||
{
|
||||
"name": "worldwideview",
|
||||
"version": "1.20.3",
|
||||
"version": "2.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"packageManager": "[email protected]",
|
||||
"scripts": {
|
||||
"setup": "node scripts/setup.mjs",
|
||||
@@ -10,19 +11,23 @@
|
||||
"dev": "next dev --webpack",
|
||||
"dev:all": "concurrently -n \"next,backends\" -c \"magenta,blue\" \"pnpm dev\" \"pnpm dev:backends\"",
|
||||
"dev:backends": "cd ../wwv-data-engine && pnpm dev",
|
||||
"predev": "npx prisma migrate deploy && node scripts/copy-cesium.mjs",
|
||||
"predev": "node scripts/boot-db.mjs && npx dotenv-cli -e .env.local -c -- npx prisma db push --accept-data-loss && npx prisma generate && node scripts/copy-cesium.mjs",
|
||||
"copy-cesium": "node scripts/copy-cesium.mjs",
|
||||
"build": "next build --webpack",
|
||||
"start": "next start",
|
||||
"test": "vitest run",
|
||||
"db:reset": "npx prisma migrate reset --force"
|
||||
"db:reset": "npx prisma migrate reset --force",
|
||||
"generate": "prisma generate"
|
||||
},
|
||||
"dependencies": {
|
||||
"@auth/prisma-adapter": "^2.11.1",
|
||||
"@prisma/adapter-better-sqlite3": "^7.5.0",
|
||||
"@prisma/client": "^7.5.0",
|
||||
"@auth/supabase-adapter": "^1.11.2",
|
||||
"@prisma/adapter-pg": "^7.6.0",
|
||||
"@prisma/client": "^7.6.0",
|
||||
"@prisma/client-runtime-utils": "7.6.0",
|
||||
"@sentry/nextjs": "^10.48.0",
|
||||
"@supabase/supabase-js": "^2.98.0",
|
||||
"@types/pg": "^8.20.0",
|
||||
"@vercel/analytics": "^1.6.1",
|
||||
"@worldwideview/wwv-plugin-sdk": "workspace:*",
|
||||
"bcryptjs": "^3.0.3",
|
||||
@@ -34,12 +39,14 @@
|
||||
"lucide-react": "^0.576.0",
|
||||
"next": "16.2.3",
|
||||
"next-auth": "^5.0.0-beta.30",
|
||||
"prisma": "^7.5.0",
|
||||
"pg": "^8.20.0",
|
||||
"prisma": "^7.6.0",
|
||||
"react": "19.2.3",
|
||||
"react-dom": "19.2.3",
|
||||
"react-player": "^3.4.0",
|
||||
"resium": "1.19.4",
|
||||
"satellite.js": "^7.0.0",
|
||||
"stripe": "^22.1.1",
|
||||
"tslib": "^2.8.1",
|
||||
"ws": "^8.14.2",
|
||||
"zustand": "^5.0.11"
|
||||
@@ -58,6 +65,7 @@
|
||||
"copy-webpack-plugin": "^14.0.0",
|
||||
"jsdom": "^28.1.0",
|
||||
"rollup-plugin-external-globals": "^0.13.0",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^5",
|
||||
"vite": "^8.0.8",
|
||||
"vitest": "^4.0.18"
|
||||
@@ -66,12 +74,10 @@
|
||||
"onlyBuiltDependencies": [
|
||||
"@prisma/engines",
|
||||
"@sentry/cli",
|
||||
"better-sqlite3",
|
||||
"esbuild",
|
||||
"prisma",
|
||||
"protobufjs",
|
||||
"sharp",
|
||||
"unrs-resolver"
|
||||
"esbuild"
|
||||
]
|
||||
}
|
||||
}
|
||||
Generated
+208
-89
@@ -11,18 +11,27 @@ importers:
|
||||
'@auth/prisma-adapter':
|
||||
specifier: ^2.11.1
|
||||
version: 2.11.1(@prisma/[email protected]([email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]))
|
||||
'@prisma/adapter-better-sqlite3':
|
||||
specifier: ^7.5.0
|
||||
'@auth/supabase-adapter':
|
||||
specifier: ^1.11.2
|
||||
version: 1.11.2(@supabase/[email protected])
|
||||
'@prisma/adapter-pg':
|
||||
specifier: ^7.6.0
|
||||
version: 7.6.0
|
||||
'@prisma/client':
|
||||
specifier: ^7.5.0
|
||||
specifier: ^7.6.0
|
||||
version: 7.6.0([email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])
|
||||
'@prisma/client-runtime-utils':
|
||||
specifier: 7.6.0
|
||||
version: 7.6.0
|
||||
'@sentry/nextjs':
|
||||
specifier: ^10.48.0
|
||||
version: 10.48.0(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))
|
||||
'@supabase/supabase-js':
|
||||
specifier: ^2.98.0
|
||||
version: 2.100.1
|
||||
'@types/pg':
|
||||
specifier: ^8.20.0
|
||||
version: 8.20.0
|
||||
'@vercel/analytics':
|
||||
specifier: ^1.6.1
|
||||
version: 1.6.1([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])
|
||||
@@ -56,8 +65,11 @@ importers:
|
||||
next-auth:
|
||||
specifier: ^5.0.0-beta.30
|
||||
version: 5.0.0-beta.30([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])
|
||||
pg:
|
||||
specifier: ^8.20.0
|
||||
version: 8.20.0
|
||||
prisma:
|
||||
specifier: ^7.5.0
|
||||
specifier: ^7.6.0
|
||||
version: 7.6.0(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])
|
||||
react:
|
||||
specifier: 19.2.3
|
||||
@@ -74,6 +86,9 @@ importers:
|
||||
satellite.js:
|
||||
specifier: ^7.0.0
|
||||
version: 7.0.0
|
||||
stripe:
|
||||
specifier: ^22.1.1
|
||||
version: 22.1.1(@types/[email protected])
|
||||
tslib:
|
||||
specifier: ^2.8.1
|
||||
version: 2.8.1
|
||||
@@ -123,6 +138,9 @@ importers:
|
||||
rollup-plugin-external-globals:
|
||||
specifier: ^0.13.0
|
||||
version: 0.13.0([email protected])
|
||||
tsx:
|
||||
specifier: ^4.21.0
|
||||
version: 4.21.0
|
||||
typescript:
|
||||
specifier: ^5
|
||||
version: 5.9.3
|
||||
@@ -189,11 +207,30 @@ packages:
|
||||
nodemailer:
|
||||
optional: true
|
||||
|
||||
'@auth/[email protected]':
|
||||
resolution: {integrity: sha512-Hx5MNBxN2fJTbJKGUKAA0wca43D0Akl3TvufY54Gn8lop7F+34vU1zA1pn0vQfIoVuLIrpfc2nkyjwIaPJMW7w==}
|
||||
peerDependencies:
|
||||
'@simplewebauthn/browser': ^9.0.1
|
||||
'@simplewebauthn/server': ^9.0.2
|
||||
nodemailer: ^7.0.7
|
||||
peerDependenciesMeta:
|
||||
'@simplewebauthn/browser':
|
||||
optional: true
|
||||
'@simplewebauthn/server':
|
||||
optional: true
|
||||
nodemailer:
|
||||
optional: true
|
||||
|
||||
'@auth/[email protected]':
|
||||
resolution: {integrity: sha512-Ke7DXP0Fy0Mlmjz/ZJLXwQash2UkA4621xCM0rMtEczr1kppLc/njCbUkHkIQ/PnmILjqSPEKeTjDPsYruvkug==}
|
||||
peerDependencies:
|
||||
'@prisma/client': '>=2.26.0 || >=3 || >=4 || >=5 || >=6'
|
||||
|
||||
'@auth/[email protected]':
|
||||
resolution: {integrity: sha512-8MmstnTw+mhFHxHZUlkY+pLj1aryZIIXtz9C0X/faZMXbCtR5ijnjZsv8F8RDsgeQGcz/dp654nH4fb6z8tR3g==}
|
||||
peerDependencies:
|
||||
'@supabase/supabase-js': ^2.43.1
|
||||
|
||||
'@babel/[email protected]':
|
||||
resolution: {integrity: sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==}
|
||||
engines: {node: '>=6.9.0'}
|
||||
@@ -567,105 +604,89 @@ packages:
|
||||
resolution: {integrity: sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@img/[email protected]':
|
||||
resolution: {integrity: sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@img/[email protected]':
|
||||
resolution: {integrity: sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==}
|
||||
cpu: [ppc64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@img/[email protected]':
|
||||
resolution: {integrity: sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@img/[email protected]':
|
||||
resolution: {integrity: sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==}
|
||||
cpu: [s390x]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@img/[email protected]':
|
||||
resolution: {integrity: sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@img/[email protected]':
|
||||
resolution: {integrity: sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@img/[email protected]':
|
||||
resolution: {integrity: sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@img/[email protected]':
|
||||
resolution: {integrity: sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==}
|
||||
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@img/[email protected]':
|
||||
resolution: {integrity: sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==}
|
||||
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@img/[email protected]':
|
||||
resolution: {integrity: sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==}
|
||||
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
|
||||
cpu: [ppc64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@img/[email protected]':
|
||||
resolution: {integrity: sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==}
|
||||
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@img/[email protected]':
|
||||
resolution: {integrity: sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==}
|
||||
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
|
||||
cpu: [s390x]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@img/[email protected]':
|
||||
resolution: {integrity: sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==}
|
||||
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@img/[email protected]':
|
||||
resolution: {integrity: sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==}
|
||||
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@img/[email protected]':
|
||||
resolution: {integrity: sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==}
|
||||
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@img/[email protected]':
|
||||
resolution: {integrity: sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==}
|
||||
@@ -763,28 +784,24 @@ packages:
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@next/[email protected]':
|
||||
resolution: {integrity: sha512-/YV0LgjHUmfhQpn9bVoGc4x4nan64pkhWR5wyEV8yCOfwwrH630KpvRg86olQHTwHIn1z59uh6JwKvHq1h4QEw==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@next/[email protected]':
|
||||
resolution: {integrity: sha512-/HiWEcp+WMZ7VajuiMEFGZ6cg0+aYZPqCJD3YJEfpVWQsKYSjXQG06vJP6F1rdA03COD9Fef4aODs3YxKx+RDQ==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@next/[email protected]':
|
||||
resolution: {integrity: sha512-Kt44hGJfZSefebhk/7nIdivoDr3Ugp5+oNz9VvF3GUtfxutucUIHfIO0ZYO8QlOPDQloUVQn4NVC/9JvHRk9hw==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@next/[email protected]':
|
||||
resolution: {integrity: sha512-O2NZ9ie3Tq6xj5Z5CSwBT3+aWAMW2PIZ4egUi9MaWLkwaehgtB7YZjPm+UpcNpKOme0IQuqDcor7BsW6QBiQBw==}
|
||||
@@ -1002,8 +1019,8 @@ packages:
|
||||
'@panva/[email protected]':
|
||||
resolution: {integrity: sha512-6oclG6Y3PiDFcoyk8srjLfVKyMfVCKJ27JwNPViuXziFpmdz+MZnZN/aKY0JGXgYuO/VghU0jcOAZgWXZ1Dmrw==}
|
||||
|
||||
'@prisma/adapter-better-sqlite3@7.6.0':
|
||||
resolution: {integrity: sha512-V0bU2nbFwwqCgzIEFDCmywNoqH9ilCYa6S32hGQxIgRbkgFC2eTl4+AJ6G+jfP0BZs3LXUirreoGNbSY/zbUGQ==}
|
||||
'@prisma/adapter-pg@7.6.0':
|
||||
resolution: {integrity: sha512-BjHNmJqqa42NqJSDPnXUfwUofWo8LJY7Ui2gqxN4DmAOb+H/gGKv+hln2Xq/1kSJXPW5AXMXuNiPDMpywvyIOw==}
|
||||
|
||||
'@prisma/[email protected]':
|
||||
resolution: {integrity: sha512-fD7jlqubsZvVODKvsp9lOpXVecx2aWGxC2l35Ioz2t+teUJ5CfR0SAMsi7UkU1VvaZmmm+DS6BdujF622nY7tQ==}
|
||||
@@ -1209,42 +1226,36 @@ packages:
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rolldown/[email protected]':
|
||||
resolution: {integrity: sha512-ZvRYMGrAklV9PEkgt4LQM6MjQX2P58HPAuecwYObY2DhS2t35R0I810bKi0wmaYORt6m/2Sm+Z+nFgb0WhXNcQ==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@rolldown/[email protected]':
|
||||
resolution: {integrity: sha512-VDpgGBzgfg5hLg+uBpCLoFG5kVvEyafmfxGUV0UHLcL5irxAK7PKNeC2MwClgk6ZAiNhmo9FLhRYgvMmedLtnQ==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [ppc64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rolldown/[email protected]':
|
||||
resolution: {integrity: sha512-y1uXY3qQWCzcPgRJATPSOUP4tCemh4uBdY7e3EZbVwCJTY3gLJWnQABgeUetvED+bt1FQ01OeZwvhLS2bpNrAQ==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [s390x]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rolldown/[email protected]':
|
||||
resolution: {integrity: sha512-023bTPBod7J3Y/4fzAN6QtpkSABR0rigtrwaP+qSEabUh5zf6ELr9Nc7GujaROuPY3uwdSIXWrvhn1KxOvurWA==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rolldown/[email protected]':
|
||||
resolution: {integrity: sha512-witB2O0/hU4CgfOOKUoeFgQ4GktPi1eEbAhaLAIpgD6+ZnhcPkUtPsoKKHRzmOoWPZue46IThdSgdo4XneOLYw==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@rolldown/[email protected]':
|
||||
resolution: {integrity: sha512-UCL68NJ0Ud5zRipXZE9dF5PmirzJE4E4BCIOOssEnM7wLDsxjc6Qb0sGDxTNRTP53I6MZpygyCpY8Aa8sPfKPg==}
|
||||
@@ -1327,79 +1338,66 @@ packages:
|
||||
resolution: {integrity: sha512-L+34Qqil+v5uC0zEubW7uByo78WOCIrBvci69E7sFASRl0X7b/MB6Cqd1lky/CtcSVTydWa2WZwFuWexjS5o6g==}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rollup/[email protected]':
|
||||
resolution: {integrity: sha512-n83O8rt4v34hgFzlkb1ycniJh7IR5RCIqt6mz1VRJD6pmhRi0CXdmfnLu9dIUS6buzh60IvACM842Ffb3xd6Gg==}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@rollup/[email protected]':
|
||||
resolution: {integrity: sha512-Nql7sTeAzhTAja3QXeAI48+/+GjBJ+QmAH13snn0AJSNL50JsDqotyudHyMbO2RbJkskbMbFJfIJKWA6R1LCJQ==}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rollup/[email protected]':
|
||||
resolution: {integrity: sha512-+pUymDhd0ys9GcKZPPWlFiZ67sTWV5UU6zOJat02M1+PiuSGDziyRuI/pPue3hoUwm2uGfxdL+trT6Z9rxnlMA==}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@rollup/[email protected]':
|
||||
resolution: {integrity: sha512-VSvgvQeIcsEvY4bKDHEDWcpW4Yw7BtlKG1GUT4FzBUlEKQK0rWHYBqQt6Fm2taXS+1bXvJT6kICu5ZwqKCnvlQ==}
|
||||
cpu: [loong64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rollup/[email protected]':
|
||||
resolution: {integrity: sha512-4LqhUomJqwe641gsPp6xLfhqWMbQV04KtPp7/dIp0nzPxAkNY1AbwL5W0MQpcalLYk07vaW9Kp1PBhdpZYYcEw==}
|
||||
cpu: [loong64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@rollup/[email protected]':
|
||||
resolution: {integrity: sha512-tLQQ9aPvkBxOc/EUT6j3pyeMD6Hb8QF2BTBnCQWP/uu1lhc9AIrIjKnLYMEroIz/JvtGYgI9dF3AxHZNaEH0rw==}
|
||||
cpu: [ppc64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rollup/[email protected]':
|
||||
resolution: {integrity: sha512-RMxFhJwc9fSXP6PqmAz4cbv3kAyvD1etJFjTx4ONqFP9DkTkXsAMU4v3Vyc5BgzC+anz7nS/9tp4obsKfqkDHg==}
|
||||
cpu: [ppc64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@rollup/[email protected]':
|
||||
resolution: {integrity: sha512-QKgFl+Yc1eEk6MmOBfRHYF6lTxiiiV3/z/BRrbSiW2I7AFTXoBFvdMEyglohPj//2mZS4hDOqeB0H1ACh3sBbg==}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rollup/[email protected]':
|
||||
resolution: {integrity: sha512-RAjXjP/8c6ZtzatZcA1RaQr6O1TRhzC+adn8YZDnChliZHviqIjmvFwHcxi4JKPSDAt6Uhf/7vqcBzQJy0PDJg==}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@rollup/[email protected]':
|
||||
resolution: {integrity: sha512-wcuocpaOlaL1COBYiA89O6yfjlp3RwKDeTIA0hM7OpmhR1Bjo9j31G1uQVpDlTvwxGn2nQs65fBFL5UFd76FcQ==}
|
||||
cpu: [s390x]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rollup/[email protected]':
|
||||
resolution: {integrity: sha512-77PpsFQUCOiZR9+LQEFg9GClyfkNXj1MP6wRnzYs0EeWbPcHs02AXu4xuUbM1zhwn3wqaizle3AEYg5aeoohhg==}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rollup/[email protected]':
|
||||
resolution: {integrity: sha512-5cIATbk5vynAjqqmyBjlciMJl1+R/CwX9oLk/EyiFXDWd95KpHdrOJT//rnUl4cUcskrd0jCCw3wpZnhIHdD9w==}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@rollup/[email protected]':
|
||||
resolution: {integrity: sha512-cl0w09WsCi17mcmWqqglez9Gk8isgeWvoUZ3WiJFYSR3zjBQc2J5/ihSjpl+VLjPqjQ/1hJRcqBfLjssREQILw==}
|
||||
@@ -1755,15 +1753,15 @@ packages:
|
||||
'@types/[email protected]':
|
||||
resolution: {integrity: sha512-8kzdPJ3FsNsVIurqBs7oodNnCEVbni9yUEkaHbgptDACOPW04jimGagZ51E6+lXUwJjgnBw+hyko/lkFWCldqw==}
|
||||
|
||||
'@types/[email protected]':
|
||||
resolution: {integrity: sha512-F0R/h2+dsy5wJAUe3tAU6oqa2qbWY5TpNfL/RGmo1y38hiyO1w3x2jPtt76wmuaJI4DQnOBu21cNXQ2STIUUWg==}
|
||||
|
||||
'@types/[email protected]':
|
||||
resolution: {integrity: sha512-U4CwmGVQcbEuqpyju8/ptOKg6gEC+Tqsvj2xS9o1g71bUh8twxnC6ZL5rZKCsGN0iyH0CwgUyc9VR5owNQF9Ng==}
|
||||
|
||||
'@types/[email protected]':
|
||||
resolution: {integrity: sha512-NoaMtzhxOrubeL/7UZuNTrejB4MPAJ0RpxZqXQf2qXuVlTPuG6Y8p4u9dKRaue4yjmC7ZhzVO2/Yyyn25znrPQ==}
|
||||
|
||||
'@types/[email protected]':
|
||||
resolution: {integrity: sha512-bEPFOaMAHTEP1EzpvHTbmwR8UsFyHSKsRisLIHVMXnpNefSbGA1bD6CVy+qKjGSqmZqNqBDV2azOBo8TgkcVow==}
|
||||
|
||||
'@types/[email protected]':
|
||||
resolution: {integrity: sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==}
|
||||
peerDependencies:
|
||||
@@ -2721,28 +2719,24 @@ packages:
|
||||
engines: {node: '>= 12.0.0'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==}
|
||||
engines: {node: '>= 12.0.0'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==}
|
||||
engines: {node: '>= 12.0.0'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==}
|
||||
engines: {node: '>= 12.0.0'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==}
|
||||
@@ -3019,10 +3013,21 @@ packages:
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-6lswVVSztmHiRtD6I8hw4qP/nDm1EJbKMRhf3HCYaqud7frGysPv7FYJ5noZQdhQtN2xJnimfMtvQq21pdbzyQ==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-U7qg+bpswf3Cs5xLzRqbXbQl85ng0mfSV/J0nnA31MCLgvEaAo7CIhmeyrmJpOr7o+zm0rXK+hNnT5l9RHkCkQ==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==}
|
||||
engines: {node: '>=4.0.0'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-gB+R+Xud1gLFuRD/QgOIgGOBE2KCQPaPwkzBBGC9oG69pHTkhQeIuejVIk3/cnDyX39av2AxomQiyPT13WKHQA==}
|
||||
peerDependencies:
|
||||
pg: '>=8.0'
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-zzdvXfS6v89r6v7OcFCHfHlyG/wvry1ALxZo4LqgUoy7W9xhBDMaqOuMiF3qEV45VqsN6rdlcehHrfDtlCPc8w==}
|
||||
|
||||
@@ -3030,6 +3035,18 @@ packages:
|
||||
resolution: {integrity: sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==}
|
||||
engines: {node: '>=4'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-ldhMxz2r8fl/6QkXnBD3CR9/xg694oT6DZQ2s6c/RI28OjtSOpxnPrUCGOBJ46RCUxcWdx3p6kw/xnDHjKvaRA==}
|
||||
engines: {node: '>= 16.0.0'}
|
||||
peerDependencies:
|
||||
pg-native: '>=3.0.1'
|
||||
peerDependenciesMeta:
|
||||
pg-native:
|
||||
optional: true
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
|
||||
|
||||
@@ -3055,6 +3072,10 @@ packages:
|
||||
resolution: {integrity: sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==}
|
||||
engines: {node: '>=4'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-nAUSGfSDGOaOAEGwqsRY27GPOea7CNipJPOA7lPbdEpx5Kg3qzdP0AaWC5MlhTWV9s4hFX39nomVZ+C4tnGOJQ==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
@@ -3321,6 +3342,10 @@ packages:
|
||||
resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==}
|
||||
engines: {node: '>= 10.x'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-QdKrJPkYCzaNwwz2vN2eDGyoW0KmQFmnwVprB41mpMzj4qujbqr6pegEchQeTn0b5PceKiLoVu0pp2QDpTcWnw==}
|
||||
|
||||
@@ -3361,6 +3386,15 @@ packages:
|
||||
resolution: {integrity: sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-cmodIYP27tBkJ8G7DuGgWw0PFuemlFZbuF3Wwr1TrjFjUa3T7NIgCe6TVwX8BO2ynu+xtTuDGfHafNDCPt9lXA==}
|
||||
engines: {node: '>=18'}
|
||||
peerDependencies:
|
||||
'@types/node': '>=18'
|
||||
peerDependenciesMeta:
|
||||
'@types/node':
|
||||
optional: true
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA==}
|
||||
engines: {node: '>= 12.0.0'}
|
||||
@@ -3527,7 +3561,7 @@ packages:
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==}
|
||||
deprecated: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.
|
||||
deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).
|
||||
hasBin: true
|
||||
|
||||
[email protected]:
|
||||
@@ -3800,6 +3834,14 @@ snapshots:
|
||||
preact: 10.24.3
|
||||
preact-render-to-string: 6.5.11([email protected])
|
||||
|
||||
'@auth/[email protected]':
|
||||
dependencies:
|
||||
'@panva/hkdf': 1.2.1
|
||||
jose: 6.2.2
|
||||
oauth4webapi: 3.8.5
|
||||
preact: 10.24.3
|
||||
preact-render-to-string: 6.5.11([email protected])
|
||||
|
||||
'@auth/[email protected](@prisma/[email protected]([email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]))':
|
||||
dependencies:
|
||||
'@auth/core': 0.41.1
|
||||
@@ -3809,6 +3851,15 @@ snapshots:
|
||||
- '@simplewebauthn/server'
|
||||
- nodemailer
|
||||
|
||||
'@auth/[email protected](@supabase/[email protected])':
|
||||
dependencies:
|
||||
'@auth/core': 0.41.2
|
||||
'@supabase/supabase-js': 2.100.1
|
||||
transitivePeerDependencies:
|
||||
- '@simplewebauthn/browser'
|
||||
- '@simplewebauthn/server'
|
||||
- nodemailer
|
||||
|
||||
'@babel/[email protected]':
|
||||
dependencies:
|
||||
'@babel/helper-validator-identifier': 7.28.5
|
||||
@@ -4564,10 +4615,14 @@ snapshots:
|
||||
|
||||
'@panva/[email protected]': {}
|
||||
|
||||
'@prisma/adapter-better-sqlite3@7.6.0':
|
||||
'@prisma/adapter-pg@7.6.0':
|
||||
dependencies:
|
||||
'@prisma/driver-adapter-utils': 7.6.0
|
||||
better-sqlite3: 12.8.0
|
||||
'@types/pg': 8.20.0
|
||||
pg: 8.20.0
|
||||
postgres-array: 3.0.4
|
||||
transitivePeerDependencies:
|
||||
- pg-native
|
||||
|
||||
'@prisma/[email protected]': {}
|
||||
|
||||
@@ -5245,7 +5300,7 @@ snapshots:
|
||||
|
||||
'@types/[email protected]':
|
||||
dependencies:
|
||||
'@types/node': 22.19.15
|
||||
'@types/node': 20.19.37
|
||||
|
||||
'@types/[email protected]': {}
|
||||
|
||||
@@ -5265,23 +5320,25 @@ snapshots:
|
||||
|
||||
'@types/[email protected]':
|
||||
dependencies:
|
||||
'@types/node': 22.19.15
|
||||
'@types/node': 20.19.37
|
||||
|
||||
'@types/[email protected]':
|
||||
dependencies:
|
||||
undici-types: 6.21.0
|
||||
|
||||
'@types/[email protected]':
|
||||
dependencies:
|
||||
undici-types: 6.21.0
|
||||
|
||||
'@types/[email protected]':
|
||||
dependencies:
|
||||
'@types/pg': 8.15.6
|
||||
'@types/pg': 8.20.0
|
||||
|
||||
'@types/[email protected]':
|
||||
dependencies:
|
||||
'@types/node': 22.19.15
|
||||
'@types/node': 20.19.37
|
||||
pg-protocol: 1.13.0
|
||||
pg-types: 2.2.0
|
||||
|
||||
'@types/[email protected]':
|
||||
dependencies:
|
||||
'@types/node': 20.19.37
|
||||
pg-protocol: 1.13.0
|
||||
pg-types: 2.2.0
|
||||
|
||||
@@ -5295,7 +5352,7 @@ snapshots:
|
||||
|
||||
'@types/[email protected]':
|
||||
dependencies:
|
||||
'@types/node': 22.19.15
|
||||
'@types/node': 20.19.37
|
||||
|
||||
'@types/[email protected]':
|
||||
optional: true
|
||||
@@ -5524,7 +5581,8 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
[email protected]:
|
||||
optional: true
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
@@ -5555,6 +5613,7 @@ snapshots:
|
||||
dependencies:
|
||||
bindings: 1.5.0
|
||||
prebuild-install: 7.1.3
|
||||
optional: true
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -5563,6 +5622,7 @@ snapshots:
|
||||
[email protected]:
|
||||
dependencies:
|
||||
file-uri-to-path: 1.0.0
|
||||
optional: true
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
@@ -5571,6 +5631,7 @@ snapshots:
|
||||
buffer: 5.7.1
|
||||
inherits: 2.0.4
|
||||
readable-stream: 3.6.2
|
||||
optional: true
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
@@ -5592,6 +5653,7 @@ snapshots:
|
||||
dependencies:
|
||||
base64-js: 1.5.1
|
||||
ieee754: 1.2.1
|
||||
optional: true
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -5663,7 +5725,8 @@ snapshots:
|
||||
dependencies:
|
||||
readdirp: 4.1.2
|
||||
|
||||
[email protected]: {}
|
||||
[email protected]:
|
||||
optional: true
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
@@ -5812,8 +5875,10 @@ snapshots:
|
||||
[email protected]:
|
||||
dependencies:
|
||||
mimic-response: 3.1.0
|
||||
optional: true
|
||||
|
||||
[email protected]: {}
|
||||
[email protected]:
|
||||
optional: true
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
@@ -5883,6 +5948,7 @@ snapshots:
|
||||
[email protected]:
|
||||
dependencies:
|
||||
once: 1.4.0
|
||||
optional: true
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -5927,7 +5993,6 @@ snapshots:
|
||||
'@esbuild/win32-arm64': 0.27.4
|
||||
'@esbuild/win32-ia32': 0.27.4
|
||||
'@esbuild/win32-x64': 0.27.4
|
||||
optional: true
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
@@ -5952,7 +6017,8 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
[email protected]:
|
||||
optional: true
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
@@ -5976,7 +6042,8 @@ snapshots:
|
||||
optionalDependencies:
|
||||
picomatch: 4.0.4
|
||||
|
||||
[email protected]: {}
|
||||
[email protected]:
|
||||
optional: true
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -5998,7 +6065,8 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
[email protected]:
|
||||
optional: true
|
||||
|
||||
[email protected]:
|
||||
optional: true
|
||||
@@ -6016,7 +6084,6 @@ snapshots:
|
||||
[email protected]:
|
||||
dependencies:
|
||||
resolve-pkg-maps: 1.0.0
|
||||
optional: true
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -6031,7 +6098,8 @@ snapshots:
|
||||
nypm: 0.6.5
|
||||
pathe: 2.0.3
|
||||
|
||||
[email protected]: {}
|
||||
[email protected]:
|
||||
optional: true
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -6126,7 +6194,8 @@ snapshots:
|
||||
dependencies:
|
||||
safer-buffer: 2.1.2
|
||||
|
||||
[email protected]: {}
|
||||
[email protected]:
|
||||
optional: true
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
@@ -6148,9 +6217,11 @@ snapshots:
|
||||
dependencies:
|
||||
sax: 1.2.1
|
||||
|
||||
[email protected]: {}
|
||||
[email protected]:
|
||||
optional: true
|
||||
|
||||
[email protected]: {}
|
||||
[email protected]:
|
||||
optional: true
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -6379,17 +6450,20 @@ snapshots:
|
||||
dependencies:
|
||||
mime-db: 1.52.0
|
||||
|
||||
[email protected]: {}
|
||||
[email protected]:
|
||||
optional: true
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
brace-expansion: 5.0.5
|
||||
|
||||
[email protected]: {}
|
||||
[email protected]:
|
||||
optional: true
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
[email protected]:
|
||||
optional: true
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
@@ -6415,7 +6489,8 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
[email protected]:
|
||||
optional: true
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
@@ -6455,6 +6530,7 @@ snapshots:
|
||||
[email protected]:
|
||||
dependencies:
|
||||
semver: 7.7.4
|
||||
optional: true
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
@@ -6491,6 +6567,7 @@ snapshots:
|
||||
[email protected]:
|
||||
dependencies:
|
||||
wrappy: 1.0.2
|
||||
optional: true
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -6536,8 +6613,17 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]:
|
||||
optional: true
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]([email protected]):
|
||||
dependencies:
|
||||
pg: 8.20.0
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]:
|
||||
@@ -6548,6 +6634,20 @@ snapshots:
|
||||
postgres-date: 1.0.7
|
||||
postgres-interval: 1.2.0
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
pg-connection-string: 2.12.0
|
||||
pg-pool: 3.13.0([email protected])
|
||||
pg-protocol: 1.13.0
|
||||
pg-types: 2.2.0
|
||||
pgpass: 1.0.5
|
||||
optionalDependencies:
|
||||
pg-cloudflare: 1.3.0
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
split2: 4.2.0
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
@@ -6578,6 +6678,8 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
@@ -6608,6 +6710,7 @@ snapshots:
|
||||
simple-get: 4.0.1
|
||||
tar-fs: 2.1.4
|
||||
tunnel-agent: 0.6.0
|
||||
optional: true
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -6659,7 +6762,7 @@ snapshots:
|
||||
'@protobufjs/path': 1.1.2
|
||||
'@protobufjs/pool': 1.1.0
|
||||
'@protobufjs/utf8': 1.1.0
|
||||
'@types/node': 22.19.15
|
||||
'@types/node': 20.19.37
|
||||
long: 5.3.2
|
||||
|
||||
[email protected]: {}
|
||||
@@ -6672,6 +6775,7 @@ snapshots:
|
||||
dependencies:
|
||||
end-of-stream: 1.4.5
|
||||
once: 1.4.0
|
||||
optional: true
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
@@ -6696,6 +6800,7 @@ snapshots:
|
||||
ini: 1.3.8
|
||||
minimist: 1.2.8
|
||||
strip-json-comments: 2.0.1
|
||||
optional: true
|
||||
|
||||
[email protected]([email protected]):
|
||||
dependencies:
|
||||
@@ -6736,6 +6841,7 @@ snapshots:
|
||||
inherits: 2.0.4
|
||||
string_decoder: 1.3.0
|
||||
util-deprecate: 1.0.2
|
||||
optional: true
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
@@ -6781,8 +6887,7 @@ snapshots:
|
||||
react: 19.2.3
|
||||
react-dom: 19.2.3([email protected])
|
||||
|
||||
[email protected]:
|
||||
optional: true
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
@@ -6873,7 +6978,8 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
[email protected]:
|
||||
optional: true
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
@@ -6925,13 +7031,15 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
[email protected]:
|
||||
optional: true
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
decompress-response: 6.0.0
|
||||
once: 1.4.0
|
||||
simple-concat: 1.0.1
|
||||
optional: true
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
@@ -6944,6 +7052,8 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
@@ -6979,12 +7089,18 @@ snapshots:
|
||||
[email protected]:
|
||||
dependencies:
|
||||
safe-buffer: 5.2.1
|
||||
optional: true
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
ansi-regex: 5.0.1
|
||||
|
||||
[email protected]: {}
|
||||
[email protected]:
|
||||
optional: true
|
||||
|
||||
[email protected](@types/[email protected]):
|
||||
optionalDependencies:
|
||||
'@types/node': 20.19.37
|
||||
|
||||
[email protected](@babel/[email protected])([email protected]):
|
||||
dependencies:
|
||||
@@ -7013,6 +7129,7 @@ snapshots:
|
||||
mkdirp-classic: 0.5.3
|
||||
pump: 3.0.4
|
||||
tar-stream: 2.2.0
|
||||
optional: true
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -7021,6 +7138,7 @@ snapshots:
|
||||
fs-constants: 1.0.0
|
||||
inherits: 2.0.4
|
||||
readable-stream: 3.6.2
|
||||
optional: true
|
||||
|
||||
[email protected]([email protected])([email protected]([email protected])):
|
||||
dependencies:
|
||||
@@ -7087,7 +7205,6 @@ snapshots:
|
||||
get-tsconfig: 4.13.7
|
||||
optionalDependencies:
|
||||
fsevents: 2.3.3
|
||||
optional: true
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -7124,7 +7241,8 @@ snapshots:
|
||||
react: 19.2.3
|
||||
optional: true
|
||||
|
||||
[email protected]: {}
|
||||
[email protected]:
|
||||
optional: true
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
@@ -7276,7 +7394,8 @@ snapshots:
|
||||
string-width: 4.2.3
|
||||
strip-ansi: 6.0.1
|
||||
|
||||
[email protected]: {}
|
||||
[email protected]:
|
||||
optional: true
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
|
||||
+14
-4
@@ -5,14 +5,24 @@ let dbUrl = process.env.DATABASE_URL;
|
||||
|
||||
if (!dbUrl) {
|
||||
try {
|
||||
const envPath = path.resolve(process.cwd(), ".env");
|
||||
if (fs.existsSync(envPath)) {
|
||||
const envContent = fs.readFileSync(envPath, "utf8");
|
||||
const match = envContent.match(/^DATABASE_URL=(.*)$/m);
|
||||
const envLocalPath = path.resolve(process.cwd(), ".env.local");
|
||||
if (fs.existsSync(envLocalPath)) {
|
||||
const envContent = fs.readFileSync(envLocalPath, "utf8");
|
||||
const match = envContent.match(/^DATABASE_URL=["']?(.*?)["']?$/m);
|
||||
if (match) {
|
||||
dbUrl = match[1].trim();
|
||||
}
|
||||
}
|
||||
if (!dbUrl) {
|
||||
const envPath = path.resolve(process.cwd(), ".env");
|
||||
if (fs.existsSync(envPath)) {
|
||||
const envContent = fs.readFileSync(envPath, "utf8");
|
||||
const match = envContent.match(/^DATABASE_URL=["']?(.*?)["']?$/m);
|
||||
if (match) {
|
||||
dbUrl = match[1].trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// Ignore
|
||||
}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "users" (
|
||||
"id" TEXT NOT NULL,
|
||||
"tenantId" TEXT,
|
||||
"email" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"hashedPassword" TEXT NOT NULL,
|
||||
"role" TEXT NOT NULL DEFAULT 'user',
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "users_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "favorites" (
|
||||
"id" TEXT NOT NULL,
|
||||
"tenantId" TEXT,
|
||||
"entityId" TEXT NOT NULL,
|
||||
"pluginId" TEXT NOT NULL,
|
||||
"label" TEXT NOT NULL,
|
||||
"pluginName" TEXT NOT NULL,
|
||||
"lastSeen" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"userId" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "favorites_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "installed_plugins" (
|
||||
"id" TEXT NOT NULL,
|
||||
"tenantId" TEXT,
|
||||
"pluginId" TEXT NOT NULL,
|
||||
"version" TEXT NOT NULL,
|
||||
"config" TEXT NOT NULL DEFAULT '{}',
|
||||
"enabled" BOOLEAN NOT NULL DEFAULT true,
|
||||
"installedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "installed_plugins_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "settings" (
|
||||
"id" TEXT NOT NULL,
|
||||
"tenantId" TEXT,
|
||||
"key" TEXT NOT NULL,
|
||||
"value" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "settings_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "workspaces" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"subdomain" TEXT NOT NULL,
|
||||
"status" TEXT NOT NULL DEFAULT 'trialing',
|
||||
"plan" TEXT NOT NULL DEFAULT 'basic',
|
||||
"stripeCustomerId" TEXT,
|
||||
"stripeSubscriptionId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "workspaces_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "workspace_members" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"workspaceId" TEXT NOT NULL,
|
||||
"role" TEXT NOT NULL DEFAULT 'member',
|
||||
"joinedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "workspace_members_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "users_tenantId_email_key" ON "users"("tenantId", "email");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "favorites_userId_entityId_key" ON "favorites"("userId", "entityId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "installed_plugins_tenantId_pluginId_key" ON "installed_plugins"("tenantId", "pluginId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "settings_tenantId_key_key" ON "settings"("tenantId", "key");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "workspaces_subdomain_key" ON "workspaces"("subdomain");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "workspace_members_userId_workspaceId_key" ON "workspace_members"("userId", "workspaceId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "favorites" ADD CONSTRAINT "favorites_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "workspace_members" ADD CONSTRAINT "workspace_members_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "workspace_members" ADD CONSTRAINT "workspace_members_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES "workspaces"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -1,3 +1,3 @@
|
||||
# Please do not edit this file manually
|
||||
# It should be added in your version-control system (e.g., Git)
|
||||
provider = "sqlite"
|
||||
provider = "postgresql"
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,3 @@
|
||||
# Please do not edit this file manually
|
||||
# It should be added in your version-control system (e.g., Git)
|
||||
provider = "sqlite"
|
||||
+49
-8
@@ -1,29 +1,34 @@
|
||||
// Prisma schema — SQLite for local, PostgreSQL for cloud.
|
||||
// Connection URL configured in prisma.config.ts
|
||||
// Prisma schema — PostgreSQL for all environments.
|
||||
// Local dev: use `npx prisma dev` for a zero-install local PGLite instance.
|
||||
// Cloud/Production: set DATABASE_URL to your Supabase/Postgres connection string.
|
||||
|
||||
datasource db {
|
||||
provider = "sqlite"
|
||||
provider = "postgresql"
|
||||
}
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client"
|
||||
provider = "prisma-client-js"
|
||||
output = "../src/generated/prisma"
|
||||
}
|
||||
|
||||
model User {
|
||||
id String @id @default(uuid())
|
||||
email String @unique
|
||||
tenantId String?
|
||||
email String
|
||||
name String
|
||||
hashedPassword String
|
||||
role String @default("user")
|
||||
createdAt DateTime @default(now())
|
||||
favorites Favorite[]
|
||||
memberships WorkspaceMember[]
|
||||
|
||||
@@unique([tenantId, email])
|
||||
@@map("users")
|
||||
}
|
||||
|
||||
model Favorite {
|
||||
id String @id @default(uuid())
|
||||
tenantId String?
|
||||
entityId String
|
||||
pluginId String
|
||||
label String
|
||||
@@ -58,19 +63,55 @@ model Favorite {
|
||||
|
||||
model InstalledPlugin {
|
||||
id String @id @default(uuid())
|
||||
pluginId String @unique
|
||||
tenantId String?
|
||||
pluginId String
|
||||
version String
|
||||
config String @default("{}")
|
||||
enabled Boolean @default(true)
|
||||
installedAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([tenantId, pluginId])
|
||||
@@map("installed_plugins")
|
||||
}
|
||||
|
||||
model Setting {
|
||||
key String @id
|
||||
value String
|
||||
id String @id @default(uuid())
|
||||
tenantId String?
|
||||
key String
|
||||
value String
|
||||
|
||||
@@unique([tenantId, key])
|
||||
@@map("settings")
|
||||
}
|
||||
|
||||
// NEW — Global workspace registry
|
||||
model Workspace {
|
||||
id String @id @default(uuid())
|
||||
name String
|
||||
subdomain String @unique
|
||||
status String @default("trialing")
|
||||
plan String @default("basic")
|
||||
stripeCustomerId String?
|
||||
stripeSubscriptionId String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
members WorkspaceMember[]
|
||||
|
||||
@@map("workspaces")
|
||||
}
|
||||
|
||||
// NEW — Links global users to workspaces with roles
|
||||
model WorkspaceMember {
|
||||
id String @id @default(uuid())
|
||||
userId String
|
||||
workspaceId String
|
||||
role String @default("member")
|
||||
joinedAt DateTime @default(now())
|
||||
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
workspace Workspace @relation(fields: [workspaceId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([userId, workspaceId])
|
||||
@@map("workspace_members")
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { execSync } from 'child_process';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
// Load environment variables manually since dotenv might not be installed globally
|
||||
const loadEnv = (file) => {
|
||||
try {
|
||||
if (fs.existsSync(file)) {
|
||||
const content = fs.readFileSync(file, 'utf8');
|
||||
content.split('\n').forEach(line => {
|
||||
const match = line.match(/^\s*([\w.-]+)\s*=\s*(.*)?\s*$/);
|
||||
if (match) {
|
||||
const key = match[1];
|
||||
let value = match[2] || '';
|
||||
// Remove quotes
|
||||
if (value.startsWith('"') && value.endsWith('"')) value = value.slice(1, -1);
|
||||
if (value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
|
||||
process.env[key] = value;
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
// Ignore read errors
|
||||
}
|
||||
};
|
||||
|
||||
loadEnv('.env');
|
||||
loadEnv('.env.local');
|
||||
|
||||
const skipLocalDb = process.env.WWV_SKIP_LOCAL_DB === 'true' || process.env.WWV_SKIP_LOCAL_DB === '1';
|
||||
|
||||
if (skipLocalDb) {
|
||||
console.log('⏭️ Skipping local PostgreSQL startup (WWV_SKIP_LOCAL_DB is set).');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
console.log('🚀 Checking local PostgreSQL database...');
|
||||
|
||||
try {
|
||||
// Check if docker is installed
|
||||
try {
|
||||
execSync('docker --version', { stdio: 'ignore' });
|
||||
} catch (e) {
|
||||
console.log('⚠️ Docker is not installed or not in PATH. Skipping local database startup.');
|
||||
console.log('💡 If you want to run a local database automatically, please install Docker Desktop.');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
// Start the db service using docker compose
|
||||
console.log('📦 Starting PostgreSQL via Docker Compose...');
|
||||
execSync('docker compose up -d db', { stdio: 'inherit' });
|
||||
|
||||
// Wait a few seconds for postgres to be ready
|
||||
console.log('⏳ Waiting for PostgreSQL to be ready...');
|
||||
|
||||
// Simple sleep since we can't easily rely on pg_isready without pg client
|
||||
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 3000);
|
||||
|
||||
console.log('✅ Local PostgreSQL database is ready!');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to start local database:', error.message);
|
||||
console.log('💡 You may need to start it manually or set WWV_SKIP_LOCAL_DB=true to use an external database.');
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { prisma } from "../src/lib/db";
|
||||
|
||||
async function main() {
|
||||
const plugins = await prisma.installedPlugin.findMany();
|
||||
console.log("Installed plugins:");
|
||||
plugins.forEach((p) => console.log(` ${p.pluginId} | config: ${p.config.substring(0, 60)}`));
|
||||
|
||||
const geojson = plugins.find((p) => p.pluginId === "geojson");
|
||||
if (geojson) {
|
||||
await prisma.installedPlugin.delete({ where: { id: geojson.id } });
|
||||
console.log("\nDeleted orphaned 'geojson' record.");
|
||||
} else {
|
||||
console.log("\nNo orphaned 'geojson' record found.");
|
||||
}
|
||||
|
||||
const remaining = await prisma.installedPlugin.findMany();
|
||||
console.log("\nRemaining plugins:");
|
||||
remaining.forEach((p) => console.log(` ${p.pluginId}`));
|
||||
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,39 @@
|
||||
import { prisma } from "../src/lib/db";
|
||||
import { hashSync } from "bcryptjs";
|
||||
|
||||
async function main() {
|
||||
const action = process.argv[2];
|
||||
|
||||
if (action === "list") {
|
||||
const users = await prisma.user.findMany();
|
||||
if (users.length === 0) {
|
||||
console.log("No users found — visit /setup to create one.");
|
||||
} else {
|
||||
users.forEach((u) =>
|
||||
console.log(` ${u.email} | ${u.name} | ${u.role} | ${u.createdAt}`)
|
||||
);
|
||||
}
|
||||
} else if (action === "reset") {
|
||||
const email = process.argv[3];
|
||||
const newPass = process.argv[4];
|
||||
if (!email || !newPass) {
|
||||
console.log("Usage: tsx scripts/manage-users.ts reset <email> <password>");
|
||||
return;
|
||||
}
|
||||
const hashed = hashSync(newPass, 12);
|
||||
await prisma.user.update({
|
||||
where: { email },
|
||||
data: { hashedPassword: hashed },
|
||||
});
|
||||
console.log(`Password reset for ${email}`);
|
||||
} else if (action === "delete-all") {
|
||||
await prisma.user.deleteMany();
|
||||
console.log("All users deleted — visit /setup to create a new admin.");
|
||||
} else {
|
||||
console.log("Usage: tsx scripts/manage-users.ts <list|reset|delete-all>");
|
||||
}
|
||||
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* @deprecated This script uses better-sqlite3 directly to migrate data
|
||||
* from Supabase into the legacy data engine's SQLite database.
|
||||
* It is NOT part of the main application's database layer.
|
||||
* It will be removed once the data engine migration is complete.
|
||||
*/
|
||||
import { createClient } from "@supabase/supabase-js";
|
||||
import Database from "better-sqlite3";
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import dotenv from "dotenv";
|
||||
|
||||
// Load environment from .env.local
|
||||
const envPath = path.resolve(process.cwd(), ".env.local");
|
||||
if (fs.existsSync(envPath)) {
|
||||
dotenv.config({ path: envPath });
|
||||
} else {
|
||||
dotenv.config();
|
||||
}
|
||||
|
||||
const SUPABASE_URL = process.env.NEXT_PUBLIC_SUPABASE_URL!;
|
||||
const SUPABASE_KEY = process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
|
||||
|
||||
if (!SUPABASE_URL || !SUPABASE_KEY) {
|
||||
console.error("Missing Supabase credentials in .env.local");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);
|
||||
|
||||
// Connect to SQLite DB (respects DB_PATH, fallback to data engine location)
|
||||
const defaultDbPath = path.resolve(process.cwd(), "packages/wwv-data-engine/data/engine.db");
|
||||
const dbPath = process.env.DB_PATH || defaultDbPath;
|
||||
console.log(`Connecting to SQLite at ${dbPath}...`);
|
||||
|
||||
// Ensure DB directory exists
|
||||
const dbDir = path.dirname(dbPath);
|
||||
if (!fs.existsSync(dbDir)) {
|
||||
fs.mkdirSync(dbDir, { recursive: true });
|
||||
}
|
||||
|
||||
const db = new Database(dbPath);
|
||||
db.pragma('journal_mode = WAL');
|
||||
|
||||
// Ensure table exists (mirroring what we'll inject into Data Engine later)
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS aviation_history (
|
||||
icao24 TEXT NOT NULL,
|
||||
ts INTEGER NOT NULL,
|
||||
lat REAL,
|
||||
lon REAL,
|
||||
alt REAL,
|
||||
hdg REAL,
|
||||
spd REAL,
|
||||
fetched_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (icao24, ts)
|
||||
)
|
||||
`);
|
||||
|
||||
const insertHistory = db.prepare(`
|
||||
INSERT OR IGNORE INTO aviation_history (icao24, ts, lat, lon, alt, hdg, spd, fetched_at)
|
||||
VALUES (@icao24, @ts, @lat, @lon, @alt, @hdg, @spd, @fetched_at)
|
||||
`);
|
||||
|
||||
async function migrate() {
|
||||
console.log("Fetching existing aviation_history records from Supabase...");
|
||||
let offset = 0;
|
||||
const limit = 10000; // Chunk size
|
||||
let totalInserted = 0;
|
||||
|
||||
while (true) {
|
||||
const { data, error } = await supabase
|
||||
.from("aviation_history")
|
||||
.select("*")
|
||||
.range(offset, offset + limit - 1);
|
||||
|
||||
if (error) {
|
||||
console.error("Fetch error:", error);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (!data || data.length === 0) {
|
||||
console.log("No more records to fetch.");
|
||||
break;
|
||||
}
|
||||
|
||||
console.log(`Processing ${data.length} records (Offset: ${offset})...`);
|
||||
|
||||
// Batch insert to SQLite
|
||||
const insertMany = db.transaction((records) => {
|
||||
for (const r of records) {
|
||||
// Determine timestamp logic: Postgres is Timestamp so convert to epoch seconds
|
||||
const tsMs = new Date(r.timestamp).getTime();
|
||||
|
||||
insertHistory.run({
|
||||
icao24: r.icao24,
|
||||
ts: Math.floor(tsMs / 1000),
|
||||
lat: r.latitude,
|
||||
lon: r.longitude,
|
||||
alt: r.altitude,
|
||||
hdg: r.heading,
|
||||
spd: r.speed,
|
||||
fetched_at: Math.floor(Date.now() / 1000)
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
insertMany(data);
|
||||
totalInserted += data.length;
|
||||
} catch (err) {
|
||||
console.error("SQLite Insert Error:", err);
|
||||
}
|
||||
|
||||
if (data.length < limit) {
|
||||
break;
|
||||
}
|
||||
|
||||
offset += limit;
|
||||
}
|
||||
|
||||
console.log(`Migration complete! Successfully injected ~${totalInserted} records into SQLite.`);
|
||||
}
|
||||
|
||||
migrate();
|
||||
@@ -0,0 +1,129 @@
|
||||
import { execSync } from "child_process";
|
||||
import fs from "fs";
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import { PrismaPg } from "@prisma/adapter-pg";
|
||||
import pg from "pg";
|
||||
const { Pool } = pg;
|
||||
|
||||
const SQLITE_DB_PATH = "./data/wwv.db";
|
||||
const MIGRATED_MARKER = "./data/wwv.db.migrated";
|
||||
|
||||
async function run() {
|
||||
if (!fs.existsSync(SQLITE_DB_PATH)) {
|
||||
// No SQLite database found, nothing to migrate
|
||||
return;
|
||||
}
|
||||
|
||||
if (fs.existsSync(MIGRATED_MARKER)) {
|
||||
console.log("[migration] SQLite database already migrated. Skipping.");
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("[migration] Legacy SQLite database detected. Initiating migration to PostgreSQL...");
|
||||
|
||||
// Initialize Prisma client connecting to PostgreSQL natively via adapter
|
||||
const connectionString = process.env.DATABASE_URL;
|
||||
if (!connectionString) {
|
||||
console.error("[migration] DATABASE_URL environment variable is missing.");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const pool = new Pool({ connectionString });
|
||||
const adapter = new PrismaPg(pool);
|
||||
const prisma = new PrismaClient({ adapter });
|
||||
|
||||
try {
|
||||
await prisma.$connect();
|
||||
|
||||
const tablesToMigrate = [
|
||||
{ sqlite: "users", prisma: prisma.user, key: "id" },
|
||||
{ sqlite: "workspaces", prisma: prisma.workspace, key: "id" },
|
||||
{ sqlite: "workspace_members", prisma: prisma.workspaceMember, key: "id" },
|
||||
{ sqlite: "favorites", prisma: prisma.favorite, key: "id" },
|
||||
{ sqlite: "installed_plugins", prisma: prisma.installedPlugin, key: "id" },
|
||||
{ sqlite: "settings", prisma: prisma.setting, key: "id" }
|
||||
];
|
||||
|
||||
for (const table of tablesToMigrate) {
|
||||
console.log(`[migration] Migrating table: ${table.sqlite}...`);
|
||||
let rowsJson = "[]";
|
||||
try {
|
||||
// Read data from SQLite
|
||||
const isWindows = process.platform === "win32";
|
||||
const cmd = isWindows
|
||||
? `docker run --rm -v "${process.cwd().replace(/\\/g, '/')}/data:/data" keinos/sqlite3 sqlite3 --json /data/wwv.db "SELECT * FROM ${table.sqlite};"`
|
||||
: `sqlite3 --json ${SQLITE_DB_PATH} "SELECT * FROM ${table.sqlite};"`;
|
||||
|
||||
const output = execSync(cmd, { encoding: "utf-8", stdio: ['pipe', 'pipe', 'ignore'] });
|
||||
if (output && output.trim()) {
|
||||
rowsJson = output;
|
||||
}
|
||||
} catch (err) {
|
||||
// Table might not exist in SQLite (e.g., workspaces was newly added), that's fine
|
||||
console.log(`[migration] Skipping table ${table.sqlite} (might not exist in legacy DB).`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const rows = JSON.parse(rowsJson);
|
||||
if (rows.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
console.log(`[migration] Found ${rows.length} rows in ${table.sqlite}. Insertions...`);
|
||||
let inserted = 0;
|
||||
for (const row of rows) {
|
||||
// Handle boolean fields which are 1/0 in SQLite
|
||||
if (table.sqlite === "installed_plugins" && "enabled" in row) {
|
||||
row.enabled = row.enabled === 1;
|
||||
}
|
||||
|
||||
// Handle dates which are strings/numbers in SQLite
|
||||
const dateFields = ["createdAt", "updatedAt", "lastSeen", "installedAt", "joinedAt"];
|
||||
for (const field of dateFields) {
|
||||
if (row[field]) {
|
||||
// SQLite dates might be stored as Unix timestamps or strings
|
||||
// If it's a number, it could be seconds or milliseconds. Prisma stores ms.
|
||||
if (typeof row[field] === "number") {
|
||||
// If it's in seconds (typical Unix timestamp), multiply by 1000
|
||||
// A timestamp in 2024 is around 1.7e9, in ms it's 1.7e12
|
||||
const isSeconds = row[field] < 1e11;
|
||||
row[field] = new Date(isSeconds ? row[field] * 1000 : row[field]);
|
||||
} else {
|
||||
row[field] = new Date(row[field]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// All these tables have "id" as the primary key.
|
||||
const exists = await table.prisma.findUnique({
|
||||
where: { id: row.id }
|
||||
});
|
||||
|
||||
if (!exists) {
|
||||
await table.prisma.create({
|
||||
data: row
|
||||
});
|
||||
inserted++;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[migration] Failed to insert row into ${table.sqlite}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
console.log(`[migration] Inserted ${inserted} new rows into PostgreSQL table ${table.sqlite}.`);
|
||||
}
|
||||
|
||||
// Mark as migrated
|
||||
fs.writeFileSync(MIGRATED_MARKER, new Date().toISOString(), "utf8");
|
||||
console.log("[migration] SQLite to PostgreSQL migration completed successfully!");
|
||||
console.log("[migration] Note: You can safely delete ./data/wwv.db now.");
|
||||
|
||||
} catch (err) {
|
||||
console.error("[migration] Fatal error during migration:", err);
|
||||
process.exit(1);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
run();
|
||||
@@ -31,6 +31,24 @@
|
||||
"sourceType": "github",
|
||||
"computedHash": "f91df0be8d0ac0f12c5402b5c53da12a31b284e5501dba027086bb12db879903"
|
||||
},
|
||||
"prisma-database-setup": {
|
||||
"source": "prisma/skills",
|
||||
"sourceType": "github",
|
||||
"skillPath": "prisma-database-setup/SKILL.md",
|
||||
"computedHash": "0d6f44ac34b1ed3f8ed2970ecf90483d0f658fd1d204458f62bfefa28f31b095"
|
||||
},
|
||||
"prisma-postgres": {
|
||||
"source": "prisma/skills",
|
||||
"sourceType": "github",
|
||||
"skillPath": "prisma-postgres/SKILL.md",
|
||||
"computedHash": "fd8f16f26e2cce1dd3e8e7916dcddbffddf295003eba86141f53e9d2d9d2bc0c"
|
||||
},
|
||||
"prisma-upgrade-v7": {
|
||||
"source": "prisma/skills",
|
||||
"sourceType": "github",
|
||||
"skillPath": "prisma-upgrade-v7/SKILL.md",
|
||||
"computedHash": "075d1fc3156d5593c3e9a559ebb07f82a2991db07125ff9df16ad90270f5c584"
|
||||
},
|
||||
"redis-best-practices": {
|
||||
"source": "mindrally/skills",
|
||||
"sourceType": "github",
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { stripe } from "@/lib/stripe/client";
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "@/lib/auth";
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const session = await auth();
|
||||
if (!session?.user) return new NextResponse("Unauthorized", { status: 401 });
|
||||
|
||||
const { priceId } = await req.json();
|
||||
|
||||
const checkoutSession = await stripe.checkout.sessions.create({
|
||||
mode: "subscription",
|
||||
payment_method_types: ["card"],
|
||||
line_items: [{ price: priceId, quantity: 1 }],
|
||||
success_url: `${process.env.NEXT_PUBLIC_APP_URL}/settings?success=true`,
|
||||
cancel_url: `${process.env.NEXT_PUBLIC_APP_URL}/settings?canceled=true`,
|
||||
client_reference_id: session.user.id,
|
||||
});
|
||||
|
||||
return NextResponse.json({ url: checkoutSession.url });
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { stripe } from "@/lib/stripe/client";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const body = await req.text();
|
||||
const sig = req.headers.get("stripe-signature");
|
||||
|
||||
let event;
|
||||
|
||||
try {
|
||||
event = stripe.webhooks.constructEvent(
|
||||
body,
|
||||
sig!,
|
||||
process.env.STRIPE_WEBHOOK_SECRET!
|
||||
);
|
||||
} catch (err: any) {
|
||||
return new NextResponse(`Webhook Error: ${err.message}`, { status: 400 });
|
||||
}
|
||||
|
||||
if (event.type === "checkout.session.completed") {
|
||||
console.log("Subscription completed!");
|
||||
// Update user tier in DB, send license key via email
|
||||
}
|
||||
|
||||
return new NextResponse(null, { status: 200 });
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { validateManifest } from "@/core/plugins/validateManifest";
|
||||
import { parseWwvManifest } from "@/core/plugins/parseWwvManifest";
|
||||
|
||||
export async function OPTIONS() {
|
||||
// Allows the WWV CLI (running on a different port) to hit this endpoint
|
||||
return new NextResponse(null, {
|
||||
status: 204,
|
||||
headers: {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Access-Control-Allow-Methods": "POST, OPTIONS",
|
||||
"Access-Control-Allow-Headers": "Content-Type",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/dev/load-unpacked
|
||||
*
|
||||
* Called by the `@worldwideview/cli` dev server when it starts.
|
||||
* It sends the `wwv-manifest.json` + `devUrl` (the CLI dev server URL).
|
||||
*/
|
||||
export async function POST(request: Request) {
|
||||
if (process.env.NODE_ENV !== "development") {
|
||||
return NextResponse.json(
|
||||
{ error: "Developer mode is only available in development environments" },
|
||||
{ status: 403, headers: { "Access-Control-Allow-Origin": "*" } }
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
|
||||
// Convert wwv-manifest.json format to PluginManifest format
|
||||
const manifest = parseWwvManifest(body);
|
||||
|
||||
// Dev-loaded plugins are unverified by default
|
||||
manifest.trust = "unverified";
|
||||
|
||||
const validation = validateManifest(manifest);
|
||||
if (!validation.valid) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid manifest", details: validation.errors },
|
||||
{ status: 400, headers: { "Access-Control-Allow-Origin": "*" } }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ status: "loaded", manifest },
|
||||
{ status: 200, headers: { "Access-Control-Allow-Origin": "*" } }
|
||||
);
|
||||
} catch (err) {
|
||||
console.error("[Load Unpacked] Error:", err);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to parse or load unpacked manifest" },
|
||||
{ status: 500, headers: { "Access-Control-Allow-Origin": "*" } }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { isCloud } from "@/core/edition";
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ subdomain: string }> }
|
||||
) {
|
||||
if (!isCloud) {
|
||||
return NextResponse.json({ status: "active", plan: "basic" });
|
||||
}
|
||||
|
||||
// Await params as required in Next.js 15+
|
||||
const resolvedParams = await params;
|
||||
const subdomain = resolvedParams.subdomain;
|
||||
|
||||
try {
|
||||
const workspace = await prisma.workspace.findUnique({
|
||||
where: { subdomain },
|
||||
select: { status: true, plan: true }
|
||||
});
|
||||
|
||||
if (!workspace) {
|
||||
return NextResponse.json({ error: "Workspace not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json(workspace);
|
||||
} catch (e) {
|
||||
console.error("Failed to lookup workspace", e);
|
||||
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -10,11 +10,11 @@ export async function GET(request: Request) {
|
||||
if (rateLimited) return rateLimited;
|
||||
|
||||
try {
|
||||
// Fetch currently installed plugins from local SQLite
|
||||
// Fetch currently installed plugins from PostgreSQL
|
||||
const installedPlugins = await getInstalledPlugins();
|
||||
|
||||
// Exclude built-in versions, only check genuine semver strings or unverified records.
|
||||
const updatablePlugins = installedPlugins.filter(p => p.version !== "built-in");
|
||||
const updatablePlugins = installedPlugins.filter((p: any) => p.version !== "built-in");
|
||||
|
||||
if (updatablePlugins.length === 0) {
|
||||
return NextResponse.json({ updates: {} });
|
||||
|
||||
@@ -17,6 +17,10 @@ const ALLOWED_REDIRECT_HOSTS = new Set([
|
||||
"worldwideview.dev",
|
||||
]);
|
||||
|
||||
if (process.env.ALLOWED_DEV_ORIGIN) {
|
||||
ALLOWED_REDIRECT_HOSTS.add(process.env.ALLOWED_DEV_ORIGIN);
|
||||
}
|
||||
|
||||
function isSafeRedirect(url: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
|
||||
@@ -104,9 +104,9 @@ export async function POST(request: Request) {
|
||||
return withCors(
|
||||
NextResponse.json({
|
||||
status: "installed",
|
||||
pluginId: record.pluginId,
|
||||
version: record.version,
|
||||
installedAt: record.installedAt,
|
||||
pluginId: record!.pluginId,
|
||||
version: record!.version,
|
||||
installedAt: record!.installedAt,
|
||||
}),
|
||||
request,
|
||||
);
|
||||
|
||||
+37
-15
@@ -2,6 +2,8 @@
|
||||
|
||||
import { signIn } from "@/lib/auth";
|
||||
import { AuthError } from "next-auth";
|
||||
import { isCloud } from "@/core/edition";
|
||||
import { createClient } from "@supabase/supabase-js";
|
||||
|
||||
interface LoginResult {
|
||||
success: boolean;
|
||||
@@ -9,23 +11,43 @@ interface LoginResult {
|
||||
}
|
||||
|
||||
export async function loginAction(formData: FormData): Promise<LoginResult> {
|
||||
try {
|
||||
await signIn("credentials", {
|
||||
email: formData.get("email") as string,
|
||||
password: formData.get("password") as string,
|
||||
redirect: false,
|
||||
const email = formData.get("email") as string;
|
||||
const password = formData.get("password") as string;
|
||||
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
|
||||
const isDummyUrl = !supabaseUrl || supabaseUrl.includes("dummy") || supabaseUrl.includes("xyz.supabase.co");
|
||||
|
||||
if (isCloud && !isDummyUrl) {
|
||||
// Use Supabase GoTrue
|
||||
const supabase = createClient(
|
||||
supabaseUrl,
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
|
||||
);
|
||||
const { error } = await supabase.auth.signInWithPassword({
|
||||
email,
|
||||
password,
|
||||
});
|
||||
|
||||
if (error) return { success: false, error: error.message };
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
if (error instanceof AuthError) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.type === "CredentialsSignin"
|
||||
? "Invalid email or password."
|
||||
: "Something went wrong.",
|
||||
};
|
||||
} else {
|
||||
try {
|
||||
await signIn("credentials", {
|
||||
email,
|
||||
password,
|
||||
redirect: false,
|
||||
});
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
if (error instanceof AuthError) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.type === "CredentialsSignin"
|
||||
? "Invalid email or password."
|
||||
: "Something went wrong.",
|
||||
};
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { pluginManager } from "@/core/plugins/PluginManager";
|
||||
import { useStore } from "@/core/state/store";
|
||||
|
||||
export function DevModeSubscriber() {
|
||||
const [connected, setConnected] = useState(false);
|
||||
const initLayer = useStore((s) => s.initLayer);
|
||||
|
||||
useEffect(() => {
|
||||
// Only run in development
|
||||
if (process.env.NODE_ENV !== "development") return;
|
||||
|
||||
let ws: WebSocket;
|
||||
let reconnectTimer: NodeJS.Timeout;
|
||||
|
||||
const connect = () => {
|
||||
// Attempt to connect to the wwv-cli dev server default port
|
||||
ws = new WebSocket("ws://localhost:24601/__wwv_dev__");
|
||||
|
||||
ws.onopen = () => {
|
||||
console.log("[DevMode] Connected to WWV Dev Server 🔧");
|
||||
setConnected(true);
|
||||
};
|
||||
|
||||
ws.onmessage = async (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
|
||||
if (data.type === "plugin:added") {
|
||||
console.log(`[DevMode] Plugin added from CLI: ${data.manifest.id}`);
|
||||
await pluginManager.loadFromManifest(data.manifest);
|
||||
initLayer(data.manifest.id, true);
|
||||
await pluginManager.enablePlugin(data.manifest.id);
|
||||
|
||||
} else if (data.type === "plugin:updated") {
|
||||
console.log(`[DevMode] Reloading plugin: ${data.pluginId}`);
|
||||
// Destroy and re-load from manifest for dev hot-reload
|
||||
pluginManager.disablePlugin(data.pluginId);
|
||||
if (data.manifest) {
|
||||
await pluginManager.loadFromManifest(data.manifest);
|
||||
initLayer(data.manifest.id, true);
|
||||
await pluginManager.enablePlugin(data.manifest.id);
|
||||
}
|
||||
|
||||
} else if (data.type === "plugin:error") {
|
||||
console.error(`[DevMode] Dev Server Build Error: ${data.error}`);
|
||||
useStore.getState().showErrorToast?.(`Build Error in ${data.pluginId}: ${data.error}`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[DevMode] Error handling message:", err);
|
||||
}
|
||||
};
|
||||
|
||||
ws.onclose = () => {
|
||||
if (connected) {
|
||||
console.log("[DevMode] Disconnected from WWV Dev Server.");
|
||||
setConnected(false);
|
||||
}
|
||||
reconnectTimer = setTimeout(connect, 2000);
|
||||
};
|
||||
|
||||
ws.onerror = () => {
|
||||
// Ignore connection refused errors when CLI is not running
|
||||
};
|
||||
};
|
||||
|
||||
connect();
|
||||
|
||||
return () => {
|
||||
clearTimeout(reconnectTimer);
|
||||
if (ws) ws.close();
|
||||
};
|
||||
}, [connected, initLayer]);
|
||||
|
||||
// This component doesn't render anything visibly
|
||||
return null;
|
||||
}
|
||||
@@ -8,7 +8,8 @@ import {
|
||||
} from "@/lib/userApiKeys";
|
||||
import { sectionHeaderStyle, inputGroupStyle, labelStyle } from "./sharedStyles";
|
||||
import ReloadToast from "@/components/ui/ReloadToast";
|
||||
|
||||
import { useStore } from "@/core/state/store";
|
||||
import { verifyLicenseKey } from "@/core/license/verifyLicense";
|
||||
type VerifyStatus = "idle" | "verifying" | "valid" | "invalid";
|
||||
|
||||
const keyInputStyle: React.CSSProperties = {
|
||||
@@ -59,6 +60,14 @@ export function ApiKeysTab() {
|
||||
return initial;
|
||||
});
|
||||
|
||||
const licenseKey = useStore((s) => s.dataConfig.licenseKey);
|
||||
const activeTier = useStore((s) => s.dataConfig.activeTier);
|
||||
const updateDataConfig = useStore((s) => s.updateDataConfig);
|
||||
|
||||
const [licenseInput, setLicenseInput] = useState(licenseKey || "");
|
||||
const [licenseStatus, setLicenseStatus] = useState<VerifyStatus>("idle");
|
||||
const [licenseError, setLicenseError] = useState("");
|
||||
|
||||
const [visible, setVisible] = useState<Record<string, boolean>>({});
|
||||
const [status, setStatus] = useState<Record<string, VerifyStatus>>({});
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
@@ -127,11 +136,89 @@ export function ApiKeysTab() {
|
||||
setErrors({});
|
||||
}, []);
|
||||
|
||||
const handleVerifyLicense = useCallback(async () => {
|
||||
if (!licenseInput) return;
|
||||
setLicenseStatus("verifying");
|
||||
setLicenseError("");
|
||||
const payload = await verifyLicenseKey(licenseInput);
|
||||
if (payload) {
|
||||
setLicenseStatus("valid");
|
||||
updateDataConfig({ licenseKey: licenseInput, activeTier: payload.tier });
|
||||
} else {
|
||||
setLicenseStatus("invalid");
|
||||
setLicenseError("Invalid or expired license key");
|
||||
updateDataConfig({ licenseKey: null, activeTier: "free" });
|
||||
}
|
||||
}, [licenseInput, updateDataConfig]);
|
||||
|
||||
const handleClearLicense = useCallback(() => {
|
||||
setLicenseInput("");
|
||||
setLicenseStatus("idle");
|
||||
setLicenseError("");
|
||||
updateDataConfig({ licenseKey: null, activeTier: "free" });
|
||||
}, [updateDataConfig]);
|
||||
|
||||
const hasAnyKey = Object.values(keys).some((v) => v.length > 0);
|
||||
|
||||
return (
|
||||
<>
|
||||
<style>{`@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }`}</style>
|
||||
<div style={{ marginBottom: "var(--space-lg)" }}>
|
||||
<div style={sectionHeaderStyle}>
|
||||
<Key size={10} style={{ marginRight: 4, verticalAlign: "middle" }} />
|
||||
License Key
|
||||
</div>
|
||||
<div style={{ fontSize: 11, color: "var(--text-muted)", marginBottom: "var(--space-md)" }}>
|
||||
Current Tier: <strong style={{ color: "var(--text-primary)", textTransform: "capitalize" }}>{activeTier}</strong>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: "var(--space-md)" }}>
|
||||
<div style={{ display: "flex", gap: 4, alignItems: "center" }}>
|
||||
<input
|
||||
type="password"
|
||||
value={licenseInput}
|
||||
placeholder="eyJhbGciOiJSUzI1NiI..."
|
||||
onChange={(e) => setLicenseInput(e.target.value)}
|
||||
style={{
|
||||
...keyInputStyle,
|
||||
border: `1px solid ${licenseStatus === "valid" ? "rgba(34,197,94,0.5)" : licenseStatus === "invalid" ? "rgba(239,68,68,0.5)" : "var(--border-subtle)"}`
|
||||
}}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
/>
|
||||
<StatusIcon status={licenseStatus} />
|
||||
<button
|
||||
onClick={handleVerifyLicense}
|
||||
disabled={!licenseInput || licenseStatus === "verifying"}
|
||||
title="Verify license"
|
||||
style={{
|
||||
...toggleBtnStyle,
|
||||
color: licenseStatus === "valid" ? "#22c55e" : licenseStatus === "invalid" ? "#ef4444" : "var(--text-muted)",
|
||||
opacity: (!licenseInput || licenseStatus === "verifying") ? 0.4 : 1,
|
||||
cursor: (!licenseInput || licenseStatus === "verifying") ? "not-allowed" : "pointer",
|
||||
}}
|
||||
>
|
||||
<ShieldCheck size={14} />
|
||||
</button>
|
||||
{licenseInput && (
|
||||
<button
|
||||
style={toggleBtnStyle}
|
||||
onClick={handleClearLicense}
|
||||
title="Clear License"
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{licenseStatus === "invalid" && licenseError && (
|
||||
<div style={{ fontSize: 10, color: "#ef4444", marginTop: 3 }}>{licenseError}</div>
|
||||
)}
|
||||
{licenseStatus === "valid" && (
|
||||
<div style={{ fontSize: 10, color: "#22c55e", marginTop: 3 }}>License verified ✓</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: "var(--space-lg)" }}>
|
||||
<div style={sectionHeaderStyle}>
|
||||
<Key size={10} style={{ marginRight: 4, verticalAlign: "middle" }} />
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
export type LicenseTier = "free" | "pro" | "team" | "enterprise";
|
||||
|
||||
export interface TierFeatures {
|
||||
maxUsers: number;
|
||||
storageQuotaBytes: number;
|
||||
historyEnabled: boolean;
|
||||
snapshotCapture: boolean;
|
||||
customDomains: boolean;
|
||||
}
|
||||
|
||||
export const TIER_FEATURES: Record<LicenseTier, TierFeatures> = {
|
||||
free: { maxUsers: 3, storageQuotaBytes: 500 * 1024 * 1024, historyEnabled: false, snapshotCapture: false, customDomains: false },
|
||||
pro: { maxUsers: 20, storageQuotaBytes: 5 * 1024 * 1024 * 1024, historyEnabled: true, snapshotCapture: true, customDomains: false },
|
||||
team: { maxUsers: -1, storageQuotaBytes: -1, historyEnabled: true, snapshotCapture: true, customDomains: false },
|
||||
enterprise: { maxUsers: -1, storageQuotaBytes: -1, historyEnabled: true, snapshotCapture: true, customDomains: true },
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
import * as jose from "jose";
|
||||
|
||||
// Public key is safe to hardcode/ship to client
|
||||
const PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
|
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu... (generate real one)
|
||||
-----END PUBLIC KEY-----`;
|
||||
|
||||
export interface LicensePayload {
|
||||
tier: "free" | "pro" | "team" | "enterprise";
|
||||
exp: number;
|
||||
org: string;
|
||||
}
|
||||
|
||||
export async function verifyLicenseKey(token: string): Promise<LicensePayload | null> {
|
||||
try {
|
||||
const publicKey = await jose.importSPKI(PUBLIC_KEY_PEM, "RS256");
|
||||
const { payload } = await jose.jwtVerify(token, publicKey);
|
||||
return payload as unknown as LicensePayload;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { PluginManifest } from "./PluginManifest";
|
||||
|
||||
/**
|
||||
* Validates and converts a wwv-manifest.json into an internal PluginManifest.
|
||||
*/
|
||||
export function parseWwvManifest(rawManifest: any): PluginManifest {
|
||||
if (!rawManifest || typeof rawManifest !== "object") {
|
||||
throw new Error("Manifest must be a JSON object");
|
||||
}
|
||||
|
||||
// Required fields mapping
|
||||
const manifest: Partial<PluginManifest> = {
|
||||
id: rawManifest.id,
|
||||
name: rawManifest.name,
|
||||
version: rawManifest.version,
|
||||
description: rawManifest.description,
|
||||
type: rawManifest.type || "data-layer",
|
||||
format: "bundle", // wwv-manifest plugins are always bundles
|
||||
trust: "unverified", // Will be overridden if fetched from marketplace
|
||||
capabilities: rawManifest.capabilities || [],
|
||||
category: rawManifest.category || "custom",
|
||||
icon: rawManifest.icon,
|
||||
compatibility: rawManifest.compatibility,
|
||||
entry: rawManifest.entry,
|
||||
assets: rawManifest.assets,
|
||||
extends: rawManifest.extends,
|
||||
};
|
||||
|
||||
return manifest as PluginManifest;
|
||||
}
|
||||
@@ -15,6 +15,8 @@ export interface DataConfig {
|
||||
showTimelineHighlight: boolean;
|
||||
};
|
||||
pluginSettings: Record<string, any>;
|
||||
licenseKey: string | null;
|
||||
activeTier: "free" | "pro" | "team" | "enterprise";
|
||||
}
|
||||
|
||||
export type AntiAliasingMode = "none" | "fxaa" | "msaa2x" | "msaa4x" | "msaa8x";
|
||||
@@ -54,6 +56,8 @@ export const createConfigSlice: StateCreator<AppStore, [], [], ConfigSlice> = (s
|
||||
showTimelineHighlight: true,
|
||||
},
|
||||
pluginSettings: {},
|
||||
licenseKey: null,
|
||||
activeTier: "free",
|
||||
},
|
||||
mapConfig: {
|
||||
showFps: false,
|
||||
|
||||
+50
-44
@@ -3,55 +3,61 @@ import Credentials from "next-auth/providers/credentials";
|
||||
import { compareSync } from "bcryptjs";
|
||||
import { timingSafeEqual } from "crypto";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { isDemo, getDemoAdminSecret, DEMO_ADMIN_ROLE } from "@/core/edition";
|
||||
import { isDemo, isCloud, getDemoAdminSecret, DEMO_ADMIN_ROLE } from "@/core/edition";
|
||||
import { authConfig } from "@/lib/auth.config";
|
||||
import { SupabaseAdapter } from "@auth/supabase-adapter";
|
||||
|
||||
// Extract local credentials logic to a helper
|
||||
const localCredentialsProvider = Credentials({
|
||||
credentials: {
|
||||
email: { label: "Email", type: "email" },
|
||||
password: { label: "Password", type: "password" },
|
||||
},
|
||||
async authorize(credentials) {
|
||||
const email = credentials?.email as string | undefined;
|
||||
const password = credentials?.password as string | undefined;
|
||||
|
||||
if (!email || !password) return null;
|
||||
|
||||
// Demo edition: virtual admin login (no DB user required)
|
||||
const adminSecret = getDemoAdminSecret();
|
||||
const secretMatch = adminSecret
|
||||
&& password.length === adminSecret.length
|
||||
&& timingSafeEqual(Buffer.from(password), Buffer.from(adminSecret));
|
||||
if (isDemo && secretMatch && email === "admin") {
|
||||
return {
|
||||
id: "demo-admin",
|
||||
name: "Demo Admin",
|
||||
email: "admin",
|
||||
role: DEMO_ADMIN_ROLE,
|
||||
};
|
||||
}
|
||||
|
||||
const user = await prisma.user.findFirst({
|
||||
where: { email }, // Note: in real cloud with RLS this would fetch tenant user if tenantId added
|
||||
});
|
||||
if (!user) return null;
|
||||
|
||||
const isValid = compareSync(password, user.hashedPassword);
|
||||
if (!isValid) return null;
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
...authConfig,
|
||||
session: { strategy: "jwt" },
|
||||
providers: [
|
||||
Credentials({
|
||||
credentials: {
|
||||
email: { label: "Email", type: "email" },
|
||||
password: { label: "Password", type: "password" },
|
||||
},
|
||||
async authorize(credentials) {
|
||||
const email = credentials?.email as string | undefined;
|
||||
const password = credentials?.password as string | undefined;
|
||||
|
||||
if (!email || !password) return null;
|
||||
|
||||
// Demo edition: virtual admin login (no DB user required)
|
||||
const adminSecret = getDemoAdminSecret();
|
||||
const secretMatch = adminSecret
|
||||
&& password.length === adminSecret.length
|
||||
&& timingSafeEqual(Buffer.from(password), Buffer.from(adminSecret));
|
||||
if (isDemo && secretMatch && email === "admin") {
|
||||
return {
|
||||
id: "demo-admin",
|
||||
name: "Demo Admin",
|
||||
email: "admin",
|
||||
role: DEMO_ADMIN_ROLE,
|
||||
};
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email },
|
||||
});
|
||||
if (!user) return null;
|
||||
|
||||
const isValid = compareSync(password, user.hashedPassword);
|
||||
if (!isValid) return null;
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
};
|
||||
},
|
||||
}),
|
||||
],
|
||||
adapter: isCloud ? SupabaseAdapter({
|
||||
url: process.env.NEXT_PUBLIC_SUPABASE_URL || "http://dummy.supabase.co",
|
||||
secret: process.env.SUPABASE_SERVICE_ROLE_KEY || "dummy",
|
||||
}) as any : undefined,
|
||||
providers: [localCredentialsProvider],
|
||||
callbacks: {
|
||||
...authConfig.callbacks,
|
||||
async jwt({ token, user }) {
|
||||
|
||||
+77
-6
@@ -1,8 +1,14 @@
|
||||
import { PrismaClient } from "../generated/prisma/client";
|
||||
import { PrismaBetterSqlite3 } from "@prisma/adapter-better-sqlite3";
|
||||
import { PrismaPg } from "@prisma/adapter-pg";
|
||||
import { Pool } from "pg";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
/**
|
||||
* Prisma client singleton.
|
||||
* Prisma client singleton — PostgreSQL only.
|
||||
*
|
||||
* Local dev: Run `npx prisma dev` for a zero-install local Postgres.
|
||||
* Production: Set DATABASE_URL to your Supabase/Postgres connection string.
|
||||
*
|
||||
* Uses globalThis to survive Next.js HMR in development.
|
||||
*/
|
||||
|
||||
@@ -10,11 +16,76 @@ const globalForPrisma = globalThis as unknown as {
|
||||
prisma: PrismaClient | undefined;
|
||||
};
|
||||
|
||||
function applyTenantIsolation(client: any) {
|
||||
// Use Prisma Client Extension to inject RLS
|
||||
return client.$extends({
|
||||
query: {
|
||||
$allModels: {
|
||||
async $allOperations({ model, operation, args, query }: { model: string, operation: string, args: any, query: any }) {
|
||||
let tenantSubdomain = null;
|
||||
try {
|
||||
const headersList = await headers();
|
||||
tenantSubdomain = headersList.get("x-tenant-subdomain");
|
||||
} catch (e) {
|
||||
// Not in a request context (e.g. scripts, background jobs)
|
||||
}
|
||||
|
||||
if (tenantSubdomain && model !== 'Workspace' && model !== 'WorkspaceMember') {
|
||||
args = args || {};
|
||||
|
||||
// Inject into data for creates
|
||||
if (operation === 'create' || operation === 'createMany') {
|
||||
if (Array.isArray(args.data)) {
|
||||
args.data = args.data.map((d: any) => ({ ...d, tenantId: tenantSubdomain }));
|
||||
} else if (args.data) {
|
||||
args.data.tenantId = tenantSubdomain;
|
||||
}
|
||||
}
|
||||
|
||||
// Inject into data for updates
|
||||
if (operation === 'update' || operation === 'updateMany') {
|
||||
if (args.data) args.data.tenantId = tenantSubdomain;
|
||||
}
|
||||
if (operation === 'upsert') {
|
||||
if (args.create) args.create.tenantId = tenantSubdomain;
|
||||
if (args.update) args.update.tenantId = tenantSubdomain;
|
||||
}
|
||||
|
||||
// Inject into where filters
|
||||
if (['findUnique', 'findFirst', 'findMany', 'update', 'updateMany', 'delete', 'deleteMany', 'count', 'upsert'].includes(operation)) {
|
||||
args.where = { ...(args.where || {}), tenantId: tenantSubdomain };
|
||||
}
|
||||
|
||||
return query(args);
|
||||
}
|
||||
return query(args);
|
||||
},
|
||||
},
|
||||
},
|
||||
}) as unknown as PrismaClient; // Cast to avoid complex type issues in consuming code for now
|
||||
}
|
||||
|
||||
function createPrismaClient(): PrismaClient {
|
||||
const adapter = new PrismaBetterSqlite3({
|
||||
url: process.env.DATABASE_URL || "file:./data/wwv.db",
|
||||
});
|
||||
return new PrismaClient({ adapter });
|
||||
const connectionString = process.env.DATABASE_URL;
|
||||
|
||||
// During Next.js build time, DATABASE_URL might not be set.
|
||||
// We shouldn't throw synchronously here to avoid breaking static generation.
|
||||
if (!connectionString) {
|
||||
console.warn("[db] DATABASE_URL is not set. Database operations will fail until it is provided.");
|
||||
// Return a dummy proxy that throws only when an operation is actually attempted
|
||||
return new Proxy({}, {
|
||||
get(target, prop) {
|
||||
if (prop === '$extends') return () => target; // needed for applyTenantIsolation
|
||||
throw new Error("[db] DATABASE_URL is missing. Please set it to a PostgreSQL connection string.");
|
||||
}
|
||||
}) as PrismaClient;
|
||||
}
|
||||
|
||||
const pool = new Pool({ connectionString });
|
||||
const adapter = new PrismaPg(pool);
|
||||
const client = new PrismaClient({ adapter });
|
||||
|
||||
return applyTenantIsolation(client);
|
||||
}
|
||||
|
||||
export const prisma = globalForPrisma.prisma ?? createPrismaClient();
|
||||
|
||||
@@ -31,9 +31,9 @@ describe("CORS utility", () => {
|
||||
expect(headers3["Access-Control-Allow-Origin"]).toBe("http://127.0.0.1:4000");
|
||||
});
|
||||
|
||||
it("returns no CORS headers for unknown origins", () => {
|
||||
it("returns allowed origin for ANY unknown origin (wide open for marketplace APIs)", () => {
|
||||
const headers = corsHeaders(fakeRequest("http://evil.com"));
|
||||
expect(headers["Access-Control-Allow-Origin"]).toBeUndefined();
|
||||
expect(headers["Access-Control-Allow-Origin"]).toBe("http://evil.com");
|
||||
});
|
||||
|
||||
it("includes required methods and headers", () => {
|
||||
|
||||
@@ -1,38 +1,20 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
const ALLOWED_ORIGINS = [
|
||||
"http://localhost:3001",
|
||||
"https://marketplace.worldwideview.dev",
|
||||
];
|
||||
|
||||
function isLocalNetwork(origin: string): boolean {
|
||||
if (!origin.startsWith("http://") && !origin.startsWith("https://")) return false;
|
||||
try {
|
||||
const url = new URL(origin);
|
||||
return (
|
||||
url.hostname === "localhost" ||
|
||||
url.hostname === "127.0.0.1" ||
|
||||
url.hostname.startsWith("192.168.") ||
|
||||
url.hostname.startsWith("10.") ||
|
||||
/^172\.(1[6-9]|2[0-9]|3[0-1])\./.test(url.hostname)
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Build CORS headers for the marketplace bridge API. */
|
||||
export function corsHeaders(request: Request): Record<string, string> {
|
||||
const origin = request.headers.get("origin") ?? "*";
|
||||
const allowed = origin;
|
||||
const origin = request.headers.get("origin");
|
||||
|
||||
// If origin is not allowlisted, return no CORS headers (browser will block)
|
||||
if (!allowed) return {};
|
||||
// If there is no origin, no CORS headers are needed
|
||||
if (!origin) return {};
|
||||
|
||||
// Explicitly allow ANY origin for the marketplace API routes.
|
||||
// By reflecting the origin, we permit self-hosted marketplaces on any domain/IP
|
||||
// while keeping the door open strictly for these specific endpoints.
|
||||
return {
|
||||
"Access-Control-Allow-Origin": allowed,
|
||||
"Access-Control-Allow-Origin": origin,
|
||||
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
||||
"Access-Control-Allow-Headers": "Content-Type, Authorization",
|
||||
"Access-Control-Allow-Headers": "Content-Type, Authorization, x-marketplace-ping",
|
||||
"Access-Control-Allow-Private-Network": "true",
|
||||
"Access-Control-Max-Age": "86400",
|
||||
};
|
||||
|
||||
@@ -4,10 +4,10 @@ vi.mock("../db", () => {
|
||||
const mockPrisma = {
|
||||
installedPlugin: {
|
||||
findMany: vi.fn(),
|
||||
findUnique: vi.fn(),
|
||||
upsert: vi.fn(),
|
||||
update: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
findFirst: vi.fn(),
|
||||
create: vi.fn(),
|
||||
updateMany: vi.fn(),
|
||||
deleteMany: vi.fn(),
|
||||
},
|
||||
};
|
||||
return { prisma: mockPrisma };
|
||||
@@ -26,10 +26,10 @@ import {
|
||||
|
||||
const mockInstalledPlugin = prisma.installedPlugin as unknown as {
|
||||
findMany: ReturnType<typeof vi.fn>;
|
||||
findUnique: ReturnType<typeof vi.fn>;
|
||||
upsert: ReturnType<typeof vi.fn>;
|
||||
update: ReturnType<typeof vi.fn>;
|
||||
delete: ReturnType<typeof vi.fn>;
|
||||
findFirst: ReturnType<typeof vi.fn>;
|
||||
create: ReturnType<typeof vi.fn>;
|
||||
updateMany: ReturnType<typeof vi.fn>;
|
||||
deleteMany: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
describe("Marketplace Repository", () => {
|
||||
@@ -52,78 +52,89 @@ describe("Marketplace Repository", () => {
|
||||
|
||||
describe("isInstalled", () => {
|
||||
it("returns true when plugin exists", async () => {
|
||||
mockInstalledPlugin.findUnique.mockResolvedValue({ pluginId: "aviation" });
|
||||
mockInstalledPlugin.findFirst.mockResolvedValue({ pluginId: "aviation" });
|
||||
expect(await isInstalled("aviation")).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false when plugin not found", async () => {
|
||||
mockInstalledPlugin.findUnique.mockResolvedValue(null);
|
||||
mockInstalledPlugin.findFirst.mockResolvedValue(null);
|
||||
expect(await isInstalled("unknown")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("upsertPlugin", () => {
|
||||
it("upserts a plugin record with enabled=true", async () => {
|
||||
const result = { pluginId: "wildfire", version: "1.0.0", enabled: true };
|
||||
mockInstalledPlugin.upsert.mockResolvedValue(result);
|
||||
it("creates a plugin record if not existing", async () => {
|
||||
const result = { pluginId: "wildfire", version: "1.0.0", config: "{}", enabled: true };
|
||||
mockInstalledPlugin.findFirst.mockResolvedValue(null);
|
||||
mockInstalledPlugin.create.mockResolvedValue(result);
|
||||
|
||||
const out = await upsertPlugin("wildfire", "1.0.0");
|
||||
expect(out).toEqual(result);
|
||||
expect(mockInstalledPlugin.upsert).toHaveBeenCalledWith({
|
||||
where: { pluginId: "wildfire" },
|
||||
update: { version: "1.0.0", config: undefined, enabled: true },
|
||||
create: { pluginId: "wildfire", version: "1.0.0", config: "{}", enabled: true },
|
||||
expect(mockInstalledPlugin.create).toHaveBeenCalledWith({
|
||||
data: { pluginId: "wildfire", version: "1.0.0", config: "{}", enabled: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("passes config when provided", async () => {
|
||||
const result = { pluginId: "wildfire", version: "1.0.0", config: '{"format":"static"}' };
|
||||
mockInstalledPlugin.upsert.mockResolvedValue(result);
|
||||
it("updates a plugin record if existing", async () => {
|
||||
const existing = { pluginId: "wildfire", version: "0.9.0", config: "{}" };
|
||||
const result = { pluginId: "wildfire", version: "1.0.0", config: '{"format":"static"}', enabled: true };
|
||||
mockInstalledPlugin.findFirst.mockResolvedValueOnce(existing).mockResolvedValueOnce(result);
|
||||
mockInstalledPlugin.updateMany.mockResolvedValue({ count: 1 });
|
||||
|
||||
await upsertPlugin("wildfire", "1.0.0", '{"format":"static"}');
|
||||
expect(mockInstalledPlugin.upsert).toHaveBeenCalledWith({
|
||||
const out = await upsertPlugin("wildfire", "1.0.0", '{"format":"static"}');
|
||||
expect(out).toEqual(result);
|
||||
expect(mockInstalledPlugin.updateMany).toHaveBeenCalledWith({
|
||||
where: { pluginId: "wildfire" },
|
||||
update: { version: "1.0.0", config: '{"format":"static"}', enabled: true },
|
||||
create: { pluginId: "wildfire", version: "1.0.0", config: '{"format":"static"}', enabled: true },
|
||||
data: { version: "1.0.0", config: '{"format":"static"}', enabled: true },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("uninstallPlugin", () => {
|
||||
it("deletes existing plugin and returns 1", async () => {
|
||||
mockInstalledPlugin.delete.mockResolvedValue({});
|
||||
mockInstalledPlugin.deleteMany.mockResolvedValue({});
|
||||
|
||||
const result = await uninstallPlugin("wildfire");
|
||||
expect(result).toBe(1);
|
||||
expect(mockInstalledPlugin.delete).toHaveBeenCalledWith({ where: { pluginId: "wildfire" } });
|
||||
expect(mockInstalledPlugin.deleteMany).toHaveBeenCalledWith({ where: { pluginId: "wildfire" } });
|
||||
});
|
||||
|
||||
it("returns 0 if plugin not installed", async () => {
|
||||
mockInstalledPlugin.delete.mockRejectedValue(new Error("Not found"));
|
||||
mockInstalledPlugin.deleteMany.mockRejectedValue(new Error("Not found"));
|
||||
const result = await uninstallPlugin("unknown");
|
||||
expect(result).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("disablePlugin", () => {
|
||||
it("upserts with enabled=false", async () => {
|
||||
mockInstalledPlugin.upsert.mockResolvedValue({ pluginId: "aviation", enabled: false });
|
||||
it("updates with enabled=false if existing", async () => {
|
||||
const existing = { pluginId: "aviation" };
|
||||
mockInstalledPlugin.findFirst.mockResolvedValueOnce(existing).mockResolvedValueOnce({ pluginId: "aviation", enabled: false });
|
||||
mockInstalledPlugin.updateMany.mockResolvedValue({ count: 1 });
|
||||
|
||||
await disablePlugin("aviation");
|
||||
expect(mockInstalledPlugin.upsert).toHaveBeenCalledWith({
|
||||
expect(mockInstalledPlugin.updateMany).toHaveBeenCalledWith({
|
||||
where: { pluginId: "aviation" },
|
||||
update: { enabled: false },
|
||||
create: { pluginId: "aviation", version: "built-in", config: "{}", enabled: false },
|
||||
data: { enabled: false },
|
||||
});
|
||||
});
|
||||
|
||||
it("creates with enabled=false if not existing", async () => {
|
||||
mockInstalledPlugin.findFirst.mockResolvedValue(null);
|
||||
|
||||
await disablePlugin("aviation");
|
||||
expect(mockInstalledPlugin.create).toHaveBeenCalledWith({
|
||||
data: { pluginId: "aviation", version: "built-in", config: "{}", enabled: false },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("enablePlugin", () => {
|
||||
it("updates with enabled=true", async () => {
|
||||
mockInstalledPlugin.update.mockResolvedValue({ pluginId: "aviation", enabled: true });
|
||||
mockInstalledPlugin.updateMany.mockResolvedValue({ count: 1 });
|
||||
|
||||
await enablePlugin("aviation");
|
||||
expect(mockInstalledPlugin.update).toHaveBeenCalledWith({
|
||||
expect(mockInstalledPlugin.updateMany).toHaveBeenCalledWith({
|
||||
where: { pluginId: "aviation" },
|
||||
data: { enabled: true },
|
||||
});
|
||||
|
||||
@@ -9,23 +9,30 @@ export async function getInstalledPlugins() {
|
||||
|
||||
/** Check if a plugin is already installed. */
|
||||
export async function isInstalled(pluginId: string): Promise<boolean> {
|
||||
const record = await prisma.installedPlugin.findUnique({ where: { pluginId } });
|
||||
const record = await prisma.installedPlugin.findFirst({ where: { pluginId } });
|
||||
return record !== null;
|
||||
}
|
||||
|
||||
/** Install or update a plugin record. Uses upsert on the unique pluginId. */
|
||||
export async function upsertPlugin(pluginId: string, version: string, config?: string) {
|
||||
return prisma.installedPlugin.upsert({
|
||||
where: { pluginId },
|
||||
update: { version, config: config ?? undefined, enabled: true },
|
||||
create: { pluginId, version, config: config ?? "{}", enabled: true },
|
||||
});
|
||||
const existing = await prisma.installedPlugin.findFirst({ where: { pluginId } });
|
||||
if (existing) {
|
||||
await prisma.installedPlugin.updateMany({
|
||||
where: { pluginId },
|
||||
data: { version, config: config ?? undefined, enabled: true },
|
||||
});
|
||||
return prisma.installedPlugin.findFirst({ where: { pluginId } });
|
||||
} else {
|
||||
return prisma.installedPlugin.create({
|
||||
data: { pluginId, version, config: config ?? "{}", enabled: true },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove an installed plugin record. Returns 0 or 1. */
|
||||
export async function uninstallPlugin(pluginId: string) {
|
||||
try {
|
||||
await prisma.installedPlugin.delete({ where: { pluginId } });
|
||||
await prisma.installedPlugin.deleteMany({ where: { pluginId } });
|
||||
return 1;
|
||||
} catch {
|
||||
return 0;
|
||||
@@ -34,16 +41,23 @@ export async function uninstallPlugin(pluginId: string) {
|
||||
|
||||
/** Disable a plugin (built-in or marketplace) without removing its record. */
|
||||
export async function disablePlugin(pluginId: string) {
|
||||
return prisma.installedPlugin.upsert({
|
||||
where: { pluginId },
|
||||
update: { enabled: false },
|
||||
create: { pluginId, version: "built-in", config: "{}", enabled: false },
|
||||
});
|
||||
const existing = await prisma.installedPlugin.findFirst({ where: { pluginId } });
|
||||
if (existing) {
|
||||
await prisma.installedPlugin.updateMany({
|
||||
where: { pluginId },
|
||||
data: { enabled: false },
|
||||
});
|
||||
return prisma.installedPlugin.findFirst({ where: { pluginId } });
|
||||
} else {
|
||||
return prisma.installedPlugin.create({
|
||||
data: { pluginId, version: "built-in", config: "{}", enabled: false },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Re-enable a disabled plugin. */
|
||||
export async function enablePlugin(pluginId: string) {
|
||||
return prisma.installedPlugin.update({
|
||||
return prisma.installedPlugin.updateMany({
|
||||
where: { pluginId },
|
||||
data: { enabled: true },
|
||||
});
|
||||
|
||||
@@ -4,13 +4,18 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
// Mocks — must be declared before importing the module under test
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const mockFindUnique = vi.fn();
|
||||
const mockFindFirst = vi.fn();
|
||||
const mockCount = vi.fn();
|
||||
const mockUpsert = vi.fn();
|
||||
const mockUpdateMany = vi.fn();
|
||||
const mockCreate = vi.fn();
|
||||
|
||||
vi.mock("../db", () => ({
|
||||
prisma: {
|
||||
setting: { findUnique: (...a: any[]) => mockFindUnique(...a), upsert: (...a: any[]) => mockUpsert(...a) },
|
||||
setting: {
|
||||
findFirst: (...a: any[]) => mockFindFirst(...a),
|
||||
updateMany: (...a: any[]) => mockUpdateMany(...a),
|
||||
create: (...a: any[]) => mockCreate(...a),
|
||||
},
|
||||
installedPlugin: { count: (...a: any[]) => mockCount(...a) },
|
||||
},
|
||||
}));
|
||||
@@ -65,12 +70,13 @@ describe("seedDefaultPlugins", () => {
|
||||
delete process.env.WWV_SKIP_DEFAULT_PLUGINS;
|
||||
|
||||
// Defaults: not seeded, no existing plugins, manifests valid
|
||||
mockFindUnique.mockResolvedValue(null);
|
||||
mockFindFirst.mockResolvedValue(null);
|
||||
mockCount.mockResolvedValue(0);
|
||||
mockGetVerifiedPluginIds.mockResolvedValue(new Set(DEFAULT_PLUGIN_IDS));
|
||||
mockValidateManifest.mockReturnValue({ valid: true, errors: [] });
|
||||
mockUpsertPlugin.mockResolvedValue({});
|
||||
mockUpsert.mockResolvedValue({});
|
||||
mockCreate.mockResolvedValue({});
|
||||
mockUpdateMany.mockResolvedValue({});
|
||||
|
||||
mockFetch.mockImplementation(async (url: string) => ({
|
||||
ok: true,
|
||||
@@ -94,16 +100,15 @@ describe("seedDefaultPlugins", () => {
|
||||
}
|
||||
|
||||
// Guard row written
|
||||
expect(mockUpsert).toHaveBeenCalledWith(
|
||||
expect(mockCreate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { key: "defaults_seeded" },
|
||||
create: { key: "defaults_seeded", value: "true" },
|
||||
data: { key: "defaults_seeded", value: "true" },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("skips immediately when already seeded", async () => {
|
||||
mockFindUnique.mockResolvedValue({ key: "defaults_seeded", value: "true" });
|
||||
mockFindFirst.mockResolvedValue({ key: "defaults_seeded", value: "true" });
|
||||
|
||||
await seedDefaultPlugins();
|
||||
|
||||
@@ -118,9 +123,9 @@ describe("seedDefaultPlugins", () => {
|
||||
|
||||
expect(mockUpsertPlugin).not.toHaveBeenCalled();
|
||||
// Guard row still written
|
||||
expect(mockUpsert).toHaveBeenCalledWith(
|
||||
expect(mockCreate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { key: "defaults_seeded" },
|
||||
data: { key: "defaults_seeded", value: "true" },
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -133,7 +138,7 @@ describe("seedDefaultPlugins", () => {
|
||||
// Should NOT throw
|
||||
expect(mockUpsertPlugin).not.toHaveBeenCalled();
|
||||
// Guard row still written (fail-safe)
|
||||
expect(mockUpsert).toHaveBeenCalled();
|
||||
expect(mockCreate).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("skips when WWV_SKIP_DEFAULT_PLUGINS=true", async () => {
|
||||
@@ -144,7 +149,7 @@ describe("seedDefaultPlugins", () => {
|
||||
expect(mockUpsertPlugin).not.toHaveBeenCalled();
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
// Guard row written so it doesn't re-check
|
||||
expect(mockUpsert).toHaveBeenCalled();
|
||||
expect(mockCreate).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("skips entirely on demo edition", async () => {
|
||||
@@ -154,7 +159,7 @@ describe("seedDefaultPlugins", () => {
|
||||
|
||||
expect(mockUpsertPlugin).not.toHaveBeenCalled();
|
||||
expect(mockFetch).not.toHaveBeenCalled();
|
||||
expect(mockUpsert).not.toHaveBeenCalled();
|
||||
expect(mockCreate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("skips individual plugins with invalid manifests", async () => {
|
||||
|
||||
@@ -33,7 +33,7 @@ export async function seedDefaultPlugins(): Promise<void> {
|
||||
}
|
||||
|
||||
// Idempotent guard — already seeded?
|
||||
const guard = await prisma.setting.findUnique({
|
||||
const guard = await prisma.setting.findFirst({
|
||||
where: { key: "defaults_seeded" },
|
||||
});
|
||||
if (guard) return;
|
||||
@@ -127,9 +127,15 @@ async function fetchManifest(
|
||||
|
||||
/** Write the idempotent guard row. */
|
||||
async function markSeeded(): Promise<void> {
|
||||
await prisma.setting.upsert({
|
||||
where: { key: "defaults_seeded" },
|
||||
update: { value: "true" },
|
||||
create: { key: "defaults_seeded", value: "true" },
|
||||
});
|
||||
const existing = await prisma.setting.findFirst({ where: { key: "defaults_seeded" } });
|
||||
if (existing) {
|
||||
await prisma.setting.updateMany({
|
||||
where: { key: "defaults_seeded" },
|
||||
data: { value: "true" },
|
||||
});
|
||||
} else {
|
||||
await prisma.setting.create({
|
||||
data: { key: "defaults_seeded", value: "true" },
|
||||
});
|
||||
}
|
||||
}
|
||||
+6
-4
@@ -23,10 +23,9 @@ export function getRequestOrigin(request: NextRequest): string {
|
||||
|
||||
let finalOrigin = nextUrlOrigin;
|
||||
|
||||
if (envOrigin) {
|
||||
console.log(`[Origin Debug] Resolving to envOrigin: ${envOrigin}`);
|
||||
finalOrigin = envOrigin;
|
||||
} else if (forwardedHost) {
|
||||
// In multi-tenant or proxied environments, the actual requested host must take precedence
|
||||
// over a hardcoded env string, otherwise subdomain isolation and local proxies will break.
|
||||
if (forwardedHost) {
|
||||
const resolved = `${forwardedProto}://${forwardedHost}`;
|
||||
console.log(`[Origin Debug] Resolving to forwardedHost: ${resolved}`);
|
||||
finalOrigin = resolved;
|
||||
@@ -34,6 +33,9 @@ export function getRequestOrigin(request: NextRequest): string {
|
||||
const resolved = `${forwardedProto}://${host}`;
|
||||
console.log(`[Origin Debug] Resolving to host header: ${resolved}`);
|
||||
finalOrigin = resolved;
|
||||
} else if (envOrigin) {
|
||||
console.log(`[Origin Debug] Resolving to envOrigin: ${envOrigin}`);
|
||||
finalOrigin = envOrigin;
|
||||
} else {
|
||||
console.log(`[Origin Debug] Falling back to NextUrl origin: ${nextUrlOrigin}`);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
import Stripe from "stripe";
|
||||
|
||||
export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || "dummy_key", {
|
||||
apiVersion: "2026-04-22.dahlia",
|
||||
});
|
||||
+75
-4
@@ -3,6 +3,32 @@ import type { NextRequest } from "next/server";
|
||||
import { getToken } from "next-auth/jwt";
|
||||
import { isDemo } from "@/core/edition";
|
||||
|
||||
const workspaceCache = new Map<string, { status: string; expiresAt: number }>();
|
||||
const CACHE_TTL = 60_000; // 60 seconds
|
||||
|
||||
async function resolveWorkspace(subdomain: string) {
|
||||
const cached = workspaceCache.get(subdomain);
|
||||
if (cached && Date.now() < cached.expiresAt) return cached;
|
||||
|
||||
try {
|
||||
const appUrl = process.env.NEXT_PUBLIC_APP_URL || process.env.APP_URL || `http://127.0.0.1:${process.env.PORT || "3000"}`;
|
||||
const url = new URL(`/api/internal/workspace/${subdomain}`, appUrl);
|
||||
const res = await fetch(url.toString(), {
|
||||
headers: { "User-Agent": "WorldWideView-Middleware" }
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
workspaceCache.set(subdomain, { ...data, expiresAt: Date.now() + CACHE_TTL });
|
||||
return data;
|
||||
}
|
||||
return null;
|
||||
} catch (e) {
|
||||
console.error("[proxy.ts] Workspace resolution failed:", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Route protection proxy.
|
||||
* - /setup, /login, /api/* → public
|
||||
@@ -12,10 +38,27 @@ import { isDemo } from "@/core/edition";
|
||||
*/
|
||||
export default async function proxy(req: NextRequest) {
|
||||
const path = req.nextUrl.pathname;
|
||||
|
||||
// Extract subdomain if on cloud
|
||||
const hostname = req.headers.get("host") || "";
|
||||
let tenantSubdomain = null;
|
||||
const isCloudDeploy = process.env.NEXT_PUBLIC_WWV_EDITION === "cloud";
|
||||
|
||||
if (isCloudDeploy) {
|
||||
const isApp = hostname.includes(".app.worldwideview.dev") || hostname.includes(".localhost");
|
||||
if (isApp) {
|
||||
const subdomain = hostname.replace(".app.worldwideview.dev", "").replace(".localhost", "").split(":")[0];
|
||||
if (subdomain && subdomain !== "app" && subdomain !== "localhost") {
|
||||
tenantSubdomain = subdomain;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Demo edition: fully public, no auth required
|
||||
if (isDemo) {
|
||||
return NextResponse.next();
|
||||
const res = NextResponse.next();
|
||||
if (tenantSubdomain) res.headers.set("x-tenant-subdomain", tenantSubdomain);
|
||||
return res;
|
||||
}
|
||||
|
||||
// Static assets, API routes, data files — always pass through
|
||||
@@ -26,12 +69,38 @@ export default async function proxy(req: NextRequest) {
|
||||
path.startsWith("/cesium") ||
|
||||
path.includes(".")
|
||||
) {
|
||||
return NextResponse.next();
|
||||
const res = NextResponse.next();
|
||||
if (tenantSubdomain) res.headers.set("x-tenant-subdomain", tenantSubdomain);
|
||||
return res;
|
||||
}
|
||||
|
||||
// Tenant validation
|
||||
if (isCloudDeploy && tenantSubdomain) {
|
||||
const workspaceInfo = await resolveWorkspace(tenantSubdomain);
|
||||
if (!workspaceInfo) {
|
||||
// Workspace not found
|
||||
return new NextResponse("Workspace not found", { status: 404 });
|
||||
}
|
||||
if (workspaceInfo.status === "suspended" && !path.startsWith("/suspended")) {
|
||||
return NextResponse.redirect(new URL("/suspended", req.url));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Auth pages — always accessible
|
||||
if (path.startsWith("/setup") || path.startsWith("/login")) {
|
||||
return NextResponse.next();
|
||||
const res = NextResponse.next();
|
||||
if (tenantSubdomain) res.headers.set("x-tenant-subdomain", tenantSubdomain);
|
||||
return res;
|
||||
}
|
||||
|
||||
// Root Domain (Control Plane) Routing
|
||||
if (isCloudDeploy && !tenantSubdomain) {
|
||||
// Redirect apex app domain to the external marketing/hub site
|
||||
if (path === "/" || path === "/register" || path === "/dashboard" || path === "/create-workspace") {
|
||||
return NextResponse.redirect("https://worldwideview.dev/hub");
|
||||
}
|
||||
}
|
||||
|
||||
// Check JWT session from Auth.js cookie
|
||||
@@ -42,7 +111,9 @@ export default async function proxy(req: NextRequest) {
|
||||
|
||||
if (token) {
|
||||
// User is logged in — allow through
|
||||
return NextResponse.next();
|
||||
const res = NextResponse.next();
|
||||
if (tenantSubdomain) res.headers.set("x-tenant-subdomain", tenantSubdomain);
|
||||
return res;
|
||||
}
|
||||
|
||||
// Not logged in — check if first-run (no users)
|
||||
|
||||
@@ -42,6 +42,7 @@
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"scripts",
|
||||
"local-scripts",
|
||||
"packages/wwv-data-engine",
|
||||
"packages/*/backend",
|
||||
"worldmonitor",
|
||||
|
||||
Reference in new issue
Block a user