# Blueprint – Commands reference

All commands are run from the **repository root** unless noted.

---

## Local development

| Command | Description |
|--------|-------------|
| `npm run dev` | Start local server (Node, port 3000) |
| `npm run dev:serve` | Same as `npx serve -s -l 3000` |
| `npx serve .` | Static server on port 3000; open http://localhost:3000 |

---

## Build & deploy

| Command | Description |
|--------|-------------|
| `npm run build` | Generate `supabase-config.js` from env (Vercel: set `BLUEPRINT_SUPABASE_URL`, `BLUEPRINT_SUPABASE_ANON_KEY`) |
| `npm start` | Same as `npx serve -s -l 3000` |

**Vercel:** Connect repo, set Build Command to `npm run build`, add env vars, deploy.

---

## Supabase

### Migrations (run in Supabase Dashboard → SQL Editor)

Run in order: `001_schema_and_rls.sql`, `002_roles_and_admin.sql`, `003_plans.sql`, `004_plans_table.sql`, `005_plans_stripe_price_id.sql`, `006_app_settings.sql`, … then any later migrations in `supabase/migrations/`.

### Set admin (SQL Editor)

```sql
UPDATE public.profiles SET role = 'admin' WHERE id = (SELECT id FROM auth.users WHERE email = 'your@email.com');
```

### Password reset (local, no email)

```bash
SUPABASE_URL=https://YOUR_PROJECT.supabase.co SUPABASE_SERVICE_ROLE_KEY=your_service_role_key node scripts/set-password-local.js your@email.com YourNewPassword
```

### Edge Functions – deploy all (recommended)

```bash
bash scripts/shell/deploy-functions.sh
```

Requires: `supabase login`, then `supabase link --project-ref YOUR_PROJECT_REF`. Edit the script to use your project ref if needed.

### Edge Functions – deploy individually

Replace `YOUR_PROJECT_REF` with your Supabase project ref (from dashboard URL).

```bash
# Auth / JWT handled inside function → use --no-verify-jwt
supabase functions deploy create-checkout-session --project-ref YOUR_PROJECT_REF --no-verify-jwt
supabase functions deploy create-billing-portal-session --project-ref YOUR_PROJECT_REF --no-verify-jwt
supabase functions deploy send-admin-email --project-ref YOUR_PROJECT_REF --no-verify-jwt
supabase functions deploy ai-assist --project-ref YOUR_PROJECT_REF --no-verify-jwt
supabase functions deploy ai-analytics-insights --project-ref YOUR_PROJECT_REF --no-verify-jwt
supabase functions deploy fetch-document --project-ref YOUR_PROJECT_REF --no-verify-jwt
supabase functions deploy ga4-measurement --project-ref YOUR_PROJECT_REF --no-verify-jwt
supabase functions deploy ga4-audit --project-ref YOUR_PROJECT_REF --no-verify-jwt
supabase functions deploy ga4-recent-events --project-ref YOUR_PROJECT_REF --no-verify-jwt
supabase functions deploy detect-website-config --project-ref YOUR_PROJECT_REF --no-verify-jwt

# No --no-verify-jwt (gateway checks JWT)
supabase functions deploy stripe-webhook --project-ref YOUR_PROJECT_REF
supabase functions deploy delete-account --project-ref YOUR_PROJECT_REF
supabase functions deploy pause-subscription --project-ref YOUR_PROJECT_REF
supabase functions deploy resume-subscription --project-ref YOUR_PROJECT_REF
```

### Edge Functions – test all

```bash
bash scripts/shell/test-all-functions.sh
```

Uses URLs and anon key in the script; edit if your project/keys differ. See also `scripts/shell/test-all-functions-commands.txt` for manual curl commands.

### Edge Functions – audit monitors

```bash
bash scripts/shell/audit-monitors.sh
```

---

## Scripts – Shell (`scripts/shell/`)

