@cedros/pay-react 1.1.29 → 1.1.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -22
- package/dist/{AISettingsSection-B7qrycfY.js → AISettingsSection-B12x5sV5.js} +2 -2
- package/dist/{AISettingsSection-DtAgMsDw.mjs → AISettingsSection-DXWDF4Cf.mjs} +4 -4
- package/dist/AutosaveIndicator-CJdkhZis.js +1 -0
- package/dist/{AutosaveIndicator-BEvABoKU.mjs → AutosaveIndicator-D966vOrP.mjs} +1 -1
- package/dist/CedrosContext-3Dz7_9Ct.js +3 -0
- package/dist/{CedrosContext-5Gjveoba.mjs → CedrosContext-DQc_k5PG.mjs} +430 -314
- package/dist/ChatLogsSection-CH37u0nX.js +1 -0
- package/dist/{ChatLogsSection-Ber5o8hF.mjs → ChatLogsSection-DR7mpuQS.mjs} +2 -2
- package/dist/{ComplianceSection-ZCr0wsvw.mjs → ComplianceSection-C61_Hf-X.mjs} +3 -3
- package/dist/ComplianceSection-DS4e2IBp.js +1 -0
- package/dist/CryptoButton-BQceZhbn.js +1 -0
- package/dist/{CryptoButton-Cl2kZbOP.mjs → CryptoButton-BuO_RZLj.mjs} +4 -5
- package/dist/CustomersSection-Bzs9Qon3.js +1 -0
- package/dist/{CustomersSection-D9UknSKC.mjs → CustomersSection-CWWvusxs.mjs} +2 -2
- package/dist/DisputesSection-ClcYIHga.js +1 -0
- package/dist/{DisputesSection-C_eySK-W.mjs → DisputesSection-D8rcS5Vs.mjs} +2 -2
- package/dist/{Dropdown-B90Zabxr.mjs → Dropdown-0y3S40Xf.mjs} +1 -1
- package/dist/Dropdown-BuKiVR_L.js +1 -0
- package/dist/{ErrorBanner-CZXsHi3H.mjs → ErrorBanner-DAjYj6Dx.mjs} +1 -1
- package/dist/ErrorBanner-DxrRVqwe.js +1 -0
- package/dist/FAQSection-0UnN2BZs.js +1 -0
- package/dist/{FAQSection-Bv_Hdt8B.mjs → FAQSection-Dck0NM-A.mjs} +3 -3
- package/dist/{ImagesSection-DpdXQ6qu.mjs → ImagesSection-Bn9GrRRa.mjs} +2 -2
- package/dist/ImagesSection-CSwBHvNl.js +1 -0
- package/dist/{InventorySection-DZMu9DMw.mjs → InventorySection-Dytfmtn8.mjs} +2 -2
- package/dist/InventorySection-ymxaMcIg.js +1 -0
- package/dist/{MessagingSection-D_cOBfFt.mjs → MessagingSection-CHFbSxJL.mjs} +3 -3
- package/dist/MessagingSection-Dtfv0DvU.js +1 -0
- package/dist/OrdersSection-BuzTs9XG.js +1 -0
- package/dist/{OrdersSection-wfPavit9.mjs → OrdersSection-vYNuVF5X.mjs} +2 -2
- package/dist/{PaymentSettingsSection-BdBDgaRg.js → PaymentSettingsSection-BOaW8lLv.js} +1 -1
- package/dist/{PaymentSettingsSection-DunzBo9n.mjs → PaymentSettingsSection-BqdGrXen.mjs} +3 -3
- package/dist/{ReturnsSection-B4FL7bUv.mjs → ReturnsSection-CRzhXKtI.mjs} +2 -2
- package/dist/ReturnsSection-i5W_3so1.js +1 -0
- package/dist/{SettingsSection-DoeNDbqd.mjs → SettingsSection-6o3d8DrH.mjs} +1 -1
- package/dist/{SettingsSection-Cz2Yjdhr.js → SettingsSection-CIhO51Zj.js} +1 -1
- package/dist/ShippingSection-BUzPW1AG.js +1 -0
- package/dist/{ShippingSection-BlVsYC6B.mjs → ShippingSection-CbNzGyCP.mjs} +2 -2
- package/dist/SingleCategorySettings-BxVUUy8R.js +3 -0
- package/dist/{SingleCategorySettings-B406nnF-.mjs → SingleCategorySettings-Qj_ptB_x.mjs} +4 -4
- package/dist/{StatsBar-D4v-I_Dj.mjs → StatsBar-CwCBHBn-.mjs} +1 -1
- package/dist/StatsBar-DDUWoizP.js +1 -0
- package/dist/StorefrontSection-CZZj5he9.js +1 -0
- package/dist/{StorefrontSection-BK_rhrAi.mjs → StorefrontSection-DIYDmj59.mjs} +4 -4
- package/dist/SubscriptionsSection-Bof5MElz.js +1 -0
- package/dist/{SubscriptionsSection-D8V9RBv-.mjs → SubscriptionsSection-lMVHdV5X.mjs} +3 -3
- package/dist/TaxSection-Be-9v60Z.js +1 -0
- package/dist/{TaxSection-Cj6TXL6x.mjs → TaxSection-dD7PzQvG.mjs} +2 -2
- package/dist/Token22Section-Di5fHsrU.js +1 -0
- package/dist/{Token22Section-DtYAcT54.mjs → Token22Section-Dos0CYEk.mjs} +2 -2
- package/dist/{WalletManager-D-eoqUDy.mjs → WalletManager-CGR69MiR.mjs} +1 -1
- package/dist/{WalletManager-DXChB9LA.js → WalletManager-ZJbGQHrn.js} +1 -1
- package/dist/{WebhooksSection-DBAIxtBy.mjs → WebhooksSection-5gqXzIhq.mjs} +2 -2
- package/dist/WebhooksSection-CiLDyl7c.js +1 -0
- package/dist/admin.js +1 -1
- package/dist/admin.mjs +4 -5
- package/dist/crypto-only.js +1 -1
- package/dist/crypto-only.mjs +102 -104
- package/dist/{index-9QF_UfSN.mjs → index-CU6M10Rs.mjs} +13 -14
- package/dist/{index-Cq9ya93W.js → index-DVxx_62C.js} +10 -10
- package/dist/index.js +1 -1
- package/dist/index.mjs +21 -23
- package/dist/pay-react.css +1 -1
- package/dist/plugin-BIkt3boU.mjs +339 -0
- package/dist/plugin-Dw8_Q8rE.js +1 -0
- package/dist/sections-D1d83mfH.js +1 -0
- package/dist/{sections-more-CMFgfU4d.mjs → sections-DcUfZQNE.mjs} +263 -270
- package/dist/src/admin/plugin.d.ts.map +1 -1
- package/dist/src/admin/sectionIds.d.ts.map +1 -1
- package/dist/src/admin.d.ts +0 -7
- package/dist/src/admin.d.ts.map +1 -1
- package/dist/src/components/admin/index.d.ts +0 -1
- package/dist/src/components/admin/index.d.ts.map +1 -1
- package/dist/src/index.d.ts +0 -1
- package/dist/src/index.d.ts.map +1 -1
- package/dist/stripe-only.js +1 -1
- package/dist/stripe-only.mjs +18 -19
- package/dist/styles-BwaDljnz.js +1 -0
- package/dist/{styles-DGagylUj.mjs → styles-fihm6qVA.mjs} +51 -52
- package/dist/testing/index.js +1 -1
- package/dist/testing/index.mjs +1 -1
- package/package.json +6 -2
- package/dist/AutosaveIndicator-DiyeAg93.js +0 -1
- package/dist/CedrosContext-CCakH2SZ.js +0 -3
- package/dist/CedrosPayAdminDashboard-CAwEvn66.js +0 -1
- package/dist/CedrosPayAdminDashboard-CBuvNAtB.mjs +0 -250
- package/dist/ChatLogsSection-DLxMMi9I.js +0 -1
- package/dist/ComplianceSection-Buu0zTiL.js +0 -1
- package/dist/CryptoButton-DxFCYDlJ.js +0 -1
- package/dist/CustomersSection-BywmMLur.js +0 -1
- package/dist/DisputesSection-DwkHGv2a.js +0 -1
- package/dist/Dropdown-CtY91emj.js +0 -1
- package/dist/ErrorBanner-Cx2dUhps.js +0 -1
- package/dist/FAQSection-DlPLnIJD.js +0 -1
- package/dist/ImagesSection-B4Jzet79.js +0 -1
- package/dist/InventorySection-BgRdpn1l.js +0 -1
- package/dist/MessagingSection-CxV-pf-f.js +0 -1
- package/dist/OrdersSection-BbAX79Ff.js +0 -1
- package/dist/ReturnsSection-7k4LZ8yp.js +0 -1
- package/dist/ShippingSection-C-HI8rOb.js +0 -1
- package/dist/SingleCategorySettings-BqC2UXt3.js +0 -3
- package/dist/StatsBar-m6GSRNxs.js +0 -1
- package/dist/StorefrontSection-Axvh_KeS.js +0 -1
- package/dist/SubscriptionsSection-EeULMWIB.js +0 -1
- package/dist/TaxSection-CzHPhaHl.js +0 -1
- package/dist/ThemeContext-CFXyYx7A.js +0 -1
- package/dist/ThemeContext-l0bqcOGW.mjs +0 -126
- package/dist/Token22Section-DqRKVG_G.js +0 -1
- package/dist/WebhooksSection-D--iPZuM.js +0 -1
- package/dist/sectionIds-B_tFiNvF.js +0 -1
- package/dist/sectionIds-DBavltrL.mjs +0 -359
- package/dist/sections-BHph7CYj.mjs +0 -9
- package/dist/sections-C2zEJr5G.js +0 -1
- package/dist/sections-more-C1VNVwkp.js +0 -1
- package/dist/src/components/admin/CedrosPayAdminDashboard.d.ts +0 -40
- package/dist/src/components/admin/CedrosPayAdminDashboard.d.ts.map +0 -1
- package/dist/src/components/admin/LazyCedrosPayAdminDashboard.d.ts +0 -4
- package/dist/src/components/admin/LazyCedrosPayAdminDashboard.d.ts.map +0 -1
- package/dist/styles--fxb3lCl.js +0 -1
package/README.md
CHANGED
|
@@ -1502,44 +1502,57 @@ For complete control over styling, use the `unstyled` prop to disable all defaul
|
|
|
1502
1502
|
|
|
1503
1503
|
---
|
|
1504
1504
|
|
|
1505
|
-
## Admin
|
|
1505
|
+
## Admin Integration
|
|
1506
1506
|
|
|
1507
|
-
Cedros Pay
|
|
1507
|
+
Cedros Pay admin UI is delivered through the shared `AdminShell` contract. Use
|
|
1508
|
+
`@cedros/admin-react` for the shell, `@cedros/login-react` for admin auth, and
|
|
1509
|
+
`@cedros/pay-react/admin` for the payment plugin.
|
|
1508
1510
|
|
|
1509
|
-
|
|
1511
|
+
`@cedros/pay-react` no longer ships a standalone admin dashboard component.
|
|
1512
|
+
Admin usage always goes through the shared Cedros admin shell.
|
|
1510
1513
|
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
```tsx
|
|
1514
|
-
import { CedrosPayAdminDashboard } from "@cedros/pay-react";
|
|
1515
|
-
|
|
1516
|
-
function AdminPage() {
|
|
1517
|
-
return (
|
|
1518
|
-
<CedrosPayAdminDashboard
|
|
1519
|
-
serverUrl="https://api.example.com"
|
|
1520
|
-
title="My Store"
|
|
1521
|
-
defaultSection="transactions"
|
|
1522
|
-
/>
|
|
1523
|
-
);
|
|
1524
|
-
}
|
|
1525
|
-
```
|
|
1526
|
-
|
|
1527
|
-
**Available Sections:**
|
|
1514
|
+
**Available Cedros Pay Sections:**
|
|
1528
1515
|
|
|
1529
1516
|
| Section | Description |
|
|
1530
1517
|
|---------|-------------|
|
|
1531
1518
|
| `transactions` | Payment history with filtering by method |
|
|
1519
|
+
| `orders` | Order records, fulfillment history, and gift card redemption status |
|
|
1532
1520
|
| `products` | Manage products, pricing, and variations |
|
|
1533
1521
|
| `subscriptions` | Configure subscription plans |
|
|
1534
1522
|
| `coupons` | Create and manage discount codes |
|
|
1535
1523
|
| `refunds` | Process refund requests |
|
|
1524
|
+
| `compliance` | Review compliance checks and enforcement status |
|
|
1525
|
+
| `chat-logs` | Inspect AI chat sessions and message history |
|
|
1526
|
+
| `customers` | Search, create, and update customer records |
|
|
1527
|
+
| `disputes` | Review and update disputes / chargebacks |
|
|
1528
|
+
| `returns` | Manage return requests and statuses |
|
|
1529
|
+
| `images` | Upload and review storefront images |
|
|
1530
|
+
| `inventory` | View inventory adjustment history |
|
|
1536
1531
|
| `storefront` | Customize shop layout and appearance |
|
|
1537
1532
|
| `ai-settings` | Configure AI-powered features |
|
|
1538
1533
|
| `payment-settings` | Payment method configuration |
|
|
1534
|
+
| `token22` | Manage gift cards, Token-22 settings, and liquidity |
|
|
1539
1535
|
| `messaging` | Email and notification templates |
|
|
1536
|
+
| `webhooks` | Monitor webhook delivery and DLQ events |
|
|
1537
|
+
| `shipping` | Manage shipping profiles and rates |
|
|
1538
|
+
| `tax` | Configure tax rates |
|
|
1540
1539
|
| `settings` | Server and integration settings |
|
|
1541
1540
|
|
|
1542
|
-
###
|
|
1541
|
+
### Required Packages
|
|
1542
|
+
|
|
1543
|
+
Install all three packages for admin usage:
|
|
1544
|
+
|
|
1545
|
+
```bash
|
|
1546
|
+
npm install @cedros/admin-react @cedros/login-react @cedros/pay-react
|
|
1547
|
+
```
|
|
1548
|
+
|
|
1549
|
+
Load the shared shell styles once in your admin host:
|
|
1550
|
+
|
|
1551
|
+
```tsx
|
|
1552
|
+
import '@cedros/admin-react/styles.css';
|
|
1553
|
+
```
|
|
1554
|
+
|
|
1555
|
+
### AdminShell Integration
|
|
1543
1556
|
|
|
1544
1557
|
For apps using both **cedros-login** and **cedros-pay**, use `AdminShell` from `@cedros/admin-react` with both plugins to create a combined admin interface:
|
|
1545
1558
|
|
|
@@ -1579,7 +1592,13 @@ function UnifiedAdmin() {
|
|
|
1579
1592
|
}
|
|
1580
1593
|
```
|
|
1581
1594
|
|
|
1582
|
-
> **Note:**
|
|
1595
|
+
> **Note:** `cedros-pay` no longer ships a standalone admin dashboard. Use
|
|
1596
|
+
> `@cedros/admin-react` with `cedrosPayPlugin` under a single `/admin`
|
|
1597
|
+
> dashboard.
|
|
1598
|
+
|
|
1599
|
+
> **Auth contract:** In the shared shell, Cedros Login is the admin auth
|
|
1600
|
+
> provider. `cedros-pay` consumes the host service bag exposed by
|
|
1601
|
+
> `cedros-login` rather than standing up its own dashboard/auth runtime.
|
|
1583
1602
|
|
|
1584
1603
|
### cedrosPayPlugin Sections
|
|
1585
1604
|
|
|
@@ -1588,14 +1607,26 @@ The plugin registers these sections for the unified dashboard:
|
|
|
1588
1607
|
| Section ID | Group | Description |
|
|
1589
1608
|
|------------|-------|-------------|
|
|
1590
1609
|
| `transactions` | Store | Payment transactions |
|
|
1610
|
+
| `orders` | Store | Orders and fulfillment details |
|
|
1591
1611
|
| `products` | Store | Product management |
|
|
1592
1612
|
| `subscriptions` | Store | Subscription plans |
|
|
1593
1613
|
| `coupons` | Store | Coupon management |
|
|
1594
1614
|
| `refunds` | Store | Refund requests |
|
|
1615
|
+
| `compliance` | Store | Compliance checks and review tools |
|
|
1616
|
+
| `chat-logs` | Store | AI chat session logs |
|
|
1617
|
+
| `customers` | Store | Customer records |
|
|
1618
|
+
| `disputes` | Store | Disputes and chargebacks |
|
|
1619
|
+
| `returns` | Store | Return request workflows |
|
|
1620
|
+
| `images` | Store | Storefront image assets |
|
|
1621
|
+
| `inventory` | Store | Inventory adjustment history |
|
|
1595
1622
|
| `storefront` | Configuration | Storefront settings |
|
|
1596
1623
|
| `ai-settings` | Configuration | AI assistant settings |
|
|
1597
1624
|
| `payment-settings` | Configuration | Payment method toggles |
|
|
1625
|
+
| `token22` | Configuration | Gift cards and Token-22 controls |
|
|
1598
1626
|
| `messaging` | Configuration | Email/webhook settings |
|
|
1627
|
+
| `webhooks` | Configuration | Webhook delivery management |
|
|
1628
|
+
| `shipping` | Configuration | Shipping profiles and rates |
|
|
1629
|
+
| `tax` | Configuration | Tax rates |
|
|
1599
1630
|
| `settings` | Configuration | Server configuration |
|
|
1600
1631
|
|
|
1601
1632
|
### Section Addressing
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),a=require("react"),v=require("./
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),a=require("react"),v=require("./plugin-Dw8_Q8rE.js"),G=require("./ErrorBanner-DxrRVqwe.js"),z=require("./Dropdown-BuKiVR_L.js"),B=require("./AutosaveIndicator-CJdkhZis.js"),w=[{id:"not_set",label:"Disabled",provider:null},{id:"gemini-2.5-flash",label:"Gemini 2.5 Flash",provider:"gemini"},{id:"gemini-2.5-pro",label:"Gemini 2.5 Pro",provider:"gemini"},{id:"openai-4o",label:"OpenAI 4o",provider:"openai"},{id:"openai-5.1",label:"OpenAI 5.1",provider:"openai"},{id:"openai-5.2",label:"OpenAI 5.2",provider:"openai"}],P=[{task:"site_chat",label:"Site Chat",description:"The conversational model that crafts responses to customer messages",defaultPrompt:`You are a friendly and helpful shopping assistant for our store. Your role is to:
|
|
2
2
|
|
|
3
3
|
- Help customers find products that match their needs
|
|
4
4
|
- Answer questions about products, shipping, returns, and store policies
|
|
@@ -48,4 +48,4 @@ Guidelines:
|
|
|
48
48
|
- Use sensory language when appropriate
|
|
49
49
|
- Keep descriptions scannable with short paragraphs
|
|
50
50
|
- Avoid superlatives and unverifiable claims
|
|
51
|
-
- Include relevant keywords naturally for SEO`}],W=[{id:"gemini",label:"Google Gemini API",placeholder:"AIza..."},{id:"openai",label:"OpenAI API",placeholder:"sk-..."}],N={apiKeys:[{provider:"gemini",isConfigured:!1},{provider:"openai",isConfigured:!1}],taskAssignments:P.map(o=>({task:o.task,label:o.label,description:o.description,assignedModel:"not_set",systemPrompt:o.defaultPrompt}))};function L({serverUrl:o,apiKey:c,authManager:d}){const[h,b]=a.useState("api-keys"),[f,y]=a.useState(N),[j,g]=a.useState(!0),[u,l]=a.useState(!1),[x,p]=a.useState(null),[C,_]=a.useState(!1),[E,$]=a.useState(null),m=a.useRef(null),[A,T]=a.useState({gemini:"",openai:""}),[S,R]=a.useState({gemini:!1,openai:!1}),I=a.useCallback(async()=>{try{let e;if(d?.isAuthenticated())e=await d.fetchWithAuth("/admin/config/ai");else{const i={"Content-Type":"application/json"};c&&(i["X-API-Key"]=c);const s=await fetch(`${o}/admin/config/ai`,{headers:i});if(!s.ok)throw new Error(`Failed to fetch: ${s.status}`);e=await s.json()}e.settings&&y(e.settings)}catch{y(N),$("Could not load saved AI settings. Showing defaults.")}finally{g(!1)}},[o,c,d]);a.useEffect(()=>{I()},[I]);const D=a.useCallback(async e=>{const i=A[e];if(i.trim()){l(!0),p(null);try{const s={provider:e,apiKey:i};if(d?.isAuthenticated())await d.fetchWithAuth("/admin/config/ai/api-key",{method:"PUT",body:JSON.stringify(s)});else{const n={"Content-Type":"application/json"};c&&(n["X-API-Key"]=c);const r=await fetch(`${o}/admin/config/ai/api-key`,{method:"PUT",headers:n,body:JSON.stringify(s)});if(!r.ok)throw new Error(`Failed to save: ${r.status}`)}y(n=>({...n,apiKeys:n.apiKeys.map(r=>r.provider===e?{...r,isConfigured:!0,maskedKey:`${i.slice(0,4)}...${i.slice(-4)}`,updatedAt:new Date().toISOString()}:r)})),T(n=>({...n,[e]:""})),_(!0),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>_(!1),3e3)}catch(s){p(s instanceof Error?s.message:"Failed to save API key")}finally{l(!1)}}},[A,o,c,d]),F=a.useCallback(async e=>{if(confirm(`Are you sure you want to delete the ${e==="gemini"?"Google Gemini":"OpenAI"} API key?`)){l(!0),p(null);try{if(d?.isAuthenticated())await d.fetchWithAuth(`/admin/config/ai/api-key/${e}`,{method:"DELETE"});else{const i={"Content-Type":"application/json"};c&&(i["X-API-Key"]=c);const s=await fetch(`${o}/admin/config/ai/api-key/${e}`,{method:"DELETE",headers:i});if(!s.ok)throw new Error(`Failed to delete: ${s.status}`)}y(i=>({...i,apiKeys:i.apiKeys.map(s=>s.provider===e?{provider:e,isConfigured:!1}:s)}))}catch(i){p(i instanceof Error?i.message:"Failed to delete API key")}finally{l(!1)}}},[o,c,d]),O=a.useCallback(async(e,i)=>{l(!0),p(null);try{const s={task:e,model:i};if(d?.isAuthenticated())await d.fetchWithAuth("/admin/config/ai/assignment",{method:"PUT",body:JSON.stringify(s)});else{const n={"Content-Type":"application/json"};c&&(n["X-API-Key"]=c);const r=await fetch(`${o}/admin/config/ai/assignment`,{method:"PUT",headers:n,body:JSON.stringify(s)});if(!r.ok)throw new Error(`Failed to save: ${r.status}`)}y(n=>({...n,taskAssignments:n.taskAssignments.map(r=>r.task===e?{...r,assignedModel:i}:r)})),_(!0),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>_(!1),3e3)}catch(s){p(s instanceof Error?s.message:"Failed to save assignment")}finally{l(!1)}},[o,c,d]),k=a.useCallback(e=>{if(e==="not_set")return!0;const i=w.find(n=>n.id===e);return i?.provider?f.apiKeys.find(n=>n.provider===i.provider)?.isConfigured??!1:!0},[f.apiKeys]),K=a.useMemo(()=>w.map(e=>{const i=k(e.id);return{value:e.id,label:i?e.label:`${e.label} (API key required)`,disabled:!i}}),[k]),q=a.useCallback(async(e,i)=>{l(!0),p(null);try{const s={task:e,systemPrompt:i};if(d?.isAuthenticated())await d.fetchWithAuth("/admin/config/ai/prompt",{method:"PUT",body:JSON.stringify(s)});else{const n={"Content-Type":"application/json"};c&&(n["X-API-Key"]=c);const r=await fetch(`${o}/admin/config/ai/prompt`,{method:"PUT",headers:n,body:JSON.stringify(s)});if(!r.ok)throw new Error(`Failed to save: ${r.status}`)}y(n=>({...n,taskAssignments:n.taskAssignments.map(r=>r.task===e?{...r,systemPrompt:i}:r)})),_(!0),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>_(!1),3e3)}catch(s){p(s instanceof Error?s.message:"Failed to save prompt")}finally{l(!1)}},[o,c,d]);return a.useEffect(()=>()=>{m.current&&clearTimeout(m.current)},[]),j?t.jsx("div",{className:"cedros-admin__section",children:t.jsxs("div",{className:"cedros-admin__loading",children:[v.Icons.loading," Loading AI settings..."]})}):t.jsxs("div",{className:"cedros-admin__ai-settings",children:[t.jsxs("div",{className:"cedros-admin__page-header",children:[t.jsx("h2",{className:"cedros-admin__page-title",children:"Store AI"}),t.jsx("p",{className:"cedros-admin__page-description",children:"Configure AI providers, model assignments, and system prompts."})]}),t.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[t.jsx("button",{type:"button",className:`cedros-admin__tab ${h==="api-keys"?"cedros-admin__tab--active":""}`,onClick:()=>b("api-keys"),children:"API Keys"}),t.jsx("button",{type:"button",className:`cedros-admin__tab ${h==="assignments"?"cedros-admin__tab--active":""}`,onClick:()=>b("assignments"),children:"Model Assignments"}),t.jsx("button",{type:"button",className:`cedros-admin__tab ${h==="prompts"?"cedros-admin__tab--active":""}`,onClick:()=>b("prompts"),children:"Prompts"})]}),x&&t.jsx("div",{className:"cedros-admin__error-banner",style:{marginTop:"1rem"},children:x}),t.jsx(G.ErrorBanner,{message:E,onRetry:I}),C&&t.jsxs("div",{className:"cedros-admin__success-banner",style:{marginTop:"1rem"},children:[v.Icons.check," Settings saved successfully"]}),h==="api-keys"&&t.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[t.jsx("div",{className:"cedros-admin__section-header",children:t.jsx("h3",{className:"cedros-admin__section-title",children:"API Keys"})}),t.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Configure API keys for AI providers. Keys are stored securely and never exposed."}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1.5rem"},children:W.map(e=>{const i=f.apiKeys.find(n=>n.provider===e.id),s=i?.isConfigured??!1;return t.jsxs("div",{className:"cedros-admin__api-key-card",style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontWeight:600},children:e.label}),s&&i?.maskedKey&&t.jsxs("div",{style:{fontSize:12,opacity:.6,marginTop:2},children:["Current key: ",i.maskedKey,i.updatedAt&&t.jsxs("span",{children:[" (updated ",new Date(i.updatedAt).toLocaleDateString(),")"]})]})]}),t.jsx("span",{className:`cedros-admin__badge ${s?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:s?"Configured":"Not Set"})]}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:t.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[t.jsx("input",{type:S[e.id]?"text":"password",className:"cedros-admin__input",placeholder:s?"Enter new key to replace":e.placeholder,value:A[e.id],onChange:n=>T(r=>({...r,[e.id]:n.target.value})),onBlur:()=>{A[e.id].trim()&&D(e.id)},style:{flex:1}}),t.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>R(n=>({...n,[e.id]:!n[e.id]})),title:S[e.id]?"Hide key":"Show key",style:{padding:"0.5rem"},children:S[e.id]?v.Icons.eyeOff:v.Icons.eye}),s&&t.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--danger",onClick:()=>F(e.id),disabled:u,title:"Remove API key",style:{padding:"0.5rem"},children:v.Icons.trash})]})})]},e.id)})})]}),h==="assignments"&&t.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[t.jsx("div",{className:"cedros-admin__section-header",children:t.jsx("h3",{className:"cedros-admin__section-title",children:"Model Assignments"})}),t.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Assign AI models to specific tasks. Models require their provider's API key to be configured."}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:f.taskAssignments.map(e=>{const i=P.find(n=>n.task===e.task),s=w.find(n=>n.id===e.assignedModel);return t.jsxs("div",{style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[t.jsxs("div",{style:{marginBottom:"0.75rem"},children:[t.jsx("div",{style:{fontWeight:600},children:i?.label??e.task}),t.jsx("div",{style:{fontSize:13,opacity:.7,marginTop:2},children:i?.description})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[t.jsx(z.FormDropdown,{value:e.assignedModel,onChange:n=>O(e.task,n),options:K,label:"",disabled:u,style:{flex:1,maxWidth:280}}),s&&s.provider&&t.jsx("span",{className:`cedros-admin__badge ${k(s.id)?"cedros-admin__badge--success":"cedros-admin__badge--warning"}`,children:k(s.id)?"Ready":"Missing API Key"})]})]},e.task)})})]}),h==="prompts"&&t.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[t.jsx("div",{className:"cedros-admin__section-header",children:t.jsx("h3",{className:"cedros-admin__section-title",children:"System Prompts"})}),t.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Configure the default system prompts for each AI task. These prompts guide the AI's behavior and responses."}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1.5rem"},children:f.taskAssignments.map(e=>{const i=P.find(s=>s.task===e.task);return t.jsx(J,{task:e.task,label:i?.label??e.task,description:i?.description??"",initialPrompt:e.systemPrompt??"",onSave:q},e.task)})})]})]})}function J({task:o,label:c,description:d,initialPrompt:h,onSave:b}){const[f,y]=a.useState(h),[j,g]=a.useState("idle"),u=a.useRef(null),l=a.useRef(null),x=a.useRef(!0);return a.useEffect(()=>{if(x.current){x.current=!1;return}return u.current&&clearTimeout(u.current),l.current&&clearTimeout(l.current),g("pending"),u.current=setTimeout(async()=>{g("saving");try{await b(o,f),g("saved"),l.current=setTimeout(()=>g("idle"),2e3)}catch{g("error")}},1500),()=>{u.current&&clearTimeout(u.current)}},[f,o,b]),a.useEffect(()=>()=>{u.current&&clearTimeout(u.current),l.current&&clearTimeout(l.current)},[]),t.jsxs("div",{style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[t.jsxs("div",{style:{marginBottom:"0.75rem",display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontWeight:600},children:c}),t.jsx("div",{style:{fontSize:13,opacity:.7,marginTop:2},children:d})]}),t.jsx(B.AutosaveIndicator,{status:j})]}),t.jsx("textarea",{className:"cedros-admin__input",value:f,onChange:p=>y(p.target.value),placeholder:"Enter system prompt...",rows:4,style:{width:"100%",resize:"vertical",fontFamily:"inherit",minHeight:100}})]})}exports.AISettingsSection=L;
|
|
51
|
+
- Include relevant keywords naturally for SEO`}],W=[{id:"gemini",label:"Google Gemini API",placeholder:"AIza..."},{id:"openai",label:"OpenAI API",placeholder:"sk-..."}],N={apiKeys:[{provider:"gemini",isConfigured:!1},{provider:"openai",isConfigured:!1}],taskAssignments:P.map(o=>({task:o.task,label:o.label,description:o.description,assignedModel:"not_set",systemPrompt:o.defaultPrompt}))};function L({serverUrl:o,apiKey:c,authManager:d}){const[h,b]=a.useState("api-keys"),[f,g]=a.useState(N),[j,y]=a.useState(!0),[u,l]=a.useState(!1),[x,p]=a.useState(null),[C,_]=a.useState(!1),[E,$]=a.useState(null),m=a.useRef(null),[A,T]=a.useState({gemini:"",openai:""}),[S,R]=a.useState({gemini:!1,openai:!1}),I=a.useCallback(async()=>{try{let e;if(d?.isAuthenticated())e=await d.fetchWithAuth("/admin/config/ai");else{const i={"Content-Type":"application/json"};c&&(i["X-API-Key"]=c);const s=await fetch(`${o}/admin/config/ai`,{headers:i});if(!s.ok)throw new Error(`Failed to fetch: ${s.status}`);e=await s.json()}e.settings&&g(e.settings)}catch{g(N),$("Could not load saved AI settings. Showing defaults.")}finally{y(!1)}},[o,c,d]);a.useEffect(()=>{I()},[I]);const D=a.useCallback(async e=>{const i=A[e];if(i.trim()){l(!0),p(null);try{const s={provider:e,apiKey:i};if(d?.isAuthenticated())await d.fetchWithAuth("/admin/config/ai/api-key",{method:"PUT",body:JSON.stringify(s)});else{const n={"Content-Type":"application/json"};c&&(n["X-API-Key"]=c);const r=await fetch(`${o}/admin/config/ai/api-key`,{method:"PUT",headers:n,body:JSON.stringify(s)});if(!r.ok)throw new Error(`Failed to save: ${r.status}`)}g(n=>({...n,apiKeys:n.apiKeys.map(r=>r.provider===e?{...r,isConfigured:!0,maskedKey:`${i.slice(0,4)}...${i.slice(-4)}`,updatedAt:new Date().toISOString()}:r)})),T(n=>({...n,[e]:""})),_(!0),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>_(!1),3e3)}catch(s){p(s instanceof Error?s.message:"Failed to save API key")}finally{l(!1)}}},[A,o,c,d]),F=a.useCallback(async e=>{if(confirm(`Are you sure you want to delete the ${e==="gemini"?"Google Gemini":"OpenAI"} API key?`)){l(!0),p(null);try{if(d?.isAuthenticated())await d.fetchWithAuth(`/admin/config/ai/api-key/${e}`,{method:"DELETE"});else{const i={"Content-Type":"application/json"};c&&(i["X-API-Key"]=c);const s=await fetch(`${o}/admin/config/ai/api-key/${e}`,{method:"DELETE",headers:i});if(!s.ok)throw new Error(`Failed to delete: ${s.status}`)}g(i=>({...i,apiKeys:i.apiKeys.map(s=>s.provider===e?{provider:e,isConfigured:!1}:s)}))}catch(i){p(i instanceof Error?i.message:"Failed to delete API key")}finally{l(!1)}}},[o,c,d]),O=a.useCallback(async(e,i)=>{l(!0),p(null);try{const s={task:e,model:i};if(d?.isAuthenticated())await d.fetchWithAuth("/admin/config/ai/assignment",{method:"PUT",body:JSON.stringify(s)});else{const n={"Content-Type":"application/json"};c&&(n["X-API-Key"]=c);const r=await fetch(`${o}/admin/config/ai/assignment`,{method:"PUT",headers:n,body:JSON.stringify(s)});if(!r.ok)throw new Error(`Failed to save: ${r.status}`)}g(n=>({...n,taskAssignments:n.taskAssignments.map(r=>r.task===e?{...r,assignedModel:i}:r)})),_(!0),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>_(!1),3e3)}catch(s){p(s instanceof Error?s.message:"Failed to save assignment")}finally{l(!1)}},[o,c,d]),k=a.useCallback(e=>{if(e==="not_set")return!0;const i=w.find(n=>n.id===e);return i?.provider?f.apiKeys.find(n=>n.provider===i.provider)?.isConfigured??!1:!0},[f.apiKeys]),K=a.useMemo(()=>w.map(e=>{const i=k(e.id);return{value:e.id,label:i?e.label:`${e.label} (API key required)`,disabled:!i}}),[k]),q=a.useCallback(async(e,i)=>{l(!0),p(null);try{const s={task:e,systemPrompt:i};if(d?.isAuthenticated())await d.fetchWithAuth("/admin/config/ai/prompt",{method:"PUT",body:JSON.stringify(s)});else{const n={"Content-Type":"application/json"};c&&(n["X-API-Key"]=c);const r=await fetch(`${o}/admin/config/ai/prompt`,{method:"PUT",headers:n,body:JSON.stringify(s)});if(!r.ok)throw new Error(`Failed to save: ${r.status}`)}g(n=>({...n,taskAssignments:n.taskAssignments.map(r=>r.task===e?{...r,systemPrompt:i}:r)})),_(!0),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>_(!1),3e3)}catch(s){p(s instanceof Error?s.message:"Failed to save prompt")}finally{l(!1)}},[o,c,d]);return a.useEffect(()=>()=>{m.current&&clearTimeout(m.current)},[]),j?t.jsx("div",{className:"cedros-admin__section",children:t.jsxs("div",{className:"cedros-admin__loading",children:[v.Icons.loading," Loading AI settings..."]})}):t.jsxs("div",{className:"cedros-admin__ai-settings",children:[t.jsxs("div",{className:"cedros-admin__page-header",children:[t.jsx("h2",{className:"cedros-admin__page-title",children:"Store AI"}),t.jsx("p",{className:"cedros-admin__page-description",children:"Configure AI providers, model assignments, and system prompts."})]}),t.jsxs("div",{className:"cedros-admin__tabs cedros-admin__tabs--line",children:[t.jsx("button",{type:"button",className:`cedros-admin__tab ${h==="api-keys"?"cedros-admin__tab--active":""}`,onClick:()=>b("api-keys"),children:"API Keys"}),t.jsx("button",{type:"button",className:`cedros-admin__tab ${h==="assignments"?"cedros-admin__tab--active":""}`,onClick:()=>b("assignments"),children:"Model Assignments"}),t.jsx("button",{type:"button",className:`cedros-admin__tab ${h==="prompts"?"cedros-admin__tab--active":""}`,onClick:()=>b("prompts"),children:"Prompts"})]}),x&&t.jsx("div",{className:"cedros-admin__error-banner",style:{marginTop:"1rem"},children:x}),t.jsx(G.ErrorBanner,{message:E,onRetry:I}),C&&t.jsxs("div",{className:"cedros-admin__success-banner",style:{marginTop:"1rem"},children:[v.Icons.check," Settings saved successfully"]}),h==="api-keys"&&t.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[t.jsx("div",{className:"cedros-admin__section-header",children:t.jsx("h3",{className:"cedros-admin__section-title",children:"API Keys"})}),t.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Configure API keys for AI providers. Keys are stored securely and never exposed."}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1.5rem"},children:W.map(e=>{const i=f.apiKeys.find(n=>n.provider===e.id),s=i?.isConfigured??!1;return t.jsxs("div",{className:"cedros-admin__api-key-card",style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[t.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"0.75rem"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontWeight:600},children:e.label}),s&&i?.maskedKey&&t.jsxs("div",{style:{fontSize:12,opacity:.6,marginTop:2},children:["Current key: ",i.maskedKey,i.updatedAt&&t.jsxs("span",{children:[" (updated ",new Date(i.updatedAt).toLocaleDateString(),")"]})]})]}),t.jsx("span",{className:`cedros-admin__badge ${s?"cedros-admin__badge--success":"cedros-admin__badge--muted"}`,children:s?"Configured":"Not Set"})]}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem"},children:t.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[t.jsx("input",{type:S[e.id]?"text":"password",className:"cedros-admin__input",placeholder:s?"Enter new key to replace":e.placeholder,value:A[e.id],onChange:n=>T(r=>({...r,[e.id]:n.target.value})),onBlur:()=>{A[e.id].trim()&&D(e.id)},style:{flex:1}}),t.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost",onClick:()=>R(n=>({...n,[e.id]:!n[e.id]})),title:S[e.id]?"Hide key":"Show key",style:{padding:"0.5rem"},children:S[e.id]?v.Icons.eyeOff:v.Icons.eye}),s&&t.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--danger",onClick:()=>F(e.id),disabled:u,title:"Remove API key",style:{padding:"0.5rem"},children:v.Icons.trash})]})})]},e.id)})})]}),h==="assignments"&&t.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[t.jsx("div",{className:"cedros-admin__section-header",children:t.jsx("h3",{className:"cedros-admin__section-title",children:"Model Assignments"})}),t.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Assign AI models to specific tasks. Models require their provider's API key to be configured."}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1rem"},children:f.taskAssignments.map(e=>{const i=P.find(n=>n.task===e.task),s=w.find(n=>n.id===e.assignedModel);return t.jsxs("div",{style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[t.jsxs("div",{style:{marginBottom:"0.75rem"},children:[t.jsx("div",{style:{fontWeight:600},children:i?.label??e.task}),t.jsx("div",{style:{fontSize:13,opacity:.7,marginTop:2},children:i?.description})]}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[t.jsx(z.FormDropdown,{value:e.assignedModel,onChange:n=>O(e.task,n),options:K,label:"",disabled:u,style:{flex:1,maxWidth:280}}),s&&s.provider&&t.jsx("span",{className:`cedros-admin__badge ${k(s.id)?"cedros-admin__badge--success":"cedros-admin__badge--warning"}`,children:k(s.id)?"Ready":"Missing API Key"})]})]},e.task)})})]}),h==="prompts"&&t.jsxs("div",{className:"cedros-admin__section",style:{marginTop:"1rem"},children:[t.jsx("div",{className:"cedros-admin__section-header",children:t.jsx("h3",{className:"cedros-admin__section-title",children:"System Prompts"})}),t.jsx("p",{style:{marginBottom:"1.5rem",opacity:.7,fontSize:14},children:"Configure the default system prompts for each AI task. These prompts guide the AI's behavior and responses."}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"1.5rem"},children:f.taskAssignments.map(e=>{const i=P.find(s=>s.task===e.task);return t.jsx(J,{task:e.task,label:i?.label??e.task,description:i?.description??"",initialPrompt:e.systemPrompt??"",onSave:q},e.task)})})]})]})}function J({task:o,label:c,description:d,initialPrompt:h,onSave:b}){const[f,g]=a.useState(h),[j,y]=a.useState("idle"),u=a.useRef(null),l=a.useRef(null),x=a.useRef(!0);return a.useEffect(()=>{if(x.current){x.current=!1;return}return u.current&&clearTimeout(u.current),l.current&&clearTimeout(l.current),y("pending"),u.current=setTimeout(async()=>{y("saving");try{await b(o,f),y("saved"),l.current=setTimeout(()=>y("idle"),2e3)}catch{y("error")}},1500),()=>{u.current&&clearTimeout(u.current)}},[f,o,b]),a.useEffect(()=>()=>{u.current&&clearTimeout(u.current),l.current&&clearTimeout(l.current)},[]),t.jsxs("div",{style:{padding:"1rem",border:"1px solid var(--cedros-admin-border)",borderRadius:8},children:[t.jsxs("div",{style:{marginBottom:"0.75rem",display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontWeight:600},children:c}),t.jsx("div",{style:{fontSize:13,opacity:.7,marginTop:2},children:d})]}),t.jsx(B.AutosaveIndicator,{status:j})]}),t.jsx("textarea",{className:"cedros-admin__input",value:f,onChange:p=>g(p.target.value),placeholder:"Enter system prompt...",rows:4,style:{width:"100%",resize:"vertical",fontFamily:"inherit",minHeight:100}})]})}exports.AISettingsSection=L;
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { jsx as n, jsxs as r } from "react/jsx-runtime";
|
|
2
2
|
import { useState as u, useRef as S, useCallback as A, useEffect as T, useMemo as q } from "react";
|
|
3
|
-
import { I as w } from "./
|
|
4
|
-
import { E as J } from "./ErrorBanner-
|
|
5
|
-
import { F as Y } from "./Dropdown-
|
|
6
|
-
import { A as X } from "./AutosaveIndicator-
|
|
3
|
+
import { I as w } from "./plugin-BIkt3boU.mjs";
|
|
4
|
+
import { E as J } from "./ErrorBanner-DAjYj6Dx.mjs";
|
|
5
|
+
import { F as Y } from "./Dropdown-0y3S40Xf.mjs";
|
|
6
|
+
import { A as X } from "./AutosaveIndicator-D966vOrP.mjs";
|
|
7
7
|
const C = [
|
|
8
8
|
{ id: "not_set", label: "Disabled", provider: null },
|
|
9
9
|
{ id: "gemini-2.5-flash", label: "Gemini 2.5 Flash", provider: "gemini" },
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const e=require("react/jsx-runtime"),i=require("./plugin-Dw8_Q8rE.js");function a({status:n,error:r}){return n==="idle"?null:e.jsxs("span",{className:`cedros-admin__autosave-indicator cedros-admin__autosave-indicator--${n}`,style:{display:"inline-flex",alignItems:"center",gap:"0.375rem",fontSize:"0.8125rem",color:n==="error"?"var(--cedros-admin-error, #ef4444)":"var(--cedros-admin-text-muted, #64748b)"},children:[n==="pending"&&e.jsx("span",{style:{opacity:.7},children:"Unsaved changes"}),n==="saving"&&e.jsxs(e.Fragment,{children:[i.Icons.loading,e.jsx("span",{children:"Saving..."})]}),n==="saved"&&e.jsxs(e.Fragment,{children:[i.Icons.check,e.jsx("span",{style:{color:"var(--cedros-admin-success, #22c55e)"},children:"Saved"})]}),n==="error"&&e.jsxs("span",{children:["Save failed",r?`: ${r}`:""]})]})}exports.AutosaveIndicator=a;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { jsxs as n, jsx as r, Fragment as i } from "react/jsx-runtime";
|
|
2
|
-
import { I as d } from "./
|
|
2
|
+
import { I as d } from "./plugin-BIkt3boU.mjs";
|
|
3
3
|
function l({ status: e, error: a }) {
|
|
4
4
|
return e === "idle" ? null : /* @__PURE__ */ n(
|
|
5
5
|
"span",
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
"use strict";const K=require("react/jsx-runtime"),b=require("react"),R=require("./uuid-C5B8o31X.js"),s=require("./fetchWithTimeout-CG0EKbhf.js"),pe=require("./tokenMintValidator-DNBhoefh.js");var ie="https://js.stripe.com/v3",we=/^https:\/\/js\.stripe\.com\/v3\/?(\?.*)?$/;var ve=function(){for(var e=document.querySelectorAll('script[src^="'.concat(ie,'"]')),t=0;t<e.length;t++){var r=e[t];if(we.test(r.src))return r}return null},te=function(e){var t="",r=document.createElement("script");r.src="".concat(ie).concat(t);var a=document.head||document.body;if(!a)throw new Error("Expected document.body not to be null. Stripe.js requires a <body> element.");return a.appendChild(r),r},be=function(e,t){!e||!e._registerWrapper||e._registerWrapper({name:"stripe-js",version:"4.6.0",startTime:t})},q=null,$=null,W=null,Ee=function(e){return function(){e(new Error("Failed to load Stripe.js"))}},Ce=function(e,t){return function(){window.Stripe?e(window.Stripe):t(new Error("Stripe.js not available"))}},Pe=function(e){return q!==null?q:(q=new Promise(function(t,r){if(typeof window>"u"||typeof document>"u"){t(null);return}if(window.Stripe){t(window.Stripe);return}try{var a=ve();if(!(a&&e)){if(!a)a=te(e);else if(a&&W!==null&&$!==null){var n;a.removeEventListener("load",W),a.removeEventListener("error",$),(n=a.parentNode)===null||n===void 0||n.removeChild(a),a=te(e)}}W=Ce(t,r),$=Ee(r),a.addEventListener("load",W),a.addEventListener("error",$)}catch(o){r(o);return}}),q.catch(function(t){return q=null,Promise.reject(t)}))},Te=function(e,t,r){if(e===null)return null;var a=e.apply(void 0,t);return be(a,r),a},j,oe=!1,se=function(){return j||(j=Pe(null).catch(function(e){return j=null,Promise.reject(e)}),j)};Promise.resolve().then(function(){return se()}).catch(function(i){oe||console.warn(i)});var ce=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];oe=!0;var a=Date.now();return se().then(function(n){return Te(n,t,a)})};function M(i,e){return i instanceof Error?i.message:typeof i=="string"?i:e}const Se={service_unavailable:"Service temporarily unavailable. Please try again later or contact support.",server_insufficient_funds:"Service temporarily unavailable. Please try again later or contact support.",insufficient_funds_token:"Insufficient token balance in your wallet. Please add more tokens and try again.",insufficient_funds_sol:"Insufficient SOL for transaction fees. Please add some SOL to your wallet and try again.",insufficient_amount:"Payment amount is insufficient. Please check the required amount.",invalid_signature:"Transaction signature is invalid. Please try again.",send_failed:"Failed to send transaction. Please try again or contact support.",timeout:"Transaction timed out. Please check the blockchain explorer or try again."};async function v(i,e,t=!1){const r=typeof i.clone=="function",a=r?i.clone():void 0;try{const n=await i.json();if(t&&n.verificationError){s.getLogger().debug(`Payment verification failed: ${n.verificationError.code}`);const o=n.verificationError.code;return Se[o]||n.verificationError.message||e}return typeof n.error=="string"?n.error:n.error&&typeof n.error=="object"&&"message"in n.error?n.error.message:e}catch{if(a)try{const n=await a.text();if(n)return n}catch{}if(!r&&typeof i.text=="function")try{const n=await i.text();if(n)return n}catch{}return e}}function O(i){const{maxRequests:e,windowMs:t}=i;let r=e,a=Date.now();const n=e/t;function o(){const d=Date.now(),g=d-a;if(g>0){const y=g*n;r=Math.min(e,r+y),a=d}}function c(){return o(),r>=1?(r-=1,!0):!1}function u(){return o(),Math.floor(r)}function l(){if(o(),r>=1)return 0;const g=(1-r)/n;return Math.ceil(g)}function f(){r=e,a=Date.now()}return{tryConsume:c,getAvailableTokens:u,getTimeUntilRefill:l,reset:f}}const D={PAYMENT:{maxRequests:10,windowMs:6e4},QUOTE:{maxRequests:30,windowMs:6e4},STRICT:{maxRequests:5,windowMs:6e4},PERMISSIVE:{maxRequests:100,windowMs:6e4}};var ue=(i=>(i.CLOSED="CLOSED",i.OPEN="OPEN",i.HALF_OPEN="HALF_OPEN",i))(ue||{});class w extends Error{constructor(e){super(e),this.name="CircuitBreakerOpenError"}}function B(i){const{failureThreshold:e,timeout:t,failureWindow:r=t*2,name:a="circuit-breaker"}=i;let n="CLOSED",o=[],c=0,u=0,l=null,f=null,d=null,g=!1;function y(){const T=Date.now()-r;o=o.filter(P=>P>T)}function m(){n==="OPEN"&&d!==null&&Date.now()>=d&&(s.getLogger().debug(`[CircuitBreaker:${a}] Transitioning OPEN → HALF_OPEN (timeout expired)`),n="HALF_OPEN",d=null)}function h(){f=Date.now(),c++,n==="HALF_OPEN"?(s.getLogger().debug(`[CircuitBreaker:${a}] Success in HALF_OPEN → CLOSED`),n="CLOSED",o=[]):n==="CLOSED"&&(o=[])}function p(T){const P=Date.now();l=P,o.push(P),y();const U=o.length;s.getLogger().warn(`[CircuitBreaker:${a}] Failure recorded (${U}/${e}):`,T.message),n==="HALF_OPEN"?(s.getLogger().warn(`[CircuitBreaker:${a}] Failed in HALF_OPEN → OPEN`),n="OPEN",d=P+t):n==="CLOSED"&&U>=e&&(s.getLogger().error(`[CircuitBreaker:${a}] Failure threshold reached (${U}) → OPEN`),n="OPEN",d=P+t)}async function k(T){if(m(),n==="OPEN"){u++;const P=d?Math.ceil((d-Date.now())/1e3):0;throw new w(`Circuit breaker is OPEN. Service is unavailable. Retry in ${P}s.`)}if(n==="HALF_OPEN"&&g)throw u++,new w("Circuit breaker is HALF_OPEN. A probe request is already in progress.");n==="HALF_OPEN"&&(g=!0);try{const P=await T();return h(),P}catch(P){throw p(P instanceof Error?P:new Error(String(P))),P}finally{g&&(g=!1)}}function L(){return m(),n}function x(){return m(),y(),{state:n,failures:o.length,successes:c,rejections:u,lastFailureTime:l,lastSuccessTime:f}}function _(){s.getLogger().debug(`[CircuitBreaker:${a}] Manual reset → CLOSED`),n="CLOSED",o=[],c=0,u=0,l=null,f=null,d=null}function N(){s.getLogger().warn(`[CircuitBreaker:${a}] Manual trip → OPEN`),n="OPEN",d=Date.now()+t}return{execute:k,getState:L,getStats:x,reset:_,trip:N}}const ke={STRICT:{failureThreshold:3,timeout:6e4},STANDARD:{failureThreshold:5,timeout:3e4},LENIENT:{failureThreshold:10,timeout:15e3}},Re={invalid_payment_proof:{message:"Payment verification failed",action:"Please try your payment again. If this continues, contact support.",technicalHint:"Invalid payment proof format"},invalid_signature:{message:"Transaction signature is invalid",action:"Please approve the transaction in your wallet and try again.",technicalHint:"Transaction signature verification failed"},invalid_transaction:{message:"Transaction format is invalid",action:"Please try your payment again. If this continues, try updating your wallet app.",technicalHint:"Malformed transaction structure"},transaction_not_found:{message:"Transaction not found on the blockchain",action:"Your transaction may still be processing. Please wait a moment and check your wallet, or try again.",technicalHint:"Transaction signature not found on-chain"},transaction_not_confirmed:{message:"Transaction is still processing",action:"Please wait a moment for the blockchain to confirm your transaction, then try again.",technicalHint:"Transaction not yet confirmed"},transaction_failed:{message:"Transaction failed on the blockchain",action:"Check your wallet for details. You may need to adjust your transaction settings or add more SOL for fees.",technicalHint:"On-chain transaction failure"},transaction_expired:{message:"Transaction took too long to process",action:"Please try your payment again. Consider increasing transaction priority if your wallet supports it.",technicalHint:"Transaction blockhash expired"},invalid_recipient:{message:"Payment was sent to the wrong address",action:"Please try again and ensure you approve the correct transaction in your wallet.",technicalHint:"Recipient address mismatch"},invalid_sender:{message:"Payment sender wallet is invalid",action:"Please reconnect your wallet and try again.",technicalHint:"Sender address validation failed"},unauthorized_refund_issuer:{message:"You are not authorized to issue refunds",action:"Only authorized accounts can process refunds. Please contact support if you believe this is an error.",technicalHint:"Refund issuer not in authorized list"},amount_below_minimum:{message:"Payment amount is too low",action:"Please check the required amount and try again.",technicalHint:"Amount below minimum threshold"},amount_mismatch:{message:"Payment amount does not match the quote",action:"The price may have changed. Please refresh and try your payment again.",technicalHint:"Amount does not match quote"},insufficient_funds_sol:{message:"Not enough SOL for transaction fees",action:"Add at least 0.001 SOL to your wallet to cover network fees, then try again.",technicalHint:"Insufficient SOL balance for fees"},insufficient_funds_token:{message:"Insufficient balance in your wallet",action:"Add more funds to your wallet and try again.",technicalHint:"Insufficient token balance"},invalid_token_mint:{message:"Incorrect payment token",action:"Please pay with the correct token as shown in the payment details.",technicalHint:"Token mint address mismatch"},not_spl_transfer:{message:"Transaction is not a valid token transfer",action:"Please ensure you are sending the correct token type from your wallet.",technicalHint:"Transaction is not an SPL token transfer"},missing_token_account:{message:"Token account not found",action:"Your wallet may need to create a token account first. Try again or use a different wallet.",technicalHint:"Associated token account does not exist"},invalid_token_program:{message:"Invalid token program",action:"Please try your payment again. If this continues, try using a different wallet.",technicalHint:"Token program ID mismatch"},missing_memo:{message:"Payment memo is required but was not included",action:"Please try your payment again and ensure transaction details are approved in your wallet.",technicalHint:"Required memo instruction missing"},invalid_memo:{message:"Payment memo format is invalid",action:"Please try your payment again.",technicalHint:"Memo does not match expected format"},payment_already_used:{message:"This payment has already been processed",action:"Check your transaction history. If you need to make another payment, please start a new transaction.",technicalHint:"Payment signature already recorded"},signature_reused:{message:"Transaction signature has already been used",action:"Please create a new payment transaction.",technicalHint:"Duplicate signature detected"},quote_expired:{message:"Payment quote has expired",action:"Prices are updated frequently. Please refresh and try your payment again.",technicalHint:"Quote timestamp expired"},missing_field:{message:"Required information is missing",action:"Please check all required fields and try again.",technicalHint:"Required field not provided"},invalid_field:{message:"Some information is invalid",action:"Please check your input and try again.",technicalHint:"Field validation failed"},invalid_amount:{message:"Payment amount is invalid",action:"Please check the amount and try again.",technicalHint:"Amount validation failed"},invalid_wallet:{message:"Wallet address is invalid",action:"Please reconnect your wallet and try again.",technicalHint:"Wallet address validation failed"},invalid_resource:{message:"Invalid item selection",action:"Please refresh the page and try again.",technicalHint:"Resource ID validation failed"},invalid_coupon:{message:"Invalid coupon code",action:"Please check the coupon code and try again.",technicalHint:"Coupon code format invalid"},invalid_cart_item:{message:"One or more cart items are invalid",action:"Please review your cart and try again.",technicalHint:"Cart item validation failed"},empty_cart:{message:"Your cart is empty",action:"Please add items to your cart before checking out.",technicalHint:"Cart contains no items"},resource_not_found:{message:"Item not found",action:"This item may no longer be available. Please refresh and try again.",technicalHint:"Resource not found in database"},cart_not_found:{message:"Shopping cart not found",action:"Your cart may have expired. Please start a new order.",technicalHint:"Cart ID not found"},refund_not_found:{message:"Refund not found",action:"Please check your refund reference number or contact support.",technicalHint:"Refund ID not found"},product_not_found:{message:"Product not available",action:"This product may no longer be available. Please browse our current selection.",technicalHint:"Product ID not found"},coupon_not_found:{message:"Coupon code not found",action:"Please check the coupon code or remove it to continue.",technicalHint:"Coupon code not in database"},session_not_found:{message:"Payment session expired",action:"Please start a new payment.",technicalHint:"Session ID not found or expired"},cart_already_paid:{message:"This order has already been paid",action:"Check your order history. If you need to make another purchase, please start a new order.",technicalHint:"Cart marked as paid"},refund_already_processed:{message:"This refund has already been processed",action:"Check your transaction history or contact support for details.",technicalHint:"Refund already completed"},coupon_expired:{message:"Coupon has expired",action:"Please remove the coupon code or use a different code.",technicalHint:"Coupon expiration date passed"},coupon_usage_limit_reached:{message:"Coupon usage limit reached",action:"This coupon has been fully redeemed. Please try a different code.",technicalHint:"Coupon max uses exceeded"},coupon_not_applicable:{message:"Coupon cannot be applied to this purchase",action:"Please check the coupon terms or remove it to continue.",technicalHint:"Coupon conditions not met"},coupon_wrong_payment_method:{message:"Coupon not valid for this payment method",action:"Try a different payment method or remove the coupon code.",technicalHint:"Coupon restricted to specific payment methods"},stripe_error:{message:"Card payment service temporarily unavailable",action:"Please try again in a moment, or use cryptocurrency payment instead.",technicalHint:"Stripe API error"},rpc_error:{message:"Blockchain network temporarily unavailable",action:"Please try again in a moment, or use card payment instead.",technicalHint:"Solana RPC error"},network_error:{message:"Network connection issue",action:"Please check your internet connection and try again.",technicalHint:"Network request failed"},internal_error:{message:"Something went wrong on our end",action:"Please try again. If this continues, contact support.",technicalHint:"Internal server error"},database_error:{message:"Service temporarily unavailable",action:"Please try again in a moment.",technicalHint:"Database operation failed"},config_error:{message:"Service configuration error",action:"Please contact support for assistance.",technicalHint:"Server misconfiguration"}};function le(i){return Re[i]||{message:"An unexpected error occurred",action:"Please try again or contact support if this continues.",technicalHint:`Unknown error code: ${i}`}}class F extends Error{code;retryable;details;httpStatus;constructor(e,t,r=!1,a,n){super(t),this.name="PaymentError",this.code=e,this.retryable=r,this.details=a,this.httpStatus=n,Object.setPrototypeOf(this,F.prototype)}canRetry(){return this.retryable}is(e){return this.code===e}isInCategory(e){return e.includes(this.code)}getUserMessage(){const e=this.getErrorInfo();return e.action?`${e.message} ${e.action}`:e.message}getShortMessage(){return this.getErrorInfo().message}getAction(){return this.getErrorInfo().action}getErrorInfo(){return le(this.code)}static fromErrorResponse(e,t){const r=e.error.retryable??de.RETRYABLE.includes(e.error.code);return new F(e.error.code,e.error.message,r,e.error.details,t)}static fromUnknown(e){return e instanceof F?e:e instanceof Error?new F("internal_error",e.message,!1):new F("internal_error",String(e),!1)}}const de={INSUFFICIENT_FUNDS:["insufficient_funds_sol","insufficient_funds_token"],TRANSACTION_PENDING:["transaction_not_confirmed","transaction_not_found"],VALIDATION:["missing_field","invalid_field","invalid_amount","invalid_wallet","invalid_resource","invalid_cart_item","empty_cart"],COUPON:["invalid_coupon","coupon_not_found","coupon_expired","coupon_usage_limit_reached","coupon_not_applicable","coupon_wrong_payment_method"],RETRYABLE:["transaction_not_confirmed","rpc_error","network_error","stripe_error"],NOT_FOUND:["resource_not_found","cart_not_found","refund_not_found","product_not_found","coupon_not_found","session_not_found","credits_hold_not_found"],CREDITS:["insufficient_credits","credits_hold_expired","credits_hold_not_found"],SECURITY:["invalid_redirect_url","rate_limit_exceeded","nonce_already_used"]},re=300*1e3,H=new Map;function _e(i){if(!i)return;const e=Number(i);if(Number.isFinite(e)&&e>=0)return Math.min(e*1e3,re);const t=Date.parse(i);if(!Number.isNaN(t))return Math.min(Math.max(t-Date.now(),0),re)}class S extends Error{httpStatus;retryAfterMs;constructor(e,t,r){super(e),this.name="RetryableHttpError",this.httpStatus=t,this.retryAfterMs=r,Object.setPrototypeOf(this,S.prototype)}static fromResponse(e,t){const r=e.headers&&typeof e.headers.get=="function"?e.headers.get("Retry-After"):null;return new S(t,e.status,_e(r))}}function xe(i){if(i instanceof F||i instanceof S)return i.httpStatus}function Ie(i){if(i instanceof S)return i.retryAfterMs}function Me(i,e){const t=xe(i);if(t!=null){const a=t;return a===429||a>=500&&a<600}const r=i.message.toLowerCase();return!!(r.includes("network")||r.includes("timeout")||r.includes("fetch failed")||r.includes("econnrefused"))}function Oe(i,e,t,r,a){const n=e*Math.pow(t,i),o=Math.min(n,r);return Math.floor(a?o*.5+Math.random()*o*.5:o)}function De(i){return new Promise(e=>setTimeout(e,i))}async function C(i,e={}){const{maxRetries:t=3,initialDelayMs:r=1e3,backoffFactor:a=2,maxDelayMs:n=3e4,jitter:o=!0,shouldRetry:c=Me,name:u="retry",inFlightKey:l}=e,f=async()=>{let y=null,m=0;for(let h=0;h<=t;h++)try{const p=await i();return h>0&&s.getLogger().debug(`[Retry:${u}] Succeeded on attempt ${h+1}/${t+1} after ${m}ms`),p}catch(p){y=p instanceof Error?p:new Error(String(p));const k=h===t,L=c(y,h);if(k||!L)throw s.getLogger().warn(`[Retry:${u}] Failed on attempt ${h+1}/${t+1}. ${k?"No more retries.":"Error not retryable."}`),y;const _=Ie(y)??Oe(h,r,a,n,o);m+=_,s.getLogger().warn(`[Retry:${u}] Attempt ${h+1}/${t+1} failed: ${y.message}. Retrying in ${_}ms...`),await De(_)}throw y||new Error("Retry failed with no error")};if(!l)return f();const d=H.get(l);if(d)return d;const g=f().finally(()=>{H.get(l)===g&&H.delete(l)});return H.set(l,g),g}const E={QUICK:{maxRetries:3,initialDelayMs:1e3,backoffFactor:2,maxDelayMs:1e4},STANDARD:{maxRetries:3,initialDelayMs:2e3,backoffFactor:2,maxDelayMs:3e4},AGGRESSIVE:{maxRetries:5,initialDelayMs:500,backoffFactor:1.5,maxDelayMs:15e3},PATIENT:{maxRetries:5,initialDelayMs:5e3,backoffFactor:2,maxDelayMs:6e4},IDEMPOTENT_WRITE:{maxRetries:1,initialDelayMs:1e3,backoffFactor:2,maxDelayMs:1e4},WRITE_ONCE:{maxRetries:0,initialDelayMs:1e3,backoffFactor:2,maxDelayMs:1e4}};class Le{stripe=null;initPromise=null;publicKey;routeDiscovery;complianceCheckEnabled;rateLimiter=O(D.PAYMENT);circuitBreaker=B({failureThreshold:5,timeout:1e4,name:"stripe-manager"});constructor(e,t,r=!1){this.publicKey=e,this.routeDiscovery=t,this.complianceCheckEnabled=r}async initialize(){this.stripe||(this.initPromise||(this.initPromise=(async()=>{try{if(this.stripe=await ce(this.publicKey),!this.stripe)throw new Error("Failed to initialize Stripe")}catch(e){throw this.initPromise=null,e}})()),await this.initPromise)}async createSession(e){if(!this.rateLimiter.tryConsume())throw new Error("Rate limit exceeded for Stripe session creation. Please try again later.");const t=R.generateUUID(),r=JSON.stringify(e);try{return await this.circuitBreaker.execute(async()=>await C(async()=>{const a=await this.routeDiscovery.buildUrl("/paywall/v1/stripe-session");s.getLogger().debug("[StripeManager] Creating session",{resource:e.resource,hasCouponCode:!!e.couponCode,hasMetadata:!!(e.metadata&&Object.keys(e.metadata).length),metadataKeyCount:e.metadata?Object.keys(e.metadata).length:0});const n=await s.fetchWithTimeout(a,{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":t},body:r});if(!n.ok){const o=await v(n,"Failed to create Stripe session");throw S.fromResponse(n,o)}return await n.json()},{...E.IDEMPOTENT_WRITE,name:"stripe-create-session",inFlightKey:`stripe:create-session:${r}`}))}catch(a){throw a instanceof w?(s.getLogger().error("[StripeManager] Circuit breaker is OPEN - Stripe service unavailable"),new Error("Stripe payment service is temporarily unavailable. Please try again in a few moments.")):a}}async redirectToCheckout(e){if(this.stripe||await this.initialize(),!this.stripe)return{success:!1,error:"Stripe not initialized"};const t=await this.stripe.redirectToCheckout({sessionId:e});return t.error?{success:!1,error:t.error.message}:{success:!0}}async runComplianceCheck(e){if(!this.complianceCheckEnabled)return null;try{const t=await this.routeDiscovery.buildUrl("/paywall/v1/compliance-check"),r=await s.fetchWithTimeout(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({resources:e})});if(!r.ok)return null;const a=await r.json();if(!a.cleared)return{success:!1,error:`Purchase blocked: ${(a.reasons??["Purchase blocked by compliance check"]).join("; ")}`}}catch{s.getLogger().warn("[StripeManager] Compliance pre-check failed, proceeding")}return null}async processPayment(e){try{const t=await this.runComplianceCheck([e.resource]);if(t)return t;const r=await this.createSession(e);return await this.redirectToCheckout(r.sessionId)}catch(t){return{success:!1,error:M(t,"Unknown error")}}}async processCartCheckout(e){const{items:t,successUrl:r,cancelUrl:a,metadata:n,customerEmail:o,customerName:c,customerPhone:u,shippingAddress:l,billingAddress:f,couponCode:d,tipAmount:g,shippingMethodId:y,paymentMethodId:m}=e,h=t.map(T=>T.resource),p=await this.runComplianceCheck(h);if(p)return p;if(!this.rateLimiter.tryConsume())return{success:!1,error:"Rate limit exceeded for cart checkout. Please try again later."};const k=R.generateUUID(),x=JSON.stringify({items:t,metadata:n,coupon:d,couponCode:d}),_=R.generateUUID(),N={items:t,metadata:n,cartId:"",successUrl:r,cancelUrl:a,customerEmail:o,customerName:c,customerPhone:u,shippingAddress:l,billingAddress:f,coupon:d,couponCode:d,tipAmount:g,shippingMethodId:y,paymentMethodId:m};try{const T=await this.circuitBreaker.execute(async()=>{const P=await C(async()=>{const J=await this.routeDiscovery.buildUrl("/paywall/v1/cart/quote"),I=await s.fetchWithTimeout(J,{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":k},body:x});if(!I.ok){const G=await v(I,"Failed to create cart quote");throw S.fromResponse(I,G)}return await I.json()},{...E.IDEMPOTENT_WRITE,name:"stripe-cart-quote",inFlightKey:`stripe:cart-quote:${x}`});if(!P.cartId)throw new Error("Invalid cart quote response: missing cartId");const U=JSON.stringify({...N,cartId:P.cartId});return await C(async()=>{const J=await this.routeDiscovery.buildUrl("/paywall/v1/cart/checkout"),I=await s.fetchWithTimeout(J,{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":_},body:U});if(!I.ok){const G=await v(I,"Failed to create cart checkout session");throw S.fromResponse(I,G)}return await I.json()},{...E.IDEMPOTENT_WRITE,name:"stripe-cart-checkout",inFlightKey:`stripe:cart-checkout:${U}`})});return await this.redirectToCheckout(T.sessionId)}catch(T){return T instanceof w?{success:!1,error:"Stripe payment service is temporarily unavailable. Please try again in a few moments."}:{success:!1,error:M(T,"Cart checkout failed")}}}}class Fe{routeDiscovery;quoteRateLimiter=O(D.QUOTE);verifyRateLimiter=O(D.PAYMENT);circuitBreaker=B({failureThreshold:5,timeout:1e4,name:"x402-manager"});constructor(e){this.routeDiscovery=e}async requestQuote(e){const{resource:t,couponCode:r}=e;if(!this.quoteRateLimiter.tryConsume())throw new Error("Rate limit exceeded for quote requests. Please try again later.");try{return await this.circuitBreaker.execute(async()=>await C(async()=>{const a="/paywall/v1/quote";s.getLogger().debug("[X402Manager] Requesting quote",r?"with coupon":"without coupon");const n=await this.routeDiscovery.buildUrl(a),o=await s.fetchWithTimeout(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({resource:t,couponCode:r||null})});if(o.status!==402)throw new Error(`Expected 402 status, got ${o.status}`);const c=await o.json();if(c.crypto){const u=c.crypto;if(!this.validateRequirement(u))throw new Error("Invalid x402 requirement received from server: missing required fields");return u}else if(c.accepts&&c.accepts.length>0){const u=c.accepts[0];if(!this.validateRequirement(u))throw new Error("Invalid x402 requirement received from server: missing required fields");return u}else throw new Error("Invalid x402 response: missing crypto or accepts field")},{...E.QUICK,name:"x402-quote"}))}catch(a){throw a instanceof w?(s.getLogger().error("[X402Manager] Circuit breaker is OPEN - x402 service unavailable"),new Error("Payment service is temporarily unavailable. Please try again in a few moments.")):a}}async requestCartQuote(e){const{items:t,metadata:r,couponCode:a}=e;if(!this.quoteRateLimiter.tryConsume())throw new Error("Rate limit exceeded for cart quote requests. Please try again later.");const n=R.generateUUID();try{return await this.circuitBreaker.execute(async()=>await C(async()=>{const o=await this.routeDiscovery.buildUrl("/paywall/v1/cart/quote"),c={items:t,metadata:r,coupon:a,couponCode:a},u=await s.fetchWithTimeout(o,{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":n},body:JSON.stringify(c)});if(u.status!==402&&!u.ok){const f=await v(u,"Failed to get cart quote");throw new Error(f)}const l=await u.json();if(!l.cartId||!l.quote)throw new Error("Invalid cart quote response: missing cartId or quote");if(l.quote.crypto&&!this.validateRequirement(l.quote.crypto))throw new Error("Invalid x402 cart quote: missing required fields in crypto quote");return l},{...E.QUICK,name:"x402-cart-quote"}))}catch(o){throw o instanceof w?(s.getLogger().error("[X402Manager] Circuit breaker is OPEN - cart quote service unavailable"),new Error("Payment service is temporarily unavailable. Please try again in a few moments.")):o}}buildPaymentHeader(e){const t=JSON.stringify(e);return s.gBase64.encode(t)}parseSettlementResponse(e){const t=e.headers.get("X-PAYMENT-RESPONSE");if(!t)return null;try{const r=s.gBase64.decode(t),a=JSON.parse(r);return typeof a.success!="boolean"?(s.getLogger().error("Invalid settlement response: missing success field"),null):a}catch(r){return s.getLogger().error("Failed to parse settlement response:",r),null}}async submitPayment(e){const{resource:t,payload:r,couponCode:a,metadata:n,resourceType:o="regular"}=e;if(!this.verifyRateLimiter.tryConsume())return{success:!1,error:"Rate limit exceeded for payment verification. Please try again later."};const c=R.generateUUID();try{return await this.circuitBreaker.execute(async()=>await C(async()=>{const l={...r,payload:{...r.payload,resource:t,resourceType:o,metadata:{...r.payload.metadata||{},...n||{},...a?{couponCode:a}:{}}}},f=this.buildPaymentHeader(l),d="/paywall/v1/verify";s.getLogger().debug("[X402Manager] Submitting payment",{resourceType:o,hasCoupon:!!a,hasMetadata:!!n});const g=await this.routeDiscovery.buildUrl(d),y=await s.fetchWithTimeout(g,{method:"POST",headers:{"Content-Type":"application/json","X-PAYMENT":f,"Idempotency-Key":c}});if(y.ok){const{settlement:h,transactionId:p}=await this.handlePaymentVerification(y,r.payload.signature);return{success:!0,transactionId:p,settlement:h||void 0}}return{success:!1,error:await v(y,"Payment verification failed",!0)}},{maxRetries:0,initialDelayMs:0,backoffFactor:1,maxDelayMs:0,name:"x402-verify"}))}catch(u){return u instanceof w?{success:!1,error:"Payment verification service is temporarily unavailable. Please try again in a few moments."}:{success:!1,error:M(u,"Unknown error")}}}async buildGaslessTransaction(e){const{resourceId:t,userWallet:r,feePayer:a,couponCode:n}=e;if(!this.quoteRateLimiter.tryConsume())throw new Error("Rate limit exceeded for gasless transaction requests. Please try again later.");try{return await this.circuitBreaker.execute(async()=>await C(async()=>{const o=await this.routeDiscovery.buildUrl("/paywall/v1/gasless-transaction"),c=await s.fetchWithTimeout(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({resourceId:t,userWallet:r,feePayer:a,couponCode:n})});if(!c.ok){const u=await v(c,"Failed to build gasless transaction");throw new Error(u)}return await c.json()},{...E.QUICK,name:"x402-gasless-build"}))}catch(o){throw o instanceof w?(s.getLogger().error("[X402Manager] Circuit breaker is OPEN - gasless transaction service unavailable"),new Error("Gasless transaction service is temporarily unavailable. Please try again in a few moments.")):o}}async submitGaslessTransaction(e){const{resource:t,partialTx:r,couponCode:a,metadata:n,resourceType:o="regular",requirement:c}=e;if(!this.verifyRateLimiter.tryConsume())return{success:!1,error:"Rate limit exceeded for gasless transaction verification. Please try again later."};const u=R.generateUUID();try{return await this.circuitBreaker.execute(async()=>await C(async()=>{const f={x402Version:0,scheme:c?.scheme||"solana-spl-transfer",network:c?.network||"mainnet-beta",payload:{signature:"",transaction:r,feePayer:c?.extra?.feePayer||"",resource:t,resourceType:o,metadata:{...n||{},...a?{couponCode:a}:{}}}},d=this.buildPaymentHeader(f),y=await this.routeDiscovery.buildUrl("/paywall/v1/verify"),m=await s.fetchWithTimeout(y,{method:"POST",headers:{"Content-Type":"application/json","X-PAYMENT":d,"Idempotency-Key":u}});if(m.ok){const{settlement:p,transactionId:k}=await this.handlePaymentVerification(m,"gasless-tx");return{success:!0,transactionId:k,settlement:p||void 0}}return{success:!1,error:await v(m,"Gasless transaction failed",!0)}},{maxRetries:0,initialDelayMs:0,backoffFactor:1,maxDelayMs:0,name:"x402-gasless-verify"}))}catch(l){return l instanceof w?{success:!1,error:"Gasless transaction verification service is temporarily unavailable. Please try again in a few moments."}:{success:!1,error:M(l,"Unknown error")}}}async handlePaymentVerification(e,t){const r=this.parseSettlementResponse(e),a=e.headers.get("Content-Type")||"";let n=t;if(a.includes("application/json"))try{n=(await e.json()).signature||t}catch(o){s.getLogger().warn("Failed to parse JSON response body:",o)}return{settlement:r,transactionId:n}}validateRequirement(e){return!!(e.scheme&&e.network&&e.maxAmountRequired&&e.resource&&e.payTo&&e.asset&&e.maxTimeoutSeconds>0)}}class Ne{stripe=null;initPromise=null;publicKey;routeDiscovery;sessionRateLimiter=O(D.PAYMENT);statusRateLimiter=O(D.QUOTE);circuitBreaker=B({failureThreshold:5,timeout:1e4,name:"subscription-manager"});constructor(e,t){this.publicKey=e,this.routeDiscovery=t}resolveSubscriptionSessionFlow(e){const t=e,r=typeof t.flow=="string"?t.flow:void 0;return r==="payment_sheet"||typeof t.paymentIntentClientSecret=="string"||typeof t.setupIntentClientSecret=="string"?{flow:"payment_sheet",paymentIntentClientSecret:typeof t.paymentIntentClientSecret=="string"?t.paymentIntentClientSecret:void 0,setupIntentClientSecret:typeof t.setupIntentClientSecret=="string"?t.setupIntentClientSecret:void 0,customerId:typeof t.customerId=="string"?t.customerId:void 0,customerEphemeralKeySecret:typeof t.customerEphemeralKeySecret=="string"?t.customerEphemeralKeySecret:void 0,sessionId:typeof t.sessionId=="string"?t.sessionId:void 0,url:typeof t.url=="string"?t.url:void 0}:(r===void 0||r==="redirect_checkout")&&typeof t.sessionId=="string"&&typeof t.url=="string"?{flow:"redirect_checkout",sessionId:t.sessionId,url:t.url}:null}async initialize(){this.stripe||(this.initPromise||(this.initPromise=(async()=>{if(this.stripe=await ce(this.publicKey),!this.stripe)throw new Error("Failed to initialize Stripe")})()),await this.initPromise)}async executeWithResilience(e,t,r,a,n=E.STANDARD){if(!e.tryConsume())throw new Error("Rate limit exceeded. Please try again later.");try{return await this.circuitBreaker.execute(()=>C(t,{...n,name:r}))}catch(o){throw o instanceof w?(s.getLogger().error(`[SubscriptionManager] Circuit breaker OPEN for ${a}`),new Error("Service temporarily unavailable. Please try again in a few moments.")):o}}async createSubscriptionSession(e){if(!this.sessionRateLimiter.tryConsume())throw new Error("Rate limit exceeded for subscription session creation. Please try again later.");const t=R.generateUUID(),r=JSON.stringify(e);try{return await this.circuitBreaker.execute(async()=>await C(async()=>{const a=await this.routeDiscovery.buildUrl("/paywall/v1/subscription/stripe-session");s.getLogger().debug("[SubscriptionManager] Creating subscription session:",{resource:e.resource,interval:e.interval,trialDays:e.trialDays});const n=await s.fetchWithTimeout(a,{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":t},body:r});if(!n.ok){const o=await v(n,"Failed to create subscription session");throw S.fromResponse(n,o)}return await n.json()},{...E.IDEMPOTENT_WRITE,name:"subscription-create-session",inFlightKey:`subscription:create-session:${r}`}))}catch(a){throw a instanceof w?(s.getLogger().error("[SubscriptionManager] Circuit breaker is OPEN - service unavailable"),new Error("Subscription service is temporarily unavailable. Please try again in a few moments.")):a}}async redirectToCheckout(e){if(this.stripe||await this.initialize(),!this.stripe)return{success:!1,error:"Stripe not initialized"};const t=await this.stripe.redirectToCheckout({sessionId:e});return t.error?{success:!1,error:t.error.message}:{success:!0,transactionId:e}}async processSubscription(e){try{const t=await this.createSubscriptionSession(e),r=this.resolveSubscriptionSessionFlow(t);return r?r.flow==="payment_sheet"?{success:!1,error:"Native payment sheet subscription sessions are not supported on web. Use redirect checkout instead."}:await this.redirectToCheckout(r.sessionId):{success:!1,error:"Subscription session response was missing required redirect checkout fields."}}catch(t){return{success:!1,error:M(t,"Subscription failed")}}}async checkSubscriptionStatus(e){if(!this.statusRateLimiter.tryConsume())throw new Error("Rate limit exceeded for subscription status check. Please try again later.");try{return await this.circuitBreaker.execute(async()=>await C(async()=>{const t=new URLSearchParams({resource:e.resource,userId:e.userId}),r=await this.routeDiscovery.buildUrl(`/paywall/v1/subscription/status?${t.toString()}`);s.getLogger().debug("[SubscriptionManager] Checking subscription status:",e);const a=await s.fetchWithTimeout(r,{method:"GET",headers:{"Content-Type":"application/json"}});if(!a.ok){const n=await v(a,"Failed to check subscription status");throw new Error(n)}return await a.json()},{...E.STANDARD,name:"subscription-status-check"}))}catch(t){throw t instanceof w?(s.getLogger().error("[SubscriptionManager] Circuit breaker is OPEN for status check"),new Error("Subscription status service is temporarily unavailable. Please try again in a few moments.")):t}}async requestSubscriptionQuote(e,t,r){if(!this.statusRateLimiter.tryConsume())throw new Error("Rate limit exceeded for subscription quote. Please try again later.");try{return await this.circuitBreaker.execute(async()=>await C(async()=>{const a=await this.routeDiscovery.buildUrl("/paywall/v1/subscription/quote"),n={resource:e,interval:t,couponCode:r?.couponCode,intervalDays:r?.intervalDays};s.getLogger().debug("[SubscriptionManager] Requesting subscription quote:",n);const o=await s.fetchWithTimeout(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(o.status!==402&&!o.ok){const c=await v(o,"Failed to get subscription quote");throw new Error(c)}return await o.json()},{...E.STANDARD,name:"subscription-quote"}))}catch(a){throw a instanceof w?(s.getLogger().error("[SubscriptionManager] Circuit breaker is OPEN for quote"),new Error("Subscription quote service is temporarily unavailable. Please try again in a few moments.")):a}}async activateX402Subscription(e){const t=JSON.stringify(e);return this.executeWithResilience(this.sessionRateLimiter,async()=>{const r=await this.routeDiscovery.buildUrl("/paywall/v1/subscription/x402/activate");s.getLogger().debug("[SubscriptionManager] Activating x402 subscription:",e);const a=await s.fetchWithTimeout(r,{method:"POST",headers:{"Content-Type":"application/json"},body:t});if(!a.ok)throw S.fromResponse(a,await v(a,"Failed to activate"));return await a.json()},"subscription-activate","activation",{...E.IDEMPOTENT_WRITE,inFlightKey:`subscription:activate:${t}`})}}class Ae{routeDiscovery;rateLimiter=O(D.PAYMENT);queryRateLimiter=O(D.QUOTE);circuitBreaker=B({failureThreshold:5,timeout:1e4,name:"subscription-change-manager"});constructor(e){this.routeDiscovery=e}async executeWithResilience(e,t,r,a,n=E.STANDARD){if(!e.tryConsume())throw new Error("Rate limit exceeded. Please try again later.");try{return await this.circuitBreaker.execute(()=>C(t,{...n,name:r}))}catch(o){throw o instanceof w?(s.getLogger().error(`[SubscriptionChangeManager] Circuit breaker OPEN for ${a}`),new Error("Service temporarily unavailable. Please try again in a few moments.")):o}}async changeSubscription(e){const t=R.generateUUID(),r=JSON.stringify(e);return this.executeWithResilience(this.rateLimiter,async()=>{const a=await this.routeDiscovery.buildUrl("/paywall/v1/subscription/change");s.getLogger().debug("[SubscriptionChangeManager] Changing subscription:",e);const n=await s.fetchWithTimeout(a,{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":t},body:r});if(!n.ok)throw S.fromResponse(n,await v(n,"Failed to change subscription"));return await n.json()},"subscription-change","plan change",{...E.IDEMPOTENT_WRITE,inFlightKey:`subscription:change:${r}`})}async previewChange(e){return this.executeWithResilience(this.queryRateLimiter,async()=>{const t=await this.routeDiscovery.buildUrl("/paywall/v1/subscription/change/preview");s.getLogger().debug("[SubscriptionChangeManager] Previewing subscription change:",e);const r=await s.fetchWithTimeout(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error(await v(r,"Failed to preview change"));return await r.json()},"subscription-preview","change preview")}async getDetails(e,t){return this.executeWithResilience(this.queryRateLimiter,async()=>{const r=new URLSearchParams({resource:e,userId:t}),a=await this.routeDiscovery.buildUrl(`/paywall/v1/subscription/details?${r}`);s.getLogger().debug("[SubscriptionChangeManager] Getting subscription details:",{resource:e,userId:t});const n=await s.fetchWithTimeout(a,{method:"GET",headers:{"Content-Type":"application/json"}});if(!n.ok)throw new Error(await v(n,"Failed to get subscription details"));return await n.json()},"subscription-details","details")}async cancel(e){const t=JSON.stringify(e);return this.executeWithResilience(this.rateLimiter,async()=>{const r=await this.routeDiscovery.buildUrl("/paywall/v1/subscription/cancel");s.getLogger().debug("[SubscriptionChangeManager] Canceling subscription:",e);const a=await s.fetchWithTimeout(r,{method:"POST",headers:{"Content-Type":"application/json"},body:t});if(!a.ok)throw S.fromResponse(a,await v(a,"Failed to cancel subscription"));return await a.json()},"subscription-cancel","cancellation",{...E.WRITE_ONCE,inFlightKey:`subscription:cancel:${t}`})}async getBillingPortalUrl(e){const t=JSON.stringify(e);return this.executeWithResilience(this.queryRateLimiter,async()=>{const r=await this.routeDiscovery.buildUrl("/paywall/v1/subscription/portal");s.getLogger().debug("[SubscriptionChangeManager] Getting billing portal URL:",e);const a=await s.fetchWithTimeout(r,{method:"POST",headers:{"Content-Type":"application/json"},body:t});if(!a.ok)throw S.fromResponse(a,await v(a,"Failed to get billing portal URL"));return await a.json()},"subscription-portal","portal",{...E.WRITE_ONCE,inFlightKey:`subscription:portal:${t}`})}}class Ue{routeDiscovery;rateLimiter=O(D.PAYMENT);circuitBreaker=B({failureThreshold:5,timeout:1e4,name:"credits-manager"});constructor(e){this.routeDiscovery=e}async requestQuote(e,t){if(!this.rateLimiter.tryConsume())throw new Error("Rate limit exceeded for credits quote. Please try again later.");try{return await this.circuitBreaker.execute(async()=>await C(async()=>{const r=await this.routeDiscovery.buildUrl("/paywall/v1/quote");s.getLogger().debug("[CreditsManager] Requesting quote");const a=await s.fetchWithTimeout(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({resource:e,couponCode:t})});if(a.status===402)return(await a.json()).credits||null;if(!a.ok){const n=await v(a,"Failed to get credits quote");throw new Error(n)}return null},{...E.STANDARD,name:"credits-quote"}))}catch(r){throw r instanceof w?(s.getLogger().error("[CreditsManager] Circuit breaker is OPEN - credits service unavailable"),new Error("Credits service is temporarily unavailable. Please try again in a few moments.")):r}}async requestCartQuote(e,t){if(!this.rateLimiter.tryConsume())throw new Error("Rate limit exceeded for cart credits quote. Please try again later.");try{return await this.circuitBreaker.execute(async()=>await C(async()=>{const r=await this.routeDiscovery.buildUrl("/paywall/v1/cart/quote");s.getLogger().debug("[CreditsManager] Requesting cart quote for items:",e.length);const a=await s.fetchWithTimeout(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({items:e,couponCode:t})});if(a.status===402||a.ok){const o=await a.json();return o.credits?{cartId:o.cartId,credits:o.credits}:null}const n=await v(a,"Failed to get cart credits quote");throw new Error(n)},{...E.STANDARD,name:"credits-cart-quote"}))}catch(r){throw r instanceof w?new Error("Credits service is temporarily unavailable. Please try again in a few moments."):r}}async createHold(e){const{resource:t,couponCode:r,authToken:a}=e;if(!this.rateLimiter.tryConsume())throw new Error("Rate limit exceeded for credits hold. Please try again later.");const n=R.generateUUID(),o=JSON.stringify({resource:t,couponCode:r});try{return await this.circuitBreaker.execute(async()=>await C(async()=>{const c=await this.routeDiscovery.buildUrl("/paywall/v1/credits/hold");s.getLogger().debug("[CreditsManager] Creating hold");const u=await s.fetchWithTimeout(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`,"Idempotency-Key":n},body:o});if(!u.ok){const l=await v(u,"Failed to create credits hold");throw S.fromResponse(u,l)}return await u.json()},{...E.IDEMPOTENT_WRITE,name:"credits-create-hold",inFlightKey:`credits:create-hold:${a}:${o}`}))}catch(c){throw c instanceof w?new Error("Credits service is temporarily unavailable. Please try again in a few moments."):c}}async createCartHold(e){const{cartId:t,authToken:r}=e;if(!this.rateLimiter.tryConsume())throw new Error("Rate limit exceeded for cart credits hold. Please try again later.");const a=R.generateUUID();try{return await this.circuitBreaker.execute(async()=>await C(async()=>{const n=await this.routeDiscovery.buildUrl(`/paywall/v1/cart/${encodeURIComponent(t)}/credits/hold`);s.getLogger().debug("[CreditsManager] Creating cart hold for cart:",t);const o=await s.fetchWithTimeout(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`,"Idempotency-Key":a},body:JSON.stringify({})});if(!o.ok){const c=await v(o,"Failed to create cart credits hold");throw S.fromResponse(o,c)}return await o.json()},{...E.IDEMPOTENT_WRITE,name:"credits-create-cart-hold",inFlightKey:`credits:create-cart-hold:${r}:${t}`}))}catch(n){throw n instanceof w?new Error("Credits service is temporarily unavailable. Please try again in a few moments."):n}}async authorizePayment(e){const{resource:t,holdId:r,couponCode:a,authToken:n,metadata:o}=e;if(!this.rateLimiter.tryConsume())return{success:!1,error:"Rate limit exceeded for credits authorization. Please try again later.",errorCode:"rate_limit_exceeded"};const c=R.generateUUID(),u=JSON.stringify({resource:t,holdId:r,couponCode:a,...o&&{metadata:o}});try{return await this.circuitBreaker.execute(async()=>await C(async()=>{const l=await this.routeDiscovery.buildUrl("/paywall/v1/credits/authorize");s.getLogger().debug("[CreditsManager] Authorizing payment");const f=await s.fetchWithTimeout(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,"Idempotency-Key":c},body:u});if(!f.ok){const g=await f.json().catch(()=>({}));throw S.fromResponse(f,g.error?.message||"Credits authorization failed")}return{success:!0,transactionId:(await f.json()).transactionId}},{...E.IDEMPOTENT_WRITE,name:"credits-authorize",inFlightKey:`credits:authorize:${n}:${u}`}))}catch(l){return l instanceof w?{success:!1,error:"Credits service is temporarily unavailable. Please try again in a few moments.",errorCode:"service_unavailable"}:{success:!1,error:M(l,"Credits authorization failed"),errorCode:"authorization_failed"}}}async authorizeCartPayment(e){const{cartId:t,holdId:r,authToken:a,metadata:n}=e;if(!this.rateLimiter.tryConsume())return{success:!1,error:"Rate limit exceeded for cart credits authorization. Please try again later.",errorCode:"rate_limit_exceeded"};const o=R.generateUUID(),c=JSON.stringify({holdId:r,...n&&{metadata:n}});try{return await this.circuitBreaker.execute(async()=>await C(async()=>{const u=await this.routeDiscovery.buildUrl(`/paywall/v1/cart/${encodeURIComponent(t)}/credits/authorize`);s.getLogger().debug("[CreditsManager] Authorizing cart payment for cart:",t);const l=await s.fetchWithTimeout(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`,"Idempotency-Key":o},body:c});if(!l.ok){const d=await l.json().catch(g=>(s.getLogger().error("[CreditsManager] Failed to parse error response JSON:",g,{cartId:t,status:l.status,statusText:l.statusText}),{}));throw S.fromResponse(l,d.error?.message||"Cart credits authorization failed")}return{success:!0,transactionId:(await l.json()).transactionId}},{...E.IDEMPOTENT_WRITE,name:"credits-cart-authorize",inFlightKey:`credits:cart-authorize:${a}:${t}:${c}`}))}catch(u){return u instanceof w?{success:!1,error:"Credits service is temporarily unavailable. Please try again in a few moments.",errorCode:"service_unavailable"}:{success:!1,error:M(u,"Cart credits authorization failed"),errorCode:"authorization_failed"}}}async releaseHold(e,t){if(e)try{await this.circuitBreaker.execute(async()=>{const r=await this.routeDiscovery.buildUrl(`/paywall/v1/credits/hold/${encodeURIComponent(e)}/release`),a=await s.fetchWithTimeout(r,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Idempotency-Key":R.generateUUID()}});if(!a.ok){const n=await v(a,"Failed to release credits hold");throw new Error(n)}})}catch(r){throw r instanceof w?new Error("Credits service is temporarily unavailable. Please try again in a few moments."):r}}async processPayment(e,t,r,a){let n=null;try{n=(await this.createHold({resource:e,couponCode:r,authToken:t})).holdId;const c=await this.authorizePayment({resource:e,holdId:n,couponCode:r,authToken:t,metadata:a});if(!c.success&&n)try{await this.releaseHold(n,t)}catch(u){s.getLogger().warn("[CreditsManager] Failed to release hold after auth failure:",u)}return{success:c.success,transactionId:c.transactionId,error:c.error}}catch(o){if(n)try{await this.releaseHold(n,t)}catch(c){s.getLogger().warn("[CreditsManager] Failed to release hold after payment failure:",c)}return{success:!1,error:M(o,"Credits payment failed")}}}async getBalance(e){try{return await this.circuitBreaker.execute(async()=>{const t=await this.routeDiscovery.buildUrl("/paywall/v1/credits/balance"),r=await s.fetchWithTimeout(t,{method:"GET",headers:{Authorization:`Bearer ${e}`}});if(!r.ok){const a=await v(r,"Failed to fetch credits balance");throw new Error(a)}return await r.json()})}catch(t){throw t instanceof w?new Error("Credits service is temporarily unavailable. Please try again in a few moments."):t}}}class Be{serverUrl;getLogger;fetchWithTimeout;routePrefix=null;discoveryPromise=null;failedDiscoveryAt=null;maxRetries=2;baseDelayMs=1e3;discoveryTimeoutMs=2e3;failedDiscoveryTtlMs=3e4;constructor(e,t){this.serverUrl=e.replace(/\/+$/,""),this.getLogger=t.getLogger,this.fetchWithTimeout=t.fetchWithTimeout}async discoverPrefix(){if(this.routePrefix!==null)return this.routePrefix;if(this.discoveryPromise)return this.discoveryPromise;if(this.failedDiscoveryAt!==null&&Date.now()-this.failedDiscoveryAt<this.failedDiscoveryTtlMs)return"";const e=(async()=>{let t=0;for(;t<this.maxRetries;)try{const r=await this.fetchWithTimeout(`${this.serverUrl}/cedros-health`,{},this.discoveryTimeoutMs);if(!r.ok){if(r.status>=400&&r.status<500)return this.getLogger().warn(`Route discovery received ${r.status} - not retrying client error`),this.failedDiscoveryAt=Date.now(),"";throw new Error(`Health check returned ${r.status}`)}const a=await r.json(),n=String(a.routePrefix??"");return this.routePrefix=n,this.failedDiscoveryAt=null,this.getLogger().debug("Route discovery successful, prefix:",n||"(empty)"),n}catch(r){if(t++,t>=this.maxRetries)return this.getLogger().warn(`Route discovery failed after ${t} attempts, using empty prefix for this request:`,r),this.failedDiscoveryAt=Date.now(),"";const a=this.baseDelayMs*Math.pow(2,t-1);this.getLogger().warn(`Route discovery failed (attempt ${t}/${this.maxRetries}), retrying in ${a}ms:`,r),await new Promise(n=>setTimeout(n,a))}return""})();this.discoveryPromise=e;try{return await this.discoveryPromise}finally{this.discoveryPromise===e&&(this.discoveryPromise=null)}}async buildUrl(e){const t=await this.discoverPrefix(),r=e.startsWith("/")?e:`/${e}`;return`${this.serverUrl}${t}${r}`}reset(){this.routePrefix=null,this.discoveryPromise=null,this.failedDiscoveryAt=null}}class qe extends Be{constructor(e){super(e,{getLogger:s.getLogger,fetchWithTimeout:s.fetchWithTimeout})}}let Y=null;async function je(){return Y||(Y=(await Promise.resolve().then(()=>require("./WalletManager-ZJbGQHrn.js"))).WalletManager),Y}const z=new Map,V=new Map;function fe(i,e,t,r,a,n){return JSON.stringify({stripePublicKey:i,serverUrl:e,solanaCluster:t,solanaEndpoint:r||"",dangerouslyAllowUnknownMint:a||!1,complianceCheck:n||!1})}async function $e(i,e,t,r,a,n){const o=fe(i,e,t,r,a,n);let c=z.get(o);if(c)return c.refCount++,s.getLogger().debug(`[ManagerCache] Reusing cached managers (refCount: ${c.refCount}):`,{stripePublicKey:i.slice(0,10)+"...",serverUrl:e}),c;const u=V.get(o);if(u)return c=await u,c.refCount++,s.getLogger().debug(`[ManagerCache] Reusing in-flight managers (refCount: ${c.refCount}):`,{stripePublicKey:i.slice(0,10)+"...",serverUrl:e}),c;s.getLogger().debug("[ManagerCache] Creating new manager instances:",{stripePublicKey:i.slice(0,10)+"...",serverUrl:e});const l=(async()=>{const f=new qe(e),d=new Le(i,f,n??!1),g=new Fe(f),y=await je(),m=new y(t,r,a??!1),h=new Ne(i,f),p=new Ae(f),k=new Ue(f);return{stripeManager:d,x402Manager:g,walletManager:m,subscriptionManager:h,subscriptionChangeManager:p,creditsManager:k,routeDiscovery:f,refCount:1}})();V.set(o,l);try{return c=await l,z.set(o,c),c}finally{V.delete(o)}}function ae(i,e,t,r,a,n){const o=fe(i,e,t,r,a,n),c=z.get(o);if(!c){s.getLogger().warn("[ManagerCache] Attempted to release non-existent managers:",{cacheKey:o});return}c.refCount--,s.getLogger().debug(`[ManagerCache] Released manager reference (refCount: ${c.refCount}):`,{stripePublicKey:i.slice(0,10)+"...",serverUrl:e}),c.refCount<=0&&(z.delete(o),s.getLogger().debug("[ManagerCache] Removed managers from cache (refCount reached 0)"))}function We(i){return`CEDROS_FEATURE_${i.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase()}`}function He(i){const e=Object.entries(i).map(([t,r])=>[t,{name:t,description:r.description,default:r.default,stage:r.stage??"experimental",envVar:We(t)}]);return Object.freeze(Object.fromEntries(e))}const A=He({complianceCheck:{description:"Enable pre-flight compliance checks before Stripe checkout.",default:!1,stage:"stable"}}),Z=Object.freeze(Object.keys(A));function Ke(){return typeof process<"u"&&process.env?process.env:{}}function X(i,e){if(i)for(const[t,r]of Object.entries(i)){if(!(t in A))throw new Error(`Unknown feature flag "${t}" in ${e}`);if(typeof r!="boolean")throw new Error(`Feature flag "${t}" in ${e} must be a boolean`)}}function he(i){if(i==null)return;const e=i.trim().toLowerCase();if(e){if(e==="1"||e==="true"||e==="yes"||e==="on")return!0;if(e==="0"||e==="false"||e==="no"||e==="off")return!1}}function ze(i){return A[i]}function Je(){return Z.map(i=>A[i])}function ee(i={}){const e=i.env??Ke();X(i.featureFlags,"featureFlags"),X(i.fallbackFlags,"fallbackFlags");const t={};for(const r of Z){const a=i.featureFlags?.[r],n=i.fallbackFlags?.[r],o=he(e[A[r].envVar]);t[r]=a??n??o??A[r].default}return t}function Ge(i,e={}){return ee(e)[i]}function Ye(i,e="featureFlags"){X(i,e)}const ne=new Set(["mainnet-beta","devnet","testnet"]);function Ve(){if(typeof window<"u"&&window.location)return window.location.origin;throw new Error("serverUrl is required in SSR/Node environments. In browser environments, it defaults to window.location.origin")}function me(i){const e=[];if(i.showCard!==!1){const a=i.stripePublicKey;(typeof a!="string"||a.trim().length===0)&&e.push({field:"stripePublicKey",message:"must be a non-empty string when card payments are enabled (showCard is not false)"})}let r;if(i.serverUrl!==void 0)typeof i.serverUrl!="string"||i.serverUrl.trim().length===0?(e.push({field:"serverUrl",message:"must be a non-empty string when provided"}),r=""):(!i.serverUrl.startsWith("http://")&&!i.serverUrl.startsWith("https://")&&e.push({field:"serverUrl",message:'must start with "http://" or "https://"'}),r=i.serverUrl);else try{r=Ve()}catch(a){e.push({field:"serverUrl",message:a instanceof Error?a.message:"failed to determine default"}),r=""}ne.has(i.solanaCluster)||e.push({field:"solanaCluster",message:`must be one of ${Array.from(ne).join(", ")}`}),i.solanaEndpoint!==void 0&&(typeof i.solanaEndpoint!="string"?e.push({field:"solanaEndpoint",message:"must be a string when provided"}):i.solanaEndpoint.trim().length===0?e.push({field:"solanaEndpoint",message:'must be a non-empty string when provided (e.g., "https://api.mainnet-beta.solana.com")'}):!i.solanaEndpoint.startsWith("http://")&&!i.solanaEndpoint.startsWith("https://")&&e.push({field:"solanaEndpoint",message:'must start with "http://" or "https://" (e.g., "https://api.mainnet-beta.solana.com")'})),i.tokenMint&&typeof i.tokenMint!="string"&&e.push({field:"tokenMint",message:"must be a string when provided"});try{Ye(i.featureFlags,"config.featureFlags")}catch(a){e.push({field:"featureFlags",message:a instanceof Error?a.message:"contains invalid values"})}if(e.length>0){const a=e.map(n=>`- ${n.field} ${n.message}`).join(`
|
|
2
|
+
`);throw new Error(`Invalid Cedros configuration:
|
|
3
|
+
${a}`)}if(i.tokenMint){const a=i.dangerouslyAllowUnknownMint===!0,n=pe.validateTokenMint(i.tokenMint,"CedrosConfig.tokenMint",a);if(!n.isValid&&n.error)throw new Error(n.error);n.warning&&s.getLogger().warn(n.warning)}return{...i,serverUrl:r}}const Qe=Object.freeze({surfaceBackground:"rgba(255, 255, 255, 0)",surfaceText:"#111827",surfaceBorder:"rgba(15, 23, 42, 0.08)",stripeBackground:"linear-gradient(135deg, #635bff 0%, #4f46e5 100%)",stripeText:"#ffffff",stripeShadow:"rgba(79, 70, 229, 0.25)",cryptoBackground:"linear-gradient(135deg, #14f195 0%, #9945ff 100%)",cryptoText:"#ffffff",cryptoShadow:"rgba(99, 102, 241, 0.25)",errorBackground:"#fee2e2",errorBorder:"#fca5a5",errorText:"#b91c1c",successBackground:"#dcfce7",successBorder:"#86efac",successText:"#166534",modalOverlay:"rgba(0, 0, 0, 0.5)",modalBackground:"#ffffff",modalBorder:"rgba(15, 23, 42, 0.08)",buttonBorderRadius:"8px",buttonPadding:"0.75rem 1.5rem",buttonFontSize:"1rem",buttonFontWeight:"600"}),Xe=Object.freeze({surfaceBackground:"rgba(17, 24, 39, 0.6)",surfaceText:"#f9fafb",surfaceBorder:"rgba(148, 163, 184, 0.25)",stripeBackground:"linear-gradient(135deg, #4f46e5 0%, #3730a3 100%)",stripeText:"#f5f3ff",stripeShadow:"rgba(99, 102, 241, 0.35)",cryptoBackground:"linear-gradient(135deg, #1dd4a6 0%, #6d28d9 100%)",cryptoText:"#ecfeff",cryptoShadow:"rgba(75, 85, 99, 0.35)",errorBackground:"#7f1d1d",errorBorder:"#fca5a5",errorText:"#fecaca",successBackground:"#14532d",successBorder:"#4ade80",successText:"#bbf7d0",modalOverlay:"rgba(0, 0, 0, 0.75)",modalBackground:"#1f2937",modalBorder:"rgba(148, 163, 184, 0.25)",buttonBorderRadius:"8px",buttonPadding:"0.75rem 1.5rem",buttonFontSize:"1rem",buttonFontWeight:"600"}),Ze={surfaceBackground:"--cedros-surface-bg",surfaceText:"--cedros-surface-text",surfaceBorder:"--cedros-surface-border",stripeBackground:"--cedros-stripe-bg",stripeText:"--cedros-stripe-text",stripeShadow:"--cedros-stripe-shadow",cryptoBackground:"--cedros-crypto-bg",cryptoText:"--cedros-crypto-text",cryptoShadow:"--cedros-crypto-shadow",errorBackground:"--cedros-error-bg",errorBorder:"--cedros-error-border",errorText:"--cedros-error-text",successBackground:"--cedros-success-bg",successBorder:"--cedros-success-border",successText:"--cedros-success-text",modalOverlay:"--cedros-modal-overlay",modalBackground:"--cedros-modal-bg",modalBorder:"--cedros-modal-border",buttonBorderRadius:"--cedros-button-radius",buttonPadding:"--cedros-button-padding",buttonFontSize:"--cedros-button-font-size",buttonFontWeight:"--cedros-button-font-weight"},ge=b.createContext(null);function et(i,e){return{...i==="dark"?Xe:Qe,...e}}function tt(i){const e=Object.entries(i).map(([t,r])=>[Ze[t],r]);return Object.fromEntries(e)}function rt({initialMode:i="light",overrides:e,unstyled:t=!1,children:r}){const[a,n]=b.useState(i),[o,c]=b.useState(e),u=b.useRef(e);b.useEffect(()=>{if(e===u.current)return;(!e||!u.current?e!==u.current:Object.keys({...e,...u.current}).some(d=>e[d]!==u.current?.[d]))&&(u.current=e,c(e))},[e]);const l=b.useMemo(()=>{const f=et(a,o),d=t?{}:tt(f),g=t?"":`cedros-theme-root cedros-theme cedros-theme--${a}`;return{mode:a,setMode:n,tokens:f,className:g,style:d,unstyled:t}},[a,o,t]);return K.jsx(ge.Provider,{value:l,children:r})}function at(){const i=b.useContext(ge);if(!i)throw new Error("useCedrosTheme must be used within CedrosProvider");return i}const Q={getAdapters:()=>[],cleanup:async()=>{},isInitialized:()=>!1,getId:()=>"stub"};function nt(){return typeof process<"u"&&process.env.NODE_ENV==="development"?0:2}const ye=b.createContext(null);function it({config:i,children:e}){const t=b.useMemo(()=>me(i),[i]),r=b.useMemo(()=>ee({featureFlags:t.featureFlags,fallbackFlags:t.complianceCheck!=null?{complianceCheck:t.complianceCheck}:void 0}),[t.featureFlags,t.complianceCheck]),[a,n]=b.useState(null),[o,c]=b.useState(Q),u=b.useRef(Q);b.useEffect(()=>{let m=!1;return Promise.resolve().then(()=>require("./walletPool-BjTXX6Vn.js")).then(({createWalletPool:h})=>{if(m)return;const p=h();u.current=p,c(p)}).catch(h=>{m||(s.getLogger().error("[CedrosProvider] Wallet pool initialization failed:",h),n("Failed to initialize Cedros provider"))}),()=>{m=!0}},[]);const[l,f]=b.useState(null);b.useEffect(()=>{let m=!1;return Promise.resolve().then(()=>require("./solanaCheck-BS3QTE63.js")).then(({checkSolanaAvailability:h})=>h()).then(h=>{m||(h.available?f(void 0):f(h.error||"Solana dependencies not available"))}).catch(h=>{m||(s.getLogger().warn("[CedrosProvider] Solana availability check failed:",h),f("Unable to verify Solana availability"))}),()=>{m=!0}},[]),b.useEffect(()=>{const m=t.logLevel??nt(),h=s.createLogger({level:m,prefix:"[CedrosPay]"});s.setLogger(h)},[t.logLevel]),b.useEffect(()=>()=>{const m=u.current;m&&m!==Q&&m.cleanup().catch(h=>{s.getLogger().warn("[CedrosProvider] Wallet pool cleanup failed:",h)})},[]);const[d,g]=b.useState(null);b.useEffect(()=>{let m=!1,h=!1;const p=t.stripePublicKey??"",k=t.serverUrl??"",L=t.solanaCluster,x=t.solanaEndpoint,_=t.dangerouslyAllowUnknownMint,N=r.complianceCheck;return $e(p,k,L,x,_,N).then(T=>{if(m){ae(p,k,L,x,_,N);return}h=!0,g(T)}).catch(T=>{m||(s.getLogger().error("[CedrosProvider] Manager initialization failed:",T),n("Failed to initialize Cedros provider"))}),()=>{m=!0,h&&ae(p,k,L,x,_,N)}},[t.stripePublicKey,t.serverUrl,t.solanaCluster,t.solanaEndpoint,t.dangerouslyAllowUnknownMint,r.complianceCheck]);const y=b.useMemo(()=>d?{config:t,featureFlags:r,...d,walletPool:o,solanaError:l}:null,[t,r,d,o,l]);return a?K.jsx("div",{role:"alert",children:a}):K.jsx(rt,{initialMode:t.theme??"light",overrides:t.themeOverrides,unstyled:t.unstyled??!1,children:y?K.jsx(ye.Provider,{value:y,children:e}):null})}function ot(){const i=b.useContext(ye);if(!i)throw new Error("useCedrosContext must be used within CedrosProvider");return i}exports.CIRCUIT_BREAKER_PRESETS=ke;exports.CedrosProvider=it;exports.CircuitBreakerOpenError=w;exports.CircuitState=ue;exports.ERROR_CATEGORIES=de;exports.FEATURE_FLAG_NAMES=Z;exports.FEATURE_FLAG_REGISTRY=A;exports.PaymentError=F;exports.RATE_LIMITER_PRESETS=D;exports.RETRY_PRESETS=E;exports.createCircuitBreaker=B;exports.createRateLimiter=O;exports.formatError=M;exports.getFeatureFlagDefinition=ze;exports.getFeatureFlagDefinitions=Je;exports.getUserFriendlyError=le;exports.isFeatureEnabled=Ge;exports.parseErrorResponse=v;exports.parseFeatureFlagBoolean=he;exports.resolveFeatureFlags=ee;exports.retryWithBackoff=C;exports.useCedrosContext=ot;exports.useCedrosTheme=at;exports.validateConfig=me;
|