@tinkerlandai/longplay-sdk 0.10.33 → 0.10.35

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 (96) hide show
  1. package/CHANGELOG.md +12 -3
  2. package/README.md +58 -9
  3. package/README.zh-CN.md +22 -5
  4. package/dist/check-response-GZZRWBEA.js +1 -0
  5. package/dist/chunk-2FE4FTPH.js +1 -0
  6. package/dist/chunk-3NCMYTNG.js +1 -0
  7. package/dist/chunk-44U3FOBB.js +1 -0
  8. package/dist/chunk-56BYGPQ6.js +1 -0
  9. package/dist/chunk-73NP72FV.js +1 -0
  10. package/dist/{chunk-KR3KDTVD.js → chunk-BLVBUN2R.js} +1 -1
  11. package/dist/chunk-BOVN2BE3.js +1 -0
  12. package/dist/chunk-BQRS7Y4K.js +1 -0
  13. package/dist/chunk-CIP5SQ5Y.js +1 -0
  14. package/dist/chunk-CKKIB2HC.js +1 -0
  15. package/dist/chunk-EM3MGDPG.js +1 -0
  16. package/dist/chunk-ETK6GC5P.js +1 -0
  17. package/dist/chunk-EUTWY7A2.js +1 -0
  18. package/dist/{chunk-NVHIGAO3.js → chunk-FMDC6N4W.js} +1 -1
  19. package/dist/chunk-GZRRVHYK.js +1 -0
  20. package/dist/{chunk-MIBRUDIS.js → chunk-KE26KWIU.js} +1 -1
  21. package/dist/{chunk-GGRDM54V.js → chunk-KPDHY76A.js} +1 -1
  22. package/dist/{chunk-FYQXSGRT.js → chunk-LF2UIJYD.js} +1 -1
  23. package/dist/{chunk-UWLEGMWX.js → chunk-MSK3VZ3A.js} +1 -1
  24. package/dist/{chunk-X4W22IH6.js → chunk-OX7PA64E.js} +1 -1
  25. package/dist/chunk-PUR5CYWX.js +1 -0
  26. package/dist/{chunk-XLSDL4D3.js → chunk-RML52BOR.js} +1 -1
  27. package/dist/chunk-RNEF4MZW.js +1 -0
  28. package/dist/chunk-SFHIFCXG.js +1 -0
  29. package/dist/{chunk-HQITRRHF.js → chunk-SXBM3DWK.js} +1 -1
  30. package/dist/chunk-TAFALMQN.js +1 -0
  31. package/dist/chunk-TJGIT5CU.js +1 -0
  32. package/dist/{chunk-KIMX3OIV.js → chunk-TLZP7BW6.js} +1 -1
  33. package/dist/chunk-TOTRALYQ.js +10 -0
  34. package/dist/chunk-U4RSRFZY.js +1 -0
  35. package/dist/chunk-UVRT4MY6.js +1 -0
  36. package/dist/chunk-V7MMTILA.js +1 -0
  37. package/dist/chunk-V7PFLFHE.js +1 -0
  38. package/dist/{chunk-BXPXJARS.js → chunk-VEX2FOFZ.js} +1 -1
  39. package/dist/chunk-W32FI2A2.js +1 -0
  40. package/dist/chunk-W6OQTXLL.js +1 -0
  41. package/dist/{chunk-EQPEUPMG.js → chunk-WZR2XCSJ.js} +1 -1
  42. package/dist/chunk-XUGEOELU.js +1 -0
  43. package/dist/chunk-YVXLCQGM.js +1 -0
  44. package/dist/content-AJDTSI7A.js +1 -0
  45. package/dist/funnel-host-purchase-Z7FCJ5CX.js +1 -0
  46. package/dist/{funnel-local-client-BeGBvi3z.d.ts → funnel-local-client-Dz1dTgES.d.ts} +22 -22
  47. package/dist/funnel-paywall-prerender-QHCUZZY3.js +1 -0
  48. package/dist/{funnel-process-client-C6QKDZun.d.ts → funnel-process-client-D6qjStm2.d.ts} +1 -1
  49. package/dist/funnel-runtime-host-UKSOOA4H.js +1 -0
  50. package/dist/index.d.ts +196 -61
  51. package/dist/index.js +1 -1
  52. package/dist/merchant-bridge-contracts-EAE4HQE4.js +1 -0
  53. package/dist/native-shell.js +1 -1
  54. package/dist/openrouter.js +1 -1
  55. package/dist/operation-contracts-HS4M2UXN.js +1 -0
  56. package/dist/page.js +1 -1
  57. package/dist/paywall-VYUBYBUI.js +1 -0
  58. package/dist/paywall-content-YQAVSO2T.js +1 -0
  59. package/dist/paywall-session-E5V42XUT.js +1 -0
  60. package/dist/popup.d.ts +20 -2
  61. package/dist/popup.js +1 -1
  62. package/dist/{presentation-loading-CiEQbUDk.d.ts → presentation-loading-CFSiS0VX.d.ts} +3 -1
  63. package/dist/react-native.d.ts +4 -4
  64. package/dist/react-native.js +1 -1
  65. package/dist/screen-renderer-R5GH7XLV.js +1 -0
  66. package/dist/server.d.ts +32 -2
  67. package/dist/server.js +3 -3
  68. package/dist/visual.js +1 -1
  69. package/package.json +1 -1
  70. package/dist/chunk-BRAVNBCC.js +0 -1
  71. package/dist/chunk-EHDHWYVJ.js +0 -1
  72. package/dist/chunk-ENZBWR3Y.js +0 -1
  73. package/dist/chunk-HQPP76BS.js +0 -1
  74. package/dist/chunk-ILEDKSRQ.js +0 -1
  75. package/dist/chunk-JN6JEKWN.js +0 -1
  76. package/dist/chunk-MPYJRLKB.js +0 -10
  77. package/dist/chunk-N7YXDSQL.js +0 -1
  78. package/dist/chunk-NAZU3EEJ.js +0 -1
  79. package/dist/chunk-NVIHK5GE.js +0 -1
  80. package/dist/chunk-R23IGK5U.js +0 -1
  81. package/dist/chunk-R4FDIYMN.js +0 -1
  82. package/dist/chunk-SCC3O2RD.js +0 -1
  83. package/dist/chunk-THMGTRXP.js +0 -1
  84. package/dist/chunk-U2R7MG3J.js +0 -1
  85. package/dist/chunk-U6E6CM7Z.js +0 -1
  86. package/dist/chunk-U6GWWCUS.js +0 -1
  87. package/dist/chunk-UHQGO6OR.js +0 -1
  88. package/dist/chunk-YTZQ5BMP.js +0 -1
  89. package/dist/content-CFX2L2BP.js +0 -1
  90. package/dist/funnel-host-purchase-MSPLT3ZV.js +0 -1
  91. package/dist/funnel-runtime-host-ATOA7MGC.js +0 -1
  92. package/dist/merchant-bridge-contracts-ZUQ6SGXZ.js +0 -1
  93. package/dist/operation-contracts-443N2P3A.js +0 -1
  94. package/dist/paywall-XAXSMLDU.js +0 -1
  95. package/dist/paywall-session-MB7BD2XP.js +0 -1
  96. package/dist/screen-renderer-3CBREMIS.js +0 -1