| Command | Description |
|--------|-------------|
| `bash scripts/shell/deploy-functions.sh` | Deploy all Supabase Edge Functions with correct flags |
| `bash scripts/shell/test-all-functions.sh` | Hit all function health endpoints |
| `bash scripts/shell/audit-monitors.sh` | Audit monitoring setup |

---

## Scripts – Maintenance (`scripts/maintenance/`)

One-off Node scripts for guides, DB checks, and migrations. Run with `node scripts/maintenance/<name>.js`. Ensure Supabase/config is set if the script talks to the DB.

| Script | Purpose |
|--------|---------|
| `check-database-guides.js` | Check guide records in DB |
| `check-guide-flags-console.js` | Check guide flags (console) |
| `cleanup-before-migration.js` | Cleanup before running a migration |
| `debug-deleted-guide.js` | Debug deleted guide issues |
| `delete-guide-console.js` | Delete a guide (console) |
| `delete-handoff-checklist.js` | Remove handoff checklist guide |
| `delete-old-guide-direct.js` | Delete old guide (direct) |
| `delete-orphan-guides.js` | Remove orphaned guide rows |
| `delete-testing-qa-guide.js` | Remove testing/QA guide |
| `fix-guide-flags.js` | Fix guide flag state |
| `remove-deleted-guides.js` | Remove deleted guides from DB |
| `test-delete-guide.js` | Test guide deletion flow |
| `test-guide-persistence.js` | Test guide persistence |
| `tmp_framework_ai_handlers.js` | Temporary framework/AI handlers |
| `trace-delete.js` | Trace delete operations |
| `validate-sections.js` | Validate checklist/guide sections |
| `verify-guides-deleted.js` | Verify guides are deleted |

---

## Other scripts (`scripts/`)

| Command | Description |
|--------|-------------|
| `node scripts/set-password-local.js your@email.com NewPassword` | Set user password (use with `SUPABASE_URL` and `SUPABASE_SERVICE_ROLE_KEY`) |
| `node scripts/write-supabase-config.js` | Write `supabase-config.js` from env (used by `npm run build`) |
| `node scripts/extract-demo-docx.js` | Extract content from demo DOCX (see script for args) |

Python patch/apply scripts in `scripts/python/` (e.g. `apply_*.py`, `patch_*.py`) are for one-off codebase patches; run with `python scripts/python/<name>.py` if needed.

---

## Stripe webhook (one-time setup)

Stripe Dashboard → Developers → Webhooks → Add endpoint:

- **URL:** `https://YOUR_PROJECT_REF.supabase.co/functions/v1/stripe-webhook`
- **Events:** `checkout.session.completed`, `customer.subscription.deleted`

Copy the signing secret into Supabase Edge Function secret: `STRIPE_WEBHOOK_SECRET`.

---

## Edge Function secrets (Supabase Dashboard → Edge Functions → Secrets)

Common secrets:

| Secret | Used by |
|--------|--------|
| `STRIPE_SECRET_KEY` | Checkout, billing portal |
| `STRIPE_WEBHOOK_SECRET` | stripe-webhook |
| `BREVO_API_KEY` | send-admin-email |
| `OPENAI_API_KEY` | ai-assist, ai-analytics-insights |
| `GA4_PROPERTY_ID` | ai-analytics-insights, ga4-recent-events (optional) |
| `GA4_SERVICE_ACCOUNT_JSON` | ga4-audit, ga4-recent-events, ai-analytics-insights (optional) |

---

## Browser console (dev / support)

Run these in the browser DevTools console on the Blueprint app (e.g. `index.html` or your deployed URL). Useful for support, testing, or incognito reset.

### Reset site (logged-out / incognito)

Clear all Blueprint-related `localStorage` and `sessionStorage`, then reload so the app starts fresh (no projects, frameworks, guides, checklist, or UI prefs).

