@tinkerlandai/longplay-react-native 0.10.17-rc.1 → 0.10.18-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +2 -2
- package/dist/index.js +2 -2
- package/native-sdk/android/assets/indiana/index.html +16 -16
- package/native-sdk/android/java/ai/tinkerland/indiana/FunnelView.kt +1 -0
- package/native-sdk/android/java/ai/tinkerland/indiana/SDKVersion.kt +1 -1
- package/native-sdk/ios/FunnelView.swift +2 -0
- package/native-sdk/ios/SDKVersion.swift +1 -1
- package/native-sdk/ios/WebView/index.html +16 -16
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var Bo=Object.defineProperty;var Ey=Object.getOwnPropertyDescriptor;var Ry=Object.getOwnPropertyNames;var ky=Object.prototype.hasOwnProperty;var jy=(e,t,n)=>t in e?Bo(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Ty=(e,t)=>{for(var n in t)Bo(e,n,{get:t[n],enumerable:!0})},Ny=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ry(t))!ky.call(e,i)&&i!==n&&Bo(e,i,{get:()=>t[i],enumerable:!(r=Ey(t,i))||r.enumerable});return e};var Dy=e=>Ny(Bo({},"__esModule",{value:!0}),e);var qe=(e,t,n)=>jy(e,typeof t!="symbol"?t+"":t,n);var qv={};Ty(qv,{LongplayError:()=>b,createConfigurationSync:()=>Oy,createFeatureClient:()=>Ss,createFunnelProcess:()=>Cy,createLocalFunnelClient:()=>Py,createLongplayReactNative:()=>Sy});module.exports=Dy(qv);var Vo=require("zod"),Fy=Vo.z.enum(["sandbox","live"]),Fe=Vo.z.object({projectId:Vo.z.string().min(1),environment:Fy}).strict();var Le=require("zod"),Vi=Le.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),Sl=Le.z.enum(["unknown","denied","provisional","granted"]),Il=Le.z.enum(["ios","android"]),Lo=Le.z.strictObject({installationId:Le.z.uuid(),publicKey:Le.z.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:Le.z.iso.datetime({offset:!0}),signature:Le.z.string().regex(/^[A-Za-z0-9_-]{86}$/)}),_s=Le.z.string().regex(/^[a-f0-9]{64}$/),vl=Lo.extend({sequence:Vi,platform:Il,credentialDigest:_s}),wl=Lo.extend({credentialDigest:_s}),Ol=Lo.extend({sequence:Vi,platform:Il}),zo=Lo.extend({sequence:Vi,credentialDigest:_s,connectionId:Le.z.uuid().nullable(),kind:Le.z.enum(["fcm_token","apns_token"]).nullable(),token:Le.z.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:Sl}),Pl=zo,Cl=zo.extend({challenge:Le.z.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),Es=Le.z.strictObject({requested:Le.z.literal(!0),expiresAt:Le.z.iso.datetime({offset:!0})}),Pr=Le.z.strictObject({installationId:Le.z.uuid(),bound:Le.z.boolean(),identitySeq:Vi,bindingGeneration:Vi,addressSeq:Le.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:Le.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:Le.z.uuid().nullable(),addressStatus:Le.z.enum(["active","invalid"]).nullable(),permission:Sl}),Rs=Le.z.strictObject({channel:Le.z.enum(["email","sms","voice","push"]),state:Le.z.enum(["unknown","allowed","denied"]),revision:Le.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:Le.z.iso.datetime({offset:!0}).nullable()}),Vv=Le.z.strictObject({state:Le.z.enum(["allowed","denied"]),revision:Le.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function _l(e,t,n){let r=["indiana_push_v1",e,t.projectId,t.environment,n.installationId,n.publicKey,n.issuedAt];e==="bind"?r.push(n.sequence,n.platform,n.credentialDigest):e==="detach"?r.push(n.sequence,n.platform):e==="read"?r.push(n.credentialDigest):r.push(n.sequence,n.credentialDigest,n.connectionId,n.kind,n.token,n.permission),e==="recovery_confirm"&&r.push(n.challenge);let i=JSON.stringify(r);if([...i].some(a=>a.charCodeAt(0)>127))throw new Error("Push proof fields must be ASCII");return Uint8Array.from(i,a=>a.charCodeAt(0))}var Ot=require("zod"),Gn=Ot.z.enum(["INVALID_PROTOCOL_VERSION","UNSUPPORTED_PROTOCOL_VERSION","PROTOCOL_RETIRED","UNAUTHENTICATED","FORBIDDEN","SCOPE_MISMATCH","INVALID_REQUEST","NOT_FOUND","CONFLICT","PAYLOAD_TOO_LARGE","RATE_LIMITED","SERVICE_UNAVAILABLE","NOT_CONFIGURED","CAPABILITY_UNAVAILABLE","INTERNAL_ERROR"]),zv=Ot.z.enum([...Gn.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),$v=Ot.z.enum([...Gn.options,"stale_revision"]),ks=Ot.z.enum(["fix_request","authenticate","check_permissions","check_scope","resolve_conflict","reload_state","retry_same_request","configure_integration","check_availability","upgrade_sdk","recover_operation","contact_support"]),js=Ot.z.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","IDENTITY_CONTEXT_CHANGED","CUSTOMER_BINDING_CONFLICT","RUN_CONTRACT_MISMATCH","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),Rl={INVALID_PROTOCOL_VERSION:{status:400,recovery:"fix_request"},UNSUPPORTED_PROTOCOL_VERSION:{status:400,recovery:"upgrade_sdk"},PROTOCOL_RETIRED:{status:410,recovery:"upgrade_sdk"},UNAUTHENTICATED:{status:401,recovery:"authenticate"},FORBIDDEN:{status:403,recovery:"check_permissions"},SCOPE_MISMATCH:{status:403,recovery:"check_scope"},INVALID_REQUEST:{status:400,recovery:"fix_request"},NOT_FOUND:{status:404,recovery:"fix_request"},CONFLICT:{status:409,recovery:"resolve_conflict"},PAYLOAD_TOO_LARGE:{status:413,recovery:"fix_request"},RATE_LIMITED:{status:429,recovery:"retry_same_request"},SERVICE_UNAVAILABLE:{status:503,recovery:"retry_same_request"},NOT_CONFIGURED:{status:501,recovery:"configure_integration"},CAPABILITY_UNAVAILABLE:{status:501,recovery:"check_availability"},INTERNAL_ERROR:{status:500,recovery:"recover_operation"}};var El={TIMEOUT:"recover_operation",NETWORK_ERROR:"recover_operation",HTTP_ERROR:"recover_operation",INVALID_RESPONSE:"recover_operation",NOT_IDENTIFIED:"authenticate",INVALID_TOKEN:"authenticate",INVALID_URL:"fix_request",INVALID_TIMEOUT:"fix_request",SERVER_ONLY:"fix_request",PROTOCOL_MISMATCH:"upgrade_sdk",IDENTITY_CHANGED:"reload_state",INVALID_STATE:"reload_state",EVENT_QUEUE_FULL:"retry_same_request",COMMAND_PENDING:"recover_operation",DECISION_PENDING:"recover_operation",DECISION_ACCEPTANCE_UNKNOWN:"recover_operation",RUN_RECONCILIATION_REQUIRED:"recover_operation",DECISION_FAILED:"contact_support",COMMAND_STORAGE_CONFLICT:"resolve_conflict",COMMAND_STORAGE_INVALID:"fix_request",CONFIGURATION_UNAVAILABLE:"check_availability",CONFIGURATION_EXPIRED:"reload_state",CONFIGURATION_CHANGED:"reload_state",CONFIGURATION_DISPOSED:"reload_state",UNSUPPORTED_SCHEMA:"upgrade_sdk",FUNNEL_STOPPED:"check_availability",PAYWALL_UNAVAILABLE:"check_availability",EVALUATION_MODE:"reload_state",SERVER_REQUIRED:"fix_request",STICKY_SAVE_FAILED:"retry_same_request",TRANSITION_LIMIT:"resolve_conflict",PRECONDITION_FAILED:"reload_state",PRODUCT_UNAVAILABLE:"fix_request",PURCHASE_HANDLER_REQUIRED:"fix_request",EVENT_HANDLER_REQUIRED:"fix_request",CLOSED:"fix_request",BRIDGE_UNAVAILABLE:"check_availability",INVALID_CONFIGURATION:"fix_request",NATIVE_OPERATION_FAILED:"contact_support",AI_PRICE_UNAVAILABLE:"fix_request",AI_USAGE_UNAVAILABLE:"recover_operation",AI_PROVIDER_ERROR:"check_availability",AI_BALANCE_REJECTED:"resolve_conflict"};function My(e,t){if(e==="CONFLICT"&&t===425)return{retryable:!0,recovery:"retry_same_request"};if(e==="CONFLICT"&&t===412)return{retryable:!1,recovery:"reload_state"};if(e==="INVALID_SERVER_RESPONSE")return{retryable:!1,recovery:"recover_operation"};if(e==="AMBIGUOUS_AUTHENTICATION")return{retryable:!1,recovery:"fix_request"};if(Object.hasOwn(El,e)){let r=El[e];return{retryable:r==="retry_same_request",recovery:r}}let n=Gn.safeParse(e);return n.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:Rl[n.data].recovery}:{retryable:!1,recovery:"contact_support"}}function kl(e,t){let n=Gn.safeParse(e);if(n.success)return e==="CONFLICT"?[409,412,425].includes(t):e==="SERVICE_UNAVAILABLE"?[408,502,503,504].includes(t):e==="INVALID_REQUEST"?[400,405,415,422].includes(t):e==="NOT_CONFIGURED"?[501,503].includes(t):Rl[n.data].status===t;let r={INVALID_SERVER_RESPONSE:[502],RESPONSE_TOO_LARGE:[502],AMBIGUOUS_AUTHENTICATION:[400],BROWSER_REQUIRED:[403],INVALID_REDIRECT_URI:[403],AUTHORIZATION_UNAVAILABLE:[400],UNREGISTERED_CLIENT:[403],MANAGEMENT_OPERATION_FAILED:[400,422,500]};return Object.hasOwn(r,e)&&(r[e]?.includes(t)??!1)}function qy(e,t=Date.now()){if(e===null)return;let n=e.trim();if(/^\d+$/.test(n)){let i=Number(n);return Number.isSafeInteger(i)?i:void 0}if(!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(n))return;let r=Date.parse(n);return Number.isFinite(r)?Math.max(0,Math.ceil((r-t)/1e3)):void 0}var jl=Ot.z.object({retryable:Ot.z.boolean(),recovery:ks,reason:js.optional(),retryAfterSeconds:Ot.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),Ts=Ot.z.object({requestId:Ot.z.uuid().optional(),error:Ot.z.object({code:Ot.z.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:Ot.z.string(),...jl.partial().shape})}),Gv=Ot.z.object({error:Ts.shape.error.extend({requestId:Ot.z.uuid().optional()})}),Kv=Ot.z.object({error:Ot.z.string(),code:Ot.z.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:Ot.z.uuid(),...jl.shape});function $o(e,t,n={}){let r=My(e,t),i=n.reason==="RESULT_UNKNOWN"?"recover_operation":n.recovery??r.recovery,a=r.retryable&&n.retryable!==!1&&i!=="recover_operation",o=a?qy(n.retryAfter??null):void 0;return{...r,retryable:a,recovery:i,...o===void 0?{}:{retryAfterSeconds:o},...n.reason?{reason:n.reason}:{}}}var Ns="X-Indiana-Protocol",Tl="X-Indiana-SDK-Version";var Ds={current:"0.10"};var Nl=require("zod"),Uy=["USD","EUR","CNY","GBP","JPY","CAD","AUD","NZD","CHF","HKD","SGD","KRW","INR","BRL","MXN","TWD","THB","IDR","MYR","PHP","VND","ZAR","AED","SAR","SEK","NOK","DKK","PLN","CZK","HUF","ILS","TRY","RON"],Ie=Nl.z.enum(Uy);var C=require("zod");var Vt=C.z.string().min(1).max(200),Jt=C.z.iso.datetime({offset:!0}),xt=C.z.number().int().nonnegative().max(1e8),Go=C.z.string().regex(/^[A-Z]{3}$/),By=["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"],Dl=C.z.enum(By),Fl=C.z.strictObject({priceId:C.z.uuid(),productVersionId:C.z.uuid(),productId:Vt,quantity:C.z.number().int().min(1).max(1e6),unitAmountMinor:xt,totalMinor:xt,interval:C.z.enum(["week","month","year","one_off"]),intervalCount:C.z.number().int().min(1).max(52),kind:C.z.enum(["fixed","prepaid","seat"]),tiers:C.z.strictObject({mode:C.z.enum(["graduated","volume"]),tiers:C.z.array(C.z.strictObject({upTo:C.z.number().int().positive().nullable(),unitAmountMinor:xt,flatAmountMinor:xt.optional()})).min(2).max(12)}).nullable()}),Vy=C.z.strictObject({grantId:C.z.uuid(),couponId:C.z.uuid(),amountMinor:xt,terms:C.z.discriminatedUnion("type",[C.z.strictObject({type:C.z.literal("percent"),percentOff:C.z.number().gt(0).max(100)}),C.z.strictObject({type:C.z.literal("amount"),amountOffMinor:xt,currency:Go})]),duration:C.z.discriminatedUnion("type",[C.z.strictObject({type:C.z.literal("once")}),C.z.strictObject({type:C.z.literal("forever")}),C.z.strictObject({type:C.z.literal("repeating"),months:C.z.number().int().min(1).max(36)})])}),Ms={provider:C.z.literal("merchant"),executor:C.z.literal("merchant"),operationId:C.z.uuid(),customerId:C.z.uuid(),configurationRevision:C.z.number().int().nonnegative(),connectionRevision:C.z.number().int().nonnegative(),currency:Go,expiresAt:Jt},Ko=C.z.strictObject({...Ms,type:C.z.literal("purchase"),mode:C.z.enum(["payment","subscription"]),lineItems:C.z.array(Fl).min(1).max(100),catalogAmountMinor:xt,discount:Vy.nullable(),trialPeriodDays:C.z.number().int().min(1).max(730).nullable(),automaticTax:C.z.boolean()}).refine(e=>e.lineItems.reduce((t,n)=>t+n.totalMinor,0)===e.catalogAmountMinor&&(!e.discount||e.discount.amountMinor<=e.catalogAmountMinor)&&new Set(e.lineItems.map(t=>t.priceId)).size===e.lineItems.length,"Purchase lines must retain the original total and unique Price identities"),Ho=C.z.strictObject({...Ms,type:C.z.literal("subscription_change"),subscriptionId:C.z.uuid(),merchantSubscriptionId:Vt,membershipId:C.z.uuid(),subscriptionAction:C.z.enum(["update","cancel","schedule","release"]),supersedesOperationId:C.z.uuid().nullable(),change:C.z.discriminatedUnion("type",[C.z.strictObject({type:C.z.literal("cancel")}),C.z.strictObject({type:C.z.literal("uncancel")}),C.z.strictObject({type:C.z.literal("plan"),productVersionId:C.z.uuid()}),C.z.strictObject({type:C.z.literal("seats"),licenseKey:Vt,quantity:C.z.number().int().nonnegative().max(1e6)}),C.z.strictObject({type:C.z.literal("quantity"),internal_feature_id:C.z.uuid(),quantity:C.z.number().int().nonnegative().max(1e6)}),C.z.strictObject({type:C.z.literal("billing_cycle"),billingCycleAnchor:C.z.union([C.z.literal("now"),C.z.number().int().positive()])})]),timing:C.z.enum(["immediate","renewal"]),effectiveAt:Jt,creditMinor:xt,debitMinor:xt,totalMinor:xt,discountMinor:xt,taxMinor:xt,proration:C.z.enum(["none","create_prorations","always_invoice"]),lineItems:C.z.array(Fl.extend({quantity:C.z.number().int().nonnegative().max(1e6)})).max(100),removePriceIds:C.z.array(C.z.uuid()).max(100)}),Qo=C.z.strictObject({...Ms,type:C.z.literal("refund"),invoiceId:C.z.uuid(),merchantInvoiceId:Vt,amountMinor:xt.refine(e=>e>0),mode:C.z.enum(["full","partial"]),entitlementAction:C.z.enum(["retain","revoke"]),cancelSubscriptions:C.z.array(Vt).max(100)}),Ml=C.z.discriminatedUnion("type",[Ko,Ho,Qo]);var Li=C.z.strictObject({phase:C.z.enum(["execution","payment","fulfillment","recording"]),code:Gn,reason:js.optional(),recovery:ks,retryable:C.z.boolean()}).refine(e=>e.reason!=="RESULT_UNKNOWN"||!e.retryable&&e.recovery==="recover_operation","Unknown financial effects require recovery of the original operation"),Fs={operationId:C.z.uuid(),customerId:C.z.uuid(),merchantExecutionId:Vt,fulfillmentStatus:C.z.enum(["not_started","pending","applied","failed","not_applicable"]),recordingStatus:C.z.enum(["not_ready","pending","accepted","failed"]),updatedAt:Jt,problem:Li.nullable(),pollAfterMs:C.z.number().int().min(1e3).max(6e4).nullable()},Cr=C.z.discriminatedUnion("type",[C.z.strictObject({...Fs,type:C.z.literal("purchase"),merchantOrderId:Vt.nullable(),paymentStatus:C.z.enum(["not_started","pending","succeeded","not_required","failed","expired","unknown"]),checkoutUrl:C.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),checkoutExpiresAt:Jt.nullable()}).refine(e=>!e.checkoutUrl||["not_started","pending"].includes(e.paymentStatus)&&e.checkoutExpiresAt!==null,"Only an unfinished original purchase may expose its checkout"),C.z.strictObject({...Fs,type:C.z.literal("subscription_change"),status:C.z.enum(["pending","scheduled","applied","failed","unknown"]),merchantSubscriptionId:Vt,scheduledFor:Jt.nullable()}).refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"A scheduled change retains its future effective time"),C.z.strictObject({...Fs,type:C.z.literal("refund"),status:C.z.enum(["pending","succeeded","failed","unknown"]),merchantRefundId:Vt.nullable()}).refine(e=>e.status!=="succeeded"||e.merchantRefundId!==null,"A successful refund retains its original merchant identity")]),ql=C.z.discriminatedUnion("lookup",[C.z.strictObject({lookup:C.z.literal("found"),operationId:C.z.uuid(),customerId:C.z.uuid(),execution:Cr,readAt:Jt}),C.z.strictObject({lookup:C.z.literal("not_received"),operationId:C.z.uuid(),customerId:C.z.uuid(),execution:C.z.null(),readAt:Jt})]).refine(e=>!e.execution||e.execution.operationId===e.operationId&&e.execution.customerId===e.customerId,"Lookup must retain the original Customer and operation"),qs=C.z.strictObject({merchantSubscriptionId:Vt,revision:C.z.number().int().positive(),status:C.z.enum(["incomplete","trialing","active","past_due","canceled","unpaid","paused","incomplete_expired"]),periodStartsAt:Jt,periodEndsAt:Jt,cancelAtPeriodEnd:C.z.boolean(),hasDiscounts:C.z.boolean(),items:C.z.array(C.z.strictObject({merchantItemId:Vt,priceId:C.z.uuid(),quantity:C.z.number().int().positive().max(1e6)})).min(1).max(100)}).refine(e=>Date.parse(e.periodEndsAt)>Date.parse(e.periodStartsAt)&&new Set(e.items.map(t=>t.priceId)).size===e.items.length,"Subscription periods and Price identities must be unambiguous"),Us=C.z.strictObject({merchantInvoiceId:Vt,currency:Go,subtotalMinor:xt,discountMinor:xt,taxMinor:xt,totalMinor:xt,paidMinor:xt,periodStartsAt:Jt.nullable(),periodEndsAt:Jt.nullable(),lines:C.z.array(C.z.strictObject({merchantLineId:Vt,priceId:C.z.uuid(),quantity:C.z.number().int().nonnegative().max(1e6),subtotalMinor:C.z.number().int().min(-1e8).max(1e8),discountMinor:xt,taxMinor:xt,totalMinor:C.z.number().int().min(-1e8).max(2e8),periodStartsAt:Jt.nullable(),periodEndsAt:Jt.nullable()}).refine(e=>e.subtotalMinor-e.discountMinor+e.taxMinor===e.totalMinor&&(e.subtotalMinor<0?e.discountMinor===0&&e.taxMinor===0:e.discountMinor<=e.subtotalMinor),"Invoice line amounts must retain the complete debit or credit")).min(1).max(100)}).refine(e=>e.subtotalMinor-e.discountMinor+e.taxMinor===e.totalMinor&&e.discountMinor<=e.subtotalMinor&&e.paidMinor===e.totalMinor&&new Set(e.lines.map(t=>t.merchantLineId)).size===e.lines.length&&e.lines.reduce((t,n)=>t+n.subtotalMinor,0)===e.subtotalMinor&&e.lines.reduce((t,n)=>t+n.discountMinor,0)===e.discountMinor&&e.lines.reduce((t,n)=>t+n.taxMinor,0)===e.taxMinor&&e.lines.reduce((t,n)=>t+n.totalMinor,0)===e.totalMinor,"A paid Invoice retains the complete financial amounts"),Zt={eventId:C.z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),customerId:C.z.uuid(),occurredAt:Jt},Ul=C.z.enum(["purchase.completed","purchase.closed","subscription.observed","subscription.change.completed","invoice.paid","refund.updated"]),Ly=C.z.strictObject({...Zt,type:C.z.literal("purchase.completed"),operationId:C.z.uuid(),merchantOrderId:Vt,paymentStatus:C.z.enum(["paid","trialing","no_payment_required"]),invoice:Us.nullable(),subscription:qs.nullable()}),zy=C.z.strictObject({...Zt,type:C.z.literal("purchase.closed"),operationId:C.z.uuid(),status:C.z.enum(["failed","expired","canceled"])}),$y=C.z.strictObject({...Zt,type:C.z.literal("subscription.observed"),operationId:C.z.uuid().nullable(),subscription:qs}),Gy=C.z.strictObject({...Zt,type:C.z.literal("subscription.change.completed"),operationId:C.z.uuid(),status:C.z.enum(["scheduled","applied"]),scheduledFor:Jt.nullable(),subscription:qs,invoice:Us.nullable()}),Ky=C.z.strictObject({...Zt,type:C.z.literal("invoice.paid"),merchantSubscriptionId:Vt.nullable(),invoice:Us}),Hy=C.z.strictObject({...Zt,type:C.z.literal("refund.updated"),operationId:C.z.uuid().nullable(),merchantInvoiceId:Vt.optional(),merchantRefundId:Vt,status:C.z.enum(["pending","succeeded","failed"]),amountMinor:xt.refine(e=>e>0),currency:Go}),Bl=[Ly.refine(e=>e.paymentStatus!=="paid"||e.invoice!==null,"A paid purchase includes its Invoice"),zy,$y,Gy.refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"Scheduled and applied changes are distinct facts"),Ky,Hy.refine(e=>e.operationId!==null||e.merchantInvoiceId!==void 0,"A native refund names its Invoice")];var T=require("zod");var Yn=require("zod"),Nt=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,Xn=Yn.z.object({customerId:Yn.z.uuid(),sessionId:Yn.z.uuid(),accessToken:Yn.z.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),refreshToken:Yn.z.string().regex(/^gg_rt_[A-Za-z0-9_-]{43}$/),expiresAt:Yn.z.iso.datetime(),refreshExpiresAt:Yn.z.iso.datetime()});var Vs=3;var Qy=["session","catalog","customer_commerce","presentation","presentation_events","purchases","operation_status","billing_records","subscription_changes","refunds"],Jy=T.z.enum(Qy);var Zy=T.z.enum(["bridge.ping","bridge.describe","session.create","catalog.read","customer.commerce.read","presentation.resolve","presentation.report","purchase.execute","operation.read","subscription.change","refund.execute"]),Ll=T.z.string().regex(/^[A-Za-z0-9_-]{1,64}$/),Wy=T.z.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(e=>"AEIMQUYcgkosw048".includes(e.at(-1)),"Use canonical base64url for a 32-byte key"),Yy=T.z.strictObject({keyId:Ll,signingSecret:Wy}),Xy=T.z.string().max(300).superRefine((e,t)=>{try{let n=new URL(e);if(n.protocol!=="https:"||n.username||n.password||n.search||n.hash||n.pathname!=="/"||n.port&&n.port!=="443"||!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.[a-z]{2,63}$/.test(n.hostname)||/(?:^|\.)(?:localhost|local|internal)$/.test(n.hostname))throw new Error("invalid origin")}catch{t.addIssue({code:"custom",message:"Use an exact public HTTPS origin"})}}).transform(e=>new URL(e).origin),zl=T.z.array(Jy).max(10).refine(e=>new Set(e).size===e.length,"Capabilities must be unique"),$l=T.z.strictObject({bridgeVersion:T.z.literal(Vs),projectId:T.z.uuid(),environmentId:T.z.uuid(),environment:T.z.enum(["sandbox","live"]),capabilities:zl,catalog:T.z.enum(["endpoint","static","none"]),billingEvents:T.z.array(Ul).max(6),profiles:T.z.array(Dl).max(32).refine(e=>new Set(e).size===e.length,"Profiles must be unique")}).superRefine((e,t)=>{let n=r=>e.capabilities.includes(r);n("catalog")!==(e.catalog!=="none")&&t.addIssue({code:"custom",path:["catalog"],message:"Catalog declaration differs from its capability"}),(n("billing_records")!==e.billingEvents.length>0||new Set(e.billingEvents).size!==e.billingEvents.length)&&t.addIssue({code:"custom",path:["billingEvents"],message:"Declare the unique supported billing events"})}),Gl=T.z.strictObject({origin:Xy,requiredCapabilities:zl}),eA=T.z.strictObject({revision:T.z.number().int().nonnegative(),checkedAt:T.z.iso.datetime(),outcome:T.z.enum(["valid","unreachable","invalid","scope_mismatch","authentication_failed","credentials_missing"]),diagnostics:T.z.strictObject({ping:T.z.enum(["passed","failed","not_checked"]),authentication:T.z.enum(["passed","failed","not_checked"]),catalog:T.z.enum(["passed","failed","not_checked","static","unsupported"])}),manifest:$l.nullable()}).superRefine((e,t)=>{e.outcome==="valid"!=(e.manifest!==null)&&t.addIssue({code:"custom",path:["manifest"],message:"Only a valid declaration carries a manifest"})}),tw=T.z.strictObject({projectId:T.z.uuid(),environmentId:T.z.uuid(),environment:T.z.enum(["sandbox","live"]),execution:T.z.enum(["indiana","record_only"]),accountId:T.z.string().nullable(),revision:T.z.number().int().nonnegative(),authentication:T.z.strictObject({keyId:Ll}).nullable(),secretStoreConfigured:T.z.boolean().optional(),connection:Gl.nullable(),check:eA.nullable()});var Vl=T.z.strictObject({projectId:T.z.uuid(),environmentId:T.z.uuid()}),nw=T.z.discriminatedUnion("action",[Vl.extend({action:T.z.literal("save"),revision:T.z.number().int().nonnegative(),connection:Gl,authentication:Yy.optional()}),Vl.extend({action:T.z.literal("check"),revision:T.z.number().int().nonnegative()})]),Ls=T.z.strictObject({projectId:T.z.uuid(),environmentId:T.z.uuid(),environment:T.z.enum(["sandbox","live"])});var tA=T.z.strictObject({nativeUserId:T.z.string().min(1).max(128),session:Xn.strict()}),nA=T.z.strictObject({nativeUserId:T.z.string().min(1).max(128),presentation:T.z.strictObject({customerId:T.z.uuid(),decisionId:T.z.uuid(),offeringVersionId:T.z.uuid(),paywallVersionId:T.z.uuid(),variant:T.z.string().min(1).max(128)}).nullable()}),rA=T.z.strictObject({decisionId:T.z.uuid(),eventId:T.z.uuid()}),Jo=T.z.strictObject({operationId:T.z.uuid(),customerId:T.z.uuid()}),Zo=T.z.strictObject({scope:Ls,operationId:T.z.uuid(),customerId:T.z.uuid(),confirmedAt:T.z.iso.datetime({offset:!0}).nullable(),initialExecutionAllowed:T.z.boolean(),instruction:Ml}).refine(e=>e.operationId===e.instruction.operationId&&e.customerId===e.instruction.customerId,"Authority must refer to the original Customer and operation"),Bs=Cr,Kn=T.z.string().min(1).max(120),iA=T.z.string().regex(/^-?[0-9]+(?:\.[0-9]{1,6})?$/),oA=T.z.strictObject({revision:Kn,updatedAt:T.z.iso.datetime(),provider:T.z.literal("merchant"),items:T.z.array(T.z.strictObject({merchantProductId:Kn,productVersionId:T.z.uuid(),name:T.z.string().min(1).max(255),kind:T.z.enum(["subscription","credit_pack"]),merchantPriceId:Kn,currency:T.z.string().regex(/^[a-z]{3}$/),amountMinor:T.z.number().int().nonnegative().max(1e8),interval:T.z.enum(["one_time","month","year"]),intervalCount:T.z.literal(1),includedCredits:T.z.string().regex(/^[0-9]{1,18}(?:\.[0-9]{1,6})?$/),creditReset:T.z.enum(["none","month"]),creditPolicyId:Kn,available:T.z.boolean()}).superRefine((e,t)=>{(e.kind==="credit_pack"&&(e.interval!=="one_time"||e.creditReset!=="none")||e.kind==="subscription"&&e.interval==="one_time"||e.available&&e.amountMinor===0)&&t.addIssue({code:"custom",message:"Unsupported version 1 catalog terms"})})).max(500)}),aA=T.z.strictObject({customerId:T.z.uuid(),revision:T.z.string().min(1).max(128),observedAt:T.z.iso.datetime(),subscriptions:T.z.array(T.z.strictObject({merchantSubscriptionId:Kn,merchantProductId:Kn,productVersionId:T.z.uuid().nullable(),status:T.z.enum(["active","trialing","past_due","cancelled","expired"]),currentPeriodStartsAt:T.z.iso.datetime().nullable(),currentPeriodEndsAt:T.z.iso.datetime().nullable(),cancelAtPeriodEnd:T.z.boolean(),scheduledChange:T.z.strictObject({effectiveAt:T.z.iso.datetime(),merchantProductId:Kn}).nullable()})).max(100),purchaseHistory:T.z.strictObject({complete:T.z.boolean(),hasPaidPurchase:T.z.boolean(),lastPaidAt:T.z.iso.datetime().nullable()}),balances:T.z.array(T.z.strictObject({bucketId:Kn,key:Kn,available:iA,expiresAt:T.z.iso.datetime().nullable(),nextResetAt:T.z.iso.datetime().nullable()})).max(100)}),rw=T.z.strictObject({bridgeVersion:T.z.literal(Vs),requestId:T.z.uuid(),command:T.z.string().min(1).max(64),scope:Ls,error:T.z.strictObject({code:T.z.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:T.z.string().min(1).max(500),retryable:T.z.boolean(),recovery:T.z.string().min(1).max(80)})}),zi=T.z.strictObject({}),sA={"bridge.ping":T.z.strictObject({challenge:T.z.uuid()}),"bridge.describe":zi,"session.create":zi,"catalog.read":zi,"customer.commerce.read":zi,"presentation.resolve":zi,"presentation.report":rA,"purchase.execute":Jo,"operation.read":Jo,"subscription.change":Jo,"refund.execute":Jo},iw={"bridge.ping":T.z.strictObject({challenge:T.z.uuid()}),"bridge.describe":$l,"session.create":tA,"catalog.read":oA,"customer.commerce.read":aA,"presentation.resolve":nA,"presentation.report":T.z.strictObject({queued:T.z.literal(!0)}),"purchase.execute":Bs,"operation.read":ql,"subscription.change":Bs,"refund.execute":Bs},ow=T.z.strictObject({bridgeVersion:T.z.literal(Vs),requestId:T.z.uuid(),scope:Ls,command:Zy,data:T.z.unknown()}).superRefine((e,t)=>{sA[e.command].safeParse(e.data).success||t.addIssue({code:"custom",path:["data"],message:"Invalid command data"})});var _r=require("zod");var Wo=_r.z.string().trim().min(1).max(64).regex(/^[a-z][a-z0-9_]*$/,"ID \u4F7F\u7528\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u4E0B\u5212\u7EBF\uFF0C\u5E76\u4EE5\u5B57\u6BCD\u5F00\u5934"),cw=_r.z.object({amountCents:_r.z.number().int().min(0).max(1e8),currency:Ie,interval:_r.z.enum(["free","month","year"]),currencyOptions:_r.z.partialRecord(Ie,_r.z.number().int().min(1).max(1e8)).optional()}).refine(e=>e.interval==="free"?e.amountCents===0:e.amountCents>0,"\u514D\u8D39\u5957\u9910\u91D1\u989D\u5FC5\u987B\u4E3A 0\uFF0C\u4ED8\u8D39\u91D1\u989D\u5FC5\u987B\u5927\u4E8E 0").refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency)&&(e.interval!=="free"||Object.keys(e.currencyOptions).length===0),"\u9644\u52A0\u5E01\u79CD\u4E0D\u80FD\u91CD\u590D\u9ED8\u8BA4\u5E01\u79CD\uFF1B\u514D\u8D39\u5957\u9910\u4E0D\u8BBE\u7F6E\u9644\u52A0\u4EF7\u683C");var F=require("zod"),cA=F.z.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Ql=F.z.enum(["single_use","continuous_use"]),zs=F.z.record(F.z.string(),F.z.union([F.z.string(),F.z.number(),F.z.boolean()]).transform(String).pipe(F.z.string())),Kl=F.z.string().min(1).max(64).refine(e=>!e.includes("::")),Jl={credit_amount:F.z.number(),tier_behavior:F.z.never().optional(),tiers:F.z.never().optional()},Zl={credit_amount:F.z.never().optional(),tier_behavior:F.z.literal("graduated"),tiers:F.z.array(F.z.strictObject({to:F.z.union([F.z.number(),F.z.literal("inf")]),credit_amount:F.z.number()}))},uA=F.z.union([F.z.strictObject({match:zs,priority:F.z.number().int().optional(),...Jl}),F.z.strictObject({match:zs,priority:F.z.number().int().optional(),...Zl})]),lA=F.z.strictObject({match:zs,factor:F.z.number().positive().optional(),add:F.z.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),Hl={metered_feature_id:F.z.string(),feature_amount:F.z.number().optional(),dimensions:F.z.record(Kl,uA).optional(),multipliers:F.z.record(Kl,lA).optional()},$s=F.z.union([F.z.strictObject({...Hl,...Jl}),F.z.strictObject({...Hl,...Zl})]),Xo=F.z.number().min(-100),Wl=F.z.record(F.z.string(),F.z.strictObject({markup:Xo})).nullish(),ea=F.z.record(F.z.string().regex(/.+\/.+/),F.z.strictObject({markup:Xo.optional(),input_cost:F.z.number().min(0).optional(),output_cost:F.z.number().min(0).optional()})).nullish(),dA=F.z.strictObject({default_markup:Xo.optional(),provider_markups:Wl,model_markups:ea}),lw=F.z.strictObject({schema:F.z.array($s).optional(),markups:dA.optional()}),pA=F.z.strictObject({filters:F.z.array(F.z.strictObject({property:F.z.string(),operator:F.z.string(),value:F.z.array(F.z.string())})),aggregate:F.z.strictObject({type:F.z.string(),property:F.z.string().nullable()}),usage_type:Ql}),Yl=F.z.strictObject({schema:F.z.array($s).min(1).refine(e=>new Set(e.map(t=>t.metered_feature_id)).size===e.length,"Credit rates must name each metered feature once"),invoice_credit:F.z.boolean().optional(),usage_type:Ql.default("single_use").overwrite(()=>"single_use"),default_markup:Xo.optional(),provider_markups:Wl}),Gs=Yl.safeExtend({schema:F.z.array($s).length(0)}),Yo={id:cA,name:F.z.string().min(1),display:F.z.strictObject({singular:F.z.string().optional(),plural:F.z.string().optional()}).nullish(),event_names:F.z.array(F.z.string()).default([]),model_markups:ea,stripe_meter:F.z.strictObject({id:F.z.string(),event_name:F.z.string()}).nullish(),stripe_product_id:F.z.string().nullish()},Ks=e=>F.z.discriminatedUnion("type",[F.z.strictObject({...Yo,...e,type:F.z.literal("boolean"),config:F.z.null()}),F.z.strictObject({...Yo,...e,type:F.z.literal("metered"),config:pA}),F.z.strictObject({...Yo,...e,type:F.z.literal("credit_system"),config:Yl}),F.z.strictObject({...Yo,...e,type:F.z.literal("ai_credit_system"),config:Gs})]),dw=Ks({}),mA=F.z.strictObject({id:F.z.boolean(),type:F.z.boolean(),usage_type:F.z.boolean()}),fA={internal_id:F.z.uuid(),org_id:F.z.uuid(),created_at:F.z.number(),env:F.z.enum(["sandbox","live"]),archived:F.z.boolean(),project_id:F.z.uuid(),environment_id:F.z.uuid(),revision:F.z.number().int().nonnegative(),update_rules:mA},Xl=Ks(fA),pw=F.z.strictObject({rows:F.z.array(Xl).max(200),nextCursor:F.z.uuid().nullable()}),mw=F.z.strictObject({features:F.z.array(Xl).max(500),limited:F.z.boolean()}),fw=F.z.union([Ks({action:F.z.literal("save"),internal_id:F.z.uuid().nullable(),revision:F.z.number().int().nonnegative()}),F.z.strictObject({action:F.z.enum(["archive","restore","delete"]),internal_id:F.z.uuid(),revision:F.z.number().int().nonnegative()})]);var kr=require("zod");var lt=require("zod"),Wt=lt.z.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),xe=lt.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),ta=lt.z.string().regex(/^-?(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>{let t=e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e;return t==="-0"?"0":t}),Hs=xe.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),ed=lt.z.string().min(1).max(64),Er=lt.z.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),td=lt.z.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),Pt=lt.z.record(ed,lt.z.union([lt.z.string().max(120),lt.z.number().finite(),lt.z.boolean()])).refine(e=>Object.keys(e).length<=16,"\u6700\u591A 16 \u4E2A\u8BA1\u4EF7\u5C5E\u6027").transform(e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,String(n)]))),nd=lt.z.record(ed,lt.z.union([lt.z.string().max(120),lt.z.number().finite(),lt.z.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),oi=e=>{let t=e.startsWith("-");t&&(e=e.slice(1));let[n,r=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");let i=BigInt(n)*BigInt("1000000")+BigInt(r.padEnd(6,"0"));return t?-i:i},rd=lt.z.array(lt.z.object({upTo:Hs.nullable(),cost:xe}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let r=e[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&oi(t.upTo)>oi(r))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),gA=lt.z.object({key:td,match:nd,priority:lt.z.number().int().default(0),cost:xe.optional(),tiers:rd.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),hA=lt.z.object({key:td,match:nd,factor:Hs.optional(),add:ta.optional()}).strict().refine(e=>e.factor!==void 0||e.add!==void 0,"A multiplier needs a factor or an add").transform(e=>({...e,factor:e.factor??"1",add:e.add??"0"})),yA=lt.z.object({units:Hs.default("1"),cost:xe,tiers:rd.optional(),dimensions:lt.z.array(gA).max(12).optional(),multipliers:lt.z.array(hA).max(4).optional()}).strict().superRefine((e,t)=>{let n=e.dimensions??[],r=e.multipliers??[];(new Set(n.map(o=>o.key)).size!==n.length||new Set(r.map(o=>o.key)).size!==r.length)&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u548C\u500D\u7387\u7684 ID \u4E0D\u80FD\u91CD\u590D"});for(let[o,s]of n.entries())for(let c of n.slice(o+1))Object.keys(s.match).length===Object.keys(c.match).length&&s.priority===c.priority&&!Object.keys(s.match).some(u=>c.match[u]!==void 0&&c.match[u]!==s.match[u])&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u53EF\u80FD\u540C\u65F6\u5339\u914D\uFF0C\u8BF7\u8C03\u6574\u4F18\u5148\u7EA7"});let i=[e.cost,...(e.tiers??[]).map(o=>o.cost),...n.flatMap(o=>[...o.cost===void 0?[]:[o.cost],...(o.tiers??[]).map(s=>s.cost)])],a=oi(e.units);for(let o of i)for(let s=0;s<1<<r.length;s++){let c=r.filter((d,h)=>s&1<<h);if(c.some((d,h)=>c.slice(h+1).some(R=>Object.keys(d.match).some(y=>R.match[y]!==void 0&&R.match[y]!==d.match[y]))))continue;let u=oi(o),l=BigInt("1"),m=BigInt("0");for(let[d,h]of r.entries())s&1<<d&&(u*=oi(h.factor??"1"),l*=BigInt("1000000"),m+=oi(h.add??"0"));let f=(u+m*l)*BigInt("1000000"),g=l*a;(f<BigInt("0")||f%g!==BigInt("0")||f/g>BigInt("999999999999999999"))&&t.addIssue({code:"custom",message:"\u6BCF\u4E2A\u4E1A\u52A1\u5355\u4F4D\u7684\u6700\u7EC8\u5355\u4EF7\u5FC5\u987B\u975E\u8D1F\u3001\u5728\u8303\u56F4\u5185\u4E14\u80FD\u7CBE\u786E\u8868\u793A\u4E3A\u6700\u591A 6 \u4F4D\u5C0F\u6570"})}}),hw=yA.safeExtend({featureKey:Er});var Rr=require("zod"),id=Rr.z.number().int().min(0).max(1e8),$i=Rr.z.strictObject({kind:Rr.z.enum(["graduated","volume"]),tiers:Rr.z.array(Rr.z.strictObject({upTo:Rr.z.number().int().min(1).max(1e4).nullable(),unitAmountMinor:id,flatAmountMinor:id.optional()})).min(1).max(12)}).refine(e=>e.tiers.at(-1)?.upTo===null&&e.tiers.slice(0,-1).every((t,n)=>{let r=e.tiers[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&t.upTo>r)}),"Tier ceilings must increase and end unbounded").refine(e=>!e.tiers.some(t=>(t.flatAmountMinor??0)>0)||e.kind==="volume"&&e.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers");function Qs(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let n=e.pricing?$i.parse(e.pricing):void 0;if(t===0)return 0;let r=0n,i=0;if(!n)r=BigInt(e.amountMinor)*BigInt(t);else for(let a of n.tiers){let o=a.upTo??1e4;if(n.kind==="volume"){if(t<=o){r=BigInt(t)*BigInt(a.unitAmountMinor)+BigInt(a.flatAmountMinor??0);break}}else t>i&&(r+=BigInt(Math.min(t,o)-i)*BigInt(a.unitAmountMinor));i=o}if(r>200000000n)throw new Error("Purchased price exceeds the payment amount limit");return Number(r)}function na(e){return Qs({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}var AA=xe.refine(e=>/[1-9]/.test(e)),ra=kr.z.strictObject({units:AA,prices:kr.z.array(kr.z.strictObject({currency:Ie,amountMinor:kr.z.number().int().min(0).max(1e8),pricing:$i.optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.currency)).size===e.length,"Currencies must be unique").refine(e=>e.every(t=>!t.pricing||t.amountMinor===0),"Tiered prices specify their rates in tiers"),minimumQuantity:kr.z.number().int().min(0).max(1e4),maximumQuantity:kr.z.number().int().min(0).max(1e4)}).refine(e=>e.maximumQuantity>=e.minimumQuantity,"Purchased quantity must fit its published bounds").refine(e=>{try{for(let t of e.prices)for(let n of[e.maximumQuantity,...t.pricing?.tiers.flatMap(r=>r.upTo===null?[]:[r.upTo,r.upTo+1])??[]])n<=e.maximumQuantity&&Qs({amountMinor:t.amountMinor,...t.pricing===void 0?{}:{pricing:t.pricing}},n);return!0}catch{return!1}},"Every purchasable quantity must fit the payment amount limit");function od(e){if(!/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/.test(e))throw new Error("Invalid quantity");let[t,n=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");return BigInt(t)*1000000n+BigInt(n.padEnd(6,"0"))}function ad(e,t,n){if(!Number.isSafeInteger(n)||n<0||n>1e4)throw new Error("Invalid purchased quantity");let r=od(e)+od(t)*BigInt(n);if(r>999999999999999999n)throw new Error("Purchased allowance exceeds the ledger quantity limit");let i=(r%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return(r/1000000n).toString()+(i?"."+i:"")}var S=require("zod");var ee=require("zod");var Rt=require("zod");var N=require("zod");function sd(e){let t=2166136261,n=e.length;for(let r=0;r<n;r++)t^=e.charCodeAt(r),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);return t>>>0}function ia(e,t,n){return n===2?sd(sd(e+t)+"")%1e4/1e4:null}function bA(e){return e<=0?[]:new Array(e).fill(1/e)}function oa(e,t){return e>=t[0]&&e<t[1]}function cd(e,t){for(let[n,r]of t.entries())if(oa(e,r))return n;return-1}function ud(e,t,n){t=t===void 0?1:t,t<0?t=0:t>1&&(t=1);let r=bA(e);n=n||r,n.length!==e&&(n=r);let i=n.reduce((s,c)=>c+s,0);(i<.99||i>1.01)&&(n=r);let a=0,o=t;return n.map(s=>{let c=a;return a+=s,[c,c+o*s]})}function ld(e,t,n){if(!t)return null;let r=t.split("?")[1];if(!r)return null;let a=r.replace(/#.*/,"").split("&").map(o=>o.split("=",2)).filter(([o])=>o===e).map(([,o])=>o===void 0?NaN:parseInt(o))[0];return a!==void 0&&a>=0&&a<n?a:null}function dd(e){try{return e()}catch{return!1}}function Gi(e){return typeof e=="string"?e:JSON.stringify(e)}function cn(e){typeof e=="number"&&(e=e+""),(!e||typeof e!="string")&&(e="0");let t=e.replace(/(^v|\+.*$)/g,"").split(/[-.]/);return t.length===3&&t.push("~"),t.map(n=>n.match(/^[0-9]+$/)?n.padStart(5," "):n).join("-")}function xA(e){try{let t=e.replace(/([^\\])\//g,"$1\\/");return new RegExp(t)}catch{return}}function pd(e,t){if(!t.length)return!1;let n=!1,r=!1;for(let i of t){let a=vA(e,i.type,i.pattern);if(i.include===!1){if(a)return!1}else n=!0,a&&(r=!0)}return r||!n}function SA(e,t,n){try{let r=t.replace(/[*.+?^${}()|[\]\\]/g,"\\$&").replace(/_____/g,".*");return n&&(r="\\/?"+r.replace(/(^\/|\/$)/g,"")+"\\/?"),new RegExp("^"+r+"$","i").test(e)}catch{return!1}}function IA(e,t){try{let n=new URL(t.replace(/^([^:/?]*)\./i,"https://$1.").replace(/\*/g,"_____"),"https://_____"),r=[[e.host,n.host,!1],[e.pathname,n.pathname,!0]];return n.hash&&r.push([e.hash,n.hash,!1]),n.searchParams.forEach((i,a)=>{r.push([e.searchParams.get(a)||"",i,!1])}),!r.some(i=>!SA(i[0],i[1],i[2]))}catch{return!1}}function vA(e,t,n){try{let r=new URL(e,"https://_");if(t==="regex"){let i=xA(n);return i?i.test(r.href)||i.test(r.href.substring(r.origin.length)):!1}else if(t==="simple")return IA(r,n);return!1}catch{return!1}}function Js(e){for(let n of["namespace","status","url","groups"])if(Object.hasOwn(e,n))throw new TypeError(`Retired experiment field: ${n}`);let t=e;if(t.hashVersion!==void 0&&t.hashVersion!==2)throw new TypeError("Only hash version 2 is supported");if(t.filters?.some(n=>n.hashVersion!==2))throw new TypeError("Only hash version 2 is supported")}function aa(e){for(let t of Object.values(e)){if(Array.isArray(t))throw new TypeError("Saved groups require typed list or condition entries");if(t&&Object.hasOwn(t,"useEmptyListGroup"))throw new TypeError("Retired saved group field: useEmptyListGroup")}}function md(e){for(let t of["overrides","groups"])if(Object.hasOwn(e,t))throw new TypeError(`Retired evaluation context field: ${t}`);aa(e.savedGroups??{})}var wA=e=>e/2**32|0,OA=e=>e>>>0;function fd(e,t,n,r){let i=wA(n),a=OA(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function gd(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var Zs=e=>e?`"${e}" `:"";function PA(e,t=""){if(typeof e!="number")throw new TypeError(Zs(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(Zs(t)+"expected integer >= 0, got "+e);return e}function sa(e,t,n=""){if(gd(e)&&(t===void 0||e.length===t))return e;t!==void 0&&PA(t,"length");let r=gd(e),i=t!==void 0?` of length ${t}`:"",a=r?`length=${e.length}`:`type=${typeof e}`,o=Zs(n)+"expected Uint8Array"+i+", got "+a;throw r?new RangeError(o):new TypeError(o)}var CA=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},hd=(e,t)=>{CA(e,t);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function Ws(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function yd(e,t){sa(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function Ys(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ca(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function vn(e,t){return e<<32-t|e>>>t}var _A=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",EA=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function ai(e){if(sa(e),_A)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=EA[e[n]];return t}function RA(e,t,n="opts"){return hd(e,"defaults"),t!==void 0&&hd(t,n),Object.assign(Object.create(null),e,t)}function Ad(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=RA({},t,"info");let n=(i,a)=>e(a).update(i).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=i=>e(i),Object.assign(n,t),Object.freeze(n)}var bd=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function xd(e,t,n){return e&t^~e&n}function Sd(e,t,n){return e&t^e&n^t&n}var ua=class{constructor(t,n,r,i){qe(this,"blockLen");qe(this,"outputLen");qe(this,"canXOF",!1);qe(this,"padOffset");qe(this,"isLE");qe(this,"buffer");qe(this,"view");qe(this,"finished",!1);qe(this,"length",0);qe(this,"pos",0);qe(this,"destroyed",!1);this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(t),this.view=ca(this.buffer)}update(t){Ws(this),sa(t);let{view:n,buffer:r,blockLen:i}=this,a=t.length,o=!1;for(let s=0;s<a;){let c=Math.min(i-this.pos,a-s);if(c===i){let u=ca(t);for(;i<=a-s;s+=i)this.process(u,s);o=!0;continue}r.set(s===0&&c===a?t:t.subarray(s,s+c),this.pos),this.pos+=c,s+=c,this.pos===i&&(this.process(n,0),this.pos=0,o=!0)}return this.length+=t.length,o&&this.roundClean(),this}digestInto(t){Ws(this),yd(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:i,isLE:a}=this,{pos:o}=this;n[o++]=128,n.fill(0,o),this.padOffset>i-o&&(this.process(r,0),n.fill(0)),fd(r,i-8,this.length*8,a),this.process(r,0),this.roundClean();let s=t===n?r:ca(t),c=this.outputLen,u=c/4,l=this.get();if(c%4||u>l.length)throw new Error("invalid outputLen");for(let m=0;m<u;m++)s.setUint32(4*m,l[m],a)}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneIntoMeta(t){let{buffer:n,length:r,finished:i,destroyed:a,pos:o}=this;return t.destroyed=a,t.finished=i,t.length=r,t.pos=o,o&&t.buffer.set(n),t}clone(){return this._cloneInto()}},Id=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var kA=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),er=new Uint32Array(64),Xs=class extends ua{constructor(n,r){super(64,n,8,!1);qe(this,"A",0);qe(this,"B",0);qe(this,"C",0);qe(this,"D",0);qe(this,"E",0);qe(this,"F",0);qe(this,"G",0);qe(this,"H",0);this.A=r[0]|0,this.B=r[1]|0,this.C=r[2]|0,this.D=r[3]|0,this.E=r[4]|0,this.F=r[5]|0,this.G=r[6]|0,this.H=r[7]|0}get(){let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:u}=this;return[n,r,i,a,o,s,c,u]}set(n,r,i,a,o,s,c,u){this.A=n|0,this.B=r|0,this.C=i|0,this.D=a|0,this.E=o|0,this.F=s|0,this.G=c|0,this.H=u|0}_cloneInto(n){return(n||(n=new this.constructor)).set(...this.get()),this._cloneIntoMeta(n)}process(n,r){for(let f=0;f<16;f++,r+=4)er[f]=n.getUint32(r,!1);for(let f=16;f<64;f++){let g=er[f-15],d=er[f-2],h=vn(g,7)^vn(g,18)^g>>>3,R=vn(d,17)^vn(d,19)^d>>>10;er[f]=R+er[f-7]+h+er[f-16]|0}let{A:i,B:a,C:o,D:s,E:c,F:u,G:l,H:m}=this;for(let f=0;f<64;f++){let g=vn(c,6)^vn(c,11)^vn(c,25),d=m+g+xd(c,u,l)+kA[f]+er[f]|0,R=(vn(i,2)^vn(i,13)^vn(i,22))+Sd(i,a,o)|0;m=l,l=u,u=c,c=s+d|0,s=o,o=a,a=i,i=d+R|0}i=i+this.A|0,a=a+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,u=u+this.F|0,l=l+this.G|0,m=m+this.H|0,this.set(i,a,o,s,c,u,l,m)}roundClean(){Ys(er)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Ys(this.buffer)}},ec=class extends Xs{constructor(){super(32,Id)}};var si=Ad(()=>new ec,bd(1));var vd=new Map,tc=32,wd=new WeakMap,Od=new WeakMap;function jA(e){return ai(si(new TextEncoder().encode(String(e))))}var da=e=>Array.isArray(e)?e.map(da):typeof e=="string"||typeof e=="number"?jA(e):null,la=e=>typeof e=="string"?e.toLowerCase():e;function Rd(e){let t=wd.get(e);return t||(t=new Set(e),wd.set(e,t)),t}function TA(e){let t=Od.get(e);return t||(t=new Set(e.map(la)),Od.set(e,t)),t}function ci(e){aa(e);for(let t of Object.values(e)){let n=t?.type==="list"||t?.type==="hashed"?t.values:null;n&&n.length>=tc&&Rd(n)}return e}function en(e,t,n,r){n=n||{},r||aa(n),r=r||new Set;for(let[i,a]of Object.entries(t))switch(i){case"$or":if(!Ed(e,a,n,r))return!1;break;case"$nor":if(Ed(e,a,n,r))return!1;break;case"$and":if(!qA(e,a,n,r))return!1;break;case"$not":if(en(e,a,n,r))return!1;break;case"$savedGroup":if(!NA(e,a,n,r))return!1;break;default:if(!Ki(a,kd(e,i),n,!1,r))return!1}return!0}function NA(e,t,n,r){if(!t||typeof t!="object"||Array.isArray(t))return!1;let{id:i,attributeKey:a}=t;if(typeof i!="string"||r.has(i)||a!==void 0&&typeof a!="string")return!1;let o=n[i];if(!o||Array.isArray(o)||typeof o!="object")return!1;let s=new Set(r).add(i);if(o.type==="list"||o.type==="hashed"){let c=a??o.attributeKey;if(typeof c!="string"||!Array.isArray(o.values))return!1;let u=kd(e,c);return jr(o.type==="hashed"?da(u):u,o.values)}return o.type==="condition"?!o.condition||typeof o.condition!="object"?!1:en(e,o.condition,n,s):!1}function kd(e,t){let n=t.split("."),r=e;for(let i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return null;return r}function Pd(e,t=!1){let n=`${e}${t?"/i":""}`,r=vd.get(n);return r||(r=new RegExp(e.replace(/([^\\])\//g,"$1\\/"),t?"i":void 0),vd.set(n,r)),r}function Ki(e,t,n,r=!1,i=new Set){if(typeof e=="string")return r?String(t).toLowerCase()===e.toLowerCase():t+""===e;if(typeof e=="number")return t*1===e;if(typeof e=="boolean")return t!==null&&!!t===e;if(e===null)return t===null;if(Array.isArray(e)||!jd(e))return JSON.stringify(t)===JSON.stringify(e);let a=e;for(let o in a)if(!MA(o,t,a[o],n,i))return!1;return!0}function jd(e){let t=Object.keys(e);return t.length>0&&t.filter(n=>n[0]==="$").length===t.length}function DA(e){if(e===null)return"null";if(Array.isArray(e))return"array";let t=typeof e;return["string","number","boolean","object","undefined"].includes(t)?t:"unknown"}function FA(e,t,n,r){if(!Array.isArray(e))return!1;let i=jd(t)?a=>Ki(t,a,n,!1,r):a=>en(a,t,n,r);for(let a=0;a<e.length;a++)if((e[a]??null)!==null&&i(e[a]))return!0;return!1}function jr(e,t,n=!1){if(n){let i;if(t.length>=tc){let a=TA(t);i=o=>{let s=la(o);return!(typeof s=="number"&&Number.isNaN(s))&&a.has(s)}}else i=a=>t.some(o=>la(a)===la(o));return Array.isArray(e)?e.some(a=>i(a)):i(e)}let r=t.length>=tc?(i=>a=>i.has(a))(Rd(t)):i=>t.includes(i);return Array.isArray(e)?e.some(i=>r(i)):r(e)}function Cd(e){return e===void 0?[]:e&&typeof e=="object"&&(e.type==="list"||e.type==="hashed")&&Array.isArray(e.values)?e.values:null}function _d(e,t,n,r=!1,i=new Set){if(!Array.isArray(e))return!1;for(let a=0;a<t.length;a++){let o=!1;for(let s=0;s<e.length;s++)if(Ki(t[a],e[s],n,r,i)){o=!0;break}if(!o)return!1}return!0}function MA(e,t,n,r,i=new Set){let a=t,o=n;switch(e){case"$veq":return cn(t)===cn(n);case"$vne":return cn(t)!==cn(n);case"$vgt":return cn(t)>cn(n);case"$vgte":return cn(t)>=cn(n);case"$vlt":return cn(t)<cn(n);case"$vlte":return cn(t)<=cn(n);case"$eq":return t===n;case"$ne":return t!==n;case"$lt":return a<o;case"$lte":return a<=o;case"$gt":return a>o;case"$gte":return a>=o;case"$exists":return n?t!=null:t==null;case"$in":return Array.isArray(n)?jr(t,n):!1;case"$ini":return Array.isArray(n)?jr(t,n,!0):!1;case"$inGroup":{let s=r[n],c=Cd(s);return c===null?!1:jr(s?.type==="hashed"?da(t):t,c)}case"$notInGroup":{let s=r[n],c=Cd(s);return c===null?!1:!jr(s?.type==="hashed"?da(t):t,c)}case"$nin":return Array.isArray(n)?!jr(t,n):!1;case"$nini":return Array.isArray(n)?!jr(t,n,!0):!1;case"$not":return!Ki(n,t,r,!1,i);case"$size":return Array.isArray(t)?Ki(n,t.length,r,!1,i):!1;case"$elemMatch":return FA(t,n,r,i);case"$all":return Array.isArray(n)?_d(t,n,r,!1,i):!1;case"$alli":return Array.isArray(n)?_d(t,n,r,!0,i):!1;case"$regex":try{return Pd(n).test(t)}catch{return!1}case"$regexi":try{return Pd(n,!0).test(t)}catch{return!1}case"$type":return DA(t)===n;default:return!1}}function Ed(e,t,n,r){if(!t.length)return!0;for(let i of t)if(en(e,i,n,r))return!0;return!1}function qA(e,t,n,r){for(let i of t)if(!en(e,i,n,r))return!1;return!0}function nc(e){return md(e),{context:e,stack:{evaluatedFeatures:new Set}}}function rc(e){return{...e.attributes,...e.attributeOverrides}}function tr(e,t,n){let r=t||"id",i="",a=rc(e);return a[r]&&(i=a[r]),!i&&n&&(a[n]&&(i=a[n]),i&&(r=n)),{hashAttribute:r,hashValue:i}}function Ye(e,t,n){e.context.log?.(t,n)}function pa(e,t){return t=t||0,`${e}__${t}`}function ic(e,t){return`${e}||${t}`}function UA(e,t,n){let r=e.stickyBucketAssignmentDocs;if(!r)return{};let{hashAttribute:i,hashValue:a}=tr(e,t),o=ic(i,Gi(a)),{hashAttribute:s,hashValue:c}=tr(e,n),u=c?ic(s,Gi(c)):null,l={};return u&&r[u]&&Object.assign(l,r[u].assignments||{}),r[o]&&Object.assign(l,r[o].assignments||{}),l}function Td({context:e,expKey:t,expBucketVersion:n,expHashAttribute:r,expFallbackAttribute:i,expMinBucketVersion:a,expMeta:o}){n=n||0,a=a||0,r=r||"id",o=o||[];let s=pa(t,n),c=UA(e,r,i);if(a>0)for(let m=0;m<a;m++){let f=pa(t,m);if(c[f]!==void 0)return{variation:-1,versionIsBlocked:!0}}let u=c[s];if(u===void 0)return{variation:-1};let l=o.findIndex(m=>m.key===u);return l<0?{variation:-1}:{variation:l}}function Nd(e,t,n,r){let i=ic(t,n),a=e.stickyBucketAssignmentDocs,o=a&&a[i]?a[i].assignments||{}:{},s={...o,...r},c=JSON.stringify(o)!==JSON.stringify(s);return{key:i,doc:{attributeName:t,attributeValue:n,assignments:s},changed:c}}function Dd(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function ma(e,t){let n=nc(t),r=Md(e,null,n);return t.onExperimentEval?.(e,r),r}function Hn(e,t){return ac(e,nc(t))}function BA(e){return e.forcedVariations||{}}function Fd(e,t,n){let{context:r}=e;if(r.trackedExperiments){let i=Bd(t,n);if(r.trackedExperiments.has(i))return;r.trackedExperiments.add(i)}oc(()=>r.onExperimentViewed?.(t,n))}function VA(e,t,n){let{context:r}=e;if(r.trackedFeatureUsage){let i=JSON.stringify(n.value);if(r.trackedFeatureUsage[t]===i)return;r.trackedFeatureUsage[t]=i}oc(()=>r.onFeatureUsage?.(t,n))}function oc(e){try{let t=e();t&&typeof t.catch=="function"&&t.catch(()=>{})}catch{}}function ac(e,t){let{context:n}=t;if(t.stack.evaluatedFeatures.has(e))return Ye(t,`evalFeature: circular dependency detected: ${t.stack.id} -> ${e}`,{from:t.stack.id,to:e}),nr(t,e,null,"cyclicPrerequisite");t.stack.evaluatedFeatures.add(e),t.stack.id=e;let r=n.features?.[e];for(let a of r?.rules??[])Js(a);let i=n.forcedFeatureValues;if(i&&i.has(e))return Ye(t,"Global override",{id:e,value:i.get(e)}),nr(t,e,i.get(e),"override");if(!r)return Ye(t,"Unknown feature",{id:e}),nr(t,e,null,"unknownFeature");if(r.rules){let a=new Set(t.stack.evaluatedFeatures);e:for(let o of r.rules){if(o.parentConditions)for(let u of o.parentConditions){t.stack.evaluatedFeatures=new Set(a);let l=ac(u.id,t);if(l.source==="cyclicPrerequisite")return nr(t,e,null,"cyclicPrerequisite");let m={value:l.value};if(!en(m,u.condition||{},n.savedGroups||{})){if(u.gate)return Ye(t,"Feature blocked by prerequisite",{id:e,rule:o}),nr(t,e,null,"prerequisite");Ye(t,"Skip rule because prerequisite evaluation fails",{id:e,rule:o});continue e}}if(o.filters&&Ud(o.filters,t)){Ye(t,"Skip rule because of filters",{id:e,rule:o});continue}if("force"in o){if(o.condition&&!qd(o.condition,t)){Ye(t,"Skip rule because of condition ff",{id:e,rule:o});continue}if(!LA(t,o.seed||e,o.hashAttribute,n.saveStickyBucketAssignmentDoc&&!o.disableStickyBucketing?o.fallbackAttribute:void 0,o.range,o.coverage,o.hashVersion)){Ye(t,"Skip rule because user not included in rollout",{id:e,rule:o});continue}return Ye(t,"Force value from rule",{id:e,rule:o}),o.tracks&&o.tracks.forEach(u=>{Fd(t,u.experiment,u.result)}),nr(t,e,o.force,"force",o.id)}if(!o.variations){Ye(t,"Skip invalid rule",{id:e,rule:o});continue}let s={variations:o.variations,key:o.key||e};"coverage"in o&&(s.coverage=o.coverage),o.weights&&(s.weights=o.weights),o.hashAttribute&&(s.hashAttribute=o.hashAttribute),o.fallbackAttribute&&(s.fallbackAttribute=o.fallbackAttribute),o.disableStickyBucketing&&(s.disableStickyBucketing=o.disableStickyBucketing),o.bucketVersion!==void 0&&(s.bucketVersion=o.bucketVersion),o.minBucketVersion!==void 0&&(s.minBucketVersion=o.minBucketVersion),o.meta&&(s.meta=o.meta),o.ranges&&(s.ranges=o.ranges),o.name&&(s.name=o.name),o.phase&&(s.phase=o.phase),o.seed&&(s.seed=o.seed),o.hashVersion&&(s.hashVersion=o.hashVersion),o.filters&&(s.filters=o.filters),o.condition&&(s.condition=o.condition);let c=Md(s,e,t);if(n.onExperimentEval?.(s,c),c.inExperiment&&!c.passthrough)return nr(t,e,c.value,"experiment",o.id,s,c)}}return Ye(t,"Use default value",{id:e,value:r.defaultValue}),nr(t,e,r.defaultValue===void 0?null:r.defaultValue,"defaultValue")}function Md(e,t,n){let{context:r}=n;Js(e);let i=e.key,a=e.variations.length;if(a<2)return Ye(n,"Invalid experiment",{id:i}),Dt(n,e,-1,!1,t);if(r.enabled===!1)return Ye(n,"Context disabled",{id:i}),Dt(n,e,-1,!1,t);if(e.urlPatterns&&!pd(r.url||"",e.urlPatterns))return Ye(n,"Skip because of url targeting",{id:i}),Dt(n,e,-1,!1,t);let o=ld(i,r.url||"",a);if(o!==null)return Ye(n,"Force via querystring",{id:i,variation:o}),Dt(n,e,o,!1,t);let c=BA(r)[i];if(c!==void 0)return Ye(n,"Force via dev tools",{id:i,variation:c}),Dt(n,e,c,!1,t);if(e.active===!1)return Ye(n,"Skip because inactive",{id:i}),Dt(n,e,-1,!1,t);let{hashAttribute:u,hashValue:l}=tr(r,e.hashAttribute,r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0);if(!l)return Ye(n,"Skip because missing hashAttribute",{id:i}),Dt(n,e,-1,!1,t);let m=-1,f=!1,g=!1;if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{variation:R,versionIsBlocked:y}=Td(Dd({context:r,expKey:e.key,expBucketVersion:e.bucketVersion,expHashAttribute:e.hashAttribute,expFallbackAttribute:e.fallbackAttribute,expMinBucketVersion:e.minBucketVersion,expMeta:e.meta}));f=R>=0,m=R,g=!!y}if(!f){if(e.filters&&Ud(e.filters,n))return Ye(n,"Skip because of filters",{id:i}),Dt(n,e,-1,!1,t);if(e.include&&!dd(e.include))return Ye(n,"Skip because of include function",{id:i}),Dt(n,e,-1,!1,t);if(e.condition&&!qd(e.condition,n))return Ye(n,"Skip because of condition exp",{id:i}),Dt(n,e,-1,!1,t);if(e.parentConditions){let R=new Set(n.stack.evaluatedFeatures);for(let y of e.parentConditions){n.stack.evaluatedFeatures=new Set(R);let A=ac(y.id,n);if(A.source==="cyclicPrerequisite")return Dt(n,e,-1,!1,t);let x={value:A.value};if(!en(x,y.condition||{},r.savedGroups||{}))return Ye(n,"Skip because prerequisite evaluation fails",{id:i}),Dt(n,e,-1,!1,t)}}}let d=ia(e.seed||i,l,e.hashVersion??2);if(d===null)return Ye(n,"Skip because of invalid hash version",{id:i}),Dt(n,e,-1,!1,t);if(!f){let R=e.ranges||ud(a,e.coverage===void 0?1:e.coverage,e.weights);m=cd(d,R)}if(g)return Ye(n,"Skip because sticky bucket version is blocked",{id:i}),Dt(n,e,-1,!1,t,void 0,!0);if(m<0)return Ye(n,"Skip because of coverage",{id:i}),Dt(n,e,-1,!1,t);if("force"in e)return Ye(n,"Force variation",{id:i,variation:e.force}),Dt(n,e,e.force===void 0?-1:e.force,!1,t);if(r.qaMode)return Ye(n,"Skip because QA mode",{id:i}),Dt(n,e,-1,!1,t);let h=Dt(n,e,m,!0,t,d,f);if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{changed:R,key:y,doc:A}=Nd(r,u,Gi(l),{[pa(e.key,e.bucketVersion)]:h.key});if(R){r.stickyBucketAssignmentDocs=r.stickyBucketAssignmentDocs||{},r.stickyBucketAssignmentDocs[y]=A;let x=r.saveStickyBucketAssignmentDoc;oc(()=>x(A))}}return Fd(n,e,h),Ye(n,"In experiment",{id:i,variation:h.variationId}),h}function nr(e,t,n,r,i,a,o){let s={value:n,on:!!n,off:!n,source:r,ruleId:i||""};return a&&(s.experiment=a),o&&(s.experimentResult=o),r!=="override"&&VA(e,t,s),s}function qd(e,t){return en(rc(t.context),e,t.context.savedGroups||{})}function Ud(e,t){return e.some(n=>{let{hashValue:r}=tr(t.context,n.attribute);if(!r)return!0;let i=ia(n.seed,r,n.hashVersion||2);return i===null?!0:!n.ranges.some(a=>oa(i,a))})}function LA(e,t,n,r,i,a,o){if(!i&&a===void 0)return!0;if(!i&&a===0)return!1;let{hashValue:s}=tr(e.context,n,r);if(!s)return!1;let c=ia(t,s,o??2);return c===null?!1:i?oa(c,i):a!==void 0?c<=a:!0}function Dt(e,t,n,r,i,a,o){let s=!0;(n<0||n>=t.variations.length)&&(n=0,s=!1);let{hashAttribute:c,hashValue:u}=tr(e.context,t.hashAttribute,e.context.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0),l=t.meta?.[n]??{},m=t.variations[0];for(let[g,d]of t.variations.entries())if(g===n){m=d;break}let f={key:l.key||""+n,featureId:i,inExperiment:s,hashUsed:r,variationId:n,value:m,hashAttribute:c,hashValue:u,stickyBucketUsed:!!o};return l.name&&(f.name=l.name),a!==void 0&&(f.bucket=a),l.passthrough&&(f.passthrough=l.passthrough),f}function Bd(e,t){return t.hashAttribute+t.hashValue+e.key+t.variationId}/*!
|
|
1
|
+
"use strict";var Bo=Object.defineProperty;var Ey=Object.getOwnPropertyDescriptor;var Ry=Object.getOwnPropertyNames;var ky=Object.prototype.hasOwnProperty;var jy=(e,t,n)=>t in e?Bo(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Ty=(e,t)=>{for(var n in t)Bo(e,n,{get:t[n],enumerable:!0})},Ny=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ry(t))!ky.call(e,i)&&i!==n&&Bo(e,i,{get:()=>t[i],enumerable:!(r=Ey(t,i))||r.enumerable});return e};var Dy=e=>Ny(Bo({},"__esModule",{value:!0}),e);var qe=(e,t,n)=>jy(e,typeof t!="symbol"?t+"":t,n);var Lv={};Ty(Lv,{LongplayError:()=>b,createConfigurationSync:()=>Oy,createFeatureClient:()=>Ss,createFunnelProcess:()=>Cy,createLocalFunnelClient:()=>Py,createLongplayReactNative:()=>Sy});module.exports=Dy(Lv);var Vo=require("zod"),Fy=Vo.z.enum(["sandbox","live"]),Fe=Vo.z.object({projectId:Vo.z.string().min(1),environment:Fy}).strict();var Le=require("zod"),Vi=Le.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),Sl=Le.z.enum(["unknown","denied","provisional","granted"]),Il=Le.z.enum(["ios","android"]),Lo=Le.z.strictObject({installationId:Le.z.uuid(),publicKey:Le.z.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:Le.z.iso.datetime({offset:!0}),signature:Le.z.string().regex(/^[A-Za-z0-9_-]{86}$/)}),_s=Le.z.string().regex(/^[a-f0-9]{64}$/),vl=Lo.extend({sequence:Vi,platform:Il,credentialDigest:_s}),wl=Lo.extend({credentialDigest:_s}),Ol=Lo.extend({sequence:Vi,platform:Il}),zo=Lo.extend({sequence:Vi,credentialDigest:_s,connectionId:Le.z.uuid().nullable(),kind:Le.z.enum(["fcm_token","apns_token"]).nullable(),token:Le.z.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:Sl}),Pl=zo,Cl=zo.extend({challenge:Le.z.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),Es=Le.z.strictObject({requested:Le.z.literal(!0),expiresAt:Le.z.iso.datetime({offset:!0})}),Pr=Le.z.strictObject({installationId:Le.z.uuid(),bound:Le.z.boolean(),identitySeq:Vi,bindingGeneration:Vi,addressSeq:Le.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:Le.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:Le.z.uuid().nullable(),addressStatus:Le.z.enum(["active","invalid"]).nullable(),permission:Sl}),Rs=Le.z.strictObject({channel:Le.z.enum(["email","sms","voice","push"]),state:Le.z.enum(["unknown","allowed","denied"]),revision:Le.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:Le.z.iso.datetime({offset:!0}).nullable()}),Gv=Le.z.strictObject({state:Le.z.enum(["allowed","denied"]),revision:Le.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function _l(e,t,n){let r=["indiana_push_v1",e,t.projectId,t.environment,n.installationId,n.publicKey,n.issuedAt];e==="bind"?r.push(n.sequence,n.platform,n.credentialDigest):e==="detach"?r.push(n.sequence,n.platform):e==="read"?r.push(n.credentialDigest):r.push(n.sequence,n.credentialDigest,n.connectionId,n.kind,n.token,n.permission),e==="recovery_confirm"&&r.push(n.challenge);let i=JSON.stringify(r);if([...i].some(a=>a.charCodeAt(0)>127))throw new Error("Push proof fields must be ASCII");return Uint8Array.from(i,a=>a.charCodeAt(0))}var Ot=require("zod"),Gn=Ot.z.enum(["INVALID_PROTOCOL_VERSION","UNSUPPORTED_PROTOCOL_VERSION","PROTOCOL_RETIRED","UNAUTHENTICATED","FORBIDDEN","SCOPE_MISMATCH","INVALID_REQUEST","NOT_FOUND","CONFLICT","PAYLOAD_TOO_LARGE","RATE_LIMITED","SERVICE_UNAVAILABLE","NOT_CONFIGURED","CAPABILITY_UNAVAILABLE","INTERNAL_ERROR"]),Hv=Ot.z.enum([...Gn.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),Qv=Ot.z.enum([...Gn.options,"stale_revision"]),ks=Ot.z.enum(["fix_request","authenticate","check_permissions","check_scope","resolve_conflict","reload_state","retry_same_request","configure_integration","check_availability","upgrade_sdk","recover_operation","contact_support"]),js=Ot.z.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","IDENTITY_CONTEXT_CHANGED","CUSTOMER_BINDING_CONFLICT","RUN_CONTRACT_MISMATCH","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),Rl={INVALID_PROTOCOL_VERSION:{status:400,recovery:"fix_request"},UNSUPPORTED_PROTOCOL_VERSION:{status:400,recovery:"upgrade_sdk"},PROTOCOL_RETIRED:{status:410,recovery:"upgrade_sdk"},UNAUTHENTICATED:{status:401,recovery:"authenticate"},FORBIDDEN:{status:403,recovery:"check_permissions"},SCOPE_MISMATCH:{status:403,recovery:"check_scope"},INVALID_REQUEST:{status:400,recovery:"fix_request"},NOT_FOUND:{status:404,recovery:"fix_request"},CONFLICT:{status:409,recovery:"resolve_conflict"},PAYLOAD_TOO_LARGE:{status:413,recovery:"fix_request"},RATE_LIMITED:{status:429,recovery:"retry_same_request"},SERVICE_UNAVAILABLE:{status:503,recovery:"retry_same_request"},NOT_CONFIGURED:{status:501,recovery:"configure_integration"},CAPABILITY_UNAVAILABLE:{status:501,recovery:"check_availability"},INTERNAL_ERROR:{status:500,recovery:"recover_operation"}};var El={TIMEOUT:"recover_operation",NETWORK_ERROR:"recover_operation",HTTP_ERROR:"recover_operation",INVALID_RESPONSE:"recover_operation",NOT_IDENTIFIED:"authenticate",INVALID_TOKEN:"authenticate",INVALID_URL:"fix_request",INVALID_TIMEOUT:"fix_request",SERVER_ONLY:"fix_request",PROTOCOL_MISMATCH:"upgrade_sdk",IDENTITY_CHANGED:"reload_state",INVALID_STATE:"reload_state",EVENT_QUEUE_FULL:"retry_same_request",COMMAND_PENDING:"recover_operation",DECISION_PENDING:"recover_operation",DECISION_ACCEPTANCE_UNKNOWN:"recover_operation",RUN_RECONCILIATION_REQUIRED:"recover_operation",DECISION_FAILED:"contact_support",COMMAND_STORAGE_CONFLICT:"resolve_conflict",COMMAND_STORAGE_INVALID:"fix_request",CONFIGURATION_UNAVAILABLE:"check_availability",CONFIGURATION_EXPIRED:"reload_state",CONFIGURATION_CHANGED:"reload_state",CONFIGURATION_DISPOSED:"reload_state",UNSUPPORTED_SCHEMA:"upgrade_sdk",FUNNEL_STOPPED:"check_availability",PAYWALL_UNAVAILABLE:"check_availability",EVALUATION_MODE:"reload_state",SERVER_REQUIRED:"fix_request",STICKY_SAVE_FAILED:"retry_same_request",TRANSITION_LIMIT:"resolve_conflict",PRECONDITION_FAILED:"reload_state",PRODUCT_UNAVAILABLE:"fix_request",PURCHASE_HANDLER_REQUIRED:"fix_request",EVENT_HANDLER_REQUIRED:"fix_request",CLOSED:"fix_request",BRIDGE_UNAVAILABLE:"check_availability",INVALID_CONFIGURATION:"fix_request",NATIVE_OPERATION_FAILED:"contact_support",AI_PRICE_UNAVAILABLE:"fix_request",AI_USAGE_UNAVAILABLE:"recover_operation",AI_PROVIDER_ERROR:"check_availability",AI_BALANCE_REJECTED:"resolve_conflict"};function My(e,t){if(e==="CONFLICT"&&t===425)return{retryable:!0,recovery:"retry_same_request"};if(e==="CONFLICT"&&t===412)return{retryable:!1,recovery:"reload_state"};if(e==="INVALID_SERVER_RESPONSE")return{retryable:!1,recovery:"recover_operation"};if(e==="AMBIGUOUS_AUTHENTICATION")return{retryable:!1,recovery:"fix_request"};if(Object.hasOwn(El,e)){let r=El[e];return{retryable:r==="retry_same_request",recovery:r}}let n=Gn.safeParse(e);return n.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:Rl[n.data].recovery}:{retryable:!1,recovery:"contact_support"}}function kl(e,t){let n=Gn.safeParse(e);if(n.success)return e==="CONFLICT"?[409,412,425].includes(t):e==="SERVICE_UNAVAILABLE"?[408,502,503,504].includes(t):e==="INVALID_REQUEST"?[400,405,415,422].includes(t):e==="NOT_CONFIGURED"?[501,503].includes(t):Rl[n.data].status===t;let r={INVALID_SERVER_RESPONSE:[502],RESPONSE_TOO_LARGE:[502],AMBIGUOUS_AUTHENTICATION:[400],BROWSER_REQUIRED:[403],INVALID_REDIRECT_URI:[403],AUTHORIZATION_UNAVAILABLE:[400],UNREGISTERED_CLIENT:[403],MANAGEMENT_OPERATION_FAILED:[400,422,500]};return Object.hasOwn(r,e)&&(r[e]?.includes(t)??!1)}function qy(e,t=Date.now()){if(e===null)return;let n=e.trim();if(/^\d+$/.test(n)){let i=Number(n);return Number.isSafeInteger(i)?i:void 0}if(!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(n))return;let r=Date.parse(n);return Number.isFinite(r)?Math.max(0,Math.ceil((r-t)/1e3)):void 0}var jl=Ot.z.object({retryable:Ot.z.boolean(),recovery:ks,reason:js.optional(),retryAfterSeconds:Ot.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),Ts=Ot.z.object({requestId:Ot.z.uuid().optional(),error:Ot.z.object({code:Ot.z.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:Ot.z.string(),...jl.partial().shape})}),Jv=Ot.z.object({error:Ts.shape.error.extend({requestId:Ot.z.uuid().optional()})}),Zv=Ot.z.object({error:Ot.z.string(),code:Ot.z.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:Ot.z.uuid(),...jl.shape});function $o(e,t,n={}){let r=My(e,t),i=n.reason==="RESULT_UNKNOWN"?"recover_operation":n.recovery??r.recovery,a=r.retryable&&n.retryable!==!1&&i!=="recover_operation",o=a?qy(n.retryAfter??null):void 0;return{...r,retryable:a,recovery:i,...o===void 0?{}:{retryAfterSeconds:o},...n.reason?{reason:n.reason}:{}}}var Ns="X-Indiana-Protocol",Tl="X-Indiana-SDK-Version";var Ds={current:"0.10"};var Nl=require("zod"),Uy=["USD","EUR","CNY","GBP","JPY","CAD","AUD","NZD","CHF","HKD","SGD","KRW","INR","BRL","MXN","TWD","THB","IDR","MYR","PHP","VND","ZAR","AED","SAR","SEK","NOK","DKK","PLN","CZK","HUF","ILS","TRY","RON"],Ie=Nl.z.enum(Uy);var C=require("zod");var Vt=C.z.string().min(1).max(200),Jt=C.z.iso.datetime({offset:!0}),xt=C.z.number().int().nonnegative().max(1e8),Go=C.z.string().regex(/^[A-Z]{3}$/),By=["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"],Dl=C.z.enum(By),Fl=C.z.strictObject({priceId:C.z.uuid(),productVersionId:C.z.uuid(),productId:Vt,quantity:C.z.number().int().min(1).max(1e6),unitAmountMinor:xt,totalMinor:xt,interval:C.z.enum(["week","month","year","one_off"]),intervalCount:C.z.number().int().min(1).max(52),kind:C.z.enum(["fixed","prepaid","seat"]),tiers:C.z.strictObject({mode:C.z.enum(["graduated","volume"]),tiers:C.z.array(C.z.strictObject({upTo:C.z.number().int().positive().nullable(),unitAmountMinor:xt,flatAmountMinor:xt.optional()})).min(2).max(12)}).nullable()}),Vy=C.z.strictObject({grantId:C.z.uuid(),couponId:C.z.uuid(),amountMinor:xt,terms:C.z.discriminatedUnion("type",[C.z.strictObject({type:C.z.literal("percent"),percentOff:C.z.number().gt(0).max(100)}),C.z.strictObject({type:C.z.literal("amount"),amountOffMinor:xt,currency:Go})]),duration:C.z.discriminatedUnion("type",[C.z.strictObject({type:C.z.literal("once")}),C.z.strictObject({type:C.z.literal("forever")}),C.z.strictObject({type:C.z.literal("repeating"),months:C.z.number().int().min(1).max(36)})])}),Ms={provider:C.z.literal("merchant"),executor:C.z.literal("merchant"),operationId:C.z.uuid(),customerId:C.z.uuid(),configurationRevision:C.z.number().int().nonnegative(),connectionRevision:C.z.number().int().nonnegative(),currency:Go,expiresAt:Jt},Ko=C.z.strictObject({...Ms,type:C.z.literal("purchase"),mode:C.z.enum(["payment","subscription"]),lineItems:C.z.array(Fl).min(1).max(100),catalogAmountMinor:xt,discount:Vy.nullable(),trialPeriodDays:C.z.number().int().min(1).max(730).nullable(),automaticTax:C.z.boolean()}).refine(e=>e.lineItems.reduce((t,n)=>t+n.totalMinor,0)===e.catalogAmountMinor&&(!e.discount||e.discount.amountMinor<=e.catalogAmountMinor)&&new Set(e.lineItems.map(t=>t.priceId)).size===e.lineItems.length,"Purchase lines must retain the original total and unique Price identities"),Ho=C.z.strictObject({...Ms,type:C.z.literal("subscription_change"),subscriptionId:C.z.uuid(),merchantSubscriptionId:Vt,membershipId:C.z.uuid(),subscriptionAction:C.z.enum(["update","cancel","schedule","release"]),supersedesOperationId:C.z.uuid().nullable(),change:C.z.discriminatedUnion("type",[C.z.strictObject({type:C.z.literal("cancel")}),C.z.strictObject({type:C.z.literal("uncancel")}),C.z.strictObject({type:C.z.literal("plan"),productVersionId:C.z.uuid()}),C.z.strictObject({type:C.z.literal("seats"),licenseKey:Vt,quantity:C.z.number().int().nonnegative().max(1e6)}),C.z.strictObject({type:C.z.literal("quantity"),internal_feature_id:C.z.uuid(),quantity:C.z.number().int().nonnegative().max(1e6)}),C.z.strictObject({type:C.z.literal("billing_cycle"),billingCycleAnchor:C.z.union([C.z.literal("now"),C.z.number().int().positive()])})]),timing:C.z.enum(["immediate","renewal"]),effectiveAt:Jt,creditMinor:xt,debitMinor:xt,totalMinor:xt,discountMinor:xt,taxMinor:xt,proration:C.z.enum(["none","create_prorations","always_invoice"]),lineItems:C.z.array(Fl.extend({quantity:C.z.number().int().nonnegative().max(1e6)})).max(100),removePriceIds:C.z.array(C.z.uuid()).max(100)}),Qo=C.z.strictObject({...Ms,type:C.z.literal("refund"),invoiceId:C.z.uuid(),merchantInvoiceId:Vt,amountMinor:xt.refine(e=>e>0),mode:C.z.enum(["full","partial"]),entitlementAction:C.z.enum(["retain","revoke"]),cancelSubscriptions:C.z.array(Vt).max(100)}),Ml=C.z.discriminatedUnion("type",[Ko,Ho,Qo]);var Li=C.z.strictObject({phase:C.z.enum(["execution","payment","fulfillment","recording"]),code:Gn,reason:js.optional(),recovery:ks,retryable:C.z.boolean()}).refine(e=>e.reason!=="RESULT_UNKNOWN"||!e.retryable&&e.recovery==="recover_operation","Unknown financial effects require recovery of the original operation"),Fs={operationId:C.z.uuid(),customerId:C.z.uuid(),merchantExecutionId:Vt,fulfillmentStatus:C.z.enum(["not_started","pending","applied","failed","not_applicable"]),recordingStatus:C.z.enum(["not_ready","pending","accepted","failed"]),updatedAt:Jt,problem:Li.nullable(),pollAfterMs:C.z.number().int().min(1e3).max(6e4).nullable()},Cr=C.z.discriminatedUnion("type",[C.z.strictObject({...Fs,type:C.z.literal("purchase"),merchantOrderId:Vt.nullable(),paymentStatus:C.z.enum(["not_started","pending","succeeded","not_required","failed","expired","unknown"]),checkoutUrl:C.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),checkoutExpiresAt:Jt.nullable()}).refine(e=>!e.checkoutUrl||["not_started","pending"].includes(e.paymentStatus)&&e.checkoutExpiresAt!==null,"Only an unfinished original purchase may expose its checkout"),C.z.strictObject({...Fs,type:C.z.literal("subscription_change"),status:C.z.enum(["pending","scheduled","applied","failed","unknown"]),merchantSubscriptionId:Vt,scheduledFor:Jt.nullable()}).refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"A scheduled change retains its future effective time"),C.z.strictObject({...Fs,type:C.z.literal("refund"),status:C.z.enum(["pending","succeeded","failed","unknown"]),merchantRefundId:Vt.nullable()}).refine(e=>e.status!=="succeeded"||e.merchantRefundId!==null,"A successful refund retains its original merchant identity")]),ql=C.z.discriminatedUnion("lookup",[C.z.strictObject({lookup:C.z.literal("found"),operationId:C.z.uuid(),customerId:C.z.uuid(),execution:Cr,readAt:Jt}),C.z.strictObject({lookup:C.z.literal("not_received"),operationId:C.z.uuid(),customerId:C.z.uuid(),execution:C.z.null(),readAt:Jt})]).refine(e=>!e.execution||e.execution.operationId===e.operationId&&e.execution.customerId===e.customerId,"Lookup must retain the original Customer and operation"),qs=C.z.strictObject({merchantSubscriptionId:Vt,revision:C.z.number().int().positive(),status:C.z.enum(["incomplete","trialing","active","past_due","canceled","unpaid","paused","incomplete_expired"]),periodStartsAt:Jt,periodEndsAt:Jt,cancelAtPeriodEnd:C.z.boolean(),hasDiscounts:C.z.boolean(),items:C.z.array(C.z.strictObject({merchantItemId:Vt,priceId:C.z.uuid(),quantity:C.z.number().int().positive().max(1e6)})).min(1).max(100)}).refine(e=>Date.parse(e.periodEndsAt)>Date.parse(e.periodStartsAt)&&new Set(e.items.map(t=>t.priceId)).size===e.items.length,"Subscription periods and Price identities must be unambiguous"),Us=C.z.strictObject({merchantInvoiceId:Vt,currency:Go,subtotalMinor:xt,discountMinor:xt,taxMinor:xt,totalMinor:xt,paidMinor:xt,periodStartsAt:Jt.nullable(),periodEndsAt:Jt.nullable(),lines:C.z.array(C.z.strictObject({merchantLineId:Vt,priceId:C.z.uuid(),quantity:C.z.number().int().nonnegative().max(1e6),subtotalMinor:C.z.number().int().min(-1e8).max(1e8),discountMinor:xt,taxMinor:xt,totalMinor:C.z.number().int().min(-1e8).max(2e8),periodStartsAt:Jt.nullable(),periodEndsAt:Jt.nullable()}).refine(e=>e.subtotalMinor-e.discountMinor+e.taxMinor===e.totalMinor&&(e.subtotalMinor<0?e.discountMinor===0&&e.taxMinor===0:e.discountMinor<=e.subtotalMinor),"Invoice line amounts must retain the complete debit or credit")).min(1).max(100)}).refine(e=>e.subtotalMinor-e.discountMinor+e.taxMinor===e.totalMinor&&e.discountMinor<=e.subtotalMinor&&e.paidMinor===e.totalMinor&&new Set(e.lines.map(t=>t.merchantLineId)).size===e.lines.length&&e.lines.reduce((t,n)=>t+n.subtotalMinor,0)===e.subtotalMinor&&e.lines.reduce((t,n)=>t+n.discountMinor,0)===e.discountMinor&&e.lines.reduce((t,n)=>t+n.taxMinor,0)===e.taxMinor&&e.lines.reduce((t,n)=>t+n.totalMinor,0)===e.totalMinor,"A paid Invoice retains the complete financial amounts"),Zt={eventId:C.z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),customerId:C.z.uuid(),occurredAt:Jt},Ul=C.z.enum(["purchase.completed","purchase.closed","subscription.observed","subscription.change.completed","invoice.paid","refund.updated"]),Ly=C.z.strictObject({...Zt,type:C.z.literal("purchase.completed"),operationId:C.z.uuid(),merchantOrderId:Vt,paymentStatus:C.z.enum(["paid","trialing","no_payment_required"]),invoice:Us.nullable(),subscription:qs.nullable()}),zy=C.z.strictObject({...Zt,type:C.z.literal("purchase.closed"),operationId:C.z.uuid(),status:C.z.enum(["failed","expired","canceled"])}),$y=C.z.strictObject({...Zt,type:C.z.literal("subscription.observed"),operationId:C.z.uuid().nullable(),subscription:qs}),Gy=C.z.strictObject({...Zt,type:C.z.literal("subscription.change.completed"),operationId:C.z.uuid(),status:C.z.enum(["scheduled","applied"]),scheduledFor:Jt.nullable(),subscription:qs,invoice:Us.nullable()}),Ky=C.z.strictObject({...Zt,type:C.z.literal("invoice.paid"),merchantSubscriptionId:Vt.nullable(),invoice:Us}),Hy=C.z.strictObject({...Zt,type:C.z.literal("refund.updated"),operationId:C.z.uuid().nullable(),merchantInvoiceId:Vt.optional(),merchantRefundId:Vt,status:C.z.enum(["pending","succeeded","failed"]),amountMinor:xt.refine(e=>e>0),currency:Go}),Bl=[Ly.refine(e=>e.paymentStatus!=="paid"||e.invoice!==null,"A paid purchase includes its Invoice"),zy,$y,Gy.refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"Scheduled and applied changes are distinct facts"),Ky,Hy.refine(e=>e.operationId!==null||e.merchantInvoiceId!==void 0,"A native refund names its Invoice")];var T=require("zod");var Yn=require("zod"),Nt=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,Xn=Yn.z.object({customerId:Yn.z.uuid(),sessionId:Yn.z.uuid(),accessToken:Yn.z.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),refreshToken:Yn.z.string().regex(/^gg_rt_[A-Za-z0-9_-]{43}$/),expiresAt:Yn.z.iso.datetime(),refreshExpiresAt:Yn.z.iso.datetime()});var Vs=3;var Qy=["session","catalog","customer_commerce","presentation","presentation_events","purchases","operation_status","billing_records","subscription_changes","refunds"],Jy=T.z.enum(Qy);var Zy=T.z.enum(["bridge.ping","bridge.describe","session.create","catalog.read","customer.commerce.read","presentation.resolve","presentation.report","purchase.execute","operation.read","subscription.change","refund.execute"]),Ll=T.z.string().regex(/^[A-Za-z0-9_-]{1,64}$/),Wy=T.z.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(e=>"AEIMQUYcgkosw048".includes(e.at(-1)),"Use canonical base64url for a 32-byte key"),Yy=T.z.strictObject({keyId:Ll,signingSecret:Wy}),Xy=T.z.string().max(300).superRefine((e,t)=>{try{let n=new URL(e);if(n.protocol!=="https:"||n.username||n.password||n.search||n.hash||n.pathname!=="/"||n.port&&n.port!=="443"||!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.[a-z]{2,63}$/.test(n.hostname)||/(?:^|\.)(?:localhost|local|internal)$/.test(n.hostname))throw new Error("invalid origin")}catch{t.addIssue({code:"custom",message:"Use an exact public HTTPS origin"})}}).transform(e=>new URL(e).origin),zl=T.z.array(Jy).max(10).refine(e=>new Set(e).size===e.length,"Capabilities must be unique"),$l=T.z.strictObject({bridgeVersion:T.z.literal(Vs),projectId:T.z.uuid(),environmentId:T.z.uuid(),environment:T.z.enum(["sandbox","live"]),capabilities:zl,catalog:T.z.enum(["endpoint","static","none"]),billingEvents:T.z.array(Ul).max(6),profiles:T.z.array(Dl).max(32).refine(e=>new Set(e).size===e.length,"Profiles must be unique")}).superRefine((e,t)=>{let n=r=>e.capabilities.includes(r);n("catalog")!==(e.catalog!=="none")&&t.addIssue({code:"custom",path:["catalog"],message:"Catalog declaration differs from its capability"}),(n("billing_records")!==e.billingEvents.length>0||new Set(e.billingEvents).size!==e.billingEvents.length)&&t.addIssue({code:"custom",path:["billingEvents"],message:"Declare the unique supported billing events"})}),Gl=T.z.strictObject({origin:Xy,requiredCapabilities:zl}),eA=T.z.strictObject({revision:T.z.number().int().nonnegative(),checkedAt:T.z.iso.datetime(),outcome:T.z.enum(["valid","unreachable","invalid","scope_mismatch","authentication_failed","credentials_missing"]),diagnostics:T.z.strictObject({ping:T.z.enum(["passed","failed","not_checked"]),authentication:T.z.enum(["passed","failed","not_checked"]),catalog:T.z.enum(["passed","failed","not_checked","static","unsupported"])}),manifest:$l.nullable()}).superRefine((e,t)=>{e.outcome==="valid"!=(e.manifest!==null)&&t.addIssue({code:"custom",path:["manifest"],message:"Only a valid declaration carries a manifest"})}),ow=T.z.strictObject({projectId:T.z.uuid(),environmentId:T.z.uuid(),environment:T.z.enum(["sandbox","live"]),execution:T.z.enum(["indiana","record_only"]),accountId:T.z.string().nullable(),revision:T.z.number().int().nonnegative(),authentication:T.z.strictObject({keyId:Ll}).nullable(),secretStoreConfigured:T.z.boolean().optional(),connection:Gl.nullable(),check:eA.nullable()});var Vl=T.z.strictObject({projectId:T.z.uuid(),environmentId:T.z.uuid()}),aw=T.z.discriminatedUnion("action",[Vl.extend({action:T.z.literal("save"),revision:T.z.number().int().nonnegative(),connection:Gl,authentication:Yy.optional()}),Vl.extend({action:T.z.literal("check"),revision:T.z.number().int().nonnegative()})]),Ls=T.z.strictObject({projectId:T.z.uuid(),environmentId:T.z.uuid(),environment:T.z.enum(["sandbox","live"])});var tA=T.z.strictObject({nativeUserId:T.z.string().min(1).max(128),session:Xn.strict()}),nA=T.z.strictObject({nativeUserId:T.z.string().min(1).max(128),presentation:T.z.strictObject({customerId:T.z.uuid(),decisionId:T.z.uuid(),offeringVersionId:T.z.uuid(),paywallVersionId:T.z.uuid(),variant:T.z.string().min(1).max(128)}).nullable()}),rA=T.z.strictObject({decisionId:T.z.uuid(),eventId:T.z.uuid()}),Jo=T.z.strictObject({operationId:T.z.uuid(),customerId:T.z.uuid()}),Zo=T.z.strictObject({scope:Ls,operationId:T.z.uuid(),customerId:T.z.uuid(),confirmedAt:T.z.iso.datetime({offset:!0}).nullable(),initialExecutionAllowed:T.z.boolean(),instruction:Ml}).refine(e=>e.operationId===e.instruction.operationId&&e.customerId===e.instruction.customerId,"Authority must refer to the original Customer and operation"),Bs=Cr,Kn=T.z.string().min(1).max(120),iA=T.z.string().regex(/^-?[0-9]+(?:\.[0-9]{1,6})?$/),oA=T.z.strictObject({revision:Kn,updatedAt:T.z.iso.datetime(),provider:T.z.literal("merchant"),items:T.z.array(T.z.strictObject({merchantProductId:Kn,productVersionId:T.z.uuid(),name:T.z.string().min(1).max(255),kind:T.z.enum(["subscription","credit_pack"]),merchantPriceId:Kn,currency:T.z.string().regex(/^[a-z]{3}$/),amountMinor:T.z.number().int().nonnegative().max(1e8),interval:T.z.enum(["one_time","month","year"]),intervalCount:T.z.literal(1),includedCredits:T.z.string().regex(/^[0-9]{1,18}(?:\.[0-9]{1,6})?$/),creditReset:T.z.enum(["none","month"]),creditPolicyId:Kn,available:T.z.boolean()}).superRefine((e,t)=>{(e.kind==="credit_pack"&&(e.interval!=="one_time"||e.creditReset!=="none")||e.kind==="subscription"&&e.interval==="one_time"||e.available&&e.amountMinor===0)&&t.addIssue({code:"custom",message:"Unsupported version 1 catalog terms"})})).max(500)}),aA=T.z.strictObject({customerId:T.z.uuid(),revision:T.z.string().min(1).max(128),observedAt:T.z.iso.datetime(),subscriptions:T.z.array(T.z.strictObject({merchantSubscriptionId:Kn,merchantProductId:Kn,productVersionId:T.z.uuid().nullable(),status:T.z.enum(["active","trialing","past_due","cancelled","expired"]),currentPeriodStartsAt:T.z.iso.datetime().nullable(),currentPeriodEndsAt:T.z.iso.datetime().nullable(),cancelAtPeriodEnd:T.z.boolean(),scheduledChange:T.z.strictObject({effectiveAt:T.z.iso.datetime(),merchantProductId:Kn}).nullable()})).max(100),purchaseHistory:T.z.strictObject({complete:T.z.boolean(),hasPaidPurchase:T.z.boolean(),lastPaidAt:T.z.iso.datetime().nullable()}),balances:T.z.array(T.z.strictObject({bucketId:Kn,key:Kn,available:iA,expiresAt:T.z.iso.datetime().nullable(),nextResetAt:T.z.iso.datetime().nullable()})).max(100)}),sw=T.z.strictObject({bridgeVersion:T.z.literal(Vs),requestId:T.z.uuid(),command:T.z.string().min(1).max(64),scope:Ls,error:T.z.strictObject({code:T.z.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:T.z.string().min(1).max(500),retryable:T.z.boolean(),recovery:T.z.string().min(1).max(80)})}),zi=T.z.strictObject({}),sA={"bridge.ping":T.z.strictObject({challenge:T.z.uuid()}),"bridge.describe":zi,"session.create":zi,"catalog.read":zi,"customer.commerce.read":zi,"presentation.resolve":zi,"presentation.report":rA,"purchase.execute":Jo,"operation.read":Jo,"subscription.change":Jo,"refund.execute":Jo},cw={"bridge.ping":T.z.strictObject({challenge:T.z.uuid()}),"bridge.describe":$l,"session.create":tA,"catalog.read":oA,"customer.commerce.read":aA,"presentation.resolve":nA,"presentation.report":T.z.strictObject({queued:T.z.literal(!0)}),"purchase.execute":Bs,"operation.read":ql,"subscription.change":Bs,"refund.execute":Bs},uw=T.z.strictObject({bridgeVersion:T.z.literal(Vs),requestId:T.z.uuid(),scope:Ls,command:Zy,data:T.z.unknown()}).superRefine((e,t)=>{sA[e.command].safeParse(e.data).success||t.addIssue({code:"custom",path:["data"],message:"Invalid command data"})});var _r=require("zod");var Wo=_r.z.string().trim().min(1).max(64).regex(/^[a-z][a-z0-9_]*$/,"ID \u4F7F\u7528\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u4E0B\u5212\u7EBF\uFF0C\u5E76\u4EE5\u5B57\u6BCD\u5F00\u5934"),pw=_r.z.object({amountCents:_r.z.number().int().min(0).max(1e8),currency:Ie,interval:_r.z.enum(["free","month","year"]),currencyOptions:_r.z.partialRecord(Ie,_r.z.number().int().min(1).max(1e8)).optional()}).refine(e=>e.interval==="free"?e.amountCents===0:e.amountCents>0,"\u514D\u8D39\u5957\u9910\u91D1\u989D\u5FC5\u987B\u4E3A 0\uFF0C\u4ED8\u8D39\u91D1\u989D\u5FC5\u987B\u5927\u4E8E 0").refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency)&&(e.interval!=="free"||Object.keys(e.currencyOptions).length===0),"\u9644\u52A0\u5E01\u79CD\u4E0D\u80FD\u91CD\u590D\u9ED8\u8BA4\u5E01\u79CD\uFF1B\u514D\u8D39\u5957\u9910\u4E0D\u8BBE\u7F6E\u9644\u52A0\u4EF7\u683C");var F=require("zod"),cA=F.z.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Ql=F.z.enum(["single_use","continuous_use"]),zs=F.z.record(F.z.string(),F.z.union([F.z.string(),F.z.number(),F.z.boolean()]).transform(String).pipe(F.z.string())),Kl=F.z.string().min(1).max(64).refine(e=>!e.includes("::")),Jl={credit_amount:F.z.number(),tier_behavior:F.z.never().optional(),tiers:F.z.never().optional()},Zl={credit_amount:F.z.never().optional(),tier_behavior:F.z.literal("graduated"),tiers:F.z.array(F.z.strictObject({to:F.z.union([F.z.number(),F.z.literal("inf")]),credit_amount:F.z.number()}))},uA=F.z.union([F.z.strictObject({match:zs,priority:F.z.number().int().optional(),...Jl}),F.z.strictObject({match:zs,priority:F.z.number().int().optional(),...Zl})]),lA=F.z.strictObject({match:zs,factor:F.z.number().positive().optional(),add:F.z.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),Hl={metered_feature_id:F.z.string(),feature_amount:F.z.number().optional(),dimensions:F.z.record(Kl,uA).optional(),multipliers:F.z.record(Kl,lA).optional()},$s=F.z.union([F.z.strictObject({...Hl,...Jl}),F.z.strictObject({...Hl,...Zl})]),Xo=F.z.number().min(-100),Wl=F.z.record(F.z.string(),F.z.strictObject({markup:Xo})).nullish(),ea=F.z.record(F.z.string().regex(/.+\/.+/),F.z.strictObject({markup:Xo.optional(),input_cost:F.z.number().min(0).optional(),output_cost:F.z.number().min(0).optional()})).nullish(),dA=F.z.strictObject({default_markup:Xo.optional(),provider_markups:Wl,model_markups:ea}),fw=F.z.strictObject({schema:F.z.array($s).optional(),markups:dA.optional()}),pA=F.z.strictObject({filters:F.z.array(F.z.strictObject({property:F.z.string(),operator:F.z.string(),value:F.z.array(F.z.string())})),aggregate:F.z.strictObject({type:F.z.string(),property:F.z.string().nullable()}),usage_type:Ql}),Yl=F.z.strictObject({schema:F.z.array($s).min(1).refine(e=>new Set(e.map(t=>t.metered_feature_id)).size===e.length,"Credit rates must name each metered feature once"),invoice_credit:F.z.boolean().optional(),usage_type:Ql.default("single_use").overwrite(()=>"single_use"),default_markup:Xo.optional(),provider_markups:Wl}),Gs=Yl.safeExtend({schema:F.z.array($s).length(0)}),Yo={id:cA,name:F.z.string().min(1),display:F.z.strictObject({singular:F.z.string().optional(),plural:F.z.string().optional()}).nullish(),event_names:F.z.array(F.z.string()).default([]),model_markups:ea,stripe_meter:F.z.strictObject({id:F.z.string(),event_name:F.z.string()}).nullish(),stripe_product_id:F.z.string().nullish()},Ks=e=>F.z.discriminatedUnion("type",[F.z.strictObject({...Yo,...e,type:F.z.literal("boolean"),config:F.z.null()}),F.z.strictObject({...Yo,...e,type:F.z.literal("metered"),config:pA}),F.z.strictObject({...Yo,...e,type:F.z.literal("credit_system"),config:Yl}),F.z.strictObject({...Yo,...e,type:F.z.literal("ai_credit_system"),config:Gs})]),gw=Ks({}),mA=F.z.strictObject({id:F.z.boolean(),type:F.z.boolean(),usage_type:F.z.boolean()}),fA={internal_id:F.z.uuid(),org_id:F.z.uuid(),created_at:F.z.number(),env:F.z.enum(["sandbox","live"]),archived:F.z.boolean(),project_id:F.z.uuid(),environment_id:F.z.uuid(),revision:F.z.number().int().nonnegative(),update_rules:mA},Xl=Ks(fA),hw=F.z.strictObject({rows:F.z.array(Xl).max(200),nextCursor:F.z.uuid().nullable()}),yw=F.z.strictObject({features:F.z.array(Xl).max(500),limited:F.z.boolean()}),Aw=F.z.union([Ks({action:F.z.literal("save"),internal_id:F.z.uuid().nullable(),revision:F.z.number().int().nonnegative()}),F.z.strictObject({action:F.z.enum(["archive","restore","delete"]),internal_id:F.z.uuid(),revision:F.z.number().int().nonnegative()})]);var kr=require("zod");var lt=require("zod"),Wt=lt.z.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),xe=lt.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),ta=lt.z.string().regex(/^-?(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>{let t=e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e;return t==="-0"?"0":t}),Hs=xe.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),ed=lt.z.string().min(1).max(64),Er=lt.z.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),td=lt.z.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),Pt=lt.z.record(ed,lt.z.union([lt.z.string().max(120),lt.z.number().finite(),lt.z.boolean()])).refine(e=>Object.keys(e).length<=16,"\u6700\u591A 16 \u4E2A\u8BA1\u4EF7\u5C5E\u6027").transform(e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,String(n)]))),nd=lt.z.record(ed,lt.z.union([lt.z.string().max(120),lt.z.number().finite(),lt.z.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),oi=e=>{let t=e.startsWith("-");t&&(e=e.slice(1));let[n,r=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");let i=BigInt(n)*BigInt("1000000")+BigInt(r.padEnd(6,"0"));return t?-i:i},rd=lt.z.array(lt.z.object({upTo:Hs.nullable(),cost:xe}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let r=e[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&oi(t.upTo)>oi(r))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),gA=lt.z.object({key:td,match:nd,priority:lt.z.number().int().default(0),cost:xe.optional(),tiers:rd.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),hA=lt.z.object({key:td,match:nd,factor:Hs.optional(),add:ta.optional()}).strict().refine(e=>e.factor!==void 0||e.add!==void 0,"A multiplier needs a factor or an add").transform(e=>({...e,factor:e.factor??"1",add:e.add??"0"})),yA=lt.z.object({units:Hs.default("1"),cost:xe,tiers:rd.optional(),dimensions:lt.z.array(gA).max(12).optional(),multipliers:lt.z.array(hA).max(4).optional()}).strict().superRefine((e,t)=>{let n=e.dimensions??[],r=e.multipliers??[];(new Set(n.map(o=>o.key)).size!==n.length||new Set(r.map(o=>o.key)).size!==r.length)&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u548C\u500D\u7387\u7684 ID \u4E0D\u80FD\u91CD\u590D"});for(let[o,s]of n.entries())for(let c of n.slice(o+1))Object.keys(s.match).length===Object.keys(c.match).length&&s.priority===c.priority&&!Object.keys(s.match).some(u=>c.match[u]!==void 0&&c.match[u]!==s.match[u])&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u53EF\u80FD\u540C\u65F6\u5339\u914D\uFF0C\u8BF7\u8C03\u6574\u4F18\u5148\u7EA7"});let i=[e.cost,...(e.tiers??[]).map(o=>o.cost),...n.flatMap(o=>[...o.cost===void 0?[]:[o.cost],...(o.tiers??[]).map(s=>s.cost)])],a=oi(e.units);for(let o of i)for(let s=0;s<1<<r.length;s++){let c=r.filter((d,h)=>s&1<<h);if(c.some((d,h)=>c.slice(h+1).some(R=>Object.keys(d.match).some(y=>R.match[y]!==void 0&&R.match[y]!==d.match[y]))))continue;let u=oi(o),l=BigInt("1"),m=BigInt("0");for(let[d,h]of r.entries())s&1<<d&&(u*=oi(h.factor??"1"),l*=BigInt("1000000"),m+=oi(h.add??"0"));let f=(u+m*l)*BigInt("1000000"),g=l*a;(f<BigInt("0")||f%g!==BigInt("0")||f/g>BigInt("999999999999999999"))&&t.addIssue({code:"custom",message:"\u6BCF\u4E2A\u4E1A\u52A1\u5355\u4F4D\u7684\u6700\u7EC8\u5355\u4EF7\u5FC5\u987B\u975E\u8D1F\u3001\u5728\u8303\u56F4\u5185\u4E14\u80FD\u7CBE\u786E\u8868\u793A\u4E3A\u6700\u591A 6 \u4F4D\u5C0F\u6570"})}}),xw=yA.safeExtend({featureKey:Er});var Rr=require("zod"),id=Rr.z.number().int().min(0).max(1e8),$i=Rr.z.strictObject({kind:Rr.z.enum(["graduated","volume"]),tiers:Rr.z.array(Rr.z.strictObject({upTo:Rr.z.number().int().min(1).max(1e4).nullable(),unitAmountMinor:id,flatAmountMinor:id.optional()})).min(1).max(12)}).refine(e=>e.tiers.at(-1)?.upTo===null&&e.tiers.slice(0,-1).every((t,n)=>{let r=e.tiers[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&t.upTo>r)}),"Tier ceilings must increase and end unbounded").refine(e=>!e.tiers.some(t=>(t.flatAmountMinor??0)>0)||e.kind==="volume"&&e.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers");function Qs(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let n=e.pricing?$i.parse(e.pricing):void 0;if(t===0)return 0;let r=0n,i=0;if(!n)r=BigInt(e.amountMinor)*BigInt(t);else for(let a of n.tiers){let o=a.upTo??1e4;if(n.kind==="volume"){if(t<=o){r=BigInt(t)*BigInt(a.unitAmountMinor)+BigInt(a.flatAmountMinor??0);break}}else t>i&&(r+=BigInt(Math.min(t,o)-i)*BigInt(a.unitAmountMinor));i=o}if(r>200000000n)throw new Error("Purchased price exceeds the payment amount limit");return Number(r)}function na(e){return Qs({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}var AA=xe.refine(e=>/[1-9]/.test(e)),ra=kr.z.strictObject({units:AA,prices:kr.z.array(kr.z.strictObject({currency:Ie,amountMinor:kr.z.number().int().min(0).max(1e8),pricing:$i.optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.currency)).size===e.length,"Currencies must be unique").refine(e=>e.every(t=>!t.pricing||t.amountMinor===0),"Tiered prices specify their rates in tiers"),minimumQuantity:kr.z.number().int().min(0).max(1e4),maximumQuantity:kr.z.number().int().min(0).max(1e4)}).refine(e=>e.maximumQuantity>=e.minimumQuantity,"Purchased quantity must fit its published bounds").refine(e=>{try{for(let t of e.prices)for(let n of[e.maximumQuantity,...t.pricing?.tiers.flatMap(r=>r.upTo===null?[]:[r.upTo,r.upTo+1])??[]])n<=e.maximumQuantity&&Qs({amountMinor:t.amountMinor,...t.pricing===void 0?{}:{pricing:t.pricing}},n);return!0}catch{return!1}},"Every purchasable quantity must fit the payment amount limit");function od(e){if(!/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/.test(e))throw new Error("Invalid quantity");let[t,n=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");return BigInt(t)*1000000n+BigInt(n.padEnd(6,"0"))}function ad(e,t,n){if(!Number.isSafeInteger(n)||n<0||n>1e4)throw new Error("Invalid purchased quantity");let r=od(e)+od(t)*BigInt(n);if(r>999999999999999999n)throw new Error("Purchased allowance exceeds the ledger quantity limit");let i=(r%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return(r/1000000n).toString()+(i?"."+i:"")}var S=require("zod");var ee=require("zod");var Rt=require("zod");var N=require("zod");function sd(e){let t=2166136261,n=e.length;for(let r=0;r<n;r++)t^=e.charCodeAt(r),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);return t>>>0}function ia(e,t,n){return n===2?sd(sd(e+t)+"")%1e4/1e4:null}function bA(e){return e<=0?[]:new Array(e).fill(1/e)}function oa(e,t){return e>=t[0]&&e<t[1]}function cd(e,t){for(let[n,r]of t.entries())if(oa(e,r))return n;return-1}function ud(e,t,n){t=t===void 0?1:t,t<0?t=0:t>1&&(t=1);let r=bA(e);n=n||r,n.length!==e&&(n=r);let i=n.reduce((s,c)=>c+s,0);(i<.99||i>1.01)&&(n=r);let a=0,o=t;return n.map(s=>{let c=a;return a+=s,[c,c+o*s]})}function ld(e,t,n){if(!t)return null;let r=t.split("?")[1];if(!r)return null;let a=r.replace(/#.*/,"").split("&").map(o=>o.split("=",2)).filter(([o])=>o===e).map(([,o])=>o===void 0?NaN:parseInt(o))[0];return a!==void 0&&a>=0&&a<n?a:null}function dd(e){try{return e()}catch{return!1}}function Gi(e){return typeof e=="string"?e:JSON.stringify(e)}function cn(e){typeof e=="number"&&(e=e+""),(!e||typeof e!="string")&&(e="0");let t=e.replace(/(^v|\+.*$)/g,"").split(/[-.]/);return t.length===3&&t.push("~"),t.map(n=>n.match(/^[0-9]+$/)?n.padStart(5," "):n).join("-")}function xA(e){try{let t=e.replace(/([^\\])\//g,"$1\\/");return new RegExp(t)}catch{return}}function pd(e,t){if(!t.length)return!1;let n=!1,r=!1;for(let i of t){let a=vA(e,i.type,i.pattern);if(i.include===!1){if(a)return!1}else n=!0,a&&(r=!0)}return r||!n}function SA(e,t,n){try{let r=t.replace(/[*.+?^${}()|[\]\\]/g,"\\$&").replace(/_____/g,".*");return n&&(r="\\/?"+r.replace(/(^\/|\/$)/g,"")+"\\/?"),new RegExp("^"+r+"$","i").test(e)}catch{return!1}}function IA(e,t){try{let n=new URL(t.replace(/^([^:/?]*)\./i,"https://$1.").replace(/\*/g,"_____"),"https://_____"),r=[[e.host,n.host,!1],[e.pathname,n.pathname,!0]];return n.hash&&r.push([e.hash,n.hash,!1]),n.searchParams.forEach((i,a)=>{r.push([e.searchParams.get(a)||"",i,!1])}),!r.some(i=>!SA(i[0],i[1],i[2]))}catch{return!1}}function vA(e,t,n){try{let r=new URL(e,"https://_");if(t==="regex"){let i=xA(n);return i?i.test(r.href)||i.test(r.href.substring(r.origin.length)):!1}else if(t==="simple")return IA(r,n);return!1}catch{return!1}}function Js(e){for(let n of["namespace","status","url","groups"])if(Object.hasOwn(e,n))throw new TypeError(`Retired experiment field: ${n}`);let t=e;if(t.hashVersion!==void 0&&t.hashVersion!==2)throw new TypeError("Only hash version 2 is supported");if(t.filters?.some(n=>n.hashVersion!==2))throw new TypeError("Only hash version 2 is supported")}function aa(e){for(let t of Object.values(e)){if(Array.isArray(t))throw new TypeError("Saved groups require typed list or condition entries");if(t&&Object.hasOwn(t,"useEmptyListGroup"))throw new TypeError("Retired saved group field: useEmptyListGroup")}}function md(e){for(let t of["overrides","groups"])if(Object.hasOwn(e,t))throw new TypeError(`Retired evaluation context field: ${t}`);aa(e.savedGroups??{})}var wA=e=>e/2**32|0,OA=e=>e>>>0;function fd(e,t,n,r){let i=wA(n),a=OA(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function gd(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var Zs=e=>e?`"${e}" `:"";function PA(e,t=""){if(typeof e!="number")throw new TypeError(Zs(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(Zs(t)+"expected integer >= 0, got "+e);return e}function sa(e,t,n=""){if(gd(e)&&(t===void 0||e.length===t))return e;t!==void 0&&PA(t,"length");let r=gd(e),i=t!==void 0?` of length ${t}`:"",a=r?`length=${e.length}`:`type=${typeof e}`,o=Zs(n)+"expected Uint8Array"+i+", got "+a;throw r?new RangeError(o):new TypeError(o)}var CA=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},hd=(e,t)=>{CA(e,t);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function Ws(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function yd(e,t){sa(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function Ys(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ca(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function vn(e,t){return e<<32-t|e>>>t}var _A=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",EA=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function ai(e){if(sa(e),_A)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=EA[e[n]];return t}function RA(e,t,n="opts"){return hd(e,"defaults"),t!==void 0&&hd(t,n),Object.assign(Object.create(null),e,t)}function Ad(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=RA({},t,"info");let n=(i,a)=>e(a).update(i).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=i=>e(i),Object.assign(n,t),Object.freeze(n)}var bd=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function xd(e,t,n){return e&t^~e&n}function Sd(e,t,n){return e&t^e&n^t&n}var ua=class{constructor(t,n,r,i){qe(this,"blockLen");qe(this,"outputLen");qe(this,"canXOF",!1);qe(this,"padOffset");qe(this,"isLE");qe(this,"buffer");qe(this,"view");qe(this,"finished",!1);qe(this,"length",0);qe(this,"pos",0);qe(this,"destroyed",!1);this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(t),this.view=ca(this.buffer)}update(t){Ws(this),sa(t);let{view:n,buffer:r,blockLen:i}=this,a=t.length,o=!1;for(let s=0;s<a;){let c=Math.min(i-this.pos,a-s);if(c===i){let u=ca(t);for(;i<=a-s;s+=i)this.process(u,s);o=!0;continue}r.set(s===0&&c===a?t:t.subarray(s,s+c),this.pos),this.pos+=c,s+=c,this.pos===i&&(this.process(n,0),this.pos=0,o=!0)}return this.length+=t.length,o&&this.roundClean(),this}digestInto(t){Ws(this),yd(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:i,isLE:a}=this,{pos:o}=this;n[o++]=128,n.fill(0,o),this.padOffset>i-o&&(this.process(r,0),n.fill(0)),fd(r,i-8,this.length*8,a),this.process(r,0),this.roundClean();let s=t===n?r:ca(t),c=this.outputLen,u=c/4,l=this.get();if(c%4||u>l.length)throw new Error("invalid outputLen");for(let m=0;m<u;m++)s.setUint32(4*m,l[m],a)}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneIntoMeta(t){let{buffer:n,length:r,finished:i,destroyed:a,pos:o}=this;return t.destroyed=a,t.finished=i,t.length=r,t.pos=o,o&&t.buffer.set(n),t}clone(){return this._cloneInto()}},Id=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var kA=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),er=new Uint32Array(64),Xs=class extends ua{constructor(n,r){super(64,n,8,!1);qe(this,"A",0);qe(this,"B",0);qe(this,"C",0);qe(this,"D",0);qe(this,"E",0);qe(this,"F",0);qe(this,"G",0);qe(this,"H",0);this.A=r[0]|0,this.B=r[1]|0,this.C=r[2]|0,this.D=r[3]|0,this.E=r[4]|0,this.F=r[5]|0,this.G=r[6]|0,this.H=r[7]|0}get(){let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:u}=this;return[n,r,i,a,o,s,c,u]}set(n,r,i,a,o,s,c,u){this.A=n|0,this.B=r|0,this.C=i|0,this.D=a|0,this.E=o|0,this.F=s|0,this.G=c|0,this.H=u|0}_cloneInto(n){return(n||(n=new this.constructor)).set(...this.get()),this._cloneIntoMeta(n)}process(n,r){for(let f=0;f<16;f++,r+=4)er[f]=n.getUint32(r,!1);for(let f=16;f<64;f++){let g=er[f-15],d=er[f-2],h=vn(g,7)^vn(g,18)^g>>>3,R=vn(d,17)^vn(d,19)^d>>>10;er[f]=R+er[f-7]+h+er[f-16]|0}let{A:i,B:a,C:o,D:s,E:c,F:u,G:l,H:m}=this;for(let f=0;f<64;f++){let g=vn(c,6)^vn(c,11)^vn(c,25),d=m+g+xd(c,u,l)+kA[f]+er[f]|0,R=(vn(i,2)^vn(i,13)^vn(i,22))+Sd(i,a,o)|0;m=l,l=u,u=c,c=s+d|0,s=o,o=a,a=i,i=d+R|0}i=i+this.A|0,a=a+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,u=u+this.F|0,l=l+this.G|0,m=m+this.H|0,this.set(i,a,o,s,c,u,l,m)}roundClean(){Ys(er)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Ys(this.buffer)}},ec=class extends Xs{constructor(){super(32,Id)}};var si=Ad(()=>new ec,bd(1));var vd=new Map,tc=32,wd=new WeakMap,Od=new WeakMap;function jA(e){return ai(si(new TextEncoder().encode(String(e))))}var da=e=>Array.isArray(e)?e.map(da):typeof e=="string"||typeof e=="number"?jA(e):null,la=e=>typeof e=="string"?e.toLowerCase():e;function Rd(e){let t=wd.get(e);return t||(t=new Set(e),wd.set(e,t)),t}function TA(e){let t=Od.get(e);return t||(t=new Set(e.map(la)),Od.set(e,t)),t}function ci(e){aa(e);for(let t of Object.values(e)){let n=t?.type==="list"||t?.type==="hashed"?t.values:null;n&&n.length>=tc&&Rd(n)}return e}function en(e,t,n,r){n=n||{},r||aa(n),r=r||new Set;for(let[i,a]of Object.entries(t))switch(i){case"$or":if(!Ed(e,a,n,r))return!1;break;case"$nor":if(Ed(e,a,n,r))return!1;break;case"$and":if(!qA(e,a,n,r))return!1;break;case"$not":if(en(e,a,n,r))return!1;break;case"$savedGroup":if(!NA(e,a,n,r))return!1;break;default:if(!Ki(a,kd(e,i),n,!1,r))return!1}return!0}function NA(e,t,n,r){if(!t||typeof t!="object"||Array.isArray(t))return!1;let{id:i,attributeKey:a}=t;if(typeof i!="string"||r.has(i)||a!==void 0&&typeof a!="string")return!1;let o=n[i];if(!o||Array.isArray(o)||typeof o!="object")return!1;let s=new Set(r).add(i);if(o.type==="list"||o.type==="hashed"){let c=a??o.attributeKey;if(typeof c!="string"||!Array.isArray(o.values))return!1;let u=kd(e,c);return jr(o.type==="hashed"?da(u):u,o.values)}return o.type==="condition"?!o.condition||typeof o.condition!="object"?!1:en(e,o.condition,n,s):!1}function kd(e,t){let n=t.split("."),r=e;for(let i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return null;return r}function Pd(e,t=!1){let n=`${e}${t?"/i":""}`,r=vd.get(n);return r||(r=new RegExp(e.replace(/([^\\])\//g,"$1\\/"),t?"i":void 0),vd.set(n,r)),r}function Ki(e,t,n,r=!1,i=new Set){if(typeof e=="string")return r?String(t).toLowerCase()===e.toLowerCase():t+""===e;if(typeof e=="number")return t*1===e;if(typeof e=="boolean")return t!==null&&!!t===e;if(e===null)return t===null;if(Array.isArray(e)||!jd(e))return JSON.stringify(t)===JSON.stringify(e);let a=e;for(let o in a)if(!MA(o,t,a[o],n,i))return!1;return!0}function jd(e){let t=Object.keys(e);return t.length>0&&t.filter(n=>n[0]==="$").length===t.length}function DA(e){if(e===null)return"null";if(Array.isArray(e))return"array";let t=typeof e;return["string","number","boolean","object","undefined"].includes(t)?t:"unknown"}function FA(e,t,n,r){if(!Array.isArray(e))return!1;let i=jd(t)?a=>Ki(t,a,n,!1,r):a=>en(a,t,n,r);for(let a=0;a<e.length;a++)if((e[a]??null)!==null&&i(e[a]))return!0;return!1}function jr(e,t,n=!1){if(n){let i;if(t.length>=tc){let a=TA(t);i=o=>{let s=la(o);return!(typeof s=="number"&&Number.isNaN(s))&&a.has(s)}}else i=a=>t.some(o=>la(a)===la(o));return Array.isArray(e)?e.some(a=>i(a)):i(e)}let r=t.length>=tc?(i=>a=>i.has(a))(Rd(t)):i=>t.includes(i);return Array.isArray(e)?e.some(i=>r(i)):r(e)}function Cd(e){return e===void 0?[]:e&&typeof e=="object"&&(e.type==="list"||e.type==="hashed")&&Array.isArray(e.values)?e.values:null}function _d(e,t,n,r=!1,i=new Set){if(!Array.isArray(e))return!1;for(let a=0;a<t.length;a++){let o=!1;for(let s=0;s<e.length;s++)if(Ki(t[a],e[s],n,r,i)){o=!0;break}if(!o)return!1}return!0}function MA(e,t,n,r,i=new Set){let a=t,o=n;switch(e){case"$veq":return cn(t)===cn(n);case"$vne":return cn(t)!==cn(n);case"$vgt":return cn(t)>cn(n);case"$vgte":return cn(t)>=cn(n);case"$vlt":return cn(t)<cn(n);case"$vlte":return cn(t)<=cn(n);case"$eq":return t===n;case"$ne":return t!==n;case"$lt":return a<o;case"$lte":return a<=o;case"$gt":return a>o;case"$gte":return a>=o;case"$exists":return n?t!=null:t==null;case"$in":return Array.isArray(n)?jr(t,n):!1;case"$ini":return Array.isArray(n)?jr(t,n,!0):!1;case"$inGroup":{let s=r[n],c=Cd(s);return c===null?!1:jr(s?.type==="hashed"?da(t):t,c)}case"$notInGroup":{let s=r[n],c=Cd(s);return c===null?!1:!jr(s?.type==="hashed"?da(t):t,c)}case"$nin":return Array.isArray(n)?!jr(t,n):!1;case"$nini":return Array.isArray(n)?!jr(t,n,!0):!1;case"$not":return!Ki(n,t,r,!1,i);case"$size":return Array.isArray(t)?Ki(n,t.length,r,!1,i):!1;case"$elemMatch":return FA(t,n,r,i);case"$all":return Array.isArray(n)?_d(t,n,r,!1,i):!1;case"$alli":return Array.isArray(n)?_d(t,n,r,!0,i):!1;case"$regex":try{return Pd(n).test(t)}catch{return!1}case"$regexi":try{return Pd(n,!0).test(t)}catch{return!1}case"$type":return DA(t)===n;default:return!1}}function Ed(e,t,n,r){if(!t.length)return!0;for(let i of t)if(en(e,i,n,r))return!0;return!1}function qA(e,t,n,r){for(let i of t)if(!en(e,i,n,r))return!1;return!0}function nc(e){return md(e),{context:e,stack:{evaluatedFeatures:new Set}}}function rc(e){return{...e.attributes,...e.attributeOverrides}}function tr(e,t,n){let r=t||"id",i="",a=rc(e);return a[r]&&(i=a[r]),!i&&n&&(a[n]&&(i=a[n]),i&&(r=n)),{hashAttribute:r,hashValue:i}}function Ye(e,t,n){e.context.log?.(t,n)}function pa(e,t){return t=t||0,`${e}__${t}`}function ic(e,t){return`${e}||${t}`}function UA(e,t,n){let r=e.stickyBucketAssignmentDocs;if(!r)return{};let{hashAttribute:i,hashValue:a}=tr(e,t),o=ic(i,Gi(a)),{hashAttribute:s,hashValue:c}=tr(e,n),u=c?ic(s,Gi(c)):null,l={};return u&&r[u]&&Object.assign(l,r[u].assignments||{}),r[o]&&Object.assign(l,r[o].assignments||{}),l}function Td({context:e,expKey:t,expBucketVersion:n,expHashAttribute:r,expFallbackAttribute:i,expMinBucketVersion:a,expMeta:o}){n=n||0,a=a||0,r=r||"id",o=o||[];let s=pa(t,n),c=UA(e,r,i);if(a>0)for(let m=0;m<a;m++){let f=pa(t,m);if(c[f]!==void 0)return{variation:-1,versionIsBlocked:!0}}let u=c[s];if(u===void 0)return{variation:-1};let l=o.findIndex(m=>m.key===u);return l<0?{variation:-1}:{variation:l}}function Nd(e,t,n,r){let i=ic(t,n),a=e.stickyBucketAssignmentDocs,o=a&&a[i]?a[i].assignments||{}:{},s={...o,...r},c=JSON.stringify(o)!==JSON.stringify(s);return{key:i,doc:{attributeName:t,attributeValue:n,assignments:s},changed:c}}function Dd(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function ma(e,t){let n=nc(t),r=Md(e,null,n);return t.onExperimentEval?.(e,r),r}function Hn(e,t){return ac(e,nc(t))}function BA(e){return e.forcedVariations||{}}function Fd(e,t,n){let{context:r}=e;if(r.trackedExperiments){let i=Bd(t,n);if(r.trackedExperiments.has(i))return;r.trackedExperiments.add(i)}oc(()=>r.onExperimentViewed?.(t,n))}function VA(e,t,n){let{context:r}=e;if(r.trackedFeatureUsage){let i=JSON.stringify(n.value);if(r.trackedFeatureUsage[t]===i)return;r.trackedFeatureUsage[t]=i}oc(()=>r.onFeatureUsage?.(t,n))}function oc(e){try{let t=e();t&&typeof t.catch=="function"&&t.catch(()=>{})}catch{}}function ac(e,t){let{context:n}=t;if(t.stack.evaluatedFeatures.has(e))return Ye(t,`evalFeature: circular dependency detected: ${t.stack.id} -> ${e}`,{from:t.stack.id,to:e}),nr(t,e,null,"cyclicPrerequisite");t.stack.evaluatedFeatures.add(e),t.stack.id=e;let r=n.features?.[e];for(let a of r?.rules??[])Js(a);let i=n.forcedFeatureValues;if(i&&i.has(e))return Ye(t,"Global override",{id:e,value:i.get(e)}),nr(t,e,i.get(e),"override");if(!r)return Ye(t,"Unknown feature",{id:e}),nr(t,e,null,"unknownFeature");if(r.rules){let a=new Set(t.stack.evaluatedFeatures);e:for(let o of r.rules){if(o.parentConditions)for(let u of o.parentConditions){t.stack.evaluatedFeatures=new Set(a);let l=ac(u.id,t);if(l.source==="cyclicPrerequisite")return nr(t,e,null,"cyclicPrerequisite");let m={value:l.value};if(!en(m,u.condition||{},n.savedGroups||{})){if(u.gate)return Ye(t,"Feature blocked by prerequisite",{id:e,rule:o}),nr(t,e,null,"prerequisite");Ye(t,"Skip rule because prerequisite evaluation fails",{id:e,rule:o});continue e}}if(o.filters&&Ud(o.filters,t)){Ye(t,"Skip rule because of filters",{id:e,rule:o});continue}if("force"in o){if(o.condition&&!qd(o.condition,t)){Ye(t,"Skip rule because of condition ff",{id:e,rule:o});continue}if(!LA(t,o.seed||e,o.hashAttribute,n.saveStickyBucketAssignmentDoc&&!o.disableStickyBucketing?o.fallbackAttribute:void 0,o.range,o.coverage,o.hashVersion)){Ye(t,"Skip rule because user not included in rollout",{id:e,rule:o});continue}return Ye(t,"Force value from rule",{id:e,rule:o}),o.tracks&&o.tracks.forEach(u=>{Fd(t,u.experiment,u.result)}),nr(t,e,o.force,"force",o.id)}if(!o.variations){Ye(t,"Skip invalid rule",{id:e,rule:o});continue}let s={variations:o.variations,key:o.key||e};"coverage"in o&&(s.coverage=o.coverage),o.weights&&(s.weights=o.weights),o.hashAttribute&&(s.hashAttribute=o.hashAttribute),o.fallbackAttribute&&(s.fallbackAttribute=o.fallbackAttribute),o.disableStickyBucketing&&(s.disableStickyBucketing=o.disableStickyBucketing),o.bucketVersion!==void 0&&(s.bucketVersion=o.bucketVersion),o.minBucketVersion!==void 0&&(s.minBucketVersion=o.minBucketVersion),o.meta&&(s.meta=o.meta),o.ranges&&(s.ranges=o.ranges),o.name&&(s.name=o.name),o.phase&&(s.phase=o.phase),o.seed&&(s.seed=o.seed),o.hashVersion&&(s.hashVersion=o.hashVersion),o.filters&&(s.filters=o.filters),o.condition&&(s.condition=o.condition);let c=Md(s,e,t);if(n.onExperimentEval?.(s,c),c.inExperiment&&!c.passthrough)return nr(t,e,c.value,"experiment",o.id,s,c)}}return Ye(t,"Use default value",{id:e,value:r.defaultValue}),nr(t,e,r.defaultValue===void 0?null:r.defaultValue,"defaultValue")}function Md(e,t,n){let{context:r}=n;Js(e);let i=e.key,a=e.variations.length;if(a<2)return Ye(n,"Invalid experiment",{id:i}),Dt(n,e,-1,!1,t);if(r.enabled===!1)return Ye(n,"Context disabled",{id:i}),Dt(n,e,-1,!1,t);if(e.urlPatterns&&!pd(r.url||"",e.urlPatterns))return Ye(n,"Skip because of url targeting",{id:i}),Dt(n,e,-1,!1,t);let o=ld(i,r.url||"",a);if(o!==null)return Ye(n,"Force via querystring",{id:i,variation:o}),Dt(n,e,o,!1,t);let c=BA(r)[i];if(c!==void 0)return Ye(n,"Force via dev tools",{id:i,variation:c}),Dt(n,e,c,!1,t);if(e.active===!1)return Ye(n,"Skip because inactive",{id:i}),Dt(n,e,-1,!1,t);let{hashAttribute:u,hashValue:l}=tr(r,e.hashAttribute,r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0);if(!l)return Ye(n,"Skip because missing hashAttribute",{id:i}),Dt(n,e,-1,!1,t);let m=-1,f=!1,g=!1;if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{variation:R,versionIsBlocked:y}=Td(Dd({context:r,expKey:e.key,expBucketVersion:e.bucketVersion,expHashAttribute:e.hashAttribute,expFallbackAttribute:e.fallbackAttribute,expMinBucketVersion:e.minBucketVersion,expMeta:e.meta}));f=R>=0,m=R,g=!!y}if(!f){if(e.filters&&Ud(e.filters,n))return Ye(n,"Skip because of filters",{id:i}),Dt(n,e,-1,!1,t);if(e.include&&!dd(e.include))return Ye(n,"Skip because of include function",{id:i}),Dt(n,e,-1,!1,t);if(e.condition&&!qd(e.condition,n))return Ye(n,"Skip because of condition exp",{id:i}),Dt(n,e,-1,!1,t);if(e.parentConditions){let R=new Set(n.stack.evaluatedFeatures);for(let y of e.parentConditions){n.stack.evaluatedFeatures=new Set(R);let A=ac(y.id,n);if(A.source==="cyclicPrerequisite")return Dt(n,e,-1,!1,t);let x={value:A.value};if(!en(x,y.condition||{},r.savedGroups||{}))return Ye(n,"Skip because prerequisite evaluation fails",{id:i}),Dt(n,e,-1,!1,t)}}}let d=ia(e.seed||i,l,e.hashVersion??2);if(d===null)return Ye(n,"Skip because of invalid hash version",{id:i}),Dt(n,e,-1,!1,t);if(!f){let R=e.ranges||ud(a,e.coverage===void 0?1:e.coverage,e.weights);m=cd(d,R)}if(g)return Ye(n,"Skip because sticky bucket version is blocked",{id:i}),Dt(n,e,-1,!1,t,void 0,!0);if(m<0)return Ye(n,"Skip because of coverage",{id:i}),Dt(n,e,-1,!1,t);if("force"in e)return Ye(n,"Force variation",{id:i,variation:e.force}),Dt(n,e,e.force===void 0?-1:e.force,!1,t);if(r.qaMode)return Ye(n,"Skip because QA mode",{id:i}),Dt(n,e,-1,!1,t);let h=Dt(n,e,m,!0,t,d,f);if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{changed:R,key:y,doc:A}=Nd(r,u,Gi(l),{[pa(e.key,e.bucketVersion)]:h.key});if(R){r.stickyBucketAssignmentDocs=r.stickyBucketAssignmentDocs||{},r.stickyBucketAssignmentDocs[y]=A;let x=r.saveStickyBucketAssignmentDoc;oc(()=>x(A))}}return Fd(n,e,h),Ye(n,"In experiment",{id:i,variation:h.variationId}),h}function nr(e,t,n,r,i,a,o){let s={value:n,on:!!n,off:!n,source:r,ruleId:i||""};return a&&(s.experiment=a),o&&(s.experimentResult=o),r!=="override"&&VA(e,t,s),s}function qd(e,t){return en(rc(t.context),e,t.context.savedGroups||{})}function Ud(e,t){return e.some(n=>{let{hashValue:r}=tr(t.context,n.attribute);if(!r)return!0;let i=ia(n.seed,r,n.hashVersion||2);return i===null?!0:!n.ranges.some(a=>oa(i,a))})}function LA(e,t,n,r,i,a,o){if(!i&&a===void 0)return!0;if(!i&&a===0)return!1;let{hashValue:s}=tr(e.context,n,r);if(!s)return!1;let c=ia(t,s,o??2);return c===null?!1:i?oa(c,i):a!==void 0?c<=a:!0}function Dt(e,t,n,r,i,a,o){let s=!0;(n<0||n>=t.variations.length)&&(n=0,s=!1);let{hashAttribute:c,hashValue:u}=tr(e.context,t.hashAttribute,e.context.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0),l=t.meta?.[n]??{},m=t.variations[0];for(let[g,d]of t.variations.entries())if(g===n){m=d;break}let f={key:l.key||""+n,featureId:i,inExperiment:s,hashUsed:r,variationId:n,value:m,hashAttribute:c,hashValue:u,stickyBucketUsed:!!o};return l.name&&(f.name=l.name),a!==void 0&&(f.bucket=a),l.passthrough&&(f.passthrough=l.passthrough),f}function Bd(e,t){return t.hashAttribute+t.hashValue+e.key+t.variationId}/*!
|
|
2
2
|
Copyright (c) 2025 GrowthBook, Inc.
|
|
3
3
|
|
|
4
4
|
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
|
|
@@ -14,4 +14,4 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
|
14
14
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
15
15
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
16
16
|
SOFTWARE.
|
|
17
|
-
*/var ve=N.z.json().superRefine((e,t)=>{let n=0;function r(i,a){if(++n>1e4||a>20){t.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof i=="string"&&(i.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(i))&&t.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(i))i.forEach(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))(o.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(o)||["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved JSON property"}),r(s,a+1)}r(e,0),new TextEncoder().encode(JSON.stringify(e)).byteLength>65536&&t.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),Ct=N.z.record(N.z.string().min(1).max(128),ve).superRefine((e,t)=>{(!ve.safeParse(e).success||Object.keys(e).length>128||new TextEncoder().encode(JSON.stringify(e)).byteLength>65536||["__proto__","constructor","prototype"].some(n=>Object.hasOwn(e,n)))&&t.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),zA=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),Yt=Ct.superRefine((e,t)=>{function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,a]of Object.entries(r)){if(i==="$savedGroup"&&!N.z.strictObject({id:N.z.uuid(),attributeKey:N.z.string().min(1).max(128).optional()}).safeParse(a).success&&t.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!i.startsWith("$")&&i.split(".").some(o=>["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved attribute path"}),i.startsWith("$")&&!zA.has(i)&&t.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${i}`}),["$regex","$regexi"].includes(i)&&typeof a=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(a)||[...a.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(o=>Number(o[1])>255||Number(o[2]||0)>255)||i==="$regexi"&&/[^\x00-\x7f]/.test(a.replace(/\\u([0-9a-f]{4})/gi,(o,s)=>String.fromCharCode(Number.parseInt(s,16)))))&&t.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(a)}catch{t.addIssue({code:"custom",message:"Invalid regular expression"})}}n(a)}}typeof e.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(e.source)&&("operator"in e||"predicates"in e||"groupId"in e)&&t.addIssue({code:"custom",message:"Obsolete condition protocol"}),n(e)}),$A=N.z.discriminatedUnion("type",[N.z.strictObject({type:N.z.literal("condition"),condition:Yt}),N.z.strictObject({type:N.z.literal("list"),attributeKey:N.z.string().min(1).max(128),values:N.z.array(N.z.union([N.z.string(),N.z.number().finite()])).max(1e5)})]).refine(e=>e.type!=="list"||new TextEncoder().encode(JSON.stringify(e.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function Qn(e){let t=new Set;function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,a]of Object.entries(r))i==="$savedGroup"&&a&&typeof a=="object"&&!Array.isArray(a)&&typeof a.id=="string"?t.add(a.id):["$inGroup","$notInGroup"].includes(i)&&typeof a=="string"?t.add(a):["$eq","$ne","$in","$nin","$ini","$nini"].includes(i)||n(a)}return n(e),[...t]}var GA=N.z.record(N.z.uuid(),$A).superRefine((e,t)=>{let n=new Set,r=new Set;function i(a){if(n.has(a)){t.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(r.has(a))return;let o=e[a];if(!o){t.addIssue({code:"custom",message:"Missing saved group dependency"});return}n.add(a),o.type==="condition"&&Qn(o.condition).forEach(i),n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),cc=N.z.tuple([N.z.number().min(0).max(1),N.z.number().min(0).max(1)]).refine(([e,t])=>e<=t),Vd=N.z.strictObject({attribute:N.z.string().optional(),seed:N.z.string().min(1),hashVersion:N.z.literal(2),ranges:N.z.array(cc).min(1).max(100)}),KA=N.z.strictObject({id:N.z.string().min(1).max(128),condition:Yt,gate:N.z.boolean().optional()}),sc={id:N.z.string().max(128).optional(),condition:Yt.optional(),parentConditions:N.z.array(KA).max(50).optional(),filters:N.z.array(Vd).max(20).optional()},HA=N.z.union([N.z.strictObject({...sc}),N.z.strictObject({...sc,force:ve,coverage:N.z.number().min(0).max(1).optional(),range:cc.optional(),seed:N.z.string().min(1).optional(),hashAttribute:N.z.string().optional(),hashVersion:N.z.literal(2).optional()}),N.z.strictObject({...sc,type:N.z.literal("experiment-ref"),experimentId:N.z.uuid(),values:N.z.record(N.z.string().min(1),ve),meta:N.z.record(N.z.string().min(1),N.z.strictObject({passthrough:N.z.boolean()})).optional()})]),QA=N.z.strictObject({defaultValue:ve,rules:N.z.array(HA).max(100)}),uO=N.z.record(N.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),QA).superRefine((e,t)=>{Object.keys(e).length>100&&t.addIssue({code:"custom",message:"Too many Features"});let n=new Set,r=new Set;function i(a){if(n.has(a)){t.addIssue({code:"custom",message:`Cyclic Feature dependency: ${a}`});return}if(r.has(a))return;let o=e[a];if(!o){t.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${a}`});return}n.add(a);for(let s of o.rules)for(let c of s.parentConditions??[])i(c.id);n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),JA=N.z.strictObject({name:N.z.string().max(80),reason:N.z.string().max(500),dateStarted:N.z.iso.datetime({offset:!0}),dateEnded:N.z.iso.datetime({offset:!0}).nullable(),coverage:N.z.number().min(0).max(1),variationWeights:N.z.array(N.z.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:Yt,savedGroups:N.z.array(N.z.strictObject({match:N.z.enum(["any","all","none"]),ids:N.z.array(N.z.uuid()).min(1)})).max(50),namespace:N.z.strictObject({id:N.z.uuid(),ranges:N.z.array(cc).min(1)}).nullable(),seed:N.z.string().min(1).max(128)}),ZA=N.z.strictObject({key:N.z.string().min(1).max(128),name:N.z.string().min(1).max(80),hypothesis:N.z.string().max(2e3),status:N.z.enum(["draft","running","stopped"]),hashAttribute:N.z.string().min(1).max(128),fallbackAttribute:N.z.string().max(128).nullable(),hashVersion:N.z.literal(2),disableStickyBucketing:N.z.boolean(),bucketVersion:N.z.number().int().min(0).max(1e3),minBucketVersion:N.z.number().int().min(0).max(1e3),variations:N.z.array(N.z.strictObject({id:N.z.string().min(1),key:N.z.string().min(1),name:N.z.string().max(80),description:N.z.string().max(500)})).min(2).max(20),phases:N.z.array(JA).min(1).max(100),releasedVariationId:N.z.string().nullable(),excludeFromPayload:N.z.boolean(),statusSchedule:N.z.strictObject({startAt:N.z.iso.datetime({offset:!0}).nullable(),stopAt:N.z.iso.datetime({offset:!0}).nullable(),stopAfter:N.z.strictObject({value:N.z.number().int().positive().max(36500),unit:N.z.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((e,t)=>{(e.minBucketVersion>e.bucketVersion||e.statusSchedule?.stopAt&&e.statusSchedule?.stopAfter||e.phases.some((n,r)=>{if(r===0)return!1;let i=e.phases[r-1];return!i?.dateEnded||Date.parse(n.dateStarted)<Date.parse(i.dateStarted)||Date.parse(i.dateEnded)>Date.parse(n.dateStarted)})||new Set(e.variations.map(n=>n.key)).size!==e.variations.length||new Set(e.variations.map(n=>n.id)).size!==e.variations.length||e.releasedVariationId!==null&&!e.variations.some(n=>n.id===e.releasedVariationId)||e.statusSchedule?.startAt&&e.statusSchedule?.stopAt&&Date.parse(e.statusSchedule.startAt)>=Date.parse(e.statusSchedule.stopAt)||e.phases.some(n=>n.dateEnded&&Date.parse(n.dateStarted)>=Date.parse(n.dateEnded)||n.namespace?.ranges.some(([r,i],a,o)=>r>=i||o.some(([s,c],u)=>u!==a&&r<c&&s<i)))||e.phases.some(n=>n.variationWeights.length!==e.variations.length))&&t.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});var WA=ZA.safeExtend({filters:N.z.array(Vd).optional()}),YA=N.z.strictObject({experiments:N.z.record(N.z.uuid(),WA),savedGroups:GA}),Hi=N.z.strictObject({attributeName:N.z.string(),attributeValue:N.z.string(),assignments:N.z.record(N.z.string(),N.z.string())}),lO=N.z.strictObject({snapshot:YA,attributes:Ct,results:Ct,stickyBucketAssignmentDocs:N.z.record(N.z.string(),Hi)}),dO=N.z.strictObject({variantKey:N.z.string().nullable(),bucketVersion:N.z.number().int().min(0),source:N.z.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:N.z.number().min(0).max(1).optional(),stickyBucketUsed:N.z.boolean().optional(),hashUsed:N.z.boolean().optional()});function rr(e){let t=new Set,n=a=>a!==null&&typeof a=="object"&&!Array.isArray(a);function r(a,o){if(n(a))for(let[s,c]of Object.entries(a))s==="$elemMatch"?i(c,o):s==="$not"?r(c,o):s==="$all"&&Array.isArray(c)&&c.forEach(u=>r(u,o))}function i(a,o=""){if(n(a)){for(let[s,c]of Object.entries(a))if(["$and","$or","$nor"].includes(s)&&Array.isArray(c))c.forEach(u=>i(u,o));else if(s==="$not")i(c,o);else if(s==="$savedGroup"&&n(c))typeof c.attributeKey=="string"&&t.add(c.attributeKey);else if(!s.startsWith("$")){let u=o?`${o}.${s}`:s;t.add(u),r(c,u)}}}return i(e),[...t]}var XA=Rt.z.enum(["active","inactive"]),eb=Rt.z.preprocess((e,t)=>{let n=0;function r(i,a){if(!(++n>1e4||a>20)){if(Array.isArray(i))i.forEach(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))["__proto__","constructor","prototype"].includes(o)&&t.addIssue({code:"custom",message:"Reserved merchandise attribute"}),r(s,a+1)}}return r(e,0),e},Ct),tb=Rt.z.strictObject({id:Rt.z.string().trim().min(1).max(255),name:Rt.z.string().trim().min(1).max(255),status:XA,metadata:eb}),hO=tb.extend({internal_id:Rt.z.uuid(),project_id:Rt.z.uuid(),environment_id:Rt.z.uuid(),created_at:Rt.z.iso.datetime({offset:!0}),updated_at:Rt.z.iso.datetime({offset:!0})}),zd=Rt.z.union([Rt.z.strictObject({id:Rt.z.string().trim().min(1).max(255)}),Rt.z.strictObject({internalId:Rt.z.uuid()})]),yO=Rt.z.enum(["customer","merchandise","context"]),AO=Rt.z.enum(["system","stored","request"]),bO=Rt.z.enum(["customer","merchandise","mixed"]),Ld=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function uc(e,t={},n=new Set){if(rr(e).some(Ld))return!0;for(let r of Qn(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&Ld(i.attributeKey)||i?.type==="condition"&&uc(i.condition,t,n))return!0}return!1}var $d=require("zod"),nb=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,wn=$d.z.string().max(16).regex(nb,"\u8BED\u8A00\u4EE3\u7801\u683C\u5F0F\u4E0D\u6B63\u786E\uFF0C\u4F8B\u5982 zh-CN\u3001en").refine(e=>{try{return Intl.getCanonicalLocales(e)[0]===e}catch{return!1}},"\u6301\u4E45\u5316\u8BED\u8A00\u4EE3\u7801\u5FC5\u987B\u4F7F\u7528\u89C4\u8303\u5199\u6CD5");var OO=ee.z.enum(["draft","active","paused","archived"]),ir=ee.z.discriminatedUnion("type",[ee.z.object({type:ee.z.literal("percent"),percentOff:ee.z.number().min(1).max(100).multipleOf(.01)}).strict(),ee.z.object({type:ee.z.literal("amount"),amountOffCents:ee.z.number().int().min(1).max(1e8),currency:Ie}).strict()]),un=ee.z.discriminatedUnion("type",[ee.z.object({type:ee.z.literal("once")}).strict(),ee.z.object({type:ee.z.literal("repeating"),months:ee.z.number().int().min(1).max(36)}).strict(),ee.z.object({type:ee.z.literal("forever")}).strict()]),Gd=[ee.z.object({type:ee.z.literal("all")}).strict(),ee.z.object({type:ee.z.literal("plans"),planIds:ee.z.array(ee.z.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],rb=ee.z.discriminatedUnion("type",[...Gd,ee.z.strictObject({type:ee.z.literal("merchandise"),scope:ee.z.discriminatedUnion("type",[ee.z.strictObject({type:ee.z.literal("all")}),ee.z.strictObject({type:ee.z.literal("selected"),merchandiseIds:ee.z.array(ee.z.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),ee.z.strictObject({type:ee.z.literal("condition"),condition:Yt})])})]),lc=ee.z.discriminatedUnion("type",[...Gd,ee.z.strictObject({type:ee.z.literal("merchandise"),scope:ee.z.strictObject({type:ee.z.enum(["all","selected","condition"])})})]),ib=ee.z.strictObject({firstPurchaseOnly:ee.z.boolean(),condition:Yt}),PO=ee.z.object({name:ee.z.string().trim().min(1).max(80),description:ee.z.string().max(500),discount:ir,duration:un,appliesTo:rb,eligibility:ib,selfClaimEnabled:ee.z.boolean().default(!1),startsAt:ee.z.iso.datetime().nullable(),endsAt:ee.z.iso.datetime().nullable(),totalLimit:ee.z.number().int().min(1).max(1e6).nullable(),perCustomerLimit:ee.z.number().int().min(1).max(10),grantWindowHours:ee.z.number().int().min(1).max(2160)}).strict().refine(e=>!e.startsAt||!e.endsAt||Date.parse(e.endsAt)>Date.parse(e.startsAt),{message:"\u7ED3\u675F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u5F00\u59CB\u65F6\u95F4",path:["endsAt"]}).refine(e=>!uc(e.eligibility.condition),{message:"Customer eligibility cannot read merchandise; use merchandise applicability",path:["eligibility","condition"]}).refine(e=>e.appliesTo.type!=="merchandise"||e.duration.type==="once",{message:"Merchandise Coupons apply to one purchase",path:["duration"]}).refine(e=>e.appliesTo.type!=="merchandise"||!e.eligibility.firstPurchaseOnly,{message:"Merchant purchase eligibility requires trusted targeting attributes",path:["eligibility","firstPurchaseOnly"]}),CO=ee.z.object({code:ee.z.string().trim().transform(e=>e.toUpperCase()).pipe(ee.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/,"\u4F18\u60E0\u7801\u53EA\u80FD\u7528 3\u201332 \u4F4D\u5B57\u6BCD\u3001\u6570\u5B57\u3001- \u548C _\uFF0C\u4EE5\u5B57\u6BCD\u6216\u6570\u5B57\u5F00\u5934")),maxRedemptions:ee.z.number().int().min(1).max(1e6).nullable(),expiresAt:ee.z.iso.datetime().nullable(),firstPurchaseOnly:ee.z.boolean(),minimumAmountCents:ee.z.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:Ie.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var Qi=ee.z.object({id:ee.z.uuid(),couponId:ee.z.uuid(),status:ee.z.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:ee.z.iso.datetime(),expiresAt:ee.z.iso.datetime(),coupon:ee.z.object({name:ee.z.string(),discount:ir,duration:un,appliesTo:lc}).strict()}).strict(),Kd=ee.z.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var Wd=S.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),dc=S.z.string().regex(/^(0|[1-9]\d{0,14})$/),ui=S.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),ob=S.z.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),Ji=ob,Jn=xe.refine(e=>/[1-9]/.test(e)),Gt=S.z.iso.datetime({offset:!0}),fa=e=>{let[t,n=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");return BigInt(t)*1000000n+BigInt(n.padEnd(6,"0"))},ab=S.z.array(S.z.object({upTo:Jn.nullable(),unitAmountMinor:Wd,flatAmountMinor:S.z.number().int().min(0).max(1e8).optional()}).strict()).min(1).max(12).refine(e=>{try{return e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let r=e[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&fa(t.upTo)>fa(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),sb=S.z.discriminatedUnion("kind",[S.z.object({kind:S.z.literal("flat"),units:Jn,unitAmountMinor:Wd}).strict(),S.z.object({kind:S.z.enum(["graduated","volume"]),units:Jn,tiers:ab}).strict()]).refine(e=>e.kind==="flat"||!e.tiers.some(t=>(t.flatAmountMinor??0)>0)||e.kind==="volume"&&e.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers"),cb=S.z.strictObject({interval:S.z.enum(["month","year"]),count:S.z.number().int().min(1).max(12),anchor:S.z.enum(["membership","calendar"])}),Zi=S.z.object({currency:Ie,pricing:sb,billingCycle:cb.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var Hd={requestId:S.z.uuid(),productVersionId:S.z.uuid(),internal_feature_id:S.z.uuid(),currency:Ie},Yd=S.z.strictObject({interval:S.z.enum(["hour","day","week","month"]),intervalCount:S.z.number().int().min(1).max(12),limit:S.z.number().int().min(1).max(1e6)}),Xd=S.z.discriminatedUnion("kind",[S.z.object({...Hd,kind:S.z.literal("auto_topup"),threshold:ta,quantity:Jn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Yd.optional()}).strict(),S.z.object({...Hd,kind:S.z.literal("postpaid"),maxAmountMinorPerPeriod:Ji,maxOutstandingMinor:Ji}).strict()]),Qd={productVersionId:S.z.uuid(),internal_feature_id:S.z.uuid(),currency:Ie},ep=S.z.discriminatedUnion("kind",[S.z.object({...Qd,kind:S.z.literal("auto_topup"),threshold:ta,quantity:Jn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Yd.optional(),purchaseAmountMinor:Ji,purchaseUnits:Jn}).strict(),S.z.object({...Qd,kind:S.z.literal("postpaid"),maxAmountMinorPerPeriod:Ji,maxOutstandingMinor:Ji,cashPrice:Zi}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),ga=S.z.object({id:S.z.uuid(),terms:ep,status:S.z.enum(["prepared","active","revoked","blocked"]),createdAt:Gt,acceptedAt:Gt.nullable(),effectiveAt:Gt.nullable(),revokedAt:Gt.nullable()}).strict().refine(e=>(e.status==="prepared"?e.acceptedAt===null:!0)&&(e.status==="active"?e.acceptedAt!==null&&e.effectiveAt!==null:!0)&&(e.status==="revoked"?e.revokedAt!==null:e.revokedAt===null),"Authorization consent and revocation must be explicit"),tp=S.z.object({authorizationId:S.z.uuid(),terms:ep,setupUrl:S.z.url().nullable()}).strict(),np=S.z.object({authorizationId:S.z.uuid(),accepted:S.z.literal(!0)}).strict(),rp=S.z.object({authorizationId:S.z.uuid(),requestId:S.z.uuid()}).strict(),ip=S.z.object({internal_feature_id:S.z.uuid(),entityId:S.z.uuid().nullable(),interval:S.z.enum(["day","week","month","year"]),anchor:S.z.enum(["billing_cycle","utc"]).optional(),basis:S.z.enum(["usage","credits"]),filter:Pt.optional(),limit:xe.nullable(),thresholds:S.z.array(S.z.number().positive().max(1)).max(8),includedThresholds:S.z.array(S.z.number().positive().max(1)).max(8).optional(),absoluteThresholds:S.z.array(Jn).max(8).optional()}).strict().refine(e=>e.thresholds.every((t,n)=>{let r=e.thresholds[n-1];return n===0||r!==void 0&&t>r})&&(e.includedThresholds??[]).every((t,n,r)=>{let i=r[n-1];return n===0||i!==void 0&&t>i})&&(e.absoluteThresholds??[]).every((t,n,r)=>{let i=r[n-1];return n===0||i!==void 0&&fa(t)>fa(i)}),"Notification thresholds must increase"),ub=ip.safeExtend({requestId:S.z.uuid()}),Jd={control:S.z.literal("overage"),requestId:S.z.uuid(),internal_feature_id:S.z.uuid(),entityId:S.z.uuid().nullable()},lb=S.z.discriminatedUnion("action",[S.z.strictObject({...Jd,action:S.z.literal("set"),allowed:S.z.boolean().nullable(),overageLimit:xe.nullable(),skipOverageBilling:S.z.boolean()}),S.z.strictObject({...Jd,action:S.z.literal("remove")})]),op=S.z.union([ub,lb]),db=S.z.strictObject({internal_feature_id:S.z.uuid(),entityId:S.z.uuid().nullable(),allowed:S.z.boolean().nullable(),overageLimit:xe.nullable(),skipOverageBilling:S.z.boolean(),interval:S.z.enum(["day","week","month","year"]),startsAt:Gt,endsAt:Gt,used:S.z.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:S.z.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:S.z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),pb=S.z.object({internal_feature_id:S.z.uuid(),entityId:S.z.uuid().nullable(),interval:S.z.enum(["day","week","month","year"]),anchor:S.z.enum(["billing_cycle","utc"]).optional(),basis:S.z.enum(["usage","credits"]),filter:Pt.optional(),startsAt:Gt,endsAt:Gt,used:Wt,reserved:Wt,limit:xe.nullable(),thresholds:S.z.array(S.z.number().positive().max(1)).max(8),notifiedThresholds:S.z.array(S.z.number().positive().max(1)).max(1024),includedThresholds:S.z.array(S.z.number().positive().max(1)).max(8).optional(),includedAllowance:S.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:S.z.array(S.z.number().positive().max(1)).max(1024).optional(),absoluteThresholds:S.z.array(Jn).max(8).optional(),notifiedAbsoluteThresholds:S.z.array(Jn).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||xe.safeParse(e.used).success&&xe.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),mb=S.z.object({authorizationId:S.z.uuid(),status:S.z.enum(["idle","pending","blocked"]),taskId:S.z.uuid().nullable(),invoiceId:S.z.uuid().nullable(),hostedInvoiceUrl:S.z.url().nullable(),purchaseCount:S.z.number().int().nonnegative(),purchaseWindowEndsAt:Gt.nullable(),attemptCount:S.z.number().int().nonnegative(),failedAttemptCount:S.z.number().int().nonnegative(),suspendedAt:Gt.nullable(),nextAttemptAt:Gt.nullable(),failureReason:S.z.string().min(1).max(240).nullable()}).strict(),ap=S.z.object({internal_feature_id:S.z.uuid().optional(),entityId:S.z.uuid().optional()}).strict(),pc=S.z.object({authorizations:S.z.array(ga).max(100),limits:S.z.array(ip).max(100),overages:S.z.array(db).max(100).optional(),windows:S.z.array(pb).max(200),autoTopups:S.z.array(mb).max(100),limited:S.z.boolean()}).strict(),fb=S.z.object({id:S.z.uuid(),internal_feature_id:S.z.uuid(),productVersionId:S.z.uuid(),authorizationId:S.z.uuid(),entityId:S.z.uuid().nullable(),units:xe,amountMinor:ui,cashPrice:Zi}).strict(),Wi=S.z.object({id:S.z.uuid(),sourceKind:S.z.enum(["product","usage","manual"]),providerInvoiceId:S.z.string().min(1).max(240).nullable(),status:S.z.enum(["accruing","open","pending","paid","failed","void"]),currency:Ie,startsAt:Gt.nullable(),endsAt:Gt.nullable(),amountMinor:S.z.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:S.z.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:dc,paidAmountMinor:dc,refundedAmountMinor:dc,createdAt:Gt,hostedInvoiceUrl:S.z.url().nullable(),adjustment:S.z.object({originalInvoiceId:S.z.uuid(),amountMinor:S.z.string().regex(/^-?(0|[1-9]\d{0,8})$/).refine(e=>e!=="-0"&&/^-?(0|[1-9]\d{0,8})$/.test(e)&&BigInt(e)>=-200000000n&&BigInt(e)<=200000000n,"Invoice adjustment exceeds the bounded minor amount"),acceptedAt:Gt.nullable(),reason:S.z.string().min(1).max(500).optional()}).strict().nullable(),lines:S.z.array(fb).max(100),linesLimited:S.z.boolean()}).strict(),sp=S.z.object({invoiceId:S.z.uuid(),accepted:S.z.literal(!0)}).strict(),cp=S.z.strictObject({requestId:S.z.uuid(),originalInvoiceId:S.z.uuid(),amountMinor:S.z.string().regex(/^[1-9]\d{0,8}$/).refine(e=>/^[1-9]\d{0,8}$/.test(e)&&BigInt(e)<=200000000n,"Supplemental amount exceeds the bounded minor amount"),reason:S.z.string().trim().min(1).max(500)}),up=S.z.object({after:S.z.uuid().nullable(),limit:S.z.number().int().min(1).max(100)}).strict(),lp=S.z.object({rows:S.z.array(Wi).max(100),nextCursor:S.z.uuid().nullable()}).strict(),Zd=S.z.strictObject({id:S.z.string(),coupon:S.z.string(),start:S.z.number().nonnegative(),end:S.z.number().nullable()}),gb=S.z.strictObject({subscriptionId:S.z.string(),customerId:S.z.string(),accountId:S.z.string(),sourceItems:S.z.array(S.z.strictObject({id:S.z.string(),price_id:S.z.string(),quantity:S.z.number().int(),discounts:S.z.array(Zd).optional()})).max(100),items:S.z.array(S.z.strictObject({id:S.z.string(),price:S.z.string(),quantity:S.z.number().int(),discounts:S.z.array(S.z.strictObject({coupon:S.z.string().optional(),terms:S.z.strictObject({id:S.z.string(),name:S.z.string().optional(),percent_off:S.z.number().optional(),amount_off:S.z.number().optional(),currency:S.z.string().optional(),duration:S.z.enum(["once","forever","repeating"]),duration_in_months:S.z.number().optional()}).optional(),discount:S.z.string().optional(),receipt:Zd.optional()})).max(20)})).max(100)}),dp=S.z.strictObject({membershipId:S.z.uuid(),requestId:S.z.uuid(),grantIds:S.z.array(S.z.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),pp=S.z.strictObject({membershipId:S.z.uuid(),operationId:S.z.uuid(),status:S.z.enum(["pending","effective"]),execution:gb.nullable(),grants:S.z.array(S.z.strictObject({id:S.z.uuid(),couponId:S.z.uuid(),name:S.z.string(),discount:ir,duration:un,startedAt:Gt.nullable()})).max(20)});var li=require("zod");var mp=li.z.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),fp=li.z.number().int().min(1).max(1e3),ha=li.z.object({cap:xe.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:li.z.number().positive().max(1e4).nullable(),cycles:li.z.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");var Zn=require("zod");var gp=Zn.z.strictObject({itemKey:Zn.z.string().regex(/^paid:feature:[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),internal_feature_id:Zn.z.uuid(),includedAmount:Zn.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:Zn.z.number().int().min(0).max(1e4),terms:ra,pricing:$i.optional(),unitAmountMinor:Zn.z.number().int().min(0).max(1e8),productId:Zn.z.string().min(1).max(255).nullable(),priceId:Zn.z.string().min(1).max(255).nullable()}).superRefine((e,t)=>{(e.quantity<e.terms.minimumQuantity||e.quantity>e.terms.maximumQuantity||e.productId===null!=(e.priceId===null)||e.quantity>0&&(e.pricing||e.unitAmountMinor>0)&&e.priceId===null)&&t.addIssue({code:"custom",message:"Purchased quantities need their published bounds and immutable price binding"});try{ad(e.includedAmount,e.terms.units,e.quantity),na({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{t.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});var te=require("zod");var Tr=xe.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Yi=te.z.string().min(1).max(120),ya=te.z.enum(["cap","overflow"]),ln=(e,t)=>{let[n,r=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");return BigInt(n)*10n**BigInt(t)+BigInt(r.padEnd(t,"0"))},Xi=e=>{try{return e()}catch{return!1}},eo=te.z.discriminatedUnion("operation",[te.z.object({operation:te.z.literal("quote"),overageBehavior:ya.optional(),internal_feature_id:te.z.uuid(),entityId:te.z.uuid().optional(),quantity:Tr,properties:Pt}).strict(),te.z.object({operation:te.z.literal("consume"),overageBehavior:ya.optional(),occurredAt:te.z.iso.datetime({offset:!0}).optional(),internal_feature_id:te.z.uuid(),entityId:te.z.uuid().optional(),quantity:xe,properties:Pt,idempotencyKey:Yi}).strict(),te.z.object({operation:te.z.literal("reserve"),occurredAt:te.z.iso.datetime({offset:!0}).optional(),internal_feature_id:te.z.uuid(),entityId:te.z.uuid().optional(),quantity:Tr,properties:Pt,idempotencyKey:Yi,expiresInSeconds:te.z.number().int().min(1).max(86400)}).strict(),te.z.object({operation:te.z.literal("confirm"),operationId:te.z.uuid(),quantity:Tr,properties:Pt.optional(),idempotencyKey:Yi}).strict(),te.z.object({operation:te.z.literal("refund"),operationId:te.z.uuid(),quantity:Tr,idempotencyKey:Yi}).strict(),te.z.object({operation:te.z.literal("release"),operationId:te.z.uuid(),idempotencyKey:Yi}).strict()]),mc=te.z.object({internal_credit_feature_id:te.z.uuid().nullable(),internal_metered_feature_id:te.z.uuid(),dimension:te.z.string().min(1).max(64),counterKey:te.z.string().min(1).max(240),cycleStart:te.z.iso.datetime({offset:!0}),unitCost:xe,units:Tr,amount:Wt,tier:te.z.number().int().min(1).max(12).nullable()}).strict(),Nr=te.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function hp(e,t){let n=e.reduce((r,i)=>r+ln(i.units,12),0n)-ln(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var yp=te.z.discriminatedUnion("funding",[te.z.strictObject({funding:te.z.literal("balance"),sourceId:te.z.uuid(),rolloverId:te.z.uuid().nullable(),units:Nr.refine(e=>/[1-9]/.test(e)),amount:Wt}),te.z.strictObject({funding:te.z.literal("unbilled"),units:Nr.refine(e=>/[1-9]/.test(e))}),te.z.object({funding:te.z.literal("prepaid"),sourceId:te.z.uuid(),units:Tr,amount:Wt,pricing:te.z.array(mc).min(1).max(12)}).strict().refine(e=>Xi(()=>e.pricing.reduce((t,n)=>t+ln(n.units,6),0n)===ln(e.units,6)&&e.pricing.reduce((t,n)=>t+ln(n.amount,12),0n)===ln(e.amount,12)&&e.pricing.every(t=>ln(t.unitCost,6)*ln(t.units,6)===ln(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),te.z.object({funding:te.z.literal("postpaid"),invoiceLineId:te.z.uuid().nullable(),units:Tr,authorizationId:te.z.uuid()}).strict()]),Aa=te.z.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),Ap=te.z.object({allowed:te.z.boolean(),internal_feature_id:te.z.uuid(),quantity:xe,requestedQuantity:xe.optional(),overageBehavior:ya.optional(),reason:Aa.nullable(),allocations:te.z.array(yp).max(500)}).strict().refine(e=>Xi(()=>e.allowed?e.reason===null&&hp(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>Xi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&ln(e.requestedQuantity,6)>=ln(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),to=te.z.object({id:te.z.uuid(),internal_feature_id:te.z.uuid(),kind:te.z.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:te.z.uuid().nullable(),quantity:xe,requestedQuantity:xe.optional(),overageBehavior:ya.optional(),accepted:te.z.boolean(),reason:te.z.enum([...Aa.options,"expired"]).nullable(),createdAt:te.z.iso.datetime({offset:!0}),reservationStatus:te.z.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:te.z.iso.datetime({offset:!0}).nullable(),allocations:te.z.array(yp).max(500)}).strict().refine(e=>Xi(()=>e.accepted?e.reason===null&&hp(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>Xi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&ln(e.requestedQuantity,6)>=ln(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");var Te=require("zod");var Dr=Te.z.iso.datetime({offset:!0}),bp=xe.refine(e=>/[1-9]/.test(e)),xp=Te.z.strictObject({interval:mp.exclude(["lifetime"]),count:fp}),hb=Te.z.strictObject({action:Te.z.literal("create"),requestId:Te.z.uuid(),internal_feature_id:Te.z.uuid(),entityId:Te.z.uuid().nullable(),amount:bp.nullable(),expiresAt:Dr.nullable(),reset:xp.nullable(),rollover:ha.nullable(),nextResetAt:Dr.nullable()}).refine(e=>e.amount!==null||e.reset===null&&e.rollover===null,"Unlimited grants cannot reset or roll over").refine(e=>!e.rollover||e.reset!==null,"Rollover requires a recurring grant").refine(e=>e.nextResetAt===null||e.reset!==null&&(e.expiresAt===null||Date.parse(e.nextResetAt)<Date.parse(e.expiresAt)),"The first reset needs a reset interval and must precede expiry"),Sp=Te.z.discriminatedUnion("action",[hb,Te.z.strictObject({action:Te.z.literal("update"),requestId:Te.z.uuid(),grantId:Te.z.uuid(),revision:Te.z.number().int().nonnegative(),amount:bp.nullable(),expiresAt:Dr.nullable(),rollover:ha.nullable(),nextResetAt:Dr.nullable()}),Te.z.strictObject({action:Te.z.enum(["add","subtract","set_remaining"]),requestId:Te.z.uuid(),grantId:Te.z.uuid(),revision:Te.z.number().int().nonnegative(),amount:xe}),Te.z.strictObject({action:Te.z.literal("revoke"),requestId:Te.z.uuid(),grantId:Te.z.uuid(),revision:Te.z.number().int().nonnegative()})]),fc=Te.z.strictObject({id:Te.z.uuid(),internal_feature_id:Te.z.uuid(),entityId:Te.z.uuid().nullable(),amount:xe.nullable(),reset:xp.nullable(),rollover:ha.nullable(),nextResetAt:Dr.nullable(),startsAt:Dr,expiresAt:Dr.nullable(),revision:Te.z.number().int().nonnegative(),revoked:Te.z.boolean(),available:Wt,held:Wt,spent:Wt}),Ip=Te.z.strictObject({customerId:Te.z.uuid(),after:Te.z.uuid().nullable(),limit:Te.z.number().int().min(1).max(100)}),vp=Te.z.strictObject({rows:Te.z.array(fc).max(100),nextCursor:Te.z.uuid().nullable()});var ie=require("zod");var Dn=ie.z.iso.datetime({offset:!0}),wp=ie.z.strictObject({invoiceId:ie.z.uuid(),after:ie.z.string().min(1).max(180).nullable(),limit:ie.z.number().int().min(1).max(100)}),yb=ie.z.strictObject({kind:ie.z.literal("product"),key:ie.z.string(),productVersionId:ie.z.uuid(),productName:ie.z.string(),itemKey:ie.z.string(),entityId:ie.z.uuid().nullable(),quantity:ie.z.number().positive(),subtotalMinor:ie.z.string().regex(/^-?\d+$/),discountMinor:ie.z.string().regex(/^\d+$/),taxMinor:ie.z.string().regex(/^-?\d+$/).nullable(),totalMinor:ie.z.string().regex(/^-?\d+$/),startsAt:Dn.nullable(),endsAt:Dn.nullable(),providerLineId:ie.z.string().nullable(),providerItemId:ie.z.string()}),Op=ie.z.strictObject({invoice:Wi,items:ie.z.array(ie.z.discriminatedUnion("kind",[yb,ie.z.strictObject({kind:ie.z.literal("invoice_credit"),key:ie.z.string(),internal_feature_id:ie.z.uuid(),internal_credit_feature_id:ie.z.uuid(),name:ie.z.string(),units:xe,reserved:xe,amountMinor:ui,grossAmountMinor:ui,creditsAppliedMinor:ui,properties:Pt,cashPrice:Zi,providerItemId:ie.z.string().nullable(),creditProviderItemId:ie.z.string().nullable()}),ie.z.strictObject({kind:ie.z.literal("usage"),key:ie.z.string(),internal_feature_id:ie.z.uuid(),name:ie.z.string(),units:xe,reserved:xe,amountMinor:ui,cashPrice:Zi})])).max(100),nextCursor:ie.z.string().min(1).max(180).nullable()}),Ab=ie.z.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),gc=ie.z.strictObject({from:Dn,to:Dn,entityId:ie.z.uuid().optional(),snapshotAt:Dn.nullable(),after:ie.z.strictObject({at:Dn,id:ie.z.uuid(),position:ie.z.number().int().nonnegative()}).nullable(),limit:ie.z.number().int().min(1).max(100)}).refine(e=>Date.parse(e.from)<Date.parse(e.to)&&Date.parse(e.to)-Date.parse(e.from)<=366*864e5,"Statement range must be positive and at most 366 days").refine(e=>e.after===null||e.snapshotAt!==null,"A cursor requires the original snapshot time"),Pp=ie.z.strictObject({customerId:ie.z.uuid(),entityId:ie.z.uuid().nullable(),from:Dn,to:Dn,snapshotAt:Dn,totals:ie.z.array(ie.z.strictObject({internal_credit_feature_id:ie.z.uuid(),name:ie.z.string(),consumed:Wt,refunded:Wt,net:Ab})).max(1e3),rows:ie.z.array(ie.z.strictObject({operationId:ie.z.uuid(),position:ie.z.number().int().nonnegative(),kind:ie.z.enum(["consume","confirm","refund"]),originalId:ie.z.uuid().nullable(),occurredAt:Dn,internal_feature_id:ie.z.uuid(),entitlementName:ie.z.string(),sourceId:ie.z.uuid(),internal_credit_feature_id:ie.z.uuid(),creditName:ie.z.string(),units:Nr,amount:Wt,pricing:ie.z.array(mc).max(12),properties:Pt})).max(100),nextCursor:gc.shape.after});var D=require("zod");var yn=require("zod");var bb=yn.z.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),xb=yn.z.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),ba=yn.z.strictObject({internal_feature_id:yn.z.uuid(),entityId:yn.z.uuid().nullable()}),Cp=ba.extend({quantity:xe,expectedRevision:yn.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:yn.z.string().min(1).max(120),properties:Pt.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),no=ba.extend({operationId:yn.z.uuid().nullable(),usage:xe,capacity:bb.nullable(),remaining:xb.nullable(),withinLimit:yn.z.boolean(),revision:yn.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:yn.z.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let n=r=>{let i=r.startsWith("-"),[a,o=""]=(i?r.slice(1):r).split(".");if(a===void 0||a==="")throw new Error("Invalid decimal value");return(i?-1n:1n)*(BigInt(a)*10n**12n+BigInt(o.padEnd(12,"0")))};(e.capacity===null!=(e.remaining===null)||(e.capacity===null?!e.withinLimit:e.remaining===null||n(e.remaining)!==n(e.capacity)-n(e.usage)||e.withinLimit!==n(e.remaining)>=0n)||e.revision===0!=(e.operationId===null)||e.operationId===null!=(e.updatedAt===null))&&t.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var Kt=D.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),On=D.z.iso.datetime({offset:!0}),Sb=D.z.enum(["access","metered","credit"]),ro={internal_feature_id:D.z.uuid(),key:Er,name:D.z.string().min(1).max(120),kind:Sb},_p=D.z.object({customerId:D.z.uuid(),snapshotAt:On,memberships:D.z.array(D.z.object({id:D.z.uuid(),productId:D.z.string().min(1).max(255),productVersionId:D.z.uuid(),billingProductVersionId:D.z.uuid(),version:D.z.number().int().positive(),key:D.z.string().min(1).max(64),name:D.z.string().min(1).max(120),groupId:D.z.string().max(255).nullable(),membershipType:D.z.enum(["main","addon"]),status:D.z.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:D.z.boolean(),accessEnabled:D.z.boolean(),renewalChange:D.z.object({productVersionId:D.z.uuid(),name:D.z.string().min(1).max(120),version:D.z.number().int().positive(),effectiveAt:On,benefitsAppliedAt:On.nullable(),timing:D.z.enum(["immediate","renewal"]),changeKind:D.z.enum(["plan","seats","quantity"]),feature:D.z.strictObject({internal_feature_id:D.z.uuid(),name:D.z.string().min(1).max(80),fromQuantity:D.z.number().int().min(0).max(1e4),toQuantity:D.z.number().int().min(0).max(1e4)}).optional(),seat:D.z.object({key:D.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:D.z.number().int().min(0).max(1e4),toQuantity:D.z.number().int().min(0).max(1e4)}).strict().nullable(),status:D.z.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(e=>e.changeKind==="seats"==(e.seat!==null)&&e.changeKind==="quantity"==(e.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:D.z.object({phase:D.z.enum(["paid","trial"]),startsAt:On,endsAt:On.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:D.z.boolean(),balances:D.z.array(D.z.object({...ro,usageType:D.z.enum(["consumable","non_consumable"]).nullable(),accessible:D.z.boolean(),unlimited:D.z.boolean(),available:Kt,held:Kt,debt:Kt,nextExpiresAt:On.nullable(),usage:no.nullable()}).strict().refine(e=>e.kind==="metered"==(e.usageType!==null)&&(e.accessible||e.available==="0"&&e.held==="0")&&(e.usageType==="non_consumable"?e.usage!==null&&e.usage.internal_feature_id===e.internal_feature_id&&e.unlimited===(e.usage.capacity===null)&&e.available===(e.usage.remaining===null||e.usage.remaining.startsWith("-")?"0":e.usage.remaining)&&e.held==="0"&&e.debt==="0":e.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:D.z.boolean()}).strict(),Ep=D.z.enum(["source","usage","transaction","invoice","debt","settlement"]),xa=D.z.object({at:On,id:D.z.uuid(),type:Ep}).strict(),Rp=D.z.object({type:Ep.nullable(),resourceKey:Er.optional(),kind:D.z.enum(["purchase","refund"]).optional(),topup:D.z.boolean().optional(),from:D.z.iso.date().nullable(),to:D.z.iso.date().nullable(),after:xa.nullable(),limit:D.z.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),di={id:D.z.uuid(),occurredAt:On},Ib=D.z.discriminatedUnion("type",[D.z.strictObject({...di,type:D.z.literal("invoice"),status:D.z.string().min(1).max(80),paid:Kt,refunded:Kt,currency:Ie,externalId:D.z.string().nullable()}),D.z.object({...di,...ro,type:D.z.literal("source"),reason:D.z.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:Kt,unlimited:D.z.boolean(),status:D.z.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:On,expiresAt:On.nullable(),orderId:D.z.uuid().nullable(),parentSourceId:D.z.uuid().nullable()}).strict(),D.z.object({...di,type:D.z.literal("usage"),internal_feature_id:D.z.uuid(),name:D.z.string().min(1).max(120),kind:D.z.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:D.z.uuid().nullable(),quantity:xe,accepted:D.z.boolean(),reason:D.z.enum([...Aa.options,"expired"]).nullable(),properties:Pt,reservationStatus:D.z.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:On.nullable(),charges:D.z.array(D.z.discriminatedUnion("funding",[D.z.strictObject({funding:D.z.literal("balance"),sourceId:D.z.uuid(),rolloverId:D.z.uuid().nullable(),units:Nr,amount:Kt}),D.z.strictObject({funding:D.z.literal("unbilled"),units:Nr}),D.z.object({...ro,funding:D.z.literal("prepaid"),amount:Kt}).strict(),D.z.object({funding:D.z.literal("postpaid"),invoiceId:D.z.uuid(),invoiceLineId:D.z.uuid(),authorizationId:D.z.uuid(),units:xe,currency:Ie}).strict()])).max(500)}).strict().refine(e=>(e.kind==="set_usage"||e.kind==="consume"&&e.quantity==="0"?e.accepted&&e.reason===null&&e.charges.length===0&&e.reservationStatus===null:e.accepted?e.reason===null&&e.charges.length>0:e.reason!==null&&e.charges.length===0)&&e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),D.z.object({...di,type:D.z.literal("transaction"),purpose:D.z.enum(["product","invoice"]),productVersionId:D.z.uuid().nullable(),productName:D.z.string().min(1).max(120).nullable(),productVersion:D.z.number().int().positive().nullable(),invoiceId:D.z.uuid().nullable(),orderId:D.z.uuid(),originalId:D.z.uuid().nullable(),kind:D.z.enum(["purchase","refund"]),amountMinor:D.z.number().int().nonnegative().max(2e8).nullable(),currency:Ie.nullable()}).strict().refine(e=>e.currency===null==(e.amountMinor===null)&&(e.purpose==="product"?e.productVersionId!==null&&e.productName!==null&&e.productVersion!==null&&e.invoiceId===null:e.productVersionId===null&&e.productName===null&&e.productVersion===null&&e.invoiceId!==null)&&e.kind==="refund"==(e.originalId!==null)&&(e.kind!=="refund"||e.amountMinor===null||e.amountMinor>0),"Payment fact provenance is incomplete"),D.z.object({...di,...ro,type:D.z.literal("debt"),sourceId:D.z.uuid(),transactionId:D.z.uuid(),amount:Kt}).strict(),D.z.object({...di,...ro,type:D.z.literal("settlement"),sourceId:D.z.uuid(),debtId:D.z.uuid(),kind:D.z.enum(["payment","usage_refund","payment_return"]),amount:Kt}).strict()]),kp=D.z.object({customerId:D.z.uuid(),rows:D.z.array(Ib).max(50),nextCursor:xa.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");var fe=require("zod"),Tp=fe.z.object({customerId:fe.z.uuid()}).strict(),Np=fe.z.discriminatedUnion("action",[fe.z.object({customerId:fe.z.uuid(),requestId:fe.z.uuid(),action:fe.z.literal("assign"),poolId:fe.z.uuid(),memberCustomerId:fe.z.uuid()}).strict(),fe.z.strictObject({customerId:fe.z.uuid(),requestId:fe.z.uuid(),action:fe.z.literal("assign_entity"),poolId:fe.z.uuid(),entityId:fe.z.uuid()}),fe.z.object({customerId:fe.z.uuid(),requestId:fe.z.uuid(),action:fe.z.literal("release"),poolId:fe.z.uuid(),slotId:fe.z.uuid()}).strict()]),io=fe.z.number().int().nonnegative(),hc=fe.z.iso.datetime({offset:!0}),yc=fe.z.strictObject({internalId:fe.z.uuid(),id:fe.z.string(),name:fe.z.string().nullable(),version:fe.z.number().int().positive()}),jp=fe.z.enum(["active","past_due"]),Ac=fe.z.strictObject({customerId:fe.z.uuid(),licenses:fe.z.array(fe.z.strictObject({id:fe.z.uuid(),linkId:fe.z.uuid(),parent:fe.z.strictObject({customerProductId:fe.z.uuid(),status:jp,product:yc}),product:yc,planLicense:fe.z.strictObject({id:fe.z.uuid(),prepaidOnly:fe.z.boolean(),isCustom:fe.z.boolean()}).nullable(),granted:io,included:io,paidQuantity:io,usage:io,remaining:io,createdAt:hc}).refine(e=>e.granted===e.included+e.paidQuantity&&e.granted===e.usage+e.remaining,"Granted seats are included plus paid, and usage plus remaining")).max(2e3),assignments:fe.z.array(fe.z.strictObject({id:fe.z.uuid(),linkId:fe.z.uuid(),status:jp,product:yc,entity:fe.z.strictObject({internalId:fe.z.uuid(),id:fe.z.string().nullable(),name:fe.z.string().nullable()}).nullable(),beneficiary:fe.z.strictObject({internalId:fe.z.uuid(),id:fe.z.string().nullable(),name:fe.z.string().nullable()}).nullable(),startedAt:hc.nullable(),endedAt:hc.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:fe.z.boolean()});var de=require("zod"),oo=de.z.enum(["email","sms","voice","push"]),nP=de.z.enum(["resend","twilio","fcm","apns"]);var rP=de.z.string().regex(/^\+[1-9]\d{1,14}$/),vb=de.z.enum(["email_recipient","sms_segment","voice_second","push_device"]);var wb=de.z.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),Ob=de.z.strictObject({subject:wb,html:de.z.string().min(1).max(131072).optional(),text:de.z.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),Pb=de.z.strictObject({body:de.z.string().min(1).max(1600).refine(e=>e.trim().length>0)}),Cb=de.z.strictObject({text:de.z.string().trim().min(1).max(4e3),language:de.z.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:de.z.number().int().min(1).max(900)}),_b=de.z.record(de.z.string().min(1).max(64),de.z.string().max(256)).refine(e=>Object.keys(e).length<=20&&Object.keys(e).every(t=>!/^(?:indiana_|google\.|gcm\.)/i.test(t)&&t!=="aps"),"Push data contains reserved fields or too many entries"),Eb=de.z.strictObject({title:de.z.string().trim().min(1).max(200),body:de.z.string().trim().min(1).max(2e3),url:de.z.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:_b.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),Dp=de.z.discriminatedUnion("channel",[de.z.strictObject({channel:de.z.literal("email"),content:Ob}),de.z.strictObject({channel:de.z.literal("sms"),content:Pb}),de.z.strictObject({channel:de.z.literal("voice"),content:Cb}),de.z.strictObject({channel:de.z.literal("push"),content:Eb})]),Fp=de.z.strictObject({requestId:de.z.uuid(),customerId:de.z.uuid(),connectionId:de.z.uuid().optional(),message:Dp,expiresAt:de.z.iso.datetime({offset:!0})}),Rb=de.z.array(de.z.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),kb=de.z.discriminatedUnion("kind",[de.z.strictObject({kind:de.z.literal("all")}),de.z.strictObject({kind:de.z.literal("customers"),customerIds:Rb})]),iP=de.z.strictObject({name:de.z.string().trim().min(1).max(120),connectionId:de.z.uuid().optional(),message:Dp,audience:kb,frequencyLimit:de.z.number().int().min(1).max(100)}),Mp=de.z.strictObject({requestId:de.z.uuid(),channel:oo,state:de.z.enum(["allowed","denied"]),expectedRevision:de.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),qp=de.z.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Up=de.z.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),oP=de.z.strictObject({meter:vb,estimatedUnits:de.z.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:de.z.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});var Oe=require("zod");var re=require("zod");var Fr=require("zod");var ao=Fr.z.strictObject({internalFeatureId:Fr.z.uuid(),name:Fr.z.string().min(1).max(120),includedAmount:Fr.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:Fr.z.enum(["hour","day","week","month","year","lifetime"]),resetCount:Fr.z.number().int().min(1).max(100),terms:ra});var st=require("zod");var Lp=require("zod");var Mr=require("zod"),Bp=Mr.z.enum(["stripe","apple","google","merchant"]),Vp=Mr.z.enum(["membership","credit_pack","lifetime"]),uP=Mr.z.enum(["active","grace","suspended","inactive","revoked"]),lP=Mr.z.strictObject({currency:Mr.z.string().regex(/^[A-Z]{3}$/),micros:Mr.z.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var pi=Lp.z.object({provider:Bp,currency:Ie}).strict();var or=st.z.strictObject({internal_feature_id:st.z.uuid(),quantity:xe.refine(e=>/[1-9]/.test(e)),properties:Pt,entityId:st.z.uuid().optional()}),zp=st.z.strictObject({requirement:or,commerce:pi.optional(),paywallId:st.z.uuid().optional()}),jb=st.z.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),bc=st.z.strictObject({productId:st.z.string().min(1),productVersionId:st.z.string().min(1),name:st.z.string().min(1).max(120),action:st.z.enum(["purchase","upgrade","addon","topup"]),membershipId:st.z.string().min(1).nullable(),currency:Ie,amountMinor:st.z.string().regex(/^(0|[1-9]\d{0,8})$/),interval:st.z.enum(["free","week","month","year","one_time"]),intervalCount:st.z.number().int().min(1).max(156)}),qr=st.z.strictObject({internal_feature_id:st.z.string().min(1),name:st.z.string().min(1).max(120),kind:st.z.enum(["access","metered","credit"]),quantity:xe,allowed:st.z.boolean(),reason:jb.nullable(),preview:st.z.strictObject({scenario:st.z.enum(["feature_flag","usage_limit"]),candidates:st.z.array(bc).max(20)}).nullable()}).superRefine((e,t)=>{(e.allowed!==(e.reason===null)||e.allowed&&e.preview!==null||new Set(e.preview?.candidates.map(n=>n.productVersionId)).size!==(e.preview?.candidates.length??0)||e.preview?.candidates.some(n=>n.action==="upgrade"!=(n.membershipId!==null)))&&t.addIssue({code:"custom",message:"Invalid access recommendation"})}),AP=st.z.strictObject({paywallId:st.z.uuid(),requirement:or});var Ia=re.z.object({plan:re.z.string().min(1).max(200).optional(),coupon:re.z.uuid().optional(),promotionCode:re.z.uuid().optional(),picker:re.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),Sa=re.z.object({text:re.z.string().optional(),label:re.z.string().optional(),alt:re.z.string().optional(),html:re.z.string().max(32768).optional(),price:re.z.object({current:re.z.string(),original:re.z.string().nullable(),period:re.z.string()}).optional(),code:re.z.string().optional(),countdownAt:re.z.iso.datetime().optional(),planId:re.z.string().min(1).max(200).optional(),planVersionId:re.z.string().min(1).max(200).optional(),currency:Ie.optional(),couponId:re.z.uuid().optional(),offerId:re.z.uuid().optional(),unavailable:re.z.boolean().optional(),unavailableReason:re.z.string().optional(),missing:re.z.array(re.z.string()).optional()}).strict(),mi=re.z.object({paywall:qr.optional(),nodes:re.z.record(re.z.string(),re.z.object({base:Sa,picker:re.z.string().optional(),byPlan:re.z.record(re.z.string(),Sa).optional()}).strict()),plans:re.z.record(re.z.string(),re.z.object({id:re.z.string().min(1).max(200),versionId:re.z.string().min(1).max(200),available:re.z.boolean(),name:re.z.string(),price:re.z.string(),period:re.z.string(),currency:Ie.optional(),amountMinor:re.z.number().int().nonnegative().optional(),interval:re.z.enum(["free","week","month","year","one_time"]).optional(),intervalCount:re.z.number().int().positive().optional(),prepaid:re.z.array(ao).max(100).optional()}).strict()),pickers:re.z.record(re.z.string(),re.z.object({options:re.z.array(re.z.string().min(1).max(200)).max(20),selected:re.z.string().min(1).max(200).nullable()}).strict()),quantities:re.z.record(re.z.string(),re.z.strictObject({minimum:re.z.number().int().nonnegative(),maximum:re.z.number().int().nonnegative(),step:re.z.number().int().positive(),value:re.z.number().int().nonnegative(),label:re.z.string(),available:re.z.boolean()})).optional(),diagnostics:re.z.array(re.z.object({nodeId:re.z.string(),message:re.z.string()}).strict())}).strict();function $p(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}var I=require("zod");function Tb(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function Gp(e){let t={};function n(r){var i;if(Tb(r)){let a=t[i=r.interaction.pickerId]??(t[i]={ids:[],defaultId:null});for(let s of r.children){let c=s.type==="stack"?s.bind?.plan:void 0;c&&!a.ids.includes(c)&&a.ids.push(c)}let o=r.children[r.interaction.defaultIndex];!a.defaultId&&o?.type==="stack"&&(a.defaultId=o.bind?.plan??null)}r.type==="stack"&&r.children.forEach(n)}return e.pages.forEach(r=>n(r.root)),t}var Fn=require("zod"),Kp=Fn.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),va=Fn.z.strictObject({tiers:Fn.z.array(Fn.z.strictObject({id:Kp,name:Fn.z.string().trim().min(1).max(80)})).min(1).max(8),assignments:Fn.z.array(Fn.z.strictObject({productVersionId:Fn.z.string().min(1).max(200),tierId:Kp,period:Fn.z.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let n=e.tiers.map(r=>r.id);(new Set(n).size!==n.length||new Set(e.assignments.map(r=>r.productVersionId)).size!==e.assignments.length||new Set(e.assignments.map(r=>`${r.tierId}:${r.period}`)).size!==e.assignments.length||e.assignments.some(r=>!n.includes(r.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function wa(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}var ce=require("zod");var Nb=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],Hp=ce.z.enum(Nb),Qp=ce.z.object({source:Hp,layout:ce.z.enum(["full","compact"]),resourceKey:Er.optional(),pageSize:ce.z.number().int().min(1).max(50),showSources:ce.z.boolean(),allowPurchase:ce.z.boolean(),outputs:ce.z.object({billing_adjustment:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((e,t)=>{(e.outputs?.billing_authorization||e.outputs?.billing_adjustment)&&e.source!=="billing_controls"&&t.addIssue({code:"custom",message:"Payment authorization routes belong to the billing controls component."}),e.resourceKey&&!["credit_balance","credit_transactions"].includes(e.source)&&t.addIssue({code:"custom",message:"\u8FD9\u4E2A\u6570\u636E\u6E90\u4E0D\u80FD\u7ED1\u5B9A\u79EF\u5206\u8D44\u6E90\u3002"}),e.showSources&&e.source!=="credit_balance"&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u4F59\u989D\u53EF\u4EE5\u5C55\u5F00\u6765\u6E90\u3002"}),e.allowPurchase&&!["credit_packs","customer_plans","membership"].includes(e.source)&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u5305\u3001\u5957\u9910\u4E0E\u4F1A\u5458\u7EC4\u4EF6\u53EF\u4EE5\u542F\u7528\u4EA4\u6613\u3002"})}),kt=ce.z.string().max(2e3),Jp=ce.z.object({id:ce.z.string().max(100),label:kt,detail:ce.z.array(kt).max(12),value:kt.optional(),status:kt.optional(),facts:ce.z.array(ce.z.object({label:kt,value:kt}).strict()).max(1e3),purchaseId:ce.z.uuid().optional(),invoiceUrl:ce.z.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:ce.z.array(ce.z.strictObject({action:ce.z.literal("invoice_open"),label:kt})).max(1).optional(),membershipActions:ce.z.array(ce.z.object({value:ce.z.string().max(100),label:kt}).strict()).max(3).optional()}).strict(),Db=ce.z.object({key:Er,name:kt,spendable:kt,reserved:kt,available:kt,expiry:kt.nullable(),sources:ce.z.array(Jp).max(50),sourceCount:ce.z.number().int().nonnegative(),sourcePage:ce.z.number().int().positive(),hasNextSources:ce.z.boolean(),hasPreviousSources:ce.z.boolean()}).strict(),Fb=ce.z.object({source:Hp,status:ce.z.enum(["idle","loading","ready","error"]),stale:ce.z.boolean(),preview:ce.z.boolean(),errorCode:ce.z.string().max(80).optional(),errorMessage:kt.optional(),resources:ce.z.array(Db).max(500),rows:ce.z.array(Jp).max(50),hasNext:ce.z.boolean(),hasPrevious:ce.z.boolean(),page:ce.z.number().int().positive(),filter:ce.z.string().max(40),updatedAt:ce.z.iso.datetime().optional(),buyingId:ce.z.uuid().optional(),membershipBusy:ce.z.boolean().optional(),billingBusy:ce.z.boolean().optional(),membershipReview:ce.z.object({title:kt,note:kt,facts:ce.z.array(ce.z.object({label:kt,value:kt}).strict()).max(100)}).strict().optional(),membershipResult:kt.optional()}).strict(),Zp=ce.z.object({nodes:ce.z.record(ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Fb)}).strict(),CP=ce.z.object({nodeId:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:ce.z.enum(["refresh","next","previous","filter","buy_pack","billing_portal","billing_authorization","billing_adjustment","invoice_open","membership_preview","membership_confirm","membership_dismiss","sources_next","sources_previous"]),value:ce.z.string().max(100).optional()}).strict();var K=require("zod"),St={state:32,enumValues:64,derived:96,bindings:256,controls:64,timers:4,effects:8,depth:12,expressionNodes:2e3},Yp=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]),Ft=K.z.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/).refine(e=>!Yp.has(e),"Reserved UI identifier"),xc=K.z.union([K.z.string().max(2e3),K.z.number().finite(),K.z.boolean(),K.z.null()]),Mb=K.z.discriminatedUnion("type",[K.z.strictObject({type:K.z.literal("enum"),values:K.z.array(xc).min(1).max(St.enumValues),default:xc}),K.z.strictObject({type:K.z.literal("number"),min:K.z.number().finite(),max:K.z.number().finite(),step:K.z.number().finite().positive(),default:K.z.number().finite()}),K.z.strictObject({type:K.z.literal("text"),maxLength:K.z.number().int().min(0).max(2e3),default:K.z.string().max(2e3).nullable()}),K.z.strictObject({type:K.z.literal("boolean"),default:K.z.boolean()})]);function Ic(e,t){if(e.type==="enum")return e.values.some(r=>r===t);if(e.type==="boolean")return typeof t=="boolean";if(e.type==="text")return t===null||typeof t=="string"&&t.length<=e.maxLength;if(typeof t!="number"||!Number.isFinite(t)||t<e.min||t>e.max)return!1;let n=(t-e.min)/e.step;return Number.isFinite(n)&&Math.abs(n-Math.round(n))<=Math.min(1e-7,Math.max(1,Math.abs(n))*Number.EPSILON*8)}var qb=Mb.superRefine((e,t)=>{e.type==="enum"&&new Set(e.values).size!==e.values.length&&t.addIssue({code:"custom",path:["values"],message:"UI enum values must be unique"}),e.type==="number"&&e.min>e.max&&t.addIssue({code:"custom",path:["max"],message:"UI number range is reversed"}),Ic(e,e.default)||t.addIssue({code:"custom",path:["default"],message:"UI default must match its state definition"})}),Ub=["add","sub","mul","div","min","max","round","floor","eq","ne","gt","gte","lt","lte","and","or","not","if","concat","number","parse_number","money","lookup","now","duration"];function Bb(e,t){return e==="now"?t===0:e==="concat"?!0:e==="lookup"?t>=4&&t%2===0:e==="if"?t===3:["sub","div","eq","ne","gt","gte","lt","lte"].includes(e)?t===2:["round","floor","not","number","parse_number","money","duration"].includes(e)?t===1:t>=1}var Br=K.z.lazy(()=>K.z.union([xc,K.z.strictObject({ref:Ft}),K.z.strictObject({op:K.z.enum(Ub),args:K.z.array(Br).max(St.expressionNodes)}).superRefine((e,t)=>{Bb(e.op,e.args.length)||t.addIssue({code:"custom",path:["args"],message:"Invalid UI expression arity"})})]));function Pn(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function Ur(e,t,n){if(!e||typeof e!="object")return!0;if(!Pn(e))return t.addIssue({code:"custom",path:n,message:"UI objects must be plain data"}),!1;for(let r of Object.keys(e)){if(Yp.has(r))return t.addIssue({code:"custom",path:[...n,r],message:"Reserved UI object key"}),!1;let i=Object.getOwnPropertyDescriptor(e,r);if(i&&!Object.hasOwn(i,"value"))return t.addIssue({code:"custom",path:[...n,r],message:"UI objects cannot contain accessors"}),!1}return!0}function fi(e,t,n,r){let i=[{value:e,depth:1,path:n}];for(;i.length;){let a=i.pop();if(++r.nodes>St.expressionNodes||a.depth>St.depth){t.addIssue({code:"custom",path:a.path,message:"UI expression budget exceeded"});return}if(!Ur(a.value,t,a.path))return;if(Pn(a.value)&&Array.isArray(a.value.args)){if(a.value.args.length>St.expressionNodes){t.addIssue({code:"custom",path:[...a.path,"args"],message:"UI expression budget exceeded"});return}for(let o=a.value.args.length-1;o>=0;o--)i.push({value:a.value.args[o],depth:a.depth+1,path:[...a.path,"args",o]})}}}var EP=K.z.unknown().superRefine((e,t)=>{fi(e,t,[],{nodes:0})}).pipe(Br),Sc=K.z.record(Ft,Br).refine(e=>Object.keys(e).length>0&&Object.keys(e).length<=St.state,"UI assignments need 1\u201332 state keys"),Vb=K.z.strictObject({target:Ft,property:K.z.enum(["text","visible","disabled","checked","value","class","aria-label","aria-selected","aria-checked","aria-valuetext","tabindex"]),expression:Br,className:Ft.optional()}).superRefine((e,t)=>{e.property==="class"!=(e.className!==void 0)&&t.addIssue({code:"custom",path:["className"],message:"Only class bindings require a safe className"})}),Lb=K.z.discriminatedUnion("type",[K.z.strictObject({type:K.z.literal("scroll_latch"),target:Ft,state:Ft}),K.z.strictObject({type:K.z.literal("input"),target:Ft,state:Ft,set:Sc.optional()}),K.z.strictObject({type:K.z.literal("action"),target:Ft,set:Sc}),K.z.strictObject({type:K.z.literal("carousel"),target:Ft,state:Ft,initialIndex:K.z.number().int().nonnegative().optional(),maxWidth:K.z.number().int().min(1).max(1e4).optional(),previousTarget:Ft.optional(),nextTarget:Ft.optional(),inactiveTargets:K.z.array(Ft).max(20).optional(),inactiveMaxWidth:K.z.number().int().min(1).max(1e4).optional()})]),zb=K.z.strictObject({afterMs:K.z.number().int().min(0).max(6e4),set:Sc}),$b=K.z.strictObject({type:K.z.literal("mosaic_waves"),target:Ft,color:K.z.string().regex(/^#[0-9a-fA-F]{6}$/),hotColor:K.z.string().regex(/^#[0-9a-fA-F]{6}$/),enabled:Br.optional(),speed:K.z.number().min(0).max(4).optional(),pitch:K.z.number().min(.05).max(4).optional(),fill:K.z.number().min(.05).max(1).optional(),feather:K.z.number().min(0).max(1).optional(),warp:K.z.number().min(0).max(4).optional(),warpScale:K.z.number().min(0).max(32).optional(),detailScale:K.z.number().min(0).max(32).optional(),waveScale:K.z.number().min(0).max(32).optional(),falloff:K.z.number().min(.1).max(32).optional(),brightness:K.z.number().min(0).max(32).optional(),ambient:K.z.number().min(0).max(1).optional(),gamma:K.z.number().min(.05).max(8).optional(),vignette:K.z.number().min(0).max(1).optional(),opacity:K.z.number().min(0).max(1).optional()}),Gb=K.z.strictObject({type:K.z.literal("number_counter"),target:Ft,value:Br,prefix:K.z.string().max(20).optional(),format:K.z.enum(["number","short"]).optional()}),Kb=K.z.strictObject({state:K.z.record(Ft,qb).refine(e=>Object.keys(e).length<=St.state,"Too many UI state keys").optional(),derived:K.z.record(Ft,Br).refine(e=>Object.keys(e).length<=St.derived,"Too many UI derived keys").optional(),bindings:K.z.array(Vb).max(St.bindings).optional(),controls:K.z.array(Lb).max(St.controls).optional(),timers:K.z.array(zb).max(St.timers).optional(),effects:K.z.array(K.z.discriminatedUnion("type",[$b,Gb])).max(St.effects).optional(),clock:K.z.boolean().optional()});function Hb(e,t){if(!Ur(e,t,[])||!Pn(e))return;for(let[r,i]of[["state",St.state],["derived",St.derived]]){let a=e[r];if(!Ur(a,t,[r]))return;if(Pn(a)&&Object.keys(a).length>i){t.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}}for(let[r,i]of[["bindings",St.bindings],["controls",St.controls],["timers",St.timers],["effects",St.effects]])if(Array.isArray(e[r])&&e[r].length>i){t.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}if(Array.isArray(e.effects)){for(let[r,i]of e.effects.entries())if(!Ur(i,t,["effects",r]))return}if(Pn(e.state))for(let[r,i]of Object.entries(e.state)){if(!Ur(i,t,["state",r]))return;if(Pn(i)&&Array.isArray(i.values)&&i.values.length>St.enumValues){t.addIssue({code:"custom",path:["state",r,"values"],message:"Too many UI enum values"});return}}let n={nodes:0};if(Pn(e.derived))for(let[r,i]of Object.entries(e.derived))fi(i,t,["derived",r],n);for(let r of["bindings","controls","timers"]){let i=e[r];if(Array.isArray(i)){for(let[a,o]of i.entries())if(!(!Ur(o,t,[r,a])||!Pn(o))){if(r==="bindings")fi(o.expression,t,[r,a,"expression"],n);else if(Ur(o.set,t,[r,a,"set"])&&Pn(o.set)){if(Object.keys(o.set).length>St.state){t.addIssue({code:"custom",path:[r,a,"set"],message:"Too many UI assignments"});return}for(let[s,c]of Object.entries(o.set))fi(c,t,[r,a,"set",s],n)}if(n.nodes>St.expressionNodes)return}}}if(Array.isArray(e.effects))for(let[r,i]of e.effects.entries())Pn(i)&&i.type==="number_counter"?fi(i.value,t,["effects",r,"value"],n):Pn(i)&&i.enabled!==void 0&&fi(i.enabled,t,["effects",r,"enabled"],n)}function Wp(e){let t=[],n=[e];for(;n.length;){let r=n.pop();!r||typeof r!="object"||("ref"in r?t.push(r.ref):n.push(...r.args))}return t}var Xp=K.z.unknown().superRefine(Hb).pipe(Kb).superRefine((e,t)=>{let n=e.state??{},r=e.derived??{},i=new Set([...Object.keys(n),...Object.keys(r)]),a=(g,d)=>{for(let h of Wp(g))i.has(h)||t.addIssue({code:"custom",path:d,message:`Unknown UI reference: ${h}`})};for(let[g,d]of Object.entries(e.derived??{}))Object.hasOwn(n,g)&&t.addIssue({code:"custom",path:["derived",g],message:"UI state and derived identifiers must be distinct"}),a(d,["derived",g]);let o=new Set,s=new Set,c=g=>{if(o.has(g))return!1;if(s.has(g))return!0;o.add(g);for(let d of Wp(r[g]))if(Object.hasOwn(r,d)&&!c(d))return!1;return o.delete(g),s.add(g),!0};for(let g of Object.keys(r))if(!c(g)){t.addIssue({code:"custom",path:["derived",g],message:"Cyclic UI derived references"});break}for(let[g,d]of(e.bindings??[]).entries())a(d.expression,["bindings",g,"expression"]);let u=new Set;for(let[g,d]of(e.effects??[]).entries())u.has(d.target)&&t.addIssue({code:"custom",path:["effects",g,"target"],message:"Effect targets must be unique"}),u.add(d.target),d.type==="number_counter"?(a(d.value,["effects",g,"value"]),typeof d.value=="number"&&Math.abs(d.value)>1e12&&t.addIssue({code:"custom",path:["effects",g,"value"],message:"Counter values must be within the display bound"})):d.enabled!==void 0&&a(d.enabled,["effects",g,"enabled"]);let l=(g,d)=>{for(let[h,R]of Object.entries(g))Object.hasOwn(n,h)||t.addIssue({code:"custom",path:[...d,h],message:"UI assignments can only update declared state"}),a(R,[...d,h])},m=new Set,f=new Set;for(let[g,d]of(e.controls??[]).entries()){if(d.type==="carousel"&&d.inactiveMaxWidth!==void 0&&d.inactiveTargets===void 0&&t.addIssue({code:"custom",path:["controls",g,"inactiveMaxWidth"],message:"Inactive width requires inactive article targets"}),d.type==="carousel")for(let h of d.inactiveTargets??[])(h===d.target||f.has(h))&&t.addIssue({code:"custom",path:["controls",g,"inactiveTargets"],message:"Inactive article targets must have one carousel owner"}),f.add(h);if(d.type==="carousel")for(let h of["previousTarget","nextTarget"]){let R=d[h];R!==void 0&&((R===d.target||m.has(R)||(e.controls??[]).some(y=>y.target===R))&&t.addIssue({code:"custom",path:["controls",g,h],message:"Carousel navigation needs a distinct, exclusive button target"}),m.add(R))}if(d.type!=="action"){let h=Object.hasOwn(n,d.state)?n[d.state]:void 0;(!h||d.type==="input"&&h.type==="enum"&&h.values.some(R=>typeof R!="string"))&&t.addIssue({code:"custom",path:["controls",g,"state"],message:"Control needs a supported declared UI state"}),d.type==="carousel"&&(h?.type!=="number"||!Number.isInteger(h.min)||h.min<0||!Number.isInteger(h.max)||h.step!==1||d.initialIndex!==void 0&&!Ic(h,d.initialIndex))&&t.addIssue({code:"custom",path:["controls",g],message:"Carousel needs bounded nonnegative integer index state"}),d.type==="scroll_latch"&&h?.type!=="boolean"&&t.addIssue({code:"custom",path:["controls",g,"state"],message:"Scroll latches require boolean UI state"})}(d.type==="input"||d.type==="action")&&d.set&&l(d.set,["controls",g,"set"])}for(let[g,d]of(e.timers??[]).entries())l(d.set,["timers",g,"set"])});var it=require("zod"),Qb=it.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Oa=it.z.discriminatedUnion("type",[it.z.object({type:it.z.literal("fixed"),productVersionId:it.z.string().min(1).max(200)}).strict(),it.z.object({type:it.z.literal("picker"),pickerId:Qb,allowedProductVersionIds:it.z.array(it.z.string().min(1).max(200)).min(1).max(20)}).strict().refine(e=>new Set(e.allowedProductVersionIds).size===e.allowedProductVersionIds.length,"Product choices must be unique")]),Jb=it.z.strictObject({min:it.z.number().finite().min(1).max(1800),max:it.z.number().finite().min(1).max(1800),viewport:it.z.number().finite().min(1).max(100)}).refine(e=>e.min<=e.max,"Desktop width range is reversed"),em={desktopWidth:Jb.optional(),mobile:it.z.enum(["sheet","fullscreen"]).optional(),backdrop:it.z.enum(["none","scrim","dim","strong-dim","blur"]).optional()},Cn=it.z.discriminatedUnion("type",[it.z.strictObject({type:it.z.literal("modal"),size:it.z.enum(["sm","md","lg"]),...em}),it.z.strictObject({type:it.z.literal("sheet"),size:it.z.enum(["sm","md","lg"]),...em}),it.z.strictObject({type:it.z.literal("fullscreen")}),it.z.strictObject({type:it.z.literal("inline")})]);var Wb=4,En={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:32768,documentBytes:2e5},co=I.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ue=I.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Yb=I.z.enum(["none","xs","sm","md","lg","xl"]),Xb=I.z.enum(["none","sm","md","lg","full"]),vc=I.z.string().regex(/^#[0-9a-fA-F]{6}$/),Oc=I.z.string().max(2048).refine(e=>{try{let t=new URL(e);return t.protocol==="https:"&&t.hostname.length>0}catch{return!1}},"\u53EA\u652F\u6301 https \u94FE\u63A5"),wc=I.z.union([Oc,I.z.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),I.z.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),I.z.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),tm=I.z.object({primary:vc,background:vc,text:vc,radius:Xb,font:I.z.enum(["system","serif","rounded","mono"]),fontAssets:I.z.object({family:I.z.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/),faces:I.z.array(I.z.object({url:Oc,weight:I.z.number().int().min(100).max(900).multipleOf(100),family:I.z.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/).optional()}).strict()).min(1).max(4)}).strict().optional()}).strict(),uo=I.z.union([I.z.enum(["primary","text","muted","background","surface"]),I.z.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),Me=(e,t)=>I.z.number().int().min(e).max(t),nm=I.z.union([I.z.enum(["fit","fill"]),Me(1,1200)]),ex=I.z.object({top:Me(0,200),right:Me(0,200),bottom:Me(0,200),left:Me(0,200)}).strict(),tx=I.z.object({top:Me(-100,200),right:Me(-100,200),bottom:Me(-100,200),left:Me(-100,200)}).strict(),rm=I.z.object({x:Me(0,100),y:Me(0,100)}).strict(),nx=I.z.discriminatedUnion("type",[I.z.object({type:I.z.literal("color"),color:uo}).strict(),I.z.object({type:I.z.literal("linear"),angle:Me(0,360),stops:I.z.array(I.z.object({color:uo,at:Me(0,100)}).strict()).min(2).max(4)}).strict(),I.z.object({type:I.z.literal("image"),src:wc,fit:I.z.enum(["cover","contain"]),position:rm.optional()}).strict()]),rx=I.z.discriminatedUnion("type",[I.z.object({type:I.z.literal("rect"),radius:I.z.union([Me(0,200),I.z.object({topLeft:Me(0,200),topRight:Me(0,200),bottomRight:Me(0,200),bottomLeft:Me(0,200)}).strict()])}).strict(),I.z.object({type:I.z.literal("pill")}).strict()]),ix=I.z.object({width:Me(0,12),color:uo,style:I.z.enum(["solid","dashed"])}).strict(),ox=I.z.object({x:Me(-40,40),y:Me(-40,40),blur:Me(0,80),spread:Me(-20,40),color:uo}).strict(),ax=I.z.object({font:I.z.enum(["system","serif","rounded","mono"]),size:Me(8,96),weight:I.z.number().int().min(100).max(900).multipleOf(100),lineHeight:I.z.number().min(.8).max(3),letterSpacing:I.z.number().min(-5).max(20),color:uo,align:I.z.enum(["start","center","end"]),italic:I.z.boolean(),decoration:I.z.enum(["none","underline","line-through"]),transform:I.z.enum(["none","uppercase"])}).strict().partial(),Vr=I.z.object({width:nm,height:nm,padding:ex,margin:tx,gap:Me(0,120),grow:I.z.union([I.z.boolean(),I.z.number().min(0).max(12)]),background:nx,opacity:I.z.number().min(0).max(1),clipContent:I.z.boolean(),shape:rx,border:ix,shadow:ox,text:ax}).strict().partial(),tn={id:co,name:I.z.string().trim().min(1).max(60).optional(),hidden:I.z.boolean().optional(),style:Vr.optional(),fallback:Ue.optional()},sx=I.z.object({...tn,type:I.z.literal("text"),productField:I.z.enum(["name","price","trial","period"]).optional(),feature:I.z.object({id:I.z.uuid(),field:I.z.enum(["name","allowance"])}).strict().optional(),text:Ue,variant:I.z.enum(["title","heading","body","caption"])}).strict(),cx=I.z.object({...tn,type:I.z.literal("image"),src:wc,localizedSrc:I.z.record(wn,wc).optional(),alt:Ue,aspect:I.z.enum(["auto","1:1","4:3","16:9","3:1"]),fit:I.z.enum(["cover","contain"]),position:rm.optional()}).strict(),ux=I.z.object({...tn,type:I.z.literal("button"),label:Ue,variant:I.z.enum(["primary","secondary","link"]),action:Ue,purpose:I.z.enum(["purchase","navigation","close"]).optional(),bind:Ia.optional()}).strict(),lx=I.z.object({...tn,type:I.z.literal("divider")}).strict(),dx=I.z.object({...tn,type:I.z.literal("customer_data"),title:Ue,data:Qp}).strict(),px=I.z.object({...tn,type:I.z.literal("spacer"),size:Yb}).strict(),mx=I.z.object({...tn,type:I.z.literal("custom_html"),html:I.z.record(wn,I.z.string().max(En.customHtml)),css:I.z.string().max(En.customCss),ui:Xp.optional()}).strict(),fx=I.z.object({...tn,type:I.z.literal("price"),fallback:Ue,parts:I.z.object({current:Vr.optional(),original:Vr.optional(),period:Vr.optional()}).strict().optional()}).strict(),gx=I.z.object({...tn,type:I.z.literal("coupon_code"),label:Ue,fallback:Ue}).strict(),hx=I.z.object({...tn,type:I.z.literal("countdown"),source:I.z.enum(["offer.ends_at","offer.expires_at","fixed"]),at:I.z.iso.datetime().optional(),granularity:I.z.enum(["day","hour","minute","second"]),expired:Ue,fallback:Ue}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),yx=I.z.object({...tn,type:I.z.literal("plan_picker"),label:Ue,fallback:Ue,planIds:I.z.array(I.z.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:I.z.string().min(1).max(200).optional(),grouping:va.safeExtend({monthLabel:Ue,yearLabel:Ue,unavailableLabel:Ue}).optional(),states:I.z.object({selected:Vr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!wa(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),Ax=I.z.object({...tn,type:I.z.literal("quantity_picker"),bind:Ia.optional(),label:Ue,fallback:Ue,internalFeatureId:I.z.uuid(),minimumQuantity:Me(0,1e4),maximumQuantity:Me(0,1e4),defaultQuantity:Me(0,1e4),step:Me(1,1e4)}).strict().refine(e=>e.minimumQuantity<=e.defaultQuantity&&e.defaultQuantity<=e.maximumQuantity&&(e.defaultQuantity-e.minimumQuantity)%e.step===0,"Quantity controls require a Product binding and valid bounds"),bx=I.z.discriminatedUnion("type",[I.z.object({type:I.z.literal("input"),label:Ue,keyboard:I.z.enum(["text","email","tel","url"]),maxLength:Me(1,500)}).strict(),I.z.object({type:I.z.literal("multiselect"),label:Ue,min:Me(0,50),max:Me(1,50)}).strict(),I.z.object({type:I.z.literal("select"),label:Ue,defaultIndex:Me(0,49),purpose:I.z.enum(["option","product","tier"]).optional(),pickerId:co.optional(),selectedStyle:Vr.optional()}).strict(),I.z.object({type:I.z.literal("tabs"),label:Ue,defaultIndex:Me(0,49),purpose:I.z.literal("tier").optional()}).strict(),I.z.object({type:I.z.literal("toggle"),label:Ue,defaultEnabled:I.z.boolean()}).strict(),I.z.object({type:I.z.literal("carousel"),label:Ue}).strict()]),_n={...tn,type:I.z.literal("stack"),direction:I.z.enum(["vertical","horizontal","overlay"]),align:I.z.enum(["start","center","end","stretch"]),justify:I.z.enum(["start","center","end","between"]),productSlot:I.z.object({index:Me(0,19),period:I.z.enum(["month","year"]).optional(),requireBinding:I.z.boolean().optional()}).strict().optional(),interaction:bx.optional(),states:I.z.object({selected:Vr.optional()}).strict().optional(),purpose:I.z.literal("benefits").optional(),purchaseAction:Ue.optional(),buttonVariant:I.z.enum(["primary","secondary","link"]).optional(),bind:Ia.optional()},im=I.z.lazy(()=>I.z.object({...tn,type:_n.type,direction:_n.direction,align:_n.align,justify:_n.justify,children:I.z.array(xx).max(En.children),productSlot:_n.productSlot,interaction:_n.interaction,states:_n.states,purpose:_n.purpose,purchaseAction:_n.purchaseAction,buttonVariant:_n.buttonVariant,bind:_n.bind}).strict()),xx=I.z.lazy(()=>I.z.union([im,sx,cx,ux,lx,px,mx,fx,gx,hx,yx,Ax,dx])),Sx=I.z.union([I.z.string().max(500),I.z.number().finite(),I.z.boolean(),I.z.null()]),so={id:Ue,event:Ue,properties:I.z.record(Ue,Sx).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},Ix=I.z.discriminatedUnion("type",[I.z.object({...so,type:I.z.literal("navigate"),close:I.z.literal(!1),pageId:co}).strict(),I.z.object({...so,type:I.z.literal("event"),close:I.z.boolean()}).strict(),I.z.object({...so,type:I.z.literal("close"),close:I.z.literal(!0)}).strict(),I.z.object({...so,type:I.z.literal("open_url"),close:I.z.boolean(),url:Oc}).strict(),I.z.object({...so,type:I.z.literal("claim_offer"),close:I.z.boolean(),couponId:I.z.uuid()}).strict()]),vx=I.z.object({defaultLocale:wn,locales:I.z.record(wn,I.z.record(Ue,I.z.string().max(En.stringLength)))}).strict(),wx=I.z.enum(["popup","paywall","onboarding","page","banner"]);var Ox=I.z.object({kind:I.z.literal("screen"),schemaVersion:I.z.literal(Wb),name:I.z.string().trim().min(1).max(80),surface:wx,initialPageId:co.optional(),presentation:Cn,theme:tm,pages:I.z.array(I.z.object({id:co,name:I.z.string().trim().min(1).max(60),root:im,theme:tm.optional(),editorPosition:I.z.object({x:I.z.number().finite().min(-1e5).max(1e5),y:I.z.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(En.pages),strings:vx,actions:I.z.array(Ix).max(En.actions)}).strict();function Ht(e,t){for(let n of e.pages)Wn(n.root,t)}var dn=Ox.superRefine((e,t)=>{let n=En;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(l=>l.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let l of e.actions)l.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(m=>m.id===l.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>n.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${n.pages} \u4E2A`}),e.actions.length>n.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${n.actions} \u4E2A`});let r=l=>t.addIssue({code:"custom",message:l}),i=Object.keys(e.strings.locales);i.includes(e.strings.defaultLocale)||r("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),i.length>En.locales&&r(`\u6700\u591A ${En.locales} \u79CD\u8BED\u8A00`);let a=new Set;for(let l of e.actions)a.has(l.id)&&r(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${l.id}`),a.add(l.id);let o=new Set;for(let l of e.pages)["next","back"].includes(l.id)&&r(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${l.id}`),o.has(l.id)&&r(`\u9875\u9762 id \u91CD\u590D\uFF1A${l.id}`),o.add(l.id);let s=new Set,c=0,u=!1;Ht(e,(l,m)=>{if(c++,m>En.depth&&(u=!0),s.has(l.id)&&r(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${l.id}`),s.add(l.id),l.type==="button"&&!a.has(l.action)&&r(`\u6309\u94AE ${l.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${l.action}`),l.type==="custom_html")for(let f of Object.keys(l.html))i.includes(f)||r(`\u81EA\u5B9A\u4E49 HTML ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${f}`);if(l.type==="image")for(let f of Object.keys(l.localizedSrc??{}))i.includes(f)||r(`\u56FE\u7247 ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${f}`)}),c>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),u&&r(`\u5C42\u7EA7\u6700\u591A ${En.depth} \u5C42`)});function Wn(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)Wn(i,t,n+1,e)}function Pa(e){let t=[],n=new Set;return Ht(e,r=>{let i=(a,o,s)=>{n.has(a)||(n.add(a),t.push({key:a,nodeId:r.id,nodeType:r.type,field:o,required:s}))};r.type==="stack"&&r.interaction&&i(r.interaction.label,"label",!0),r.fallback&&i(r.fallback,"text",!0),r.type==="text"&&i(r.text,"text",!0),r.type==="customer_data"&&i(r.title,"title",!0),(r.type==="plan_picker"||r.type==="quantity_picker"||r.type==="coupon_code")&&i(r.label,"label",!0),r.type==="plan_picker"&&r.grouping&&(i(r.grouping.monthLabel,"label",!0),i(r.grouping.yearLabel,"label",!0),i(r.grouping.unavailableLabel,"text",!0)),r.type==="countdown"&&i(r.expired,"text",!0),r.type==="button"&&i(r.label,"label",!0),r.type==="image"&&(i(`image:${r.id}`,"src",!1),i(r.alt,"alt",!1)),r.type==="custom_html"&&i(`html:${r.id}`,"html",!0)}),t}function Px(e,t,n){if(t.field==="html"){let r;return Ht(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=lo(e,t.nodeId);return r?.type==="image"?r.localizedSrc?.[n]??(n===e.strings.defaultLocale?r.src:void 0):void 0}return e.strings.locales[n]?.[t.key]}function ar(e){let t=Pa(e).filter(r=>r.required);return Object.keys(e.strings.locales).sort((r,i)=>r===e.strings.defaultLocale?-1:i===e.strings.defaultLocale?1:0).map(r=>{let i=t.filter(a=>!Px(e,a,r)?.trim()).map(a=>a.key);return{locale:r,total:t.length,filled:t.length-i.length,missing:i,complete:i.length===0}})}function Cx(e,t){let n=null;return Wn(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function lo(e,t){for(let n of e.pages){let r=Cx(n.root,t);if(r)return r}return null}var Mt=require("zod"),It=Mt.z.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/).refine(e=>e.split(".").every(t=>t.length>0&&!["__proto__","constructor","prototype"].includes(t)),"Reserved or empty variable path"),Pc=Mt.z.strictObject({type:Mt.z.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:Mt.z.boolean(),enum:Mt.z.array(Mt.z.string().max(255)).min(1).max(100).optional()}),gi=Pc.extend({type:Mt.z.enum([...Pc.shape.type.options,"array"]),items:Pc.optional()}).superRefine((e,t)=>{(e.type==="array"!=!!e.items||e.enum&&e.type!=="string"||e.items?.enum&&e.items.type!=="string")&&t.addIssue({code:"custom",message:"Array requires items; only strings support enum"})}),hi=gi.safeExtend({source:Mt.z.discriminatedUnion("type",[Mt.z.strictObject({type:Mt.z.literal("input")}),Mt.z.strictObject({type:Mt.z.literal("node")}),Mt.z.strictObject({type:Mt.z.enum(["parameter","attribute"]),key:It})])}),VP=Mt.z.record(It,hi),Cc=Mt.z.record(It,It).refine(e=>Object.keys(e).length<=20);function An(e,t){return e?t===null?e.nullable:e.enum&&(typeof t!="string"||!e.enum.includes(t))?!1:e.type==="array"?Array.isArray(t)&&t.length<=100&&!!e.items&&t.every(n=>An(e.items,n)):["offering_version","reward","paywall_version"].includes(e.type)?typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===2&&t.type===e.type&&Mt.z.uuid().safeParse(t.id).success:e.type==="json"||(e.type==="strings"?Array.isArray(t)&&t.every(n=>typeof n=="string"):typeof t===e.type):!1}function _c(e,t){return e.nullable&&!t.nullable?!1:t.type==="json"?!0:e.type!==t.type||t.enum&&(!e.enum||e.enum.some(n=>!t.enum.includes(n)))?!1:e.type!=="array"||!!e.items&&!!t.items&&_c(e.items,t.items)}function Ca(e,t){let n={};for(let[r,i]of Object.entries(e)){let a=i.source,o=a.type==="input"?t.answers:a.type==="node"?t.results??{}:a.type==="parameter"?t.parameters:t.attributes,s=a.type==="parameter"||a.type==="attribute"?a.key:r,c=Object.hasOwn(o,s),u=o[s];if(a.type==="attribute"&&s.includes(".")&&(!c||s.startsWith("merchandise."))){u=o,c=!0;for(let l of s.split(".")){if(!u||typeof u!="object"||!Object.hasOwn(u,l)||Array.isArray(u)&&(!/^(0|[1-9]\d*)$/.test(l)||Number(l)>=u.length)){c=!1;break}u=u[l]}}if(!(!c||u===void 0)){if(!An(i,u))throw new Error(`Invalid variable value: ${r}`);n[r]=u}}return n}function yi(e,t){let n={};for(let[r,i]of Object.entries(e.writes??{})){if(!Object.hasOwn(t,r))throw new Error(`Node output is missing: ${r}`);if(Object.hasOwn(n,i))throw new Error("Node outputs cannot overwrite one another");n[i]=t[r]}return n}function om(e,t,n){let r=new Set(Object.values(t.writes??{}));for(let[i,a]of Object.entries(n))if(!r.has(i)||e[i]?.source.type!=="node"||!An(e[i],a))throw new Error(`Invalid node variable write: ${i}`);if(r.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}var sr=require("zod");var Rn=sr.z.string().min(1).max(255).regex(/^[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+){0,9}$/).refine(e=>e.split(".").every(t=>!["__proto__","constructor","prototype"].includes(t)),"Reserved value path"),Mn=sr.z.discriminatedUnion("source",[sr.z.strictObject({source:sr.z.literal("literal"),value:ve}),sr.z.strictObject({source:sr.z.literal("variable"),key:sr.z.string().min(1).max(255),path:Rn.optional()})]);function am(e,t){if(!t)return e;for(let n of Rn.parse(t).split(".")){if(Array.isArray(e)){if(!/^(0|[1-9]\d*)$/.test(n)||Number(n)>=e.length)return;e=e[Number(n)];continue}if(e===null||typeof e!="object"||!Object.hasOwn(e,n))return;e=Reflect.get(e,n)}return e}function Ec(e,t){if(e.source==="literal")return structuredClone(e.value);let n=Ca(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(ve.parse(am(n[e.key],e.path)))}function Rc(e,t){let n=[...t].sort((i,a)=>a.length-i.length).find(i=>e===i||e.startsWith(i+"."));if(!n)return null;let r=e===n?void 0:e.slice(n.length+1);return r&&!Rn.safeParse(r).success?null:{key:n,path:r}}function kc(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Ht(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap($p))]}function _a(e){return kc(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function pn(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("A JSON value is required");let n=new TextEncoder().encode(t).length,r=!1;for(let i=0;i<t.length;i++){let a=t.charAt(i);if(r)a==="\\"?i++:a==='"'&&(r=!1);else if(a==='"')r=!0;else if(a===":"||a===",")n++;else if(a==="-"||a>="0"&&a<="9"){let o=i;for(;i+1<t.length&&/[0-9.eE+-]/.test(t.charAt(i+1));)i++;let s=t.slice(o,i+1);if(!/[eE]/.test(s))continue;let[c="",u]=s.split(/[eE]/),l=c.replace(/^-/,""),m=l.replace(".","").length,f=(l.includes(".")?l.indexOf("."):m)+Number(u),g=f<=0?2-f+m:f>=m?f:m+1;n+=g+(c.startsWith("-")?1:0)-s.length}}return n}var cr=Oe.z.enum(["page","popup","banner"]),_x=3e5,sm=Oe.z.strictObject({type:Oe.z.enum(["string","number","boolean","strings","json"]),nullable:Oe.z.boolean()}),Ex=Oe.z.strictObject({inputs:Oe.z.record(Ue,sm.extend({required:Oe.z.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:Oe.z.record(Ue,sm).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),Rx=Oe.z.strictObject({kind:cr,schemaVersion:Oe.z.literal(1),name:Oe.z.string().trim().min(1).max(80),screen:dn,contract:Ex}),Ea=Rx.superRefine((e,t)=>{let n=(i,a)=>t.addIssue({code:"custom",message:i,path:a});e.screen.surface!==e.kind&&n("Content surface must match its domain",["screen","surface"]),e.screen.name!==e.name&&n("Content has one editable name",["screen","name"]),e.kind==="banner"&&e.screen.presentation.type!=="inline"&&n("Banner requires an inline container",["screen","presentation"]),e.kind!=="banner"&&e.screen.presentation.type==="inline"&&n("Inline presentation belongs to Banner",["screen","presentation"]),e.screen.actions.some(i=>i.type!=="event"&&i.type!=="navigate")&&n("Content actions must emit host intents or navigate locally",["screen","actions"]);let r=new Set(e.screen.actions.filter(i=>i.type==="event").map(i=>i.id));(Object.keys(e.contract.outputs).some(i=>!r.has(i))||[...r].some(i=>!Object.hasOwn(e.contract.outputs,i)))&&n("Every event needs exactly one output declaration",["contract","outputs"]),pn(e)>_x&&n("Content document exceeds its byte budget",[])});function kx(e,t){if(e===null)return t.nullable;switch(t.type){case"json":return!0;case"string":return typeof e=="string";case"number":return typeof e=="number"&&Number.isFinite(e);case"boolean":return typeof e=="boolean";case"strings":return Array.isArray(e)&&e.every(n=>typeof n=="string")}}var jx=Ea.superRefine((e,t)=>{for(let n of _a(e.screen))Object.keys(e.contract.inputs).some(r=>n===r||n.startsWith(r+"."))||t.addIssue({code:"custom",path:["contract","inputs"],message:"Declare every reusable input read"});for(let n of e.screen.actions){if(n.type!=="event")continue;let r=e.contract.outputs[n.id],i=Object.hasOwn(n.properties,"value")?n.properties.value:n.properties;r&&!kx(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}ar(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),cm=Oe.z.strictObject({id:Oe.z.uuid(),kind:cr,projectId:Oe.z.uuid(),environmentId:Oe.z.uuid(),name:Oe.z.string(),revision:Oe.z.number().int().nonnegative(),status:Oe.z.enum(["draft","published","archived"]),publishedVersionId:Oe.z.uuid().nullable(),createdAt:Oe.z.iso.datetime({offset:!0}),updatedAt:Oe.z.iso.datetime({offset:!0})}),tC=cm.extend({draft:Ea}),nC=Oe.z.strictObject({rows:Oe.z.array(cm).max(200),nextCursor:Oe.z.uuid().nullable()}),jc=Oe.z.strictObject({id:Oe.z.uuid(),kind:cr,resourceId:Oe.z.uuid(),projectId:Oe.z.uuid(),environmentId:Oe.z.uuid(),version:Oe.z.number().int().positive(),sourceRevision:Oe.z.number().int().nonnegative(),document:jx,createdAt:Oe.z.iso.datetime({offset:!0})}),rC=jc.omit({document:!0}),iC=Oe.z.discriminatedUnion("action",[Oe.z.strictObject({action:Oe.z.literal("create"),kind:cr,id:Oe.z.uuid(),document:Ea}),Oe.z.strictObject({action:Oe.z.literal("save"),kind:cr,id:Oe.z.uuid(),revision:Oe.z.number().int().nonnegative(),document:Ea}),Oe.z.strictObject({action:Oe.z.enum(["publish","archive"]),kind:cr,id:Oe.z.uuid(),revision:Oe.z.number().int().nonnegative()})]).superRefine((e,t)=>{"document"in e&&e.document.kind!==e.kind&&t.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});var Tc=require("zod"),Ai={funnelId:Tc.z.uuid().optional(),funnelVersionId:Tc.z.uuid().optional()};var po=require("zod"),Ra=po.z.strictObject({runId:po.z.uuid(),bindingId:po.z.uuid(),receiptId:po.z.uuid()});var ot=require("zod");var Be=require("zod");var Xe=require("zod"),cC=Xe.z.discriminatedUnion("action",[Xe.z.strictObject({action:Xe.z.literal("create"),couponId:Xe.z.uuid(),productBindingId:Xe.z.uuid(),storeOfferId:Xe.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:Xe.z.enum(["introductory","promotional"])}),Xe.z.strictObject({action:Xe.z.literal("set_enabled"),id:Xe.z.uuid(),revision:Xe.z.number().int().nonnegative(),enabled:Xe.z.boolean()})]),uC=Xe.z.array(Xe.z.strictObject({id:Xe.z.uuid(),couponId:Xe.z.uuid(),productBindingId:Xe.z.uuid(),storeOfferId:Xe.z.string().min(1).max(255).nullable(),storeOfferType:Xe.z.enum(["introductory","promotional"]),enabled:Xe.z.boolean(),revision:Xe.z.number().int().nonnegative()})).max(500),bi=Xe.z.strictObject({offerKind:Xe.z.enum(["none","introductory","promotional"]),offerId:Xe.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:Xe.z.number().int().min(0).max(1e8),trialDays:Xe.z.number().int().min(1).max(730).nullable()}).superRefine((e,t)=>{(e.offerKind==="none"&&(e.offerId!==null||e.discountMinor!==0||e.trialDays!==null)||e.trialDays!==null&&e.discountMinor!==0)&&t.addIssue({code:"custom",message:"Select one store purchase option with its exact terms"})}),lC=Xe.z.record(Xe.z.uuid(),bi).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var Nc=Be.z.object({type:Be.z.literal("native_purchase"),receiptId:Be.z.uuid(),orderId:Be.z.uuid(),productVersionId:Be.z.uuid(),provider:Be.z.enum(["apple","google"]),productId:Be.z.string().min(1).max(255),productKind:Vp,replacement:Be.z.strictObject({sourceOrderId:Be.z.uuid(),sourceProductId:Be.z.string().min(1).max(255),policy:Be.z.enum(["apple_store","google_full_price"]),sourceAccountTokens:Be.z.array(Be.z.uuid()).max(50)}).nullable(),appAccountToken:Be.z.uuid().optional(),obfuscatedAccountId:Be.z.string().min(1).max(64).optional(),obfuscatedProfileId:Be.z.uuid().optional(),basePlanId:Be.z.string().min(1).max(255).optional(),offerId:Be.z.string().min(1).max(255).optional(),offerKind:Be.z.enum(["none","introductory","promotional"]),currency:Ie,catalogAmountMinor:Be.z.number().int().nonnegative().max(1e8),discountMinor:Be.z.number().int().nonnegative().max(1e8),trialDays:Be.z.number().int().min(1).max(730).nullable(),seatBundle:Be.z.array(Be.z.strictObject({key:Be.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:Be.z.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:Be.z.strictObject({offerId:Be.z.string().min(1).max(255),keyId:Be.z.string().min(1).max(255),nonce:Be.z.uuid(),signature:Be.z.string().min(1).max(1024),timestamp:Be.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,t)=>{let n=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(n?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!n&&e.productKind==="membership"&&e.basePlanId===void 0||e.discountMinor>e.catalogAmountMinor||new Set(e.seatBundle.map(i=>i.key)).size!==e.seatBundle.length||e.trialDays!==null&&(e.discountMinor!==0||e.offerKind==="none")||e.offerKind==="none"&&e.discountMinor!==0||(n?!e.appAccountToken||e.obfuscatedAccountId!==void 0||e.obfuscatedProfileId!==void 0||e.basePlanId!==void 0||e.offerKind==="promotional"!=(e.applePromotionalOffer!==null)||e.offerKind==="promotional"!=(e.offerId!==void 0)||e.applePromotionalOffer!==null&&e.applePromotionalOffer.offerId!==e.offerId:e.appAccountToken!==void 0||!e.obfuscatedAccountId||!e.obfuscatedProfileId||e.applePromotionalOffer!==null||e.offerKind==="none"!=(e.offerId===void 0)))&&t.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});var p=require("zod");var _e=require("zod/v4"),um=require("zod/v4"),Tx=um.z.registry(),{BillingInterval:lm}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{BillingInterval:e}})(),{DisplaySchema:Nx}=(e=>({DisplaySchema:e.object({primary_text:e.string().meta({description:"Main display text (e.g. '$10' or '100 messages')."}),secondary_text:e.string().optional().meta({description:"Secondary display text (e.g. 'per month' or 'then $0.5 per 100')."})})}))(_e.z),{withSpecDefault:Dx}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(Tx),{COMMON:dm}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:Fx}={STRIPE_PRESENTMENT_CURRENCIES:["usd","aed","afn","all","amd","ang","aoa","ars","aud","awg","azn","bam","bbd","bdt","bif","bmd","bnd","bob","brl","bsd","bwp","byn","bzd","cad","cdf","chf","clp","cny","cop","crc","cve","czk","djf","dkk","dop","dzd","egp","etb","eur","fjd","fkp","gbp","gel","gip","gmd","gnf","gtq","gyd","hkd","hnl","htg","huf","idr","ils","inr","isk","jmd","jpy","kes","kgs","khr","kmf","krw","kyd","kzt","lak","lbp","lkr","lrd","lsl","mad","mdl","mga","mkd","mmk","mnt","mop","mur","mvr","mwk","mxn","myr","mzn","nad","ngn","nio","nok","npr","nzd","pab","pen","pgk","php","pkr","pln","pyg","qar","ron","rsd","rub","rwf","sar","sbd","scr","sek","sgd","shp","sle","sos","srd","std","szl","thb","tjs","top","try","ttd","twd","tzs","uah","ugx","uyu","uzs","vnd","vuv","wst","xaf","xcd","xcg","xof","xpf","yer","zar","zmw"]},{COMMON_SET:Mx}=(e=>({COMMON_SET:new Set(e)}))(dm),{hasNoDuplicateCurrencies:pm}={hasNoDuplicateCurrencies:t=>{let n=new Set;for(let{currency:r}of t){let i=r.toLowerCase();if(n.has(i))return!1;n.add(i)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:mm}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:qx}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(_e.z),{Infinite:Ux}={Infinite:"inf"},{TierBehavior:Bx}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:fm}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Vx}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:Lx}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:zx}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:$x}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(_e.z),{ApiCreditTierSchema:gm}=(e=>({ApiCreditTierSchema:e.object({to:e.union([e.number().positive(),e.enum(["inf"])]).meta({description:"Inclusive upper usage boundary for this graduated tier. The final tier must be 'inf'."}),credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group within this tier."})})}))(_e.z),{VIOLATION_MESSAGES:Gx}={VIOLATION_MESSAGES:{non_final_infinity:"Only the final tier may use an 'inf' boundary.",not_increasing:"Tier boundaries must be strictly increasing.",final_not_infinity:"The final tier must use an 'inf' boundary."}},{MarkupEntrySchema:hm}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(_e.z),{ModelMarkupsSchema:Kx}=((e,t)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),t.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(_e.z,hm),{InvoiceUsageEntrySchema:Hx}=(e=>({InvoiceUsageEntrySchema:e.object({feature_id:e.string().meta({description:"The metered feature whose units are being converted."}),quantity:e.number().nonnegative().meta({description:"Billable units of the metered feature. Converted to the credit-system feature through its rate card."}),properties:e.record(e.string(),e.unknown()).optional().meta({description:"Event properties used to pick the rate card dimension and multipliers."})}).strict()}))(_e.z),{AttachDiscountSchema:ym}=(e=>({AttachDiscountSchema:e.object({reward_id:e.string().optional().meta({description:"The ID of the reward to apply as a discount."}),promotion_code:e.string().optional().meta({description:"The promotion code to apply as a discount."})}).refine(n=>n.reward_id||n.promotion_code,{message:"Either reward_id or promotion_code must be provided."}).meta({title:"AttachDiscount",description:"A discount to apply. Can be either a reward ID or a promotion code."})}))(_e.z),{CustomLineItemSchema:Qx}=(e=>({CustomLineItemSchema:e.object({amount:e.number().meta({description:"Amount in dollars for this line item (e.g. 10.50). Can be negative for credits."}),description:e.string().meta({description:"Description for the line item."})})}))(_e.z),{UnixMsTimestampSchema:Jx}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(_e.z),{CreateInvoicePreviewLineSchema:Zx}=(e=>({CreateInvoicePreviewLineSchema:e.object({plan_id:e.string().nullable(),feature_id:e.string().nullable(),description:e.string(),amount:e.number(),amount_after_discounts:e.number(),quantity:e.number().nullable(),prorated:e.boolean(),period_start:e.number().nullable(),period_end:e.number().nullable()})}))(_e.z),{ReissueInvoiceParamsSchema:Am}=(e=>({ReissueInvoiceParamsSchema:e.object({invoice_id:e.string().meta({description:"The Autumn invoice ID to void and replace.",example:"inv_2b3c4d5e6f7g8h"}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer and memo are applied to the replacement invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the replacement invoice. Defaults to the original invoice's due date; required when that date has already passed."}),update_customer_email:e.email().optional().meta({description:"Updates the customer's billing email before the replacement is issued, so Stripe sends the new invoice to this address."})})}))(_e.z),{InvoiceModeParamsSchema:Lr}=(e=>({InvoiceModeParamsSchema:e.object({enabled:e.boolean().meta({description:"When true, creates an invoice and sends it to the customer instead of charging their card immediately. Uses Stripe's send_invoice collection method."}),enable_plan_immediately:e.boolean().default(!1).meta({description:"If true, enables the plan immediately even though the invoice is not paid yet."}),finalize:e.boolean().default(!0).meta({description:"If true, finalizes the invoice so it can be sent to the customer. If false, keeps it as a draft for manual review."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer (e.g. bank details) is applied to the invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the invoice before it is due (Stripe days_until_due)."})}).meta({title:"InvoiceMode",description:"Invoice mode configuration. Creates an invoice instead of charging the card immediately."})}))(_e.z),{InvoiceTemplateSchema:Wx}=(e=>({InvoiceTemplateSchema:e.object({id:e.string().meta({description:"Unique identifier for the invoice template."}),name:e.string().meta({description:"User-defined name to distinguish this template when sending an invoice."}),footer:e.string().optional().meta({description:"Footer text rendered on the invoice, typically bank details so customers can pay directly."}),memo:e.string().optional().meta({description:"Memo shown near the top of the invoice (Stripe invoice description), e.g. a contact line for payment questions."}),net_terms_days:e.number().int().positive().optional().meta({description:"Default number of days the customer has to pay before the invoice is due. Overridable when sending."}),created_at:e.number().optional().meta({description:"Timestamp (ms) when the template was created."})})}))(_e.z),{BasePriceSchema:Yx}=((e,t,n)=>({BasePriceSchema:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),interval:e.enum(t).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),display:n.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(_e.z,lm,Nx),{CURRENCY_CODES:Xx}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(dm,Fx,Mx),{ApiPriceProcessorsSchema:bm}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(_e.z,qx),{AllocatedBillingFieldSchema:eS}=((e,t)=>({AllocatedBillingFieldSchema:e.enum(t).optional().meta({internal:!0,description:"How an allocated usage_based price bills mid-cycle quantity changes. 'arrear' (default) bills at period end. 'prorated_legacy' is only returned for prices still on the legacy immediate-proration behavior; omit it to migrate the price to 'arrear'."})}))(_e.z,Vx),{CreditDimensionNameSchema:tS}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(_e.z,Lx,zx),{ApiCreditMatchSchema:xm}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))($x),{findCreditTierViolations:nS}=(e=>({findCreditTierViolations:n=>{let r=[],i=(o,s)=>r.push({index:o,reason:s,message:e[s]}),a=0;for(let[o,s]of n.entries()){let c=o===n.length-1;if(s==="inf"){c||i(o,"non_final_infinity");continue}(!Number.isFinite(s)||s<=a)&&i(o,"not_increasing"),a=s,c&&i(o,"final_not_infinity")}return r}}))(Gx),{ApiCreditMultiplierSchema:rS}=((e,t)=>({ApiCreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional().meta({description:"Multiplies the matched rate. All matching multipliers stack."}),add:e.number().optional().meta({description:"Added to the rate after every factor is applied, in credits per billing-unit group."})}).strict().refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(_e.z,xm),{ProviderMarkupsSchema:iS}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(_e.z,hm),{InvoiceFeatureQuantitySchema:Sm}=((e,t,n)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(t).meta({description:"Which of the feature's prices to use: 'prepaid' or 'usage_based'."}),quantity:e.number().nonnegative().optional().meta({description:"Billable feature units in total, exclusive of any included usage. Not per seat or per entity. For a credit-system feature this is the number of credits."}),usage:e.array(n).optional().meta({description:"For credit-system features: billable units of the source features, converted through the credit rate card. Mutually exclusive with quantity."}),prorate:e.boolean().optional().meta({description:"Whether to prorate this line against period_start / period_end. Defaults to true for prepaid and false for usage-based."})}).strict().refine(i=>i.quantity!==void 0!=(i.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(_e.z,fm,Hx),{CreateInvoicePreviewSchema:Dc}=((e,t)=>({CreateInvoicePreviewSchema:e.object({currency:e.string(),lines:e.array(t),subtotal:e.number(),discount_total:e.number(),tax:e.object({total:e.number(),amount_inclusive:e.number(),amount_exclusive:e.number(),status:e.enum(["complete","incomplete"])}).nullable(),total:e.number(),due_date:e.number().nullable()})}))(_e.z,Zx),{SUPPORTED_SET:oS}=(e=>({SUPPORTED_SET:new Set(e)}))(Xx),{ApiCreditDimensionBaseSchema:aS}=((e,t)=>({ApiCreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(_e.z,xm),{refineGraduatedTiers:Im}=(e=>({refineGraduatedTiers:(n,r)=>{let i=e(n.tiers.map(a=>a.to));for(let{index:a,message:o}of i)r.addIssue({code:"custom",message:o,path:["tiers",a,"to"]})}}))(nS),{ApiFeatureMarkupsOverrideSchema:sS}=((e,t,n)=>({ApiFeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional().meta({description:"Default percentage markup for customers on this plan. Use -100 to make usage free."}),provider_markups:t.meta({description:"Per-provider markup percentages for customers on this plan."}),model_markups:n.meta({description:"Per-model markup overrides for customers on this plan."})})}))(_e.z,iS,Kx),{isValidCurrencyCode:cS}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(oS),{ApiCreditDimensionSchema:uS}=((e,t,n,r)=>({ApiCreditDimensionSchema:e.union([t.extend({tier_behavior:e.literal("graduated"),tiers:e.array(n).min(1)}).strict().superRefine(r),t.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(_e.z,aS,gm,Im),{CurrencyCodeSchema:vm}=((e,t)=>({CurrencyCodeSchema:e.string().refine(t,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(_e.z,cS),{AdditionalCurrencyTierSchema:lS}=((e,t)=>({AdditionalCurrencyTierSchema:e.object({currency:t,amount:e.number().optional().meta({description:"Per-unit amount for this tier in this currency."}),flat_amount:e.number().optional().meta({description:"Flat amount for this tier in this currency, if the tier uses one."})}).refine(r=>r.amount!==void 0||r.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(_e.z,vm),{ApiCreditSchemaItemBaseSchema:wm}=((e,t,n,r)=>({ApiCreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string().nonempty().meta({description:"ID of the metered feature that draws from this credit system."}),billing_units:e.number().positive().optional().meta({description:"Number of metered-feature units priced together. Defaults to one when omitted."}),dimensions:e.record(t,n).optional().meta({description:"Named rates chosen by event properties. The most specific match sets the rate; with no match the item's own rate applies."}),multipliers:e.record(t,r).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(_e.z,tS,uS,rS),{ApiFlatCreditSchemaItemSchema:dS}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(wm,_e.z),{AdditionalCurrencyPriceSchema:pS}=((e,t)=>({AdditionalCurrencyPriceSchema:e.object({currency:t,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(_e.z,vm),{AdditionalCurrencyTierArraySchema:mS}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(_e.z,lS,pm,mm),{ApiGraduatedCreditSchemaItemSchema:fS}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(wm,_e.z,gm,Im),{AdditionalCurrencyPriceArraySchema:Om}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(_e.z,pS,pm,mm),{ApiUsageTierWithCurrenciesSchema:gS}=((e,t,n)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:n.optional().meta({description:"Per-currency amounts for this tier. Tier boundaries ('to') are shared across all currencies."})}).refine(i=>i.amount!==void 0||i.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(i=>({...i,amount:i.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:n.optional()}))}))(_e.z,Ux,mS),{ApiCreditSchemaItemSchema:hS}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(_e.z,fS,dS),{BasePriceParamsSchema:yS}=((e,t,n,r)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:t({schema:n.number().optional(),defaultValue:1,description:"Number of intervals per billing cycle. Defaults to 1."}),additional_currencies:r.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),base_currency:n.string().optional().meta({internal:!0}),entitlement_id:n.string().optional().meta({internal:!0}),price_id:n.string().optional().meta({internal:!0}),stripe_price_id:n.string().optional().meta({description:"Stripe price id this base price is billed under. Set by sync flows to capture the actual Stripe price when it differs from the catalog default.",internal:!0})}).meta({title:"BasePrice",description:"Base price configuration for a plan."})}))(Yx,Dx,_e.z,Om),{PlanItemPriceParamsSchema:AS}=((e,t,n,r,i,a,o)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(c=>c??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:t.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(i).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(a).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:o,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(_e.z,Om,gS,Bx,lm,fm,eS),{ApiFeatureOverrideSchema:bS}=((e,t,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(t).optional().meta({description:"For credit system features: replaces the feature's credit_schema entirely for customers on this plan."}),markups:n.optional().meta({description:"For AI credit system features: replaces the feature's markup chain entirely for customers on this plan. An unset level means no markup at that level rather than inheriting the feature's."})})}))(_e.z,hS,sS),{InvoiceBasePriceParamsSchema:Pm}=((e,t)=>({InvoiceBasePriceParamsSchema:e.pick({amount:!0,interval:!0,interval_count:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(yS,bm),{InvoiceItemPriceParamsSchema:xS}=((e,t)=>({InvoiceItemPriceParamsSchema:e.pick({amount:!0,tiers:!0,tier_behavior:!0,interval:!0,interval_count:!0,billing_units:!0,billing_method:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(AS,bm),{InvoiceLicenseQuantitySchema:SS}=((e,t,n)=>({InvoiceLicenseQuantitySchema:e.object({license_plan_id:e.string().meta({description:"The license plan linked to the parent plan."}),quantity:e.number().int().nonnegative().meta({description:"Billable seats, exclusive of any included seats."}),customize:e.object({price:t.nullable().optional()}).strict().optional().meta({description:"Override the license's per-seat price on this invoice."}),feature_quantities:e.array(n).optional().meta({description:"Feature charges priced through the license plan."}),prorate:e.boolean().optional().meta({description:"Whether to prorate seat charges against period_start / period_end. Defaults to true."})}).strict()}))(_e.z,Pm,Sm),{InvoiceCustomizeItemSchema:IS}=((e,t,n)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:t.optional().meta({description:"Pricing to use for this feature on this invoice."}),feature_override:n.pick({credit_schema:!0}).strict().optional().meta({description:"For credit-system features: a credit rate card to use when converting `usage` on this invoice."})}).strict()}))(_e.z,xS,bS),{InvoiceCustomizeSchema:vS}=((e,t,n)=>({InvoiceCustomizeSchema:e.object({price:t.nullable().optional().meta({description:"Override the plan's base price for this invoice. Pass null or an amount of 0 to omit the base price line."}),items:e.array(n).optional().meta({description:"Override feature pricing for this invoice. Only pricing fields are accepted; grants, resets and rollovers are not part of an invoice."})}).strict().meta({title:"InvoiceCustomize",description:"Pricing overrides applied to this invoice only. The catalog and the customer's plan are not changed."})}))(_e.z,Pm,IS),{InvoicePlanParamsSchema:wS}=((e,t,n,r,i)=>({InvoicePlanParamsSchema:e.object({plan_id:e.string().meta({description:"The catalog plan (or variant) whose pricing to use."}),version:e.number().optional().meta({description:"Plan version. Defaults to the active version."}),customize:t.optional(),feature_quantities:e.array(n).optional(),license_quantities:e.array(r).optional(),discounts:e.array(i).optional().meta({description:"Discounts applied only to this plan's lines."}),prorate:e.boolean().optional().meta({description:"Whether to prorate the base price against period_start / period_end. Defaults to true."})}).strict()}))(_e.z,vS,Sm,SS,ym),{CreateInvoiceParamsSchema:xi}=((e,t,n,r,i)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(t).optional(),custom_line_items:e.array(n).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(r).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:i.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start \u2192 period_end against one price interval starting at period_start."}),period_end:i.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(o=>o.period_start===void 0==(o.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(o=>o.period_start===void 0||o.period_end===void 0||o.period_end>o.period_start,{message:"period_end must be after period_start."})}))(_e.z,wS,Qx,ym,Jx);var Em=p.z.strictObject({requestId:p.z.uuid(),predecessorOperationId:p.z.uuid().optional(),invoiceMode:Lr.optional(),entityId:p.z.uuid().optional(),billingSubscriptionId:p.z.uuid().optional(),newBillingSubscription:p.z.literal(!0).optional(),offerId:p.z.uuid().optional(),nativeOffer:bi.optional(),plans:p.z.array(p.z.strictObject({productVersionId:p.z.uuid(),seatQuantities:p.z.record(Wo,p.z.number().int().min(0).max(1e4)).optional(),featureQuantities:p.z.record(p.z.uuid(),p.z.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100,"At most 100 feature quantities").optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Plan versions must be unique"),provider:p.z.enum(["stripe","apple","google","merchant"]),currency:Ie}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||["apple","google"].includes(e.provider)&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||["stripe","merchant"].includes(e.provider)&&!e.billingSubscriptionId,"A new billing subscription has no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),$r=p.z.strictObject({operationId:p.z.uuid()}),qt=p.z.number().int().min(0).max(1e8),OS=p.z.strictObject({lineId:p.z.uuid(),productVersionId:p.z.uuid(),productName:p.z.string().min(1).max(80),interval:p.z.enum(["free","week","month","year","one_time"]),intervalCount:p.z.number().int().min(1).max(156).optional(),baseAmountMinor:qt,seats:p.z.array(p.z.strictObject({key:Wo,quantity:p.z.number().int().min(0).max(1e4),includedQuantity:p.z.number().int().min(0).max(1e4),maximumQuantity:p.z.number().int().min(0).max(1e4),unitAmountMinor:qt})).max(20),prepaid:p.z.array(gp).max(100).optional(),catalogAmountMinor:qt,trial:p.z.strictObject({days:p.z.number().int().min(1).max(730),cardRequired:p.z.boolean()}).nullable()}).refine(e=>new Set(e.seats.map(t=>t.key)).size===e.seats.length&&e.seats.every(t=>t.quantity>=t.includedQuantity&&t.quantity<=t.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((t,n)=>t+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((t,n)=>t+na({quantity:n.quantity,unitAmountMinor:n.unitAmountMinor,...n.pricing===void 0?{}:{pricing:n.pricing}}),0)===e.catalogAmountMinor,"Quote must retain its published base price and component quantities"),Rm=p.z.string().regex(/^[A-Za-z0-9_-]{1,200}$/),PS=p.z.strictObject({id:Rm,name:p.z.string().min(1).max(40),percent_off:p.z.number().gt(0).max(100).optional(),amount_off:p.z.number().int().positive().optional(),currency:p.z.string().regex(/^[a-z]{3}$/).optional(),duration:p.z.enum(["once","repeating","forever"]),duration_in_months:p.z.number().int().min(1).max(36).optional()}).refine(e=>e.percent_off===void 0!=(e.amount_off===void 0)&&e.amount_off===void 0==(e.currency===void 0)&&e.duration==="repeating"==(e.duration_in_months!==void 0),"A Stripe coupon has one percentage or amount and months only when repeating"),CS=p.z.strictObject({subscriptionId:p.z.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:p.z.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:p.z.array(p.z.strictObject({id:p.z.string(),price_id:p.z.string(),quantity:p.z.number().int().nonnegative(),discounts:p.z.array(p.z.strictObject({id:p.z.string(),coupon:p.z.string(),start:p.z.number(),end:p.z.number().nullable()})).optional()})).min(1).max(100),prorationDate:p.z.number().int().nonnegative(),amountMinor:p.z.number().int().positive(),periodStartMs:p.z.number(),periodEndMs:p.z.number()}),km=p.z.strictObject({invoiceMode:Lr.optional(),append:CS.optional(),provider:p.z.literal("stripe"),executor:p.z.enum(["indiana","merchant"]),accountId:p.z.string().regex(/^acct_[A-Za-z0-9]+$/),mode:p.z.enum(["payment","subscription"]),lineItems:p.z.array(p.z.strictObject({price:p.z.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:p.z.number().int().min(1).max(1e4),priceId:p.z.uuid(),productName:p.z.string().min(1).max(80),amountMinor:p.z.number().int().min(0).max(1e8),currency:p.z.string().regex(/^[a-z]{3}$/),interval:p.z.enum(["week","month","year","one_off"]),intervalCount:p.z.number().int().min(1).max(52),slot:p.z.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:p.z.strictObject({mode:p.z.enum(["graduated","volume"]),tiers:p.z.array(p.z.strictObject({upTo:p.z.number().int().min(1).max(1e6).nullable(),unitAmountMinor:p.z.number().int().min(0).max(1e8),flatAmountMinor:p.z.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:p.z.array(p.z.strictObject({coupon:Rm,terms:PS})).max(1),trialPeriodDays:p.z.number().int().min(1).max(730).nullable(),metadata:p.z.strictObject({grooveCheckoutId:p.z.uuid(),grooveCustomerId:p.z.uuid()}),expiresAt:p.z.iso.datetime({offset:!0})}),Si=p.z.strictObject({operationId:p.z.uuid(),entityId:p.z.uuid().nullable(),billingSubscriptionId:p.z.uuid().nullable(),discount:p.z.strictObject({offerId:p.z.uuid(),couponId:p.z.uuid(),discount:ir,duration:un,amountMinor:qt,allocations:p.z.array(p.z.strictObject({productVersionId:p.z.uuid(),amountMinor:qt})).min(1).max(20),expiresAt:p.z.iso.datetime({offset:!0})}).nullable(),charge:p.z.strictObject({effectiveAt:p.z.iso.datetime({offset:!0}),periodEndsAt:p.z.iso.datetime({offset:!0}),debitMinor:qt,discountMinor:qt,taxMinor:qt,totalMinor:qt}).nullable(),expiresAt:p.z.iso.datetime({offset:!0}),provider:p.z.enum(["stripe","apple","google","merchant"]),nativeOffer:bi.optional(),currency:Ie,lines:p.z.array(OS).min(1).max(20),catalogAmountMinor:qt,automaticTax:p.z.boolean(),execution:p.z.union([km,Ko]).nullable()}).refine(e=>e.provider==="merchant"?e.execution?.provider==="merchant"&&e.execution.operationId===e.operationId&&e.execution.catalogAmountMinor===e.catalogAmountMinor&&e.execution.currency===e.currency&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&e.execution.discount?.grantId===e.discount?.offerId:e.provider==="stripe"?e.execution?.provider!=="merchant"&&(e.lines[0]?.trial?.cardRequired===!1&&!e.execution?.invoiceMode?.enabled?e.execution===null&&e.discount===null:e.execution!==null&&e.execution.metadata.grooveCheckoutId===e.operationId&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.mode===(e.lines.some(t=>!["one_time","free"].includes(t.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(t=>t.price!==null))&&e.execution.discounts.every(t=>t.coupon===t.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(t=>e.discount!==null&&(t.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&t.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${t.terms.amount_off}`&&t.terms.amount_off===e.discount.discount.amountOffCents&&t.terms.currency?.toUpperCase()===e.currency&&t.terms.duration==="once"))):e.execution===null,"Stripe execution must carry the quote identity, expiry, mode, trial and held coupon").refine(e=>(!e.discount||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.discount.duration.type==="once")&&e.discount.amountMinor<=e.catalogAmountMinor&&e.discount.allocations.length===e.lines.length&&e.discount.allocations.every((t,n)=>{let r=e.lines[n];return r!==void 0&&t.productVersionId===r.productVersionId&&t.amountMinor<=r.catalogAmountMinor})&&e.discount.allocations.reduce((t,n)=>t+n.amountMinor,0)===e.discount.amountMinor)&&(["stripe","merchant"].includes(e.provider)?e.nativeOffer===void 0:e.nativeOffer!==void 0&&e.lines.length===1&&e.nativeOffer.discountMinor<=e.catalogAmountMinor&&e.nativeOffer.trialDays===(e.lines[0]?.trial?.days??null)&&(!e.discount||e.nativeOffer.discountMinor===e.discount.amountMinor))&&(!e.charge||e.billingSubscriptionId!==null&&e.charge.totalMinor===e.charge.debitMinor-e.charge.discountMinor+e.charge.taxMinor&&e.charge.discountMinor<=e.charge.debitMinor&&Date.parse(e.charge.periodEndsAt)>Date.parse(e.charge.effectiveAt))&&new Set(e.lines.map(t=>t.lineId)).size===e.lines.length&&e.lines.reduce((t,n)=>t+n.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),Ii=p.z.strictObject({operationId:p.z.uuid(),orderId:p.z.uuid(),append:p.z.boolean().optional(),invoiceMode:p.z.boolean().optional(),status:p.z.enum(["pending","complete","cancelled","failed"]),executor:p.z.enum(["indiana","merchant"]),checkoutUrl:p.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:p.z.union([km,Ko]).nullable(),currency:Ie,catalogAmountMinor:qt,taxMinor:qt,totalMinor:p.z.number().int().min(0).max(2e8).nullable(),quoteFinalized:p.z.boolean(),nativePurchase:Nc.nullable(),confirmedAt:p.z.iso.datetime({offset:!0}).nullable().optional(),quote:Si.optional(),merchantExecution:Cr.nullable().optional(),problem:Li.nullable().optional(),authority:Zo.optional()}).refine(e=>(e.checkoutUrl===null||e.executor==="indiana"||e.merchantExecution?.type==="purchase")&&(e.execution===null||e.executor==="merchant"),"Only Indiana-executed purchases carry a Checkout URL and only record-only purchases carry execution instructions"),ja=p.z.strictObject({enabled:p.z.literal(!0),featureIds:p.z.array(p.z.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),jm=p.z.strictObject({requestId:p.z.uuid(),invoiceMode:Lr.optional(),membershipId:p.z.uuid(),carryOverBalances:ja.optional(),carryOverUsages:ja.optional(),membershipIds:p.z.array(p.z.uuid()).min(1).max(20).optional(),prorationBehavior:p.z.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:p.z.enum(["immediate","renewal","store"]),change:p.z.discriminatedUnion("type",[p.z.strictObject({type:p.z.literal("plan"),productVersionId:p.z.uuid()}),p.z.strictObject({type:p.z.literal("seats"),licenseKey:Wo,quantity:p.z.number().int().min(0).max(1e4)}),p.z.strictObject({type:p.z.literal("quantity"),internal_feature_id:p.z.uuid(),quantity:p.z.number().int().min(0).max(1e4)}),p.z.strictObject({type:p.z.literal("cancel")}),p.z.strictObject({type:p.z.literal("uncancel")}),p.z.strictObject({type:p.z.literal("billing_cycle"),billingCycleAnchor:p.z.union([p.z.literal("now"),p.z.number().int().positive().max(0xe677d21fdbff)])})])}).refine(e=>e.timing!=="store"||e.change.type==="plan","Store timing applies to a native plan replacement").refine(e=>e.change.type!=="billing_cycle"||e.timing===(e.change.billingCycleAnchor==="now"?"immediate":"renewal"),"Use immediate for now and renewal for a future millisecond anchor").refine(e=>!e.membershipIds||["cancel","uncancel"].includes(e.change.type)&&e.membershipIds.includes(e.membershipId)&&new Set(e.membershipIds).size===e.membershipIds.length,"Grouped actions require unique cancel/uncancel targets including the primary membership").refine(e=>!e.carryOverBalances&&!e.carryOverUsages||e.change.type==="plan"&&e.timing==="immediate","Carry applies only to immediate upgrades").refine(e=>!e.prorationBehavior||e.change.type==="quantity","prorationBehavior applies to prepaid quantity changes"),ka=p.z.string().regex(/^price_[A-Za-z0-9]+$/),Cm=p.z.strictObject({grooveUpdateId:p.z.uuid(),grooveCustomerId:p.z.uuid()}),_m=p.z.strictObject({price:ka.nullable(),priceId:p.z.uuid().optional(),quantity:p.z.number().int().min(0).max(1e4)}),Tm=p.z.strictObject({provider:p.z.literal("stripe"),invoiceMode:Lr.optional(),executor:p.z.enum(["indiana","merchant"]),accountId:p.z.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:p.z.string().regex(/^sub_[A-Za-z0-9]+$/),action:p.z.enum(["update","cancel","schedule","release"]),update:p.z.strictObject({items:p.z.array(_m).max(20),remove:p.z.array(ka).max(20),restoreItems:p.z.array(p.z.strictObject({price:ka,quantity:p.z.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:p.z.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:p.z.number().int().positive().optional(),paymentBehavior:p.z.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:p.z.boolean().optional(),clearCancelAt:p.z.literal(!0).optional(),billingCycleAnchorNow:p.z.literal(!0).optional(),metadata:Cm}).nullable(),cancel:p.z.strictObject({prorate:p.z.literal(!1),invoiceNow:p.z.literal(!1)}).nullable(),schedule:p.z.strictObject({currentItems:p.z.array(p.z.strictObject({price:ka,quantity:p.z.number().int().min(0).max(1e4)})).max(20),nextItems:p.z.array(_m).min(1).max(20),switchAt:p.z.number().int().positive(),interval:p.z.enum(["week","month","year"]),intervalCount:p.z.number().int().min(1).max(52),resetBillingCycleAnchor:p.z.literal(!0).optional(),metadata:Cm}).nullable(),release:p.z.strictObject({schedule:p.z.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:p.z.iso.datetime({offset:!0})}).refine(e=>["update","cancel","schedule","release"].every(t=>e[t]!==null==(e.action===t))&&(e.executor==="indiana"||[...e.update?.items??[],...e.schedule?.nextItems??[]].every(t=>t.price!==null)),"Stripe update execution carries exactly its action, with bound Prices for the merchant"),Ta=p.z.strictObject({carryOverBalances:ja.optional(),carryOverUsages:ja.optional(),operationId:p.z.uuid(),membershipId:p.z.uuid(),productVersionId:p.z.uuid(),timing:p.z.enum(["immediate","renewal"]),effectiveAt:p.z.iso.datetime({offset:!0}),expiresAt:p.z.iso.datetime({offset:!0}),currency:Ie,creditMinor:qt,debitMinor:qt,discountMinor:qt,taxMinor:qt,totalMinor:qt,retainedProductVersionIds:p.z.array(p.z.uuid()).max(19),execution:p.z.union([Tm,Ho])}),_S=p.z.strictObject({operationId:p.z.uuid(),invoiceMode:p.z.boolean().optional(),membershipId:p.z.uuid(),productVersionId:p.z.uuid(),status:p.z.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:p.z.enum(["immediate","renewal"]),effectiveAt:p.z.iso.datetime({offset:!0}),checkoutUrl:p.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:p.z.enum(["indiana","merchant"]),execution:p.z.union([Tm,Ho]).nullable(),confirmedAt:p.z.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Cr.nullable().optional(),problem:Li.nullable().optional(),quote:Ta.optional(),authority:Zo.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),ES=p.z.strictObject({operationId:p.z.uuid(),membershipId:p.z.uuid(),productVersionId:p.z.uuid(),timing:p.z.literal("store"),effectiveAt:p.z.null(),expiresAt:p.z.iso.datetime({offset:!0}),currency:Ie,creditMinor:p.z.null(),debitMinor:p.z.null(),discountMinor:p.z.null(),taxMinor:p.z.null(),totalMinor:p.z.null(),retainedProductVersionIds:p.z.array(p.z.uuid()).max(19),store:p.z.strictObject({provider:p.z.enum(["apple","google"]),productId:p.z.string().min(1).max(255),catalogAmountMinor:qt,policy:p.z.enum(["apple_store","google_full_price"])})}),RS=p.z.strictObject({operationId:p.z.uuid(),membershipId:p.z.uuid(),productVersionId:p.z.uuid(),status:p.z.enum(["prepared","pending","effective","cancelled","failed"]),timing:p.z.literal("store"),effectiveAt:p.z.iso.datetime({offset:!0}).nullable(),checkoutUrl:p.z.null(),nativePurchase:Nc.nullable()}),Nm=p.z.union([Ta,ES]),Fc=p.z.union([_S,RS]),mo=p.z.number().int().positive().max(2e8),zr=p.z.number().int().min(0).max(2e8),Dm=p.z.strictObject({requestId:p.z.uuid(),invoiceId:p.z.uuid(),mode:p.z.enum(["full","partial"]),amountMinor:mo.optional(),entitlementAction:p.z.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),Fm=p.z.strictObject({provider:p.z.literal("stripe"),executor:p.z.enum(["indiana","merchant"]),accountId:p.z.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:p.z.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:mo,currency:p.z.string().regex(/^[a-z]{3}$/),metadata:p.z.strictObject({indianaRefundId:p.z.uuid()}),idempotencyKey:p.z.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:p.z.array(p.z.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),Mc=p.z.strictObject({operationId:p.z.uuid(),invoiceId:p.z.uuid(),providerInvoiceId:p.z.string().min(1).max(200),currency:Ie,paidMinor:zr,refundedMinor:zr,pendingMinor:zr,amountMinor:mo,mode:p.z.enum(["full","partial"]),entitlementAction:p.z.enum(["retain","revoke"]),revokes:p.z.strictObject({customerProductIds:p.z.array(p.z.uuid()).max(100),subscriptionIds:p.z.array(p.z.string().min(1).max(200)).max(20)}),execution:p.z.union([Fm,Qo]),expiresAt:p.z.iso.datetime({offset:!0})}).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&(e.execution.provider==="merchant"?e.execution.merchantInvoiceId===e.providerInvoiceId&&e.execution.operationId===e.operationId&&e.execution.currency===e.currency:e.execution.invoice===e.providerInvoiceId&&e.execution.metadata.indianaRefundId===e.operationId&&e.execution.currency===e.currency.toLowerCase())&&(e.entitlementAction==="revoke"||e.revokes.customerProductIds.length===0&&e.revokes.subscriptionIds.length===0),"Refund quote must stay within the refundable amount and match its execution"),Na=p.z.strictObject({operationId:p.z.uuid(),invoiceId:p.z.uuid(),providerInvoiceId:p.z.string().min(1).max(200),status:p.z.enum(["quoted","pending","succeeded","failed","expired"]),executor:p.z.enum(["indiana","merchant"]),currency:Ie,amountMinor:mo,mode:p.z.enum(["full","partial"]),entitlementAction:p.z.enum(["retain","revoke"]),refundId:p.z.string().min(1).max(200).nullable(),quote:Mc.optional(),execution:p.z.union([Fm,Qo]).nullable(),confirmedAt:p.z.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Cr.nullable().optional(),problem:Li.nullable().optional(),authority:Zo.optional(),failureReason:p.z.string().min(1).max(200).nullable(),createdAt:p.z.iso.datetime({offset:!0}),completedAt:p.z.iso.datetime({offset:!0}).nullable()}).refine(e=>(e.execution===null||e.executor==="merchant"&&e.status==="quoted")&&(e.status!=="succeeded"||e.refundId!==null),"Only quoted record-only refunds carry instructions; a succeeded refund names its Stripe refund"),PC=p.z.strictObject({invoiceId:p.z.uuid(),currency:Ie,paidMinor:zr,refundedMinor:zr,pendingMinor:zr,refundableMinor:zr,executor:p.z.enum(["indiana","merchant"]).nullable(),canRefund:p.z.boolean(),operations:p.z.array(Na).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),CC=p.z.strictObject({requestId:p.z.uuid(),mode:p.z.enum(["full","partial"]),amountMinor:mo.optional(),entitlementAction:p.z.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount");var Mm=ot.z.strictObject({requestId:ot.z.uuid(),targets:ot.z.array(ot.z.strictObject({membershipId:ot.z.uuid(),action:ot.z.enum(["cancel","uncancel"]),timing:ot.z.enum(["immediate","renewal"])}).refine(e=>e.action!=="uncancel"||e.timing==="immediate","Restoration is immediate")).min(1).max(100)}).refine(e=>new Set(e.targets.map(t=>t.membershipId)).size===e.targets.length,"Duplicate batch target"),Da=ot.z.strictObject({batchId:ot.z.uuid()}),kS=ot.z.strictObject({operationId:ot.z.uuid(),membershipIds:ot.z.array(ot.z.uuid()).min(1).max(20),provider:ot.z.enum(["stripe","apple","google"]),action:ot.z.enum(["cancel","uncancel"]),timing:ot.z.enum(["immediate","renewal"]),status:ot.z.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:Ta.nullable(),managementUrl:ot.z.url().nullable(),failureCode:ot.z.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),fo=ot.z.strictObject({batchId:ot.z.uuid(),ready:ot.z.boolean(),status:ot.z.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:ot.z.iso.datetime({offset:!0}),acceptedAt:ot.z.iso.datetime({offset:!0}).nullable(),groups:ot.z.array(kS).min(1).max(100)});var je=require("zod"),jS=je.z.string().trim().min(1).max(240),qc={requestId:je.z.uuid(),reason:jS},Fa=je.z.discriminatedUnion("action",[je.z.strictObject({...qc,action:je.z.literal("start"),productVersionId:je.z.uuid(),entityId:je.z.uuid().optional(),days:je.z.number().int().min(1).max(730).optional()}),je.z.strictObject({...qc,action:je.z.literal("extend"),membershipId:je.z.uuid(),days:je.z.number().int().min(1).max(730)}),je.z.strictObject({...qc,action:je.z.literal("end"),membershipId:je.z.uuid()})]),qm=je.z.strictObject({operationId:je.z.uuid()}),Um=je.z.iso.datetime({offset:!0}),TS=je.z.strictObject({provider:je.z.literal("stripe"),executor:je.z.enum(["indiana","merchant"]),accountId:je.z.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:je.z.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:je.z.union([je.z.literal("now"),Um]),prorationBehavior:je.z.literal("none")}),Uc=je.z.strictObject({operationId:je.z.uuid(),action:je.z.enum(["start","extend","end"]),status:je.z.enum(["pending","effective"]),managedBy:je.z.enum(["indiana","stripe"]),membershipIds:je.z.array(je.z.uuid()).min(1).max(20),endsAt:Um.nullable(),execution:TS.nullable()}).refine(e=>e.execution!==null==(e.managedBy==="stripe"&&e.status==="pending")&&e.action==="end"==(e.endsAt===null)&&(e.action!=="start"||e.managedBy==="indiana")&&(e.execution===null||e.execution.trialEnd==="now"==(e.action==="end")),"Only a pending Stripe trial change carries execution instructions"),kC=je.z.strictObject({groupId:je.z.uuid(),productVersionId:je.z.uuid(),enabled:je.z.boolean()});var Je=require("zod");var Bm=Je.z.strictObject({requestId:Je.z.uuid(),currency:Ie,makeDefault:Je.z.boolean()}),Vm=Je.z.strictObject({setupId:Je.z.uuid()}),NS=Je.z.strictObject({provider:Je.z.literal("stripe"),executor:Je.z.literal("merchant"),accountId:Je.z.string().regex(/^acct_[A-Za-z0-9]+$/),mode:Je.z.literal("setup"),currency:Je.z.string().regex(/^[a-z]{3}$/),customer:Je.z.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:Je.z.uuid(),metadata:Je.z.strictObject({grooveProjectId:Je.z.uuid(),grooveEnvironmentId:Je.z.uuid(),grooveCustomerId:Je.z.uuid(),groovePaymentSetupId:Je.z.uuid()}),setDefaultPaymentMethod:Je.z.boolean(),expiresAt:Je.z.iso.datetime({offset:!0})}),Bc=Je.z.strictObject({id:Je.z.uuid(),provider:Je.z.literal("stripe"),status:Je.z.enum(["prepared","complete","expired"]),currency:Ie,makeDefault:Je.z.boolean(),url:Je.z.url().nullable(),createdAt:Je.z.iso.datetime({offset:!0}),expiresAt:Je.z.iso.datetime({offset:!0}),completedAt:Je.z.iso.datetime({offset:!0}).nullable(),execution:NS.nullable()});var jt=require("zod"),Lm=jt.z.union([jt.z.string(),jt.z.number(),jt.z.boolean(),jt.z.null()]),zm=jt.z.strictObject({customerId:jt.z.uuid()}),$m=jt.z.strictObject({customerId:jt.z.uuid(),provider:jt.z.literal("stripe"),checkedAt:jt.z.iso.datetime({offset:!0}),status:jt.z.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:jt.z.number().int().nonnegative(),differences:jt.z.array(jt.z.strictObject({subscriptionId:jt.z.string().startsWith("sub_"),itemId:jt.z.string().nullable(),field:jt.z.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Lm,actual:Lm})).max(1e4)});var we=require("zod");var Ma=we.z.iso.datetime({offset:!0}),qa=we.z.strictObject({createdAt:Ma,id:we.z.uuid()}),Ua=we.z.strictObject({customerId:we.z.uuid().optional(),entityId:we.z.uuid().optional(),productId:we.z.string().min(1).max(256).optional(),provider:we.z.enum(["stripe","apple","google","merchant","free"]).optional(),status:we.z.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:qa.optional(),limit:we.z.number().int().min(1).max(100).optional()}),Vc={id:we.z.uuid(),customerId:we.z.uuid(),entityId:we.z.uuid().nullable(),productId:we.z.string().min(1).max(256),productVersionId:we.z.uuid(),name:we.z.string().min(1).max(120),provider:we.z.enum(["stripe","apple","google","merchant","free"]),createdAt:Ma},DS=we.z.strictObject({...Vc,status:we.z.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:we.z.boolean(),billingSubscriptionId:we.z.uuid().nullable()}),FS=we.z.strictObject({...Vc,status:we.z.enum(["active","ended","refunded"]),orderId:we.z.uuid().nullable(),transactionId:we.z.uuid().nullable(),currency:Ie.nullable(),amountMinor:we.z.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),MS=we.z.strictObject({...Vc,status:we.z.enum(["blocked","resolved"]),conflict:we.z.strictObject({detectedAt:Ma,blockingMembershipIds:we.z.array(we.z.uuid()).min(1).max(100),transactionId:we.z.uuid()}),resolvedAt:Ma.nullable()}),Gm=Ua.extend({status:we.z.enum(["blocked","resolved"]).optional()}),Km=we.z.strictObject({customerId:we.z.uuid(),orderId:we.z.uuid()}),Hm=we.z.strictObject({orderId:we.z.uuid(),status:we.z.enum(["blocked","resolved"])}),Qm=we.z.strictObject({items:we.z.array(DS).max(100),nextCursor:qa.nullable()}),Jm=we.z.strictObject({items:we.z.array(FS).max(100),nextCursor:qa.nullable()}),Zm=we.z.strictObject({items:we.z.array(MS).max(100),nextCursor:qa.nullable()});var tt=require("zod");var Wm=tt.z.union([tt.z.strictObject({intent:tt.z.literal("read"),requestId:tt.z.uuid(),purchaseIntentId:tt.z.uuid()}),tt.z.strictObject({requestId:tt.z.uuid(),provider:tt.z.literal("apple"),purchaseIntentId:tt.z.uuid(),productId:tt.z.string().min(1).max(255).optional(),signedTransaction:tt.z.string().min(1).max(131072)}),tt.z.strictObject({requestId:tt.z.uuid(),provider:tt.z.literal("google"),purchaseIntentId:tt.z.uuid(),productId:tt.z.string().min(1).max(255).optional(),purchaseToken:tt.z.string().min(1).max(16384)})]),Ym=tt.z.strictObject({requestId:tt.z.uuid(),orderId:tt.z.uuid(),purchaseIntentId:tt.z.uuid(),status:tt.z.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:Ie,refunded:tt.z.boolean(),completion:tt.z.strictObject({transactionIds:tt.z.array(tt.z.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:tt.z.boolean()}).nullable()});var V=require("zod"),zc=V.z.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),qS=V.z.record(V.z.string(),V.z.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),US=3,go=20,BS=US*go,Lc=V.z.strictObject({type:V.z.literal("product"),productId:zc}),Xm={type:V.z.literal("group"),key:V.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:V.z.string().trim().min(1).max(80)},VS=V.z.discriminatedUnion("type",[Lc,V.z.strictObject({...Xm,items:V.z.array(Lc).max(go)})]),LS=V.z.discriminatedUnion("type",[Lc,V.z.strictObject({...Xm,items:V.z.array(VS).max(go)})]),zS=V.z.array(LS).max(go).superRefine((e,t)=>{let n=new Set,r=new Set,i=0;function a(o){for(let s of o){i++;let c=s.type==="product"?n:r,u=s.type==="product"?s.productId:s.key;c.has(u)&&t.addIssue({code:"custom",message:s.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),c.add(u),s.type==="group"&&a(s.items)}}a(e),(n.size>go||i>BS)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function $c(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:$c(t))}var vi=V.z.strictObject({lookupKey:V.z.string().trim().min(1).max(200),displayName:V.z.string().trim().min(1).max(1500),items:zS,metadata:qS}),$S=V.z.strictObject({product:V.z.record(V.z.string(),V.z.json()),prices:V.z.array(V.z.record(V.z.string(),V.z.json())),entitlements:V.z.array(V.z.record(V.z.string(),V.z.json())),freeTrials:V.z.array(V.z.record(V.z.string(),V.z.json())),licenses:V.z.array(V.z.record(V.z.string(),V.z.json()))}),ef=vi.extend({id:V.z.uuid(),projectId:V.z.uuid(),environmentId:V.z.uuid(),state:V.z.enum(["active","archived"]),isCurrent:V.z.boolean(),revision:V.z.number().int().nonnegative(),publishedVersionId:V.z.uuid().nullable(),createdAt:V.z.iso.datetime({offset:!0})}).superRefine((e,t)=>{e.isCurrent&&(e.state!=="active"||!e.publishedVersionId)&&t.addIssue({code:"custom",message:"Current Offering must be active and published"})}),tf=V.z.strictObject({id:V.z.uuid(),offeringId:V.z.uuid(),projectId:V.z.uuid(),environmentId:V.z.uuid(),version:V.z.number().int().positive(),document:vi,productEvidence:V.z.record(zc,$S),createdAt:V.z.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=$c(e.document);(!n.length||HS(e.document).length>0||Object.keys(e.productEvidence).length!==n.length||n.some(r=>!Object.hasOwn(e.productEvidence,r)))&&t.addIssue({code:"custom",message:"Published Offering requires evidence for every Product"})}),GS=V.z.strictObject({rows:V.z.array(ef).max(200),versions:V.z.array(tf).max(500)}),BC=V.z.discriminatedUnion("action",[V.z.strictObject({action:V.z.literal("create"),document:vi}),V.z.strictObject({action:V.z.literal("save"),id:V.z.uuid(),revision:V.z.number().int().nonnegative(),document:vi}),V.z.strictObject({action:V.z.enum(["publish","set_current","archive","restore"]),id:V.z.uuid(),revision:V.z.number().int().nonnegative()})]),VC=V.z.strictObject({record:ef,version:tf.nullable()}),nf=V.z.discriminatedUnion("type",[V.z.strictObject({type:V.z.literal("current")}),V.z.strictObject({type:V.z.literal("id"),id:V.z.uuid()}),V.z.strictObject({type:V.z.literal("lookup_key"),lookupKey:V.z.string().min(1).max(200)}),V.z.strictObject({type:V.z.literal("version"),versionId:V.z.uuid()})]),KS=V.z.strictObject({internalId:zc,id:V.z.string(),name:V.z.string().nullable(),version:V.z.number().int().positive(),archived:V.z.boolean()}),LC=GS.extend({products:V.z.array(KS).max(500),pagination:V.z.strictObject({rows:V.z.string().nullable(),versions:V.z.string().nullable(),products:V.z.string().nullable()}).optional()});function HS(e){let t=[];$c(e).length||t.push("Select at least one Product before publishing");function n(r){for(let i of r)i.type==="group"&&(i.items.length||t.push("Every published group requires a Product"),n(i.items))}return n(e.items),t}var ho=require("zod");var rf=ho.z.strictObject({id:ho.z.uuid(),offeringId:ho.z.uuid(),version:ho.z.number().int().positive(),document:vi});var vt=require("zod");var ye=require("zod");var Gr=require("zod");var Ba=Gr.z.strictObject({items:Gr.z.array(Gr.z.strictObject({productVersionId:Gr.z.string().min(1).max(200),label:Gr.z.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:Gr.z.string().min(1).max(200).nullable(),grouping:va.optional()});function of(e,t,n){let r=e.type==="fixed"?e.productVersionId:t[e.pickerId];return typeof r!="string"||!Object.values(n.plans).some(i=>i.versionId===r&&i.available)||e.type==="picker"&&(!e.allowedProductVersionIds.includes(r)||!n.pickers[e.pickerId]?.options.includes(r))?null:r}var Gc=ye.z.discriminatedUnion("type",[ye.z.strictObject({type:ye.z.literal("event"),event:ye.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),ye.z.strictObject({type:ye.z.literal("open_url"),url:ye.z.url().refine(e=>new URL(e).protocol==="https:")})]),QS=dn,JS=ye.z.discriminatedUnion("type",[ye.z.object({type:ye.z.literal("checkout"),product:Oa}).strict(),ye.z.object({type:ye.z.literal("close")}).strict(),ye.z.object({type:ye.z.literal("action"),action:Gc}).strict()]),wi=ye.z.object({schemaVersion:ye.z.literal(3),kind:ye.z.literal("paywall"),name:ye.z.string().trim().min(1).max(80),presentation:Cn,requirement:or.optional(),products:Ba,offeringVersionId:ye.z.uuid().nullable(),offeringId:ye.z.uuid(),screen:QS,buttons:ye.z.record(ye.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),JS)}).strict(),e_=wi.superRefine((e,t)=>{(e.screen.surface!=="paywall"||e.screen.actions.some(r=>!["event","navigate"].includes(r.type)||r.close))&&t.addIssue({code:"custom",message:"Paywall screen is incomplete"});for(let r of WS(e))t.addIssue({code:"custom",message:r});for(let r of ZS(e))t.addIssue({code:"custom",message:r});ar(e.screen).some(r=>!r.complete)&&t.addIssue({code:"custom",message:"Paywall needs complete local content"}),(Object.keys(e.buttons).length!==e.screen.actions.filter(r=>r.type!=="navigate").length||e.screen.actions.some(r=>r.type!=="navigate"&&!Object.hasOwn(e.buttons,r.id)))&&t.addIssue({code:"custom",message:"Paywall buttons require matching node policies"}),Object.values(e.buttons).some(r=>r.type==="checkout")||t.addIssue({code:"custom",message:"A paywall requires a purchase or membership change button"})});function ZS(e){let t=e.products.items.map(a=>a.productVersionId),n=Gp(e.screen),r=new Set,i=[];(!t.length||!e.products.defaultProductVersionId||!t.includes(e.products.defaultProductVersionId))&&i.push("products"),e.offeringVersionId||i.push("offering"),e.products.grouping&&(!wa(e.products.grouping,t)||e.products.grouping.tiers.some(a=>!e.products.grouping.assignments.some(o=>o.tierId===a.id)))&&i.push("grouping");for(let a of Object.values(e.buttons))if(a.type==="checkout"){let o=a.product;if(o.type==="fixed")r.add(o.productVersionId);else{o.allowedProductVersionIds.forEach(u=>r.add(u));let s=!1,c=n[o.pickerId];c&&(s=!0,(o.allowedProductVersionIds.some(u=>!c.ids.includes(u))||c.ids.some(u=>!o.allowedProductVersionIds.includes(u)))&&i.push("picker")),Ht(e.screen,u=>{if(u.id!==o.pickerId||u.type!=="plan_picker")return;s=!0,(JSON.stringify(u.planIds)!==JSON.stringify(t)||JSON.stringify(o.allowedProductVersionIds)!==JSON.stringify(t)||u.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let l=u.grouping?{tiers:u.grouping.tiers,assignments:u.grouping.assignments}:void 0;JSON.stringify(l)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),s||i.push("picker")}}return(!r.size||[...r].some(a=>!t.includes(a)))&&i.push("purchase"),Ht(e.screen,a=>{a.type==="stack"&&a.productSlot&&!a.bind?.plan&&i.push(`productBinding:${a.id}`),(a.type==="stack"||a.type==="button")&&a.bind?.plan&&!t.includes(a.bind.plan)&&i.push("binding"),a.type==="plan_picker"&&(!a.planIds?.length||a.planIds.some(o=>!t.includes(o)))&&i.push("binding")}),[...new Set(i)]}function WS(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),Wn(s.root,c=>{let u=c.type==="button"?c.action:c.type==="stack"?c.purchaseAction:void 0;if(u){let l=e.screen.actions.find(f=>f.id===u);l?.type==="navigate"&&r.get(s.id).push(l.pageId);let m=e.buttons[u];s.id!==n.id&&m&&m.type!=="close"&&t.push(`purchaseScreen:${c.id}`)}s.id!==n.id&&(c.type==="plan_picker"||c.type==="stack"&&c.productSlot)&&t.push(`packageScreen:${c.id}`)});let i=new Set;function a(s){if(!i.has(s)){i.add(s);for(let c of r.get(s)??[])a(c)}}let o=e.screen.initialPageId??e.screen.pages[0]?.id;o?a(o):t.push("initialPage");for(let s of e.screen.pages)i.has(s.id)||t.push(`unreachableScreen:${s.id}`);return[...new Set(t)]}var af=ye.z.object({id:ye.z.uuid(),projectId:ye.z.uuid(),environmentId:ye.z.uuid(),revision:ye.z.number().int().nonnegative(),state:ye.z.enum(["active","archived"]),publishedVersionId:ye.z.uuid().nullable(),updatedAt:ye.z.iso.datetime({offset:!0}),draft:wi}).strict(),t_=ye.z.object({rows:ye.z.array(af).max(200),nextCursor:ye.z.uuid().nullable()}).strict(),n_=af.omit({draft:!0}).extend({name:ye.z.string(),productCount:ye.z.number().int().nonnegative()}).strict(),r_=ye.z.discriminatedUnion("action",[ye.z.object({action:ye.z.literal("save"),id:ye.z.uuid().nullable(),revision:ye.z.number().int().nonnegative(),document:wi}).strict(),ye.z.object({action:ye.z.enum(["publish","archive"]),id:ye.z.uuid(),revision:ye.z.number().int().nonnegative()}).strict()]),i_=ye.z.object({paywalls:ye.z.array(ye.z.object({id:ye.z.uuid(),paywallId:ye.z.uuid(),version:ye.z.number().int().positive(),name:ye.z.string().min(1).max(80),presentation:Cn,buttons:wi.shape.buttons}).strict()).max(500),limited:ye.z.boolean()}).strict();var Re=require("zod");var Lt=require("zod");var Oi=Lt.z.string().regex(/^[a-f0-9]{64}$/),YS=Sa.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),sf=Lt.z.strictObject({couponDigests:Lt.z.record(Lt.z.uuid(),Oi),variables:Lt.z.record(wn,Lt.z.record(Lt.z.uuid(),Lt.z.partialRecord(Lt.z.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),Lt.z.string()))),locales:Lt.z.record(wn,mi.extend({nodes:Lt.z.record(Lt.z.string(),Lt.z.strictObject({base:YS})),plans:Lt.z.object({}).strict(),pickers:Lt.z.object({}).strict()}).omit({paywall:!0}))});var Ve=require("zod");var yo=require("zod"),Kc=yo.z.strictObject({eventsEnabled:yo.z.boolean(),experimentViewsEnabled:yo.z.boolean(),featureUsageEnabled:yo.z.boolean()}),u_=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function cf(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}var $=require("zod");var Hc=$.z.tuple([$.z.number().min(0).max(1),$.z.number().min(0).max(1)]).refine(([e,t])=>e<=t),XS=$.z.strictObject({attribute:$.z.string().optional(),seed:$.z.string(),hashVersion:$.z.literal(2),ranges:$.z.array(Hc).max(100)}),e0=$.z.strictObject({id:$.z.string().min(1).max(255),condition:Yt,gate:$.z.boolean().optional()}),t0=$.z.strictObject({key:$.z.string().optional(),name:$.z.string().optional(),passthrough:$.z.boolean().optional()}),uf={condition:Yt.optional(),parentConditions:$.z.array(e0).max(100).optional(),weights:$.z.array($.z.number().min(0).max(1)).max(20).optional(),coverage:$.z.number().min(0).max(1).optional(),hashAttribute:$.z.string().optional(),fallbackAttribute:$.z.string().optional(),hashVersion:$.z.literal(2).optional(),disableStickyBucketing:$.z.boolean().optional(),bucketVersion:$.z.number().int().nonnegative().optional(),minBucketVersion:$.z.number().int().nonnegative().optional(),filters:$.z.array(XS).max(100).optional(),ranges:$.z.array(Hc).max(20).optional(),meta:$.z.array(t0).max(20).optional(),seed:$.z.string().optional(),name:$.z.string().optional(),phase:$.z.string().optional()},Pi=$.z.strictObject({...uf,key:$.z.string().min(1).max(255),variations:$.z.tuple([ve,ve]).rest(ve).refine(e=>e.length<=20),urlPatterns:$.z.array($.z.strictObject({include:$.z.boolean(),type:$.z.enum(["regex","simple"]),pattern:$.z.string()})).max(100).optional(),force:$.z.number().int().nonnegative().optional(),active:$.z.boolean().optional(),persistQueryString:$.z.boolean().optional()}),Qc=$.z.strictObject({value:ve,variationId:$.z.number().int(),key:$.z.string(),name:$.z.string().optional(),bucket:$.z.number().optional(),passthrough:$.z.boolean().optional(),inExperiment:$.z.boolean(),hashUsed:$.z.boolean().optional(),hashAttribute:$.z.string(),hashValue:$.z.string(),featureId:$.z.string().nullable(),stickyBucketUsed:$.z.boolean().optional()}),n0=$.z.strictObject({...uf,id:$.z.string().max(255).optional(),force:ve.optional(),variations:$.z.array(ve).min(2).max(20).optional(),key:$.z.string().optional(),range:Hc.optional(),tracks:$.z.array($.z.strictObject({experiment:Pi,result:Qc})).max(100).optional()}),r0=$.z.strictObject({defaultValue:ve.optional(),rules:$.z.array(n0).max(500).optional()}),Ao=$.z.record($.z.string(),$.z.union([$.z.strictObject({type:$.z.literal("hashed"),attributeKey:$.z.string(),values:$.z.array($.z.string().regex(/^[a-f0-9]{64}$/))}),$.z.strictObject({type:$.z.literal("list"),attributeKey:$.z.string(),values:$.z.array($.z.union([$.z.string(),$.z.number()]))}),$.z.strictObject({type:$.z.literal("condition"),condition:Yt})])),bn=$.z.strictObject({scope:Fe,generation:$.z.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:$.z.iso.datetime({offset:!0}),expiresAt:$.z.iso.datetime({offset:!0}).nullable(),features:$.z.record($.z.string(),r0),savedGroups:Ao,experiments:$.z.record($.z.uuid(),Pi)});var bo=bn.extend({analyticsConfig:Kc,remoteFeatures:Ve.z.array(Ve.z.string().min(1).max(255)).max(500)}),Jc=bo.omit({evaluatedAt:!0,expiresAt:!0}).superRefine((e,t)=>{for(let n of e.remoteFeatures)Object.hasOwn(e.features,n)&&t.addIssue({code:"custom",path:["features",n],message:"Remote Feature definitions cannot be public"});for(let[n,r]of Object.entries(e.savedGroups))r.type==="list"&&t.addIssue({code:"custom",path:["savedGroups",n],message:"Raw Saved Group lists cannot be public"})}),lf=Ve.z.strictObject({attributes:Ct,features:Ve.z.array(Ve.z.string().min(1).max(255)).max(500).optional(),customerId:Ve.z.uuid().optional()}),i0=Ve.z.strictObject({value:ve,source:Ve.z.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:Ve.z.boolean(),off:Ve.z.boolean(),ruleId:Ve.z.string(),experimentResult:Qc.optional()}),Va=Ve.z.strictObject({generation:bn.shape.generation,evaluatedAt:bn.shape.evaluatedAt,expiresAt:bn.shape.expiresAt,features:Ve.z.record(Ve.z.string(),i0),merchandiseContext:Ve.z.strictObject({merchandiseId:Ve.z.uuid(),merchandise:Ct}).optional()}),df=Ve.z.strictObject({customerId:Ve.z.uuid().optional(),events:Ve.z.array(Ve.z.strictObject({eventUuid:Ve.z.uuid(),timestamp:Ve.z.iso.datetime({offset:!0}),name:Ve.z.string().min(1).max(255),merchandise:zd.optional(),properties:Ve.z.record(Ve.z.string(),ve).default({}),deviceId:Ve.z.string().min(1).max(255).optional(),sessionId:Ve.z.string().min(1).max(255).optional()})).min(1).max(100)}),pf=Ve.z.strictObject({inserted:Ve.z.number().int().nonnegative(),duplicates:Ve.z.number().int().nonnegative(),rejected:Ve.z.number().int().nonnegative(),skipped:Ve.z.number().int().nonnegative(),analyticsConfig:Kc});var L=require("zod");var mf=require("zod"),ff=mf.z.enum(["funnel-run/1","funnel-process/1"]),gf="funnel-process/1";function Zc(e,t=[]){let n=[];Ht(e,i=>{i.hidden&&n.push("Hidden components must not be delivered"),t.includes(i.type)&&n.push(`Node type ${i.type} cannot be delivered`)});let r=new Set(Pa(e).map(i=>i.key));for(let[i,a]of Object.entries(e.strings.locales))for(let o of Object.keys(a))r.has(o)||n.push(`Unused string ${o} must not be delivered (${i})`);return n}function hf(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>hf(t)??[])}}function o0(e){let t=e.pages.map(i=>{let a=hf(i.root);return a?.type==="stack"?{...i,root:a}:{...i,root:{type:"stack",id:i.root.id,...i.root.name===void 0?{}:{name:i.root.name},direction:"vertical",align:"stretch",justify:"start",children:[]}}}),n=new Set(Pa({pages:t}).map(i=>i.key)),r=Object.fromEntries(Object.entries(e.strings.locales).map(([i,a])=>[i,Object.fromEntries(Object.entries(a).filter(([o])=>n.has(o)))]));return{...e,pages:t,strings:{...e.strings,locales:r}}}function yf(e,t=[]){let n=dn.parse(structuredClone(o0(e))),r=a=>a.type!=="stack"||a.interaction!==void 0||a.children.some(r);for(let a of n.pages)if(!r(a.root))throw new Error(`Page ${a.id} has no visible content`);let i=Zc(n,t);if(i.length)throw new Error(i.join("; "));return n}var Q=require("zod");var M=require("zod");var pt=require("zod"),La=pt.z.strictObject({schemaVersion:pt.z.literal(1),renderKey:pt.z.string().min(1).max(256),routeTemplate:pt.z.string().startsWith("/").max(2048),selectors:pt.z.array(pt.z.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:pt.z.array(pt.z.number().int().min(0)).min(1),absent:pt.z.array(pt.z.number().int().min(0))}).superRefine((e,t)=>{let n=[...e.present,...e.absent];(new Set(e.selectors).size!==e.selectors.length||new Set(n).size!==n.length||n.length!==e.selectors.length||n.some(r=>r>=e.selectors.length))&&t.addIssue({code:"custom",message:"Incomplete or ambiguous render signature"})}),Af=pt.z.strictObject({renderKey:pt.z.string().min(1).max(256),routeKey:pt.z.string().min(1).max(256),stateKey:pt.z.string().min(1).max(256),documentKey:pt.z.string().min(1).max(256),documentHash:pt.z.string().regex(/^[a-f0-9]{64}$/),compositionKey:pt.z.string().min(1).max(256),entryMode:pt.z.enum(["hard","soft"]),match:pt.z.strictObject({present:pt.z.array(pt.z.number().int().min(0)),absent:pt.z.array(pt.z.number().int().min(0))})});var ur=require("zod"),a0=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],Wc="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",s0=ur.z.string().regex(new RegExp(`^${Wc}/${Wc}/${Wc}/manifest\\.json$`)),bf=ur.z.strictObject({kind:ur.z.literal("gcs-resumable"),url:ur.z.url(),bucket:ur.z.enum(a0),objectKey:s0,byteLength:ur.z.number().int().positive(),expiresAt:ur.z.iso.datetime()}).superRefine((e,t)=>{let n=new URL(e.url),r=n.searchParams,i=["uploadType","upload_id","name","upload_protocol","ifGenerationMatch"];(n.origin!=="https://storage.googleapis.com"||n.username||n.password||n.hash||n.pathname!==`/upload/storage/v1/b/${e.bucket}/o`||[...r.keys()].some(a=>!i.includes(a)||r.getAll(a).length!==1)||r.get("uploadType")!=="resumable"||!/^[A-Za-z0-9_-]{1,4096}$/.test(r.get("upload_id")??"")||r.has("name")&&r.get("name")!==`app-manifests/${e.objectKey}`||r.has("upload_protocol")&&r.get("upload_protocol")!=="resumable"||r.has("ifGenerationMatch")&&r.get("ifGenerationMatch")!=="0")&&t.addIssue({code:"custom",message:"Invalid IAM upload capability"})});var bt=M.z.string().min(1).max(256),mn=M.z.string().regex(/^[a-f0-9]{64}$/),za=M.z.strictObject({versionId:M.z.uuid(),manifestDigest:mn,sourceGraphDigest:mn,pageKey:bt,stateKey:bt,documentKey:bt,documentHash:mn,elementKey:bt.optional(),nodeId:bt.optional(),contentHash:mn.optional(),renderKey:bt.optional()}),xf=M.z.strictObject({pageKey:bt,documentKey:bt,expectedDocumentHash:mn,renderKey:bt.optional(),nodeId:bt,elementKey:bt,expectedContentHash:mn,property:M.z.enum(["text","fontSize","color"]),value:M.z.union([M.z.string().max(4e3),M.z.number().finite()])}),Sf=M.z.strictObject({versionId:M.z.uuid(),manifestDigest:mn,sourceGraphDigest:mn,pageKey:bt,stateKey:bt,documentKey:bt,documentHash:mn,renderKey:bt.optional(),patches:M.z.array(xf.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),c0=/^[a-z][a-z0-9-]{0,39}$/,xo=M.z.string().regex(c0),Xc=M.z.enum(["web","ios","android"]),P_=M.z.discriminatedUnion("action",[M.z.strictObject({action:M.z.literal("register"),requestId:M.z.uuid(),client:xo,platform:Xc,label:M.z.string().trim().min(1).max(100),sha256:mn,bytes:M.z.number().int().min(1),transferBytes:M.z.number().int().min(1)}),M.z.strictObject({action:M.z.literal("complete"),versionId:M.z.uuid()}),M.z.strictObject({action:M.z.literal("current"),versionId:M.z.uuid(),expectedCurrent:M.z.uuid().nullable()}),M.z.strictObject({action:M.z.literal("delivery"),enabled:M.z.boolean()}),M.z.strictObject({action:M.z.literal("changes"),versionId:M.z.uuid(),experimentId:M.z.uuid(),variationId:bt,changesetId:M.z.uuid().nullable(),expectedRevision:mn.nullable(),editorUrl:M.z.string().url().max(2048),patches:M.z.array(xf).max(200)})]),eu=M.z.strictObject({id:M.z.uuid(),projectId:M.z.uuid(),environmentId:M.z.uuid(),clientKey:xo,platform:Xc,label:M.z.string(),sha256:mn,bytes:M.z.number().int().positive(),objectKey:M.z.string(),state:M.z.enum(["uploading","ready","rejected"]),isCurrent:M.z.boolean(),revision:M.z.number().int().nonnegative(),createdAt:M.z.string(),expiresAt:M.z.string(),readyAt:M.z.string().nullable(),summary:M.z.record(M.z.string(),M.z.json()),routeTree:M.z.json().nullable(),validation:M.z.record(M.z.string(),M.z.json())}),u0=M.z.strictObject({key:xo,platform:Xc,currentId:M.z.uuid().nullable()}),C_=M.z.strictObject({rows:M.z.array(eu).max(100),nextCursor:M.z.uuid().nullable(),clients:M.z.array(u0).max(20)}),Yc=M.z.strictObject({storedBytes:M.z.number().int().nonnegative(),reservedBytes:M.z.number().int().nonnegative(),chargedBytes:M.z.number().int().nonnegative(),versions:M.z.number().int().nonnegative(),objects:M.z.number().int().nonnegative(),orphanObjects:M.z.number().int().nonnegative(),missingReadyObjects:M.z.number().int().nonnegative(),unknownObjectSizes:M.z.number().int().nonnegative(),byteLimit:M.z.number().int().positive(),versionLimit:M.z.number().int().positive(),remainingBytes:M.z.number().int().nonnegative()}),__=M.z.strictObject({asOf:M.z.iso.datetime({offset:!0}),reclamation:M.z.literal("manual-review-required"),buckets:M.z.strictObject({source:Yc,runtime:Yc,previews:Yc})}),E_=M.z.strictObject({version:eu,actorId:M.z.uuid(),claims:M.z.record(M.z.string(),M.z.json())}),R_=M.z.strictObject({version:eu,upload:bf.nullable()}),k_=M.z.object({format:M.z.literal("indiana-route-state-index"),schemaVersion:M.z.literal(3),routes:M.z.array(M.z.object({routeKey:bt,path:M.z.string(),documentKey:bt,documentHash:mn,initialStateKey:bt,initialRenderKey:bt})),renders:M.z.array(Af)}).loose().superRefine((e,t)=>{(!e.renders||e.routes.some(n=>!e.renders?.some(r=>r.renderKey===n.initialRenderKey&&r.routeKey===n.routeKey&&r.documentKey===n.documentKey&&r.stateKey===n.initialStateKey&&r.documentHash===n.documentHash&&r.entryMode==="hard")))&&t.addIssue({code:"custom",message:"Incomplete render catalog"})}),j_=M.z.strictObject({rows:M.z.array(M.z.object({id:M.z.uuid(),name:M.z.string(),status:M.z.string(),variations:M.z.array(M.z.object({id:bt,key:bt,name:M.z.string().optional()}).loose())}).loose()),limited:M.z.boolean()}),T_=M.z.strictObject({enabled:M.z.boolean(),allowedOrigins:M.z.array(M.z.string())});var Kr=require("zod");var If=Kr.z.strictObject({id:Kr.z.uuid(),name:Kr.z.string().trim().min(1).max(80),client:xo,source:za,event:Kr.z.enum(["screen_enter","button_click"]),cooldownSeconds:Kr.z.number().int().min(0).max(2592e3),behavior:Kr.z.literal("observe")}).superRefine((e,t)=>{e.event==="button_click"&&(!e.source.nodeId||!e.source.elementKey)&&t.addIssue({code:"custom",path:["source"],message:"Choose a uniquely bound button"})});var ze=require("zod");var tu=ve,l0=["parameters","answers","results","variables"];function nu(e){return l0.some(t=>e===t||e.startsWith(t+"."))}function ru(e){let t={};for(let[r,i]of Object.entries(Ca(e.declarations,e))){let a=r.split(".");if(a.some(c=>["__proto__","constructor","prototype"].includes(c)))throw new Error("Reserved result path");let o=t;for(let c of a.slice(0,-1)){Object.hasOwn(o,c)||(o[c]={});let u=o[c];if(!u||typeof u!="object"||Array.isArray(u))throw new Error("Ambiguous result path");o=u}let s=a.at(-1);if(s===void 0)throw new Error("Empty result path");o[s]=i}return{...Object.fromEntries(Object.entries(e.attributes).filter(([r])=>!nu(r))),variables:t}}var ft=require("zod");var $a=ft.z.discriminatedUnion("kind",[ft.z.object({kind:ft.z.literal("ledger"),cursor:xa}).strict(),ft.z.object({kind:ft.z.literal("billing"),cursor:ft.z.uuid()}).strict()]),d0=ft.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),lr=ft.z.record(ft.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ft.z.union([ft.z.string().max(500),ft.z.boolean(),ft.z.array(ft.z.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),p0=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function iu(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>iu(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||p0.test(n)||iu(r,t+1)))}var m0=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,dr=ft.z.record(d0,ve).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!iu(e)&&!m0.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var vf=ft.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ga=ft.z.array(ft.z.object({variable:vf,componentId:vf,required:ft.z.boolean()}).strict()).max(40).refine(e=>new Set(e.map(t=>t.variable)).size===e.length&&new Set(e.map(t=>t.componentId)).size===e.length,"Input bindings must be unique"),z_=ft.z.object({bindings:Ga,answers:lr,values:ft.z.record(ft.z.string(),ve).optional()}).strict();var wf=require("zod"),Ka=wf.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var ou=ze.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Of=ze.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),Pf=dr.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),au=ze.z.record(ou,ze.z.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),f0=Mn,Cf=ze.z.strictObject({type:ze.z.literal("external_task"),endpointId:ze.z.uuid(),taskKey:ou,inputs:ze.z.record(ou,f0).refine(e=>Object.keys(e).length<=20),outputs:au}),_f=ze.z.strictObject({maxAttempts:ze.z.number().int().min(1).max(5),retryDelaySeconds:ze.z.number().int().min(1).max(30),backoff:ze.z.enum(["fixed","exponential"]),requestTimeoutSeconds:ze.z.number().int().min(1).max(10),timeoutSeconds:ze.z.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var W_=ze.z.strictObject({outcome:ze.z.enum(["success","failure"]),data:Pf});var Y_=ze.z.discriminatedUnion("operation",[ze.z.strictObject({operation:ze.z.literal("signal"),runId:ze.z.uuid(),nodeId:Of,eventName:Ka,eventId:ze.z.uuid(),data:Pf}),ze.z.strictObject({operation:ze.z.literal("read_results"),runId:ze.z.uuid()})]),X_=ze.z.strictObject({scope:Fe,runId:ze.z.uuid(),eventId:ze.z.uuid(),accepted:ze.z.boolean()}),g0=ze.z.record(Of,tu),e1=ze.z.strictObject({scope:Fe,runId:ze.z.uuid(),results:g0});var kn={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},Ef="00000000-0000-0000-0000-000000000000";var J=require("zod");var Ze=require("zod");var o1=Ze.z.enum(["local","remote"]),su=Ze.z.strictObject({port:Ze.z.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:ve.optional(),sticky:Ze.z.array(Ze.z.strictObject({expected:Hi.nullable(),next:Hi})).max(100),exposures:Ze.z.array(ve).max(100),features:Ze.z.array(ve).max(100)}),Rf=Ze.z.strictObject({type:Ze.z.literal("evaluate"),receiptId:Ze.z.uuid(),environmentId:Ze.z.uuid(),policyRevision:Ze.z.number().int().nonnegative(),attributes:Ct,sticky:Ze.z.record(Ze.z.string(),Hi)}),kf=Rf.extend({runId:Ze.z.uuid(),versionId:Ze.z.uuid(),nodeId:Ze.z.string().min(1).max(64),visit:Ze.z.number().int().nonnegative(),revision:Ze.z.number().int().nonnegative()}),cu=Rf.omit({type:!0,receiptId:!0}).extend({type:Ze.z.literal("evaluate_segment")}),jf=Ze.z.strictObject({nodeId:Ze.z.string().min(1).max(64),result:su}),Tf=cu.extend({runId:Ze.z.uuid(),versionId:Ze.z.uuid(),nodeId:Ze.z.string().min(1).max(64),visit:Ze.z.number().int().nonnegative(),revision:Ze.z.number().int().nonnegative(),parameters:dr,answers:lr,variables:Ze.z.record(Ze.z.string(),ve)});var ue=require("zod");var uu=ue.z.array(ue.z.string().trim().min(1).max(40).refine(e=>!e.includes(","),"\u6807\u7B7E\u4E0D\u80FD\u5305\u542B\u9017\u53F7")).max(20).refine(e=>new Set(e).size===e.length,"\u6807\u7B7E\u4E0D\u80FD\u91CD\u590D"),Ha=ue.z.intersection(Ct,ue.z.looseObject({tags:uu.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),Qa=ue.z.string().trim().max(80),Ja=ue.z.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),Za=ue.z.union([ue.z.email().max(254),ue.z.literal("")]),Wa=ue.z.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),Nf=ue.z.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),Df=ue.z.object({externalUserId:Nf.optional(),name:Qa.default(""),email:Za.default(""),phone:Ja.optional(),attributes:Ha.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),Hr=ue.z.discriminatedUnion("type",[ue.z.strictObject({type:ue.z.literal("id"),value:ue.z.uuid()}),ue.z.strictObject({type:ue.z.literal("externalUserId"),value:Nf})]),Ci=ue.z.strictObject({name:Qa.optional(),email:Za.optional(),phone:Ja.optional(),attributes:Ha.optional(),fingerprint:Wa.optional()}),Ya=e=>!e.customerData||e.customer?.type==="externalUserId",Xa="customerData requires an externalUserId customer",_i=ue.z.object({id:ue.z.uuid(),externalUserId:ue.z.string().min(1).max(255).nullable(),name:Qa,email:Za,phone:Ja.optional(),attributes:Ha,createdAt:ue.z.iso.datetime()}).strict(),Ff=ue.z.object({customer:_i,changed:ue.z.boolean(),replayed:ue.z.boolean()}).strict(),h0=ue.z.discriminatedUnion("type",[ue.z.object({type:ue.z.literal("id"),value:ue.z.uuid()}).strict(),ue.z.object({type:ue.z.literal("externalUserId"),value:ue.z.string().trim().min(1).max(255)}).strict()]),y0=ue.z.object({name:Qa.optional(),email:Za.optional(),phone:Ja.optional(),attributes:Ha.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:ue.z.array(ue.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:ue.z.strictObject({add:uu,remove:uu}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),lu=ue.z.object({lookup:h0}).strict(),Mf=lu.extend({requestId:ue.z.uuid(),patch:y0}).strict(),qf=ue.z.object({search:ue.z.string().trim().max(200).default(""),tag:ue.z.string().trim().max(40).default(""),planId:ue.z.string().max(200).default(""),versionId:ue.z.string().max(200).default(""),holdingStatus:ue.z.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:ue.z.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:ue.z.union([ue.z.iso.datetime(),ue.z.literal("")]).default(""),createdUntil:ue.z.union([ue.z.iso.datetime(),ue.z.literal("")]).default(""),offset:ue.z.coerce.number().int().min(0).max(1e5).default(0),limit:ue.z.coerce.number().int().min(1).max(100).default(50)}).strict(),Uf=ue.z.object({customers:_i.array(),hasMore:ue.z.boolean(),total:ue.z.number().int().nonnegative().nullable(),evaluatedAt:ue.z.iso.datetime()}).strict();var So=J.z.discriminatedUnion("type",[J.z.strictObject({type:J.z.literal("literal"),value:ve}),J.z.strictObject({type:J.z.literal("variable"),key:It,path:Rn.optional()}),J.z.strictObject({type:J.z.literal("feature"),featureKey:J.z.string().min(1).max(128)})]),A0=J.z.strictObject({requestId:J.z.uuid(),decisionId:J.z.uuid(),customerId:J.z.uuid(),externalUserId:J.z.string().min(1).max(255).nullable(),versionId:J.z.uuid(),receiptId:J.z.uuid(),value:ve}),b0={funnelId:J.z.uuid(),requestId:J.z.uuid(),customer:Hr,customerData:Ci.optional(),attributes:Ct.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},g1=J.z.discriminatedUnion("operation",[J.z.strictObject({operation:J.z.literal("decide"),...b0}).refine(Ya,Xa),J.z.strictObject({operation:J.z.literal("read_decision"),decisionId:J.z.uuid()}),J.z.strictObject({operation:J.z.literal("evaluate_decision"),decisionId:J.z.uuid(),requestId:J.z.uuid(),nodeId:J.z.string().min(1).max(64),visit:J.z.number().int().nonnegative(),revision:J.z.number().int().nonnegative(),receiptId:J.z.uuid(),policyRevision:J.z.number().int().nonnegative(),generation:J.z.string().min(1).max(256),result:su}),J.z.strictObject({operation:J.z.literal("feature_config"),funnelId:J.z.uuid()}),J.z.strictObject({operation:J.z.literal("commit_decision_segment"),decisionId:J.z.uuid(),requestId:J.z.uuid(),nodeId:J.z.string().min(1).max(64),visit:J.z.number().int().nonnegative(),revision:J.z.number().int().nonnegative(),policyRevision:J.z.number().int().nonnegative(),generation:J.z.string().min(1).max(256),steps:J.z.array(jf).max(32),boundary:J.z.strictObject({nodeId:J.z.string().min(1).max(64),visit:J.z.number().int().nonnegative()}).optional()}),J.z.strictObject({operation:J.z.literal("segment_configuration"),funnelId:J.z.uuid(),versionId:J.z.uuid()}),J.z.strictObject({operation:J.z.literal("configuration"),funnelId:J.z.uuid(),versionId:J.z.uuid().optional()}),J.z.strictObject({operation:J.z.literal("local_configuration"),funnelId:J.z.uuid()}),J.z.strictObject({operation:J.z.literal("report_used"),decisionId:J.z.uuid(),eventId:J.z.uuid(),occurredAt:J.z.iso.datetime({offset:!0}),reference:J.z.string().min(1).max(128).optional()})]),h1=J.z.strictObject({scope:Fe,decisionId:J.z.uuid(),requestId:J.z.uuid(),status:J.z.enum(["pending","completed","failed"]),decision:A0.nullable(),evaluation:J.z.discriminatedUnion("type",[kf,Tf]).optional()}).refine(e=>e.status==="completed"==(e.decision!==null)&&(!e.decision||e.decision.decisionId===e.decisionId&&e.decision.requestId===e.requestId),"Completed decisions carry their committed result"),y1=J.z.strictObject({scope:Fe,decisionId:J.z.uuid(),eventId:J.z.uuid(),source:J.z.literal("caller_reported")});var Tt=require("zod");var Bf=Tt.z.strictObject({type:Tt.z.literal("bundle"),paywall:Mn.optional(),offering:Mn.optional(),coupons:Mn,data:Mn}),x0=e=>Tt.z.strictObject({type:Tt.z.literal(e),id:Tt.z.uuid()}),I1=Tt.z.strictObject({type:Tt.z.literal("bundle"),paywallVersionId:Tt.z.uuid().optional(),offeringVersionId:Tt.z.uuid().optional(),couponIds:Tt.z.array(Tt.z.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:ve});var v1=Tt.z.strictObject({type:Tt.z.literal("bundle"),offering:x0("offering_version").nullable(),paywall:Tt.z.strictObject({versionId:Tt.z.uuid(),paywallId:Tt.z.uuid(),offeringVersionId:Tt.z.uuid()}).nullable(),coupons:Tt.z.array(Qi).max(20),data:ve});var xn=require("zod");var fn=require("zod");var Vf=fn.z.union([fn.z.string(),fn.z.number().finite(),fn.z.boolean(),fn.z.null()]),S0=fn.z.union([Vf,fn.z.array(Vf).min(1).max(20)]),I0=fn.z.record(Rn,S0).refine(e=>Object.keys(e).length<=10),Lf=fn.z.strictObject({path:Rn,type:fn.z.enum(["string","number","boolean","strings"]),nullable:fn.z.boolean().optional(),aggregation:fn.z.enum(["count","exists"]).optional(),where:I0.optional()}).superRefine((e,t)=>{(e.aggregation==="count"&&e.type!=="number"||e.aggregation==="exists"&&e.type!=="boolean"||!e.aggregation&&e.where)&&t.addIssue({code:"custom",message:"Collection summaries require their matching type"})});var v0=["sendMessage","checkEntitlement","resolveOffering","readHoldings","readLedger","readBillingInvoice","readCreditStatement","previewAttach","attach","readSubscriptionOperation","previewUpdate","update","readSubscriptionUpdate","setupPayment","readPaymentSetup","verifySubscriptions","previewRefund","refund","readRefund","restoreNativePurchase","readBillingControls","prepareBillingAuthorization","confirmBillingAuthorization","setBillingCoupons","revokeBillingAuthorization","listBillingInvoices","confirmBillingAdjustment","manageBillingLimits","readSeats","manageSeat","quoteBalance","mutateBalance","trackUsage","readUsage","setUsage","adjustBalance","readBalanceSource","manageBalanceGrant","listBalanceGrants","manageUsageEntity","readUsageAnalytics","readCreditAnalytics","submitUsageBatch","readUsageBatch","redeemCoupon","listOffers","grantOffer","redeemReward","createReferralCode","claimRewardProduct"],zf=xn.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),w0=Mn,$f=xn.z.discriminatedUnion("type",[Cf,xn.z.strictObject({type:xn.z.literal("claim_offer"),coupon:Mn}),xn.z.strictObject({type:xn.z.literal("event"),event:zf}),xn.z.strictObject({type:xn.z.literal("api"),operation:xn.z.enum(v0),inputs:xn.z.record(Rn,w0).refine(e=>Object.keys(e).length<=40),outputs:xn.z.record(zf,Lf).refine(e=>Object.keys(e).length<=20)})]);var dt=Ka,O0=Q.z.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),gn={id:dt,name:Q.z.string().trim().min(1).max(80),position:Q.z.strictObject({x:Q.z.number().finite(),y:Q.z.number().finite()}).optional()},P0={success:dt,cancel:dt,unavailable:dt,failure:dt},du=Q.z.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),pu=Q.z.enum(["same_window","new_window"]),C0=Q.z.discriminatedUnion("type",[Q.z.strictObject({...gn,type:Q.z.literal("entry"),next:dt,triggers:Q.z.array(If).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),Q.z.strictObject({...gn,type:Q.z.literal("screen"),screenId:dt,presentation:Cn,outputs:Q.z.record(dt,dt),offering:Q.z.discriminatedUnion("source",[Q.z.strictObject({source:Q.z.literal("variable"),key:It}),Q.z.strictObject({source:Q.z.literal("fixed"),versionId:Q.z.uuid()})]).optional()}),Q.z.strictObject({...gn,type:Q.z.literal("offering"),configuration:Q.z.discriminatedUnion("source",[Q.z.strictObject({source:Q.z.literal("fixed"),versionId:Q.z.uuid()}),Q.z.strictObject({source:Q.z.literal("feature"),featureKey:Q.z.string().min(1).max(128)})]),writes:Q.z.strictObject({value:It}),next:dt}),Q.z.strictObject({...gn,type:Q.z.literal("coupon"),couponId:Q.z.uuid(),writes:Q.z.strictObject({value:It}),next:dt}),Q.z.strictObject({...gn,type:Q.z.literal("coupons"),couponIds:Q.z.array(Q.z.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:Q.z.strictObject({value:It}),next:dt}),Q.z.strictObject({...gn,type:Q.z.literal("output"),value:Q.z.discriminatedUnion("type",[...So.options,Bf,Q.z.strictObject({type:Q.z.literal("selection"),screenId:dt,offeringKey:It})])}),Q.z.strictObject({...gn,type:Q.z.literal("condition"),cases:Q.z.array(Q.z.strictObject({condition:Yt,target:dt})).min(1).max(50),default:dt}),Q.z.strictObject({...gn,type:Q.z.literal("feature"),featureKey:Q.z.string().min(1).max(128),writes:Q.z.strictObject({value:It}),next:dt}),Q.z.strictObject({...gn,type:Q.z.literal("split"),experimentId:Q.z.uuid(),applyPageExperiment:Q.z.literal(!0).optional(),routes:Q.z.record(O0,dt).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:dt}),Q.z.strictObject({...gn,type:Q.z.literal("action"),...P0,execution:_f,action:$f,writes:Cc.optional()}),Q.z.strictObject({...gn,type:Q.z.literal("external_page"),appManifest:za.optional(),url:du,openIn:pu,opened:dt,failed:dt}),Q.z.strictObject({...gn,type:Q.z.literal("end"),outcome:Q.z.enum(["completed","closed","ineligible","failed"]),output:So.optional()}),Q.z.strictObject({...gn,type:Q.z.literal("wait"),writes:Cc.optional(),wait:Q.z.discriminatedUnion("type",[Q.z.strictObject({type:Q.z.literal("duration"),delaySeconds:Q.z.number().int().min(1).max(2592e3),elapsed:dt}),Q.z.strictObject({type:Q.z.literal("event"),eventName:dt,outputs:au,timeoutSeconds:Q.z.number().int().min(1).max(2592e3),received:dt,timeout:dt})])})]),mu=Q.z.strictObject({version:Q.z.literal(5),entry:dt,nodes:Q.z.array(C0).min(1).max(kn.flowNodes)}),fu=mu.superRefine((e,t)=>{_0(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function es(e){switch(e.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":return[e.next];case"screen":return Object.values(e.outputs);case"condition":return[...e.cases.map(t=>t.target),e.default];case"split":return[...Object.values(e.routes),e.notParticipating];case"action":return[e.success,e.cancel,e.unavailable,e.failure];case"external_page":return[e.opened,e.failed];case"end":case"output":return[];case"wait":return e.wait.type==="duration"?[e.wait.elapsed]:[e.wait.received,e.wait.timeout]}}function _0(e,t){let n=[],r=new Map(e.nodes.map(l=>[l.id,l])),i=(l,m,f)=>{n.push(l),t?.({message:l,reason:m,path:f?["nodes",e.nodes.indexOf(f)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(l=>l.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(l=>l.type==="screen").length>kn.pages||e.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>kn.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let l of e.nodes){for(let m of es(l))m===e.entry&&i("An entry cannot be a transition target","entryTarget",l),r.has(m)||i(`Missing target ${m}`,"missingTarget",l);l.type==="screen"&&(a.has(l.screenId)&&i("Every screen has exactly one node owner","screenOwner",l),a.add(l.screenId))}let o=new Set,s=new Set,c=new Set;function u(l){if(o.has(l)){i("Flow edges must not form a cycle","cycle",r.get(l));return}if(!(s.has(l)||!r.has(l))){o.add(l),c.add(l);for(let m of es(r.get(l)))u(m);o.delete(l),s.add(l)}}u(e.entry);for(let l of e.nodes)c.has(l.id)||i("Every node must be reachable from Entry","unreachable",l);return[...new Set(n)]}var gu={maxTransitions:1e4,runTimeoutSeconds:2592e3};function Gf(e,t,n){let r=[...t].sort((s,c)=>c.length-s.length),i=new Set,a=(s,c=!1)=>{let u=r.find(l=>s===l||c&&s.startsWith(l+"."));i.add(u??s)};if(e.type==="condition"){let s=n?.startsWith("case_")?Number(n.slice(5)):e.cases.length-1;for(let c of e.cases.slice(0,s+1))for(let u of rr(c.condition))u.startsWith("variables.")&&a(u.slice(10),!0)}if(e.type==="screen"&&e.offering?.source==="variable"&&a(e.offering.key),e.type==="action"&&(e.action.type==="api"||e.action.type==="external_task"))for(let s of Object.values(e.action.inputs))s.source==="variable"&&a(s.key);e.type==="action"&&e.action.type==="claim_offer"&&e.action.coupon.source==="variable"&&a(e.action.coupon.key);let o=e.type==="output"?e.value:e.type==="end"?e.output:null;if(o?.type==="variable"&&a(o.key),o?.type==="bundle")for(let s of[o.paywall,o.offering,o.coupons,o.data])s?.source==="variable"&&a(s.key);return o?.type==="selection"&&a(o.offeringKey),[...i]}var q=require("zod");var Ei=q.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),ts=e=>q.z.record(q.z.string(),ve).refine(t=>pn(t)<=e,"Funnel evidence exceeds its byte budget"),Z1=q.z.enum(["local_segment","evaluation","presentation","timer","event","operation"]),yu=q.z.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Au=q.z.discriminatedUnion("type",[q.z.strictObject({type:q.z.literal("flag"),key:q.z.string().min(1).max(128)}),q.z.strictObject({type:q.z.literal("experiment"),id:q.z.uuid()}),q.z.strictObject({type:q.z.literal("saved_group"),id:q.z.uuid()}),q.z.strictObject({type:q.z.literal("config"),key:q.z.string().min(1).max(128)}),q.z.strictObject({type:q.z.literal("constant"),key:q.z.string().min(1).max(128)}),q.z.strictObject({type:q.z.literal("paywall_version"),id:q.z.uuid()}),q.z.strictObject({type:q.z.literal("offering_version"),id:q.z.uuid()}),q.z.strictObject({type:q.z.literal("reward"),id:q.z.uuid()})]),Io=q.z.strictObject({schemaVersion:q.z.literal(1),kind:yu,selector:Au.nullable(),context:ts(131072),contract:q.z.strictObject({version:q.z.number().int().positive(),evaluator:q.z.string().min(1).max(128),policyRevision:q.z.number().int().nonnegative()})}).refine(e=>pn(e)<=131072,"Node input exceeds its byte budget"),Kf=q.z.strictObject({schemaVersion:q.z.literal(1),kind:yu,outcome:q.z.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:ts(131072),route:q.z.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:ts(131072)}).refine(e=>pn(e)<=131072,"Node result exceeds its byte budget"),W1=q.z.strictObject({schemaVersion:q.z.literal(1),operations:q.z.record(Ei,q.z.strictObject({attempts:q.z.number().int().nonnegative(),maxAttempts:q.z.number().int().min(1).max(5),deadlineAt:q.z.iso.datetime({offset:!0}),retryAt:q.z.iso.datetime({offset:!0}).nullable(),error:q.z.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:q.z.strictObject({type:Ei,id:q.z.uuid()}).nullable()}))}).refine(e=>pn(e)<=65536,"Execution state exceeds its byte budget"),Qr={receiptId:q.z.uuid()},hu=q.z.iso.datetime({offset:!0}),Y1=q.z.discriminatedUnion("type",[q.z.strictObject({type:q.z.literal("node_entered"),details:q.z.strictObject({kind:yu})}),q.z.strictObject({type:q.z.literal("presentation_shown"),details:q.z.strictObject({...Qr,source:q.z.literal("client"),occurredAt:hu.optional()})}),q.z.strictObject({type:q.z.literal("decision_accepted"),details:q.z.strictObject(Qr)}),q.z.strictObject({type:q.z.literal("signal_received"),details:q.z.strictObject({signalId:q.z.uuid(),nodeId:Ei,eventName:Ei,data:ts(8192),source:q.z.literal("server"),occurredAt:hu})}),q.z.strictObject({type:q.z.literal("signal_consumed"),details:q.z.strictObject({...Qr,signalId:q.z.uuid()})}),q.z.strictObject({type:q.z.literal("wait_elapsed"),details:q.z.strictObject(Qr)}),q.z.strictObject({type:q.z.literal("wait_timeout"),details:q.z.strictObject(Qr)}),q.z.strictObject({type:q.z.literal("operation_completed"),details:q.z.strictObject({...Qr,operation:Ei,reference:q.z.strictObject({type:Ei,id:q.z.uuid()}).nullable()})}),q.z.strictObject({type:q.z.literal("execution_recovered"),details:q.z.strictObject({generation:q.z.number().int().positive(),reason:q.z.enum(["interrupted","expired_lease","delivery_failed"])})}),q.z.strictObject({type:q.z.literal("execution_failed"),details:q.z.strictObject({generation:q.z.number().int().positive(),code:q.z.string().regex(/^[a-z_]{1,64}$/)})}),q.z.strictObject({type:q.z.literal("run_completed"),details:q.z.strictObject({outcome:q.z.enum(["completed","ineligible","failed"])})}),q.z.strictObject({type:q.z.literal("run_closed"),details:q.z.strictObject({source:q.z.enum(["client","server","expiry"])})}),q.z.strictObject({type:q.z.literal("treatment_used"),details:q.z.strictObject({...Qr,source:q.z.enum(["client","server"]),occurredAt:hu,reference:q.z.string().min(1).max(128).optional()})})]);var Sn=L.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),E0=L.z.discriminatedUnion("type",[L.z.strictObject({id:Sn,type:L.z.literal("owned"),publicData:sf.optional(),document:dn.refine(e=>["page","popup","onboarding"].includes(e.surface)&&e.pages.length===1&&e.actions.every(t=>t.type==="event"&&!t.close),"A Funnel owns one Page or Popup per screen and emits outputs; Paywall owns its purchase policies")}),L.z.strictObject({id:Sn,type:L.z.literal("paywall"),paywallVersionId:L.z.uuid()})]),bu={executionContract:ff.optional(),kind:L.z.literal("funnel"),schemaVersion:L.z.literal(4),screens:L.z.array(E0).max(kn.pages),references:L.z.record(Sn,Au).refine(e=>Object.keys(e).length<=500),inputs:L.z.array(L.z.strictObject({variable:Sn,screenId:Sn,componentId:Sn,required:L.z.boolean()})).max(kn.questions),variables:L.z.record(It,hi).refine(e=>Object.keys(e).length<=kn.logicNodes),outputSchema:gi,execution:L.z.strictObject({runTimeoutSeconds:L.z.number().int().min(1).max(gu.runTimeoutSeconds),maxTransitions:L.z.number().int().min(1).max(gu.maxTransitions)})},yE=L.z.strictObject({...bu,graph:mu});function R0(e,t){let n=!1,r=(i,a)=>{let o=i.type==="stack"||i.type==="button"?i.bind?.coupon??a:a;i.type==="text"&&Object.values(e.strings.locales).some(s=>s[i.text]?.includes("{{offer."))&&!(o&&t(o))&&(n=!0),i.type==="stack"&&i.children.forEach(s=>r(s,o))};for(let i of e.pages)r(i.root);return n}function rs(e){return Array.isArray(e)?e.some(rs):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===Ef:rs(n))}function k0(e){let t=[],n=new Set(Object.values(e.references).flatMap(r=>r.type==="reward"?[r.id]:[]));for(let[r,i]of e.screens.entries()){if(i.type!=="owned")continue;let a;try{a=yf(i.document)}catch(o){t.push({message:o instanceof Error?o.message:"Screen cannot be delivered",reason:"screen",path:["screens",r,"document"]});continue}for(let[o,s]of e.inputs.entries())s.screenId===i.id&&!lo(a,s.componentId)&&t.push({message:`Local Funnel input ${s.variable} targets hidden component ${s.componentId} on screen ${s.screenId}`,reason:"inputBinding",path:["inputs",o]})}for(let[r,i]of e.graph.nodes.entries()){let a=["graph","nodes",r],o=i.type==="screen"?e.screens.find(s=>s.id===i.screenId):void 0;o?.type==="owned"&&(o.document.actions.some(s=>typeof s.properties.templateKey=="string"&&s.properties.templateKey.startsWith("popup-coupon-"))&&t.push({message:"Funnel screens claim Coupons through a Claim Coupon step",reason:"coupon",path:a}),R0(o.document,s=>n.has(s))&&t.push({message:"Offer copy shows the Coupon of a Claim Coupon step",reason:"coupon",path:a})),(i.type==="output"&&i.value.type==="literal"&&rs(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&rs(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function Hf(e,t){for(let{message:n,reason:r,path:i}of k0(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function Qf(e,t){let n=(g,d,h=[])=>t.addIssue({code:"custom",message:g,path:h,params:{reason:d}}),r=Object.values(e.references),i=new Map(e.screens.map(g=>[g.id,g])),a=(g,d)=>r.some(h=>h.type===g&&("id"in h?h.id:h.key)===d);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let o=e.graph.nodes.filter(g=>g.type==="screen");(o.length!==i.size||o.some(g=>!i.has(g.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(g=>c.some(d=>g!==d&&d.startsWith(g+".")))&&n("Variable paths must not overlap","variable");function u(g,d){Object.hasOwn(e.variables,g)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(d)]);let h=s.get(g)??new Set;h.add(d.id),s.set(g,h)}for(let[g,d]of e.graph.nodes.entries()){let h=["graph","nodes",g],R=d.type==="feature"?d.featureKey:d.type==="offering"&&d.configuration.source==="feature"?d.configuration.featureKey:d.type==="output"&&d.value.type==="feature"?d.value.featureKey:d.type==="end"&&d.output?.type==="feature"?d.output.featureKey:null;R&&!a("flag",R)&&n("Flag selectors require an explicit GB resource reference","feature",h);let y=d.type==="feature"||d.type==="offering"||d.type==="coupon"||d.type==="coupons"||d.type==="action"&&d.action.type==="api"?["value"]:d.type==="action"&&d.action.type==="external_task"?Object.keys(d.action.outputs):d.type==="wait"&&d.wait.type==="event"?Object.keys(d.wait.outputs):[],A="writes"in d?d.writes??{}:{};(y.length!==Object.keys(A).length||y.some(v=>!Object.hasOwn(A,v))||new Set(Object.values(A)).size!==Object.values(A).length)&&n("Node writes must map every named output exactly once","variable",h);for(let[v,P]of Object.entries(A)){u(P,d);let j=e.variables[P],_=d.type==="offering"?"offering_version":d.type==="coupon"?"reward":d.type==="action"&&d.action.type==="api"?"json":d.type==="action"&&d.action.type==="external_task"?d.action.outputs[v]:d.type==="wait"&&d.wait.type==="event"?d.wait.outputs[v]:void 0;(j?.source.type!=="node"||_&&j.type!==_)&&n("Node writer source or output type does not match declaration","variable",h)}if(d.type==="coupons"){let v=e.variables[d.writes.value];(v?.type!=="array"||v.items?.type!=="reward"||v.items.nullable||v.nullable)&&n("Coupons output requires a non-null Reward array","variable",h);for(let P of d.couponIds)a("reward",P)||n("Coupons require Reward references","coupon",h)}if(d.type==="split"&&!a("experiment",d.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",h),d.type==="coupon"&&!a("reward",d.couponId)&&n("Coupon selectors require a Reward reference","coupon",h),d.type==="action"&&d.action.type==="claim_offer"&&d.action.coupon.source==="literal"){let v=d.action.coupon.value;(!v||typeof v!="object"||Array.isArray(v)||v.type!=="reward"||typeof v.id!="string"||Object.keys(v).length!==2||!a("reward",v.id))&&n("Coupon claims require a Reward reference","coupon",h)}if(d.type==="offering"&&d.configuration.source==="fixed"&&!a("offering_version",d.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",h),d.type==="screen"&&d.offering?.source==="variable"&&e.variables[d.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",h),d.type==="action"&&d.action.type==="claim_offer"&&d.action.coupon.source==="variable"&&(e.variables[d.action.coupon.key]?.type!=="reward"||d.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",h),d.type==="screen"){let v=i.get(d.screenId);if(d.offering?.source==="fixed"&&!a("offering_version",d.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",h),v?.type==="paywall"&&d.offering&&n("Paywall owns its fixed Offering Version","offering",h),v?.type==="paywall"&&!a("paywall_version",v.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",h),v?.type==="owned"){let P=v.document.pages[0];if(!P){n("Owned screen requires a page","screen",h);continue}ar(v.document).some(_=>!_.complete)&&n("Owned screens require complete local content","translations",h);let j=new Set(v.document.actions.map(_=>_.id));(j.size!==Object.keys(d.outputs).length||Object.keys(d.outputs).some(_=>!j.has(_)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",h),Wn(P.root,_=>{!d.offering&&(_.type==="plan_picker"||(_.type==="stack"||_.type==="button")&&_.bind?.plan||_.type==="customer_data"&&["customer_plans","credit_packs"].includes(_.data.source))&&n("Product presentation requires an Offering Version","offering",h),_.type==="customer_data"&&Object.values(_.data.outputs??{}).some(X=>X!==void 0&&!j.has(X))&&n("Customer components require declared screen outcomes","componentOutput",h)})}}d.type==="end"&&["completed","ineligible"].includes(d.outcome)&&!d.output&&n("Completed and ineligible ends require a declared output","output",h),d.type==="end"&&d.output?.type==="literal"&&!An(e.outputSchema,d.output.value)&&n("Terminal output does not match outputSchema","output",h),d.type==="output"&&d.value.type==="literal"&&!An(e.outputSchema,d.value.value)&&n("Terminal output does not match outputSchema","output",h);let x=d.type==="output"?d.value:d.type==="end"?d.output:void 0;if(x?.type==="variable"&&!x.path){let v=e.variables[x.key];v&&!_c(v,e.outputSchema)&&n("Variable output does not match outputSchema","output",h)}if(d.type==="screen"){let v=i.get(d.screenId);if(v?.type==="owned")for(let P of kc(v.document))(/^(input|params)\./.test(P)||P.startsWith("variables.")&&!Rc(P.slice(10),c))&&n("Screen values must reference registered variables","variable",h)}if(d.type==="condition")for(let v of d.cases){for(let P of Qn(v.condition))a("saved_group",P)||n("Conditions require explicit Saved Group references","savedGroup",h);for(let P of rr(v.condition))P.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",h)}if(d.type==="output"&&d.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",h);for(let[v,P]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let j=d.value[v];if(j)if(j.source==="literal"){let _=v==="coupons"?j.value:[j.value];(!Array.isArray(_)||_.length>20||_.some(X=>!An({type:P,nullable:!1},X)||!a(P,X.id))||v==="coupons"&&new Set(_.map(X=>X.id)).size!==_.length)&&n("Bundle requires distinct scoped resource references",v==="coupons"?"coupon":v==="paywall"?"paywall":"offering",[...h,"value",v])}else{let _=e.variables[j.key];(j.path||!_||_.nullable||(v==="coupons"?_.type!=="array"||_.items?.type!=="reward"||_.items.nullable:_.type!==P))&&n("Bundle binding type does not match its slot","output",h)}}}}for(let[g,d]of e.graph.nodes.entries()){let h=d.type==="screen"?i.get(d.screenId):void 0,R=[...Gf(d,c),...h?.type==="owned"?_a(h.document).map(y=>Rc(y,c)?.key??y):[]];for(let y of new Set(R)){let P=function(j){if(j===d.id)return!0;if(v.has(j))return!1;v.add(j);let _=e.graph.nodes.find(le=>le.id===j);return _?(x.has(j)?_.type==="action"?[_.cancel,_.unavailable,_.failure]:_.type==="wait"&&_.wait.type==="event"?[_.wait.timeout]:[]:es(_)).some(P):!1};var f=P;if(!Object.hasOwn(e.variables,y)){n("Consumed variable is undeclared","variable",["graph","nodes",g]);continue}let A=e.variables[y];if(d.type==="screen"&&A.source.type==="input"&&e.inputs.some(j=>j.screenId===d.screenId&&j.variable===y)||A.source.type==="parameter"||A.source.type==="attribute")continue;let x=A.source.type==="input"?new Set(e.inputs.filter(j=>j.variable===y&&j.required).flatMap(j=>o.filter(_=>_.screenId===j.screenId).map(_=>_.id))):s.get(y)??new Set,v=new Set;(!x.size||P(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",g])}}(new Set(e.inputs.map(g=>g.variable)).size!==e.inputs.length||new Set(e.inputs.map(g=>`${g.screenId}:${g.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[g,d]of e.inputs.entries()){e.variables[d.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",g]);let h=i.get(d.screenId),R=h?.type==="owned"?lo(h.document,d.componentId):null;if((R?.type!=="stack"||!R.interaction||!["input","toggle","select","multiselect","tabs"].includes(R.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",g]),R?.type==="stack"&&R.interaction){let y=R.interaction.type==="toggle"?"boolean":R.interaction.type==="multiselect"?"strings":"string";e.variables[d.variable]?.type!==y&&n("Input variable type does not match component","inputBinding",["inputs",g]);let A=e.variables[d.variable]?.enum;A&&!R.children.filter(x=>!x.hidden).every(x=>A.includes(x.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",g])}}for(let[g,d]of Object.entries(e.variables))d.enum&&d.type!=="string"&&n("Only string variables support enum","variable",["variables",g]),d.source.type==="input"&&!e.inputs.some(h=>h.variable===g)&&n("Input variable requires a component binding","inputBinding",["variables",g]);let l=0,m=0;for(let g of e.screens)if(g.type==="owned"){for(let d of g.document.pages)Wn(d.root,()=>{l++});m+=g.document.actions.length}(l>kn.components||m>kn.actions||pn(e)>kn.documentBytes)&&n("Funnel document exceeds its budget","budget")}var j0=L.z.strictObject({...bu,graph:fu}).superRefine(Qf),Ri=L.z.strictObject({...bu,graph:fu,displayName:L.z.string().trim().min(1).max(80)}).superRefine(Qf),AE=Ri.superRefine(Hf),bE=j0.superRefine(Hf),ns=L.z.string().regex(Nt),vo={requestId:L.z.uuid(),nodeId:Sn,visit:L.z.number().int().nonnegative(),revision:L.z.number().int().nonnegative(),customerToken:ns.optional()},T0=L.z.discriminatedUnion("type",[L.z.strictObject({type:L.z.literal("screen"),output:Sn,answers:lr,selection:L.z.record(Sn,L.z.union([L.z.string().max(200),L.z.boolean(),L.z.number().int().min(0).max(1e4)])).optional()}),L.z.strictObject({type:L.z.literal("paywall_quote"),featureQuantities:L.z.record(L.z.uuid(),L.z.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100).optional(),actionId:Sn,productVersionId:L.z.uuid(),offerId:L.z.uuid().optional(),nativeOffer:bi.optional(),predecessor:L.z.strictObject({operationId:L.z.uuid().nullable(),generation:L.z.number().int().positive()}).optional()}),L.z.strictObject({type:L.z.literal("paywall_confirm"),operationId:L.z.uuid()}),L.z.strictObject({type:L.z.literal("paywall_cancel"),operationId:L.z.uuid()}),L.z.strictObject({type:L.z.literal("client_action"),receiptId:L.z.uuid(),outcome:L.z.enum(["success","cancel","failure","opened","failed"])})]),N0=L.z.object({nodeId:Sn,visit:L.z.number().int().nonnegative(),revision:L.z.number().int().nonnegative(),components:L.z.record(Sn,L.z.object({resourceKey:L.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:L.z.number().int().min(1).max(1e5),after:$a.nullable(),filter:L.z.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),_t=L.z.discriminatedUnion("operation",[L.z.strictObject({operation:L.z.literal("start"),funnelId:L.z.uuid(),requestId:L.z.uuid(),customer:Hr.optional(),customerData:Ci.optional(),locale:L.z.string().min(1).max(35),parameters:dr}).refine(Ya,Xa),L.z.strictObject({operation:L.z.literal("get"),settlementRequestId:L.z.uuid().optional(),data:N0.optional(),purchase:L.z.strictObject({receiptId:L.z.uuid(),operationId:L.z.uuid()}).optional(),customerToken:ns.optional()}),L.z.strictObject({operation:L.z.literal("resume"),requestId:L.z.uuid(),customerToken:ns.optional()}),L.z.strictObject({operation:L.z.literal("submit"),...vo,input:T0}),L.z.strictObject({operation:L.z.literal("back"),...vo}),L.z.strictObject({operation:L.z.literal("shown"),...vo}),L.z.strictObject({operation:L.z.literal("close"),...vo}),L.z.strictObject({operation:L.z.literal("commit_segment"),...vo,policyRevision:L.z.number().int().nonnegative(),generation:L.z.string().min(1).max(256)}),L.z.strictObject({operation:L.z.literal("review"),receiptId:L.z.uuid().optional(),customerToken:ns.optional()})]);function is(e,t){let n=new Set,r=new Set,i=new Set,a=[],o=new Map,s=new Map,c=new Map;function u(d){for(let h of Qn(d))l(h)}function l(d){if(i.has(d)||!Object.hasOwn(t.savedGroups,d))return;let h=t.savedGroups[d];h&&(i.add(d),c.set(d,h),a.push(()=>{!Array.isArray(h)&&h.type==="condition"&&u(h.condition)}))}function m(d){for(let h of["hashAttribute","fallbackAttribute"])if(d[h]!==void 0&&nu(d[h]))throw new Error(`Funnel GB ${h} uses a reserved flow namespace`);u(d.condition);for(let h of d.parentConditions??[])f(h.id),u(h.condition)}function f(d,h=!1){let R=Object.hasOwn(t.features,d)?t.features[d]:void 0;if(!R){if(h)throw new Error("Required GB Feature is unavailable");return}n.has(d)||(n.add(d),o.set(d,R),a.push(()=>{for(let y of R.rules??[]){m(y);for(let A of y.tracks??[])m(A.experiment)}}))}function g(d){let h=Object.hasOwn(t.experiments,d)?t.experiments[d]:void 0;if(!h)throw new Error("Required GB Experiment is unavailable");r.has(d)||(r.add(d),s.set(d,h),a.push(()=>m(h)))}for(let d of e.graph.nodes){d.type==="feature"&&f(d.featureKey,!0),d.type==="split"&&g(d.experimentId),d.type==="condition"&&d.cases.forEach(R=>u(R.condition)),d.type==="offering"&&d.configuration.source==="feature"&&f(d.configuration.featureKey,!0);let h=d.type==="output"?d.value:d.type==="end"?d.output:null;h?.type==="feature"&&f(h.featureKey,!0)}for(let d of a)d();return{...t,features:Object.fromEntries(o),experiments:Object.fromEntries(s),savedGroups:Object.fromEntries(c)}}var ae=require("zod");function Jf(e,t){let n=[],r={};Ht(e,i=>{if(i.hidden)return!1;if(i.type!=="quantity_picker")return;let a=i.bind?.plan?[i.bind.plan]:[];i.bind?.picker&&Ht(e,o=>{if(o.type==="plan_picker"&&o.id===i.bind?.picker&&a.push(...o.planIds??[]),o.type==="stack"&&o.interaction?.type==="select"&&o.interaction.pickerId===i.bind?.picker)for(let s of o.children)s.type==="stack"&&s.bind?.plan&&a.push(s.bind.plan)}),a.length||n.push(`Quantity control ${i.id} needs a Product binding`);for(let o of new Set(a)){let s=t[o]?.prepaid?.find(u=>u.internalFeatureId===i.internalFeatureId)?.terms,c=r[o]??(r[o]=new Set);(!s||c.has(i.internalFeatureId)||i.minimumQuantity<s.minimumQuantity||i.maximumQuantity>s.maximumQuantity)&&n.push(`Quantity control ${i.id} must match its Product's prepaid Feature and bounds`),c.add(i.internalFeatureId)}});for(let[i,a]of Object.entries(t))for(let o of a.prepaid??[])r[i]?.has(o.internalFeatureId)||n.push(`Product ${i} needs a quantity control for ${o.internalFeatureId}`);return n}function Zf(e,t,n,r){let i=r.plans[t];if(!i?.available)throw new Error("Selected Product is unavailable");let a={};if(Ht(e,o=>{if(o.hidden)return!1;if(o.type!=="quantity_picker"||o.hidden||(o.bind?.plan??(o.bind?.picker?n[o.bind.picker]:void 0))!==t)return;let c=i.prepaid?.find(l=>l.internalFeatureId===o.internalFeatureId)?.terms,u=n[o.id];if(!c||typeof u!="number"||!Number.isSafeInteger(u)||u<Math.max(c.minimumQuantity,o.minimumQuantity)||u>Math.min(c.maximumQuantity,o.maximumQuantity)||(u-o.minimumQuantity)%o.step!==0||a[o.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");a[o.internalFeatureId]=u}),(i.prepaid??[]).some(o=>a[o.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return a}var ki=require("zod");var Wf=ki.z.object({defaultLocale:wn,locales:ki.z.record(wn,ki.z.object({name:ki.z.string().max(80),description:ki.z.string().max(500)}).strict())}).strict().superRefine((e,t)=>{let n=Object.keys(e.locales);(!n.length||n.length>20||!e.locales[e.defaultLocale])&&t.addIssue({code:"custom",message:"Invalid content languages"}),new TextEncoder().encode(JSON.stringify(e)).length>5e4&&t.addIssue({code:"custom",message:"Content exceeds 50 KB"})});var D0=["customer_data","coupon_code"],Yf=ae.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),F0=ae.z.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),os=(e,t)=>new Set(e.map(t)).size===e.length,M0=ae.z.strictObject({currency:Ie,amountMinor:ae.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),q0=ae.z.strictObject({featureId:ae.z.uuid(),name:ae.z.string().trim().min(1).max(120),allowance:ae.z.string().max(40).nullable(),access:ae.z.boolean()}),U0=ae.z.strictObject({stripe:ae.z.strictObject({prices:ae.z.array(M0).min(1).max(50)}).optional(),apple:ae.z.strictObject({productIds:ae.z.array(Yf).min(1).max(10)}).optional(),google:ae.z.strictObject({products:ae.z.array(ae.z.strictObject({productId:Yf,basePlanId:F0.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!os(e.stripe.prices,n=>n.currency)||e.apple&&!os(e.apple.productIds,n=>n)||e.google&&!os(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),B0=ae.z.strictObject({name:ae.z.string().trim().min(1).max(80),interval:ae.z.enum(["free","week","month","year","one_time"]),intervalCount:ae.z.number().int().min(1).max(100),trial:ae.z.strictObject({days:ae.z.number().int().min(1).max(730),cardRequired:ae.z.boolean()}).nullable(),benefits:ae.z.array(q0).max(50).refine(e=>os(e,t=>t.featureId),"Duplicate benefit"),channels:U0,prepaid:ae.z.array(ao).max(100).optional()}),V0=ae.z.strictObject({digest:Oi,content:ae.z.strictObject({discount:ir,duration:un,appliesTo:lc,displayCopy:Wf.nullable(),firstPurchaseOnly:ae.z.boolean(),qualificationRequired:ae.z.boolean(),startsAt:ae.z.iso.datetime().nullable(),endsAt:ae.z.iso.datetime().nullable(),grantWindowHours:ae.z.number().int().positive(),perCustomerLimit:ae.z.number().int().positive()})}),L0=ae.z.discriminatedUnion("type",[ae.z.strictObject({type:ae.z.literal("checkout"),product:Oa}),ae.z.strictObject({type:ae.z.literal("close")}),ae.z.strictObject({type:ae.z.literal("action"),action:Gc})]),as=ae.z.strictObject({kind:ae.z.literal("paywall"),formatVersion:ae.z.literal(1),name:ae.z.string().trim().min(1).max(80),offeringVersionId:ae.z.uuid(),presentation:Cn,screen:dn,products:Ba,catalog:ae.z.record(ae.z.uuid(),B0),buttons:ae.z.record(Ue,L0),coupons:ae.z.record(ae.z.uuid(),V0)}).superRefine((e,t)=>{let n=h=>t.addIssue({code:"custom",message:h}),{screen:r}=e;Jf(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),Zc(r,D0).forEach(n),ar(r).some(h=>!h.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,o=new Set;Ht(r,h=>{let R="bind"in h?h.bind:void 0;R?.promotionCode&&n("Promotion codes must not be published"),R?.plan&&i.add(R.plan),R?.coupon&&a.add(R.coupon),h.type==="plan_picker"&&(h.planIds?.forEach(y=>i.add(y)),h.defaultPlan&&i.add(h.defaultPlan)),h.type==="text"&&h.feature&&o.add(h.feature.id)});let s=e.products.items.map(h=>h.productVersionId),c=Object.keys(e.catalog);(s.length!==c.length||s.some(h=>!Object.hasOwn(e.catalog,h)))&&n("Catalog must contain exactly the displayed Products");let u=new Set(s);e.products.defaultProductVersionId!==null&&!u.has(e.products.defaultProductVersionId)&&n("Default Product must be displayed");for(let h of i)u.has(h)||n("Screen references a Product that is not displayed");for(let h of Object.values(e.catalog))!h.channels.stripe&&!h.channels.apple&&!h.channels.google&&n("A displayed Product needs at least one sales channel");let l=new Set(Object.values(e.catalog).flatMap(h=>h.benefits.map(R=>R.featureId)));for(let h of o)l.has(h)||n("Feature text must read a displayed benefit");let m=r.actions.filter(h=>h.type!=="navigate");r.actions.some(h=>h.type!=="event"&&h.type!=="navigate")&&n("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==m.length||m.some(h=>!Object.hasOwn(e.buttons,h.id)))&&n("Buttons must match the screen's actions");let g=!1;for(let h of Object.values(e.buttons)){if(h.type!=="checkout")continue;g=!0,(h.product.type==="fixed"?[h.product.productVersionId]:h.product.allowedProductVersionIds).some(y=>!u.has(y))&&n("Checkout may only sell displayed Products")}g||n("A Paywall needs a checkout button");let d=Object.keys(e.coupons);(d.length!==a.size||d.some(h=>!a.has(h)))&&n("Coupons must be exactly the bound Coupons")}),Xf=ae.z.strictObject({state:ae.z.enum(["published","archived"]),controlRevision:ae.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:ae.z.uuid(),versions:ae.z.record(ae.z.uuid(),ae.z.strictObject({version:ae.z.number().int().positive(),artifact:ae.z.string().min(1),sourceDigest:ae.z.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var nn={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},xu=Re.z.string().regex(/^[a-f0-9]{64}$/),Su=Re.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),vu=Fe.extend({environmentId:Re.z.uuid()}),eg=Re.z.strictObject({features:Re.z.array(Re.z.string()).max(500),experiments:Re.z.record(Re.z.uuid(),Re.z.array(Re.z.string()).max(20)),savedGroups:Re.z.array(Re.z.string()).max(1e3)}),wu=Re.z.strictObject({kind:Re.z.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:Re.z.number().int().positive(),url:Re.z.string().min(1).max(2048),sha256:xu,byteLength:Re.z.number().int().positive().max(nn.maxArtifactBytes),generation:xu.optional()}),z0=Re.z.strictObject({state:Re.z.enum(["active","paused","archived"]),controlRevision:Su,evaluationMode:Re.z.enum(["local","remote"]),evaluationRevision:Su,currentVersionId:Re.z.uuid(),versions:Re.z.record(Re.z.uuid(),Re.z.strictObject({artifact:Re.z.string(),dependencies:eg,definitionDigest:Oi.optional(),couponDigests:Re.z.record(Re.z.uuid(),Oi).optional()}))}),Ou=Re.z.strictObject({kind:Re.z.literal("sdk_configuration"),schemaVersion:Re.z.literal(1),scope:vu,revision:Su,generation:xu,policy:Re.z.strictObject({refreshIntervalSeconds:Re.z.number().positive().max(15),maxControlAgeSeconds:Re.z.number().positive().max(60)}),gb:Re.z.strictObject({features:Re.z.string().nullable(),pageExperiments:Re.z.string().nullable()}),artifacts:Re.z.record(Re.z.string(),wu),funnels:Re.z.record(Re.z.uuid(),z0),paywalls:Re.z.record(Re.z.uuid(),Xf).optional()}).superRefine((e,t)=>{let n=(r,i)=>{r!==null&&e.artifacts[r]?.kind!==i&&t.addIssue({code:"custom",message:"Missing or wrong-kind configuration artifact"})};n(e.gb.features,"gb_features"),n(e.gb.pageExperiments,"gb_page_experiments");for(let r of Object.values(e.paywalls??{}))for(let i of Object.values(r.versions))n(i.artifact,"paywall");for(let r of Object.values(e.funnels)){r.evaluationMode==="remote"&&Object.keys(r.versions).length&&t.addIssue({code:"custom",message:"Remote Funnel graphs cannot be public"}),r.evaluationMode==="local"&&!r.versions[r.currentVersionId]&&t.addIssue({code:"custom",message:"Current Funnel Version is not retained"});for(let i of Object.values(r.versions))n(i.artifact,"funnel")}});function Et(e){if(Array.isArray(e))return`[${e.map(Et).join(",")}]`;if(e!==null&&typeof e=="object")return`{${Object.entries(e).sort(([n],[r])=>n<r?-1:n>r?1:0).map(([n,r])=>`${JSON.stringify(n)}:${Et(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function Pu(e){return ai(si(typeof e=="string"?new TextEncoder().encode(e):e))}function tg(e){return Pu(Et(e))}var Iu=class extends Error{constructor(n,r){super(n);qe(this,"dependency",r)}};function ng(e,t){let n=l=>l.type==="feature"?l.featureKey:l.type==="end"&&l.output?.type==="feature"?l.output.featureKey:l.type==="output"&&l.value.type==="feature"?l.value.featureKey:void 0,r=(l,m)=>e.graph.nodes.find(f=>l==="experiment"?f.type==="split"&&f.experimentId===m:l==="feature"&&n(f)===m)?.name,i=(l,m,f=r(m.type,m.resource))=>new Iu(l,{...m,...f?{step:f}:{}});for(let l of Object.values(e.references)){let m=l.type==="flag"?!Object.hasOwn(t.features,l.key)||t.remoteFeatures.includes(l.key)?{type:"feature",resource:l.key}:null:l.type==="experiment"?Object.hasOwn(t.experiments,l.id)?null:{type:"experiment",resource:l.id}:l.type==="saved_group"&&!Object.hasOwn(t.savedGroups,l.id)?{type:"saved_group",resource:l.id}:null;if(m)throw i("Funnel dependency is absent from GB public delivery",{reason:"unavailable",...m})}let a=is(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),o=new Set(t.remoteFeatures);for(let l of e.graph.nodes){let m=n(l);if(!m)continue;let f=a.features[m],g=l.type==="feature"?e.variables[l.writes.value]:e.outputSchema,d={type:"feature",resource:m};if(!f||!g)throw i("Required public Feature declaration is unavailable",{reason:"unavailable",...d},l.name);if([f.defaultValue,...(f.rules??[]).flatMap(R=>[...Object.hasOwn(R,"force")?[R.force]:[],...R.variations??[],...(R.tracks??[]).flatMap(y=>y.experiment.variations)])].some(R=>R===void 0||!An(g,R)))throw i("GB Feature values violate the Funnel type contract",{reason:"value_type",...d},l.name)}let s=new Set,c=(l,m)=>{for(let f of Qn(l)){if(s.has(f))continue;let g=t.savedGroups[f];if(!g)throw i("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:f},m);s.add(f),!Array.isArray(g)&&g.type==="condition"&&c(g.condition,m)}},u=(l,m)=>{if(o.has(l)||!t.features[l])throw i("Local Funnel requires public Local prerequisites",{reason:"unavailable",type:"feature",resource:l},m)};for(let l of e.graph.nodes)if(l.type==="condition")for(let m of l.cases)c(m.condition,l.name);for(let[l,m]of Object.entries(a.features)){let f=r("feature",l);for(let g of m.rules??[]){c(g.condition,f);for(let d of[...g.parentConditions??[],...(g.tracks??[]).flatMap(h=>h.experiment.parentConditions??[])])u(d.id,f),c(d.condition,f);for(let d of g.tracks??[])c(d.experiment.condition,f)}}for(let[l,m]of Object.entries(a.experiments)){let f=r("experiment",l);c(m.condition,f);for(let g of m.parentConditions??[])u(g.id,f),c(g.condition,f)}for(let l of e.graph.nodes)if(l.type==="split"){let m=a.experiments[l.experimentId],f={type:"experiment",resource:l.experimentId};if(!m)throw i("Local Funnel requires a public Experiment",{reason:"unavailable",...f},l.name);for(let g of m.variations)if(typeof g!="string"||!Object.hasOwn(l.routes,g))throw i("Experiment variation has no declared Funnel route",{reason:"variation_route",...f},l.name)}return eg.parse({features:Object.keys(a.features).sort(),experiments:Object.fromEntries(Object.entries(a.experiments).map(([l,m])=>[l,m.variations.map(String)])),savedGroups:[...s].sort()})}function rg(e){return Ri.parse(e)}var ig=vt.z.strictObject({processContext:Ra.optional(),...Ai,selector:vt.z.discriminatedUnion("type",[vt.z.strictObject({type:vt.z.literal("paywall"),paywallId:vt.z.uuid()}),vt.z.strictObject({type:vt.z.literal("version"),versionId:vt.z.uuid()})]),customerId:vt.z.uuid().optional(),commerce:pi,locale:vt.z.string().min(1).max(35),requirement:or.optional()}),wo=vt.z.strictObject({id:vt.z.uuid(),paywallId:vt.z.uuid(),version:vt.z.number().int().positive(),document:wi.omit({requirement:!0,offeringId:!0}),offering:vt.z.strictObject({id:vt.z.uuid()}),content:vt.z.strictObject({environmentId:vt.z.uuid(),offeringVersionId:vt.z.uuid(),artifact:wu.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:mi,check:qr.nullable()}).superRefine((e,t)=>{let n=new Set(e.document.products.items.map(r=>r.productVersionId));(e.document.offeringVersionId!==e.offering.id||Object.values(e.capabilities.plans).some(r=>!n.has(r.versionId)))&&t.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})}),Jr=vt.z.strictObject(wo.shape).omit({document:!0,offering:!0}).extend({content:wo.shape.content.unwrap()});function og(e,t){let n=as.parse(t);if(n.offeringVersionId!==e.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");let r=structuredClone(e.capabilities);for(let[i,a]of Object.entries(n.catalog)){let o=r.plans[i],s=a.channels.stripe?.prices.find(c=>c.currency===o?.currency);o&&s&&Object.assign(o,{amountMinor:s.amountMinor,interval:a.interval,intervalCount:a.intervalCount,...a.prepaid?.length?{prepaid:a.prepaid}:{}})}return wo.parse({...e,capabilities:r,document:{schemaVersion:3,kind:n.kind,name:n.name,presentation:n.presentation,products:n.products,offeringVersionId:n.offeringVersionId,screen:n.screen,buttons:n.buttons},offering:{id:n.offeringVersionId}})}var zt=require("zod");var ag={requestId:zt.z.uuid(),sourceId:zt.z.uuid(),expectedAvailable:Kt},sg=zt.z.discriminatedUnion("action",[zt.z.strictObject({...ag,action:zt.z.enum(["add","subtract","set_remaining"]),amount:xe}),zt.z.strictObject({...ag,action:zt.z.literal("edit"),granted:xe,expiresAt:zt.z.iso.datetime({offset:!0}).nullable(),nextResetAt:zt.z.iso.datetime({offset:!0}).nullable(),expectedRevision:zt.z.number().int().nonnegative()})]),Cu=zt.z.strictObject({sourceId:zt.z.uuid(),available:Kt,held:Kt,spent:Kt,adjustmentGrantId:zt.z.uuid().nullable()}),cg=Cu.extend({granted:Kt,expiresAt:zt.z.iso.datetime({offset:!0}).nullable(),nextResetAt:zt.z.iso.datetime({offset:!0}).nullable(),revision:zt.z.number().int().nonnegative()});var rn=require("zod"),ug=rn.z.discriminatedUnion("action",[rn.z.object({action:rn.z.literal("upsert"),externalId:rn.z.string().min(1).max(128),name:rn.z.string().trim().min(1).max(80)}).strict(),rn.z.object({action:rn.z.literal("archive"),entityId:rn.z.uuid()}).strict()]),lg=rn.z.object({id:rn.z.uuid(),externalId:rn.z.string().min(1).max(128),name:rn.z.string().min(1).max(80),archived:rn.z.boolean()}).strict();var Ut=require("zod");var pr=require("zod"),pg=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],dg=pr.z.string().regex(/.+\/.+/),_u=pr.z.number().min(-100),Zr=pr.z.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),$0=pr.z.strictObject({input:Zr,output:Zr,cache_read:Zr.optional(),cache_write:Zr.optional(),reasoning:Zr.optional(),input_audio:Zr.optional(),output_audio:Zr.optional()}),Eu=(e,t)=>pr.z.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),dR=pr.z.strictObject({defaultMarkup:_u,providerMarkups:Eu(pr.z.string().min(1),_u),modelMarkups:Eu(dg,_u),customModels:Eu(dg,$0.partial())});var be=require("zod"),Wr=be.z.iso.datetime({offset:!0}),mr=be.z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),G0=be.z.discriminatedUnion("kind",[be.z.object({kind:be.z.literal("absolute"),from:Wr,to:Wr}).strict(),be.z.object({kind:be.z.literal("last_days"),days:be.z.union([be.z.literal(1),be.z.literal(7),be.z.literal(30),be.z.literal(90)])}).strict(),be.z.object({kind:be.z.literal("billing_cycles"),membershipId:be.z.uuid(),count:be.z.number().int().min(1).max(12),includeCurrent:be.z.boolean()}).strict()]),mg=be.z.string().max(100).refine(e=>{if(e!=="UTC"&&!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+\-]+)+$/.test(e))return!1;try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Use an IANA timezone"),K0=be.z.object({key:be.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:be.z.array(be.z.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),Yr=be.z.object({range:G0,timezone:mg,filterBy:be.z.array(K0).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:be.z.enum(["hour","day","week","month"]),internal_feature_id:be.z.uuid().nullable(),entityId:be.z.uuid().nullable(),topN:be.z.number().int().min(1).max(50).nullable(),groupBy:be.z.union([be.z.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),be.z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:be.z.object({bucket:Wr,group:be.z.string().max(240),isOther:be.z.boolean(),internal_feature_id:be.z.uuid(),resourceId:be.z.uuid()}).strict().nullable(),limit:be.z.number().int().min(1).max(100)}).strict().superRefine((e,t)=>{if(e.range.kind!=="absolute"){e.interval==="hour"&&e.range.kind==="last_days"&&e.range.days>31&&t.addIssue({code:"custom",message:"Hourly reports are bounded to 31 days"});return}let n=Date.parse(e.range.to)-Date.parse(e.range.from);(n<=0||n>366*864e5||e.interval==="hour"&&n>31*864e5)&&t.addIssue({code:"custom",message:"Reporting range must be positive and bounded (31 days hourly, 366 days otherwise)"})}),fg=be.z.object({from:Wr,to:Wr,interval:be.z.enum(["hour","day","week","month"]),timezone:mg,rows:be.z.array(be.z.object({bucket:Wr,group:be.z.string().max(240),isOther:be.z.boolean(),internal_feature_id:be.z.uuid(),resourceId:be.z.uuid(),consumedUnits:mr,refundedUnits:mr,reservedUnits:mr,charged:mr,refunded:mr,reserved:mr,netUnits:mr,netCharged:mr}).strict()).max(100),nextCursor:be.z.object({bucket:Wr,group:be.z.string().max(240),isOther:be.z.boolean(),internal_feature_id:be.z.uuid(),resourceId:be.z.uuid()}).strict().nullable()}).strict();var ji=Ut.z.string().regex(/^(0|[1-9]\d{0,29})$/),gg=Ut.z.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),Ru=Ut.z.strictObject({bucket:Ut.z.iso.datetime({offset:!0}),group:Ut.z.string().max(240),isOther:Ut.z.boolean(),internal_feature_id:Ut.z.uuid()}),hg=Ut.z.strictObject({...Yr.shape,groupBy:Ut.z.union([Ut.z.enum(["customer","entity","entitlement"]),Ut.z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Ru.nullable()}).superRefine((e,t)=>{let n=Yr.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),yg=Ut.z.strictObject({from:Ut.z.iso.datetime({offset:!0}),to:Ut.z.iso.datetime({offset:!0}),interval:Yr.shape.interval,timezone:Yr.shape.timezone,rows:Ut.z.array(Ut.z.strictObject({...Ru.shape,eventCount:ji,units:gg,tokenEventCount:ji,tokens:Ut.z.strictObject(Object.fromEntries(pg.map(e=>[e,ji]))),totalTokens:ji,providerCostEventCount:ji,providerCostUsd:gg,invalidTelemetryEventCount:ji})).max(100),nextCursor:Ru.nullable()});var gt=require("zod");var Ag=gt.z.object({requestId:gt.z.uuid(),items:gt.z.array(gt.z.object({customerId:gt.z.uuid(),command:eo.options[1]}).strict()).min(1).max(1e3)}).strict().refine(e=>new Set(e.items.map(t=>t.customerId+":"+t.command.idempotencyKey)).size===e.items.length,"Each logical event must appear once in a batch"),bg=gt.z.object({batchId:gt.z.uuid(),after:gt.z.number().int().min(-1).max(999),limit:gt.z.number().int().min(1).max(100)}).strict(),xg=gt.z.object({batchId:gt.z.uuid(),status:gt.z.enum(["queued","complete"]),total:gt.z.number().int().min(1).max(1e3),processed:gt.z.number().int().min(0).max(1e3),items:gt.z.array(gt.z.object({position:gt.z.number().int().min(0).max(999),customerId:gt.z.uuid(),idempotencyKey:gt.z.string().min(1).max(120),status:gt.z.enum(["queued","accepted","rejected","failed"]),receipt:to.nullable(),errorCode:gt.z.enum(["invalid_request","forbidden","conflict","internal_error"]).nullable()}).strict().refine(e=>e.status==="queued"?e.receipt===null&&e.errorCode===null:e.status==="failed"?e.receipt===null&&e.errorCode!==null:e.receipt!==null&&e.errorCode===null&&e.receipt.accepted===(e.status==="accepted"))).max(100),nextAfter:gt.z.number().int().min(0).max(999).nullable()}).strict();var k=require("zod");var H0=k.z.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),Sg=k.z.enum(["draft","active","paused","archived"]),Ig=k.z.string().min(1).max(256),vg=k.z.array(Ig).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),Q0=k.z.strictObject({duration:k.z.enum(["day","week","month","year"]),length:k.z.number().int().min(1).max(3660)}),J0=k.z.strictObject({internal_feature_id:k.z.uuid(),allowance:k.z.number().nonnegative().max(1e15).nullable(),expiry:Q0.nullable()}),Z0=k.z.discriminatedUnion("type",[k.z.strictObject({type:k.z.literal("feature_grant"),grants:k.z.array(J0).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),k.z.strictObject({type:k.z.literal("free_product"),productId:Ig,duration:un}),k.z.strictObject({type:k.z.literal("invoice_credits"),amount:k.z.number().positive().max(1e8),duration:un,rollover:k.z.boolean(),productIds:vg})]),W0=k.z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),wg=k.z.object({key:W0,name:k.z.string().trim().min(1).max(80),configuration:Z0}).strict(),Og=k.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),ku=k.z.object({code:Og,maxUses:k.z.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:k.z.boolean()}).strict(),Pg=k.z.object({key:k.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:k.z.string().trim().min(1).max(80),rewardId:k.z.uuid(),redeemOn:k.z.enum(["customer_creation","checkout"]),receivedBy:k.z.enum(["referrer","all"]),maxRedemptions:k.z.number().int().min(1).max(1e6).nullable(),productIds:vg,excludeTrial:k.z.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),Cg={id:k.z.uuid(),projectId:k.z.uuid(),environmentId:k.z.uuid(),revision:k.z.number().int().nonnegative(),status:Sg,createdAt:k.z.iso.datetime({offset:!0}),updatedAt:k.z.iso.datetime({offset:!0})},Y0=wg.extend(Cg).strict(),X0=Pg.safeExtend(Cg).strict(),SR=k.z.strictObject({id:k.z.uuid(),key:k.z.string(),name:k.z.string(),type:H0,status:Sg}),IR=k.z.discriminatedUnion("action",[k.z.object({action:k.z.literal("save"),id:k.z.uuid().nullable(),revision:k.z.number().int().nonnegative(),input:wg}).strict(),k.z.object({action:k.z.enum(["activate","pause","resume","archive","delete"]),id:k.z.uuid(),revision:k.z.number().int().nonnegative()}).strict()]),vR=k.z.discriminatedUnion("action",[k.z.object({action:k.z.literal("save"),id:k.z.uuid().nullable(),revision:k.z.number().int().nonnegative(),input:Pg}).strict(),k.z.object({action:k.z.enum(["activate","pause","resume","archive","delete"]),id:k.z.uuid(),revision:k.z.number().int().nonnegative()}).strict()]),_g=k.z.object({id:k.z.uuid(),rewardId:k.z.uuid(),programId:k.z.uuid().nullable(),customerId:k.z.uuid(),referrerId:k.z.uuid().nullable(),status:k.z.enum(["pending","applied","unavailable"]),result:k.z.record(k.z.string(),k.z.unknown()).nullable(),createdAt:k.z.iso.datetime({offset:!0})}).strict(),Eg=k.z.object({code:Og,requestId:k.z.uuid()}).strict(),Rg=k.z.strictObject({redemptionId:k.z.uuid(),currency:Ie,requestId:k.z.uuid(),accepted:k.z.literal(!0)}),eI=k.z.strictObject({type:k.z.literal("checkout"),orderId:k.z.uuid(),productVersionId:k.z.uuid(),currency:Ie,duration:un,renewalAmountMinor:k.z.number().int().positive().max(1e8),status:k.z.enum(["created","pending","trialing","paid","cancelled","failed"]),url:k.z.url().nullable()}),kg=k.z.discriminatedUnion("type",[eI,k.z.strictObject({type:k.z.literal("subscription"),operationId:k.z.uuid(),membershipId:k.z.uuid(),productVersionId:k.z.uuid(),currency:Ie,duration:un,renewalAmountMinor:k.z.number().int().positive().max(1e8),status:k.z.enum(["pending","running","applied","failed"])})]),jg=k.z.object({programId:k.z.uuid(),requestId:k.z.uuid()}).strict(),Tg=k.z.object({id:k.z.uuid(),programId:k.z.uuid(),code:ku.shape.code,createdAt:k.z.iso.datetime({offset:!0})}).strict(),wR=k.z.object({rows:k.z.array(Y0).max(100),nextCursor:k.z.uuid().nullable()}).strict(),OR=k.z.object({rows:k.z.array(X0).max(100),nextCursor:k.z.uuid().nullable()}).strict(),tI=ku.extend({id:k.z.uuid(),redemptions:k.z.number().int().nonnegative()}).strict(),nI=k.z.strictObject({id:k.z.uuid(),programId:k.z.uuid().nullable(),customerId:k.z.uuid().nullable(),referrerId:k.z.uuid().nullable(),code:k.z.string().nullable(),status:k.z.enum(["pending","triggered","applied"]),createdAt:k.z.iso.datetime({offset:!0})}),PR=k.z.object({codes:k.z.array(tI).max(100),redemptions:k.z.array(nI).max(100),customers:k.z.record(k.z.uuid(),k.z.string()),codesCursor:k.z.uuid().nullable(),redemptionsCursor:k.z.uuid().nullable()}).strict(),CR=k.z.discriminatedUnion("action",[k.z.object({action:k.z.literal("create"),rewardId:k.z.uuid(),revision:k.z.number().int().nonnegative(),input:ku}).strict(),k.z.object({action:k.z.literal("remove"),rewardId:k.z.uuid(),revision:k.z.number().int().nonnegative(),codeId:k.z.uuid()}).strict()]);var w=require("zod");var Z=require("zod"),qn={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},Oo=e=>new Set(e).size===e.length,ju=Z.z.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),rI=Z.z.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),Po=Z.z.string().min(1).max(200).regex(/^[a-zA-Z0-9_./-]+$/).refine(e=>!e.includes("..")&&!e.endsWith(".")&&!e.split("/").some(t=>!t||t.startsWith(".")||t.endsWith(".lock"))),iI=Z.z.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),Ng=Z.z.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var Dg=Z.z.strictObject({id:Z.z.uuid(),repo:rI,platform:Z.z.enum(["github","gitlab","bitbucket"]),branches:Z.z.array(Po).min(1).max(4).refine(Oo),workflow:Z.z.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:Z.z.array(Z.z.uuid()).min(1).max(4).refine(Oo),include:Z.z.array(Ng).min(1).max(16),exclude:Z.z.array(Ng).max(16),methods:Z.z.array(Z.z.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(Oo),maxAgeHours:Z.z.number().int().min(1).max(720)}),Fg=Dg.extend({revision:Z.z.number().int().positive()}),ER=Z.z.strictObject({repository:Dg,expectedRevision:Z.z.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),Mg=Z.z.strictObject({repositoryId:Z.z.uuid(),branch:Po}),oI=Z.z.array(ju).max(qn.keys).refine(Oo),qg=Z.z.strictObject({repository:Fg.omit({keyIds:!0}),branch:Po,keys:oI,keySetHash:Z.z.string().regex(/^[a-f0-9]{64}$/)}),aI=Z.z.strictObject({filePath:iI,startingLineNumber:Z.z.number().int().min(1).max(1e7)}),Tu=Z.z.strictObject({protocol:Z.z.literal(1),repositoryId:Z.z.uuid(),branch:Po,workflow:Z.z.string().max(200),configurationRevision:Z.z.number().int().positive(),keySetHash:Z.z.string().regex(/^[a-f0-9]{64}$/),commit:Z.z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:Z.z.uuid(),runNumber:Z.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:Z.z.number().int().min(1).max(1e4),scannerVersion:Z.z.literal("1"),scannedAt:Z.z.iso.datetime({offset:!0}),coverage:Z.z.strictObject({complete:Z.z.literal(!0),files:Z.z.number().int().min(0).max(qn.files),sourceBytes:Z.z.number().int().min(0).max(qn.sourceBytes),unresolvedCalls:Z.z.number().int().min(0).max(1e6),unsupportedFiles:Z.z.number().int().min(0).max(qn.files)}),features:Z.z.array(Z.z.strictObject({key:ju,refs:Z.z.array(aI).max(qn.referencesPerKey)})).max(qn.keys)}).superRefine((e,t)=>{Oo(e.features.map(n=>n.key))||t.addIssue({code:"custom",path:["features"],message:"Duplicate feature"}),e.features.reduce((n,r)=>n+r.refs.length,0)>qn.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),Nu=Z.z.strictObject({scanId:Z.z.uuid(),commit:Z.z.string(),receivedAt:Z.z.string(),references:Z.z.number().int().nonnegative(),removedReferences:Z.z.number().int().nonnegative()}),sI=Nu.extend({repositoryId:Z.z.uuid(),branch:Po,workflow:Z.z.string(),digest:Z.z.string(),configurationRevision:Z.z.number().int().positive(),runNumber:Z.z.number().int().positive(),runAttempt:Z.z.number().int().positive(),scannedAt:Z.z.string(),keySetHash:Z.z.string(),coverage:Tu.shape.coverage}),cI=Z.z.strictObject({repositories:Z.z.array(Fg).max(qn.repositories),scans:Z.z.array(sI).max(qn.repositories*qn.branches)}),uI=Z.z.strictObject({key:ju,references:Z.z.number().int().nonnegative(),coveredTargets:Z.z.number().int().nonnegative(),expiredTargets:Z.z.number().int().nonnegative(),uncertainTargets:Z.z.number().int().nonnegative()}),RR=Z.z.strictObject({available:Z.z.boolean().default(!0),settings:cI,expectedTargets:Z.z.number().int().min(0).max(80),features:Z.z.array(uI).max(2001),truncated:Z.z.boolean()});var Ee=require("zod");var on=Ee.z.string().min(1).max(200),ss=Ee.z.iso.datetime({offset:!0}),Co=Ee.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),Du=Ee.z.number().int().min(0).max(1e12),Vg=Ee.z.number().int().min(1).max(1e12),Ug={...Zt,type:Ee.z.literal("coupon.redeemed"),grantId:Ee.z.uuid()},Bg={...Zt,type:Ee.z.literal("usage.observed"),merchantTransactionId:on,resource:on,unit:on,quantity:Vg},lI=Ee.z.strictObject({...Zt,type:Ee.z.literal("fulfillment.updated"),operationId:Ee.z.uuid(),merchantFulfillmentId:on,status:Ee.z.enum(["pending","applied","failed"])}),dI=Ee.z.strictObject({...Zt,type:Ee.z.literal("benefit.claimed"),merchantBenefitId:on,resource:on,unit:on,quantity:Vg,expiresAt:ss.nullable(),revision:Co}),pI=Ee.z.strictObject({...Zt,type:Ee.z.literal("benefit.closed"),merchantBenefitId:on,status:Ee.z.enum(["failed","expired","canceled"]),revision:Co}),mI=Ee.z.strictObject({...Zt,type:Ee.z.literal("benefit.updated"),merchantBenefitId:on,status:Ee.z.enum(["active","expired","revoked"]),remainingQuantity:Du.nullable(),expiresAt:ss.nullable(),revision:Co}),fI=Ee.z.strictObject({...Zt,type:Ee.z.literal("authorization.updated"),merchantAuthorizationId:on,kind:Ee.z.literal("auto_topup"),status:Ee.z.enum(["pending","effective","revoked","failed"]),termsReference:on.nullable(),revision:Co}),gI=Ee.z.strictObject({...Zt,type:Ee.z.literal("balance.observed"),resource:on,unit:on,availableQuantity:Du,reservedQuantity:Du,periodStartsAt:ss.nullable(),periodEndsAt:ss.nullable(),revision:Co}),Lg=Ee.z.union([Ee.z.discriminatedUnion("type",[...Bl,lI,dI,pI,mI,fI,gI]),Ee.z.strictObject({...Ug,productVersionId:Ee.z.uuid(),subscriptionId:Ee.z.string().trim().min(1).max(255)}),Ee.z.strictObject({...Ug,merchandiseId:Ee.z.uuid()}),Ee.z.strictObject({...Bg,operation:Ee.z.literal("consume")}),Ee.z.strictObject({...Bg,operation:Ee.z.literal("reverse"),reversalOf:on})]),zg=Ee.z.strictObject({id:Ee.z.uuid(),eventId:Ee.z.string().min(1).max(200),source:Ee.z.literal("merchant"),providerVerified:Ee.z.literal(!1),outcome:Ee.z.string().min(1).max(100)});var oe=require("zod");var $g=Am,hI=$g.extend({invoice_id:$g.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),Fu=oe.z.strictObject({name:oe.z.string().trim().min(1).max(255),memo:oe.z.string().max(1e4).nullable().optional(),footer:oe.z.string().max(1e4).nullable().optional(),net_terms_days:oe.z.number().int().positive().nullable().optional()}),yI=Fu.extend({id:oe.z.string().min(1).max(255),created_at:oe.z.number().nullable()}),Gg=oe.z.strictObject({items:oe.z.array(yI).max(50),nextCursor:oe.z.uuid().nullable()}),DR=oe.z.discriminatedUnion("action",[oe.z.strictObject({action:oe.z.literal("create"),requestId:oe.z.uuid(),values:Fu}),oe.z.strictObject({action:oe.z.literal("update"),id:oe.z.string().min(1).max(255),values:Fu}),oe.z.strictObject({action:oe.z.literal("delete"),id:oe.z.string().min(1).max(255)})]),Kg=oe.z.discriminatedUnion("action",[oe.z.strictObject({action:oe.z.literal("create"),requestId:oe.z.uuid(),params:xi}),oe.z.strictObject({action:oe.z.enum(["finalize","send","pay","void"]),requestId:oe.z.uuid(),invoiceId:oe.z.uuid()}),oe.z.strictObject({action:oe.z.literal("reissue"),requestId:oe.z.uuid(),invoiceId:oe.z.uuid(),params:hI})]),Mu=oe.z.strictObject({id:oe.z.uuid(),customerId:oe.z.uuid(),providerInvoiceId:oe.z.string().nullable(),status:oe.z.enum(["draft","open","paid","void","uncollectible"]),currency:oe.z.string(),totalMinor:oe.z.string().regex(/^-?\d+$/),paidMinor:oe.z.string().regex(/^\d+$/),refundedMinor:oe.z.string().regex(/^\d+$/),hostedInvoiceUrl:oe.z.url().nullable(),createdAt:oe.z.number(),collectionMethod:oe.z.enum(["send_invoice","charge_automatically"]).nullable()}),Hg=Mu.extend({lines:oe.z.array(oe.z.strictObject({id:oe.z.uuid(),description:oe.z.string(),amountMinor:oe.z.string().regex(/^-?\d+$/),netAmountMinor:oe.z.string().regex(/^-?\d+$/),quantity:oe.z.number().nullable(),periodStart:oe.z.number().nullable(),periodEnd:oe.z.number().nullable()})).max(1e3)}),Ti=oe.z.strictObject({taskId:oe.z.uuid(),status:oe.z.enum(["ready","running","done","dead"]),invoice:Mu.nullable(),errorCode:oe.z.string().nullable()}),Qg=oe.z.strictObject({items:oe.z.array(Mu).max(50),nextCursor:oe.z.uuid().nullable(),operations:oe.z.array(Ti).max(50),operationsLimited:oe.z.boolean()});var AI=w.z.enum(["customers:read","customers:write","entitlements:read","content:read","sessions:create","funnels:run","offers:resolve","offers:grant","billing:read","billing:write","credits:read","credits:consume","credits:manage","features:read","events:write","messaging:write","code-references:read","code-references:write","app-manifests:write"]),Jg={scope:Fe,permissions:w.z.array(AI),expiresAt:w.z.iso.datetime().nullable()},Ok=w.z.discriminatedUnion("kind",[w.z.object({...Jg,kind:w.z.literal("server"),keyId:w.z.string().min(1)}),w.z.object({...Jg,kind:w.z.literal("customer"),customerId:w.z.string().min(1),identityKind:w.z.enum(["identified","guest"]),expiresAt:w.z.iso.datetime()})]),z=w.z.object({requestId:w.z.uuid(),scope:Fe}).strict(),bI=Df.safeExtend({fingerprint:Wa.optional()}).strict(),xI=z.extend({customer:_i,created:w.z.boolean()});function Zg(){return z.extend({offer:Qi.nullable(),reason:Kd.nullable()})}var O={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:Fp,response:z.extend({message:w.z.object({messageId:w.z.uuid(),channel:oo,acceptedAt:w.z.iso.datetime({offset:!0}),status:w.z.enum(["accepted","sending","completed","canceled"]),replayed:w.z.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:w.z.strictObject({messageId:w.z.uuid()}),response:z.extend({message:w.z.object({id:w.z.uuid(),channel:oo,status:w.z.enum(["accepted","sending","completed","canceled"]),deliveries:w.z.array(w.z.object({id:w.z.uuid(),status:qp,attempts:w.z.number().int().nonnegative(),receipts:w.z.array(w.z.object({kind:Up,occurredAt:w.z.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:vl,response:z.extend({installation:Pr})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:wl,response:z.extend({installation:Pr})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:zo,response:z.extend({installation:Pr})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:w.z.strictObject({channel:oo}),response:z.extend({preference:Rs})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:Mp,response:z.extend({preference:Rs})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:w.z.strictObject({cursor:w.z.uuid().optional()}),response:z.extend({templates:Gg})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),params:xi}),response:z.extend({preview:Dc})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),requestId:w.z.uuid(),params:xi}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:z.extend({operation:Ti})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),command:Kg}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:z.extend({operation:Ti})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),taskId:w.z.uuid()}),response:z.extend({operation:Ti})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),cursor:w.z.uuid().optional()}),response:z.extend({invoices:Qg})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),invoiceId:w.z.uuid()}),response:z.extend({invoice:Hg})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:Mg,response:z.extend({config:qg})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:Tu,response:z.extend({receipt:Nu})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:w.z.strictObject({}),response:z.extend({payload:bo})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:lf,response:z.merge(Va)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:df,response:z.merge(pf)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),sourceId:w.z.uuid()}),response:z.extend({balance:cg})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),command:sg}),response:z.extend({balance:Cu})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:w.z.strictObject({internal_feature_id:w.z.uuid(),customerId:w.z.uuid().optional(),entityId:w.z.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:z.extend({internal_feature_id:w.z.uuid(),config:Gs,model_markups:ea})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),query:ba}),response:z.extend({usage:no})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),command:Cp}),response:z.extend({usage:no})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),command:Sp}),response:z.extend({grant:fc})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:Ip,response:z.extend({grants:vp})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:w.z.union(Wm.options.map(e=>e.extend({customerId:w.z.uuid().optional(),customerToken:w.z.string().regex(Nt).optional()}))),response:z.extend({operation:Ym})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:Bm.extend({customerId:w.z.uuid().optional()}),response:z.extend({setup:Bc})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Vm.extend({customerId:w.z.uuid().optional()}),response:z.extend({setup:Bc})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:Mm.safeExtend({customerId:w.z.uuid()}),response:z.extend({batch:fo})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:Da.extend({customerId:w.z.uuid()}),response:z.extend({batch:fo})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:Da.extend({customerId:w.z.uuid()}),response:z.extend({batch:fo})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:Da.extend({customerId:w.z.uuid()}),response:z.extend({batch:fo})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:w.z.discriminatedUnion("action",[Fa.options[0].extend({customerId:w.z.uuid()}),Fa.options[1].extend({customerId:w.z.uuid()}),Fa.options[2].extend({customerId:w.z.uuid()})]),response:z.extend({trial:Uc})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:qm.extend({customerId:w.z.uuid()}),response:z.extend({trial:Uc})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:Ua,response:z.extend({subscriptions:Qm})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:Ua,response:z.extend({purchases:Jm})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:Gm,response:z.extend({conflicts:Zm})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:Km,response:z.extend({resolution:Hm})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:zm,response:z.extend({verification:$m})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:Em.safeExtend({...Ai,customerId:w.z.uuid().optional()}),response:z.extend({quote:Si})},recordMerchantEvent:{method:"POST",path:"merchant/events/record",permission:"billing:write",audience:"server",request:Lg,response:z.extend({record:zg})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:$r.extend({customerId:w.z.uuid().optional(),intent:w.z.enum(["confirm","cancel"]).optional()}),response:z.extend({operation:Ii})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:$r.extend({customerId:w.z.uuid().optional()}),response:z.extend({operation:Ii})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:jm.safeExtend({customerId:w.z.uuid().optional()}),response:z.extend({quote:Nm})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:$r.extend({customerId:w.z.uuid().optional(),intent:w.z.enum(["confirm","cancel"]).optional()}),response:z.extend({operation:Fc})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:$r.extend({customerId:w.z.uuid().optional()}),response:z.extend({operation:Fc})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:Dm.safeExtend({customerId:w.z.uuid()}),response:z.extend({quote:Mc})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:$r.extend({customerId:w.z.uuid()}),response:z.extend({operation:Na})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:$r.extend({customerId:w.z.uuid()}),response:z.extend({operation:Na})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:ap,response:z.extend({controls:pc})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:Xd,response:z.extend({prepared:tp})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:np,response:z.extend({authorization:ga})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:dp,response:z.extend({coupons:pp})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:rp,response:z.extend({authorization:ga})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:up,response:z.extend({invoices:lp})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:cp.extend({customerId:w.z.uuid()}),response:z.extend({operation:Ti})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:sp,response:z.extend({invoice:Wi})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:w.z.object({customerId:w.z.uuid(),command:op}).strict(),response:z.extend({controls:pc})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:w.z.object({customerId:w.z.uuid(),command:ug}).strict(),response:z.extend({entity:lg})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:w.z.strictObject({customerId:w.z.uuid().nullable(),query:hg}),response:z.extend({analytics:yg})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:w.z.object({customerId:w.z.uuid().nullable(),query:Yr}).strict(),response:z.extend({analytics:fg})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:Ag,response:z.extend({batchId:w.z.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:bg,response:z.extend({batch:xg})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:zp.extend({customerId:w.z.string().min(1).optional()}),response:z.extend({check:qr})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:w.z.strictObject({kind:cr,selector:w.z.discriminatedUnion("type",[w.z.strictObject({type:w.z.literal("resource"),id:w.z.uuid()}),w.z.strictObject({type:w.z.literal("version"),id:w.z.uuid()})]),customerId:w.z.string().min(1).optional()}),response:z.extend({content:jc})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:ig,response:z.extend({paywall:Jr})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:w.z.strictObject({processContext:Ra.optional(),...Ai,selector:nf,customerId:w.z.string().min(1).optional(),commerce:pi,requirement:or.optional()}),response:z.extend({offering:rf,candidates:w.z.array(bc).max(20),availability:w.z.array(w.z.strictObject({productVersionId:w.z.uuid(),available:w.z.boolean(),reason:w.z.enum(["platform_binding_missing","commercial_runtime_pending","commerce_not_configured","currency_mismatch","product_unavailable","already_attached","attach_in_progress","already_scheduled","subscription_change_required","purchase_conflict"]).nullable()})).max(20),check:qr.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:w.z.object({customerId:w.z.uuid().optional(),entityId:w.z.uuid().optional()}).strict(),response:z.extend({holdings:_p})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:w.z.object({customerId:w.z.uuid().optional(),query:Rp}).strict(),response:z.extend({ledger:kp})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:wp.extend({customerId:w.z.uuid().optional()}),response:z.extend({detail:Op})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:gc.safeExtend({customerId:w.z.uuid().optional()}),response:z.extend({statement:Pp})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:w.z.object({customerId:w.z.uuid().optional(),command:eo.options[0]}).strict(),response:z.extend({quote:Ap})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),command:w.z.union([w.z.strictObject({eventName:w.z.string().min(1),quantity:xe.optional(),properties:Pt.optional(),entityId:w.z.uuid().optional(),idempotencyKey:w.z.string().min(1).max(120)}),w.z.strictObject({internal_feature_id:w.z.uuid(),quantity:xe.optional(),properties:Pt.optional(),entityId:w.z.uuid().optional(),idempotencyKey:w.z.string().min(1).max(120)})])}),response:z.extend({receipts:w.z.array(to).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:w.z.object({customerId:w.z.uuid(),command:eo.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:z.extend({receipt:to})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:Eg,response:z.extend({redemption:_g})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:jg,response:z.extend({referralCode:Tg})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:Rg,response:z.extend({checkout:kg})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:Tp,response:z.extend({seats:Ac})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Np,response:z.extend({seats:Ac})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:bI,response:xI},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:lu,response:z.extend({customer:_i})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:qf,response:z.extend(Uf.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:Mf,response:z.extend(Ff.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:w.z.object({customerId:w.z.uuid()}).strict(),response:z.extend(Xn.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:w.z.strictObject({}),response:z.extend(Xn.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),sessionId:w.z.uuid().optional()}),response:z.extend({revoked:w.z.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:w.z.strictObject({guestToken:w.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:Wa.optional()}),response:z.extend({customerId:w.z.uuid(),guestToken:w.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:w.z.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:w.z.strictObject({guestToken:w.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:z.extend(Xn.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:w.z.strictObject({guestToken:w.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:w.z.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:w.z.uuid()}),response:z.extend({customer:_i,switched:w.z.boolean(),replayed:w.z.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:w.z.strictObject({code:w.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:w.z.uuid()}),response:Zg()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:w.z.object({}).strict(),response:z.extend({offers:w.z.array(Qi)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:w.z.object({customerId:w.z.string().min(1).max(255).optional(),couponId:w.z.uuid(),...Ai,requestId:w.z.uuid(),couponContentDigest:w.z.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:Zg()}},Pk={recordMerchantEvent:O.recordMerchantEvent,sendMessage:O.sendMessage,readMessage:O.readMessage,bindPushInstallation:O.bindPushInstallation,readPushInstallation:O.readPushInstallation,updatePushAddress:O.updatePushAddress,readMessagingPreference:O.readMessagingPreference,setMessagingPreference:O.setMessagingPreference,listInvoiceTemplates:O.listInvoiceTemplates,previewInvoice:O.previewInvoice,createInvoice:O.createInvoice,manageInvoice:O.manageInvoice,readInvoiceOperation:O.readInvoiceOperation,listInvoices:O.listInvoices,getInvoice:O.getInvoice,getCodeReferenceConfig:O.getCodeReferenceConfig,submitCodeReferences:O.submitCodeReferences,getFeatures:O.getFeatures,evaluateFeatures:O.evaluateFeatures,trackEvents:O.trackEvents,setupPayment:O.setupPayment,readPaymentSetup:O.readPaymentSetup,previewSubscriptionBatch:O.previewSubscriptionBatch,confirmSubscriptionBatch:O.confirmSubscriptionBatch,readSubscriptionBatch:O.readSubscriptionBatch,abandonSubscriptionBatch:O.abandonSubscriptionBatch,manageSubscriptionTrial:O.manageSubscriptionTrial,readSubscriptionTrial:O.readSubscriptionTrial,listSubscriptions:O.listSubscriptions,listPurchases:O.listPurchases,listSubscriptionConflicts:O.listSubscriptionConflicts,retrySubscriptionConflict:O.retrySubscriptionConflict,readAiPricing:O.readAiPricing,readUsage:O.readUsage,setUsage:O.setUsage,previewRefund:O.previewRefund,refund:O.refund,readRefund:O.readRefund,previewUpdate:O.previewUpdate,update:O.update,readSubscriptionUpdate:O.readSubscriptionUpdate,restoreNativePurchase:O.restoreNativePurchase,verifySubscriptions:O.verifySubscriptions,previewAttach:O.previewAttach,attach:O.attach,readSubscriptionOperation:O.readSubscriptionOperation,manageBalanceGrant:O.manageBalanceGrant,readBalanceSource:O.readBalanceSource,adjustBalance:O.adjustBalance,listBalanceGrants:O.listBalanceGrants,readBillingControls:O.readBillingControls,prepareBillingAuthorization:O.prepareBillingAuthorization,confirmBillingAuthorization:O.confirmBillingAuthorization,setBillingCoupons:O.setBillingCoupons,revokeBillingAuthorization:O.revokeBillingAuthorization,listBillingInvoices:O.listBillingInvoices,confirmBillingAdjustment:O.confirmBillingAdjustment,prepareBillingAdjustment:O.prepareBillingAdjustment,manageBillingLimits:O.manageBillingLimits,createCustomer:O.createCustomer,getCustomer:O.getCustomer,listCustomers:O.listCustomers,updateCustomer:O.updateCustomer,createSession:O.createSession,refreshSession:O.refreshSession,revokeSessions:O.revokeSessions,createGuestCustomer:O.createGuestCustomer,resumeGuestSession:O.resumeGuestSession,claimGuestCustomer:O.claimGuestCustomer,checkEntitlement:O.checkEntitlement,resolveOffering:O.resolveOffering,resolveContent:O.resolveContent,resolvePaywall:O.resolvePaywall,readHoldings:O.readHoldings,readLedger:O.readLedger,readBillingInvoice:O.readBillingInvoice,readCreditStatement:O.readCreditStatement,quoteBalance:O.quoteBalance,trackUsage:O.trackUsage,mutateBalance:O.mutateBalance,manageUsageEntity:O.manageUsageEntity,readUsageAnalytics:O.readUsageAnalytics,readCreditAnalytics:O.readCreditAnalytics,submitUsageBatch:O.submitUsageBatch,readUsageBatch:O.readUsageBatch,listOffers:O.listOffers,grantOffer:O.grantOffer,redeemCoupon:O.redeemCoupon,redeemReward:O.redeemReward,createReferralCode:O.createReferralCode,claimRewardProduct:O.claimRewardProduct,readSeats:O.readSeats,manageSeat:O.manageSeat};var cs=require("zod");var _o=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function qu(e,t,n){let r={},i,a,o,s="next",c;switch(e.type){case"entry":c=e.next;break;case"condition":{let u=e.cases.findIndex(l=>en(t.attributes??{},l.condition,t.savedGroups??{}));s=u<0?"default":`case:${u}`,c=u<0?e.default:e.cases[u].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new _o("Required GB Feature is unavailable");i=Hn(e.featureKey,t),o=i.value,Object.assign(r,yi(e,{value:o})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new _o("Required GB Experiment is unavailable");if(a=ma(u,t),o=a.value,s=a.inExperiment&&!a.passthrough&&typeof o=="string"?o:"notParticipating",c=s==="notParticipating"?e.notParticipating:e.routes[s],!c)throw new _o("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:Hn(e.configuration.featureKey,t).value;o={type:"offering_version",id:cs.z.uuid().parse(u)},Object.assign(r,yi(e,{value:o})),c=e.next;break}case"coupon":case"coupons":o=e.type==="coupons"?e.couponIds.map(u=>({type:"reward",id:u})):{type:"reward",id:e.couponId},Object.assign(r,yi(e,{value:o})),c=e.next;break}return{port:s,target:c,projections:r,...o===void 0?{}:{value:o},...i?{feature:i}:{},...a?{experiment:a}:{}}}function Wg(e,t,n){cs.z.uuid().parse(e),cs.z.number().int().nonnegative().parse(t);let r=ai(si(new TextEncoder().encode(JSON.stringify([e,t,n])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}var H=require("zod");var fr=H.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),SI=H.z.enum(["running","waiting","completed","closed","ineligible","failed"]),Uu=H.z.discriminatedUnion("type",[cu,H.z.strictObject({type:H.z.literal("wait"),receiptId:H.z.uuid(),kind:H.z.enum(["timer","event","operation"]),deadline:H.z.iso.datetime({offset:!0}).nullable(),eventName:fr.optional()}),H.z.strictObject({type:H.z.literal("open_url"),receiptId:H.z.uuid(),url:du,openIn:pu}),H.z.strictObject({type:H.z.literal("event"),receiptId:H.z.uuid(),event:fr})]),us=H.z.strictObject({type:H.z.literal("funnel"),id:H.z.uuid(),versionId:H.z.uuid()}),II={id:fr,presentation:Cn,outputs:H.z.array(fr).max(250),inputs:Ga,values:H.z.record(H.z.string(),ve).optional(),offeringKey:It.optional(),capabilities:mi,customerData:Zp,dataCursors:H.z.record(fr,$a.nullable())},vI=H.z.strictObject({...II,content:H.z.strictObject({type:H.z.literal("document"),document:dn})}),Eo=H.z.strictObject({id:H.z.uuid(),source:us,revision:H.z.number().int().nonnegative(),visit:H.z.number().int().nonnegative(),nodeId:fr,nodeType:H.z.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:SI,stopped:H.z.boolean(),canBack:H.z.boolean(),authenticated:H.z.boolean(),locale:H.z.string().min(1).max(35),answers:lr,parameters:dr,variables:H.z.record(H.z.string(),ve),output:ve.nullable(),screen:vI.nullable(),paywall:H.z.strictObject({receiptId:H.z.uuid(),resolution:H.z.union([wo,Jr]),quote:Si.nullable(),operation:Ii.nullable(),purchaseRequestId:H.z.uuid().nullable(),selectionGeneration:H.z.number().int().nonnegative().optional(),canReselect:H.z.boolean().optional()}).nullable(),instruction:Uu.nullable(),pendingRequest:H.z.strictObject({requestId:H.z.uuid(),authenticationRequired:H.z.boolean()}).nullable(),runExpiresAt:H.z.iso.datetime({offset:!0}),credentialExpiresAt:H.z.iso.datetime({offset:!0}).nullable()}),ls=H.z.strictObject({scope:Fe,run:Eo,settlement:H.z.strictObject({requestId:H.z.uuid(),state:H.z.enum(["pending","unknown","settled"]),operationId:H.z.uuid().nullable(),receiptId:H.z.uuid().nullable().optional()}).optional(),purchase:H.z.strictObject({receiptId:H.z.uuid(),quote:Si.nullable(),operation:Ii.nullable(),canReselect:H.z.boolean().optional()}).optional(),review:H.z.strictObject({activeOperationId:H.z.uuid().nullable(),pages:H.z.array(H.z.strictObject({receiptId:H.z.uuid(),nodeId:fr,visit:H.z.number().int().nonnegative()})).max(100),page:H.z.strictObject({receiptId:H.z.uuid(),nodeId:fr,visit:H.z.number().int().nonnegative(),document:dn,answers:lr,inputs:Ga,values:H.z.record(H.z.string(),ve).optional()}).nullable(),coupons:H.z.array(H.z.strictObject({grantId:H.z.uuid(),status:H.z.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:H.z.string().nullable()})).max(100),purchases:H.z.array(H.z.strictObject({receiptId:H.z.uuid(),operationId:H.z.uuid(),status:H.z.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:H.z.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:H.z.uuid().optional()}),Yg=ls.extend({run:Eo.extend({paywall:Eo.shape.paywall.unwrap().extend({resolution:Jr}).nullable()})});var Xg="X-Indiana-Server-Key";var se=require("zod");var Ae=require("zod");var wt=require("zod");var wI=wt.z.strictObject({selector:wt.z.string().min(1).max(2048),action:wt.z.enum(["set","append","remove"]),attribute:wt.z.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:wt.z.string().max(5e4).optional(),parentSelector:wt.z.string().max(2048).optional(),insertBeforeSelector:wt.z.string().max(2048).optional()}),OI=wt.z.strictObject({variation:wt.z.string().min(1).max(128),description:wt.z.string().max(2e3).default(""),css:wt.z.string().max(1e5).default(""),js:wt.z.string().max(1e5).default(""),domMutations:wt.z.array(wI).max(200).default([]),iam:Sf.optional(),renderGuard:La.optional()}),Bu=OI.omit({variation:!0,description:!0,iam:!0}),PI=Pi.omit({variations:!0,active:!0}).extend({changeId:wt.z.string().regex(/^[a-f0-9]{64}$/),variations:wt.z.tuple([Bu,Bu]).rest(Bu).refine(e=>e.length<=20)}),eh=wt.z.strictObject({trackExposures:wt.z.boolean(),environmentId:wt.z.uuid(),generation:wt.z.string().regex(/^[a-f0-9]{64}$/),experiments:wt.z.array(PI).max(100),savedGroups:Ao});var Ro=Ae.z.string().regex(/^[a-f0-9]{64}$/),nj=Ae.z.strictObject({iam:Ro,executionContracts:Ae.z.union([Ae.z.tuple([Ae.z.literal("funnel-run/1")]),Ae.z.tuple([Ae.z.literal("funnel-process/1")])]).default(["funnel-run/1"])}),CI=Ae.z.strictObject({release:Ro,render:La,button:Ae.z.strictObject({selector:Ae.z.string().min(1).max(512),elementKey:Ae.z.string().min(1).max(256),tag:Ae.z.enum(["button","a","input"])}).nullable()}),rj=Ae.z.strictObject({scope:Fe.extend({environmentId:Ae.z.uuid()}),release:Ro,validatedAt:Ae.z.iso.datetime({offset:!0}),validUntil:Ae.z.iso.datetime({offset:!0}),entries:Ae.z.array(Ae.z.strictObject({id:Ae.z.uuid(),funnelId:Ae.z.uuid(),versionId:Ae.z.uuid(),event:Ae.z.enum(["screen_enter","button_click"]),target:CI})).max(4e3)}),th=Ae.z.strictObject({operation:Ae.z.literal("entry_start"),funnelId:Ae.z.uuid(),versionId:Ae.z.uuid(),entryId:Ae.z.uuid(),release:Ro,requestId:Ae.z.uuid(),locale:Ae.z.string().min(1).max(35).default("en")}),nh=Ae.z.strictObject({scope:Fe,suppressed:Ae.z.literal(!0),reason:Ae.z.enum(["frequency","in_progress"]),retryAt:Ae.z.iso.datetime({offset:!0}).nullable()}),ij=Ae.z.strictObject({experimentId:Ae.z.uuid(),splitNodeId:Ae.z.string().min(1).max(128)}),_I=Ae.z.strictObject({experimentId:Ae.z.uuid(),experimentKey:Ae.z.string().min(1).max(128),variationKey:Ae.z.string().min(1).max(128),inExperiment:Ae.z.boolean(),generation:Ae.z.string().min(1).max(256)}),ko=Ae.z.strictObject({operation:Ae.z.literal("page_experiments"),release:Ro,usedReceiptIds:Ae.z.array(Ae.z.uuid()).max(20).default([]),customerToken:Ae.z.string().regex(Nt).optional()}),rh=Ae.z.strictObject({scope:Fe,runId:Ae.z.uuid(),assignments:Ae.z.array(_I.extend({receiptId:Ae.z.uuid()})).max(100),payload:eh});var jn=se.z.literal(gf),EI=se.z.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),Vu=se.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),ih=se.z.discriminatedUnion("type",[se.z.strictObject({type:se.z.literal("guest"),guestToken:Vu}),se.z.strictObject({type:se.z.literal("customer"),customer:Hr,customerData:Ci.optional()})]),Lu=se.z.strictObject({id:se.z.uuid(),runId:se.z.uuid(),customerId:se.z.uuid(),requestId:se.z.uuid(),acceptedAt:se.z.iso.datetime({offset:!0})}),RI=se.z.strictObject({participantId:se.z.uuid(),startedAs:se.z.enum(["guest","identified"]),binding:Lu.omit({runId:!0,requestId:!0}).nullable()}),kI=se.z.union([Uu,se.z.strictObject({type:se.z.literal("authentication_required"),reason:se.z.enum(["customer_required","customer_experiment_required"]),nodeId:se.z.string().min(1).max(64),visit:se.z.number().int().nonnegative()})]),jI=Eo.omit({authenticated:!0}).extend({identity:RI,instruction:kI.nullable()}),TI=se.z.discriminatedUnion("operation",[_t.options[2].omit({customerToken:!0}),_t.options[3].omit({customerToken:!0}),_t.options[4].omit({customerToken:!0}),_t.options[5].omit({customerToken:!0}),_t.options[6].omit({customerToken:!0}),_t.options[7].omit({customerToken:!0})]),ds={contract:jn,customerToken:se.z.string().regex(Nt)},oh={contract:jn,requestId:se.z.uuid(),runToken:EI,externalUserId:Hr.options[1].shape.value},ah=se.z.discriminatedUnion("operation",[se.z.strictObject({contract:jn,operation:se.z.literal("describe")}),se.z.strictObject({contract:jn,operation:se.z.literal("start"),source:ih,funnelId:_t.options[0].shape.funnelId,requestId:se.z.uuid(),locale:_t.options[0].shape.locale,parameters:_t.options[0].shape.parameters}),th.omit({operation:!0}).extend({contract:jn,operation:se.z.literal("entry_start"),source:ih}),se.z.strictObject({...oh,operation:se.z.literal("bind_customer"),guestToken:Vu,claimRequestId:se.z.uuid(),expectedBindingId:se.z.null()}),se.z.strictObject({...oh,operation:se.z.literal("binding_status"),guestToken:Vu.optional()}),_t.options[1].omit({operation:!0,customerToken:!0}).extend({...ds,operation:se.z.literal("get"),settlementBindingId:se.z.uuid().nullable().optional()}),_t.options[8].omit({operation:!0,customerToken:!0}).extend({...ds,operation:se.z.literal("review")}),ko.omit({customerToken:!0}).extend(ds),se.z.strictObject({...ds,operation:se.z.literal("command"),identity:se.z.strictObject({bindingId:se.z.uuid().nullable()}),command:TI})]),zu=ls.omit({run:!0}).extend({contract:jn,run:jI,settlement:ls.shape.settlement.unwrap().extend({accepted:se.z.boolean().nullable().optional()}).optional()}),mj=nh.extend({contract:jn}),fj=se.z.discriminatedUnion("operation",[ah.options[1].omit({contract:!0,source:!0,requestId:!0}),ah.options[2].omit({contract:!0,source:!0,requestId:!0})]),gj=zu.extend({binding:Lu,outcome:se.z.enum(["bound","already_bound"]),replayed:se.z.boolean()}),hj=se.z.discriminatedUnion("state",[se.z.strictObject({contract:jn,scope:Fe,state:se.z.literal("not_accepted")}),se.z.strictObject({contract:jn,scope:Fe,state:se.z.literal("conflict")}),se.z.strictObject({contract:jn,scope:Fe,state:se.z.literal("bound"),binding:Lu})]),yj=se.z.strictObject({contract:jn,scope:Fe,keyId:se.z.uuid(),operations:se.z.array(se.z.string()).max(20)});var Ne=require("zod");var Ni=Ne.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ch=Ne.z.strictObject({entry:Ni,nodes:Ne.z.array(Ne.z.strictObject({id:Ni,type:Ne.z.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:Ne.z.record(Ne.z.string(),Ni),writes:Ne.z.record(It,It),resources:Ne.z.strictObject({screenId:Ni.optional(),paywallVersionId:Ne.z.uuid().optional(),couponId:Ne.z.uuid().optional(),couponIds:Ne.z.array(Ne.z.uuid()).max(20).optional(),experimentId:Ne.z.uuid().optional(),featureKey:Ne.z.string().optional(),offeringVersionId:Ne.z.uuid().optional()})})).min(1).max(500)}),sh={scope:Fe,funnelId:Ne.z.uuid(),versionId:Ne.z.uuid(),evaluationRevision:Ne.z.number().int().nonnegative(),expiresAt:Ne.z.iso.datetime({offset:!0}).nullable(),topology:ch},ps=Ne.z.discriminatedUnion("evaluationMode",[Ne.z.strictObject({...sh,evaluationMode:Ne.z.literal("local"),growth:bn,conditions:Ne.z.record(Ni,Ne.z.array(Ne.z.strictObject({condition:Yt,port:Ne.z.string()})))}),Ne.z.strictObject({...sh,evaluationMode:Ne.z.literal("remote")})]),NI=ps.options[0].extend({evaluation:Ne.z.strictObject({maxTransitions:Ne.z.number().int().min(1).max(1e4),variables:Ne.z.record(It,hi),outputSchema:gi,terminals:Ne.z.record(Ni,Ne.z.strictObject({outcome:Ne.z.enum(["completed","closed","ineligible","failed"]),output:So.nullable()}))})});function DI(e){return ch.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let n={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":n.next=t.next;break;case"screen":Object.assign(n,t.outputs),r.screenId=t.screenId;{let a=e.screens.find(o=>o.id===t.screenId);a?.type==="paywall"&&(r.paywallVersionId=a.paywallVersionId)}break;case"condition":t.cases.forEach((a,o)=>{n[`case:${o}`]=a.target}),n.default=t.default;break;case"split":Object.assign(n,t.routes),n.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let a of["success","cancel","unavailable","failure"])n[a]=t[a];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=Ne.z.uuid().parse(t.action.coupon.value.id));break;case"external_page":n.opened=t.opened,n.failed=t.failed;break;case"wait":t.wait.type==="duration"?n.elapsed=t.wait.elapsed:(n.received=t.wait.received,n.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let i=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return i?.type==="feature"&&(r.featureKey=i.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:n,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function $u(e){let t=Ri.parse(e.document),n=e.evaluationMode==="local"?bn.parse(e.payload):null;if(n&&(n.scope.projectId!==e.scope.projectId||n.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:n?.expiresAt??null,topology:DI(t)};return ps.parse(e.evaluationMode==="remote"?r:{...r,growth:is(t,n),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((a,o)=>({condition:a.condition,port:`case:${o}`}))]))})}function uh(e){let t=$u(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=Ri.parse(e.document);return NI.parse({...t,evaluation:{maxTransitions:n.execution.maxTransitions,variables:n.variables,outputSchema:n.outputSchema,terminals:Object.fromEntries(n.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}var nt=require("zod");var lh=nt.z.string().regex(/^[a-f0-9]{64}$/),FI=Pi.omit({variations:!0,active:!0}).extend({changeId:lh,variations:nt.z.array(nt.z.strictObject({urlRedirect:nt.z.string().max(2048)})).min(2).max(20)}),dh=nt.z.strictObject({environmentId:nt.z.uuid(),trackExposures:nt.z.boolean(),generation:lh,experiments:nt.z.array(FI).max(100),savedGroups:Ao}),MI=nt.z.strictObject({eventUuid:nt.z.uuid(),timestamp:nt.z.iso.datetime({offset:!0}).optional(),deviceId:nt.z.string().min(1).max(128),sessionId:nt.z.string().min(1).max(128).optional(),url:nt.z.url().max(2048),pageTitle:nt.z.string().max(512).optional(),experimentKey:nt.z.string().min(1).max(255),variationKey:nt.z.string().min(1).max(64)}),_j=nt.z.strictObject({events:nt.z.array(MI).min(1).max(20)}),Ej=nt.z.strictObject({inserted:nt.z.number().int().nonnegative(),duplicates:nt.z.number().int().nonnegative(),skipped:nt.z.number().int().nonnegative(),rejected:nt.z.array(nt.z.strictObject({index:nt.z.number().int().nonnegative(),reason:nt.z.string()}))});var ct=require("zod");var Ku=32,qI=522240;function Hu(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var UI=ct.z.strictObject({nodeId:ct.z.string().min(1).max(64),visit:ct.z.number().int().nonnegative(),revision:ct.z.number().int().nonnegative()}),Gu=ct.z.record(ct.z.string(),ve),BI=ct.z.strictObject({id:ct.z.uuid(),nodeId:ct.z.string().min(1).max(64),visit:ct.z.number().int().nonnegative(),input:ct.z.strictObject({schemaVersion:Io.shape.schemaVersion,kind:Io.shape.kind,selector:Io.shape.selector,contract:Io.shape.contract}),context:Gu,removed:ct.z.array(ct.z.string()).max(100),attributes:Gu,removedAttributes:ct.z.array(ct.z.string()).max(100),result:Kf,offeringVersionId:ct.z.uuid().nullable(),events:ct.z.strictObject({entered:ct.z.string().regex(/^[1-9][0-9]{0,18}$/),decision:ct.z.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),Nj=ct.z.strictObject({schemaVersion:ct.z.literal(1),mode:ct.z.enum(["local","remote"]),versionId:ct.z.uuid(),generation:ct.z.number().int().positive(),base:UI,context:Gu,steps:ct.z.array(BI).min(1).max(Ku)}).refine(e=>pn(e)<=qI,"Segment exceeds its byte budget");var VI=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function jo(e){return Array.isArray(e)?e.some(jo):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&jo(n):!VI.test(t))}function ph(e,t,n,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(s=>s.id===t.screenId&&s.type==="paywall")))return"customer_required";let i=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(i&&["bundle","selection","offering"].includes(i.type)||t.type==="condition"&&t.cases.some(s=>jo(s.condition)))return"customer_required";let a=JSON.stringify([t,t.type==="screen"?e.screens.find(s=>s.id===t.screenId):null]);for(let[s,c]of Object.entries(e.variables))if(c.source.type==="attribute"&&c.source.key!=="funnelParticipantId"&&(a.includes(`variables.${s}`)||a.includes(JSON.stringify(s))))return"customer_required";if(t.type==="split"){let s=n.experiments?.[t.experimentId];if((s?.hashAttribute??"id")!=="funnelParticipantId"||jo(s?.condition)||s?.parentConditions?.length)return"customer_experiment_required"}let o=t.type==="feature"?t.featureKey:i?.type==="feature"?i.featureKey:void 0;return o&&n.features?.[o]?.rules?.some(s=>(s.hashAttribute??"id")!=="funnelParticipantId"||jo(s.condition)||s.parentConditions?.length)?"customer_experiment_required":null}var Qu=class extends Error{constructor(n,r){super(r);qe(this,"code",n);this.name="FunnelLocalCalculationError"}},mh=(e,t)=>new Qu(e,t),LI=e=>({experiments:e.experiments,features:e.features});function zI(e,t=mh){let n=new Map(e.topology.nodes.map(o=>[o.id,o])),r=ci(e.growth.savedGroups),i=LI(e.growth);function a(o,s){if(!Object.hasOwn(e.growth.features,o))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Hn(o,s).value}return{nodes:n,savedGroups:r,features:i.features,feature:a,evaluate(o,s){let c=n.get(o);if(!c)throw t("NOT_FOUND","Funnel node is unavailable");let u,l;if(c.type==="condition"){let f=e.conditions[c.id];if(!f)throw t("INVALID_RESPONSE","Local condition rules are unavailable");u=qu({id:c.id,name:c.id,type:"condition",cases:f.map(g=>({condition:g.condition,target:c.outputs[g.port]})),default:c.outputs.default},s,i.experiments).port}else if(c.type==="feature"){if(!c.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");l=a(c.resources.featureKey,s),u="next"}else if(c.type==="split"){if(!(c.resources.experimentId?e.growth.experiments[c.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let g=qu({id:c.id,name:c.id,type:"split",experimentId:c.resources.experimentId,routes:c.outputs,notParticipating:c.outputs.notParticipating},s,i.experiments);l=g.value,u=g.port}else if(["offering","end","output"].includes(c.type)&&c.resources.featureKey)l=a(c.resources.featureKey,s),u=c.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let m=c.outputs[u]??(u==="value"?c.id:void 0);if(!m)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:o,port:u,target:m,...l===void 0?{}:{value:l}}}}}function $I(e,t){let n=ps.parse(e);if(n.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=n.expiresAt?Date.parse(n.expiresAt):null,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let a=zI(n,t);return(o,s)=>(i(),GI(a,o,s))}function GI(e,t,n){let r=Ct.parse(n.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:a,onExperimentViewed:o}=n,s={attributes:r,...i?{saveStickyBucketAssignmentDoc:c=>i(structuredClone(c))}:{},...a?{onFeatureUsage:(c,u)=>a(c,structuredClone(u))}:{},...o?{onExperimentViewed:(c,u)=>o(structuredClone(c),structuredClone(u))}:{},features:e.features,savedGroups:e.savedGroups,...n.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(n.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,s)}function KI(e,t,n){let r=[],i=[],a=[],o=e(t,{...n.attributes?{attributes:n.attributes}:{},stickyBucketAssignmentDocs:n.sticky,saveStickyBucketAssignmentDoc(s){let c=r.findIndex(m=>m.next.attributeName===s.attributeName&&m.next.attributeValue===s.attributeValue),u=s.attributeName+"||"+s.attributeValue,l={expected:n.sticky[u]??null,next:s};c<0?r.push(l):r[c]=l},onExperimentViewed(s,c){c.inExperiment&&c.hashUsed&&!c.passthrough&&i.push(ve.parse({key:s.key,variationId:c.variationId,keyUsed:c.key,hashAttribute:c.hashAttribute,hashValue:c.hashValue}))},onFeatureUsage(s,c){a.push(ve.parse({feature:s,value:c.value,source:c.source,...c.ruleId?{ruleId:c.ruleId}:{}}))}});return{port:o.port,...o.value===void 0?{}:{value:o.value},sticky:r,exposures:i,features:a}}function fh(e,t,n,r=mh){let i=n,a=new Map(t.graph.nodes.map(R=>[R.id,R])),o=structuredClone(n.variables),s=structuredClone(i.sticky),c=[],u=n.nodeId,l=n.visit,m=!1,f,g=R=>ph(t,R,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),d=R=>(f??(f=$I(e,r)),KI(f,R,{attributes:ru({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:o,savedGroups:{}}),sticky:s}));for(let R=0;R<Ku;R++){let y=a.get(u);if(!y||!Hu(y)||g(y))break;if(l>=t.execution.maxTransitions&&(l>t.execution.maxTransitions||y.type!=="end"&&y.type!=="output")){if(!c.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let A,x;if(["condition","feature","split"].includes(y.type)||y.type==="offering"&&y.configuration.source==="feature")A=d(y.id),y.type==="offering"&&(A.value={type:"offering_version",id:String(A.value)}),y.type==="condition"?x=A.port==="default"?y.default:y.cases[Number(A.port.slice(5))]?.target:y.type==="split"?x=A.port==="notParticipating"?y.notParticipating:y.routes[A.port]:(y.type==="feature"||y.type==="offering")&&(x=y.next);else if(A={port:"next",sticky:[],exposures:[],features:[]},(y.type==="entry"||y.type==="coupon"||y.type==="coupons")&&(x=y.next),y.type==="offering"&&y.configuration.source==="fixed"&&(A.value={type:"offering_version",id:y.configuration.versionId},x=y.next),y.type==="end"||y.type==="output"){let P=y.type==="end"?y.output:y.value;if(A=P?.type==="feature"?d(y.id):{...A,port:"value",value:P?.type==="literal"?P.value:P?.type==="variable"?Ec({source:"variable",key:P.key,...P.path?{path:P.path}:{}},{declarations:t.variables,answers:n.answers,results:o,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},P&&(A.value===void 0||!An(t.outputSchema,A.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let v=[...c,{nodeId:u,result:A}];if(pn({steps:v})>6e4){if(!c.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(c.push({nodeId:u,result:A}),y.type==="feature"||y.type==="offering"||y.type==="coupon"||y.type==="coupons"){let P=y.type==="coupons"?y.couponIds.map(_=>({type:"reward",id:_})):y.type==="coupon"?{type:"reward",id:y.couponId}:A.value;if(P===void 0)throw r("INVALID_RESPONSE","Node output is missing");let j=yi(y,{value:P});om(t.variables,y,j),Object.assign(o,j)}for(let P of A.sticky)s[`${P.next.attributeName}||${P.next.attributeValue}`]=structuredClone(P.next);if(y.type==="end"||y.type==="output"){m=!0;break}if(!x)throw r("INVALID_RESPONSE","Local pure exit is unavailable");u=x,l++}let h=a.get(u);return{steps:c,...!m&&h&&(!Hu(h)||g(h))?{boundary:{nodeId:u,visit:l}}:{}}}var b=class extends Error{constructor(n,r,i,a,o){super(r);qe(this,"code",n);qe(this,"status",i);qe(this,"requestId",a);qe(this,"commandRequestId");qe(this,"retryable");qe(this,"recovery");qe(this,"retryAfterSeconds");qe(this,"reason");this.name="IndianaError",this.reason=o?.reason;let s=$o(n,i??0,{...o,retryAfter:o?.retryAfterSeconds===void 0?void 0:String(o.retryAfterSeconds)});this.retryable=s.retryable,this.recovery=s.recovery,this.retryAfterSeconds=s.retryAfterSeconds}};var To=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new b("INVALID_STATE","Installation sequence exhausted");return e+1},HI=async e=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(e,t=>t.charCodeAt(0))))].map(t=>t.toString(16).padStart(2,"0")).join("");function Un(e,t){return e.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 b("INVALID_STATE","Installation journal is invalid");return t({...n})})}function gh(e,t,n){let r=null,i=0,a=0,o=0,s=Promise.resolve(),c=!1;if(e&&(!n||Fe.parse(e.scope).projectId!==n.projectId||e.scope.environment!==n.environment))throw new b("SCOPE_MISMATCH","Push installation belongs to another scope");let u=()=>{if(c)throw new b("CLOSED","SDK client was destroyed");if(!e)throw new b("NOT_CONFIGURED","Configure this client's native Push host first");return e},l=x=>{if(x!==i)throw new b("IDENTITY_CHANGED","Identity changed during Push operation")};async function m(x){let v=u();if(!v.sha256&&!globalThis.crypto?.subtle)throw new b("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let P=v.sha256?await v.sha256(Uint8Array.from(x,j=>j.charCodeAt(0))):await HI(x);if(!/^[a-f0-9]{64}$/.test(P))throw new b("INVALID_STATE","Push credential digest is invalid");return P}function f(x){let v=Pr.parse(x);if(v.installationId.toLowerCase()!==u().installationId.toLowerCase())throw new b("INVALID_RESPONSE","Push response belongs to another installation");return v}async function g(x,v){let P=u(),j={installationId:P.installationId,publicKey:P.publicKey,issuedAt:new Date().toISOString(),...v},_=await P.sign(_l(x,P.scope,j));return{...j,signature:_}}let d=(x,v,P)=>t.requestWithCredential?t.requestWithCredential(x,v,P):t.request(x,v);async function h(){let x=u(),v=i,P=r?await(t.session?.access()??r):null,j=Un(x,Se=>Se),_;if(j.detachSeq!==null){let Se=j.detachSeq,At=Ol.parse(await g("detach",{sequence:Se,platform:x.platform}));try{let We=await t.request("push/installations/detach",{...x.scope,...At},"POST",{installationDetach:!0});if(!We||typeof We!="object"||!("installation"in We))throw new b("INVALID_RESPONSE","Push detach acknowledgement is invalid");let De=f(We.installation);if(De.bound||De.identitySeq!==Se)throw new b("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(We){if(We instanceof b&&We.status===404)_=We;else if(!(We instanceof b)||We.status!==412)throw We}_||Un(x,We=>({...We,detachSeq:We.detachSeq===Se?null:We.detachSeq}))}if(l(v),!P){if(_)throw _;return null}let X=O.bindPushInstallation,le=X.request.parse(await g("bind",{sequence:o,platform:x.platform,credentialDigest:await m(P)}));l(v);let he=X.response.parse(await d(X.path,le,P));l(v);let ke=f(he.installation);if(!ke.bound||ke.identitySeq!==o)throw new b("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return _&&j.detachSeq!==null&&o>j.detachSeq&&Un(x,Se=>({...Se,detachSeq:Se.detachSeq===j.detachSeq?null:Se.detachSeq})),ke}async function R(){u();let x=i,v=r?await(t.session?.access()??r):null;if(!v)throw new b("NOT_IDENTIFIED","Identify before reading this installation");let P=O.readPushInstallation,j=P.request.parse(await g("read",{credentialDigest:await m(v)}));l(x);let _=P.response.parse(await d(P.path,j,v));return l(x),f(_.installation)}function y(x=h){let v=s.catch(()=>{}).then(x);return s=v,v.catch(P=>{try{e?.onError?.(P instanceof Error?P:new Error("Push synchronization failed"))}catch{}}),v}async function A(x,v,P){let j=u(),_=v.identity,X=v.observation,le=r?await(t.session?.access()??r):null;if(l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");if(!le)throw new b("NOT_IDENTIFIED","Identify before recovering a Push address");if(!x.connectionId||!x.kind||!x.token||!["granted","provisional"].includes(x.permission))throw new b("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await y(async()=>{if(l(_),await h(),l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let he=Un(j,De=>P?De:{...De,addressSeq:To(De.addressSeq)}),Se=await g(P?"recovery_confirm":"recovery_request",{...x,sequence:he.addressSeq,credentialDigest:await m(le),...P?{challenge:P}:{}}),At=P?Cl.parse(Se):Pl.parse(Se);if(l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let We=await d(`push/installations/recovery/${P?"confirm":"request"}`,At,le);if(l(_),X!==a||Un(j,De=>De).addressSeq!==he.addressSeq)throw new b("INVALID_STATE","Push observation changed during recovery");if(P){let De=O.updatePushAddress.response.parse(We),rt=f(De.installation);if(!rt.bound||rt.identitySeq!==o||rt.addressSeq!==he.addressSeq||rt.connectionId!==x.connectionId||rt.addressStatus!=="active")throw new b("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return rt}if(!We||typeof We!="object"||!("recovery"in We))throw new b("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return Es.parse(We.recovery)})}return{recoveryObserver(){u();let x={identity:i,observation:++a};return{async request(v){return Es.parse(await A(v,x))},async confirm(v,P){return Pr.parse(await A(P,x,v))}}},identify(x){if(!e)return;o=Un(e,P=>({...P,identitySeq:To(P.identitySeq)})).identitySeq,r=x,i++,a++},reset(){if(e)try{Un(e,x=>{let v=To(x.identitySeq);return{...x,identitySeq:v,detachSeq:v}})}finally{r=null,i++,a++}},start(){e&&!c&&y()},destroy(){c=!0,r=null,i++,a++},async sync(){return await y()},read:R,async recover(){let x=u(),v=i,P=o;return a++,await y(async()=>{l(v);let j=await R();return l(v),o=Un(x,X=>{if(X.identitySeq!==P)throw new b("IDENTITY_CHANGED","A newer installation intent exists");return{...X,identitySeq:To(Math.max(X.identitySeq,j.identitySeq)),addressSeq:Math.max(X.addressSeq,j.addressSeq)}}).identitySeq,await h()})},tokenObserver(){u();let x=++a,v=i;return async P=>{if(x!==a||v!==i)return null;let j=u(),_=r?await(t.session?.access()??r):null;if(!_)throw new b("NOT_IDENTIFIED","Identify before registering a Push token");if(await y(),l(v),x!==a)return null;let X=Un(j,Se=>({...Se,addressSeq:To(Se.addressSeq)})),le=O.updatePushAddress,he=le.request.parse(await g("address",{...P,sequence:X.addressSeq,credentialDigest:await m(_)}));if(l(v),x!==a)return null;let ke=await d(le.path,he,_);return l(v),x!==a||Un(j,Se=>Se).addressSeq!==X.addressSeq?null:f(le.response.parse(ke).installation)}}}}var yh=require("zod");function hh(e,t,n,r){try{return e.parse(t)}catch(i){throw r&&i instanceof yh.ZodError?new b(n,r):i}}async function ge(e,t,n,r={},i){let a=typeof r=="function"?{}:r,o=hh(t.request,n,"INVALID_REQUEST",a.request);try{let s=await e(t.path,o,t.method,i),c=typeof r=="function"?r:r.parseResponse;return c?c(t.response,s):hh(t.response,s,"INVALID_RESPONSE",a.response)}catch(s){throw s instanceof b&&o!==null&&typeof o=="object"&&"requestId"in o&&typeof o.requestId=="string"&&(s.commandRequestId??(s.commandRequestId=o.requestId)),s}}function Ah(e,t){let n={async preference(r){let i=O.readMessagingPreference;return(await ge(e,i,{channel:r})).preference},async setPreference(r){let i=O.setMessagingPreference;return(await ge(e,i,r)).preference}};return{messaging:n,push:{sync:t.sync,read:t.read,recover:t.recover,tokenObserver:t.tokenObserver,recoveryObserver:t.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return n.setPreference({...r,channel:"push"})}}}}var bh={name:"@tinkerlandai/longplay-sdk",version:"0.10.17-rc.1",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}}};function Qe(e){return typeof e=="string"?e:String(e)}var JI=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function ZI(e){return e.replace(JI,"$1\uFFFD")}function Yu(e,t){if(typeof e!="object"||e==null){let n="";throw n+="The provided value is not an object",new TypeError(n)}return e}function _h(e){if(e!=null&&(typeof e=="object"||typeof e=="function")){let t=e[Symbol.iterator];if(t==null)return;if(typeof t!="function")throw new TypeError("The provided value is not iterable");let n=t.call(e);if(!n||typeof n!="object")throw new TypeError("Result of the Symbol.iterator method is not an object");return n}}function xh(e){let t;if(Array.isArray(e)){let n=e.map(Qe);if(n.length===2)return n}else if((t=_h(e))!=null){let n=Yu(t.next()),r=Yu(t.next());if(!n.done&&!r.done)return[Qe(n.value),Qe(r.value)]}throw new TypeError("Each query pair must be an iterable [name, value] tuple")}var Sh="0123456789ABCDEF",WI=/(?:%[0-9A-Fa-f]{2})+/g;function Bn(e){return`%${Sh[e>>4&15]}${Sh[15&e]}`}function Eh(e,t,n=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?n&&e===32?"+":t(e)?Bn(e):String.fromCharCode(e):e<=2047?Bn(192|e>>6)+Bn(128|63&e):e<=65535?Bn(224|e>>12)+Bn(128|e>>6&63)+Bn(128|63&e):Bn(240|e>>18)+Bn(128|e>>12&63)+Bn(128|e>>6&63)+Bn(128|63&e)}function Xu(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function el(e,t=!1){let n=0;for(;n<e.length;n++){let r=e.charCodeAt(n);if(r===37||t&&r===43)break}return n===e.length?e:(t?e.replace(/\+/g," "):e).replace(WI,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function Fo(e){return e<=31||e>126}function YI(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return Fo(e)}}function sl(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return Fo(e)}}function XI(e){return sl(e)||e===39}function tl(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return sl(e)}}function ys(e){switch(e){case 47:case 58:case 59:case 61:case 64:case 91:case 92:case 93:case 124:return!0;default:return tl(e)}}function Ih(e){switch(e){case 33:case 39:case 40:case 41:case 126:return!0;default:return(function(n){switch(n){case 36:case 37:case 38:case 43:case 44:return!0;default:return ys(n)}})(e)}}function Rh(e,t){return Eh(e=e||0,t)}function Vn(e,t,n=!1){let r=0;for(;r<e.length;r++){let a=e.charCodeAt(r);if(a>=128||n&&a===32||t(a))break}if(r===e.length)return e;let i=e.slice(0,r);for(;r<e.length;r++){let a=e.charCodeAt(r),o=a;if(a>=55296&&a<=56319&&r+1<e.length){let s=e.charCodeAt(r+1);s>=56320&&s<=57343&&(o=(a-55296<<10)+s-56320+65536,r++)}i+=Eh(o,t,n)}return i}function cl(e){let t=[],n=0,r=0;for(;r<=e.length;){if(r=e.indexOf("&",n),r<0&&(r=e.length),r!==n){let i=e.slice(n,r),a=i.indexOf("=");a<0&&(a=i.length),t.push([el(i.slice(0,a),!0),el(i.slice(a+1),!0)])}if(n=r+1,r===e.length)break}return t}function nl(e){let t="";for(let n=0;n<e.length;n++){let r=Vn(e[n][0],Ih,!0),i=Vn(e[n][1],Ih,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var ev=[2191,2191,3164,3164,3292,3292,6863,6877,6880,6891,8385,8385,11158,11158,42958,42959,42962,42962,42964,42964,42993,42993,64451,64466,64912,64913,64968,64974,67904,67929,69317,69319,69328,69336,69370,69371,72544,72551,73136,73179,73184,73193,93856,93880,93883,93907,94194,94198,100344,100351,101641,101662,101760,101874,118010,118012,118458,118480,118496,118512,124608,124638,124640,124661,124670,124671,128728,128728,128887,128890,129232,129240,129620,129623,129674,129674,129678,129678,129736,129736,129741,129741,129770,129770,129775,129775,130042,130042,177978,177983,183970,183981,205744,210041],tv=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],nv=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],rv=[2381,2381,2509,2509,2637,2637,2765,2765,2893,2893,3021,3021,3149,3149,3277,3277,3387,3388,3405,3405,3530,3530,3642,3642,3770,3770,3972,3972,4153,4154,5908,5909,5940,5940,6098,6098,6752,6752,6980,6980,7082,7083,7154,7155,11647,11647,43014,43014,43052,43052,43204,43204,43347,43347,43456,43456,43766,43766,44013,44013,68159,68159,69702,69702,69744,69744,69759,69759,69817,69817,69939,69940,70080,70080,70197,70197,70378,70378,70477,70477,70606,70608,70722,70722,70850,70850,71103,71103,71231,71231,71350,71350,71467,71467,71737,71737,71997,71998,72160,72160,72244,72244,72263,72263,72345,72345,72767,72767,73028,73029,73111,73111,73537,73538,90415,90415];function iv(e){for(let t=0;t<e.length;t++){let n=e.codePointAt(t);if(n>65535&&t++,n<=32||n===37||n===127||n>=55296&&n<=57343||n>=128&&n<=159||n>=64976&&n<=65007||!(65534&~n)||n===65533)return!0}return!1}var[ov,av,sv,vh]=[[[],"0,6,7,8,m,w,10,1b,1d,1f,72,73,7k,8k,dt,2rk","AAAAAAAAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAA/AAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAADAAABwfwAAAAAAAMADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhAAAAQAAAAAAAAQCAAABAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgACAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAP///////////////wAAAAAAAAAAAAAAAAAAAAA="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAEF9+P/+BwAAAMAA//8AAPz/////BlADAAAAAJwAAPz///8AAADA//H/5+X8AAAAAAAAAAAA/P///wcAAAAAAAAAAAAAPv0vAD0BAABA/gAA/5/5/f8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8g+N8B+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAYAAAAAAAAAAAAAD/////CwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANgAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/HgwAAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAP3////+BwAAAMDu//////////////8vAADAAJwAAP3///8AAADg////////AAAAAAAAAAAA/P///wcAAAAAAAAAAAAA////Ab0H//9H/gAA/9////8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL/G//8T+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAfgAAAAAAAAAAAAD+////DwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANwAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/Hg4AAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"0,3,4,5,6,7,8,9,a,b,c,d,e,f,g,j,n,o,p,q,r,s,t,w,18,19,1c,4m,4o,4p,4q,4r,6z,72,73,75,76,77,7e,7h,7i,7j,7k,7l,7m,7n,7o,7p,7q,7r,7s,7t,7u,7v,7w,7x,7y,7z,8k,9t,a2,a3,a7,cc,cv,cx,cy,d6,dc,dd,de,dg,dh,di,dk,dl,2rk,2rl","AAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAD//////////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD4AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/v////+/tgAAAAAAAAAAAP8XAAAAAAD4//8AAAEAAAAAAAAAAAAAAMCfnz0AAACAAgAAAP///wcAAAAAAAAAAAAAwP8BAAAAAAAA+A8gAADA++8+AAAAAAAOAAAAAAAAgP8AAAAAAPz///v///8HAAAAAAAAFP4h/gAMAAAAAgAAAAAAABAeIAAADAAAQAYAAAAAAAAQhjkCAAAAIwAGAAAAAAAAEL4hAAAMAAD8AgAAAAAAAJAeIGAADAAAAAQAAAAAAAAAASAAAAAAAAARAAAAAAAA0ME9YAAMAAAAAgAAAAAAAJBAMAAADAAAAAMAAAAAAAAYHiAAAAwAAAACAAAAAAAAAAAEXAAAAAAAAAAAAAAA8geAfwAAAAAAAAAAAAAAAPIfAH8AAAAAAAAAAAADAACgAgAAAAAAAP5/3+D//v///x9AAAAAAAAAAAAAAAAA4P1mAAAAwwEAHgBkIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAAAAMAAAADAAAAAwAAAAAAAAAsD9A/g8gAAAAAAC4AAAAAAAAAAAAAAAAAABgAAAAAAIAAAAAAAAAAAAAAAAAAIcBBA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAJAAAAAAAAQH/lH/ifAAAAAAAA//////8//w8AAA8AAAAAANAXBAAAAAD4DwADAAAAPDsAAAAAAABAowMAAAAAAADwzwAAAAAAAAAAAAAAAAAAAAAAAAD3//0hEAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////wDIAAAAfAAAAAAAAB/8AAAAAAAAAAAAAAAA/////wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAwAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAA/////wAAAAAAPAAAAAAAAAAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAID3PwAAAMAAAAAAAAAAAAAAAwBECAAAYBAAAAAAAAAAAAAAAAAAAAAAAAAwAAAA//8DgAAAAADAPwAAgP8DAAAAAAAHAAAAAADIMwAAAAAgAAAAAAAAAAB+ZgAIEAAAAAAAEAAAAAAAAJ3BAgAAAAAwQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICEAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8AAP//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAMAHAAAAAAAAAAAAAAAAAAAAAG7wAAAAAACHAAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAPAAAAAAAAAAAD4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAAAAAAAAA/AAAAAAAAAAAwP8BAAAAAAA8AAAAAAAAAAAAAAAAAAAAAgAAAAAAAP9/AAAAAAAZgAMAAAAAAHgGBAAAAAAAAAAHAAAAgO8fAAAAAAAAAAgAAwAAAAAAwH8AngAAAAAAAAAAAAAAgNNAAgAAAAAAAAAAAAAAAAAAAAAAAID4BwAAAwAAAAAAABgBAAAAwB8fAAAAAAAAAAD4AUAFAAYAAAAAAAAAAAAA/1wAAEAAAAAAAAAAAAAA+IUNAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8sAEAADAAAAAAAAAAAAAA+KcBAAAAAAAAAAAAAAAAKL8AAAAAAAAAAAAAAACgvA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgP8GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFgIAAAAAAAAAAAAAAAAAAAAAADwDAEAAAD+BwAAAAD4eYAAfg4AAAAAAPx/AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf78AAAAAAAAAAAAA/P///G0AAAAAAAAAAAAAAAAAAAB+tL8AAAAAAAAAAACjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAAwAAAAAAwAcFAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//4H/PwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMD/4wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHwAAAAAAAAB/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAgAcAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGAPAAAAAAAAAAAAAAD//////z///38AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAD+P/nDwAAADwAAAAAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////9/+P//////HyAAEAAA+P7/AAAAAAAAAAAAAH////nbBwAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASMAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAADwDwAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAA////////////////AAAAAAAAAAAAAAAAAAAAAP///////////////////////////////////////wAA"]].map(function([t,n,r]){return[t,n.split(",").map(i=>parseInt(i,36)),Uint8Array.from(atob(r),i=>i.charCodeAt(0))]});function cv(e,t){return t===931||t===1010||t===120531||t===120589||t===120647||t===120705||t===120763?"\u03C3":t>=5112&&t<=5117?String.fromCodePoint(t-8):t>=43888&&t<=43967?String.fromCodePoint(t-38864):t>=93856&&t<=93880?String.fromCodePoint(t+27):t===837||t===890||t>=8064&&t<=8111||t>=8114&&t<=8188?e.normalize("NFD").replace(/\u0345/g,"\u03B9").normalize("NFC").toLowerCase():""}function kh(e,t){for(let n=0;n<e.length;n+=2)if(t>=e[n]&&t<=e[n+1])return!0;return!1}function No(e,t){let[n,r,i]=e,a=t>>8;for(let c=0;c<n.length;c+=2)if(a>=n[c]&&a<=n[c+1])return!0;let o=r.indexOf(a);if(o<0)return!1;let s=255&t;return!!(i[32*o+(s>>3)]&1<<(7&s))}function uv(e){let t=Array.from(e,n=>n.codePointAt(0));for(let n=0;n<t.length;n++){let r=t[n];if(r!==8204&&r!==8205||n>0&&kh(rv,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&No(vh,t[i]);)i--;let a=n+1;for(;a<t.length&&No(vh,t[a]);)a++;if(!(i>=0&&a<t.length&&No(av,t[i])&&No(sv,t[a])))return!1}return!0}var lv=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,dv=/\p{Script=Latin}/u;function pv(e){return!lv.test(e)||!dv.test(e)}var gr=36,fs=1,rl=26,mv=38,fv=700,gv=72,hv=128,yv=2147483647;function wh(e){return String.fromCharCode(e+22+75*+(e<26))}function Av(e,t,n){let r=0;for(e=n?Math.floor(e/fv):e>>1,e+=Math.floor(e/t);e>(gr-fs)*rl>>1;r+=gr)e=Math.floor(e/(gr-fs));return Math.floor(r+(gr-fs+1)*e/(e+mv))}function bv(e){let t=Array.from(e,c=>c.codePointAt(0)),n="",r=0;for(let c=0;c<t.length;c++){let u=t[c];u<128&&(n+=String.fromCharCode(u),r++)}let i=r;i&&(n+="-");let a=hv,o=0,s=gv;for(;r<t.length;){let c=yv;for(let u=0;u<t.length;u++){let l=t[u];l>=a&&l<c&&(c=l)}o+=(c-a)*(r+1),a=c;for(let u=0;u<t.length;u++){let l=t[u];if(l<a&&o++,l===a){let m=o;for(let f=gr;;f+=gr){let g=f<=s?fs:f>=s+rl?rl:f-s;if(m<g)break;n+=wh(g+(m-g)%(gr-g)),m=Math.floor((m-g)/(gr-g))}n+=wh(m),s=Av(o,r+1,r===i),o=0,r++}}o++,a++}return n}function Ju(e){let t=10;if(e.length>=2&&e[0]==="0"&&(e[1]==="x"||e[1]==="X"))e=e.slice(2),t=16;else if(e.length>=2&&e[0]==="0")e=e.slice(1),t=8;else if(e==="")return-1;let n=0;for(let r=0;r<e.length;r++){let i=Xu(e.charCodeAt(r));if(i>=t||i<0)return-1;n=n*t+i}return n}function Oh(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function jh(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function Th(e){return e.length===2&&jh(e.codePointAt(0),e.codePointAt(1))}function Ph(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function ht(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function Nh(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function il(e,t){if(e[0]==="[")return e[e.length-1]==="]"?(function(r){let i=[0,0,0,0,0,0,0,0],a=null,o=0,s=0,c=Array.from(r,u=>u.codePointAt(0));if(c[s]===58){if(c[s+1]!==58)return null;s+=2,o++,a=o}for(;s<c.length;){if(o===8)return null;if(c[s]===58){if(a!==null)return null;s++,o++,a=o;continue}let u=0,l=0,m=0;for(;m<4&&(u=Xu(c[s]))>=0;)l=(l<<4)+u,s++,m++;if(c[s]===46){if(m===0||o>6)return null;s-=m;let f=0;for(;c[s]!==void 0;){let g=0;if(f>0)if(c[s]===46&&f<4)s++;else return null;if(c[s]==null||c[s]<48||c[s]>57)return null;for(;c[s]>=48&&c[s]<=57;){if(g=10*g+Xu(c[s]),g>255)return null;s++}i[o]=256*i[o]+g,f++,f%2==0&&o++}if(f!==4)return null;break}else if(c[s]===58){if(c[++s]===void 0)return null}else if(c[s]!==void 0)return null;i[o]=l,o++}if(a!==null){let u=o-a;for(o=7;o!==0&&u>0;){let l=i[a+u-1];i[a+u-1]=i[o],i[o]=l,o--,u--}}else if(a===null&&o!==8)return null;return i})(e.substring(1,e.length-1)):null;if(t)return(function(r){return Ph(r)?null:Vn(r,Fo)})(e);{let n=(function(i){let a=!1,o=!1;for(let c=0;c<i.length;c++){let u=i.charCodeAt(c);if(u<=32||u===37||u===127)return null;if(u>=128){a=!0;break}u>=65&&u<=90&&(o=!0)}if(!a)return i!==""?o?i.toLowerCase():i:null;if((function(u){for(let l of u){let m=l.codePointAt(0);if(/[\p{Cn}\p{Co}\p{Cs}\p{Noncharacter_Code_Point}]/u.test(l)&&!kh(ev,m)||No(ov,m))return!0}return!1})(i))return null;let s=(i=(function(u){let l="";for(let m of u){let f=m.codePointAt(0);if(f!==8204&&f!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(m))continue;let g=cv(m,f);if(g){l+=g;continue}let d=tv.indexOf(f);l+=d<0?m:nv[d]}return l})(i).normalize("NFKC").replace(/[\u3002\uff0e\uff61]/g,".").toLowerCase()).split(".");for(let c=0;c<s.length;c++){let u=s[c];if(u==="")continue;let l=/[^\0-\x7f]/.test(u);if(iv(u)||l&&(/^\p{Mark}/u.test(u)||!uv(u)||!pv(u)||u.startsWith("xn--")))return null;l&&(s[c]=`xn--${bv(u)}`)}return(i=s.join("."))!==""?i:null})(e.indexOf("%")===-1?e:el(e));return n===null||Ph(n)?null:(function(i){let a=i.length,o=i.lastIndexOf(".",a-2)+1;if(i.charCodeAt(a-1)===46&&a--,a<=o)return!1;if(Ju(i.slice(o,a))>=0)return!0;for(;o<a;o++){let s=i.charCodeAt(o);if(s<48||s>57)return!1}return!0})(n)?(function(i){let a=i.split("."),o=a.length;if(a[o-1]||o--,o>4)return null;let s=0;for(let u=0;u<o-1;u++){let l=Ju(a[u]);if(l<0||l>255)return null;s+=l*(1<<8*(3-u))}let c=Ju(a[o-1]);return c<0||c>=256**(5-o)?null:(s+=c,s)})(n):n}}function ol(e){return typeof e=="number"?(function(n){let i="";return i+=`${(n>>>24&255).toString(10)}.`,i+=`${(n>>>16&255).toString(10)}.`,i+=`${(n>>>8&255).toString(10)}.`,i+=(n&255).toString(10),i})(e):Array.isArray(e)?`[${(function(n){let r=(function(s){let c=-1,u=-1,l=1,m=0;for(let f=0;f<s.length;++f)s[f]!==0?(m>l&&(c=u,l=m),u=-1,m=0):(u===-1&&(u=f),++m);return m>l?u:c})(n),i="",a=!1;for(let o=0;o<=7;++o)if(!(a&&n[o]===0)){if(a&&(a=!1),r===o){i+=o===0?"::":":",a=!0;continue}i+=n[o].toString(16),o!==7&&(i+=":")}return i})(e)}]`:e}function Dh(e){e.path.length>0&&(e.path.length!==1||e.scheme!=="file"||!(function(n){return/^[A-Za-z]:$/u.test(n)})(e.path[0]))&&e.path.pop()}function Fh(e){return e.username!==""||e.password!==""}function Zu(e){return e.host===null||e.host===""||e.scheme==="file"}var E=0,U="",Pe="",$e=null,B,gs=!1,hs=!1,Xr=!1,yt;function hn(e,t,n,r){t||(e=(function(o){let s=0,c=o.length;for(;s<c&&!(o.charCodeAt(s)>32);++s);for(;c>s&&!(o.charCodeAt(c-1)>32);--c);return o.substring(s,c)})(e)),e=(function(o){let s=0;for(;s<o.length;s++){let u=o.charCodeAt(s);if(u===9||u===10||u===13)break}if(s===o.length)return o;let c=o.slice(0,s);for(;s<o.length;s++){let u=o.charCodeAt(s);u!==9&&u!==10&&u!==13&&(c+=o[s])}return c})(e),E=0,U=e,Pe="",$e=n||null,B=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},gs=!1,hs=!1,Xr=!1,yt=r||0;let i=xv;switch(r){case 3:case 4:i=As;break;case 5:i=ll;break;case 6:i=ei;break;case 7:i=hr;break;case 8:i=Ln}return i(G(e,E))!==1?B:null}function ne(e,t){return E+=E===e?Tn(t):1,E<=U.length}function G(e,t){return t<e.length?e.codePointAt(t):void 0}function Tn(e){return e!=null&&e>65535?2:1}function Mh(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var xv=e=>{let t=E;if(e!=null&&(e>=65&&e<=90||e>=97&&e<=122)){let n=E+1;for(e=U.charCodeAt(n);e===43||e===45||e===46||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57;)n++,e=U.charCodeAt(n);return Pe=U.slice(E,n).toLowerCase(),E=n,Sv(n<U.length?e:void 0)}else return yt?1:(--E,ne(t,e)?qh(G(U,E)):0)},Sv=e=>{let t=E;if(e===58){if(yt){if(ht(B.scheme)!==ht(Pe))return 0;if((Fh(B)||B.port!==null)&&Pe==="file")return 0;if(B.scheme==="file"&&B.host==="")return 0}return B.scheme=Pe,yt?(B.port===Nh(B.scheme)&&(B.port=null),0):(Pe="",B.scheme==="file"?ne(t,e)?dl(G(U,E)):0:ht(B.scheme)&&$e!==null&&$e.scheme===B.scheme?ne(t,e)?Iv(G(U,E)):0:ht(B.scheme)?ne(t,e)?wv(G(U,E)):0:G(U,E+1)===47?(E++,ne(t,e)?vv(G(U,E)):0):(B.path=[""],B.opaquePath=!0,ne(t,e)?Bh(G(U,E)):0))}else return yt?1:(Pe="",E=-1,ne(t,e)?qh(G(U,E)):0)},qh=e=>{let t=E;return $e===null||$e.opaquePath&&e!==35?1:$e.opaquePath&&e===35?(B.scheme=$e.scheme,B.path=$e.path.slice(),B.opaquePath=$e.opaquePath,B.query=$e.query,B.fragment="",ne(t,e)?Ln(G(U,E)):0):$e.scheme==="file"?(E--,ne(t,e)?dl(G(U,E)):0):(E--,ne(t,e)?ul(G(U,E)):0)},Iv=e=>{let t=E;return e===47&&G(U,E+1)===47?(++E,ne(t,e)?xs(G(U,E)):0):(E--,ne(t,e)?ul(G(U,E)):0)},vv=e=>{let t=E;return e===47?ne(t,e)?Di(G(U,E)):0:(E--,ne(t,e)?Nn(G(U,E)):0)},ul=e=>{let t=E;return B.scheme=$e.scheme,e===47||ht(B.scheme)&&e===92?ne(t,e)?Ch(G(U,E)):0:(B.username=$e.username,B.password=$e.password,B.host=$e.host,B.port=$e.port,B.path=$e.path.slice(),B.query=$e.query,e===63?(B.query="",ne(t,e)?hr(G(U,E)):0):e===35?(B.fragment="",ne(t,e)?Ln(G(U,E)):0):e!=null?(B.query=null,B.path.pop(),E--,ne(t,e)?Nn(G(U,E)):0):ne(t,e)?ul(G(U,E)):0)},Ch=e=>{let t=E;return ht(B.scheme)&&(e===47||e===92)?ne(t,e)?xs(G(U,E)):0:e===47?ne(t,e)?Di(G(U,E)):0:(B.username=$e.username,B.password=$e.password,B.host=$e.host,B.port=$e.port,E--,ne(t,e)?Nn(G(U,E)):0)},wv=e=>{let t=E;return e===47&&G(U,E+1)===47?E++:E--,ne(t,e)?xs(G(U,E)):0},xs=e=>{let t=E;return e!==47&&e!==92?(E--,ne(t,e)?Di(G(U,E)):0):ne(t,e)?xs(G(U,E)):0},Di=e=>{let t=E;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!ht(B.scheme))){let n=E+Tn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===64||r===35||r===47||r===63||r===92&&ht(B.scheme))break;n+=Tn(r)}return Pe+=U.slice(E,n),E=n-1,ne(t,e)?Di(G(U,E)):0}if(e===64){gs&&(Pe=`%40${Pe}`),gs=!0;for(let n=0;n<Pe.length;n++){let r=Pe.codePointAt(n);if(r===58&&!hs){hs=!0;continue}let i=Rh(r,ys);hs?B.password+=i:B.username+=i,r!=null&&r>65535&&n++}return Pe="",ne(t,e)?Di(G(U,E)):0}else return e==null||e===35||e===47||e===63||e===92&&ht(B.scheme)?gs&&Pe===""?1:(E-=Pe.length+1,Pe="",ne(t,e)?As(G(U,E)):0):(Pe+=Mh(e),ne(t,e)?Di(G(U,E)):0)},As=e=>{let t=E;if(yt&&B.scheme==="file")return E--,ne(t,e)?pl(G(U,E)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!ht(B.scheme))){let n=E+Tn(e);for(e===91?Xr=!0:e===93&&(Xr=!1);n<U.length;){let r=G(U,n);if(r==null||!Xr&&r===58||r===35||r===47||r===63||r===92&&ht(B.scheme))break;r===91?Xr=!0:r===93&&(Xr=!1),n+=Tn(r)}return Pe+=U.slice(E,n),E=n-1,ne(t,e)?As(G(U,E)):0}else if(e===58&&!Xr){if(Pe===""||yt===4)return 1;let n=il(Pe,!ht(B.scheme));return n===null?1:(B.host=ol(n),Pe="",ne(t,e)?ll(G(U,E)):0)}else if(e==null||e===35||e===47||e===63||e===92&&ht(B.scheme)){if(E--,ht(B.scheme)&&Pe==="")return 1;if(yt&&Pe===""&&(Fh(B)||B.port!==null))return 1;let n=il(Pe,!ht(B.scheme));return n===null?1:(B.host=ol(n),Pe="",yt?0:ne(t,e)?ei(G(U,E)):0)}else return Pe+=Mh(e),ne(t,e)?As(G(U,E)):0},ll=e=>{let t=E;if(e!=null&&e>=48&&e<=57){let n=E+1;for(;n<U.length;){let r=U.charCodeAt(n);if(r<48||r>57)break;n++}return Pe+=U.slice(E,n),E=n-1,ne(t,e)?ll(G(U,E)):0}else if(yt||e==null||e===35||e===47||e===63||e===92&&ht(B.scheme)){if(Pe!==""){let n=parseInt(Pe,10);if(n>65535)return 1;if(B.port=n===Nh(B.scheme)?null:n,Pe="",yt)return 0}return yt?1:(E--,ne(t,e)?ei(G(U,E)):0)}else return 1};function Uh(e,t){let n=e.length-t;if(n<2)return!1;if(jh(G(e,t),G(e,t+1))){if(n===2)return!0;{let r=G(e,t+2);return r===47||r===92||r===63||r===35}}else return!1}var dl=e=>{let t=E;return B.scheme="file",B.host="",e===47||e===92?ne(t,e)?Ov(G(U,E)):0:$e?.scheme==="file"?(B.host=$e.host,B.path=$e.path.slice(),B.opaquePath=$e.opaquePath,B.query=$e.query,e===63?(B.query="",ne(t,e)?hr(G(U,E)):0):e===35?(B.fragment="",ne(t,e)?Ln(G(U,E)):0):e!=null?(B.query=null,Uh(U,E)?B.path=[]:Dh(B),E--,ne(t,e)?Nn(G(U,E)):0):ne(t,e)?dl(G(U,E)):0):(E--,ne(t,e)?Nn(G(U,E)):0)},Ov=e=>{let t=E;return e===47||e===92?ne(t,e)?pl(G(U,E)):0:($e!==null&&$e.scheme==="file"&&(!Uh(U,E)&&(function(r){if(r.length===2){let i=r.codePointAt(0),a=r.codePointAt(1);return(i>=65&&i<=90||i>=97&&i<=122)&&a===58}else return!1})($e.path[0])&&B.path.push($e.path[0]),B.host=$e.host),E--,ne(t,e)?Nn(G(U,E)):0)},pl=e=>{let t=E;if(e!=null&&e!==47&&e!==92&&e!==63&&e!==35){let n=E+Tn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===47||r===92||r===63||r===35)break;n+=Tn(r)}return Pe+=U.slice(E,n),E=n-1,ne(t,e)?pl(G(U,E)):0}else if(e==null||e===47||e===92||e===63||e===35){if(E--,!yt&&Th(Pe))return ne(t,e)?Nn(G(U,E)):0;if(Pe==="")return B.host="",yt?0:ne(t,e)?ei(G(U,E)):0;{let n=il(Pe,!ht(B.scheme));return n===null?1:(n==="localhost"&&(n=""),B.host=ol(n),Pe="",yt?0:ne(t,e)?ei(G(U,E)):0)}}return 1},ei=e=>{let t=E;return ht(B.scheme)?(e!==92&&e!==47&&E--,ne(t,e)?Nn(G(U,E)):0):!yt&&e===63?(B.query="",ne(t,e)?hr(G(U,E)):0):!yt&&e===35?(B.fragment="",ne(t,e)?Ln(G(U,E)):0):e!=null?(e!==47&&E--,ne(t,e)?Nn(G(U,E)):0):(yt&&B.host===null&&B.path.push(""),ne(t,e)?ei(G(U,E)):0)},Nn=e=>{let t=E;if(e!=null&&e!==47&&(!ht(B.scheme)||e!==92)&&(yt||e!==63&&e!==35)){let n=E+Tn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===47||ht(B.scheme)&&r===92||!yt&&(r===63||r===35))break;n+=Tn(r)}Pe+=Vn(U.slice(E,n),tl),E=n,e=G(U,n)}if(e==null||e===47||ht(B.scheme)&&e===92||!yt&&(e===63||e===35)){let n=ht(B.scheme)&&e===92;return(function(i){switch(i){case"..":case"%2e.":case"%2E.":case".%2e":case".%2E":case"%2e%2e":case"%2E%2e":case"%2e%2E":case"%2E%2E":return!0;default:return!1}})(Pe)?(Dh(B),e!==47&&!n&&B.path.push("")):Oh(Pe)&&e!==47&&!n?B.path.push(""):Oh(Pe)||(B.scheme==="file"&&B.path.length===0&&Th(Pe)&&(Pe=`${Pe[0]}:`),B.path.push(Pe)),Pe="",e===63?(B.query="",ne(t,e)?hr(G(U,E)):0):e===35?(B.fragment="",ne(t,e)?Ln(G(U,E)):0):ne(t,e)?Nn(G(U,E)):0}else return Pe+=Rh(e,tl),ne(t,e)?Nn(G(U,E)):0},Bh=e=>{let t=E;if(e===63)return B.query="",ne(t,e)?hr(G(U,E)):0;if(e===35)return B.fragment="",ne(t,e)?Ln(G(U,E)):0;if(e!=null){let n=E+Tn(e);for(;n<U.length;){let i=G(U,n);if(i===63||i===35)break;n+=Tn(i)}let r=U.slice(E,n);if(n<U.length&&r.charCodeAt(r.length-1)===32?B.path[0]+=Vn(r.slice(0,-1),Fo)+"%20":B.path[0]+=Vn(r,Fo),E=n,(e=G(U,n))===63)return B.query="",ne(t,e)?hr(G(U,E)):0;if(e===35)return B.fragment="",ne(t,e)?Ln(G(U,E)):0}return ne(t,e)?Bh(G(U,E)):0},hr=e=>{let t=E,n=E;if(e!=null){if(yt)n=U.length;else{let i=U.indexOf("#",E);n=i===-1?U.length:i}let r=ht(B.scheme)?XI:sl;B.query+=Vn(U.slice(E,n),r)}return E=n,G(U,n)===35&&!yt?(B.fragment="",ne(t,e)?Ln(G(U,E)):0):ne(t,e)?hr(G(U,E)):0},Ln=e=>{let t=E;return e!=null&&(B.fragment+=Vn(U.slice(E),YI),E=U.length),ne(t,e)?Ln(G(U,E)):0};function al(e){if(e.opaquePath)return e.path[0];{let t="";for(let n of e.path)t+=`/${n}`;return t}}function Vh(e){switch(e.scheme){case"blob":{let t=hn(al(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":Vh(t)}case"ftp":case"http":case"https":case"ws":case"wss":return(function(n){let r=`${n.scheme}://`;return r+=n.host,n.port!==null&&(r+=`:${n.port}`),r})(e);default:return"null"}}var He=Symbol("URLImpl"),In=class e{constructor(t,n){if(t===void 0&&n===void 0)throw new TypeError('The "url" argument must be specified.');t=Qe(t),n!=null&&(n=Qe(n));let r=null;if(n!=null&&(r=hn(n,null,null,0),r==null))throw new TypeError(`Invalid base URL: ${n}`);let i=hn(t,null,r,0);if(i==null)throw new TypeError(`Invalid URL: ${t}`);this[He]={url:i,query:null}}static createObjectURL(t){throw new TypeError("URL.createObjetURL is unsupported")}static revokeObjectURL(t){}static parse(t,n){t=Qe(t),n!==void 0&&(n=Qe(n));try{return new e(t,n)}catch{return null}}static canParse(t,n){t=Qe(t),n!==void 0&&(n=Qe(n));let r=null;return n!=null&&(r=hn(n,null,null,0),r==null)?!1:hn(t,null,r,0)!=null}get href(){return(function(n){let r=`${n.scheme}:`;return n.host!==null&&(r+="//",(n.username!==""||n.password!=="")&&(r+=n.username,n.password!==""&&(r+=`:${n.password}`),r+="@"),r+=n.host,n.port!==null&&(r+=`:${n.port}`)),n.host===null&&!n.opaquePath&&n.path.length>1&&n.path[0]===""&&(r+="/."),r+=al(n),n.query!==null&&(r+=`?${n.query}`),n.fragment!==null&&(r+=`#${n.fragment}`),r})(this[He].url)}set href(t){let n=hn(t=Qe(t),null,null,0);if(n==null)throw new TypeError(`Invalid URL: ${t}`);this[He].url=n,this[He].query&&Wu(this[He].query,n.query)}get origin(){return Vh(this[He].url)}get protocol(){return`${this[He].url.scheme}:`}set protocol(t){hn(`${t=Qe(t)}:`,this[He].url,null,2)}get username(){return this[He].url.username}set username(t){t=Qe(t),Zu(this[He].url)||(function(r,i){r.username=Vn(i,ys)})(this[He].url,t)}get password(){return this[He].url.password}set password(t){t=Qe(t),Zu(this[He].url)||(function(r,i){r.password=Vn(i,ys)})(this[He].url,t)}get host(){let{url:t}=this[He];return t.host==null?"":t.port==null?t.host:`${t.host}:${t.port}`}set host(t){t=Qe(t),this[He].url.opaquePath||hn(t,this[He].url,null,3)}get hostname(){let{url:t}=this[He];return t.host!=null?t.host:""}set hostname(t){t=Qe(t),this[He].url.opaquePath||hn(t,this[He].url,null,4)}get port(){let{url:t}=this[He];return t.port!=null?`${t.port}`:""}set port(t){t=Qe(t);let{url:n}=this[He];Zu(n)||(t?hn(t,n,null,5):n.port=null)}get pathname(){return al(this[He].url)}set pathname(t){t=Qe(t);let{url:n}=this[He];n.opaquePath||(n.path=[],hn(t,n,null,6))}get search(){let{url:t}=this[He];return t.query?`?${t.query}`:""}set search(t){t=Qe(t);let{url:n,query:r}=this[He];if(!t)n.query=null,r&&Wu(r,null);else{let i=t[0]==="?"?t.substring(1):t;n.query="",hn(i,n,null,7),r&&Wu(r,n.query)}}get searchParams(){let t=this[He],n=t.query;return n==null&&(n=t.query=(function(i,a){let o=new bs;return o[ut].url=i,o[ut].serialized=a==null,a&&(o[ut].list=cl(a)),o})(this,t.url.query)),n}get hash(){let{url:t}=this[He];return t.fragment?`#${t.fragment}`:""}set hash(t){t=Qe(t);let{url:n}=this[He];if(!t)n.fragment=null;else{let r=t[0]==="#"?t.substring(1):t;n.fragment="",hn(r,n,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(In.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var ut=Symbol("URLSearchParamsImpl"),Pv=Symbol.dispose||Symbol.for("dispose");function Wu(e,t){t?e[ut].list=cl(t):e[ut].list.length=0,e[ut].serialized=t==null}function ms(e){if(e.url){let t=nl(e.list);(function(r,i){r[He].url.query=i})(e.url,t||null),e.serialized=!0}}var Cv=typeof Iterator<"u"?Iterator:Object,Do=class extends Cv{constructor(t,n){super(),this[ut]={ptr:t,map:n,index:0}}next(){let t=this[ut];return t.index<t.ptr.list.length?{value:t.map(t.ptr.list[t.index++]),done:!1}:{value:void 0,done:!0}}[Symbol.iterator](){return this}[Pv](){}},bs=class{constructor(t){let n=this[ut]={list:[],url:null,serialized:!0},r;if(Array.isArray(t))for(let i=0;i<t.length;i++)n.list.push(xh(t[i]));else if((r=_h(t))!=null){let i;for(;!(i=Yu(r.next())).done;)n.list.push(xh(i.value))}else if((typeof t=="object"||typeof t=="function")&&t!=null){let i=Object.keys(t);for(let a=0;a<i.length;a++){let o=i[a],s=ZI(o),c=Qe(t[o]),u=n.list.find(l=>l[0]===s);u?u[1]=c:n.list.push([s,c])}}else if(t!==void 0){let i=Qe(t);i=i[0]==="?"?i.substring(1):i,n.list=cl(i)}}get size(){return this[ut].list.length}append(t,n){t=Qe(t),n=Qe(n),this[ut].list.push([t,n]);let r=this[ut];r.url&&r.serialized?(function(a,o){let s=a[He].url;s.query=s.query?`${s.query}&${o}`:o})(r.url,nl([[t,n]])):ms(r)}delete(t,n){t=Qe(t),n=n!=null?Qe(n):void 0;let{list:r}=this[ut],i=0;for(;i<r.length;)r[i][0]===t&&(n==null||r[i][1]===n)?r.splice(i,1):i++;ms(this[ut])}get(t){t=Qe(t);let{list:n}=this[ut];for(let r=0;r<n.length;r++)if(n[r][0]===t)return n[r][1];return null}getAll(t){t=Qe(t);let n=[],{list:r}=this[ut];for(let i=0;i<r.length;i++)r[i][0]===t&&n.push(r[i][1]);return n}has(t,n){t=Qe(t),n=n!=null?Qe(n):void 0;let{list:r}=this[ut];for(let i=0;i<r.length;i++)if(r[i][0]===t&&(n==null||r[i][1]===n))return!0;return!1}set(t,n){t=Qe(t),n=Qe(n);let{list:r}=this[ut],i=!1,a=!1,o=0;for(;o<r.length;)r[o][0]===t?i?(r.splice(o,1),a=!0):(i=!0,r[o][1]!==n&&(r[o][1]=n,a=!0),o++):o++;i||(r.push([t,n]),a=!0),a&&ms(this[ut])}sort(){this[ut].list.sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0),ms(this[ut])}forEach(t,n){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:r}=this[ut];for(let i=0;i<r.length;i++)t.call(n,r[i][1],r[i][0],this)}entries(){return new Do(this[ut],t=>t)}keys(){return new Do(this[ut],t=>t[0])}values(){return new Do(this[ut],t=>t[1])}toString(){return nl(this[ut].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(bs.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var yr="https://api.longplayai.com";function Lh(e){let t,n=()=>typeof t=="string"?t:t?.accessToken,r=0,i,a=new Map,o=()=>{for(let m of[...a.keys()])try{m()}catch{}};function s(m){let f=++r;i=void 0,t=void 0;for(let g of[...a.values()])try{g?.()}catch{}f===r&&(t=m,o())}let c=()=>s();function u(m,f=!1){let g=Xn.safeParse(m);if(!g.success||f&&Date.parse(g.data.expiresAt)<=Date.now()||Date.parse(g.data.refreshExpiresAt)<=Date.now()||Date.parse(g.data.refreshExpiresAt)<Date.parse(g.data.expiresAt))throw new b("INVALID_RESPONSE","Invalid customer session credentials");return g.data}async function l(){if(i)return i;let m=typeof t=="object"?t:void 0,f=r;if(!m||Date.parse(m.refreshExpiresAt)<=Date.now())throw m&&c(),new b("UNAUTHENTICATED","Customer authentication is required",401);let g=(async()=>{try{let d=await e(m.refreshToken);if(f!==r)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");let h=u(d,!0);if(h.customerId!==m.customerId||h.sessionId!==m.sessionId)throw new b("SCOPE_MISMATCH","Refresh changed the customer session");return t=h,{...h}}catch(d){throw f!==r?new b("IDENTITY_CHANGED","Customer identity changed during refresh"):(d instanceof b&&d.status===401&&c(),d)}})();i=g;try{return await g}finally{i===g&&(i=void 0)}}return{identify(m){let f=typeof m=="string"?m:u(m),g=typeof f=="string"?f:f.accessToken;if(!g.trim()||/\s/.test(g)||g.length>4096)throw new b("INVALID_TOKEN","A server-issued token is required");s(f)},reset:c,subscribeIdentity(m,f){return a.set(m,f),()=>{a.delete(m)}},access(){let m=typeof t=="object"?t:void 0;if(m&&Date.parse(m.expiresAt)<=Date.now()+3e4){let g=r;return l().then(()=>{let d=n();if(g!==r||!d)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");return d})}let f=n();if(!f)throw new b("NOT_IDENTIFIED","Identify a customer session before making a request");return f},peek:n,snapshot:()=>typeof t=="object"?{...t}:void 0,refresh:l}}var zh=Symbol("IndianaNoContent");function Ar(e,t,n=In){let r=e.configuration?.scope,i=e.scope??(r&&{projectId:r.projectId,environment:r.environment}),a=i?Fe.parse(i):void 0;if(a&&r&&(a.projectId!==r.projectId||a.environment!==r.environment))throw new b("SCOPE_MISMATCH","Configuration belongs to another App/environment");let o=new n(e.baseUrl??yr);if(o.username||o.password||o.search||o.hash)throw new b("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(o.protocol!=="https:"&&!(o.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(o.hostname)))throw new b("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let s=e.fetch??globalThis.fetch.bind(globalThis),c=e.timeoutMs??1e4;if(!Number.isFinite(c)||c<1||c>12e4)throw new b("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let u=!1,l=0,m=null,f=new Set,g=e.session??Lh(async A=>{let x=await y("customer-sessions/refresh",{},"POST",{},A);if(!x||typeof x!="object")throw new b("INVALID_RESPONSE","Invalid refresh response");let{requestId:v,scope:P,...j}=x;return j});function d(){l+=1,m=null;for(let A of f)A.abort();f.clear()}let h=g.subscribeIdentity(d);function R(){u||g.reset()}async function y(A,x={},v="POST",P={},j){let _=P.installationDetach===!0;if(_&&(A!=="push/installations/detach"||v!=="POST"))throw new b("INVALID_REQUEST","Installation authority only detaches this installation");if(!j&&!_)throw new b("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let X=l,le=new AbortController;_||f.add(le);let he=()=>!_&&X!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new b("TIMEOUT","Longplay request timed out"),ke,Se=new Promise((De,rt)=>{ke=()=>rt(he()),le.signal.addEventListener("abort",ke,{once:!0})}),At=setTimeout(()=>le.abort(),P.timeoutMs??c),We=async()=>{let De=await s(`${o.href.replace(/\/$/,"")}/api/v1/${A}`,{method:v,headers:{...P.headers,"Content-Type":"application/json",..._?{}:{Authorization:`Bearer ${j}`},[Ns]:Ds.current,[Tl]:bh.version,...a?{"X-Indiana-Project":a.projectId,"X-Indiana-Environment":a.environment}:{}},body:v==="POST"?JSON.stringify(x):void 0,signal:le.signal,credentials:"omit",cache:"no-store",redirect:"error",...P.keepalive?{keepalive:!0}:{}});if(le.signal.aborted)throw he();let rt;try{rt=De.status===204?zh:await De.json()}catch{throw le.signal.aborted?he():new b(De.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",De.status,De.headers.get("X-Request-Id")??void 0)}if(le.signal.aborted)throw he();if(!_&&X!==l)throw new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!De.ok){let mt=Ts.safeParse(rt),Qt=mt.success&&(!Gn.safeParse(mt.data.error.code).success||kl(mt.data.error.code,De.status)),Ir=Qt?mt.data.error.code:"HTTP_ERROR",vr=$o(Ir,De.status,{retryAfter:De.headers.get("Retry-After"),recovery:Qt?mt.data.error.recovery:void 0,reason:Qt?mt.data.error.reason:void 0});throw new b(Ir,Qt?mt.data.error.message:"Longplay request failed",De.status,De.headers.get("X-Request-Id")??(mt.success?mt.data.requestId:void 0),{...vr,...mt.success&&mt.data.error.retryable===!1?{retryable:!1}:{},...vr.retryAfterSeconds===void 0&&mt.success&&mt.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:mt.data.error.retryAfterSeconds}:{}})}if(De.headers.get(Ns)!==Ds.current)throw new b("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&rt!==zh){let mt=rt&&typeof rt=="object"&&"scope"in rt?rt:rt&&typeof rt=="object"&&"configuration"in rt?rt.configuration:null;if(!mt||typeof mt!="object"||!("scope"in mt))throw new b("INVALID_RESPONSE","Response is missing its App/environment scope");let Qt=Fe.safeParse(mt.scope);if(!Qt.success||Qt.data.projectId!==a.projectId||Qt.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let ni=De.headers.get("X-Indiana-Telemetry-Subject");if(ni){if(!/^[a-f0-9]{64}$/.test(ni))throw new b("INVALID_RESPONSE","Invalid telemetry identity");m!==ni&&(m=ni,t?.(m))}return rt};try{return await Promise.race([We(),Se])}catch(De){throw!_&&X!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):De instanceof b?De:new b(le.signal.aborted?"TIMEOUT":"NETWORK_ERROR",le.signal.aborted?"Longplay request timed out":"Unable to read the Longplay response")}finally{clearTimeout(At),le.signal.removeEventListener("abort",ke),f.delete(le)}}return{session:g,requestWithCredential(A,x,v,P={}){return u?Promise.reject(new b("CLOSED","SDK client was destroyed")):y(A,x,"POST",P,v)},subjectKey:()=>m,identify(A){if(u)throw new b("CLOSED","SDK client was destroyed");if(a&&typeof A=="object"&&"scope"in A){let x=Fe.safeParse(A.scope);if(!x.success||x.data.projectId!==a.projectId||x.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Customer session belongs to another App/environment")}g.identify(A)},reset:R,dispose(){u||(u=!0,h(),d())},request(A,x={},v="POST",P={}){if(u)return Promise.reject(new b("CLOSED","SDK client was destroyed"));if(P.installationDetach)return y(A,x,v,P);let j=l;try{let _=g.access(),X=le=>{if(j!==l)throw new b("IDENTITY_CHANGED","Customer identity changed before dispatch");return y(A,x,v,P,le)};return typeof _=="string"?X(_):_.then(X)}catch(_){return Promise.reject(_)}}}}function $h(e,t,n={}){let r=!1;function i(){if(r)throw new b("CLOSED","SDK client was destroyed")}let a=new Set,o=c=>{for(let u of a)try{u(c)}catch{}},s=e.session.subscribeIdentity(()=>{o(!!e.session.peek()),n.afterChange?.()},()=>{t()});return{assertActive:i,isIdentified:()=>!r&&!!e.session.peek(),methods:{subscribeIdentity(c){return i(),a.add(c),()=>{a.delete(c)}},identify(c){i();let u=typeof c=="string"?c:c.accessToken;if(!Nt.test(u))throw new b("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(u),e.identify(c)},reset(){if(!r)try{n.beforeReset?.()}finally{e.reset()}},destroy(){if(!r){r=!0,s(),a.clear();try{n.beforeDestroy?.(),t()}finally{e.dispose()}}}}}}function Ge(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new b("INVALID_REQUEST","Customer requests use the verified session identity")}var _v={...O.readHoldings,request:O.readHoldings.request.omit({customerId:!0})};function Gh(e){return{async checkEntitlement(t){Ge(t);let n=O.checkEntitlement;return ge(e,n,t)},async readHoldings(t={}){return ge(e,_v,t)}}}function Kh(e){return{async readLedger(t){let n=O.readLedger;return ge(e,n,{query:t})},async readCreditStatement(t){Ge(t);let n=O.readCreditStatement;return ge(e,n,t)},async quoteBalance(t){Ge(t);let n=O.quoteBalance;return ge(e,n,{command:t})}}}function Hh(e){return{async setupPayment(t){Ge(t);let n=O.setupPayment;return ge(e,n,t)},async readPaymentSetup(t){Ge(t);let n=O.readPaymentSetup;return ge(e,n,t)},async readBillingInvoice(t){Ge(t);let n=O.readBillingInvoice;return ge(e,n,t)},async readBillingControls(t={}){Ge(t);let n=O.readBillingControls;return ge(e,n,t)},async prepareBillingAuthorization(t){Ge(t);let n=O.prepareBillingAuthorization;return ge(e,n,t)},async confirmBillingAuthorization(t){Ge(t);let n=O.confirmBillingAuthorization;return ge(e,n,t)},async setBillingCoupons(t){Ge(t);let n=O.setBillingCoupons;return ge(e,n,t,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(t){Ge(t);let n=O.revokeBillingAuthorization;return ge(e,n,t)},async listBillingInvoices(t={after:null,limit:25}){Ge(t);let n=O.listBillingInvoices;return ge(e,n,t)},async confirmBillingAdjustment(t){Ge(t);let n=O.confirmBillingAdjustment;return ge(e,n,t)}}}function Qh(e){return{async previewUpdate(t){Ge(t);let n=O.previewUpdate;return ge(e,n,t)},async update(t){Ge(t);let n=O.update;return ge(e,n,t)},async readSubscriptionUpdate(t){Ge(t);let n=O.readSubscriptionUpdate;return ge(e,n,t)},async restoreNativePurchase(t){Ge(t);let n=O.restoreNativePurchase;return ge(e,n,t)},async previewAttach(t){Ge(t);let n=O.previewAttach;return ge(e,n,t)},async attach(t){Ge(t);let n=O.attach;return ge(e,n,t)},async readSubscriptionOperation(t){Ge(t);let n=O.readSubscriptionOperation;return ge(e,n,t)}}}function Jh(e){return{async redeemReward(t){return Ge(t),(await ge(e,O.redeemReward,{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(t){return Ge(t),(await ge(e,O.claimRewardProduct,t,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(t){return Ge(t),(await ge(e,O.createReferralCode,{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(t,n=crypto.randomUUID()){let r=await ge(e,O.redeemCoupon,{code:t,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(t,n=crypto.randomUUID()){let r=await ge(e,O.grantOffer,{couponId:t,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await ge(e,O.listOffers,{},{response:"Invalid offers response"})).offers}}}function Zh(e){return{...Gh(e),...Kh(e),...Hh(e),...Qh(e),...Jh(e)}}function Wh(e){return{async resolveContent(t){Ge(t);let n=O.resolveContent;return ge(e,n,t)},async resolvePaywall(t){Ge(t);let n=O.resolvePaywall;return ge(e,n,t)},async resolveOffering(t){Ge(t);let n=O.resolveOffering;return ge(e,n,t)}}}var ml=e=>new TextEncoder().encode(JSON.stringify(e)).length,Yh=16384;function Xh(e,t){let n=0,r,i=d=>{r={config:structuredClone(d),until:Date.now()+3e4}},a=[],o=null,s;function c(){if(!t())throw new b("NOT_IDENTIFIED","Call identify before using Features or events")}function u(){s||!a.length||(s=setTimeout(()=>{s=void 0,m().catch(()=>{}).finally(u)},5e3),typeof s=="object"&&"unref"in s&&s.unref())}function l(d,h={},R={}){if(c(),r&&Date.now()<r.until&&!cf(r.config,d))return;g();let y=O.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:d,properties:h,...R}]}).events[0];if(ml({events:[y]})>Yh)throw new b("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new b("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(y)),u()}async function m(d=!1){if(c(),o)return o;let h=n,R=(async()=>{let y={inserted:0,duplicates:0,rejected:0,skipped:0},A=a.length;for(;A&&h===n;){let x=[],v=ml({events:[]});for(let _ of a.slice(0,Math.min(A,100))){let X=ml(_)+(x.length?1:0);if(x.length&&v+X>Yh)break;x.push(_),v+=X}let P=O.trackEvents,j=await ge(e,P,{events:x},void 0,{keepalive:d});if(h!==n)throw new b("IDENTITY_CHANGED","Event identity changed during delivery");if(j.inserted+j.duplicates+j.rejected+j.skipped!==x.length)throw new b("INVALID_RESPONSE","Incomplete event acknowledgement");i(j.analyticsConfig),a.splice(0,x.length),A-=x.length,y.inserted+=j.inserted,y.duplicates+=j.duplicates,y.rejected+=j.rejected,y.skipped+=j.skipped}return y})();o=R;try{return await R}finally{o===R&&(o=null)}}let f;function g(){if(f||typeof document>"u")return;let d=()=>{document.visibilityState==="hidden"&&t()&&a.length&&m(!0).catch(()=>{})};document.addEventListener("visibilitychange",d),f=()=>document.removeEventListener("visibilitychange",d)}return{rememberConfiguration:i,track:l,flush:m,reset(){n++,r=void 0,clearTimeout(s),s=void 0,a=[],o=null},detachVisibility(){f?.(),f=void 0}}}function Ss(e){let t=null,n=null,r=0,i=0,a=new Set,o=null,s=null,c=new Set,u=()=>{for(let y of c)try{y()}catch{}},l={attributes:Ct.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(y,A)=>{!a.has(y)&&(!t||!("analyticsConfig"in t)||t.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(y,structuredClone(A),structuredClone(l.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(y,A)=>(!t||!("analyticsConfig"in t)||t.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(y),structuredClone(A),structuredClone(l.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?y=>e.saveStickyBucketAssignmentDoc(structuredClone(y)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},m=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function f(y,A=new Set){return a.has(y)?!o||!o.features[y]||["unknownFeature","cyclicPrerequisite"].includes(o.features[y].source):A.has(y)?!1:(A.add(y),(t?.features[y]?.rules??[]).some(x=>[...x.parentConditions??[],...(x.tracks??[]).flatMap(v=>v.experiment.parentConditions??[])].some(v=>f(v.id,A))))}let g=y=>{if(e.assertUsable?.(t?.generation),!t)throw new Error("Initialize the Feature client before evaluation");if(t.expiresAt&&Date.parse(t.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return o?.expiresAt&&Date.parse(o.expiresAt)<=Date.now()&&(o=null,l.features=t.features),a.has(y)?!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now()?m():structuredClone(o.features[y]??m()):e.evaluateRemote&&(l.attributes?.merchandise||l.attributes?.merchandiseId)&&!o||f(y)?m():structuredClone(Hn(y,l))};async function d(){if(!t||!a.size&&!l.attributes?.merchandise&&!l.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(a.size)throw new Error("Remote Feature evaluation requires a server loader");return}let y=i;if(s?.revision===y)return s.loading;let A=r,x=t,v=[...a],P=(async()=>{let j=Va.parse(await e.evaluateRemote({attributes:structuredClone(l.attributes),features:v}));if(!(A!==r||y!==i||x!==t)){if(e.assertUsable?.(x.generation),j.generation!==x.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(v.some(_=>!Object.hasOwn(j.features,_))||Object.keys(j.features).some(_=>!a.has(_)))throw new Error("Invalid remote Feature results");if(l.attributes?.merchandise||l.attributes?.merchandiseId){if(!j.merchandiseContext)throw new Error("Server did not resolve merchandise context");l.attributes=Ct.parse({...l.attributes,...j.merchandiseContext})}o=structuredClone(j),l.features={...x.features,...Object.fromEntries(Object.entries(o.features).map(([_,X])=>[_,{defaultValue:X.value}]))},u()}})();s={revision:y,loading:P};try{await P}finally{s?.loading===P&&(s=null)}}function h(){d().catch(y=>{try{e.onError?.(y)}catch{}})}async function R(){if(n)return n;let y=r,A=(async()=>{let x=await e.load(),v="remoteFeatures"in x?bo.parse(x):null,P=v??bn.parse(x);if(P.scope.projectId!==e.scope.projectId||P.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(y!==r)throw new Error("Feature client was reset");if(e.assertUsable&&t?.generation===P.generation){let{evaluatedAt:_,expiresAt:X,...le}=t,{evaluatedAt:he,expiresAt:ke,...Se}=P;if(Et(le)!==Et(Se))throw new Error("Immutable Feature generation changed content");return t.evaluatedAt=P.evaluatedAt,t.expiresAt=P.expiresAt,u(),(!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())&&h(),structuredClone(t)}let j=new Set(v?.remoteFeatures??[]);if([...j].some(_=>Object.hasOwn(P.features,_)))throw new Error("Remote Feature definitions must not be delivered locally");return t&&"analyticsConfig"in t&&"analyticsConfig"in P&&!t.analyticsConfig.experimentViewsEnabled&&v?.analyticsConfig.experimentViewsEnabled&&l.trackedExperiments?.clear(),t=structuredClone(P),a=j,o=null,s=null,i++,l.features=t.features,l.savedGroups=ci(t.savedGroups),l.trackedFeatureUsage={},u(),h(),structuredClone(t)})();n=A;try{return await A}finally{n===A&&(n=null)}}return{init:R,refresh:R,refreshRemote:d,get generation(){return t?.generation??null},get expiresAt(){return t?.expiresAt??null},subscribe(y){return c.add(y),()=>{c.delete(y)}},setAttributes(y){let A=Ct.parse(y);(l.attributes?.merchandise||l.attributes?.merchandiseId||y.merchandise||y.merchandiseId)&&l.trackedExperiments?.clear(),l.attributes=A,i++,o=null,s=null,l.features=t?.features??{},l.trackedFeatureUsage={},u(),h()},evalFeature:g,isOn(y){return g(y).on},isOff(y){return g(y).off},getFeatureValue(y,A){let x=g(y).value;return structuredClone(x===null?A:x)},reset(){r++,i++,n=null,s=null,t=null,o=null,a.clear(),l.features={},l.savedGroups={},l.stickyBucketAssignmentDocs={},l.attributes={},l.trackedFeatureUsage={},l.trackedExperiments?.clear(),u()}}}function ey(e){let t=e.merchandise;if(typeof e.merchandiseId=="string")return{internalId:e.merchandiseId};if(!(!t||typeof t!="object"||Array.isArray(t))){if(typeof t.internalId=="string")return{internalId:t.internalId};if(typeof t.externalId=="string")return{id:t.externalId};if(typeof t.id=="string")return{id:t.id}}}function Ev(e){let t=ey(e),{merchandiseId:n,merchandise:r,...i}=e;return{...i,...t?{merchandise:t}:{}}}function ty(e,t,n,r,i){if(i&&r&&(i.scope.projectId!==r.projectId||i.scope.environment!==r.environment))throw new b("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,o=new Set;function s(){if(!t())throw new b("NOT_IDENTIFIED","Call identify before using Features or events")}async function c(u={}){i||s();let l=a,m=!1,f=async()=>{if(m||l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let he=O.getFeatures,ke=i?{scope:{projectId:i.scope.projectId,environment:i.scope.environment},payload:await i.features()}:await ge(e,he,{});if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");if(r&&(ke.scope.projectId!==r.projectId||ke.scope.environment!==r.environment))throw new b("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(ke.payload.analyticsConfig),ke},g=await f(),d=!0,h,R=he=>{try{u.onError?.(he)}catch{}},y=(he,ke,Se)=>{try{let At=ey(Se);n.track(he,ke,At?{merchandise:At}:{})}catch(At){R(At)}},A=Ss({assertUsable:i?.assertFeatures,scope:g.scope,attributes:u.attributes,onError:u.onError,load:async()=>d?(d=!1,g.payload):(await f()).payload,evaluateRemote:async he=>{if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let ke=O.evaluateFeatures,Se=await ge(e,ke,{...he,attributes:Ev(he.attributes)});if(Se.scope.projectId!==g.scope.projectId||Se.scope.environment!==g.scope.environment)throw new b("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:Se.generation,evaluatedAt:Se.evaluatedAt,expiresAt:Se.expiresAt,features:Se.features,...Se.merchandiseContext?{merchandiseContext:Se.merchandiseContext}:{}}},onExperimentViewed:(he,ke,Se)=>y("Experiment Viewed",{experimentId:he.key,variationId:ke.key},Se),onFeatureUsage:(he,ke,Se)=>y("Feature Evaluated",{feature:he,value:ke.value,source:ke.source,ruleId:ke.ruleId,...ke.experimentResult?{variationId:ke.experimentResult.key}:{}},Se)}),x=A.refresh;function v(){clearTimeout(h),!i&&(m||l!==a||!A.expiresAt||(h=setTimeout(()=>{P().catch(R)},Math.min(2147483647,Math.max(1e3,Date.parse(A.expiresAt)-Date.now()))),typeof h=="object"&&"unref"in h&&h.unref()))}async function P(){try{return await x()}finally{v()}}let j=()=>{m||P().catch(R)},_=A.subscribe(v),X=i?.subscribe(()=>{!m&&i.fresh&&P().catch(R)});function le(){m||(m=!0,clearTimeout(h),typeof window<"u"&&window.removeEventListener("focus",j),_(),X?.(),A.reset(),o.delete(le))}o.add(le);try{await A.init(),(u.attributes?.merchandise||u.attributes?.merchandiseId)&&await A.refreshRemote()}catch(he){throw le(),he}return v(),!i&&typeof window<"u"&&window.addEventListener("focus",j),Object.assign(A,{refresh:P,destroy:le})}return{features:c,reset(u){a++,u();for(let l of o)l()}}}var ny=require("zod");function ry(e,t){let n="source"in t?{funnelId:t.source.id,funnelVersionId:t.source.versionId}:"versionId"in t?{funnelId:t.funnelId,funnelVersionId:t.versionId}:t,r=ny.z.object({funnelId:us.shape.id,funnelVersionId:us.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new b("INVALID_REQUEST","A valid Funnel source is required");let i=Object.freeze(r.data);function a(o){if("customerId"in o)throw new b("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in o&&o.funnelId!==void 0&&o.funnelId!==i.funnelId||"funnelVersionId"in o&&o.funnelVersionId!==void 0&&o.funnelVersionId!==i.funnelVersionId)throw new b("SCOPE_MISMATCH","The original Funnel source cannot change");return{...o,...i}}return{async claimCoupon(o,s=crypto.randomUUID()){let c=O.grantOffer,u=await ge(e,c,a({couponId:o,requestId:s}));return{offer:u.offer,reason:u.reason}},async resolveOffering(o){let s=O.resolveOffering;return ge(e,s,a(o))},async resolvePaywall(o){let s=O.resolvePaywall;return ge(e,s,a(o))},async previewAttach(o){let s=O.previewAttach;return ge(e,s,a(o))}}}function iy(e){let t=Ar(e),n=t.request,r;try{r=gh(e.push,t,e.scope??e.configuration?.scope)}catch(s){throw t.dispose(),s}let i=$h(t,()=>{o.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=Xh(n,i.isIdentified),o=ty(n,i.isIdentified,a,e.scope,e.configuration);return{session:t.session,...Ah(n,r),...Zh(n),...Wh(n),forFunnel(s){return i.assertActive(),ry(n,s)},async features(s={}){return i.assertActive(),o.features(s)},track(s,c,u={}){return a.track(s,c,u)},flush(){return a.flush()},...i.methods}}function Fi(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,a)=>Fi(i,t[a]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let n=Object.entries(e),r=Object.entries(t);return n.length===r.length&&n.every(([i,a])=>Object.hasOwn(t,i)&&Fi(a,Reflect.get(t,i)))}function Is(e,t){let n=Yg.safeParse(t);if(!n.success)throw new b("INVALID_RESPONSE","Funnel response contract changed");let r=n.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new b("SCOPE_MISMATCH","Funnel scope changed");return r}var Mi=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function vs(e){let t=Nt.test(e.apiKey);if(typeof window<"u"&&!t)throw new b("SERVER_ONLY","Funnel starts are issued by your backend");if(!t&&!Mi.test(e.apiKey))throw new b("INVALID_TOKEN","A customer credential or server API key is required");return{async start(n){let r=_t.safeParse({...n,operation:"start"});if(!r.success||r.data.operation!=="start"||(t?r.data.customer!==void 0:r.data.customer===void 0))throw new b("INVALID_REQUEST","Invalid current Funnel start");let i=r.data,a=Ar({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||a.identify(e.apiKey);let o=Is(e,await a.request("funnels",i));if(!o.runToken)throw new b("INVALID_RESPONSE","Funnel start credentials are missing");if(o.run.source.id!==i.funnelId||o.run.locale!==(i.locale??"en")||!Fi(o.run.parameters,i.parameters??{})||(i.customer?!o.customerId||i.customer.type==="id"&&o.customerId!==i.customer.value:o.customerId!==void 0))throw new b("INVALID_RESPONSE","Funnel start contract changed");return{...o,runToken:o.runToken}}finally{a.dispose()}}}}async function fl(e,t,n){if(Number(e.headers.get("content-length"))>t)throw e.body?.cancel().catch(()=>{}),n.error("limit");let r=e.body?.getReader();if(!r)throw n.error("missing");let i=[],a=0,o=!1,s=()=>{},c=new Promise((m,f)=>{s=()=>f(n.signal?.reason),n.signal?.addEventListener("abort",s,{once:!0}),n.signal?.aborted&&s()});try{for(;;){let m=await Promise.race([r.read(),c]);if(m.done){o=!0;break}if(a+=m.value.length,a>t)throw n.error("limit");i.push(m.value)}}finally{n.signal?.removeEventListener("abort",s),o||r.cancel().catch(()=>{}),r.releaseLock()}n.signal?.throwIfAborted();let u=new Uint8Array(a),l=0;for(let m of i)u.set(m,l),l+=m.length;return u}async function oy(e,t,n){return new TextDecoder("utf-8",{fatal:!0}).decode(await fl(e,t,n))}function ws(e,t){let n=typeof e=="string"?new TextEncoder().encode(e):e;return n.byteLength===t.byteLength&&Pu(n)===t.sha256}async function Os(e,t){let n=Jr.parse(t),{artifact:r,environmentId:i}=n.content,a=new In(e.baseUrl??yr).origin,o=new In(r.url,a);if(o.origin!==a||o.username||o.password||o.search||o.hash||o.pathname!==`/api/v1/configuration/${i}/artifacts/${r.sha256}`)throw new b("INVALID_RESPONSE","Public Paywall locator is not trusted");let s=new AbortController,c,u=new Promise((m,f)=>{c=setTimeout(()=>{let g=new b("TIMEOUT","Public Paywall read timed out");s.abort(g),f(g)},nn.initializationMs)}),l=(async()=>{let m=await(e.fetch??globalThis.fetch)(o,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:s.signal});if(s.signal.aborted&&(m.body?.cancel().catch(()=>{}),s.signal.throwIfAborted()),!m.ok||!m.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(m.headers.get("content-length"))>r.byteLength)throw m.body?.cancel().catch(()=>{}),new b("INVALID_RESPONSE","Public Paywall is unavailable");let f=await fl(m,r.byteLength,{signal:s.signal,error:g=>new b("INVALID_RESPONSE",g==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!ws(f,r))throw new b("INVALID_RESPONSE","Public Paywall digest or size changed");return og(n,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(f)))})();try{return await Promise.race([l,u])}finally{clearTimeout(c)}}var ay=(e,t)=>new b(e,t);async function gl(e,t,{predict:n=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new b("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new b("SCOPE_MISMATCH","Evaluation environment changed");let i=null,a;if(n)try{let o=await e.funnel(t.source.id,t.source.versionId);a=o.manifest.generation,i=Rv(e,t,o)}catch{i=null}return a??(a=e.snapshot?.generation??(await e.refresh()).generation),{advance:{policyRevision:r.policyRevision,generation:a},prediction:i}}function Rv(e,t,n){let r=t.instruction;if(r?.type!=="evaluate_segment"||!n.growth||n.control.evaluationMode!=="local"||n.control.evaluationRevision!==r.policyRevision)return null;let{analyticsConfig:i,remoteFeatures:a,...o}=n.growth,s=$u({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t.source.id,versionId:t.source.versionId,evaluationMode:"local",evaluationRevision:r.policyRevision,document:n.document,payload:bn.parse(o)}),c=kv(s,n.document,{...t,...r}),u=c.steps.at(-1),l=c.boundary??(u?.result.port==="value"?{nodeId:u.nodeId,visit:t.visit+c.steps.length-1}:null);return l?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:l.nodeId,visit:l.visit,terminal:!c.boundary}:null}function kv(e,t,n){return fh(e,t,n,ay)}var an=require("zod");var sy=_t.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new b("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),cy=an.z.strictObject({schemaVersion:an.z.literal(1),scope:Fe,runId:an.z.uuid(),funnelId:an.z.uuid(),versionId:an.z.uuid(),processBindingIds:an.z.record(an.z.uuid(),an.z.uuid().nullable()).optional(),command:sy.optional(),closeCommand:sy.refine(e=>e.operation==="close").optional(),purchase:an.z.strictObject({receiptId:an.z.uuid(),operationId:an.z.uuid(),generation:an.z.number().int().nonnegative()}).optional(),closed:an.z.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),Xt=()=>new b("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Ps=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function uy(e){let t=0,n=null,r=u=>JSON.stringify([u.scope,u.runId,u.funnelId,u.versionId]),i=Promise.resolve();async function a(){let u=await e.read();if(!Number.isSafeInteger(u.revision)||u.revision<0)throw new b("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:u.revision,entry:u.entry===null?null:cy.parse(u.entry)}}function o(u){let l=i.then(u);return i=l.catch(()=>{}),l}async function s(u){for(let l=0;l<4;l++){let m=await a();if(m.entry&&n!==null&&r(m.entry)!==n)throw Xt();let f=u(m.entry,m.revision);if(Ps(m.entry,f)){t=m.revision;return}let g=await e.write(m.revision,f);if(g!==null){if(!Number.isSafeInteger(g)||g<=m.revision)throw Xt();t=g;return}}throw Xt()}function c(u,l){if(!u||!l)return u;if(u.processBindingIds&&Object.hasOwn(u.processBindingIds,l)){let m={...u.processBindingIds};delete m[l],u={...u,processBindingIds:m}}return u.command?.requestId===l?u.closeCommand?{...u,command:u.closeCommand,closeCommand:void 0}:u.purchase?{...u,command:void 0}:null:u.closeCommand?.requestId===l?{...u,closeCommand:void 0}:u}return{bind(u){let l=JSON.stringify([u.scope,u.runId,u.funnelId,u.versionId]);if(n!==null&&n!==l)throw Xt();n=l},async load(){let u=await a();return t=u.revision,n=u.entry?r(u.entry):null,u.entry},retain(u){let l=cy.parse(u),m=l.command;return!m||n!==null&&r(l)!==n?Promise.reject(Xt()):(n??(n=r(l)),o(()=>s((f,g)=>{if(f&&!Ps(r(f),r(l)))throw Xt();if(f&&l.processBindingIds){for(let[d,h]of Object.entries(l.processBindingIds))if(f.processBindingIds&&Object.hasOwn(f.processBindingIds,d)&&f.processBindingIds[d]!==h)throw Xt();f={...f,processBindingIds:{...f.processBindingIds,...l.processBindingIds}}}if(!f){if(g!==t&&m.operation!=="close")throw Xt();return l}if(!f.command)return{...f,command:m,...m.operation==="close"?{closed:!0}:{}};if(m.operation==="close"&&f.command.operation!=="close"){if(f.command.requestId===m.requestId||f.closeCommand&&!Ps(f.closeCommand,m))throw Xt();return{...f,closeCommand:m,closed:!0}}if(!Ps(f.command,m))throw Xt();return f})))},observePurchase(u,l,m,f){return o(()=>s((g,d)=>{if(!g&&d!==t||g&&r(g)!==r({...u,schemaVersion:1}))throw Xt();if(g?.purchase&&g.purchase.generation>l.generation)return c(g,f);if(g?.purchase&&g.purchase.generation===l.generation&&g.purchase.operationId!==l.operationId)throw Xt();return m?!g?.purchase||g.purchase.operationId!==l.operationId?c(g,f):c(g.command?{...g,purchase:void 0}:null,f):c({schemaVersion:1,...u,...g,purchase:l},f)}))},settle(u){return o(()=>s(l=>c(l,u)))}}}function ly(e){let t,n,r=()=>new b("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,n=e.locks??globalThis.navigator?.locks,!t||!n||!globalThis.crypto?.subtle)throw r();let s=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??yr).href,e.runToken])),c=new Uint8Array(await crypto.subtle.digest("SHA-256",s));return"indiana.funnel.commands.v1."+Array.from(c,u=>u.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function a(s){try{let c=await i;return await n.request(c,{mode:"exclusive"},()=>s(c))}catch(c){throw c instanceof b?c:r()}}function o(s){let c=t.getItem(s);if(c===null)return{revision:0,entry:null};if(c.length>1048576)throw r();let u=JSON.parse(c);if(!u||typeof u!="object"||!("revision"in u)||!("entry"in u)||!Number.isSafeInteger(u.revision)||Number(u.revision)<0)throw r();return{revision:Number(u.revision),entry:u.entry}}return{read:()=>a(o),write:(s,c)=>a(u=>{if(o(u).revision!==s)return null;if(!Number.isSafeInteger(s+1))throw r();return t.setItem(u,JSON.stringify({revision:s+1,entry:c})),s+1})}}function dy(e,t){let n=t&&{...t},r=null,i=0,a=new AbortController;function o(){i++,a.abort(new b("IDENTITY_CHANGED","Run identity changed")),a=new AbortController}let s=!1,c,u=0,l=new Set;return{get scope(){return n},bindScope(m){if(n&&(n.projectId!==m.projectId||n.environment!==m.environment))throw new b("SCOPE_MISMATCH","Run scope changed");n??(n={...m})},get view(){return r},get generation(){return i},get signal(){return a.signal},get disposed(){return s},get customerToken(){return c},get readSequence(){return u},nextRead(){return++u},assertCurrent(m,f="Run identity changed during the request"){if(m!==i||s)throw new b("IDENTITY_CHANGED",f)},assertRun(m){if(r&&(m.id!==r.id||m.source.type!==r.source.type||m.source.id!==r.source.id||m.source.versionId!==r.source.versionId||m.locale!==r.locale||!Fi(m.parameters,r.parameters)))throw new b("INVALID_RESPONSE","Run version changed");if(e&&m.source.id!==e)throw new b("INVALID_RESPONSE","Run belongs to another Funnel")},publish(m,f,g,d,h){if(!(m.operation==="review"&&r&&r!==g&&f.run.revision<=r.revision)&&!(r&&f.run.revision===r.revision&&d!==void 0&&d<u)&&(m.operation==="review"&&!f.run.stopped&&["running","waiting"].includes(f.run.status)&&r&&f.run.nodeId===r.nodeId&&f.run.visit===r.visit&&f.run.revision===r.revision&&(f.run.screen=r.screen,(r.paywall?.quote?.operationId===f.review?.activeOperationId||!r.paywall?.quote&&f.review?.activeOperationId===null)&&(f.run.paywall=r.paywall)),!(r?.paywall&&f.run.paywall&&r.paywall.receiptId===f.run.paywall.receiptId&&(f.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||f.run.revision>=r.revision)r=f.run;else if(!h)return;if(r)for(let R of l)try{R(structuredClone(r))}catch{}}},identify(m){if(s)throw new b("IDENTITY_CHANGED","Controller was reset");if(!Nt.test(m))throw new b("INVALID_TOKEN","Customer credential required");o(),c=m},subscribe(m){return l.add(m),()=>l.delete(m)},reset(){s||(s=!0,o(),c=void 0,r=null,l.clear())}}}function br(e){let{customerToken:t,...n}=e;return n}var jv=e=>!(e instanceof b)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function py({journal:e,state:t,call:n,processIdentity:r}){let i=null,a=null,o=!1,s={command:null,close:null},c=new Set,u,l=null,m=e?e.load().then(y=>{if(t.disposed)throw new b("IDENTITY_CHANGED","Controller was reset during command restoration");if(l=y,!y)return;if(r){if([y.command,y.closeCommand].some(x=>x&&!Object.hasOwn(y.processBindingIds??{},x.requestId)))throw new b("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(y.processBindingIds??{})}if(t.scope&&(y.scope.projectId!==t.scope.projectId||y.scope.environment!==t.scope.environment))throw new b("SCOPE_MISMATCH","Pending command belongs to another scope");if(u=y.purchase,o=y.closed===!0,!y.command)return;let A=y.command;i=A.operation==="close"?null:A,a=A.operation==="close"?A:y.closeCommand?.operation==="close"?y.closeCommand:null,a&&(o=!0);for(let x of[i,a])x&&c.add(x.requestId)}):Promise.resolve();m.catch(()=>{});async function f(y){e&&await m;let A=t.generation;if(e){if(!t.view||!t.scope)throw new b("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:br(y),...r?{processBindingIds:{[y.requestId]:r.binding(y.requestId)}}:{}})}if(A!==t.generation||i!==y&&a!==y)throw new b("IDENTITY_CHANGED","Run changed before command dispatch");let x=c.has(y.requestId);c.add(y.requestId);try{return await n(y)}catch(v){throw A===t.generation&&(i===y||a===y)&&!x&&!jv(v)&&(e&&await e.settle(y.requestId),A===t.generation&&R(y)),v}}function g(y){let A=_t.parse(y);if(A.operation==="start"||A.operation==="get"||A.operation==="review")throw new b("INVALID_REQUEST","Mutation required");if(o&&A.operation!=="close"){if(i?.requestId===A.requestId)return h(A.requestId);throw new b("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(A.operation==="close"){if(i?.requestId===A.requestId)throw new b("INVALID_REQUEST","Close requires its own request identity");if(o=!0,a&&JSON.stringify(br(a))!==JSON.stringify(br(A)))throw new b("COMMAND_PENDING","Retry the original Close");return a??(a=A),s.close?s.close:d(a,"close")}if(i){if(JSON.stringify(br(i))!==JSON.stringify(br(A)))throw new b("COMMAND_PENDING","Retry the original command before sending another");if(s.command)return s.command}else i=A;return d(i,"command")}function d(y,A){let x=f(y);s[A]=x;let v=()=>{s[A]===x&&(s[A]=null)};return x.then(v,v),x}function h(y){return n({operation:"get",settlementRequestId:y})}function R(y){return!y||i!==y&&a!==y?!1:(i===y&&(i=null),a===y&&(a=null),c.delete(y.requestId),!i&&!a&&(l=null),!0)}return{ready:m,get pending(){return i},get closing(){return a},get closeRequested(){return o},get inFlight(){return s.command},get closeFlight(){return s.close},get purchase(){return u},assertBinding(y){if(l&&(y.run.id!==l.runId||y.run.source.id!==l.funnelId||y.run.source.versionId!==l.versionId))throw new b("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(y,A,x,v){let P=y.operation==="get"?y.settlementRequestId:"requestId"in y&&y.operation!=="start"?y.requestId:void 0,j=P&&A.settlement?.state==="settled"&&A.run.pendingRequest?.requestId!==P&&(y.operation==="get"||!o||y.operation==="close"||!["running","waiting"].includes(A.run.status))?P:void 0,_=i?.requestId===j?i:a?.requestId===j?a:void 0;e?.bind({scope:A.scope,runId:A.run.id,funnelId:A.run.source.id,versionId:A.run.source.versionId});let X=A.run.paywall,le=X??A.purchase,he=le?.operation,ke=A.settlement&&(!X||X.purchaseRequestId===A.settlement.requestId)&&(!u||u.operationId===A.settlement.operationId)?A.settlement:void 0,Se=he?.operationId??le?.quote?.operationId??ke?.operationId,At=le?.receiptId??ke?.receiptId,We=X?.selectionGeneration??u?.generation??0;if(e&&Se&&At&&y.operation!=="review"&&(!t.view||A.run.revision>=t.view.revision)&&(v===void 0||v>=t.readSequence)&&(!u||We>=u.generation)){let De={receiptId:At,operationId:Se,generation:We},rt=he?.status==="complete"||le?.canReselect===!0;await e.observePurchase({scope:A.scope,runId:A.run.id,funnelId:A.run.source.id,versionId:A.run.source.versionId},De,rt,j),t.assertCurrent(x),(!u||De.generation>=u.generation)&&(v===void 0||v>=t.readSequence)&&(rt?u?.operationId===De.operationId&&(u=void 0):u=De)}else e&&j&&await e.settle(j);return t.assertCurrent(x),j?R(_):!1},stop(){o=!0},submit:g,settle:h,reset(){o=!0,i=null,a=null,u=void 0,l=null,s.close=null,c.clear(),s.command=null}}}function xr(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new b("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!Mi.test(e.serverKey)))throw new b("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new b("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let t=Ar({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),n=dy(e.funnelId,e.scope??e.configuration?.scope),r=e.session?.subscribeIdentity(u),i=null,a=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?ly(e):void 0),o=a&&uy(a),s=py({journal:o,state:n,call:l,processIdentity:e.process});async function c(A){if(e.process)return e.process.request(A);let x=n.generation;n.assertCurrent(x);let v=performance.now()+(e.timeoutMs??35e3),P=n.customerToken??("customerToken"in A?A.customerToken:void 0);if(e.session){let X=n.signal,le,he=()=>{},ke=new Promise((Se,At)=>{he=()=>At(X.reason),X.addEventListener("abort",he,{once:!0}),le=setTimeout(()=>At(new b("TIMEOUT","Longplay request timed out")),Math.max(1,v-performance.now()))});try{P=await Promise.race([Promise.resolve().then(()=>(n.assertCurrent(x),e.session.access())),ke])}finally{clearTimeout(le),X.removeEventListener("abort",he)}}n.assertCurrent(x);let j={...A,...P?{customerToken:P}:{}},_=A.operation==="page_experiments"?ko.parse(j):_t.parse(j);return t.requestWithCredential("funnels",_,e.runToken,{headers:e.serverKey&&!P?{[Xg]:e.serverKey}:void 0,timeoutMs:Math.max(1,v-performance.now())})}function u(){r?.(),n.reset(),s.reset(),i=null,t.dispose()}async function l(A,x){let v=n.generation,P=()=>n.assertCurrent(v);o&&await s.ready,P();let j=n.view,_=Is(e,await c(A));if(A.operation==="review"&&!_.review)throw new b("INVALID_RESPONSE","Historical projection is missing");if(P(),_.runToken&&_.runToken!==e.runToken)throw new b("INVALID_RESPONSE","Run credential changed");let X=A.operation==="get"?A.settlementRequestId:"requestId"in A&&A.operation!=="start"?A.requestId:void 0;if(X&&_.settlement?.requestId!==X)throw new b("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");s.assertBinding(_),n.assertRun(_.run),n.bindScope(_.scope);let le=await s.observe(A,_,v,x);return!_.run.stopped&&["running","waiting"].includes(_.run.status)&&A.operation==="get"&&A.settlementRequestId||(P(),["running","waiting"].includes(_.run.status)||s.stop(),n.publish(A,_,j,x,le)),_}let m=s.submit,f=null,g=new WeakMap;function d(A){let x=g.get(A);if(x)return x;let v=R(A);return g.set(A,v),v}let h=!1;async function R(A){let x=await A;if(x.run.instruction?.type!=="evaluate_segment")return x;if(f)return f;h=!0;let v=n.generation,P=(async()=>{for(let j=0;j<32&&x.run.instruction?.type==="evaluate_segment";j++){if(s.pending||s.closeRequested)return x;let _=x.run;if(x.run.instruction?.type==="evaluate_segment"){let{advance:le}=await gl(e.configuration,_,{predict:!1});if(v!==n.generation)throw new b("IDENTITY_CHANGED","Run identity changed during segment calculation");if(s.pending||s.closeRequested)return x;if(n.view&&(n.view.revision!==_.revision||n.view.visit!==_.visit||n.view.nodeId!==_.nodeId))return l({operation:"get"});let he=!0;gl(e.configuration,_).then(({prediction:ke})=>{he&&v===n.generation&&!s.closeRequested&&n.view?.id===_.id&&!n.view.stopped&&n.view.nodeId===_.nodeId&&n.view.visit===_.visit&&n.view.revision===_.revision&&(i=ke)}).catch(()=>{});try{x=await m({operation:"commit_segment",requestId:Wg(_.id,_.visit,`segment:${_.revision}`),nodeId:_.nodeId,visit:_.visit,revision:_.revision,...le})}finally{he=!1,i=null}}}return x})();f=P;try{return await P}finally{f===P&&(f=null)}}let y={get configuration(){return h?e.configuration:void 0},get configurationReady(){return!0},get view(){return n.view?structuredClone(n.view):null},get pendingCommand(){let A=s.closing??s.pending;return A?structuredClone(br(A)):null},get pendingCommands(){return[s.pending,s.closing].filter(A=>A!==null).map(A=>structuredClone(br(A)))},get pendingPurchase(){return s.purchase?structuredClone(s.purchase):null},get hasDurableJournal(){return o!==void 0},get prediction(){let A=n.view;return i&&A&&!A.stopped&&["running","waiting"].includes(A.status)&&A.id===i.runId&&A.nodeId===i.from.nodeId&&A.visit===i.from.visit&&A.revision===i.from.revision&&!s.closeRequested?structuredClone(i):null},settle:s.settle,get webViewUrl(){return"bundled"},resolvePaywall(A){return Os(e,A)},async pageExperiments(A,x=[]){let v=n.generation;n.assertCurrent(v);let P=n.view?.id;if(!P)throw new b("INVALID_REQUEST","Read the Run before its page experiments");let j=rh.parse(await c(ko.parse({operation:"page_experiments",release:A,usedReceiptIds:x})));if(n.assertCurrent(v),j.runId!==P||j.scope.projectId!==n.scope?.projectId||j.scope.environment!==n.scope?.environment)throw new b("SCOPE_MISMATCH","Page experiment Run changed");return j},review(A){return l({operation:"review",...A?{receiptId:A}:{}},n.nextRead())},async get(A,x){o&&await s.ready,x??(x=s.purchase&&{receiptId:s.purchase.receiptId,operationId:s.purchase.operationId});let v=n.nextRead();return d(l({operation:"get",...A?{data:A}:{},...x?{purchase:x}:{}},v))},resume(A=n.view?.pendingRequest?.requestId){return A?s.closeRequested?y.settle(A):s.pending?.requestId===A?d(m(s.pending)):d(m({operation:"resume",requestId:A})):Promise.reject(new b("INVALID_REQUEST","No interrupted command is available"))},submit(A){return d(m(A))},retry(){return s.closeFlight?s.closeFlight:s.closing?m(s.closing):s.closeRequested&&s.pending?y.settle(s.pending.requestId):s.inFlight?d(s.inFlight):s.pending?d(m(s.pending)):Promise.reject(new b("INVALID_REQUEST","No command is pending"))},identify(A){n.identify(A),i=null,t.reset()},subscribe:n.subscribe,reset:u};return y}function my(e){if(!Nt.test(e.customerToken))throw new b("INVALID_TOKEN","A customer credential is required");if(!e.scope)throw new b("INVALID_REQUEST","An explicit App and environment scope is required");let t=vs({...e,scope:e.scope,apiKey:e.customerToken});return{async start(n){let r=await t.start(n),i=xr({...e,runToken:r.runToken});i.identify(e.customerToken);let a=r.run.instruction?.type==="evaluate_segment"?await i.get():r;return{...r,...a,controller:i}}}}function fy(e,t){let n=r=>"document"in r?r.offering.id:r.content.offeringVersionId;return e.id===t.id&&n(e)===n(t)&&e.content?.artifact.sha256===t.content?.artifact.sha256}function gy(e,t,n){if(e.operationId!==t.operationId||t.currency!==void 0&&e.currency!==t.currency)throw new b("INVALID_RESPONSE",n)}function hy(e,t,n){let r=Object.fromEntries((e.lines[0]?.prepaid??[]).map(i=>[i.internal_feature_id,i.quantity]));if(t.featureQuantities&&(Object.keys(r).length!==Object.keys(t.featureQuantities).length||Object.entries(t.featureQuantities).some(([i,a])=>r[i]!==a)))throw new b("INVALID_RESPONSE","The purchase quote changed its selected quantities");if(e.lines.length!==1||e.lines[0].productVersionId!==t.productVersionId||t.currency!==void 0&&e.currency!==t.currency||t.provider!==void 0&&e.provider!==t.provider&&!(t.provider==="stripe"&&e.provider==="merchant"&&e.execution?.provider==="merchant"))throw new b("INVALID_RESPONSE",n)}function yy(e,t,n=!1){return!e||e.operationId!==t?.operationId?t:e.status==="complete"&&t.status!=="complete"||e.status!=="pending"&&(t.status==="pending"||n&&t.status!=="complete")?e:t}function Ay(e){let{quote:t,operation:n,requestId:r}=e,a={type:"recover",operationId:n?.operationId??t?.operationId??null,requestId:r};if(e.destroyed||e.pending)return a;if(!n)return t?{type:"cancel",operationId:t.operationId}:a;let o=n.merchantExecution;if(o?.type==="purchase"){if(["succeeded","not_required"].includes(o.paymentStatus))return!["applied","not_applicable"].includes(o.fulfillmentStatus)||n.problem?.phase==="fulfillment"||o.problem?.phase==="fulfillment"?{type:"fulfillment",operationId:n.operationId}:{type:o.recordingStatus==="accepted"&&n.status==="complete"?"complete":"recording",operationId:n.operationId};if(n.status==="pending"&&n.checkoutUrl&&o.checkoutUrl===n.checkoutUrl&&o.checkoutExpiresAt&&Date.parse(o.checkoutExpiresAt)>Date.now()&&["not_started","pending"].includes(o.paymentStatus))return{type:"checkout",operationId:n.operationId,checkoutUrl:n.checkoutUrl}}let s=[n.problem,o?.problem],c=s.every(u=>!u||u.phase==="execution"&&u.reason!=="RESULT_UNKNOWN");return!s.some(Boolean)&&n.status==="complete"&&n.executor!=="merchant"?{type:"complete",operationId:n.operationId}:c&&e.canReselect!==!1&&["cancelled","failed"].includes(n.status)&&!n.checkoutUrl&&!n.execution&&!n.nativePurchase&&(n.executor!=="merchant"?!n.confirmedAt&&(n.status==="cancelled"||!n.quoteFinalized):!o&&!n.quoteFinalized||o?.type==="purchase"&&["failed","expired"].includes(o.paymentStatus)&&o.fulfillmentStatus==="not_applicable"&&o.recordingStatus==="accepted")?{type:"native",operationId:n.operationId}:n.status==="pending"&&c&&!n.quoteFinalized&&!o&&!n.checkoutUrl&&!n.execution&&!n.nativePurchase?{type:"cancel",operationId:n.operationId}:a}async function by(e,t){if(!Nt.test(t.customerToken))throw new b("INVALID_TOKEN","A verified Customer credential is required");if(e.session&&e.session.peek()!==t.customerToken)throw new b("SCOPE_MISMATCH","Paywall credential does not match the shared session");let n=O.resolvePaywall.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale,...t.requirement?{requirement:t.requirement}:{}}),r=Ar(e);e.session||r.identify(t.customerToken);let i=null,a=!1,o=null,s=null,c=null,u=null,l=null,m=null,f=null,g=0;function d(){if(a)throw new b("IDENTITY_CHANGED","Paywall is closed")}async function h(){d();let x=O.resolvePaywall,v=await ge(r.request,x,{...n,selector:i?{type:"version",versionId:i.id}:n.selector}),P=await Os(e,v.paywall);if(d(),t.paywallVersionId?P.id!==t.paywallVersionId:P.paywallId!==t.paywallId)throw new b("INVALID_RESPONSE","The requested Paywall changed");if(i&&(!fy(P,i)||P.paywallId!==i.paywallId))throw new b("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return i=P,structuredClone(i)}async function R(x){if(d(),u&&x!=="read")throw new b("COMMAND_PENDING","Wait for the original quote");if(!o)throw new b("INVALID_REQUEST","A quoted purchase is required");let v=o;if(x!=="read"){if(f){if(m===x)return f;throw new b("COMMAND_PENDING","Wait for the original purchase command")}if(m&&m!==x)throw new b("COMMAND_PENDING","Read the original purchase before changing an uncertain command");m=x,g++}let P=m,j=g,_=x==="read"&&f===null,X=x==="read"?O.readSubscriptionOperation:O.attach,le=(async()=>{let he=await ge(r.request,X,{operationId:v.operationId,...x==="read"?{}:{intent:x}});return gy(he.operation,{operationId:v.operationId,currency:n.commerce.currency},"The purchase operation changed"),d(),o?.operationId!==v.operationId?structuredClone(he.operation):(s=yy(s,he.operation),(x!=="read"||_&&f===null)&&g===j&&m===P&&(m=null),structuredClone(s))})();if(x!=="read"){f=le;let he=()=>{f===le&&(f=null)};le.then(he,he)}return le}let y={get view(){return i?structuredClone(i):null},get quote(){return o?structuredClone(o):null},get operation(){return s?structuredClone(s):null},get webViewUrl(){return"bundled"},get recovery(){return Ay({quote:o,operation:s,requestId:l,pending:u!==null||m!==null,destroyed:a})},get pendingCancellation(){return!a&&m==="cancel"},refresh:h,async preview(x){if(d(),!i)throw new b("INVALID_REQUEST","Load the Paywall first");let v=i.document.buttons[x.actionId];if(v?.type!=="checkout")throw new b("INVALID_REQUEST","Choose an authored purchase action");let P=of(v.product,x.selection,i.capabilities);if(!P)throw new b("PRODUCT_UNAVAILABLE","Choose an available Product");let j=Zf(i.document.screen,P,x.selection,i.capabilities),_=O.previewAttach.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,requestId:x.requestId,plans:[{productVersionId:P,...Object.keys(j).length?{featureQuantities:j}:{}}],provider:n.commerce.provider,currency:n.commerce.currency,...x.offerId?{offerId:x.offerId}:{},...x.nativeOffer?{nativeOffer:x.nativeOffer}:{}}),X=JSON.stringify(_);if(c&&c!==X&&(u||m||!s||s.status==="pending"))throw new b("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(c===X){if(u)return u;if(o)return structuredClone(o)}c!==X&&(o=null,s=null),c=X,l=_.requestId;let le=(async()=>{let he=O.previewAttach,ke=await ge(r.request,he,_);return d(),hy(ke.quote,{productVersionId:P,featureQuantities:j,currency:n.commerce.currency,provider:n.commerce.provider},"The purchase quote changed its selected Product or presentment"),o=ke.quote,s=null,structuredClone(o)})();u=le;try{return await le}finally{u===le&&(u=null)}},confirm:()=>R("confirm"),cancel:()=>R("cancel"),read:()=>R("read"),destroy(){a||(a=!0,A?.(),r.dispose(),i=null,o=null,s=null,c=null,l=null)}},A=e.session?.subscribeIdentity(y.destroy);try{return await h(),y}catch(x){throw y.destroy(),x}}function xy(e,t){let n,r=0,i=-1,a,o=!1,s=()=>{if(o)throw new b("CLOSED","Native host was destroyed");if(!e.nativeModule)throw new b("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return e.nativeModule},c=()=>new b("IDENTITY_CHANGED","Customer identity changed during the native operation"),u=t.subscribeIdentity(()=>{r++,i=-1;let g=r;n&&e.nativeModule&&n.then(d=>e.nativeModule.reset(d,g)).catch(()=>{})}),l=e.nativeEvents?.(g=>{!n||!e.nativeModule||typeof g?.requestId!="string"||(async()=>{let d=await n;if(g.instanceId!==d)return;if(g.kind==="credential"){let y=r,A=null;try{if(!o&&g.revision===y){let x=await t.access();!o&&r===y&&(A=x)}}finally{await e.nativeModule.provideCredential(d,g.requestId,A)}return}let h=!1,R=r;try{if(o||g.revision!==R||!e.onNativeAction)throw c();await e.onNativeAction(g.action),h=!o&&r===R}finally{await e.nativeModule.acknowledge(d,g.requestId,h)}})().catch(()=>{})});async function m(g,d={}){let h=s();if(t.snapshot()&&!e.nativeEvents)throw new b("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let R=r,y=await t.access();if(o||r!==R)throw c();if(!n){let v=h.create(JSON.stringify({baseUrl:e.baseUrl??"https://api.longplayai.com",scope:e.scope,timeout:(e.timeoutMs??15e3)/1e3,credentialEvents:!!e.nativeEvents}));n=v,v.catch(()=>{n===v&&(n=void 0)})}let A=await n;if(o||r!==R)throw c();if(i!==R){if(!a||a.epoch!==R){let P=(async()=>{if(await h.identify(A,JSON.stringify({revision:R,credentials:y})),o||r!==R)throw await h.reset(A,R),c();i=R})();a={epoch:R,task:P}}let v=a;try{await v.task}finally{a===v&&(a=void 0)}}let x=await h.invoke(A,g,JSON.stringify(d));if(o||r!==R)throw c();try{return JSON.parse(x)}catch{throw new b("INVALID_RESPONSE","Native host returned invalid JSON")}}async function f(g,d){let h=await m(g,d);if(!h||typeof h!="object"||Array.isArray(h)||h.status!=="complete"&&h.status!=="dismissed")throw new b("INVALID_RESPONSE","Native presentation returned an invalid result");return h}return{showFunnel(g){return f("showFunnel",{runToken:g})},showPaywall(g){return f("showPaywall",g)},showContent(g){return f("showContent",g)},purchaseSubscription(g,d){return m("purchaseSubscription",{operationId:g,accepted:d})},switchSubscription(g,d){return m("switchSubscription",{operationId:g,accepted:d})},restorePurchases(){return m("restorePurchases")},manageSubscriptions(g){return m("manageSubscriptions",g?{productId:g}:{})},async dismiss(){r++,i=-1,n&&await s().reset(await n,r)},async destroy(){o||(o=!0,r++,u(),l?.(),n&&e.nativeModule&&await e.nativeModule.destroy(await n))}}}var Tv=O.trackUsage.request.shape.command,Nv=O.trackUsage.response;function Sy(e){let t=Fe.parse(e.scope),n=iy({...e,scope:t}),r={...e,scope:t,session:n.session},i=xy(e,n.session),a=0,o=!1;n.subscribeIdentity(()=>{a++});let s=()=>{if(o)throw new b("CLOSED","SDK client was destroyed");let c=n.session.peek();if(!c)throw new b("UNAUTHENTICATED","Identify the Customer first");return c};return{...n,native:i,async destroy(){o||(o=!0,a++,n.destroy(),await i.destroy())},funnel(){return my({...r,customerToken:s()})},resumeFunnel(c){return s(),xr({...r,runToken:c})},paywall(c){return by(r,{...c,customerToken:s()})},async trackUsage(c){if(s(),!e.usageReporter)throw new b("INVALID_REQUEST","Configure your authenticated backend usageReporter");let u=Tv.parse(c),l=a,m;try{m=await e.usageReporter(u)}catch(g){throw l!==a?new b("IDENTITY_CHANGED","Customer identity changed during usage reporting"):g}if(l!==a)throw new b("IDENTITY_CHANGED","Customer identity changed during usage reporting");let f=Nv.parse(m);if(f.scope.projectId!==t.projectId||f.scope.environment!==t.environment)throw new b("INVALID_RESPONSE","Usage response scope differs");return f}}}var wy=require("zod");var qi=require("zod");var Dv=qi.z.record(qi.z.string().regex(/^[a-f0-9]{64}$/),qi.z.strictObject({at:qi.z.number(),text:qi.z.string()})),ti=2*1048576,Fv=100;function Mv(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Iy(e,t){let n=t===void 0?Mv():t,r=new Map,i=0,a=!1,o=!1,s,c;async function u(m){if(!n)return null;let f;try{let g=await Promise.race([Promise.resolve().then(()=>n.getItem(m)),new Promise(d=>{f=setTimeout(()=>d(null),Fv)})]);return typeof g=="string"&&g.length<=ti&&new TextEncoder().encode(g).byteLength<=ti?g:null}catch{return null}finally{clearTimeout(f)}}function l(){if(c)return c;let m=(async()=>{try{let f=await u(`${e}:artifacts`);if(f)return Dv.parse(JSON.parse(f))}catch{}return{}})();return c=m,m.finally(()=>{c===m&&(c=void 0)}),m}return{async readManifest(){return u(e)},writeManifest(m){!n||m.length>ti||new TextEncoder().encode(m).byteLength>ti||(s=m,!o&&(o=!0,Promise.resolve().then(async()=>{try{for(;s!==void 0;){let f=s;try{await n.setItem(e,f)}catch{}s===f&&(s=void 0)}}finally{o=!1}})))},async readArtifact(m){let f=(await l())[m],g=Date.now();return f&&g>=f.at&&g-f.at<=nn.retentionMs?f.text:void 0},writeArtifact(m,f){if(!n||f.length>ti)return;let g=r.get(m);if(g?.text===f||!g&&r.size>=128)return;let d=new TextEncoder().encode(f).byteLength;i-(g?.byteLength??0)+d>ti||(r.set(m,{text:f,byteLength:d}),i+=d-(g?.byteLength??0),!a&&(a=!0,Promise.resolve().then(async()=>{try{for(;r.size;){let h=new Map(r);try{let R={...await l()},y=Date.now();for(let[P,j]of h)R[P]={at:y,text:j.text};let A={},x=2,v=0;for(let[P,j]of Object.entries(R).sort(([,_],[,X])=>X.at-_.at)){if(j.at>y||y-j.at>nn.retentionMs)continue;let _=new TextEncoder().encode(JSON.stringify({[P]:j})).byteLength;x+_>ti||v>=128||(A[P]=j,x+=_,v++)}await n.setItem(`${e}:artifacts`,JSON.stringify(A))}catch{}finally{for(let[R,y]of h)r.get(R)===y&&(r.delete(R),i-=y.byteLength)}}}finally{a=!1}})))}}}var Ce=(e,t)=>new b(e,t),Sr=()=>performance.now(),vy=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function Oy(e){let t=vu.parse(e.scope),n=new In(e.origin??yr);if(n.username||n.password||n.search||n.hash||n.pathname!=="/"||n.protocol!=="https:"&&!(n.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(n.hostname)))throw Ce("INVALID_URL","Configuration requires a trusted HTTPS origin");let r=new Set([n.origin,...(e.assetOrigins??[]).map(Y=>{let W=new In(Y);if(W.protocol!=="https:"||W.username||W.password||W.search||W.hash||W.pathname!=="/")throw Ce("INVALID_URL","Invalid configuration asset origin");return W.origin})]),i=e.fetch??globalThis.fetch.bind(globalThis),a=`/api/v1/configuration/${t.environmentId}`,o=`indiana:configuration:1:${n.origin}:${Et(t)}`,s=Iy(o,e.storage),c,u=0,l=0,m=!1,f=!1,g=0,d=0,h,R,y,A,x=0,v=new Set,P=new Set,j=new Map,_=new Map,X=0,le=!1;function he(){for(let Y of v)try{Y()}catch{}}function ke(Y){try{e.onError?.(Y)}catch{}}let Se=()=>!f&&!m&&!!c&&Sr()<u&&Date.now()<l;function At(){if(!Se())throw Ce("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function We(Y,W,pe){if(!j.has(Y)){for(;j.size&&(j.size>=128||X+pe>nn.maxCacheBytes);){let me=j.entries().next().value;X-=me[1].byteLength,j.delete(me[0])}j.set(Y,{text:W,byteLength:pe}),X+=pe}}function De(Y,W,pe){return oy(Y,W,{signal:pe,error:me=>Ce("INVALID_RESPONSE",me==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function rt(Y){let W=new In(Y,n);if(!r.has(W.origin)||W.username||W.password||W.hash||W.search)throw Ce("INVALID_URL","Configuration artifact origin is not trusted");return W.href}async function Mo(Y,W,pe=!1){let me=await i(rt(Y),{method:"GET",credentials:"omit",redirect:"error",cache:pe?"default":"no-cache",signal:W,headers:{}});if(me.status===429){let et=me.headers.get("retry-after")??"";x=/^\d+$/.test(et)?Number(et)*1e3:Math.max(0,Date.parse(et)-Date.now())||15e3}if(!me.ok&&me.status!==304)throw Ce(`CONFIGURATION_HTTP_${me.status}`,"Configuration synchronization failed");return me}function ni(Y,W,pe){let me=Date.parse(Y.headers.get("x-indiana-config-validated-at")??""),et=Date.parse(Y.headers.get("x-indiana-config-valid-until")??""),at=Date.parse(Y.headers.get("date")??""),Ke=Y.headers.get("age"),sn=Ke!==null&&/^\d+(\.\d+)?$/.test(Ke)?Number(Ke)*1e3:NaN;if(![me,et,at,sn].every(Number.isFinite)||et<=me||et-me>nn.maxControlAgeMs||me>at+1e3)throw Ce("INVALID_RESPONSE","Configuration freshness evidence is invalid");let Bt=Math.min(et-me,pe.maxControlAgeSeconds*1e3,nn.maxControlAgeMs)-Math.max(sn,at-me,0)-(Sr()-W);if(Bt<=0)throw Ce("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return Sr()+Bt}function mt(){if(clearTimeout(y),clearTimeout(A),f||!v.size)return;Se()&&(A=setTimeout(()=>{Se()?mt():he()},Math.max(1,u-Sr())),vy(A));let Y=d?Math.min(15e3,1e3*2**Math.min(d-1,4)):Math.min(15e3,(c?.policy.refreshIntervalSeconds??15)*1e3);y=setTimeout(()=>{Qt().catch(ke)},Math.max(x,Y*(.8+Math.random()*.2))),vy(y)}async function Qt(){if(f)throw Ce("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(h)return h;let Y=g,W=new AbortController;R=W;let pe=(async()=>{if(!le){le=!0;try{let Uo=await s.readManifest();if(Uo&&!c){let $n=Ou.parse(JSON.parse(Uo));Et($n.scope)===Et(t)&&(c=$n)}}catch{}}W.signal.throwIfAborted();let Ke=c,sn=Sr(),$t=await Mo(a,W.signal);$t.status===304&&(!Ke||!$t.headers.has("x-indiana-config-validated-at")||!$t.headers.has("x-indiana-config-valid-until")||!$t.headers.has("age"))&&($t=await Mo(a,W.signal));let Bt=$t.status===304?Ke:Ou.parse(JSON.parse(await De($t,nn.maxManifestBytes,W.signal))),{generation:ri,...ii}=Bt,zn=$t.headers.get("etag");if(Et(Bt.scope)!==Et(t)||tg(ii)!==ri||zn!==`"${ri}"`&&zn!==`W/"${ri}"`)throw Ce("INVALID_RESPONSE","Configuration scope or content identity changed");if(Ke&&(Bt.revision<Ke.revision||Bt.revision===Ke.revision&&Bt.generation!==Ke.generation))throw Ce("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[Uo,$n]of Object.entries(Ke?.funnels??{})){let Or=Bt.funnels[Uo];if(Or&&(Or.controlRevision<$n.controlRevision||Or.evaluationRevision<$n.evaluationRevision||Or.controlRevision===$n.controlRevision&&Or.state!==$n.state||Or.evaluationRevision===$n.evaluationRevision&&Or.evaluationMode!==$n.evaluationMode))throw Ce("INVALID_RESPONSE","Funnel control revision changed identity")}let wr=ni($t,sn,Bt.policy);if(W.signal.throwIfAborted(),Y!==g)throw Ce("CONFIGURATION_DISPOSED","Configuration scope changed");return c=Bt,u=wr,l=Date.now()+Math.max(0,wr-Sr()),m=!1,d=0,x=0,s.writeManifest(Et(Bt)),he(),structuredClone(Bt)})(),me=setTimeout(()=>W.abort(Ce("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),nn.initializationMs),et=new Promise((Ke,sn)=>W.signal.addEventListener("abort",()=>sn(W.signal.reason),{once:!0})),at=Promise.race([pe,et]).catch(Ke=>{throw d++,(Ke instanceof wy.z.ZodError||Ke instanceof SyntaxError||Ke instanceof b&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(Ke.code))&&(u=0,m=!0,he()),Ke}).finally(()=>{clearTimeout(me),h===at&&(h=void 0),mt()});return h=at,at}async function Ir(Y){let W=Y.sha256,pe=ii=>ws(ii,Y);rt(Y.url);let me=j.get(W);if(me){if(me.byteLength!==Y.byteLength)throw Ce("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return j.delete(W),j.set(W,me),me.text}let et=_.get(W);if(et){if(et.byteLength!==Y.byteLength)throw Ce("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return et.promise}let at=new AbortController;P.add(at);let Ke=g,sn=(async()=>{try{let wr=await s.readArtifact(W);if(wr&&pe(wr)){if(at.signal.throwIfAborted(),f||Ke!==g)throw Ce("CONFIGURATION_DISPOSED","Configuration scope changed");return We(W,wr,Y.byteLength),wr}}catch{}at.signal.throwIfAborted();let ii=await Mo(Y.url,at.signal,!0),zn=await De(ii,Y.byteLength,at.signal);if(!pe(zn))throw Ce("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(f||Ke!==g)throw Ce("CONFIGURATION_DISPOSED","Configuration scope changed");return We(W,zn,Y.byteLength),s.writeArtifact(W,zn),zn})(),$t=setTimeout(()=>at.abort(Ce("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),nn.initializationMs),Bt=new Promise((ii,zn)=>at.signal.addEventListener("abort",()=>zn(at.signal.reason),{once:!0})),ri=Promise.race([sn,Bt]).finally(()=>{clearTimeout($t),P.delete(at),_.delete(W)});return _.set(W,{promise:ri,byteLength:Y.byteLength}),ri}async function vr(){return Se()||await Qt(),At(),c}async function Ui(Y){let W,pe=new Promise((me,et)=>{W=setTimeout(()=>et(Ce("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),nn.initializationMs)});try{return await Promise.race([Y(),pe])}finally{clearTimeout(W)}}function Bi(Y,W){if(At(),c?.generation!==Y.generation)throw Ce("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(W&&c.funnels[W]?.state!=="active")throw Ce("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function yl(Y){let W=Y.gb.features;if(!W)throw Ce("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let pe=Y.artifacts[W];if(pe.formatVersion!==1)throw Ce("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let me=Jc.parse(JSON.parse(await Ir(pe)));if(Et(me.scope)!==Et({projectId:t.projectId,environment:t.environment})||me.generation!==pe.generation||me.remoteFeatures.some(et=>Object.hasOwn(me.features,et)))throw Ce("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return Bi(Y),{...me,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,u-Sr())).toISOString()}}async function Al(Y,W){let pe=await vr(),me=pe.funnels[Y];W&&(!me||me.evaluationMode==="local"&&!me.versions[W])&&(h&&await h,pe=await Qt()),Bi(pe,Y);let et=pe.funnels[Y];if(et.evaluationMode!=="local")throw Ce("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let at=W??et.currentVersionId,Ke=et.versions[at];if(!Ke)throw Ce("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(pe.artifacts[Ke.artifact].formatVersion!==3)throw Ce("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[sn,$t]=await Promise.all([Ir(pe.artifacts[Ke.artifact]).then(Bt=>rg(JSON.parse(Bt))),et.evaluationMode==="local"?yl(pe):void 0]);if($t&&Et(ng(sn,$t))!==Et(Ke.dependencies))throw Ce("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return Bi(pe,Y),{document:sn,growth:$t,versionId:at,control:structuredClone(et),manifest:structuredClone(pe)}}async function bl(Y,W){try{return await Al(Y,W)}catch(pe){if(!(pe instanceof b)||!(pe.code==="CONFIGURATION_CHANGED"||pe.code==="CONFIGURATION_HTTP_404"&&Se()))throw pe;let me=c?.generation;if(h&&await h,await Qt(),pe.code!=="CONFIGURATION_CHANGED"&&c?.generation===me)throw pe;return Al(Y,W)}}function Cs(){m=!0,he(),Qt().catch(ke)}let qo=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Cs()};function _y(Y){if(f)throw Ce("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return v.add(Y),v.size===1&&(typeof window<"u"&&(window.addEventListener("online",Cs),window.addEventListener("focus",qo),document.addEventListener("visibilitychange",qo)),mt()),()=>{v.delete(Y),v.size||(clearTimeout(y),clearTimeout(A),xl())}}function xl(){typeof window<"u"&&(window.removeEventListener("online",Cs),window.removeEventListener("focus",qo),document.removeEventListener("visibilitychange",qo))}return{scope:Object.freeze({...t}),refresh:Qt,subscribe:_y,assertFresh:At,assertFeatures(Y){At();let W=c.gb.features;if(!W)throw Ce("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(Y!==void 0&&c.artifacts[W].generation!==Y)throw Ce("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return Se()},get snapshot(){return c?structuredClone(c):null},get remainingMs(){return Se()?Math.max(0,u-Sr()):0},async features(){return Ui(async()=>yl(await vr()))},pageExperiments:()=>Ui(async()=>{let Y=await vr(),W=Y.gb.pageExperiments;if(!W)throw Ce("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let pe=Y.artifacts[W];if(pe.formatVersion!==1)throw Ce("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let me=dh.parse(JSON.parse(await Ir(pe)));if(me.environmentId!==t.environmentId||me.generation!==pe.generation)throw Ce("INVALID_RESPONSE","Page experiment scope or generation changed");return Bi(Y),me}),funnel:(Y,W)=>Ui(()=>bl(Y,W)),paywall:(Y,W)=>Ui(async()=>{let pe=await vr(),me=pe.paywalls?.[Y];if(!me||!W&&me.state!=="published")throw Ce("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let et=W??me.currentVersionId,at=me.versions[et],Ke=at&&pe.artifacts[at.artifact];if(!Ke||Ke.kind!=="paywall"||Ke.formatVersion!==1)throw Ce("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let sn=as.parse(JSON.parse(await Ir(Ke)));return Bi(pe),{document:sn,versionId:et,version:at.version,control:structuredClone(me),manifest:structuredClone(pe)}}),async localFunnel(Y,W){let pe=await Ui(()=>bl(Y,W));if(!pe.growth)throw Ce("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:me,remoteFeatures:et,...at}=pe.growth;return uh({scope:{projectId:t.projectId,environment:t.environment},funnelId:Y,versionId:pe.versionId,evaluationMode:"local",evaluationRevision:pe.control.evaluationRevision,document:pe.document,payload:at})},assertFunnel(Y,W,pe){At();let me=c.funnels[Y];if(!me||me.state!=="active")throw Ce("FUNNEL_STOPPED","Funnel is paused or unavailable");if(me.evaluationMode!=="local")throw Ce("EVALUATION_MODE","This Funnel now executes at Longplay");if(W!==void 0&&me.controlRevision!==W)throw Ce("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(pe!==void 0&&!me.versions[pe])throw Ce("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!f){f=!0,g++,u=0,R?.abort(Ce("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(y),clearTimeout(A),xl(),he(),v.clear();for(let Y of P)Y.abort(Ce("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));j.clear(),X=0}}}}async function Py(e){e={...e};let t=e.configuration;if(!t)throw new b("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let n={projectId:t.scope.projectId,environment:t.scope.environment};if(e.scope&&Et(n)!==Et(e.scope))throw new b("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await t.funnel(e.funnelId)).control.evaluationMode!=="local")throw new b("EVALUATION_MODE","This Funnel uses Remote evaluation");let i=Mi.test(e.credential);if(i?!e.customerId:e.customerId!==void 0)throw new b("INVALID_REQUEST","Only Server-Key starts name their Customer");let a=vs({...e,scope:n,apiKey:e.credential}),o=s=>{let c=xr({...e,scope:n,runToken:s,...i?{serverKey:e.credential}:{}});return i||c.identify(e.credential),c};return{async start(s){let c=await a.start({...s,funnelId:e.funnelId,...i?{customer:{type:"id",value:e.customerId}}:{}}),u=o(c.runToken),l=await u.get();return{...c,...l,controller:u}},async restore(s){let c=o(s),u=await c.get();if(u.run.source.id!==e.funnelId)throw c.reset(),new b("SCOPE_MISMATCH","Run belongs to another Funnel");return{...u,runToken:s,controller:c}}}}function hl(e,...t){try{Promise.resolve(e?.(...t)).catch(()=>{})}catch{}}function Cy(e){if(!e.scope)throw new b("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(e.session!==void 0)throw new b("INVALID_CONFIGURATION","The merchant process adapter owns the session");let t=null,n,r=0,i=new Set,a=new Map,o=new Map;async function s(f){let g,d=new Promise((h,R)=>{g=setTimeout(()=>R(new b("TIMEOUT","Process bridge request timed out")),e.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(f),d])}finally{clearTimeout(g)}}function c(f){throw f instanceof b&&(f.status===401||f.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear()),f}function u(f,g){if(g!==r)throw new b("IDENTITY_CHANGED","Process was detached during a request");let d=zu.parse(f);if(d.scope.projectId!==e.scope.projectId||d.scope.environment!==e.scope.environment)throw new b("SCOPE_MISMATCH","Process response belongs to another App/environment");if(t&&(t.run.id!==d.run.id||t.run.source.versionId!==d.run.source.versionId||t.run.source.id!==d.run.source.id||t.run.runExpiresAt!==d.run.runExpiresAt||t.run.identity.startedAs!==d.run.identity.startedAs||t.run.identity.participantId!==d.run.identity.participantId||t.run.identity.binding&&d.run.identity.binding&&t.run.identity.binding.id!==d.run.identity.binding.id))throw new b("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!t||d.run.revision>=t.run.revision){if(t?.run.identity.binding&&!d.run.identity.binding)throw new b("INVALID_RESPONSE","The process lost its Customer binding");t=d;for(let j of i)hl(j,d.run);d.run.instruction?.type==="authentication_required"&&hl(e.onAuthenticationRequired,d.run)}d.settlement?.accepted!==void 0&&o.set(d.settlement.requestId,d.settlement.accepted);let{identity:h,instruction:R,...y}=d.run,{contract:A,settlement:x,...v}=d,P=x&&(({accepted:j,..._})=>_)(x);return{...v,run:{...y,authenticated:h.binding!==null,instruction:R?.type==="authentication_required"?null:R},...P?{settlement:P}:{}}}let l=f=>(a.has(f)||a.set(f,t?.run.identity.binding?.id??null),a.get(f));async function m(f){let g=r,d=t?.run.identity.binding?.id??null,h=y=>{if(d!==(t?.run.identity.binding?.id??null))throw y;return c(y)};if(f.operation==="page_experiments"){if(!e.adapter.pageExperiments)throw new b("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return s(()=>e.adapter.pageExperiments(f.release,f.usedReceiptIds)).catch(h)}let R;if(f.operation==="get"){let{operation:y,customerToken:A,...x}=f;R=await s(()=>e.adapter.get({...x,...x.settlementRequestId?{settlementBindingId:l(x.settlementRequestId)}:{}})).catch(h)}else if(f.operation==="review")R=await s(()=>e.adapter.review(f.receiptId)).catch(h);else{if(f.operation==="start")throw new b("INVALID_REQUEST","Use process.open for entry");{let{customerToken:y,...A}=f;R=await s(()=>e.adapter.command(A,l(A.requestId))).catch(h)}}return u(R,g)}return{get view(){return t?.run??null},get controller(){return n},async open(f){let g=r,d=await s(()=>e.adapter.open(f)).catch(c);if(u(d,g),!n){n=xr({...e,runToken:d.runToken,process:{request:m,binding:l,restore(y){for(let[A,x]of Object.entries(y))a.set(A,x)}}});let h=n,R=h.submit;h.submit=async y=>{try{return await R(y)}catch(A){if(!(A instanceof b)||A.reason!=="IDENTITY_CONTEXT_CHANGED"||y.operation!=="submit"||y.input.type!=="screen"||a.get(y.requestId)!==null)throw A;await h.settle?.(y.requestId),await h.get();let x=h.view;if(o.get(y.requestId)!==!1||!x||x.id!==t?.run.id||x.nodeId!==y.nodeId||x.visit!==y.visit||!t?.run.identity.binding)throw A;return R({...y,requestId:crypto.randomUUID(),revision:x.revision})}}}await n.get();for(let h of n.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(t?.run.identity.binding?.id??null)&&await n.settle?.(h.requestId);return{run:t.run,controller:n}},async syncIdentity(){let f=r;u(await s(()=>e.adapter.syncIdentity()).catch(c),f),await n?.get();for(let g of n?.pendingCommands??[])a.has(g.requestId)&&a.get(g.requestId)!==(t?.run.identity.binding?.id??null)&&await n?.settle?.(g.requestId);return t.run},async detach(){r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear(),await s(()=>e.adapter.detach())},forProcess(f){if(!t?.run.identity.binding)throw new b("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:t.run.id,bindingId:t.run.identity.binding.id,receiptId:f}},subscribe(f){return i.add(f),()=>{i.delete(f)}},destroy(){r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear(),i.clear()}}}
|
|
17
|
+
*/var ve=N.z.json().superRefine((e,t)=>{let n=0;function r(i,a){if(++n>1e4||a>20){t.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof i=="string"&&(i.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(i))&&t.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(i))i.forEach(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))(o.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(o)||["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved JSON property"}),r(s,a+1)}r(e,0),new TextEncoder().encode(JSON.stringify(e)).byteLength>65536&&t.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),Ct=N.z.record(N.z.string().min(1).max(128),ve).superRefine((e,t)=>{(!ve.safeParse(e).success||Object.keys(e).length>128||new TextEncoder().encode(JSON.stringify(e)).byteLength>65536||["__proto__","constructor","prototype"].some(n=>Object.hasOwn(e,n)))&&t.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),zA=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),Yt=Ct.superRefine((e,t)=>{function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,a]of Object.entries(r)){if(i==="$savedGroup"&&!N.z.strictObject({id:N.z.uuid(),attributeKey:N.z.string().min(1).max(128).optional()}).safeParse(a).success&&t.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!i.startsWith("$")&&i.split(".").some(o=>["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved attribute path"}),i.startsWith("$")&&!zA.has(i)&&t.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${i}`}),["$regex","$regexi"].includes(i)&&typeof a=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(a)||[...a.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(o=>Number(o[1])>255||Number(o[2]||0)>255)||i==="$regexi"&&/[^\x00-\x7f]/.test(a.replace(/\\u([0-9a-f]{4})/gi,(o,s)=>String.fromCharCode(Number.parseInt(s,16)))))&&t.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(a)}catch{t.addIssue({code:"custom",message:"Invalid regular expression"})}}n(a)}}typeof e.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(e.source)&&("operator"in e||"predicates"in e||"groupId"in e)&&t.addIssue({code:"custom",message:"Obsolete condition protocol"}),n(e)}),$A=N.z.discriminatedUnion("type",[N.z.strictObject({type:N.z.literal("condition"),condition:Yt}),N.z.strictObject({type:N.z.literal("list"),attributeKey:N.z.string().min(1).max(128),values:N.z.array(N.z.union([N.z.string(),N.z.number().finite()])).max(1e5)})]).refine(e=>e.type!=="list"||new TextEncoder().encode(JSON.stringify(e.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function Qn(e){let t=new Set;function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,a]of Object.entries(r))i==="$savedGroup"&&a&&typeof a=="object"&&!Array.isArray(a)&&typeof a.id=="string"?t.add(a.id):["$inGroup","$notInGroup"].includes(i)&&typeof a=="string"?t.add(a):["$eq","$ne","$in","$nin","$ini","$nini"].includes(i)||n(a)}return n(e),[...t]}var GA=N.z.record(N.z.uuid(),$A).superRefine((e,t)=>{let n=new Set,r=new Set;function i(a){if(n.has(a)){t.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(r.has(a))return;let o=e[a];if(!o){t.addIssue({code:"custom",message:"Missing saved group dependency"});return}n.add(a),o.type==="condition"&&Qn(o.condition).forEach(i),n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),cc=N.z.tuple([N.z.number().min(0).max(1),N.z.number().min(0).max(1)]).refine(([e,t])=>e<=t),Vd=N.z.strictObject({attribute:N.z.string().optional(),seed:N.z.string().min(1),hashVersion:N.z.literal(2),ranges:N.z.array(cc).min(1).max(100)}),KA=N.z.strictObject({id:N.z.string().min(1).max(128),condition:Yt,gate:N.z.boolean().optional()}),sc={id:N.z.string().max(128).optional(),condition:Yt.optional(),parentConditions:N.z.array(KA).max(50).optional(),filters:N.z.array(Vd).max(20).optional()},HA=N.z.union([N.z.strictObject({...sc}),N.z.strictObject({...sc,force:ve,coverage:N.z.number().min(0).max(1).optional(),range:cc.optional(),seed:N.z.string().min(1).optional(),hashAttribute:N.z.string().optional(),hashVersion:N.z.literal(2).optional()}),N.z.strictObject({...sc,type:N.z.literal("experiment-ref"),experimentId:N.z.uuid(),values:N.z.record(N.z.string().min(1),ve),meta:N.z.record(N.z.string().min(1),N.z.strictObject({passthrough:N.z.boolean()})).optional()})]),QA=N.z.strictObject({defaultValue:ve,rules:N.z.array(HA).max(100)}),mO=N.z.record(N.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),QA).superRefine((e,t)=>{Object.keys(e).length>100&&t.addIssue({code:"custom",message:"Too many Features"});let n=new Set,r=new Set;function i(a){if(n.has(a)){t.addIssue({code:"custom",message:`Cyclic Feature dependency: ${a}`});return}if(r.has(a))return;let o=e[a];if(!o){t.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${a}`});return}n.add(a);for(let s of o.rules)for(let c of s.parentConditions??[])i(c.id);n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),JA=N.z.strictObject({name:N.z.string().max(80),reason:N.z.string().max(500),dateStarted:N.z.iso.datetime({offset:!0}),dateEnded:N.z.iso.datetime({offset:!0}).nullable(),coverage:N.z.number().min(0).max(1),variationWeights:N.z.array(N.z.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:Yt,savedGroups:N.z.array(N.z.strictObject({match:N.z.enum(["any","all","none"]),ids:N.z.array(N.z.uuid()).min(1)})).max(50),namespace:N.z.strictObject({id:N.z.uuid(),ranges:N.z.array(cc).min(1)}).nullable(),seed:N.z.string().min(1).max(128)}),ZA=N.z.strictObject({key:N.z.string().min(1).max(128),name:N.z.string().min(1).max(80),hypothesis:N.z.string().max(2e3),status:N.z.enum(["draft","running","stopped"]),hashAttribute:N.z.string().min(1).max(128),fallbackAttribute:N.z.string().max(128).nullable(),hashVersion:N.z.literal(2),disableStickyBucketing:N.z.boolean(),bucketVersion:N.z.number().int().min(0).max(1e3),minBucketVersion:N.z.number().int().min(0).max(1e3),variations:N.z.array(N.z.strictObject({id:N.z.string().min(1),key:N.z.string().min(1),name:N.z.string().max(80),description:N.z.string().max(500)})).min(2).max(20),phases:N.z.array(JA).min(1).max(100),releasedVariationId:N.z.string().nullable(),excludeFromPayload:N.z.boolean(),statusSchedule:N.z.strictObject({startAt:N.z.iso.datetime({offset:!0}).nullable(),stopAt:N.z.iso.datetime({offset:!0}).nullable(),stopAfter:N.z.strictObject({value:N.z.number().int().positive().max(36500),unit:N.z.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((e,t)=>{(e.minBucketVersion>e.bucketVersion||e.statusSchedule?.stopAt&&e.statusSchedule?.stopAfter||e.phases.some((n,r)=>{if(r===0)return!1;let i=e.phases[r-1];return!i?.dateEnded||Date.parse(n.dateStarted)<Date.parse(i.dateStarted)||Date.parse(i.dateEnded)>Date.parse(n.dateStarted)})||new Set(e.variations.map(n=>n.key)).size!==e.variations.length||new Set(e.variations.map(n=>n.id)).size!==e.variations.length||e.releasedVariationId!==null&&!e.variations.some(n=>n.id===e.releasedVariationId)||e.statusSchedule?.startAt&&e.statusSchedule?.stopAt&&Date.parse(e.statusSchedule.startAt)>=Date.parse(e.statusSchedule.stopAt)||e.phases.some(n=>n.dateEnded&&Date.parse(n.dateStarted)>=Date.parse(n.dateEnded)||n.namespace?.ranges.some(([r,i],a,o)=>r>=i||o.some(([s,c],u)=>u!==a&&r<c&&s<i)))||e.phases.some(n=>n.variationWeights.length!==e.variations.length))&&t.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});var WA=ZA.safeExtend({filters:N.z.array(Vd).optional()}),YA=N.z.strictObject({experiments:N.z.record(N.z.uuid(),WA),savedGroups:GA}),Hi=N.z.strictObject({attributeName:N.z.string(),attributeValue:N.z.string(),assignments:N.z.record(N.z.string(),N.z.string())}),fO=N.z.strictObject({snapshot:YA,attributes:Ct,results:Ct,stickyBucketAssignmentDocs:N.z.record(N.z.string(),Hi)}),gO=N.z.strictObject({variantKey:N.z.string().nullable(),bucketVersion:N.z.number().int().min(0),source:N.z.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:N.z.number().min(0).max(1).optional(),stickyBucketUsed:N.z.boolean().optional(),hashUsed:N.z.boolean().optional()});function rr(e){let t=new Set,n=a=>a!==null&&typeof a=="object"&&!Array.isArray(a);function r(a,o){if(n(a))for(let[s,c]of Object.entries(a))s==="$elemMatch"?i(c,o):s==="$not"?r(c,o):s==="$all"&&Array.isArray(c)&&c.forEach(u=>r(u,o))}function i(a,o=""){if(n(a)){for(let[s,c]of Object.entries(a))if(["$and","$or","$nor"].includes(s)&&Array.isArray(c))c.forEach(u=>i(u,o));else if(s==="$not")i(c,o);else if(s==="$savedGroup"&&n(c))typeof c.attributeKey=="string"&&t.add(c.attributeKey);else if(!s.startsWith("$")){let u=o?`${o}.${s}`:s;t.add(u),r(c,u)}}}return i(e),[...t]}var XA=Rt.z.enum(["active","inactive"]),eb=Rt.z.preprocess((e,t)=>{let n=0;function r(i,a){if(!(++n>1e4||a>20)){if(Array.isArray(i))i.forEach(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))["__proto__","constructor","prototype"].includes(o)&&t.addIssue({code:"custom",message:"Reserved merchandise attribute"}),r(s,a+1)}}return r(e,0),e},Ct),tb=Rt.z.strictObject({id:Rt.z.string().trim().min(1).max(255),name:Rt.z.string().trim().min(1).max(255),status:XA,metadata:eb}),xO=tb.extend({internal_id:Rt.z.uuid(),project_id:Rt.z.uuid(),environment_id:Rt.z.uuid(),created_at:Rt.z.iso.datetime({offset:!0}),updated_at:Rt.z.iso.datetime({offset:!0})}),zd=Rt.z.union([Rt.z.strictObject({id:Rt.z.string().trim().min(1).max(255)}),Rt.z.strictObject({internalId:Rt.z.uuid()})]),SO=Rt.z.enum(["customer","merchandise","context"]),IO=Rt.z.enum(["system","stored","request"]),vO=Rt.z.enum(["customer","merchandise","mixed"]),Ld=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function uc(e,t={},n=new Set){if(rr(e).some(Ld))return!0;for(let r of Qn(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&Ld(i.attributeKey)||i?.type==="condition"&&uc(i.condition,t,n))return!0}return!1}var $d=require("zod"),nb=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,wn=$d.z.string().max(16).regex(nb,"\u8BED\u8A00\u4EE3\u7801\u683C\u5F0F\u4E0D\u6B63\u786E\uFF0C\u4F8B\u5982 zh-CN\u3001en").refine(e=>{try{return Intl.getCanonicalLocales(e)[0]===e}catch{return!1}},"\u6301\u4E45\u5316\u8BED\u8A00\u4EE3\u7801\u5FC5\u987B\u4F7F\u7528\u89C4\u8303\u5199\u6CD5");var EO=ee.z.enum(["draft","active","paused","archived"]),ir=ee.z.discriminatedUnion("type",[ee.z.object({type:ee.z.literal("percent"),percentOff:ee.z.number().min(1).max(100).multipleOf(.01)}).strict(),ee.z.object({type:ee.z.literal("amount"),amountOffCents:ee.z.number().int().min(1).max(1e8),currency:Ie}).strict()]),un=ee.z.discriminatedUnion("type",[ee.z.object({type:ee.z.literal("once")}).strict(),ee.z.object({type:ee.z.literal("repeating"),months:ee.z.number().int().min(1).max(36)}).strict(),ee.z.object({type:ee.z.literal("forever")}).strict()]),Gd=[ee.z.object({type:ee.z.literal("all")}).strict(),ee.z.object({type:ee.z.literal("plans"),planIds:ee.z.array(ee.z.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],rb=ee.z.discriminatedUnion("type",[...Gd,ee.z.strictObject({type:ee.z.literal("merchandise"),scope:ee.z.discriminatedUnion("type",[ee.z.strictObject({type:ee.z.literal("all")}),ee.z.strictObject({type:ee.z.literal("selected"),merchandiseIds:ee.z.array(ee.z.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),ee.z.strictObject({type:ee.z.literal("condition"),condition:Yt})])})]),lc=ee.z.discriminatedUnion("type",[...Gd,ee.z.strictObject({type:ee.z.literal("merchandise"),scope:ee.z.strictObject({type:ee.z.enum(["all","selected","condition"])})})]),ib=ee.z.strictObject({firstPurchaseOnly:ee.z.boolean(),condition:Yt}),RO=ee.z.object({name:ee.z.string().trim().min(1).max(80),description:ee.z.string().max(500),discount:ir,duration:un,appliesTo:rb,eligibility:ib,selfClaimEnabled:ee.z.boolean().default(!1),startsAt:ee.z.iso.datetime().nullable(),endsAt:ee.z.iso.datetime().nullable(),totalLimit:ee.z.number().int().min(1).max(1e6).nullable(),perCustomerLimit:ee.z.number().int().min(1).max(10),grantWindowHours:ee.z.number().int().min(1).max(2160)}).strict().refine(e=>!e.startsAt||!e.endsAt||Date.parse(e.endsAt)>Date.parse(e.startsAt),{message:"\u7ED3\u675F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u5F00\u59CB\u65F6\u95F4",path:["endsAt"]}).refine(e=>!uc(e.eligibility.condition),{message:"Customer eligibility cannot read merchandise; use merchandise applicability",path:["eligibility","condition"]}).refine(e=>e.appliesTo.type!=="merchandise"||e.duration.type==="once",{message:"Merchandise Coupons apply to one purchase",path:["duration"]}).refine(e=>e.appliesTo.type!=="merchandise"||!e.eligibility.firstPurchaseOnly,{message:"Merchant purchase eligibility requires trusted targeting attributes",path:["eligibility","firstPurchaseOnly"]}),kO=ee.z.object({code:ee.z.string().trim().transform(e=>e.toUpperCase()).pipe(ee.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/,"\u4F18\u60E0\u7801\u53EA\u80FD\u7528 3\u201332 \u4F4D\u5B57\u6BCD\u3001\u6570\u5B57\u3001- \u548C _\uFF0C\u4EE5\u5B57\u6BCD\u6216\u6570\u5B57\u5F00\u5934")),maxRedemptions:ee.z.number().int().min(1).max(1e6).nullable(),expiresAt:ee.z.iso.datetime().nullable(),firstPurchaseOnly:ee.z.boolean(),minimumAmountCents:ee.z.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:Ie.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var Qi=ee.z.object({id:ee.z.uuid(),couponId:ee.z.uuid(),status:ee.z.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:ee.z.iso.datetime(),expiresAt:ee.z.iso.datetime(),coupon:ee.z.object({name:ee.z.string(),discount:ir,duration:un,appliesTo:lc}).strict()}).strict(),Kd=ee.z.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var Wd=S.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),dc=S.z.string().regex(/^(0|[1-9]\d{0,14})$/),ui=S.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),ob=S.z.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),Ji=ob,Jn=xe.refine(e=>/[1-9]/.test(e)),Gt=S.z.iso.datetime({offset:!0}),fa=e=>{let[t,n=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");return BigInt(t)*1000000n+BigInt(n.padEnd(6,"0"))},ab=S.z.array(S.z.object({upTo:Jn.nullable(),unitAmountMinor:Wd,flatAmountMinor:S.z.number().int().min(0).max(1e8).optional()}).strict()).min(1).max(12).refine(e=>{try{return e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let r=e[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&fa(t.upTo)>fa(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),sb=S.z.discriminatedUnion("kind",[S.z.object({kind:S.z.literal("flat"),units:Jn,unitAmountMinor:Wd}).strict(),S.z.object({kind:S.z.enum(["graduated","volume"]),units:Jn,tiers:ab}).strict()]).refine(e=>e.kind==="flat"||!e.tiers.some(t=>(t.flatAmountMinor??0)>0)||e.kind==="volume"&&e.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers"),cb=S.z.strictObject({interval:S.z.enum(["month","year"]),count:S.z.number().int().min(1).max(12),anchor:S.z.enum(["membership","calendar"])}),Zi=S.z.object({currency:Ie,pricing:sb,billingCycle:cb.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var Hd={requestId:S.z.uuid(),productVersionId:S.z.uuid(),internal_feature_id:S.z.uuid(),currency:Ie},Yd=S.z.strictObject({interval:S.z.enum(["hour","day","week","month"]),intervalCount:S.z.number().int().min(1).max(12),limit:S.z.number().int().min(1).max(1e6)}),Xd=S.z.discriminatedUnion("kind",[S.z.object({...Hd,kind:S.z.literal("auto_topup"),threshold:ta,quantity:Jn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Yd.optional()}).strict(),S.z.object({...Hd,kind:S.z.literal("postpaid"),maxAmountMinorPerPeriod:Ji,maxOutstandingMinor:Ji}).strict()]),Qd={productVersionId:S.z.uuid(),internal_feature_id:S.z.uuid(),currency:Ie},ep=S.z.discriminatedUnion("kind",[S.z.object({...Qd,kind:S.z.literal("auto_topup"),threshold:ta,quantity:Jn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Yd.optional(),purchaseAmountMinor:Ji,purchaseUnits:Jn}).strict(),S.z.object({...Qd,kind:S.z.literal("postpaid"),maxAmountMinorPerPeriod:Ji,maxOutstandingMinor:Ji,cashPrice:Zi}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),ga=S.z.object({id:S.z.uuid(),terms:ep,status:S.z.enum(["prepared","active","revoked","blocked"]),createdAt:Gt,acceptedAt:Gt.nullable(),effectiveAt:Gt.nullable(),revokedAt:Gt.nullable()}).strict().refine(e=>(e.status==="prepared"?e.acceptedAt===null:!0)&&(e.status==="active"?e.acceptedAt!==null&&e.effectiveAt!==null:!0)&&(e.status==="revoked"?e.revokedAt!==null:e.revokedAt===null),"Authorization consent and revocation must be explicit"),tp=S.z.object({authorizationId:S.z.uuid(),terms:ep,setupUrl:S.z.url().nullable()}).strict(),np=S.z.object({authorizationId:S.z.uuid(),accepted:S.z.literal(!0)}).strict(),rp=S.z.object({authorizationId:S.z.uuid(),requestId:S.z.uuid()}).strict(),ip=S.z.object({internal_feature_id:S.z.uuid(),entityId:S.z.uuid().nullable(),interval:S.z.enum(["day","week","month","year"]),anchor:S.z.enum(["billing_cycle","utc"]).optional(),basis:S.z.enum(["usage","credits"]),filter:Pt.optional(),limit:xe.nullable(),thresholds:S.z.array(S.z.number().positive().max(1)).max(8),includedThresholds:S.z.array(S.z.number().positive().max(1)).max(8).optional(),absoluteThresholds:S.z.array(Jn).max(8).optional()}).strict().refine(e=>e.thresholds.every((t,n)=>{let r=e.thresholds[n-1];return n===0||r!==void 0&&t>r})&&(e.includedThresholds??[]).every((t,n,r)=>{let i=r[n-1];return n===0||i!==void 0&&t>i})&&(e.absoluteThresholds??[]).every((t,n,r)=>{let i=r[n-1];return n===0||i!==void 0&&fa(t)>fa(i)}),"Notification thresholds must increase"),ub=ip.safeExtend({requestId:S.z.uuid()}),Jd={control:S.z.literal("overage"),requestId:S.z.uuid(),internal_feature_id:S.z.uuid(),entityId:S.z.uuid().nullable()},lb=S.z.discriminatedUnion("action",[S.z.strictObject({...Jd,action:S.z.literal("set"),allowed:S.z.boolean().nullable(),overageLimit:xe.nullable(),skipOverageBilling:S.z.boolean()}),S.z.strictObject({...Jd,action:S.z.literal("remove")})]),op=S.z.union([ub,lb]),db=S.z.strictObject({internal_feature_id:S.z.uuid(),entityId:S.z.uuid().nullable(),allowed:S.z.boolean().nullable(),overageLimit:xe.nullable(),skipOverageBilling:S.z.boolean(),interval:S.z.enum(["day","week","month","year"]),startsAt:Gt,endsAt:Gt,used:S.z.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:S.z.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:S.z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),pb=S.z.object({internal_feature_id:S.z.uuid(),entityId:S.z.uuid().nullable(),interval:S.z.enum(["day","week","month","year"]),anchor:S.z.enum(["billing_cycle","utc"]).optional(),basis:S.z.enum(["usage","credits"]),filter:Pt.optional(),startsAt:Gt,endsAt:Gt,used:Wt,reserved:Wt,limit:xe.nullable(),thresholds:S.z.array(S.z.number().positive().max(1)).max(8),notifiedThresholds:S.z.array(S.z.number().positive().max(1)).max(1024),includedThresholds:S.z.array(S.z.number().positive().max(1)).max(8).optional(),includedAllowance:S.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:S.z.array(S.z.number().positive().max(1)).max(1024).optional(),absoluteThresholds:S.z.array(Jn).max(8).optional(),notifiedAbsoluteThresholds:S.z.array(Jn).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||xe.safeParse(e.used).success&&xe.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),mb=S.z.object({authorizationId:S.z.uuid(),status:S.z.enum(["idle","pending","blocked"]),taskId:S.z.uuid().nullable(),invoiceId:S.z.uuid().nullable(),hostedInvoiceUrl:S.z.url().nullable(),purchaseCount:S.z.number().int().nonnegative(),purchaseWindowEndsAt:Gt.nullable(),attemptCount:S.z.number().int().nonnegative(),failedAttemptCount:S.z.number().int().nonnegative(),suspendedAt:Gt.nullable(),nextAttemptAt:Gt.nullable(),failureReason:S.z.string().min(1).max(240).nullable()}).strict(),ap=S.z.object({internal_feature_id:S.z.uuid().optional(),entityId:S.z.uuid().optional()}).strict(),pc=S.z.object({authorizations:S.z.array(ga).max(100),limits:S.z.array(ip).max(100),overages:S.z.array(db).max(100).optional(),windows:S.z.array(pb).max(200),autoTopups:S.z.array(mb).max(100),limited:S.z.boolean()}).strict(),fb=S.z.object({id:S.z.uuid(),internal_feature_id:S.z.uuid(),productVersionId:S.z.uuid(),authorizationId:S.z.uuid(),entityId:S.z.uuid().nullable(),units:xe,amountMinor:ui,cashPrice:Zi}).strict(),Wi=S.z.object({id:S.z.uuid(),sourceKind:S.z.enum(["product","usage","manual"]),providerInvoiceId:S.z.string().min(1).max(240).nullable(),status:S.z.enum(["accruing","open","pending","paid","failed","void"]),currency:Ie,startsAt:Gt.nullable(),endsAt:Gt.nullable(),amountMinor:S.z.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:S.z.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:dc,paidAmountMinor:dc,refundedAmountMinor:dc,createdAt:Gt,hostedInvoiceUrl:S.z.url().nullable(),adjustment:S.z.object({originalInvoiceId:S.z.uuid(),amountMinor:S.z.string().regex(/^-?(0|[1-9]\d{0,8})$/).refine(e=>e!=="-0"&&/^-?(0|[1-9]\d{0,8})$/.test(e)&&BigInt(e)>=-200000000n&&BigInt(e)<=200000000n,"Invoice adjustment exceeds the bounded minor amount"),acceptedAt:Gt.nullable(),reason:S.z.string().min(1).max(500).optional()}).strict().nullable(),lines:S.z.array(fb).max(100),linesLimited:S.z.boolean()}).strict(),sp=S.z.object({invoiceId:S.z.uuid(),accepted:S.z.literal(!0)}).strict(),cp=S.z.strictObject({requestId:S.z.uuid(),originalInvoiceId:S.z.uuid(),amountMinor:S.z.string().regex(/^[1-9]\d{0,8}$/).refine(e=>/^[1-9]\d{0,8}$/.test(e)&&BigInt(e)<=200000000n,"Supplemental amount exceeds the bounded minor amount"),reason:S.z.string().trim().min(1).max(500)}),up=S.z.object({after:S.z.uuid().nullable(),limit:S.z.number().int().min(1).max(100)}).strict(),lp=S.z.object({rows:S.z.array(Wi).max(100),nextCursor:S.z.uuid().nullable()}).strict(),Zd=S.z.strictObject({id:S.z.string(),coupon:S.z.string(),start:S.z.number().nonnegative(),end:S.z.number().nullable()}),gb=S.z.strictObject({subscriptionId:S.z.string(),customerId:S.z.string(),accountId:S.z.string(),sourceItems:S.z.array(S.z.strictObject({id:S.z.string(),price_id:S.z.string(),quantity:S.z.number().int(),discounts:S.z.array(Zd).optional()})).max(100),items:S.z.array(S.z.strictObject({id:S.z.string(),price:S.z.string(),quantity:S.z.number().int(),discounts:S.z.array(S.z.strictObject({coupon:S.z.string().optional(),terms:S.z.strictObject({id:S.z.string(),name:S.z.string().optional(),percent_off:S.z.number().optional(),amount_off:S.z.number().optional(),currency:S.z.string().optional(),duration:S.z.enum(["once","forever","repeating"]),duration_in_months:S.z.number().optional()}).optional(),discount:S.z.string().optional(),receipt:Zd.optional()})).max(20)})).max(100)}),dp=S.z.strictObject({membershipId:S.z.uuid(),requestId:S.z.uuid(),grantIds:S.z.array(S.z.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),pp=S.z.strictObject({membershipId:S.z.uuid(),operationId:S.z.uuid(),status:S.z.enum(["pending","effective"]),execution:gb.nullable(),grants:S.z.array(S.z.strictObject({id:S.z.uuid(),couponId:S.z.uuid(),name:S.z.string(),discount:ir,duration:un,startedAt:Gt.nullable()})).max(20)});var li=require("zod");var mp=li.z.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),fp=li.z.number().int().min(1).max(1e3),ha=li.z.object({cap:xe.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:li.z.number().positive().max(1e4).nullable(),cycles:li.z.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");var Zn=require("zod");var gp=Zn.z.strictObject({itemKey:Zn.z.string().regex(/^paid:feature:[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),internal_feature_id:Zn.z.uuid(),includedAmount:Zn.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:Zn.z.number().int().min(0).max(1e4),terms:ra,pricing:$i.optional(),unitAmountMinor:Zn.z.number().int().min(0).max(1e8),productId:Zn.z.string().min(1).max(255).nullable(),priceId:Zn.z.string().min(1).max(255).nullable()}).superRefine((e,t)=>{(e.quantity<e.terms.minimumQuantity||e.quantity>e.terms.maximumQuantity||e.productId===null!=(e.priceId===null)||e.quantity>0&&(e.pricing||e.unitAmountMinor>0)&&e.priceId===null)&&t.addIssue({code:"custom",message:"Purchased quantities need their published bounds and immutable price binding"});try{ad(e.includedAmount,e.terms.units,e.quantity),na({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{t.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});var te=require("zod");var Tr=xe.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Yi=te.z.string().min(1).max(120),ya=te.z.enum(["cap","overflow"]),ln=(e,t)=>{let[n,r=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");return BigInt(n)*10n**BigInt(t)+BigInt(r.padEnd(t,"0"))},Xi=e=>{try{return e()}catch{return!1}},eo=te.z.discriminatedUnion("operation",[te.z.object({operation:te.z.literal("quote"),overageBehavior:ya.optional(),internal_feature_id:te.z.uuid(),entityId:te.z.uuid().optional(),quantity:Tr,properties:Pt}).strict(),te.z.object({operation:te.z.literal("consume"),overageBehavior:ya.optional(),occurredAt:te.z.iso.datetime({offset:!0}).optional(),internal_feature_id:te.z.uuid(),entityId:te.z.uuid().optional(),quantity:xe,properties:Pt,idempotencyKey:Yi}).strict(),te.z.object({operation:te.z.literal("reserve"),occurredAt:te.z.iso.datetime({offset:!0}).optional(),internal_feature_id:te.z.uuid(),entityId:te.z.uuid().optional(),quantity:Tr,properties:Pt,idempotencyKey:Yi,expiresInSeconds:te.z.number().int().min(1).max(86400)}).strict(),te.z.object({operation:te.z.literal("confirm"),operationId:te.z.uuid(),quantity:Tr,properties:Pt.optional(),idempotencyKey:Yi}).strict(),te.z.object({operation:te.z.literal("refund"),operationId:te.z.uuid(),quantity:Tr,idempotencyKey:Yi}).strict(),te.z.object({operation:te.z.literal("release"),operationId:te.z.uuid(),idempotencyKey:Yi}).strict()]),mc=te.z.object({internal_credit_feature_id:te.z.uuid().nullable(),internal_metered_feature_id:te.z.uuid(),dimension:te.z.string().min(1).max(64),counterKey:te.z.string().min(1).max(240),cycleStart:te.z.iso.datetime({offset:!0}),unitCost:xe,units:Tr,amount:Wt,tier:te.z.number().int().min(1).max(12).nullable()}).strict(),Nr=te.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function hp(e,t){let n=e.reduce((r,i)=>r+ln(i.units,12),0n)-ln(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var yp=te.z.discriminatedUnion("funding",[te.z.strictObject({funding:te.z.literal("balance"),sourceId:te.z.uuid(),rolloverId:te.z.uuid().nullable(),units:Nr.refine(e=>/[1-9]/.test(e)),amount:Wt}),te.z.strictObject({funding:te.z.literal("unbilled"),units:Nr.refine(e=>/[1-9]/.test(e))}),te.z.object({funding:te.z.literal("prepaid"),sourceId:te.z.uuid(),units:Tr,amount:Wt,pricing:te.z.array(mc).min(1).max(12)}).strict().refine(e=>Xi(()=>e.pricing.reduce((t,n)=>t+ln(n.units,6),0n)===ln(e.units,6)&&e.pricing.reduce((t,n)=>t+ln(n.amount,12),0n)===ln(e.amount,12)&&e.pricing.every(t=>ln(t.unitCost,6)*ln(t.units,6)===ln(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),te.z.object({funding:te.z.literal("postpaid"),invoiceLineId:te.z.uuid().nullable(),units:Tr,authorizationId:te.z.uuid()}).strict()]),Aa=te.z.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),Ap=te.z.object({allowed:te.z.boolean(),internal_feature_id:te.z.uuid(),quantity:xe,requestedQuantity:xe.optional(),overageBehavior:ya.optional(),reason:Aa.nullable(),allocations:te.z.array(yp).max(500)}).strict().refine(e=>Xi(()=>e.allowed?e.reason===null&&hp(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>Xi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&ln(e.requestedQuantity,6)>=ln(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),to=te.z.object({id:te.z.uuid(),internal_feature_id:te.z.uuid(),kind:te.z.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:te.z.uuid().nullable(),quantity:xe,requestedQuantity:xe.optional(),overageBehavior:ya.optional(),accepted:te.z.boolean(),reason:te.z.enum([...Aa.options,"expired"]).nullable(),createdAt:te.z.iso.datetime({offset:!0}),reservationStatus:te.z.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:te.z.iso.datetime({offset:!0}).nullable(),allocations:te.z.array(yp).max(500)}).strict().refine(e=>Xi(()=>e.accepted?e.reason===null&&hp(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>Xi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&ln(e.requestedQuantity,6)>=ln(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");var Te=require("zod");var Dr=Te.z.iso.datetime({offset:!0}),bp=xe.refine(e=>/[1-9]/.test(e)),xp=Te.z.strictObject({interval:mp.exclude(["lifetime"]),count:fp}),hb=Te.z.strictObject({action:Te.z.literal("create"),requestId:Te.z.uuid(),internal_feature_id:Te.z.uuid(),entityId:Te.z.uuid().nullable(),amount:bp.nullable(),expiresAt:Dr.nullable(),reset:xp.nullable(),rollover:ha.nullable(),nextResetAt:Dr.nullable()}).refine(e=>e.amount!==null||e.reset===null&&e.rollover===null,"Unlimited grants cannot reset or roll over").refine(e=>!e.rollover||e.reset!==null,"Rollover requires a recurring grant").refine(e=>e.nextResetAt===null||e.reset!==null&&(e.expiresAt===null||Date.parse(e.nextResetAt)<Date.parse(e.expiresAt)),"The first reset needs a reset interval and must precede expiry"),Sp=Te.z.discriminatedUnion("action",[hb,Te.z.strictObject({action:Te.z.literal("update"),requestId:Te.z.uuid(),grantId:Te.z.uuid(),revision:Te.z.number().int().nonnegative(),amount:bp.nullable(),expiresAt:Dr.nullable(),rollover:ha.nullable(),nextResetAt:Dr.nullable()}),Te.z.strictObject({action:Te.z.enum(["add","subtract","set_remaining"]),requestId:Te.z.uuid(),grantId:Te.z.uuid(),revision:Te.z.number().int().nonnegative(),amount:xe}),Te.z.strictObject({action:Te.z.literal("revoke"),requestId:Te.z.uuid(),grantId:Te.z.uuid(),revision:Te.z.number().int().nonnegative()})]),fc=Te.z.strictObject({id:Te.z.uuid(),internal_feature_id:Te.z.uuid(),entityId:Te.z.uuid().nullable(),amount:xe.nullable(),reset:xp.nullable(),rollover:ha.nullable(),nextResetAt:Dr.nullable(),startsAt:Dr,expiresAt:Dr.nullable(),revision:Te.z.number().int().nonnegative(),revoked:Te.z.boolean(),available:Wt,held:Wt,spent:Wt}),Ip=Te.z.strictObject({customerId:Te.z.uuid(),after:Te.z.uuid().nullable(),limit:Te.z.number().int().min(1).max(100)}),vp=Te.z.strictObject({rows:Te.z.array(fc).max(100),nextCursor:Te.z.uuid().nullable()});var ie=require("zod");var Dn=ie.z.iso.datetime({offset:!0}),wp=ie.z.strictObject({invoiceId:ie.z.uuid(),after:ie.z.string().min(1).max(180).nullable(),limit:ie.z.number().int().min(1).max(100)}),yb=ie.z.strictObject({kind:ie.z.literal("product"),key:ie.z.string(),productVersionId:ie.z.uuid(),productName:ie.z.string(),itemKey:ie.z.string(),entityId:ie.z.uuid().nullable(),quantity:ie.z.number().positive(),subtotalMinor:ie.z.string().regex(/^-?\d+$/),discountMinor:ie.z.string().regex(/^\d+$/),taxMinor:ie.z.string().regex(/^-?\d+$/).nullable(),totalMinor:ie.z.string().regex(/^-?\d+$/),startsAt:Dn.nullable(),endsAt:Dn.nullable(),providerLineId:ie.z.string().nullable(),providerItemId:ie.z.string()}),Op=ie.z.strictObject({invoice:Wi,items:ie.z.array(ie.z.discriminatedUnion("kind",[yb,ie.z.strictObject({kind:ie.z.literal("invoice_credit"),key:ie.z.string(),internal_feature_id:ie.z.uuid(),internal_credit_feature_id:ie.z.uuid(),name:ie.z.string(),units:xe,reserved:xe,amountMinor:ui,grossAmountMinor:ui,creditsAppliedMinor:ui,properties:Pt,cashPrice:Zi,providerItemId:ie.z.string().nullable(),creditProviderItemId:ie.z.string().nullable()}),ie.z.strictObject({kind:ie.z.literal("usage"),key:ie.z.string(),internal_feature_id:ie.z.uuid(),name:ie.z.string(),units:xe,reserved:xe,amountMinor:ui,cashPrice:Zi})])).max(100),nextCursor:ie.z.string().min(1).max(180).nullable()}),Ab=ie.z.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),gc=ie.z.strictObject({from:Dn,to:Dn,entityId:ie.z.uuid().optional(),snapshotAt:Dn.nullable(),after:ie.z.strictObject({at:Dn,id:ie.z.uuid(),position:ie.z.number().int().nonnegative()}).nullable(),limit:ie.z.number().int().min(1).max(100)}).refine(e=>Date.parse(e.from)<Date.parse(e.to)&&Date.parse(e.to)-Date.parse(e.from)<=366*864e5,"Statement range must be positive and at most 366 days").refine(e=>e.after===null||e.snapshotAt!==null,"A cursor requires the original snapshot time"),Pp=ie.z.strictObject({customerId:ie.z.uuid(),entityId:ie.z.uuid().nullable(),from:Dn,to:Dn,snapshotAt:Dn,totals:ie.z.array(ie.z.strictObject({internal_credit_feature_id:ie.z.uuid(),name:ie.z.string(),consumed:Wt,refunded:Wt,net:Ab})).max(1e3),rows:ie.z.array(ie.z.strictObject({operationId:ie.z.uuid(),position:ie.z.number().int().nonnegative(),kind:ie.z.enum(["consume","confirm","refund"]),originalId:ie.z.uuid().nullable(),occurredAt:Dn,internal_feature_id:ie.z.uuid(),entitlementName:ie.z.string(),sourceId:ie.z.uuid(),internal_credit_feature_id:ie.z.uuid(),creditName:ie.z.string(),units:Nr,amount:Wt,pricing:ie.z.array(mc).max(12),properties:Pt})).max(100),nextCursor:gc.shape.after});var D=require("zod");var yn=require("zod");var bb=yn.z.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),xb=yn.z.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),ba=yn.z.strictObject({internal_feature_id:yn.z.uuid(),entityId:yn.z.uuid().nullable()}),Cp=ba.extend({quantity:xe,expectedRevision:yn.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:yn.z.string().min(1).max(120),properties:Pt.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),no=ba.extend({operationId:yn.z.uuid().nullable(),usage:xe,capacity:bb.nullable(),remaining:xb.nullable(),withinLimit:yn.z.boolean(),revision:yn.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:yn.z.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let n=r=>{let i=r.startsWith("-"),[a,o=""]=(i?r.slice(1):r).split(".");if(a===void 0||a==="")throw new Error("Invalid decimal value");return(i?-1n:1n)*(BigInt(a)*10n**12n+BigInt(o.padEnd(12,"0")))};(e.capacity===null!=(e.remaining===null)||(e.capacity===null?!e.withinLimit:e.remaining===null||n(e.remaining)!==n(e.capacity)-n(e.usage)||e.withinLimit!==n(e.remaining)>=0n)||e.revision===0!=(e.operationId===null)||e.operationId===null!=(e.updatedAt===null))&&t.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var Kt=D.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),On=D.z.iso.datetime({offset:!0}),Sb=D.z.enum(["access","metered","credit"]),ro={internal_feature_id:D.z.uuid(),key:Er,name:D.z.string().min(1).max(120),kind:Sb},_p=D.z.object({customerId:D.z.uuid(),snapshotAt:On,memberships:D.z.array(D.z.object({id:D.z.uuid(),productId:D.z.string().min(1).max(255),productVersionId:D.z.uuid(),billingProductVersionId:D.z.uuid(),version:D.z.number().int().positive(),key:D.z.string().min(1).max(64),name:D.z.string().min(1).max(120),groupId:D.z.string().max(255).nullable(),membershipType:D.z.enum(["main","addon"]),status:D.z.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:D.z.boolean(),accessEnabled:D.z.boolean(),renewalChange:D.z.object({productVersionId:D.z.uuid(),name:D.z.string().min(1).max(120),version:D.z.number().int().positive(),effectiveAt:On,benefitsAppliedAt:On.nullable(),timing:D.z.enum(["immediate","renewal"]),changeKind:D.z.enum(["plan","seats","quantity"]),feature:D.z.strictObject({internal_feature_id:D.z.uuid(),name:D.z.string().min(1).max(80),fromQuantity:D.z.number().int().min(0).max(1e4),toQuantity:D.z.number().int().min(0).max(1e4)}).optional(),seat:D.z.object({key:D.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:D.z.number().int().min(0).max(1e4),toQuantity:D.z.number().int().min(0).max(1e4)}).strict().nullable(),status:D.z.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(e=>e.changeKind==="seats"==(e.seat!==null)&&e.changeKind==="quantity"==(e.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:D.z.object({phase:D.z.enum(["paid","trial"]),startsAt:On,endsAt:On.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:D.z.boolean(),balances:D.z.array(D.z.object({...ro,usageType:D.z.enum(["consumable","non_consumable"]).nullable(),accessible:D.z.boolean(),unlimited:D.z.boolean(),available:Kt,held:Kt,debt:Kt,nextExpiresAt:On.nullable(),usage:no.nullable()}).strict().refine(e=>e.kind==="metered"==(e.usageType!==null)&&(e.accessible||e.available==="0"&&e.held==="0")&&(e.usageType==="non_consumable"?e.usage!==null&&e.usage.internal_feature_id===e.internal_feature_id&&e.unlimited===(e.usage.capacity===null)&&e.available===(e.usage.remaining===null||e.usage.remaining.startsWith("-")?"0":e.usage.remaining)&&e.held==="0"&&e.debt==="0":e.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:D.z.boolean()}).strict(),Ep=D.z.enum(["source","usage","transaction","invoice","debt","settlement"]),xa=D.z.object({at:On,id:D.z.uuid(),type:Ep}).strict(),Rp=D.z.object({type:Ep.nullable(),resourceKey:Er.optional(),kind:D.z.enum(["purchase","refund"]).optional(),topup:D.z.boolean().optional(),from:D.z.iso.date().nullable(),to:D.z.iso.date().nullable(),after:xa.nullable(),limit:D.z.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),di={id:D.z.uuid(),occurredAt:On},Ib=D.z.discriminatedUnion("type",[D.z.strictObject({...di,type:D.z.literal("invoice"),status:D.z.string().min(1).max(80),paid:Kt,refunded:Kt,currency:Ie,externalId:D.z.string().nullable()}),D.z.object({...di,...ro,type:D.z.literal("source"),reason:D.z.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:Kt,unlimited:D.z.boolean(),status:D.z.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:On,expiresAt:On.nullable(),orderId:D.z.uuid().nullable(),parentSourceId:D.z.uuid().nullable()}).strict(),D.z.object({...di,type:D.z.literal("usage"),internal_feature_id:D.z.uuid(),name:D.z.string().min(1).max(120),kind:D.z.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:D.z.uuid().nullable(),quantity:xe,accepted:D.z.boolean(),reason:D.z.enum([...Aa.options,"expired"]).nullable(),properties:Pt,reservationStatus:D.z.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:On.nullable(),charges:D.z.array(D.z.discriminatedUnion("funding",[D.z.strictObject({funding:D.z.literal("balance"),sourceId:D.z.uuid(),rolloverId:D.z.uuid().nullable(),units:Nr,amount:Kt}),D.z.strictObject({funding:D.z.literal("unbilled"),units:Nr}),D.z.object({...ro,funding:D.z.literal("prepaid"),amount:Kt}).strict(),D.z.object({funding:D.z.literal("postpaid"),invoiceId:D.z.uuid(),invoiceLineId:D.z.uuid(),authorizationId:D.z.uuid(),units:xe,currency:Ie}).strict()])).max(500)}).strict().refine(e=>(e.kind==="set_usage"||e.kind==="consume"&&e.quantity==="0"?e.accepted&&e.reason===null&&e.charges.length===0&&e.reservationStatus===null:e.accepted?e.reason===null&&e.charges.length>0:e.reason!==null&&e.charges.length===0)&&e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),D.z.object({...di,type:D.z.literal("transaction"),purpose:D.z.enum(["product","invoice"]),productVersionId:D.z.uuid().nullable(),productName:D.z.string().min(1).max(120).nullable(),productVersion:D.z.number().int().positive().nullable(),invoiceId:D.z.uuid().nullable(),orderId:D.z.uuid(),originalId:D.z.uuid().nullable(),kind:D.z.enum(["purchase","refund"]),amountMinor:D.z.number().int().nonnegative().max(2e8).nullable(),currency:Ie.nullable()}).strict().refine(e=>e.currency===null==(e.amountMinor===null)&&(e.purpose==="product"?e.productVersionId!==null&&e.productName!==null&&e.productVersion!==null&&e.invoiceId===null:e.productVersionId===null&&e.productName===null&&e.productVersion===null&&e.invoiceId!==null)&&e.kind==="refund"==(e.originalId!==null)&&(e.kind!=="refund"||e.amountMinor===null||e.amountMinor>0),"Payment fact provenance is incomplete"),D.z.object({...di,...ro,type:D.z.literal("debt"),sourceId:D.z.uuid(),transactionId:D.z.uuid(),amount:Kt}).strict(),D.z.object({...di,...ro,type:D.z.literal("settlement"),sourceId:D.z.uuid(),debtId:D.z.uuid(),kind:D.z.enum(["payment","usage_refund","payment_return"]),amount:Kt}).strict()]),kp=D.z.object({customerId:D.z.uuid(),rows:D.z.array(Ib).max(50),nextCursor:xa.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");var fe=require("zod"),Tp=fe.z.object({customerId:fe.z.uuid()}).strict(),Np=fe.z.discriminatedUnion("action",[fe.z.object({customerId:fe.z.uuid(),requestId:fe.z.uuid(),action:fe.z.literal("assign"),poolId:fe.z.uuid(),memberCustomerId:fe.z.uuid()}).strict(),fe.z.strictObject({customerId:fe.z.uuid(),requestId:fe.z.uuid(),action:fe.z.literal("assign_entity"),poolId:fe.z.uuid(),entityId:fe.z.uuid()}),fe.z.object({customerId:fe.z.uuid(),requestId:fe.z.uuid(),action:fe.z.literal("release"),poolId:fe.z.uuid(),slotId:fe.z.uuid()}).strict()]),io=fe.z.number().int().nonnegative(),hc=fe.z.iso.datetime({offset:!0}),yc=fe.z.strictObject({internalId:fe.z.uuid(),id:fe.z.string(),name:fe.z.string().nullable(),version:fe.z.number().int().positive()}),jp=fe.z.enum(["active","past_due"]),Ac=fe.z.strictObject({customerId:fe.z.uuid(),licenses:fe.z.array(fe.z.strictObject({id:fe.z.uuid(),linkId:fe.z.uuid(),parent:fe.z.strictObject({customerProductId:fe.z.uuid(),status:jp,product:yc}),product:yc,planLicense:fe.z.strictObject({id:fe.z.uuid(),prepaidOnly:fe.z.boolean(),isCustom:fe.z.boolean()}).nullable(),granted:io,included:io,paidQuantity:io,usage:io,remaining:io,createdAt:hc}).refine(e=>e.granted===e.included+e.paidQuantity&&e.granted===e.usage+e.remaining,"Granted seats are included plus paid, and usage plus remaining")).max(2e3),assignments:fe.z.array(fe.z.strictObject({id:fe.z.uuid(),linkId:fe.z.uuid(),status:jp,product:yc,entity:fe.z.strictObject({internalId:fe.z.uuid(),id:fe.z.string().nullable(),name:fe.z.string().nullable()}).nullable(),beneficiary:fe.z.strictObject({internalId:fe.z.uuid(),id:fe.z.string().nullable(),name:fe.z.string().nullable()}).nullable(),startedAt:hc.nullable(),endedAt:hc.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:fe.z.boolean()});var de=require("zod"),oo=de.z.enum(["email","sms","voice","push"]),aP=de.z.enum(["resend","twilio","fcm","apns"]);var sP=de.z.string().regex(/^\+[1-9]\d{1,14}$/),vb=de.z.enum(["email_recipient","sms_segment","voice_second","push_device"]);var wb=de.z.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),Ob=de.z.strictObject({subject:wb,html:de.z.string().min(1).max(131072).optional(),text:de.z.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),Pb=de.z.strictObject({body:de.z.string().min(1).max(1600).refine(e=>e.trim().length>0)}),Cb=de.z.strictObject({text:de.z.string().trim().min(1).max(4e3),language:de.z.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:de.z.number().int().min(1).max(900)}),_b=de.z.record(de.z.string().min(1).max(64),de.z.string().max(256)).refine(e=>Object.keys(e).length<=20&&Object.keys(e).every(t=>!/^(?:indiana_|google\.|gcm\.)/i.test(t)&&t!=="aps"),"Push data contains reserved fields or too many entries"),Eb=de.z.strictObject({title:de.z.string().trim().min(1).max(200),body:de.z.string().trim().min(1).max(2e3),url:de.z.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:_b.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),Dp=de.z.discriminatedUnion("channel",[de.z.strictObject({channel:de.z.literal("email"),content:Ob}),de.z.strictObject({channel:de.z.literal("sms"),content:Pb}),de.z.strictObject({channel:de.z.literal("voice"),content:Cb}),de.z.strictObject({channel:de.z.literal("push"),content:Eb})]),Fp=de.z.strictObject({requestId:de.z.uuid(),customerId:de.z.uuid(),connectionId:de.z.uuid().optional(),message:Dp,expiresAt:de.z.iso.datetime({offset:!0})}),Rb=de.z.array(de.z.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),kb=de.z.discriminatedUnion("kind",[de.z.strictObject({kind:de.z.literal("all")}),de.z.strictObject({kind:de.z.literal("customers"),customerIds:Rb})]),cP=de.z.strictObject({name:de.z.string().trim().min(1).max(120),connectionId:de.z.uuid().optional(),message:Dp,audience:kb,frequencyLimit:de.z.number().int().min(1).max(100)}),Mp=de.z.strictObject({requestId:de.z.uuid(),channel:oo,state:de.z.enum(["allowed","denied"]),expectedRevision:de.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),qp=de.z.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Up=de.z.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),uP=de.z.strictObject({meter:vb,estimatedUnits:de.z.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:de.z.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});var Oe=require("zod");var re=require("zod");var Fr=require("zod");var ao=Fr.z.strictObject({internalFeatureId:Fr.z.uuid(),name:Fr.z.string().min(1).max(120),includedAmount:Fr.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:Fr.z.enum(["hour","day","week","month","year","lifetime"]),resetCount:Fr.z.number().int().min(1).max(100),terms:ra});var st=require("zod");var Lp=require("zod");var Mr=require("zod"),Bp=Mr.z.enum(["stripe","apple","google","merchant"]),Vp=Mr.z.enum(["membership","credit_pack","lifetime"]),mP=Mr.z.enum(["active","grace","suspended","inactive","revoked"]),fP=Mr.z.strictObject({currency:Mr.z.string().regex(/^[A-Z]{3}$/),micros:Mr.z.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var pi=Lp.z.object({provider:Bp,currency:Ie}).strict();var or=st.z.strictObject({internal_feature_id:st.z.uuid(),quantity:xe.refine(e=>/[1-9]/.test(e)),properties:Pt,entityId:st.z.uuid().optional()}),zp=st.z.strictObject({requirement:or,commerce:pi.optional(),paywallId:st.z.uuid().optional()}),jb=st.z.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),bc=st.z.strictObject({productId:st.z.string().min(1),productVersionId:st.z.string().min(1),name:st.z.string().min(1).max(120),action:st.z.enum(["purchase","upgrade","addon","topup"]),membershipId:st.z.string().min(1).nullable(),currency:Ie,amountMinor:st.z.string().regex(/^(0|[1-9]\d{0,8})$/),interval:st.z.enum(["free","week","month","year","one_time"]),intervalCount:st.z.number().int().min(1).max(156)}),qr=st.z.strictObject({internal_feature_id:st.z.string().min(1),name:st.z.string().min(1).max(120),kind:st.z.enum(["access","metered","credit"]),quantity:xe,allowed:st.z.boolean(),reason:jb.nullable(),preview:st.z.strictObject({scenario:st.z.enum(["feature_flag","usage_limit"]),candidates:st.z.array(bc).max(20)}).nullable()}).superRefine((e,t)=>{(e.allowed!==(e.reason===null)||e.allowed&&e.preview!==null||new Set(e.preview?.candidates.map(n=>n.productVersionId)).size!==(e.preview?.candidates.length??0)||e.preview?.candidates.some(n=>n.action==="upgrade"!=(n.membershipId!==null)))&&t.addIssue({code:"custom",message:"Invalid access recommendation"})}),IP=st.z.strictObject({paywallId:st.z.uuid(),requirement:or});var Ia=re.z.object({plan:re.z.string().min(1).max(200).optional(),coupon:re.z.uuid().optional(),promotionCode:re.z.uuid().optional(),picker:re.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),Sa=re.z.object({text:re.z.string().optional(),label:re.z.string().optional(),alt:re.z.string().optional(),html:re.z.string().max(32768).optional(),price:re.z.object({current:re.z.string(),original:re.z.string().nullable(),period:re.z.string()}).optional(),code:re.z.string().optional(),countdownAt:re.z.iso.datetime().optional(),planId:re.z.string().min(1).max(200).optional(),planVersionId:re.z.string().min(1).max(200).optional(),currency:Ie.optional(),couponId:re.z.uuid().optional(),offerId:re.z.uuid().optional(),unavailable:re.z.boolean().optional(),unavailableReason:re.z.string().optional(),missing:re.z.array(re.z.string()).optional()}).strict(),mi=re.z.object({paywall:qr.optional(),nodes:re.z.record(re.z.string(),re.z.object({base:Sa,picker:re.z.string().optional(),byPlan:re.z.record(re.z.string(),Sa).optional()}).strict()),plans:re.z.record(re.z.string(),re.z.object({id:re.z.string().min(1).max(200),versionId:re.z.string().min(1).max(200),available:re.z.boolean(),name:re.z.string(),price:re.z.string(),period:re.z.string(),currency:Ie.optional(),amountMinor:re.z.number().int().nonnegative().optional(),interval:re.z.enum(["free","week","month","year","one_time"]).optional(),intervalCount:re.z.number().int().positive().optional(),prepaid:re.z.array(ao).max(100).optional()}).strict()),pickers:re.z.record(re.z.string(),re.z.object({options:re.z.array(re.z.string().min(1).max(200)).max(20),selected:re.z.string().min(1).max(200).nullable()}).strict()),quantities:re.z.record(re.z.string(),re.z.strictObject({minimum:re.z.number().int().nonnegative(),maximum:re.z.number().int().nonnegative(),step:re.z.number().int().positive(),value:re.z.number().int().nonnegative(),label:re.z.string(),available:re.z.boolean()})).optional(),diagnostics:re.z.array(re.z.object({nodeId:re.z.string(),message:re.z.string()}).strict())}).strict();function $p(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}var I=require("zod");function Tb(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function Gp(e){let t={};function n(r){var i;if(Tb(r)){let a=t[i=r.interaction.pickerId]??(t[i]={ids:[],defaultId:null});for(let s of r.children){let c=s.type==="stack"?s.bind?.plan:void 0;c&&!a.ids.includes(c)&&a.ids.push(c)}let o=r.children[r.interaction.defaultIndex];!a.defaultId&&o?.type==="stack"&&(a.defaultId=o.bind?.plan??null)}r.type==="stack"&&r.children.forEach(n)}return e.pages.forEach(r=>n(r.root)),t}var Fn=require("zod"),Kp=Fn.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),va=Fn.z.strictObject({tiers:Fn.z.array(Fn.z.strictObject({id:Kp,name:Fn.z.string().trim().min(1).max(80)})).min(1).max(8),assignments:Fn.z.array(Fn.z.strictObject({productVersionId:Fn.z.string().min(1).max(200),tierId:Kp,period:Fn.z.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let n=e.tiers.map(r=>r.id);(new Set(n).size!==n.length||new Set(e.assignments.map(r=>r.productVersionId)).size!==e.assignments.length||new Set(e.assignments.map(r=>`${r.tierId}:${r.period}`)).size!==e.assignments.length||e.assignments.some(r=>!n.includes(r.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function wa(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}var ce=require("zod");var Nb=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],Hp=ce.z.enum(Nb),Qp=ce.z.object({source:Hp,layout:ce.z.enum(["full","compact"]),resourceKey:Er.optional(),pageSize:ce.z.number().int().min(1).max(50),showSources:ce.z.boolean(),allowPurchase:ce.z.boolean(),outputs:ce.z.object({billing_adjustment:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((e,t)=>{(e.outputs?.billing_authorization||e.outputs?.billing_adjustment)&&e.source!=="billing_controls"&&t.addIssue({code:"custom",message:"Payment authorization routes belong to the billing controls component."}),e.resourceKey&&!["credit_balance","credit_transactions"].includes(e.source)&&t.addIssue({code:"custom",message:"\u8FD9\u4E2A\u6570\u636E\u6E90\u4E0D\u80FD\u7ED1\u5B9A\u79EF\u5206\u8D44\u6E90\u3002"}),e.showSources&&e.source!=="credit_balance"&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u4F59\u989D\u53EF\u4EE5\u5C55\u5F00\u6765\u6E90\u3002"}),e.allowPurchase&&!["credit_packs","customer_plans","membership"].includes(e.source)&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u5305\u3001\u5957\u9910\u4E0E\u4F1A\u5458\u7EC4\u4EF6\u53EF\u4EE5\u542F\u7528\u4EA4\u6613\u3002"})}),kt=ce.z.string().max(2e3),Jp=ce.z.object({id:ce.z.string().max(100),label:kt,detail:ce.z.array(kt).max(12),value:kt.optional(),status:kt.optional(),facts:ce.z.array(ce.z.object({label:kt,value:kt}).strict()).max(1e3),purchaseId:ce.z.uuid().optional(),invoiceUrl:ce.z.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:ce.z.array(ce.z.strictObject({action:ce.z.literal("invoice_open"),label:kt})).max(1).optional(),membershipActions:ce.z.array(ce.z.object({value:ce.z.string().max(100),label:kt}).strict()).max(3).optional()}).strict(),Db=ce.z.object({key:Er,name:kt,spendable:kt,reserved:kt,available:kt,expiry:kt.nullable(),sources:ce.z.array(Jp).max(50),sourceCount:ce.z.number().int().nonnegative(),sourcePage:ce.z.number().int().positive(),hasNextSources:ce.z.boolean(),hasPreviousSources:ce.z.boolean()}).strict(),Fb=ce.z.object({source:Hp,status:ce.z.enum(["idle","loading","ready","error"]),stale:ce.z.boolean(),preview:ce.z.boolean(),errorCode:ce.z.string().max(80).optional(),errorMessage:kt.optional(),resources:ce.z.array(Db).max(500),rows:ce.z.array(Jp).max(50),hasNext:ce.z.boolean(),hasPrevious:ce.z.boolean(),page:ce.z.number().int().positive(),filter:ce.z.string().max(40),updatedAt:ce.z.iso.datetime().optional(),buyingId:ce.z.uuid().optional(),membershipBusy:ce.z.boolean().optional(),billingBusy:ce.z.boolean().optional(),membershipReview:ce.z.object({title:kt,note:kt,facts:ce.z.array(ce.z.object({label:kt,value:kt}).strict()).max(100)}).strict().optional(),membershipResult:kt.optional()}).strict(),Zp=ce.z.object({nodes:ce.z.record(ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Fb)}).strict(),kP=ce.z.object({nodeId:ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:ce.z.enum(["refresh","next","previous","filter","buy_pack","billing_portal","billing_authorization","billing_adjustment","invoice_open","membership_preview","membership_confirm","membership_dismiss","sources_next","sources_previous"]),value:ce.z.string().max(100).optional()}).strict();var K=require("zod"),St={state:32,enumValues:64,derived:96,bindings:256,controls:64,timers:4,effects:8,depth:12,expressionNodes:2e3},Yp=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]),Ft=K.z.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/).refine(e=>!Yp.has(e),"Reserved UI identifier"),xc=K.z.union([K.z.string().max(2e3),K.z.number().finite(),K.z.boolean(),K.z.null()]),Mb=K.z.discriminatedUnion("type",[K.z.strictObject({type:K.z.literal("enum"),values:K.z.array(xc).min(1).max(St.enumValues),default:xc}),K.z.strictObject({type:K.z.literal("number"),min:K.z.number().finite(),max:K.z.number().finite(),step:K.z.number().finite().positive(),default:K.z.number().finite()}),K.z.strictObject({type:K.z.literal("text"),maxLength:K.z.number().int().min(0).max(2e3),default:K.z.string().max(2e3).nullable()}),K.z.strictObject({type:K.z.literal("boolean"),default:K.z.boolean()})]);function Ic(e,t){if(e.type==="enum")return e.values.some(r=>r===t);if(e.type==="boolean")return typeof t=="boolean";if(e.type==="text")return t===null||typeof t=="string"&&t.length<=e.maxLength;if(typeof t!="number"||!Number.isFinite(t)||t<e.min||t>e.max)return!1;let n=(t-e.min)/e.step;return Number.isFinite(n)&&Math.abs(n-Math.round(n))<=Math.min(1e-7,Math.max(1,Math.abs(n))*Number.EPSILON*8)}var qb=Mb.superRefine((e,t)=>{e.type==="enum"&&new Set(e.values).size!==e.values.length&&t.addIssue({code:"custom",path:["values"],message:"UI enum values must be unique"}),e.type==="number"&&e.min>e.max&&t.addIssue({code:"custom",path:["max"],message:"UI number range is reversed"}),Ic(e,e.default)||t.addIssue({code:"custom",path:["default"],message:"UI default must match its state definition"})}),Ub=["add","sub","mul","div","min","max","round","floor","eq","ne","gt","gte","lt","lte","and","or","not","if","concat","number","parse_number","money","lookup","now","duration"];function Bb(e,t){return e==="now"?t===0:e==="concat"?!0:e==="lookup"?t>=4&&t%2===0:e==="if"?t===3:["sub","div","eq","ne","gt","gte","lt","lte"].includes(e)?t===2:["round","floor","not","number","parse_number","money","duration"].includes(e)?t===1:t>=1}var Br=K.z.lazy(()=>K.z.union([xc,K.z.strictObject({ref:Ft}),K.z.strictObject({op:K.z.enum(Ub),args:K.z.array(Br).max(St.expressionNodes)}).superRefine((e,t)=>{Bb(e.op,e.args.length)||t.addIssue({code:"custom",path:["args"],message:"Invalid UI expression arity"})})]));function Pn(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function Ur(e,t,n){if(!e||typeof e!="object")return!0;if(!Pn(e))return t.addIssue({code:"custom",path:n,message:"UI objects must be plain data"}),!1;for(let r of Object.keys(e)){if(Yp.has(r))return t.addIssue({code:"custom",path:[...n,r],message:"Reserved UI object key"}),!1;let i=Object.getOwnPropertyDescriptor(e,r);if(i&&!Object.hasOwn(i,"value"))return t.addIssue({code:"custom",path:[...n,r],message:"UI objects cannot contain accessors"}),!1}return!0}function fi(e,t,n,r){let i=[{value:e,depth:1,path:n}];for(;i.length;){let a=i.pop();if(++r.nodes>St.expressionNodes||a.depth>St.depth){t.addIssue({code:"custom",path:a.path,message:"UI expression budget exceeded"});return}if(!Ur(a.value,t,a.path))return;if(Pn(a.value)&&Array.isArray(a.value.args)){if(a.value.args.length>St.expressionNodes){t.addIssue({code:"custom",path:[...a.path,"args"],message:"UI expression budget exceeded"});return}for(let o=a.value.args.length-1;o>=0;o--)i.push({value:a.value.args[o],depth:a.depth+1,path:[...a.path,"args",o]})}}}var TP=K.z.unknown().superRefine((e,t)=>{fi(e,t,[],{nodes:0})}).pipe(Br),Sc=K.z.record(Ft,Br).refine(e=>Object.keys(e).length>0&&Object.keys(e).length<=St.state,"UI assignments need 1\u201332 state keys"),Vb=K.z.strictObject({target:Ft,property:K.z.enum(["text","visible","disabled","checked","value","class","aria-label","aria-selected","aria-checked","aria-valuetext","tabindex"]),expression:Br,className:Ft.optional()}).superRefine((e,t)=>{e.property==="class"!=(e.className!==void 0)&&t.addIssue({code:"custom",path:["className"],message:"Only class bindings require a safe className"})}),Lb=K.z.discriminatedUnion("type",[K.z.strictObject({type:K.z.literal("scroll_latch"),target:Ft,state:Ft}),K.z.strictObject({type:K.z.literal("input"),target:Ft,state:Ft,set:Sc.optional()}),K.z.strictObject({type:K.z.literal("action"),target:Ft,set:Sc}),K.z.strictObject({type:K.z.literal("carousel"),target:Ft,state:Ft,initialIndex:K.z.number().int().nonnegative().optional(),maxWidth:K.z.number().int().min(1).max(1e4).optional(),previousTarget:Ft.optional(),nextTarget:Ft.optional(),inactiveTargets:K.z.array(Ft).max(20).optional(),inactiveMaxWidth:K.z.number().int().min(1).max(1e4).optional()})]),zb=K.z.strictObject({afterMs:K.z.number().int().min(0).max(6e4),set:Sc}),$b=K.z.strictObject({type:K.z.literal("mosaic_waves"),target:Ft,color:K.z.string().regex(/^#[0-9a-fA-F]{6}$/),hotColor:K.z.string().regex(/^#[0-9a-fA-F]{6}$/),enabled:Br.optional(),speed:K.z.number().min(0).max(4).optional(),pitch:K.z.number().min(.05).max(4).optional(),fill:K.z.number().min(.05).max(1).optional(),feather:K.z.number().min(0).max(1).optional(),warp:K.z.number().min(0).max(4).optional(),warpScale:K.z.number().min(0).max(32).optional(),detailScale:K.z.number().min(0).max(32).optional(),waveScale:K.z.number().min(0).max(32).optional(),falloff:K.z.number().min(.1).max(32).optional(),brightness:K.z.number().min(0).max(32).optional(),ambient:K.z.number().min(0).max(1).optional(),gamma:K.z.number().min(.05).max(8).optional(),vignette:K.z.number().min(0).max(1).optional(),opacity:K.z.number().min(0).max(1).optional()}),Gb=K.z.strictObject({type:K.z.literal("number_counter"),target:Ft,value:Br,prefix:K.z.string().max(20).optional(),format:K.z.enum(["number","short"]).optional()}),Kb=K.z.strictObject({state:K.z.record(Ft,qb).refine(e=>Object.keys(e).length<=St.state,"Too many UI state keys").optional(),derived:K.z.record(Ft,Br).refine(e=>Object.keys(e).length<=St.derived,"Too many UI derived keys").optional(),bindings:K.z.array(Vb).max(St.bindings).optional(),controls:K.z.array(Lb).max(St.controls).optional(),timers:K.z.array(zb).max(St.timers).optional(),effects:K.z.array(K.z.discriminatedUnion("type",[$b,Gb])).max(St.effects).optional(),clock:K.z.boolean().optional()});function Hb(e,t){if(!Ur(e,t,[])||!Pn(e))return;for(let[r,i]of[["state",St.state],["derived",St.derived]]){let a=e[r];if(!Ur(a,t,[r]))return;if(Pn(a)&&Object.keys(a).length>i){t.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}}for(let[r,i]of[["bindings",St.bindings],["controls",St.controls],["timers",St.timers],["effects",St.effects]])if(Array.isArray(e[r])&&e[r].length>i){t.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}if(Array.isArray(e.effects)){for(let[r,i]of e.effects.entries())if(!Ur(i,t,["effects",r]))return}if(Pn(e.state))for(let[r,i]of Object.entries(e.state)){if(!Ur(i,t,["state",r]))return;if(Pn(i)&&Array.isArray(i.values)&&i.values.length>St.enumValues){t.addIssue({code:"custom",path:["state",r,"values"],message:"Too many UI enum values"});return}}let n={nodes:0};if(Pn(e.derived))for(let[r,i]of Object.entries(e.derived))fi(i,t,["derived",r],n);for(let r of["bindings","controls","timers"]){let i=e[r];if(Array.isArray(i)){for(let[a,o]of i.entries())if(!(!Ur(o,t,[r,a])||!Pn(o))){if(r==="bindings")fi(o.expression,t,[r,a,"expression"],n);else if(Ur(o.set,t,[r,a,"set"])&&Pn(o.set)){if(Object.keys(o.set).length>St.state){t.addIssue({code:"custom",path:[r,a,"set"],message:"Too many UI assignments"});return}for(let[s,c]of Object.entries(o.set))fi(c,t,[r,a,"set",s],n)}if(n.nodes>St.expressionNodes)return}}}if(Array.isArray(e.effects))for(let[r,i]of e.effects.entries())Pn(i)&&i.type==="number_counter"?fi(i.value,t,["effects",r,"value"],n):Pn(i)&&i.enabled!==void 0&&fi(i.enabled,t,["effects",r,"enabled"],n)}function Wp(e){let t=[],n=[e];for(;n.length;){let r=n.pop();!r||typeof r!="object"||("ref"in r?t.push(r.ref):n.push(...r.args))}return t}var Xp=K.z.unknown().superRefine(Hb).pipe(Kb).superRefine((e,t)=>{let n=e.state??{},r=e.derived??{},i=new Set([...Object.keys(n),...Object.keys(r)]),a=(g,d)=>{for(let h of Wp(g))i.has(h)||t.addIssue({code:"custom",path:d,message:`Unknown UI reference: ${h}`})};for(let[g,d]of Object.entries(e.derived??{}))Object.hasOwn(n,g)&&t.addIssue({code:"custom",path:["derived",g],message:"UI state and derived identifiers must be distinct"}),a(d,["derived",g]);let o=new Set,s=new Set,c=g=>{if(o.has(g))return!1;if(s.has(g))return!0;o.add(g);for(let d of Wp(r[g]))if(Object.hasOwn(r,d)&&!c(d))return!1;return o.delete(g),s.add(g),!0};for(let g of Object.keys(r))if(!c(g)){t.addIssue({code:"custom",path:["derived",g],message:"Cyclic UI derived references"});break}for(let[g,d]of(e.bindings??[]).entries())a(d.expression,["bindings",g,"expression"]);let u=new Set;for(let[g,d]of(e.effects??[]).entries())u.has(d.target)&&t.addIssue({code:"custom",path:["effects",g,"target"],message:"Effect targets must be unique"}),u.add(d.target),d.type==="number_counter"?(a(d.value,["effects",g,"value"]),typeof d.value=="number"&&Math.abs(d.value)>1e12&&t.addIssue({code:"custom",path:["effects",g,"value"],message:"Counter values must be within the display bound"})):d.enabled!==void 0&&a(d.enabled,["effects",g,"enabled"]);let l=(g,d)=>{for(let[h,R]of Object.entries(g))Object.hasOwn(n,h)||t.addIssue({code:"custom",path:[...d,h],message:"UI assignments can only update declared state"}),a(R,[...d,h])},m=new Set,f=new Set;for(let[g,d]of(e.controls??[]).entries()){if(d.type==="carousel"&&d.inactiveMaxWidth!==void 0&&d.inactiveTargets===void 0&&t.addIssue({code:"custom",path:["controls",g,"inactiveMaxWidth"],message:"Inactive width requires inactive article targets"}),d.type==="carousel")for(let h of d.inactiveTargets??[])(h===d.target||f.has(h))&&t.addIssue({code:"custom",path:["controls",g,"inactiveTargets"],message:"Inactive article targets must have one carousel owner"}),f.add(h);if(d.type==="carousel")for(let h of["previousTarget","nextTarget"]){let R=d[h];R!==void 0&&((R===d.target||m.has(R)||(e.controls??[]).some(y=>y.target===R))&&t.addIssue({code:"custom",path:["controls",g,h],message:"Carousel navigation needs a distinct, exclusive button target"}),m.add(R))}if(d.type!=="action"){let h=Object.hasOwn(n,d.state)?n[d.state]:void 0;(!h||d.type==="input"&&h.type==="enum"&&h.values.some(R=>typeof R!="string"))&&t.addIssue({code:"custom",path:["controls",g,"state"],message:"Control needs a supported declared UI state"}),d.type==="carousel"&&(h?.type!=="number"||!Number.isInteger(h.min)||h.min<0||!Number.isInteger(h.max)||h.step!==1||d.initialIndex!==void 0&&!Ic(h,d.initialIndex))&&t.addIssue({code:"custom",path:["controls",g],message:"Carousel needs bounded nonnegative integer index state"}),d.type==="scroll_latch"&&h?.type!=="boolean"&&t.addIssue({code:"custom",path:["controls",g,"state"],message:"Scroll latches require boolean UI state"})}(d.type==="input"||d.type==="action")&&d.set&&l(d.set,["controls",g,"set"])}for(let[g,d]of(e.timers??[]).entries())l(d.set,["timers",g,"set"])});var it=require("zod"),Qb=it.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Oa=it.z.discriminatedUnion("type",[it.z.object({type:it.z.literal("fixed"),productVersionId:it.z.string().min(1).max(200)}).strict(),it.z.object({type:it.z.literal("picker"),pickerId:Qb,allowedProductVersionIds:it.z.array(it.z.string().min(1).max(200)).min(1).max(20)}).strict().refine(e=>new Set(e.allowedProductVersionIds).size===e.allowedProductVersionIds.length,"Product choices must be unique")]),Jb=it.z.strictObject({min:it.z.number().finite().min(1).max(1800),max:it.z.number().finite().min(1).max(1800),viewport:it.z.number().finite().min(1).max(100)}).refine(e=>e.min<=e.max,"Desktop width range is reversed"),em={desktopWidth:Jb.optional(),mobile:it.z.enum(["sheet","fullscreen"]).optional(),backdrop:it.z.enum(["none","scrim","dim","strong-dim","blur"]).optional()},Cn=it.z.discriminatedUnion("type",[it.z.strictObject({type:it.z.literal("modal"),size:it.z.enum(["sm","md","lg"]),...em}),it.z.strictObject({type:it.z.literal("sheet"),size:it.z.enum(["sm","md","lg"]),...em}),it.z.strictObject({type:it.z.literal("fullscreen")}),it.z.strictObject({type:it.z.literal("inline")})]);var Wb=4,En={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:32768,documentBytes:2e5},co=I.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ue=I.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Yb=I.z.enum(["none","xs","sm","md","lg","xl"]),Xb=I.z.enum(["none","sm","md","lg","full"]),vc=I.z.string().regex(/^#[0-9a-fA-F]{6}$/),Oc=I.z.string().max(2048).refine(e=>{try{let t=new URL(e);return t.protocol==="https:"&&t.hostname.length>0}catch{return!1}},"\u53EA\u652F\u6301 https \u94FE\u63A5"),wc=I.z.union([Oc,I.z.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),I.z.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),I.z.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),tm=I.z.object({primary:vc,background:vc,text:vc,radius:Xb,font:I.z.enum(["system","serif","rounded","mono"]),fontAssets:I.z.object({family:I.z.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/),faces:I.z.array(I.z.object({url:Oc,weight:I.z.number().int().min(100).max(900).multipleOf(100),family:I.z.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/).optional()}).strict()).min(1).max(4)}).strict().optional()}).strict(),uo=I.z.union([I.z.enum(["primary","text","muted","background","surface"]),I.z.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),Me=(e,t)=>I.z.number().int().min(e).max(t),nm=I.z.union([I.z.enum(["fit","fill"]),Me(1,1200)]),ex=I.z.object({top:Me(0,200),right:Me(0,200),bottom:Me(0,200),left:Me(0,200)}).strict(),tx=I.z.object({top:Me(-100,200),right:Me(-100,200),bottom:Me(-100,200),left:Me(-100,200)}).strict(),rm=I.z.object({x:Me(0,100),y:Me(0,100)}).strict(),nx=I.z.discriminatedUnion("type",[I.z.object({type:I.z.literal("color"),color:uo}).strict(),I.z.object({type:I.z.literal("linear"),angle:Me(0,360),stops:I.z.array(I.z.object({color:uo,at:Me(0,100)}).strict()).min(2).max(4)}).strict(),I.z.object({type:I.z.literal("image"),src:wc,fit:I.z.enum(["cover","contain"]),position:rm.optional()}).strict()]),rx=I.z.discriminatedUnion("type",[I.z.object({type:I.z.literal("rect"),radius:I.z.union([Me(0,200),I.z.object({topLeft:Me(0,200),topRight:Me(0,200),bottomRight:Me(0,200),bottomLeft:Me(0,200)}).strict()])}).strict(),I.z.object({type:I.z.literal("pill")}).strict()]),ix=I.z.object({width:Me(0,12),color:uo,style:I.z.enum(["solid","dashed"])}).strict(),ox=I.z.object({x:Me(-40,40),y:Me(-40,40),blur:Me(0,80),spread:Me(-20,40),color:uo}).strict(),ax=I.z.object({font:I.z.enum(["system","serif","rounded","mono"]),size:Me(8,96),weight:I.z.number().int().min(100).max(900).multipleOf(100),lineHeight:I.z.number().min(.8).max(3),letterSpacing:I.z.number().min(-5).max(20),color:uo,align:I.z.enum(["start","center","end"]),italic:I.z.boolean(),decoration:I.z.enum(["none","underline","line-through"]),transform:I.z.enum(["none","uppercase"])}).strict().partial(),Vr=I.z.object({width:nm,height:nm,padding:ex,margin:tx,gap:Me(0,120),grow:I.z.union([I.z.boolean(),I.z.number().min(0).max(12)]),background:nx,opacity:I.z.number().min(0).max(1),clipContent:I.z.boolean(),shape:rx,border:ix,shadow:ox,text:ax}).strict().partial(),tn={id:co,name:I.z.string().trim().min(1).max(60).optional(),hidden:I.z.boolean().optional(),style:Vr.optional(),fallback:Ue.optional()},sx=I.z.object({...tn,type:I.z.literal("text"),productField:I.z.enum(["name","price","trial","period"]).optional(),feature:I.z.object({id:I.z.uuid(),field:I.z.enum(["name","allowance"])}).strict().optional(),text:Ue,variant:I.z.enum(["title","heading","body","caption"])}).strict(),cx=I.z.object({...tn,type:I.z.literal("image"),src:wc,localizedSrc:I.z.record(wn,wc).optional(),alt:Ue,aspect:I.z.enum(["auto","1:1","4:3","16:9","3:1"]),fit:I.z.enum(["cover","contain"]),position:rm.optional()}).strict(),ux=I.z.object({...tn,type:I.z.literal("button"),label:Ue,variant:I.z.enum(["primary","secondary","link"]),action:Ue,purpose:I.z.enum(["purchase","navigation","close"]).optional(),bind:Ia.optional()}).strict(),lx=I.z.object({...tn,type:I.z.literal("divider")}).strict(),dx=I.z.object({...tn,type:I.z.literal("customer_data"),title:Ue,data:Qp}).strict(),px=I.z.object({...tn,type:I.z.literal("spacer"),size:Yb}).strict(),mx=I.z.object({...tn,type:I.z.literal("custom_html"),html:I.z.record(wn,I.z.string().max(En.customHtml)),css:I.z.string().max(En.customCss),ui:Xp.optional()}).strict(),fx=I.z.object({...tn,type:I.z.literal("price"),fallback:Ue,parts:I.z.object({current:Vr.optional(),original:Vr.optional(),period:Vr.optional()}).strict().optional()}).strict(),gx=I.z.object({...tn,type:I.z.literal("coupon_code"),label:Ue,fallback:Ue}).strict(),hx=I.z.object({...tn,type:I.z.literal("countdown"),source:I.z.enum(["offer.ends_at","offer.expires_at","fixed"]),at:I.z.iso.datetime().optional(),granularity:I.z.enum(["day","hour","minute","second"]),expired:Ue,fallback:Ue}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),yx=I.z.object({...tn,type:I.z.literal("plan_picker"),label:Ue,fallback:Ue,planIds:I.z.array(I.z.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:I.z.string().min(1).max(200).optional(),grouping:va.safeExtend({monthLabel:Ue,yearLabel:Ue,unavailableLabel:Ue}).optional(),states:I.z.object({selected:Vr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!wa(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),Ax=I.z.object({...tn,type:I.z.literal("quantity_picker"),bind:Ia.optional(),label:Ue,fallback:Ue,internalFeatureId:I.z.uuid(),minimumQuantity:Me(0,1e4),maximumQuantity:Me(0,1e4),defaultQuantity:Me(0,1e4),step:Me(1,1e4)}).strict().refine(e=>e.minimumQuantity<=e.defaultQuantity&&e.defaultQuantity<=e.maximumQuantity&&(e.defaultQuantity-e.minimumQuantity)%e.step===0,"Quantity controls require a Product binding and valid bounds"),bx=I.z.discriminatedUnion("type",[I.z.object({type:I.z.literal("input"),label:Ue,keyboard:I.z.enum(["text","email","tel","url"]),maxLength:Me(1,500)}).strict(),I.z.object({type:I.z.literal("multiselect"),label:Ue,min:Me(0,50),max:Me(1,50)}).strict(),I.z.object({type:I.z.literal("select"),label:Ue,defaultIndex:Me(0,49),purpose:I.z.enum(["option","product","tier"]).optional(),pickerId:co.optional(),selectedStyle:Vr.optional()}).strict(),I.z.object({type:I.z.literal("tabs"),label:Ue,defaultIndex:Me(0,49),purpose:I.z.literal("tier").optional()}).strict(),I.z.object({type:I.z.literal("toggle"),label:Ue,defaultEnabled:I.z.boolean()}).strict(),I.z.object({type:I.z.literal("carousel"),label:Ue}).strict()]),_n={...tn,type:I.z.literal("stack"),direction:I.z.enum(["vertical","horizontal","overlay"]),align:I.z.enum(["start","center","end","stretch"]),justify:I.z.enum(["start","center","end","between"]),productSlot:I.z.object({index:Me(0,19),period:I.z.enum(["month","year"]).optional(),requireBinding:I.z.boolean().optional()}).strict().optional(),interaction:bx.optional(),states:I.z.object({selected:Vr.optional()}).strict().optional(),purpose:I.z.literal("benefits").optional(),purchaseAction:Ue.optional(),buttonVariant:I.z.enum(["primary","secondary","link"]).optional(),bind:Ia.optional()},im=I.z.lazy(()=>I.z.object({...tn,type:_n.type,direction:_n.direction,align:_n.align,justify:_n.justify,children:I.z.array(xx).max(En.children),productSlot:_n.productSlot,interaction:_n.interaction,states:_n.states,purpose:_n.purpose,purchaseAction:_n.purchaseAction,buttonVariant:_n.buttonVariant,bind:_n.bind}).strict()),xx=I.z.lazy(()=>I.z.union([im,sx,cx,ux,lx,px,mx,fx,gx,hx,yx,Ax,dx])),Sx=I.z.union([I.z.string().max(500),I.z.number().finite(),I.z.boolean(),I.z.null()]),so={id:Ue,event:Ue,properties:I.z.record(Ue,Sx).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},Ix=I.z.discriminatedUnion("type",[I.z.object({...so,type:I.z.literal("navigate"),close:I.z.literal(!1),pageId:co}).strict(),I.z.object({...so,type:I.z.literal("event"),close:I.z.boolean()}).strict(),I.z.object({...so,type:I.z.literal("close"),close:I.z.literal(!0)}).strict(),I.z.object({...so,type:I.z.literal("open_url"),close:I.z.boolean(),url:Oc}).strict(),I.z.object({...so,type:I.z.literal("claim_offer"),close:I.z.boolean(),couponId:I.z.uuid()}).strict()]),vx=I.z.object({defaultLocale:wn,locales:I.z.record(wn,I.z.record(Ue,I.z.string().max(En.stringLength)))}).strict(),wx=I.z.enum(["popup","paywall","onboarding","page","banner"]);var Ox=I.z.object({kind:I.z.literal("screen"),schemaVersion:I.z.literal(Wb),name:I.z.string().trim().min(1).max(80),surface:wx,initialPageId:co.optional(),presentation:Cn,theme:tm,pages:I.z.array(I.z.object({id:co,name:I.z.string().trim().min(1).max(60),root:im,theme:tm.optional(),editorPosition:I.z.object({x:I.z.number().finite().min(-1e5).max(1e5),y:I.z.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(En.pages),strings:vx,actions:I.z.array(Ix).max(En.actions)}).strict();function Ht(e,t){for(let n of e.pages)Wn(n.root,t)}var dn=Ox.superRefine((e,t)=>{let n=En;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(l=>l.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let l of e.actions)l.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(m=>m.id===l.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>n.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${n.pages} \u4E2A`}),e.actions.length>n.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${n.actions} \u4E2A`});let r=l=>t.addIssue({code:"custom",message:l}),i=Object.keys(e.strings.locales);i.includes(e.strings.defaultLocale)||r("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),i.length>En.locales&&r(`\u6700\u591A ${En.locales} \u79CD\u8BED\u8A00`);let a=new Set;for(let l of e.actions)a.has(l.id)&&r(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${l.id}`),a.add(l.id);let o=new Set;for(let l of e.pages)["next","back"].includes(l.id)&&r(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${l.id}`),o.has(l.id)&&r(`\u9875\u9762 id \u91CD\u590D\uFF1A${l.id}`),o.add(l.id);let s=new Set,c=0,u=!1;Ht(e,(l,m)=>{if(c++,m>En.depth&&(u=!0),s.has(l.id)&&r(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${l.id}`),s.add(l.id),l.type==="button"&&!a.has(l.action)&&r(`\u6309\u94AE ${l.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${l.action}`),l.type==="custom_html")for(let f of Object.keys(l.html))i.includes(f)||r(`\u81EA\u5B9A\u4E49 HTML ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${f}`);if(l.type==="image")for(let f of Object.keys(l.localizedSrc??{}))i.includes(f)||r(`\u56FE\u7247 ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${f}`)}),c>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),u&&r(`\u5C42\u7EA7\u6700\u591A ${En.depth} \u5C42`)});function Wn(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)Wn(i,t,n+1,e)}function Pa(e){let t=[],n=new Set;return Ht(e,r=>{let i=(a,o,s)=>{n.has(a)||(n.add(a),t.push({key:a,nodeId:r.id,nodeType:r.type,field:o,required:s}))};r.type==="stack"&&r.interaction&&i(r.interaction.label,"label",!0),r.fallback&&i(r.fallback,"text",!0),r.type==="text"&&i(r.text,"text",!0),r.type==="customer_data"&&i(r.title,"title",!0),(r.type==="plan_picker"||r.type==="quantity_picker"||r.type==="coupon_code")&&i(r.label,"label",!0),r.type==="plan_picker"&&r.grouping&&(i(r.grouping.monthLabel,"label",!0),i(r.grouping.yearLabel,"label",!0),i(r.grouping.unavailableLabel,"text",!0)),r.type==="countdown"&&i(r.expired,"text",!0),r.type==="button"&&i(r.label,"label",!0),r.type==="image"&&(i(`image:${r.id}`,"src",!1),i(r.alt,"alt",!1)),r.type==="custom_html"&&i(`html:${r.id}`,"html",!0)}),t}function Px(e,t,n){if(t.field==="html"){let r;return Ht(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=lo(e,t.nodeId);return r?.type==="image"?r.localizedSrc?.[n]??(n===e.strings.defaultLocale?r.src:void 0):void 0}return e.strings.locales[n]?.[t.key]}function ar(e){let t=Pa(e).filter(r=>r.required);return Object.keys(e.strings.locales).sort((r,i)=>r===e.strings.defaultLocale?-1:i===e.strings.defaultLocale?1:0).map(r=>{let i=t.filter(a=>!Px(e,a,r)?.trim()).map(a=>a.key);return{locale:r,total:t.length,filled:t.length-i.length,missing:i,complete:i.length===0}})}function Cx(e,t){let n=null;return Wn(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function lo(e,t){for(let n of e.pages){let r=Cx(n.root,t);if(r)return r}return null}var Mt=require("zod"),It=Mt.z.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/).refine(e=>e.split(".").every(t=>t.length>0&&!["__proto__","constructor","prototype"].includes(t)),"Reserved or empty variable path"),Pc=Mt.z.strictObject({type:Mt.z.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:Mt.z.boolean(),enum:Mt.z.array(Mt.z.string().max(255)).min(1).max(100).optional()}),gi=Pc.extend({type:Mt.z.enum([...Pc.shape.type.options,"array"]),items:Pc.optional()}).superRefine((e,t)=>{(e.type==="array"!=!!e.items||e.enum&&e.type!=="string"||e.items?.enum&&e.items.type!=="string")&&t.addIssue({code:"custom",message:"Array requires items; only strings support enum"})}),hi=gi.safeExtend({source:Mt.z.discriminatedUnion("type",[Mt.z.strictObject({type:Mt.z.literal("input")}),Mt.z.strictObject({type:Mt.z.literal("node")}),Mt.z.strictObject({type:Mt.z.enum(["parameter","attribute"]),key:It})])}),GP=Mt.z.record(It,hi),Cc=Mt.z.record(It,It).refine(e=>Object.keys(e).length<=20);function An(e,t){return e?t===null?e.nullable:e.enum&&(typeof t!="string"||!e.enum.includes(t))?!1:e.type==="array"?Array.isArray(t)&&t.length<=100&&!!e.items&&t.every(n=>An(e.items,n)):["offering_version","reward","paywall_version"].includes(e.type)?typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===2&&t.type===e.type&&Mt.z.uuid().safeParse(t.id).success:e.type==="json"||(e.type==="strings"?Array.isArray(t)&&t.every(n=>typeof n=="string"):typeof t===e.type):!1}function _c(e,t){return e.nullable&&!t.nullable?!1:t.type==="json"?!0:e.type!==t.type||t.enum&&(!e.enum||e.enum.some(n=>!t.enum.includes(n)))?!1:e.type!=="array"||!!e.items&&!!t.items&&_c(e.items,t.items)}function Ca(e,t){let n={};for(let[r,i]of Object.entries(e)){let a=i.source,o=a.type==="input"?t.answers:a.type==="node"?t.results??{}:a.type==="parameter"?t.parameters:t.attributes,s=a.type==="parameter"||a.type==="attribute"?a.key:r,c=Object.hasOwn(o,s),u=o[s];if(a.type==="attribute"&&s.includes(".")&&(!c||s.startsWith("merchandise."))){u=o,c=!0;for(let l of s.split(".")){if(!u||typeof u!="object"||!Object.hasOwn(u,l)||Array.isArray(u)&&(!/^(0|[1-9]\d*)$/.test(l)||Number(l)>=u.length)){c=!1;break}u=u[l]}}if(!(!c||u===void 0)){if(!An(i,u))throw new Error(`Invalid variable value: ${r}`);n[r]=u}}return n}function yi(e,t){let n={};for(let[r,i]of Object.entries(e.writes??{})){if(!Object.hasOwn(t,r))throw new Error(`Node output is missing: ${r}`);if(Object.hasOwn(n,i))throw new Error("Node outputs cannot overwrite one another");n[i]=t[r]}return n}function om(e,t,n){let r=new Set(Object.values(t.writes??{}));for(let[i,a]of Object.entries(n))if(!r.has(i)||e[i]?.source.type!=="node"||!An(e[i],a))throw new Error(`Invalid node variable write: ${i}`);if(r.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}var sr=require("zod");var Rn=sr.z.string().min(1).max(255).regex(/^[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+){0,9}$/).refine(e=>e.split(".").every(t=>!["__proto__","constructor","prototype"].includes(t)),"Reserved value path"),Mn=sr.z.discriminatedUnion("source",[sr.z.strictObject({source:sr.z.literal("literal"),value:ve}),sr.z.strictObject({source:sr.z.literal("variable"),key:sr.z.string().min(1).max(255),path:Rn.optional()})]);function am(e,t){if(!t)return e;for(let n of Rn.parse(t).split(".")){if(Array.isArray(e)){if(!/^(0|[1-9]\d*)$/.test(n)||Number(n)>=e.length)return;e=e[Number(n)];continue}if(e===null||typeof e!="object"||!Object.hasOwn(e,n))return;e=Reflect.get(e,n)}return e}function Ec(e,t){if(e.source==="literal")return structuredClone(e.value);let n=Ca(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(ve.parse(am(n[e.key],e.path)))}function Rc(e,t){let n=[...t].sort((i,a)=>a.length-i.length).find(i=>e===i||e.startsWith(i+"."));if(!n)return null;let r=e===n?void 0:e.slice(n.length+1);return r&&!Rn.safeParse(r).success?null:{key:n,path:r}}function kc(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Ht(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap($p))]}function _a(e){return kc(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function pn(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("A JSON value is required");let n=new TextEncoder().encode(t).length,r=!1;for(let i=0;i<t.length;i++){let a=t.charAt(i);if(r)a==="\\"?i++:a==='"'&&(r=!1);else if(a==='"')r=!0;else if(a===":"||a===",")n++;else if(a==="-"||a>="0"&&a<="9"){let o=i;for(;i+1<t.length&&/[0-9.eE+-]/.test(t.charAt(i+1));)i++;let s=t.slice(o,i+1);if(!/[eE]/.test(s))continue;let[c="",u]=s.split(/[eE]/),l=c.replace(/^-/,""),m=l.replace(".","").length,f=(l.includes(".")?l.indexOf("."):m)+Number(u),g=f<=0?2-f+m:f>=m?f:m+1;n+=g+(c.startsWith("-")?1:0)-s.length}}return n}var cr=Oe.z.enum(["page","popup","banner"]),_x=3e5,sm=Oe.z.strictObject({type:Oe.z.enum(["string","number","boolean","strings","json"]),nullable:Oe.z.boolean()}),Ex=Oe.z.strictObject({inputs:Oe.z.record(Ue,sm.extend({required:Oe.z.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:Oe.z.record(Ue,sm).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),Rx=Oe.z.strictObject({kind:cr,schemaVersion:Oe.z.literal(1),name:Oe.z.string().trim().min(1).max(80),screen:dn,contract:Ex}),Ea=Rx.superRefine((e,t)=>{let n=(i,a)=>t.addIssue({code:"custom",message:i,path:a});e.screen.surface!==e.kind&&n("Content surface must match its domain",["screen","surface"]),e.screen.name!==e.name&&n("Content has one editable name",["screen","name"]),e.kind==="banner"&&e.screen.presentation.type!=="inline"&&n("Banner requires an inline container",["screen","presentation"]),e.kind!=="banner"&&e.screen.presentation.type==="inline"&&n("Inline presentation belongs to Banner",["screen","presentation"]),e.screen.actions.some(i=>i.type!=="event"&&i.type!=="navigate")&&n("Content actions must emit host intents or navigate locally",["screen","actions"]);let r=new Set(e.screen.actions.filter(i=>i.type==="event").map(i=>i.id));(Object.keys(e.contract.outputs).some(i=>!r.has(i))||[...r].some(i=>!Object.hasOwn(e.contract.outputs,i)))&&n("Every event needs exactly one output declaration",["contract","outputs"]),pn(e)>_x&&n("Content document exceeds its byte budget",[])});function kx(e,t){if(e===null)return t.nullable;switch(t.type){case"json":return!0;case"string":return typeof e=="string";case"number":return typeof e=="number"&&Number.isFinite(e);case"boolean":return typeof e=="boolean";case"strings":return Array.isArray(e)&&e.every(n=>typeof n=="string")}}var jx=Ea.superRefine((e,t)=>{for(let n of _a(e.screen))Object.keys(e.contract.inputs).some(r=>n===r||n.startsWith(r+"."))||t.addIssue({code:"custom",path:["contract","inputs"],message:"Declare every reusable input read"});for(let n of e.screen.actions){if(n.type!=="event")continue;let r=e.contract.outputs[n.id],i=Object.hasOwn(n.properties,"value")?n.properties.value:n.properties;r&&!kx(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}ar(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),cm=Oe.z.strictObject({id:Oe.z.uuid(),kind:cr,projectId:Oe.z.uuid(),environmentId:Oe.z.uuid(),name:Oe.z.string(),revision:Oe.z.number().int().nonnegative(),status:Oe.z.enum(["draft","published","archived"]),publishedVersionId:Oe.z.uuid().nullable(),createdAt:Oe.z.iso.datetime({offset:!0}),updatedAt:Oe.z.iso.datetime({offset:!0})}),oC=cm.extend({draft:Ea}),aC=Oe.z.strictObject({rows:Oe.z.array(cm).max(200),nextCursor:Oe.z.uuid().nullable()}),jc=Oe.z.strictObject({id:Oe.z.uuid(),kind:cr,resourceId:Oe.z.uuid(),projectId:Oe.z.uuid(),environmentId:Oe.z.uuid(),version:Oe.z.number().int().positive(),sourceRevision:Oe.z.number().int().nonnegative(),document:jx,createdAt:Oe.z.iso.datetime({offset:!0})}),sC=jc.omit({document:!0}),cC=Oe.z.discriminatedUnion("action",[Oe.z.strictObject({action:Oe.z.literal("create"),kind:cr,id:Oe.z.uuid(),document:Ea}),Oe.z.strictObject({action:Oe.z.literal("save"),kind:cr,id:Oe.z.uuid(),revision:Oe.z.number().int().nonnegative(),document:Ea}),Oe.z.strictObject({action:Oe.z.enum(["publish","archive"]),kind:cr,id:Oe.z.uuid(),revision:Oe.z.number().int().nonnegative()})]).superRefine((e,t)=>{"document"in e&&e.document.kind!==e.kind&&t.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});var Tc=require("zod"),Ai={funnelId:Tc.z.uuid().optional(),funnelVersionId:Tc.z.uuid().optional()};var po=require("zod"),Ra=po.z.strictObject({runId:po.z.uuid(),bindingId:po.z.uuid(),receiptId:po.z.uuid()});var ot=require("zod");var Be=require("zod");var Xe=require("zod"),pC=Xe.z.discriminatedUnion("action",[Xe.z.strictObject({action:Xe.z.literal("create"),couponId:Xe.z.uuid(),productBindingId:Xe.z.uuid(),storeOfferId:Xe.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:Xe.z.enum(["introductory","promotional"])}),Xe.z.strictObject({action:Xe.z.literal("set_enabled"),id:Xe.z.uuid(),revision:Xe.z.number().int().nonnegative(),enabled:Xe.z.boolean()})]),mC=Xe.z.array(Xe.z.strictObject({id:Xe.z.uuid(),couponId:Xe.z.uuid(),productBindingId:Xe.z.uuid(),storeOfferId:Xe.z.string().min(1).max(255).nullable(),storeOfferType:Xe.z.enum(["introductory","promotional"]),enabled:Xe.z.boolean(),revision:Xe.z.number().int().nonnegative()})).max(500),bi=Xe.z.strictObject({offerKind:Xe.z.enum(["none","introductory","promotional"]),offerId:Xe.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:Xe.z.number().int().min(0).max(1e8),trialDays:Xe.z.number().int().min(1).max(730).nullable()}).superRefine((e,t)=>{(e.offerKind==="none"&&(e.offerId!==null||e.discountMinor!==0||e.trialDays!==null)||e.trialDays!==null&&e.discountMinor!==0)&&t.addIssue({code:"custom",message:"Select one store purchase option with its exact terms"})}),fC=Xe.z.record(Xe.z.uuid(),bi).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var Nc=Be.z.object({type:Be.z.literal("native_purchase"),receiptId:Be.z.uuid(),orderId:Be.z.uuid(),productVersionId:Be.z.uuid(),provider:Be.z.enum(["apple","google"]),productId:Be.z.string().min(1).max(255),productKind:Vp,replacement:Be.z.strictObject({sourceOrderId:Be.z.uuid(),sourceProductId:Be.z.string().min(1).max(255),policy:Be.z.enum(["apple_store","google_full_price"]),sourceAccountTokens:Be.z.array(Be.z.uuid()).max(50)}).nullable(),appAccountToken:Be.z.uuid().optional(),obfuscatedAccountId:Be.z.string().min(1).max(64).optional(),obfuscatedProfileId:Be.z.uuid().optional(),basePlanId:Be.z.string().min(1).max(255).optional(),offerId:Be.z.string().min(1).max(255).optional(),offerKind:Be.z.enum(["none","introductory","promotional"]),currency:Ie,catalogAmountMinor:Be.z.number().int().nonnegative().max(1e8),discountMinor:Be.z.number().int().nonnegative().max(1e8),trialDays:Be.z.number().int().min(1).max(730).nullable(),seatBundle:Be.z.array(Be.z.strictObject({key:Be.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:Be.z.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:Be.z.strictObject({offerId:Be.z.string().min(1).max(255),keyId:Be.z.string().min(1).max(255),nonce:Be.z.uuid(),signature:Be.z.string().min(1).max(1024),timestamp:Be.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,t)=>{let n=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(n?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!n&&e.productKind==="membership"&&e.basePlanId===void 0||e.discountMinor>e.catalogAmountMinor||new Set(e.seatBundle.map(i=>i.key)).size!==e.seatBundle.length||e.trialDays!==null&&(e.discountMinor!==0||e.offerKind==="none")||e.offerKind==="none"&&e.discountMinor!==0||(n?!e.appAccountToken||e.obfuscatedAccountId!==void 0||e.obfuscatedProfileId!==void 0||e.basePlanId!==void 0||e.offerKind==="promotional"!=(e.applePromotionalOffer!==null)||e.offerKind==="promotional"!=(e.offerId!==void 0)||e.applePromotionalOffer!==null&&e.applePromotionalOffer.offerId!==e.offerId:e.appAccountToken!==void 0||!e.obfuscatedAccountId||!e.obfuscatedProfileId||e.applePromotionalOffer!==null||e.offerKind==="none"!=(e.offerId===void 0)))&&t.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});var p=require("zod");var _e=require("zod/v4"),um=require("zod/v4"),Tx=um.z.registry(),{BillingInterval:lm}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{BillingInterval:e}})(),{DisplaySchema:Nx}=(e=>({DisplaySchema:e.object({primary_text:e.string().meta({description:"Main display text (e.g. '$10' or '100 messages')."}),secondary_text:e.string().optional().meta({description:"Secondary display text (e.g. 'per month' or 'then $0.5 per 100')."})})}))(_e.z),{withSpecDefault:Dx}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(Tx),{COMMON:dm}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:Fx}={STRIPE_PRESENTMENT_CURRENCIES:["usd","aed","afn","all","amd","ang","aoa","ars","aud","awg","azn","bam","bbd","bdt","bif","bmd","bnd","bob","brl","bsd","bwp","byn","bzd","cad","cdf","chf","clp","cny","cop","crc","cve","czk","djf","dkk","dop","dzd","egp","etb","eur","fjd","fkp","gbp","gel","gip","gmd","gnf","gtq","gyd","hkd","hnl","htg","huf","idr","ils","inr","isk","jmd","jpy","kes","kgs","khr","kmf","krw","kyd","kzt","lak","lbp","lkr","lrd","lsl","mad","mdl","mga","mkd","mmk","mnt","mop","mur","mvr","mwk","mxn","myr","mzn","nad","ngn","nio","nok","npr","nzd","pab","pen","pgk","php","pkr","pln","pyg","qar","ron","rsd","rub","rwf","sar","sbd","scr","sek","sgd","shp","sle","sos","srd","std","szl","thb","tjs","top","try","ttd","twd","tzs","uah","ugx","uyu","uzs","vnd","vuv","wst","xaf","xcd","xcg","xof","xpf","yer","zar","zmw"]},{COMMON_SET:Mx}=(e=>({COMMON_SET:new Set(e)}))(dm),{hasNoDuplicateCurrencies:pm}={hasNoDuplicateCurrencies:t=>{let n=new Set;for(let{currency:r}of t){let i=r.toLowerCase();if(n.has(i))return!1;n.add(i)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:mm}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:qx}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(_e.z),{Infinite:Ux}={Infinite:"inf"},{TierBehavior:Bx}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:fm}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Vx}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:Lx}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:zx}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:$x}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(_e.z),{ApiCreditTierSchema:gm}=(e=>({ApiCreditTierSchema:e.object({to:e.union([e.number().positive(),e.enum(["inf"])]).meta({description:"Inclusive upper usage boundary for this graduated tier. The final tier must be 'inf'."}),credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group within this tier."})})}))(_e.z),{VIOLATION_MESSAGES:Gx}={VIOLATION_MESSAGES:{non_final_infinity:"Only the final tier may use an 'inf' boundary.",not_increasing:"Tier boundaries must be strictly increasing.",final_not_infinity:"The final tier must use an 'inf' boundary."}},{MarkupEntrySchema:hm}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(_e.z),{ModelMarkupsSchema:Kx}=((e,t)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),t.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(_e.z,hm),{InvoiceUsageEntrySchema:Hx}=(e=>({InvoiceUsageEntrySchema:e.object({feature_id:e.string().meta({description:"The metered feature whose units are being converted."}),quantity:e.number().nonnegative().meta({description:"Billable units of the metered feature. Converted to the credit-system feature through its rate card."}),properties:e.record(e.string(),e.unknown()).optional().meta({description:"Event properties used to pick the rate card dimension and multipliers."})}).strict()}))(_e.z),{AttachDiscountSchema:ym}=(e=>({AttachDiscountSchema:e.object({reward_id:e.string().optional().meta({description:"The ID of the reward to apply as a discount."}),promotion_code:e.string().optional().meta({description:"The promotion code to apply as a discount."})}).refine(n=>n.reward_id||n.promotion_code,{message:"Either reward_id or promotion_code must be provided."}).meta({title:"AttachDiscount",description:"A discount to apply. Can be either a reward ID or a promotion code."})}))(_e.z),{CustomLineItemSchema:Qx}=(e=>({CustomLineItemSchema:e.object({amount:e.number().meta({description:"Amount in dollars for this line item (e.g. 10.50). Can be negative for credits."}),description:e.string().meta({description:"Description for the line item."})})}))(_e.z),{UnixMsTimestampSchema:Jx}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(_e.z),{CreateInvoicePreviewLineSchema:Zx}=(e=>({CreateInvoicePreviewLineSchema:e.object({plan_id:e.string().nullable(),feature_id:e.string().nullable(),description:e.string(),amount:e.number(),amount_after_discounts:e.number(),quantity:e.number().nullable(),prorated:e.boolean(),period_start:e.number().nullable(),period_end:e.number().nullable()})}))(_e.z),{ReissueInvoiceParamsSchema:Am}=(e=>({ReissueInvoiceParamsSchema:e.object({invoice_id:e.string().meta({description:"The Autumn invoice ID to void and replace.",example:"inv_2b3c4d5e6f7g8h"}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer and memo are applied to the replacement invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the replacement invoice. Defaults to the original invoice's due date; required when that date has already passed."}),update_customer_email:e.email().optional().meta({description:"Updates the customer's billing email before the replacement is issued, so Stripe sends the new invoice to this address."})})}))(_e.z),{InvoiceModeParamsSchema:Lr}=(e=>({InvoiceModeParamsSchema:e.object({enabled:e.boolean().meta({description:"When true, creates an invoice and sends it to the customer instead of charging their card immediately. Uses Stripe's send_invoice collection method."}),enable_plan_immediately:e.boolean().default(!1).meta({description:"If true, enables the plan immediately even though the invoice is not paid yet."}),finalize:e.boolean().default(!0).meta({description:"If true, finalizes the invoice so it can be sent to the customer. If false, keeps it as a draft for manual review."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer (e.g. bank details) is applied to the invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the invoice before it is due (Stripe days_until_due)."})}).meta({title:"InvoiceMode",description:"Invoice mode configuration. Creates an invoice instead of charging the card immediately."})}))(_e.z),{InvoiceTemplateSchema:Wx}=(e=>({InvoiceTemplateSchema:e.object({id:e.string().meta({description:"Unique identifier for the invoice template."}),name:e.string().meta({description:"User-defined name to distinguish this template when sending an invoice."}),footer:e.string().optional().meta({description:"Footer text rendered on the invoice, typically bank details so customers can pay directly."}),memo:e.string().optional().meta({description:"Memo shown near the top of the invoice (Stripe invoice description), e.g. a contact line for payment questions."}),net_terms_days:e.number().int().positive().optional().meta({description:"Default number of days the customer has to pay before the invoice is due. Overridable when sending."}),created_at:e.number().optional().meta({description:"Timestamp (ms) when the template was created."})})}))(_e.z),{BasePriceSchema:Yx}=((e,t,n)=>({BasePriceSchema:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),interval:e.enum(t).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),display:n.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(_e.z,lm,Nx),{CURRENCY_CODES:Xx}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(dm,Fx,Mx),{ApiPriceProcessorsSchema:bm}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(_e.z,qx),{AllocatedBillingFieldSchema:eS}=((e,t)=>({AllocatedBillingFieldSchema:e.enum(t).optional().meta({internal:!0,description:"How an allocated usage_based price bills mid-cycle quantity changes. 'arrear' (default) bills at period end. 'prorated_legacy' is only returned for prices still on the legacy immediate-proration behavior; omit it to migrate the price to 'arrear'."})}))(_e.z,Vx),{CreditDimensionNameSchema:tS}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(_e.z,Lx,zx),{ApiCreditMatchSchema:xm}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))($x),{findCreditTierViolations:nS}=(e=>({findCreditTierViolations:n=>{let r=[],i=(o,s)=>r.push({index:o,reason:s,message:e[s]}),a=0;for(let[o,s]of n.entries()){let c=o===n.length-1;if(s==="inf"){c||i(o,"non_final_infinity");continue}(!Number.isFinite(s)||s<=a)&&i(o,"not_increasing"),a=s,c&&i(o,"final_not_infinity")}return r}}))(Gx),{ApiCreditMultiplierSchema:rS}=((e,t)=>({ApiCreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional().meta({description:"Multiplies the matched rate. All matching multipliers stack."}),add:e.number().optional().meta({description:"Added to the rate after every factor is applied, in credits per billing-unit group."})}).strict().refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(_e.z,xm),{ProviderMarkupsSchema:iS}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(_e.z,hm),{InvoiceFeatureQuantitySchema:Sm}=((e,t,n)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(t).meta({description:"Which of the feature's prices to use: 'prepaid' or 'usage_based'."}),quantity:e.number().nonnegative().optional().meta({description:"Billable feature units in total, exclusive of any included usage. Not per seat or per entity. For a credit-system feature this is the number of credits."}),usage:e.array(n).optional().meta({description:"For credit-system features: billable units of the source features, converted through the credit rate card. Mutually exclusive with quantity."}),prorate:e.boolean().optional().meta({description:"Whether to prorate this line against period_start / period_end. Defaults to true for prepaid and false for usage-based."})}).strict().refine(i=>i.quantity!==void 0!=(i.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(_e.z,fm,Hx),{CreateInvoicePreviewSchema:Dc}=((e,t)=>({CreateInvoicePreviewSchema:e.object({currency:e.string(),lines:e.array(t),subtotal:e.number(),discount_total:e.number(),tax:e.object({total:e.number(),amount_inclusive:e.number(),amount_exclusive:e.number(),status:e.enum(["complete","incomplete"])}).nullable(),total:e.number(),due_date:e.number().nullable()})}))(_e.z,Zx),{SUPPORTED_SET:oS}=(e=>({SUPPORTED_SET:new Set(e)}))(Xx),{ApiCreditDimensionBaseSchema:aS}=((e,t)=>({ApiCreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(_e.z,xm),{refineGraduatedTiers:Im}=(e=>({refineGraduatedTiers:(n,r)=>{let i=e(n.tiers.map(a=>a.to));for(let{index:a,message:o}of i)r.addIssue({code:"custom",message:o,path:["tiers",a,"to"]})}}))(nS),{ApiFeatureMarkupsOverrideSchema:sS}=((e,t,n)=>({ApiFeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional().meta({description:"Default percentage markup for customers on this plan. Use -100 to make usage free."}),provider_markups:t.meta({description:"Per-provider markup percentages for customers on this plan."}),model_markups:n.meta({description:"Per-model markup overrides for customers on this plan."})})}))(_e.z,iS,Kx),{isValidCurrencyCode:cS}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(oS),{ApiCreditDimensionSchema:uS}=((e,t,n,r)=>({ApiCreditDimensionSchema:e.union([t.extend({tier_behavior:e.literal("graduated"),tiers:e.array(n).min(1)}).strict().superRefine(r),t.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(_e.z,aS,gm,Im),{CurrencyCodeSchema:vm}=((e,t)=>({CurrencyCodeSchema:e.string().refine(t,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(_e.z,cS),{AdditionalCurrencyTierSchema:lS}=((e,t)=>({AdditionalCurrencyTierSchema:e.object({currency:t,amount:e.number().optional().meta({description:"Per-unit amount for this tier in this currency."}),flat_amount:e.number().optional().meta({description:"Flat amount for this tier in this currency, if the tier uses one."})}).refine(r=>r.amount!==void 0||r.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(_e.z,vm),{ApiCreditSchemaItemBaseSchema:wm}=((e,t,n,r)=>({ApiCreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string().nonempty().meta({description:"ID of the metered feature that draws from this credit system."}),billing_units:e.number().positive().optional().meta({description:"Number of metered-feature units priced together. Defaults to one when omitted."}),dimensions:e.record(t,n).optional().meta({description:"Named rates chosen by event properties. The most specific match sets the rate; with no match the item's own rate applies."}),multipliers:e.record(t,r).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(_e.z,tS,uS,rS),{ApiFlatCreditSchemaItemSchema:dS}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(wm,_e.z),{AdditionalCurrencyPriceSchema:pS}=((e,t)=>({AdditionalCurrencyPriceSchema:e.object({currency:t,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(_e.z,vm),{AdditionalCurrencyTierArraySchema:mS}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(_e.z,lS,pm,mm),{ApiGraduatedCreditSchemaItemSchema:fS}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(wm,_e.z,gm,Im),{AdditionalCurrencyPriceArraySchema:Om}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(_e.z,pS,pm,mm),{ApiUsageTierWithCurrenciesSchema:gS}=((e,t,n)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:n.optional().meta({description:"Per-currency amounts for this tier. Tier boundaries ('to') are shared across all currencies."})}).refine(i=>i.amount!==void 0||i.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(i=>({...i,amount:i.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:n.optional()}))}))(_e.z,Ux,mS),{ApiCreditSchemaItemSchema:hS}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(_e.z,fS,dS),{BasePriceParamsSchema:yS}=((e,t,n,r)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:t({schema:n.number().optional(),defaultValue:1,description:"Number of intervals per billing cycle. Defaults to 1."}),additional_currencies:r.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),base_currency:n.string().optional().meta({internal:!0}),entitlement_id:n.string().optional().meta({internal:!0}),price_id:n.string().optional().meta({internal:!0}),stripe_price_id:n.string().optional().meta({description:"Stripe price id this base price is billed under. Set by sync flows to capture the actual Stripe price when it differs from the catalog default.",internal:!0})}).meta({title:"BasePrice",description:"Base price configuration for a plan."})}))(Yx,Dx,_e.z,Om),{PlanItemPriceParamsSchema:AS}=((e,t,n,r,i,a,o)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(c=>c??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:t.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(i).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(a).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:o,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(_e.z,Om,gS,Bx,lm,fm,eS),{ApiFeatureOverrideSchema:bS}=((e,t,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(t).optional().meta({description:"For credit system features: replaces the feature's credit_schema entirely for customers on this plan."}),markups:n.optional().meta({description:"For AI credit system features: replaces the feature's markup chain entirely for customers on this plan. An unset level means no markup at that level rather than inheriting the feature's."})})}))(_e.z,hS,sS),{InvoiceBasePriceParamsSchema:Pm}=((e,t)=>({InvoiceBasePriceParamsSchema:e.pick({amount:!0,interval:!0,interval_count:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(yS,bm),{InvoiceItemPriceParamsSchema:xS}=((e,t)=>({InvoiceItemPriceParamsSchema:e.pick({amount:!0,tiers:!0,tier_behavior:!0,interval:!0,interval_count:!0,billing_units:!0,billing_method:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(AS,bm),{InvoiceLicenseQuantitySchema:SS}=((e,t,n)=>({InvoiceLicenseQuantitySchema:e.object({license_plan_id:e.string().meta({description:"The license plan linked to the parent plan."}),quantity:e.number().int().nonnegative().meta({description:"Billable seats, exclusive of any included seats."}),customize:e.object({price:t.nullable().optional()}).strict().optional().meta({description:"Override the license's per-seat price on this invoice."}),feature_quantities:e.array(n).optional().meta({description:"Feature charges priced through the license plan."}),prorate:e.boolean().optional().meta({description:"Whether to prorate seat charges against period_start / period_end. Defaults to true."})}).strict()}))(_e.z,Pm,Sm),{InvoiceCustomizeItemSchema:IS}=((e,t,n)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:t.optional().meta({description:"Pricing to use for this feature on this invoice."}),feature_override:n.pick({credit_schema:!0}).strict().optional().meta({description:"For credit-system features: a credit rate card to use when converting `usage` on this invoice."})}).strict()}))(_e.z,xS,bS),{InvoiceCustomizeSchema:vS}=((e,t,n)=>({InvoiceCustomizeSchema:e.object({price:t.nullable().optional().meta({description:"Override the plan's base price for this invoice. Pass null or an amount of 0 to omit the base price line."}),items:e.array(n).optional().meta({description:"Override feature pricing for this invoice. Only pricing fields are accepted; grants, resets and rollovers are not part of an invoice."})}).strict().meta({title:"InvoiceCustomize",description:"Pricing overrides applied to this invoice only. The catalog and the customer's plan are not changed."})}))(_e.z,Pm,IS),{InvoicePlanParamsSchema:wS}=((e,t,n,r,i)=>({InvoicePlanParamsSchema:e.object({plan_id:e.string().meta({description:"The catalog plan (or variant) whose pricing to use."}),version:e.number().optional().meta({description:"Plan version. Defaults to the active version."}),customize:t.optional(),feature_quantities:e.array(n).optional(),license_quantities:e.array(r).optional(),discounts:e.array(i).optional().meta({description:"Discounts applied only to this plan's lines."}),prorate:e.boolean().optional().meta({description:"Whether to prorate the base price against period_start / period_end. Defaults to true."})}).strict()}))(_e.z,vS,Sm,SS,ym),{CreateInvoiceParamsSchema:xi}=((e,t,n,r,i)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(t).optional(),custom_line_items:e.array(n).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(r).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:i.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start \u2192 period_end against one price interval starting at period_start."}),period_end:i.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(o=>o.period_start===void 0==(o.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(o=>o.period_start===void 0||o.period_end===void 0||o.period_end>o.period_start,{message:"period_end must be after period_start."})}))(_e.z,wS,Qx,ym,Jx);var Em=p.z.strictObject({requestId:p.z.uuid(),predecessorOperationId:p.z.uuid().optional(),invoiceMode:Lr.optional(),entityId:p.z.uuid().optional(),billingSubscriptionId:p.z.uuid().optional(),newBillingSubscription:p.z.literal(!0).optional(),offerId:p.z.uuid().optional(),nativeOffer:bi.optional(),plans:p.z.array(p.z.strictObject({productVersionId:p.z.uuid(),seatQuantities:p.z.record(Wo,p.z.number().int().min(0).max(1e4)).optional(),featureQuantities:p.z.record(p.z.uuid(),p.z.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100,"At most 100 feature quantities").optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Plan versions must be unique"),provider:p.z.enum(["stripe","apple","google","merchant"]),currency:Ie}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||["apple","google"].includes(e.provider)&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||["stripe","merchant"].includes(e.provider)&&!e.billingSubscriptionId,"A new billing subscription has no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),$r=p.z.strictObject({operationId:p.z.uuid()}),qt=p.z.number().int().min(0).max(1e8),OS=p.z.strictObject({lineId:p.z.uuid(),productVersionId:p.z.uuid(),productName:p.z.string().min(1).max(80),interval:p.z.enum(["free","week","month","year","one_time"]),intervalCount:p.z.number().int().min(1).max(156).optional(),baseAmountMinor:qt,seats:p.z.array(p.z.strictObject({key:Wo,quantity:p.z.number().int().min(0).max(1e4),includedQuantity:p.z.number().int().min(0).max(1e4),maximumQuantity:p.z.number().int().min(0).max(1e4),unitAmountMinor:qt})).max(20),prepaid:p.z.array(gp).max(100).optional(),catalogAmountMinor:qt,trial:p.z.strictObject({days:p.z.number().int().min(1).max(730),cardRequired:p.z.boolean()}).nullable()}).refine(e=>new Set(e.seats.map(t=>t.key)).size===e.seats.length&&e.seats.every(t=>t.quantity>=t.includedQuantity&&t.quantity<=t.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((t,n)=>t+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((t,n)=>t+na({quantity:n.quantity,unitAmountMinor:n.unitAmountMinor,...n.pricing===void 0?{}:{pricing:n.pricing}}),0)===e.catalogAmountMinor,"Quote must retain its published base price and component quantities"),Rm=p.z.string().regex(/^[A-Za-z0-9_-]{1,200}$/),PS=p.z.strictObject({id:Rm,name:p.z.string().min(1).max(40),percent_off:p.z.number().gt(0).max(100).optional(),amount_off:p.z.number().int().positive().optional(),currency:p.z.string().regex(/^[a-z]{3}$/).optional(),duration:p.z.enum(["once","repeating","forever"]),duration_in_months:p.z.number().int().min(1).max(36).optional()}).refine(e=>e.percent_off===void 0!=(e.amount_off===void 0)&&e.amount_off===void 0==(e.currency===void 0)&&e.duration==="repeating"==(e.duration_in_months!==void 0),"A Stripe coupon has one percentage or amount and months only when repeating"),CS=p.z.strictObject({subscriptionId:p.z.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:p.z.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:p.z.array(p.z.strictObject({id:p.z.string(),price_id:p.z.string(),quantity:p.z.number().int().nonnegative(),discounts:p.z.array(p.z.strictObject({id:p.z.string(),coupon:p.z.string(),start:p.z.number(),end:p.z.number().nullable()})).optional()})).min(1).max(100),prorationDate:p.z.number().int().nonnegative(),amountMinor:p.z.number().int().positive(),periodStartMs:p.z.number(),periodEndMs:p.z.number()}),km=p.z.strictObject({invoiceMode:Lr.optional(),append:CS.optional(),provider:p.z.literal("stripe"),executor:p.z.enum(["indiana","merchant"]),accountId:p.z.string().regex(/^acct_[A-Za-z0-9]+$/),mode:p.z.enum(["payment","subscription"]),lineItems:p.z.array(p.z.strictObject({price:p.z.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:p.z.number().int().min(1).max(1e4),priceId:p.z.uuid(),productName:p.z.string().min(1).max(80),amountMinor:p.z.number().int().min(0).max(1e8),currency:p.z.string().regex(/^[a-z]{3}$/),interval:p.z.enum(["week","month","year","one_off"]),intervalCount:p.z.number().int().min(1).max(52),slot:p.z.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:p.z.strictObject({mode:p.z.enum(["graduated","volume"]),tiers:p.z.array(p.z.strictObject({upTo:p.z.number().int().min(1).max(1e6).nullable(),unitAmountMinor:p.z.number().int().min(0).max(1e8),flatAmountMinor:p.z.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:p.z.array(p.z.strictObject({coupon:Rm,terms:PS})).max(1),trialPeriodDays:p.z.number().int().min(1).max(730).nullable(),metadata:p.z.strictObject({grooveCheckoutId:p.z.uuid(),grooveCustomerId:p.z.uuid()}),expiresAt:p.z.iso.datetime({offset:!0})}),Si=p.z.strictObject({operationId:p.z.uuid(),entityId:p.z.uuid().nullable(),billingSubscriptionId:p.z.uuid().nullable(),discount:p.z.strictObject({offerId:p.z.uuid(),couponId:p.z.uuid(),discount:ir,duration:un,amountMinor:qt,allocations:p.z.array(p.z.strictObject({productVersionId:p.z.uuid(),amountMinor:qt})).min(1).max(20),expiresAt:p.z.iso.datetime({offset:!0})}).nullable(),charge:p.z.strictObject({effectiveAt:p.z.iso.datetime({offset:!0}),periodEndsAt:p.z.iso.datetime({offset:!0}),debitMinor:qt,discountMinor:qt,taxMinor:qt,totalMinor:qt}).nullable(),expiresAt:p.z.iso.datetime({offset:!0}),provider:p.z.enum(["stripe","apple","google","merchant"]),nativeOffer:bi.optional(),currency:Ie,lines:p.z.array(OS).min(1).max(20),catalogAmountMinor:qt,automaticTax:p.z.boolean(),execution:p.z.union([km,Ko]).nullable()}).refine(e=>e.provider==="merchant"?e.execution?.provider==="merchant"&&e.execution.operationId===e.operationId&&e.execution.catalogAmountMinor===e.catalogAmountMinor&&e.execution.currency===e.currency&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&e.execution.discount?.grantId===e.discount?.offerId:e.provider==="stripe"?e.execution?.provider!=="merchant"&&(e.lines[0]?.trial?.cardRequired===!1&&!e.execution?.invoiceMode?.enabled?e.execution===null&&e.discount===null:e.execution!==null&&e.execution.metadata.grooveCheckoutId===e.operationId&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.mode===(e.lines.some(t=>!["one_time","free"].includes(t.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(t=>t.price!==null))&&e.execution.discounts.every(t=>t.coupon===t.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(t=>e.discount!==null&&(t.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&t.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${t.terms.amount_off}`&&t.terms.amount_off===e.discount.discount.amountOffCents&&t.terms.currency?.toUpperCase()===e.currency&&t.terms.duration==="once"))):e.execution===null,"Stripe execution must carry the quote identity, expiry, mode, trial and held coupon").refine(e=>(!e.discount||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.discount.duration.type==="once")&&e.discount.amountMinor<=e.catalogAmountMinor&&e.discount.allocations.length===e.lines.length&&e.discount.allocations.every((t,n)=>{let r=e.lines[n];return r!==void 0&&t.productVersionId===r.productVersionId&&t.amountMinor<=r.catalogAmountMinor})&&e.discount.allocations.reduce((t,n)=>t+n.amountMinor,0)===e.discount.amountMinor)&&(["stripe","merchant"].includes(e.provider)?e.nativeOffer===void 0:e.nativeOffer!==void 0&&e.lines.length===1&&e.nativeOffer.discountMinor<=e.catalogAmountMinor&&e.nativeOffer.trialDays===(e.lines[0]?.trial?.days??null)&&(!e.discount||e.nativeOffer.discountMinor===e.discount.amountMinor))&&(!e.charge||e.billingSubscriptionId!==null&&e.charge.totalMinor===e.charge.debitMinor-e.charge.discountMinor+e.charge.taxMinor&&e.charge.discountMinor<=e.charge.debitMinor&&Date.parse(e.charge.periodEndsAt)>Date.parse(e.charge.effectiveAt))&&new Set(e.lines.map(t=>t.lineId)).size===e.lines.length&&e.lines.reduce((t,n)=>t+n.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),Ii=p.z.strictObject({operationId:p.z.uuid(),orderId:p.z.uuid(),append:p.z.boolean().optional(),invoiceMode:p.z.boolean().optional(),status:p.z.enum(["pending","complete","cancelled","failed"]),executor:p.z.enum(["indiana","merchant"]),checkoutUrl:p.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:p.z.union([km,Ko]).nullable(),currency:Ie,catalogAmountMinor:qt,taxMinor:qt,totalMinor:p.z.number().int().min(0).max(2e8).nullable(),quoteFinalized:p.z.boolean(),nativePurchase:Nc.nullable(),confirmedAt:p.z.iso.datetime({offset:!0}).nullable().optional(),quote:Si.optional(),merchantExecution:Cr.nullable().optional(),problem:Li.nullable().optional(),authority:Zo.optional()}).refine(e=>(e.checkoutUrl===null||e.executor==="indiana"||e.merchantExecution?.type==="purchase")&&(e.execution===null||e.executor==="merchant"),"Only Indiana-executed purchases carry a Checkout URL and only record-only purchases carry execution instructions"),ja=p.z.strictObject({enabled:p.z.literal(!0),featureIds:p.z.array(p.z.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),jm=p.z.strictObject({requestId:p.z.uuid(),invoiceMode:Lr.optional(),membershipId:p.z.uuid(),carryOverBalances:ja.optional(),carryOverUsages:ja.optional(),membershipIds:p.z.array(p.z.uuid()).min(1).max(20).optional(),prorationBehavior:p.z.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:p.z.enum(["immediate","renewal","store"]),change:p.z.discriminatedUnion("type",[p.z.strictObject({type:p.z.literal("plan"),productVersionId:p.z.uuid()}),p.z.strictObject({type:p.z.literal("seats"),licenseKey:Wo,quantity:p.z.number().int().min(0).max(1e4)}),p.z.strictObject({type:p.z.literal("quantity"),internal_feature_id:p.z.uuid(),quantity:p.z.number().int().min(0).max(1e4)}),p.z.strictObject({type:p.z.literal("cancel")}),p.z.strictObject({type:p.z.literal("uncancel")}),p.z.strictObject({type:p.z.literal("billing_cycle"),billingCycleAnchor:p.z.union([p.z.literal("now"),p.z.number().int().positive().max(0xe677d21fdbff)])})])}).refine(e=>e.timing!=="store"||e.change.type==="plan","Store timing applies to a native plan replacement").refine(e=>e.change.type!=="billing_cycle"||e.timing===(e.change.billingCycleAnchor==="now"?"immediate":"renewal"),"Use immediate for now and renewal for a future millisecond anchor").refine(e=>!e.membershipIds||["cancel","uncancel"].includes(e.change.type)&&e.membershipIds.includes(e.membershipId)&&new Set(e.membershipIds).size===e.membershipIds.length,"Grouped actions require unique cancel/uncancel targets including the primary membership").refine(e=>!e.carryOverBalances&&!e.carryOverUsages||e.change.type==="plan"&&e.timing==="immediate","Carry applies only to immediate upgrades").refine(e=>!e.prorationBehavior||e.change.type==="quantity","prorationBehavior applies to prepaid quantity changes"),ka=p.z.string().regex(/^price_[A-Za-z0-9]+$/),Cm=p.z.strictObject({grooveUpdateId:p.z.uuid(),grooveCustomerId:p.z.uuid()}),_m=p.z.strictObject({price:ka.nullable(),priceId:p.z.uuid().optional(),quantity:p.z.number().int().min(0).max(1e4)}),Tm=p.z.strictObject({provider:p.z.literal("stripe"),invoiceMode:Lr.optional(),executor:p.z.enum(["indiana","merchant"]),accountId:p.z.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:p.z.string().regex(/^sub_[A-Za-z0-9]+$/),action:p.z.enum(["update","cancel","schedule","release"]),update:p.z.strictObject({items:p.z.array(_m).max(20),remove:p.z.array(ka).max(20),restoreItems:p.z.array(p.z.strictObject({price:ka,quantity:p.z.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:p.z.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:p.z.number().int().positive().optional(),paymentBehavior:p.z.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:p.z.boolean().optional(),clearCancelAt:p.z.literal(!0).optional(),billingCycleAnchorNow:p.z.literal(!0).optional(),metadata:Cm}).nullable(),cancel:p.z.strictObject({prorate:p.z.literal(!1),invoiceNow:p.z.literal(!1)}).nullable(),schedule:p.z.strictObject({currentItems:p.z.array(p.z.strictObject({price:ka,quantity:p.z.number().int().min(0).max(1e4)})).max(20),nextItems:p.z.array(_m).min(1).max(20),switchAt:p.z.number().int().positive(),interval:p.z.enum(["week","month","year"]),intervalCount:p.z.number().int().min(1).max(52),resetBillingCycleAnchor:p.z.literal(!0).optional(),metadata:Cm}).nullable(),release:p.z.strictObject({schedule:p.z.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:p.z.iso.datetime({offset:!0})}).refine(e=>["update","cancel","schedule","release"].every(t=>e[t]!==null==(e.action===t))&&(e.executor==="indiana"||[...e.update?.items??[],...e.schedule?.nextItems??[]].every(t=>t.price!==null)),"Stripe update execution carries exactly its action, with bound Prices for the merchant"),Ta=p.z.strictObject({carryOverBalances:ja.optional(),carryOverUsages:ja.optional(),operationId:p.z.uuid(),membershipId:p.z.uuid(),productVersionId:p.z.uuid(),timing:p.z.enum(["immediate","renewal"]),effectiveAt:p.z.iso.datetime({offset:!0}),expiresAt:p.z.iso.datetime({offset:!0}),currency:Ie,creditMinor:qt,debitMinor:qt,discountMinor:qt,taxMinor:qt,totalMinor:qt,retainedProductVersionIds:p.z.array(p.z.uuid()).max(19),execution:p.z.union([Tm,Ho])}),_S=p.z.strictObject({operationId:p.z.uuid(),invoiceMode:p.z.boolean().optional(),membershipId:p.z.uuid(),productVersionId:p.z.uuid(),status:p.z.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:p.z.enum(["immediate","renewal"]),effectiveAt:p.z.iso.datetime({offset:!0}),checkoutUrl:p.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:p.z.enum(["indiana","merchant"]),execution:p.z.union([Tm,Ho]).nullable(),confirmedAt:p.z.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Cr.nullable().optional(),problem:Li.nullable().optional(),quote:Ta.optional(),authority:Zo.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),ES=p.z.strictObject({operationId:p.z.uuid(),membershipId:p.z.uuid(),productVersionId:p.z.uuid(),timing:p.z.literal("store"),effectiveAt:p.z.null(),expiresAt:p.z.iso.datetime({offset:!0}),currency:Ie,creditMinor:p.z.null(),debitMinor:p.z.null(),discountMinor:p.z.null(),taxMinor:p.z.null(),totalMinor:p.z.null(),retainedProductVersionIds:p.z.array(p.z.uuid()).max(19),store:p.z.strictObject({provider:p.z.enum(["apple","google"]),productId:p.z.string().min(1).max(255),catalogAmountMinor:qt,policy:p.z.enum(["apple_store","google_full_price"])})}),RS=p.z.strictObject({operationId:p.z.uuid(),membershipId:p.z.uuid(),productVersionId:p.z.uuid(),status:p.z.enum(["prepared","pending","effective","cancelled","failed"]),timing:p.z.literal("store"),effectiveAt:p.z.iso.datetime({offset:!0}).nullable(),checkoutUrl:p.z.null(),nativePurchase:Nc.nullable()}),Nm=p.z.union([Ta,ES]),Fc=p.z.union([_S,RS]),mo=p.z.number().int().positive().max(2e8),zr=p.z.number().int().min(0).max(2e8),Dm=p.z.strictObject({requestId:p.z.uuid(),invoiceId:p.z.uuid(),mode:p.z.enum(["full","partial"]),amountMinor:mo.optional(),entitlementAction:p.z.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),Fm=p.z.strictObject({provider:p.z.literal("stripe"),executor:p.z.enum(["indiana","merchant"]),accountId:p.z.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:p.z.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:mo,currency:p.z.string().regex(/^[a-z]{3}$/),metadata:p.z.strictObject({indianaRefundId:p.z.uuid()}),idempotencyKey:p.z.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:p.z.array(p.z.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),Mc=p.z.strictObject({operationId:p.z.uuid(),invoiceId:p.z.uuid(),providerInvoiceId:p.z.string().min(1).max(200),currency:Ie,paidMinor:zr,refundedMinor:zr,pendingMinor:zr,amountMinor:mo,mode:p.z.enum(["full","partial"]),entitlementAction:p.z.enum(["retain","revoke"]),revokes:p.z.strictObject({customerProductIds:p.z.array(p.z.uuid()).max(100),subscriptionIds:p.z.array(p.z.string().min(1).max(200)).max(20)}),execution:p.z.union([Fm,Qo]),expiresAt:p.z.iso.datetime({offset:!0})}).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&(e.execution.provider==="merchant"?e.execution.merchantInvoiceId===e.providerInvoiceId&&e.execution.operationId===e.operationId&&e.execution.currency===e.currency:e.execution.invoice===e.providerInvoiceId&&e.execution.metadata.indianaRefundId===e.operationId&&e.execution.currency===e.currency.toLowerCase())&&(e.entitlementAction==="revoke"||e.revokes.customerProductIds.length===0&&e.revokes.subscriptionIds.length===0),"Refund quote must stay within the refundable amount and match its execution"),Na=p.z.strictObject({operationId:p.z.uuid(),invoiceId:p.z.uuid(),providerInvoiceId:p.z.string().min(1).max(200),status:p.z.enum(["quoted","pending","succeeded","failed","expired"]),executor:p.z.enum(["indiana","merchant"]),currency:Ie,amountMinor:mo,mode:p.z.enum(["full","partial"]),entitlementAction:p.z.enum(["retain","revoke"]),refundId:p.z.string().min(1).max(200).nullable(),quote:Mc.optional(),execution:p.z.union([Fm,Qo]).nullable(),confirmedAt:p.z.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Cr.nullable().optional(),problem:Li.nullable().optional(),authority:Zo.optional(),failureReason:p.z.string().min(1).max(200).nullable(),createdAt:p.z.iso.datetime({offset:!0}),completedAt:p.z.iso.datetime({offset:!0}).nullable()}).refine(e=>(e.execution===null||e.executor==="merchant"&&e.status==="quoted")&&(e.status!=="succeeded"||e.refundId!==null),"Only quoted record-only refunds carry instructions; a succeeded refund names its Stripe refund"),RC=p.z.strictObject({invoiceId:p.z.uuid(),currency:Ie,paidMinor:zr,refundedMinor:zr,pendingMinor:zr,refundableMinor:zr,executor:p.z.enum(["indiana","merchant"]).nullable(),canRefund:p.z.boolean(),operations:p.z.array(Na).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),kC=p.z.strictObject({requestId:p.z.uuid(),mode:p.z.enum(["full","partial"]),amountMinor:mo.optional(),entitlementAction:p.z.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount");var Mm=ot.z.strictObject({requestId:ot.z.uuid(),targets:ot.z.array(ot.z.strictObject({membershipId:ot.z.uuid(),action:ot.z.enum(["cancel","uncancel"]),timing:ot.z.enum(["immediate","renewal"])}).refine(e=>e.action!=="uncancel"||e.timing==="immediate","Restoration is immediate")).min(1).max(100)}).refine(e=>new Set(e.targets.map(t=>t.membershipId)).size===e.targets.length,"Duplicate batch target"),Da=ot.z.strictObject({batchId:ot.z.uuid()}),kS=ot.z.strictObject({operationId:ot.z.uuid(),membershipIds:ot.z.array(ot.z.uuid()).min(1).max(20),provider:ot.z.enum(["stripe","apple","google"]),action:ot.z.enum(["cancel","uncancel"]),timing:ot.z.enum(["immediate","renewal"]),status:ot.z.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:Ta.nullable(),managementUrl:ot.z.url().nullable(),failureCode:ot.z.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),fo=ot.z.strictObject({batchId:ot.z.uuid(),ready:ot.z.boolean(),status:ot.z.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:ot.z.iso.datetime({offset:!0}),acceptedAt:ot.z.iso.datetime({offset:!0}).nullable(),groups:ot.z.array(kS).min(1).max(100)});var je=require("zod"),jS=je.z.string().trim().min(1).max(240),qc={requestId:je.z.uuid(),reason:jS},Fa=je.z.discriminatedUnion("action",[je.z.strictObject({...qc,action:je.z.literal("start"),productVersionId:je.z.uuid(),entityId:je.z.uuid().optional(),days:je.z.number().int().min(1).max(730).optional()}),je.z.strictObject({...qc,action:je.z.literal("extend"),membershipId:je.z.uuid(),days:je.z.number().int().min(1).max(730)}),je.z.strictObject({...qc,action:je.z.literal("end"),membershipId:je.z.uuid()})]),qm=je.z.strictObject({operationId:je.z.uuid()}),Um=je.z.iso.datetime({offset:!0}),TS=je.z.strictObject({provider:je.z.literal("stripe"),executor:je.z.enum(["indiana","merchant"]),accountId:je.z.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:je.z.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:je.z.union([je.z.literal("now"),Um]),prorationBehavior:je.z.literal("none")}),Uc=je.z.strictObject({operationId:je.z.uuid(),action:je.z.enum(["start","extend","end"]),status:je.z.enum(["pending","effective"]),managedBy:je.z.enum(["indiana","stripe"]),membershipIds:je.z.array(je.z.uuid()).min(1).max(20),endsAt:Um.nullable(),execution:TS.nullable()}).refine(e=>e.execution!==null==(e.managedBy==="stripe"&&e.status==="pending")&&e.action==="end"==(e.endsAt===null)&&(e.action!=="start"||e.managedBy==="indiana")&&(e.execution===null||e.execution.trialEnd==="now"==(e.action==="end")),"Only a pending Stripe trial change carries execution instructions"),DC=je.z.strictObject({groupId:je.z.uuid(),productVersionId:je.z.uuid(),enabled:je.z.boolean()});var Je=require("zod");var Bm=Je.z.strictObject({requestId:Je.z.uuid(),currency:Ie,makeDefault:Je.z.boolean()}),Vm=Je.z.strictObject({setupId:Je.z.uuid()}),NS=Je.z.strictObject({provider:Je.z.literal("stripe"),executor:Je.z.literal("merchant"),accountId:Je.z.string().regex(/^acct_[A-Za-z0-9]+$/),mode:Je.z.literal("setup"),currency:Je.z.string().regex(/^[a-z]{3}$/),customer:Je.z.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:Je.z.uuid(),metadata:Je.z.strictObject({grooveProjectId:Je.z.uuid(),grooveEnvironmentId:Je.z.uuid(),grooveCustomerId:Je.z.uuid(),groovePaymentSetupId:Je.z.uuid()}),setDefaultPaymentMethod:Je.z.boolean(),expiresAt:Je.z.iso.datetime({offset:!0})}),Bc=Je.z.strictObject({id:Je.z.uuid(),provider:Je.z.literal("stripe"),status:Je.z.enum(["prepared","complete","expired"]),currency:Ie,makeDefault:Je.z.boolean(),url:Je.z.url().nullable(),createdAt:Je.z.iso.datetime({offset:!0}),expiresAt:Je.z.iso.datetime({offset:!0}),completedAt:Je.z.iso.datetime({offset:!0}).nullable(),execution:NS.nullable()});var jt=require("zod"),Lm=jt.z.union([jt.z.string(),jt.z.number(),jt.z.boolean(),jt.z.null()]),zm=jt.z.strictObject({customerId:jt.z.uuid()}),$m=jt.z.strictObject({customerId:jt.z.uuid(),provider:jt.z.literal("stripe"),checkedAt:jt.z.iso.datetime({offset:!0}),status:jt.z.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:jt.z.number().int().nonnegative(),differences:jt.z.array(jt.z.strictObject({subscriptionId:jt.z.string().startsWith("sub_"),itemId:jt.z.string().nullable(),field:jt.z.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Lm,actual:Lm})).max(1e4)});var we=require("zod");var Ma=we.z.iso.datetime({offset:!0}),qa=we.z.strictObject({createdAt:Ma,id:we.z.uuid()}),Ua=we.z.strictObject({customerId:we.z.uuid().optional(),entityId:we.z.uuid().optional(),productId:we.z.string().min(1).max(256).optional(),provider:we.z.enum(["stripe","apple","google","merchant","free"]).optional(),status:we.z.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:qa.optional(),limit:we.z.number().int().min(1).max(100).optional()}),Vc={id:we.z.uuid(),customerId:we.z.uuid(),entityId:we.z.uuid().nullable(),productId:we.z.string().min(1).max(256),productVersionId:we.z.uuid(),name:we.z.string().min(1).max(120),provider:we.z.enum(["stripe","apple","google","merchant","free"]),createdAt:Ma},DS=we.z.strictObject({...Vc,status:we.z.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:we.z.boolean(),billingSubscriptionId:we.z.uuid().nullable()}),FS=we.z.strictObject({...Vc,status:we.z.enum(["active","ended","refunded"]),orderId:we.z.uuid().nullable(),transactionId:we.z.uuid().nullable(),currency:Ie.nullable(),amountMinor:we.z.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),MS=we.z.strictObject({...Vc,status:we.z.enum(["blocked","resolved"]),conflict:we.z.strictObject({detectedAt:Ma,blockingMembershipIds:we.z.array(we.z.uuid()).min(1).max(100),transactionId:we.z.uuid()}),resolvedAt:Ma.nullable()}),Gm=Ua.extend({status:we.z.enum(["blocked","resolved"]).optional()}),Km=we.z.strictObject({customerId:we.z.uuid(),orderId:we.z.uuid()}),Hm=we.z.strictObject({orderId:we.z.uuid(),status:we.z.enum(["blocked","resolved"])}),Qm=we.z.strictObject({items:we.z.array(DS).max(100),nextCursor:qa.nullable()}),Jm=we.z.strictObject({items:we.z.array(FS).max(100),nextCursor:qa.nullable()}),Zm=we.z.strictObject({items:we.z.array(MS).max(100),nextCursor:qa.nullable()});var tt=require("zod");var Wm=tt.z.union([tt.z.strictObject({intent:tt.z.literal("read"),requestId:tt.z.uuid(),purchaseIntentId:tt.z.uuid()}),tt.z.strictObject({requestId:tt.z.uuid(),provider:tt.z.literal("apple"),purchaseIntentId:tt.z.uuid(),productId:tt.z.string().min(1).max(255).optional(),signedTransaction:tt.z.string().min(1).max(131072)}),tt.z.strictObject({requestId:tt.z.uuid(),provider:tt.z.literal("google"),purchaseIntentId:tt.z.uuid(),productId:tt.z.string().min(1).max(255).optional(),purchaseToken:tt.z.string().min(1).max(16384)})]),Ym=tt.z.strictObject({requestId:tt.z.uuid(),orderId:tt.z.uuid(),purchaseIntentId:tt.z.uuid(),status:tt.z.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:Ie,refunded:tt.z.boolean(),completion:tt.z.strictObject({transactionIds:tt.z.array(tt.z.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:tt.z.boolean()}).nullable()});var V=require("zod"),zc=V.z.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),qS=V.z.record(V.z.string(),V.z.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),US=3,go=20,BS=US*go,Lc=V.z.strictObject({type:V.z.literal("product"),productId:zc}),Xm={type:V.z.literal("group"),key:V.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:V.z.string().trim().min(1).max(80)},VS=V.z.discriminatedUnion("type",[Lc,V.z.strictObject({...Xm,items:V.z.array(Lc).max(go)})]),LS=V.z.discriminatedUnion("type",[Lc,V.z.strictObject({...Xm,items:V.z.array(VS).max(go)})]),zS=V.z.array(LS).max(go).superRefine((e,t)=>{let n=new Set,r=new Set,i=0;function a(o){for(let s of o){i++;let c=s.type==="product"?n:r,u=s.type==="product"?s.productId:s.key;c.has(u)&&t.addIssue({code:"custom",message:s.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),c.add(u),s.type==="group"&&a(s.items)}}a(e),(n.size>go||i>BS)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function $c(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:$c(t))}var vi=V.z.strictObject({lookupKey:V.z.string().trim().min(1).max(200),displayName:V.z.string().trim().min(1).max(1500),items:zS,metadata:qS}),$S=V.z.strictObject({product:V.z.record(V.z.string(),V.z.json()),prices:V.z.array(V.z.record(V.z.string(),V.z.json())),entitlements:V.z.array(V.z.record(V.z.string(),V.z.json())),freeTrials:V.z.array(V.z.record(V.z.string(),V.z.json())),licenses:V.z.array(V.z.record(V.z.string(),V.z.json()))}),ef=vi.extend({id:V.z.uuid(),projectId:V.z.uuid(),environmentId:V.z.uuid(),state:V.z.enum(["active","archived"]),isCurrent:V.z.boolean(),revision:V.z.number().int().nonnegative(),publishedVersionId:V.z.uuid().nullable(),createdAt:V.z.iso.datetime({offset:!0})}).superRefine((e,t)=>{e.isCurrent&&(e.state!=="active"||!e.publishedVersionId)&&t.addIssue({code:"custom",message:"Current Offering must be active and published"})}),tf=V.z.strictObject({id:V.z.uuid(),offeringId:V.z.uuid(),projectId:V.z.uuid(),environmentId:V.z.uuid(),version:V.z.number().int().positive(),document:vi,productEvidence:V.z.record(zc,$S),createdAt:V.z.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=$c(e.document);(!n.length||HS(e.document).length>0||Object.keys(e.productEvidence).length!==n.length||n.some(r=>!Object.hasOwn(e.productEvidence,r)))&&t.addIssue({code:"custom",message:"Published Offering requires evidence for every Product"})}),GS=V.z.strictObject({rows:V.z.array(ef).max(200),versions:V.z.array(tf).max(500)}),$C=V.z.discriminatedUnion("action",[V.z.strictObject({action:V.z.literal("create"),document:vi}),V.z.strictObject({action:V.z.literal("save"),id:V.z.uuid(),revision:V.z.number().int().nonnegative(),document:vi}),V.z.strictObject({action:V.z.enum(["publish","set_current","archive","restore"]),id:V.z.uuid(),revision:V.z.number().int().nonnegative()})]),GC=V.z.strictObject({record:ef,version:tf.nullable()}),nf=V.z.discriminatedUnion("type",[V.z.strictObject({type:V.z.literal("current")}),V.z.strictObject({type:V.z.literal("id"),id:V.z.uuid()}),V.z.strictObject({type:V.z.literal("lookup_key"),lookupKey:V.z.string().min(1).max(200)}),V.z.strictObject({type:V.z.literal("version"),versionId:V.z.uuid()})]),KS=V.z.strictObject({internalId:zc,id:V.z.string(),name:V.z.string().nullable(),version:V.z.number().int().positive(),archived:V.z.boolean()}),KC=GS.extend({products:V.z.array(KS).max(500),pagination:V.z.strictObject({rows:V.z.string().nullable(),versions:V.z.string().nullable(),products:V.z.string().nullable()}).optional()});function HS(e){let t=[];$c(e).length||t.push("Select at least one Product before publishing");function n(r){for(let i of r)i.type==="group"&&(i.items.length||t.push("Every published group requires a Product"),n(i.items))}return n(e.items),t}var ho=require("zod");var rf=ho.z.strictObject({id:ho.z.uuid(),offeringId:ho.z.uuid(),version:ho.z.number().int().positive(),document:vi});var vt=require("zod");var ye=require("zod");var Gr=require("zod");var Ba=Gr.z.strictObject({items:Gr.z.array(Gr.z.strictObject({productVersionId:Gr.z.string().min(1).max(200),label:Gr.z.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:Gr.z.string().min(1).max(200).nullable(),grouping:va.optional()});function of(e,t,n){let r=e.type==="fixed"?e.productVersionId:t[e.pickerId];return typeof r!="string"||!Object.values(n.plans).some(i=>i.versionId===r&&i.available)||e.type==="picker"&&(!e.allowedProductVersionIds.includes(r)||!n.pickers[e.pickerId]?.options.includes(r))?null:r}var Gc=ye.z.discriminatedUnion("type",[ye.z.strictObject({type:ye.z.literal("event"),event:ye.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),ye.z.strictObject({type:ye.z.literal("open_url"),url:ye.z.url().refine(e=>new URL(e).protocol==="https:")})]),QS=dn,JS=ye.z.discriminatedUnion("type",[ye.z.object({type:ye.z.literal("checkout"),product:Oa}).strict(),ye.z.object({type:ye.z.literal("close")}).strict(),ye.z.object({type:ye.z.literal("action"),action:Gc}).strict()]),wi=ye.z.object({schemaVersion:ye.z.literal(3),kind:ye.z.literal("paywall"),name:ye.z.string().trim().min(1).max(80),presentation:Cn,requirement:or.optional(),products:Ba,offeringVersionId:ye.z.uuid().nullable(),offeringId:ye.z.uuid(),screen:QS,buttons:ye.z.record(ye.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),JS)}).strict(),i_=wi.superRefine((e,t)=>{(e.screen.surface!=="paywall"||e.screen.actions.some(r=>!["event","navigate"].includes(r.type)||r.close))&&t.addIssue({code:"custom",message:"Paywall screen is incomplete"});for(let r of WS(e))t.addIssue({code:"custom",message:r});for(let r of ZS(e))t.addIssue({code:"custom",message:r});ar(e.screen).some(r=>!r.complete)&&t.addIssue({code:"custom",message:"Paywall needs complete local content"}),(Object.keys(e.buttons).length!==e.screen.actions.filter(r=>r.type!=="navigate").length||e.screen.actions.some(r=>r.type!=="navigate"&&!Object.hasOwn(e.buttons,r.id)))&&t.addIssue({code:"custom",message:"Paywall buttons require matching node policies"}),Object.values(e.buttons).some(r=>r.type==="checkout")||t.addIssue({code:"custom",message:"A paywall requires a purchase or membership change button"})});function ZS(e){let t=e.products.items.map(a=>a.productVersionId),n=Gp(e.screen),r=new Set,i=[];(!t.length||!e.products.defaultProductVersionId||!t.includes(e.products.defaultProductVersionId))&&i.push("products"),e.offeringVersionId||i.push("offering"),e.products.grouping&&(!wa(e.products.grouping,t)||e.products.grouping.tiers.some(a=>!e.products.grouping.assignments.some(o=>o.tierId===a.id)))&&i.push("grouping");for(let a of Object.values(e.buttons))if(a.type==="checkout"){let o=a.product;if(o.type==="fixed")r.add(o.productVersionId);else{o.allowedProductVersionIds.forEach(u=>r.add(u));let s=!1,c=n[o.pickerId];c&&(s=!0,(o.allowedProductVersionIds.some(u=>!c.ids.includes(u))||c.ids.some(u=>!o.allowedProductVersionIds.includes(u)))&&i.push("picker")),Ht(e.screen,u=>{if(u.id!==o.pickerId||u.type!=="plan_picker")return;s=!0,(JSON.stringify(u.planIds)!==JSON.stringify(t)||JSON.stringify(o.allowedProductVersionIds)!==JSON.stringify(t)||u.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let l=u.grouping?{tiers:u.grouping.tiers,assignments:u.grouping.assignments}:void 0;JSON.stringify(l)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),s||i.push("picker")}}return(!r.size||[...r].some(a=>!t.includes(a)))&&i.push("purchase"),Ht(e.screen,a=>{a.type==="stack"&&a.productSlot&&!a.bind?.plan&&i.push(`productBinding:${a.id}`),(a.type==="stack"||a.type==="button")&&a.bind?.plan&&!t.includes(a.bind.plan)&&i.push("binding"),a.type==="plan_picker"&&(!a.planIds?.length||a.planIds.some(o=>!t.includes(o)))&&i.push("binding")}),[...new Set(i)]}function WS(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),Wn(s.root,c=>{let u=c.type==="button"?c.action:c.type==="stack"?c.purchaseAction:void 0;if(u){let l=e.screen.actions.find(f=>f.id===u);l?.type==="navigate"&&r.get(s.id).push(l.pageId);let m=e.buttons[u];s.id!==n.id&&m&&m.type!=="close"&&t.push(`purchaseScreen:${c.id}`)}s.id!==n.id&&(c.type==="plan_picker"||c.type==="stack"&&c.productSlot)&&t.push(`packageScreen:${c.id}`)});let i=new Set;function a(s){if(!i.has(s)){i.add(s);for(let c of r.get(s)??[])a(c)}}let o=e.screen.initialPageId??e.screen.pages[0]?.id;o?a(o):t.push("initialPage");for(let s of e.screen.pages)i.has(s.id)||t.push(`unreachableScreen:${s.id}`);return[...new Set(t)]}var af=ye.z.object({id:ye.z.uuid(),projectId:ye.z.uuid(),environmentId:ye.z.uuid(),revision:ye.z.number().int().nonnegative(),state:ye.z.enum(["active","archived"]),publishedVersionId:ye.z.uuid().nullable(),updatedAt:ye.z.iso.datetime({offset:!0}),draft:wi}).strict(),o_=ye.z.object({rows:ye.z.array(af).max(200),nextCursor:ye.z.uuid().nullable()}).strict(),a_=af.omit({draft:!0}).extend({name:ye.z.string(),productCount:ye.z.number().int().nonnegative()}).strict(),s_=ye.z.discriminatedUnion("action",[ye.z.object({action:ye.z.literal("save"),id:ye.z.uuid().nullable(),revision:ye.z.number().int().nonnegative(),document:wi}).strict(),ye.z.object({action:ye.z.enum(["publish","archive"]),id:ye.z.uuid(),revision:ye.z.number().int().nonnegative()}).strict()]),c_=ye.z.object({paywalls:ye.z.array(ye.z.object({id:ye.z.uuid(),paywallId:ye.z.uuid(),version:ye.z.number().int().positive(),name:ye.z.string().min(1).max(80),presentation:Cn,buttons:wi.shape.buttons}).strict()).max(500),limited:ye.z.boolean()}).strict();var Re=require("zod");var Lt=require("zod");var Oi=Lt.z.string().regex(/^[a-f0-9]{64}$/),YS=Sa.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),sf=Lt.z.strictObject({couponDigests:Lt.z.record(Lt.z.uuid(),Oi),variables:Lt.z.record(wn,Lt.z.record(Lt.z.uuid(),Lt.z.partialRecord(Lt.z.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),Lt.z.string()))),locales:Lt.z.record(wn,mi.extend({nodes:Lt.z.record(Lt.z.string(),Lt.z.strictObject({base:YS})),plans:Lt.z.object({}).strict(),pickers:Lt.z.object({}).strict()}).omit({paywall:!0}))});var Ve=require("zod");var yo=require("zod"),Kc=yo.z.strictObject({eventsEnabled:yo.z.boolean(),experimentViewsEnabled:yo.z.boolean(),featureUsageEnabled:yo.z.boolean()}),m_=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function cf(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}var $=require("zod");var Hc=$.z.tuple([$.z.number().min(0).max(1),$.z.number().min(0).max(1)]).refine(([e,t])=>e<=t),XS=$.z.strictObject({attribute:$.z.string().optional(),seed:$.z.string(),hashVersion:$.z.literal(2),ranges:$.z.array(Hc).max(100)}),e0=$.z.strictObject({id:$.z.string().min(1).max(255),condition:Yt,gate:$.z.boolean().optional()}),t0=$.z.strictObject({key:$.z.string().optional(),name:$.z.string().optional(),passthrough:$.z.boolean().optional()}),uf={condition:Yt.optional(),parentConditions:$.z.array(e0).max(100).optional(),weights:$.z.array($.z.number().min(0).max(1)).max(20).optional(),coverage:$.z.number().min(0).max(1).optional(),hashAttribute:$.z.string().optional(),fallbackAttribute:$.z.string().optional(),hashVersion:$.z.literal(2).optional(),disableStickyBucketing:$.z.boolean().optional(),bucketVersion:$.z.number().int().nonnegative().optional(),minBucketVersion:$.z.number().int().nonnegative().optional(),filters:$.z.array(XS).max(100).optional(),ranges:$.z.array(Hc).max(20).optional(),meta:$.z.array(t0).max(20).optional(),seed:$.z.string().optional(),name:$.z.string().optional(),phase:$.z.string().optional()},Pi=$.z.strictObject({...uf,key:$.z.string().min(1).max(255),variations:$.z.tuple([ve,ve]).rest(ve).refine(e=>e.length<=20),urlPatterns:$.z.array($.z.strictObject({include:$.z.boolean(),type:$.z.enum(["regex","simple"]),pattern:$.z.string()})).max(100).optional(),force:$.z.number().int().nonnegative().optional(),active:$.z.boolean().optional(),persistQueryString:$.z.boolean().optional()}),Qc=$.z.strictObject({value:ve,variationId:$.z.number().int(),key:$.z.string(),name:$.z.string().optional(),bucket:$.z.number().optional(),passthrough:$.z.boolean().optional(),inExperiment:$.z.boolean(),hashUsed:$.z.boolean().optional(),hashAttribute:$.z.string(),hashValue:$.z.string(),featureId:$.z.string().nullable(),stickyBucketUsed:$.z.boolean().optional()}),n0=$.z.strictObject({...uf,id:$.z.string().max(255).optional(),force:ve.optional(),variations:$.z.array(ve).min(2).max(20).optional(),key:$.z.string().optional(),range:Hc.optional(),tracks:$.z.array($.z.strictObject({experiment:Pi,result:Qc})).max(100).optional()}),r0=$.z.strictObject({defaultValue:ve.optional(),rules:$.z.array(n0).max(500).optional()}),Ao=$.z.record($.z.string(),$.z.union([$.z.strictObject({type:$.z.literal("hashed"),attributeKey:$.z.string(),values:$.z.array($.z.string().regex(/^[a-f0-9]{64}$/))}),$.z.strictObject({type:$.z.literal("list"),attributeKey:$.z.string(),values:$.z.array($.z.union([$.z.string(),$.z.number()]))}),$.z.strictObject({type:$.z.literal("condition"),condition:Yt})])),bn=$.z.strictObject({scope:Fe,generation:$.z.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:$.z.iso.datetime({offset:!0}),expiresAt:$.z.iso.datetime({offset:!0}).nullable(),features:$.z.record($.z.string(),r0),savedGroups:Ao,experiments:$.z.record($.z.uuid(),Pi)});var bo=bn.extend({analyticsConfig:Kc,remoteFeatures:Ve.z.array(Ve.z.string().min(1).max(255)).max(500)}),Jc=bo.omit({evaluatedAt:!0,expiresAt:!0}).superRefine((e,t)=>{for(let n of e.remoteFeatures)Object.hasOwn(e.features,n)&&t.addIssue({code:"custom",path:["features",n],message:"Remote Feature definitions cannot be public"});for(let[n,r]of Object.entries(e.savedGroups))r.type==="list"&&t.addIssue({code:"custom",path:["savedGroups",n],message:"Raw Saved Group lists cannot be public"})}),lf=Ve.z.strictObject({attributes:Ct,features:Ve.z.array(Ve.z.string().min(1).max(255)).max(500).optional(),customerId:Ve.z.uuid().optional()}),i0=Ve.z.strictObject({value:ve,source:Ve.z.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:Ve.z.boolean(),off:Ve.z.boolean(),ruleId:Ve.z.string(),experimentResult:Qc.optional()}),Va=Ve.z.strictObject({generation:bn.shape.generation,evaluatedAt:bn.shape.evaluatedAt,expiresAt:bn.shape.expiresAt,features:Ve.z.record(Ve.z.string(),i0),merchandiseContext:Ve.z.strictObject({merchandiseId:Ve.z.uuid(),merchandise:Ct}).optional()}),df=Ve.z.strictObject({customerId:Ve.z.uuid().optional(),events:Ve.z.array(Ve.z.strictObject({eventUuid:Ve.z.uuid(),timestamp:Ve.z.iso.datetime({offset:!0}),name:Ve.z.string().min(1).max(255),merchandise:zd.optional(),properties:Ve.z.record(Ve.z.string(),ve).default({}),deviceId:Ve.z.string().min(1).max(255).optional(),sessionId:Ve.z.string().min(1).max(255).optional()})).min(1).max(100)}),pf=Ve.z.strictObject({inserted:Ve.z.number().int().nonnegative(),duplicates:Ve.z.number().int().nonnegative(),rejected:Ve.z.number().int().nonnegative(),skipped:Ve.z.number().int().nonnegative(),analyticsConfig:Kc});var L=require("zod");var mf=require("zod"),ff=mf.z.enum(["funnel-run/1","funnel-process/1"]),gf="funnel-process/1";function Zc(e,t=[]){let n=[];Ht(e,i=>{i.hidden&&n.push("Hidden components must not be delivered"),t.includes(i.type)&&n.push(`Node type ${i.type} cannot be delivered`)});let r=new Set(Pa(e).map(i=>i.key));for(let[i,a]of Object.entries(e.strings.locales))for(let o of Object.keys(a))r.has(o)||n.push(`Unused string ${o} must not be delivered (${i})`);return n}function hf(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>hf(t)??[])}}function o0(e){let t=e.pages.map(i=>{let a=hf(i.root);return a?.type==="stack"?{...i,root:a}:{...i,root:{type:"stack",id:i.root.id,...i.root.name===void 0?{}:{name:i.root.name},direction:"vertical",align:"stretch",justify:"start",children:[]}}}),n=new Set(Pa({pages:t}).map(i=>i.key)),r=Object.fromEntries(Object.entries(e.strings.locales).map(([i,a])=>[i,Object.fromEntries(Object.entries(a).filter(([o])=>n.has(o)))]));return{...e,pages:t,strings:{...e.strings,locales:r}}}function yf(e,t=[]){let n=dn.parse(structuredClone(o0(e))),r=a=>a.type!=="stack"||a.interaction!==void 0||a.children.some(r);for(let a of n.pages)if(!r(a.root))throw new Error(`Page ${a.id} has no visible content`);let i=Zc(n,t);if(i.length)throw new Error(i.join("; "));return n}var Q=require("zod");var M=require("zod");var pt=require("zod"),La=pt.z.strictObject({schemaVersion:pt.z.literal(1),renderKey:pt.z.string().min(1).max(256),routeTemplate:pt.z.string().startsWith("/").max(2048),selectors:pt.z.array(pt.z.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:pt.z.array(pt.z.number().int().min(0)).min(1),absent:pt.z.array(pt.z.number().int().min(0))}).superRefine((e,t)=>{let n=[...e.present,...e.absent];(new Set(e.selectors).size!==e.selectors.length||new Set(n).size!==n.length||n.length!==e.selectors.length||n.some(r=>r>=e.selectors.length))&&t.addIssue({code:"custom",message:"Incomplete or ambiguous render signature"})}),Af=pt.z.strictObject({renderKey:pt.z.string().min(1).max(256),routeKey:pt.z.string().min(1).max(256),stateKey:pt.z.string().min(1).max(256),documentKey:pt.z.string().min(1).max(256),documentHash:pt.z.string().regex(/^[a-f0-9]{64}$/),compositionKey:pt.z.string().min(1).max(256),entryMode:pt.z.enum(["hard","soft"]),match:pt.z.strictObject({present:pt.z.array(pt.z.number().int().min(0)),absent:pt.z.array(pt.z.number().int().min(0))})});var ur=require("zod"),a0=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],Wc="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",s0=ur.z.string().regex(new RegExp(`^${Wc}/${Wc}/${Wc}/manifest\\.json$`)),bf=ur.z.strictObject({kind:ur.z.literal("gcs-resumable"),url:ur.z.url(),bucket:ur.z.enum(a0),objectKey:s0,byteLength:ur.z.number().int().positive(),expiresAt:ur.z.iso.datetime()}).superRefine((e,t)=>{let n=new URL(e.url),r=n.searchParams,i=["uploadType","upload_id","name","upload_protocol","ifGenerationMatch"];(n.origin!=="https://storage.googleapis.com"||n.username||n.password||n.hash||n.pathname!==`/upload/storage/v1/b/${e.bucket}/o`||[...r.keys()].some(a=>!i.includes(a)||r.getAll(a).length!==1)||r.get("uploadType")!=="resumable"||!/^[A-Za-z0-9_-]{1,4096}$/.test(r.get("upload_id")??"")||r.has("name")&&r.get("name")!==`app-manifests/${e.objectKey}`||r.has("upload_protocol")&&r.get("upload_protocol")!=="resumable"||r.has("ifGenerationMatch")&&r.get("ifGenerationMatch")!=="0")&&t.addIssue({code:"custom",message:"Invalid IAM upload capability"})});var bt=M.z.string().min(1).max(256),mn=M.z.string().regex(/^[a-f0-9]{64}$/),za=M.z.strictObject({versionId:M.z.uuid(),manifestDigest:mn,sourceGraphDigest:mn,pageKey:bt,stateKey:bt,documentKey:bt,documentHash:mn,elementKey:bt.optional(),nodeId:bt.optional(),contentHash:mn.optional(),renderKey:bt.optional()}),xf=M.z.strictObject({pageKey:bt,documentKey:bt,expectedDocumentHash:mn,renderKey:bt.optional(),nodeId:bt,elementKey:bt,expectedContentHash:mn,property:M.z.enum(["text","fontSize","color"]),value:M.z.union([M.z.string().max(4e3),M.z.number().finite()])}),Sf=M.z.strictObject({versionId:M.z.uuid(),manifestDigest:mn,sourceGraphDigest:mn,pageKey:bt,stateKey:bt,documentKey:bt,documentHash:mn,renderKey:bt.optional(),patches:M.z.array(xf.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),c0=/^[a-z][a-z0-9-]{0,39}$/,xo=M.z.string().regex(c0),Xc=M.z.enum(["web","ios","android"]),R_=M.z.discriminatedUnion("action",[M.z.strictObject({action:M.z.literal("register"),requestId:M.z.uuid(),client:xo,platform:Xc,label:M.z.string().trim().min(1).max(100),sha256:mn,bytes:M.z.number().int().min(1),transferBytes:M.z.number().int().min(1)}),M.z.strictObject({action:M.z.literal("complete"),versionId:M.z.uuid()}),M.z.strictObject({action:M.z.literal("current"),versionId:M.z.uuid(),expectedCurrent:M.z.uuid().nullable()}),M.z.strictObject({action:M.z.literal("delivery"),enabled:M.z.boolean()}),M.z.strictObject({action:M.z.literal("changes"),versionId:M.z.uuid(),experimentId:M.z.uuid(),variationId:bt,changesetId:M.z.uuid().nullable(),expectedRevision:mn.nullable(),editorUrl:M.z.string().url().max(2048),patches:M.z.array(xf).max(200)})]),eu=M.z.strictObject({id:M.z.uuid(),projectId:M.z.uuid(),environmentId:M.z.uuid(),clientKey:xo,platform:Xc,label:M.z.string(),sha256:mn,bytes:M.z.number().int().positive(),objectKey:M.z.string(),state:M.z.enum(["uploading","ready","rejected"]),isCurrent:M.z.boolean(),revision:M.z.number().int().nonnegative(),createdAt:M.z.string(),expiresAt:M.z.string(),readyAt:M.z.string().nullable(),summary:M.z.record(M.z.string(),M.z.json()),routeTree:M.z.json().nullable(),validation:M.z.record(M.z.string(),M.z.json())}),u0=M.z.strictObject({key:xo,platform:Xc,currentId:M.z.uuid().nullable()}),k_=M.z.strictObject({rows:M.z.array(eu).max(100),nextCursor:M.z.uuid().nullable(),clients:M.z.array(u0).max(20)}),Yc=M.z.strictObject({storedBytes:M.z.number().int().nonnegative(),reservedBytes:M.z.number().int().nonnegative(),chargedBytes:M.z.number().int().nonnegative(),versions:M.z.number().int().nonnegative(),objects:M.z.number().int().nonnegative(),orphanObjects:M.z.number().int().nonnegative(),missingReadyObjects:M.z.number().int().nonnegative(),unknownObjectSizes:M.z.number().int().nonnegative(),byteLimit:M.z.number().int().positive(),versionLimit:M.z.number().int().positive(),remainingBytes:M.z.number().int().nonnegative()}),j_=M.z.strictObject({asOf:M.z.iso.datetime({offset:!0}),reclamation:M.z.literal("manual-review-required"),buckets:M.z.strictObject({source:Yc,runtime:Yc,previews:Yc})}),T_=M.z.strictObject({version:eu,actorId:M.z.uuid(),claims:M.z.record(M.z.string(),M.z.json())}),N_=M.z.strictObject({version:eu,upload:bf.nullable()}),D_=M.z.object({format:M.z.literal("indiana-route-state-index"),schemaVersion:M.z.literal(3),routes:M.z.array(M.z.object({routeKey:bt,path:M.z.string(),documentKey:bt,documentHash:mn,initialStateKey:bt,initialRenderKey:bt})),renders:M.z.array(Af)}).loose().superRefine((e,t)=>{(!e.renders||e.routes.some(n=>!e.renders?.some(r=>r.renderKey===n.initialRenderKey&&r.routeKey===n.routeKey&&r.documentKey===n.documentKey&&r.stateKey===n.initialStateKey&&r.documentHash===n.documentHash&&r.entryMode==="hard")))&&t.addIssue({code:"custom",message:"Incomplete render catalog"})}),F_=M.z.strictObject({rows:M.z.array(M.z.object({id:M.z.uuid(),name:M.z.string(),status:M.z.string(),variations:M.z.array(M.z.object({id:bt,key:bt,name:M.z.string().optional()}).loose())}).loose()),limited:M.z.boolean()}),M_=M.z.strictObject({enabled:M.z.boolean(),allowedOrigins:M.z.array(M.z.string())});var Kr=require("zod");var If=Kr.z.strictObject({id:Kr.z.uuid(),name:Kr.z.string().trim().min(1).max(80),client:xo,source:za,event:Kr.z.enum(["screen_enter","button_click"]),cooldownSeconds:Kr.z.number().int().min(0).max(2592e3),behavior:Kr.z.literal("observe")}).superRefine((e,t)=>{e.event==="button_click"&&(!e.source.nodeId||!e.source.elementKey)&&t.addIssue({code:"custom",path:["source"],message:"Choose a uniquely bound button"})});var ze=require("zod");var tu=ve,l0=["parameters","answers","results","variables"];function nu(e){return l0.some(t=>e===t||e.startsWith(t+"."))}function ru(e){let t={};for(let[r,i]of Object.entries(Ca(e.declarations,e))){let a=r.split(".");if(a.some(c=>["__proto__","constructor","prototype"].includes(c)))throw new Error("Reserved result path");let o=t;for(let c of a.slice(0,-1)){Object.hasOwn(o,c)||(o[c]={});let u=o[c];if(!u||typeof u!="object"||Array.isArray(u))throw new Error("Ambiguous result path");o=u}let s=a.at(-1);if(s===void 0)throw new Error("Empty result path");o[s]=i}return{...Object.fromEntries(Object.entries(e.attributes).filter(([r])=>!nu(r))),variables:t}}var ft=require("zod");var $a=ft.z.discriminatedUnion("kind",[ft.z.object({kind:ft.z.literal("ledger"),cursor:xa}).strict(),ft.z.object({kind:ft.z.literal("billing"),cursor:ft.z.uuid()}).strict()]),d0=ft.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),lr=ft.z.record(ft.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ft.z.union([ft.z.string().max(500),ft.z.boolean(),ft.z.array(ft.z.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),p0=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function iu(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>iu(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||p0.test(n)||iu(r,t+1)))}var m0=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,dr=ft.z.record(d0,ve).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!iu(e)&&!m0.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var vf=ft.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ga=ft.z.array(ft.z.object({variable:vf,componentId:vf,required:ft.z.boolean()}).strict()).max(40).refine(e=>new Set(e.map(t=>t.variable)).size===e.length&&new Set(e.map(t=>t.componentId)).size===e.length,"Input bindings must be unique"),H_=ft.z.object({bindings:Ga,answers:lr,values:ft.z.record(ft.z.string(),ve).optional()}).strict();var wf=require("zod"),Ka=wf.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var ou=ze.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Of=ze.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),Pf=dr.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),au=ze.z.record(ou,ze.z.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),f0=Mn,Cf=ze.z.strictObject({type:ze.z.literal("external_task"),endpointId:ze.z.uuid(),taskKey:ou,inputs:ze.z.record(ou,f0).refine(e=>Object.keys(e).length<=20),outputs:au}),_f=ze.z.strictObject({maxAttempts:ze.z.number().int().min(1).max(5),retryDelaySeconds:ze.z.number().int().min(1).max(30),backoff:ze.z.enum(["fixed","exponential"]),requestTimeoutSeconds:ze.z.number().int().min(1).max(10),timeoutSeconds:ze.z.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var t1=ze.z.strictObject({outcome:ze.z.enum(["success","failure"]),data:Pf});var n1=ze.z.discriminatedUnion("operation",[ze.z.strictObject({operation:ze.z.literal("signal"),runId:ze.z.uuid(),nodeId:Of,eventName:Ka,eventId:ze.z.uuid(),data:Pf}),ze.z.strictObject({operation:ze.z.literal("read_results"),runId:ze.z.uuid()})]),r1=ze.z.strictObject({scope:Fe,runId:ze.z.uuid(),eventId:ze.z.uuid(),accepted:ze.z.boolean()}),g0=ze.z.record(Of,tu),i1=ze.z.strictObject({scope:Fe,runId:ze.z.uuid(),results:g0});var kn={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},Ef="00000000-0000-0000-0000-000000000000";var J=require("zod");var Ze=require("zod");var u1=Ze.z.enum(["local","remote"]),su=Ze.z.strictObject({port:Ze.z.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:ve.optional(),sticky:Ze.z.array(Ze.z.strictObject({expected:Hi.nullable(),next:Hi})).max(100),exposures:Ze.z.array(ve).max(100),features:Ze.z.array(ve).max(100)}),Rf=Ze.z.strictObject({type:Ze.z.literal("evaluate"),receiptId:Ze.z.uuid(),environmentId:Ze.z.uuid(),policyRevision:Ze.z.number().int().nonnegative(),attributes:Ct,sticky:Ze.z.record(Ze.z.string(),Hi)}),kf=Rf.extend({runId:Ze.z.uuid(),versionId:Ze.z.uuid(),nodeId:Ze.z.string().min(1).max(64),visit:Ze.z.number().int().nonnegative(),revision:Ze.z.number().int().nonnegative()}),cu=Rf.omit({type:!0,receiptId:!0}).extend({type:Ze.z.literal("evaluate_segment")}),jf=Ze.z.strictObject({nodeId:Ze.z.string().min(1).max(64),result:su}),Tf=cu.extend({runId:Ze.z.uuid(),versionId:Ze.z.uuid(),nodeId:Ze.z.string().min(1).max(64),visit:Ze.z.number().int().nonnegative(),revision:Ze.z.number().int().nonnegative(),parameters:dr,answers:lr,variables:Ze.z.record(Ze.z.string(),ve)});var ue=require("zod");var uu=ue.z.array(ue.z.string().trim().min(1).max(40).refine(e=>!e.includes(","),"\u6807\u7B7E\u4E0D\u80FD\u5305\u542B\u9017\u53F7")).max(20).refine(e=>new Set(e).size===e.length,"\u6807\u7B7E\u4E0D\u80FD\u91CD\u590D"),Ha=ue.z.intersection(Ct,ue.z.looseObject({tags:uu.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),Qa=ue.z.string().trim().max(80),Ja=ue.z.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),Za=ue.z.union([ue.z.email().max(254),ue.z.literal("")]),Wa=ue.z.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),Nf=ue.z.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),Df=ue.z.object({externalUserId:Nf.optional(),name:Qa.default(""),email:Za.default(""),phone:Ja.optional(),attributes:Ha.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),Hr=ue.z.discriminatedUnion("type",[ue.z.strictObject({type:ue.z.literal("id"),value:ue.z.uuid()}),ue.z.strictObject({type:ue.z.literal("externalUserId"),value:Nf})]),Ci=ue.z.strictObject({name:Qa.optional(),email:Za.optional(),phone:Ja.optional(),attributes:Ha.optional(),fingerprint:Wa.optional()}),Ya=e=>!e.customerData||e.customer?.type==="externalUserId",Xa="customerData requires an externalUserId customer",_i=ue.z.object({id:ue.z.uuid(),externalUserId:ue.z.string().min(1).max(255).nullable(),name:Qa,email:Za,phone:Ja.optional(),attributes:Ha,createdAt:ue.z.iso.datetime()}).strict(),Ff=ue.z.object({customer:_i,changed:ue.z.boolean(),replayed:ue.z.boolean()}).strict(),h0=ue.z.discriminatedUnion("type",[ue.z.object({type:ue.z.literal("id"),value:ue.z.uuid()}).strict(),ue.z.object({type:ue.z.literal("externalUserId"),value:ue.z.string().trim().min(1).max(255)}).strict()]),y0=ue.z.object({name:Qa.optional(),email:Za.optional(),phone:Ja.optional(),attributes:Ha.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:ue.z.array(ue.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:ue.z.strictObject({add:uu,remove:uu}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),lu=ue.z.object({lookup:h0}).strict(),Mf=lu.extend({requestId:ue.z.uuid(),patch:y0}).strict(),qf=ue.z.object({search:ue.z.string().trim().max(200).default(""),tag:ue.z.string().trim().max(40).default(""),planId:ue.z.string().max(200).default(""),versionId:ue.z.string().max(200).default(""),holdingStatus:ue.z.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:ue.z.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:ue.z.union([ue.z.iso.datetime(),ue.z.literal("")]).default(""),createdUntil:ue.z.union([ue.z.iso.datetime(),ue.z.literal("")]).default(""),offset:ue.z.coerce.number().int().min(0).max(1e5).default(0),limit:ue.z.coerce.number().int().min(1).max(100).default(50)}).strict(),Uf=ue.z.object({customers:_i.array(),hasMore:ue.z.boolean(),total:ue.z.number().int().nonnegative().nullable(),evaluatedAt:ue.z.iso.datetime()}).strict();var So=J.z.discriminatedUnion("type",[J.z.strictObject({type:J.z.literal("literal"),value:ve}),J.z.strictObject({type:J.z.literal("variable"),key:It,path:Rn.optional()}),J.z.strictObject({type:J.z.literal("feature"),featureKey:J.z.string().min(1).max(128)})]),A0=J.z.strictObject({requestId:J.z.uuid(),decisionId:J.z.uuid(),customerId:J.z.uuid(),externalUserId:J.z.string().min(1).max(255).nullable(),versionId:J.z.uuid(),receiptId:J.z.uuid(),value:ve}),b0={funnelId:J.z.uuid(),requestId:J.z.uuid(),customer:Hr,customerData:Ci.optional(),attributes:Ct.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},b1=J.z.discriminatedUnion("operation",[J.z.strictObject({operation:J.z.literal("decide"),...b0}).refine(Ya,Xa),J.z.strictObject({operation:J.z.literal("read_decision"),decisionId:J.z.uuid()}),J.z.strictObject({operation:J.z.literal("evaluate_decision"),decisionId:J.z.uuid(),requestId:J.z.uuid(),nodeId:J.z.string().min(1).max(64),visit:J.z.number().int().nonnegative(),revision:J.z.number().int().nonnegative(),receiptId:J.z.uuid(),policyRevision:J.z.number().int().nonnegative(),generation:J.z.string().min(1).max(256),result:su}),J.z.strictObject({operation:J.z.literal("feature_config"),funnelId:J.z.uuid()}),J.z.strictObject({operation:J.z.literal("commit_decision_segment"),decisionId:J.z.uuid(),requestId:J.z.uuid(),nodeId:J.z.string().min(1).max(64),visit:J.z.number().int().nonnegative(),revision:J.z.number().int().nonnegative(),policyRevision:J.z.number().int().nonnegative(),generation:J.z.string().min(1).max(256),steps:J.z.array(jf).max(32),boundary:J.z.strictObject({nodeId:J.z.string().min(1).max(64),visit:J.z.number().int().nonnegative()}).optional()}),J.z.strictObject({operation:J.z.literal("segment_configuration"),funnelId:J.z.uuid(),versionId:J.z.uuid()}),J.z.strictObject({operation:J.z.literal("configuration"),funnelId:J.z.uuid(),versionId:J.z.uuid().optional()}),J.z.strictObject({operation:J.z.literal("local_configuration"),funnelId:J.z.uuid()}),J.z.strictObject({operation:J.z.literal("report_used"),decisionId:J.z.uuid(),eventId:J.z.uuid(),occurredAt:J.z.iso.datetime({offset:!0}),reference:J.z.string().min(1).max(128).optional()})]),x1=J.z.strictObject({scope:Fe,decisionId:J.z.uuid(),requestId:J.z.uuid(),status:J.z.enum(["pending","completed","failed"]),decision:A0.nullable(),evaluation:J.z.discriminatedUnion("type",[kf,Tf]).optional()}).refine(e=>e.status==="completed"==(e.decision!==null)&&(!e.decision||e.decision.decisionId===e.decisionId&&e.decision.requestId===e.requestId),"Completed decisions carry their committed result"),S1=J.z.strictObject({scope:Fe,decisionId:J.z.uuid(),eventId:J.z.uuid(),source:J.z.literal("caller_reported")});var Tt=require("zod");var Bf=Tt.z.strictObject({type:Tt.z.literal("bundle"),paywall:Mn.optional(),offering:Mn.optional(),coupons:Mn,data:Mn}),x0=e=>Tt.z.strictObject({type:Tt.z.literal(e),id:Tt.z.uuid()}),P1=Tt.z.strictObject({type:Tt.z.literal("bundle"),paywallVersionId:Tt.z.uuid().optional(),offeringVersionId:Tt.z.uuid().optional(),couponIds:Tt.z.array(Tt.z.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:ve});var C1=Tt.z.strictObject({type:Tt.z.literal("bundle"),offering:x0("offering_version").nullable(),paywall:Tt.z.strictObject({versionId:Tt.z.uuid(),paywallId:Tt.z.uuid(),offeringVersionId:Tt.z.uuid()}).nullable(),coupons:Tt.z.array(Qi).max(20),data:ve});var xn=require("zod");var fn=require("zod");var Vf=fn.z.union([fn.z.string(),fn.z.number().finite(),fn.z.boolean(),fn.z.null()]),S0=fn.z.union([Vf,fn.z.array(Vf).min(1).max(20)]),I0=fn.z.record(Rn,S0).refine(e=>Object.keys(e).length<=10),Lf=fn.z.strictObject({path:Rn,type:fn.z.enum(["string","number","boolean","strings"]),nullable:fn.z.boolean().optional(),aggregation:fn.z.enum(["count","exists"]).optional(),where:I0.optional()}).superRefine((e,t)=>{(e.aggregation==="count"&&e.type!=="number"||e.aggregation==="exists"&&e.type!=="boolean"||!e.aggregation&&e.where)&&t.addIssue({code:"custom",message:"Collection summaries require their matching type"})});var v0=["sendMessage","checkEntitlement","resolveOffering","readHoldings","readLedger","readBillingInvoice","readCreditStatement","previewAttach","attach","readSubscriptionOperation","previewUpdate","update","readSubscriptionUpdate","setupPayment","readPaymentSetup","verifySubscriptions","previewRefund","refund","readRefund","restoreNativePurchase","readBillingControls","prepareBillingAuthorization","confirmBillingAuthorization","setBillingCoupons","revokeBillingAuthorization","listBillingInvoices","confirmBillingAdjustment","manageBillingLimits","readSeats","manageSeat","quoteBalance","mutateBalance","trackUsage","readUsage","setUsage","adjustBalance","readBalanceSource","manageBalanceGrant","listBalanceGrants","manageUsageEntity","readUsageAnalytics","readCreditAnalytics","submitUsageBatch","readUsageBatch","redeemCoupon","listOffers","grantOffer","redeemReward","createReferralCode","claimRewardProduct"],zf=xn.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),w0=Mn,$f=xn.z.discriminatedUnion("type",[Cf,xn.z.strictObject({type:xn.z.literal("claim_offer"),coupon:Mn}),xn.z.strictObject({type:xn.z.literal("event"),event:zf}),xn.z.strictObject({type:xn.z.literal("api"),operation:xn.z.enum(v0),inputs:xn.z.record(Rn,w0).refine(e=>Object.keys(e).length<=40),outputs:xn.z.record(zf,Lf).refine(e=>Object.keys(e).length<=20)})]);var dt=Ka,O0=Q.z.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),gn={id:dt,name:Q.z.string().trim().min(1).max(80),position:Q.z.strictObject({x:Q.z.number().finite(),y:Q.z.number().finite()}).optional()},P0={success:dt,cancel:dt,unavailable:dt,failure:dt},du=Q.z.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),pu=Q.z.enum(["same_window","new_window"]),C0=Q.z.discriminatedUnion("type",[Q.z.strictObject({...gn,type:Q.z.literal("entry"),next:dt,triggers:Q.z.array(If).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),Q.z.strictObject({...gn,type:Q.z.literal("screen"),screenId:dt,presentation:Cn,outputs:Q.z.record(dt,dt),offering:Q.z.discriminatedUnion("source",[Q.z.strictObject({source:Q.z.literal("variable"),key:It}),Q.z.strictObject({source:Q.z.literal("fixed"),versionId:Q.z.uuid()})]).optional()}),Q.z.strictObject({...gn,type:Q.z.literal("offering"),configuration:Q.z.discriminatedUnion("source",[Q.z.strictObject({source:Q.z.literal("fixed"),versionId:Q.z.uuid()}),Q.z.strictObject({source:Q.z.literal("feature"),featureKey:Q.z.string().min(1).max(128)})]),writes:Q.z.strictObject({value:It}),next:dt}),Q.z.strictObject({...gn,type:Q.z.literal("coupon"),couponId:Q.z.uuid(),writes:Q.z.strictObject({value:It}),next:dt}),Q.z.strictObject({...gn,type:Q.z.literal("coupons"),couponIds:Q.z.array(Q.z.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:Q.z.strictObject({value:It}),next:dt}),Q.z.strictObject({...gn,type:Q.z.literal("output"),value:Q.z.discriminatedUnion("type",[...So.options,Bf,Q.z.strictObject({type:Q.z.literal("selection"),screenId:dt,offeringKey:It})])}),Q.z.strictObject({...gn,type:Q.z.literal("condition"),cases:Q.z.array(Q.z.strictObject({condition:Yt,target:dt})).min(1).max(50),default:dt}),Q.z.strictObject({...gn,type:Q.z.literal("feature"),featureKey:Q.z.string().min(1).max(128),writes:Q.z.strictObject({value:It}),next:dt}),Q.z.strictObject({...gn,type:Q.z.literal("split"),experimentId:Q.z.uuid(),applyPageExperiment:Q.z.literal(!0).optional(),routes:Q.z.record(O0,dt).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:dt}),Q.z.strictObject({...gn,type:Q.z.literal("action"),...P0,execution:_f,action:$f,writes:Cc.optional()}),Q.z.strictObject({...gn,type:Q.z.literal("external_page"),appManifest:za.optional(),url:du,openIn:pu,opened:dt,failed:dt}),Q.z.strictObject({...gn,type:Q.z.literal("end"),outcome:Q.z.enum(["completed","closed","ineligible","failed"]),output:So.optional()}),Q.z.strictObject({...gn,type:Q.z.literal("wait"),writes:Cc.optional(),wait:Q.z.discriminatedUnion("type",[Q.z.strictObject({type:Q.z.literal("duration"),delaySeconds:Q.z.number().int().min(1).max(2592e3),elapsed:dt}),Q.z.strictObject({type:Q.z.literal("event"),eventName:dt,outputs:au,timeoutSeconds:Q.z.number().int().min(1).max(2592e3),received:dt,timeout:dt})])})]),mu=Q.z.strictObject({version:Q.z.literal(5),entry:dt,nodes:Q.z.array(C0).min(1).max(kn.flowNodes)}),fu=mu.superRefine((e,t)=>{_0(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function es(e){switch(e.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":return[e.next];case"screen":return Object.values(e.outputs);case"condition":return[...e.cases.map(t=>t.target),e.default];case"split":return[...Object.values(e.routes),e.notParticipating];case"action":return[e.success,e.cancel,e.unavailable,e.failure];case"external_page":return[e.opened,e.failed];case"end":case"output":return[];case"wait":return e.wait.type==="duration"?[e.wait.elapsed]:[e.wait.received,e.wait.timeout]}}function _0(e,t){let n=[],r=new Map(e.nodes.map(l=>[l.id,l])),i=(l,m,f)=>{n.push(l),t?.({message:l,reason:m,path:f?["nodes",e.nodes.indexOf(f)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(l=>l.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(l=>l.type==="screen").length>kn.pages||e.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>kn.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let l of e.nodes){for(let m of es(l))m===e.entry&&i("An entry cannot be a transition target","entryTarget",l),r.has(m)||i(`Missing target ${m}`,"missingTarget",l);l.type==="screen"&&(a.has(l.screenId)&&i("Every screen has exactly one node owner","screenOwner",l),a.add(l.screenId))}let o=new Set,s=new Set,c=new Set;function u(l){if(o.has(l)){i("Flow edges must not form a cycle","cycle",r.get(l));return}if(!(s.has(l)||!r.has(l))){o.add(l),c.add(l);for(let m of es(r.get(l)))u(m);o.delete(l),s.add(l)}}u(e.entry);for(let l of e.nodes)c.has(l.id)||i("Every node must be reachable from Entry","unreachable",l);return[...new Set(n)]}var gu={maxTransitions:1e4,runTimeoutSeconds:2592e3};function Gf(e,t,n){let r=[...t].sort((s,c)=>c.length-s.length),i=new Set,a=(s,c=!1)=>{let u=r.find(l=>s===l||c&&s.startsWith(l+"."));i.add(u??s)};if(e.type==="condition"){let s=n?.startsWith("case_")?Number(n.slice(5)):e.cases.length-1;for(let c of e.cases.slice(0,s+1))for(let u of rr(c.condition))u.startsWith("variables.")&&a(u.slice(10),!0)}if(e.type==="screen"&&e.offering?.source==="variable"&&a(e.offering.key),e.type==="action"&&(e.action.type==="api"||e.action.type==="external_task"))for(let s of Object.values(e.action.inputs))s.source==="variable"&&a(s.key);e.type==="action"&&e.action.type==="claim_offer"&&e.action.coupon.source==="variable"&&a(e.action.coupon.key);let o=e.type==="output"?e.value:e.type==="end"?e.output:null;if(o?.type==="variable"&&a(o.key),o?.type==="bundle")for(let s of[o.paywall,o.offering,o.coupons,o.data])s?.source==="variable"&&a(s.key);return o?.type==="selection"&&a(o.offeringKey),[...i]}var q=require("zod");var Ei=q.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),ts=e=>q.z.record(q.z.string(),ve).refine(t=>pn(t)<=e,"Funnel evidence exceeds its byte budget"),eE=q.z.enum(["local_segment","evaluation","presentation","timer","event","operation"]),yu=q.z.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Au=q.z.discriminatedUnion("type",[q.z.strictObject({type:q.z.literal("flag"),key:q.z.string().min(1).max(128)}),q.z.strictObject({type:q.z.literal("experiment"),id:q.z.uuid()}),q.z.strictObject({type:q.z.literal("saved_group"),id:q.z.uuid()}),q.z.strictObject({type:q.z.literal("config"),key:q.z.string().min(1).max(128)}),q.z.strictObject({type:q.z.literal("constant"),key:q.z.string().min(1).max(128)}),q.z.strictObject({type:q.z.literal("paywall_version"),id:q.z.uuid()}),q.z.strictObject({type:q.z.literal("offering_version"),id:q.z.uuid()}),q.z.strictObject({type:q.z.literal("reward"),id:q.z.uuid()})]),Io=q.z.strictObject({schemaVersion:q.z.literal(1),kind:yu,selector:Au.nullable(),context:ts(131072),contract:q.z.strictObject({version:q.z.number().int().positive(),evaluator:q.z.string().min(1).max(128),policyRevision:q.z.number().int().nonnegative()})}).refine(e=>pn(e)<=131072,"Node input exceeds its byte budget"),Kf=q.z.strictObject({schemaVersion:q.z.literal(1),kind:yu,outcome:q.z.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:ts(131072),route:q.z.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:ts(131072)}).refine(e=>pn(e)<=131072,"Node result exceeds its byte budget"),tE=q.z.strictObject({schemaVersion:q.z.literal(1),operations:q.z.record(Ei,q.z.strictObject({attempts:q.z.number().int().nonnegative(),maxAttempts:q.z.number().int().min(1).max(5),deadlineAt:q.z.iso.datetime({offset:!0}),retryAt:q.z.iso.datetime({offset:!0}).nullable(),error:q.z.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:q.z.strictObject({type:Ei,id:q.z.uuid()}).nullable()}))}).refine(e=>pn(e)<=65536,"Execution state exceeds its byte budget"),Qr={receiptId:q.z.uuid()},hu=q.z.iso.datetime({offset:!0}),nE=q.z.discriminatedUnion("type",[q.z.strictObject({type:q.z.literal("node_entered"),details:q.z.strictObject({kind:yu})}),q.z.strictObject({type:q.z.literal("presentation_shown"),details:q.z.strictObject({...Qr,source:q.z.literal("client"),occurredAt:hu.optional()})}),q.z.strictObject({type:q.z.literal("decision_accepted"),details:q.z.strictObject(Qr)}),q.z.strictObject({type:q.z.literal("signal_received"),details:q.z.strictObject({signalId:q.z.uuid(),nodeId:Ei,eventName:Ei,data:ts(8192),source:q.z.literal("server"),occurredAt:hu})}),q.z.strictObject({type:q.z.literal("signal_consumed"),details:q.z.strictObject({...Qr,signalId:q.z.uuid()})}),q.z.strictObject({type:q.z.literal("wait_elapsed"),details:q.z.strictObject(Qr)}),q.z.strictObject({type:q.z.literal("wait_timeout"),details:q.z.strictObject(Qr)}),q.z.strictObject({type:q.z.literal("operation_completed"),details:q.z.strictObject({...Qr,operation:Ei,reference:q.z.strictObject({type:Ei,id:q.z.uuid()}).nullable()})}),q.z.strictObject({type:q.z.literal("execution_recovered"),details:q.z.strictObject({generation:q.z.number().int().positive(),reason:q.z.enum(["interrupted","expired_lease","delivery_failed"])})}),q.z.strictObject({type:q.z.literal("execution_failed"),details:q.z.strictObject({generation:q.z.number().int().positive(),code:q.z.string().regex(/^[a-z_]{1,64}$/)})}),q.z.strictObject({type:q.z.literal("run_completed"),details:q.z.strictObject({outcome:q.z.enum(["completed","ineligible","failed"])})}),q.z.strictObject({type:q.z.literal("run_closed"),details:q.z.strictObject({source:q.z.enum(["client","server","expiry"])})}),q.z.strictObject({type:q.z.literal("treatment_used"),details:q.z.strictObject({...Qr,source:q.z.enum(["client","server"]),occurredAt:hu,reference:q.z.string().min(1).max(128).optional()})})]);var Sn=L.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),E0=L.z.discriminatedUnion("type",[L.z.strictObject({id:Sn,type:L.z.literal("owned"),publicData:sf.optional(),document:dn.refine(e=>["page","popup","onboarding"].includes(e.surface)&&e.pages.length===1&&e.actions.every(t=>t.type==="event"&&!t.close),"A Funnel owns one Page or Popup per screen and emits outputs; Paywall owns its purchase policies")}),L.z.strictObject({id:Sn,type:L.z.literal("paywall"),paywallVersionId:L.z.uuid()})]),bu={executionContract:ff.optional(),kind:L.z.literal("funnel"),schemaVersion:L.z.literal(4),screens:L.z.array(E0).max(kn.pages),references:L.z.record(Sn,Au).refine(e=>Object.keys(e).length<=500),inputs:L.z.array(L.z.strictObject({variable:Sn,screenId:Sn,componentId:Sn,required:L.z.boolean()})).max(kn.questions),variables:L.z.record(It,hi).refine(e=>Object.keys(e).length<=kn.logicNodes),outputSchema:gi,execution:L.z.strictObject({runTimeoutSeconds:L.z.number().int().min(1).max(gu.runTimeoutSeconds),maxTransitions:L.z.number().int().min(1).max(gu.maxTransitions)})},SE=L.z.strictObject({...bu,graph:mu});function R0(e,t){let n=!1,r=(i,a)=>{let o=i.type==="stack"||i.type==="button"?i.bind?.coupon??a:a;i.type==="text"&&Object.values(e.strings.locales).some(s=>s[i.text]?.includes("{{offer."))&&!(o&&t(o))&&(n=!0),i.type==="stack"&&i.children.forEach(s=>r(s,o))};for(let i of e.pages)r(i.root);return n}function rs(e){return Array.isArray(e)?e.some(rs):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===Ef:rs(n))}function k0(e){let t=[],n=new Set(Object.values(e.references).flatMap(r=>r.type==="reward"?[r.id]:[]));for(let[r,i]of e.screens.entries()){if(i.type!=="owned")continue;let a;try{a=yf(i.document)}catch(o){t.push({message:o instanceof Error?o.message:"Screen cannot be delivered",reason:"screen",path:["screens",r,"document"]});continue}for(let[o,s]of e.inputs.entries())s.screenId===i.id&&!lo(a,s.componentId)&&t.push({message:`Local Funnel input ${s.variable} targets hidden component ${s.componentId} on screen ${s.screenId}`,reason:"inputBinding",path:["inputs",o]})}for(let[r,i]of e.graph.nodes.entries()){let a=["graph","nodes",r],o=i.type==="screen"?e.screens.find(s=>s.id===i.screenId):void 0;o?.type==="owned"&&(o.document.actions.some(s=>typeof s.properties.templateKey=="string"&&s.properties.templateKey.startsWith("popup-coupon-"))&&t.push({message:"Funnel screens claim Coupons through a Claim Coupon step",reason:"coupon",path:a}),R0(o.document,s=>n.has(s))&&t.push({message:"Offer copy shows the Coupon of a Claim Coupon step",reason:"coupon",path:a})),(i.type==="output"&&i.value.type==="literal"&&rs(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&rs(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function Hf(e,t){for(let{message:n,reason:r,path:i}of k0(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function Qf(e,t){let n=(g,d,h=[])=>t.addIssue({code:"custom",message:g,path:h,params:{reason:d}}),r=Object.values(e.references),i=new Map(e.screens.map(g=>[g.id,g])),a=(g,d)=>r.some(h=>h.type===g&&("id"in h?h.id:h.key)===d);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let o=e.graph.nodes.filter(g=>g.type==="screen");(o.length!==i.size||o.some(g=>!i.has(g.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(g=>c.some(d=>g!==d&&d.startsWith(g+".")))&&n("Variable paths must not overlap","variable");function u(g,d){Object.hasOwn(e.variables,g)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(d)]);let h=s.get(g)??new Set;h.add(d.id),s.set(g,h)}for(let[g,d]of e.graph.nodes.entries()){let h=["graph","nodes",g],R=d.type==="feature"?d.featureKey:d.type==="offering"&&d.configuration.source==="feature"?d.configuration.featureKey:d.type==="output"&&d.value.type==="feature"?d.value.featureKey:d.type==="end"&&d.output?.type==="feature"?d.output.featureKey:null;R&&!a("flag",R)&&n("Flag selectors require an explicit GB resource reference","feature",h);let y=d.type==="feature"||d.type==="offering"||d.type==="coupon"||d.type==="coupons"||d.type==="action"&&d.action.type==="api"?["value"]:d.type==="action"&&d.action.type==="external_task"?Object.keys(d.action.outputs):d.type==="wait"&&d.wait.type==="event"?Object.keys(d.wait.outputs):[],A="writes"in d?d.writes??{}:{};(y.length!==Object.keys(A).length||y.some(v=>!Object.hasOwn(A,v))||new Set(Object.values(A)).size!==Object.values(A).length)&&n("Node writes must map every named output exactly once","variable",h);for(let[v,P]of Object.entries(A)){u(P,d);let j=e.variables[P],_=d.type==="offering"?"offering_version":d.type==="coupon"?"reward":d.type==="action"&&d.action.type==="api"?"json":d.type==="action"&&d.action.type==="external_task"?d.action.outputs[v]:d.type==="wait"&&d.wait.type==="event"?d.wait.outputs[v]:void 0;(j?.source.type!=="node"||_&&j.type!==_)&&n("Node writer source or output type does not match declaration","variable",h)}if(d.type==="coupons"){let v=e.variables[d.writes.value];(v?.type!=="array"||v.items?.type!=="reward"||v.items.nullable||v.nullable)&&n("Coupons output requires a non-null Reward array","variable",h);for(let P of d.couponIds)a("reward",P)||n("Coupons require Reward references","coupon",h)}if(d.type==="split"&&!a("experiment",d.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",h),d.type==="coupon"&&!a("reward",d.couponId)&&n("Coupon selectors require a Reward reference","coupon",h),d.type==="action"&&d.action.type==="claim_offer"&&d.action.coupon.source==="literal"){let v=d.action.coupon.value;(!v||typeof v!="object"||Array.isArray(v)||v.type!=="reward"||typeof v.id!="string"||Object.keys(v).length!==2||!a("reward",v.id))&&n("Coupon claims require a Reward reference","coupon",h)}if(d.type==="offering"&&d.configuration.source==="fixed"&&!a("offering_version",d.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",h),d.type==="screen"&&d.offering?.source==="variable"&&e.variables[d.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",h),d.type==="action"&&d.action.type==="claim_offer"&&d.action.coupon.source==="variable"&&(e.variables[d.action.coupon.key]?.type!=="reward"||d.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",h),d.type==="screen"){let v=i.get(d.screenId);if(d.offering?.source==="fixed"&&!a("offering_version",d.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",h),v?.type==="paywall"&&d.offering&&n("Paywall owns its fixed Offering Version","offering",h),v?.type==="paywall"&&!a("paywall_version",v.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",h),v?.type==="owned"){let P=v.document.pages[0];if(!P){n("Owned screen requires a page","screen",h);continue}ar(v.document).some(_=>!_.complete)&&n("Owned screens require complete local content","translations",h);let j=new Set(v.document.actions.map(_=>_.id));(j.size!==Object.keys(d.outputs).length||Object.keys(d.outputs).some(_=>!j.has(_)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",h),Wn(P.root,_=>{!d.offering&&(_.type==="plan_picker"||(_.type==="stack"||_.type==="button")&&_.bind?.plan||_.type==="customer_data"&&["customer_plans","credit_packs"].includes(_.data.source))&&n("Product presentation requires an Offering Version","offering",h),_.type==="customer_data"&&Object.values(_.data.outputs??{}).some(X=>X!==void 0&&!j.has(X))&&n("Customer components require declared screen outcomes","componentOutput",h)})}}d.type==="end"&&["completed","ineligible"].includes(d.outcome)&&!d.output&&n("Completed and ineligible ends require a declared output","output",h),d.type==="end"&&d.output?.type==="literal"&&!An(e.outputSchema,d.output.value)&&n("Terminal output does not match outputSchema","output",h),d.type==="output"&&d.value.type==="literal"&&!An(e.outputSchema,d.value.value)&&n("Terminal output does not match outputSchema","output",h);let x=d.type==="output"?d.value:d.type==="end"?d.output:void 0;if(x?.type==="variable"&&!x.path){let v=e.variables[x.key];v&&!_c(v,e.outputSchema)&&n("Variable output does not match outputSchema","output",h)}if(d.type==="screen"){let v=i.get(d.screenId);if(v?.type==="owned")for(let P of kc(v.document))(/^(input|params)\./.test(P)||P.startsWith("variables.")&&!Rc(P.slice(10),c))&&n("Screen values must reference registered variables","variable",h)}if(d.type==="condition")for(let v of d.cases){for(let P of Qn(v.condition))a("saved_group",P)||n("Conditions require explicit Saved Group references","savedGroup",h);for(let P of rr(v.condition))P.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",h)}if(d.type==="output"&&d.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",h);for(let[v,P]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let j=d.value[v];if(j)if(j.source==="literal"){let _=v==="coupons"?j.value:[j.value];(!Array.isArray(_)||_.length>20||_.some(X=>!An({type:P,nullable:!1},X)||!a(P,X.id))||v==="coupons"&&new Set(_.map(X=>X.id)).size!==_.length)&&n("Bundle requires distinct scoped resource references",v==="coupons"?"coupon":v==="paywall"?"paywall":"offering",[...h,"value",v])}else{let _=e.variables[j.key];(j.path||!_||_.nullable||(v==="coupons"?_.type!=="array"||_.items?.type!=="reward"||_.items.nullable:_.type!==P))&&n("Bundle binding type does not match its slot","output",h)}}}}for(let[g,d]of e.graph.nodes.entries()){let h=d.type==="screen"?i.get(d.screenId):void 0,R=[...Gf(d,c),...h?.type==="owned"?_a(h.document).map(y=>Rc(y,c)?.key??y):[]];for(let y of new Set(R)){let P=function(j){if(j===d.id)return!0;if(v.has(j))return!1;v.add(j);let _=e.graph.nodes.find(le=>le.id===j);return _?(x.has(j)?_.type==="action"?[_.cancel,_.unavailable,_.failure]:_.type==="wait"&&_.wait.type==="event"?[_.wait.timeout]:[]:es(_)).some(P):!1};var f=P;if(!Object.hasOwn(e.variables,y)){n("Consumed variable is undeclared","variable",["graph","nodes",g]);continue}let A=e.variables[y];if(d.type==="screen"&&A.source.type==="input"&&e.inputs.some(j=>j.screenId===d.screenId&&j.variable===y)||A.source.type==="parameter"||A.source.type==="attribute")continue;let x=A.source.type==="input"?new Set(e.inputs.filter(j=>j.variable===y&&j.required).flatMap(j=>o.filter(_=>_.screenId===j.screenId).map(_=>_.id))):s.get(y)??new Set,v=new Set;(!x.size||P(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",g])}}(new Set(e.inputs.map(g=>g.variable)).size!==e.inputs.length||new Set(e.inputs.map(g=>`${g.screenId}:${g.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[g,d]of e.inputs.entries()){e.variables[d.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",g]);let h=i.get(d.screenId),R=h?.type==="owned"?lo(h.document,d.componentId):null;if((R?.type!=="stack"||!R.interaction||!["input","toggle","select","multiselect","tabs"].includes(R.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",g]),R?.type==="stack"&&R.interaction){let y=R.interaction.type==="toggle"?"boolean":R.interaction.type==="multiselect"?"strings":"string";e.variables[d.variable]?.type!==y&&n("Input variable type does not match component","inputBinding",["inputs",g]);let A=e.variables[d.variable]?.enum;A&&!R.children.filter(x=>!x.hidden).every(x=>A.includes(x.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",g])}}for(let[g,d]of Object.entries(e.variables))d.enum&&d.type!=="string"&&n("Only string variables support enum","variable",["variables",g]),d.source.type==="input"&&!e.inputs.some(h=>h.variable===g)&&n("Input variable requires a component binding","inputBinding",["variables",g]);let l=0,m=0;for(let g of e.screens)if(g.type==="owned"){for(let d of g.document.pages)Wn(d.root,()=>{l++});m+=g.document.actions.length}(l>kn.components||m>kn.actions||pn(e)>kn.documentBytes)&&n("Funnel document exceeds its budget","budget")}var j0=L.z.strictObject({...bu,graph:fu}).superRefine(Qf),Ri=L.z.strictObject({...bu,graph:fu,displayName:L.z.string().trim().min(1).max(80)}).superRefine(Qf),IE=Ri.superRefine(Hf),vE=j0.superRefine(Hf),ns=L.z.string().regex(Nt),vo={requestId:L.z.uuid(),nodeId:Sn,visit:L.z.number().int().nonnegative(),revision:L.z.number().int().nonnegative(),customerToken:ns.optional()},T0=L.z.discriminatedUnion("type",[L.z.strictObject({type:L.z.literal("screen"),output:Sn,answers:lr,selection:L.z.record(Sn,L.z.union([L.z.string().max(200),L.z.boolean(),L.z.number().int().min(0).max(1e4)])).optional()}),L.z.strictObject({type:L.z.literal("paywall_quote"),featureQuantities:L.z.record(L.z.uuid(),L.z.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100).optional(),actionId:Sn,productVersionId:L.z.uuid(),offerId:L.z.uuid().optional(),nativeOffer:bi.optional(),predecessor:L.z.strictObject({operationId:L.z.uuid().nullable(),generation:L.z.number().int().positive()}).optional()}),L.z.strictObject({type:L.z.literal("paywall_confirm"),operationId:L.z.uuid()}),L.z.strictObject({type:L.z.literal("paywall_cancel"),operationId:L.z.uuid()}),L.z.strictObject({type:L.z.literal("client_action"),receiptId:L.z.uuid(),outcome:L.z.enum(["success","cancel","failure","opened","failed"])})]),N0=L.z.object({nodeId:Sn,visit:L.z.number().int().nonnegative(),revision:L.z.number().int().nonnegative(),components:L.z.record(Sn,L.z.object({resourceKey:L.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:L.z.number().int().min(1).max(1e5),after:$a.nullable(),filter:L.z.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),_t=L.z.discriminatedUnion("operation",[L.z.strictObject({operation:L.z.literal("start"),funnelId:L.z.uuid(),requestId:L.z.uuid(),customer:Hr.optional(),customerData:Ci.optional(),locale:L.z.string().min(1).max(35),parameters:dr}).refine(Ya,Xa),L.z.strictObject({operation:L.z.literal("get"),settlementRequestId:L.z.uuid().optional(),data:N0.optional(),purchase:L.z.strictObject({receiptId:L.z.uuid(),operationId:L.z.uuid()}).optional(),customerToken:ns.optional()}),L.z.strictObject({operation:L.z.literal("resume"),requestId:L.z.uuid(),customerToken:ns.optional()}),L.z.strictObject({operation:L.z.literal("submit"),...vo,input:T0}),L.z.strictObject({operation:L.z.literal("back"),...vo}),L.z.strictObject({operation:L.z.literal("shown"),...vo}),L.z.strictObject({operation:L.z.literal("close"),...vo}),L.z.strictObject({operation:L.z.literal("commit_segment"),...vo,policyRevision:L.z.number().int().nonnegative(),generation:L.z.string().min(1).max(256)}),L.z.strictObject({operation:L.z.literal("review"),receiptId:L.z.uuid().optional(),customerToken:ns.optional()})]);function is(e,t){let n=new Set,r=new Set,i=new Set,a=[],o=new Map,s=new Map,c=new Map;function u(d){for(let h of Qn(d))l(h)}function l(d){if(i.has(d)||!Object.hasOwn(t.savedGroups,d))return;let h=t.savedGroups[d];h&&(i.add(d),c.set(d,h),a.push(()=>{!Array.isArray(h)&&h.type==="condition"&&u(h.condition)}))}function m(d){for(let h of["hashAttribute","fallbackAttribute"])if(d[h]!==void 0&&nu(d[h]))throw new Error(`Funnel GB ${h} uses a reserved flow namespace`);u(d.condition);for(let h of d.parentConditions??[])f(h.id),u(h.condition)}function f(d,h=!1){let R=Object.hasOwn(t.features,d)?t.features[d]:void 0;if(!R){if(h)throw new Error("Required GB Feature is unavailable");return}n.has(d)||(n.add(d),o.set(d,R),a.push(()=>{for(let y of R.rules??[]){m(y);for(let A of y.tracks??[])m(A.experiment)}}))}function g(d){let h=Object.hasOwn(t.experiments,d)?t.experiments[d]:void 0;if(!h)throw new Error("Required GB Experiment is unavailable");r.has(d)||(r.add(d),s.set(d,h),a.push(()=>m(h)))}for(let d of e.graph.nodes){d.type==="feature"&&f(d.featureKey,!0),d.type==="split"&&g(d.experimentId),d.type==="condition"&&d.cases.forEach(R=>u(R.condition)),d.type==="offering"&&d.configuration.source==="feature"&&f(d.configuration.featureKey,!0);let h=d.type==="output"?d.value:d.type==="end"?d.output:null;h?.type==="feature"&&f(h.featureKey,!0)}for(let d of a)d();return{...t,features:Object.fromEntries(o),experiments:Object.fromEntries(s),savedGroups:Object.fromEntries(c)}}var ae=require("zod");function Jf(e,t){let n=[],r={};Ht(e,i=>{if(i.hidden)return!1;if(i.type!=="quantity_picker")return;let a=i.bind?.plan?[i.bind.plan]:[];i.bind?.picker&&Ht(e,o=>{if(o.type==="plan_picker"&&o.id===i.bind?.picker&&a.push(...o.planIds??[]),o.type==="stack"&&o.interaction?.type==="select"&&o.interaction.pickerId===i.bind?.picker)for(let s of o.children)s.type==="stack"&&s.bind?.plan&&a.push(s.bind.plan)}),a.length||n.push(`Quantity control ${i.id} needs a Product binding`);for(let o of new Set(a)){let s=t[o]?.prepaid?.find(u=>u.internalFeatureId===i.internalFeatureId)?.terms,c=r[o]??(r[o]=new Set);(!s||c.has(i.internalFeatureId)||i.minimumQuantity<s.minimumQuantity||i.maximumQuantity>s.maximumQuantity)&&n.push(`Quantity control ${i.id} must match its Product's prepaid Feature and bounds`),c.add(i.internalFeatureId)}});for(let[i,a]of Object.entries(t))for(let o of a.prepaid??[])r[i]?.has(o.internalFeatureId)||n.push(`Product ${i} needs a quantity control for ${o.internalFeatureId}`);return n}function Zf(e,t,n,r){let i=r.plans[t];if(!i?.available)throw new Error("Selected Product is unavailable");let a={};if(Ht(e,o=>{if(o.hidden)return!1;if(o.type!=="quantity_picker"||o.hidden||(o.bind?.plan??(o.bind?.picker?n[o.bind.picker]:void 0))!==t)return;let c=i.prepaid?.find(l=>l.internalFeatureId===o.internalFeatureId)?.terms,u=n[o.id];if(!c||typeof u!="number"||!Number.isSafeInteger(u)||u<Math.max(c.minimumQuantity,o.minimumQuantity)||u>Math.min(c.maximumQuantity,o.maximumQuantity)||(u-o.minimumQuantity)%o.step!==0||a[o.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");a[o.internalFeatureId]=u}),(i.prepaid??[]).some(o=>a[o.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return a}var ki=require("zod");var Wf=ki.z.object({defaultLocale:wn,locales:ki.z.record(wn,ki.z.object({name:ki.z.string().max(80),description:ki.z.string().max(500)}).strict())}).strict().superRefine((e,t)=>{let n=Object.keys(e.locales);(!n.length||n.length>20||!e.locales[e.defaultLocale])&&t.addIssue({code:"custom",message:"Invalid content languages"}),new TextEncoder().encode(JSON.stringify(e)).length>5e4&&t.addIssue({code:"custom",message:"Content exceeds 50 KB"})});var D0=["customer_data","coupon_code"],Yf=ae.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),F0=ae.z.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),os=(e,t)=>new Set(e.map(t)).size===e.length,M0=ae.z.strictObject({currency:Ie,amountMinor:ae.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),q0=ae.z.strictObject({featureId:ae.z.uuid(),name:ae.z.string().trim().min(1).max(120),allowance:ae.z.string().max(40).nullable(),access:ae.z.boolean()}),U0=ae.z.strictObject({stripe:ae.z.strictObject({prices:ae.z.array(M0).min(1).max(50)}).optional(),apple:ae.z.strictObject({productIds:ae.z.array(Yf).min(1).max(10)}).optional(),google:ae.z.strictObject({products:ae.z.array(ae.z.strictObject({productId:Yf,basePlanId:F0.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!os(e.stripe.prices,n=>n.currency)||e.apple&&!os(e.apple.productIds,n=>n)||e.google&&!os(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),B0=ae.z.strictObject({name:ae.z.string().trim().min(1).max(80),interval:ae.z.enum(["free","week","month","year","one_time"]),intervalCount:ae.z.number().int().min(1).max(100),trial:ae.z.strictObject({days:ae.z.number().int().min(1).max(730),cardRequired:ae.z.boolean()}).nullable(),benefits:ae.z.array(q0).max(50).refine(e=>os(e,t=>t.featureId),"Duplicate benefit"),channels:U0,prepaid:ae.z.array(ao).max(100).optional()}),V0=ae.z.strictObject({digest:Oi,content:ae.z.strictObject({discount:ir,duration:un,appliesTo:lc,displayCopy:Wf.nullable(),firstPurchaseOnly:ae.z.boolean(),qualificationRequired:ae.z.boolean(),startsAt:ae.z.iso.datetime().nullable(),endsAt:ae.z.iso.datetime().nullable(),grantWindowHours:ae.z.number().int().positive(),perCustomerLimit:ae.z.number().int().positive()})}),L0=ae.z.discriminatedUnion("type",[ae.z.strictObject({type:ae.z.literal("checkout"),product:Oa}),ae.z.strictObject({type:ae.z.literal("close")}),ae.z.strictObject({type:ae.z.literal("action"),action:Gc})]),as=ae.z.strictObject({kind:ae.z.literal("paywall"),formatVersion:ae.z.literal(1),name:ae.z.string().trim().min(1).max(80),offeringVersionId:ae.z.uuid(),presentation:Cn,screen:dn,products:Ba,catalog:ae.z.record(ae.z.uuid(),B0),buttons:ae.z.record(Ue,L0),coupons:ae.z.record(ae.z.uuid(),V0)}).superRefine((e,t)=>{let n=h=>t.addIssue({code:"custom",message:h}),{screen:r}=e;Jf(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),Zc(r,D0).forEach(n),ar(r).some(h=>!h.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,o=new Set;Ht(r,h=>{let R="bind"in h?h.bind:void 0;R?.promotionCode&&n("Promotion codes must not be published"),R?.plan&&i.add(R.plan),R?.coupon&&a.add(R.coupon),h.type==="plan_picker"&&(h.planIds?.forEach(y=>i.add(y)),h.defaultPlan&&i.add(h.defaultPlan)),h.type==="text"&&h.feature&&o.add(h.feature.id)});let s=e.products.items.map(h=>h.productVersionId),c=Object.keys(e.catalog);(s.length!==c.length||s.some(h=>!Object.hasOwn(e.catalog,h)))&&n("Catalog must contain exactly the displayed Products");let u=new Set(s);e.products.defaultProductVersionId!==null&&!u.has(e.products.defaultProductVersionId)&&n("Default Product must be displayed");for(let h of i)u.has(h)||n("Screen references a Product that is not displayed");for(let h of Object.values(e.catalog))!h.channels.stripe&&!h.channels.apple&&!h.channels.google&&n("A displayed Product needs at least one sales channel");let l=new Set(Object.values(e.catalog).flatMap(h=>h.benefits.map(R=>R.featureId)));for(let h of o)l.has(h)||n("Feature text must read a displayed benefit");let m=r.actions.filter(h=>h.type!=="navigate");r.actions.some(h=>h.type!=="event"&&h.type!=="navigate")&&n("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==m.length||m.some(h=>!Object.hasOwn(e.buttons,h.id)))&&n("Buttons must match the screen's actions");let g=!1;for(let h of Object.values(e.buttons)){if(h.type!=="checkout")continue;g=!0,(h.product.type==="fixed"?[h.product.productVersionId]:h.product.allowedProductVersionIds).some(y=>!u.has(y))&&n("Checkout may only sell displayed Products")}g||n("A Paywall needs a checkout button");let d=Object.keys(e.coupons);(d.length!==a.size||d.some(h=>!a.has(h)))&&n("Coupons must be exactly the bound Coupons")}),Xf=ae.z.strictObject({state:ae.z.enum(["published","archived"]),controlRevision:ae.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:ae.z.uuid(),versions:ae.z.record(ae.z.uuid(),ae.z.strictObject({version:ae.z.number().int().positive(),artifact:ae.z.string().min(1),sourceDigest:ae.z.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var nn={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},xu=Re.z.string().regex(/^[a-f0-9]{64}$/),Su=Re.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),vu=Fe.extend({environmentId:Re.z.uuid()}),eg=Re.z.strictObject({features:Re.z.array(Re.z.string()).max(500),experiments:Re.z.record(Re.z.uuid(),Re.z.array(Re.z.string()).max(20)),savedGroups:Re.z.array(Re.z.string()).max(1e3)}),wu=Re.z.strictObject({kind:Re.z.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:Re.z.number().int().positive(),url:Re.z.string().min(1).max(2048),sha256:xu,byteLength:Re.z.number().int().positive().max(nn.maxArtifactBytes),generation:xu.optional()}),z0=Re.z.strictObject({state:Re.z.enum(["active","paused","archived"]),controlRevision:Su,evaluationMode:Re.z.enum(["local","remote"]),evaluationRevision:Su,currentVersionId:Re.z.uuid(),versions:Re.z.record(Re.z.uuid(),Re.z.strictObject({artifact:Re.z.string(),dependencies:eg,definitionDigest:Oi.optional(),couponDigests:Re.z.record(Re.z.uuid(),Oi).optional()}))}),Ou=Re.z.strictObject({kind:Re.z.literal("sdk_configuration"),schemaVersion:Re.z.literal(1),scope:vu,revision:Su,generation:xu,policy:Re.z.strictObject({refreshIntervalSeconds:Re.z.number().positive().max(15),maxControlAgeSeconds:Re.z.number().positive().max(60)}),gb:Re.z.strictObject({features:Re.z.string().nullable(),pageExperiments:Re.z.string().nullable()}),artifacts:Re.z.record(Re.z.string(),wu),funnels:Re.z.record(Re.z.uuid(),z0),paywalls:Re.z.record(Re.z.uuid(),Xf).optional()}).superRefine((e,t)=>{let n=(r,i)=>{r!==null&&e.artifacts[r]?.kind!==i&&t.addIssue({code:"custom",message:"Missing or wrong-kind configuration artifact"})};n(e.gb.features,"gb_features"),n(e.gb.pageExperiments,"gb_page_experiments");for(let r of Object.values(e.paywalls??{}))for(let i of Object.values(r.versions))n(i.artifact,"paywall");for(let r of Object.values(e.funnels)){r.evaluationMode==="remote"&&Object.keys(r.versions).length&&t.addIssue({code:"custom",message:"Remote Funnel graphs cannot be public"}),r.evaluationMode==="local"&&!r.versions[r.currentVersionId]&&t.addIssue({code:"custom",message:"Current Funnel Version is not retained"});for(let i of Object.values(r.versions))n(i.artifact,"funnel")}});function Et(e){if(Array.isArray(e))return`[${e.map(Et).join(",")}]`;if(e!==null&&typeof e=="object")return`{${Object.entries(e).sort(([n],[r])=>n<r?-1:n>r?1:0).map(([n,r])=>`${JSON.stringify(n)}:${Et(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function Pu(e){return ai(si(typeof e=="string"?new TextEncoder().encode(e):e))}function tg(e){return Pu(Et(e))}var Iu=class extends Error{constructor(n,r){super(n);qe(this,"dependency",r)}};function ng(e,t){let n=l=>l.type==="feature"?l.featureKey:l.type==="end"&&l.output?.type==="feature"?l.output.featureKey:l.type==="output"&&l.value.type==="feature"?l.value.featureKey:void 0,r=(l,m)=>e.graph.nodes.find(f=>l==="experiment"?f.type==="split"&&f.experimentId===m:l==="feature"&&n(f)===m)?.name,i=(l,m,f=r(m.type,m.resource))=>new Iu(l,{...m,...f?{step:f}:{}});for(let l of Object.values(e.references)){let m=l.type==="flag"?!Object.hasOwn(t.features,l.key)||t.remoteFeatures.includes(l.key)?{type:"feature",resource:l.key}:null:l.type==="experiment"?Object.hasOwn(t.experiments,l.id)?null:{type:"experiment",resource:l.id}:l.type==="saved_group"&&!Object.hasOwn(t.savedGroups,l.id)?{type:"saved_group",resource:l.id}:null;if(m)throw i("Funnel dependency is absent from GB public delivery",{reason:"unavailable",...m})}let a=is(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),o=new Set(t.remoteFeatures);for(let l of e.graph.nodes){let m=n(l);if(!m)continue;let f=a.features[m],g=l.type==="feature"?e.variables[l.writes.value]:e.outputSchema,d={type:"feature",resource:m};if(!f||!g)throw i("Required public Feature declaration is unavailable",{reason:"unavailable",...d},l.name);if([f.defaultValue,...(f.rules??[]).flatMap(R=>[...Object.hasOwn(R,"force")?[R.force]:[],...R.variations??[],...(R.tracks??[]).flatMap(y=>y.experiment.variations)])].some(R=>R===void 0||!An(g,R)))throw i("GB Feature values violate the Funnel type contract",{reason:"value_type",...d},l.name)}let s=new Set,c=(l,m)=>{for(let f of Qn(l)){if(s.has(f))continue;let g=t.savedGroups[f];if(!g)throw i("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:f},m);s.add(f),!Array.isArray(g)&&g.type==="condition"&&c(g.condition,m)}},u=(l,m)=>{if(o.has(l)||!t.features[l])throw i("Local Funnel requires public Local prerequisites",{reason:"unavailable",type:"feature",resource:l},m)};for(let l of e.graph.nodes)if(l.type==="condition")for(let m of l.cases)c(m.condition,l.name);for(let[l,m]of Object.entries(a.features)){let f=r("feature",l);for(let g of m.rules??[]){c(g.condition,f);for(let d of[...g.parentConditions??[],...(g.tracks??[]).flatMap(h=>h.experiment.parentConditions??[])])u(d.id,f),c(d.condition,f);for(let d of g.tracks??[])c(d.experiment.condition,f)}}for(let[l,m]of Object.entries(a.experiments)){let f=r("experiment",l);c(m.condition,f);for(let g of m.parentConditions??[])u(g.id,f),c(g.condition,f)}for(let l of e.graph.nodes)if(l.type==="split"){let m=a.experiments[l.experimentId],f={type:"experiment",resource:l.experimentId};if(!m)throw i("Local Funnel requires a public Experiment",{reason:"unavailable",...f},l.name);for(let g of m.variations)if(typeof g!="string"||!Object.hasOwn(l.routes,g))throw i("Experiment variation has no declared Funnel route",{reason:"variation_route",...f},l.name)}return eg.parse({features:Object.keys(a.features).sort(),experiments:Object.fromEntries(Object.entries(a.experiments).map(([l,m])=>[l,m.variations.map(String)])),savedGroups:[...s].sort()})}function rg(e){return Ri.parse(e)}var ig=vt.z.strictObject({processContext:Ra.optional(),...Ai,selector:vt.z.discriminatedUnion("type",[vt.z.strictObject({type:vt.z.literal("paywall"),paywallId:vt.z.uuid()}),vt.z.strictObject({type:vt.z.literal("version"),versionId:vt.z.uuid()})]),customerId:vt.z.uuid().optional(),commerce:pi,locale:vt.z.string().min(1).max(35),requirement:or.optional()}),wo=vt.z.strictObject({id:vt.z.uuid(),paywallId:vt.z.uuid(),version:vt.z.number().int().positive(),document:wi.omit({requirement:!0,offeringId:!0}),offering:vt.z.strictObject({id:vt.z.uuid()}),content:vt.z.strictObject({environmentId:vt.z.uuid(),offeringVersionId:vt.z.uuid(),artifact:wu.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:mi,check:qr.nullable()}).superRefine((e,t)=>{let n=new Set(e.document.products.items.map(r=>r.productVersionId));(e.document.offeringVersionId!==e.offering.id||Object.values(e.capabilities.plans).some(r=>!n.has(r.versionId)))&&t.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})}),Jr=vt.z.strictObject(wo.shape).omit({document:!0,offering:!0}).extend({content:wo.shape.content.unwrap()});function og(e,t){let n=as.parse(t);if(n.offeringVersionId!==e.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");let r=structuredClone(e.capabilities);for(let[i,a]of Object.entries(n.catalog)){let o=r.plans[i],s=a.channels.stripe?.prices.find(c=>c.currency===o?.currency);o&&s&&Object.assign(o,{amountMinor:s.amountMinor,interval:a.interval,intervalCount:a.intervalCount,...a.prepaid?.length?{prepaid:a.prepaid}:{}})}return wo.parse({...e,capabilities:r,document:{schemaVersion:3,kind:n.kind,name:n.name,presentation:n.presentation,products:n.products,offeringVersionId:n.offeringVersionId,screen:n.screen,buttons:n.buttons},offering:{id:n.offeringVersionId}})}var zt=require("zod");var ag={requestId:zt.z.uuid(),sourceId:zt.z.uuid(),expectedAvailable:Kt},sg=zt.z.discriminatedUnion("action",[zt.z.strictObject({...ag,action:zt.z.enum(["add","subtract","set_remaining"]),amount:xe}),zt.z.strictObject({...ag,action:zt.z.literal("edit"),granted:xe,expiresAt:zt.z.iso.datetime({offset:!0}).nullable(),nextResetAt:zt.z.iso.datetime({offset:!0}).nullable(),expectedRevision:zt.z.number().int().nonnegative()})]),Cu=zt.z.strictObject({sourceId:zt.z.uuid(),available:Kt,held:Kt,spent:Kt,adjustmentGrantId:zt.z.uuid().nullable()}),cg=Cu.extend({granted:Kt,expiresAt:zt.z.iso.datetime({offset:!0}).nullable(),nextResetAt:zt.z.iso.datetime({offset:!0}).nullable(),revision:zt.z.number().int().nonnegative()});var rn=require("zod"),ug=rn.z.discriminatedUnion("action",[rn.z.object({action:rn.z.literal("upsert"),externalId:rn.z.string().min(1).max(128),name:rn.z.string().trim().min(1).max(80)}).strict(),rn.z.object({action:rn.z.literal("archive"),entityId:rn.z.uuid()}).strict()]),lg=rn.z.object({id:rn.z.uuid(),externalId:rn.z.string().min(1).max(128),name:rn.z.string().min(1).max(80),archived:rn.z.boolean()}).strict();var Ut=require("zod");var pr=require("zod"),pg=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],dg=pr.z.string().regex(/.+\/.+/),_u=pr.z.number().min(-100),Zr=pr.z.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),$0=pr.z.strictObject({input:Zr,output:Zr,cache_read:Zr.optional(),cache_write:Zr.optional(),reasoning:Zr.optional(),input_audio:Zr.optional(),output_audio:Zr.optional()}),Eu=(e,t)=>pr.z.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),gR=pr.z.strictObject({defaultMarkup:_u,providerMarkups:Eu(pr.z.string().min(1),_u),modelMarkups:Eu(dg,_u),customModels:Eu(dg,$0.partial())});var be=require("zod"),Wr=be.z.iso.datetime({offset:!0}),mr=be.z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),G0=be.z.discriminatedUnion("kind",[be.z.object({kind:be.z.literal("absolute"),from:Wr,to:Wr}).strict(),be.z.object({kind:be.z.literal("last_days"),days:be.z.union([be.z.literal(1),be.z.literal(7),be.z.literal(30),be.z.literal(90)])}).strict(),be.z.object({kind:be.z.literal("billing_cycles"),membershipId:be.z.uuid(),count:be.z.number().int().min(1).max(12),includeCurrent:be.z.boolean()}).strict()]),mg=be.z.string().max(100).refine(e=>{if(e!=="UTC"&&!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+\-]+)+$/.test(e))return!1;try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Use an IANA timezone"),K0=be.z.object({key:be.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:be.z.array(be.z.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),Yr=be.z.object({range:G0,timezone:mg,filterBy:be.z.array(K0).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:be.z.enum(["hour","day","week","month"]),internal_feature_id:be.z.uuid().nullable(),entityId:be.z.uuid().nullable(),topN:be.z.number().int().min(1).max(50).nullable(),groupBy:be.z.union([be.z.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),be.z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:be.z.object({bucket:Wr,group:be.z.string().max(240),isOther:be.z.boolean(),internal_feature_id:be.z.uuid(),resourceId:be.z.uuid()}).strict().nullable(),limit:be.z.number().int().min(1).max(100)}).strict().superRefine((e,t)=>{if(e.range.kind!=="absolute"){e.interval==="hour"&&e.range.kind==="last_days"&&e.range.days>31&&t.addIssue({code:"custom",message:"Hourly reports are bounded to 31 days"});return}let n=Date.parse(e.range.to)-Date.parse(e.range.from);(n<=0||n>366*864e5||e.interval==="hour"&&n>31*864e5)&&t.addIssue({code:"custom",message:"Reporting range must be positive and bounded (31 days hourly, 366 days otherwise)"})}),fg=be.z.object({from:Wr,to:Wr,interval:be.z.enum(["hour","day","week","month"]),timezone:mg,rows:be.z.array(be.z.object({bucket:Wr,group:be.z.string().max(240),isOther:be.z.boolean(),internal_feature_id:be.z.uuid(),resourceId:be.z.uuid(),consumedUnits:mr,refundedUnits:mr,reservedUnits:mr,charged:mr,refunded:mr,reserved:mr,netUnits:mr,netCharged:mr}).strict()).max(100),nextCursor:be.z.object({bucket:Wr,group:be.z.string().max(240),isOther:be.z.boolean(),internal_feature_id:be.z.uuid(),resourceId:be.z.uuid()}).strict().nullable()}).strict();var ji=Ut.z.string().regex(/^(0|[1-9]\d{0,29})$/),gg=Ut.z.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),Ru=Ut.z.strictObject({bucket:Ut.z.iso.datetime({offset:!0}),group:Ut.z.string().max(240),isOther:Ut.z.boolean(),internal_feature_id:Ut.z.uuid()}),hg=Ut.z.strictObject({...Yr.shape,groupBy:Ut.z.union([Ut.z.enum(["customer","entity","entitlement"]),Ut.z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Ru.nullable()}).superRefine((e,t)=>{let n=Yr.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),yg=Ut.z.strictObject({from:Ut.z.iso.datetime({offset:!0}),to:Ut.z.iso.datetime({offset:!0}),interval:Yr.shape.interval,timezone:Yr.shape.timezone,rows:Ut.z.array(Ut.z.strictObject({...Ru.shape,eventCount:ji,units:gg,tokenEventCount:ji,tokens:Ut.z.strictObject(Object.fromEntries(pg.map(e=>[e,ji]))),totalTokens:ji,providerCostEventCount:ji,providerCostUsd:gg,invalidTelemetryEventCount:ji})).max(100),nextCursor:Ru.nullable()});var gt=require("zod");var Ag=gt.z.object({requestId:gt.z.uuid(),items:gt.z.array(gt.z.object({customerId:gt.z.uuid(),command:eo.options[1]}).strict()).min(1).max(1e3)}).strict().refine(e=>new Set(e.items.map(t=>t.customerId+":"+t.command.idempotencyKey)).size===e.items.length,"Each logical event must appear once in a batch"),bg=gt.z.object({batchId:gt.z.uuid(),after:gt.z.number().int().min(-1).max(999),limit:gt.z.number().int().min(1).max(100)}).strict(),xg=gt.z.object({batchId:gt.z.uuid(),status:gt.z.enum(["queued","complete"]),total:gt.z.number().int().min(1).max(1e3),processed:gt.z.number().int().min(0).max(1e3),items:gt.z.array(gt.z.object({position:gt.z.number().int().min(0).max(999),customerId:gt.z.uuid(),idempotencyKey:gt.z.string().min(1).max(120),status:gt.z.enum(["queued","accepted","rejected","failed"]),receipt:to.nullable(),errorCode:gt.z.enum(["invalid_request","forbidden","conflict","internal_error"]).nullable()}).strict().refine(e=>e.status==="queued"?e.receipt===null&&e.errorCode===null:e.status==="failed"?e.receipt===null&&e.errorCode!==null:e.receipt!==null&&e.errorCode===null&&e.receipt.accepted===(e.status==="accepted"))).max(100),nextAfter:gt.z.number().int().min(0).max(999).nullable()}).strict();var k=require("zod");var H0=k.z.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),Sg=k.z.enum(["draft","active","paused","archived"]),Ig=k.z.string().min(1).max(256),vg=k.z.array(Ig).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),Q0=k.z.strictObject({duration:k.z.enum(["day","week","month","year"]),length:k.z.number().int().min(1).max(3660)}),J0=k.z.strictObject({internal_feature_id:k.z.uuid(),allowance:k.z.number().nonnegative().max(1e15).nullable(),expiry:Q0.nullable()}),Z0=k.z.discriminatedUnion("type",[k.z.strictObject({type:k.z.literal("feature_grant"),grants:k.z.array(J0).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),k.z.strictObject({type:k.z.literal("free_product"),productId:Ig,duration:un}),k.z.strictObject({type:k.z.literal("invoice_credits"),amount:k.z.number().positive().max(1e8),duration:un,rollover:k.z.boolean(),productIds:vg})]),W0=k.z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),wg=k.z.object({key:W0,name:k.z.string().trim().min(1).max(80),configuration:Z0}).strict(),Og=k.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),ku=k.z.object({code:Og,maxUses:k.z.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:k.z.boolean()}).strict(),Pg=k.z.object({key:k.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:k.z.string().trim().min(1).max(80),rewardId:k.z.uuid(),redeemOn:k.z.enum(["customer_creation","checkout"]),receivedBy:k.z.enum(["referrer","all"]),maxRedemptions:k.z.number().int().min(1).max(1e6).nullable(),productIds:vg,excludeTrial:k.z.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),Cg={id:k.z.uuid(),projectId:k.z.uuid(),environmentId:k.z.uuid(),revision:k.z.number().int().nonnegative(),status:Sg,createdAt:k.z.iso.datetime({offset:!0}),updatedAt:k.z.iso.datetime({offset:!0})},Y0=wg.extend(Cg).strict(),X0=Pg.safeExtend(Cg).strict(),OR=k.z.strictObject({id:k.z.uuid(),key:k.z.string(),name:k.z.string(),type:H0,status:Sg}),PR=k.z.discriminatedUnion("action",[k.z.object({action:k.z.literal("save"),id:k.z.uuid().nullable(),revision:k.z.number().int().nonnegative(),input:wg}).strict(),k.z.object({action:k.z.enum(["activate","pause","resume","archive","delete"]),id:k.z.uuid(),revision:k.z.number().int().nonnegative()}).strict()]),CR=k.z.discriminatedUnion("action",[k.z.object({action:k.z.literal("save"),id:k.z.uuid().nullable(),revision:k.z.number().int().nonnegative(),input:Pg}).strict(),k.z.object({action:k.z.enum(["activate","pause","resume","archive","delete"]),id:k.z.uuid(),revision:k.z.number().int().nonnegative()}).strict()]),_g=k.z.object({id:k.z.uuid(),rewardId:k.z.uuid(),programId:k.z.uuid().nullable(),customerId:k.z.uuid(),referrerId:k.z.uuid().nullable(),status:k.z.enum(["pending","applied","unavailable"]),result:k.z.record(k.z.string(),k.z.unknown()).nullable(),createdAt:k.z.iso.datetime({offset:!0})}).strict(),Eg=k.z.object({code:Og,requestId:k.z.uuid()}).strict(),Rg=k.z.strictObject({redemptionId:k.z.uuid(),currency:Ie,requestId:k.z.uuid(),accepted:k.z.literal(!0)}),eI=k.z.strictObject({type:k.z.literal("checkout"),orderId:k.z.uuid(),productVersionId:k.z.uuid(),currency:Ie,duration:un,renewalAmountMinor:k.z.number().int().positive().max(1e8),status:k.z.enum(["created","pending","trialing","paid","cancelled","failed"]),url:k.z.url().nullable()}),kg=k.z.discriminatedUnion("type",[eI,k.z.strictObject({type:k.z.literal("subscription"),operationId:k.z.uuid(),membershipId:k.z.uuid(),productVersionId:k.z.uuid(),currency:Ie,duration:un,renewalAmountMinor:k.z.number().int().positive().max(1e8),status:k.z.enum(["pending","running","applied","failed"])})]),jg=k.z.object({programId:k.z.uuid(),requestId:k.z.uuid()}).strict(),Tg=k.z.object({id:k.z.uuid(),programId:k.z.uuid(),code:ku.shape.code,createdAt:k.z.iso.datetime({offset:!0})}).strict(),_R=k.z.object({rows:k.z.array(Y0).max(100),nextCursor:k.z.uuid().nullable()}).strict(),ER=k.z.object({rows:k.z.array(X0).max(100),nextCursor:k.z.uuid().nullable()}).strict(),tI=ku.extend({id:k.z.uuid(),redemptions:k.z.number().int().nonnegative()}).strict(),nI=k.z.strictObject({id:k.z.uuid(),programId:k.z.uuid().nullable(),customerId:k.z.uuid().nullable(),referrerId:k.z.uuid().nullable(),code:k.z.string().nullable(),status:k.z.enum(["pending","triggered","applied"]),createdAt:k.z.iso.datetime({offset:!0})}),RR=k.z.object({codes:k.z.array(tI).max(100),redemptions:k.z.array(nI).max(100),customers:k.z.record(k.z.uuid(),k.z.string()),codesCursor:k.z.uuid().nullable(),redemptionsCursor:k.z.uuid().nullable()}).strict(),kR=k.z.discriminatedUnion("action",[k.z.object({action:k.z.literal("create"),rewardId:k.z.uuid(),revision:k.z.number().int().nonnegative(),input:ku}).strict(),k.z.object({action:k.z.literal("remove"),rewardId:k.z.uuid(),revision:k.z.number().int().nonnegative(),codeId:k.z.uuid()}).strict()]);var w=require("zod");var Z=require("zod"),qn={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},Oo=e=>new Set(e).size===e.length,ju=Z.z.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),rI=Z.z.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),Po=Z.z.string().min(1).max(200).regex(/^[a-zA-Z0-9_./-]+$/).refine(e=>!e.includes("..")&&!e.endsWith(".")&&!e.split("/").some(t=>!t||t.startsWith(".")||t.endsWith(".lock"))),iI=Z.z.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),Ng=Z.z.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var Dg=Z.z.strictObject({id:Z.z.uuid(),repo:rI,platform:Z.z.enum(["github","gitlab","bitbucket"]),branches:Z.z.array(Po).min(1).max(4).refine(Oo),workflow:Z.z.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:Z.z.array(Z.z.uuid()).min(1).max(4).refine(Oo),include:Z.z.array(Ng).min(1).max(16),exclude:Z.z.array(Ng).max(16),methods:Z.z.array(Z.z.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(Oo),maxAgeHours:Z.z.number().int().min(1).max(720)}),Fg=Dg.extend({revision:Z.z.number().int().positive()}),TR=Z.z.strictObject({repository:Dg,expectedRevision:Z.z.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),Mg=Z.z.strictObject({repositoryId:Z.z.uuid(),branch:Po}),oI=Z.z.array(ju).max(qn.keys).refine(Oo),qg=Z.z.strictObject({repository:Fg.omit({keyIds:!0}),branch:Po,keys:oI,keySetHash:Z.z.string().regex(/^[a-f0-9]{64}$/)}),aI=Z.z.strictObject({filePath:iI,startingLineNumber:Z.z.number().int().min(1).max(1e7)}),Tu=Z.z.strictObject({protocol:Z.z.literal(1),repositoryId:Z.z.uuid(),branch:Po,workflow:Z.z.string().max(200),configurationRevision:Z.z.number().int().positive(),keySetHash:Z.z.string().regex(/^[a-f0-9]{64}$/),commit:Z.z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:Z.z.uuid(),runNumber:Z.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:Z.z.number().int().min(1).max(1e4),scannerVersion:Z.z.literal("1"),scannedAt:Z.z.iso.datetime({offset:!0}),coverage:Z.z.strictObject({complete:Z.z.literal(!0),files:Z.z.number().int().min(0).max(qn.files),sourceBytes:Z.z.number().int().min(0).max(qn.sourceBytes),unresolvedCalls:Z.z.number().int().min(0).max(1e6),unsupportedFiles:Z.z.number().int().min(0).max(qn.files)}),features:Z.z.array(Z.z.strictObject({key:ju,refs:Z.z.array(aI).max(qn.referencesPerKey)})).max(qn.keys)}).superRefine((e,t)=>{Oo(e.features.map(n=>n.key))||t.addIssue({code:"custom",path:["features"],message:"Duplicate feature"}),e.features.reduce((n,r)=>n+r.refs.length,0)>qn.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),Nu=Z.z.strictObject({scanId:Z.z.uuid(),commit:Z.z.string(),receivedAt:Z.z.string(),references:Z.z.number().int().nonnegative(),removedReferences:Z.z.number().int().nonnegative()}),sI=Nu.extend({repositoryId:Z.z.uuid(),branch:Po,workflow:Z.z.string(),digest:Z.z.string(),configurationRevision:Z.z.number().int().positive(),runNumber:Z.z.number().int().positive(),runAttempt:Z.z.number().int().positive(),scannedAt:Z.z.string(),keySetHash:Z.z.string(),coverage:Tu.shape.coverage}),cI=Z.z.strictObject({repositories:Z.z.array(Fg).max(qn.repositories),scans:Z.z.array(sI).max(qn.repositories*qn.branches)}),uI=Z.z.strictObject({key:ju,references:Z.z.number().int().nonnegative(),coveredTargets:Z.z.number().int().nonnegative(),expiredTargets:Z.z.number().int().nonnegative(),uncertainTargets:Z.z.number().int().nonnegative()}),NR=Z.z.strictObject({available:Z.z.boolean().default(!0),settings:cI,expectedTargets:Z.z.number().int().min(0).max(80),features:Z.z.array(uI).max(2001),truncated:Z.z.boolean()});var Ee=require("zod");var on=Ee.z.string().min(1).max(200),ss=Ee.z.iso.datetime({offset:!0}),Co=Ee.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),Du=Ee.z.number().int().min(0).max(1e12),Vg=Ee.z.number().int().min(1).max(1e12),Ug={...Zt,type:Ee.z.literal("coupon.redeemed"),grantId:Ee.z.uuid()},Bg={...Zt,type:Ee.z.literal("usage.observed"),merchantTransactionId:on,resource:on,unit:on,quantity:Vg},lI=Ee.z.strictObject({...Zt,type:Ee.z.literal("fulfillment.updated"),operationId:Ee.z.uuid(),merchantFulfillmentId:on,status:Ee.z.enum(["pending","applied","failed"])}),dI=Ee.z.strictObject({...Zt,type:Ee.z.literal("benefit.claimed"),merchantBenefitId:on,resource:on,unit:on,quantity:Vg,expiresAt:ss.nullable(),revision:Co}),pI=Ee.z.strictObject({...Zt,type:Ee.z.literal("benefit.closed"),merchantBenefitId:on,status:Ee.z.enum(["failed","expired","canceled"]),revision:Co}),mI=Ee.z.strictObject({...Zt,type:Ee.z.literal("benefit.updated"),merchantBenefitId:on,status:Ee.z.enum(["active","expired","revoked"]),remainingQuantity:Du.nullable(),expiresAt:ss.nullable(),revision:Co}),fI=Ee.z.strictObject({...Zt,type:Ee.z.literal("authorization.updated"),merchantAuthorizationId:on,kind:Ee.z.literal("auto_topup"),status:Ee.z.enum(["pending","effective","revoked","failed"]),termsReference:on.nullable(),revision:Co}),gI=Ee.z.strictObject({...Zt,type:Ee.z.literal("balance.observed"),resource:on,unit:on,availableQuantity:Du,reservedQuantity:Du,periodStartsAt:ss.nullable(),periodEndsAt:ss.nullable(),revision:Co}),Lg=Ee.z.union([Ee.z.discriminatedUnion("type",[...Bl,lI,dI,pI,mI,fI,gI]),Ee.z.strictObject({...Ug,productVersionId:Ee.z.uuid(),subscriptionId:Ee.z.string().trim().min(1).max(255)}),Ee.z.strictObject({...Ug,merchandiseId:Ee.z.uuid()}),Ee.z.strictObject({...Bg,operation:Ee.z.literal("consume")}),Ee.z.strictObject({...Bg,operation:Ee.z.literal("reverse"),reversalOf:on})]),zg=Ee.z.strictObject({id:Ee.z.uuid(),eventId:Ee.z.string().min(1).max(200),source:Ee.z.literal("merchant"),providerVerified:Ee.z.literal(!1),outcome:Ee.z.string().min(1).max(100)});var oe=require("zod");var $g=Am,hI=$g.extend({invoice_id:$g.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),Fu=oe.z.strictObject({name:oe.z.string().trim().min(1).max(255),memo:oe.z.string().max(1e4).nullable().optional(),footer:oe.z.string().max(1e4).nullable().optional(),net_terms_days:oe.z.number().int().positive().nullable().optional()}),yI=Fu.extend({id:oe.z.string().min(1).max(255),created_at:oe.z.number().nullable()}),Gg=oe.z.strictObject({items:oe.z.array(yI).max(50),nextCursor:oe.z.uuid().nullable()}),UR=oe.z.discriminatedUnion("action",[oe.z.strictObject({action:oe.z.literal("create"),requestId:oe.z.uuid(),values:Fu}),oe.z.strictObject({action:oe.z.literal("update"),id:oe.z.string().min(1).max(255),values:Fu}),oe.z.strictObject({action:oe.z.literal("delete"),id:oe.z.string().min(1).max(255)})]),Kg=oe.z.discriminatedUnion("action",[oe.z.strictObject({action:oe.z.literal("create"),requestId:oe.z.uuid(),params:xi}),oe.z.strictObject({action:oe.z.enum(["finalize","send","pay","void"]),requestId:oe.z.uuid(),invoiceId:oe.z.uuid()}),oe.z.strictObject({action:oe.z.literal("reissue"),requestId:oe.z.uuid(),invoiceId:oe.z.uuid(),params:hI})]),Mu=oe.z.strictObject({id:oe.z.uuid(),customerId:oe.z.uuid(),providerInvoiceId:oe.z.string().nullable(),status:oe.z.enum(["draft","open","paid","void","uncollectible"]),currency:oe.z.string(),totalMinor:oe.z.string().regex(/^-?\d+$/),paidMinor:oe.z.string().regex(/^\d+$/),refundedMinor:oe.z.string().regex(/^\d+$/),hostedInvoiceUrl:oe.z.url().nullable(),createdAt:oe.z.number(),collectionMethod:oe.z.enum(["send_invoice","charge_automatically"]).nullable()}),Hg=Mu.extend({lines:oe.z.array(oe.z.strictObject({id:oe.z.uuid(),description:oe.z.string(),amountMinor:oe.z.string().regex(/^-?\d+$/),netAmountMinor:oe.z.string().regex(/^-?\d+$/),quantity:oe.z.number().nullable(),periodStart:oe.z.number().nullable(),periodEnd:oe.z.number().nullable()})).max(1e3)}),Ti=oe.z.strictObject({taskId:oe.z.uuid(),status:oe.z.enum(["ready","running","done","dead"]),invoice:Mu.nullable(),errorCode:oe.z.string().nullable()}),Qg=oe.z.strictObject({items:oe.z.array(Mu).max(50),nextCursor:oe.z.uuid().nullable(),operations:oe.z.array(Ti).max(50),operationsLimited:oe.z.boolean()});var AI=w.z.enum(["customers:read","customers:write","entitlements:read","content:read","sessions:create","funnels:run","offers:resolve","offers:grant","billing:read","billing:write","credits:read","credits:consume","credits:manage","features:read","events:write","messaging:write","code-references:read","code-references:write","app-manifests:write"]),Jg={scope:Fe,permissions:w.z.array(AI),expiresAt:w.z.iso.datetime().nullable()},Ek=w.z.discriminatedUnion("kind",[w.z.object({...Jg,kind:w.z.literal("server"),keyId:w.z.string().min(1)}),w.z.object({...Jg,kind:w.z.literal("customer"),customerId:w.z.string().min(1),identityKind:w.z.enum(["identified","guest"]),expiresAt:w.z.iso.datetime()})]),z=w.z.object({requestId:w.z.uuid(),scope:Fe}).strict(),bI=Df.safeExtend({fingerprint:Wa.optional()}).strict(),xI=z.extend({customer:_i,created:w.z.boolean()});function Zg(){return z.extend({offer:Qi.nullable(),reason:Kd.nullable()})}var O={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:Fp,response:z.extend({message:w.z.object({messageId:w.z.uuid(),channel:oo,acceptedAt:w.z.iso.datetime({offset:!0}),status:w.z.enum(["accepted","sending","completed","canceled"]),replayed:w.z.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:w.z.strictObject({messageId:w.z.uuid()}),response:z.extend({message:w.z.object({id:w.z.uuid(),channel:oo,status:w.z.enum(["accepted","sending","completed","canceled"]),deliveries:w.z.array(w.z.object({id:w.z.uuid(),status:qp,attempts:w.z.number().int().nonnegative(),receipts:w.z.array(w.z.object({kind:Up,occurredAt:w.z.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:vl,response:z.extend({installation:Pr})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:wl,response:z.extend({installation:Pr})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:zo,response:z.extend({installation:Pr})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:w.z.strictObject({channel:oo}),response:z.extend({preference:Rs})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:Mp,response:z.extend({preference:Rs})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:w.z.strictObject({cursor:w.z.uuid().optional()}),response:z.extend({templates:Gg})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),params:xi}),response:z.extend({preview:Dc})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),requestId:w.z.uuid(),params:xi}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:z.extend({operation:Ti})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),command:Kg}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:z.extend({operation:Ti})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),taskId:w.z.uuid()}),response:z.extend({operation:Ti})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),cursor:w.z.uuid().optional()}),response:z.extend({invoices:Qg})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),invoiceId:w.z.uuid()}),response:z.extend({invoice:Hg})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:Mg,response:z.extend({config:qg})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:Tu,response:z.extend({receipt:Nu})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:w.z.strictObject({}),response:z.extend({payload:bo})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:lf,response:z.merge(Va)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:df,response:z.merge(pf)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),sourceId:w.z.uuid()}),response:z.extend({balance:cg})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),command:sg}),response:z.extend({balance:Cu})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:w.z.strictObject({internal_feature_id:w.z.uuid(),customerId:w.z.uuid().optional(),entityId:w.z.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:z.extend({internal_feature_id:w.z.uuid(),config:Gs,model_markups:ea})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),query:ba}),response:z.extend({usage:no})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),command:Cp}),response:z.extend({usage:no})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),command:Sp}),response:z.extend({grant:fc})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:Ip,response:z.extend({grants:vp})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:w.z.union(Wm.options.map(e=>e.extend({customerId:w.z.uuid().optional(),customerToken:w.z.string().regex(Nt).optional()}))),response:z.extend({operation:Ym})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:Bm.extend({customerId:w.z.uuid().optional()}),response:z.extend({setup:Bc})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Vm.extend({customerId:w.z.uuid().optional()}),response:z.extend({setup:Bc})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:Mm.safeExtend({customerId:w.z.uuid()}),response:z.extend({batch:fo})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:Da.extend({customerId:w.z.uuid()}),response:z.extend({batch:fo})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:Da.extend({customerId:w.z.uuid()}),response:z.extend({batch:fo})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:Da.extend({customerId:w.z.uuid()}),response:z.extend({batch:fo})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:w.z.discriminatedUnion("action",[Fa.options[0].extend({customerId:w.z.uuid()}),Fa.options[1].extend({customerId:w.z.uuid()}),Fa.options[2].extend({customerId:w.z.uuid()})]),response:z.extend({trial:Uc})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:qm.extend({customerId:w.z.uuid()}),response:z.extend({trial:Uc})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:Ua,response:z.extend({subscriptions:Qm})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:Ua,response:z.extend({purchases:Jm})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:Gm,response:z.extend({conflicts:Zm})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:Km,response:z.extend({resolution:Hm})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:zm,response:z.extend({verification:$m})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:Em.safeExtend({...Ai,customerId:w.z.uuid().optional()}),response:z.extend({quote:Si})},recordMerchantEvent:{method:"POST",path:"merchant/events/record",permission:"billing:write",audience:"server",request:Lg,response:z.extend({record:zg})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:$r.extend({customerId:w.z.uuid().optional(),intent:w.z.enum(["confirm","cancel"]).optional()}),response:z.extend({operation:Ii})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:$r.extend({customerId:w.z.uuid().optional()}),response:z.extend({operation:Ii})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:jm.safeExtend({customerId:w.z.uuid().optional()}),response:z.extend({quote:Nm})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:$r.extend({customerId:w.z.uuid().optional(),intent:w.z.enum(["confirm","cancel"]).optional()}),response:z.extend({operation:Fc})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:$r.extend({customerId:w.z.uuid().optional()}),response:z.extend({operation:Fc})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:Dm.safeExtend({customerId:w.z.uuid()}),response:z.extend({quote:Mc})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:$r.extend({customerId:w.z.uuid()}),response:z.extend({operation:Na})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:$r.extend({customerId:w.z.uuid()}),response:z.extend({operation:Na})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:ap,response:z.extend({controls:pc})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:Xd,response:z.extend({prepared:tp})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:np,response:z.extend({authorization:ga})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:dp,response:z.extend({coupons:pp})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:rp,response:z.extend({authorization:ga})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:up,response:z.extend({invoices:lp})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:cp.extend({customerId:w.z.uuid()}),response:z.extend({operation:Ti})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:sp,response:z.extend({invoice:Wi})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:w.z.object({customerId:w.z.uuid(),command:op}).strict(),response:z.extend({controls:pc})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:w.z.object({customerId:w.z.uuid(),command:ug}).strict(),response:z.extend({entity:lg})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:w.z.strictObject({customerId:w.z.uuid().nullable(),query:hg}),response:z.extend({analytics:yg})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:w.z.object({customerId:w.z.uuid().nullable(),query:Yr}).strict(),response:z.extend({analytics:fg})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:Ag,response:z.extend({batchId:w.z.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:bg,response:z.extend({batch:xg})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:zp.extend({customerId:w.z.string().min(1).optional()}),response:z.extend({check:qr})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:w.z.strictObject({kind:cr,selector:w.z.discriminatedUnion("type",[w.z.strictObject({type:w.z.literal("resource"),id:w.z.uuid()}),w.z.strictObject({type:w.z.literal("version"),id:w.z.uuid()})]),customerId:w.z.string().min(1).optional()}),response:z.extend({content:jc})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:ig,response:z.extend({paywall:Jr})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:w.z.strictObject({processContext:Ra.optional(),...Ai,selector:nf,customerId:w.z.string().min(1).optional(),commerce:pi,requirement:or.optional()}),response:z.extend({offering:rf,candidates:w.z.array(bc).max(20),availability:w.z.array(w.z.strictObject({productVersionId:w.z.uuid(),available:w.z.boolean(),reason:w.z.enum(["platform_binding_missing","commercial_runtime_pending","commerce_not_configured","currency_mismatch","product_unavailable","already_attached","attach_in_progress","already_scheduled","subscription_change_required","purchase_conflict"]).nullable()})).max(20),check:qr.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:w.z.object({customerId:w.z.uuid().optional(),entityId:w.z.uuid().optional()}).strict(),response:z.extend({holdings:_p})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:w.z.object({customerId:w.z.uuid().optional(),query:Rp}).strict(),response:z.extend({ledger:kp})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:wp.extend({customerId:w.z.uuid().optional()}),response:z.extend({detail:Op})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:gc.safeExtend({customerId:w.z.uuid().optional()}),response:z.extend({statement:Pp})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:w.z.object({customerId:w.z.uuid().optional(),command:eo.options[0]}).strict(),response:z.extend({quote:Ap})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),command:w.z.union([w.z.strictObject({eventName:w.z.string().min(1),quantity:xe.optional(),properties:Pt.optional(),entityId:w.z.uuid().optional(),idempotencyKey:w.z.string().min(1).max(120)}),w.z.strictObject({internal_feature_id:w.z.uuid(),quantity:xe.optional(),properties:Pt.optional(),entityId:w.z.uuid().optional(),idempotencyKey:w.z.string().min(1).max(120)})])}),response:z.extend({receipts:w.z.array(to).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:w.z.object({customerId:w.z.uuid(),command:eo.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:z.extend({receipt:to})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:Eg,response:z.extend({redemption:_g})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:jg,response:z.extend({referralCode:Tg})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:Rg,response:z.extend({checkout:kg})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:Tp,response:z.extend({seats:Ac})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Np,response:z.extend({seats:Ac})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:bI,response:xI},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:lu,response:z.extend({customer:_i})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:qf,response:z.extend(Uf.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:Mf,response:z.extend(Ff.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:w.z.object({customerId:w.z.uuid()}).strict(),response:z.extend(Xn.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:w.z.strictObject({}),response:z.extend(Xn.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:w.z.strictObject({customerId:w.z.uuid(),sessionId:w.z.uuid().optional()}),response:z.extend({revoked:w.z.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:w.z.strictObject({guestToken:w.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:Wa.optional()}),response:z.extend({customerId:w.z.uuid(),guestToken:w.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:w.z.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:w.z.strictObject({guestToken:w.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:z.extend(Xn.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:w.z.strictObject({guestToken:w.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:w.z.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:w.z.uuid()}),response:z.extend({customer:_i,switched:w.z.boolean(),replayed:w.z.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:w.z.strictObject({code:w.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:w.z.uuid()}),response:Zg()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:w.z.object({}).strict(),response:z.extend({offers:w.z.array(Qi)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:w.z.object({customerId:w.z.string().min(1).max(255).optional(),couponId:w.z.uuid(),...Ai,requestId:w.z.uuid(),couponContentDigest:w.z.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:Zg()}},Rk={recordMerchantEvent:O.recordMerchantEvent,sendMessage:O.sendMessage,readMessage:O.readMessage,bindPushInstallation:O.bindPushInstallation,readPushInstallation:O.readPushInstallation,updatePushAddress:O.updatePushAddress,readMessagingPreference:O.readMessagingPreference,setMessagingPreference:O.setMessagingPreference,listInvoiceTemplates:O.listInvoiceTemplates,previewInvoice:O.previewInvoice,createInvoice:O.createInvoice,manageInvoice:O.manageInvoice,readInvoiceOperation:O.readInvoiceOperation,listInvoices:O.listInvoices,getInvoice:O.getInvoice,getCodeReferenceConfig:O.getCodeReferenceConfig,submitCodeReferences:O.submitCodeReferences,getFeatures:O.getFeatures,evaluateFeatures:O.evaluateFeatures,trackEvents:O.trackEvents,setupPayment:O.setupPayment,readPaymentSetup:O.readPaymentSetup,previewSubscriptionBatch:O.previewSubscriptionBatch,confirmSubscriptionBatch:O.confirmSubscriptionBatch,readSubscriptionBatch:O.readSubscriptionBatch,abandonSubscriptionBatch:O.abandonSubscriptionBatch,manageSubscriptionTrial:O.manageSubscriptionTrial,readSubscriptionTrial:O.readSubscriptionTrial,listSubscriptions:O.listSubscriptions,listPurchases:O.listPurchases,listSubscriptionConflicts:O.listSubscriptionConflicts,retrySubscriptionConflict:O.retrySubscriptionConflict,readAiPricing:O.readAiPricing,readUsage:O.readUsage,setUsage:O.setUsage,previewRefund:O.previewRefund,refund:O.refund,readRefund:O.readRefund,previewUpdate:O.previewUpdate,update:O.update,readSubscriptionUpdate:O.readSubscriptionUpdate,restoreNativePurchase:O.restoreNativePurchase,verifySubscriptions:O.verifySubscriptions,previewAttach:O.previewAttach,attach:O.attach,readSubscriptionOperation:O.readSubscriptionOperation,manageBalanceGrant:O.manageBalanceGrant,readBalanceSource:O.readBalanceSource,adjustBalance:O.adjustBalance,listBalanceGrants:O.listBalanceGrants,readBillingControls:O.readBillingControls,prepareBillingAuthorization:O.prepareBillingAuthorization,confirmBillingAuthorization:O.confirmBillingAuthorization,setBillingCoupons:O.setBillingCoupons,revokeBillingAuthorization:O.revokeBillingAuthorization,listBillingInvoices:O.listBillingInvoices,confirmBillingAdjustment:O.confirmBillingAdjustment,prepareBillingAdjustment:O.prepareBillingAdjustment,manageBillingLimits:O.manageBillingLimits,createCustomer:O.createCustomer,getCustomer:O.getCustomer,listCustomers:O.listCustomers,updateCustomer:O.updateCustomer,createSession:O.createSession,refreshSession:O.refreshSession,revokeSessions:O.revokeSessions,createGuestCustomer:O.createGuestCustomer,resumeGuestSession:O.resumeGuestSession,claimGuestCustomer:O.claimGuestCustomer,checkEntitlement:O.checkEntitlement,resolveOffering:O.resolveOffering,resolveContent:O.resolveContent,resolvePaywall:O.resolvePaywall,readHoldings:O.readHoldings,readLedger:O.readLedger,readBillingInvoice:O.readBillingInvoice,readCreditStatement:O.readCreditStatement,quoteBalance:O.quoteBalance,trackUsage:O.trackUsage,mutateBalance:O.mutateBalance,manageUsageEntity:O.manageUsageEntity,readUsageAnalytics:O.readUsageAnalytics,readCreditAnalytics:O.readCreditAnalytics,submitUsageBatch:O.submitUsageBatch,readUsageBatch:O.readUsageBatch,listOffers:O.listOffers,grantOffer:O.grantOffer,redeemCoupon:O.redeemCoupon,redeemReward:O.redeemReward,createReferralCode:O.createReferralCode,claimRewardProduct:O.claimRewardProduct,readSeats:O.readSeats,manageSeat:O.manageSeat};var cs=require("zod");var _o=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function qu(e,t,n){let r={},i,a,o,s="next",c;switch(e.type){case"entry":c=e.next;break;case"condition":{let u=e.cases.findIndex(l=>en(t.attributes??{},l.condition,t.savedGroups??{}));s=u<0?"default":`case:${u}`,c=u<0?e.default:e.cases[u].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new _o("Required GB Feature is unavailable");i=Hn(e.featureKey,t),o=i.value,Object.assign(r,yi(e,{value:o})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new _o("Required GB Experiment is unavailable");if(a=ma(u,t),o=a.value,s=a.inExperiment&&!a.passthrough&&typeof o=="string"?o:"notParticipating",c=s==="notParticipating"?e.notParticipating:e.routes[s],!c)throw new _o("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:Hn(e.configuration.featureKey,t).value;o={type:"offering_version",id:cs.z.uuid().parse(u)},Object.assign(r,yi(e,{value:o})),c=e.next;break}case"coupon":case"coupons":o=e.type==="coupons"?e.couponIds.map(u=>({type:"reward",id:u})):{type:"reward",id:e.couponId},Object.assign(r,yi(e,{value:o})),c=e.next;break}return{port:s,target:c,projections:r,...o===void 0?{}:{value:o},...i?{feature:i}:{},...a?{experiment:a}:{}}}function Wg(e,t,n){cs.z.uuid().parse(e),cs.z.number().int().nonnegative().parse(t);let r=ai(si(new TextEncoder().encode(JSON.stringify([e,t,n])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}var H=require("zod");var fr=H.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),SI=H.z.enum(["running","waiting","completed","closed","ineligible","failed"]),Uu=H.z.discriminatedUnion("type",[cu,H.z.strictObject({type:H.z.literal("wait"),receiptId:H.z.uuid(),kind:H.z.enum(["timer","event","operation"]),deadline:H.z.iso.datetime({offset:!0}).nullable(),eventName:fr.optional()}),H.z.strictObject({type:H.z.literal("open_url"),receiptId:H.z.uuid(),url:du,openIn:pu}),H.z.strictObject({type:H.z.literal("event"),receiptId:H.z.uuid(),event:fr})]),us=H.z.strictObject({type:H.z.literal("funnel"),id:H.z.uuid(),versionId:H.z.uuid()}),II={id:fr,presentation:Cn,outputs:H.z.array(fr).max(250),inputs:Ga,values:H.z.record(H.z.string(),ve).optional(),offeringKey:It.optional(),capabilities:mi,customerData:Zp,dataCursors:H.z.record(fr,$a.nullable())},vI=H.z.strictObject({...II,content:H.z.strictObject({type:H.z.literal("document"),document:dn})}),Eo=H.z.strictObject({id:H.z.uuid(),source:us,revision:H.z.number().int().nonnegative(),visit:H.z.number().int().nonnegative(),nodeId:fr,nodeType:H.z.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:SI,stopped:H.z.boolean(),canBack:H.z.boolean(),authenticated:H.z.boolean(),locale:H.z.string().min(1).max(35),answers:lr,parameters:dr,variables:H.z.record(H.z.string(),ve),output:ve.nullable(),screen:vI.nullable(),paywall:H.z.strictObject({receiptId:H.z.uuid(),resolution:H.z.union([wo,Jr]),quote:Si.nullable(),operation:Ii.nullable(),purchaseRequestId:H.z.uuid().nullable(),selectionGeneration:H.z.number().int().nonnegative().optional(),canReselect:H.z.boolean().optional()}).nullable(),instruction:Uu.nullable(),pendingRequest:H.z.strictObject({requestId:H.z.uuid(),authenticationRequired:H.z.boolean()}).nullable(),runExpiresAt:H.z.iso.datetime({offset:!0}),credentialExpiresAt:H.z.iso.datetime({offset:!0}).nullable()}),ls=H.z.strictObject({scope:Fe,run:Eo,settlement:H.z.strictObject({requestId:H.z.uuid(),state:H.z.enum(["pending","unknown","settled"]),operationId:H.z.uuid().nullable(),receiptId:H.z.uuid().nullable().optional()}).optional(),purchase:H.z.strictObject({receiptId:H.z.uuid(),quote:Si.nullable(),operation:Ii.nullable(),canReselect:H.z.boolean().optional()}).optional(),review:H.z.strictObject({activeOperationId:H.z.uuid().nullable(),pages:H.z.array(H.z.strictObject({receiptId:H.z.uuid(),nodeId:fr,visit:H.z.number().int().nonnegative()})).max(100),page:H.z.strictObject({receiptId:H.z.uuid(),nodeId:fr,visit:H.z.number().int().nonnegative(),document:dn,answers:lr,inputs:Ga,values:H.z.record(H.z.string(),ve).optional()}).nullable(),coupons:H.z.array(H.z.strictObject({grantId:H.z.uuid(),status:H.z.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:H.z.string().nullable()})).max(100),purchases:H.z.array(H.z.strictObject({receiptId:H.z.uuid(),operationId:H.z.uuid(),status:H.z.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:H.z.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:H.z.uuid().optional()}),Yg=ls.extend({run:Eo.extend({paywall:Eo.shape.paywall.unwrap().extend({resolution:Jr}).nullable()})});var Xg="X-Indiana-Server-Key";var se=require("zod");var Ae=require("zod");var wt=require("zod");var wI=wt.z.strictObject({selector:wt.z.string().min(1).max(2048),action:wt.z.enum(["set","append","remove"]),attribute:wt.z.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:wt.z.string().max(5e4).optional(),parentSelector:wt.z.string().max(2048).optional(),insertBeforeSelector:wt.z.string().max(2048).optional()}),OI=wt.z.strictObject({variation:wt.z.string().min(1).max(128),description:wt.z.string().max(2e3).default(""),css:wt.z.string().max(1e5).default(""),js:wt.z.string().max(1e5).default(""),domMutations:wt.z.array(wI).max(200).default([]),iam:Sf.optional(),renderGuard:La.optional()}),Bu=OI.omit({variation:!0,description:!0,iam:!0}),PI=Pi.omit({variations:!0,active:!0}).extend({changeId:wt.z.string().regex(/^[a-f0-9]{64}$/),variations:wt.z.tuple([Bu,Bu]).rest(Bu).refine(e=>e.length<=20)}),eh=wt.z.strictObject({trackExposures:wt.z.boolean(),environmentId:wt.z.uuid(),generation:wt.z.string().regex(/^[a-f0-9]{64}$/),experiments:wt.z.array(PI).max(100),savedGroups:Ao});var Ro=Ae.z.string().regex(/^[a-f0-9]{64}$/),aj=Ae.z.strictObject({iam:Ro,executionContracts:Ae.z.union([Ae.z.tuple([Ae.z.literal("funnel-run/1")]),Ae.z.tuple([Ae.z.literal("funnel-process/1")])]).default(["funnel-run/1"])}),CI=Ae.z.strictObject({release:Ro,render:La,button:Ae.z.strictObject({selector:Ae.z.string().min(1).max(512),elementKey:Ae.z.string().min(1).max(256),tag:Ae.z.enum(["button","a","input"])}).nullable()}),sj=Ae.z.strictObject({scope:Fe.extend({environmentId:Ae.z.uuid()}),release:Ro,validatedAt:Ae.z.iso.datetime({offset:!0}),validUntil:Ae.z.iso.datetime({offset:!0}),entries:Ae.z.array(Ae.z.strictObject({id:Ae.z.uuid(),funnelId:Ae.z.uuid(),versionId:Ae.z.uuid(),event:Ae.z.enum(["screen_enter","button_click"]),target:CI})).max(4e3)}),th=Ae.z.strictObject({operation:Ae.z.literal("entry_start"),funnelId:Ae.z.uuid(),versionId:Ae.z.uuid(),entryId:Ae.z.uuid(),release:Ro,requestId:Ae.z.uuid(),locale:Ae.z.string().min(1).max(35).default("en")}),nh=Ae.z.strictObject({scope:Fe,suppressed:Ae.z.literal(!0),reason:Ae.z.enum(["frequency","in_progress"]),retryAt:Ae.z.iso.datetime({offset:!0}).nullable()}),cj=Ae.z.strictObject({experimentId:Ae.z.uuid(),splitNodeId:Ae.z.string().min(1).max(128)}),_I=Ae.z.strictObject({experimentId:Ae.z.uuid(),experimentKey:Ae.z.string().min(1).max(128),variationKey:Ae.z.string().min(1).max(128),inExperiment:Ae.z.boolean(),generation:Ae.z.string().min(1).max(256)}),ko=Ae.z.strictObject({operation:Ae.z.literal("page_experiments"),release:Ro,usedReceiptIds:Ae.z.array(Ae.z.uuid()).max(20).default([]),customerToken:Ae.z.string().regex(Nt).optional()}),rh=Ae.z.strictObject({scope:Fe,runId:Ae.z.uuid(),assignments:Ae.z.array(_I.extend({receiptId:Ae.z.uuid()})).max(100),payload:eh});var jn=se.z.literal(gf),EI=se.z.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),Vu=se.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),ih=se.z.discriminatedUnion("type",[se.z.strictObject({type:se.z.literal("guest"),guestToken:Vu}),se.z.strictObject({type:se.z.literal("customer"),customer:Hr,customerData:Ci.optional()})]),Lu=se.z.strictObject({id:se.z.uuid(),runId:se.z.uuid(),customerId:se.z.uuid(),requestId:se.z.uuid(),acceptedAt:se.z.iso.datetime({offset:!0})}),RI=se.z.strictObject({participantId:se.z.uuid(),startedAs:se.z.enum(["guest","identified"]),binding:Lu.omit({runId:!0,requestId:!0}).nullable()}),kI=se.z.union([Uu,se.z.strictObject({type:se.z.literal("authentication_required"),reason:se.z.enum(["customer_required","customer_experiment_required"]),nodeId:se.z.string().min(1).max(64),visit:se.z.number().int().nonnegative()})]),jI=Eo.omit({authenticated:!0}).extend({identity:RI,instruction:kI.nullable()}),TI=se.z.discriminatedUnion("operation",[_t.options[2].omit({customerToken:!0}),_t.options[3].omit({customerToken:!0}),_t.options[4].omit({customerToken:!0}),_t.options[5].omit({customerToken:!0}),_t.options[6].omit({customerToken:!0}),_t.options[7].omit({customerToken:!0})]),ds={contract:jn,customerToken:se.z.string().regex(Nt)},oh={contract:jn,requestId:se.z.uuid(),runToken:EI,externalUserId:Hr.options[1].shape.value},ah=se.z.discriminatedUnion("operation",[se.z.strictObject({contract:jn,operation:se.z.literal("describe")}),se.z.strictObject({contract:jn,operation:se.z.literal("start"),source:ih,funnelId:_t.options[0].shape.funnelId,requestId:se.z.uuid(),locale:_t.options[0].shape.locale,parameters:_t.options[0].shape.parameters}),th.omit({operation:!0}).extend({contract:jn,operation:se.z.literal("entry_start"),source:ih}),se.z.strictObject({...oh,operation:se.z.literal("bind_customer"),guestToken:Vu,claimRequestId:se.z.uuid(),expectedBindingId:se.z.null()}),se.z.strictObject({...oh,operation:se.z.literal("binding_status"),guestToken:Vu.optional()}),_t.options[1].omit({operation:!0,customerToken:!0}).extend({...ds,operation:se.z.literal("get"),settlementBindingId:se.z.uuid().nullable().optional()}),_t.options[8].omit({operation:!0,customerToken:!0}).extend({...ds,operation:se.z.literal("review")}),ko.omit({customerToken:!0}).extend(ds),se.z.strictObject({...ds,operation:se.z.literal("command"),identity:se.z.strictObject({bindingId:se.z.uuid().nullable()}),command:TI})]),zu=ls.omit({run:!0}).extend({contract:jn,run:jI,settlement:ls.shape.settlement.unwrap().extend({accepted:se.z.boolean().nullable().optional()}).optional()}),yj=nh.extend({contract:jn}),Aj=se.z.discriminatedUnion("operation",[ah.options[1].omit({contract:!0,source:!0,requestId:!0}),ah.options[2].omit({contract:!0,source:!0,requestId:!0})]),bj=zu.extend({binding:Lu,outcome:se.z.enum(["bound","already_bound"]),replayed:se.z.boolean()}),xj=se.z.discriminatedUnion("state",[se.z.strictObject({contract:jn,scope:Fe,state:se.z.literal("not_accepted")}),se.z.strictObject({contract:jn,scope:Fe,state:se.z.literal("conflict")}),se.z.strictObject({contract:jn,scope:Fe,state:se.z.literal("bound"),binding:Lu})]),Sj=se.z.strictObject({contract:jn,scope:Fe,keyId:se.z.uuid(),operations:se.z.array(se.z.string()).max(20)});var Ne=require("zod");var Ni=Ne.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ch=Ne.z.strictObject({entry:Ni,nodes:Ne.z.array(Ne.z.strictObject({id:Ni,type:Ne.z.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:Ne.z.record(Ne.z.string(),Ni),writes:Ne.z.record(It,It),resources:Ne.z.strictObject({screenId:Ni.optional(),paywallVersionId:Ne.z.uuid().optional(),couponId:Ne.z.uuid().optional(),couponIds:Ne.z.array(Ne.z.uuid()).max(20).optional(),experimentId:Ne.z.uuid().optional(),featureKey:Ne.z.string().optional(),offeringVersionId:Ne.z.uuid().optional()})})).min(1).max(500)}),sh={scope:Fe,funnelId:Ne.z.uuid(),versionId:Ne.z.uuid(),evaluationRevision:Ne.z.number().int().nonnegative(),expiresAt:Ne.z.iso.datetime({offset:!0}).nullable(),topology:ch},ps=Ne.z.discriminatedUnion("evaluationMode",[Ne.z.strictObject({...sh,evaluationMode:Ne.z.literal("local"),growth:bn,conditions:Ne.z.record(Ni,Ne.z.array(Ne.z.strictObject({condition:Yt,port:Ne.z.string()})))}),Ne.z.strictObject({...sh,evaluationMode:Ne.z.literal("remote")})]),NI=ps.options[0].extend({evaluation:Ne.z.strictObject({maxTransitions:Ne.z.number().int().min(1).max(1e4),variables:Ne.z.record(It,hi),outputSchema:gi,terminals:Ne.z.record(Ni,Ne.z.strictObject({outcome:Ne.z.enum(["completed","closed","ineligible","failed"]),output:So.nullable()}))})});function DI(e){return ch.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let n={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":n.next=t.next;break;case"screen":Object.assign(n,t.outputs),r.screenId=t.screenId;{let a=e.screens.find(o=>o.id===t.screenId);a?.type==="paywall"&&(r.paywallVersionId=a.paywallVersionId)}break;case"condition":t.cases.forEach((a,o)=>{n[`case:${o}`]=a.target}),n.default=t.default;break;case"split":Object.assign(n,t.routes),n.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let a of["success","cancel","unavailable","failure"])n[a]=t[a];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=Ne.z.uuid().parse(t.action.coupon.value.id));break;case"external_page":n.opened=t.opened,n.failed=t.failed;break;case"wait":t.wait.type==="duration"?n.elapsed=t.wait.elapsed:(n.received=t.wait.received,n.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let i=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return i?.type==="feature"&&(r.featureKey=i.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:n,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function $u(e){let t=Ri.parse(e.document),n=e.evaluationMode==="local"?bn.parse(e.payload):null;if(n&&(n.scope.projectId!==e.scope.projectId||n.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:n?.expiresAt??null,topology:DI(t)};return ps.parse(e.evaluationMode==="remote"?r:{...r,growth:is(t,n),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((a,o)=>({condition:a.condition,port:`case:${o}`}))]))})}function uh(e){let t=$u(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=Ri.parse(e.document);return NI.parse({...t,evaluation:{maxTransitions:n.execution.maxTransitions,variables:n.variables,outputSchema:n.outputSchema,terminals:Object.fromEntries(n.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}var nt=require("zod");var lh=nt.z.string().regex(/^[a-f0-9]{64}$/),FI=Pi.omit({variations:!0,active:!0}).extend({changeId:lh,variations:nt.z.array(nt.z.strictObject({urlRedirect:nt.z.string().max(2048)})).min(2).max(20)}),dh=nt.z.strictObject({environmentId:nt.z.uuid(),trackExposures:nt.z.boolean(),generation:lh,experiments:nt.z.array(FI).max(100),savedGroups:Ao}),MI=nt.z.strictObject({eventUuid:nt.z.uuid(),timestamp:nt.z.iso.datetime({offset:!0}).optional(),deviceId:nt.z.string().min(1).max(128),sessionId:nt.z.string().min(1).max(128).optional(),url:nt.z.url().max(2048),pageTitle:nt.z.string().max(512).optional(),experimentKey:nt.z.string().min(1).max(255),variationKey:nt.z.string().min(1).max(64)}),jj=nt.z.strictObject({events:nt.z.array(MI).min(1).max(20)}),Tj=nt.z.strictObject({inserted:nt.z.number().int().nonnegative(),duplicates:nt.z.number().int().nonnegative(),skipped:nt.z.number().int().nonnegative(),rejected:nt.z.array(nt.z.strictObject({index:nt.z.number().int().nonnegative(),reason:nt.z.string()}))});var ct=require("zod");var Ku=32,qI=522240;function Hu(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var UI=ct.z.strictObject({nodeId:ct.z.string().min(1).max(64),visit:ct.z.number().int().nonnegative(),revision:ct.z.number().int().nonnegative()}),Gu=ct.z.record(ct.z.string(),ve),BI=ct.z.strictObject({id:ct.z.uuid(),nodeId:ct.z.string().min(1).max(64),visit:ct.z.number().int().nonnegative(),input:ct.z.strictObject({schemaVersion:Io.shape.schemaVersion,kind:Io.shape.kind,selector:Io.shape.selector,contract:Io.shape.contract}),context:Gu,removed:ct.z.array(ct.z.string()).max(100),attributes:Gu,removedAttributes:ct.z.array(ct.z.string()).max(100),result:Kf,offeringVersionId:ct.z.uuid().nullable(),events:ct.z.strictObject({entered:ct.z.string().regex(/^[1-9][0-9]{0,18}$/),decision:ct.z.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),qj=ct.z.strictObject({schemaVersion:ct.z.literal(1),mode:ct.z.enum(["local","remote"]),versionId:ct.z.uuid(),generation:ct.z.number().int().positive(),base:UI,context:Gu,steps:ct.z.array(BI).min(1).max(Ku)}).refine(e=>pn(e)<=qI,"Segment exceeds its byte budget");var VI=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function jo(e){return Array.isArray(e)?e.some(jo):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&jo(n):!VI.test(t))}function ph(e,t,n,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(s=>s.id===t.screenId&&s.type==="paywall")))return"customer_required";let i=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(i&&["bundle","selection","offering"].includes(i.type)||t.type==="condition"&&t.cases.some(s=>jo(s.condition)))return"customer_required";let a=JSON.stringify([t,t.type==="screen"?e.screens.find(s=>s.id===t.screenId):null]);for(let[s,c]of Object.entries(e.variables))if(c.source.type==="attribute"&&c.source.key!=="funnelParticipantId"&&(a.includes(`variables.${s}`)||a.includes(JSON.stringify(s))))return"customer_required";if(t.type==="split"){let s=n.experiments?.[t.experimentId];if((s?.hashAttribute??"id")!=="funnelParticipantId"||jo(s?.condition)||s?.parentConditions?.length)return"customer_experiment_required"}let o=t.type==="feature"?t.featureKey:i?.type==="feature"?i.featureKey:void 0;return o&&n.features?.[o]?.rules?.some(s=>(s.hashAttribute??"id")!=="funnelParticipantId"||jo(s.condition)||s.parentConditions?.length)?"customer_experiment_required":null}var Qu=class extends Error{constructor(n,r){super(r);qe(this,"code",n);this.name="FunnelLocalCalculationError"}},mh=(e,t)=>new Qu(e,t),LI=e=>({experiments:e.experiments,features:e.features});function zI(e,t=mh){let n=new Map(e.topology.nodes.map(o=>[o.id,o])),r=ci(e.growth.savedGroups),i=LI(e.growth);function a(o,s){if(!Object.hasOwn(e.growth.features,o))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Hn(o,s).value}return{nodes:n,savedGroups:r,features:i.features,feature:a,evaluate(o,s){let c=n.get(o);if(!c)throw t("NOT_FOUND","Funnel node is unavailable");let u,l;if(c.type==="condition"){let f=e.conditions[c.id];if(!f)throw t("INVALID_RESPONSE","Local condition rules are unavailable");u=qu({id:c.id,name:c.id,type:"condition",cases:f.map(g=>({condition:g.condition,target:c.outputs[g.port]})),default:c.outputs.default},s,i.experiments).port}else if(c.type==="feature"){if(!c.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");l=a(c.resources.featureKey,s),u="next"}else if(c.type==="split"){if(!(c.resources.experimentId?e.growth.experiments[c.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let g=qu({id:c.id,name:c.id,type:"split",experimentId:c.resources.experimentId,routes:c.outputs,notParticipating:c.outputs.notParticipating},s,i.experiments);l=g.value,u=g.port}else if(["offering","end","output"].includes(c.type)&&c.resources.featureKey)l=a(c.resources.featureKey,s),u=c.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let m=c.outputs[u]??(u==="value"?c.id:void 0);if(!m)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:o,port:u,target:m,...l===void 0?{}:{value:l}}}}}function $I(e,t){let n=ps.parse(e);if(n.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=n.expiresAt?Date.parse(n.expiresAt):null,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let a=zI(n,t);return(o,s)=>(i(),GI(a,o,s))}function GI(e,t,n){let r=Ct.parse(n.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:a,onExperimentViewed:o}=n,s={attributes:r,...i?{saveStickyBucketAssignmentDoc:c=>i(structuredClone(c))}:{},...a?{onFeatureUsage:(c,u)=>a(c,structuredClone(u))}:{},...o?{onExperimentViewed:(c,u)=>o(structuredClone(c),structuredClone(u))}:{},features:e.features,savedGroups:e.savedGroups,...n.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(n.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,s)}function KI(e,t,n){let r=[],i=[],a=[],o=e(t,{...n.attributes?{attributes:n.attributes}:{},stickyBucketAssignmentDocs:n.sticky,saveStickyBucketAssignmentDoc(s){let c=r.findIndex(m=>m.next.attributeName===s.attributeName&&m.next.attributeValue===s.attributeValue),u=s.attributeName+"||"+s.attributeValue,l={expected:n.sticky[u]??null,next:s};c<0?r.push(l):r[c]=l},onExperimentViewed(s,c){c.inExperiment&&c.hashUsed&&!c.passthrough&&i.push(ve.parse({key:s.key,variationId:c.variationId,keyUsed:c.key,hashAttribute:c.hashAttribute,hashValue:c.hashValue}))},onFeatureUsage(s,c){a.push(ve.parse({feature:s,value:c.value,source:c.source,...c.ruleId?{ruleId:c.ruleId}:{}}))}});return{port:o.port,...o.value===void 0?{}:{value:o.value},sticky:r,exposures:i,features:a}}function fh(e,t,n,r=mh){let i=n,a=new Map(t.graph.nodes.map(R=>[R.id,R])),o=structuredClone(n.variables),s=structuredClone(i.sticky),c=[],u=n.nodeId,l=n.visit,m=!1,f,g=R=>ph(t,R,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),d=R=>(f??(f=$I(e,r)),KI(f,R,{attributes:ru({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:o,savedGroups:{}}),sticky:s}));for(let R=0;R<Ku;R++){let y=a.get(u);if(!y||!Hu(y)||g(y))break;if(l>=t.execution.maxTransitions&&(l>t.execution.maxTransitions||y.type!=="end"&&y.type!=="output")){if(!c.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let A,x;if(["condition","feature","split"].includes(y.type)||y.type==="offering"&&y.configuration.source==="feature")A=d(y.id),y.type==="offering"&&(A.value={type:"offering_version",id:String(A.value)}),y.type==="condition"?x=A.port==="default"?y.default:y.cases[Number(A.port.slice(5))]?.target:y.type==="split"?x=A.port==="notParticipating"?y.notParticipating:y.routes[A.port]:(y.type==="feature"||y.type==="offering")&&(x=y.next);else if(A={port:"next",sticky:[],exposures:[],features:[]},(y.type==="entry"||y.type==="coupon"||y.type==="coupons")&&(x=y.next),y.type==="offering"&&y.configuration.source==="fixed"&&(A.value={type:"offering_version",id:y.configuration.versionId},x=y.next),y.type==="end"||y.type==="output"){let P=y.type==="end"?y.output:y.value;if(A=P?.type==="feature"?d(y.id):{...A,port:"value",value:P?.type==="literal"?P.value:P?.type==="variable"?Ec({source:"variable",key:P.key,...P.path?{path:P.path}:{}},{declarations:t.variables,answers:n.answers,results:o,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},P&&(A.value===void 0||!An(t.outputSchema,A.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let v=[...c,{nodeId:u,result:A}];if(pn({steps:v})>6e4){if(!c.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(c.push({nodeId:u,result:A}),y.type==="feature"||y.type==="offering"||y.type==="coupon"||y.type==="coupons"){let P=y.type==="coupons"?y.couponIds.map(_=>({type:"reward",id:_})):y.type==="coupon"?{type:"reward",id:y.couponId}:A.value;if(P===void 0)throw r("INVALID_RESPONSE","Node output is missing");let j=yi(y,{value:P});om(t.variables,y,j),Object.assign(o,j)}for(let P of A.sticky)s[`${P.next.attributeName}||${P.next.attributeValue}`]=structuredClone(P.next);if(y.type==="end"||y.type==="output"){m=!0;break}if(!x)throw r("INVALID_RESPONSE","Local pure exit is unavailable");u=x,l++}let h=a.get(u);return{steps:c,...!m&&h&&(!Hu(h)||g(h))?{boundary:{nodeId:u,visit:l}}:{}}}var b=class extends Error{constructor(n,r,i,a,o){super(r);qe(this,"code",n);qe(this,"status",i);qe(this,"requestId",a);qe(this,"commandRequestId");qe(this,"retryable");qe(this,"recovery");qe(this,"retryAfterSeconds");qe(this,"reason");this.name="IndianaError",this.reason=o?.reason;let s=$o(n,i??0,{...o,retryAfter:o?.retryAfterSeconds===void 0?void 0:String(o.retryAfterSeconds)});this.retryable=s.retryable,this.recovery=s.recovery,this.retryAfterSeconds=s.retryAfterSeconds}};var To=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new b("INVALID_STATE","Installation sequence exhausted");return e+1},HI=async e=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(e,t=>t.charCodeAt(0))))].map(t=>t.toString(16).padStart(2,"0")).join("");function Un(e,t){return e.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 b("INVALID_STATE","Installation journal is invalid");return t({...n})})}function gh(e,t,n){let r=null,i=0,a=0,o=0,s=Promise.resolve(),c=!1;if(e&&(!n||Fe.parse(e.scope).projectId!==n.projectId||e.scope.environment!==n.environment))throw new b("SCOPE_MISMATCH","Push installation belongs to another scope");let u=()=>{if(c)throw new b("CLOSED","SDK client was destroyed");if(!e)throw new b("NOT_CONFIGURED","Configure this client's native Push host first");return e},l=x=>{if(x!==i)throw new b("IDENTITY_CHANGED","Identity changed during Push operation")};async function m(x){let v=u();if(!v.sha256&&!globalThis.crypto?.subtle)throw new b("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let P=v.sha256?await v.sha256(Uint8Array.from(x,j=>j.charCodeAt(0))):await HI(x);if(!/^[a-f0-9]{64}$/.test(P))throw new b("INVALID_STATE","Push credential digest is invalid");return P}function f(x){let v=Pr.parse(x);if(v.installationId.toLowerCase()!==u().installationId.toLowerCase())throw new b("INVALID_RESPONSE","Push response belongs to another installation");return v}async function g(x,v){let P=u(),j={installationId:P.installationId,publicKey:P.publicKey,issuedAt:new Date().toISOString(),...v},_=await P.sign(_l(x,P.scope,j));return{...j,signature:_}}let d=(x,v,P)=>t.requestWithCredential?t.requestWithCredential(x,v,P):t.request(x,v);async function h(){let x=u(),v=i,P=r?await(t.session?.access()??r):null,j=Un(x,Se=>Se),_;if(j.detachSeq!==null){let Se=j.detachSeq,At=Ol.parse(await g("detach",{sequence:Se,platform:x.platform}));try{let We=await t.request("push/installations/detach",{...x.scope,...At},"POST",{installationDetach:!0});if(!We||typeof We!="object"||!("installation"in We))throw new b("INVALID_RESPONSE","Push detach acknowledgement is invalid");let De=f(We.installation);if(De.bound||De.identitySeq!==Se)throw new b("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(We){if(We instanceof b&&We.status===404)_=We;else if(!(We instanceof b)||We.status!==412)throw We}_||Un(x,We=>({...We,detachSeq:We.detachSeq===Se?null:We.detachSeq}))}if(l(v),!P){if(_)throw _;return null}let X=O.bindPushInstallation,le=X.request.parse(await g("bind",{sequence:o,platform:x.platform,credentialDigest:await m(P)}));l(v);let he=X.response.parse(await d(X.path,le,P));l(v);let ke=f(he.installation);if(!ke.bound||ke.identitySeq!==o)throw new b("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return _&&j.detachSeq!==null&&o>j.detachSeq&&Un(x,Se=>({...Se,detachSeq:Se.detachSeq===j.detachSeq?null:Se.detachSeq})),ke}async function R(){u();let x=i,v=r?await(t.session?.access()??r):null;if(!v)throw new b("NOT_IDENTIFIED","Identify before reading this installation");let P=O.readPushInstallation,j=P.request.parse(await g("read",{credentialDigest:await m(v)}));l(x);let _=P.response.parse(await d(P.path,j,v));return l(x),f(_.installation)}function y(x=h){let v=s.catch(()=>{}).then(x);return s=v,v.catch(P=>{try{e?.onError?.(P instanceof Error?P:new Error("Push synchronization failed"))}catch{}}),v}async function A(x,v,P){let j=u(),_=v.identity,X=v.observation,le=r?await(t.session?.access()??r):null;if(l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");if(!le)throw new b("NOT_IDENTIFIED","Identify before recovering a Push address");if(!x.connectionId||!x.kind||!x.token||!["granted","provisional"].includes(x.permission))throw new b("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await y(async()=>{if(l(_),await h(),l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let he=Un(j,De=>P?De:{...De,addressSeq:To(De.addressSeq)}),Se=await g(P?"recovery_confirm":"recovery_request",{...x,sequence:he.addressSeq,credentialDigest:await m(le),...P?{challenge:P}:{}}),At=P?Cl.parse(Se):Pl.parse(Se);if(l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let We=await d(`push/installations/recovery/${P?"confirm":"request"}`,At,le);if(l(_),X!==a||Un(j,De=>De).addressSeq!==he.addressSeq)throw new b("INVALID_STATE","Push observation changed during recovery");if(P){let De=O.updatePushAddress.response.parse(We),rt=f(De.installation);if(!rt.bound||rt.identitySeq!==o||rt.addressSeq!==he.addressSeq||rt.connectionId!==x.connectionId||rt.addressStatus!=="active")throw new b("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return rt}if(!We||typeof We!="object"||!("recovery"in We))throw new b("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return Es.parse(We.recovery)})}return{recoveryObserver(){u();let x={identity:i,observation:++a};return{async request(v){return Es.parse(await A(v,x))},async confirm(v,P){return Pr.parse(await A(P,x,v))}}},identify(x){if(!e)return;o=Un(e,P=>({...P,identitySeq:To(P.identitySeq)})).identitySeq,r=x,i++,a++},reset(){if(e)try{Un(e,x=>{let v=To(x.identitySeq);return{...x,identitySeq:v,detachSeq:v}})}finally{r=null,i++,a++}},start(){e&&!c&&y()},destroy(){c=!0,r=null,i++,a++},async sync(){return await y()},read:R,async recover(){let x=u(),v=i,P=o;return a++,await y(async()=>{l(v);let j=await R();return l(v),o=Un(x,X=>{if(X.identitySeq!==P)throw new b("IDENTITY_CHANGED","A newer installation intent exists");return{...X,identitySeq:To(Math.max(X.identitySeq,j.identitySeq)),addressSeq:Math.max(X.addressSeq,j.addressSeq)}}).identitySeq,await h()})},tokenObserver(){u();let x=++a,v=i;return async P=>{if(x!==a||v!==i)return null;let j=u(),_=r?await(t.session?.access()??r):null;if(!_)throw new b("NOT_IDENTIFIED","Identify before registering a Push token");if(await y(),l(v),x!==a)return null;let X=Un(j,Se=>({...Se,addressSeq:To(Se.addressSeq)})),le=O.updatePushAddress,he=le.request.parse(await g("address",{...P,sequence:X.addressSeq,credentialDigest:await m(_)}));if(l(v),x!==a)return null;let ke=await d(le.path,he,_);return l(v),x!==a||Un(j,Se=>Se).addressSeq!==X.addressSeq?null:f(le.response.parse(ke).installation)}}}}var yh=require("zod");function hh(e,t,n,r){try{return e.parse(t)}catch(i){throw r&&i instanceof yh.ZodError?new b(n,r):i}}async function ge(e,t,n,r={},i){let a=typeof r=="function"?{}:r,o=hh(t.request,n,"INVALID_REQUEST",a.request);try{let s=await e(t.path,o,t.method,i),c=typeof r=="function"?r:r.parseResponse;return c?c(t.response,s):hh(t.response,s,"INVALID_RESPONSE",a.response)}catch(s){throw s instanceof b&&o!==null&&typeof o=="object"&&"requestId"in o&&typeof o.requestId=="string"&&(s.commandRequestId??(s.commandRequestId=o.requestId)),s}}function Ah(e,t){let n={async preference(r){let i=O.readMessagingPreference;return(await ge(e,i,{channel:r})).preference},async setPreference(r){let i=O.setMessagingPreference;return(await ge(e,i,r)).preference}};return{messaging:n,push:{sync:t.sync,read:t.read,recover:t.recover,tokenObserver:t.tokenObserver,recoveryObserver:t.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return n.setPreference({...r,channel:"push"})}}}}var bh={name:"@tinkerlandai/longplay-sdk",version:"0.10.18-rc.1",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}}};function Qe(e){return typeof e=="string"?e:String(e)}var JI=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function ZI(e){return e.replace(JI,"$1\uFFFD")}function Yu(e,t){if(typeof e!="object"||e==null){let n="";throw n+="The provided value is not an object",new TypeError(n)}return e}function _h(e){if(e!=null&&(typeof e=="object"||typeof e=="function")){let t=e[Symbol.iterator];if(t==null)return;if(typeof t!="function")throw new TypeError("The provided value is not iterable");let n=t.call(e);if(!n||typeof n!="object")throw new TypeError("Result of the Symbol.iterator method is not an object");return n}}function xh(e){let t;if(Array.isArray(e)){let n=e.map(Qe);if(n.length===2)return n}else if((t=_h(e))!=null){let n=Yu(t.next()),r=Yu(t.next());if(!n.done&&!r.done)return[Qe(n.value),Qe(r.value)]}throw new TypeError("Each query pair must be an iterable [name, value] tuple")}var Sh="0123456789ABCDEF",WI=/(?:%[0-9A-Fa-f]{2})+/g;function Bn(e){return`%${Sh[e>>4&15]}${Sh[15&e]}`}function Eh(e,t,n=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?n&&e===32?"+":t(e)?Bn(e):String.fromCharCode(e):e<=2047?Bn(192|e>>6)+Bn(128|63&e):e<=65535?Bn(224|e>>12)+Bn(128|e>>6&63)+Bn(128|63&e):Bn(240|e>>18)+Bn(128|e>>12&63)+Bn(128|e>>6&63)+Bn(128|63&e)}function Xu(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function el(e,t=!1){let n=0;for(;n<e.length;n++){let r=e.charCodeAt(n);if(r===37||t&&r===43)break}return n===e.length?e:(t?e.replace(/\+/g," "):e).replace(WI,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function Fo(e){return e<=31||e>126}function YI(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return Fo(e)}}function sl(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return Fo(e)}}function XI(e){return sl(e)||e===39}function tl(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return sl(e)}}function ys(e){switch(e){case 47:case 58:case 59:case 61:case 64:case 91:case 92:case 93:case 124:return!0;default:return tl(e)}}function Ih(e){switch(e){case 33:case 39:case 40:case 41:case 126:return!0;default:return(function(n){switch(n){case 36:case 37:case 38:case 43:case 44:return!0;default:return ys(n)}})(e)}}function Rh(e,t){return Eh(e=e||0,t)}function Vn(e,t,n=!1){let r=0;for(;r<e.length;r++){let a=e.charCodeAt(r);if(a>=128||n&&a===32||t(a))break}if(r===e.length)return e;let i=e.slice(0,r);for(;r<e.length;r++){let a=e.charCodeAt(r),o=a;if(a>=55296&&a<=56319&&r+1<e.length){let s=e.charCodeAt(r+1);s>=56320&&s<=57343&&(o=(a-55296<<10)+s-56320+65536,r++)}i+=Eh(o,t,n)}return i}function cl(e){let t=[],n=0,r=0;for(;r<=e.length;){if(r=e.indexOf("&",n),r<0&&(r=e.length),r!==n){let i=e.slice(n,r),a=i.indexOf("=");a<0&&(a=i.length),t.push([el(i.slice(0,a),!0),el(i.slice(a+1),!0)])}if(n=r+1,r===e.length)break}return t}function nl(e){let t="";for(let n=0;n<e.length;n++){let r=Vn(e[n][0],Ih,!0),i=Vn(e[n][1],Ih,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var ev=[2191,2191,3164,3164,3292,3292,6863,6877,6880,6891,8385,8385,11158,11158,42958,42959,42962,42962,42964,42964,42993,42993,64451,64466,64912,64913,64968,64974,67904,67929,69317,69319,69328,69336,69370,69371,72544,72551,73136,73179,73184,73193,93856,93880,93883,93907,94194,94198,100344,100351,101641,101662,101760,101874,118010,118012,118458,118480,118496,118512,124608,124638,124640,124661,124670,124671,128728,128728,128887,128890,129232,129240,129620,129623,129674,129674,129678,129678,129736,129736,129741,129741,129770,129770,129775,129775,130042,130042,177978,177983,183970,183981,205744,210041],tv=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],nv=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],rv=[2381,2381,2509,2509,2637,2637,2765,2765,2893,2893,3021,3021,3149,3149,3277,3277,3387,3388,3405,3405,3530,3530,3642,3642,3770,3770,3972,3972,4153,4154,5908,5909,5940,5940,6098,6098,6752,6752,6980,6980,7082,7083,7154,7155,11647,11647,43014,43014,43052,43052,43204,43204,43347,43347,43456,43456,43766,43766,44013,44013,68159,68159,69702,69702,69744,69744,69759,69759,69817,69817,69939,69940,70080,70080,70197,70197,70378,70378,70477,70477,70606,70608,70722,70722,70850,70850,71103,71103,71231,71231,71350,71350,71467,71467,71737,71737,71997,71998,72160,72160,72244,72244,72263,72263,72345,72345,72767,72767,73028,73029,73111,73111,73537,73538,90415,90415];function iv(e){for(let t=0;t<e.length;t++){let n=e.codePointAt(t);if(n>65535&&t++,n<=32||n===37||n===127||n>=55296&&n<=57343||n>=128&&n<=159||n>=64976&&n<=65007||!(65534&~n)||n===65533)return!0}return!1}var[ov,av,sv,vh]=[[[],"0,6,7,8,m,w,10,1b,1d,1f,72,73,7k,8k,dt,2rk","AAAAAAAAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAA/AAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAADAAABwfwAAAAAAAMADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhAAAAQAAAAAAAAQCAAABAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgACAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAP///////////////wAAAAAAAAAAAAAAAAAAAAA="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAEF9+P/+BwAAAMAA//8AAPz/////BlADAAAAAJwAAPz///8AAADA//H/5+X8AAAAAAAAAAAA/P///wcAAAAAAAAAAAAAPv0vAD0BAABA/gAA/5/5/f8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8g+N8B+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAYAAAAAAAAAAAAAD/////CwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANgAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/HgwAAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAP3////+BwAAAMDu//////////////8vAADAAJwAAP3///8AAADg////////AAAAAAAAAAAA/P///wcAAAAAAAAAAAAA////Ab0H//9H/gAA/9////8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL/G//8T+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAfgAAAAAAAAAAAAD+////DwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANwAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/Hg4AAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"0,3,4,5,6,7,8,9,a,b,c,d,e,f,g,j,n,o,p,q,r,s,t,w,18,19,1c,4m,4o,4p,4q,4r,6z,72,73,75,76,77,7e,7h,7i,7j,7k,7l,7m,7n,7o,7p,7q,7r,7s,7t,7u,7v,7w,7x,7y,7z,8k,9t,a2,a3,a7,cc,cv,cx,cy,d6,dc,dd,de,dg,dh,di,dk,dl,2rk,2rl","AAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAD//////////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD4AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/v////+/tgAAAAAAAAAAAP8XAAAAAAD4//8AAAEAAAAAAAAAAAAAAMCfnz0AAACAAgAAAP///wcAAAAAAAAAAAAAwP8BAAAAAAAA+A8gAADA++8+AAAAAAAOAAAAAAAAgP8AAAAAAPz///v///8HAAAAAAAAFP4h/gAMAAAAAgAAAAAAABAeIAAADAAAQAYAAAAAAAAQhjkCAAAAIwAGAAAAAAAAEL4hAAAMAAD8AgAAAAAAAJAeIGAADAAAAAQAAAAAAAAAASAAAAAAAAARAAAAAAAA0ME9YAAMAAAAAgAAAAAAAJBAMAAADAAAAAMAAAAAAAAYHiAAAAwAAAACAAAAAAAAAAAEXAAAAAAAAAAAAAAA8geAfwAAAAAAAAAAAAAAAPIfAH8AAAAAAAAAAAADAACgAgAAAAAAAP5/3+D//v///x9AAAAAAAAAAAAAAAAA4P1mAAAAwwEAHgBkIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAAAAMAAAADAAAAAwAAAAAAAAAsD9A/g8gAAAAAAC4AAAAAAAAAAAAAAAAAABgAAAAAAIAAAAAAAAAAAAAAAAAAIcBBA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAJAAAAAAAAQH/lH/ifAAAAAAAA//////8//w8AAA8AAAAAANAXBAAAAAD4DwADAAAAPDsAAAAAAABAowMAAAAAAADwzwAAAAAAAAAAAAAAAAAAAAAAAAD3//0hEAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////wDIAAAAfAAAAAAAAB/8AAAAAAAAAAAAAAAA/////wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAwAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAA/////wAAAAAAPAAAAAAAAAAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAID3PwAAAMAAAAAAAAAAAAAAAwBECAAAYBAAAAAAAAAAAAAAAAAAAAAAAAAwAAAA//8DgAAAAADAPwAAgP8DAAAAAAAHAAAAAADIMwAAAAAgAAAAAAAAAAB+ZgAIEAAAAAAAEAAAAAAAAJ3BAgAAAAAwQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICEAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8AAP//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAMAHAAAAAAAAAAAAAAAAAAAAAG7wAAAAAACHAAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAPAAAAAAAAAAAD4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAAAAAAAAA/AAAAAAAAAAAwP8BAAAAAAA8AAAAAAAAAAAAAAAAAAAAAgAAAAAAAP9/AAAAAAAZgAMAAAAAAHgGBAAAAAAAAAAHAAAAgO8fAAAAAAAAAAgAAwAAAAAAwH8AngAAAAAAAAAAAAAAgNNAAgAAAAAAAAAAAAAAAAAAAAAAAID4BwAAAwAAAAAAABgBAAAAwB8fAAAAAAAAAAD4AUAFAAYAAAAAAAAAAAAA/1wAAEAAAAAAAAAAAAAA+IUNAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8sAEAADAAAAAAAAAAAAAA+KcBAAAAAAAAAAAAAAAAKL8AAAAAAAAAAAAAAACgvA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgP8GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFgIAAAAAAAAAAAAAAAAAAAAAADwDAEAAAD+BwAAAAD4eYAAfg4AAAAAAPx/AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf78AAAAAAAAAAAAA/P///G0AAAAAAAAAAAAAAAAAAAB+tL8AAAAAAAAAAACjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAAwAAAAAAwAcFAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//4H/PwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMD/4wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHwAAAAAAAAB/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAgAcAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGAPAAAAAAAAAAAAAAD//////z///38AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAD+P/nDwAAADwAAAAAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////9/+P//////HyAAEAAA+P7/AAAAAAAAAAAAAH////nbBwAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASMAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAADwDwAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAA////////////////AAAAAAAAAAAAAAAAAAAAAP///////////////////////////////////////wAA"]].map(function([t,n,r]){return[t,n.split(",").map(i=>parseInt(i,36)),Uint8Array.from(atob(r),i=>i.charCodeAt(0))]});function cv(e,t){return t===931||t===1010||t===120531||t===120589||t===120647||t===120705||t===120763?"\u03C3":t>=5112&&t<=5117?String.fromCodePoint(t-8):t>=43888&&t<=43967?String.fromCodePoint(t-38864):t>=93856&&t<=93880?String.fromCodePoint(t+27):t===837||t===890||t>=8064&&t<=8111||t>=8114&&t<=8188?e.normalize("NFD").replace(/\u0345/g,"\u03B9").normalize("NFC").toLowerCase():""}function kh(e,t){for(let n=0;n<e.length;n+=2)if(t>=e[n]&&t<=e[n+1])return!0;return!1}function No(e,t){let[n,r,i]=e,a=t>>8;for(let c=0;c<n.length;c+=2)if(a>=n[c]&&a<=n[c+1])return!0;let o=r.indexOf(a);if(o<0)return!1;let s=255&t;return!!(i[32*o+(s>>3)]&1<<(7&s))}function uv(e){let t=Array.from(e,n=>n.codePointAt(0));for(let n=0;n<t.length;n++){let r=t[n];if(r!==8204&&r!==8205||n>0&&kh(rv,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&No(vh,t[i]);)i--;let a=n+1;for(;a<t.length&&No(vh,t[a]);)a++;if(!(i>=0&&a<t.length&&No(av,t[i])&&No(sv,t[a])))return!1}return!0}var lv=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,dv=/\p{Script=Latin}/u;function pv(e){return!lv.test(e)||!dv.test(e)}var gr=36,fs=1,rl=26,mv=38,fv=700,gv=72,hv=128,yv=2147483647;function wh(e){return String.fromCharCode(e+22+75*+(e<26))}function Av(e,t,n){let r=0;for(e=n?Math.floor(e/fv):e>>1,e+=Math.floor(e/t);e>(gr-fs)*rl>>1;r+=gr)e=Math.floor(e/(gr-fs));return Math.floor(r+(gr-fs+1)*e/(e+mv))}function bv(e){let t=Array.from(e,c=>c.codePointAt(0)),n="",r=0;for(let c=0;c<t.length;c++){let u=t[c];u<128&&(n+=String.fromCharCode(u),r++)}let i=r;i&&(n+="-");let a=hv,o=0,s=gv;for(;r<t.length;){let c=yv;for(let u=0;u<t.length;u++){let l=t[u];l>=a&&l<c&&(c=l)}o+=(c-a)*(r+1),a=c;for(let u=0;u<t.length;u++){let l=t[u];if(l<a&&o++,l===a){let m=o;for(let f=gr;;f+=gr){let g=f<=s?fs:f>=s+rl?rl:f-s;if(m<g)break;n+=wh(g+(m-g)%(gr-g)),m=Math.floor((m-g)/(gr-g))}n+=wh(m),s=Av(o,r+1,r===i),o=0,r++}}o++,a++}return n}function Ju(e){let t=10;if(e.length>=2&&e[0]==="0"&&(e[1]==="x"||e[1]==="X"))e=e.slice(2),t=16;else if(e.length>=2&&e[0]==="0")e=e.slice(1),t=8;else if(e==="")return-1;let n=0;for(let r=0;r<e.length;r++){let i=Xu(e.charCodeAt(r));if(i>=t||i<0)return-1;n=n*t+i}return n}function Oh(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function jh(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function Th(e){return e.length===2&&jh(e.codePointAt(0),e.codePointAt(1))}function Ph(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function ht(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function Nh(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function il(e,t){if(e[0]==="[")return e[e.length-1]==="]"?(function(r){let i=[0,0,0,0,0,0,0,0],a=null,o=0,s=0,c=Array.from(r,u=>u.codePointAt(0));if(c[s]===58){if(c[s+1]!==58)return null;s+=2,o++,a=o}for(;s<c.length;){if(o===8)return null;if(c[s]===58){if(a!==null)return null;s++,o++,a=o;continue}let u=0,l=0,m=0;for(;m<4&&(u=Xu(c[s]))>=0;)l=(l<<4)+u,s++,m++;if(c[s]===46){if(m===0||o>6)return null;s-=m;let f=0;for(;c[s]!==void 0;){let g=0;if(f>0)if(c[s]===46&&f<4)s++;else return null;if(c[s]==null||c[s]<48||c[s]>57)return null;for(;c[s]>=48&&c[s]<=57;){if(g=10*g+Xu(c[s]),g>255)return null;s++}i[o]=256*i[o]+g,f++,f%2==0&&o++}if(f!==4)return null;break}else if(c[s]===58){if(c[++s]===void 0)return null}else if(c[s]!==void 0)return null;i[o]=l,o++}if(a!==null){let u=o-a;for(o=7;o!==0&&u>0;){let l=i[a+u-1];i[a+u-1]=i[o],i[o]=l,o--,u--}}else if(a===null&&o!==8)return null;return i})(e.substring(1,e.length-1)):null;if(t)return(function(r){return Ph(r)?null:Vn(r,Fo)})(e);{let n=(function(i){let a=!1,o=!1;for(let c=0;c<i.length;c++){let u=i.charCodeAt(c);if(u<=32||u===37||u===127)return null;if(u>=128){a=!0;break}u>=65&&u<=90&&(o=!0)}if(!a)return i!==""?o?i.toLowerCase():i:null;if((function(u){for(let l of u){let m=l.codePointAt(0);if(/[\p{Cn}\p{Co}\p{Cs}\p{Noncharacter_Code_Point}]/u.test(l)&&!kh(ev,m)||No(ov,m))return!0}return!1})(i))return null;let s=(i=(function(u){let l="";for(let m of u){let f=m.codePointAt(0);if(f!==8204&&f!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(m))continue;let g=cv(m,f);if(g){l+=g;continue}let d=tv.indexOf(f);l+=d<0?m:nv[d]}return l})(i).normalize("NFKC").replace(/[\u3002\uff0e\uff61]/g,".").toLowerCase()).split(".");for(let c=0;c<s.length;c++){let u=s[c];if(u==="")continue;let l=/[^\0-\x7f]/.test(u);if(iv(u)||l&&(/^\p{Mark}/u.test(u)||!uv(u)||!pv(u)||u.startsWith("xn--")))return null;l&&(s[c]=`xn--${bv(u)}`)}return(i=s.join("."))!==""?i:null})(e.indexOf("%")===-1?e:el(e));return n===null||Ph(n)?null:(function(i){let a=i.length,o=i.lastIndexOf(".",a-2)+1;if(i.charCodeAt(a-1)===46&&a--,a<=o)return!1;if(Ju(i.slice(o,a))>=0)return!0;for(;o<a;o++){let s=i.charCodeAt(o);if(s<48||s>57)return!1}return!0})(n)?(function(i){let a=i.split("."),o=a.length;if(a[o-1]||o--,o>4)return null;let s=0;for(let u=0;u<o-1;u++){let l=Ju(a[u]);if(l<0||l>255)return null;s+=l*(1<<8*(3-u))}let c=Ju(a[o-1]);return c<0||c>=256**(5-o)?null:(s+=c,s)})(n):n}}function ol(e){return typeof e=="number"?(function(n){let i="";return i+=`${(n>>>24&255).toString(10)}.`,i+=`${(n>>>16&255).toString(10)}.`,i+=`${(n>>>8&255).toString(10)}.`,i+=(n&255).toString(10),i})(e):Array.isArray(e)?`[${(function(n){let r=(function(s){let c=-1,u=-1,l=1,m=0;for(let f=0;f<s.length;++f)s[f]!==0?(m>l&&(c=u,l=m),u=-1,m=0):(u===-1&&(u=f),++m);return m>l?u:c})(n),i="",a=!1;for(let o=0;o<=7;++o)if(!(a&&n[o]===0)){if(a&&(a=!1),r===o){i+=o===0?"::":":",a=!0;continue}i+=n[o].toString(16),o!==7&&(i+=":")}return i})(e)}]`:e}function Dh(e){e.path.length>0&&(e.path.length!==1||e.scheme!=="file"||!(function(n){return/^[A-Za-z]:$/u.test(n)})(e.path[0]))&&e.path.pop()}function Fh(e){return e.username!==""||e.password!==""}function Zu(e){return e.host===null||e.host===""||e.scheme==="file"}var E=0,U="",Pe="",$e=null,B,gs=!1,hs=!1,Xr=!1,yt;function hn(e,t,n,r){t||(e=(function(o){let s=0,c=o.length;for(;s<c&&!(o.charCodeAt(s)>32);++s);for(;c>s&&!(o.charCodeAt(c-1)>32);--c);return o.substring(s,c)})(e)),e=(function(o){let s=0;for(;s<o.length;s++){let u=o.charCodeAt(s);if(u===9||u===10||u===13)break}if(s===o.length)return o;let c=o.slice(0,s);for(;s<o.length;s++){let u=o.charCodeAt(s);u!==9&&u!==10&&u!==13&&(c+=o[s])}return c})(e),E=0,U=e,Pe="",$e=n||null,B=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},gs=!1,hs=!1,Xr=!1,yt=r||0;let i=xv;switch(r){case 3:case 4:i=As;break;case 5:i=ll;break;case 6:i=ei;break;case 7:i=hr;break;case 8:i=Ln}return i(G(e,E))!==1?B:null}function ne(e,t){return E+=E===e?Tn(t):1,E<=U.length}function G(e,t){return t<e.length?e.codePointAt(t):void 0}function Tn(e){return e!=null&&e>65535?2:1}function Mh(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var xv=e=>{let t=E;if(e!=null&&(e>=65&&e<=90||e>=97&&e<=122)){let n=E+1;for(e=U.charCodeAt(n);e===43||e===45||e===46||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57;)n++,e=U.charCodeAt(n);return Pe=U.slice(E,n).toLowerCase(),E=n,Sv(n<U.length?e:void 0)}else return yt?1:(--E,ne(t,e)?qh(G(U,E)):0)},Sv=e=>{let t=E;if(e===58){if(yt){if(ht(B.scheme)!==ht(Pe))return 0;if((Fh(B)||B.port!==null)&&Pe==="file")return 0;if(B.scheme==="file"&&B.host==="")return 0}return B.scheme=Pe,yt?(B.port===Nh(B.scheme)&&(B.port=null),0):(Pe="",B.scheme==="file"?ne(t,e)?dl(G(U,E)):0:ht(B.scheme)&&$e!==null&&$e.scheme===B.scheme?ne(t,e)?Iv(G(U,E)):0:ht(B.scheme)?ne(t,e)?wv(G(U,E)):0:G(U,E+1)===47?(E++,ne(t,e)?vv(G(U,E)):0):(B.path=[""],B.opaquePath=!0,ne(t,e)?Bh(G(U,E)):0))}else return yt?1:(Pe="",E=-1,ne(t,e)?qh(G(U,E)):0)},qh=e=>{let t=E;return $e===null||$e.opaquePath&&e!==35?1:$e.opaquePath&&e===35?(B.scheme=$e.scheme,B.path=$e.path.slice(),B.opaquePath=$e.opaquePath,B.query=$e.query,B.fragment="",ne(t,e)?Ln(G(U,E)):0):$e.scheme==="file"?(E--,ne(t,e)?dl(G(U,E)):0):(E--,ne(t,e)?ul(G(U,E)):0)},Iv=e=>{let t=E;return e===47&&G(U,E+1)===47?(++E,ne(t,e)?xs(G(U,E)):0):(E--,ne(t,e)?ul(G(U,E)):0)},vv=e=>{let t=E;return e===47?ne(t,e)?Di(G(U,E)):0:(E--,ne(t,e)?Nn(G(U,E)):0)},ul=e=>{let t=E;return B.scheme=$e.scheme,e===47||ht(B.scheme)&&e===92?ne(t,e)?Ch(G(U,E)):0:(B.username=$e.username,B.password=$e.password,B.host=$e.host,B.port=$e.port,B.path=$e.path.slice(),B.query=$e.query,e===63?(B.query="",ne(t,e)?hr(G(U,E)):0):e===35?(B.fragment="",ne(t,e)?Ln(G(U,E)):0):e!=null?(B.query=null,B.path.pop(),E--,ne(t,e)?Nn(G(U,E)):0):ne(t,e)?ul(G(U,E)):0)},Ch=e=>{let t=E;return ht(B.scheme)&&(e===47||e===92)?ne(t,e)?xs(G(U,E)):0:e===47?ne(t,e)?Di(G(U,E)):0:(B.username=$e.username,B.password=$e.password,B.host=$e.host,B.port=$e.port,E--,ne(t,e)?Nn(G(U,E)):0)},wv=e=>{let t=E;return e===47&&G(U,E+1)===47?E++:E--,ne(t,e)?xs(G(U,E)):0},xs=e=>{let t=E;return e!==47&&e!==92?(E--,ne(t,e)?Di(G(U,E)):0):ne(t,e)?xs(G(U,E)):0},Di=e=>{let t=E;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!ht(B.scheme))){let n=E+Tn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===64||r===35||r===47||r===63||r===92&&ht(B.scheme))break;n+=Tn(r)}return Pe+=U.slice(E,n),E=n-1,ne(t,e)?Di(G(U,E)):0}if(e===64){gs&&(Pe=`%40${Pe}`),gs=!0;for(let n=0;n<Pe.length;n++){let r=Pe.codePointAt(n);if(r===58&&!hs){hs=!0;continue}let i=Rh(r,ys);hs?B.password+=i:B.username+=i,r!=null&&r>65535&&n++}return Pe="",ne(t,e)?Di(G(U,E)):0}else return e==null||e===35||e===47||e===63||e===92&&ht(B.scheme)?gs&&Pe===""?1:(E-=Pe.length+1,Pe="",ne(t,e)?As(G(U,E)):0):(Pe+=Mh(e),ne(t,e)?Di(G(U,E)):0)},As=e=>{let t=E;if(yt&&B.scheme==="file")return E--,ne(t,e)?pl(G(U,E)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!ht(B.scheme))){let n=E+Tn(e);for(e===91?Xr=!0:e===93&&(Xr=!1);n<U.length;){let r=G(U,n);if(r==null||!Xr&&r===58||r===35||r===47||r===63||r===92&&ht(B.scheme))break;r===91?Xr=!0:r===93&&(Xr=!1),n+=Tn(r)}return Pe+=U.slice(E,n),E=n-1,ne(t,e)?As(G(U,E)):0}else if(e===58&&!Xr){if(Pe===""||yt===4)return 1;let n=il(Pe,!ht(B.scheme));return n===null?1:(B.host=ol(n),Pe="",ne(t,e)?ll(G(U,E)):0)}else if(e==null||e===35||e===47||e===63||e===92&&ht(B.scheme)){if(E--,ht(B.scheme)&&Pe==="")return 1;if(yt&&Pe===""&&(Fh(B)||B.port!==null))return 1;let n=il(Pe,!ht(B.scheme));return n===null?1:(B.host=ol(n),Pe="",yt?0:ne(t,e)?ei(G(U,E)):0)}else return Pe+=Mh(e),ne(t,e)?As(G(U,E)):0},ll=e=>{let t=E;if(e!=null&&e>=48&&e<=57){let n=E+1;for(;n<U.length;){let r=U.charCodeAt(n);if(r<48||r>57)break;n++}return Pe+=U.slice(E,n),E=n-1,ne(t,e)?ll(G(U,E)):0}else if(yt||e==null||e===35||e===47||e===63||e===92&&ht(B.scheme)){if(Pe!==""){let n=parseInt(Pe,10);if(n>65535)return 1;if(B.port=n===Nh(B.scheme)?null:n,Pe="",yt)return 0}return yt?1:(E--,ne(t,e)?ei(G(U,E)):0)}else return 1};function Uh(e,t){let n=e.length-t;if(n<2)return!1;if(jh(G(e,t),G(e,t+1))){if(n===2)return!0;{let r=G(e,t+2);return r===47||r===92||r===63||r===35}}else return!1}var dl=e=>{let t=E;return B.scheme="file",B.host="",e===47||e===92?ne(t,e)?Ov(G(U,E)):0:$e?.scheme==="file"?(B.host=$e.host,B.path=$e.path.slice(),B.opaquePath=$e.opaquePath,B.query=$e.query,e===63?(B.query="",ne(t,e)?hr(G(U,E)):0):e===35?(B.fragment="",ne(t,e)?Ln(G(U,E)):0):e!=null?(B.query=null,Uh(U,E)?B.path=[]:Dh(B),E--,ne(t,e)?Nn(G(U,E)):0):ne(t,e)?dl(G(U,E)):0):(E--,ne(t,e)?Nn(G(U,E)):0)},Ov=e=>{let t=E;return e===47||e===92?ne(t,e)?pl(G(U,E)):0:($e!==null&&$e.scheme==="file"&&(!Uh(U,E)&&(function(r){if(r.length===2){let i=r.codePointAt(0),a=r.codePointAt(1);return(i>=65&&i<=90||i>=97&&i<=122)&&a===58}else return!1})($e.path[0])&&B.path.push($e.path[0]),B.host=$e.host),E--,ne(t,e)?Nn(G(U,E)):0)},pl=e=>{let t=E;if(e!=null&&e!==47&&e!==92&&e!==63&&e!==35){let n=E+Tn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===47||r===92||r===63||r===35)break;n+=Tn(r)}return Pe+=U.slice(E,n),E=n-1,ne(t,e)?pl(G(U,E)):0}else if(e==null||e===47||e===92||e===63||e===35){if(E--,!yt&&Th(Pe))return ne(t,e)?Nn(G(U,E)):0;if(Pe==="")return B.host="",yt?0:ne(t,e)?ei(G(U,E)):0;{let n=il(Pe,!ht(B.scheme));return n===null?1:(n==="localhost"&&(n=""),B.host=ol(n),Pe="",yt?0:ne(t,e)?ei(G(U,E)):0)}}return 1},ei=e=>{let t=E;return ht(B.scheme)?(e!==92&&e!==47&&E--,ne(t,e)?Nn(G(U,E)):0):!yt&&e===63?(B.query="",ne(t,e)?hr(G(U,E)):0):!yt&&e===35?(B.fragment="",ne(t,e)?Ln(G(U,E)):0):e!=null?(e!==47&&E--,ne(t,e)?Nn(G(U,E)):0):(yt&&B.host===null&&B.path.push(""),ne(t,e)?ei(G(U,E)):0)},Nn=e=>{let t=E;if(e!=null&&e!==47&&(!ht(B.scheme)||e!==92)&&(yt||e!==63&&e!==35)){let n=E+Tn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===47||ht(B.scheme)&&r===92||!yt&&(r===63||r===35))break;n+=Tn(r)}Pe+=Vn(U.slice(E,n),tl),E=n,e=G(U,n)}if(e==null||e===47||ht(B.scheme)&&e===92||!yt&&(e===63||e===35)){let n=ht(B.scheme)&&e===92;return(function(i){switch(i){case"..":case"%2e.":case"%2E.":case".%2e":case".%2E":case"%2e%2e":case"%2E%2e":case"%2e%2E":case"%2E%2E":return!0;default:return!1}})(Pe)?(Dh(B),e!==47&&!n&&B.path.push("")):Oh(Pe)&&e!==47&&!n?B.path.push(""):Oh(Pe)||(B.scheme==="file"&&B.path.length===0&&Th(Pe)&&(Pe=`${Pe[0]}:`),B.path.push(Pe)),Pe="",e===63?(B.query="",ne(t,e)?hr(G(U,E)):0):e===35?(B.fragment="",ne(t,e)?Ln(G(U,E)):0):ne(t,e)?Nn(G(U,E)):0}else return Pe+=Rh(e,tl),ne(t,e)?Nn(G(U,E)):0},Bh=e=>{let t=E;if(e===63)return B.query="",ne(t,e)?hr(G(U,E)):0;if(e===35)return B.fragment="",ne(t,e)?Ln(G(U,E)):0;if(e!=null){let n=E+Tn(e);for(;n<U.length;){let i=G(U,n);if(i===63||i===35)break;n+=Tn(i)}let r=U.slice(E,n);if(n<U.length&&r.charCodeAt(r.length-1)===32?B.path[0]+=Vn(r.slice(0,-1),Fo)+"%20":B.path[0]+=Vn(r,Fo),E=n,(e=G(U,n))===63)return B.query="",ne(t,e)?hr(G(U,E)):0;if(e===35)return B.fragment="",ne(t,e)?Ln(G(U,E)):0}return ne(t,e)?Bh(G(U,E)):0},hr=e=>{let t=E,n=E;if(e!=null){if(yt)n=U.length;else{let i=U.indexOf("#",E);n=i===-1?U.length:i}let r=ht(B.scheme)?XI:sl;B.query+=Vn(U.slice(E,n),r)}return E=n,G(U,n)===35&&!yt?(B.fragment="",ne(t,e)?Ln(G(U,E)):0):ne(t,e)?hr(G(U,E)):0},Ln=e=>{let t=E;return e!=null&&(B.fragment+=Vn(U.slice(E),YI),E=U.length),ne(t,e)?Ln(G(U,E)):0};function al(e){if(e.opaquePath)return e.path[0];{let t="";for(let n of e.path)t+=`/${n}`;return t}}function Vh(e){switch(e.scheme){case"blob":{let t=hn(al(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":Vh(t)}case"ftp":case"http":case"https":case"ws":case"wss":return(function(n){let r=`${n.scheme}://`;return r+=n.host,n.port!==null&&(r+=`:${n.port}`),r})(e);default:return"null"}}var He=Symbol("URLImpl"),In=class e{constructor(t,n){if(t===void 0&&n===void 0)throw new TypeError('The "url" argument must be specified.');t=Qe(t),n!=null&&(n=Qe(n));let r=null;if(n!=null&&(r=hn(n,null,null,0),r==null))throw new TypeError(`Invalid base URL: ${n}`);let i=hn(t,null,r,0);if(i==null)throw new TypeError(`Invalid URL: ${t}`);this[He]={url:i,query:null}}static createObjectURL(t){throw new TypeError("URL.createObjetURL is unsupported")}static revokeObjectURL(t){}static parse(t,n){t=Qe(t),n!==void 0&&(n=Qe(n));try{return new e(t,n)}catch{return null}}static canParse(t,n){t=Qe(t),n!==void 0&&(n=Qe(n));let r=null;return n!=null&&(r=hn(n,null,null,0),r==null)?!1:hn(t,null,r,0)!=null}get href(){return(function(n){let r=`${n.scheme}:`;return n.host!==null&&(r+="//",(n.username!==""||n.password!=="")&&(r+=n.username,n.password!==""&&(r+=`:${n.password}`),r+="@"),r+=n.host,n.port!==null&&(r+=`:${n.port}`)),n.host===null&&!n.opaquePath&&n.path.length>1&&n.path[0]===""&&(r+="/."),r+=al(n),n.query!==null&&(r+=`?${n.query}`),n.fragment!==null&&(r+=`#${n.fragment}`),r})(this[He].url)}set href(t){let n=hn(t=Qe(t),null,null,0);if(n==null)throw new TypeError(`Invalid URL: ${t}`);this[He].url=n,this[He].query&&Wu(this[He].query,n.query)}get origin(){return Vh(this[He].url)}get protocol(){return`${this[He].url.scheme}:`}set protocol(t){hn(`${t=Qe(t)}:`,this[He].url,null,2)}get username(){return this[He].url.username}set username(t){t=Qe(t),Zu(this[He].url)||(function(r,i){r.username=Vn(i,ys)})(this[He].url,t)}get password(){return this[He].url.password}set password(t){t=Qe(t),Zu(this[He].url)||(function(r,i){r.password=Vn(i,ys)})(this[He].url,t)}get host(){let{url:t}=this[He];return t.host==null?"":t.port==null?t.host:`${t.host}:${t.port}`}set host(t){t=Qe(t),this[He].url.opaquePath||hn(t,this[He].url,null,3)}get hostname(){let{url:t}=this[He];return t.host!=null?t.host:""}set hostname(t){t=Qe(t),this[He].url.opaquePath||hn(t,this[He].url,null,4)}get port(){let{url:t}=this[He];return t.port!=null?`${t.port}`:""}set port(t){t=Qe(t);let{url:n}=this[He];Zu(n)||(t?hn(t,n,null,5):n.port=null)}get pathname(){return al(this[He].url)}set pathname(t){t=Qe(t);let{url:n}=this[He];n.opaquePath||(n.path=[],hn(t,n,null,6))}get search(){let{url:t}=this[He];return t.query?`?${t.query}`:""}set search(t){t=Qe(t);let{url:n,query:r}=this[He];if(!t)n.query=null,r&&Wu(r,null);else{let i=t[0]==="?"?t.substring(1):t;n.query="",hn(i,n,null,7),r&&Wu(r,n.query)}}get searchParams(){let t=this[He],n=t.query;return n==null&&(n=t.query=(function(i,a){let o=new bs;return o[ut].url=i,o[ut].serialized=a==null,a&&(o[ut].list=cl(a)),o})(this,t.url.query)),n}get hash(){let{url:t}=this[He];return t.fragment?`#${t.fragment}`:""}set hash(t){t=Qe(t);let{url:n}=this[He];if(!t)n.fragment=null;else{let r=t[0]==="#"?t.substring(1):t;n.fragment="",hn(r,n,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(In.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var ut=Symbol("URLSearchParamsImpl"),Pv=Symbol.dispose||Symbol.for("dispose");function Wu(e,t){t?e[ut].list=cl(t):e[ut].list.length=0,e[ut].serialized=t==null}function ms(e){if(e.url){let t=nl(e.list);(function(r,i){r[He].url.query=i})(e.url,t||null),e.serialized=!0}}var Cv=typeof Iterator<"u"?Iterator:Object,Do=class extends Cv{constructor(t,n){super(),this[ut]={ptr:t,map:n,index:0}}next(){let t=this[ut];return t.index<t.ptr.list.length?{value:t.map(t.ptr.list[t.index++]),done:!1}:{value:void 0,done:!0}}[Symbol.iterator](){return this}[Pv](){}},bs=class{constructor(t){let n=this[ut]={list:[],url:null,serialized:!0},r;if(Array.isArray(t))for(let i=0;i<t.length;i++)n.list.push(xh(t[i]));else if((r=_h(t))!=null){let i;for(;!(i=Yu(r.next())).done;)n.list.push(xh(i.value))}else if((typeof t=="object"||typeof t=="function")&&t!=null){let i=Object.keys(t);for(let a=0;a<i.length;a++){let o=i[a],s=ZI(o),c=Qe(t[o]),u=n.list.find(l=>l[0]===s);u?u[1]=c:n.list.push([s,c])}}else if(t!==void 0){let i=Qe(t);i=i[0]==="?"?i.substring(1):i,n.list=cl(i)}}get size(){return this[ut].list.length}append(t,n){t=Qe(t),n=Qe(n),this[ut].list.push([t,n]);let r=this[ut];r.url&&r.serialized?(function(a,o){let s=a[He].url;s.query=s.query?`${s.query}&${o}`:o})(r.url,nl([[t,n]])):ms(r)}delete(t,n){t=Qe(t),n=n!=null?Qe(n):void 0;let{list:r}=this[ut],i=0;for(;i<r.length;)r[i][0]===t&&(n==null||r[i][1]===n)?r.splice(i,1):i++;ms(this[ut])}get(t){t=Qe(t);let{list:n}=this[ut];for(let r=0;r<n.length;r++)if(n[r][0]===t)return n[r][1];return null}getAll(t){t=Qe(t);let n=[],{list:r}=this[ut];for(let i=0;i<r.length;i++)r[i][0]===t&&n.push(r[i][1]);return n}has(t,n){t=Qe(t),n=n!=null?Qe(n):void 0;let{list:r}=this[ut];for(let i=0;i<r.length;i++)if(r[i][0]===t&&(n==null||r[i][1]===n))return!0;return!1}set(t,n){t=Qe(t),n=Qe(n);let{list:r}=this[ut],i=!1,a=!1,o=0;for(;o<r.length;)r[o][0]===t?i?(r.splice(o,1),a=!0):(i=!0,r[o][1]!==n&&(r[o][1]=n,a=!0),o++):o++;i||(r.push([t,n]),a=!0),a&&ms(this[ut])}sort(){this[ut].list.sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0),ms(this[ut])}forEach(t,n){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:r}=this[ut];for(let i=0;i<r.length;i++)t.call(n,r[i][1],r[i][0],this)}entries(){return new Do(this[ut],t=>t)}keys(){return new Do(this[ut],t=>t[0])}values(){return new Do(this[ut],t=>t[1])}toString(){return nl(this[ut].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(bs.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var yr="https://api.longplayai.com";function Lh(e){let t,n=()=>typeof t=="string"?t:t?.accessToken,r=0,i,a=new Map,o=()=>{for(let m of[...a.keys()])try{m()}catch{}};function s(m){let f=++r;i=void 0,t=void 0;for(let g of[...a.values()])try{g?.()}catch{}f===r&&(t=m,o())}let c=()=>s();function u(m,f=!1){let g=Xn.safeParse(m);if(!g.success||f&&Date.parse(g.data.expiresAt)<=Date.now()||Date.parse(g.data.refreshExpiresAt)<=Date.now()||Date.parse(g.data.refreshExpiresAt)<Date.parse(g.data.expiresAt))throw new b("INVALID_RESPONSE","Invalid customer session credentials");return g.data}async function l(){if(i)return i;let m=typeof t=="object"?t:void 0,f=r;if(!m||Date.parse(m.refreshExpiresAt)<=Date.now())throw m&&c(),new b("UNAUTHENTICATED","Customer authentication is required",401);let g=(async()=>{try{let d=await e(m.refreshToken);if(f!==r)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");let h=u(d,!0);if(h.customerId!==m.customerId||h.sessionId!==m.sessionId)throw new b("SCOPE_MISMATCH","Refresh changed the customer session");return t=h,{...h}}catch(d){throw f!==r?new b("IDENTITY_CHANGED","Customer identity changed during refresh"):(d instanceof b&&d.status===401&&c(),d)}})();i=g;try{return await g}finally{i===g&&(i=void 0)}}return{identify(m){let f=typeof m=="string"?m:u(m),g=typeof f=="string"?f:f.accessToken;if(!g.trim()||/\s/.test(g)||g.length>4096)throw new b("INVALID_TOKEN","A server-issued token is required");s(f)},reset:c,subscribeIdentity(m,f){return a.set(m,f),()=>{a.delete(m)}},access(){let m=typeof t=="object"?t:void 0;if(m&&Date.parse(m.expiresAt)<=Date.now()+3e4){let g=r;return l().then(()=>{let d=n();if(g!==r||!d)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");return d})}let f=n();if(!f)throw new b("NOT_IDENTIFIED","Identify a customer session before making a request");return f},peek:n,snapshot:()=>typeof t=="object"?{...t}:void 0,refresh:l}}var zh=Symbol("IndianaNoContent");function Ar(e,t,n=In){let r=e.configuration?.scope,i=e.scope??(r&&{projectId:r.projectId,environment:r.environment}),a=i?Fe.parse(i):void 0;if(a&&r&&(a.projectId!==r.projectId||a.environment!==r.environment))throw new b("SCOPE_MISMATCH","Configuration belongs to another App/environment");let o=new n(e.baseUrl??yr);if(o.username||o.password||o.search||o.hash)throw new b("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(o.protocol!=="https:"&&!(o.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(o.hostname)))throw new b("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let s=e.fetch??globalThis.fetch.bind(globalThis),c=e.timeoutMs??1e4;if(!Number.isFinite(c)||c<1||c>12e4)throw new b("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let u=!1,l=0,m=null,f=new Set,g=e.session??Lh(async A=>{let x=await y("customer-sessions/refresh",{},"POST",{},A);if(!x||typeof x!="object")throw new b("INVALID_RESPONSE","Invalid refresh response");let{requestId:v,scope:P,...j}=x;return j});function d(){l+=1,m=null;for(let A of f)A.abort();f.clear()}let h=g.subscribeIdentity(d);function R(){u||g.reset()}async function y(A,x={},v="POST",P={},j){let _=P.installationDetach===!0;if(_&&(A!=="push/installations/detach"||v!=="POST"))throw new b("INVALID_REQUEST","Installation authority only detaches this installation");if(!j&&!_)throw new b("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let X=l,le=new AbortController;_||f.add(le);let he=()=>!_&&X!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new b("TIMEOUT","Longplay request timed out"),ke,Se=new Promise((De,rt)=>{ke=()=>rt(he()),le.signal.addEventListener("abort",ke,{once:!0})}),At=setTimeout(()=>le.abort(),P.timeoutMs??c),We=async()=>{let De=await s(`${o.href.replace(/\/$/,"")}/api/v1/${A}`,{method:v,headers:{...P.headers,"Content-Type":"application/json",..._?{}:{Authorization:`Bearer ${j}`},[Ns]:Ds.current,[Tl]:bh.version,...a?{"X-Indiana-Project":a.projectId,"X-Indiana-Environment":a.environment}:{}},body:v==="POST"?JSON.stringify(x):void 0,signal:le.signal,credentials:"omit",cache:"no-store",redirect:"error",...P.keepalive?{keepalive:!0}:{}});if(le.signal.aborted)throw he();let rt;try{rt=De.status===204?zh:await De.json()}catch{throw le.signal.aborted?he():new b(De.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",De.status,De.headers.get("X-Request-Id")??void 0)}if(le.signal.aborted)throw he();if(!_&&X!==l)throw new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!De.ok){let mt=Ts.safeParse(rt),Qt=mt.success&&(!Gn.safeParse(mt.data.error.code).success||kl(mt.data.error.code,De.status)),Ir=Qt?mt.data.error.code:"HTTP_ERROR",vr=$o(Ir,De.status,{retryAfter:De.headers.get("Retry-After"),recovery:Qt?mt.data.error.recovery:void 0,reason:Qt?mt.data.error.reason:void 0});throw new b(Ir,Qt?mt.data.error.message:"Longplay request failed",De.status,De.headers.get("X-Request-Id")??(mt.success?mt.data.requestId:void 0),{...vr,...mt.success&&mt.data.error.retryable===!1?{retryable:!1}:{},...vr.retryAfterSeconds===void 0&&mt.success&&mt.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:mt.data.error.retryAfterSeconds}:{}})}if(De.headers.get(Ns)!==Ds.current)throw new b("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&rt!==zh){let mt=rt&&typeof rt=="object"&&"scope"in rt?rt:rt&&typeof rt=="object"&&"configuration"in rt?rt.configuration:null;if(!mt||typeof mt!="object"||!("scope"in mt))throw new b("INVALID_RESPONSE","Response is missing its App/environment scope");let Qt=Fe.safeParse(mt.scope);if(!Qt.success||Qt.data.projectId!==a.projectId||Qt.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let ni=De.headers.get("X-Indiana-Telemetry-Subject");if(ni){if(!/^[a-f0-9]{64}$/.test(ni))throw new b("INVALID_RESPONSE","Invalid telemetry identity");m!==ni&&(m=ni,t?.(m))}return rt};try{return await Promise.race([We(),Se])}catch(De){throw!_&&X!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):De instanceof b?De:new b(le.signal.aborted?"TIMEOUT":"NETWORK_ERROR",le.signal.aborted?"Longplay request timed out":"Unable to read the Longplay response")}finally{clearTimeout(At),le.signal.removeEventListener("abort",ke),f.delete(le)}}return{session:g,requestWithCredential(A,x,v,P={}){return u?Promise.reject(new b("CLOSED","SDK client was destroyed")):y(A,x,"POST",P,v)},subjectKey:()=>m,identify(A){if(u)throw new b("CLOSED","SDK client was destroyed");if(a&&typeof A=="object"&&"scope"in A){let x=Fe.safeParse(A.scope);if(!x.success||x.data.projectId!==a.projectId||x.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Customer session belongs to another App/environment")}g.identify(A)},reset:R,dispose(){u||(u=!0,h(),d())},request(A,x={},v="POST",P={}){if(u)return Promise.reject(new b("CLOSED","SDK client was destroyed"));if(P.installationDetach)return y(A,x,v,P);let j=l;try{let _=g.access(),X=le=>{if(j!==l)throw new b("IDENTITY_CHANGED","Customer identity changed before dispatch");return y(A,x,v,P,le)};return typeof _=="string"?X(_):_.then(X)}catch(_){return Promise.reject(_)}}}}function $h(e,t,n={}){let r=!1;function i(){if(r)throw new b("CLOSED","SDK client was destroyed")}let a=new Set,o=c=>{for(let u of a)try{u(c)}catch{}},s=e.session.subscribeIdentity(()=>{o(!!e.session.peek()),n.afterChange?.()},()=>{t()});return{assertActive:i,isIdentified:()=>!r&&!!e.session.peek(),methods:{subscribeIdentity(c){return i(),a.add(c),()=>{a.delete(c)}},identify(c){i();let u=typeof c=="string"?c:c.accessToken;if(!Nt.test(u))throw new b("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(u),e.identify(c)},reset(){if(!r)try{n.beforeReset?.()}finally{e.reset()}},destroy(){if(!r){r=!0,s(),a.clear();try{n.beforeDestroy?.(),t()}finally{e.dispose()}}}}}}function Ge(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new b("INVALID_REQUEST","Customer requests use the verified session identity")}var _v={...O.readHoldings,request:O.readHoldings.request.omit({customerId:!0})};function Gh(e){return{async checkEntitlement(t){Ge(t);let n=O.checkEntitlement;return ge(e,n,t)},async readHoldings(t={}){return ge(e,_v,t)}}}function Kh(e){return{async readLedger(t){let n=O.readLedger;return ge(e,n,{query:t})},async readCreditStatement(t){Ge(t);let n=O.readCreditStatement;return ge(e,n,t)},async quoteBalance(t){Ge(t);let n=O.quoteBalance;return ge(e,n,{command:t})}}}function Hh(e){return{async setupPayment(t){Ge(t);let n=O.setupPayment;return ge(e,n,t)},async readPaymentSetup(t){Ge(t);let n=O.readPaymentSetup;return ge(e,n,t)},async readBillingInvoice(t){Ge(t);let n=O.readBillingInvoice;return ge(e,n,t)},async readBillingControls(t={}){Ge(t);let n=O.readBillingControls;return ge(e,n,t)},async prepareBillingAuthorization(t){Ge(t);let n=O.prepareBillingAuthorization;return ge(e,n,t)},async confirmBillingAuthorization(t){Ge(t);let n=O.confirmBillingAuthorization;return ge(e,n,t)},async setBillingCoupons(t){Ge(t);let n=O.setBillingCoupons;return ge(e,n,t,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(t){Ge(t);let n=O.revokeBillingAuthorization;return ge(e,n,t)},async listBillingInvoices(t={after:null,limit:25}){Ge(t);let n=O.listBillingInvoices;return ge(e,n,t)},async confirmBillingAdjustment(t){Ge(t);let n=O.confirmBillingAdjustment;return ge(e,n,t)}}}function Qh(e){return{async previewUpdate(t){Ge(t);let n=O.previewUpdate;return ge(e,n,t)},async update(t){Ge(t);let n=O.update;return ge(e,n,t)},async readSubscriptionUpdate(t){Ge(t);let n=O.readSubscriptionUpdate;return ge(e,n,t)},async restoreNativePurchase(t){Ge(t);let n=O.restoreNativePurchase;return ge(e,n,t)},async previewAttach(t){Ge(t);let n=O.previewAttach;return ge(e,n,t)},async attach(t){Ge(t);let n=O.attach;return ge(e,n,t)},async readSubscriptionOperation(t){Ge(t);let n=O.readSubscriptionOperation;return ge(e,n,t)}}}function Jh(e){return{async redeemReward(t){return Ge(t),(await ge(e,O.redeemReward,{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(t){return Ge(t),(await ge(e,O.claimRewardProduct,t,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(t){return Ge(t),(await ge(e,O.createReferralCode,{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(t,n=crypto.randomUUID()){let r=await ge(e,O.redeemCoupon,{code:t,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(t,n=crypto.randomUUID()){let r=await ge(e,O.grantOffer,{couponId:t,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await ge(e,O.listOffers,{},{response:"Invalid offers response"})).offers}}}function Zh(e){return{...Gh(e),...Kh(e),...Hh(e),...Qh(e),...Jh(e)}}function Wh(e){return{async resolveContent(t){Ge(t);let n=O.resolveContent;return ge(e,n,t)},async resolvePaywall(t){Ge(t);let n=O.resolvePaywall;return ge(e,n,t)},async resolveOffering(t){Ge(t);let n=O.resolveOffering;return ge(e,n,t)}}}var ml=e=>new TextEncoder().encode(JSON.stringify(e)).length,Yh=16384;function Xh(e,t){let n=0,r,i=d=>{r={config:structuredClone(d),until:Date.now()+3e4}},a=[],o=null,s;function c(){if(!t())throw new b("NOT_IDENTIFIED","Call identify before using Features or events")}function u(){s||!a.length||(s=setTimeout(()=>{s=void 0,m().catch(()=>{}).finally(u)},5e3),typeof s=="object"&&"unref"in s&&s.unref())}function l(d,h={},R={}){if(c(),r&&Date.now()<r.until&&!cf(r.config,d))return;g();let y=O.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:d,properties:h,...R}]}).events[0];if(ml({events:[y]})>Yh)throw new b("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new b("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(y)),u()}async function m(d=!1){if(c(),o)return o;let h=n,R=(async()=>{let y={inserted:0,duplicates:0,rejected:0,skipped:0},A=a.length;for(;A&&h===n;){let x=[],v=ml({events:[]});for(let _ of a.slice(0,Math.min(A,100))){let X=ml(_)+(x.length?1:0);if(x.length&&v+X>Yh)break;x.push(_),v+=X}let P=O.trackEvents,j=await ge(e,P,{events:x},void 0,{keepalive:d});if(h!==n)throw new b("IDENTITY_CHANGED","Event identity changed during delivery");if(j.inserted+j.duplicates+j.rejected+j.skipped!==x.length)throw new b("INVALID_RESPONSE","Incomplete event acknowledgement");i(j.analyticsConfig),a.splice(0,x.length),A-=x.length,y.inserted+=j.inserted,y.duplicates+=j.duplicates,y.rejected+=j.rejected,y.skipped+=j.skipped}return y})();o=R;try{return await R}finally{o===R&&(o=null)}}let f;function g(){if(f||typeof document>"u")return;let d=()=>{document.visibilityState==="hidden"&&t()&&a.length&&m(!0).catch(()=>{})};document.addEventListener("visibilitychange",d),f=()=>document.removeEventListener("visibilitychange",d)}return{rememberConfiguration:i,track:l,flush:m,reset(){n++,r=void 0,clearTimeout(s),s=void 0,a=[],o=null},detachVisibility(){f?.(),f=void 0}}}function Ss(e){let t=null,n=null,r=0,i=0,a=new Set,o=null,s=null,c=new Set,u=()=>{for(let y of c)try{y()}catch{}},l={attributes:Ct.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(y,A)=>{!a.has(y)&&(!t||!("analyticsConfig"in t)||t.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(y,structuredClone(A),structuredClone(l.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(y,A)=>(!t||!("analyticsConfig"in t)||t.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(y),structuredClone(A),structuredClone(l.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?y=>e.saveStickyBucketAssignmentDoc(structuredClone(y)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},m=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function f(y,A=new Set){return a.has(y)?!o||!o.features[y]||["unknownFeature","cyclicPrerequisite"].includes(o.features[y].source):A.has(y)?!1:(A.add(y),(t?.features[y]?.rules??[]).some(x=>[...x.parentConditions??[],...(x.tracks??[]).flatMap(v=>v.experiment.parentConditions??[])].some(v=>f(v.id,A))))}let g=y=>{if(e.assertUsable?.(t?.generation),!t)throw new Error("Initialize the Feature client before evaluation");if(t.expiresAt&&Date.parse(t.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return o?.expiresAt&&Date.parse(o.expiresAt)<=Date.now()&&(o=null,l.features=t.features),a.has(y)?!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now()?m():structuredClone(o.features[y]??m()):e.evaluateRemote&&(l.attributes?.merchandise||l.attributes?.merchandiseId)&&!o||f(y)?m():structuredClone(Hn(y,l))};async function d(){if(!t||!a.size&&!l.attributes?.merchandise&&!l.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(a.size)throw new Error("Remote Feature evaluation requires a server loader");return}let y=i;if(s?.revision===y)return s.loading;let A=r,x=t,v=[...a],P=(async()=>{let j=Va.parse(await e.evaluateRemote({attributes:structuredClone(l.attributes),features:v}));if(!(A!==r||y!==i||x!==t)){if(e.assertUsable?.(x.generation),j.generation!==x.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(v.some(_=>!Object.hasOwn(j.features,_))||Object.keys(j.features).some(_=>!a.has(_)))throw new Error("Invalid remote Feature results");if(l.attributes?.merchandise||l.attributes?.merchandiseId){if(!j.merchandiseContext)throw new Error("Server did not resolve merchandise context");l.attributes=Ct.parse({...l.attributes,...j.merchandiseContext})}o=structuredClone(j),l.features={...x.features,...Object.fromEntries(Object.entries(o.features).map(([_,X])=>[_,{defaultValue:X.value}]))},u()}})();s={revision:y,loading:P};try{await P}finally{s?.loading===P&&(s=null)}}function h(){d().catch(y=>{try{e.onError?.(y)}catch{}})}async function R(){if(n)return n;let y=r,A=(async()=>{let x=await e.load(),v="remoteFeatures"in x?bo.parse(x):null,P=v??bn.parse(x);if(P.scope.projectId!==e.scope.projectId||P.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(y!==r)throw new Error("Feature client was reset");if(e.assertUsable&&t?.generation===P.generation){let{evaluatedAt:_,expiresAt:X,...le}=t,{evaluatedAt:he,expiresAt:ke,...Se}=P;if(Et(le)!==Et(Se))throw new Error("Immutable Feature generation changed content");return t.evaluatedAt=P.evaluatedAt,t.expiresAt=P.expiresAt,u(),(!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())&&h(),structuredClone(t)}let j=new Set(v?.remoteFeatures??[]);if([...j].some(_=>Object.hasOwn(P.features,_)))throw new Error("Remote Feature definitions must not be delivered locally");return t&&"analyticsConfig"in t&&"analyticsConfig"in P&&!t.analyticsConfig.experimentViewsEnabled&&v?.analyticsConfig.experimentViewsEnabled&&l.trackedExperiments?.clear(),t=structuredClone(P),a=j,o=null,s=null,i++,l.features=t.features,l.savedGroups=ci(t.savedGroups),l.trackedFeatureUsage={},u(),h(),structuredClone(t)})();n=A;try{return await A}finally{n===A&&(n=null)}}return{init:R,refresh:R,refreshRemote:d,get generation(){return t?.generation??null},get expiresAt(){return t?.expiresAt??null},subscribe(y){return c.add(y),()=>{c.delete(y)}},setAttributes(y){let A=Ct.parse(y);(l.attributes?.merchandise||l.attributes?.merchandiseId||y.merchandise||y.merchandiseId)&&l.trackedExperiments?.clear(),l.attributes=A,i++,o=null,s=null,l.features=t?.features??{},l.trackedFeatureUsage={},u(),h()},evalFeature:g,isOn(y){return g(y).on},isOff(y){return g(y).off},getFeatureValue(y,A){let x=g(y).value;return structuredClone(x===null?A:x)},reset(){r++,i++,n=null,s=null,t=null,o=null,a.clear(),l.features={},l.savedGroups={},l.stickyBucketAssignmentDocs={},l.attributes={},l.trackedFeatureUsage={},l.trackedExperiments?.clear(),u()}}}function ey(e){let t=e.merchandise;if(typeof e.merchandiseId=="string")return{internalId:e.merchandiseId};if(!(!t||typeof t!="object"||Array.isArray(t))){if(typeof t.internalId=="string")return{internalId:t.internalId};if(typeof t.externalId=="string")return{id:t.externalId};if(typeof t.id=="string")return{id:t.id}}}function Ev(e){let t=ey(e),{merchandiseId:n,merchandise:r,...i}=e;return{...i,...t?{merchandise:t}:{}}}function ty(e,t,n,r,i){if(i&&r&&(i.scope.projectId!==r.projectId||i.scope.environment!==r.environment))throw new b("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,o=new Set;function s(){if(!t())throw new b("NOT_IDENTIFIED","Call identify before using Features or events")}async function c(u={}){i||s();let l=a,m=!1,f=async()=>{if(m||l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let he=O.getFeatures,ke=i?{scope:{projectId:i.scope.projectId,environment:i.scope.environment},payload:await i.features()}:await ge(e,he,{});if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");if(r&&(ke.scope.projectId!==r.projectId||ke.scope.environment!==r.environment))throw new b("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(ke.payload.analyticsConfig),ke},g=await f(),d=!0,h,R=he=>{try{u.onError?.(he)}catch{}},y=(he,ke,Se)=>{try{let At=ey(Se);n.track(he,ke,At?{merchandise:At}:{})}catch(At){R(At)}},A=Ss({assertUsable:i?.assertFeatures,scope:g.scope,attributes:u.attributes,onError:u.onError,load:async()=>d?(d=!1,g.payload):(await f()).payload,evaluateRemote:async he=>{if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let ke=O.evaluateFeatures,Se=await ge(e,ke,{...he,attributes:Ev(he.attributes)});if(Se.scope.projectId!==g.scope.projectId||Se.scope.environment!==g.scope.environment)throw new b("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:Se.generation,evaluatedAt:Se.evaluatedAt,expiresAt:Se.expiresAt,features:Se.features,...Se.merchandiseContext?{merchandiseContext:Se.merchandiseContext}:{}}},onExperimentViewed:(he,ke,Se)=>y("Experiment Viewed",{experimentId:he.key,variationId:ke.key},Se),onFeatureUsage:(he,ke,Se)=>y("Feature Evaluated",{feature:he,value:ke.value,source:ke.source,ruleId:ke.ruleId,...ke.experimentResult?{variationId:ke.experimentResult.key}:{}},Se)}),x=A.refresh;function v(){clearTimeout(h),!i&&(m||l!==a||!A.expiresAt||(h=setTimeout(()=>{P().catch(R)},Math.min(2147483647,Math.max(1e3,Date.parse(A.expiresAt)-Date.now()))),typeof h=="object"&&"unref"in h&&h.unref()))}async function P(){try{return await x()}finally{v()}}let j=()=>{m||P().catch(R)},_=A.subscribe(v),X=i?.subscribe(()=>{!m&&i.fresh&&P().catch(R)});function le(){m||(m=!0,clearTimeout(h),typeof window<"u"&&window.removeEventListener("focus",j),_(),X?.(),A.reset(),o.delete(le))}o.add(le);try{await A.init(),(u.attributes?.merchandise||u.attributes?.merchandiseId)&&await A.refreshRemote()}catch(he){throw le(),he}return v(),!i&&typeof window<"u"&&window.addEventListener("focus",j),Object.assign(A,{refresh:P,destroy:le})}return{features:c,reset(u){a++,u();for(let l of o)l()}}}var ny=require("zod");function ry(e,t){let n="source"in t?{funnelId:t.source.id,funnelVersionId:t.source.versionId}:"versionId"in t?{funnelId:t.funnelId,funnelVersionId:t.versionId}:t,r=ny.z.object({funnelId:us.shape.id,funnelVersionId:us.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new b("INVALID_REQUEST","A valid Funnel source is required");let i=Object.freeze(r.data);function a(o){if("customerId"in o)throw new b("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in o&&o.funnelId!==void 0&&o.funnelId!==i.funnelId||"funnelVersionId"in o&&o.funnelVersionId!==void 0&&o.funnelVersionId!==i.funnelVersionId)throw new b("SCOPE_MISMATCH","The original Funnel source cannot change");return{...o,...i}}return{async claimCoupon(o,s=crypto.randomUUID()){let c=O.grantOffer,u=await ge(e,c,a({couponId:o,requestId:s}));return{offer:u.offer,reason:u.reason}},async resolveOffering(o){let s=O.resolveOffering;return ge(e,s,a(o))},async resolvePaywall(o){let s=O.resolvePaywall;return ge(e,s,a(o))},async previewAttach(o){let s=O.previewAttach;return ge(e,s,a(o))}}}function iy(e){let t=Ar(e),n=t.request,r;try{r=gh(e.push,t,e.scope??e.configuration?.scope)}catch(s){throw t.dispose(),s}let i=$h(t,()=>{o.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=Xh(n,i.isIdentified),o=ty(n,i.isIdentified,a,e.scope,e.configuration);return{session:t.session,...Ah(n,r),...Zh(n),...Wh(n),forFunnel(s){return i.assertActive(),ry(n,s)},async features(s={}){return i.assertActive(),o.features(s)},track(s,c,u={}){return a.track(s,c,u)},flush(){return a.flush()},...i.methods}}function Fi(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,a)=>Fi(i,t[a]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let n=Object.entries(e),r=Object.entries(t);return n.length===r.length&&n.every(([i,a])=>Object.hasOwn(t,i)&&Fi(a,Reflect.get(t,i)))}function Is(e,t){let n=Yg.safeParse(t);if(!n.success)throw new b("INVALID_RESPONSE","Funnel response contract changed");let r=n.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new b("SCOPE_MISMATCH","Funnel scope changed");return r}var Mi=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function vs(e){let t=Nt.test(e.apiKey);if(typeof window<"u"&&!t)throw new b("SERVER_ONLY","Funnel starts are issued by your backend");if(!t&&!Mi.test(e.apiKey))throw new b("INVALID_TOKEN","A customer credential or server API key is required");return{async start(n){let r=_t.safeParse({...n,operation:"start"});if(!r.success||r.data.operation!=="start"||(t?r.data.customer!==void 0:r.data.customer===void 0))throw new b("INVALID_REQUEST","Invalid current Funnel start");let i=r.data,a=Ar({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||a.identify(e.apiKey);let o=Is(e,await a.request("funnels",i));if(!o.runToken)throw new b("INVALID_RESPONSE","Funnel start credentials are missing");if(o.run.source.id!==i.funnelId||o.run.locale!==(i.locale??"en")||!Fi(o.run.parameters,i.parameters??{})||(i.customer?!o.customerId||i.customer.type==="id"&&o.customerId!==i.customer.value:o.customerId!==void 0))throw new b("INVALID_RESPONSE","Funnel start contract changed");return{...o,runToken:o.runToken}}finally{a.dispose()}}}}async function fl(e,t,n){if(Number(e.headers.get("content-length"))>t)throw e.body?.cancel().catch(()=>{}),n.error("limit");let r=e.body?.getReader();if(!r)throw n.error("missing");let i=[],a=0,o=!1,s=()=>{},c=new Promise((m,f)=>{s=()=>f(n.signal?.reason),n.signal?.addEventListener("abort",s,{once:!0}),n.signal?.aborted&&s()});try{for(;;){let m=await Promise.race([r.read(),c]);if(m.done){o=!0;break}if(a+=m.value.length,a>t)throw n.error("limit");i.push(m.value)}}finally{n.signal?.removeEventListener("abort",s),o||r.cancel().catch(()=>{}),r.releaseLock()}n.signal?.throwIfAborted();let u=new Uint8Array(a),l=0;for(let m of i)u.set(m,l),l+=m.length;return u}async function oy(e,t,n){return new TextDecoder("utf-8",{fatal:!0}).decode(await fl(e,t,n))}function ws(e,t){let n=typeof e=="string"?new TextEncoder().encode(e):e;return n.byteLength===t.byteLength&&Pu(n)===t.sha256}async function Os(e,t){let n=Jr.parse(t),{artifact:r,environmentId:i}=n.content,a=new In(e.baseUrl??yr).origin,o=new In(r.url,a);if(o.origin!==a||o.username||o.password||o.search||o.hash||o.pathname!==`/api/v1/configuration/${i}/artifacts/${r.sha256}`)throw new b("INVALID_RESPONSE","Public Paywall locator is not trusted");let s=new AbortController,c,u=new Promise((m,f)=>{c=setTimeout(()=>{let g=new b("TIMEOUT","Public Paywall read timed out");s.abort(g),f(g)},nn.initializationMs)}),l=(async()=>{let m=await(e.fetch??globalThis.fetch)(o,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:s.signal});if(s.signal.aborted&&(m.body?.cancel().catch(()=>{}),s.signal.throwIfAborted()),!m.ok||!m.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(m.headers.get("content-length"))>r.byteLength)throw m.body?.cancel().catch(()=>{}),new b("INVALID_RESPONSE","Public Paywall is unavailable");let f=await fl(m,r.byteLength,{signal:s.signal,error:g=>new b("INVALID_RESPONSE",g==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!ws(f,r))throw new b("INVALID_RESPONSE","Public Paywall digest or size changed");return og(n,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(f)))})();try{return await Promise.race([l,u])}finally{clearTimeout(c)}}var ay=(e,t)=>new b(e,t);var Rv=3,kv=2e3;function jv(e){return e instanceof TypeError||e instanceof b&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Tv(e){for(let t=1;;t++)try{return await e.refresh()}catch(n){if(t===Rv||!jv(n))throw n;await new Promise(r=>setTimeout(r,t*kv))}}async function gl(e,t,{predict:n=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new b("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new b("SCOPE_MISMATCH","Evaluation environment changed");let i=null,a;if(n)try{let o=await e.funnel(t.source.id,t.source.versionId);a=o.manifest.generation,i=Nv(e,t,o)}catch{i=null}return a??(a=e.snapshot?.generation??(await Tv(e)).generation),{advance:{policyRevision:r.policyRevision,generation:a},prediction:i}}function Nv(e,t,n){let r=t.instruction;if(r?.type!=="evaluate_segment"||!n.growth||n.control.evaluationMode!=="local"||n.control.evaluationRevision!==r.policyRevision)return null;let{analyticsConfig:i,remoteFeatures:a,...o}=n.growth,s=$u({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t.source.id,versionId:t.source.versionId,evaluationMode:"local",evaluationRevision:r.policyRevision,document:n.document,payload:bn.parse(o)}),c=Dv(s,n.document,{...t,...r}),u=c.steps.at(-1),l=c.boundary??(u?.result.port==="value"?{nodeId:u.nodeId,visit:t.visit+c.steps.length-1}:null);return l?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:l.nodeId,visit:l.visit,terminal:!c.boundary}:null}function Dv(e,t,n){return fh(e,t,n,ay)}var an=require("zod");var sy=_t.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new b("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),cy=an.z.strictObject({schemaVersion:an.z.literal(1),scope:Fe,runId:an.z.uuid(),funnelId:an.z.uuid(),versionId:an.z.uuid(),processBindingIds:an.z.record(an.z.uuid(),an.z.uuid().nullable()).optional(),command:sy.optional(),closeCommand:sy.refine(e=>e.operation==="close").optional(),purchase:an.z.strictObject({receiptId:an.z.uuid(),operationId:an.z.uuid(),generation:an.z.number().int().nonnegative()}).optional(),closed:an.z.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),Xt=()=>new b("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Ps=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function uy(e){let t=0,n=null,r=u=>JSON.stringify([u.scope,u.runId,u.funnelId,u.versionId]),i=Promise.resolve();async function a(){let u=await e.read();if(!Number.isSafeInteger(u.revision)||u.revision<0)throw new b("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:u.revision,entry:u.entry===null?null:cy.parse(u.entry)}}function o(u){let l=i.then(u);return i=l.catch(()=>{}),l}async function s(u){for(let l=0;l<4;l++){let m=await a();if(m.entry&&n!==null&&r(m.entry)!==n)throw Xt();let f=u(m.entry,m.revision);if(Ps(m.entry,f)){t=m.revision;return}let g=await e.write(m.revision,f);if(g!==null){if(!Number.isSafeInteger(g)||g<=m.revision)throw Xt();t=g;return}}throw Xt()}function c(u,l){if(!u||!l)return u;if(u.processBindingIds&&Object.hasOwn(u.processBindingIds,l)){let m={...u.processBindingIds};delete m[l],u={...u,processBindingIds:m}}return u.command?.requestId===l?u.closeCommand?{...u,command:u.closeCommand,closeCommand:void 0}:u.purchase?{...u,command:void 0}:null:u.closeCommand?.requestId===l?{...u,closeCommand:void 0}:u}return{bind(u){let l=JSON.stringify([u.scope,u.runId,u.funnelId,u.versionId]);if(n!==null&&n!==l)throw Xt();n=l},async load(){let u=await a();return t=u.revision,n=u.entry?r(u.entry):null,u.entry},retain(u){let l=cy.parse(u),m=l.command;return!m||n!==null&&r(l)!==n?Promise.reject(Xt()):(n??(n=r(l)),o(()=>s((f,g)=>{if(f&&!Ps(r(f),r(l)))throw Xt();if(f&&l.processBindingIds){for(let[d,h]of Object.entries(l.processBindingIds))if(f.processBindingIds&&Object.hasOwn(f.processBindingIds,d)&&f.processBindingIds[d]!==h)throw Xt();f={...f,processBindingIds:{...f.processBindingIds,...l.processBindingIds}}}if(!f){if(g!==t&&m.operation!=="close")throw Xt();return l}if(!f.command)return{...f,command:m,...m.operation==="close"?{closed:!0}:{}};if(m.operation==="close"&&f.command.operation!=="close"){if(f.command.requestId===m.requestId||f.closeCommand&&!Ps(f.closeCommand,m))throw Xt();return{...f,closeCommand:m,closed:!0}}if(!Ps(f.command,m))throw Xt();return f})))},observePurchase(u,l,m,f){return o(()=>s((g,d)=>{if(!g&&d!==t||g&&r(g)!==r({...u,schemaVersion:1}))throw Xt();if(g?.purchase&&g.purchase.generation>l.generation)return c(g,f);if(g?.purchase&&g.purchase.generation===l.generation&&g.purchase.operationId!==l.operationId)throw Xt();return m?!g?.purchase||g.purchase.operationId!==l.operationId?c(g,f):c(g.command?{...g,purchase:void 0}:null,f):c({schemaVersion:1,...u,...g,purchase:l},f)}))},settle(u){return o(()=>s(l=>c(l,u)))}}}function ly(e){let t,n,r=()=>new b("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,n=e.locks??globalThis.navigator?.locks,!t||!n||!globalThis.crypto?.subtle)throw r();let s=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??yr).href,e.runToken])),c=new Uint8Array(await crypto.subtle.digest("SHA-256",s));return"indiana.funnel.commands.v1."+Array.from(c,u=>u.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function a(s){try{let c=await i;return await n.request(c,{mode:"exclusive"},()=>s(c))}catch(c){throw c instanceof b?c:r()}}function o(s){let c=t.getItem(s);if(c===null)return{revision:0,entry:null};if(c.length>1048576)throw r();let u=JSON.parse(c);if(!u||typeof u!="object"||!("revision"in u)||!("entry"in u)||!Number.isSafeInteger(u.revision)||Number(u.revision)<0)throw r();return{revision:Number(u.revision),entry:u.entry}}return{read:()=>a(o),write:(s,c)=>a(u=>{if(o(u).revision!==s)return null;if(!Number.isSafeInteger(s+1))throw r();return t.setItem(u,JSON.stringify({revision:s+1,entry:c})),s+1})}}function dy(e,t){let n=t&&{...t},r=null,i=0,a=new AbortController;function o(){i++,a.abort(new b("IDENTITY_CHANGED","Run identity changed")),a=new AbortController}let s=!1,c,u=0,l=new Set;return{get scope(){return n},bindScope(m){if(n&&(n.projectId!==m.projectId||n.environment!==m.environment))throw new b("SCOPE_MISMATCH","Run scope changed");n??(n={...m})},get view(){return r},get generation(){return i},get signal(){return a.signal},get disposed(){return s},get customerToken(){return c},get readSequence(){return u},nextRead(){return++u},assertCurrent(m,f="Run identity changed during the request"){if(m!==i||s)throw new b("IDENTITY_CHANGED",f)},assertRun(m){if(r&&(m.id!==r.id||m.source.type!==r.source.type||m.source.id!==r.source.id||m.source.versionId!==r.source.versionId||m.locale!==r.locale||!Fi(m.parameters,r.parameters)))throw new b("INVALID_RESPONSE","Run version changed");if(e&&m.source.id!==e)throw new b("INVALID_RESPONSE","Run belongs to another Funnel")},publish(m,f,g,d,h){if(!(m.operation==="review"&&r&&r!==g&&f.run.revision<=r.revision)&&!(r&&f.run.revision===r.revision&&d!==void 0&&d<u)&&(m.operation==="review"&&!f.run.stopped&&["running","waiting"].includes(f.run.status)&&r&&f.run.nodeId===r.nodeId&&f.run.visit===r.visit&&f.run.revision===r.revision&&(f.run.screen=r.screen,(r.paywall?.quote?.operationId===f.review?.activeOperationId||!r.paywall?.quote&&f.review?.activeOperationId===null)&&(f.run.paywall=r.paywall)),!(r?.paywall&&f.run.paywall&&r.paywall.receiptId===f.run.paywall.receiptId&&(f.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||f.run.revision>=r.revision)r=f.run;else if(!h)return;if(r)for(let R of l)try{R(structuredClone(r))}catch{}}},identify(m){if(s)throw new b("IDENTITY_CHANGED","Controller was reset");if(!Nt.test(m))throw new b("INVALID_TOKEN","Customer credential required");o(),c=m},subscribe(m){return l.add(m),()=>l.delete(m)},reset(){s||(s=!0,o(),c=void 0,r=null,l.clear())}}}function br(e){let{customerToken:t,...n}=e;return n}var Fv=e=>!(e instanceof b)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function py({journal:e,state:t,call:n,processIdentity:r}){let i=null,a=null,o=!1,s={command:null,close:null},c=new Set,u,l=null,m=e?e.load().then(y=>{if(t.disposed)throw new b("IDENTITY_CHANGED","Controller was reset during command restoration");if(l=y,!y)return;if(r){if([y.command,y.closeCommand].some(x=>x&&!Object.hasOwn(y.processBindingIds??{},x.requestId)))throw new b("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(y.processBindingIds??{})}if(t.scope&&(y.scope.projectId!==t.scope.projectId||y.scope.environment!==t.scope.environment))throw new b("SCOPE_MISMATCH","Pending command belongs to another scope");if(u=y.purchase,o=y.closed===!0,!y.command)return;let A=y.command;i=A.operation==="close"?null:A,a=A.operation==="close"?A:y.closeCommand?.operation==="close"?y.closeCommand:null,a&&(o=!0);for(let x of[i,a])x&&c.add(x.requestId)}):Promise.resolve();m.catch(()=>{});async function f(y){e&&await m;let A=t.generation;if(e){if(!t.view||!t.scope)throw new b("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:br(y),...r?{processBindingIds:{[y.requestId]:r.binding(y.requestId)}}:{}})}if(A!==t.generation||i!==y&&a!==y)throw new b("IDENTITY_CHANGED","Run changed before command dispatch");let x=c.has(y.requestId);c.add(y.requestId);try{return await n(y)}catch(v){throw A===t.generation&&(i===y||a===y)&&!x&&!Fv(v)&&(e&&await e.settle(y.requestId),A===t.generation&&R(y)),v}}function g(y){let A=_t.parse(y);if(A.operation==="start"||A.operation==="get"||A.operation==="review")throw new b("INVALID_REQUEST","Mutation required");if(o&&A.operation!=="close"){if(i?.requestId===A.requestId)return h(A.requestId);throw new b("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(A.operation==="close"){if(i?.requestId===A.requestId)throw new b("INVALID_REQUEST","Close requires its own request identity");if(o=!0,a&&JSON.stringify(br(a))!==JSON.stringify(br(A)))throw new b("COMMAND_PENDING","Retry the original Close");return a??(a=A),s.close?s.close:d(a,"close")}if(i){if(JSON.stringify(br(i))!==JSON.stringify(br(A)))throw new b("COMMAND_PENDING","Retry the original command before sending another");if(s.command)return s.command}else i=A;return d(i,"command")}function d(y,A){let x=f(y);s[A]=x;let v=()=>{s[A]===x&&(s[A]=null)};return x.then(v,v),x}function h(y){return n({operation:"get",settlementRequestId:y})}function R(y){return!y||i!==y&&a!==y?!1:(i===y&&(i=null),a===y&&(a=null),c.delete(y.requestId),!i&&!a&&(l=null),!0)}return{ready:m,get pending(){return i},get closing(){return a},get closeRequested(){return o},get inFlight(){return s.command},get closeFlight(){return s.close},get purchase(){return u},assertBinding(y){if(l&&(y.run.id!==l.runId||y.run.source.id!==l.funnelId||y.run.source.versionId!==l.versionId))throw new b("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(y,A,x,v){let P=y.operation==="get"?y.settlementRequestId:"requestId"in y&&y.operation!=="start"?y.requestId:void 0,j=P&&A.settlement?.state==="settled"&&A.run.pendingRequest?.requestId!==P&&(y.operation==="get"||!o||y.operation==="close"||!["running","waiting"].includes(A.run.status))?P:void 0,_=i?.requestId===j?i:a?.requestId===j?a:void 0;e?.bind({scope:A.scope,runId:A.run.id,funnelId:A.run.source.id,versionId:A.run.source.versionId});let X=A.run.paywall,le=X??A.purchase,he=le?.operation,ke=A.settlement&&(!X||X.purchaseRequestId===A.settlement.requestId)&&(!u||u.operationId===A.settlement.operationId)?A.settlement:void 0,Se=he?.operationId??le?.quote?.operationId??ke?.operationId,At=le?.receiptId??ke?.receiptId,We=X?.selectionGeneration??u?.generation??0;if(e&&Se&&At&&y.operation!=="review"&&(!t.view||A.run.revision>=t.view.revision)&&(v===void 0||v>=t.readSequence)&&(!u||We>=u.generation)){let De={receiptId:At,operationId:Se,generation:We},rt=he?.status==="complete"||le?.canReselect===!0;await e.observePurchase({scope:A.scope,runId:A.run.id,funnelId:A.run.source.id,versionId:A.run.source.versionId},De,rt,j),t.assertCurrent(x),(!u||De.generation>=u.generation)&&(v===void 0||v>=t.readSequence)&&(rt?u?.operationId===De.operationId&&(u=void 0):u=De)}else e&&j&&await e.settle(j);return t.assertCurrent(x),j?R(_):!1},stop(){o=!0},submit:g,settle:h,reset(){o=!0,i=null,a=null,u=void 0,l=null,s.close=null,c.clear(),s.command=null}}}function xr(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new b("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!Mi.test(e.serverKey)))throw new b("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new b("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let t=Ar({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),n=dy(e.funnelId,e.scope??e.configuration?.scope),r=e.session?.subscribeIdentity(u),i=null,a=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?ly(e):void 0),o=a&&uy(a),s=py({journal:o,state:n,call:l,processIdentity:e.process});async function c(A){if(e.process)return e.process.request(A);let x=n.generation;n.assertCurrent(x);let v=performance.now()+(e.timeoutMs??35e3),P=n.customerToken??("customerToken"in A?A.customerToken:void 0);if(e.session){let X=n.signal,le,he=()=>{},ke=new Promise((Se,At)=>{he=()=>At(X.reason),X.addEventListener("abort",he,{once:!0}),le=setTimeout(()=>At(new b("TIMEOUT","Longplay request timed out")),Math.max(1,v-performance.now()))});try{P=await Promise.race([Promise.resolve().then(()=>(n.assertCurrent(x),e.session.access())),ke])}finally{clearTimeout(le),X.removeEventListener("abort",he)}}n.assertCurrent(x);let j={...A,...P?{customerToken:P}:{}},_=A.operation==="page_experiments"?ko.parse(j):_t.parse(j);return t.requestWithCredential("funnels",_,e.runToken,{headers:e.serverKey&&!P?{[Xg]:e.serverKey}:void 0,timeoutMs:Math.max(1,v-performance.now())})}function u(){r?.(),n.reset(),s.reset(),i=null,t.dispose()}async function l(A,x){let v=n.generation,P=()=>n.assertCurrent(v);o&&await s.ready,P();let j=n.view,_=Is(e,await c(A));if(A.operation==="review"&&!_.review)throw new b("INVALID_RESPONSE","Historical projection is missing");if(P(),_.runToken&&_.runToken!==e.runToken)throw new b("INVALID_RESPONSE","Run credential changed");let X=A.operation==="get"?A.settlementRequestId:"requestId"in A&&A.operation!=="start"?A.requestId:void 0;if(X&&_.settlement?.requestId!==X)throw new b("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");s.assertBinding(_),n.assertRun(_.run),n.bindScope(_.scope);let le=await s.observe(A,_,v,x);return!_.run.stopped&&["running","waiting"].includes(_.run.status)&&A.operation==="get"&&A.settlementRequestId||(P(),["running","waiting"].includes(_.run.status)||s.stop(),n.publish(A,_,j,x,le)),_}let m=s.submit,f=null,g=new WeakMap;function d(A){let x=g.get(A);if(x)return x;let v=R(A);return g.set(A,v),v}let h=!1;async function R(A){let x=await A;if(x.run.instruction?.type!=="evaluate_segment")return x;if(f)return f;h=!0;let v=n.generation,P=(async()=>{for(let j=0;j<32&&x.run.instruction?.type==="evaluate_segment";j++){if(s.pending||s.closeRequested)return x;let _=x.run;if(x.run.instruction?.type==="evaluate_segment"){let{advance:le}=await gl(e.configuration,_,{predict:!1});if(v!==n.generation)throw new b("IDENTITY_CHANGED","Run identity changed during segment calculation");if(s.pending||s.closeRequested)return x;if(n.view&&(n.view.revision!==_.revision||n.view.visit!==_.visit||n.view.nodeId!==_.nodeId))return l({operation:"get"});let he=!0;gl(e.configuration,_).then(({prediction:ke})=>{he&&v===n.generation&&!s.closeRequested&&n.view?.id===_.id&&!n.view.stopped&&n.view.nodeId===_.nodeId&&n.view.visit===_.visit&&n.view.revision===_.revision&&(i=ke)}).catch(()=>{});try{x=await m({operation:"commit_segment",requestId:Wg(_.id,_.visit,`segment:${_.revision}`),nodeId:_.nodeId,visit:_.visit,revision:_.revision,...le})}finally{he=!1,i=null}}}return x})();f=P;try{return await P}finally{f===P&&(f=null)}}let y={get configuration(){return h?e.configuration:void 0},get configurationReady(){return!0},get view(){return n.view?structuredClone(n.view):null},get pendingCommand(){let A=s.closing??s.pending;return A?structuredClone(br(A)):null},get pendingCommands(){return[s.pending,s.closing].filter(A=>A!==null).map(A=>structuredClone(br(A)))},get pendingPurchase(){return s.purchase?structuredClone(s.purchase):null},get hasDurableJournal(){return o!==void 0},get prediction(){let A=n.view;return i&&A&&!A.stopped&&["running","waiting"].includes(A.status)&&A.id===i.runId&&A.nodeId===i.from.nodeId&&A.visit===i.from.visit&&A.revision===i.from.revision&&!s.closeRequested?structuredClone(i):null},settle:s.settle,get webViewUrl(){return"bundled"},resolvePaywall(A){return Os(e,A)},async pageExperiments(A,x=[]){let v=n.generation;n.assertCurrent(v);let P=n.view?.id;if(!P)throw new b("INVALID_REQUEST","Read the Run before its page experiments");let j=rh.parse(await c(ko.parse({operation:"page_experiments",release:A,usedReceiptIds:x})));if(n.assertCurrent(v),j.runId!==P||j.scope.projectId!==n.scope?.projectId||j.scope.environment!==n.scope?.environment)throw new b("SCOPE_MISMATCH","Page experiment Run changed");return j},review(A){return l({operation:"review",...A?{receiptId:A}:{}},n.nextRead())},async get(A,x){o&&await s.ready,x??(x=s.purchase&&{receiptId:s.purchase.receiptId,operationId:s.purchase.operationId});let v=n.nextRead();return d(l({operation:"get",...A?{data:A}:{},...x?{purchase:x}:{}},v))},resume(A=n.view?.pendingRequest?.requestId){return A?s.closeRequested?y.settle(A):s.pending?.requestId===A?d(m(s.pending)):d(m({operation:"resume",requestId:A})):Promise.reject(new b("INVALID_REQUEST","No interrupted command is available"))},submit(A){return d(m(A))},retry(){return s.closeFlight?s.closeFlight:s.closing?m(s.closing):s.closeRequested&&s.pending?y.settle(s.pending.requestId):s.inFlight?d(s.inFlight):s.pending?d(m(s.pending)):Promise.reject(new b("INVALID_REQUEST","No command is pending"))},identify(A){n.identify(A),i=null,t.reset()},subscribe:n.subscribe,reset:u};return y}function my(e){if(!Nt.test(e.customerToken))throw new b("INVALID_TOKEN","A customer credential is required");if(!e.scope)throw new b("INVALID_REQUEST","An explicit App and environment scope is required");let t=vs({...e,scope:e.scope,apiKey:e.customerToken});return{async start(n){let r=await t.start(n),i=xr({...e,runToken:r.runToken});i.identify(e.customerToken);let a=r.run.instruction?.type==="evaluate_segment"?await i.get():r;return{...r,...a,controller:i}}}}function fy(e,t){let n=r=>"document"in r?r.offering.id:r.content.offeringVersionId;return e.id===t.id&&n(e)===n(t)&&e.content?.artifact.sha256===t.content?.artifact.sha256}function gy(e,t,n){if(e.operationId!==t.operationId||t.currency!==void 0&&e.currency!==t.currency)throw new b("INVALID_RESPONSE",n)}function hy(e,t,n){let r=Object.fromEntries((e.lines[0]?.prepaid??[]).map(i=>[i.internal_feature_id,i.quantity]));if(t.featureQuantities&&(Object.keys(r).length!==Object.keys(t.featureQuantities).length||Object.entries(t.featureQuantities).some(([i,a])=>r[i]!==a)))throw new b("INVALID_RESPONSE","The purchase quote changed its selected quantities");if(e.lines.length!==1||e.lines[0].productVersionId!==t.productVersionId||t.currency!==void 0&&e.currency!==t.currency||t.provider!==void 0&&e.provider!==t.provider&&!(t.provider==="stripe"&&e.provider==="merchant"&&e.execution?.provider==="merchant"))throw new b("INVALID_RESPONSE",n)}function yy(e,t,n=!1){return!e||e.operationId!==t?.operationId?t:e.status==="complete"&&t.status!=="complete"||e.status!=="pending"&&(t.status==="pending"||n&&t.status!=="complete")?e:t}function Ay(e){let{quote:t,operation:n,requestId:r}=e,a={type:"recover",operationId:n?.operationId??t?.operationId??null,requestId:r};if(e.destroyed||e.pending)return a;if(!n)return t?{type:"cancel",operationId:t.operationId}:a;let o=n.merchantExecution;if(o?.type==="purchase"){if(["succeeded","not_required"].includes(o.paymentStatus))return!["applied","not_applicable"].includes(o.fulfillmentStatus)||n.problem?.phase==="fulfillment"||o.problem?.phase==="fulfillment"?{type:"fulfillment",operationId:n.operationId}:{type:o.recordingStatus==="accepted"&&n.status==="complete"?"complete":"recording",operationId:n.operationId};if(n.status==="pending"&&n.checkoutUrl&&o.checkoutUrl===n.checkoutUrl&&o.checkoutExpiresAt&&Date.parse(o.checkoutExpiresAt)>Date.now()&&["not_started","pending"].includes(o.paymentStatus))return{type:"checkout",operationId:n.operationId,checkoutUrl:n.checkoutUrl}}let s=[n.problem,o?.problem],c=s.every(u=>!u||u.phase==="execution"&&u.reason!=="RESULT_UNKNOWN");return!s.some(Boolean)&&n.status==="complete"&&n.executor!=="merchant"?{type:"complete",operationId:n.operationId}:c&&e.canReselect!==!1&&["cancelled","failed"].includes(n.status)&&!n.checkoutUrl&&!n.execution&&!n.nativePurchase&&(n.executor!=="merchant"?!n.confirmedAt&&(n.status==="cancelled"||!n.quoteFinalized):!o&&!n.quoteFinalized||o?.type==="purchase"&&["failed","expired"].includes(o.paymentStatus)&&o.fulfillmentStatus==="not_applicable"&&o.recordingStatus==="accepted")?{type:"native",operationId:n.operationId}:n.status==="pending"&&c&&!n.quoteFinalized&&!o&&!n.checkoutUrl&&!n.execution&&!n.nativePurchase?{type:"cancel",operationId:n.operationId}:a}async function by(e,t){if(!Nt.test(t.customerToken))throw new b("INVALID_TOKEN","A verified Customer credential is required");if(e.session&&e.session.peek()!==t.customerToken)throw new b("SCOPE_MISMATCH","Paywall credential does not match the shared session");let n=O.resolvePaywall.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale,...t.requirement?{requirement:t.requirement}:{}}),r=Ar(e);e.session||r.identify(t.customerToken);let i=null,a=!1,o=null,s=null,c=null,u=null,l=null,m=null,f=null,g=0;function d(){if(a)throw new b("IDENTITY_CHANGED","Paywall is closed")}async function h(){d();let x=O.resolvePaywall,v=await ge(r.request,x,{...n,selector:i?{type:"version",versionId:i.id}:n.selector}),P=await Os(e,v.paywall);if(d(),t.paywallVersionId?P.id!==t.paywallVersionId:P.paywallId!==t.paywallId)throw new b("INVALID_RESPONSE","The requested Paywall changed");if(i&&(!fy(P,i)||P.paywallId!==i.paywallId))throw new b("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return i=P,structuredClone(i)}async function R(x){if(d(),u&&x!=="read")throw new b("COMMAND_PENDING","Wait for the original quote");if(!o)throw new b("INVALID_REQUEST","A quoted purchase is required");let v=o;if(x!=="read"){if(f){if(m===x)return f;throw new b("COMMAND_PENDING","Wait for the original purchase command")}if(m&&m!==x)throw new b("COMMAND_PENDING","Read the original purchase before changing an uncertain command");m=x,g++}let P=m,j=g,_=x==="read"&&f===null,X=x==="read"?O.readSubscriptionOperation:O.attach,le=(async()=>{let he=await ge(r.request,X,{operationId:v.operationId,...x==="read"?{}:{intent:x}});return gy(he.operation,{operationId:v.operationId,currency:n.commerce.currency},"The purchase operation changed"),d(),o?.operationId!==v.operationId?structuredClone(he.operation):(s=yy(s,he.operation),(x!=="read"||_&&f===null)&&g===j&&m===P&&(m=null),structuredClone(s))})();if(x!=="read"){f=le;let he=()=>{f===le&&(f=null)};le.then(he,he)}return le}let y={get view(){return i?structuredClone(i):null},get quote(){return o?structuredClone(o):null},get operation(){return s?structuredClone(s):null},get webViewUrl(){return"bundled"},get recovery(){return Ay({quote:o,operation:s,requestId:l,pending:u!==null||m!==null,destroyed:a})},get pendingCancellation(){return!a&&m==="cancel"},refresh:h,async preview(x){if(d(),!i)throw new b("INVALID_REQUEST","Load the Paywall first");let v=i.document.buttons[x.actionId];if(v?.type!=="checkout")throw new b("INVALID_REQUEST","Choose an authored purchase action");let P=of(v.product,x.selection,i.capabilities);if(!P)throw new b("PRODUCT_UNAVAILABLE","Choose an available Product");let j=Zf(i.document.screen,P,x.selection,i.capabilities),_=O.previewAttach.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,requestId:x.requestId,plans:[{productVersionId:P,...Object.keys(j).length?{featureQuantities:j}:{}}],provider:n.commerce.provider,currency:n.commerce.currency,...x.offerId?{offerId:x.offerId}:{},...x.nativeOffer?{nativeOffer:x.nativeOffer}:{}}),X=JSON.stringify(_);if(c&&c!==X&&(u||m||!s||s.status==="pending"))throw new b("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(c===X){if(u)return u;if(o)return structuredClone(o)}c!==X&&(o=null,s=null),c=X,l=_.requestId;let le=(async()=>{let he=O.previewAttach,ke=await ge(r.request,he,_);return d(),hy(ke.quote,{productVersionId:P,featureQuantities:j,currency:n.commerce.currency,provider:n.commerce.provider},"The purchase quote changed its selected Product or presentment"),o=ke.quote,s=null,structuredClone(o)})();u=le;try{return await le}finally{u===le&&(u=null)}},confirm:()=>R("confirm"),cancel:()=>R("cancel"),read:()=>R("read"),destroy(){a||(a=!0,A?.(),r.dispose(),i=null,o=null,s=null,c=null,l=null)}},A=e.session?.subscribeIdentity(y.destroy);try{return await h(),y}catch(x){throw y.destroy(),x}}function xy(e,t){let n,r=0,i=-1,a,o=!1,s=()=>{if(o)throw new b("CLOSED","Native host was destroyed");if(!e.nativeModule)throw new b("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return e.nativeModule},c=()=>new b("IDENTITY_CHANGED","Customer identity changed during the native operation"),u=t.subscribeIdentity(()=>{r++,i=-1;let g=r;n&&e.nativeModule&&n.then(d=>e.nativeModule.reset(d,g)).catch(()=>{})}),l=e.nativeEvents?.(g=>{!n||!e.nativeModule||typeof g?.requestId!="string"||(async()=>{let d=await n;if(g.instanceId!==d)return;if(g.kind==="credential"){let y=r,A=null;try{if(!o&&g.revision===y){let x=await t.access();!o&&r===y&&(A=x)}}finally{await e.nativeModule.provideCredential(d,g.requestId,A)}return}let h=!1,R=r;try{if(o||g.revision!==R||!e.onNativeAction)throw c();await e.onNativeAction(g.action),h=!o&&r===R}finally{await e.nativeModule.acknowledge(d,g.requestId,h)}})().catch(()=>{})});async function m(g,d={}){let h=s();if(t.snapshot()&&!e.nativeEvents)throw new b("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let R=r,y=await t.access();if(o||r!==R)throw c();if(!n){let v=h.create(JSON.stringify({baseUrl:e.baseUrl??"https://api.longplayai.com",scope:e.scope,timeout:(e.timeoutMs??15e3)/1e3,credentialEvents:!!e.nativeEvents}));n=v,v.catch(()=>{n===v&&(n=void 0)})}let A=await n;if(o||r!==R)throw c();if(i!==R){if(!a||a.epoch!==R){let P=(async()=>{if(await h.identify(A,JSON.stringify({revision:R,credentials:y})),o||r!==R)throw await h.reset(A,R),c();i=R})();a={epoch:R,task:P}}let v=a;try{await v.task}finally{a===v&&(a=void 0)}}let x=await h.invoke(A,g,JSON.stringify(d));if(o||r!==R)throw c();try{return JSON.parse(x)}catch{throw new b("INVALID_RESPONSE","Native host returned invalid JSON")}}async function f(g,d){let h=await m(g,d);if(!h||typeof h!="object"||Array.isArray(h)||h.status!=="complete"&&h.status!=="dismissed")throw new b("INVALID_RESPONSE","Native presentation returned an invalid result");return h}return{showFunnel(g){return f("showFunnel",{runToken:g})},showPaywall(g){return f("showPaywall",g)},showContent(g){return f("showContent",g)},purchaseSubscription(g,d){return m("purchaseSubscription",{operationId:g,accepted:d})},switchSubscription(g,d){return m("switchSubscription",{operationId:g,accepted:d})},restorePurchases(){return m("restorePurchases")},manageSubscriptions(g){return m("manageSubscriptions",g?{productId:g}:{})},async dismiss(){r++,i=-1,n&&await s().reset(await n,r)},async destroy(){o||(o=!0,r++,u(),l?.(),n&&e.nativeModule&&await e.nativeModule.destroy(await n))}}}var Mv=O.trackUsage.request.shape.command,qv=O.trackUsage.response;function Sy(e){let t=Fe.parse(e.scope),n=iy({...e,scope:t}),r={...e,scope:t,session:n.session},i=xy(e,n.session),a=0,o=!1;n.subscribeIdentity(()=>{a++});let s=()=>{if(o)throw new b("CLOSED","SDK client was destroyed");let c=n.session.peek();if(!c)throw new b("UNAUTHENTICATED","Identify the Customer first");return c};return{...n,native:i,async destroy(){o||(o=!0,a++,n.destroy(),await i.destroy())},funnel(){return my({...r,customerToken:s()})},resumeFunnel(c){return s(),xr({...r,runToken:c})},paywall(c){return by(r,{...c,customerToken:s()})},async trackUsage(c){if(s(),!e.usageReporter)throw new b("INVALID_REQUEST","Configure your authenticated backend usageReporter");let u=Mv.parse(c),l=a,m;try{m=await e.usageReporter(u)}catch(g){throw l!==a?new b("IDENTITY_CHANGED","Customer identity changed during usage reporting"):g}if(l!==a)throw new b("IDENTITY_CHANGED","Customer identity changed during usage reporting");let f=qv.parse(m);if(f.scope.projectId!==t.projectId||f.scope.environment!==t.environment)throw new b("INVALID_RESPONSE","Usage response scope differs");return f}}}var wy=require("zod");var qi=require("zod");var Uv=qi.z.record(qi.z.string().regex(/^[a-f0-9]{64}$/),qi.z.strictObject({at:qi.z.number(),text:qi.z.string()})),ti=2*1048576,Bv=100;function Vv(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Iy(e,t){let n=t===void 0?Vv():t,r=new Map,i=0,a=!1,o=!1,s,c;async function u(m){if(!n)return null;let f;try{let g=await Promise.race([Promise.resolve().then(()=>n.getItem(m)),new Promise(d=>{f=setTimeout(()=>d(null),Bv)})]);return typeof g=="string"&&g.length<=ti&&new TextEncoder().encode(g).byteLength<=ti?g:null}catch{return null}finally{clearTimeout(f)}}function l(){if(c)return c;let m=(async()=>{try{let f=await u(`${e}:artifacts`);if(f)return Uv.parse(JSON.parse(f))}catch{}return{}})();return c=m,m.finally(()=>{c===m&&(c=void 0)}),m}return{async readManifest(){return u(e)},writeManifest(m){!n||m.length>ti||new TextEncoder().encode(m).byteLength>ti||(s=m,!o&&(o=!0,Promise.resolve().then(async()=>{try{for(;s!==void 0;){let f=s;try{await n.setItem(e,f)}catch{}s===f&&(s=void 0)}}finally{o=!1}})))},async readArtifact(m){let f=(await l())[m],g=Date.now();return f&&g>=f.at&&g-f.at<=nn.retentionMs?f.text:void 0},writeArtifact(m,f){if(!n||f.length>ti)return;let g=r.get(m);if(g?.text===f||!g&&r.size>=128)return;let d=new TextEncoder().encode(f).byteLength;i-(g?.byteLength??0)+d>ti||(r.set(m,{text:f,byteLength:d}),i+=d-(g?.byteLength??0),!a&&(a=!0,Promise.resolve().then(async()=>{try{for(;r.size;){let h=new Map(r);try{let R={...await l()},y=Date.now();for(let[P,j]of h)R[P]={at:y,text:j.text};let A={},x=2,v=0;for(let[P,j]of Object.entries(R).sort(([,_],[,X])=>X.at-_.at)){if(j.at>y||y-j.at>nn.retentionMs)continue;let _=new TextEncoder().encode(JSON.stringify({[P]:j})).byteLength;x+_>ti||v>=128||(A[P]=j,x+=_,v++)}await n.setItem(`${e}:artifacts`,JSON.stringify(A))}catch{}finally{for(let[R,y]of h)r.get(R)===y&&(r.delete(R),i-=y.byteLength)}}}finally{a=!1}})))}}}var Ce=(e,t)=>new b(e,t),Sr=()=>performance.now(),vy=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function Oy(e){let t=vu.parse(e.scope),n=new In(e.origin??yr);if(n.username||n.password||n.search||n.hash||n.pathname!=="/"||n.protocol!=="https:"&&!(n.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(n.hostname)))throw Ce("INVALID_URL","Configuration requires a trusted HTTPS origin");let r=new Set([n.origin,...(e.assetOrigins??[]).map(Y=>{let W=new In(Y);if(W.protocol!=="https:"||W.username||W.password||W.search||W.hash||W.pathname!=="/")throw Ce("INVALID_URL","Invalid configuration asset origin");return W.origin})]),i=e.fetch??globalThis.fetch.bind(globalThis),a=`/api/v1/configuration/${t.environmentId}`,o=`indiana:configuration:1:${n.origin}:${Et(t)}`,s=Iy(o,e.storage),c,u=0,l=0,m=!1,f=!1,g=0,d=0,h,R,y,A,x=0,v=new Set,P=new Set,j=new Map,_=new Map,X=0,le=!1;function he(){for(let Y of v)try{Y()}catch{}}function ke(Y){try{e.onError?.(Y)}catch{}}let Se=()=>!f&&!m&&!!c&&Sr()<u&&Date.now()<l;function At(){if(!Se())throw Ce("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function We(Y,W,pe){if(!j.has(Y)){for(;j.size&&(j.size>=128||X+pe>nn.maxCacheBytes);){let me=j.entries().next().value;X-=me[1].byteLength,j.delete(me[0])}j.set(Y,{text:W,byteLength:pe}),X+=pe}}function De(Y,W,pe){return oy(Y,W,{signal:pe,error:me=>Ce("INVALID_RESPONSE",me==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function rt(Y){let W=new In(Y,n);if(!r.has(W.origin)||W.username||W.password||W.hash||W.search)throw Ce("INVALID_URL","Configuration artifact origin is not trusted");return W.href}async function Mo(Y,W,pe=!1){let me=await i(rt(Y),{method:"GET",credentials:"omit",redirect:"error",cache:pe?"default":"no-cache",signal:W,headers:{}});if(me.status===429){let et=me.headers.get("retry-after")??"";x=/^\d+$/.test(et)?Number(et)*1e3:Math.max(0,Date.parse(et)-Date.now())||15e3}if(!me.ok&&me.status!==304)throw Ce(`CONFIGURATION_HTTP_${me.status}`,"Configuration synchronization failed");return me}function ni(Y,W,pe){let me=Date.parse(Y.headers.get("x-indiana-config-validated-at")??""),et=Date.parse(Y.headers.get("x-indiana-config-valid-until")??""),at=Date.parse(Y.headers.get("date")??""),Ke=Y.headers.get("age"),sn=Ke!==null&&/^\d+(\.\d+)?$/.test(Ke)?Number(Ke)*1e3:NaN;if(![me,et,at,sn].every(Number.isFinite)||et<=me||et-me>nn.maxControlAgeMs||me>at+1e3)throw Ce("INVALID_RESPONSE","Configuration freshness evidence is invalid");let Bt=Math.min(et-me,pe.maxControlAgeSeconds*1e3,nn.maxControlAgeMs)-Math.max(sn,at-me,0)-(Sr()-W);if(Bt<=0)throw Ce("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return Sr()+Bt}function mt(){if(clearTimeout(y),clearTimeout(A),f||!v.size)return;Se()&&(A=setTimeout(()=>{Se()?mt():he()},Math.max(1,u-Sr())),vy(A));let Y=d?Math.min(15e3,1e3*2**Math.min(d-1,4)):Math.min(15e3,(c?.policy.refreshIntervalSeconds??15)*1e3);y=setTimeout(()=>{Qt().catch(ke)},Math.max(x,Y*(.8+Math.random()*.2))),vy(y)}async function Qt(){if(f)throw Ce("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(h)return h;let Y=g,W=new AbortController;R=W;let pe=(async()=>{if(!le){le=!0;try{let Uo=await s.readManifest();if(Uo&&!c){let $n=Ou.parse(JSON.parse(Uo));Et($n.scope)===Et(t)&&(c=$n)}}catch{}}W.signal.throwIfAborted();let Ke=c,sn=Sr(),$t=await Mo(a,W.signal);$t.status===304&&(!Ke||!$t.headers.has("x-indiana-config-validated-at")||!$t.headers.has("x-indiana-config-valid-until")||!$t.headers.has("age"))&&($t=await Mo(a,W.signal));let Bt=$t.status===304?Ke:Ou.parse(JSON.parse(await De($t,nn.maxManifestBytes,W.signal))),{generation:ri,...ii}=Bt,zn=$t.headers.get("etag");if(Et(Bt.scope)!==Et(t)||tg(ii)!==ri||zn!==`"${ri}"`&&zn!==`W/"${ri}"`)throw Ce("INVALID_RESPONSE","Configuration scope or content identity changed");if(Ke&&(Bt.revision<Ke.revision||Bt.revision===Ke.revision&&Bt.generation!==Ke.generation))throw Ce("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[Uo,$n]of Object.entries(Ke?.funnels??{})){let Or=Bt.funnels[Uo];if(Or&&(Or.controlRevision<$n.controlRevision||Or.evaluationRevision<$n.evaluationRevision||Or.controlRevision===$n.controlRevision&&Or.state!==$n.state||Or.evaluationRevision===$n.evaluationRevision&&Or.evaluationMode!==$n.evaluationMode))throw Ce("INVALID_RESPONSE","Funnel control revision changed identity")}let wr=ni($t,sn,Bt.policy);if(W.signal.throwIfAborted(),Y!==g)throw Ce("CONFIGURATION_DISPOSED","Configuration scope changed");return c=Bt,u=wr,l=Date.now()+Math.max(0,wr-Sr()),m=!1,d=0,x=0,s.writeManifest(Et(Bt)),he(),structuredClone(Bt)})(),me=setTimeout(()=>W.abort(Ce("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),nn.initializationMs),et=new Promise((Ke,sn)=>W.signal.addEventListener("abort",()=>sn(W.signal.reason),{once:!0})),at=Promise.race([pe,et]).catch(Ke=>{throw d++,(Ke instanceof wy.z.ZodError||Ke instanceof SyntaxError||Ke instanceof b&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(Ke.code))&&(u=0,m=!0,he()),Ke}).finally(()=>{clearTimeout(me),h===at&&(h=void 0),mt()});return h=at,at}async function Ir(Y){let W=Y.sha256,pe=ii=>ws(ii,Y);rt(Y.url);let me=j.get(W);if(me){if(me.byteLength!==Y.byteLength)throw Ce("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return j.delete(W),j.set(W,me),me.text}let et=_.get(W);if(et){if(et.byteLength!==Y.byteLength)throw Ce("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return et.promise}let at=new AbortController;P.add(at);let Ke=g,sn=(async()=>{try{let wr=await s.readArtifact(W);if(wr&&pe(wr)){if(at.signal.throwIfAborted(),f||Ke!==g)throw Ce("CONFIGURATION_DISPOSED","Configuration scope changed");return We(W,wr,Y.byteLength),wr}}catch{}at.signal.throwIfAborted();let ii=await Mo(Y.url,at.signal,!0),zn=await De(ii,Y.byteLength,at.signal);if(!pe(zn))throw Ce("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(f||Ke!==g)throw Ce("CONFIGURATION_DISPOSED","Configuration scope changed");return We(W,zn,Y.byteLength),s.writeArtifact(W,zn),zn})(),$t=setTimeout(()=>at.abort(Ce("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),nn.initializationMs),Bt=new Promise((ii,zn)=>at.signal.addEventListener("abort",()=>zn(at.signal.reason),{once:!0})),ri=Promise.race([sn,Bt]).finally(()=>{clearTimeout($t),P.delete(at),_.delete(W)});return _.set(W,{promise:ri,byteLength:Y.byteLength}),ri}async function vr(){return Se()||await Qt(),At(),c}async function Ui(Y){let W,pe=new Promise((me,et)=>{W=setTimeout(()=>et(Ce("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),nn.initializationMs)});try{return await Promise.race([Y(),pe])}finally{clearTimeout(W)}}function Bi(Y,W){if(At(),c?.generation!==Y.generation)throw Ce("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(W&&c.funnels[W]?.state!=="active")throw Ce("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function yl(Y){let W=Y.gb.features;if(!W)throw Ce("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let pe=Y.artifacts[W];if(pe.formatVersion!==1)throw Ce("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let me=Jc.parse(JSON.parse(await Ir(pe)));if(Et(me.scope)!==Et({projectId:t.projectId,environment:t.environment})||me.generation!==pe.generation||me.remoteFeatures.some(et=>Object.hasOwn(me.features,et)))throw Ce("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return Bi(Y),{...me,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,u-Sr())).toISOString()}}async function Al(Y,W){let pe=await vr(),me=pe.funnels[Y];W&&(!me||me.evaluationMode==="local"&&!me.versions[W])&&(h&&await h,pe=await Qt()),Bi(pe,Y);let et=pe.funnels[Y];if(et.evaluationMode!=="local")throw Ce("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let at=W??et.currentVersionId,Ke=et.versions[at];if(!Ke)throw Ce("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(pe.artifacts[Ke.artifact].formatVersion!==3)throw Ce("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[sn,$t]=await Promise.all([Ir(pe.artifacts[Ke.artifact]).then(Bt=>rg(JSON.parse(Bt))),et.evaluationMode==="local"?yl(pe):void 0]);if($t&&Et(ng(sn,$t))!==Et(Ke.dependencies))throw Ce("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return Bi(pe,Y),{document:sn,growth:$t,versionId:at,control:structuredClone(et),manifest:structuredClone(pe)}}async function bl(Y,W){try{return await Al(Y,W)}catch(pe){if(!(pe instanceof b)||!(pe.code==="CONFIGURATION_CHANGED"||pe.code==="CONFIGURATION_HTTP_404"&&Se()))throw pe;let me=c?.generation;if(h&&await h,await Qt(),pe.code!=="CONFIGURATION_CHANGED"&&c?.generation===me)throw pe;return Al(Y,W)}}function Cs(){m=!0,he(),Qt().catch(ke)}let qo=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Cs()};function _y(Y){if(f)throw Ce("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return v.add(Y),v.size===1&&(typeof window<"u"&&(window.addEventListener("online",Cs),window.addEventListener("focus",qo),document.addEventListener("visibilitychange",qo)),mt()),()=>{v.delete(Y),v.size||(clearTimeout(y),clearTimeout(A),xl())}}function xl(){typeof window<"u"&&(window.removeEventListener("online",Cs),window.removeEventListener("focus",qo),document.removeEventListener("visibilitychange",qo))}return{scope:Object.freeze({...t}),refresh:Qt,subscribe:_y,assertFresh:At,assertFeatures(Y){At();let W=c.gb.features;if(!W)throw Ce("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(Y!==void 0&&c.artifacts[W].generation!==Y)throw Ce("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return Se()},get snapshot(){return c?structuredClone(c):null},get remainingMs(){return Se()?Math.max(0,u-Sr()):0},async features(){return Ui(async()=>yl(await vr()))},pageExperiments:()=>Ui(async()=>{let Y=await vr(),W=Y.gb.pageExperiments;if(!W)throw Ce("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let pe=Y.artifacts[W];if(pe.formatVersion!==1)throw Ce("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let me=dh.parse(JSON.parse(await Ir(pe)));if(me.environmentId!==t.environmentId||me.generation!==pe.generation)throw Ce("INVALID_RESPONSE","Page experiment scope or generation changed");return Bi(Y),me}),funnel:(Y,W)=>Ui(()=>bl(Y,W)),paywall:(Y,W)=>Ui(async()=>{let pe=await vr(),me=pe.paywalls?.[Y];if(!me||!W&&me.state!=="published")throw Ce("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let et=W??me.currentVersionId,at=me.versions[et],Ke=at&&pe.artifacts[at.artifact];if(!Ke||Ke.kind!=="paywall"||Ke.formatVersion!==1)throw Ce("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let sn=as.parse(JSON.parse(await Ir(Ke)));return Bi(pe),{document:sn,versionId:et,version:at.version,control:structuredClone(me),manifest:structuredClone(pe)}}),async localFunnel(Y,W){let pe=await Ui(()=>bl(Y,W));if(!pe.growth)throw Ce("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:me,remoteFeatures:et,...at}=pe.growth;return uh({scope:{projectId:t.projectId,environment:t.environment},funnelId:Y,versionId:pe.versionId,evaluationMode:"local",evaluationRevision:pe.control.evaluationRevision,document:pe.document,payload:at})},assertFunnel(Y,W,pe){At();let me=c.funnels[Y];if(!me||me.state!=="active")throw Ce("FUNNEL_STOPPED","Funnel is paused or unavailable");if(me.evaluationMode!=="local")throw Ce("EVALUATION_MODE","This Funnel now executes at Longplay");if(W!==void 0&&me.controlRevision!==W)throw Ce("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(pe!==void 0&&!me.versions[pe])throw Ce("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!f){f=!0,g++,u=0,R?.abort(Ce("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(y),clearTimeout(A),xl(),he(),v.clear();for(let Y of P)Y.abort(Ce("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));j.clear(),X=0}}}}async function Py(e){e={...e};let t=e.configuration;if(!t)throw new b("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let n={projectId:t.scope.projectId,environment:t.scope.environment};if(e.scope&&Et(n)!==Et(e.scope))throw new b("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await t.funnel(e.funnelId)).control.evaluationMode!=="local")throw new b("EVALUATION_MODE","This Funnel uses Remote evaluation");let i=Mi.test(e.credential);if(i?!e.customerId:e.customerId!==void 0)throw new b("INVALID_REQUEST","Only Server-Key starts name their Customer");let a=vs({...e,scope:n,apiKey:e.credential}),o=s=>{let c=xr({...e,scope:n,runToken:s,...i?{serverKey:e.credential}:{}});return i||c.identify(e.credential),c};return{async start(s){let c=await a.start({...s,funnelId:e.funnelId,...i?{customer:{type:"id",value:e.customerId}}:{}}),u=o(c.runToken),l=await u.get();return{...c,...l,controller:u}},async restore(s){let c=o(s),u=await c.get();if(u.run.source.id!==e.funnelId)throw c.reset(),new b("SCOPE_MISMATCH","Run belongs to another Funnel");return{...u,runToken:s,controller:c}}}}function hl(e,...t){try{Promise.resolve(e?.(...t)).catch(()=>{})}catch{}}function Cy(e){if(!e.scope)throw new b("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(e.session!==void 0)throw new b("INVALID_CONFIGURATION","The merchant process adapter owns the session");let t=null,n,r=0,i=new Set,a=new Map,o=new Map;async function s(f){let g,d=new Promise((h,R)=>{g=setTimeout(()=>R(new b("TIMEOUT","Process bridge request timed out")),e.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(f),d])}finally{clearTimeout(g)}}function c(f){throw f instanceof b&&(f.status===401||f.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear()),f}function u(f,g){if(g!==r)throw new b("IDENTITY_CHANGED","Process was detached during a request");let d=zu.parse(f);if(d.scope.projectId!==e.scope.projectId||d.scope.environment!==e.scope.environment)throw new b("SCOPE_MISMATCH","Process response belongs to another App/environment");if(t&&(t.run.id!==d.run.id||t.run.source.versionId!==d.run.source.versionId||t.run.source.id!==d.run.source.id||t.run.runExpiresAt!==d.run.runExpiresAt||t.run.identity.startedAs!==d.run.identity.startedAs||t.run.identity.participantId!==d.run.identity.participantId||t.run.identity.binding&&d.run.identity.binding&&t.run.identity.binding.id!==d.run.identity.binding.id))throw new b("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!t||d.run.revision>=t.run.revision){if(t?.run.identity.binding&&!d.run.identity.binding)throw new b("INVALID_RESPONSE","The process lost its Customer binding");t=d;for(let j of i)hl(j,d.run);d.run.instruction?.type==="authentication_required"&&hl(e.onAuthenticationRequired,d.run)}d.settlement?.accepted!==void 0&&o.set(d.settlement.requestId,d.settlement.accepted);let{identity:h,instruction:R,...y}=d.run,{contract:A,settlement:x,...v}=d,P=x&&(({accepted:j,..._})=>_)(x);return{...v,run:{...y,authenticated:h.binding!==null,instruction:R?.type==="authentication_required"?null:R},...P?{settlement:P}:{}}}let l=f=>(a.has(f)||a.set(f,t?.run.identity.binding?.id??null),a.get(f));async function m(f){let g=r,d=t?.run.identity.binding?.id??null,h=y=>{if(d!==(t?.run.identity.binding?.id??null))throw y;return c(y)};if(f.operation==="page_experiments"){if(!e.adapter.pageExperiments)throw new b("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return s(()=>e.adapter.pageExperiments(f.release,f.usedReceiptIds)).catch(h)}let R;if(f.operation==="get"){let{operation:y,customerToken:A,...x}=f;R=await s(()=>e.adapter.get({...x,...x.settlementRequestId?{settlementBindingId:l(x.settlementRequestId)}:{}})).catch(h)}else if(f.operation==="review")R=await s(()=>e.adapter.review(f.receiptId)).catch(h);else{if(f.operation==="start")throw new b("INVALID_REQUEST","Use process.open for entry");{let{customerToken:y,...A}=f;R=await s(()=>e.adapter.command(A,l(A.requestId))).catch(h)}}return u(R,g)}return{get view(){return t?.run??null},get controller(){return n},async open(f){let g=r,d=await s(()=>e.adapter.open(f)).catch(c);if(u(d,g),!n){n=xr({...e,runToken:d.runToken,process:{request:m,binding:l,restore(y){for(let[A,x]of Object.entries(y))a.set(A,x)}}});let h=n,R=h.submit;h.submit=async y=>{try{return await R(y)}catch(A){if(!(A instanceof b)||A.reason!=="IDENTITY_CONTEXT_CHANGED"||y.operation!=="submit"||y.input.type!=="screen"||a.get(y.requestId)!==null)throw A;await h.settle?.(y.requestId),await h.get();let x=h.view;if(o.get(y.requestId)!==!1||!x||x.id!==t?.run.id||x.nodeId!==y.nodeId||x.visit!==y.visit||!t?.run.identity.binding)throw A;return R({...y,requestId:crypto.randomUUID(),revision:x.revision})}}}await n.get();for(let h of n.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(t?.run.identity.binding?.id??null)&&await n.settle?.(h.requestId);return{run:t.run,controller:n}},async syncIdentity(){let f=r;u(await s(()=>e.adapter.syncIdentity()).catch(c),f),await n?.get();for(let g of n?.pendingCommands??[])a.has(g.requestId)&&a.get(g.requestId)!==(t?.run.identity.binding?.id??null)&&await n?.settle?.(g.requestId);return t.run},async detach(){r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear(),await s(()=>e.adapter.detach())},forProcess(f){if(!t?.run.identity.binding)throw new b("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:t.run.id,bindingId:t.run.identity.binding.id,receiptId:f}},subscribe(f){return i.add(f),()=>{i.delete(f)}},destroy(){r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear(),i.clear()}}}
|