{"project":"despia_v3_landing","branch":"main","commit":"2610bc4610586aefcab21c455eedf8a609160b27","component":{"name":"Lovable","route":{"info":{"meta":{"promptWatch":{"tag":"script","attrs":{},"content":{"type":"value","value":"(function() { var script = document.createElement('script'); script.setAttribute('data-project-id', 'b0214ced-57ba-4364-8e71-09c628154fbf'); script.src = 'https://ingest.promptwatch.com/js/client.min.js'; document.head.appendChild(script); })();"}}}},"path":[{"name":"setup","type":"static"},{"name":"lovable","type":"static"}],"query":{}},"onLoad":{"actions":[{"name":"@toddle/gotToURL","arguments":[{"name":"URL","formula":{"name":"@toddle/concatenate","type":"function","arguments":[{"name":"0","type":{"type":"Array \\| String"},"formula":{"type":"value","value":"https://lovable.dev/"}},{"name":"0","type":{"type":"Array \\| String"},"formula":{"type":"value","value":"?autosubmit=true"}},{"name":"0","type":{"type":"Array \\| String"},"formula":{"name":"@toddle/concatenate","type":"function","arguments":[{"name":"0","type":{"type":"Array \\| String"},"formula":{"type":"value","value":"#prompt="}},{"name":"0","type":{"type":"Array \\| String"},"formula":{"name":"@toddle/encodeURIComponent","type":"function","arguments":[{"name":"URIComponent","type":{"type":"String"},"formula":{"name":"@toddle/string","type":"function","arguments":[{"name":"Input","type":{"type":"Any"},"formula":{"type":"value","value":"# Despia × Lovable\n\n> Authoritative prompt for setting up **Despia-native** features in a Lovable project: RevenueCat purchases, server-authoritative unlock via events, DB concepts, Apple/Google login behavior, deep links, push, link handling, UI guardrails, and a **Lovable browsing ritual** for always-fresh docs. Tailored for Lovable’s built-in tools (no external scripts).\n\n---\n\n## 0) Operating Mode (read first)\n\n* **Native layer:** use **Despia** only.\n\n  ```bash\n  npm install despia-native\n  ```\n\n  ```ts\n  import despia from 'despia-native';\n  ```\n\n  Call `despia('scheme://...')` where needed and read Despia variables **directly** (e.g., device UUID, push player id). **No custom wrappers.**\n\n* **Deep links & associated domains:**\n  Host iOS **AASA** at `/.well-known/apple-app-site-association` and Android **assetlinks.json** at `/.well-known/assetlinks.json` (HTTPS JSON, **no redirects**). **Associated domains automatically handle app/universal links and JSON path routing**; keep link handling minimal beyond hosting these files and mapping returns to your https callback pages in the app.\n\n* **Runtime & store checks (optional):**\n  You may detect the Despia environment and optionally query store location to guide UI policy (e.g., when to expose a secondary web checkout alongside native IAP).\n\n---\n\n## 1) Lovable Docs Ritual (run for EVERY native feature)\n\n1. **Open** the Despia × Lovable sitemap.\n2. **Find** the page for the requested feature (e.g., contacts, biometrics, revenuecat, onesignal, safe-area, applejs, deeplinks).\n3. **Open & review** that page.\n4. **Locate** the **“Lovable Prompt”** (or canonical prompt/code block) and **copy the latest prompt**.\n5. **Paste & execute** that prompt here to generate code/config.\n6. At the **top** of your reply, list the **source URL(s)**. Add them to **`DESPIA_README.md → Documentation Sources`** (or output a PATCH block).\n7. If live retrieval fails, use any **Docs Cache** recorded in `DESPIA_README.md`, then retry live later.\n\n> Heuristic: Prefer pages whose title/path contains the feature keyword **and** include an explicit “Lovable Prompt.” If several match, pick the newest/clearest.\n\n---\n\n## 2) Authentication (production behavior)\n\n**Principle:** Keep the **backend unopinionated**. Lovable owns Google and may evolve it. The **only prescribed** backend concept is **Sign in with Apple** using **AppleJS inline** + **custom Edge Functions** on **Lovable Cloud**. Do **not** use prebuilt Apple-login paths from third-party auth packages.\n\n### 2.1 Google\n\n* **Lovable configures Google** end-to-end.\n* In Despia settings, ensure the Google OAuth domain opens externally where required, and that associated domains are valid so returns land in a first-party https context inside the app. No further backend specification here.\n\n### 2.2 Sign in with Apple — concept only\n\n* **Client:** Use **AppleJS inline** on **iOS, Android, and Web**. (AppleJS handles fallbacks.)\n* **Server:** Implement **custom Edge Functions** on **Lovable Cloud** dedicated to Apple sign-in. These functions verify the Apple credential and create/authenticate sessions.\n* **Do NOT** use prebuilts (e.g., Supabase/Lovable Apple provider paths).\n\n**Conceptual flow (no names, no routes, no transport specifics):**\n\n1. Client **initiates** AppleJS and receives an **Apple credential** (ID token; email may be present only on first consent).\n2. Client **hands off** that credential to **server-side logic** via a **trusted first-party channel** appropriate to your app.\n3. Server **verifies** the credential using Apple’s keys and validates claims.\n4. Server derives:\n\n   * a **stable subject identifier** (Apple’s unique user ID), and\n   * an **email** if Apple provided one this time.\n5. **Account-linking rules:**\n\n   * If a record with this **stable subject** exists → **authenticate** that user.\n   * Else if the **email** matches an existing account → **link** this subject to that account → **authenticate**.\n   * Else **create** a new account tied to the subject (store email if provided) → **authenticate**.\n6. **Durability rule:** Treat the **Apple stable subject** as the **primary key** for Apple identity. If a user later **changes/hides email**, authentication still succeeds because the subject is unchanged.\n7. Server **issues a session** (cookie or token — implementation is your choice).\n\n### 2.3 (Optional) Device & push association after login\n\n* After any successful auth, the client can **associate device identity and push identity** with the authenticated user using your usual mechanism. Keep it flexible; this prompt doesn’t prescribe route names or payload shapes.\n\n---\n\n## 3) RevenueCat — Production Setup & Flows\n\n### 3.1 Console checklist\n\n* Connect **App Store** & **Play Console**.\n* Create **products → entitlements → offerings**; record store product IDs.\n* **App User ID** should be your user identifier (passed to RC as the external id).\n* Configure a **Webhook** to your backend (protect with a secret).\n\n### 3.2 Frontend — start purchase, handle success, unlock via server (server is authority)\n\n#### 3.2.a Start native purchase (primary path)\n\n```ts\nimport despia from 'despia-native';\n\nexport async function startNativePurchase(productId: string, userId: string) {\n  // Optional: check store location to influence UI policy (e.g., show secondary web checkout in allowed regions)\n  try { await despia('getstorelocation://', ['storeLocation']); } catch {}\n\n  // Trigger native IAP via Despia → RevenueCat\n  await despia(\n    `revenuecat://purchase?external_id=${encodeURIComponent(userId)}&product=${encodeURIComponent(productId)}`\n  );\n}\n```\n\n#### 3.2.b `iapSuccess` hint & boot-time reality (server wins)\n\nDespia may call `window.iapSuccess(payload)` (also on app start). **Do not** unlock based solely on this hint—**wait for server-confirmed entitlement**.\n\n```ts\ntype IapSuccessPayload = {\n  planID: string;\n  transactionID: string;\n  subreceipts: unknown; // JSON string or object; parse defensively\n};\n\ndeclare global { interface Window { iapSuccess?: (p: IapSuccessPayload) => void } }\n\nlet _iapBound = false;\nexport function bindIapSuccessOnce(getEntitlements: () => Promise<{ active?: boolean } | null>) {\n  if (_iapBound) return; _iapBound = true;\n\n  window.iapSuccess = async ({ planID, transactionID, subreceipts }: IapSuccessPayload) => {\n    try {\n      const current = await getEntitlements();\n      if (current?.active) return;\n\n      const receipts = typeof subreceipts === 'string' ? safeParseJSON(subreceipts) : subreceipts;\n\n      // Optimistic UI can show a spinner; subscribe to your realtime channel for entitlement updates.\n      const confirmed = await waitForSubscriptionConfirm(getEntitlements, { timeoutMs: 15000, intervalMs: 1500 });\n\n      if (!confirmed) {\n        // Optionally expose a \"Refresh Purchases\" / \"Try Unlock\" button to re-check when webhooks land.\n      }\n    } catch (err) {\n      // Degrade gracefully; allow manual refresh of entitlements.\n      console.error('iapSuccess handler error', err);\n    }\n  };\n}\n\nfunction safeParseJSON(s: string) { try { return JSON.parse(s); } catch { return s; } }\n\nasync function waitForSubscriptionConfirm(\n  getEntitlements: () => Promise<{ active?: boolean } | null>,\n  opts:{timeoutMs:number; intervalMs:number}\n) {\n  const start = Date.now();\n  while (Date.now() - start < opts.timeoutMs) {\n    const ent = await getEntitlements();\n    if (ent?.active) return true;\n    await new Promise(r => setTimeout(r, opts.intervalMs));\n  }\n  return false;\n}\n```\n\n> The UI code above is backend-agnostic: pass in **any** `getEntitlements()` you like. No route names required.\n\n#### 3.2.c Server-driven offerings (don’t hardcode products)\n\n* The client **requests offerings from the server** and renders whatever is returned (ids, titles, price text, etc.).\n* The **shape** of that response is up to the backend. Keep the client generic: display products given, start purchases using the store ids, and decide whether to show a **secondary web checkout** based on a boolean flag or policy in that response.\n\n#### 3.2.d Optional: Web Billing (secondary, policy-dependent)\n\n* If your policy allows, expose a **secondary web checkout** in addition to native IAP. After payment, rely on **server events + realtime** to unlock (there is **no** `iapSuccess` for web).\n\n### 3.3 Backend contract — authoritative events (concept only)\n\n* Treat **server events/webhooks** (e.g., from RevenueCat) as the **source of truth** for entitlement.\n* Handle events **idempotently**, **synchronize** the subscriber state, then **notify** clients (e.g., realtime/pub-sub).\n* Storage models and event shapes are **intentionally unspecified** here.\n\n---\n\n## 4) Database & Realtime (conceptual only)\n\nModel **concepts**, not columns or names:\n\n* **Users** — canonical user record.\n* **User Identities** — mapping of external identities to users (e.g., Apple stable subject, with optional email snapshot).\n* **Devices (optional)** — association of device identity and push identity with the user.\n* **Subscriptions (optional)** — subscription status synced from authoritative server events.\n\n**Rules to encode for Apple login:**\n\n* If **identity by stable subject** exists → **authenticate**.\n* Else if **email matches** an existing account → **link** subject → **authenticate**.\n* Else **create** account + identity → **authenticate**.\n* On later logins where **email changed/hidden**, rely on the **stable subject** and **still authenticate**.\n\nRealtime is optional—use it to emit session/entitlement updates to clients.\n\n---\n\n## 5) Push (OneSignal) — quick hookup\n\n* Create OneSignal app; configure **APNs** + **Firebase**.\n* Add your **OneSignal App ID** in Despia project settings.\n* After login, the client may **associate push identity and device identity** with the authenticated user using your preferred mechanism.\n* Backend sends via OneSignal REST (implementation details are up to you).\n\n---\n\n## 6) Link Handling & Deep Links (non-negotiable)\n\n* Internal navigation uses the SPA router; **no full reloads**.\n* External links may open in a new browser context. In Despia settings, mark OAuth/payment domains as **Always Open in Browser** when appropriate.\n* Deep links should return to **https callbacks** on your primary domain that run **inside the app WebView** so cookies/sessions are first-party.\n\n### 6.1 iOS — Apple App Site Association (AASA)\n\n**Host at:** `/.well-known/apple-app-site-association` (no extension; HTTPS; no redirects)\n\n```json\n{\n  \"applinks\": {\n    \"details\": [\n      {\n        \"appIDs\": [\"TEAMID.BUNDLEID\"],\n        \"components\": [{ \"/\": \"/*\" }]\n      }\n    ]\n  }\n}\n```\n\nFill in **TEAMID** (Apple Developer) and **BUNDLEID** (Despia Publishing Panel).\n\n### 6.2 Android — Digital Asset Links (assetlinks.json)\n\n**Host at:** `/.well-known/assetlinks.json` (HTTPS; no redirects)\n\n```json\n[\n  {\n    \"relation\": [\"delegate_permission/common.handle_all_urls\"],\n    \"target\": {\n      \"namespace\": \"android_app\",\n      \"package_name\": \"PACKAGE_NAME\",\n      \"sha256_cert_fingerprints\": [\"SHA256_FINGERPRINT\"]\n    }\n  }\n]\n```\n\nFill in **PACKAGE_NAME** (Despia Publishing) and **SHA256_FINGERPRINT** (Play Console → App Integrity).\n\n---\n\n## 7) Mobile UI Guardrails\n\n* **Safe areas:** use platform-provided safe-area vars on fixed bars, drawers, toasts, spacers.\n* **Stable shell:** top & bottom bars stay mounted; only middle content transitions (**~120–160ms** fade/translate). Avoid full-screen global loaders.\n* **Touch model:** use a mobile-first component set; remove desktop hover patterns; prefer `active` + `focus-visible`; optional light haptics via Despia.\n\n---\n\n## 8) Project Anchoring & Recovery\n\n* Before any native work, open **`DESPIA_README.md`** (source of truth).\n* Always follow the **Docs Ritual** (§1).\n* If chat context resets: README banner → `DESPIA_README.md` → Ritual.\n\n---\n\n## 9) Minimal PATCH blocks Lovable can output (if it can’t write files)\n\n**README.md (banner)**\n\n```md\n> 🚦 **Native Setup Source of Truth**\n> Before any native feature work, open **`DESPIA_README.md`**, then open the **Despia sitemap**, pick the feature page, and use the **latest Lovable Prompt** from that page.\n```\n\n**DESPIA_README.md → Documentation Sources**\n\n```md\n## Documentation Sources (memory-proof)\n- Primary sitemap: <ADD-SITEMAP-URL>\n- Feature page(s) used most recently:\n  - <PASTE-URL-1>\n  - <PASTE-URL-2>\n```\n\n---\n\n## 10) Footer Macro (append on native-related replies)\n\n> 📘 *Native work anchored:* Opened sitemap → selected feature page → applied **latest Lovable Prompt** → logged source URLs to **`DESPIA_README.md`**. If context was cut off, reopen README banner → `DESPIA_README.md` → repeat the ritual.\n\n---\n\n### Quick Reference (frontend only; backend-agnostic)\n\n**Despia variables (examples)**\n\n```ts\n// Available from despia-native; read directly where needed\n// e.g., device UUID, push player id, app version, etc.\n```\n\n**IAP hooks in UI (backend-agnostic)**\n\n```ts\n// Bootstrap (e.g., App.tsx)\nuseEffect(() => {\n  // Provide your own getEntitlements() that consults your server however you like\n  bindIapSuccessOnce(() => getEntitlements());\n}, []);\n\n// Start a purchase (ids come from your server-driven offerings)\nawait startNativePurchase('pro_monthly', currentUser.id);\n```\n\n**Apple login recap**\n\n* **AppleJS inline** on **iOS/Android/Web**\n* **Custom Edge Functions** on **Lovable Cloud** verify Apple credential, apply **subject/email link rules**, and issue a session\n* **Stable subject** is the durable key; email changes do **not** block login\n* **No** prebuilt Apple provider paths"}}],"display_name":"String"}}],"display_name":"Encode URI Component"}}],"display_name":"Concatenate","variableArguments":true}}],"display_name":"Concatenate","variableArguments":true}}]}],"trigger":"Load"},"nodes":{}},"components":[]}