```javascript
(function () {
  var keys = [];
  for (var i = 0; i < localStorage.length; i++) keys.push(localStorage.key(i));
  keys.forEach(function (k) {
    if (/^blueprint|^crossDomain|^gaAudit|^lastViewedGaAudit|^lastImplementationToolsTab/.test(k)) localStorage.removeItem(k);
  });
  if (typeof sessionStorage !== 'undefined') {
    ['blueprint_checkout_success', 'blueprint_return_to_pricing', 'blueprint_signup_plan', 'blueprint_billing_interval'].forEach(function (k) { sessionStorage.removeItem(k); });
  }
  console.log('Blueprint storage cleared. Reloading.');
  location.reload();
})();
```

**Alternative (no reload):** Omit the `location.reload()` line if you only want to clear storage; the UI may be stale until you refresh or navigate.

### Open product tour (presentation slides)

The Tour is no longer linked in the footer; you can still open it from the console:

```javascript
if (window.Blueprint && window.Blueprint.presentationModal) window.Blueprint.presentationModal.open();
```

### Inspect current project / framework (guest)

```javascript
console.log('Project:', localStorage.getItem('crossDomainSelectedProjectId'));
console.log('Guides key:', (window.Blueprint && window.Blueprint.storage && window.Blueprint.storage.KEYS && window.Blueprint.storage.KEYS.GUIDES) || 'crossDomainGuides');
```

### List all Blueprint-related storage keys

```javascript
var out = { local: [], session: [] };
for (var i = 0; i < localStorage.length; i++) {
  var k = localStorage.key(i);
  if (/blueprint|crossDomain|gaAudit|lastViewedGaAudit|lastImplementationToolsTab/.test(k)) out.local.push(k);
}
if (typeof sessionStorage !== 'undefined') {
  for (var j = 0; j < sessionStorage.length; j++) {
    var s = sessionStorage.key(j);
    if (/blueprint/.test(s)) out.session.push(s);
  }
}
console.table(out.local); console.table(out.session);
```

### Clear only projects/frameworks/guides (keep UI prefs)

```javascript
['crossDomainProjects', 'crossDomainFrameworks', 'crossDomainGuides', 'crossDomainChecklist', 'crossDomainSelectedProjectId', 'crossDomainSelectedGuideId'].forEach(function (k) { localStorage.removeItem(k); });
console.log('Projects/frameworks/guides cleared. Reload to see empty state.');
```

### Error messages gate (toasts)

Error toasts (e.g. “Failed to save”, “Session expired”) are **hidden by default**. You can turn them on in **Account & Profile → Account** via the “Show error messages” checkbox; that choice is stored in `localStorage` and persists until you change it.

**Console:**

| Action | Command |
|--------|--------|
| Turn error toasts **on** | `Blueprint.setShowErrorMessages(true); location.reload();` |
| Turn error toasts **off** | `Blueprint.setShowErrorMessages(false); location.reload();` |
| Check current setting | `Blueprint.getShowErrorMessages()` |
| Reset to default (hidden) | `localStorage.removeItem('blueprintShowErrorMessages'); location.reload();` |

When the gate is off, failed actions do not show a toast; you can still see the message in the console as `[Blueprint] <message>` (from `console.warn`).

### Debug / verbose console logs

Verbose Blueprint logs (checklist, GA Audit, persist, invalidate caches, etc.) are **off by default** so the console stays quiet. Enable them only when debugging.

**Enable verbose logs:**

```javascript
localStorage.setItem('blueprintDebug', 'true');
location.reload();
```

Or, for the current page only (lost on reload): `window.__BLUEPRINT_DEBUG = true;` then reload.

**Disable verbose logs (quiet console):**

```javascript
localStorage.removeItem('blueprintDebug');
location.reload();
```

**Check if debug logging is on:** `Blueprint.isDebugLog()` (or inspect `localStorage.getItem('blueprintDebug')`).

---

*For full setup (auth, Stripe, AI, etc.) see [README.md](../README.md).*