@@ -0,0 +1 @@
1
+ import{a as G}from"./chunk-ZGCKQWQ5.js";import{b as Z}from"./chunk-VYFSRHXM.js";import{a as j,b as Q,c as x}from"./chunk-KE26KWIU.js";import{d as l}from"./chunk-TJGIT5CU.js";import{a as L,b as F,c as H}from"./chunk-V7MMTILA.js";import{b as e}from"./chunk-VF6QMMEA.js";var fe=["purchase.subscription","purchase.one_time","purchase.prepaid","purchase.trial","purchase.seats","purchase.tiered","tax.automatic","discount.percent.once","discount.percent.repeating","discount.percent.forever","discount.amount.once","discount.amount.repeating","discount.amount.forever","subscription.cancel.immediate","subscription.cancel.renewal","subscription.resume","subscription.plan.immediate","subscription.plan.renewal","subscription.seats","subscription.quantity","subscription.billing_cycle","subscription.proration","refund.full","refund.partial","refund.revoke"],K=e.enum(fe),W=e.enum(["purchase.completed","purchase.closed","subscription.observed","subscription.change.completed","subscription.change.closed","invoice.paid","refund.updated"]);var o=e.string().min(1).max(200),c=e.iso.datetime({offset:!0}),i=e.number().int().nonnegative().max(1e8),y=e.string().regex(/^[A-Z]{3}$/),m=e.strictObject({priceId:e.uuid(),productVersionId:e.uuid(),productId:o,quantity:e.number().int().min(1).max(1e6),unitAmountMinor:i,totalMinor:i,interval:e.enum(["week","month","year","one_off"]),intervalCount:e.number().int().min(1).max(52),kind:e.enum(["fixed","prepaid","seat"]),tiers:e.strictObject({mode:e.enum(["graduated","volume"]),tiers:e.array(e.strictObject({upTo:e.number().int().positive().nullable(),unitAmountMinor:i,flatAmountMinor:i.optional()})).min(2).max(12)}).nullable()}),I=e.strictObject({grantId:e.uuid(),couponId:e.uuid(),amountMinor:i,applicationPolicy:G.optional(),applicableProductIds:e.array(o).min(1).max(100).optional(),terms:e.discriminatedUnion("type",[e.strictObject({type:e.literal("percent"),percentOff:e.number().gt(0).max(100)}),e.strictObject({type:e.literal("amount"),amountOffMinor:i,currency:y})]),duration:e.discriminatedUnion("type",[e.strictObject({type:e.literal("once")}),e.strictObject({type:e.literal("forever")}),e.strictObject({type:e.literal("repeating"),months:e.number().int().min(1).max(36)})])}),E={provider:e.literal("merchant"),executor:e.literal("merchant"),operationId:e.uuid(),customerId:e.uuid(),configurationRevision:e.number().int().nonnegative(),connectionRevision:e.number().int().nonnegative(),currency:y,expiresAt:c},ge=e.strictObject({...E,type:e.literal("purchase"),mode:e.enum(["payment","subscription"]),lineItems:e.array(m).min(1).max(100),catalogAmountMinor:i,nativeDiscountMinor:i.optional(),discount:I.nullable(),trialPeriodDays:e.number().int().min(1).max(730).nullable(),automaticTax:e.boolean()}).refine(t=>t.lineItems.reduce((n,r)=>n+r.totalMinor,0)===t.catalogAmountMinor&&(t.discount?.amountMinor??0)+(t.nativeDiscountMinor??0)<=t.catalogAmountMinor&&new Set(t.lineItems.map(n=>n.priceId)).size===t.lineItems.length,"Purchase lines must retain the original total and unique Price identities"),S=e.strictObject({...E,type:e.literal("subscription_change"),subscriptionId:e.uuid(),merchantSubscriptionId:o,membershipId:e.uuid(),subscriptionAction:e.enum(["update","cancel","schedule","release"]),supersedesOperationId:e.uuid().nullable(),change:e.discriminatedUnion("type",[e.strictObject({type:e.literal("cancel")}),e.strictObject({type:e.literal("uncancel")}),e.strictObject({type:e.literal("plan"),productVersionId:e.uuid()}),e.strictObject({type:e.literal("seats"),licenseKey:o,quantity:e.number().int().nonnegative().max(1e6)}),e.strictObject({type:e.literal("quantity"),internal_feature_id:e.uuid(),quantity:e.number().int().nonnegative().max(1e6)}),e.strictObject({type:e.literal("billing_cycle"),billingCycleAnchor:e.union([e.literal("now"),e.number().int().positive()])})]),timing:e.enum(["immediate","renewal"]),effectiveAt:c,creditMinor:i,debitMinor:i,totalMinor:i,discountMinor:i,discount:I.nullable().optional(),taxMinor:i,proration:e.enum(["none","create_prorations","always_invoice"]),lineItems:e.array(m.extend({quantity:e.number().int().nonnegative().max(1e6)})).max(100),removePriceIds:e.array(e.uuid()).max(100),sourceLineItems:e.array(m).min(1).max(100).optional()}),xe=e.strictObject({...E,type:e.literal("refund"),invoiceId:e.uuid(),merchantInvoiceId:o,amountMinor:i.refine(t=>t>0),mode:e.enum(["full","partial"]),entitlementAction:e.enum(["retain","revoke"]),cancelSubscriptions:e.array(o).max(100)}),Y=e.discriminatedUnion("type",[ge,S,xe]);function We(t){let n=new Set;if(t.type==="purchase")n.add(t.mode==="subscription"?"purchase.subscription":"purchase.one_time"),t.lineItems.some(r=>r.kind==="prepaid")&&n.add("purchase.prepaid"),t.lineItems.some(r=>r.kind==="seat")&&n.add("purchase.seats"),t.lineItems.some(r=>r.tiers!==null)&&n.add("purchase.tiered"),t.trialPeriodDays!==null&&n.add("purchase.trial"),t.automaticTax&&n.add("tax.automatic"),t.discount&&n.add(`discount.${t.discount.terms.type}.${t.discount.duration.type}`);else if(t.type==="refund")n.add(`refund.${t.mode}`),t.entitlementAction==="revoke"&&n.add("refund.revoke");else{let r=t.change.type;r==="cancel"?n.add(`subscription.cancel.${t.timing}`):r==="uncancel"?n.add("subscription.resume"):r==="plan"?n.add(`subscription.plan.${t.timing}`):n.add(`subscription.${r}`),t.proration!=="none"&&n.add("subscription.proration"),t.discount&&n.add(`discount.${t.discount.terms.type}.${t.discount.duration.type}`)}return[...n].sort()}function Xe(t){return t.type==="purchase"?t.mode==="subscription"?["purchase.completed","purchase.closed","subscription.observed","invoice.paid"]:["purchase.completed","purchase.closed"]:t.type==="subscription_change"?["subscription.change.completed","subscription.change.closed","subscription.observed",...t.change.type==="cancel"||t.change.type==="uncancel"?[]:["invoice.paid"]]:["refund.updated",...t.entitlementAction==="revoke"&&t.cancelSubscriptions.length?["subscription.observed"]:[]]}var ye=e.strictObject({phase:e.enum(["execution","payment","fulfillment","recording"]),code:L,reason:H.optional(),recovery:F,retryable:e.boolean()}).refine(t=>t.reason!=="RESULT_UNKNOWN"||!t.retryable&&t.recovery==="recover_operation","Unknown financial effects require recovery of the original operation"),Ie=e.strictObject({type:e.literal("redirect"),url:e.url().startsWith("https://"),expiresAt:c}),B={operationId:e.uuid(),customerId:e.uuid(),merchantExecutionId:o,fulfillmentStatus:e.enum(["not_started","pending","applied","failed","not_applicable"]),recordingStatus:e.enum(["not_ready","pending","accepted","failed"]),updatedAt:c,problem:ye.nullable(),pollAfterMs:e.number().int().min(1e3).max(6e4).nullable()},T=e.discriminatedUnion("type",[e.strictObject({...B,type:e.literal("purchase"),merchantOrderId:o.nullable(),paymentStatus:e.enum(["not_started","pending","succeeded","not_required","failed","expired","unknown"]),checkoutUrl:e.url().refine(t=>new URL(t).protocol==="https:").nullable(),checkoutExpiresAt:c.nullable()}).refine(t=>!t.checkoutUrl||["not_started","pending"].includes(t.paymentStatus)&&t.checkoutExpiresAt!==null,"Only an unfinished original purchase may expose its checkout"),e.strictObject({...B,type:e.literal("subscription_change"),status:e.enum(["pending","scheduled","applied","failed","unknown"]),merchantSubscriptionId:o,scheduledFor:c.nullable(),nextAction:Ie.optional()}).refine(t=>t.status==="scheduled"==(t.scheduledFor!==null),"A scheduled change retains its future effective time"),e.strictObject({...B,type:e.literal("refund"),status:e.enum(["pending","succeeded","failed","unknown"]),merchantRefundId:o.nullable()}).refine(t=>t.status!=="succeeded"||t.merchantRefundId!==null,"A successful refund retains its original merchant identity")]),ee=e.discriminatedUnion("lookup",[e.strictObject({lookup:e.literal("found"),operationId:e.uuid(),customerId:e.uuid(),execution:T,readAt:c}),e.strictObject({lookup:e.literal("not_received"),operationId:e.uuid(),customerId:e.uuid(),execution:e.null(),readAt:c})]).refine(t=>!t.execution||t.execution.operationId===t.operationId&&t.execution.customerId===t.customerId,"Lookup must retain the original Customer and operation"),te=e.strictObject({merchantPriceId:o,productId:o,kind:e.enum(["fixed","prepaid"]),currency:y,unitAmountMinor:i,interval:e.enum(["one_off","day","week","month","year"]),intervalCount:e.number().int().min(1).max(100)}),X={merchantItemId:o,quantity:e.number().int().positive().max(1e6)},Se=t=>t.priceId??JSON.stringify(t.nativePrice),k=e.strictObject({merchantSubscriptionId:o,revision:e.number().int().positive(),status:e.enum(["incomplete","trialing","active","past_due","canceled","unpaid","paused","incomplete_expired"]),periodStartsAt:c,periodEndsAt:c,cancelAtPeriodEnd:e.boolean(),hasDiscounts:e.boolean(),items:e.array(e.union([e.strictObject({...X,priceId:e.uuid()}),e.strictObject({...X,nativePrice:te})])).min(1).max(100)}).refine(t=>Date.parse(t.periodEndsAt)>Date.parse(t.periodStartsAt)&&new Set(t.items.map(Se)).size===t.items.length&&new Set(t.items.map(n=>n.merchantItemId)).size===t.items.length,"Subscription periods and Price identities must be unambiguous"),J={merchantLineId:o,quantity:e.number().int().nonnegative().max(1e6),subtotalMinor:e.number().int().min(-1e8).max(1e8),discountMinor:i,taxMinor:i,totalMinor:e.number().int().min(-1e8).max(2e8),periodStartsAt:c.nullable(),periodEndsAt:c.nullable()},R=e.strictObject({merchantInvoiceId:o,reason:e.enum(["renewal","adjustment"]).optional(),currency:y,subtotalMinor:i,discountMinor:i,taxMinor:i,totalMinor:i,paidMinor:i,periodStartsAt:c.nullable(),periodEndsAt:c.nullable(),lines:e.array(e.union([e.strictObject({...J,priceId:e.uuid()}),e.strictObject({...J,nativePrice:te})]).refine(t=>t.subtotalMinor-t.discountMinor+t.taxMinor===t.totalMinor&&(t.subtotalMinor<0?t.discountMinor===0&&t.taxMinor===0:t.discountMinor<=t.subtotalMinor),"Invoice line amounts must retain the complete debit or credit")).min(1).max(100)}).refine(t=>t.subtotalMinor-t.discountMinor+t.taxMinor===t.totalMinor&&t.discountMinor<=t.subtotalMinor&&t.paidMinor===t.totalMinor&&new Set(t.lines.map(n=>n.merchantLineId)).size===t.lines.length&&t.lines.reduce((n,r)=>n+r.subtotalMinor,0)===t.subtotalMinor&&t.lines.reduce((n,r)=>n+r.discountMinor,0)===t.discountMinor&&t.lines.reduce((n,r)=>n+r.taxMinor,0)===t.taxMinor&&t.lines.reduce((n,r)=>n+r.totalMinor,0)===t.totalMinor,"A paid Invoice retains the complete financial amounts"),p={eventId:e.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),customerId:e.uuid(),occurredAt:c},Me=e.strictObject({...p,type:e.literal("purchase.completed"),operationId:e.uuid(),merchantOrderId:o,paymentStatus:e.enum(["paid","trialing","no_payment_required"]),invoice:R.refine(t=>t.lines.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable(),subscription:k.refine(t=>t.items.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable()}),_e=e.strictObject({...p,type:e.literal("purchase.closed"),operationId:e.uuid(),status:e.enum(["failed","expired","canceled"])}),Oe=e.strictObject({...p,type:e.literal("subscription.observed"),operationId:e.uuid().nullable(),subscription:k}),ve=e.strictObject({...p,type:e.literal("subscription.change.completed"),operationId:e.uuid(),status:e.enum(["scheduled","applied"]),scheduledFor:c.nullable(),subscription:k.refine(t=>t.items.every(n=>"priceId"in n),"An operation result retains its quoted Price identities"),invoice:R.refine(t=>t.lines.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable()}),Ae=e.strictObject({...p,type:e.literal("subscription.change.closed"),operationId:e.uuid(),merchantSubscriptionId:o,merchantInvoiceId:o.nullable(),status:e.enum(["failed","expired","canceled"])}),je=e.strictObject({...p,type:e.literal("invoice.paid"),merchantSubscriptionId:o.nullable(),invoice:R}),Pe=e.strictObject({...p,type:e.literal("refund.updated"),operationId:e.uuid().nullable(),merchantInvoiceId:o.optional(),merchantRefundId:o,status:e.enum(["pending","succeeded","failed"]),amountMinor:i.refine(t=>t>0),currency:y}),Je=[Me.refine(t=>t.paymentStatus!=="paid"||t.invoice!==null,"A paid purchase includes its Invoice"),_e,Oe.refine(t=>t.operationId===null||t.subscription.items.every(n=>"priceId"in n),"Native Price references cannot replace an operation's quoted Prices"),ve.refine(t=>t.status==="scheduled"==(t.scheduledFor!==null),"Scheduled and applied changes are distinct facts"),Ae,je,Pe.refine(t=>t.operationId!==null||t.merchantInvoiceId!==void 0,"A native refund names its Invoice")];var z=e.strictObject({days:e.number().int().min(1).max(730),cardRequired:e.boolean()}),rt=e.object({...z.shape,featureAllowances:e.record(e.uuid(),e.number().int().min(0).max(1e9)),creditAmounts:e.record(e.uuid(),l)}).strict(),it=e.object({id:e.uuid(),planVersionId:e.uuid(),slot:e.string(),cardRequired:e.boolean(),status:e.enum(["pending","active","converted","canceled","expired","failed"]),startsAt:e.iso.datetime().nullable(),endsAt:e.iso.datetime().nullable(),createdAt:e.iso.datetime()}).strict();var qe=e.number().int().positive().max(2e8),ne=e.number().int().min(0).max(2e8),re=t=>t.mode==="partial"==(t.amountMinor!==void 0),P=e.strictObject({mode:e.enum(["full","partial"]),amountMinor:qe.optional(),entitlementAction:e.enum(["retain","revoke"])});var a=e.string().min(1).max(200),b=e.iso.datetime({offset:!0}),f=ne,ie=f.maxValue,C=e.number().int().min(-ie).max(ie),q=e.string().regex(/^[A-Z]{3}$/),oe=e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),ae=e.array(a).max(100).refine(t=>new Set(t).size===t.length),Ce=e.strictObject({merchantProductId:a,merchantPriceId:a,productVersionId:e.uuid().optional(),quantity:l.refine(t=>/[1-9]/.test(t))}),w={subject:Q,operationId:e.uuid(),configurationRevision:oe,connectionRevision:oe,expiresAt:b},D=e.discriminatedUnion("action",[e.strictObject({...w,action:e.literal("purchase"),mode:e.enum(["payment","subscription"]),currency:q,items:e.array(Ce).min(1).max(100),offerRefs:ae}),e.strictObject({...w,action:e.literal("subscription_change"),currency:q,merchantSubscriptionId:a,change:S.shape.change,timing:S.shape.timing,proration:S.shape.proration,offerRefs:ae}),e.strictObject({...w,action:e.literal("refund"),currency:q,merchantInvoiceId:a,mode:P.shape.mode,amountMinor:P.shape.amountMinor,entitlementAction:P.shape.entitlementAction}).refine(re,"Only a partial refund chooses amountMinor")]),ht=e.strictObject({request:D,requestedAt:b,preparationAllowed:e.boolean()}).refine(t=>!t.preparationAllowed||Date.parse(t.requestedAt)<Date.parse(t.request.expiresAt),"Preparation authority must be within its original validity"),Be=e.strictObject({merchantLineId:a,merchantPriceId:a.nullable(),quantity:l.refine(t=>/[1-9]/.test(t)),subtotalMinor:C,discountMinor:f,taxMinor:f.nullable(),totalMinor:C.nullable()}).refine(t=>t.taxMinor===null==(t.totalMinor===null)&&(t.totalMinor===null||t.totalMinor===t.subtotalMinor-t.discountMinor+t.taxMinor),"A quote line retains exact known totals; unknown tax is not zero"),Ee=e.strictObject({items:e.array(e.strictObject({merchantPriceId:a,quantity:l.refine(t=>/[1-9]/.test(t)),interval:m.shape.interval.exclude(["one_off"]),intervalCount:m.shape.intervalCount,amountMinor:m.shape.totalMinor,amountAfterOfferMinor:m.shape.totalMinor.optional()})).min(1).max(100),trial:z.nullable(),discount:I.nullable().optional(),discountExpiresAt:b.nullable().optional(),initialAmountMinor:m.shape.totalMinor.optional()}),ce=e.strictObject({request:D,requestDigest:j,merchantQuoteId:a,quoteTermsDigest:j,termsVersion:a,sourceRevisions:e.array(e.strictObject({reference:a,revision:a})).max(100),observedAt:b,expiresAt:b,currency:q,automaticTax:e.boolean(),lines:e.array(Be).max(100),subscriptionTerms:Ee.nullable(),subtotalMinor:C,discountMinor:f,nativeDiscountMinor:f.optional(),discount:I.nullable().optional(),taxMinor:f.nullable(),totalMinor:C.nullable(),effectiveAt:b.nullable(),expectedEffects:e.array(e.strictObject({reference:a,kind:e.enum(["grant","revoke","change"]),description:e.string().min(1).max(1e3),quantity:l.nullable(),unit:a.nullable()}).refine(t=>t.quantity===null==(t.unit===null),"Quantified effects name their native unit")).max(100),requiredConsents:e.array(e.strictObject({reference:a,version:a,summary:e.string().min(1).max(1e3)})).max(20)}),U=ce.superRefine((t,n)=>{let{quoteTermsDigest:r,...u}=t,h=t.lines.every(s=>s.taxMinor!==null),A=t.request.action==="purchase"&&t.request.mode==="subscription"!=(t.subscriptionTerms!==null),be=t.subscriptionTerms!==null&&(t.request.action==="refund"||t.request.action==="subscription_change"&&t.request.change.type==="cancel");(t.requestDigest!==x(t.request)||t.quoteTermsDigest!==x(u)||t.currency!==t.request.currency||A||be||t.lines.length===0&&(t.request.action!=="subscription_change"||t.subtotalMinor!==0||t.discountMinor!==0||t.taxMinor!==0||t.totalMinor!==0)||Date.parse(t.observedAt)>=Date.parse(t.expiresAt)||Date.parse(t.expiresAt)>Date.parse(t.request.expiresAt)||new Set(t.lines.map(s=>s.merchantLineId)).size!==t.lines.length||new Set(t.sourceRevisions.map(s=>s.reference)).size!==t.sourceRevisions.length||new Set(t.requiredConsents.map(s=>s.reference)).size!==t.requiredConsents.length||t.subtotalMinor!==t.lines.reduce((s,g)=>s+g.subtotalMinor,0)||t.discountMinor!==t.lines.reduce((s,g)=>s+g.discountMinor,0)||t.taxMinor!==null!==h||!h&&!t.automaticTax||t.taxMinor===null!=(t.totalMinor===null)||h&&(t.taxMinor!==t.lines.reduce((s,g)=>s+g.taxMinor,0)||t.totalMinor!==t.subtotalMinor-t.discountMinor+t.taxMinor)||t.request.action!=="subscription_change"&&(t.subtotalMinor<0||t.totalMinor!==null&&t.totalMinor<0)||t.request.action==="refund"&&(t.taxMinor===null||t.totalMinor===null||t.totalMinor<=0||t.request.mode==="partial"&&t.totalMinor!==t.request.amountMinor))&&n.addIssue({code:"custom",message:"Merchant terms must retain the original selection, scope, validity, digest and totals"})});function bt(t,n,r,u){return t.request.operationId===n&&t.request.action===r&&t.currency===u}function ft(t){return x(D.parse(t))}function gt(t){return x(ce.omit({quoteTermsDigest:!0}).parse(t))}var Te=e.strictObject({quoteTermsDigest:j,consents:e.array(e.strictObject({reference:a,version:a})).max(20)});function xt(t){return{quoteTermsDigest:t.quoteTermsDigest,consents:t.requiredConsents.map(({reference:n,version:r})=>({reference:n,version:r}))}}var ke=Te.extend({operationId:e.uuid()}).refine(t=>new Set(t.consents.map(n=>n.reference)).size===t.consents.length);function yt(t,n){let r=U.parse(t),u=ke.parse(n);return u.operationId===r.request.operationId&&u.quoteTermsDigest===r.quoteTermsDigest&&u.consents.length===r.requiredConsents.length&&r.requiredConsents.every(h=>u.consents.some(A=>A.reference===h.reference&&A.version===h.version))}var M=3,Ot="/integrations/indiana",vt="X-Indiana-Merchant-Bridge-Version",Re=["session","catalog","customer_commerce","presentation","presentation_events","purchases","operation_status","billing_records","subscription_changes","refunds"],ze=e.enum(Re),At={session:{command:"session.create",authority:"merchant_user"},catalog:{command:"catalog.read",authority:"merchant_catalog_reader"},customer_commerce:{command:"customer.commerce.read",authority:"merchant_user"},presentation:{command:"presentation.resolve",authority:"merchant_user"},presentation_events:{command:"presentation.report",authority:"merchant_user"},purchases:{command:"purchase.execute",authority:"merchant_user"},operation_status:{command:"operation.read",authority:"merchant_user"},billing_records:{command:null,authority:"indiana_server_key"},subscription_changes:{command:"subscription.change",authority:"merchant_user"},refunds:{command:"refund.execute",authority:"merchant_refund_authority"}},$=e.enum(["bridge.ping","bridge.describe","session.create","catalog.read","customer.commerce.read","presentation.resolve","presentation.report","purchase.execute","operation.read","subscription.change","refund.execute"]),ue=e.string().regex(/^[A-Za-z0-9_-]{1,64}$/),we=e.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(t=>"AEIMQUYcgkosw048".includes(t.at(-1)),"Use canonical base64url for a 32-byte key"),De=e.strictObject({keyId:ue,signingSecret:we}),Ue=e.string().max(300).superRefine((t,n)=>{try{let r=new URL(t);if(r.protocol!=="https:"||r.username||r.password||r.search||r.hash||r.pathname!=="/"||r.port&&r.port!=="443"||!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.[a-z]{2,63}$/.test(r.hostname)||/(?:^|\.)(?:localhost|local|internal)$/.test(r.hostname))throw new Error("invalid origin")}catch{n.addIssue({code:"custom",message:"Use an exact public HTTPS origin"})}}).transform(t=>new URL(t).origin),me=e.array(ze).max(10).refine(t=>new Set(t).size===t.length,"Capabilities must be unique"),V=e.strictObject({bridgeVersion:e.literal(M),projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"]),capabilities:me,catalog:e.enum(["endpoint","static","none"]),billingEvents:e.array(W).max(7),profiles:e.array(K).max(32).refine(t=>new Set(t).size===t.length,"Profiles must be unique")}).superRefine((t,n)=>{let r=u=>t.capabilities.includes(u);r("catalog")!==(t.catalog!=="none")&&n.addIssue({code:"custom",path:["catalog"],message:"Catalog declaration differs from its capability"}),(r("billing_records")!==t.billingEvents.length>0||new Set(t.billingEvents).size!==t.billingEvents.length)&&n.addIssue({code:"custom",path:["billingEvents"],message:"Declare the unique supported billing events"})}),de=e.strictObject({origin:Ue,requiredCapabilities:me}),$e=e.strictObject({revision:e.number().int().nonnegative(),checkedAt:e.iso.datetime(),outcome:e.enum(["valid","unreachable","invalid","scope_mismatch","authentication_failed","credentials_missing"]),diagnostics:e.strictObject({ping:e.enum(["passed","failed","not_checked"]),authentication:e.enum(["passed","failed","not_checked"]),catalog:e.enum(["passed","failed","not_checked","static","unsupported"])}),manifest:V.nullable()}).superRefine((t,n)=>{t.outcome==="valid"!=(t.manifest!==null)&&n.addIssue({code:"custom",path:["manifest"],message:"Only a valid declaration carries a manifest"})}),jt=e.strictObject({projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"]),execution:e.enum(["indiana","record_only"]),accountId:e.string().nullable(),revision:e.number().int().nonnegative(),authentication:e.strictObject({keyId:ue}).nullable(),secretStoreConfigured:e.boolean().optional(),connection:de.nullable(),check:$e.nullable()});var se=e.strictObject({projectId:e.uuid(),environmentId:e.uuid()}),Pt=e.discriminatedUnion("action",[se.extend({action:e.literal("save"),revision:e.number().int().nonnegative(),connection:de,authentication:De.optional()}),se.extend({action:e.literal("check"),revision:e.number().int().nonnegative()})]),_=e.strictObject({projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"])});function qt(t){return e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),command:$,scope:_,data:t})}var le=e.strictObject({nativeUserId:e.string().min(1).max(128),session:Z.strict()}),pe=e.strictObject({nativeUserId:e.string().min(1).max(128),presentation:e.strictObject({customerId:e.uuid(),decisionId:e.uuid(),offeringVersionId:e.uuid(),paywallVersionId:e.uuid(),variant:e.string().min(1).max(128)}).nullable()}),he=e.strictObject({decisionId:e.uuid(),eventId:e.uuid()}),O=e.strictObject({operationId:e.uuid(),customerId:e.uuid()}),Ct=e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),command:e.string().min(1).max(64),scope:_,error:e.strictObject({code:e.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:e.string().min(1).max(500),retryable:e.boolean(),recovery:e.string().min(1).max(80)})});var zt=e.strictObject({scope:_,operationId:e.uuid(),customerId:e.uuid(),confirmedAt:e.iso.datetime({offset:!0}).nullable(),initialExecutionAllowed:e.boolean(),instruction:Y,merchantTerms:U.optional()}).refine(t=>t.operationId===t.instruction.operationId&&t.customerId===t.instruction.customerId&&(!t.merchantTerms||t.merchantTerms.request.operationId===t.operationId&&t.merchantTerms.request.subject.customerId===t.customerId&&t.merchantTerms.request.action===t.instruction.type&&t.merchantTerms.currency===t.instruction.currency&&Object.entries(t.scope).every(([n,r])=>t.merchantTerms.request.subject.scope[n]===r)),"Authority must refer to the original Customer and operation"),N=T,d=e.string().min(1).max(120),Ve=e.string().regex(/^-?[0-9]+(?:\.[0-9]{1,6})?$/),Ne=e.strictObject({revision:d,updatedAt:e.iso.datetime(),provider:e.literal("merchant"),items:e.array(e.strictObject({merchantProductId:d,productVersionId:e.uuid(),name:e.string().min(1).max(255),kind:e.enum(["subscription","credit_pack"]),merchantPriceId:d,currency:e.string().regex(/^[a-z]{3}$/),amountMinor:e.number().int().nonnegative().max(1e8),interval:e.enum(["one_time","month","year"]),intervalCount:e.literal(1),includedCredits:e.string().regex(/^[0-9]{1,18}(?:\.[0-9]{1,6})?$/),creditReset:e.enum(["none","month"]),creditPolicyId:d,available:e.boolean()}).superRefine((t,n)=>{(t.kind==="credit_pack"&&(t.interval!=="one_time"||t.creditReset!=="none")||t.kind==="subscription"&&t.interval==="one_time"||t.available&&t.amountMinor===0)&&n.addIssue({code:"custom",message:"Unsupported version 1 catalog terms"})})).max(500)}),Le=e.strictObject({customerId:e.uuid(),revision:e.string().min(1).max(128),observedAt:e.iso.datetime(),subscriptions:e.array(e.strictObject({merchantSubscriptionId:d,merchantProductId:d,productVersionId:e.uuid().nullable(),status:e.enum(["active","trialing","past_due","cancelled","expired"]),currentPeriodStartsAt:e.iso.datetime().nullable(),currentPeriodEndsAt:e.iso.datetime().nullable(),cancelAtPeriodEnd:e.boolean(),scheduledChange:e.strictObject({effectiveAt:e.iso.datetime(),merchantProductId:d}).nullable()})).max(100),purchaseHistory:e.strictObject({complete:e.boolean(),hasPaidPurchase:e.boolean(),lastPaidAt:e.iso.datetime().nullable()}),balances:e.array(e.strictObject({bucketId:d,key:d,available:Ve,expiresAt:e.iso.datetime().nullable(),nextResetAt:e.iso.datetime().nullable()})).max(100)}),v=e.strictObject({}),Fe={"bridge.ping":e.strictObject({challenge:e.uuid()}),"bridge.describe":v,"session.create":v,"catalog.read":v,"customer.commerce.read":v,"presentation.resolve":v,"presentation.report":he,"purchase.execute":O,"operation.read":O,"subscription.change":O,"refund.execute":O},wt={"bridge.ping":e.strictObject({challenge:e.uuid()}),"bridge.describe":V,"session.create":le,"catalog.read":Ne,"customer.commerce.read":Le,"presentation.resolve":pe,"presentation.report":e.strictObject({queued:e.literal(!0)}),"purchase.execute":N,"operation.read":ee,"subscription.change":N,"refund.execute":N},Dt=e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),scope:_,command:$,data:e.unknown()}).superRefine((t,n)=>{Fe[t.command].safeParse(t.data).success||n.addIssue({code:"custom",path:["data"],message:"Invalid command data"})});export{ge as a,S as b,xe as c,We as d,Xe as e,ye as f,T as g,ee as h,p as i,Je as j,z as k,qe as l,ne as m,re as n,P as o,ht as p,U as q,bt as r,ft as s,gt as t,Te as u,xt as v,yt as w,M as x,Ot as y,vt as z,Re as A,At as B,De as C,Ue as D,V as E,_ as F,qt as G,le as H,pe as I,he as J,O as K,Ct as L,zt as M,N,Le as O,Fe as P,wt as Q,Dt as R};
@@ -0,0 +1 @@
1
+ var t="https://api.longplayai.com";var p={name:"@tinkerlandai/longplay-sdk",version:"0.10.35",description:"Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit && tsc --noEmit -p tsconfig.test.json",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};export{p as a,t as b};
@@ -0,0 +1 @@
1
+ import{a as Vn,b as Un,c as ln,d as un,e as Ue,f as Mn,g as $n,h as xn,i as Gn}from"./chunk-SFHIFCXG.js";import{b as Qn}from"./chunk-YVXLCQGM.js";import{b as En,c as Jn}from"./chunk-73NP72FV.js";import{a as Sn}from"./chunk-W32FI2A2.js";import{c as On,e as An,f as _n,h as Ln,i as Ae,j as Ze,k as Hn,l as Ke}from"./chunk-XUGEOELU.js";import{$ as Xe}from"./chunk-TAFALMQN.js";import{a as Ve,d as qn}from"./chunk-3NCMYTNG.js";import{b as Pn}from"./chunk-VEX2FOFZ.js";import{a as Dn,c as kn,d as Tn,e as Nn,f as Fn}from"./chunk-V7PFLFHE.js";import{E as Cn,da as Rn}from"./chunk-BQRS7Y4K.js";import{a as m}from"./chunk-OX7PA64E.js";import{a as Ce}from"./chunk-DSPLGTQI.js";async function dn(t){let{session:b,load:C}=nt(t);try{return await C(),b}catch(e){throw b.destroy(),e}}function nt(t){let b=t.view;if(!b?.paywall)throw new m("INVALID_REQUEST","The current node is not a Paywall");let C=b.paywall.receiptId,e=b.nodeId,w=b.visit,k=b.paywall.resolution,o=b.paywall,F="document"in k?{document:k.document,offering:k.offering,capabilities:k.capabilities}:null;function c(){let i=o.resolution;return"document"in i?i:F&&{...i,document:F.document,offering:F.offering,capabilities:Dn(i.capabilities,F.capabilities)}}function I(i){if(!kn(i,k))throw new m("INVALID_RESPONSE","The pinned Paywall binding changed")}let P=!1,U=new Set,ne=null;function f(){let i=c();if(i&&!P)for(let u of U)Ce(u,structuredClone(i))}async function L(){T();let i=c();if(i)return structuredClone(i);if(!ne){let u=(async()=>{if("document"in o.resolution||!t.resolvePaywall)throw new m("INVALID_RESPONSE","Public Paywall reader is unavailable");let g=await En(t,o.resolution);return T(),I(g),F={document:g.document,offering:g.offering,capabilities:g.capabilities},f(),c()})();ne=u;let a=()=>{ne===u&&(ne=null)};u.then(a,a)}return ne.then(u=>structuredClone(u))}let s=new AbortController,S=(t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])).find(i=>i.operation==="submit"&&i.nodeId===e&&i.visit===w&&i.input.type==="paywall_quote")?.requestId??b.paywall.purchaseRequestId,Y=0,Q=null,G=new Set,E=null,J=new Map;function D(i){if(i.purchase&&i.purchase.receiptId!==C)throw new m("INVALID_RESPONSE","Purchase receipt changed");let u=i.run.paywall;return i.purchase??(u?.receiptId===C?u:null)}function T(){if(P)throw new m("IDENTITY_CHANGED","Paywall presentation has closed")}function N(i,u,a){if(T(),u!==Y||a!==void 0&&o.quote?.operationId!==a)return!1;let g=o.selectionGeneration??0,d=i.run.paywall;if(d?.receiptId===C){if((d.selectionGeneration??0)<(o.selectionGeneration??0))return!1;I(d.resolution)}let l=D(i),H=d?.receiptId===C&&(d.selectionGeneration??0)>g,V=H?l?.quote??null:l?.quote??o.quote,O=l?.operation??(V?.operationId===o.quote?.operationId?o.operation:null);return V&&O&&Tn(O,{operationId:V.operationId},"Purchase operation changed"),(H||V?.operationId!==o.quote?.operationId)&&(Y++,d?.receiptId===C&&(S=d.purchaseRequestId)),d?.canReselect===!0&&d.purchaseRequestId===E&&!(t.pendingCommands??[t.pendingCommand]).some(te=>te?.requestId===E)&&(E=null),o={...o,...d?.receiptId===C?d:{},...a!==void 0&&!H&&l?.canReselect!==void 0?{canReselect:l.canReselect}:{},quote:V,operation:Fn(o.operation,O,!0)},f(),!0}function ce(i,u,a){return new Promise((g,d)=>{let l=!1,H=()=>{clearTimeout(Te),s.signal.removeEventListener("abort",te)},V=Ee=>{l||(l=!0,H(),g(Ee))},O=Ee=>{l||(l=!0,H(),d(Ee))},te=()=>O(new m("IDENTITY_CHANGED","Paywall presentation has closed")),Te=setTimeout(()=>O(new m("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,a)),Math.max(0,u-Date.now()));s.signal.addEventListener("abort",te,{once:!0}),s.signal.aborted&&te(),i.then(V,O)})}function pe(i){return new Promise(u=>{let a=()=>{clearTimeout(g),s.signal.removeEventListener("abort",a),u()},g=setTimeout(a,i);s.signal.addEventListener("abort",a,{once:!0}),s.signal.aborted&&a()})}function B(i,u){T();let a=J.get(i)??t.pendingCommands?.find(l=>l.requestId===i)??t.pendingCommand;if(a?.operation==="submit"&&a.requestId===i&&a.nodeId===e&&a.visit===w){u.type==="paywall_quote"&&a.input.type==="paywall_quote"&&a.input.predecessor&&!u.predecessor&&(u={...u,predecessor:a.input.predecessor});let l=Xe.parse(a),H=Xe.parse({...a,input:u});if(l.operation!=="submit"||H.operation!=="submit"||JSON.stringify(l.input)!==JSON.stringify(H.input))throw new m("CONFLICT","A purchase request cannot change its input");return J.set(i,l),l}let g=t.view;if(!g||g.nodeId!==e||g.visit!==w||g.paywall?.receiptId!==C)throw new m("PRECONDITION_FAILED","The Paywall visit has changed");let d=Xe.parse({operation:"submit",requestId:i,nodeId:e,visit:w,revision:g.revision,input:structuredClone(u)});if(d.operation!=="submit")throw new m("INVALID_REQUEST","A purchase submission is required");return J.set(i,d),d}async function Pe(i,u){T();let{requestId:a,input:g}=i,d=Date.now()+3e4;G.add(a);try{let l=await ce(t.submit(i),d,a);for(;l.run.pendingRequest?.requestId===a&&Date.now()<d&&!P&&(await pe(Math.min(1e3,d-Date.now())),!(P||Date.now()>=d));)l=await ce(t.resume(a),d,a);if(P)throw new m("IDENTITY_CHANGED","Paywall presentation has closed");if(l.run.pendingRequest?.requestId===a)throw new m("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,a);if(!N(l,u,g.type==="paywall_confirm"||g.type==="paywall_cancel"?g.operationId:void 0))throw new m("PRECONDITION_FAILED","The purchase selection has changed");E===a&&(E=null)}catch(l){if(E=a,g.type==="paywall_quote"&&t.settle&&!P&&l instanceof m&&l.status!==void 0&&![401,425].includes(l.status)&&!l.retryable&&l.recovery!=="recover_operation")try{if((await ce(t.settle(a),d,a)).settlement?.state==="settled"){let V=await ce(t.get(),d,a);N(V,u)&&V.run.paywall?.purchaseRequestId===a&&o.canReselect===!0&&J.delete(a)}}catch{}throw l instanceof m&&l.code==="COMMAND_PENDING"&&l.status===void 0&&J.delete(a),l}finally{G.delete(a)}}async function X(i){if(!o.quote)throw new m("INVALID_REQUEST","A quoted purchase is required");let u=i==="confirm"?"paywall_confirm":"paywall_cancel",a=[...J.values(),...t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])].find(d=>d.operation==="submit"&&d.input.type===u&&"operationId"in d.input&&d.input.operationId===o.quote.operationId),g=a?.operation==="submit"&&a.input.type===u&&"operationId"in a.input&&a.input.operationId===o.quote.operationId?a.requestId:crypto.randomUUID();if(await Pe(B(g,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:o.quote.operationId}),Y),!o.operation)throw new m("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(o.operation)}let M={get view(){return structuredClone(c())},get quote(){return o.quote?structuredClone(o.quote):null},get operation(){return o.operation?structuredClone(o.operation):null},get webViewUrl(){return t.webViewUrl},get canReselect(){return o.canReselect===!0&&E===null},get recovery(){let i=t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[]),u=t.pendingPurchase;if(u&&(u.receiptId!==C||u.operationId!==o.quote?.operationId))return{type:"recover",operationId:u.operationId,requestId:i[0]?.requestId??null};let a=Ve({quote:o.quote,operation:o.operation,requestId:i[0]?.requestId??E??S,pending:G.size>0||i.length>0||E!==null,destroyed:P,canReselect:o.canReselect});return a.type==="recover"&&a.requestId===null&&!P&&t.hasDurableJournal===!0&&!o.quote&&!o.operation&&(o.selectionGeneration??0)===0&&!u&&!i.length&&!G.size&&!S?{type:"native",operationId:null}:a},get pendingCancellation(){return!P&&(t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])).some(i=>i.operation==="submit"&&i.nodeId===e&&i.visit===w&&i.input.type==="paywall_cancel"&&i.input.operationId===o.quote?.operationId)},subscribe(i){return P?()=>{}:(U.add(i),()=>U.delete(i))},async refresh(){T();let i=Y,u=await t.get();if(N(u,i),u.run.paywall?.receiptId!==C)throw new m("PRECONDITION_FAILED","Paywall presentation has changed");return L()},preview(i){let u=c();if(!u)return Promise.reject(new m("PRECONDITION_FAILED","Load the Paywall presentation first"));if(S&&S!==i.requestId&&(Q||o.canReselect!==!0))return Promise.reject(new m("COMMAND_PENDING","Retry the original purchase before starting another"));let a=u.document.buttons[i.actionId],g=a?.type==="checkout"?Pn(a.product,i.selection,u.capabilities):null;if(!g)return Promise.reject(new m("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let d=Rn(u.document.screen,g,i.selection,u.capabilities),l=S!==i.requestId&&(o.selectionGeneration??0)>0?{operationId:o.quote?.operationId??null,generation:o.selectionGeneration??0}:void 0;if(l&&o.canReselect!==!0)return Promise.reject(new m("COMMAND_PENDING","Original purchase requires authoritative termination"));let H;try{H=B(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:g,...Object.keys(d).length?{featureQuantities:d}:{},...l?{predecessor:l}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{}})}catch(te){return Promise.reject(te)}if(S===i.requestId&&Q)return Q;S!==i.requestId&&Y++;let V=Y;S=i.requestId;let O=(async()=>{if(await Pe(H,V),!o.quote)throw new m("INVALID_RESPONSE","The accepted quote is missing");return Nn(o.quote,{productVersionId:g,featureQuantities:d},"The selected purchase changed"),structuredClone(o.quote)})();return Q=O,O.then(()=>{Q===O&&(Q=null)},te=>{Q===O&&(Q=null),S===i.requestId&&t.pendingCommand?.requestId!==i.requestId&&te instanceof m&&te.status!==void 0&&te.status<500&&![401,425].includes(te.status)&&(S=null)}),O},confirm:()=>X("confirm"),cancel:()=>X("cancel"),async read(){if(T(),!o.quote)throw new m("INVALID_REQUEST","A quoted purchase is required");let i=o.quote.operationId,u=Y,a=t.pendingCommands?.find(V=>V.operation==="submit"&&(V.input.type==="paywall_confirm"||V.input.type==="paywall_cancel")&&V.input.operationId===i)??t.pendingCommand;a?.operation==="submit"&&(a.input.type==="paywall_confirm"||a.input.type==="paywall_cancel")&&a.input.operationId===i&&await t.settle?.(a.requestId);let g=await t.get(void 0,{receiptId:C,operationId:i});T();let d=D(g);if(d?.quote&&d.quote.operationId!==i||d?.operation&&d.operation.operationId!==i)throw new m("INVALID_RESPONSE","Purchase operation changed");let l=N(g,u,i),H=l?o.operation:d?.operation;if(!H)throw new m("INVALID_RESPONSE","The current purchase result is missing");return l&&G.size===0&&!(t.pendingCommands?.length??(t.pendingCommand?1:0))&&(E=null),structuredClone(H)},destroy(){P=!0,j(),U.clear(),s.abort(),J.clear()}},j=t.subscribe(i=>{P||i.nodeId!==e||i.visit!==w||i.paywall?.receiptId!==C||(i.paywall.selectionGeneration??0)<(o.selectionGeneration??0)||(I(i.paywall.resolution),o={...o,resolution:i.paywall.resolution},f())});return{session:M,load:L}}function zn(t){let b=new Set,C=new Set,e=null;async function w(c,I){let P=!1;for(;!t.stopped&&t.key===c&&t.client.pendingCommand?.requestId===I;){if(!t.client.settle)throw new m("COMMAND_PENDING","The original display acknowledgement is still pending");await t.client.settle(I),P=!0,t.client.pendingCommand?.requestId===I&&await new Promise(U=>setTimeout(U,1500))}t.stopped||t.key!==c||(P&&await t.client.get(),!(t.stopped||t.key!==c)&&b.add(c))}function k(c,I){e=I;let P=()=>{e===I&&(e=null),C.delete(c)};return I.then(P,U=>{P(),t.busy||t.fail(U)}),I}function o(c){if(t.reviewing||b.has(c)||C.has(c)||t.stopped)return;C.add(c);let I=async()=>{if(t.reviewing||t.stopped||t.key!==c||b.has(c)){C.delete(c);return}if(t.busy||t.client.pendingCommand){setTimeout(()=>{I()},250);return}let P=(async()=>{if(t.staleRead){if(await t.staleRead,t.stopped||t.key!==c)return;if(t.client.pendingCommand){setTimeout(()=>{I()},250);return}}let U=t.client.view,ne=t.expected(),f=ne.requestId;try{await t.client.submit({operation:"shown",...ne})}catch(L){if(!(L instanceof m)||L.code!=="CONFLICT"||L.status!==409||t.client.pendingCommand)throw L;await t.client.get();let s=t.client.view;if(t.stopped||t.reviewing||t.key!==c||!s||!U||s.id!==U.id||s.source.versionId!==U.source.versionId||s.nodeId!==ne.nodeId||s.visit!==ne.visit||s.revision<=ne.revision||s.stopped||!s.screen&&(!s.paywall||s.paywall.receiptId!==U.paywall?.receiptId)||!["running","waiting"].includes(s.status)||t.client.pendingCommand)throw L;let R=t.expected();f=R.requestId,await t.client.submit({operation:"shown",...R})}await w(c,f)})();k(c,P)};I()}function F(){if(e)return e;let c=t.client.pendingCommand;if(c?.operation!=="shown")return null;let I=t.key;return C.add(I),k(I,(async()=>{await t.client.retry(),await w(I,c.requestId)})())}return{report:o,settled:F,get inFlight(){return e}}}function Bn(t){let b={},C=new Map;async function e(w){let k=t.client.view,o=k?.screen,F=o?.customerData.nodes[w.nodeId];if(t.stopped||t.busy||!k||!o||!F)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(w.action)){let L=t.document,s=L?Cn(L,w.nodeId):null,R=s?.type==="customer_data"?s.data.outputs?.[w.action]:void 0;R&&o.outputs.includes(R)?await t.perform(()=>t.client.submit({operation:"submit",...t.expected(),input:{type:"screen",output:R,answers:t.answers,selection:w.value?{[w.nodeId]:w.value}:{}}})):await t.onIntent?.(w,k);return}let I=w.action.startsWith("sources_")?F.resources.find(L=>L.key===w.value):null;if(w.action.startsWith("sources_")&&!I)throw new m("INVALID_REQUEST","Choose a current resource");let P=`${k.visit}:${w.nodeId}:${I?.key??""}`,U=C.get(P)??[null],f=b[w.nodeId]??{page:1,after:null,filter:"all",...I?{resourceKey:I.key}:{}};if(w.action==="filter"){let L=w.value;if(!L||!(F.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(L))throw new m("INVALID_REQUEST","Unknown data filter");f={page:1,after:null,filter:L},U.splice(0,U.length,null)}else if(w.action==="next"||w.action==="sources_next"){let L=I?.sources.at(-1),s=I?L?{kind:"ledger",cursor:{at:L.detail[0],id:L.id,type:"source"}}:null:o.dataCursors[w.nodeId];if(!s||!I&&!F.hasNext)return;U[f.page]=s,f={...f,page:f.page+1,after:s}}else if(w.action==="previous"||w.action==="sources_previous"){if(f.page<=1)return;f={...f,page:f.page-1,after:U[f.page-2]??null}}C.set(P,U),b={...b,[w.nodeId]:f},await t.perform(()=>t.client.get({nodeId:k.nodeId,visit:k.visit,revision:k.revision,components:b}))}return{get queries(){return b},intent:e,reset(){b={},C.clear()}}}function jn(t){let{doc:b,holder:C,reviewHolder:e,mountScreenPreview:w}=t,k=!1,o,F=0,c=null,I="",P,U=new Map,ne=s=>s?`${s.id}:${s.nodeId}:${s.visit}:${s.revision}:${s.paywall?.quote?.operationId??""}`:"";async function f(s){if(t.stopped||!t.client.review||k&&s===o&&P?.active)return;let R=!k||s!==o;k||(I=ne(t.client.view),U.set(I,structuredClone(t.answers))),k=!0,o=s,C.hidden=!0,t.suspend(!0),e.hidden=!1;let S=++F;R&&(P?.finish("dismissed"),c?.destroy(),c=null,e.replaceChildren(),P=Ze(e,t.loadingOptions,"funnel",()=>{L()}));let Y=R?P:void 0;try{if(Y?.start(!1,t.client.view?.locale),S!==F||t.stopped)return;let Q=t.client.review(s),G=await(Y?.wait(Q,Ae)??Q);if(t.stopped||S!==F||!k)return;if(!G.review)throw new m("INVALID_RESPONSE","Historical projection is missing");c?.destroy(),c=null,Y||e.replaceChildren();let E=b.createElement("div"),J=Y?Ke(E,e):()=>{};e.append(E);let D=G.run.locale.startsWith("zh"),T=t.chrome;E.style.cssText=T.history;let N=b.createElement("p");N.textContent=D?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",N.style.cssText=T.historyTitle,E.append(N);let ce=b.createElement("p");ce.style.cssText=T.historyNote,ce.textContent=G.review.pages.length?D?"\u9009\u62E9\u4E00\u9875\u67E5\u770B\u5F53\u65F6\u7684\u5185\u5BB9\uFF0C\u56DE\u770B\u4E0D\u4F1A\u6539\u52A8\u4EFB\u4F55\u4FE1\u606F\u3002":"Choose a page to see it as it was. Nothing here can be changed.":D?"\u8FD8\u6CA1\u6709\u53EF\u56DE\u770B\u7684\u9875\u9762\u3002":"There are no earlier pages yet.",E.append(ce);let pe=G.review.page?.receiptId,B=b.createElement("div");B.style.cssText=T.historyPages;for(let[M,j]of G.review.pages.entries()){let i=b.createElement("button");i.type="button",i.textContent=D?`\u7B2C ${M+1} \u9875`:`Page ${M+1}`;let u=pe!==void 0&&j.receiptId===pe;i.style.cssText=u?T.primary:T.secondary,u&&i.setAttribute("aria-current","page"),Ue(i,()=>t.chrome.focus),i.onclick=()=>{f(j.receiptId)},B.append(i)}if(B.childElementCount&&E.append(B),G.review.page){let M=G.review.page,j=b.createElement("div");j.inert=!0,j.style.cssText=T.historyPage,E.append(j),c=w(j,{mode:"live",rendererUrl:t.client.webViewUrl,title:M.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{S===F&&!t.stopped&&Y?.present(J)},onError:u=>{if(S!==F||t.stopped)return;let a=new Error(u);Y?.finish("error",a),c?.destroy(),c=null,E.remove(),t.fail(a)},onEscape:()=>{L()}});let i=c;if(i.update(M.document,G.run.locale,{serverInput:{bindings:M.inputs,answers:M.answers,values:M.values}}),await i.ready,t.stopped||S!==F||!k)return}let Pe=D?{issued:"\u5DF2\u9886\u53D6",reserved:"\u5DF2\u9884\u7559",redeemed:"\u5DF2\u4F7F\u7528",expired:"\u5DF2\u8FC7\u671F",revoked:"\u5DF2\u64A4\u9500",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},X=b.createElement("div");X.style.cssText=T.historyRecords;for(let M of[...G.review.coupons.map((j,i)=>`${D?"\u4F18\u60E0\u5238":"Coupon"} ${i+1}: ${Pe[j.status]}`),...G.review.purchases.map((j,i)=>`${D?"\u8D2D\u4E70":"Purchase"} ${i+1}: ${Gn(j.status,D)}`)]){let j=b.createElement("p");j.textContent=M,j.style.margin="0",X.append(j)}X.childElementCount&&E.append(X),G.review.page||Y?.present(J),t.client.view&&await t.enqueue(t.client.view)}catch(Q){if(S!==F||t.stopped)return;Y?.finish("error",Q),c?.destroy(),c=null,e.replaceChildren(),t.fail(Q)}}async function L(){if(!k||t.stopped||!t.client.review)return;let s=++F;P?.finish("dismissed");try{if(await t.client.review(),t.stopped||s!==F)return;k=!1,F++,P?.finish("dismissed"),c?.destroy(),c=null,e.replaceChildren(),e.hidden=!0,C.hidden=!1;let R=t.client.view;ne(R)!==I?(U.set(I,structuredClone(t.answers)),t.resetScreen()):(U.delete(I),t.suspend(!1)),R&&await t.enqueue(R)}catch(R){if(s!==F||t.stopped)return;c?.destroy(),c=null,e.replaceChildren(),t.fail(R)}}return{get active(){return k},get receipt(){return o},open:f,exit:L,get drafts(){return new Map([...U].map(([s,R])=>[s,structuredClone(R)]))},stop(){k=!1,F++,P?.finish("dismissed"),c?.destroy(),c=null,e.replaceChildren(),e.hidden=!0,C.hidden=!1}}}var cn=5e3;async function tt(t,b,C){let e=b,w=e.prepared&&Qn(e.prepared),k=()=>{};function o(){e.prepared&&e.prepared.state!=="adopted"&&w?.release()}let F=()=>e.prepared?.state==="shown"&&!!w?.modal,c=e.client.identitySignal,I;try{I=await Promise.all([import("./screen-renderer-R5GH7XLV.js"),import("./paywall-VYUBYBUI.js")]),e.signal?.throwIfAborted(),c?.throwIfAborted()}catch(n){throw o(),n}let[{mountScreenPreview:P},{showPaywall:U}]=I,ne=(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&e.appManifestRelease?Jn({client:e.client,appManifestRelease:e.appManifestRelease,onError:e.onError}):void 0;ne?.start();let f=t.ownerDocument,L=Ln(f),s=f.createElement("section"),R=f.createElement("div"),S=f.createElement("div"),Y=f.createElement("div"),Q=f.createElement("button");Y.hidden=!0,Q.type="button";let G=f.createElement("p"),E=f.createElement("p"),J=f.createElement("button"),D=f.createElement("button"),T=f.createElement("button"),N=f.createElement("dialog"),ce;s.dataset.indianaFunnel="",s.setAttribute("aria-busy","false"),G.setAttribute("role","status"),E.setAttribute("role","alert"),E.hidden=!0,J.type=D.type=T.type="button",S.append(J,Q,G,E,T,D),s.append(R,Y,S),t.append(s);let pe=Un,B=ln(pe),Pe="",X=(f.documentElement.lang||"").startsWith("zh"),M,j="",i;for(let n of[J,Q,T,D])Ue(n,()=>B.focus);function u(){let n=X?"\u5173\u95ED":"Close";D.parentElement===N?(D.textContent="\xD7",D.setAttribute("aria-label",n),_n(D,pe)):(D.textContent=n,D.removeAttribute("aria-label"),D.style.cssText=B.link+";margin-inline-start:auto")}function a(n){let r=n?.screen?.content.document.theme??pe,p=JSON.stringify([r.primary,r.background,r.text,r.radius,r.font,D.parentElement===N]);if(p===Pe)return;Pe=p,pe=r;let _=D.parentElement===N;B=ln(pe,_),s.style.cssText=B.root+";min-width:0"+(_?";display:flex;flex-direction:column;min-height:100%":""),S.style.cssText=B.bar+(_?";margin-top:auto":""),J.style.cssText=Q.style.cssText=B.secondary,T.style.cssText=B.primary,G.style.cssText=B.status,E.style.cssText=B.alert,u(),un(J)}function g(){S.hidden=J.hidden&&Q.hidden&&T.hidden&&E.hidden&&!G.textContent&&(D.hidden||D.parentElement!==S),M?.responsive&&i!==void 0&&M.setContentHeight(i+S.getBoundingClientRect().height)}a();let d=null,l=null,H=null,V="",O="",te=!1,Te="",Ee="",Me="",h=!1,le=0,$e=!1,pn="",en=null,nn=Promise.resolve(),fn=!e.client.view,z=C,Ne,_e,xe="",Ge,ue=!1,qe=null,he=!1,Qe=()=>e.client.pendingCommand?.operation==="close",de=null,Z=null,mn=Sn({document:f,run:async()=>{(!l?.observing||e.client.pendingCommand)&&await rn()},delay:()=>{if(!(h||!H||!["running","waiting"].includes(H.status)&&!e.client.pendingCommand)&&!(l?.observing&&!e.client.pendingCommand))return H.pendingRequest||e.client.pendingCommand?1500:cn},hiddenDelay:()=>!h&&e.client.pendingCommand?15e3:void 0}),K=null;function tn(){return Z&&e.client.hasDurableJournal===!0&&K?.acknowledged===!0&&K.operationId===Z.operationId&&e.client.view?.id===K.runId&&e.client.view?.status==="closed"&&e.client.view.revision===K.revision+1&&!(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0))&&!e.client.pendingPurchase?Z:null}function wn(n){let r=n.run.paywall;if(K&&n.settlement?.requestId===K.requestId&&n.settlement.state==="settled"&&n.settlement.operationId===null&&n.run.id===K.runId&&n.run.status==="closed"&&!n.run.pendingRequest&&n.run.revision===K.revision+1&&n.run.nodeId===K.nodeId&&n.run.visit===K.visit&&r?.receiptId===K.receiptId&&r.selectionGeneration===K.selectionGeneration&&(r.quote?.operationId??null)===K.operationId&&(r.operation?.operationId??r.quote?.operationId??null)===K.operationId){let p=K.operationId===null&&r.selectionGeneration===0&&!r.quote&&!r.operation&&!r.purchaseRequestId,_=Ve({quote:r.quote,operation:r.operation,requestId:r.purchaseRequestId,pending:!1,destroyed:!1,canReselect:r.canReselect});(p||r.canReselect===!0&&_.type==="native")&&(K.acknowledged=!0)}}let De=null,Je=new Set,we={},Fe=!1,fe=(n,r=null)=>{h||(De=r,Fe=!1,E.textContent=Mn(n,X),E.hidden=!1,T.hidden=e.client.pendingCommand===null,g(),Ce(e.onError,n))},yn=()=>{h||(De=null,E.textContent=$n(X),E.hidden=!1,T.hidden=!0,g())};function ke(){let n=e.client.view;if(!n)throw new m("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:n.revision}}let A=jn({client:e.client,doc:f,holder:R,reviewHolder:Y,mountScreenPreview:P,loadingOptions:e,get chrome(){return B},get stopped(){return h},get answers(){return we},suspend(n){l?.setSuspended(n)},resetScreen(){V="",O="",Te=""},enqueue:ye,fail:fe}),Le=zn({client:e.client,expected:ke,fail:fe,get stopped(){return h},get reviewing(){return A.active},get key(){return V},get busy(){return le},get staleRead(){return en}}),ze=Bn({client:e.client,expected:ke,perform:Oe,onIntent:e.onCustomerDataIntent,get stopped(){return h},get busy(){return le},get document(){return d?.document},get answers(){return we}}),Be=n=>`${n.id}:${n.nodeId}:${n.visit}`,Se=n=>n&&(n.screen||n.paywall)?Be(n):"";function Re(){let n=e.client.view;J.disabled=!A.active&&(le>0||!!e.client.pendingCommand||!n?.canBack||n.stopped||!["running","waiting"].includes(n.status)||!Se(n)||O!==Se(n)),J.hidden=!A.active&&!n?.canBack,un(J);let r=!!l&&!A.active;D.hidden=r&&!z?.active,Q.hidden=!e.client.review||r&&!n?.canBack,r&&(G.textContent=""),g()}async function gn(n){if(!n)return;let r=e.client.view;await n;let p=e.client.view;if(!r||!p||p.id!==r.id||p.nodeId!==r.nodeId||p.visit!==r.visit||p.stopped||!["running","waiting"].includes(p.status))throw new m("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Oe(n,r=!1,p){if(!((le||he||de||Z)&&!r||h||A.active&&!r)){le++,s.setAttribute("aria-busy","true"),E.hidden=!0,De=null,Fe=!1,Re();try{if(r||await gn(Le.inFlight),h)return;let _=await n();h||await ye(e.client.view??_.run)}catch(_){p?.(_)&&e.client.pendingCommand===null?yn():fe(_,e.client.pendingCommand?.requestId??null)}finally{le=Math.max(0,le-1),s.setAttribute("aria-busy",String(le>0)),h||(T.hidden=e.client.pendingCommand===null,Re())}}}function He(){mn.schedule()}async function rn(){if(!(h||$e||le)){if(A.active){await A.open(A.receipt);return}$e=!0;try{let n=e.client.pendingCommand;n&&e.client.settle&&await e.client.settle(n.requestId);let r=e.client.view,p=ze.queries,_=await e.client.get(r?.screen&&Object.keys(p).length?{nodeId:r.nodeId,visit:r.visit,revision:r.revision,components:p}:void 0);Fe&&!h&&(Fe=!1,E.hidden=!0,g()),!h&&p===ze.queries&&await ye(e.client.view??_.run)}catch(n){fe(n),Fe=!h}finally{$e=!1}}}function je(n,r,p){if(z?.active){let ae=z;return ae.setDismissHandler(()=>hn(ae)),ae}let _=Ze(t,e,"funnel",()=>hn(_),Vn);return z=_,_.start(n,r,p),_}function hn(n){h||ue||(ue=!0,n.finish("dismissed"),ve(),s.hidden=!0,e.client.view?Ie().finally(re):re())}function on(){clearTimeout(Ge?.timeout),Ge=void 0}function ve(){on(),Ne?.abort(),Ne=void 0,d?.destroy(),d=null,l?.destroy(),l=null,_e?.(),_e=void 0,N.open&&N.close(),R.replaceChildren(),R.style.cssText="",i=void 0,V="",O="",te=!1,Te="",Me=""}function vn(){let n=f.defaultView;M?.responsive&&n&&d?.resizeViewport?.(n.innerHeight,n.innerWidth)}function sn(){M?.destroy(),M=void 0,j=""}function We(n){let r=n.screen?.presentation;if(!r||r.type==="inline"){N.open&&N.close(),sn(),D.parentElement!==S&&S.append(D),s.parentElement!==t&&t.append(s);for(let ae of["flex","display","flex-direction","justify-content"])R.style.removeProperty(ae);a(n),g();return}s.parentElement!==N&&(N.append(D,s),t.append(N)),R.style.flex="1 0 auto",R.style.display="flex",R.style.flexDirection="column",R.style.justifyContent="center",a(n);let p=n.screen.content.document,_=JSON.stringify([r,Pe]);if(_!==j){sn(),j=_;let ae={sm:420,md:640,lg:900},ge="size"in r&&!r.backdrop?",0 0 0 100vmax #16142566":"";N.style.cssText=`box-sizing:border-box;padding:0;border:0;overflow:auto;background:${pe.background};color:${pe.text};`+(r.type==="fullscreen"?"width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;margin:0;border-radius:0":`width:${ae[r.size]}px;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0003${ge};`+(r.type==="sheet"?"margin:auto auto 0;border-radius:14px 14px 0 0":"border-radius:14px")),M=On(N,{presentation:r,theme:p.theme,pages:p.pages},vn),M.latch()}g(),N.setAttribute("aria-label",(ce?.screen===n.screen?.content.document.name?ce?.label:void 0)??d?.document?.name??n.screen?.content.document.name??"Funnel")}async function Wn(n){if(h||ue||he&&(Qe()||["running","waiting"].includes(n.status))||(H=n,De&&e.client.pendingCommand?.requestId!==De&&(E.hidden=!0,De=null),X=n.locale.startsWith("zh"),Q.textContent=X?"\u56DE\u770B":"History",J.textContent=A.active?X?"\u8FD4\u56DE\u5F53\u524D":"Return to current":X?"\u8FD4\u56DE":"Back",u(),T.textContent=X?"\u91CD\u8BD5":"Retry",T.hidden=e.client.pendingCommand===null,G.textContent=n.pendingRequest?X?"\u6B63\u5728\u5904\u7406":"Processing":n.instruction?.type==="wait"?X?"\u7B49\u5F85\u4E2D":"Waiting":"",Re(),pn!==`${n.revision}:${n.visit}:${n.status}:${n.stopped}`&&(pn=`${n.revision}:${n.visit}:${n.status}:${n.stopped}`,Ce(e.onState,structuredClone(n))),h||ue))return;if((!n.pendingRequest||he&&n.status==="closed")&&["closed","ineligible","failed"].includes(n.status)){re();return}if(n.stopped&&F()){re();return}if(n.stopped||e.client.configurationReady===!1){A.stop(),o(),ve(),z?.finish("skipped"),s.hidden=!0,He();return}if(s.hidden=!1,A.active){He();return}let r=Se(n),p=e.client.view;if(p&&p.revision>n.revision&&Se(p)!==r)return;let _=!n.instruction&&!n.pendingRequest&&n.nodeType==="screen"&&["running","waiting"].includes(n.status);r!==V&&(V&&z?.finish("dismissed"),ve(),V=r,we={...n.answers},ze.reset());let ae=Be(n);if(xe===ae){s.hidden=!0;return}if(_&&!r){s.hidden=!0;let $=e.prepared?.state==="shown"?null:je(!0,n.locale);!h&&!ue&&Ge?.key!==ae&&(on(),Ge={key:ae,timeout:setTimeout(()=>{let y=e.client.view;if(h||!$?.active&&e.prepared?.state!=="shown"||!y||Be(y)!==ae)return;xe=ae;let W=new Error("Funnel screen preparation timed out");$?.finish("error",W),o(),ve(),fe(W)},Ae)}),He();return}on();let ee=$=>{let y=e.client.view;return!h&&!ue&&!qe&&!$.aborted&&e.client.configurationReady!==!1&&!!y&&!y.stopped&&!["closed","ineligible","failed"].includes(y.status)&&Se(y)===r},ge=($,y)=>{ee(y)&&(xe=r,z?.finish("error",$),ve(),s.hidden=!0,fe($))};if(r||((n.instruction&&n.instruction.type!=="evaluate_segment"||!["running","waiting"].includes(n.status))&&o(),We(n),n.instruction?.type!=="event"&&n.instruction?.type!=="open_url"&&z?.finish("skipped")),n.screen){o();let $=n.screen.content;if(!d){let x=n.screen.presentation.type!=="inline",oe=je(x,n.locale);if(h||ue)return;let ie=(Ne=new AbortController).signal;We(n),_e=x?Hn(N):Ke(s,t),d=P(R,{mode:"live",rendererUrl:e.client.webViewUrl,title:$.document.name,...x?{hostPresentation:()=>M?.type??n.screen.presentation.type}:{},onResize:v=>{i=v,M?.responsive&&M.setContentHeight(v+S.getBoundingClientRect().height)},onAction(v,me={},et={}){if(A.active||!ee(ie)||O!==r)return;we={...we,...et};let an=n.screen?.inputs??[],bn=Object.fromEntries(an.filter(({variable:be})=>Object.hasOwn(we,be)).map(({variable:be})=>[be,we[be]]));if(xn(an,bn).length){yn();return}Oe(()=>e.client.submit({operation:"submit",...ke(),input:{type:"screen",output:v,answers:bn,selection:me}}),!1,be=>an.length>0&&be instanceof m&&be.code==="INVALID_REQUEST"&&be.status!==void 0&&be.status<500)},onAnswers:v=>{A.active||!ee(ie)||O!==r||(we={...we,...v})},onCustomerDataIntent:v=>{A.active||!ee(ie)||O!==r||ze.intent(v).catch(fe)},onEscape:()=>{!ee(ie)||O!==r||A.active||de||Z||Ie()},onError:v=>{let me=new Error(v);O===r?fe(me):ge(me,ie)},onRendered:v=>{if(!(!ee(ie)||O===r))try{oe.present(me=>{_e?.(),_e=void 0,v&&(ce={screen:$.document.name,label:v},N.setAttribute("aria-label",v)),x&&(N.showModal(),M?.responsive&&N.focus({preventScroll:!0}),!me&&e.loading!=="host"&&An(N,M?.type??n.screen.presentation.type,M?.responsive)),O=r,te=x,Re()}),ee(ie)&&Le.report(r)}catch(me){ge(me,ie)}}}),vn()}let y={capabilities:n.screen.capabilities,customerData:n.screen.customerData,parameters:n.parameters,serverInput:{bindings:n.screen.inputs,answers:we,values:n.screen.values}},W=JSON.stringify([$,n.locale,y.parameters,n.screen.inputs,n.screen.values]);if(W!==Te)d.update($.document,n.locale,y),Te=W,Ee=JSON.stringify(y.capabilities),Me=JSON.stringify(y.customerData);else{let x=JSON.stringify(y.capabilities);x!==Ee&&(d.updateCapabilities(y.capabilities),Ee=x),JSON.stringify(y.customerData)!==Me&&(d.updateCustomerData(y.customerData),Me=JSON.stringify(y.customerData))}let se=d;if(se)try{await(z?.wait(se.ready)??se.ready)}catch(x){Ne&&ge(x,Ne.signal)}}else if(n.paywall&&!l){let $=n.paywall.resolution,y="document"in $?$.document:null,W=w,se=null,x=(Ne=new AbortController).signal,oe={loading:"host",signal:x,canInteract:()=>ee(x)&&!A.active&&!de&&!Z,beforeAction:async()=>{le++;try{await gn(Le.settled()),E.hidden=!0,De=null,Fe=!1,g()}finally{le=Math.max(0,le-1)}},start:()=>dn(e.client),onObservationChange:He,onPurchase:e.onPurchase,onCheckoutUrl:e.onCheckoutUrl,resumeCheckout:e.resumeCheckout,allowNewPurchase:e.allowNewPurchase,checkoutNavigation:e.checkoutNavigation,terminateCheckout:e.terminateCheckout,confirmOnHostedCheckout:e.confirmOnHostedCheckout,resolveOfferId:e.resolveOfferId,onEvent:e.onEvent,onOpenUrl:v=>e.onOpenUrl?e.onOpenUrl({receiptId:n.paywall.receiptId,url:v,openIn:"same_window"}):f.defaultView?.location.assign(v),onAction:async v=>{if(A.active)return;let me=await e.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:e.client.view?.revision??n.revision,input:{type:"screen",output:v,answers:{}}});await ye(e.client.view??me.run)},onError:v=>{O===r?fe(v):ge(v,x)}},ie={quoteError:v=>Ce(e.onError,v),present(v){ee(x)&&(se?.present(()=>{v(),O=r,te=!!R.querySelector("dialog[open]"),Re()}),ee(x)&&Le.report(r))},async dismiss(){if(!(h||x.aborted||A.active||de||Z||!he&&!ee(x))){if(he=!0,(e.resumeCheckout||e.terminateCheckout)&&Kn()){H=e.client.view,re();return}await Ie()}}};if(W){let v=await W.adopt(n,{options:oe,handoff:ie,start:()=>dn(e.client)});v&&ee(x)&&!h?(We(n),l=v,z?.active&&z.present(()=>{}),O=r,te=W.modal,Re(),Le.report(r),A.active&&l.setSuspended(!0)):(v?.destroy(),o())}if(h||ue)return;if(!l){if(se=je(!0,n.locale,y),h||ue)return;We(n);let v=await U(R,oe,ie).catch(me=>(ge(me,x),null));!ee(x)&&!(he&&!h&&!x.aborted)?v?.host?.destroy():v&&(l=v.host,l?.setSuspended(A.active))}}if(h||ue)return;Re();let q=n.instruction;if(q&&(q.type==="open_url"||q.type==="event")&&!Je.has(q.receiptId)){let $=f.createElement("button");$.type="button",$.style.cssText=B.primary,Ue($,()=>B.focus),R.style.cssText=B.stage,$.textContent=q.type==="open_url"?`${X?"\u524D\u5F80":"Continue to"} ${new URL(q.url).host}`:X?"\u7EE7\u7EED":"Continue",$.onclick=()=>{let y=ke(),W=q.type==="open_url"&&!e.onOpenUrl&&q.openIn==="new_window"?Yn(q.url):null;Oe(async()=>{let se="success";if(q.type==="open_url")if(e.onOpenUrl)try{se=await e.onOpenUrl({receiptId:q.receiptId,url:q.url,openIn:q.openIn})===!1?"failed":"opened"}catch(oe){Ce(e.onError,oe),se="failed"}else se=q.openIn==="new_window"&&!W?"failed":"opened";if(q.type==="event"){if(!e.onEvent)throw new m("EVENT_HANDLER_REQUIRED","Provide the event handler");await e.onEvent(q.event)}if(h||e.client.view?.nodeId!==y.nodeId||e.client.view.visit!==y.visit)throw new m("PRECONDITION_FAILED","The client action visit changed");let x=await e.client.submit({operation:"submit",...y,input:{type:"client_action",receiptId:q.receiptId,outcome:se}});return Je.add(q.receiptId),q.type==="open_url"&&!e.onOpenUrl&&q.openIn==="same_window"&&f.defaultView?.location.assign(q.url),x})},z?.active?z.present(()=>R.replaceChildren($)):R.replaceChildren($)}!n.pendingRequest&&n.status==="completed"&&!Je.has(`complete:${n.id}`)&&(Je.add(`complete:${n.id}`),Ce(e.onComplete,structuredClone(n))),He()}function Yn(n){let r=f.defaultView?.open(n,"_blank")??null;return r&&(r.opener=null),r}function ye(n){return Re(),nn=nn.catch(()=>{}).then(async()=>{try{await Wn(n)}catch(r){throw z?.active&&(xe=Be(n),z.finish("error",r),ve(),s.hidden=!0),r}}),nn}let Xn=e.client.subscribe(n=>{if(!fn){if(n.stopped&&(te||F())&&!he){H=n,re();return}!he&&(n.stopped||e.client.configurationReady===!1||V&&O!==V&&(Se(n)!==V||["closed","ineligible","failed"].includes(n.status)))&&(ve(),z?.finish("dismissed"),s.hidden=!0),ye(n).catch(fe)}}),Zn=e.client.subscribeError?.(fe);function Kn(){let n=e.client.view,r=n?.paywall;return!!r?.operation&&!!n&&["running","waiting"].includes(n.status)&&qn(Ve({quote:r.quote,operation:r.operation,requestId:r.purchaseRequestId,pending:!1,destroyed:!1,canReselect:r.canReselect}))}function Ie(n){if(qe)return qe;if(h||!n&&(de||Z))return Promise.resolve();let r=!n&&Qe();return!r&&e.client.view&&!["running","waiting"].includes(e.client.view.status)?(H=e.client.view,re(),Promise.resolve()):(qe=Oe(async()=>{let p=r?await e.client.retry():await e.client.submit({operation:"close",...n??ke()});return n&&wn(p),p},!0).then(()=>{let p=e.client.view;p?.status==="closed"&&!Qe()&&(H=p,re())}).finally(()=>{qe=null}),qe)}function re(){ne?.destroy(),!h&&(h=!0,k(),o(),e.signal?.removeEventListener("abort",re),c?.removeEventListener("abort",re),z?.finish("dismissed"),mn.destroy(),Xn(),Zn?.(),ve(),sn(),A.stop(),N.remove(),s.remove(),L(),Ce(e.onDismiss,H?structuredClone(H):null))}J.onclick=()=>{if(!J.disabled){if(A.active){A.exit();return}Oe(()=>e.client.submit({operation:"back",...ke()}))}},Q.onclick=()=>{A.open()},D.onclick=()=>{z?.active?z.dismiss():de||Ie()},T.onclick=()=>{Qe()?Ie():Oe(()=>e.client.retry())},N.addEventListener("cancel",n=>{n.preventDefault(),z?.active?z.dismiss():de||Ie()}),e.signal?.addEventListener("abort",re,{once:!0}),c?.addEventListener("abort",re,{once:!0});let Ye=!1;w&&(k=w.onClose(()=>{h||ue||(ue=!0,z?.finish("dismissed"),ve(),s.hidden=!0,e.client.view?Ie().finally(re):Ye=!0)}));let In={destroy:re,refresh:rn,get recovery(){let n=tn();if(n)return n;if(!h&&!le&&!he&&!de&&l){let r=l.recovery;if(r.type!=="native")return r}return{type:"recover",operationId:e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??Z?.operationId??null,requestId:e.client.pendingCommand?.requestId??null}},prepareFallback(){if(de)return de;let n=tn();if(n)return Promise.resolve(n);let r=e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??Z?.operationId??null,p=()=>({type:"recover",operationId:r,requestId:e.client.pendingCommand?.requestId??null});if(e.client.hasDurableJournal!==!0){let q=l?.recovery;return Promise.resolve(q&&q.type!=="native"&&q.type!=="cancel"?q:p())}let _=(e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[])).some(q=>q.operation==="close");if(h&&!(_||Z&&e.client.view?.status==="closed")||le||$e||qe||A.active||!l&&!Z&&!_)return Promise.resolve(p());let ae=l,ee=(async()=>{try{if(!Z&&_){let y=await e.client.retry();return await ye(e.client.view??y.run),p()}if(!Z){let y=await ae.prepareFallback();if(y.type!=="native")return y;if(e.client.hasDurableJournal!==!0)return p();Z=y}let q=e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[]);if(q.length){let y=q.find(se=>se.operation==="close");if(!y||!K||y.requestId!==K.requestId)return p();let W=await e.client.retry();wn(W),await ye(e.client.view??W.run)}else{let y=e.client.view,W=y?.paywall;if(!y||!W||W.selectionGeneration===void 0||(W.quote?.operationId??null)!==Z.operationId||Z.operationId!==null&&W.canReselect!==!0)return p();let se=W.selectionGeneration,x=await e.client.get();await ye(e.client.view??x.run);let oe=e.client.view,ie=oe?.paywall;if(!oe||!ie||!["running","waiting"].includes(oe.status)||oe.stopped||oe.id!==y.id||oe.nodeId!==y.nodeId||oe.visit!==y.visit||ie.receiptId!==W.receiptId||ie.selectionGeneration!==se||(ie.quote?.operationId??null)!==Z.operationId||Z.operationId!==null&&ie.canReselect!==!0||e.client.pendingPurchase||(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0)))return p();let v=ke();K={runId:oe.id,operationId:Z.operationId,revision:v.revision,requestId:v.requestId,nodeId:oe.nodeId,visit:oe.visit,receiptId:ie.receiptId,selectionGeneration:se,acknowledged:!1},await Ie(v)}let $=tn();return $?(re(),$):p()}catch(q){return fe(q),p()}})();de=ee;let ge=()=>{de===ee&&(de=null)};return ee.then(ge,ge),ee},review:A.open,exitReview:A.exit,get unappliedDrafts(){return A.drafts}};try{let n=e.client.view;if(n)((e.client.viewAgeMs??cn)>=cn||n.instruction?.type==="evaluate_segment")&&(en=rn().finally(()=>{en=null})),await ye(n);else{if(s.hidden=!0,h)throw new DOMException("Presentation cancelled","AbortError");let r=Ye||e.prepared?.state==="shown"?null:je(e.client.view?.screen?.presentation.type!=="inline",e.client.view?.locale);if(h||ue&&!Ye)throw new DOMException("Presentation cancelled","AbortError");let p=e.client.get(),_=await(r?r.wait(p,Ae):it(p,Ae));if(fn=!1,Ye)return h||await Ie().finally(re),In;await ye(e.client.view??_.run)}}catch(n){throw z?.finish("error",n),re(),n}return In}function it(t,b){let C;return Promise.race([t,new Promise((e,w)=>{C=setTimeout(()=>w(new Error("Presentation data timed out")),b)})]).finally(()=>clearTimeout(C))}function $t(t,b,C){return tt(t,b,C)}export{tt as a,$t as b};
@@ -0,0 +1 @@
1
+ import{a as p}from"./chunk-OX7PA64E.js";import{a as d}from"./chunk-VF6QMMEA.js";function I(n,r,i){if(!["subscriptions/operations/read","subscriptions/updates/read","subscriptions/refunds/read"].includes(n))return;let e=r,s=i,o=s.operation;if(o.operationId!==e.operationId||[o.authority,o.merchantExecution].some(t=>t&&(t.operationId!==e.operationId||e.customerId!==void 0&&t.customerId!==e.customerId))||o.authority&&(o.authority.scope.projectId!==s.scope.projectId||o.authority.scope.environment!==s.scope.environment))throw new p("INVALID_RESPONSE","Original commerce operation changed")}function g(n){try{return structuredClone(n)}catch{return n}}async function E(n,r){let i=n.captureIdentity?.(),{apiOperations:e}=await import("./operation-contracts-HS4M2UXN.js");return i?.(),e[r]}function m(n,r,i,e){try{return n.parse(r)}catch(s){throw e&&s instanceof d?new p(i,e):s}}async function P(n,r,i,e={},s){let o=typeof e=="function"?{}:e,t=m(r.request,i,"INVALID_REQUEST",o.request);try{let a=await n(r.path,t,r.method,s),u=typeof e=="function"?e:e.parseResponse,c=u?u(r.response,a):m(r.response,a,"INVALID_RESPONSE",o.response);return I(r.path,t,c),c}catch(a){throw a instanceof p&&t!==null&&typeof t=="object"&&"requestId"in t&&typeof t.requestId=="string"&&(a.commandRequestId??=t.requestId),a}}export{g as a,E as b,P as c};
@@ -1,4 +1,4 @@
1
- import{a as $,b as N,c as J,d as q}from"./chunk-KIMX3OIV.js";import{a as P}from"./chunk-3VUPVXAV.js";import{a as D}from"./chunk-UHQGO6OR.js";import{a as _}from"./chunk-DSPLGTQI.js";import{b as C,c as O,e as j}from"./chunk-7QL4GF4C.js";async function B(e,t,o,n={}){let r=n.message??"Invalid SDK JSON response",s=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||s!==null&&(!/^\d+$/.test(s)||Number(s)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(r);let u;try{u=await P(e,t,{signal:o,error:()=>Error(r)})}catch(p){throw o.aborted?Error(r):p}return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(u))}async function G(e,t){if(!e?.body)return;let o=new AbortController,n=()=>o.abort(t?.reason);t?.addEventListener("abort",n,{once:!0}),t?.aborted&&n();let r=setTimeout(()=>o.abort(Error("Exposure response timeout")),2e3);try{return await P(e,16384,{signal:o.signal,error:()=>Error("Exposure response budget")})}finally{clearTimeout(r),t?.removeEventListener("abort",n)}}var be=2*1024*1024,V=256*1024;async function Y(e,t,o,n){let r=()=>{},s=new Promise((u,p)=>{r=()=>p(n.reason),n.addEventListener("abort",r,{once:!0}),n.aborted&&r()});try{let u=e(t,{...o,signal:n});return u.then(p=>{n.aborted&&p.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([u,s])}finally{n.removeEventListener("abort",r)}}async function M(e,t,o,n=!1){if(new TextEncoder().encode(o).byteLength>65536)throw Error("Exposure request budget");let r=new URL(t);r.searchParams.set("sdkVersion",D.version);let s=new AbortController,u=setTimeout(()=>s.abort(Error("Exposure request timeout")),5e3);try{let p=await Y(e,r.href,{method:"POST",headers:{"Content-Type":"text/plain"},body:o,credentials:"omit",keepalive:n,redirect:"error"},s.signal),a=await G(p,s.signal),c;try{c=a&&JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch{}return{response:p,receipt:c}}finally{clearTimeout(u)}}function H(e){let t,o=!1;return{async read(n,r){if(o)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let s=new AbortController;t=s;let{signal:u}=s,p=setTimeout(()=>s.abort(Error("Experiment request timeout")),5e3);try{let a=await Y(e,n,{cache:"no-cache",credentials:"omit",redirect:"error"},u),c=await B(a,r,u);return u.throwIfAborted(),c}finally{clearTimeout(p),t===s&&(t=void 0)}},destroy(){o=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}var Q=20,ie=65536,se=5e3,ae=5,K=e=>new TextEncoder().encode(JSON.stringify(e)).length;function ce(e,t){let o=e,n=r=>Number.isSafeInteger(r)&&r>=0;return!!o&&typeof o=="object"&&n(o.inserted)&&n(o.duplicates)&&n(o.skipped)&&Array.isArray(o.rejected)&&o.inserted+o.duplicates+o.skipped+o.rejected.length===t&&o.rejected.every(r=>!!r&&typeof r=="object"&&n(r.index)&&r.index<t&&typeof r.reason=="string")&&new Set(o.rejected.map(r=>r.index)).size===o.rejected.length}function F(e){let t=[],o,n,r=(a,c)=>{try{e.log?.(`${e.label} ${a}`,c)}catch{}};function s(a){o===void 0&&!n&&t.length&&(o=setTimeout(()=>{p()},a))}async function u(a,c){let g,f;try{({response:g,receipt:f}=await M(e.fetch,e.endpoint,JSON.stringify({events:a}),c))}catch(h){return r("not sent",{error:h}),!1}return g.status===408||g.status===429||g.status>=500?(r("not sent",{status:g.status}),!1):g.ok?ce(f,a.length)?(f.rejected.length&&r("rejected",{rejected:f.rejected}),!0):(r("not acknowledged",{status:g.status}),!1):(r("rejected",{status:g.status,events:a.length}),!0)}function p(a=!0){if(n)return n;clearTimeout(o),o=void 0;let c=[],g=K({events:[]});for(;t.length&&c.length<Q;){let m=K(t[0].event)+(c.length?1:0);if(c.length&&g+m>ie)break;c.push(t.shift()),g+=m}if(!c.length)return Promise.resolve();let f=1e3,h=u(c.map(m=>m.event),a).then(m=>{if(m)return;f=se;let y=c.filter(b=>++b.attempts<ae);y.length<c.length&&r("dropped after retries",{events:c.length-y.length}),t.unshift(...y)}).finally(()=>{n===h&&(n=void 0),s(f)});return n=h,h}return{push(a){t.push({event:structuredClone(a),attempts:0}),t.length>=Q?p():s(1e3)},flush:p}}/*!
1
+ import{a as $,b as N,c as J,d as q}from"./chunk-TLZP7BW6.js";import{a as P}from"./chunk-3VUPVXAV.js";import{a as D}from"./chunk-EM3MGDPG.js";import{b as C,c as O,e as j}from"./chunk-7QL4GF4C.js";import{a as _}from"./chunk-DSPLGTQI.js";async function B(e,t,o,n={}){let r=n.message??"Invalid SDK JSON response",s=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||s!==null&&(!/^\d+$/.test(s)||Number(s)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(r);let u;try{u=await P(e,t,{signal:o,error:()=>Error(r)})}catch(p){throw o.aborted?Error(r):p}return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(u))}async function G(e,t){if(!e?.body)return;let o=new AbortController,n=()=>o.abort(t?.reason);t?.addEventListener("abort",n,{once:!0}),t?.aborted&&n();let r=setTimeout(()=>o.abort(Error("Exposure response timeout")),2e3);try{return await P(e,16384,{signal:o.signal,error:()=>Error("Exposure response budget")})}finally{clearTimeout(r),t?.removeEventListener("abort",n)}}var be=2*1024*1024,V=256*1024;async function Y(e,t,o,n){let r=()=>{},s=new Promise((u,p)=>{r=()=>p(n.reason),n.addEventListener("abort",r,{once:!0}),n.aborted&&r()});try{let u=e(t,{...o,signal:n});return u.then(p=>{n.aborted&&p.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([u,s])}finally{n.removeEventListener("abort",r)}}async function M(e,t,o,n=!1){if(new TextEncoder().encode(o).byteLength>65536)throw Error("Exposure request budget");let r=new URL(t);r.searchParams.set("sdkVersion",D.version);let s=new AbortController,u=setTimeout(()=>s.abort(Error("Exposure request timeout")),5e3);try{let p=await Y(e,r.href,{method:"POST",headers:{"Content-Type":"text/plain"},body:o,credentials:"omit",keepalive:n,redirect:"error"},s.signal),a=await G(p,s.signal),c;try{c=a&&JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch{}return{response:p,receipt:c}}finally{clearTimeout(u)}}function H(e){let t,o=!1;return{async read(n,r){if(o)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let s=new AbortController;t=s;let{signal:u}=s,p=setTimeout(()=>s.abort(Error("Experiment request timeout")),5e3);try{let a=await Y(e,n,{cache:"no-cache",credentials:"omit",redirect:"error"},u),c=await B(a,r,u);return u.throwIfAborted(),c}finally{clearTimeout(p),t===s&&(t=void 0)}},destroy(){o=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}var Q=20,ie=65536,se=5e3,ae=5,K=e=>new TextEncoder().encode(JSON.stringify(e)).length;function ce(e,t){let o=e,n=r=>Number.isSafeInteger(r)&&r>=0;return!!o&&typeof o=="object"&&n(o.inserted)&&n(o.duplicates)&&n(o.skipped)&&Array.isArray(o.rejected)&&o.inserted+o.duplicates+o.skipped+o.rejected.length===t&&o.rejected.every(r=>!!r&&typeof r=="object"&&n(r.index)&&r.index<t&&typeof r.reason=="string")&&new Set(o.rejected.map(r=>r.index)).size===o.rejected.length}function F(e){let t=[],o,n,r=(a,c)=>{try{e.log?.(`${e.label} ${a}`,c)}catch{}};function s(a){o===void 0&&!n&&t.length&&(o=setTimeout(()=>{p()},a))}async function u(a,c){let g,f;try{({response:g,receipt:f}=await M(e.fetch,e.endpoint,JSON.stringify({events:a}),c))}catch(h){return r("not sent",{error:h}),!1}return g.status===408||g.status===429||g.status>=500?(r("not sent",{status:g.status}),!1):g.ok?ce(f,a.length)?(f.rejected.length&&r("rejected",{rejected:f.rejected}),!0):(r("not acknowledged",{status:g.status}),!1):(r("rejected",{status:g.status,events:a.length}),!0)}function p(a=!0){if(n)return n;clearTimeout(o),o=void 0;let c=[],g=K({events:[]});for(;t.length&&c.length<Q;){let m=K(t[0].event)+(c.length?1:0);if(c.length&&g+m>ie)break;c.push(t.shift()),g+=m}if(!c.length)return Promise.resolve();let f=1e3,h=u(c.map(m=>m.event),a).then(m=>{if(m)return;f=se;let y=c.filter(b=>++b.attempts<ae);y.length<c.length&&r("dropped after retries",{events:c.length-y.length}),t.unshift(...y)}).finally(()=>{n===h&&(n=void 0),s(f)});return n=h,h}return{push(a){t.push({event:structuredClone(a),attempts:0}),t.length>=Q?p():s(1e3)},flush:p}}/*!
2
2
  Portions ported from GrowthBook sdk-js @ ed29827 (GrowthBook.ts auto experiments, util.ts mergeQueryStrings,
3
3
  plugins/auto-attributes.ts). Copyright (c) GrowthBook, Inc. MIT License.
4
4
  */function ue(e,t){let o,n;try{o=new URL(e),n=new URL(t)}catch{return t}return o.searchParams.forEach((r,s)=>{n.searchParams.has(s)||n.searchParams.set(s,r)}),n.toString()}function de(e,t){let o=navigator.userAgent,n=new URLSearchParams(t.search),r={};for(let s of["source","medium","campaign","term","content"]){let u=n.get(`utm_${s}`);u!==null&&(r[`utm${s[0].toUpperCase()}${s.slice(1)}`]=u)}return{id:e,deviceId:e,url:t.href,path:t.pathname,host:t.host,query:t.search,pageTitle:typeof document>"u"?"":document.title,browser:/Edg/.test(o)?"edge":/Chrome/.test(o)?"chrome":/Firefox/.test(o)?"firefox":/Safari/.test(o)?"safari":"unknown",deviceType:/Mobi/.test(o)?"mobile":"desktop",...r}}function le(e){let t=e;if(!(!!t&&typeof t=="object"&&typeof t.environmentId=="string"&&typeof t.trackExposures=="boolean"&&/^[a-f0-9]{64}$/.test(t.generation??"")&&Array.isArray(t.experiments)&&t.experiments.length<=100&&t.experiments.every(n=>!!n&&!["namespace","status","url","groups"].some(r=>Object.hasOwn(n,r))&&(n.hashVersion===void 0||n.hashVersion===2)&&typeof n.key=="string"&&Array.isArray(n.variations)&&n.variations.length>=2&&n.variations.every(r=>!!r&&typeof r.urlRedirect=="string")&&(n.urlPatterns===void 0||Array.isArray(n.urlPatterns)))&&!!t.savedGroups&&typeof t.savedGroups=="object"&&!Array.isArray(t.savedGroups)))throw new Error("Invalid page experiment payload");return t}function Te(e){if(e.configuration&&e.configuration.scope.environmentId!==e.environmentId)throw new Error("Page configuration belongs to another App environment");let t=J(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("environmentId must be the App environment ID");let o=e.fetch??globalThis.fetch.bind(globalThis),n=H(async(i,d)=>{let l=await o(i,d);if(!l.ok)throw l.body?.cancel().catch(()=>{}),new Error(`Page experiments unavailable (${l.status})`);return l}),r=e.log?(i,d)=>_(e.log,i,d):void 0,s=`${t}/api/v1/page-experiments/${e.environmentId}`,u=$(e.deviceIdCookie??"indiana_did"),p=N(),a=null,c={...e.attributes??{}},g="",f=!1,h=!1,m=0,y=0,b=new Map,S=F({endpoint:`${s}/events`,fetch:o,log:r,label:"Exposure"}),k=S.flush,E={trackedExperiments:new Set,log:r,onExperimentViewed:(i,d)=>{e.trackExposures===!1||a?.trackExposures===!1||S.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:u,...p?{sessionId:p}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:i.key,variationKey:d.key})}},z=()=>{E.url=location.href,E.attributes={...de(u,location),...c}};function W(i){if(!e.disableCrossOriginUrlRedirects)return!1;try{let d=new URL(location.href);return i.variations.some(l=>{if(!l.urlRedirect)return!1;let v=new URL(l.urlRedirect);return v.protocol!==d.protocol||v.host!==d.host})}catch{return!0}}function X(i,d){let l=e.configuration?.snapshot?.generation,v=y,te=location.href;g=i;let re=e.navigate??(w=>location.replace(w)),ne=e.navigateDelay??(e.navigate?0:100),oe=e.maxNavigateDelay??1e3;Promise.all([Promise.race([d,new Promise(w=>setTimeout(w,oe))]),new Promise(w=>setTimeout(w,ne))]).then(()=>{!f&&v===y&&location.href===te&&(!e.configuration||e.configuration.fresh&&e.configuration.snapshot?.generation===l)&&re(i)})}function x(){if(!(!a||f||e.configuration&&!e.configuration.fresh)){z();for(let i of a.experiments){if(W(i)){r?.("Auto experiment blocked",{id:i.key});continue}let d;try{d=j(i,E)}catch(l){r?.("Skipping page experiment",{id:i.key,error:String(l)});continue}if(b.set(i.key,d),!!d.inExperiment){if(d.value.urlRedirect){let l=i.persistQueryString?ue(location.href,d.value.urlRedirect):d.value.urlRedirect;C(l,i.urlPatterns??[])?r?.("Skipping redirect because original URL matches redirect URL",{id:i.key}):l!==g&&X(l,k())}break}}}}let R="",Z=()=>{location.href!==R&&(y++,R=location.href,g="",x())},T,L;function ee(){T??=q(Z),addEventListener("pagehide",I)}let I=()=>{k()};async function A(){if(f)return!1;let i=++m,d;try{d=e.configuration?await e.configuration.pageExperiments():await n.read(s,V)}catch(v){if(f||i!==m)return!1;throw v}if(f||i!==m)return!1;let l=le(d);if(l.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Page experiment payload scope changed");return a?.trackExposures===!1&&l.trackExposures&&E.trackedExperiments?.clear(),a=l,E.savedGroups=O(l.savedGroups),!0}function U(){f||(L??=e.configuration?.subscribe(()=>{!f&&e.configuration?.fresh&&A().then(i=>{i&&x()}).catch(i=>r?.("Page configuration unavailable",{error:String(i)}))}),ee(),R=location.href)}return{async start(){h||f||(h=!0,await A()&&(U(),x()))},async refresh(){await A()&&(y++,h&&U(),g="",x())},setAttributes(i){y++,g="",c={...i},x()},getResults(){return new Map(b)},get generation(){return a?.generation??null},destroy(){f||(f=!0,m++,n.destroy(),L?.(),T?.(),removeEventListener("pagehide",I),a=null,b.clear(),k())}}}export{be as a,H as b,F as c,ue as d,de as e,le as f,Te as g};
@@ -0,0 +1 @@
1
+ import{e as h}from"./chunk-44U3FOBB.js";import{c as N}from"./chunk-EUTWY7A2.js";import{b as J}from"./chunk-LF2UIJYD.js";import{v as Q}from"./chunk-CKKIB2HC.js";import{b as x}from"./chunk-W6OQTXLL.js";import{a as j}from"./chunk-3NCMYTNG.js";import{b as L}from"./chunk-VEX2FOFZ.js";import{c as H,d as K,e as B,f as F}from"./chunk-V7PFLFHE.js";import{b as U}from"./chunk-56BYGPQ6.js";import{a as M}from"./chunk-VYFSRHXM.js";import{da as G}from"./chunk-BQRS7Y4K.js";import{a as l}from"./chunk-OX7PA64E.js";import{a as W}from"./chunk-DSPLGTQI.js";async function ce(I,o){if(!M.test(o.customerToken))throw new l("INVALID_TOKEN","A verified Customer credential is required");if(I.session&&I.session.peek()!==o.customerToken)throw new l("SCOPE_MISMATCH","Paywall credential does not match the shared session");let u=h.resolvePaywall.request.parse({funnelId:o.funnelId,funnelVersionId:o.funnelVersionId,selector:o.paywallVersionId?{type:"version",versionId:o.paywallVersionId}:{type:"paywall",paywallId:o.paywallId},commerce:o.commerce,locale:o.locale,...o.requirement?{requirement:o.requirement}:{}}),S=U(I);I.session||S.identify(o.customerToken);let r=null,P=!1,D=new AbortController,s=null,c=null,v=null,w=null,R=null,d=null,f=null,A=0,O=null,_="",V=0,b=new Map,q=new Set;function g(){if(P)throw new l("IDENTITY_CHANGED","Paywall is closed")}function k(){let e=JSON.stringify([A,f!==null]);if(!O||e!==_){_=e;let t=Y(++V);O=t;let a=()=>{O===t&&(O=null)};t.then(a,a)}return O.then(t=>structuredClone(t))}async function Y(e){g();let t=h.resolvePaywall,a=await N(S.request,t,{...u,selector:r?{type:"version",versionId:r.id}:u.selector});J(u,a.paywall.check,a.scope);let i=await x(I,a.paywall);if(g(),o.paywallVersionId?i.id!==o.paywallVersionId:i.paywallId!==o.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");if(r&&(!H(i,r)||i.paywallId!==r.paywallId))throw new l("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");if(e!==V)return structuredClone(r??i);r=i;for(let m of q)W(m,structuredClone(r));return structuredClone(r)}async function E(e){if(g(),w&&e!=="read")throw new l("COMMAND_PENDING","Wait for the original quote");if(!s)throw new l("INVALID_REQUEST","A quoted purchase is required");let t=s;if(e!=="read"){if(f){if(d===e)return f;throw new l("COMMAND_PENDING","Wait for the original purchase command")}if(d&&d!==e)throw new l("COMMAND_PENDING","Read the original purchase before changing an uncertain command");d=e,A++,V++}let a=d,i=A,m=e==="read"&&f===null,p=JSON.stringify([t.operationId,i,f!==null]);if(e==="read"&&b.has(p))return b.get(p).then(n=>structuredClone(n));let C=e==="read"?h.readSubscriptionOperation:h.attach,y=(async()=>{let n=await N(S.request,C,{operationId:t.operationId,...e==="read"?{}:{intent:e},...e==="confirm"&&t.merchantTerms?{merchantConfirmation:Q(t.merchantTerms)}:{}});return K(n.operation,{operationId:t.operationId,currency:u.commerce.currency},"The purchase operation changed"),g(),s?.operationId!==t.operationId?structuredClone(n.operation):(c=F(c,n.operation),(e!=="read"||m&&f===null)&&A===i&&d===a&&(d=null),structuredClone(c))})();if(e!=="read"){f=y;let n=()=>{f===y&&(f=null)};y.then(n,n)}else{b.set(p,y);let n=()=>{b.get(p)===y&&b.delete(p)};y.then(n,n)}return y.then(n=>structuredClone(n))}let T={signal:D.signal,get view(){return r?structuredClone(r):null},get quote(){return s?structuredClone(s):null},get operation(){return c?structuredClone(c):null},get webViewUrl(){return"bundled"},get recovery(){return j({quote:s,operation:c,requestId:R,pending:w!==null||d!==null,destroyed:P})},get pendingCancellation(){return!P&&d==="cancel"},refresh:k,subscribe(e){return P?()=>{}:(q.add(e),()=>q.delete(e))},async preview(e){if(g(),!r)throw new l("INVALID_REQUEST","Load the Paywall first");let t=r.document.buttons[e.actionId];if(t?.type!=="checkout")throw new l("INVALID_REQUEST","Choose an authored purchase action");let a=L(t.product,e.selection,r.capabilities);if(!a)throw new l("PRODUCT_UNAVAILABLE","Choose an available Product");let i=G(r.document.screen,a,e.selection,r.capabilities),m=h.previewAttach.request.parse({funnelId:u.funnelId,funnelVersionId:u.funnelVersionId,requestId:e.requestId,plans:[{productVersionId:a,...Object.keys(i).length?{featureQuantities:i}:{}}],provider:u.commerce.provider,currency:u.commerce.currency,...e.offerId?{offerId:e.offerId}:{},...e.nativeOffer?{nativeOffer:e.nativeOffer}:{}}),p=JSON.stringify(m);if(v&&v!==p&&(w||d||!c||c.status==="pending"))throw new l("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(v===p){if(w)return w;if(s)return structuredClone(s)}v!==p&&(s=null,c=null),v=p,R=m.requestId;let C=(async()=>{let y=h.previewAttach,n=await N(S.request,y,m);return g(),B(n.quote,{productVersionId:a,featureQuantities:i,currency:u.commerce.currency,provider:u.commerce.provider},"The purchase quote changed its selected Product or presentment"),s=n.quote,c=null,structuredClone(s)})();w=C;try{return await C}finally{w===C&&(w=null)}},confirm:()=>E("confirm"),cancel:()=>E("cancel"),read:()=>E("read"),destroy(){P||(P=!0,D.abort(),q.clear(),b.clear(),z?.(),S.dispose(),r=null,s=null,c=null,v=null,R=null)}},z=I.session?.subscribeIdentity(T.destroy);try{return await k(),T}catch(e){throw T.destroy(),e}}export{ce as a};
@@ -1 +1 @@
1
- import{g as p}from"./chunk-R4FDIYMN.js";import{b as r}from"./chunk-VF6QMMEA.js";import{a as i,b as s}from"./chunk-BID4UGWB.js";var b=r.string().regex(/^[a-f0-9]{64}$/),j=r.strictObject({scope:r.strictObject({projectId:r.uuid(),environmentId:r.uuid(),environment:p}),customerId:r.uuid()});function l(u){let n=e=>{if(Array.isArray(e))return`[${e.map(n).join(",")}]`;if(e!==null&&typeof e=="object"){let c=Object.getPrototypeOf(e);if(c!==Object.prototype&&c!==null)throw new TypeError("Commerce protocol digests require JSON objects");return`{${Object.entries(e).filter(([,o])=>o!==void 0).sort(([o],[t])=>o<t?-1:o>t?1:0).map(([o,t])=>`${JSON.stringify(o)}:${n(t)}`).join(",")}}`}if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return JSON.stringify(e);throw new TypeError("Commerce protocol digests require JSON values")};return i(s(new TextEncoder().encode(n(u))))}export{b as a,j as b,l as c};
1
+ import{a as p}from"./chunk-TJGIT5CU.js";import{b as r}from"./chunk-VF6QMMEA.js";import{a as i,b as s}from"./chunk-BID4UGWB.js";var b=r.string().regex(/^[a-f0-9]{64}$/),j=r.strictObject({scope:r.strictObject({projectId:r.uuid(),environmentId:r.uuid(),environment:p}),customerId:r.uuid()});function l(u){let n=e=>{if(Array.isArray(e))return`[${e.map(n).join(",")}]`;if(e!==null&&typeof e=="object"){let c=Object.getPrototypeOf(e);if(c!==Object.prototype&&c!==null)throw new TypeError("Commerce protocol digests require JSON objects");return`{${Object.entries(e).filter(([,o])=>o!==void 0).sort(([o],[t])=>o<t?-1:o>t?1:0).map(([o,t])=>`${JSON.stringify(o)}:${n(t)}`).join(",")}}`}if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return JSON.stringify(e);throw new TypeError("Commerce protocol digests require JSON values")};return i(s(new TextEncoder().encode(n(u))))}export{b as a,j as b,l as c};
@@ -1 +1 @@
1
- import{a,b as o,c as i}from"./chunk-JN6JEKWN.js";import{a as p}from"./chunk-X4W22IH6.js";function c(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new p("INVALID_REQUEST","Customer requests use the verified session identity")}function I(e){return{async previewUpdate(t){t=a(t),c(t);let r=await o(e,"previewUpdate");return i(e,r,t)},async update(t){t=a(t),c(t);let r=await o(e,"update");return i(e,r,t)},async readSubscriptionUpdate(t){t=a(t),c(t);let r=await o(e,"readSubscriptionUpdate");return i(e,r,t)},async restoreNativePurchase(t){t=a(t),c(t);let r=await o(e,"restoreNativePurchase");return i(e,r,t)},async previewAttach(t){t=a(t),c(t);let r=await o(e,"previewAttach");return i(e,r,t)},async attach(t){t=a(t),c(t);let r=await o(e,"attach");return i(e,r,t)},async readSubscriptionOperation(t){t=a(t),c(t);let r=await o(e,"readSubscriptionOperation");return i(e,r,t)}}}export{c as a,I as b};
1
+ import{a,b as o,c as i}from"./chunk-EUTWY7A2.js";import{a as p}from"./chunk-OX7PA64E.js";function c(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new p("INVALID_REQUEST","Customer requests use the verified session identity")}function I(e){return{async previewUpdate(t){t=a(t),c(t);let r=await o(e,"previewUpdate");return i(e,r,t)},async update(t){t=a(t),c(t);let r=await o(e,"update");return i(e,r,t)},async readSubscriptionUpdate(t){t=a(t),c(t);let r=await o(e,"readSubscriptionUpdate");return i(e,r,t)},async restoreNativePurchase(t){t=a(t),c(t);let r=await o(e,"restoreNativePurchase");return i(e,r,t)},async previewAttach(t){t=a(t),c(t);let r=await o(e,"previewAttach");return i(e,r,t)},async attach(t){t=a(t),c(t);let r=await o(e,"attach");return i(e,r,t)},async readSubscriptionOperation(t){t=a(t),c(t);let r=await o(e,"readSubscriptionOperation");return i(e,r,t)}}}export{c as a,I as b};
@@ -1 +1 @@
1
- import{r as o}from"./chunk-N7YXDSQL.js";import{a as i}from"./chunk-X4W22IH6.js";function m(t,e,n,r){if(!o(t,e)||n!==void 0&&e.observation&&e.observation.subject.customerId!==n||r!==void 0&&e.observation!==void 0&&(e.observation.subject.scope.projectId!==r.projectId||e.observation.subject.scope.environment!==r.environment))throw new i("INVALID_RESPONSE","The access requirement or Customer changed");return e}function d(t,e,n){if(t.requirement){if(!e)throw new i("INVALID_RESPONSE","The requested access check is missing");m(t.requirement,e,t.customerId,n)}}export{m as a,d as b};
1
+ import{m as o}from"./chunk-U4RSRFZY.js";import{a as i}from"./chunk-OX7PA64E.js";function m(t,e,n,r){if(!o(t,e)||n!==void 0&&e.observation&&e.observation.subject.customerId!==n||r!==void 0&&e.observation!==void 0&&(e.observation.subject.scope.projectId!==r.projectId||e.observation.subject.scope.environment!==r.environment))throw new i("INVALID_RESPONSE","The access requirement or Customer changed");return e}function d(t,e,n){if(t.requirement){if(!e)throw new i("INVALID_RESPONSE","The requested access check is missing");m(t.requirement,e,t.customerId,n)}}export{m as a,d as b};
@@ -1 +1 @@
1
- import{a as n}from"./chunk-X4W22IH6.js";function o(r,e){try{return r.parse(e)}catch{throw new n("INVALID_RESPONSE","Invalid gateway response")}}export{o as a};
1
+ import{a as n}from"./chunk-OX7PA64E.js";function o(r,e){try{return r.parse(e)}catch{throw new n("INVALID_RESPONSE","Invalid gateway response")}}export{o as a};
@@ -1 +1 @@
1
- import{f as o}from"./chunk-R4FDIYMN.js";var n=class extends Error{constructor(t,s,y,i,r){super(s);this.code=t;this.status=y;this.requestId=i;this.name="IndianaError",this.reason=r?.reason;let e=o(t,y??0,{...r,retryAfter:r?.retryAfterSeconds===void 0?void 0:String(r.retryAfterSeconds)});this.retryable=e.retryable,this.recovery=e.recovery,this.retryAfterSeconds=e.retryAfterSeconds}code;status;requestId;commandRequestId;retryable;recovery;retryAfterSeconds;reason};export{n as a};
1
+ import{f as o}from"./chunk-V7MMTILA.js";var n=class extends Error{constructor(t,s,y,i,r){super(s);this.code=t;this.status=y;this.requestId=i;this.name="IndianaError",this.reason=r?.reason;let e=o(t,y??0,{...r,retryAfter:r?.retryAfterSeconds===void 0?void 0:String(r.retryAfterSeconds)});this.retryable=e.retryable,this.recovery=e.recovery,this.retryAfterSeconds=e.retryAfterSeconds}code;status;requestId;commandRequestId;retryable;recovery;retryAfterSeconds;reason};export{n as a};
@@ -0,0 +1 @@
1
+ import{_ as ie,d as Q,k as Y,o as ee,p as te,q as ne,t as O,v as re,y as oe}from"./chunk-TAFALMQN.js";import{a as F}from"./chunk-VEX2FOFZ.js";import{B as k,H as h,I as D,J as C,K as A,ca as ae,e as J,j as Z,l as W,p as I,q as S,s as R,v as X,x as w,y as P,z as H}from"./chunk-BQRS7Y4K.js";import{a as T,f as K}from"./chunk-U4RSRFZY.js";import{b as j}from"./chunk-TJGIT5CU.js";import{b as e}from"./chunk-VF6QMMEA.js";import{a as L,b as U}from"./chunk-BID4UGWB.js";var V=e.strictObject({eventsEnabled:e.boolean(),experimentViewsEnabled:e.boolean(),featureUsageEnabled:e.boolean()}),Je=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function Ke(t,r){return r==="experiment_exposure"?t.experimentViewsEnabled:r==="feature_usage"?t.featureUsageEnabled:t.eventsEnabled}var z=e.tuple([e.number().min(0).max(1),e.number().min(0).max(1)]).refine(([t,r])=>t<=r),xe=e.strictObject({attribute:e.string().optional(),seed:e.string(),hashVersion:e.literal(2),ranges:e.array(z).max(100)}),ve=e.strictObject({id:e.string().min(1).max(255),condition:C,gate:e.boolean().optional()}),Se=e.strictObject({key:e.string().optional(),name:e.string().optional(),passthrough:e.boolean().optional()}),se={condition:C.optional(),parentConditions:e.array(ve).max(100).optional(),weights:e.array(e.number().min(0).max(1)).max(20).optional(),coverage:e.number().min(0).max(1).optional(),hashAttribute:e.string().optional(),fallbackAttribute:e.string().optional(),hashVersion:e.literal(2).optional(),disableStickyBucketing:e.boolean().optional(),bucketVersion:e.number().int().nonnegative().optional(),minBucketVersion:e.number().int().nonnegative().optional(),filters:e.array(xe).max(100).optional(),ranges:e.array(z).max(20).optional(),meta:e.array(Se).max(20).optional(),seed:e.string().optional(),name:e.string().optional(),phase:e.string().optional()},ce=e.strictObject({...se,key:e.string().min(1).max(255),variations:e.tuple([h,h]).rest(h).refine(t=>t.length<=20),urlPatterns:e.array(e.strictObject({include:e.boolean(),type:e.enum(["regex","simple"]),pattern:e.string()})).max(100).optional(),force:e.number().int().nonnegative().optional(),active:e.boolean().optional(),persistQueryString:e.boolean().optional()}),G=e.strictObject({value:h,variationId:e.number().int(),key:e.string(),name:e.string().optional(),bucket:e.number().optional(),passthrough:e.boolean().optional(),inExperiment:e.boolean(),hashUsed:e.boolean().optional(),hashAttribute:e.string(),hashValue:e.string(),featureId:e.string().nullable(),stickyBucketUsed:e.boolean().optional()}),we=e.strictObject({...se,id:e.string().max(255).optional(),force:h.optional(),variations:e.array(h).min(2).max(20).optional(),key:e.string().optional(),range:z.optional(),tracks:e.array(e.strictObject({experiment:ce,result:G})).max(100).optional()}),Oe=e.strictObject({defaultValue:h.optional(),rules:e.array(we).max(500).optional()}),je=e.record(e.string(),e.union([e.strictObject({type:e.literal("hashed"),attributeKey:e.string(),values:e.array(e.string().regex(/^[a-f0-9]{64}$/))}),e.strictObject({type:e.literal("list"),attributeKey:e.string(),values:e.array(e.union([e.string(),e.number()]))}),e.strictObject({type:e.literal("condition"),condition:C})])),v=e.strictObject({scope:j,generation:e.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:e.iso.datetime({offset:!0}),expiresAt:e.iso.datetime({offset:!0}).nullable(),features:e.record(e.string(),Oe),savedGroups:je,experiments:e.record(e.uuid(),ce)});var Ie=v.extend({analyticsConfig:V,remoteFeatures:e.array(e.string().min(1).max(255)).max(500)}),rt=Ie.omit({evaluatedAt:!0,expiresAt:!0}).superRefine((t,r)=>{for(let a of t.remoteFeatures)Object.hasOwn(t.features,a)&&r.addIssue({code:"custom",path:["features",a],message:"Remote Feature definitions cannot be public"});for(let[a,o]of Object.entries(t.savedGroups))o.type==="list"&&r.addIssue({code:"custom",path:["savedGroups",a],message:"Raw Saved Group lists cannot be public"})}),ot=e.strictObject({attributes:D,features:e.array(e.string().min(1).max(255)).max(500).optional(),customerId:e.uuid().optional()}),pe=e.strictObject({value:h,source:e.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:e.boolean(),off:e.boolean(),ruleId:e.string(),experimentResult:G.optional()}),it=e.strictObject({generation:v.shape.generation,evaluatedAt:v.shape.evaluatedAt,expiresAt:v.shape.expiresAt,features:e.record(e.string(),pe),merchandiseContext:e.strictObject({merchandiseId:e.uuid(),merchandise:D}).optional()}),le={eventUuid:e.uuid(),timestamp:e.iso.datetime({offset:!0}),merchandise:Y.optional(),deviceId:e.string().min(1).max(255).optional(),sessionId:e.string().min(1).max(255).optional()},ue={...le,generation:v.shape.generation},Pe=e.discriminatedUnion("kind",[e.strictObject({...le,kind:e.literal("custom"),name:e.string().min(1).max(255),properties:e.record(e.string(),h).default({})}),e.strictObject({...ue,kind:e.literal("experiment_exposure"),experimentId:e.string().min(1).max(255),variationId:e.string().min(1).max(255)}),e.strictObject({...ue,kind:e.literal("feature_usage"),feature:e.string().min(1).max(255),value:h,source:pe.shape.source,ruleId:e.string().max(255),variationId:e.string().min(1).max(255).optional()})]),at=e.strictObject({customerId:e.uuid().optional(),events:e.array(Pe).min(1).max(100)}),ke=e.strictObject({eventUuid:e.uuid(),reason:e.enum(["invalid_event","invalid_merchandise","not_delivered","reserved_name"])}),st=e.strictObject({inserted:e.number().int().nonnegative(),duplicates:e.number().int().nonnegative(),rejected:e.number().int().nonnegative(),skipped:e.number().int().nonnegative(),rejections:e.array(ke).max(100),analyticsConfig:V});function me(t,r){let a=new Set,o=new Set,c=new Set,p=[],g=new Map,f=new Map,d=new Map;function m(s){for(let n of A(s))i(n)}function i(s){if(c.has(s)||!Object.hasOwn(r.savedGroups,s))return;let n=r.savedGroups[s];n&&(c.add(s),d.set(s,n),p.push(()=>{!Array.isArray(n)&&n.type==="condition"&&m(n.condition)}))}function u(s){for(let n of["hashAttribute","fallbackAttribute"])if(s[n]!==void 0&&oe(s[n]))throw new Error(`Funnel GB ${n} uses a reserved flow namespace`);m(s.condition);for(let n of s.parentConditions??[])l(n.id),m(n.condition)}function l(s,n=!1){let b=Object.hasOwn(r.features,s)?r.features[s]:void 0;if(!b){if(n)throw new Error("Required GB Feature is unavailable");return}a.has(s)||(a.add(s),g.set(s,b),p.push(()=>{for(let x of b.rules??[]){u(x);for(let he of x.tracks??[])u(he.experiment)}}))}function y(s){let n=Object.hasOwn(r.experiments,s)?r.experiments[s]:void 0;if(!n)throw new Error("Required GB Experiment is unavailable");o.has(s)||(o.add(s),f.set(s,n),p.push(()=>u(n)))}for(let s of t.graph.nodes){s.type==="feature"&&l(s.featureKey,!0),s.type==="split"&&y(s.experimentId),s.type==="condition"&&s.cases.forEach(b=>m(b.condition)),s.type==="offering"&&s.configuration.source==="feature"&&l(s.configuration.featureKey,!0);let n=s.type==="output"?s.value:s.type==="end"?s.output:null;n?.type==="feature"&&l(n.featureKey,!0)}for(let s of p)s();return{...r,features:Object.fromEntries(g),experiments:Object.fromEntries(f),savedGroups:Object.fromEntries(d)}}var de=e.object({defaultLocale:R,locales:e.record(R,e.object({name:e.string().max(80),description:e.string().max(500)}).strict())}).strict().superRefine((t,r)=>{let a=Object.keys(t.locales);(!a.length||a.length>20||!t.locales[t.defaultLocale])&&r.addIssue({code:"custom",message:"Invalid content languages"}),new TextEncoder().encode(JSON.stringify(t)).length>5e4&&r.addIssue({code:"custom",message:"Content exceeds 50 KB"})});var M=e.discriminatedUnion("type",[e.strictObject({type:e.literal("event"),event:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),e.strictObject({type:e.literal("open_url"),url:e.url().refine(t=>new URL(t).protocol==="https:")})]),Ce=P,Ae=e.discriminatedUnion("type",[e.object({type:e.literal("checkout"),product:I}).strict(),e.object({type:e.literal("close")}).strict(),e.object({type:e.literal("action"),action:M}).strict()]),E=e.object({schemaVersion:e.literal(3),kind:e.literal("paywall"),name:e.string().trim().min(1).max(80),presentation:S,requirement:K.optional(),products:F,offeringVersionId:e.uuid().nullable(),offeringId:e.uuid(),screen:Ce,buttons:e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ae)}).strict(),jt=E.superRefine((t,r)=>{(t.screen.surface!=="paywall"||t.screen.actions.some(o=>!["event","navigate"].includes(o.type)||o.close))&&r.addIssue({code:"custom",message:"Paywall screen is incomplete"});for(let o of Ee(t))r.addIssue({code:"custom",message:o});for(let o of Fe(t))r.addIssue({code:"custom",message:o});for(let o of t.screen.actions){let c=o.properties.closeControl;c!==void 0&&(c!=="content"||t.buttons[o.id]?.type!=="close")&&r.addIssue({code:"custom",path:["screen","actions",o.id],message:'Only a close button can carry closeControl, and its value is "content"'})}k(t.screen).some(o=>!o.complete)&&r.addIssue({code:"custom",message:"Paywall needs complete local content"}),(Object.keys(t.buttons).length!==t.screen.actions.filter(o=>o.type!=="navigate").length||t.screen.actions.some(o=>o.type!=="navigate"&&!Object.hasOwn(t.buttons,o.id)))&&r.addIssue({code:"custom",message:"Paywall buttons require matching node policies"}),Object.values(t.buttons).some(o=>o.type==="checkout")||r.addIssue({code:"custom",message:"A paywall requires a purchase or membership change button"})});function Fe(t){let r=t.products.items.map(p=>p.productVersionId),a=Z(t.screen),o=new Set,c=[];(!r.length||!t.products.defaultProductVersionId||!r.includes(t.products.defaultProductVersionId))&&c.push("products"),t.offeringVersionId||c.push("offering"),t.products.grouping&&(!W(t.products.grouping,r)||t.products.grouping.tiers.some(p=>!t.products.grouping.assignments.some(g=>g.tierId===p.id)))&&c.push("grouping");for(let p of Object.values(t.buttons))if(p.type==="checkout"){let g=p.product;if(g.type==="fixed")o.add(g.productVersionId);else{g.allowedProductVersionIds.forEach(m=>o.add(m));let f=!1,d=a[g.pickerId];d&&(f=!0,(g.allowedProductVersionIds.some(m=>!d.ids.includes(m))||d.ids.some(m=>!g.allowedProductVersionIds.includes(m)))&&c.push("picker")),w(t.screen,m=>{if(m.id!==g.pickerId||m.type!=="plan_picker")return;f=!0,(JSON.stringify(m.planIds)!==JSON.stringify(r)||JSON.stringify(g.allowedProductVersionIds)!==JSON.stringify(r)||m.defaultPlan!==t.products.defaultProductVersionId)&&c.push("picker");let i=m.grouping?{tiers:m.grouping.tiers,assignments:m.grouping.assignments}:void 0;JSON.stringify(i)!==JSON.stringify(t.products.grouping)&&c.push("grouping")}),f||c.push("picker")}}return(!o.size||[...o].some(p=>!r.includes(p)))&&c.push("purchase"),w(t.screen,p=>{p.type==="stack"&&p.productSlot&&!p.bind?.plan&&c.push(`productBinding:${p.id}`),(p.type==="stack"||p.type==="button")&&p.bind?.plan&&!r.includes(p.bind.plan)&&c.push("binding"),p.type==="plan_picker"&&(!p.planIds?.length||p.planIds.some(g=>!r.includes(g)))&&c.push("binding")}),[...new Set(c)]}function Ee(t){let r=[],a=t.screen.pages.at(-1),o=new Map;for(let f of t.screen.pages)o.set(f.id,[]),H(f.root,d=>{let m=d.type==="button"?d.action:d.type==="stack"?d.purchaseAction:void 0;if(m){let i=t.screen.actions.find(l=>l.id===m);i?.type==="navigate"&&o.get(f.id).push(i.pageId);let u=t.buttons[m];f.id!==a.id&&u&&u.type!=="close"&&r.push(`purchaseScreen:${d.id}`)}f.id!==a.id&&(d.type==="plan_picker"||d.type==="stack"&&d.productSlot)&&r.push(`packageScreen:${d.id}`)});let c=new Set;function p(f){if(!c.has(f)){c.add(f);for(let d of o.get(f)??[])p(d)}}let g=t.screen.initialPageId??t.screen.pages[0]?.id;g?p(g):r.push("initialPage");for(let f of t.screen.pages)c.has(f.id)||r.push(`unreachableScreen:${f.id}`);return[...new Set(r)]}var fe=e.object({id:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),revision:e.number().int().nonnegative(),state:e.enum(["active","archived"]),publishedVersionId:e.uuid().nullable(),updatedAt:e.iso.datetime({offset:!0}),draft:E}).strict(),It=e.object({rows:e.array(fe).max(200),nextCursor:e.uuid().nullable()}).strict(),Pt=fe.omit({draft:!0}).extend({name:e.string(),productCount:e.number().int().nonnegative()}).strict(),kt=e.discriminatedUnion("action",[e.object({action:e.literal("save"),id:e.uuid().nullable(),revision:e.number().int().nonnegative(),document:E}).strict(),e.object({action:e.enum(["publish","archive"]),id:e.uuid(),revision:e.number().int().nonnegative()}).strict()]),Ct=e.object({paywalls:e.array(e.object({id:e.uuid(),paywallId:e.uuid(),version:e.number().int().positive(),name:e.string().min(1).max(80),presentation:S,buttons:E.shape.buttons}).strict()).max(500),limited:e.boolean()}).strict();var _e=["customer_data","coupon_code"],ge=e.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),Re=e.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),_=(t,r)=>new Set(t.map(r)).size===t.length,De=e.strictObject({currency:T,amountMinor:e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),Ve=e.strictObject({featureId:e.uuid(),name:e.string().trim().min(1).max(120),allowance:e.string().max(40).nullable(),access:e.boolean()}),ze=e.strictObject({stripe:e.strictObject({prices:e.array(De).min(1).max(50)}).optional(),apple:e.strictObject({productIds:e.array(ge).min(1).max(10)}).optional(),google:e.strictObject({products:e.array(e.strictObject({productId:ge,basePlanId:Re.nullable()})).min(1).max(10)}).optional()}).superRefine((t,r)=>{(t.stripe&&!_(t.stripe.prices,a=>a.currency)||t.apple&&!_(t.apple.productIds,a=>a)||t.google&&!_(t.google.products,a=>`${a.productId}:${a.basePlanId}`))&&r.addIssue({code:"custom",message:"Duplicate channel entry"})}),Ge=e.strictObject({name:e.string().trim().min(1).max(80),interval:e.enum(["free","week","month","year","one_time"]),intervalCount:e.number().int().min(1).max(100),trial:e.strictObject({days:e.number().int().min(1).max(730),cardRequired:e.boolean()}).nullable(),benefits:e.array(Ve).max(50).refine(t=>_(t,r=>r.featureId),"Duplicate benefit"),channels:ze,prepaid:e.array(J).max(100).optional()}),Me=e.strictObject({digest:O,content:e.strictObject({discount:ee,duration:te,appliesTo:ne,displayCopy:de.nullable(),firstPurchaseOnly:e.boolean(),qualificationRequired:e.boolean(),startsAt:e.iso.datetime().nullable(),endsAt:e.iso.datetime().nullable(),grantWindowHours:e.number().int().positive(),perCustomerLimit:e.number().int().positive()})}),qe=e.discriminatedUnion("type",[e.strictObject({type:e.literal("checkout"),product:I}),e.strictObject({type:e.literal("close")}),e.strictObject({type:e.literal("action"),action:M})]),Nt=e.strictObject({kind:e.literal("paywall"),formatVersion:e.literal(1),name:e.string().trim().min(1).max(80),offeringVersionId:e.uuid(),presentation:S,screen:P,products:F,catalog:e.record(e.uuid(),Ge),buttons:e.record(X,qe),coupons:e.record(e.uuid(),Me)}).superRefine((t,r)=>{let a=n=>r.addIssue({code:"custom",message:n}),{screen:o}=t;ae(o,t.catalog).forEach(a),o.surface!=="paywall"&&a("Screen must be a Paywall"),re(o,_e).forEach(a),k(o).some(n=>!n.complete)&&a("Every published locale must be complete");let c=new Set,p=new Set,g=new Set;w(o,n=>{let b="bind"in n?n.bind:void 0;b?.promotionCode&&a("Promotion codes must not be published"),b?.plan&&c.add(b.plan),b?.coupon&&p.add(b.coupon),n.type==="plan_picker"&&(n.planIds?.forEach(x=>c.add(x)),n.defaultPlan&&c.add(n.defaultPlan)),n.type==="text"&&n.feature&&g.add(n.feature.id)});let f=t.products.items.map(n=>n.productVersionId),d=Object.keys(t.catalog);(f.length!==d.length||f.some(n=>!Object.hasOwn(t.catalog,n)))&&a("Catalog must contain exactly the displayed Products");let m=new Set(f);t.products.defaultProductVersionId!==null&&!m.has(t.products.defaultProductVersionId)&&a("Default Product must be displayed");for(let n of c)m.has(n)||a("Screen references a Product that is not displayed");for(let n of Object.values(t.catalog))!n.channels.stripe&&!n.channels.apple&&!n.channels.google&&a("A displayed Product needs at least one sales channel");let i=new Set(Object.values(t.catalog).flatMap(n=>n.benefits.map(b=>b.featureId)));for(let n of g)i.has(n)||a("Feature text must read a displayed benefit");let u=o.actions.filter(n=>n.type!=="navigate");o.actions.some(n=>n.type!=="event"&&n.type!=="navigate")&&a("Paywall actions are events or navigation"),(Object.keys(t.buttons).length!==u.length||u.some(n=>!Object.hasOwn(t.buttons,n.id)))&&a("Buttons must match the screen's actions");let y=!1;for(let n of Object.values(t.buttons)){if(n.type!=="checkout")continue;y=!0,(n.product.type==="fixed"?[n.product.productVersionId]:n.product.allowedProductVersionIds).some(x=>!m.has(x))&&a("Checkout may only sell displayed Products")}y||a("A Paywall needs a checkout button");let s=Object.keys(t.coupons);(s.length!==p.size||s.some(n=>!p.has(n)))&&a("Coupons must be exactly the bound Coupons")}),ye=e.strictObject({state:e.enum(["published","archived"]),controlRevision:e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:e.uuid(),versions:e.record(e.uuid(),e.strictObject({version:e.number().int().positive(),artifact:e.string().min(1),sourceDigest:e.string().regex(/^[a-f0-9]{64}$/)}))}).refine(t=>Object.keys(t.versions).length>0,"Reviewed Paywall Versions are required");var Be={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},q=e.string().regex(/^[a-f0-9]{64}$/),B=e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Ne=j.extend({environmentId:e.uuid()}),be=e.strictObject({features:e.array(e.string()).max(500),experiments:e.record(e.uuid(),e.array(e.string()).max(20)),savedGroups:e.array(e.string()).max(1e3)}),$e=e.strictObject({kind:e.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:e.number().int().positive(),url:e.string().min(1).max(2048),sha256:q,byteLength:e.number().int().positive().max(Be.maxArtifactBytes),generation:q.optional()}),Le=e.strictObject({state:e.enum(["active","paused","archived"]),controlRevision:B,evaluationMode:e.enum(["local","remote"]),evaluationRevision:B,currentVersionId:e.uuid(),versions:e.record(e.uuid(),e.strictObject({artifact:e.string(),dependencies:be,definitionDigest:O.optional(),couponDigests:e.record(e.uuid(),O).optional()}))}),Qt=e.strictObject({kind:e.literal("sdk_configuration"),schemaVersion:e.literal(1),scope:Ne,revision:B,generation:q,policy:e.strictObject({refreshIntervalSeconds:e.number().positive().max(15),maxControlAgeSeconds:e.number().positive().max(60)}),gb:e.strictObject({features:e.string().nullable(),pageExperiments:e.string().nullable()}),artifacts:e.record(e.string(),$e),funnels:e.record(e.uuid(),Le),paywalls:e.record(e.uuid(),ye).optional()}).superRefine((t,r)=>{let a=(o,c)=>{o!==null&&t.artifacts[o]?.kind!==c&&r.addIssue({code:"custom",message:"Missing or wrong-kind configuration artifact"})};a(t.gb.features,"gb_features"),a(t.gb.pageExperiments,"gb_page_experiments");for(let o of Object.values(t.paywalls??{}))for(let c of Object.values(o.versions))a(c.artifact,"paywall");for(let o of Object.values(t.funnels)){o.evaluationMode==="remote"&&Object.keys(o.versions).length&&r.addIssue({code:"custom",message:"Remote Funnel graphs cannot be public"}),o.evaluationMode==="local"&&!o.versions[o.currentVersionId]&&r.addIssue({code:"custom",message:"Current Funnel Version is not retained"});for(let c of Object.values(o.versions))a(c.artifact,"funnel")}});function N(t){if(Array.isArray(t))return`[${t.map(N).join(",")}]`;if(t!==null&&typeof t=="object")return`{${Object.entries(t).sort(([a],[o])=>a<o?-1:a>o?1:0).map(([a,o])=>`${JSON.stringify(a)}:${N(o)}`).join(",")}}`;let r=JSON.stringify(t);if(r===void 0)throw new Error("Configuration must contain JSON values");return r}function Ue(t){return L(U(typeof t=="string"?new TextEncoder().encode(t):t))}function Yt(t){return Ue(N(t))}var $=class extends Error{constructor(a,o){super(a);this.dependency=o}dependency};function en(t,r){let a=i=>i.type==="feature"?i.featureKey:i.type==="end"&&i.output?.type==="feature"?i.output.featureKey:i.type==="output"&&i.value.type==="feature"?i.value.featureKey:void 0,o=(i,u)=>t.graph.nodes.find(l=>i==="experiment"?l.type==="split"&&l.experimentId===u:i==="feature"&&a(l)===u)?.name,c=(i,u,l=o(u.type,u.resource))=>new $(i,{...u,...l?{step:l}:{}});for(let i of Object.values(t.references)){let u=i.type==="flag"?!Object.hasOwn(r.features,i.key)||r.remoteFeatures.includes(i.key)?{type:"feature",resource:i.key}:null:i.type==="experiment"?Object.hasOwn(r.experiments,i.id)?null:{type:"experiment",resource:i.id}:i.type==="saved_group"&&!Object.hasOwn(r.savedGroups,i.id)?{type:"saved_group",resource:i.id}:null;if(u)throw c("Funnel dependency is absent from GB public delivery",{reason:"unavailable",...u})}let p=me(t,{...r,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),g=new Set(r.remoteFeatures);for(let i of t.graph.nodes){let u=a(i);if(!u)continue;let l=p.features[u],y=i.type==="feature"?t.variables[i.writes.value]:t.outputSchema,s={type:"feature",resource:u};if(!l||!y)throw c("Required public Feature declaration is unavailable",{reason:"unavailable",...s},i.name);if([l.defaultValue,...(l.rules??[]).flatMap(b=>[...Object.hasOwn(b,"force")?[b.force]:[],...b.variations??[],...(b.tracks??[]).flatMap(x=>x.experiment.variations)])].some(b=>b===void 0||!Q(y,b)))throw c("GB Feature values violate the Funnel type contract",{reason:"value_type",...s},i.name)}let f=new Set,d=(i,u)=>{for(let l of A(i)){if(f.has(l))continue;let y=r.savedGroups[l];if(!y)throw c("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:l},u);f.add(l),!Array.isArray(y)&&y.type==="condition"&&d(y.condition,u)}},m=(i,u)=>{if(g.has(i)||!r.features[i])throw c("Local Funnel requires public Local prerequisites",{reason:"unavailable",type:"feature",resource:i},u)};for(let i of t.graph.nodes)if(i.type==="condition")for(let u of i.cases)d(u.condition,i.name);for(let[i,u]of Object.entries(p.features)){let l=o("feature",i);for(let y of u.rules??[]){d(y.condition,l);for(let s of[...y.parentConditions??[],...(y.tracks??[]).flatMap(n=>n.experiment.parentConditions??[])])m(s.id,l),d(s.condition,l);for(let s of y.tracks??[])d(s.experiment.condition,l)}}for(let[i,u]of Object.entries(p.experiments)){let l=o("experiment",i);d(u.condition,l);for(let y of u.parentConditions??[])m(y.id,l),d(y.condition,l)}for(let i of t.graph.nodes)if(i.type==="split"){let u=p.experiments[i.experimentId],l={type:"experiment",resource:i.experimentId};if(!u)throw c("Local Funnel requires a public Experiment",{reason:"unavailable",...l},i.name);for(let y of u.variations)if(typeof y!="string"||!Object.hasOwn(i.routes,y))throw c("Experiment variation has no declared Funnel route",{reason:"variation_route",...l},i.name)}return be.parse({features:Object.keys(p.features).sort(),experiments:Object.fromEntries(Object.entries(p.experiments).map(([i,u])=>[i,u.variations.map(String)])),savedGroups:[...f].sort()})}function tn(t){return ie.parse(t)}export{E as a,Ke as b,ce as c,je as d,v as e,Ie as f,rt as g,ot as h,it as i,at as j,st as k,me as l,Nt as m,Be as n,Ne as o,$e as p,Qt as q,N as r,Ue as s,Yt as t,en as u,tn as v};
@@ -1 +1 @@
1
- import{a as T,b as se}from"./chunk-GGRDM54V.js";import{b as re,h as ae,j as ce}from"./chunk-KR3KDTVD.js";import{a as oe,b as j}from"./chunk-FYQXSGRT.js";import{c as Z,e as ee,f as te,g as H,h as G,j as ne}from"./chunk-7MNJH5GB.js";import{F as M,b as J}from"./chunk-U6E6CM7Z.js";import{a as b,b as f,c as m}from"./chunk-JN6JEKWN.js";import{b as W,j as X}from"./chunk-NAZU3EEJ.js";import{E as $}from"./chunk-R23IGK5U.js";import{b as ie}from"./chunk-U2R7MG3J.js";import{a as B}from"./chunk-VYFSRHXM.js";import{a as s}from"./chunk-X4W22IH6.js";import{h as Q}from"./chunk-R4FDIYMN.js";import{b as K}from"./chunk-VF6QMMEA.js";import{a as z}from"./chunk-DSPLGTQI.js";var U=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new s("INVALID_STATE","Installation sequence exhausted");return t+1},Se=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function _(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new s("INVALID_STATE","Installation journal is invalid");return e({...n})})}function ue(t,e,n){let r=null,o=0,a=0,d=0,y=Promise.resolve(),g=!1;if(t&&(!n||Q.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new s("SCOPE_MISMATCH","Push installation belongs to another scope");let l=()=>{if(g)throw new s("CLOSED","SDK client was destroyed");if(!t)throw new s("NOT_CONFIGURED","Configure this client's native Push host first");return t},O=i=>{if(i!==o)throw new s("IDENTITY_CHANGED","Identity changed during Push operation")};async function F(i){let c=l();if(!c.sha256&&!globalThis.crypto?.subtle)throw new s("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let u=c.sha256?await c.sha256(Uint8Array.from(i,A=>A.charCodeAt(0))):await Se(i);if(!/^[a-f0-9]{64}$/.test(u))throw new s("INVALID_STATE","Push credential digest is invalid");return u}function p(i){let c=G.parse(i);if(c.installationId.toLowerCase()!==l().installationId.toLowerCase())throw new s("INVALID_RESPONSE","Push response belongs to another installation");return c}async function S(i,c){let u=l(),A={installationId:u.installationId,publicKey:u.publicKey,issuedAt:new Date().toISOString(),...c},w=await u.sign(ne(i,u.scope,A));return{...A,signature:w}}let I=(i,c,u)=>e.requestWithCredential?e.requestWithCredential(i,c,u):e.request(i,c);async function q(){let i=l(),c=o,u=r?await(e.session?.access()??r):null,A=_(i,v=>v),w;if(A.detachSeq!==null){let v=A.detachSeq,V=Z.parse(await S("detach",{sequence:v,platform:i.platform}));try{let k=await e.request("push/installations/detach",{...i.scope,...V},"POST",{installationDetach:!0});if(!k||typeof k!="object"||!("installation"in k))throw new s("INVALID_RESPONSE","Push detach acknowledgement is invalid");let x=p(k.installation);if(x.bound||x.identitySeq!==v)throw new s("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(k){if(k instanceof s&&k.status===404)w=k;else if(!(k instanceof s)||k.status!==412)throw k}w||_(i,k=>({...k,detachSeq:k.detachSeq===v?null:k.detachSeq}))}if(O(c),!u){if(w)throw w;return null}let C=(await import("./operation-contracts-443N2P3A.js")).apiOperations.bindPushInstallation,D=C.request.parse(await S("bind",{sequence:d,platform:i.platform,credentialDigest:await F(u)}));O(c);let R=C.response.parse(await I(C.path,D,u));O(c);let N=p(R.installation);if(!N.bound||N.identitySeq!==d)throw new s("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return w&&A.detachSeq!==null&&d>A.detachSeq&&_(i,v=>({...v,detachSeq:v.detachSeq===A.detachSeq?null:v.detachSeq})),N}async function h(){l();let i=o,c=r?await(e.session?.access()??r):null;if(!c)throw new s("NOT_IDENTIFIED","Identify before reading this installation");let u=(await import("./operation-contracts-443N2P3A.js")).apiOperations.readPushInstallation,A=u.request.parse(await S("read",{credentialDigest:await F(c)}));O(i);let w=u.response.parse(await I(u.path,A,c));return O(i),p(w.installation)}function P(i=q){let c=y.catch(()=>{}).then(i);return y=c,c.catch(u=>{try{t?.onError?.(u instanceof Error?u:new Error("Push synchronization failed"))}catch{}}),c}async function E(i,c,u){let A=l(),w=c.identity,C=c.observation,D=r?await(e.session?.access()??r):null;if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");if(!D)throw new s("NOT_IDENTIFIED","Identify before recovering a Push address");if(!i.connectionId||!i.kind||!i.token||!["granted","provisional"].includes(i.permission))throw new s("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await P(async()=>{if(O(w),await q(),O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let R=_(A,x=>u?x:{...x,addressSeq:U(x.addressSeq)}),v=await S(u?"recovery_confirm":"recovery_request",{...i,sequence:R.addressSeq,credentialDigest:await F(D),...u?{challenge:u}:{}}),V=u?te.parse(v):ee.parse(v);if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let k=await I(`push/installations/recovery/${u?"confirm":"request"}`,V,D);if(O(w),C!==a||_(A,x=>x).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");if(u){let{apiOperations:x}=await import("./operation-contracts-443N2P3A.js");if(O(w),C!==a||_(A,Oe=>Oe).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");let Ae=x.updatePushAddress.response.parse(k),L=p(Ae.installation);if(!L.bound||L.identitySeq!==d||L.addressSeq!==R.addressSeq||L.connectionId!==i.connectionId||L.addressStatus!=="active")throw new s("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return L}if(!k||typeof k!="object"||!("recovery"in k))throw new s("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return H.parse(k.recovery)})}return{recoveryObserver(){l();let i={identity:o,observation:++a};return{async request(c){return H.parse(await E(c,i))},async confirm(c,u){return G.parse(await E(u,i,c))}}},identify(i){if(!t)return;d=_(t,u=>({...u,identitySeq:U(u.identitySeq)})).identitySeq,r=i,o++,a++},reset(){if(t)try{_(t,i=>{let c=U(i.identitySeq);return{...i,identitySeq:c,detachSeq:c}})}finally{r=null,o++,a++}},start(){t&&!g&&P()},destroy(){g=!0,r=null,o++,a++},async sync(){return await P()},read:h,async recover(){let i=l(),c=o,u=d;return a++,await P(async()=>{O(c);let A=await h();return O(c),d=_(i,C=>{if(C.identitySeq!==u)throw new s("IDENTITY_CHANGED","A newer installation intent exists");return{...C,identitySeq:U(Math.max(C.identitySeq,A.identitySeq)),addressSeq:Math.max(C.addressSeq,A.addressSeq)}}).identitySeq,await q()})},tokenObserver(){l();let i=++a,c=o;return async u=>{if(i!==a||c!==o)return null;let A=l(),w=r?await(e.session?.access()??r):null;if(!w)throw new s("NOT_IDENTIFIED","Identify before registering a Push token");if(await P(),O(c),i!==a)return null;let C=_(A,v=>({...v,addressSeq:U(v.addressSeq)})),D=(await import("./operation-contracts-443N2P3A.js")).apiOperations.updatePushAddress,R=D.request.parse(await S("address",{...u,sequence:C.addressSeq,credentialDigest:await F(w)}));if(O(c),i!==a)return null;let N=await I(D.path,R,w);return O(c),i!==a||_(A,v=>v).addressSeq!==C.addressSeq?null:p(D.response.parse(N).installation)}}}}function de(t,e){let n={async preference(r){let o=await f(t,"readMessagingPreference");return(await m(t,o,{channel:r})).preference},async setPreference(r){r=b(r);let o=await f(t,"setMessagingPreference");return(await m(t,o,r)).preference}};return{messaging:n,push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return r=b(r),n.setPreference({...r,channel:"push"})}}}}function le(t,e,n={}){let r=!1;function o(){if(r)throw new s("CLOSED","SDK client was destroyed")}let a=new Set,d=g=>{for(let l of a)try{l(g)}catch{}},y=t.session.subscribeIdentity(()=>{d(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:o,isIdentified:()=>!r&&!!t.session.peek(),methods:{subscribeIdentity(g){return o(),a.add(g),()=>{a.delete(g)}},identify(g){o();let l=typeof g=="string"?g:g.accessToken;if(!B.test(l))throw new s("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(l),t.identify(g)},reset(){if(!r)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!r){r=!0,y(),a.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}function pe(t){return{async checkEntitlement(e){e=b(e),T(e);let n=await f(t,"checkEntitlement"),r=n.request.parse(e),o=await m(t,n,r);return oe(r.requirement,o.check,void 0,o.scope),o},async readHoldings(e={}){e=b(e);let n=await f(t,"readHoldings"),r={...n,request:n.request.omit({customerId:!0})};return m(t,r,e)}}}function fe(t){return{async readLedger(e){e=b(e);let n=await f(t,"readLedger");return m(t,n,{query:e})},async readCreditStatement(e){e=b(e),T(e);let n=await f(t,"readCreditStatement");return m(t,n,e)},async quoteBalance(e){e=b(e),T(e);let n=await f(t,"quoteBalance");return m(t,n,{command:e})}}}function me(t){return{async setupPayment(e){e=b(e),T(e);let n=await f(t,"setupPayment");return m(t,n,e)},async readPaymentSetup(e){e=b(e),T(e);let n=await f(t,"readPaymentSetup");return m(t,n,e)},async readBillingInvoice(e){e=b(e),T(e);let n=await f(t,"readBillingInvoice");return m(t,n,e)},async readBillingControls(e={}){e=b(e),T(e);let n=await f(t,"readBillingControls");return m(t,n,e)},async prepareBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"prepareBillingAuthorization");return m(t,n,e)},async confirmBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"confirmBillingAuthorization");return m(t,n,e)},async setBillingCoupons(e){e=b(e),T(e);let n=await f(t,"setBillingCoupons");return m(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"revokeBillingAuthorization");return m(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){e=b(e),T(e);let n=await f(t,"listBillingInvoices");return m(t,n,e)},async confirmBillingAdjustment(e){e=b(e),T(e);let n=await f(t,"confirmBillingAdjustment");return m(t,n,e)}}}function ye(t){return{async redeemReward(e){return e=b(e),T(e),(await m(t,await f(t,"redeemReward"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return e=b(e),T(e),(await m(t,await f(t,"claimRewardProduct"),e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return e=b(e),T(e),(await m(t,await f(t,"createReferralCode"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){typeof e=="string"&&(e=e.trim().toUpperCase());let r=await m(t,await f(t,"redeemCoupon"),{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await m(t,await f(t,"grantOffer"),{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await m(t,await f(t,"listOffers"),{},{response:"Invalid offers response"})).offers}}}function Ie(t){return{...pe(t),...fe(t),...me(t),...se(t),...ye(t)}}function he(t){return{async resolveContent(e){e=b(e),T(e);let n=await f(t,"resolveContent");return m(t,n,e)},async resolvePaywall(e){e=b(e),T(e);let n=await f(t,"resolvePaywall"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.paywall.check,o.scope),o},async resolveOffering(e){e=b(e),T(e);let n=await f(t,"resolveOffering"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.check,o.scope),o}}}var Y=t=>new TextEncoder().encode(JSON.stringify(t)).length,we=16384,Pe=5e3,Ce=6e4,Re=5;function Te(t){return t instanceof s&&t.status!==void 0&&t.status>=400&&t.status<500&&!t.retryable}function ge(t,e){let n=0,r,o=h=>{r={config:structuredClone(h),until:Date.now()+3e4}},a=[],d=null,y,g=0;function l(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}function O(){y||!a.length||!e()||(y=setTimeout(()=>{y=void 0,S().catch(()=>{}).finally(O)},Math.min(Pe*2**g,Ce)),typeof y=="object"&&"unref"in y&&y.unref())}function F(h){if(l(),r&&Date.now()<r.until&&!W(r.config,h.kind))return;q();let P=X.parse({events:[{...h,eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString()}]}).events[0];if(Y({events:[P]})>we)throw new s("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new s("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(P)),O()}function p(h,P={},E={}){F({kind:"custom",name:h,properties:P,...E})}async function S(h=!1){if(l(),d)return d;let P=n,E=(async()=>{let i={inserted:0,duplicates:0,rejected:0,skipped:0,rejections:[]},c=a.length;for(;c&&P===n;){let u=[],A=Y({events:[]});for(let C of a.slice(0,Math.min(c,100))){let D=Y(C)+(u.length?1:0);if(u.length&&A+D>we)break;u.push(C),A+=D}let w;try{let C=await f(t,"trackEvents");if(w=await m(t,C,{events:u},void 0,{keepalive:h}),P!==n)throw new s("IDENTITY_CHANGED","Event identity changed during delivery");if(w.inserted+w.duplicates+w.rejected+w.skipped!==u.length||w.rejections.length!==w.rejected)throw new s("INVALID_RESPONSE","Incomplete event acknowledgement")}catch(C){throw P===n&&(g++,(Te(C)||g>=Re)&&(a.splice(0,u.length),g=0)),C}g=0,o(w.analyticsConfig),a.splice(0,u.length),c-=u.length,i.inserted+=w.inserted,i.duplicates+=w.duplicates,i.rejected+=w.rejected,i.skipped+=w.skipped,i.rejections.push(...w.rejections)}return i})();d=E;try{return await E}finally{d===E&&(d=null)}}let I;function q(){if(I||typeof document>"u")return;let h=()=>{document.visibilityState==="hidden"&&e()&&a.length&&S(!0).catch(()=>{})};document.addEventListener("visibilitychange",h),I=()=>document.removeEventListener("visibilitychange",h)}return{rememberConfiguration:o,track:p,observe:F,flush:S,reset(){n++,r=void 0,clearTimeout(y),y=void 0,a=[],g=0,d=null},detachVisibility(){I?.(),I=void 0}}}function ve(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}var qe=new Set([...$,"merchandiseId","merchandise"]);function ke(t){let e=ve(t);return{...Object.fromEntries(Object.entries(t).filter(([r])=>!qe.has(r))),...e?{merchandise:e}:{}}}function Ee(t,e,n,r,o){if(o&&r&&(o.scope.projectId!==r.projectId||o.scope.environment!==r.environment))throw new s("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,d=new Set;function y(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}async function g(l={}){o||y();let O=a,F=!1,p=async()=>{if(F||O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let R=o?{scope:{projectId:o.scope.projectId,environment:o.scope.environment},payload:await o.features()}:await m(t,await f(t,"getFeatures"),{});if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");if(r&&(R.scope.projectId!==r.projectId||R.scope.environment!==r.environment))throw new s("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(R.payload.analyticsConfig),R},S=await p(),I=!0,q,h=R=>{try{l.onError?.(R)}catch{}},P=(R,N)=>{try{let v=ve(N);n.observe({...R,...v?{merchandise:v}:{}})}catch(v){h(v)}},E=ae({assertUsable:o?.assertFeatures,scope:S.scope,attributes:l.attributes,onError:l.onError,load:async()=>I?(I=!1,S.payload):(await p()).payload,evaluateRemote:async R=>{if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let N=await f(t,"evaluateFeatures"),v=await m(t,N,{...R,attributes:ke(R.attributes)});if(v.scope.projectId!==S.scope.projectId||v.scope.environment!==S.scope.environment)throw new s("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:v.generation,evaluatedAt:v.evaluatedAt,expiresAt:v.expiresAt,features:v.features,...v.merchandiseContext?{merchandiseContext:v.merchandiseContext}:{}}},onExperimentViewed:(R,N,v,V)=>P({kind:"experiment_exposure",generation:V,experimentId:R.key,variationId:N.key},v),onFeatureUsage:(R,N,v,V)=>P({kind:"feature_usage",generation:V,feature:R,value:N.value??null,source:N.source,ruleId:N.ruleId,...N.experimentResult?{variationId:N.experimentResult.key}:{}},v)}),i=E.refresh;function c(){clearTimeout(q),!o&&(F||O!==a||!E.expiresAt||(q=setTimeout(()=>{u().catch(h)},Math.min(2147483647,Math.max(1e3,Date.parse(E.expiresAt)-Date.now()))),typeof q=="object"&&"unref"in q&&q.unref()))}async function u(){try{return await i()}finally{c()}}let A=()=>{F||u().catch(h)},w=E.subscribe(c),C=o?.subscribe(()=>{!F&&o.fresh&&u().catch(h)});function D(){F||(F=!0,clearTimeout(q),typeof window<"u"&&window.removeEventListener("focus",A),w(),C?.(),E.reset(),d.delete(D))}d.add(D);try{await E.init(),(l.attributes?.merchandise||l.attributes?.merchandiseId)&&await E.refreshRemote()}catch(R){throw D(),R}return c(),!o&&typeof window<"u"&&window.addEventListener("focus",A),Object.assign(E,{refresh:u,destroy:D})}return{features:g,reset(l){a++,l();for(let O of d)O()}}}function be(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=K.object({funnelId:J.shape.id,funnelVersionId:J.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new s("INVALID_REQUEST","A valid Funnel source is required");let o=Object.freeze(r.data);function a(d){if("customerId"in d)throw new s("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in d&&d.funnelId!==void 0&&d.funnelId!==o.funnelId||"funnelVersionId"in d&&d.funnelVersionId!==void 0&&d.funnelVersionId!==o.funnelVersionId)throw new s("SCOPE_MISMATCH","The original Funnel source cannot change");return{...d,...o}}return{async claimCoupon(d,y=crypto.randomUUID()){let g=await f(t,"grantOffer"),l=await m(t,g,a({couponId:d,requestId:y}));return{offer:l.offer,reason:l.reason}},async resolveOffering(d){d=b(d);let y=await f(t,"resolveOffering"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.check,l.scope),l},async resolvePaywall(d){d=b(d);let y=await f(t,"resolvePaywall"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.paywall.check,l.scope),l},async previewAttach(d){d=b(d);let y=await f(t,"previewAttach");return m(t,y,a(d))}}}function xt(t){return Ne(t)}function Ne(t){let e=ie(t),n=e.request,r;try{r=ue(t.push,e,t.scope??t.configuration?.scope)}catch(y){throw e.dispose(),y}let o=le(e,()=>{d.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=ge(n,o.isIdentified),d=Ee(n,o.isIdentified,a,t.scope,t.configuration);return{session:e.session,...de(n,r),...Ie(n),...he(n),forFunnel(y){return o.assertActive(),be(n,y)},async features(y={}){return o.assertActive(),d.features(y)},track(y,g,l={}){return a.track(y,g,l)},flush(){return a.flush()},...o.methods}}function Mt(t){if(!B.test(t.customerToken))throw new s("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new s("INVALID_REQUEST","An explicit App and environment scope is required");let e=ce({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),o=M({...t,runToken:r.runToken,initialResponse:r});o.identify(t.customerToken);let a=await o.get();return{...r,...a,controller:o}}}}function Kt(t){if(!t.scope)throw new s("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new s("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,r=0,o=new Set,a=new Map,d=new Map;async function y(p){let S,I=new Promise((q,h)=>{S=setTimeout(()=>h(new s("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(p),I])}finally{clearTimeout(S)}}function g(p){throw p instanceof s&&(p.status===401||p.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear()),p}function l(p,S){if(S!==r)throw new s("IDENTITY_CHANGED","Process was detached during a request");let I=re.parse(p);if(I.scope.projectId!==t.scope.projectId||I.scope.environment!==t.scope.environment)throw new s("SCOPE_MISMATCH","Process response belongs to another App/environment");if(e&&(e.run.id!==I.run.id||e.run.source.versionId!==I.run.source.versionId||e.run.source.id!==I.run.source.id||e.run.runExpiresAt!==I.run.runExpiresAt||e.run.identity.startedAs!==I.run.identity.startedAs||e.run.identity.participantId!==I.run.identity.participantId||e.run.identity.binding&&I.run.identity.binding&&e.run.identity.binding.id!==I.run.identity.binding.id))throw new s("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!e||I.run.revision>=e.run.revision){if(e?.run.identity.binding&&!I.run.identity.binding)throw new s("INVALID_RESPONSE","The process lost its Customer binding");e=I;for(let A of o)z(A,I.run);I.run.instruction?.type==="authentication_required"&&z(t.onAuthenticationRequired,I.run)}I.settlement?.accepted!==void 0&&d.set(I.settlement.requestId,I.settlement.accepted);let{identity:q,instruction:h,...P}=I.run,{contract:E,settlement:i,...c}=I,u=i&&(({accepted:A,...w})=>w)(i);return{...c,run:{...P,authenticated:q.binding!==null,instruction:h?.type==="authentication_required"?null:h},...u?{settlement:u}:{}}}let O=p=>(a.has(p)||a.set(p,e?.run.identity.binding?.id??null),a.get(p));async function F(p){let S=r,I=e?.run.identity.binding?.id??null,q=P=>{if(I!==(e?.run.identity.binding?.id??null))throw P;return g(P)};if(p.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new s("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return y(()=>t.adapter.pageExperiments(p.release,p.usedReceiptIds)).catch(q)}let h;if(p.operation==="get"){let{operation:P,customerToken:E,...i}=p;h=await y(()=>t.adapter.get({...i,...i.settlementRequestId?{settlementBindingId:O(i.settlementRequestId)}:{}})).catch(q)}else if(p.operation==="review")h=await y(()=>t.adapter.review(p.receiptId)).catch(q);else{if(p.operation==="start")throw new s("INVALID_REQUEST","Use process.open for entry");{let{customerToken:P,...E}=p;h=await y(()=>t.adapter.command(E,O(E.requestId))).catch(q)}}return l(h,S)}return{get view(){return e?.run??null},get controller(){return n},async open(p){let S=r,I=await y(()=>t.adapter.open(p)).catch(g),q=l(I,S);if(!n){n=M({...t,runToken:I.runToken,initialResponse:q,process:{request:F,binding:O,restore(E){for(let[i,c]of Object.entries(E))a.set(i,c)}}});let h=n,P=h.submit;h.submit=async E=>{try{return await P(E)}catch(i){if(!(i instanceof s)||i.reason!=="IDENTITY_CONTEXT_CHANGED"||E.operation!=="submit"||E.input.type!=="screen"||a.get(E.requestId)!==null)throw i;await h.settle?.(E.requestId),await h.get();let c=h.view;if(d.get(E.requestId)!==!1||!c||c.id!==e?.run.id||c.nodeId!==E.nodeId||c.visit!==E.visit||!e?.run.identity.binding)throw i;return P({...E,requestId:crypto.randomUUID(),revision:c.revision})}}}await n.get();for(let h of n.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(e?.run.identity.binding?.id??null)&&await n.settle?.(h.requestId);return{run:e.run,controller:n}},async syncIdentity(){let p=r;l(await y(()=>t.adapter.syncIdentity()).catch(g),p),await n?.get();for(let S of n?.pendingCommands??[])a.has(S.requestId)&&a.get(S.requestId)!==(e?.run.identity.binding?.id??null)&&await n?.settle?.(S.requestId);return e.run},async detach(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),await y(()=>t.adapter.detach())},forProcess(p){if(!e?.run.identity.binding)throw new s("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:p}},subscribe(p){return o.add(p),()=>{o.delete(p)}},destroy(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),o.clear()}}}export{xt as a,Ne as b,Mt as c,Kt as d};
1
+ import{a as T,b as se}from"./chunk-KPDHY76A.js";import{b as re,h as ae,j as ce}from"./chunk-BLVBUN2R.js";import{F as M,b as J}from"./chunk-2FE4FTPH.js";import{a as b,b as f,c as m}from"./chunk-EUTWY7A2.js";import{c as Z,e as ee,f as te,g as H,h as G,j as ne}from"./chunk-7MNJH5GB.js";import{a as oe,b as j}from"./chunk-LF2UIJYD.js";import{b as W,j as X}from"./chunk-PUR5CYWX.js";import{E as $}from"./chunk-TAFALMQN.js";import{b as ie}from"./chunk-56BYGPQ6.js";import{a as B}from"./chunk-VYFSRHXM.js";import{b as Q}from"./chunk-TJGIT5CU.js";import{a as s}from"./chunk-OX7PA64E.js";import{b as K}from"./chunk-VF6QMMEA.js";import{a as z}from"./chunk-DSPLGTQI.js";var U=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new s("INVALID_STATE","Installation sequence exhausted");return t+1},Se=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function _(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new s("INVALID_STATE","Installation journal is invalid");return e({...n})})}function ue(t,e,n){let r=null,o=0,a=0,d=0,y=Promise.resolve(),g=!1;if(t&&(!n||Q.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new s("SCOPE_MISMATCH","Push installation belongs to another scope");let l=()=>{if(g)throw new s("CLOSED","SDK client was destroyed");if(!t)throw new s("NOT_CONFIGURED","Configure this client's native Push host first");return t},O=i=>{if(i!==o)throw new s("IDENTITY_CHANGED","Identity changed during Push operation")};async function F(i){let c=l();if(!c.sha256&&!globalThis.crypto?.subtle)throw new s("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let u=c.sha256?await c.sha256(Uint8Array.from(i,A=>A.charCodeAt(0))):await Se(i);if(!/^[a-f0-9]{64}$/.test(u))throw new s("INVALID_STATE","Push credential digest is invalid");return u}function p(i){let c=G.parse(i);if(c.installationId.toLowerCase()!==l().installationId.toLowerCase())throw new s("INVALID_RESPONSE","Push response belongs to another installation");return c}async function S(i,c){let u=l(),A={installationId:u.installationId,publicKey:u.publicKey,issuedAt:new Date().toISOString(),...c},w=await u.sign(ne(i,u.scope,A));return{...A,signature:w}}let I=(i,c,u)=>e.requestWithCredential?e.requestWithCredential(i,c,u):e.request(i,c);async function q(){let i=l(),c=o,u=r?await(e.session?.access()??r):null,A=_(i,v=>v),w;if(A.detachSeq!==null){let v=A.detachSeq,V=Z.parse(await S("detach",{sequence:v,platform:i.platform}));try{let k=await e.request("push/installations/detach",{...i.scope,...V},"POST",{installationDetach:!0});if(!k||typeof k!="object"||!("installation"in k))throw new s("INVALID_RESPONSE","Push detach acknowledgement is invalid");let x=p(k.installation);if(x.bound||x.identitySeq!==v)throw new s("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(k){if(k instanceof s&&k.status===404)w=k;else if(!(k instanceof s)||k.status!==412)throw k}w||_(i,k=>({...k,detachSeq:k.detachSeq===v?null:k.detachSeq}))}if(O(c),!u){if(w)throw w;return null}let C=(await import("./operation-contracts-HS4M2UXN.js")).apiOperations.bindPushInstallation,D=C.request.parse(await S("bind",{sequence:d,platform:i.platform,credentialDigest:await F(u)}));O(c);let R=C.response.parse(await I(C.path,D,u));O(c);let N=p(R.installation);if(!N.bound||N.identitySeq!==d)throw new s("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return w&&A.detachSeq!==null&&d>A.detachSeq&&_(i,v=>({...v,detachSeq:v.detachSeq===A.detachSeq?null:v.detachSeq})),N}async function h(){l();let i=o,c=r?await(e.session?.access()??r):null;if(!c)throw new s("NOT_IDENTIFIED","Identify before reading this installation");let u=(await import("./operation-contracts-HS4M2UXN.js")).apiOperations.readPushInstallation,A=u.request.parse(await S("read",{credentialDigest:await F(c)}));O(i);let w=u.response.parse(await I(u.path,A,c));return O(i),p(w.installation)}function P(i=q){let c=y.catch(()=>{}).then(i);return y=c,c.catch(u=>{try{t?.onError?.(u instanceof Error?u:new Error("Push synchronization failed"))}catch{}}),c}async function E(i,c,u){let A=l(),w=c.identity,C=c.observation,D=r?await(e.session?.access()??r):null;if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");if(!D)throw new s("NOT_IDENTIFIED","Identify before recovering a Push address");if(!i.connectionId||!i.kind||!i.token||!["granted","provisional"].includes(i.permission))throw new s("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await P(async()=>{if(O(w),await q(),O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let R=_(A,x=>u?x:{...x,addressSeq:U(x.addressSeq)}),v=await S(u?"recovery_confirm":"recovery_request",{...i,sequence:R.addressSeq,credentialDigest:await F(D),...u?{challenge:u}:{}}),V=u?te.parse(v):ee.parse(v);if(O(w),C!==a)throw new s("INVALID_STATE","Push observation changed during recovery");let k=await I(`push/installations/recovery/${u?"confirm":"request"}`,V,D);if(O(w),C!==a||_(A,x=>x).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");if(u){let{apiOperations:x}=await import("./operation-contracts-HS4M2UXN.js");if(O(w),C!==a||_(A,Oe=>Oe).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");let Ae=x.updatePushAddress.response.parse(k),L=p(Ae.installation);if(!L.bound||L.identitySeq!==d||L.addressSeq!==R.addressSeq||L.connectionId!==i.connectionId||L.addressStatus!=="active")throw new s("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return L}if(!k||typeof k!="object"||!("recovery"in k))throw new s("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return H.parse(k.recovery)})}return{recoveryObserver(){l();let i={identity:o,observation:++a};return{async request(c){return H.parse(await E(c,i))},async confirm(c,u){return G.parse(await E(u,i,c))}}},identify(i){if(!t)return;d=_(t,u=>({...u,identitySeq:U(u.identitySeq)})).identitySeq,r=i,o++,a++},reset(){if(t)try{_(t,i=>{let c=U(i.identitySeq);return{...i,identitySeq:c,detachSeq:c}})}finally{r=null,o++,a++}},start(){t&&!g&&P()},destroy(){g=!0,r=null,o++,a++},async sync(){return await P()},read:h,async recover(){let i=l(),c=o,u=d;return a++,await P(async()=>{O(c);let A=await h();return O(c),d=_(i,C=>{if(C.identitySeq!==u)throw new s("IDENTITY_CHANGED","A newer installation intent exists");return{...C,identitySeq:U(Math.max(C.identitySeq,A.identitySeq)),addressSeq:Math.max(C.addressSeq,A.addressSeq)}}).identitySeq,await q()})},tokenObserver(){l();let i=++a,c=o;return async u=>{if(i!==a||c!==o)return null;let A=l(),w=r?await(e.session?.access()??r):null;if(!w)throw new s("NOT_IDENTIFIED","Identify before registering a Push token");if(await P(),O(c),i!==a)return null;let C=_(A,v=>({...v,addressSeq:U(v.addressSeq)})),D=(await import("./operation-contracts-HS4M2UXN.js")).apiOperations.updatePushAddress,R=D.request.parse(await S("address",{...u,sequence:C.addressSeq,credentialDigest:await F(w)}));if(O(c),i!==a)return null;let N=await I(D.path,R,w);return O(c),i!==a||_(A,v=>v).addressSeq!==C.addressSeq?null:p(D.response.parse(N).installation)}}}}function de(t,e){let n={async preference(r){let o=await f(t,"readMessagingPreference");return(await m(t,o,{channel:r})).preference},async setPreference(r){r=b(r);let o=await f(t,"setMessagingPreference");return(await m(t,o,r)).preference}};return{messaging:n,push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return r=b(r),n.setPreference({...r,channel:"push"})}}}}function le(t,e,n={}){let r=!1;function o(){if(r)throw new s("CLOSED","SDK client was destroyed")}let a=new Set,d=g=>{for(let l of a)try{l(g)}catch{}},y=t.session.subscribeIdentity(()=>{d(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:o,isIdentified:()=>!r&&!!t.session.peek(),methods:{subscribeIdentity(g){return o(),a.add(g),()=>{a.delete(g)}},identify(g){o();let l=typeof g=="string"?g:g.accessToken;if(!B.test(l))throw new s("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(l),t.identify(g)},reset(){if(!r)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!r){r=!0,y(),a.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}function pe(t){return{async checkEntitlement(e){e=b(e),T(e);let n=await f(t,"checkEntitlement"),r=n.request.parse(e),o=await m(t,n,r);return oe(r.requirement,o.check,void 0,o.scope),o},async readHoldings(e={}){e=b(e);let n=await f(t,"readHoldings"),r={...n,request:n.request.omit({customerId:!0})};return m(t,r,e)}}}function fe(t){return{async readLedger(e){e=b(e);let n=await f(t,"readLedger");return m(t,n,{query:e})},async readCreditStatement(e){e=b(e),T(e);let n=await f(t,"readCreditStatement");return m(t,n,e)},async quoteBalance(e){e=b(e),T(e);let n=await f(t,"quoteBalance");return m(t,n,{command:e})}}}function me(t){return{async setupPayment(e){e=b(e),T(e);let n=await f(t,"setupPayment");return m(t,n,e)},async readPaymentSetup(e){e=b(e),T(e);let n=await f(t,"readPaymentSetup");return m(t,n,e)},async readBillingInvoice(e){e=b(e),T(e);let n=await f(t,"readBillingInvoice");return m(t,n,e)},async readBillingControls(e={}){e=b(e),T(e);let n=await f(t,"readBillingControls");return m(t,n,e)},async prepareBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"prepareBillingAuthorization");return m(t,n,e)},async confirmBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"confirmBillingAuthorization");return m(t,n,e)},async setBillingCoupons(e){e=b(e),T(e);let n=await f(t,"setBillingCoupons");return m(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){e=b(e),T(e);let n=await f(t,"revokeBillingAuthorization");return m(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){e=b(e),T(e);let n=await f(t,"listBillingInvoices");return m(t,n,e)},async confirmBillingAdjustment(e){e=b(e),T(e);let n=await f(t,"confirmBillingAdjustment");return m(t,n,e)}}}function ye(t){return{async redeemReward(e){return e=b(e),T(e),(await m(t,await f(t,"redeemReward"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return e=b(e),T(e),(await m(t,await f(t,"claimRewardProduct"),e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return e=b(e),T(e),(await m(t,await f(t,"createReferralCode"),{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){typeof e=="string"&&(e=e.trim().toUpperCase());let r=await m(t,await f(t,"redeemCoupon"),{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await m(t,await f(t,"grantOffer"),{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await m(t,await f(t,"listOffers"),{},{response:"Invalid offers response"})).offers}}}function Ie(t){return{...pe(t),...fe(t),...me(t),...se(t),...ye(t)}}function he(t){return{async resolveContent(e){e=b(e),T(e);let n=await f(t,"resolveContent");return m(t,n,e)},async resolvePaywall(e){e=b(e),T(e);let n=await f(t,"resolvePaywall"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.paywall.check,o.scope),o},async resolveOffering(e){e=b(e),T(e);let n=await f(t,"resolveOffering"),r=n.request.parse(e),o=await m(t,n,r);return j(r,o.check,o.scope),o}}}var Y=t=>new TextEncoder().encode(JSON.stringify(t)).length,we=16384,Pe=5e3,Ce=6e4,Re=5;function Te(t){return t instanceof s&&t.status!==void 0&&t.status>=400&&t.status<500&&!t.retryable}function ge(t,e){let n=0,r,o=h=>{r={config:structuredClone(h),until:Date.now()+3e4}},a=[],d=null,y,g=0;function l(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}function O(){y||!a.length||!e()||(y=setTimeout(()=>{y=void 0,S().catch(()=>{}).finally(O)},Math.min(Pe*2**g,Ce)),typeof y=="object"&&"unref"in y&&y.unref())}function F(h){if(l(),r&&Date.now()<r.until&&!W(r.config,h.kind))return;q();let P=X.parse({events:[{...h,eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString()}]}).events[0];if(Y({events:[P]})>we)throw new s("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new s("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(P)),O()}function p(h,P={},E={}){F({kind:"custom",name:h,properties:P,...E})}async function S(h=!1){if(l(),d)return d;let P=n,E=(async()=>{let i={inserted:0,duplicates:0,rejected:0,skipped:0,rejections:[]},c=a.length;for(;c&&P===n;){let u=[],A=Y({events:[]});for(let C of a.slice(0,Math.min(c,100))){let D=Y(C)+(u.length?1:0);if(u.length&&A+D>we)break;u.push(C),A+=D}let w;try{let C=await f(t,"trackEvents");if(w=await m(t,C,{events:u},void 0,{keepalive:h}),P!==n)throw new s("IDENTITY_CHANGED","Event identity changed during delivery");if(w.inserted+w.duplicates+w.rejected+w.skipped!==u.length||w.rejections.length!==w.rejected)throw new s("INVALID_RESPONSE","Incomplete event acknowledgement")}catch(C){throw P===n&&(g++,(Te(C)||g>=Re)&&(a.splice(0,u.length),g=0)),C}g=0,o(w.analyticsConfig),a.splice(0,u.length),c-=u.length,i.inserted+=w.inserted,i.duplicates+=w.duplicates,i.rejected+=w.rejected,i.skipped+=w.skipped,i.rejections.push(...w.rejections)}return i})();d=E;try{return await E}finally{d===E&&(d=null)}}let I;function q(){if(I||typeof document>"u")return;let h=()=>{document.visibilityState==="hidden"&&e()&&a.length&&S(!0).catch(()=>{})};document.addEventListener("visibilitychange",h),I=()=>document.removeEventListener("visibilitychange",h)}return{rememberConfiguration:o,track:p,observe:F,flush:S,reset(){n++,r=void 0,clearTimeout(y),y=void 0,a=[],g=0,d=null},detachVisibility(){I?.(),I=void 0}}}function ve(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}var qe=new Set([...$,"merchandiseId","merchandise"]);function ke(t){let e=ve(t);return{...Object.fromEntries(Object.entries(t).filter(([r])=>!qe.has(r))),...e?{merchandise:e}:{}}}function Ee(t,e,n,r,o){if(o&&r&&(o.scope.projectId!==r.projectId||o.scope.environment!==r.environment))throw new s("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,d=new Set;function y(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}async function g(l={}){o||y();let O=a,F=!1,p=async()=>{if(F||O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let R=o?{scope:{projectId:o.scope.projectId,environment:o.scope.environment},payload:await o.features()}:await m(t,await f(t,"getFeatures"),{});if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");if(r&&(R.scope.projectId!==r.projectId||R.scope.environment!==r.environment))throw new s("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(R.payload.analyticsConfig),R},S=await p(),I=!0,q,h=R=>{try{l.onError?.(R)}catch{}},P=(R,N)=>{try{let v=ve(N);n.observe({...R,...v?{merchandise:v}:{}})}catch(v){h(v)}},E=ae({assertUsable:o?.assertFeatures,scope:S.scope,attributes:l.attributes,onError:l.onError,load:async()=>I?(I=!1,S.payload):(await p()).payload,evaluateRemote:async R=>{if(O!==a)throw new s("IDENTITY_CHANGED","Feature identity changed");let N=await f(t,"evaluateFeatures"),v=await m(t,N,{...R,attributes:ke(R.attributes)});if(v.scope.projectId!==S.scope.projectId||v.scope.environment!==S.scope.environment)throw new s("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:v.generation,evaluatedAt:v.evaluatedAt,expiresAt:v.expiresAt,features:v.features,...v.merchandiseContext?{merchandiseContext:v.merchandiseContext}:{}}},onExperimentViewed:(R,N,v,V)=>P({kind:"experiment_exposure",generation:V,experimentId:R.key,variationId:N.key},v),onFeatureUsage:(R,N,v,V)=>P({kind:"feature_usage",generation:V,feature:R,value:N.value??null,source:N.source,ruleId:N.ruleId,...N.experimentResult?{variationId:N.experimentResult.key}:{}},v)}),i=E.refresh;function c(){clearTimeout(q),!o&&(F||O!==a||!E.expiresAt||(q=setTimeout(()=>{u().catch(h)},Math.min(2147483647,Math.max(1e3,Date.parse(E.expiresAt)-Date.now()))),typeof q=="object"&&"unref"in q&&q.unref()))}async function u(){try{return await i()}finally{c()}}let A=()=>{F||u().catch(h)},w=E.subscribe(c),C=o?.subscribe(()=>{!F&&o.fresh&&u().catch(h)});function D(){F||(F=!0,clearTimeout(q),typeof window<"u"&&window.removeEventListener("focus",A),w(),C?.(),E.reset(),d.delete(D))}d.add(D);try{await E.init(),(l.attributes?.merchandise||l.attributes?.merchandiseId)&&await E.refreshRemote()}catch(R){throw D(),R}return c(),!o&&typeof window<"u"&&window.addEventListener("focus",A),Object.assign(E,{refresh:u,destroy:D})}return{features:g,reset(l){a++,l();for(let O of d)O()}}}function be(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=K.object({funnelId:J.shape.id,funnelVersionId:J.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new s("INVALID_REQUEST","A valid Funnel source is required");let o=Object.freeze(r.data);function a(d){if("customerId"in d)throw new s("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in d&&d.funnelId!==void 0&&d.funnelId!==o.funnelId||"funnelVersionId"in d&&d.funnelVersionId!==void 0&&d.funnelVersionId!==o.funnelVersionId)throw new s("SCOPE_MISMATCH","The original Funnel source cannot change");return{...d,...o}}return{async claimCoupon(d,y=crypto.randomUUID()){let g=await f(t,"grantOffer"),l=await m(t,g,a({couponId:d,requestId:y}));return{offer:l.offer,reason:l.reason}},async resolveOffering(d){d=b(d);let y=await f(t,"resolveOffering"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.check,l.scope),l},async resolvePaywall(d){d=b(d);let y=await f(t,"resolvePaywall"),g=y.request.parse(a(d)),l=await m(t,y,g);return j(g,l.paywall.check,l.scope),l},async previewAttach(d){d=b(d);let y=await f(t,"previewAttach");return m(t,y,a(d))}}}function xt(t){return Ne(t)}function Ne(t){let e=ie(t),n=e.request,r;try{r=ue(t.push,e,t.scope??t.configuration?.scope)}catch(y){throw e.dispose(),y}let o=le(e,()=>{d.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=ge(n,o.isIdentified),d=Ee(n,o.isIdentified,a,t.scope,t.configuration);return{session:e.session,...de(n,r),...Ie(n),...he(n),forFunnel(y){return o.assertActive(),be(n,y)},async features(y={}){return o.assertActive(),d.features(y)},track(y,g,l={}){return a.track(y,g,l)},flush(){return a.flush()},...o.methods}}function Mt(t){if(!B.test(t.customerToken))throw new s("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new s("INVALID_REQUEST","An explicit App and environment scope is required");let e=ce({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),o=M({...t,runToken:r.runToken,initialResponse:r});o.identify(t.customerToken);let a=await o.get();return{...r,...a,controller:o}}}}function Kt(t){if(!t.scope)throw new s("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new s("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,r=0,o=new Set,a=new Map,d=new Map;async function y(p){let S,I=new Promise((q,h)=>{S=setTimeout(()=>h(new s("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(p),I])}finally{clearTimeout(S)}}function g(p){throw p instanceof s&&(p.status===401||p.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear()),p}function l(p,S){if(S!==r)throw new s("IDENTITY_CHANGED","Process was detached during a request");let I=re.parse(p);if(I.scope.projectId!==t.scope.projectId||I.scope.environment!==t.scope.environment)throw new s("SCOPE_MISMATCH","Process response belongs to another App/environment");if(e&&(e.run.id!==I.run.id||e.run.source.versionId!==I.run.source.versionId||e.run.source.id!==I.run.source.id||e.run.runExpiresAt!==I.run.runExpiresAt||e.run.identity.startedAs!==I.run.identity.startedAs||e.run.identity.participantId!==I.run.identity.participantId||e.run.identity.binding&&I.run.identity.binding&&e.run.identity.binding.id!==I.run.identity.binding.id))throw new s("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!e||I.run.revision>=e.run.revision){if(e?.run.identity.binding&&!I.run.identity.binding)throw new s("INVALID_RESPONSE","The process lost its Customer binding");e=I;for(let A of o)z(A,I.run);I.run.instruction?.type==="authentication_required"&&z(t.onAuthenticationRequired,I.run)}I.settlement?.accepted!==void 0&&d.set(I.settlement.requestId,I.settlement.accepted);let{identity:q,instruction:h,...P}=I.run,{contract:E,settlement:i,...c}=I,u=i&&(({accepted:A,...w})=>w)(i);return{...c,run:{...P,authenticated:q.binding!==null,instruction:h?.type==="authentication_required"?null:h},...u?{settlement:u}:{}}}let O=p=>(a.has(p)||a.set(p,e?.run.identity.binding?.id??null),a.get(p));async function F(p){let S=r,I=e?.run.identity.binding?.id??null,q=P=>{if(I!==(e?.run.identity.binding?.id??null))throw P;return g(P)};if(p.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new s("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return y(()=>t.adapter.pageExperiments(p.release,p.usedReceiptIds)).catch(q)}let h;if(p.operation==="get"){let{operation:P,customerToken:E,...i}=p;h=await y(()=>t.adapter.get({...i,...i.settlementRequestId?{settlementBindingId:O(i.settlementRequestId)}:{}})).catch(q)}else if(p.operation==="review")h=await y(()=>t.adapter.review(p.receiptId)).catch(q);else{if(p.operation==="start")throw new s("INVALID_REQUEST","Use process.open for entry");{let{customerToken:P,...E}=p;h=await y(()=>t.adapter.command(E,O(E.requestId))).catch(q)}}return l(h,S)}return{get view(){return e?.run??null},get controller(){return n},async open(p){let S=r,I=await y(()=>t.adapter.open(p)).catch(g),q=l(I,S);if(!n){n=M({...t,runToken:I.runToken,initialResponse:q,process:{request:F,binding:O,restore(E){for(let[i,c]of Object.entries(E))a.set(i,c)}}});let h=n,P=h.submit;h.submit=async E=>{try{return await P(E)}catch(i){if(!(i instanceof s)||i.reason!=="IDENTITY_CONTEXT_CHANGED"||E.operation!=="submit"||E.input.type!=="screen"||a.get(E.requestId)!==null)throw i;await h.settle?.(E.requestId),await h.get();let c=h.view;if(d.get(E.requestId)!==!1||!c||c.id!==e?.run.id||c.nodeId!==E.nodeId||c.visit!==E.visit||!e?.run.identity.binding)throw i;return P({...E,requestId:crypto.randomUUID(),revision:c.revision})}}}await n.get();for(let h of n.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(e?.run.identity.binding?.id??null)&&await n.settle?.(h.requestId);return{run:e.run,controller:n}},async syncIdentity(){let p=r;l(await y(()=>t.adapter.syncIdentity()).catch(g),p),await n?.get();for(let S of n?.pendingCommands??[])a.has(S.requestId)&&a.get(S.requestId)!==(e?.run.identity.binding?.id??null)&&await n?.settle?.(S.requestId);return e.run},async detach(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),await y(()=>t.adapter.detach())},forProcess(p){if(!e?.run.identity.binding)throw new s("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:p}},subscribe(p){return o.add(p),()=>{o.delete(p)}},destroy(){r++,n?.reset(),n=void 0,e=null,a.clear(),d.clear(),o.clear()}}}export{xt as a,Ne as b,Mt as c,Kt as d};
@@ -0,0 +1 @@
1
+ import{b as Re}from"./chunk-KPDHY76A.js";import{a as G}from"./chunk-MSK3VZ3A.js";import{A as _e,E as W,G as ke,d as Pe,f as x,k as Se,v as Ee,w as be,y as Oe}from"./chunk-2FE4FTPH.js";import{a as we,b as ge,c as ye}from"./chunk-EUTWY7A2.js";import{$ as U}from"./chunk-TAFALMQN.js";import{a as X}from"./chunk-3NCMYTNG.js";import{f as Z}from"./chunk-V7PFLFHE.js";import{b as ve}from"./chunk-56BYGPQ6.js";import{b as $}from"./chunk-TJGIT5CU.js";import{a as l}from"./chunk-OX7PA64E.js";import{b as Ce}from"./chunk-EM3MGDPG.js";import{b as n}from"./chunk-VF6QMMEA.js";import{a as ue}from"./chunk-DSPLGTQI.js";var g=U.options,Ve=n.discriminatedUnion("operation",[g[1].omit({customerToken:!0}),g[2].omit({customerToken:!0}),g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0}),g[8].omit({customerToken:!0}),Se.omit({customerToken:!0})]),ce=n.strictObject({receiptId:n.uuid(),operationId:n.uuid()}),We=n.discriminatedUnion("operation",[n.strictObject({operation:n.literal("find_purchase")}),n.strictObject({operation:n.literal("recover_start"),intent:n.enum(["lookup","resume"]),start:n.strictObject({requestId:g[0].shape.requestId,funnelId:g[0].shape.funnelId,locale:g[0].shape.locale,parameters:g[0].shape.parameters})}),n.strictObject({operation:n.literal("recover_run"),runId:n.uuid(),funnelId:n.uuid()}),n.strictObject({operation:n.literal("recover_purchase"),runId:n.uuid(),funnelId:n.uuid(),purchase:ce}),n.strictObject({operation:n.literal("terminate_checkout"),runId:n.uuid(),funnelId:n.uuid(),purchase:ce}),n.strictObject({operation:n.literal("settle_command"),runId:n.uuid(),funnelId:n.uuid(),requestId:n.uuid(),command:n.discriminatedUnion("operation",[g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0})]).optional()}).refine(a=>!a.command||a.requestId===a.command.requestId),n.strictObject({operation:n.literal("run_command"),runId:n.uuid(),funnelId:n.uuid(),command:Ve})]),ee=n.strictObject({runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),startRequestId:n.uuid(),runExpiresAt:n.iso.datetime({offset:!0}),status:x.shape.run.shape.status}),N={scope:$,customerId:n.uuid()},Fe=n.discriminatedUnion("outcome",[n.strictObject({...N,outcome:n.literal("unknown"),target:n.null(),view:n.null(),access:n.null()}),n.strictObject({...N,outcome:n.literal("resolved"),target:ee,view:x.shape.run.nullable(),access:n.discriminatedUnion("type",[n.strictObject({type:n.literal("customer")}),n.strictObject({type:n.literal("operation_only"),cause:n.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((a,d)=>{a.outcome==="resolved"&&(a.access.type==="customer"!=(a.view!==null)||a.view&&(a.view.id!==a.target.runId||a.view.source.id!==a.target.funnelId||a.view.source.versionId!==a.target.versionId||a.view.status!==a.target.status||a.view.runExpiresAt!==a.target.runExpiresAt||a.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),qe=n.strictObject({...N,target:ee,view:x.shape.run.nullable(),settlement:n.strictObject({requestId:n.uuid(),state:n.enum(["pending","unknown","settled"]),acceptance:n.enum(["accepted","not_accepted","unknown"]),receiptPhase:n.enum(["accepted","processing","done"]).nullable(),basis:n.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:n.uuid().nullable(),operationId:n.uuid().nullable()}),purchase:x.shape.purchase.unwrap().nullable()}).superRefine((a,d)=>{let p=a.settlement;(p.acceptance==="accepted"!=(p.receiptPhase!==null)||p.acceptance==="accepted"&&p.basis!=="receipt"||p.acceptance==="unknown"&&(p.state!=="unknown"||p.basis!=="none")||p.acceptance!=="accepted"&&(p.operationId!==null||p.receiptId!==null)||p.acceptance==="not_accepted"&&(p.state!=="settled"||!["run_terminal","position_advanced"].includes(p.basis))||a.purchase&&(a.purchase.receiptId!==p.receiptId||a.purchase.operation&&a.purchase.operation.operationId!==p.operationId||a.purchase.quote&&a.purchase.quote.operationId!==p.operationId)||a.view&&(a.view.id!==a.target.runId||a.view.source.id!==a.target.funnelId||a.view.source.versionId!==a.target.versionId||a.view.status!==a.target.status||a.view.runExpiresAt!==a.target.runExpiresAt||a.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Ae=n.strictObject({...N,target:ee,purchase:x.shape.purchase.unwrap()}).superRefine((a,d)=>{(!a.purchase.operation||typeof a.purchase.canReselect!="boolean"||a.purchase.quote&&a.purchase.quote.operationId!==a.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})}),Ne=n.discriminatedUnion("outcome",[n.strictObject({...N,outcome:n.literal("none")}),n.strictObject({...N,outcome:n.literal("blocked")}),n.strictObject({...N,outcome:n.literal("found"),target:ee,start:n.strictObject({locale:g[0].shape.locale,parameters:g[0].shape.parameters}),purchase:ce})]);var Ge=U.options[0].refine(a=>!a.customer&&!a.customerData),Me=n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),terminal:n.enum(["complete","native"]).nullable()}),je=n.strictObject({schemaVersion:n.literal(1),baseUrl:n.url(),scope:$,customerId:n.uuid(),sessionId:n.uuid(),start:Ge,allowed:n.array(n.enum(["merchant","record_only","indiana","native"])),run:n.strictObject({id:n.uuid(),versionId:n.uuid(),status:Pe.shape.status,revision:n.number().int().nonnegative(),runExpiresAt:n.iso.datetime({offset:!0}).optional()}).optional(),purchases:n.array(Me).max(100),operationCommand:n.strictObject({operationId:n.uuid(),intent:n.literal("confirm")}).optional(),journal:n.strictObject({revision:n.number().int().nonnegative(),entry:Ee.nullable()})});function Te(a){return Oe({...a,namespace:"purchases",identity:[a.scope.projectId,a.scope.environment,a.customerId]})}function Ue(a){let d=new URL(a.baseUrl??Ce).href,p=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function S(){a.assertCurrent();try{let C=await a.storage.read();if(a.assertCurrent(),!Number.isSafeInteger(C.revision)||C.revision<0)throw p();let u=C.entry===null?null:je.parse(C.entry);if(u&&(u.baseUrl!==d||u.customerId!==a.customerId||u.scope.projectId!==a.scope.projectId||u.scope.environment!==a.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(u?.journal.entry&&(u.journal.entry.scope.projectId!==u.scope.projectId||u.journal.entry.scope.environment!==u.scope.environment||u.journal.entry.funnelId!==u.start.funnelId||u.journal.entry.runId!==u.run?.id||u.journal.entry.versionId!==u.run?.versionId)||u?.operationCommand&&!u.purchases.some(E=>E.operationId===u.operationCommand?.operationId))throw p();return{revision:C.revision,entry:u}}catch(C){throw C instanceof l?C:p()}}async function M(C){for(let u=0;u<8;u++){let E=await S(),O=C(structuredClone(E.entry));if(JSON.stringify(O)===JSON.stringify(E.entry))return O;O&&je.parse(O),a.assertCurrent();let R;try{R=await a.storage.write(E.revision,O)}catch{throw p()}if(a.assertCurrent(),R!==null){if(!Number.isSafeInteger(R)||R<=E.revision)throw p();return O}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:S,update:M,baseUrl:d}}var ze=5*6e4;function Be(a,d){let p=a.purchases.find(S=>S.type==="checkout");if(!a.actions.includes("continue_checkout")||p?.type!=="checkout"||d!==void 0&&p.operationId!==d)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return p.checkoutUrl}function Ct(a){let d={...a,scope:{...a.scope},executionPolicy:structuredClone(a.executionPolicy)},p=d.session.snapshot();if(!p)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:S,sessionId:M}=p,C=!1,u=null,E,O=null,R=!1,q,z,B,k={mode:"idle",status:"idle",actions:["start"],purchases:[]},y=new Map,j=new Map,le=new AbortController,Q=new Set,D=ve(d),de=Re(D.request);function H(e){return{code:e instanceof l?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof l&&e.status!==void 0?{status:e.status}:{}}}function w(){if(C||d.session.snapshot()?.customerId!==S)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let f=Ue({...d,customerId:S,assertCurrent:w,storage:d.storage??Te({baseUrl:d.baseUrl,scope:d.scope,customerId:S})}),xe=d.session.subscribeIdentity(pe);function pe(){C||(C=!0,clearTimeout(B),le.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),xe(),u?.reset(),u=null,O=null,D.dispose(),Q.clear(),y.clear(),j.clear())}function P(e){w();let t=JSON.stringify(e)!==JSON.stringify(k);k=e,clearTimeout(B),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(B=setTimeout(()=>{T().catch(()=>{})},5e3)),t&&ue(d.onRecovery,structuredClone(e));for(let r of t?Q:[]){if(C)break;ue(r,structuredClone(e))}return structuredClone(e)}function I(e){if(w(),!e||e.start.requestId!==E)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function b(e){let t=[...e.purchases],r=e.journal.entry?.purchase;return r&&!t.some(o=>o.operationId===r.operationId)&&t.push({receiptId:r.receiptId,operationId:r.operationId,terminal:null}),t}function A(e){return e.run&&!["running","waiting"].includes(e.run.status)&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&b(e).every(t=>t.terminal!==null)}function _(e,t){let r=e.journal.entry?.command??e.journal.entry?.closeCommand,o=b(e).map(v=>{let se=y.get(v.operationId);return v.terminal&&!se?{type:v.terminal,operationId:v.operationId}:X({quote:se?.quote??null,operation:se??null,requestId:r?.requestId??null,pending:!1,destroyed:!1,canReselect:j.get(v.operationId)===!0})}),c=o.filter(v=>!["complete","native"].includes(v.type)),i=c[0],s=c.length===1&&i?.operationId?y.get(i.operationId):void 0;if(s&&(i?.type==="checkout"||i?.type==="cancel"))try{W({allowed:e.allowed.filter(v=>d.executionPolicy.allowed.includes(v))},s.quote)}catch(v){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:o,error:H(v)}}let m;if(t==="operation"&&!r&&i?.type==="cancel"&&s?.quote&&!s.problem&&!s.confirmedAt)try{W({allowed:e.allowed.filter(v=>d.executionPolicy.allowed.includes(v))},s.quote),Date.parse(s.quote.expiresAt)>Date.now()&&(m={operationId:s.operationId,quote:s.quote})}catch{}let h=o.length>0&&c.length===0,V=A(e)||t==="operation"&&h&&!r&&!e.operationCommand?"complete":i?.type==="checkout"?"checkout":i?.type==="fulfillment"?"fulfillment":i?.type==="recording"?"recording":r||e.operationCommand||i&&i.type!=="cancel"||t==="operation"&&!m?"waiting_result":"ready";return{mode:t,status:V,purchases:o,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...A(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...c.length===1&&i?.type==="checkout"?["continue_checkout"]:[]]}}function te(e){let t=X({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&j.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function ne(e){if(!e.operation)return;let t={...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}};if(t.merchantExecution&&t.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let r=Z(y.get(t.operationId)??null,t);y.set(t.operationId,r),r===t&&j.set(t.operationId,e.canReselect===!0)}async function De(e){w();for(let r of[e.purchase,e.run.paywall])r&&ne(r);let t=await f.update(r=>{if(I(r),r.run&&(r.run.id!==e.run.id||r.run.versionId!==e.run.source.versionId))throw new l("SCOPE_MISMATCH","The original purchase Run changed");let o=b(r);for(let c of[e.purchase,e.run.paywall]){let i=c?.operation?.operationId??c?.quote?.operationId;if(!c||!i)continue;let s=o.find(h=>h.operationId===i);if(s&&s.receiptId!==c.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let m=te(y.get(i));s?s.terminal??=m:o.push({receiptId:c.receiptId,operationId:i,terminal:m})}return{...r,purchases:o,run:r.run&&(r.run.revision>e.run.revision||!["running","waiting"].includes(r.run.status)&&["running","waiting"].includes(e.run.status))?r.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});I(t),t.run&&!["running","waiting"].includes(t.run.status)&&b(t).some(r=>!r.terminal)&&(t=await L(t,!t.journal.entry?.command&&!t.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(r=>!!r)))),I(t),P(_(t,"run"))}function He(){return{async read(){let{entry:e}=await f.read();return I(e),structuredClone(e.journal)},async write(e,t){let r=null;return await f.update(o=>{if(I(o),o.operationCommand&&t?.command&&t.command.operation!=="close")throw new l("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return r=null,o.journal.revision!==e?o:(r=e+1,{...o,journal:{revision:r,entry:t}})}),r}}}async function L(e,t=!1,r=new Set){I(e);let o=b(e);for(let i of o){if(i.terminal)continue;let s=r.has(i.operationId)?y.get(i.operationId):void 0;if(s??=await oe(e,i),w(),s.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(s.merchantExecution&&s.merchantExecution.customerId!==S)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&X({quote:s.quote??null,operation:s,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){if({operation:s}=await de.attach({operationId:i.operationId,intent:"cancel"}),w(),s.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");s=await oe(e,i)}y.set(i.operationId,Z(y.get(i.operationId)??null,s))}let c=await f.update(i=>{I(i);let s=i.operationCommand&&y.get(i.operationCommand.operationId);return{...i,...s&&(s.confirmedAt||s.merchantExecution||s.status!=="pending")?{operationCommand:void 0}:{},purchases:b(i).map(m=>({...m,terminal:m.terminal??te(y.get(m.operationId))}))}});return I(c),c}async function Y(e){w();let t=await D.request("funnels",e);return w(),t}async function Le(){let e=G(Ne,await Y({operation:"find_purchase"}));if(e.customerId!==S||e.scope.projectId!==d.scope.projectId||e.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(e.outcome!=="found")return e.outcome;let{target:t,purchase:r}=e;return await f.update(o=>o&&!A(o)?o:{schemaVersion:1,baseUrl:f.baseUrl,scope:d.scope,customerId:S,sessionId:M,start:{operation:"start",requestId:t.startRequestId,funnelId:t.funnelId,...e.start},allowed:[...d.executionPolicy.allowed],run:{id:t.runId,versionId:t.versionId,status:t.status,revision:0,runExpiresAt:t.runExpiresAt},purchases:[{...r,terminal:null}],journal:{revision:0,entry:null}}),"found"}let J;function re(e){let t=J;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<ze))return t.job;let r={at:Date.now(),job:Le().then(o=>(r.outcome=o,r.at=Date.now(),o),o=>{throw J===r&&(J=void 0),o})};return J=r,r.job}async function oe(e,t,r="recover_purchase"){let o=G(Ae,await Y({operation:r,runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId}}));if(ae(e,o),o.purchase.receiptId!==t.receiptId||o.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return ne(o.purchase),y.get(t.operationId)}async function me(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let r=G(qe,await Y({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(ae(e,r),r.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");r.purchase&&ne(r.purchase);let o=await f.update(c=>{I(c);let i=b(c),{receiptId:s,operationId:m}=r.settlement;if(s&&m){let V=i.find(v=>v.operationId===m);if(V&&V.receiptId!==s)throw new l("INVALID_RESPONSE","Original Receipt changed");V||i.push({receiptId:s,operationId:m,terminal:te(y.get(m))})}let h=r.settlement.state==="settled"?be(c.journal.entry,t.requestId):c.journal.entry;return{...c,purchases:i,journal:h===c.journal.entry?c.journal:{revision:c.journal.revision+1,entry:h}}});I(o),e=o}return e}function ae(e,t){if(t.customerId!==S||t.scope.projectId!==d.scope.projectId||t.scope.environment!==d.scope.environment||t.target.funnelId!==e.start.funnelId||t.target.startRequestId!==e.start.requestId||e.run&&(t.target.runId!==e.run.id||t.target.versionId!==e.run.versionId))throw new l("SCOPE_MISMATCH","The original recovery binding changed")}async function ie(e,t){if(I(e),e.run&&(e=await me(e)),!b(e).length&&A(e))return P(_(e,"operation"));if(!b(e).length)return P({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:H(t)});R=!0;let r=await L(e);return P(_(r,"operation"))}async function K(e,t=!1,r=!0){if(E=e.start.requestId,O=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!u){let o=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:t?"resume":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},c;try{c=await Y(o)}catch(h){if(!e.run&&h instanceof l&&(h.status===void 0||h.status>=500))return P({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:k.purchases,error:H(h)});throw h}let i=G(Fe,c);if(i.customerId!==S||i.scope.projectId!==d.scope.projectId||i.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(i.outcome==="unknown")return P({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:k.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}});ae(e,i);let s=await f.update(h=>(I(h),{...h,run:{id:i.target.runId,versionId:i.target.versionId,status:i.target.status,revision:i.view?.revision??h.run?.revision??0,runExpiresAt:i.target.runExpiresAt}}));if(I(s),e=s,i.access.type==="operation_only")return ie(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await me(e);let m=i.view;if(m.locale!==e.start.locale||!_e(m.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");u=ke({...d,customerRun:{runId:i.target.runId,customerId:S,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(h=>d.executionPolicy.allowed.includes(h))},funnelCommandStorage:He(),onAcceptedResponse:De},{scope:i.scope,run:m})}try{await u.get(),u.view?.pendingRequest?.requestId===e.start.requestId&&!u.pendingCommands?.length&&await u.resume(u.view.pendingRequest.requestId);for(let c of u.pendingCommands??[])c.operation!=="close"&&await u.settle?.(c.requestId);u.pendingCommands?.length&&await u.retry(),w();let o=(await f.read()).entry;return I(o),P(_(o,"run"))}catch(o){if(w(),r&&o instanceof l&&(o.status===401||o.status===409&&o.reason==="STATE_CHANGED")){u.reset(),u=null;let c=(await f.read()).entry;return I(c),K(c,!1,!1)}throw o}}function F(e,t="read",r){if(w(),q)return t==="read"||t===z?q:q.then(()=>F(e,t,r),()=>F(e,t,r));clearTimeout(B);let o=e().catch(c=>{throw!C&&!r?.(c)&&P({mode:"blocked",status:"blocked",actions:["refresh"],purchases:k.purchases,error:H(c)}),c});return q=o,z=t,o.then(()=>{q===o&&(q=void 0,z=void 0)},()=>{q===o&&(q=void 0,z=void 0)}),o}function T(){return F(async()=>{let{entry:e}=await f.read();if(!e||A(e)){if(await re(!1)==="blocked")return fe();({entry:e}=await f.read())}return e?(E&&e.start.requestId!==E&&(u?.reset(),u=null,y.clear(),j.clear(),R=!1),R&&E===e.start.requestId?ie(e,k.error):K(e)):P({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function fe(){return P({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:H(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function he(){let e=await T();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:F(async()=>{let t=(await f.read()).entry;if(I(t),!R){if(!u?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let s=u.view.paywall.operation;if(s?.confirmedAt||s?.merchantExecution||s&&s.status!=="pending")return P(_(t,"run"));if(u.pendingCommands?.length)await u.retry();else{let h=u.view;await u.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:h.nodeId,visit:h.visit,revision:h.revision,input:{type:"paywall_confirm",operationId:h.paywall.quote.operationId}})}let m=(await f.read()).entry;return I(m),P(_(m,"run"))}let r=t.operationCommand?.operationId??k.confirmation?.operationId,o=r&&y.get(r);if(!r||!o||t.journal.entry?.command||t.journal.entry?.closeCommand)throw new l("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");W({allowed:t.allowed.filter(s=>d.executionPolicy.allowed.includes(s))},o.quote),await f.update(s=>{if(I(s),s.journal.entry?.command||s.journal.entry?.closeCommand||s.operationCommand&&s.operationCommand.operationId!==r)throw new l("PURCHASE_PENDING","Another original command is pending");return{...s,operationCommand:{operationId:r,intent:"confirm"}}});let c=await de.attach({operationId:r,intent:"confirm"});if(w(),c.operation.operationId!==r)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");y.set(r,Z(o,c.operation));let i=(await f.read()).entry;return I(i),P(_(await L(i,!1,new Set([r])),"operation"))},"confirm")}async function Ie(){w();let{entry:e}=await f.read();return e?A(e)?"finished":"pending":"none"}return{get controller(){return u},get recovery(){return structuredClone(k)},get attempt(){return w(),structuredClone(O)},get identitySignal(){return le.signal},retained:Ie,async findPurchase(){let e=await Ie();if(e==="pending")return e;let t=await re(!0);return w(),t==="none"?e:t},async readPaywall(e){w();let t=we(e),[r,{readPaywallContent:o},{validateResourceCheck:c}]=await Promise.all([ge(D.request,"resolvePaywall"),import("./paywall-content-YQAVSO2T.js"),import("./check-response-GZZRWBEA.js")]);w();let i=r.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),s=await ye(D.request,r,i);c(i,s.paywall.check,s.scope);let m=await o(d,s.paywall);if(w(),t.paywallVersionId?m.id!==t.paywallVersionId:m.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return m},start(e){let t=U.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(t.operation!=="start"||t.customer||t.customerData)throw new l("INVALID_REQUEST","A Customer-owned Funnel start is required");return F(async()=>{let r=(await f.read()).entry;if((!r||A(r))&&await re(!0)==="blocked")return fe();let o=await f.update(c=>{if(c&&!A(c)){if(c.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return c}return{schemaVersion:1,baseUrl:f.baseUrl,scope:d.scope,customerId:S,sessionId:M,start:t,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!o)throw new l("PURCHASE_STORAGE_INVALID","Original start was not retained");return E!==o.start.requestId&&(u?.reset(),u=null,y.clear(),j.clear(),R=!1),R?ie(o,k.error):K(o,!0)},`start:${t.funnelId}`)},refresh:T,confirm:he,retry:()=>R?he():F(async()=>{let{entry:e}=await f.read();return e?K(e,!0):P({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return u?.view?F(async()=>{if(!u?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(u.pendingCommands?.find(r=>r.operation==="close"))await u.retry();else if(["running","waiting"].includes(u.view.status)){let r=u.view;await u.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:r.nodeId,visit:r.visit,revision:r.revision})}let t=(await f.read()).entry;return I(t),P(_(t,"run"))},"close"):T()},async continueCheckout(e,t){let r=t?await F(async()=>{let{entry:o}=await f.read();if(I(o),!o.run||!b(o).some(i=>i.operationId===t&&!i.terminal))throw new l("PURCHASE_PENDING","The original Checkout changed");let c=await L(o);return P(_(c,R?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await T();w(),await e(Be(r,t))},async terminateCheckout(e){let t=await T();if(!t.purchases.find(o=>o.type==="checkout"&&o.operationId===e)||!t.actions.includes("continue_checkout"))throw new l("PURCHASE_PENDING","The original Checkout has changed");return F(async()=>{let{entry:o}=await f.read();I(o);let c=b(o).find(s=>s.operationId===e&&!s.terminal);if(!c||!o.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await oe(o,c,"terminate_checkout");let i=await L(o,!1,new Set([e]));return P(_(i,R?"operation":"run"))},`terminate:${e}`,o=>o instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(o.code))},subscribe(e){return Q.add(e),()=>{Q.delete(e)}},destroy:pe}}export{Te as a,Be as b,Ct as c};
@@ -0,0 +1 @@
1
+ import{d as f}from"./chunk-XUGEOELU.js";import{a as x}from"./chunk-OX7PA64E.js";function P(e,t,o,a,n){let{presentation:i,screen:s}=o,b=Object.entries(o.buttons??{}).filter(([,p])=>p.type==="close").map(([p])=>p),c=e.ownerDocument.defaultView,l=s.pages.find(p=>p.id===s.initialPageId)?.theme??s.theme,w={background:s.theme.background,text:s.theme.text};t.inert=!0,t.style.cssText="width:100%;min-width:0;overflow:hidden;visibility:hidden";let u=!1,d,g=p=>{c&&d?.resizeViewport(Math.max(1,c.innerHeight-(p==="modal"?32:0)),c.innerWidth)},r=i.type==="inline"?void 0:f(e,{...s,presentation:i,theme:w},g);return r?.latch(),c&&r?.responsive&&r.setContentHeight(c.innerHeight-(r.type==="modal"?32:0)),e.style.background=l.background,e.style.color=l.text,r?(i.type==="fullscreen"||i.type==="sheet")&&(e.style.position="fixed"):e.style.position="relative",import("./screen-renderer-R5GH7XLV.js").then(({mountScreenPreview:p})=>{u||(d=p(t,{mode:"live",skeleton:!0,closeActions:b,hostPresentation:()=>r?.type??i.type,reportContentHeight:r?.responsive,onResize(k){if(!c||!r?.responsive)return;let $=r.type==="modal"?32:0,m=Math.min(k,Math.max(0,c.innerHeight-$));t.style.height=`${m}px`,r.setContentHeight(m)},onRendered:n,onError(){d&&(d.destroy(),d=void 0)}}),r?.responsive&&g(r.type),d.update({...s,presentation:i},a,{serverInput:{bindings:[],answers:{}}}))}).catch(()=>{d?.destroy(),d=void 0}),()=>{u=!0,d?.destroy(),r?.destroy()}}var T={none:0,sm:4,md:8,lg:14,full:9999},z={system:"system-ui,sans-serif",serif:"Georgia,serif",rounded:"ui-rounded,system-ui,sans-serif",mono:"ui-monospace,monospace"},E={primary:"#172033",background:"#FFFFFF",text:"#172033",radius:"md",font:"system"};function y(e){let[t,o,a]=[1,3,5].map(n=>{let i=Number.parseInt(e.slice(n,n+2),16)/255;return i<=.03928?i/12.92:((i+.055)/1.055)**2.4});return .2126*t+.7152*o+.0722*a}function H(e,t=!0){let o=y(e.primary),a=(o+.05)/.05>1.05/(o+.05)?"#111318":"#FFFFFF",n=`color-mix(in srgb, ${e.text} 22%, ${e.background})`,i=`${T[e.radius]}px`,s=`appearance:none;margin:0;min-height:44px;padding:10px 18px;border:0;border-radius:${i};font:inherit;font-size:15px;font-weight:600;line-height:1.25;cursor:pointer;touch-action:manipulation`;return{root:`width:100%;box-sizing:border-box;${t?`background:${e.background};`:""}color:${e.text};font:14px/1.5 ${z[e.font]}`,controls:"display:flex;gap:12px;padding:0 20px 12px;align-items:center;flex-wrap:wrap",pinned:`position:sticky;bottom:0;z-index:1;box-sizing:border-box;padding-top:12px;background:${e.background};border-top:1px solid ${n}`,bar:`display:flex;gap:8px;padding:12px 16px;align-items:center;flex-wrap:wrap;border-top:1px solid ${n}`,message:"flex:1 1 200px;min-width:0;margin:0;font-size:13px",status:"margin:0;font-size:13px;opacity:.72",alert:`flex:1 1 200px;min-width:0;margin:0;font-size:13px;font-weight:500;color:${y(e.background)>.4?"#B42318":"#FDA29B"}`,panel:`flex:1 0 100%;box-sizing:border-box;display:flex;flex-direction:column;gap:8px;padding:16px;border:1px solid ${n};border-radius:${i}`,summary:"margin:0;font-size:15px;font-weight:600",terms:"display:flex;flex-direction:column;gap:4px;font-size:13px;opacity:.72",actions:"display:flex;gap:8px;flex-wrap:wrap;margin-top:4px",primary:`${s};background:${e.primary};color:${a}`,secondary:`${s};background:transparent;color:${e.text};box-shadow:inset 0 0 0 1px ${n}`,link:`${s};background:transparent;color:${e.text};opacity:.72;font-weight:500`,stage:"display:flex;justify-content:center;padding:24px 20px",history:"display:flex;flex-direction:column;gap:12px;padding:20px",historyTitle:"margin:0;padding-inline-end:40px;font-size:17px;font-weight:600;line-height:1.3",historyNote:"margin:0;font-size:13px;opacity:.72",historyPages:"display:flex;gap:8px;flex-wrap:wrap;margin:0;padding:0;list-style:none",historyPage:`border:1px solid ${n};border-radius:${i};overflow:hidden`,historyRecords:`display:flex;flex-direction:column;gap:4px;margin:0;padding:12px 0 0;list-style:none;font-size:13px;border-top:1px solid ${n}`,focus:e.text}}function S(e){e.style.opacity=e.disabled?".55":"",e.style.cursor=e.disabled?"not-allowed":"pointer"}function R(e,t){e.addEventListener("focus",()=>{let o=!0;try{o=e.matches(":focus-visible")}catch{}o&&(e.style.outline=`2px solid ${t()}`,e.style.outlineOffset="2px")}),e.addEventListener("blur",()=>{e.style.outline="",e.style.outlineOffset=""})}var h={en:{network:"Connection problem. Check your network and try again.",timeout:"This is taking longer than expected. Try again.",other:"Something went wrong. Try again.",required:"Answer the questions marked * to continue."},zh:{network:"\u7F51\u7EDC\u8FDE\u63A5\u5F02\u5E38\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u540E\u91CD\u8BD5\u3002",timeout:"\u54CD\u5E94\u65F6\u95F4\u8FC7\u957F\uFF0C\u8BF7\u91CD\u8BD5\u3002",other:"\u51FA\u4E86\u70B9\u95EE\u9898\uFF0C\u8BF7\u91CD\u8BD5\u3002",required:"\u8BF7\u5148\u56DE\u7B54\u5E26 * \u7684\u95EE\u9898\u3002"}};function O(e,t){let o=h[t?"zh":"en"],a=e instanceof x?e.code:void 0;return a==="NETWORK_ERROR"?o.network:a==="TIMEOUT"?o.timeout:o.other}function A(e){return h[e?"zh":"en"].required}function C(e,t){return e.filter(({variable:o,required:a})=>{let n=t[o];return a&&(n==null||n===""||Array.isArray(n)&&n.length===0)})}var v={zh:{pending:"\u5904\u7406\u4E2D",complete:"\u5DF2\u5B8C\u6210",cancelled:"\u5DF2\u53D6\u6D88",failed:"\u5931\u8D25",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"},en:{pending:"Processing",complete:"Completed",cancelled:"Cancelled",failed:"Failed",unknown:"Status unconfirmed"}};function I(e,t){return v[t?"zh":"en"][e]}export{P as a,E as b,H as c,S as d,R as e,O as f,A as g,C as h,I as i};