@cedros/pay-react 1.1.28 → 1.1.29

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.
Files changed (172) hide show
  1. package/dist/{AISettingsSection-DELur7D2.js → AISettingsSection-B7qrycfY.js} +2 -2
  2. package/dist/{AISettingsSection-BlIv3CzS.mjs → AISettingsSection-DtAgMsDw.mjs} +6 -4
  3. package/dist/{AutosaveIndicator-Bed0-ekg.mjs → AutosaveIndicator-BEvABoKU.mjs} +1 -1
  4. package/dist/AutosaveIndicator-DiyeAg93.js +1 -0
  5. package/dist/CedrosContext-5Gjveoba.mjs +2555 -0
  6. package/dist/CedrosContext-CCakH2SZ.js +3 -0
  7. package/dist/CedrosPayAdminDashboard-CAwEvn66.js +1 -0
  8. package/dist/CedrosPayAdminDashboard-CBuvNAtB.mjs +250 -0
  9. package/dist/{ChatLogsSection-v4zwzCTC.mjs → ChatLogsSection-Ber5o8hF.mjs} +19 -17
  10. package/dist/ChatLogsSection-DLxMMi9I.js +1 -0
  11. package/dist/ComplianceSection-Buu0zTiL.js +1 -0
  12. package/dist/{ComplianceSection-CemgfDrL.mjs → ComplianceSection-ZCr0wsvw.mjs} +18 -15
  13. package/dist/{CryptoButton-BV9owVe2.mjs → CryptoButton-Cl2kZbOP.mjs} +26 -24
  14. package/dist/CryptoButton-DxFCYDlJ.js +1 -0
  15. package/dist/CustomersSection-BywmMLur.js +1 -0
  16. package/dist/{CustomersSection-D_j7OrfS.mjs → CustomersSection-D9UknSKC.mjs} +21 -19
  17. package/dist/{DisputesSection-BcAbXp3K.mjs → DisputesSection-C_eySK-W.mjs} +19 -17
  18. package/dist/DisputesSection-DwkHGv2a.js +1 -0
  19. package/dist/Dropdown-B90Zabxr.mjs +111 -0
  20. package/dist/Dropdown-CtY91emj.js +1 -0
  21. package/dist/ErrorBanner-CZXsHi3H.mjs +22 -0
  22. package/dist/ErrorBanner-Cx2dUhps.js +1 -0
  23. package/dist/{FAQSection-Dn38OhB_.mjs → FAQSection-Bv_Hdt8B.mjs} +8 -6
  24. package/dist/FAQSection-DlPLnIJD.js +1 -0
  25. package/dist/ImagesSection-B4Jzet79.js +1 -0
  26. package/dist/{ImagesSection-Ctw9Icym.mjs → ImagesSection-DpdXQ6qu.mjs} +6 -4
  27. package/dist/InventorySection-BgRdpn1l.js +1 -0
  28. package/dist/{InventorySection-DmhjUlRZ.mjs → InventorySection-DZMu9DMw.mjs} +25 -23
  29. package/dist/MessagingSection-CxV-pf-f.js +1 -0
  30. package/dist/{MessagingSection-B1FaGxkp.mjs → MessagingSection-D_cOBfFt.mjs} +5 -4
  31. package/dist/OrdersSection-BbAX79Ff.js +1 -0
  32. package/dist/{OrdersSection-Bj8bPdg8.mjs → OrdersSection-wfPavit9.mjs} +27 -24
  33. package/dist/PaymentSettingsSection-BdBDgaRg.js +1 -0
  34. package/dist/PaymentSettingsSection-DunzBo9n.mjs +648 -0
  35. package/dist/ReturnsSection-7k4LZ8yp.js +1 -0
  36. package/dist/{ReturnsSection-BC0L8r2e.mjs → ReturnsSection-B4FL7bUv.mjs} +11 -9
  37. package/dist/{SettingsSection-vdYFSNxB.js → SettingsSection-Cz2Yjdhr.js} +1 -1
  38. package/dist/{SettingsSection-KYdEizq_.mjs → SettingsSection-DoeNDbqd.mjs} +1 -1
  39. package/dist/{ShippingSection-BOgto6_9.mjs → ShippingSection-BlVsYC6B.mjs} +5 -3
  40. package/dist/ShippingSection-C-HI8rOb.js +1 -0
  41. package/dist/{SingleCategorySettings-suJ8z9d8.mjs → SingleCategorySettings-B406nnF-.mjs} +143 -140
  42. package/dist/SingleCategorySettings-BqC2UXt3.js +3 -0
  43. package/dist/StatsBar-D4v-I_Dj.mjs +25 -0
  44. package/dist/StatsBar-m6GSRNxs.js +1 -0
  45. package/dist/StorefrontSection-Axvh_KeS.js +1 -0
  46. package/dist/{StorefrontSection-BRvIGBEJ.mjs → StorefrontSection-BK_rhrAi.mjs} +121 -119
  47. package/dist/{SubscriptionsSection-D60qrX9a.mjs → SubscriptionsSection-D8V9RBv-.mjs} +11 -9
  48. package/dist/SubscriptionsSection-EeULMWIB.js +1 -0
  49. package/dist/{TaxSection-C7-pv-Rl.mjs → TaxSection-Cj6TXL6x.mjs} +23 -21
  50. package/dist/TaxSection-CzHPhaHl.js +1 -0
  51. package/dist/ThemeContext-CFXyYx7A.js +1 -0
  52. package/dist/ThemeContext-l0bqcOGW.mjs +126 -0
  53. package/dist/Token22Section-DqRKVG_G.js +1 -0
  54. package/dist/{Token22Section-CrHLQ0EB.mjs → Token22Section-DtYAcT54.mjs} +7 -6
  55. package/dist/{WalletManager-BIwH8Dw_.mjs → WalletManager-D-eoqUDy.mjs} +21 -19
  56. package/dist/WalletManager-DXChB9LA.js +1 -0
  57. package/dist/WebhooksSection-D--iPZuM.js +1 -0
  58. package/dist/{WebhooksSection-COPW4Ec0.mjs → WebhooksSection-DBAIxtBy.mjs} +40 -38
  59. package/dist/admin.d.ts +2 -0
  60. package/dist/admin.js +1 -0
  61. package/dist/admin.mjs +8 -0
  62. package/dist/configApi-BS5UJfzm.js +1 -0
  63. package/dist/{configApi-6XhAJGKX.mjs → configApi-BUXZOMWK.mjs} +57 -3
  64. package/dist/crypto-only.js +1 -1
  65. package/dist/crypto-only.mjs +214 -202
  66. package/dist/dateHelpers-BKW_lGND.js +1 -0
  67. package/dist/dateHelpers-yvPkofYQ.mjs +6 -0
  68. package/dist/fetchWithTimeout-CG0EKbhf.js +1 -0
  69. package/dist/fetchWithTimeout-DmMOwL0Q.mjs +195 -0
  70. package/dist/index-9QF_UfSN.mjs +18668 -0
  71. package/dist/index-Cq9ya93W.js +84 -0
  72. package/dist/index.js +1 -1
  73. package/dist/index.mjs +74 -64
  74. package/dist/safeHref-DqJPLPl5.mjs +12 -0
  75. package/dist/safeHref-DyHIpVjY.js +1 -0
  76. package/dist/sectionIds-B_tFiNvF.js +1 -0
  77. package/dist/sectionIds-DBavltrL.mjs +359 -0
  78. package/dist/sections-BHph7CYj.mjs +9 -0
  79. package/dist/sections-C2zEJr5G.js +1 -0
  80. package/dist/sections-more-C1VNVwkp.js +1 -0
  81. package/dist/sections-more-CMFgfU4d.mjs +3082 -0
  82. package/dist/src/admin/index.d.ts +3 -3
  83. package/dist/src/admin/index.d.ts.map +1 -1
  84. package/dist/src/admin/plugin.d.ts.map +1 -1
  85. package/dist/src/admin/types.d.ts +2 -6
  86. package/dist/src/admin/types.d.ts.map +1 -1
  87. package/dist/src/admin.d.ts +9 -0
  88. package/dist/src/admin.d.ts.map +1 -0
  89. package/dist/src/components/admin/LazyCedrosPayAdminDashboard.d.ts +4 -0
  90. package/dist/src/components/admin/LazyCedrosPayAdminDashboard.d.ts.map +1 -0
  91. package/dist/src/components/admin/PaymentReadinessChecklist.d.ts +9 -0
  92. package/dist/src/components/admin/PaymentReadinessChecklist.d.ts.map +1 -0
  93. package/dist/src/components/admin/PaymentSettingsSection.d.ts.map +1 -1
  94. package/dist/src/components/admin/PaymentSetupGuide.d.ts +6 -0
  95. package/dist/src/components/admin/PaymentSetupGuide.d.ts.map +1 -0
  96. package/dist/src/components/admin/ProductsSection.d.ts.map +1 -1
  97. package/dist/src/components/admin/configApi.d.ts +1 -1
  98. package/dist/src/components/admin/configApi.d.ts.map +1 -1
  99. package/dist/src/components/admin/icons.d.ts +3 -50
  100. package/dist/src/components/admin/icons.d.ts.map +1 -1
  101. package/dist/src/components/admin/index.d.ts +1 -1
  102. package/dist/src/components/admin/index.d.ts.map +1 -1
  103. package/dist/src/components/admin/types.d.ts +43 -0
  104. package/dist/src/components/admin/types.d.ts.map +1 -1
  105. package/dist/src/context/CedrosContext.d.ts +2 -0
  106. package/dist/src/context/CedrosContext.d.ts.map +1 -1
  107. package/dist/src/ecommerce/__tests__/featureFlags.test.d.ts +2 -0
  108. package/dist/src/ecommerce/__tests__/featureFlags.test.d.ts.map +1 -0
  109. package/dist/src/ecommerce/adapters/paywall/paywallAdapter.d.ts.map +1 -1
  110. package/dist/src/ecommerce/components/general/ErrorBoundary.d.ts +1 -1
  111. package/dist/src/ecommerce/components/ui/button.d.ts +1 -1
  112. package/dist/src/ecommerce/components/ui/sheet.d.ts +1 -1
  113. package/dist/src/ecommerce/config/context.d.ts +2 -0
  114. package/dist/src/ecommerce/config/context.d.ts.map +1 -1
  115. package/dist/src/ecommerce/config/types.d.ts +2 -0
  116. package/dist/src/ecommerce/config/types.d.ts.map +1 -1
  117. package/dist/src/ecommerce/index.d.ts +2 -0
  118. package/dist/src/ecommerce/index.d.ts.map +1 -1
  119. package/dist/src/featureFlags.d.ts +41 -0
  120. package/dist/src/featureFlags.d.ts.map +1 -0
  121. package/dist/src/index.d.ts +4 -2
  122. package/dist/src/index.d.ts.map +1 -1
  123. package/dist/src/managers/StripeManager.d.ts.map +1 -1
  124. package/dist/src/managers/SubscriptionManager.d.ts +1 -0
  125. package/dist/src/managers/SubscriptionManager.d.ts.map +1 -1
  126. package/dist/src/types/index.d.ts +14 -1
  127. package/dist/src/types/index.d.ts.map +1 -1
  128. package/dist/src/types/subscription.d.ts +47 -1
  129. package/dist/src/types/subscription.d.ts.map +1 -1
  130. package/dist/src/utils/validateConfig.d.ts.map +1 -1
  131. package/dist/stripe-only.js +1 -1
  132. package/dist/stripe-only.mjs +35 -33
  133. package/dist/styles--fxb3lCl.js +1 -0
  134. package/dist/{styles-D4SQkuV3.mjs → styles-DGagylUj.mjs} +53 -51
  135. package/dist/testing/index.js +1 -1
  136. package/dist/testing/index.mjs +1 -1
  137. package/dist/tokenMintValidator-DAjQld0r.mjs +98 -0
  138. package/dist/tokenMintValidator-DNBhoefh.js +4 -0
  139. package/dist/{walletPool-DE-t1wSW.mjs → walletPool-9MylB2QK.mjs} +1 -1
  140. package/dist/walletPool-BjTXX6Vn.js +1 -0
  141. package/package.json +3 -3
  142. package/dist/AutosaveIndicator-Dn_qA2hK.js +0 -1
  143. package/dist/CedrosContext-C2RjHLaQ.js +0 -6
  144. package/dist/CedrosContext-CY6zvjvJ.mjs +0 -2801
  145. package/dist/ChatLogsSection-BH5tLA4T.js +0 -1
  146. package/dist/ComplianceSection-DP2a9-S0.js +0 -1
  147. package/dist/CryptoButton-DpiCnyXE.js +0 -1
  148. package/dist/CustomersSection-CBwy_waO.js +0 -1
  149. package/dist/DisputesSection-BLjIk60n.js +0 -1
  150. package/dist/FAQSection-wNeH0i6Q.js +0 -1
  151. package/dist/ImagesSection-0ZzKlzMJ.js +0 -1
  152. package/dist/InventorySection-zV6lTmue.js +0 -1
  153. package/dist/MessagingSection-B_wdFR0j.js +0 -1
  154. package/dist/OrdersSection-Dw2FX-1d.js +0 -1
  155. package/dist/PaymentSettingsSection-BYF4D-GR.js +0 -1
  156. package/dist/PaymentSettingsSection-EnMxeWjv.mjs +0 -94
  157. package/dist/ReturnsSection-D_pJVxuG.js +0 -1
  158. package/dist/ShippingSection-1DRSTu49.js +0 -1
  159. package/dist/SingleCategorySettings-DwCnBdRf.js +0 -3
  160. package/dist/StorefrontSection-RumGkb3C.js +0 -1
  161. package/dist/SubscriptionsSection-C2aLLn7L.js +0 -1
  162. package/dist/TaxSection-Dt1DnM51.js +0 -1
  163. package/dist/Token22Section-DY3mUwTY.js +0 -1
  164. package/dist/WalletManager-B3UdQ5pQ.js +0 -1
  165. package/dist/WebhooksSection-CKeiJ7Py.js +0 -1
  166. package/dist/configApi-DkduMQg1.js +0 -1
  167. package/dist/index-C0g-JxJk.js +0 -84
  168. package/dist/index-DXnuQp5x.mjs +0 -22128
  169. package/dist/sections-C1NpK7hk.mjs +0 -9
  170. package/dist/sections-DVVSZBhW.js +0 -1
  171. package/dist/styles-BT4bhFey.js +0 -1
  172. package/dist/walletPool-IS7R3MR1.js +0 -1
@@ -0,0 +1,3 @@
1
+ "use strict";const G=require("react/jsx-runtime"),S=require("react"),k=require("./uuid-C5B8o31X.js"),s=require("./fetchWithTimeout-CG0EKbhf.js"),ge=require("./ThemeContext-CFXyYx7A.js"),pe=require("./tokenMintValidator-DNBhoefh.js");var ne="https://js.stripe.com/v3",we=/^https:\/\/js\.stripe\.com\/v3\/?(\?.*)?$/;var ve=function(){for(var e=document.querySelectorAll('script[src^="'.concat(ne,'"]')),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(ne).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})},$=null,W=null,H=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 $!==null?$:($=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&&H!==null&&W!==null){var i;a.removeEventListener("load",H),a.removeEventListener("error",W),(i=a.parentNode)===null||i===void 0||i.removeChild(a),a=te(e)}}H=Ce(t,r),W=Ee(r),a.addEventListener("load",H),a.addEventListener("error",W)}catch(o){r(o);return}}),$.catch(function(t){return $=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(n){oe||console.warn(n)});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(i){return Te(i,t,a)})};function D(n,e){return n instanceof Error?n.message:typeof n=="string"?n: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(n,e,t=!1){const r=typeof n.clone=="function",a=r?n.clone():void 0;try{const i=await n.json();if(t&&i.verificationError){s.getLogger().debug(`Payment verification failed: ${i.verificationError.code}`);const o=i.verificationError.code;return Se[o]||i.verificationError.message||e}return typeof i.error=="string"?i.error:i.error&&typeof i.error=="object"&&"message"in i.error?i.error.message:e}catch{if(a)try{const i=await a.text();if(i)return i}catch{}if(!r&&typeof n.text=="function")try{const i=await n.text();if(i)return i}catch{}return e}}function L(n){const{maxRequests:e,windowMs:t}=n;let r=e,a=Date.now();const i=e/t;function o(){const h=Date.now(),y=h-a;if(y>0){const g=y*i;r=Math.min(e,r+g),a=h}}function c(){return o(),r>=1?(r-=1,!0):!1}function l(){return o(),Math.floor(r)}function u(){if(o(),r>=1)return 0;const y=(1-r)/i;return Math.ceil(y)}function f(){r=e,a=Date.now()}return{tryConsume:c,getAvailableTokens:l,getTimeUntilRefill:u,reset:f}}const x={PAYMENT:{maxRequests:10,windowMs:6e4},QUOTE:{maxRequests:30,windowMs:6e4},STRICT:{maxRequests:5,windowMs:6e4},PERMISSIVE:{maxRequests:100,windowMs:6e4}};var le=(n=>(n.CLOSED="CLOSED",n.OPEN="OPEN",n.HALF_OPEN="HALF_OPEN",n))(le||{});class w extends Error{constructor(e){super(e),this.name="CircuitBreakerOpenError"}}function q(n){const{failureThreshold:e,timeout:t,failureWindow:r=t*2,name:a="circuit-breaker"}=n;let i="CLOSED",o=[],c=0,l=0,u=null,f=null,h=null,y=!1;function g(){const P=Date.now()-r;o=o.filter(C=>C>P)}function m(){i==="OPEN"&&h!==null&&Date.now()>=h&&(s.getLogger().debug(`[CircuitBreaker:${a}] Transitioning OPEN → HALF_OPEN (timeout expired)`),i="HALF_OPEN",h=null)}function d(){f=Date.now(),c++,i==="HALF_OPEN"?(s.getLogger().debug(`[CircuitBreaker:${a}] Success in HALF_OPEN → CLOSED`),i="CLOSED",o=[]):i==="CLOSED"&&(o=[])}function p(P){const C=Date.now();u=C,o.push(C),g();const U=o.length;s.getLogger().warn(`[CircuitBreaker:${a}] Failure recorded (${U}/${e}):`,P.message),i==="HALF_OPEN"?(s.getLogger().warn(`[CircuitBreaker:${a}] Failed in HALF_OPEN → OPEN`),i="OPEN",h=C+t):i==="CLOSED"&&U>=e&&(s.getLogger().error(`[CircuitBreaker:${a}] Failure threshold reached (${U}) → OPEN`),i="OPEN",h=C+t)}async function R(P){if(m(),i==="OPEN"){l++;const C=h?Math.ceil((h-Date.now())/1e3):0;throw new w(`Circuit breaker is OPEN. Service is unavailable. Retry in ${C}s.`)}if(i==="HALF_OPEN"&&y)throw l++,new w("Circuit breaker is HALF_OPEN. A probe request is already in progress.");i==="HALF_OPEN"&&(y=!0);try{const C=await P();return d(),C}catch(C){throw p(C instanceof Error?C:new Error(String(C))),C}finally{y&&(y=!1)}}function O(){return m(),i}function I(){return m(),g(),{state:i,failures:o.length,successes:c,rejections:l,lastFailureTime:u,lastSuccessTime:f}}function _(){s.getLogger().debug(`[CircuitBreaker:${a}] Manual reset → CLOSED`),i="CLOSED",o=[],c=0,l=0,u=null,f=null,h=null}function A(){s.getLogger().warn(`[CircuitBreaker:${a}] Manual trip → OPEN`),i="OPEN",h=Date.now()+t}return{execute:R,getState:O,getStats:I,reset:_,trip:A}}const Re={STRICT:{failureThreshold:3,timeout:6e4},STANDARD:{failureThreshold:5,timeout:3e4},LENIENT:{failureThreshold:10,timeout:15e3}},ke={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 ue(n){return ke[n]||{message:"An unexpected error occurred",action:"Please try again or contact support if this continues.",technicalHint:`Unknown error code: ${n}`}}class F extends Error{code;retryable;details;httpStatus;constructor(e,t,r=!1,a,i){super(t),this.name="PaymentError",this.code=e,this.retryable=r,this.details=a,this.httpStatus=i,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 ue(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,B=new Map;function _e(n){if(!n)return;const e=Number(n);if(Number.isFinite(e)&&e>=0)return Math.min(e*1e3,re);const t=Date.parse(n);if(!Number.isNaN(t))return Math.min(Math.max(t-Date.now(),0),re)}class T extends Error{httpStatus;retryAfterMs;constructor(e,t,r){super(e),this.name="RetryableHttpError",this.httpStatus=t,this.retryAfterMs=r,Object.setPrototypeOf(this,T.prototype)}static fromResponse(e,t){const r=e.headers&&typeof e.headers.get=="function"?e.headers.get("Retry-After"):null;return new T(t,e.status,_e(r))}}function Ie(n){if(n instanceof F||n instanceof T)return n.httpStatus}function Me(n){if(n instanceof T)return n.retryAfterMs}function De(n,e){const t=Ie(n);if(t!=null){const a=t;return a===429||a>=500&&a<600}const r=n.message.toLowerCase();return!!(r.includes("network")||r.includes("timeout")||r.includes("fetch failed")||r.includes("econnrefused"))}function Le(n,e,t,r,a){const i=e*Math.pow(t,n),o=Math.min(i,r);return Math.floor(a?o*.5+Math.random()*o*.5:o)}function xe(n){return new Promise(e=>setTimeout(e,n))}async function E(n,e={}){const{maxRetries:t=3,initialDelayMs:r=1e3,backoffFactor:a=2,maxDelayMs:i=3e4,jitter:o=!0,shouldRetry:c=De,name:l="retry",inFlightKey:u}=e,f=async()=>{let g=null,m=0;for(let d=0;d<=t;d++)try{const p=await n();return d>0&&s.getLogger().debug(`[Retry:${l}] Succeeded on attempt ${d+1}/${t+1} after ${m}ms`),p}catch(p){g=p instanceof Error?p:new Error(String(p));const R=d===t,O=c(g,d);if(R||!O)throw s.getLogger().warn(`[Retry:${l}] Failed on attempt ${d+1}/${t+1}. ${R?"No more retries.":"Error not retryable."}`),g;const _=Me(g)??Le(d,r,a,i,o);m+=_,s.getLogger().warn(`[Retry:${l}] Attempt ${d+1}/${t+1} failed: ${g.message}. Retrying in ${_}ms...`),await xe(_)}throw g||new Error("Retry failed with no error")};if(!u)return f();const h=B.get(u);if(h)return h;const y=f().finally(()=>{B.get(u)===y&&B.delete(u)});return B.set(u,y),y}const b={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 Oe{stripe=null;initPromise=null;publicKey;routeDiscovery;complianceCheckEnabled;rateLimiter=L(x.PAYMENT);circuitBreaker=q({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=k.generateUUID(),r=JSON.stringify(e);try{return await this.circuitBreaker.execute(async()=>await E(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 i=await s.fetchWithTimeout(a,{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":t},body:r});if(!i.ok){const o=await v(i,"Failed to create Stripe session");throw T.fromResponse(i,o)}return await i.json()},{...b.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:D(t,"Unknown error")}}}async processCartCheckout(e){const{items:t,successUrl:r,cancelUrl:a,metadata:i,customerEmail:o,customerName:c,customerPhone:l,shippingAddress:u,billingAddress:f,couponCode:h,tipAmount:y,shippingMethodId:g,paymentMethodId:m}=e,d=t.map(P=>P.resource),p=await this.runComplianceCheck(d);if(p)return p;if(!this.rateLimiter.tryConsume())return{success:!1,error:"Rate limit exceeded for cart checkout. Please try again later."};const R=k.generateUUID(),I=JSON.stringify({items:t,metadata:i,coupon:h,couponCode:h}),_=k.generateUUID(),A={items:t,metadata:i,cartId:"",successUrl:r,cancelUrl:a,customerEmail:o,customerName:c,customerPhone:l,shippingAddress:u,billingAddress:f,coupon:h,couponCode:h,tipAmount:y,shippingMethodId:g,paymentMethodId:m};try{const P=await this.circuitBreaker.execute(async()=>{const C=await E(async()=>{const z=await this.routeDiscovery.buildUrl("/paywall/v1/cart/quote"),M=await s.fetchWithTimeout(z,{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":R},body:I});if(!M.ok){const J=await v(M,"Failed to create cart quote");throw T.fromResponse(M,J)}return await M.json()},{...b.IDEMPOTENT_WRITE,name:"stripe-cart-quote",inFlightKey:`stripe:cart-quote:${I}`});if(!C.cartId)throw new Error("Invalid cart quote response: missing cartId");const U=JSON.stringify({...A,cartId:C.cartId});return await E(async()=>{const z=await this.routeDiscovery.buildUrl("/paywall/v1/cart/checkout"),M=await s.fetchWithTimeout(z,{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":_},body:U});if(!M.ok){const J=await v(M,"Failed to create cart checkout session");throw T.fromResponse(M,J)}return await M.json()},{...b.IDEMPOTENT_WRITE,name:"stripe-cart-checkout",inFlightKey:`stripe:cart-checkout:${U}`})});return await this.redirectToCheckout(P.sessionId)}catch(P){return P instanceof w?{success:!1,error:"Stripe payment service is temporarily unavailable. Please try again in a few moments."}:{success:!1,error:D(P,"Cart checkout failed")}}}}class Fe{routeDiscovery;quoteRateLimiter=L(x.QUOTE);verifyRateLimiter=L(x.PAYMENT);circuitBreaker=q({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 E(async()=>{const a="/paywall/v1/quote";s.getLogger().debug("[X402Manager] Requesting quote",r?"with coupon":"without coupon");const i=await this.routeDiscovery.buildUrl(a),o=await s.fetchWithTimeout(i,{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 l=c.crypto;if(!this.validateRequirement(l))throw new Error("Invalid x402 requirement received from server: missing required fields");return l}else if(c.accepts&&c.accepts.length>0){const l=c.accepts[0];if(!this.validateRequirement(l))throw new Error("Invalid x402 requirement received from server: missing required fields");return l}else throw new Error("Invalid x402 response: missing crypto or accepts field")},{...b.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 i=k.generateUUID();try{return await this.circuitBreaker.execute(async()=>await E(async()=>{const o=await this.routeDiscovery.buildUrl("/paywall/v1/cart/quote"),c={items:t,metadata:r,coupon:a,couponCode:a},l=await s.fetchWithTimeout(o,{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":i},body:JSON.stringify(c)});if(l.status!==402&&!l.ok){const f=await v(l,"Failed to get cart quote");throw new Error(f)}const u=await l.json();if(!u.cartId||!u.quote)throw new Error("Invalid cart quote response: missing cartId or quote");if(u.quote.crypto&&!this.validateRequirement(u.quote.crypto))throw new Error("Invalid x402 cart quote: missing required fields in crypto quote");return u},{...b.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:i,resourceType:o="regular"}=e;if(!this.verifyRateLimiter.tryConsume())return{success:!1,error:"Rate limit exceeded for payment verification. Please try again later."};const c=k.generateUUID();try{return await this.circuitBreaker.execute(async()=>await E(async()=>{const u={...r,payload:{...r.payload,resource:t,resourceType:o,metadata:{...r.payload.metadata||{},...i||{},...a?{couponCode:a}:{}}}},f=this.buildPaymentHeader(u),h="/paywall/v1/verify";s.getLogger().debug("[X402Manager] Submitting payment",{resourceType:o,hasCoupon:!!a,hasMetadata:!!i});const y=await this.routeDiscovery.buildUrl(h),g=await s.fetchWithTimeout(y,{method:"POST",headers:{"Content-Type":"application/json","X-PAYMENT":f,"Idempotency-Key":c}});if(g.ok){const{settlement:d,transactionId:p}=await this.handlePaymentVerification(g,r.payload.signature);return{success:!0,transactionId:p,settlement:d||void 0}}return{success:!1,error:await v(g,"Payment verification failed",!0)}},{maxRetries:0,initialDelayMs:0,backoffFactor:1,maxDelayMs:0,name:"x402-verify"}))}catch(l){return l instanceof w?{success:!1,error:"Payment verification service is temporarily unavailable. Please try again in a few moments."}:{success:!1,error:D(l,"Unknown error")}}}async buildGaslessTransaction(e){const{resourceId:t,userWallet:r,feePayer:a,couponCode:i}=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 E(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:i})});if(!c.ok){const l=await v(c,"Failed to build gasless transaction");throw new Error(l)}return await c.json()},{...b.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:i,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 l=k.generateUUID();try{return await this.circuitBreaker.execute(async()=>await E(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:{...i||{},...a?{couponCode:a}:{}}}},h=this.buildPaymentHeader(f),g=await this.routeDiscovery.buildUrl("/paywall/v1/verify"),m=await s.fetchWithTimeout(g,{method:"POST",headers:{"Content-Type":"application/json","X-PAYMENT":h,"Idempotency-Key":l}});if(m.ok){const{settlement:p,transactionId:R}=await this.handlePaymentVerification(m,"gasless-tx");return{success:!0,transactionId:R,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(u){return u instanceof w?{success:!1,error:"Gasless transaction verification service is temporarily unavailable. Please try again in a few moments."}:{success:!1,error:D(u,"Unknown error")}}}async handlePaymentVerification(e,t){const r=this.parseSettlementResponse(e),a=e.headers.get("Content-Type")||"";let i=t;if(a.includes("application/json"))try{i=(await e.json()).signature||t}catch(o){s.getLogger().warn("Failed to parse JSON response body:",o)}return{settlement:r,transactionId:i}}validateRequirement(e){return!!(e.scheme&&e.network&&e.maxAmountRequired&&e.resource&&e.payTo&&e.asset&&e.maxTimeoutSeconds>0)}}class Ae{stripe=null;initPromise=null;publicKey;routeDiscovery;sessionRateLimiter=L(x.PAYMENT);statusRateLimiter=L(x.QUOTE);circuitBreaker=q({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,i=b.STANDARD){if(!e.tryConsume())throw new Error("Rate limit exceeded. Please try again later.");try{return await this.circuitBreaker.execute(()=>E(t,{...i,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=k.generateUUID(),r=JSON.stringify(e);try{return await this.circuitBreaker.execute(async()=>await E(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 i=await s.fetchWithTimeout(a,{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":t},body:r});if(!i.ok){const o=await v(i,"Failed to create subscription session");throw T.fromResponse(i,o)}return await i.json()},{...b.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:D(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 E(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 i=await v(a,"Failed to check subscription status");throw new Error(i)}return await a.json()},{...b.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 E(async()=>{const a=await this.routeDiscovery.buildUrl("/paywall/v1/subscription/quote"),i={resource:e,interval:t,couponCode:r?.couponCode,intervalDays:r?.intervalDays};s.getLogger().debug("[SubscriptionManager] Requesting subscription quote:",i);const o=await s.fetchWithTimeout(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(o.status!==402&&!o.ok){const c=await v(o,"Failed to get subscription quote");throw new Error(c)}return await o.json()},{...b.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 T.fromResponse(a,await v(a,"Failed to activate"));return await a.json()},"subscription-activate","activation",{...b.IDEMPOTENT_WRITE,inFlightKey:`subscription:activate:${t}`})}}class Ne{routeDiscovery;rateLimiter=L(x.PAYMENT);queryRateLimiter=L(x.QUOTE);circuitBreaker=q({failureThreshold:5,timeout:1e4,name:"subscription-change-manager"});constructor(e){this.routeDiscovery=e}async executeWithResilience(e,t,r,a,i=b.STANDARD){if(!e.tryConsume())throw new Error("Rate limit exceeded. Please try again later.");try{return await this.circuitBreaker.execute(()=>E(t,{...i,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=k.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 i=await s.fetchWithTimeout(a,{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":t},body:r});if(!i.ok)throw T.fromResponse(i,await v(i,"Failed to change subscription"));return await i.json()},"subscription-change","plan change",{...b.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 i=await s.fetchWithTimeout(a,{method:"GET",headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(await v(i,"Failed to get subscription details"));return await i.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 T.fromResponse(a,await v(a,"Failed to cancel subscription"));return await a.json()},"subscription-cancel","cancellation",{...b.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 T.fromResponse(a,await v(a,"Failed to get billing portal URL"));return await a.json()},"subscription-portal","portal",{...b.WRITE_ONCE,inFlightKey:`subscription:portal:${t}`})}}class Ue{routeDiscovery;rateLimiter=L(x.PAYMENT);circuitBreaker=q({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 E(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 i=await v(a,"Failed to get credits quote");throw new Error(i)}return null},{...b.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 E(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 i=await v(a,"Failed to get cart credits quote");throw new Error(i)},{...b.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 i=k.generateUUID(),o=JSON.stringify({resource:t,couponCode:r});try{return await this.circuitBreaker.execute(async()=>await E(async()=>{const c=await this.routeDiscovery.buildUrl("/paywall/v1/credits/hold");s.getLogger().debug("[CreditsManager] Creating hold");const l=await s.fetchWithTimeout(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`,"Idempotency-Key":i},body:o});if(!l.ok){const u=await v(l,"Failed to create credits hold");throw T.fromResponse(l,u)}return await l.json()},{...b.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=k.generateUUID();try{return await this.circuitBreaker.execute(async()=>await E(async()=>{const i=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(i,{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 T.fromResponse(o,c)}return await o.json()},{...b.IDEMPOTENT_WRITE,name:"credits-create-cart-hold",inFlightKey:`credits:create-cart-hold:${r}:${t}`}))}catch(i){throw i instanceof w?new Error("Credits service is temporarily unavailable. Please try again in a few moments."):i}}async authorizePayment(e){const{resource:t,holdId:r,couponCode:a,authToken:i,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=k.generateUUID(),l=JSON.stringify({resource:t,holdId:r,couponCode:a,...o&&{metadata:o}});try{return await this.circuitBreaker.execute(async()=>await E(async()=>{const u=await this.routeDiscovery.buildUrl("/paywall/v1/credits/authorize");s.getLogger().debug("[CreditsManager] Authorizing payment");const f=await s.fetchWithTimeout(u,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`,"Idempotency-Key":c},body:l});if(!f.ok){const y=await f.json().catch(()=>({}));throw T.fromResponse(f,y.error?.message||"Credits authorization failed")}return{success:!0,transactionId:(await f.json()).transactionId}},{...b.IDEMPOTENT_WRITE,name:"credits-authorize",inFlightKey:`credits:authorize:${i}:${l}`}))}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:D(u,"Credits authorization failed"),errorCode:"authorization_failed"}}}async authorizeCartPayment(e){const{cartId:t,holdId:r,authToken:a,metadata:i}=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=k.generateUUID(),c=JSON.stringify({holdId:r,...i&&{metadata:i}});try{return await this.circuitBreaker.execute(async()=>await E(async()=>{const l=await this.routeDiscovery.buildUrl(`/paywall/v1/cart/${encodeURIComponent(t)}/credits/authorize`);s.getLogger().debug("[CreditsManager] Authorizing cart payment for cart:",t);const u=await s.fetchWithTimeout(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`,"Idempotency-Key":o},body:c});if(!u.ok){const h=await u.json().catch(y=>(s.getLogger().error("[CreditsManager] Failed to parse error response JSON:",y,{cartId:t,status:u.status,statusText:u.statusText}),{}));throw T.fromResponse(u,h.error?.message||"Cart credits authorization failed")}return{success:!0,transactionId:(await u.json()).transactionId}},{...b.IDEMPOTENT_WRITE,name:"credits-cart-authorize",inFlightKey:`credits:cart-authorize:${a}:${t}:${c}`}))}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:D(l,"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":k.generateUUID()}});if(!a.ok){const i=await v(a,"Failed to release credits hold");throw new Error(i)}})}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 i=null;try{i=(await this.createHold({resource:e,couponCode:r,authToken:t})).holdId;const c=await this.authorizePayment({resource:e,holdId:i,couponCode:r,authToken:t,metadata:a});if(!c.success&&i)try{await this.releaseHold(i,t)}catch(l){s.getLogger().warn("[CreditsManager] Failed to release hold after auth failure:",l)}return{success:c.success,transactionId:c.transactionId,error:c.error}}catch(o){if(i)try{await this.releaseHold(i,t)}catch(c){s.getLogger().warn("[CreditsManager] Failed to release hold after payment failure:",c)}return{success:!1,error:D(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 qe{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(),i=String(a.routePrefix??"");return this.routePrefix=i,this.failedDiscoveryAt=null,this.getLogger().debug("Route discovery successful, prefix:",i||"(empty)"),i}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(i=>setTimeout(i,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 $e extends qe{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-DXChB9LA.js"))).WalletManager),Y}const K=new Map,V=new Map;function he(n,e,t,r,a,i){return JSON.stringify({stripePublicKey:n,serverUrl:e,solanaCluster:t,solanaEndpoint:r||"",dangerouslyAllowUnknownMint:a||!1,complianceCheck:i||!1})}async function We(n,e,t,r,a,i){const o=he(n,e,t,r,a,i);let c=K.get(o);if(c)return c.refCount++,s.getLogger().debug(`[ManagerCache] Reusing cached managers (refCount: ${c.refCount}):`,{stripePublicKey:n.slice(0,10)+"...",serverUrl:e}),c;const l=V.get(o);if(l)return c=await l,c.refCount++,s.getLogger().debug(`[ManagerCache] Reusing in-flight managers (refCount: ${c.refCount}):`,{stripePublicKey:n.slice(0,10)+"...",serverUrl:e}),c;s.getLogger().debug("[ManagerCache] Creating new manager instances:",{stripePublicKey:n.slice(0,10)+"...",serverUrl:e});const u=(async()=>{const f=new $e(e),h=new Oe(n,f,i??!1),y=new Fe(f),g=await je(),m=new g(t,r,a??!1),d=new Ae(n,f),p=new Ne(f),R=new Ue(f);return{stripeManager:h,x402Manager:y,walletManager:m,subscriptionManager:d,subscriptionChangeManager:p,creditsManager:R,routeDiscovery:f,refCount:1}})();V.set(o,u);try{return c=await u,K.set(o,c),c}finally{V.delete(o)}}function ae(n,e,t,r,a,i){const o=he(n,e,t,r,a,i),c=K.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:n.slice(0,10)+"...",serverUrl:e}),c.refCount<=0&&(K.delete(o),s.getLogger().debug("[ManagerCache] Removed managers from cache (refCount reached 0)"))}function He(n){return`CEDROS_FEATURE_${n.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase()}`}function Be(n){const e=Object.entries(n).map(([t,r])=>[t,{name:t,description:r.description,default:r.default,stage:r.stage??"experimental",envVar:He(t)}]);return Object.freeze(Object.fromEntries(e))}const N=Be({complianceCheck:{description:"Enable pre-flight compliance checks before Stripe checkout.",default:!1,stage:"stable"}}),Z=Object.freeze(Object.keys(N));function Ke(){return typeof process<"u"&&process.env?process.env:{}}function X(n,e){if(n)for(const[t,r]of Object.entries(n)){if(!(t in N))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 fe(n){if(n==null)return;const e=n.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(n){return N[n]}function Je(){return Z.map(n=>N[n])}function ee(n={}){const e=n.env??Ke();X(n.featureFlags,"featureFlags"),X(n.fallbackFlags,"fallbackFlags");const t={};for(const r of Z){const a=n.featureFlags?.[r],i=n.fallbackFlags?.[r],o=fe(e[N[r].envVar]);t[r]=a??i??o??N[r].default}return t}function Ge(n,e={}){return ee(e)[n]}function Ye(n,e="featureFlags"){X(n,e)}const ie=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(n){const e=[];if(n.showCard!==!1){const a=n.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(n.serverUrl!==void 0)typeof n.serverUrl!="string"||n.serverUrl.trim().length===0?(e.push({field:"serverUrl",message:"must be a non-empty string when provided"}),r=""):(!n.serverUrl.startsWith("http://")&&!n.serverUrl.startsWith("https://")&&e.push({field:"serverUrl",message:'must start with "http://" or "https://"'}),r=n.serverUrl);else try{r=Ve()}catch(a){e.push({field:"serverUrl",message:a instanceof Error?a.message:"failed to determine default"}),r=""}ie.has(n.solanaCluster)||e.push({field:"solanaCluster",message:`must be one of ${Array.from(ie).join(", ")}`}),n.solanaEndpoint!==void 0&&(typeof n.solanaEndpoint!="string"?e.push({field:"solanaEndpoint",message:"must be a string when provided"}):n.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")'}):!n.solanaEndpoint.startsWith("http://")&&!n.solanaEndpoint.startsWith("https://")&&e.push({field:"solanaEndpoint",message:'must start with "http://" or "https://" (e.g., "https://api.mainnet-beta.solana.com")'})),n.tokenMint&&typeof n.tokenMint!="string"&&e.push({field:"tokenMint",message:"must be a string when provided"});try{Ye(n.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(i=>`- ${i.field} ${i.message}`).join(`
2
+ `);throw new Error(`Invalid Cedros configuration:
3
+ ${a}`)}if(n.tokenMint){const a=n.dangerouslyAllowUnknownMint===!0,i=pe.validateTokenMint(n.tokenMint,"CedrosConfig.tokenMint",a);if(!i.isValid&&i.error)throw new Error(i.error);i.warning&&s.getLogger().warn(i.warning)}return{...n,serverUrl:r}}const Q={getAdapters:()=>[],cleanup:async()=>{},isInitialized:()=>!1,getId:()=>"stub"};function Qe(){return typeof process<"u"&&process.env.NODE_ENV==="development"?0:2}const ye=S.createContext(null);function Xe({config:n,children:e}){const t=S.useMemo(()=>me(n),[n]),r=S.useMemo(()=>ee({featureFlags:t.featureFlags,fallbackFlags:t.complianceCheck!=null?{complianceCheck:t.complianceCheck}:void 0}),[t.featureFlags,t.complianceCheck]),[a,i]=S.useState(null),[o,c]=S.useState(Q),l=S.useRef(Q);S.useEffect(()=>{let m=!1;return Promise.resolve().then(()=>require("./walletPool-BjTXX6Vn.js")).then(({createWalletPool:d})=>{if(m)return;const p=d();l.current=p,c(p)}).catch(d=>{m||(s.getLogger().error("[CedrosProvider] Wallet pool initialization failed:",d),i("Failed to initialize Cedros provider"))}),()=>{m=!0}},[]);const[u,f]=S.useState(null);S.useEffect(()=>{let m=!1;return Promise.resolve().then(()=>require("./solanaCheck-BS3QTE63.js")).then(({checkSolanaAvailability:d})=>d()).then(d=>{m||(d.available?f(void 0):f(d.error||"Solana dependencies not available"))}).catch(d=>{m||(s.getLogger().warn("[CedrosProvider] Solana availability check failed:",d),f("Unable to verify Solana availability"))}),()=>{m=!0}},[]),S.useEffect(()=>{const m=t.logLevel??Qe(),d=s.createLogger({level:m,prefix:"[CedrosPay]"});s.setLogger(d)},[t.logLevel]),S.useEffect(()=>()=>{const m=l.current;m&&m!==Q&&m.cleanup().catch(d=>{s.getLogger().warn("[CedrosProvider] Wallet pool cleanup failed:",d)})},[]);const[h,y]=S.useState(null);S.useEffect(()=>{let m=!1,d=!1;const p=t.stripePublicKey??"",R=t.serverUrl??"",O=t.solanaCluster,I=t.solanaEndpoint,_=t.dangerouslyAllowUnknownMint,A=r.complianceCheck;return We(p,R,O,I,_,A).then(P=>{if(m){ae(p,R,O,I,_,A);return}d=!0,y(P)}).catch(P=>{m||(s.getLogger().error("[CedrosProvider] Manager initialization failed:",P),i("Failed to initialize Cedros provider"))}),()=>{m=!0,d&&ae(p,R,O,I,_,A)}},[t.stripePublicKey,t.serverUrl,t.solanaCluster,t.solanaEndpoint,t.dangerouslyAllowUnknownMint,r.complianceCheck]);const g=S.useMemo(()=>h?{config:t,featureFlags:r,...h,walletPool:o,solanaError:u}:null,[t,r,h,o,u]);return a?G.jsx("div",{role:"alert",children:a}):G.jsx(ge.CedrosThemeProvider,{initialMode:t.theme??"light",overrides:t.themeOverrides,unstyled:t.unstyled??!1,children:g?G.jsx(ye.Provider,{value:g,children:e}):null})}function Ze(){const n=S.useContext(ye);if(!n)throw new Error("useCedrosContext must be used within CedrosProvider");return n}exports.CIRCUIT_BREAKER_PRESETS=Re;exports.CedrosProvider=Xe;exports.CircuitBreakerOpenError=w;exports.CircuitState=le;exports.ERROR_CATEGORIES=de;exports.FEATURE_FLAG_NAMES=Z;exports.FEATURE_FLAG_REGISTRY=N;exports.PaymentError=F;exports.RATE_LIMITER_PRESETS=x;exports.RETRY_PRESETS=b;exports.createCircuitBreaker=q;exports.createRateLimiter=L;exports.formatError=D;exports.getFeatureFlagDefinition=ze;exports.getFeatureFlagDefinitions=Je;exports.getUserFriendlyError=ue;exports.isFeatureEnabled=Ge;exports.parseErrorResponse=v;exports.parseFeatureFlagBoolean=fe;exports.resolveFeatureFlags=ee;exports.retryWithBackoff=E;exports.useCedrosContext=Ze;exports.validateConfig=me;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),s=require("react"),R=require("@solana/wallet-adapter-react"),t=require("./sectionIds-B_tFiNvF.js"),E=require("./ThemeContext-CFXyYx7A.js"),S=require("./sections-more-C1VNVwkp.js"),O={publicKey:null};function w({serverUrl:e,cedrosLoginToken:r,isAdmin:c=!1,wallet:o=O}){const a=s.useMemo(()=>{const l=new t.AdminAuthManager(e);return l.setCedrosLoginAuth(r??null,c),l},[e,r,c]);s.useEffect(()=>{o.publicKey&&o.signMessage?a.setWalletSigner({publicKey:o.publicKey,signMessage:o.signMessage}):a.setWalletSigner(null)},[a,o.publicKey,o.signMessage]);const m=a.getAuthMethod(),h=a.isAuthenticated(),g=!!(o.publicKey&&o.signMessage),p=!!(r&&c),y=s.useMemo(()=>{if(!o.publicKey)return null;const l=o.publicKey.toBase58();return`${l.slice(0,4)}...${l.slice(-4)}`},[o.publicKey]),v=s.useCallback((l,b)=>a.fetchWithAuth(l,b),[a]);return{authMethod:m,isAuthenticated:h,walletConnected:g,walletAddress:y,cedrosLoginAvailable:p,authManager:a,fetchWithAuth:v}}const K=s.lazy(()=>Promise.resolve().then(()=>require("./SubscriptionsSection-EeULMWIB.js")).then(e=>({default:e.SubscriptionsSection}))),$=s.lazy(()=>Promise.resolve().then(()=>require("./StorefrontSection-Axvh_KeS.js")).then(e=>({default:e.StorefrontSection}))),W=s.lazy(()=>Promise.resolve().then(()=>require("./AISettingsSection-B7qrycfY.js")).then(e=>({default:e.AISettingsSection}))),D=s.lazy(()=>Promise.resolve().then(()=>require("./PaymentSettingsSection-BdBDgaRg.js")).then(e=>({default:e.PaymentSettingsSection}))),G=s.lazy(()=>Promise.resolve().then(()=>require("./MessagingSection-CxV-pf-f.js")).then(e=>({default:e.MessagingSection}))),Q=s.lazy(()=>Promise.resolve().then(()=>require("./FAQSection-DlPLnIJD.js")).then(e=>({default:e.FAQSection}))),B=s.lazy(()=>Promise.resolve().then(()=>require("./Token22Section-DqRKVG_G.js")).then(e=>({default:e.Token22Section}))),F=s.lazy(()=>Promise.resolve().then(()=>require("./OrdersSection-BbAX79Ff.js")).then(e=>({default:e.OrdersSection}))),Y=s.lazy(()=>Promise.resolve().then(()=>require("./ComplianceSection-Buu0zTiL.js")).then(e=>({default:e.ComplianceSection}))),Z=s.lazy(()=>Promise.resolve().then(()=>require("./ChatLogsSection-DLxMMi9I.js")).then(e=>({default:e.ChatLogsSection}))),H=s.lazy(()=>Promise.resolve().then(()=>require("./CustomersSection-BywmMLur.js")).then(e=>({default:e.CustomersSection}))),J=s.lazy(()=>Promise.resolve().then(()=>require("./DisputesSection-DwkHGv2a.js")).then(e=>({default:e.DisputesSection}))),V=s.lazy(()=>Promise.resolve().then(()=>require("./WebhooksSection-D--iPZuM.js")).then(e=>({default:e.WebhooksSection}))),X=s.lazy(()=>Promise.resolve().then(()=>require("./ShippingSection-C-HI8rOb.js")).then(e=>({default:e.ShippingSection}))),U=s.lazy(()=>Promise.resolve().then(()=>require("./TaxSection-CzHPhaHl.js")).then(e=>({default:e.TaxSection}))),ee=s.lazy(()=>Promise.resolve().then(()=>require("./ReturnsSection-7k4LZ8yp.js")).then(e=>({default:e.ReturnsSection}))),se=s.lazy(()=>Promise.resolve().then(()=>require("./ImagesSection-B4Jzet79.js")).then(e=>({default:e.ImagesSection}))),ne=s.lazy(()=>Promise.resolve().then(()=>require("./InventorySection-BgRdpn1l.js")).then(e=>({default:e.InventorySection}))),I=[{label:"Menu",sections:[{id:"transactions",label:"Transactions",icon:t.Icons.transactions},{id:"orders",label:"Orders",icon:t.Icons.transactions},{id:"products",label:"Products",icon:t.Icons.products},{id:"subscriptions",label:"Subscriptions",icon:t.Icons.calendarRepeat},{id:"coupons",label:"Coupons",icon:t.Icons.coupons},{id:"refunds",label:"Refunds",icon:t.Icons.refunds},{id:"compliance",label:"Compliance",icon:t.Icons.shield},{id:"chat-logs",label:"Chat Logs",icon:t.Icons.chat},{id:"customers",label:"Customers",icon:t.Icons.user},{id:"disputes",label:"Disputes",icon:t.Icons.shield},{id:"returns",label:"Returns",icon:t.Icons.refunds},{id:"images",label:"Images",icon:t.Icons.eye},{id:"inventory",label:"Inventory",icon:t.Icons.products}]},{label:"Configuration",collapsible:!0,sections:[{id:"storefront",label:"Storefront",icon:t.Icons.storefront},{id:"ai-settings",label:"Store AI",icon:t.Icons.brain},{id:"faqs",label:"Knowledge Base",icon:t.Icons.faq},{id:"payment-settings",label:"Payment Options",icon:t.Icons.creditCard},{id:"token22",label:"Gift Cards & Token-22",icon:t.Icons.wallet},{id:"messaging",label:"Store Messages",icon:t.Icons.mail},{id:"webhooks",label:"Webhooks",icon:t.Icons.globe},{id:"shipping",label:"Shipping",icon:t.Icons.products},{id:"tax",label:"Tax Rates",icon:t.Icons.transactions},{id:"settings",label:"Store Server",icon:t.Icons.server}]}],te=I.flatMap(e=>e.sections);function oe(){const[e,r]=s.useState(()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");return s.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: dark)"),o=a=>r(a.matches?"dark":"light");return c.addEventListener("change",o),()=>c.removeEventListener("change",o)},[]),e}function ie(e,r,c){return e!=="system"?e:r||c}const ae={products:S.ProductsSection,transactions:S.TransactionsSection,coupons:S.CouponsSection,refunds:S.RefundsSection,settings:S.SettingsSection,subscriptions:K,storefront:$,"ai-settings":W,"payment-settings":D,messaging:G,faqs:Q,token22:B,orders:F,compliance:Y,"chat-logs":Z,customers:H,disputes:J,webhooks:V,shipping:X,tax:U,returns:ee,images:se,inventory:ne},ce=new Set(["products","transactions","coupons","refunds","settings"]);function re({activeSection:e,serverUrl:r,apiKey:c,pageSize:o,authManager:a}){const m=ae[e];if(!m)return null;const h={serverUrl:r,apiKey:c,pageSize:o,authManager:a};return ce.has(e)?n.jsx(m,{...h}):n.jsx(s.Suspense,{fallback:n.jsx("div",{className:"cedros-admin__loading-text",children:"Loading section..."}),children:n.jsx(m,{...h})})}function le({serverUrl:e,apiKey:r,title:c="Cedros Pay",sections:o=["transactions","orders","products","subscriptions","coupons","refunds","storefront","ai-settings","faqs","payment-settings","messaging","settings"],defaultSection:a="transactions",refreshInterval:m=3e4,pageSize:h=20,onSectionChange:g,className:p="",cedrosLoginToken:y,isAdmin:v=!1,theme:l="system"}){const[b,x]=s.useState(a),[C]=s.useState(!1),[z,j]=s.useState(new Set),L=s.useCallback(i=>{j(f=>{const d=new Set(f);return d.has(i)?d.delete(i):d.add(i),d})},[]),N=E.useCedrosThemeOptional(),q=oe(),_=ie(l,N?.mode??null,q)==="dark"?"cedros-admin--dark":"",P=R.useWallet(),{authManager:A,isAuthenticated:T}=w({serverUrl:e,cedrosLoginToken:y,isAdmin:v,wallet:P}),k=s.useCallback(i=>{x(i),g?.(i)},[g]),M=te.filter(i=>o.includes(i.id)).find(i=>i.id===b);return C?n.jsxs("div",{className:`cedros-admin cedros-admin--loading ${_} ${p}`,children:[t.Icons.loading,n.jsx("span",{className:"cedros-admin__loading-text",children:"Loading dashboard..."})]}):T?n.jsxs("div",{className:`cedros-admin ${_} ${p}`,children:[n.jsxs("aside",{className:"cedros-admin__sidebar",children:[n.jsx("div",{className:"cedros-admin__sidebar-header",children:n.jsxs("div",{className:"cedros-admin__logo",children:[t.Icons.wallet,n.jsx("span",{className:"cedros-admin__logo-text",children:c})]})}),n.jsx("nav",{className:"cedros-admin__nav",children:I.map(i=>{const f=i.sections.filter(u=>o.includes(u.id));if(f.length===0)return null;const d=i.collapsible&&z.has(i.label);return n.jsxs("div",{className:"cedros-admin__nav-group",children:[i.collapsible?n.jsxs("button",{type:"button",className:"cedros-admin__nav-label cedros-admin__nav-label--collapsible",onClick:()=>L(i.label),"aria-expanded":!d,children:[i.label,n.jsx("span",{className:`cedros-admin__nav-label-icon ${d?"":"cedros-admin__nav-label-icon--expanded"}`,children:t.Icons.chevronRight})]}):n.jsx("span",{className:"cedros-admin__nav-label",children:i.label}),!d&&f.map(u=>n.jsxs("button",{type:"button",className:`cedros-admin__nav-item ${b===u.id?"cedros-admin__nav-item--active":""}`,onClick:()=>k(u.id),"aria-current":b===u.id?"page":void 0,children:[n.jsx("span",{className:"cedros-admin__nav-icon",children:u.icon}),n.jsx("span",{className:"cedros-admin__nav-text",children:u.label})]},u.id))]},i.label)})})]}),n.jsxs("main",{className:"cedros-admin__main",children:[n.jsx("header",{className:"cedros-admin__header",children:n.jsxs("div",{className:"cedros-admin__breadcrumb",children:[n.jsx("span",{className:"cedros-admin__breadcrumb-root",children:c}),n.jsx("span",{className:"cedros-admin__breadcrumb-sep",children:t.Icons.chevronRight}),n.jsx("span",{className:"cedros-admin__breadcrumb-current",children:M?.label})]})}),n.jsx("div",{className:"cedros-admin__content",children:n.jsx(re,{activeSection:b,serverUrl:e,apiKey:r,pageSize:h,authManager:A})})]})]}):n.jsx("div",{className:`cedros-admin cedros-admin--unauthenticated ${_} ${p}`,children:n.jsx("p",{className:"cedros-admin__auth-prompt",children:"Please connect a wallet or sign in as admin to access the dashboard."})})}exports.CedrosPayAdminDashboard=le;
@@ -0,0 +1,250 @@
1
+ import { jsxs as l, jsx as s } from "react/jsx-runtime";
2
+ import { useMemo as N, useEffect as A, useCallback as L, useState as _, Suspense as W, lazy as a } from "react";
3
+ import { useWallet as D } from "@solana/wallet-adapter-react";
4
+ import { A as G, I as n } from "./sectionIds-DBavltrL.mjs";
5
+ import { a as q } from "./ThemeContext-l0bqcOGW.mjs";
6
+ import { S as Q, R as j, C as B, T as F, P as Y } from "./sections-more-CMFgfU4d.mjs";
7
+ const Z = { publicKey: null };
8
+ function H({
9
+ serverUrl: e,
10
+ cedrosLoginToken: r,
11
+ isAdmin: c = !1,
12
+ wallet: t = Z
13
+ }) {
14
+ const o = N(() => {
15
+ const d = new G(e);
16
+ return d.setCedrosLoginAuth(r ?? null, c), d;
17
+ }, [e, r, c]);
18
+ A(() => {
19
+ t.publicKey && t.signMessage ? o.setWalletSigner({
20
+ publicKey: t.publicKey,
21
+ signMessage: t.signMessage
22
+ }) : o.setWalletSigner(null);
23
+ }, [o, t.publicKey, t.signMessage]);
24
+ const h = o.getAuthMethod(), p = o.isAuthenticated(), f = !!(t.publicKey && t.signMessage), b = !!(r && c), y = N(() => {
25
+ if (!t.publicKey) return null;
26
+ const d = t.publicKey.toBase58();
27
+ return `${d.slice(0, 4)}...${d.slice(-4)}`;
28
+ }, [t.publicKey]), v = L(
29
+ (d, S) => o.fetchWithAuth(d, S),
30
+ [o]
31
+ );
32
+ return {
33
+ authMethod: h,
34
+ isAuthenticated: p,
35
+ walletConnected: f,
36
+ walletAddress: y,
37
+ cedrosLoginAvailable: b,
38
+ authManager: o,
39
+ fetchWithAuth: v
40
+ };
41
+ }
42
+ const J = a(
43
+ () => import("./SubscriptionsSection-D8V9RBv-.mjs").then((e) => ({ default: e.SubscriptionsSection }))
44
+ ), V = a(
45
+ () => import("./StorefrontSection-BK_rhrAi.mjs").then((e) => ({ default: e.StorefrontSection }))
46
+ ), X = a(
47
+ () => import("./AISettingsSection-DtAgMsDw.mjs").then((e) => ({ default: e.AISettingsSection }))
48
+ ), U = a(
49
+ () => import("./PaymentSettingsSection-DunzBo9n.mjs").then((e) => ({ default: e.PaymentSettingsSection }))
50
+ ), ee = a(
51
+ () => import("./MessagingSection-D_cOBfFt.mjs").then((e) => ({ default: e.MessagingSection }))
52
+ ), ne = a(
53
+ () => import("./FAQSection-Bv_Hdt8B.mjs").then((e) => ({ default: e.FAQSection }))
54
+ ), se = a(
55
+ () => import("./Token22Section-DtYAcT54.mjs").then((e) => ({ default: e.Token22Section }))
56
+ ), te = a(
57
+ () => import("./OrdersSection-wfPavit9.mjs").then((e) => ({ default: e.OrdersSection }))
58
+ ), ie = a(
59
+ () => import("./ComplianceSection-ZCr0wsvw.mjs").then((e) => ({ default: e.ComplianceSection }))
60
+ ), ae = a(
61
+ () => import("./ChatLogsSection-Ber5o8hF.mjs").then((e) => ({ default: e.ChatLogsSection }))
62
+ ), oe = a(
63
+ () => import("./CustomersSection-D9UknSKC.mjs").then((e) => ({ default: e.CustomersSection }))
64
+ ), ce = a(
65
+ () => import("./DisputesSection-C_eySK-W.mjs").then((e) => ({ default: e.DisputesSection }))
66
+ ), re = a(
67
+ () => import("./WebhooksSection-DBAIxtBy.mjs").then((e) => ({ default: e.WebhooksSection }))
68
+ ), de = a(
69
+ () => import("./ShippingSection-BlVsYC6B.mjs").then((e) => ({ default: e.ShippingSection }))
70
+ ), le = a(
71
+ () => import("./TaxSection-Cj6TXL6x.mjs").then((e) => ({ default: e.TaxSection }))
72
+ ), me = a(
73
+ () => import("./ReturnsSection-B4FL7bUv.mjs").then((e) => ({ default: e.ReturnsSection }))
74
+ ), ue = a(
75
+ () => import("./ImagesSection-DpdXQ6qu.mjs").then((e) => ({ default: e.ImagesSection }))
76
+ ), he = a(
77
+ () => import("./InventorySection-DZMu9DMw.mjs").then((e) => ({ default: e.InventorySection }))
78
+ ), T = [
79
+ {
80
+ label: "Menu",
81
+ sections: [
82
+ { id: "transactions", label: "Transactions", icon: n.transactions },
83
+ { id: "orders", label: "Orders", icon: n.transactions },
84
+ { id: "products", label: "Products", icon: n.products },
85
+ { id: "subscriptions", label: "Subscriptions", icon: n.calendarRepeat },
86
+ { id: "coupons", label: "Coupons", icon: n.coupons },
87
+ { id: "refunds", label: "Refunds", icon: n.refunds },
88
+ { id: "compliance", label: "Compliance", icon: n.shield },
89
+ { id: "chat-logs", label: "Chat Logs", icon: n.chat },
90
+ { id: "customers", label: "Customers", icon: n.user },
91
+ { id: "disputes", label: "Disputes", icon: n.shield },
92
+ { id: "returns", label: "Returns", icon: n.refunds },
93
+ { id: "images", label: "Images", icon: n.eye },
94
+ { id: "inventory", label: "Inventory", icon: n.products }
95
+ ]
96
+ },
97
+ {
98
+ label: "Configuration",
99
+ collapsible: !0,
100
+ sections: [
101
+ { id: "storefront", label: "Storefront", icon: n.storefront },
102
+ { id: "ai-settings", label: "Store AI", icon: n.brain },
103
+ { id: "faqs", label: "Knowledge Base", icon: n.faq },
104
+ { id: "payment-settings", label: "Payment Options", icon: n.creditCard },
105
+ { id: "token22", label: "Gift Cards & Token-22", icon: n.wallet },
106
+ { id: "messaging", label: "Store Messages", icon: n.mail },
107
+ { id: "webhooks", label: "Webhooks", icon: n.globe },
108
+ { id: "shipping", label: "Shipping", icon: n.products },
109
+ { id: "tax", label: "Tax Rates", icon: n.transactions },
110
+ { id: "settings", label: "Store Server", icon: n.server }
111
+ ]
112
+ }
113
+ ], pe = T.flatMap((e) => e.sections);
114
+ function Se() {
115
+ const [e, r] = _(() => typeof window > "u" ? "light" : window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
116
+ return A(() => {
117
+ const c = window.matchMedia("(prefers-color-scheme: dark)"), t = (o) => r(o.matches ? "dark" : "light");
118
+ return c.addEventListener("change", t), () => c.removeEventListener("change", t);
119
+ }, []), e;
120
+ }
121
+ function be(e, r, c) {
122
+ return e !== "system" ? e : r || c;
123
+ }
124
+ const fe = {
125
+ products: Y,
126
+ transactions: F,
127
+ coupons: B,
128
+ refunds: j,
129
+ settings: Q,
130
+ subscriptions: J,
131
+ storefront: V,
132
+ "ai-settings": X,
133
+ "payment-settings": U,
134
+ messaging: ee,
135
+ faqs: ne,
136
+ token22: se,
137
+ orders: te,
138
+ compliance: ie,
139
+ "chat-logs": ae,
140
+ customers: oe,
141
+ disputes: ce,
142
+ webhooks: re,
143
+ shipping: de,
144
+ tax: le,
145
+ returns: me,
146
+ images: ue,
147
+ inventory: he
148
+ }, ge = /* @__PURE__ */ new Set(["products", "transactions", "coupons", "refunds", "settings"]);
149
+ function _e({ activeSection: e, serverUrl: r, apiKey: c, pageSize: t, authManager: o }) {
150
+ const h = fe[e];
151
+ if (!h) return null;
152
+ const p = { serverUrl: r, apiKey: c, pageSize: t, authManager: o };
153
+ return ge.has(e) ? /* @__PURE__ */ s(h, { ...p }) : /* @__PURE__ */ s(W, { fallback: /* @__PURE__ */ s("div", { className: "cedros-admin__loading-text", children: "Loading section..." }), children: /* @__PURE__ */ s(h, { ...p }) });
154
+ }
155
+ function ke({
156
+ serverUrl: e,
157
+ apiKey: r,
158
+ title: c = "Cedros Pay",
159
+ sections: t = ["transactions", "orders", "products", "subscriptions", "coupons", "refunds", "storefront", "ai-settings", "faqs", "payment-settings", "messaging", "settings"],
160
+ defaultSection: o = "transactions",
161
+ refreshInterval: h = 3e4,
162
+ pageSize: p = 20,
163
+ onSectionChange: f,
164
+ className: b = "",
165
+ cedrosLoginToken: y,
166
+ isAdmin: v = !1,
167
+ theme: d = "system"
168
+ }) {
169
+ const [S, z] = _(o), [k] = _(!1), [I, M] = _(/* @__PURE__ */ new Set()), x = L((i) => {
170
+ M((g) => {
171
+ const m = new Set(g);
172
+ return m.has(i) ? m.delete(i) : m.add(i), m;
173
+ });
174
+ }, []), R = q(), E = Se(), C = be(d, R?.mode ?? null, E) === "dark" ? "cedros-admin--dark" : "", O = D(), { authManager: K, isAuthenticated: $ } = H({
175
+ serverUrl: e,
176
+ cedrosLoginToken: y,
177
+ isAdmin: v,
178
+ wallet: O
179
+ }), w = L(
180
+ (i) => {
181
+ z(i), f?.(i);
182
+ },
183
+ [f]
184
+ ), P = pe.filter((i) => t.includes(i.id)).find((i) => i.id === S);
185
+ return k ? /* @__PURE__ */ l("div", { className: `cedros-admin cedros-admin--loading ${C} ${b}`, children: [
186
+ n.loading,
187
+ /* @__PURE__ */ s("span", { className: "cedros-admin__loading-text", children: "Loading dashboard..." })
188
+ ] }) : $ ? /* @__PURE__ */ l("div", { className: `cedros-admin ${C} ${b}`, children: [
189
+ /* @__PURE__ */ l("aside", { className: "cedros-admin__sidebar", children: [
190
+ /* @__PURE__ */ s("div", { className: "cedros-admin__sidebar-header", children: /* @__PURE__ */ l("div", { className: "cedros-admin__logo", children: [
191
+ n.wallet,
192
+ /* @__PURE__ */ s("span", { className: "cedros-admin__logo-text", children: c })
193
+ ] }) }),
194
+ /* @__PURE__ */ s("nav", { className: "cedros-admin__nav", children: T.map((i) => {
195
+ const g = i.sections.filter((u) => t.includes(u.id));
196
+ if (g.length === 0) return null;
197
+ const m = i.collapsible && I.has(i.label);
198
+ return /* @__PURE__ */ l("div", { className: "cedros-admin__nav-group", children: [
199
+ i.collapsible ? /* @__PURE__ */ l(
200
+ "button",
201
+ {
202
+ type: "button",
203
+ className: "cedros-admin__nav-label cedros-admin__nav-label--collapsible",
204
+ onClick: () => x(i.label),
205
+ "aria-expanded": !m,
206
+ children: [
207
+ i.label,
208
+ /* @__PURE__ */ s("span", { className: `cedros-admin__nav-label-icon ${m ? "" : "cedros-admin__nav-label-icon--expanded"}`, children: n.chevronRight })
209
+ ]
210
+ }
211
+ ) : /* @__PURE__ */ s("span", { className: "cedros-admin__nav-label", children: i.label }),
212
+ !m && g.map((u) => /* @__PURE__ */ l(
213
+ "button",
214
+ {
215
+ type: "button",
216
+ className: `cedros-admin__nav-item ${S === u.id ? "cedros-admin__nav-item--active" : ""}`,
217
+ onClick: () => w(u.id),
218
+ "aria-current": S === u.id ? "page" : void 0,
219
+ children: [
220
+ /* @__PURE__ */ s("span", { className: "cedros-admin__nav-icon", children: u.icon }),
221
+ /* @__PURE__ */ s("span", { className: "cedros-admin__nav-text", children: u.label })
222
+ ]
223
+ },
224
+ u.id
225
+ ))
226
+ ] }, i.label);
227
+ }) })
228
+ ] }),
229
+ /* @__PURE__ */ l("main", { className: "cedros-admin__main", children: [
230
+ /* @__PURE__ */ s("header", { className: "cedros-admin__header", children: /* @__PURE__ */ l("div", { className: "cedros-admin__breadcrumb", children: [
231
+ /* @__PURE__ */ s("span", { className: "cedros-admin__breadcrumb-root", children: c }),
232
+ /* @__PURE__ */ s("span", { className: "cedros-admin__breadcrumb-sep", children: n.chevronRight }),
233
+ /* @__PURE__ */ s("span", { className: "cedros-admin__breadcrumb-current", children: P?.label })
234
+ ] }) }),
235
+ /* @__PURE__ */ s("div", { className: "cedros-admin__content", children: /* @__PURE__ */ s(
236
+ _e,
237
+ {
238
+ activeSection: S,
239
+ serverUrl: e,
240
+ apiKey: r,
241
+ pageSize: p,
242
+ authManager: K
243
+ }
244
+ ) })
245
+ ] })
246
+ ] }) : /* @__PURE__ */ s("div", { className: `cedros-admin cedros-admin--unauthenticated ${C} ${b}`, children: /* @__PURE__ */ s("p", { className: "cedros-admin__auth-prompt", children: "Please connect a wallet or sign in as admin to access the dashboard." }) });
247
+ }
248
+ export {
249
+ ke as CedrosPayAdminDashboard
250
+ };
@@ -1,8 +1,10 @@
1
1
  import { jsxs as s, jsx as e, Fragment as W } from "react/jsx-runtime";
2
2
  import { useState as i, useCallback as k, useEffect as j } from "react";
3
- import { k as r, E as B, I as M } from "./index-DXnuQp5x.mjs";
4
- function R({ serverUrl: b, apiKey: m, pageSize: o = 20, authManager: h }) {
5
- const [y, v] = i([]), [u, I] = i(0), [d, f] = i(0), [E, x] = i(!0), [L, _] = i(null), [c, $] = i("all"), [S, C] = i(null), [F, N] = i(!1), p = k(async (t) => {
3
+ import { I as B } from "./sectionIds-DBavltrL.mjs";
4
+ import { E as M } from "./ErrorBanner-CZXsHi3H.mjs";
5
+ import { f as d } from "./dateHelpers-yvPkofYQ.mjs";
6
+ function H({ serverUrl: b, apiKey: m, pageSize: o = 20, authManager: h }) {
7
+ const [y, v] = i([]), [u, I] = i(0), [r, f] = i(0), [E, x] = i(!0), [L, _] = i(null), [c, $] = i("all"), [S, C] = i(null), [F, N] = i(!1), p = k(async (t) => {
6
8
  if (h?.isAuthenticated())
7
9
  return h.fetchWithAuth(t);
8
10
  const a = { "Content-Type": "application/json" };
@@ -14,7 +16,7 @@ function R({ serverUrl: b, apiKey: m, pageSize: o = 20, authManager: h }) {
14
16
  x(!0), _(null);
15
17
  try {
16
18
  const t = new URLSearchParams();
17
- t.set("limit", String(o)), t.set("offset", String(d)), c !== "all" && t.set("status", c);
19
+ t.set("limit", String(o)), t.set("offset", String(r)), c !== "all" && t.set("status", c);
18
20
  const a = await p(
19
21
  `/admin/chats?${t.toString()}`
20
22
  );
@@ -24,7 +26,7 @@ function R({ serverUrl: b, apiKey: m, pageSize: o = 20, authManager: h }) {
24
26
  } finally {
25
27
  x(!1);
26
28
  }
27
- }, [p, o, d, c]);
29
+ }, [p, o, r, c]);
28
30
  j(() => {
29
31
  w();
30
32
  }, [w]);
@@ -38,7 +40,7 @@ function R({ serverUrl: b, apiKey: m, pageSize: o = 20, authManager: h }) {
38
40
  } finally {
39
41
  N(!1);
40
42
  }
41
- }, g = Math.max(1, Math.ceil(u / o)), A = Math.floor(d / o) + 1;
43
+ }, g = Math.max(1, Math.ceil(u / o)), A = Math.floor(r / o) + 1;
42
44
  if (S) {
43
45
  const { session: t, messages: a } = S;
44
46
  return /* @__PURE__ */ s("div", { children: [
@@ -66,9 +68,9 @@ function R({ serverUrl: b, apiKey: m, pageSize: o = 20, authManager: h }) {
66
68
  " · "
67
69
  ] }),
68
70
  "Started ",
69
- r(t.createdAt),
71
+ d(t.createdAt),
70
72
  " · Last message ",
71
- r(t.lastMessageAt)
73
+ d(t.lastMessageAt)
72
74
  ] }),
73
75
  /* @__PURE__ */ e("div", { style: { display: "flex", flexDirection: "column", gap: "0.75rem", maxWidth: "640px" }, children: a.map((n) => /* @__PURE__ */ s(
74
76
  "div",
@@ -99,7 +101,7 @@ function R({ serverUrl: b, apiKey: m, pageSize: o = 20, authManager: h }) {
99
101
  l.priceCents != null ? ` ($${(l.priceCents / 100).toFixed(2)})` : ""
100
102
  ] }, l.id)) }),
101
103
  n.actions && n.actions.length > 0 && /* @__PURE__ */ e("div", { style: { maxWidth: "85%", marginTop: "0.25rem", fontSize: "0.75rem", fontStyle: "italic", color: "var(--cedros-admin-text-muted, #888)" }, children: n.actions.join(" · ") }),
102
- /* @__PURE__ */ e("div", { style: { fontSize: "0.7rem", color: "var(--cedros-admin-text-muted, #aaa)", marginTop: "0.15rem" }, children: r(n.createdAt) })
104
+ /* @__PURE__ */ e("div", { style: { fontSize: "0.7rem", color: "var(--cedros-admin-text-muted, #aaa)", marginTop: "0.15rem" }, children: d(n.createdAt) })
103
105
  ]
104
106
  },
105
107
  n.id
@@ -108,7 +110,7 @@ function R({ serverUrl: b, apiKey: m, pageSize: o = 20, authManager: h }) {
108
110
  }
109
111
  return /* @__PURE__ */ s("div", { children: [
110
112
  /* @__PURE__ */ e("div", { className: "cedros-admin__section-header", children: /* @__PURE__ */ e("h3", { className: "cedros-admin__section-title", children: "Chat Logs" }) }),
111
- /* @__PURE__ */ e(B, { message: L }),
113
+ /* @__PURE__ */ e(M, { message: L }),
112
114
  /* @__PURE__ */ s("div", { style: { display: "flex", gap: "0.5rem", marginBottom: "1rem", alignItems: "center" }, children: [
113
115
  /* @__PURE__ */ s(
114
116
  "select",
@@ -133,7 +135,7 @@ function R({ serverUrl: b, apiKey: m, pageSize: o = 20, authManager: h }) {
133
135
  ] })
134
136
  ] }),
135
137
  E || F ? /* @__PURE__ */ s("div", { className: "cedros-admin__loading", children: [
136
- M.loading,
138
+ B.loading,
137
139
  " Loading chat sessions..."
138
140
  ] }) : y.length === 0 ? /* @__PURE__ */ e("div", { className: "cedros-admin__empty", children: "No chat sessions found." }) : /* @__PURE__ */ s(W, { children: [
139
141
  /* @__PURE__ */ e("div", { className: "cedros-admin__table-container", children: /* @__PURE__ */ s("table", { className: "cedros-admin__table", children: [
@@ -152,8 +154,8 @@ function R({ serverUrl: b, apiKey: m, pageSize: o = 20, authManager: h }) {
152
154
  ] }) : /* @__PURE__ */ e("span", { style: { color: "var(--cedros-admin-text-muted, #888)" }, children: "Anonymous" }) }),
153
155
  /* @__PURE__ */ e("td", { children: t.messageCount }),
154
156
  /* @__PURE__ */ e("td", { children: /* @__PURE__ */ e("span", { className: `cedros-admin__badge cedros-admin__badge--${t.status === "active" ? "success" : "muted"}`, children: t.status }) }),
155
- /* @__PURE__ */ e("td", { children: r(t.lastMessageAt) }),
156
- /* @__PURE__ */ e("td", { children: r(t.createdAt) }),
157
+ /* @__PURE__ */ e("td", { children: d(t.lastMessageAt) }),
158
+ /* @__PURE__ */ e("td", { children: d(t.createdAt) }),
157
159
  /* @__PURE__ */ e("td", { children: /* @__PURE__ */ e(
158
160
  "button",
159
161
  {
@@ -171,8 +173,8 @@ function R({ serverUrl: b, apiKey: m, pageSize: o = 20, authManager: h }) {
171
173
  {
172
174
  type: "button",
173
175
  className: "cedros-admin__button cedros-admin__button--ghost cedros-admin__button--sm",
174
- disabled: d === 0,
175
- onClick: () => f(Math.max(0, d - o)),
176
+ disabled: r === 0,
177
+ onClick: () => f(Math.max(0, r - o)),
176
178
  children: "Previous"
177
179
  }
178
180
  ),
@@ -188,7 +190,7 @@ function R({ serverUrl: b, apiKey: m, pageSize: o = 20, authManager: h }) {
188
190
  type: "button",
189
191
  className: "cedros-admin__button cedros-admin__button--ghost cedros-admin__button--sm",
190
192
  disabled: A >= g,
191
- onClick: () => f(d + o),
193
+ onClick: () => f(r + o),
192
194
  children: "Next"
193
195
  }
194
196
  )
@@ -197,5 +199,5 @@ function R({ serverUrl: b, apiKey: m, pageSize: o = 20, authManager: h }) {
197
199
  ] });
198
200
  }
199
201
  export {
200
- R as ChatLogsSection
202
+ H as ChatLogsSection
201
203
  };
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),n=require("react"),E=require("./sectionIds-B_tFiNvF.js"),D=require("./ErrorBanner-Cx2dUhps.js"),o=require("./dateHelpers-BKW_lGND.js");function $({serverUrl:_,apiKey:l,pageSize:i=20,authManager:m}){const[g,b]=n.useState([]),[h,w]=n.useState(0),[r,u]=n.useState(0),[A,p]=n.useState(!0),[k,x]=n.useState(null),[d,T]=n.useState("all"),[y,v]=n.useState(null),[I,S]=n.useState(!1),f=n.useCallback(async t=>{if(m?.isAuthenticated())return m.fetchWithAuth(t);const a={"Content-Type":"application/json"};l&&(a["X-API-Key"]=l);const s=await fetch(`${_}${t}`,{headers:a});if(!s.ok)throw new Error(`Request failed: ${s.status}`);return s.json()},[_,l,m]),C=n.useCallback(async()=>{p(!0),x(null);try{const t=new URLSearchParams;t.set("limit",String(i)),t.set("offset",String(r)),d!=="all"&&t.set("status",d);const a=await f(`/admin/chats?${t.toString()}`);b(a.sessions??[]),w(a.total??0)}catch{x("Failed to load chat sessions"),b([])}finally{p(!1)}},[f,i,r,d]);n.useEffect(()=>{C()},[C]);const L=async t=>{S(!0);try{const a=await f(`/admin/chats/${encodeURIComponent(t)}`);v(a)}catch{x("Failed to load chat session")}finally{S(!1)}},j=Math.max(1,Math.ceil(h/i)),N=Math.floor(r/i)+1;if(y){const{session:t,messages:a}=y;return e.jsxs("div",{children:[e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--sm",onClick:()=>v(null),style:{marginBottom:"1rem"},children:"← Back to sessions"}),e.jsx("div",{className:"cedros-admin__section-header",children:e.jsxs("h3",{className:"cedros-admin__section-title",children:["Chat Session",e.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--muted",style:{marginLeft:"0.5rem"},children:[t.messageCount," messages"]})]})}),e.jsxs("div",{style:{fontSize:"0.85rem",color:"var(--cedros-admin-text-muted, #888)",marginBottom:"1rem"},children:[t.customerEmail&&e.jsxs("span",{children:["Customer: ",e.jsx("strong",{children:t.customerEmail})," · "]}),"Started ",o.formatDateTime(t.createdAt)," · Last message ",o.formatDateTime(t.lastMessageAt)]}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem",maxWidth:"640px"},children:a.map(s=>e.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:s.role==="user"?"flex-end":"flex-start"},children:[e.jsx("div",{style:{maxWidth:"85%",padding:"0.5rem 0.75rem",borderRadius:"0.75rem",fontSize:"0.85rem",lineHeight:"1.4",background:s.role==="user"?"var(--cedros-admin-bg-dark, #1a1a1a)":"var(--cedros-admin-bg-muted, #f5f5f5)",color:s.role==="user"?"#fff":"var(--cedros-admin-text, #333)"},children:e.jsx("span",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"},children:s.content})}),s.products&&s.products.length>0&&e.jsx("div",{style:{maxWidth:"85%",marginTop:"0.25rem",display:"flex",flexWrap:"wrap",gap:"0.25rem"},children:s.products.map(c=>e.jsxs("span",{className:"cedros-admin__badge cedros-admin__badge--muted",style:{fontSize:"0.75rem"},children:[c.name,c.priceCents!=null?` ($${(c.priceCents/100).toFixed(2)})`:""]},c.id))}),s.actions&&s.actions.length>0&&e.jsx("div",{style:{maxWidth:"85%",marginTop:"0.25rem",fontSize:"0.75rem",fontStyle:"italic",color:"var(--cedros-admin-text-muted, #888)"},children:s.actions.join(" · ")}),e.jsx("div",{style:{fontSize:"0.7rem",color:"var(--cedros-admin-text-muted, #aaa)",marginTop:"0.15rem"},children:o.formatDateTime(s.createdAt)})]},s.id))})]})}return e.jsxs("div",{children:[e.jsx("div",{className:"cedros-admin__section-header",children:e.jsx("h3",{className:"cedros-admin__section-title",children:"Chat Logs"})}),e.jsx(D.ErrorBanner,{message:k}),e.jsxs("div",{style:{display:"flex",gap:"0.5rem",marginBottom:"1rem",alignItems:"center"},children:[e.jsxs("select",{className:"cedros-admin__input",value:d,onChange:t=>{T(t.target.value),u(0)},style:{width:"auto",fontSize:"0.85rem"},children:[e.jsx("option",{value:"all",children:"All statuses"}),e.jsx("option",{value:"active",children:"Active"}),e.jsx("option",{value:"archived",children:"Archived"})]}),e.jsxs("span",{style:{fontSize:"0.85rem",color:"var(--cedros-admin-text-muted, #888)"},children:[h," session",h!==1?"s":""]})]}),A||I?e.jsxs("div",{className:"cedros-admin__loading",children:[E.Icons.loading," Loading chat sessions..."]}):g.length===0?e.jsx("div",{className:"cedros-admin__empty",children:"No chat sessions found."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"cedros-admin__table-container",children:e.jsxs("table",{className:"cedros-admin__table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Customer"}),e.jsx("th",{children:"Messages"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Last Message"}),e.jsx("th",{children:"Started"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:g.map(t=>e.jsxs("tr",{children:[e.jsx("td",{children:t.customerEmail?e.jsx("span",{title:t.customerId,children:t.customerEmail}):t.customerId?e.jsxs("code",{style:{fontSize:"0.75rem"},children:[t.customerId.slice(0,12),"..."]}):e.jsx("span",{style:{color:"var(--cedros-admin-text-muted, #888)"},children:"Anonymous"})}),e.jsx("td",{children:t.messageCount}),e.jsx("td",{children:e.jsx("span",{className:`cedros-admin__badge cedros-admin__badge--${t.status==="active"?"success":"muted"}`,children:t.status})}),e.jsx("td",{children:o.formatDateTime(t.lastMessageAt)}),e.jsx("td",{children:o.formatDateTime(t.createdAt)}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--sm",onClick:()=>L(t.id),children:"View"})})]},t.id))})]})}),j>1&&e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:"0.75rem",fontSize:"0.85rem"},children:[e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--sm",disabled:r===0,onClick:()=>u(Math.max(0,r-i)),children:"Previous"}),e.jsxs("span",{children:["Page ",N," of ",j]}),e.jsx("button",{type:"button",className:"cedros-admin__button cedros-admin__button--ghost cedros-admin__button--sm",disabled:N>=j,onClick:()=>u(r+i),children:"Next"})]})]})]})}exports.ChatLogsSection=$;