@tinkerlandai/longplay-react-native 0.10.18 → 0.10.19-rc.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +61365 -32414
- package/dist/index.d.ts +61365 -32414
- package/dist/index.js +2 -2
- package/native-sdk/android/assets/indiana/index.html +33 -33
- package/native-sdk/android/java/ai/tinkerland/indiana/MerchantCommerceSemantics.kt +65 -2
- package/native-sdk/android/java/ai/tinkerland/indiana/SDKVersion.kt +1 -1
- package/native-sdk/android/resources/funnel-wire-schemas.json +1 -1
- package/native-sdk/ios/MerchantCommerceSemantics.swift +72 -1
- package/native-sdk/ios/SDKVersion.swift +1 -1
- package/native-sdk/ios/WebView/index.html +33 -33
- package/native-sdk/ios/funnel-wire-schemas.json +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var gy=Object.defineProperty;var hy=(e,t,n)=>t in e?gy(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var qe=(e,t,n)=>hy(e,typeof t!="symbol"?t+"":t,n);import{z as ws}from"zod";var yy=ws.enum(["sandbox","live"]),Ne=ws.object({projectId:ws.string().min(1),environment:yy}).strict();import{z as Ge}from"zod";var qi=Ge.number().int().min(1).max(Number.MAX_SAFE_INTEGER),bl=Ge.enum(["unknown","denied","provisional","granted"]),xl=Ge.enum(["ios","android"]),Mo=Ge.strictObject({installationId:Ge.uuid(),publicKey:Ge.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:Ge.iso.datetime({offset:!0}),signature:Ge.string().regex(/^[A-Za-z0-9_-]{86}$/)}),Os=Ge.string().regex(/^[a-f0-9]{64}$/),Sl=Mo.extend({sequence:qi,platform:xl,credentialDigest:Os}),Il=Mo.extend({credentialDigest:Os}),vl=Mo.extend({sequence:qi,platform:xl}),qo=Mo.extend({sequence:qi,credentialDigest:Os,connectionId:Ge.uuid().nullable(),kind:Ge.enum(["fcm_token","apns_token"]).nullable(),token:Ge.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:bl}),wl=qo,Ol=qo.extend({challenge:Ge.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),Ps=Ge.strictObject({requested:Ge.literal(!0),expiresAt:Ge.iso.datetime({offset:!0})}),Ir=Ge.strictObject({installationId:Ge.uuid(),bound:Ge.boolean(),identitySeq:qi,bindingGeneration:qi,addressSeq:Ge.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:Ge.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:Ge.uuid().nullable(),addressStatus:Ge.enum(["active","invalid"]).nullable(),permission:bl}),Cs=Ge.strictObject({channel:Ge.enum(["email","sms","voice","push"]),state:Ge.enum(["unknown","allowed","denied"]),revision:Ge.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:Ge.iso.datetime({offset:!0}).nullable()}),Bv=Ge.strictObject({state:Ge.enum(["allowed","denied"]),revision:Ge.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function Pl(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))}import{z as Et}from"zod";var $n=Et.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=Et.enum([...$n.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),$v=Et.enum([...$n.options,"stale_revision"]),_s=Et.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"]),Es=Et.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"]),_l={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 Cl={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 Ay(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(Cl,e)){let r=Cl[e];return{retryable:r==="retry_same_request",recovery:r}}let n=$n.safeParse(e);return n.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:_l[n.data].recovery}:{retryable:!1,recovery:"contact_support"}}function El(e,t){let n=$n.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):_l[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 by(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 Rl=Et.object({retryable:Et.boolean(),recovery:_s,reason:Es.optional(),retryAfterSeconds:Et.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),Rs=Et.object({requestId:Et.uuid().optional(),error:Et.object({code:Et.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:Et.string(),...Rl.partial().shape})}),Gv=Et.object({error:Rs.shape.error.extend({requestId:Et.uuid().optional()})}),Kv=Et.object({error:Et.string(),code:Et.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:Et.uuid(),...Rl.shape});function Uo(e,t,n={}){let r=Ay(e,t),i=n.reason==="RESULT_UNKNOWN"?"recover_operation":n.recovery??r.recovery,a=r.retryable&&n.retryable!==!1&&i!=="recover_operation",o=a?by(n.retryAfter??null):void 0;return{...r,retryable:a,recovery:i,...o===void 0?{}:{retryAfterSeconds:o},...n.reason?{reason:n.reason}:{}}}var ks="X-Indiana-Protocol",kl="X-Indiana-SDK-Version";var js={current:"0.10"};import{z as xy}from"zod";var Sy=["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=xy.enum(Sy);import{z as C}from"zod";var Ut=C.string().min(1).max(200),Jt=C.iso.datetime({offset:!0}),xt=C.number().int().nonnegative().max(1e8),Bo=C.string().regex(/^[A-Z]{3}$/),Iy=["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"],jl=C.enum(Iy),Tl=C.strictObject({priceId:C.uuid(),productVersionId:C.uuid(),productId:Ut,quantity:C.number().int().min(1).max(1e6),unitAmountMinor:xt,totalMinor:xt,interval:C.enum(["week","month","year","one_off"]),intervalCount:C.number().int().min(1).max(52),kind:C.enum(["fixed","prepaid","seat"]),tiers:C.strictObject({mode:C.enum(["graduated","volume"]),tiers:C.array(C.strictObject({upTo:C.number().int().positive().nullable(),unitAmountMinor:xt,flatAmountMinor:xt.optional()})).min(2).max(12)}).nullable()}),vy=C.strictObject({grantId:C.uuid(),couponId:C.uuid(),amountMinor:xt,terms:C.discriminatedUnion("type",[C.strictObject({type:C.literal("percent"),percentOff:C.number().gt(0).max(100)}),C.strictObject({type:C.literal("amount"),amountOffMinor:xt,currency:Bo})]),duration:C.discriminatedUnion("type",[C.strictObject({type:C.literal("once")}),C.strictObject({type:C.literal("forever")}),C.strictObject({type:C.literal("repeating"),months:C.number().int().min(1).max(36)})])}),Ns={provider:C.literal("merchant"),executor:C.literal("merchant"),operationId:C.uuid(),customerId:C.uuid(),configurationRevision:C.number().int().nonnegative(),connectionRevision:C.number().int().nonnegative(),currency:Bo,expiresAt:Jt},Vo=C.strictObject({...Ns,type:C.literal("purchase"),mode:C.enum(["payment","subscription"]),lineItems:C.array(Tl).min(1).max(100),catalogAmountMinor:xt,discount:vy.nullable(),trialPeriodDays:C.number().int().min(1).max(730).nullable(),automaticTax:C.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"),Lo=C.strictObject({...Ns,type:C.literal("subscription_change"),subscriptionId:C.uuid(),merchantSubscriptionId:Ut,membershipId:C.uuid(),subscriptionAction:C.enum(["update","cancel","schedule","release"]),supersedesOperationId:C.uuid().nullable(),change:C.discriminatedUnion("type",[C.strictObject({type:C.literal("cancel")}),C.strictObject({type:C.literal("uncancel")}),C.strictObject({type:C.literal("plan"),productVersionId:C.uuid()}),C.strictObject({type:C.literal("seats"),licenseKey:Ut,quantity:C.number().int().nonnegative().max(1e6)}),C.strictObject({type:C.literal("quantity"),internal_feature_id:C.uuid(),quantity:C.number().int().nonnegative().max(1e6)}),C.strictObject({type:C.literal("billing_cycle"),billingCycleAnchor:C.union([C.literal("now"),C.number().int().positive()])})]),timing:C.enum(["immediate","renewal"]),effectiveAt:Jt,creditMinor:xt,debitMinor:xt,totalMinor:xt,discountMinor:xt,taxMinor:xt,proration:C.enum(["none","create_prorations","always_invoice"]),lineItems:C.array(Tl.extend({quantity:C.number().int().nonnegative().max(1e6)})).max(100),removePriceIds:C.array(C.uuid()).max(100)}),zo=C.strictObject({...Ns,type:C.literal("refund"),invoiceId:C.uuid(),merchantInvoiceId:Ut,amountMinor:xt.refine(e=>e>0),mode:C.enum(["full","partial"]),entitlementAction:C.enum(["retain","revoke"]),cancelSubscriptions:C.array(Ut).max(100)}),Nl=C.discriminatedUnion("type",[Vo,Lo,zo]);var Ui=C.strictObject({phase:C.enum(["execution","payment","fulfillment","recording"]),code:$n,reason:Es.optional(),recovery:_s,retryable:C.boolean()}).refine(e=>e.reason!=="RESULT_UNKNOWN"||!e.retryable&&e.recovery==="recover_operation","Unknown financial effects require recovery of the original operation"),Ts={operationId:C.uuid(),customerId:C.uuid(),merchantExecutionId:Ut,fulfillmentStatus:C.enum(["not_started","pending","applied","failed","not_applicable"]),recordingStatus:C.enum(["not_ready","pending","accepted","failed"]),updatedAt:Jt,problem:Ui.nullable(),pollAfterMs:C.number().int().min(1e3).max(6e4).nullable()},vr=C.discriminatedUnion("type",[C.strictObject({...Ts,type:C.literal("purchase"),merchantOrderId:Ut.nullable(),paymentStatus:C.enum(["not_started","pending","succeeded","not_required","failed","expired","unknown"]),checkoutUrl:C.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.strictObject({...Ts,type:C.literal("subscription_change"),status:C.enum(["pending","scheduled","applied","failed","unknown"]),merchantSubscriptionId:Ut,scheduledFor:Jt.nullable()}).refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"A scheduled change retains its future effective time"),C.strictObject({...Ts,type:C.literal("refund"),status:C.enum(["pending","succeeded","failed","unknown"]),merchantRefundId:Ut.nullable()}).refine(e=>e.status!=="succeeded"||e.merchantRefundId!==null,"A successful refund retains its original merchant identity")]),Dl=C.discriminatedUnion("lookup",[C.strictObject({lookup:C.literal("found"),operationId:C.uuid(),customerId:C.uuid(),execution:vr,readAt:Jt}),C.strictObject({lookup:C.literal("not_received"),operationId:C.uuid(),customerId:C.uuid(),execution:C.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"),Ds=C.strictObject({merchantSubscriptionId:Ut,revision:C.number().int().positive(),status:C.enum(["incomplete","trialing","active","past_due","canceled","unpaid","paused","incomplete_expired"]),periodStartsAt:Jt,periodEndsAt:Jt,cancelAtPeriodEnd:C.boolean(),hasDiscounts:C.boolean(),items:C.array(C.strictObject({merchantItemId:Ut,priceId:C.uuid(),quantity:C.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"),Fs=C.strictObject({merchantInvoiceId:Ut,currency:Bo,subtotalMinor:xt,discountMinor:xt,taxMinor:xt,totalMinor:xt,paidMinor:xt,periodStartsAt:Jt.nullable(),periodEndsAt:Jt.nullable(),lines:C.array(C.strictObject({merchantLineId:Ut,priceId:C.uuid(),quantity:C.number().int().nonnegative().max(1e6),subtotalMinor:C.number().int().min(-1e8).max(1e8),discountMinor:xt,taxMinor:xt,totalMinor:C.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.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),customerId:C.uuid(),occurredAt:Jt},Fl=C.enum(["purchase.completed","purchase.closed","subscription.observed","subscription.change.completed","invoice.paid","refund.updated"]),wy=C.strictObject({...Zt,type:C.literal("purchase.completed"),operationId:C.uuid(),merchantOrderId:Ut,paymentStatus:C.enum(["paid","trialing","no_payment_required"]),invoice:Fs.nullable(),subscription:Ds.nullable()}),Oy=C.strictObject({...Zt,type:C.literal("purchase.closed"),operationId:C.uuid(),status:C.enum(["failed","expired","canceled"])}),Py=C.strictObject({...Zt,type:C.literal("subscription.observed"),operationId:C.uuid().nullable(),subscription:Ds}),Cy=C.strictObject({...Zt,type:C.literal("subscription.change.completed"),operationId:C.uuid(),status:C.enum(["scheduled","applied"]),scheduledFor:Jt.nullable(),subscription:Ds,invoice:Fs.nullable()}),_y=C.strictObject({...Zt,type:C.literal("invoice.paid"),merchantSubscriptionId:Ut.nullable(),invoice:Fs}),Ey=C.strictObject({...Zt,type:C.literal("refund.updated"),operationId:C.uuid().nullable(),merchantInvoiceId:Ut.optional(),merchantRefundId:Ut,status:C.enum(["pending","succeeded","failed"]),amountMinor:xt.refine(e=>e>0),currency:Bo}),Ml=[wy.refine(e=>e.paymentStatus!=="paid"||e.invoice!==null,"A paid purchase includes its Invoice"),Oy,Py,Cy.refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"Scheduled and applied changes are distinct facts"),_y,Ey.refine(e=>e.operationId!==null||e.merchantInvoiceId!==void 0,"A native refund names its Invoice")];import{z as T}from"zod";import{z as wr}from"zod";var kt=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,Wn=wr.object({customerId:wr.uuid(),sessionId:wr.uuid(),accessToken:wr.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),refreshToken:wr.string().regex(/^gg_rt_[A-Za-z0-9_-]{43}$/),expiresAt:wr.iso.datetime(),refreshExpiresAt:wr.iso.datetime()});var qs=3;var Ry=["session","catalog","customer_commerce","presentation","presentation_events","purchases","operation_status","billing_records","subscription_changes","refunds"],ky=T.enum(Ry);var jy=T.enum(["bridge.ping","bridge.describe","session.create","catalog.read","customer.commerce.read","presentation.resolve","presentation.report","purchase.execute","operation.read","subscription.change","refund.execute"]),Ul=T.string().regex(/^[A-Za-z0-9_-]{1,64}$/),Ty=T.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(e=>"AEIMQUYcgkosw048".includes(e.at(-1)),"Use canonical base64url for a 32-byte key"),Ny=T.strictObject({keyId:Ul,signingSecret:Ty}),Dy=T.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),Bl=T.array(ky).max(10).refine(e=>new Set(e).size===e.length,"Capabilities must be unique"),Vl=T.strictObject({bridgeVersion:T.literal(qs),projectId:T.uuid(),environmentId:T.uuid(),environment:T.enum(["sandbox","live"]),capabilities:Bl,catalog:T.enum(["endpoint","static","none"]),billingEvents:T.array(Fl).max(6),profiles:T.array(jl).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"})}),Ll=T.strictObject({origin:Dy,requiredCapabilities:Bl}),Fy=T.strictObject({revision:T.number().int().nonnegative(),checkedAt:T.iso.datetime(),outcome:T.enum(["valid","unreachable","invalid","scope_mismatch","authentication_failed","credentials_missing"]),diagnostics:T.strictObject({ping:T.enum(["passed","failed","not_checked"]),authentication:T.enum(["passed","failed","not_checked"]),catalog:T.enum(["passed","failed","not_checked","static","unsupported"])}),manifest:Vl.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.strictObject({projectId:T.uuid(),environmentId:T.uuid(),environment:T.enum(["sandbox","live"]),execution:T.enum(["indiana","record_only"]),accountId:T.string().nullable(),revision:T.number().int().nonnegative(),authentication:T.strictObject({keyId:Ul}).nullable(),secretStoreConfigured:T.boolean().optional(),connection:Ll.nullable(),check:Fy.nullable()});var ql=T.strictObject({projectId:T.uuid(),environmentId:T.uuid()}),aw=T.discriminatedUnion("action",[ql.extend({action:T.literal("save"),revision:T.number().int().nonnegative(),connection:Ll,authentication:Ny.optional()}),ql.extend({action:T.literal("check"),revision:T.number().int().nonnegative()})]),Us=T.strictObject({projectId:T.uuid(),environmentId:T.uuid(),environment:T.enum(["sandbox","live"])});var My=T.strictObject({nativeUserId:T.string().min(1).max(128),session:Wn.strict()}),qy=T.strictObject({nativeUserId:T.string().min(1).max(128),presentation:T.strictObject({customerId:T.uuid(),decisionId:T.uuid(),offeringVersionId:T.uuid(),paywallVersionId:T.uuid(),variant:T.string().min(1).max(128)}).nullable()}),Uy=T.strictObject({decisionId:T.uuid(),eventId:T.uuid()}),$o=T.strictObject({operationId:T.uuid(),customerId:T.uuid()}),Go=T.strictObject({scope:Us,operationId:T.uuid(),customerId:T.uuid(),confirmedAt:T.iso.datetime({offset:!0}).nullable(),initialExecutionAllowed:T.boolean(),instruction:Nl}).refine(e=>e.operationId===e.instruction.operationId&&e.customerId===e.instruction.customerId,"Authority must refer to the original Customer and operation"),Ms=vr,Gn=T.string().min(1).max(120),By=T.string().regex(/^-?[0-9]+(?:\.[0-9]{1,6})?$/),Vy=T.strictObject({revision:Gn,updatedAt:T.iso.datetime(),provider:T.literal("merchant"),items:T.array(T.strictObject({merchantProductId:Gn,productVersionId:T.uuid(),name:T.string().min(1).max(255),kind:T.enum(["subscription","credit_pack"]),merchantPriceId:Gn,currency:T.string().regex(/^[a-z]{3}$/),amountMinor:T.number().int().nonnegative().max(1e8),interval:T.enum(["one_time","month","year"]),intervalCount:T.literal(1),includedCredits:T.string().regex(/^[0-9]{1,18}(?:\.[0-9]{1,6})?$/),creditReset:T.enum(["none","month"]),creditPolicyId:Gn,available:T.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)}),Ly=T.strictObject({customerId:T.uuid(),revision:T.string().min(1).max(128),observedAt:T.iso.datetime(),subscriptions:T.array(T.strictObject({merchantSubscriptionId:Gn,merchantProductId:Gn,productVersionId:T.uuid().nullable(),status:T.enum(["active","trialing","past_due","cancelled","expired"]),currentPeriodStartsAt:T.iso.datetime().nullable(),currentPeriodEndsAt:T.iso.datetime().nullable(),cancelAtPeriodEnd:T.boolean(),scheduledChange:T.strictObject({effectiveAt:T.iso.datetime(),merchantProductId:Gn}).nullable()})).max(100),purchaseHistory:T.strictObject({complete:T.boolean(),hasPaidPurchase:T.boolean(),lastPaidAt:T.iso.datetime().nullable()}),balances:T.array(T.strictObject({bucketId:Gn,key:Gn,available:By,expiresAt:T.iso.datetime().nullable(),nextResetAt:T.iso.datetime().nullable()})).max(100)}),sw=T.strictObject({bridgeVersion:T.literal(qs),requestId:T.uuid(),command:T.string().min(1).max(64),scope:Us,error:T.strictObject({code:T.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:T.string().min(1).max(500),retryable:T.boolean(),recovery:T.string().min(1).max(80)})}),Bi=T.strictObject({}),zy={"bridge.ping":T.strictObject({challenge:T.uuid()}),"bridge.describe":Bi,"session.create":Bi,"catalog.read":Bi,"customer.commerce.read":Bi,"presentation.resolve":Bi,"presentation.report":Uy,"purchase.execute":$o,"operation.read":$o,"subscription.change":$o,"refund.execute":$o},cw={"bridge.ping":T.strictObject({challenge:T.uuid()}),"bridge.describe":Vl,"session.create":My,"catalog.read":Vy,"customer.commerce.read":Ly,"presentation.resolve":qy,"presentation.report":T.strictObject({queued:T.literal(!0)}),"purchase.execute":Ms,"operation.read":Dl,"subscription.change":Ms,"refund.execute":Ms},uw=T.strictObject({bridgeVersion:T.literal(qs),requestId:T.uuid(),scope:Us,command:jy,data:T.unknown()}).superRefine((e,t)=>{zy[e.command].safeParse(e.data).success||t.addIssue({code:"custom",path:["data"],message:"Invalid command data"})});import{z as Yr}from"zod";var Ko=Yr.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"),mw=Yr.object({amountCents:Yr.number().int().min(0).max(1e8),currency:Ie,interval:Yr.enum(["free","month","year"]),currencyOptions:Yr.partialRecord(Ie,Yr.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");import{z as F}from"zod";var $y=F.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Gl=F.enum(["single_use","continuous_use"]),Bs=F.record(F.string(),F.union([F.string(),F.number(),F.boolean()]).transform(String).pipe(F.string())),zl=F.string().min(1).max(64).refine(e=>!e.includes("::")),Kl={credit_amount:F.number(),tier_behavior:F.never().optional(),tiers:F.never().optional()},Hl={credit_amount:F.never().optional(),tier_behavior:F.literal("graduated"),tiers:F.array(F.strictObject({to:F.union([F.number(),F.literal("inf")]),credit_amount:F.number()}))},Gy=F.union([F.strictObject({match:Bs,priority:F.number().int().optional(),...Kl}),F.strictObject({match:Bs,priority:F.number().int().optional(),...Hl})]),Ky=F.strictObject({match:Bs,factor:F.number().positive().optional(),add:F.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),$l={metered_feature_id:F.string(),feature_amount:F.number().optional(),dimensions:F.record(zl,Gy).optional(),multipliers:F.record(zl,Ky).optional()},Vs=F.union([F.strictObject({...$l,...Kl}),F.strictObject({...$l,...Hl})]),Qo=F.number().min(-100),Ql=F.record(F.string(),F.strictObject({markup:Qo})).nullish(),Jo=F.record(F.string().regex(/.+\/.+/),F.strictObject({markup:Qo.optional(),input_cost:F.number().min(0).optional(),output_cost:F.number().min(0).optional()})).nullish(),Hy=F.strictObject({default_markup:Qo.optional(),provider_markups:Ql,model_markups:Jo}),hw=F.strictObject({schema:F.array(Vs).optional(),markups:Hy.optional()}),Qy=F.strictObject({filters:F.array(F.strictObject({property:F.string(),operator:F.string(),value:F.array(F.string())})),aggregate:F.strictObject({type:F.string(),property:F.string().nullable()}),usage_type:Gl}),Jl=F.strictObject({schema:F.array(Vs).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.boolean().optional(),usage_type:Gl.default("single_use").overwrite(()=>"single_use"),default_markup:Qo.optional(),provider_markups:Ql}),Ls=Jl.safeExtend({schema:F.array(Vs).length(0)}),Ho={id:$y,name:F.string().min(1),display:F.strictObject({singular:F.string().optional(),plural:F.string().optional()}).nullish(),event_names:F.array(F.string()).default([]),model_markups:Jo,stripe_meter:F.strictObject({id:F.string(),event_name:F.string()}).nullish(),stripe_product_id:F.string().nullish()},zs=e=>F.discriminatedUnion("type",[F.strictObject({...Ho,...e,type:F.literal("boolean"),config:F.null()}),F.strictObject({...Ho,...e,type:F.literal("metered"),config:Qy}),F.strictObject({...Ho,...e,type:F.literal("credit_system"),config:Jl}),F.strictObject({...Ho,...e,type:F.literal("ai_credit_system"),config:Ls})]),yw=zs({}),Jy=F.strictObject({id:F.boolean(),type:F.boolean(),usage_type:F.boolean()}),Zy={internal_id:F.uuid(),org_id:F.uuid(),created_at:F.number(),env:F.enum(["sandbox","live"]),archived:F.boolean(),project_id:F.uuid(),environment_id:F.uuid(),revision:F.number().int().nonnegative(),update_rules:Jy},Zl=zs(Zy),Aw=F.strictObject({rows:F.array(Zl).max(200),nextCursor:F.uuid().nullable()}),bw=F.strictObject({features:F.array(Zl).max(500),limited:F.boolean()}),xw=F.union([zs({action:F.literal("save"),internal_id:F.uuid().nullable(),revision:F.number().int().nonnegative()}),F.strictObject({action:F.enum(["archive","restore","delete"]),internal_id:F.uuid(),revision:F.number().int().nonnegative()})]);import{z as ti}from"zod";import{z as dt}from"zod";var Wt=dt.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),xe=dt.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),Zo=dt.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}),$s=xe.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),Wl=dt.string().min(1).max(64),Or=dt.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Yl=dt.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),vt=dt.record(Wl,dt.union([dt.string().max(120),dt.number().finite(),dt.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)]))),Xl=dt.record(Wl,dt.union([dt.string().max(120),dt.number().finite(),dt.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),Xr=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},ed=dt.array(dt.object({upTo:$s.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&&Xr(t.upTo)>Xr(r))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),Wy=dt.object({key:Yl,match:Xl,priority:dt.number().int().default(0),cost:xe.optional(),tiers:ed.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),Yy=dt.object({key:Yl,match:Xl,factor:$s.optional(),add:Zo.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"})),Xy=dt.object({units:$s.default("1"),cost:xe,tiers:ed.optional(),dimensions:dt.array(Wy).max(12).optional(),multipliers:dt.array(Yy).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=Xr(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=Xr(o),l=BigInt("1"),m=BigInt("0");for(let[d,h]of r.entries())s&1<<d&&(u*=Xr(h.factor??"1"),l*=BigInt("1000000"),m+=Xr(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"})}}),vw=Xy.safeExtend({featureKey:Or});import{z as ei}from"zod";var td=ei.number().int().min(0).max(1e8),Vi=ei.strictObject({kind:ei.enum(["graduated","volume"]),tiers:ei.array(ei.strictObject({upTo:ei.number().int().min(1).max(1e4).nullable(),unitAmountMinor:td,flatAmountMinor:td.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 Gs(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let n=e.pricing?Vi.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 Wo(e){return Gs({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}var eA=xe.refine(e=>/[1-9]/.test(e)),Yo=ti.strictObject({units:eA,prices:ti.array(ti.strictObject({currency:Ie,amountMinor:ti.number().int().min(0).max(1e8),pricing:Vi.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:ti.number().int().min(0).max(1e4),maximumQuantity:ti.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&&Gs({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 nd(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 rd(e,t,n){if(!Number.isSafeInteger(n)||n<0||n>1e4)throw new Error("Invalid purchased quantity");let r=nd(e)+nd(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:"")}import{z as S}from"zod";import{z as te}from"zod";import{z as Tt}from"zod";import{z as N}from"zod";function id(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 Xo(e,t,n){return n===2?id(id(e+t)+"")%1e4/1e4:null}function tA(e){return e<=0?[]:new Array(e).fill(1/e)}function ea(e,t){return e>=t[0]&&e<t[1]}function od(e,t){for(let[n,r]of t.entries())if(ea(e,r))return n;return-1}function ad(e,t,n){t=t===void 0?1:t,t<0?t=0:t>1&&(t=1);let r=tA(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 sd(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 cd(e){try{return e()}catch{return!1}}function Li(e){return typeof e=="string"?e:JSON.stringify(e)}function an(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 nA(e){try{let t=e.replace(/([^\\])\//g,"$1\\/");return new RegExp(t)}catch{return}}function ud(e,t){if(!t.length)return!1;let n=!1,r=!1;for(let i of t){let a=oA(e,i.type,i.pattern);if(i.include===!1){if(a)return!1}else n=!0,a&&(r=!0)}return r||!n}function rA(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=>!rA(i[0],i[1],i[2]))}catch{return!1}}function oA(e,t,n){try{let r=new URL(e,"https://_");if(t==="regex"){let i=nA(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 Ks(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 ta(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 ld(e){for(let t of["overrides","groups"])if(Object.hasOwn(e,t))throw new TypeError(`Retired evaluation context field: ${t}`);ta(e.savedGroups??{})}var aA=e=>e/2**32|0,sA=e=>e>>>0;function dd(e,t,n,r){let i=aA(n),a=sA(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function pd(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var Hs=e=>e?`"${e}" `:"";function cA(e,t=""){if(typeof e!="number")throw new TypeError(Hs(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(Hs(t)+"expected integer >= 0, got "+e);return e}function na(e,t,n=""){if(pd(e)&&(t===void 0||e.length===t))return e;t!==void 0&&cA(t,"length");let r=pd(e),i=t!==void 0?` of length ${t}`:"",a=r?`length=${e.length}`:`type=${typeof e}`,o=Hs(n)+"expected Uint8Array"+i+", got "+a;throw r?new RangeError(o):new TypeError(o)}var uA=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},md=(e,t)=>{uA(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 Qs(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function fd(e,t){na(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function Js(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ra(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Sn(e,t){return e<<32-t|e>>>t}var lA=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",dA=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function ni(e){if(na(e),lA)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=dA[e[n]];return t}function pA(e,t,n="opts"){return md(e,"defaults"),t!==void 0&&md(t,n),Object.assign(Object.create(null),e,t)}function gd(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=pA({},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 hd=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function yd(e,t,n){return e&t^~e&n}function Ad(e,t,n){return e&t^e&n^t&n}var ia=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=ra(this.buffer)}update(t){Qs(this),na(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=ra(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){Qs(this),fd(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)),dd(r,i-8,this.length*8,a),this.process(r,0),this.roundClean();let s=t===n?r:ra(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()}},bd=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var mA=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]),Yn=new Uint32Array(64),Zs=class extends ia{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)Yn[f]=n.getUint32(r,!1);for(let f=16;f<64;f++){let g=Yn[f-15],d=Yn[f-2],h=Sn(g,7)^Sn(g,18)^g>>>3,R=Sn(d,17)^Sn(d,19)^d>>>10;Yn[f]=R+Yn[f-7]+h+Yn[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=Sn(c,6)^Sn(c,11)^Sn(c,25),d=m+g+yd(c,u,l)+mA[f]+Yn[f]|0,R=(Sn(i,2)^Sn(i,13)^Sn(i,22))+Ad(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(){Js(Yn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Js(this.buffer)}},Ws=class extends Zs{constructor(){super(32,bd)}};var ri=gd(()=>new Ws,hd(1));var xd=new Map,Ys=32,Sd=new WeakMap,Id=new WeakMap;function fA(e){return ni(ri(new TextEncoder().encode(String(e))))}var aa=e=>Array.isArray(e)?e.map(aa):typeof e=="string"||typeof e=="number"?fA(e):null,oa=e=>typeof e=="string"?e.toLowerCase():e;function Cd(e){let t=Sd.get(e);return t||(t=new Set(e),Sd.set(e,t)),t}function gA(e){let t=Id.get(e);return t||(t=new Set(e.map(oa)),Id.set(e,t)),t}function ii(e){ta(e);for(let t of Object.values(e)){let n=t?.type==="list"||t?.type==="hashed"?t.values:null;n&&n.length>=Ys&&Cd(n)}return e}function en(e,t,n,r){n=n||{},r||ta(n),r=r||new Set;for(let[i,a]of Object.entries(t))switch(i){case"$or":if(!Pd(e,a,n,r))return!1;break;case"$nor":if(Pd(e,a,n,r))return!1;break;case"$and":if(!xA(e,a,n,r))return!1;break;case"$not":if(en(e,a,n,r))return!1;break;case"$savedGroup":if(!hA(e,a,n,r))return!1;break;default:if(!zi(a,_d(e,i),n,!1,r))return!1}return!0}function hA(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=_d(e,c);return Pr(o.type==="hashed"?aa(u):u,o.values)}return o.type==="condition"?!o.condition||typeof o.condition!="object"?!1:en(e,o.condition,n,s):!1}function _d(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 vd(e,t=!1){let n=`${e}${t?"/i":""}`,r=xd.get(n);return r||(r=new RegExp(e.replace(/([^\\])\//g,"$1\\/"),t?"i":void 0),xd.set(n,r)),r}function zi(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)||!Ed(e))return JSON.stringify(t)===JSON.stringify(e);let a=e;for(let o in a)if(!bA(o,t,a[o],n,i))return!1;return!0}function Ed(e){let t=Object.keys(e);return t.length>0&&t.filter(n=>n[0]==="$").length===t.length}function yA(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 AA(e,t,n,r){if(!Array.isArray(e))return!1;let i=Ed(t)?a=>zi(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 Pr(e,t,n=!1){if(n){let i;if(t.length>=Ys){let a=gA(t);i=o=>{let s=oa(o);return!(typeof s=="number"&&Number.isNaN(s))&&a.has(s)}}else i=a=>t.some(o=>oa(a)===oa(o));return Array.isArray(e)?e.some(a=>i(a)):i(e)}let r=t.length>=Ys?(i=>a=>i.has(a))(Cd(t)):i=>t.includes(i);return Array.isArray(e)?e.some(i=>r(i)):r(e)}function wd(e){return e===void 0?[]:e&&typeof e=="object"&&(e.type==="list"||e.type==="hashed")&&Array.isArray(e.values)?e.values:null}function Od(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(zi(t[a],e[s],n,r,i)){o=!0;break}if(!o)return!1}return!0}function bA(e,t,n,r,i=new Set){let a=t,o=n;switch(e){case"$veq":return an(t)===an(n);case"$vne":return an(t)!==an(n);case"$vgt":return an(t)>an(n);case"$vgte":return an(t)>=an(n);case"$vlt":return an(t)<an(n);case"$vlte":return an(t)<=an(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)?Pr(t,n):!1;case"$ini":return Array.isArray(n)?Pr(t,n,!0):!1;case"$inGroup":{let s=r[n],c=wd(s);return c===null?!1:Pr(s?.type==="hashed"?aa(t):t,c)}case"$notInGroup":{let s=r[n],c=wd(s);return c===null?!1:!Pr(s?.type==="hashed"?aa(t):t,c)}case"$nin":return Array.isArray(n)?!Pr(t,n):!1;case"$nini":return Array.isArray(n)?!Pr(t,n,!0):!1;case"$not":return!zi(n,t,r,!1,i);case"$size":return Array.isArray(t)?zi(n,t.length,r,!1,i):!1;case"$elemMatch":return AA(t,n,r,i);case"$all":return Array.isArray(n)?Od(t,n,r,!1,i):!1;case"$alli":return Array.isArray(n)?Od(t,n,r,!0,i):!1;case"$regex":try{return vd(n).test(t)}catch{return!1}case"$regexi":try{return vd(n,!0).test(t)}catch{return!1}case"$type":return yA(t)===n;default:return!1}}function Pd(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 xA(e,t,n,r){for(let i of t)if(!en(e,i,n,r))return!1;return!0}function Xs(e){return ld(e),{context:e,stack:{evaluatedFeatures:new Set}}}function ec(e){return{...e.attributes,...e.attributeOverrides}}function Xn(e,t,n){let r=t||"id",i="",a=ec(e);return a[r]&&(i=a[r]),!i&&n&&(a[n]&&(i=a[n]),i&&(r=n)),{hashAttribute:r,hashValue:i}}function Ze(e,t,n){e.context.log?.(t,n)}function sa(e,t){return t=t||0,`${e}__${t}`}function tc(e,t){return`${e}||${t}`}function SA(e,t,n){let r=e.stickyBucketAssignmentDocs;if(!r)return{};let{hashAttribute:i,hashValue:a}=Xn(e,t),o=tc(i,Li(a)),{hashAttribute:s,hashValue:c}=Xn(e,n),u=c?tc(s,Li(c)):null,l={};return u&&r[u]&&Object.assign(l,r[u].assignments||{}),r[o]&&Object.assign(l,r[o].assignments||{}),l}function Rd({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=sa(t,n),c=SA(e,r,i);if(a>0)for(let m=0;m<a;m++){let f=sa(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 kd(e,t,n,r){let i=tc(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 jd(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function ca(e,t){let n=Xs(t),r=Nd(e,null,n);return t.onExperimentEval?.(e,r),r}function Kn(e,t){return rc(e,Xs(t))}function IA(e){return e.forcedVariations||{}}function Td(e,t,n){let{context:r}=e;if(r.trackedExperiments){let i=Md(t,n);if(r.trackedExperiments.has(i))return;r.trackedExperiments.add(i)}nc(()=>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}nc(()=>r.onFeatureUsage?.(t,n))}function nc(e){try{let t=e();t&&typeof t.catch=="function"&&t.catch(()=>{})}catch{}}function rc(e,t){let{context:n}=t;if(t.stack.evaluatedFeatures.has(e))return Ze(t,`evalFeature: circular dependency detected: ${t.stack.id} -> ${e}`,{from:t.stack.id,to:e}),er(t,e,null,"cyclicPrerequisite");t.stack.evaluatedFeatures.add(e),t.stack.id=e;let r=n.features?.[e];for(let a of r?.rules??[])Ks(a);let i=n.forcedFeatureValues;if(i&&i.has(e))return Ze(t,"Global override",{id:e,value:i.get(e)}),er(t,e,i.get(e),"override");if(!r)return Ze(t,"Unknown feature",{id:e}),er(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=rc(u.id,t);if(l.source==="cyclicPrerequisite")return er(t,e,null,"cyclicPrerequisite");let m={value:l.value};if(!en(m,u.condition||{},n.savedGroups||{})){if(u.gate)return Ze(t,"Feature blocked by prerequisite",{id:e,rule:o}),er(t,e,null,"prerequisite");Ze(t,"Skip rule because prerequisite evaluation fails",{id:e,rule:o});continue e}}if(o.filters&&Fd(o.filters,t)){Ze(t,"Skip rule because of filters",{id:e,rule:o});continue}if("force"in o){if(o.condition&&!Dd(o.condition,t)){Ze(t,"Skip rule because of condition ff",{id:e,rule:o});continue}if(!wA(t,o.seed||e,o.hashAttribute,n.saveStickyBucketAssignmentDoc&&!o.disableStickyBucketing?o.fallbackAttribute:void 0,o.range,o.coverage,o.hashVersion)){Ze(t,"Skip rule because user not included in rollout",{id:e,rule:o});continue}return Ze(t,"Force value from rule",{id:e,rule:o}),o.tracks&&o.tracks.forEach(u=>{Td(t,u.experiment,u.result)}),er(t,e,o.force,"force",o.id)}if(!o.variations){Ze(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=Nd(s,e,t);if(n.onExperimentEval?.(s,c),c.inExperiment&&!c.passthrough)return er(t,e,c.value,"experiment",o.id,s,c)}}return Ze(t,"Use default value",{id:e,value:r.defaultValue}),er(t,e,r.defaultValue===void 0?null:r.defaultValue,"defaultValue")}function Nd(e,t,n){let{context:r}=n;Ks(e);let i=e.key,a=e.variations.length;if(a<2)return Ze(n,"Invalid experiment",{id:i}),jt(n,e,-1,!1,t);if(r.enabled===!1)return Ze(n,"Context disabled",{id:i}),jt(n,e,-1,!1,t);if(e.urlPatterns&&!ud(r.url||"",e.urlPatterns))return Ze(n,"Skip because of url targeting",{id:i}),jt(n,e,-1,!1,t);let o=sd(i,r.url||"",a);if(o!==null)return Ze(n,"Force via querystring",{id:i,variation:o}),jt(n,e,o,!1,t);let c=IA(r)[i];if(c!==void 0)return Ze(n,"Force via dev tools",{id:i,variation:c}),jt(n,e,c,!1,t);if(e.active===!1)return Ze(n,"Skip because inactive",{id:i}),jt(n,e,-1,!1,t);let{hashAttribute:u,hashValue:l}=Xn(r,e.hashAttribute,r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0);if(!l)return Ze(n,"Skip because missing hashAttribute",{id:i}),jt(n,e,-1,!1,t);let m=-1,f=!1,g=!1;if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{variation:R,versionIsBlocked:y}=Rd(jd({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&&Fd(e.filters,n))return Ze(n,"Skip because of filters",{id:i}),jt(n,e,-1,!1,t);if(e.include&&!cd(e.include))return Ze(n,"Skip because of include function",{id:i}),jt(n,e,-1,!1,t);if(e.condition&&!Dd(e.condition,n))return Ze(n,"Skip because of condition exp",{id:i}),jt(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=rc(y.id,n);if(A.source==="cyclicPrerequisite")return jt(n,e,-1,!1,t);let x={value:A.value};if(!en(x,y.condition||{},r.savedGroups||{}))return Ze(n,"Skip because prerequisite evaluation fails",{id:i}),jt(n,e,-1,!1,t)}}}let d=Xo(e.seed||i,l,e.hashVersion??2);if(d===null)return Ze(n,"Skip because of invalid hash version",{id:i}),jt(n,e,-1,!1,t);if(!f){let R=e.ranges||ad(a,e.coverage===void 0?1:e.coverage,e.weights);m=od(d,R)}if(g)return Ze(n,"Skip because sticky bucket version is blocked",{id:i}),jt(n,e,-1,!1,t,void 0,!0);if(m<0)return Ze(n,"Skip because of coverage",{id:i}),jt(n,e,-1,!1,t);if("force"in e)return Ze(n,"Force variation",{id:i,variation:e.force}),jt(n,e,e.force===void 0?-1:e.force,!1,t);if(r.qaMode)return Ze(n,"Skip because QA mode",{id:i}),jt(n,e,-1,!1,t);let h=jt(n,e,m,!0,t,d,f);if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{changed:R,key:y,doc:A}=kd(r,u,Li(l),{[sa(e.key,e.bucketVersion)]:h.key});if(R){r.stickyBucketAssignmentDocs=r.stickyBucketAssignmentDocs||{},r.stickyBucketAssignmentDocs[y]=A;let x=r.saveStickyBucketAssignmentDoc;nc(()=>x(A))}}return Td(n,e,h),Ze(n,"In experiment",{id:i,variation:h.variationId}),h}function er(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 Dd(e,t){return en(ec(t.context),e,t.context.savedGroups||{})}function Fd(e,t){return e.some(n=>{let{hashValue:r}=Xn(t.context,n.attribute);if(!r)return!0;let i=Xo(n.seed,r,n.hashVersion||2);return i===null?!0:!n.ranges.some(a=>ea(i,a))})}function wA(e,t,n,r,i,a,o){if(!i&&a===void 0)return!0;if(!i&&a===0)return!1;let{hashValue:s}=Xn(e.context,n,r);if(!s)return!1;let c=Xo(t,s,o??2);return c===null?!1:i?ea(c,i):a!==void 0?c<=a:!0}function jt(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}=Xn(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 Md(e,t){return t.hashAttribute+t.hashValue+e.key+t.variationId}/*!
|
|
1
|
+
var Xy=Object.defineProperty;var eA=(e,t,n)=>t in e?Xy(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Be=(e,t,n)=>eA(e,typeof t!="symbol"?t+"":t,n);import{z as Gs}from"zod";var Ks=Gs.enum(["sandbox","live"]),De=Gs.object({projectId:Gs.string().min(1),environment:Ks}).strict();import{z as He}from"zod";var Zi=He.number().int().min(1).max(Number.MAX_SAFE_INTEGER),Hl=He.enum(["unknown","denied","provisional","granted"]),Ql=He.enum(["ios","android"]),ta=He.strictObject({installationId:He.uuid(),publicKey:He.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:He.iso.datetime({offset:!0}),signature:He.string().regex(/^[A-Za-z0-9_-]{86}$/)}),Hs=He.string().regex(/^[a-f0-9]{64}$/),Jl=ta.extend({sequence:Zi,platform:Ql,credentialDigest:Hs}),Zl=ta.extend({credentialDigest:Hs}),Wl=ta.extend({sequence:Zi,platform:Ql}),na=ta.extend({sequence:Zi,credentialDigest:Hs,connectionId:He.uuid().nullable(),kind:He.enum(["fcm_token","apns_token"]).nullable(),token:He.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:Hl}),Yl=na,Xl=na.extend({challenge:He.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),Qs=He.strictObject({requested:He.literal(!0),expiresAt:He.iso.datetime({offset:!0})}),kr=He.strictObject({installationId:He.uuid(),bound:He.boolean(),identitySeq:Zi,bindingGeneration:Zi,addressSeq:He.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:He.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:He.uuid().nullable(),addressStatus:He.enum(["active","invalid"]).nullable(),permission:Hl}),Js=He.strictObject({channel:He.enum(["email","sms","voice","push"]),state:He.enum(["unknown","allowed","denied"]),revision:He.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:He.iso.datetime({offset:!0}).nullable()}),Ew=He.strictObject({state:He.enum(["allowed","denied"]),revision:He.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function ed(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))}import{z as kt}from"zod";var Jn=kt.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"]),jw=kt.enum([...Jn.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),Tw=kt.enum([...Jn.options,"stale_revision"]),Zs=kt.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"]),Ws=kt.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"]),nd={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 td={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 tA(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(td,e)){let r=td[e];return{retryable:r==="retry_same_request",recovery:r}}let n=Jn.safeParse(e);return n.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:nd[n.data].recovery}:{retryable:!1,recovery:"contact_support"}}function rd(e,t){let n=Jn.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):nd[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 nA(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 id=kt.object({retryable:kt.boolean(),recovery:Zs,reason:Ws.optional(),retryAfterSeconds:kt.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),Ys=kt.object({requestId:kt.uuid().optional(),error:kt.object({code:kt.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:kt.string(),...id.partial().shape})}),Nw=kt.object({error:Ys.shape.error.extend({requestId:kt.uuid().optional()})}),Dw=kt.object({error:kt.string(),code:kt.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:kt.uuid(),...id.shape});function ra(e,t,n={}){let r=tA(e,t),i=n.reason==="RESULT_UNKNOWN"?"recover_operation":n.recovery??r.recovery,a=r.retryable&&n.retryable!==!1&&i!=="recover_operation",o=a?nA(n.retryAfter??null):void 0;return{...r,retryable:a,recovery:i,...o===void 0?{}:{retryAfterSeconds:o},...n.reason?{reason:n.reason}:{}}}var Xs="X-Indiana-Protocol",od="X-Indiana-SDK-Version";var ec={current:"0.10"};import{z as rA}from"zod";var iA=["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=rA.enum(iA);import{z as P}from"zod";var jt=P.string().min(1).max(200),en=P.iso.datetime({offset:!0}),It=P.number().int().nonnegative().max(1e8),ia=P.string().regex(/^[A-Z]{3}$/),oA=["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"],ad=P.enum(oA),si=P.strictObject({priceId:P.uuid(),productVersionId:P.uuid(),productId:jt,quantity:P.number().int().min(1).max(1e6),unitAmountMinor:It,totalMinor:It,interval:P.enum(["week","month","year","one_off"]),intervalCount:P.number().int().min(1).max(52),kind:P.enum(["fixed","prepaid","seat"]),tiers:P.strictObject({mode:P.enum(["graduated","volume"]),tiers:P.array(P.strictObject({upTo:P.number().int().positive().nullable(),unitAmountMinor:It,flatAmountMinor:It.optional()})).min(2).max(12)}).nullable()}),aA=P.strictObject({grantId:P.uuid(),couponId:P.uuid(),amountMinor:It,terms:P.discriminatedUnion("type",[P.strictObject({type:P.literal("percent"),percentOff:P.number().gt(0).max(100)}),P.strictObject({type:P.literal("amount"),amountOffMinor:It,currency:ia})]),duration:P.discriminatedUnion("type",[P.strictObject({type:P.literal("once")}),P.strictObject({type:P.literal("forever")}),P.strictObject({type:P.literal("repeating"),months:P.number().int().min(1).max(36)})])}),nc={provider:P.literal("merchant"),executor:P.literal("merchant"),operationId:P.uuid(),customerId:P.uuid(),configurationRevision:P.number().int().nonnegative(),connectionRevision:P.number().int().nonnegative(),currency:ia,expiresAt:en},oa=P.strictObject({...nc,type:P.literal("purchase"),mode:P.enum(["payment","subscription"]),lineItems:P.array(si).min(1).max(100),catalogAmountMinor:It,discount:aA.nullable(),trialPeriodDays:P.number().int().min(1).max(730).nullable(),automaticTax:P.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"),nr=P.strictObject({...nc,type:P.literal("subscription_change"),subscriptionId:P.uuid(),merchantSubscriptionId:jt,membershipId:P.uuid(),subscriptionAction:P.enum(["update","cancel","schedule","release"]),supersedesOperationId:P.uuid().nullable(),change:P.discriminatedUnion("type",[P.strictObject({type:P.literal("cancel")}),P.strictObject({type:P.literal("uncancel")}),P.strictObject({type:P.literal("plan"),productVersionId:P.uuid()}),P.strictObject({type:P.literal("seats"),licenseKey:jt,quantity:P.number().int().nonnegative().max(1e6)}),P.strictObject({type:P.literal("quantity"),internal_feature_id:P.uuid(),quantity:P.number().int().nonnegative().max(1e6)}),P.strictObject({type:P.literal("billing_cycle"),billingCycleAnchor:P.union([P.literal("now"),P.number().int().positive()])})]),timing:P.enum(["immediate","renewal"]),effectiveAt:en,creditMinor:It,debitMinor:It,totalMinor:It,discountMinor:It,taxMinor:It,proration:P.enum(["none","create_prorations","always_invoice"]),lineItems:P.array(si.extend({quantity:P.number().int().nonnegative().max(1e6)})).max(100),removePriceIds:P.array(P.uuid()).max(100)}),aa=P.strictObject({...nc,type:P.literal("refund"),invoiceId:P.uuid(),merchantInvoiceId:jt,amountMinor:It.refine(e=>e>0),mode:P.enum(["full","partial"]),entitlementAction:P.enum(["retain","revoke"]),cancelSubscriptions:P.array(jt).max(100)}),sd=P.discriminatedUnion("type",[oa,nr,aa]);var Wi=P.strictObject({phase:P.enum(["execution","payment","fulfillment","recording"]),code:Jn,reason:Ws.optional(),recovery:Zs,retryable:P.boolean()}).refine(e=>e.reason!=="RESULT_UNKNOWN"||!e.retryable&&e.recovery==="recover_operation","Unknown financial effects require recovery of the original operation"),tc={operationId:P.uuid(),customerId:P.uuid(),merchantExecutionId:jt,fulfillmentStatus:P.enum(["not_started","pending","applied","failed","not_applicable"]),recordingStatus:P.enum(["not_ready","pending","accepted","failed"]),updatedAt:en,problem:Wi.nullable(),pollAfterMs:P.number().int().min(1e3).max(6e4).nullable()},jr=P.discriminatedUnion("type",[P.strictObject({...tc,type:P.literal("purchase"),merchantOrderId:jt.nullable(),paymentStatus:P.enum(["not_started","pending","succeeded","not_required","failed","expired","unknown"]),checkoutUrl:P.url().refine(e=>new URL(e).protocol==="https:").nullable(),checkoutExpiresAt:en.nullable()}).refine(e=>!e.checkoutUrl||["not_started","pending"].includes(e.paymentStatus)&&e.checkoutExpiresAt!==null,"Only an unfinished original purchase may expose its checkout"),P.strictObject({...tc,type:P.literal("subscription_change"),status:P.enum(["pending","scheduled","applied","failed","unknown"]),merchantSubscriptionId:jt,scheduledFor:en.nullable()}).refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"A scheduled change retains its future effective time"),P.strictObject({...tc,type:P.literal("refund"),status:P.enum(["pending","succeeded","failed","unknown"]),merchantRefundId:jt.nullable()}).refine(e=>e.status!=="succeeded"||e.merchantRefundId!==null,"A successful refund retains its original merchant identity")]),cd=P.discriminatedUnion("lookup",[P.strictObject({lookup:P.literal("found"),operationId:P.uuid(),customerId:P.uuid(),execution:jr,readAt:en}),P.strictObject({lookup:P.literal("not_received"),operationId:P.uuid(),customerId:P.uuid(),execution:P.null(),readAt:en})]).refine(e=>!e.execution||e.execution.operationId===e.operationId&&e.execution.customerId===e.customerId,"Lookup must retain the original Customer and operation"),rc=P.strictObject({merchantSubscriptionId:jt,revision:P.number().int().positive(),status:P.enum(["incomplete","trialing","active","past_due","canceled","unpaid","paused","incomplete_expired"]),periodStartsAt:en,periodEndsAt:en,cancelAtPeriodEnd:P.boolean(),hasDiscounts:P.boolean(),items:P.array(P.strictObject({merchantItemId:jt,priceId:P.uuid(),quantity:P.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"),ic=P.strictObject({merchantInvoiceId:jt,currency:ia,subtotalMinor:It,discountMinor:It,taxMinor:It,totalMinor:It,paidMinor:It,periodStartsAt:en.nullable(),periodEndsAt:en.nullable(),lines:P.array(P.strictObject({merchantLineId:jt,priceId:P.uuid(),quantity:P.number().int().nonnegative().max(1e6),subtotalMinor:P.number().int().min(-1e8).max(1e8),discountMinor:It,taxMinor:It,totalMinor:P.number().int().min(-1e8).max(2e8),periodStartsAt:en.nullable(),periodEndsAt:en.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"),Ht={eventId:P.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),customerId:P.uuid(),occurredAt:en},ud=P.enum(["purchase.completed","purchase.closed","subscription.observed","subscription.change.completed","subscription.change.closed","invoice.paid","refund.updated"]),sA=P.strictObject({...Ht,type:P.literal("purchase.completed"),operationId:P.uuid(),merchantOrderId:jt,paymentStatus:P.enum(["paid","trialing","no_payment_required"]),invoice:ic.nullable(),subscription:rc.nullable()}),cA=P.strictObject({...Ht,type:P.literal("purchase.closed"),operationId:P.uuid(),status:P.enum(["failed","expired","canceled"])}),uA=P.strictObject({...Ht,type:P.literal("subscription.observed"),operationId:P.uuid().nullable(),subscription:rc}),lA=P.strictObject({...Ht,type:P.literal("subscription.change.completed"),operationId:P.uuid(),status:P.enum(["scheduled","applied"]),scheduledFor:en.nullable(),subscription:rc,invoice:ic.nullable()}),dA=P.strictObject({...Ht,type:P.literal("subscription.change.closed"),operationId:P.uuid(),merchantSubscriptionId:jt,merchantInvoiceId:jt.nullable(),status:P.enum(["failed","expired","canceled"])}),pA=P.strictObject({...Ht,type:P.literal("invoice.paid"),merchantSubscriptionId:jt.nullable(),invoice:ic}),mA=P.strictObject({...Ht,type:P.literal("refund.updated"),operationId:P.uuid().nullable(),merchantInvoiceId:jt.optional(),merchantRefundId:jt,status:P.enum(["pending","succeeded","failed"]),amountMinor:It.refine(e=>e>0),currency:ia}),ld=[sA.refine(e=>e.paymentStatus!=="paid"||e.invoice!==null,"A paid purchase includes its Invoice"),cA,uA,lA.refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"Scheduled and applied changes are distinct facts"),dA,pA,mA.refine(e=>e.operationId!==null||e.merchantInvoiceId!==void 0,"A native refund names its Invoice")];import{z as ci}from"zod";var fA=e=>e/2**32|0,hA=e=>e>>>0;function dd(e,t,n,r){let i=fA(n),a=hA(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function pd(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var oc=e=>e?`"${e}" `:"";function gA(e,t=""){if(typeof e!="number")throw new TypeError(oc(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(oc(t)+"expected integer >= 0, got "+e);return e}function sa(e,t,n=""){if(pd(e)&&(t===void 0||e.length===t))return e;t!==void 0&&gA(t,"length");let r=pd(e),i=t!==void 0?` of length ${t}`:"",a=r?`length=${e.length}`:`type=${typeof e}`,o=oc(n)+"expected Uint8Array"+i+", got "+a;throw r?new RangeError(o):new TypeError(o)}var yA=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},md=(e,t)=>{yA(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 ac(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function fd(e,t){sa(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function sc(...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 On(e,t){return e<<32-t|e>>>t}var AA=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",bA=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function rr(e){if(sa(e),AA)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=bA[e[n]];return t}function xA(e,t,n="opts"){return md(e,"defaults"),t!==void 0&&md(t,n),Object.assign(Object.create(null),e,t)}function hd(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=xA({},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 gd=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function yd(e,t,n){return e&t^~e&n}function Ad(e,t,n){return e&t^e&n^t&n}var ua=class{constructor(t,n,r,i){Be(this,"blockLen");Be(this,"outputLen");Be(this,"canXOF",!1);Be(this,"padOffset");Be(this,"isLE");Be(this,"buffer");Be(this,"view");Be(this,"finished",!1);Be(this,"length",0);Be(this,"pos",0);Be(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){ac(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){ac(this),fd(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)),dd(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 p=0;p<u;p++)s.setUint32(4*p,l[p],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()}},bd=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var SA=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]),ir=new Uint32Array(64),cc=class extends ua{constructor(n,r){super(64,n,8,!1);Be(this,"A",0);Be(this,"B",0);Be(this,"C",0);Be(this,"D",0);Be(this,"E",0);Be(this,"F",0);Be(this,"G",0);Be(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 m=0;m<16;m++,r+=4)ir[m]=n.getUint32(r,!1);for(let m=16;m<64;m++){let h=ir[m-15],d=ir[m-2],g=On(h,7)^On(h,18)^h>>>3,R=On(d,17)^On(d,19)^d>>>10;ir[m]=R+ir[m-7]+g+ir[m-16]|0}let{A:i,B:a,C:o,D:s,E:c,F:u,G:l,H:p}=this;for(let m=0;m<64;m++){let h=On(c,6)^On(c,11)^On(c,25),d=p+h+yd(c,u,l)+SA[m]+ir[m]|0,R=(On(i,2)^On(i,13)^On(i,22))+Ad(i,a,o)|0;p=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,p=p+this.H|0,this.set(i,a,o,s,c,u,l,p)}roundClean(){sc(ir)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),sc(this.buffer)}},uc=class extends cc{constructor(){super(32,bd)}};var or=hd(()=>new uc,gd(1));var ui=ci.string().regex(/^[a-f0-9]{64}$/),li=ci.strictObject({scope:ci.strictObject({projectId:ci.uuid(),environmentId:ci.uuid(),environment:Ks}),customerId:ci.uuid()});function Yi(e){let t=n=>{if(Array.isArray(n))return`[${n.map(t).join(",")}]`;if(n!==null&&typeof n=="object"){let r=Object.getPrototypeOf(n);if(r!==Object.prototype&&r!==null)throw new TypeError("Commerce protocol digests require JSON objects");return`{${Object.entries(n).filter(([,i])=>i!==void 0).sort(([i],[a])=>i<a?-1:i>a?1:0).map(([i,a])=>`${JSON.stringify(i)}:${t(a)}`).join(",")}}`}if(n===null||typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n))return JSON.stringify(n);throw new TypeError("Commerce protocol digests require JSON values")};return rr(or(new TextEncoder().encode(t(e))))}import{z as je}from"zod";import{z as mt}from"zod";var tn=mt.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),de=mt.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),la=mt.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}),lc=de.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),xd=mt.string().min(1).max(64),Tr=mt.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Sd=mt.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),Ot=mt.record(xd,mt.union([mt.string().max(120),mt.number().finite(),mt.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)]))),Id=mt.record(xd,mt.union([mt.string().max(120),mt.number().finite(),mt.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),di=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},vd=mt.array(mt.object({upTo:lc.nullable(),cost:de}).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&&di(t.upTo)>di(r))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),IA=mt.object({key:Sd,match:Id,priority:mt.number().int().default(0),cost:de.optional(),tiers:vd.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),vA=mt.object({key:Sd,match:Id,factor:lc.optional(),add:la.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"})),wA=mt.object({units:lc.default("1"),cost:de,tiers:vd.optional(),dimensions:mt.array(IA).max(12).optional(),multipliers:mt.array(vA).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=di(e.units);for(let o of i)for(let s=0;s<1<<r.length;s++){let c=r.filter((d,g)=>s&1<<g);if(c.some((d,g)=>c.slice(g+1).some(R=>Object.keys(d.match).some(y=>R.match[y]!==void 0&&R.match[y]!==d.match[y]))))continue;let u=di(o),l=BigInt("1"),p=BigInt("0");for(let[d,g]of r.entries())s&1<<d&&(u*=di(g.factor??"1"),l*=BigInt("1000000"),p+=di(g.add??"0"));let m=(u+p*l)*BigInt("1000000"),h=l*a;(m<BigInt("0")||m%h!==BigInt("0")||m/h>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"})}}),cO=wA.safeExtend({featureKey:Tr});import{z as Nt}from"zod";var Xi=Nt.strictObject({days:Nt.number().int().min(1).max(730),cardRequired:Nt.boolean()}),pO=Nt.object({...Xi.shape,featureAllowances:Nt.record(Nt.uuid(),Nt.number().int().min(0).max(1e9)),creditAmounts:Nt.record(Nt.uuid(),de)}).strict(),mO=Nt.object({id:Nt.uuid(),planVersionId:Nt.uuid(),slot:Nt.string(),cardRequired:Nt.boolean(),status:Nt.enum(["pending","active","converted","canceled","expired","failed"]),startsAt:Nt.iso.datetime().nullable(),endsAt:Nt.iso.datetime().nullable(),createdAt:Nt.iso.datetime()}).strict();import{z as eo}from"zod";var dc=eo.number().int().positive().max(2e8),da=eo.number().int().min(0).max(2e8),to=e=>e.mode==="partial"==(e.amountMinor!==void 0),Nr=eo.strictObject({mode:eo.enum(["full","partial"]),amountMinor:dc.optional(),entitlementAction:eo.enum(["retain","revoke"])});var Dt=je.string().min(1).max(200),no=je.iso.datetime({offset:!0}),ro=da,wd=ro.maxValue,ma=je.number().int().min(-wd).max(wd),pa=je.string().regex(/^[A-Z]{3}$/),Od=je.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Pd=je.array(Dt).max(100).refine(e=>new Set(e).size===e.length),OA=je.strictObject({merchantProductId:Dt,merchantPriceId:Dt,productVersionId:je.uuid().optional(),quantity:de.refine(e=>/[1-9]/.test(e))}),pc={subject:li,operationId:je.uuid(),configurationRevision:Od,connectionRevision:Od,expiresAt:no},Cd=je.discriminatedUnion("action",[je.strictObject({...pc,action:je.literal("purchase"),mode:je.enum(["payment","subscription"]),currency:pa,items:je.array(OA).min(1).max(100),offerRefs:Pd}),je.strictObject({...pc,action:je.literal("subscription_change"),currency:pa,merchantSubscriptionId:Dt,change:nr.shape.change,timing:nr.shape.timing,proration:nr.shape.proration,offerRefs:Pd}),je.strictObject({...pc,action:je.literal("refund"),currency:pa,merchantInvoiceId:Dt,mode:Nr.shape.mode,amountMinor:Nr.shape.amountMinor,entitlementAction:Nr.shape.entitlementAction}).refine(to,"Only a partial refund chooses amountMinor")]),vO=je.strictObject({request:Cd,requestedAt:no,preparationAllowed:je.boolean()}).refine(e=>!e.preparationAllowed||Date.parse(e.requestedAt)<Date.parse(e.request.expiresAt),"Preparation authority must be within its original validity"),PA=je.strictObject({merchantLineId:Dt,merchantPriceId:Dt.nullable(),quantity:de.refine(e=>/[1-9]/.test(e)),subtotalMinor:ma,discountMinor:ro,taxMinor:ro.nullable(),totalMinor:ma.nullable()}).refine(e=>e.taxMinor===null==(e.totalMinor===null)&&(e.totalMinor===null||e.totalMinor===e.subtotalMinor-e.discountMinor+e.taxMinor),"A quote line retains exact known totals; unknown tax is not zero"),CA=je.strictObject({items:je.array(je.strictObject({merchantPriceId:Dt,quantity:de.refine(e=>/[1-9]/.test(e)),interval:si.shape.interval.exclude(["one_off"]),intervalCount:si.shape.intervalCount,amountMinor:si.shape.totalMinor})).min(1).max(100),trial:Xi.nullable()}),_A=je.strictObject({request:Cd,requestDigest:ui,merchantQuoteId:Dt,quoteTermsDigest:ui,termsVersion:Dt,sourceRevisions:je.array(je.strictObject({reference:Dt,revision:Dt})).max(100),observedAt:no,expiresAt:no,currency:pa,automaticTax:je.boolean(),lines:je.array(PA).max(100),subscriptionTerms:CA.nullable(),subtotalMinor:ma,discountMinor:ro,taxMinor:ro.nullable(),totalMinor:ma.nullable(),effectiveAt:no.nullable(),expectedEffects:je.array(je.strictObject({reference:Dt,kind:je.enum(["grant","revoke","change"]),description:je.string().min(1).max(1e3),quantity:de.nullable(),unit:Dt.nullable()}).refine(e=>e.quantity===null==(e.unit===null),"Quantified effects name their native unit")).max(100),requiredConsents:je.array(je.strictObject({reference:Dt,version:Dt,summary:je.string().min(1).max(1e3)})).max(20)}),pi=_A.superRefine((e,t)=>{let{quoteTermsDigest:n,...r}=e,i=e.lines.every(s=>s.taxMinor!==null),a=e.request.action==="purchase"&&e.request.mode==="subscription"!=(e.subscriptionTerms!==null),o=e.subscriptionTerms!==null&&(e.request.action==="refund"||e.request.action==="subscription_change"&&e.request.change.type==="cancel");(e.requestDigest!==Yi(e.request)||e.quoteTermsDigest!==Yi(r)||e.currency!==e.request.currency||a||o||e.lines.length===0&&(e.request.action!=="subscription_change"||e.subtotalMinor!==0||e.discountMinor!==0||e.taxMinor!==0||e.totalMinor!==0)||Date.parse(e.observedAt)>=Date.parse(e.expiresAt)||Date.parse(e.expiresAt)>Date.parse(e.request.expiresAt)||new Set(e.lines.map(s=>s.merchantLineId)).size!==e.lines.length||new Set(e.sourceRevisions.map(s=>s.reference)).size!==e.sourceRevisions.length||new Set(e.requiredConsents.map(s=>s.reference)).size!==e.requiredConsents.length||e.subtotalMinor!==e.lines.reduce((s,c)=>s+c.subtotalMinor,0)||e.discountMinor!==e.lines.reduce((s,c)=>s+c.discountMinor,0)||e.taxMinor!==null!==i||!i&&!e.automaticTax||e.taxMinor===null!=(e.totalMinor===null)||i&&(e.taxMinor!==e.lines.reduce((s,c)=>s+c.taxMinor,0)||e.totalMinor!==e.subtotalMinor-e.discountMinor+e.taxMinor)||e.request.action!=="subscription_change"&&(e.subtotalMinor<0||e.totalMinor!==null&&e.totalMinor<0)||e.request.action==="refund"&&(e.taxMinor===null||e.totalMinor===null||e.totalMinor<=0||e.request.mode==="partial"&&e.totalMinor!==e.request.amountMinor))&&t.addIssue({code:"custom",message:"Merchant terms must retain the original selection, scope, validity, digest and totals"})});function fa(e,t,n,r){return e.request.operationId===t&&e.request.action===n&&e.currency===r}var io=je.strictObject({quoteTermsDigest:ui,consents:je.array(je.strictObject({reference:Dt,version:Dt})).max(20)});function _d(e){return{quoteTermsDigest:e.quoteTermsDigest,consents:e.requiredConsents.map(({reference:t,version:n})=>({reference:t,version:n}))}}var wO=io.extend({operationId:je.uuid()}).refine(e=>new Set(e.consents.map(t=>t.reference)).size===e.consents.length);import{z as qe}from"zod";var mc=qe.strictObject({operationId:qe.uuid(),customerId:qe.uuid(),externalUserId:qe.string().min(1).max(256),modelId:qe.string().min(1).max(256),quantity:qe.number().int().min(1).max(1e6),validForDays:qe.number().int().min(1).max(3660)}),Rd=qe.strictObject({operationId:qe.uuid(),customerId:qe.uuid(),status:qe.literal("applied"),voucherId:qe.uuid(),modelId:qe.string().min(1).max(256),quantity:qe.number().int().positive(),issuedAt:qe.iso.datetime({offset:!0}),expiresAt:qe.iso.datetime({offset:!0})}).refine(e=>Date.parse(e.expiresAt)>Date.parse(e.issuedAt),{message:"A benefit must expire after it is issued"}),Ed=qe.strictObject({operationId:qe.uuid(),customerId:qe.uuid()}),CO=qe.discriminatedUnion("lookup",[Ed.extend({lookup:qe.literal("not_received")}),Ed.extend({lookup:qe.literal("found"),result:Rd}).refine(e=>e.result.operationId===e.operationId&&e.result.customerId===e.customerId)]),kd=qe.strictObject({customerId:qe.string().min(1).max(256),modelId:qe.string().min(1).max(256),quantity:mc.shape.quantity,validForDays:mc.shape.validForDays,requestId:qe.uuid()}),jd=qe.strictObject({customerId:qe.string().min(1).max(256),operationId:qe.uuid()}),fc=qe.strictObject({operationId:qe.uuid(),customerId:qe.uuid(),taskId:qe.uuid(),status:qe.enum(["pending","applied","rejected"]),terms:mc,receipt:Rd.nullable(),failureCode:qe.enum(["INVALID_REQUEST","CONNECTION_CHANGED"]).nullable()}).superRefine((e,t)=>{(e.terms.operationId!==e.operationId||e.terms.customerId!==e.customerId||e.status==="applied"!=(e.receipt!==null)||e.status==="rejected"!=(e.failureCode!==null)||e.receipt&&(e.receipt.operationId!==e.operationId||e.receipt.customerId!==e.customerId||e.receipt.modelId!==e.terms.modelId||e.receipt.quantity!==e.terms.quantity))&&t.addIssue({code:"custom",message:"Benefit result differs from the original accepted operation"})});import{z as T}from"zod";import{z as Dr}from"zod";var Ft=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,ar=Dr.object({customerId:Dr.uuid(),sessionId:Dr.uuid(),accessToken:Dr.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),refreshToken:Dr.string().regex(/^gg_rt_[A-Za-z0-9_-]{43}$/),expiresAt:Dr.iso.datetime(),refreshExpiresAt:Dr.iso.datetime()});var gc=3;var EA=["session","catalog","customer_commerce","presentation","presentation_events","purchases","operation_status","billing_records","subscription_changes","refunds"],RA=T.enum(EA);var kA=T.enum(["bridge.ping","bridge.describe","session.create","catalog.read","customer.commerce.read","presentation.resolve","presentation.report","purchase.execute","operation.read","subscription.change","refund.execute"]),Nd=T.string().regex(/^[A-Za-z0-9_-]{1,64}$/),jA=T.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(e=>"AEIMQUYcgkosw048".includes(e.at(-1)),"Use canonical base64url for a 32-byte key"),TA=T.strictObject({keyId:Nd,signingSecret:jA}),NA=T.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),Dd=T.array(RA).max(10).refine(e=>new Set(e).size===e.length,"Capabilities must be unique"),Fd=T.strictObject({bridgeVersion:T.literal(gc),projectId:T.uuid(),environmentId:T.uuid(),environment:T.enum(["sandbox","live"]),capabilities:Dd,catalog:T.enum(["endpoint","static","none"]),billingEvents:T.array(ud).max(7),profiles:T.array(ad).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"})}),Md=T.strictObject({origin:NA,requiredCapabilities:Dd}),DA=T.strictObject({revision:T.number().int().nonnegative(),checkedAt:T.iso.datetime(),outcome:T.enum(["valid","unreachable","invalid","scope_mismatch","authentication_failed","credentials_missing"]),diagnostics:T.strictObject({ping:T.enum(["passed","failed","not_checked"]),authentication:T.enum(["passed","failed","not_checked"]),catalog:T.enum(["passed","failed","not_checked","static","unsupported"])}),manifest:Fd.nullable()}).superRefine((e,t)=>{e.outcome==="valid"!=(e.manifest!==null)&&t.addIssue({code:"custom",path:["manifest"],message:"Only a valid declaration carries a manifest"})}),DO=T.strictObject({projectId:T.uuid(),environmentId:T.uuid(),environment:T.enum(["sandbox","live"]),execution:T.enum(["indiana","record_only"]),accountId:T.string().nullable(),revision:T.number().int().nonnegative(),authentication:T.strictObject({keyId:Nd}).nullable(),secretStoreConfigured:T.boolean().optional(),connection:Md.nullable(),check:DA.nullable()});var Td=T.strictObject({projectId:T.uuid(),environmentId:T.uuid()}),FO=T.discriminatedUnion("action",[Td.extend({action:T.literal("save"),revision:T.number().int().nonnegative(),connection:Md,authentication:TA.optional()}),Td.extend({action:T.literal("check"),revision:T.number().int().nonnegative()})]),yc=T.strictObject({projectId:T.uuid(),environmentId:T.uuid(),environment:T.enum(["sandbox","live"])});var FA=T.strictObject({nativeUserId:T.string().min(1).max(128),session:ar.strict()}),MA=T.strictObject({nativeUserId:T.string().min(1).max(128),presentation:T.strictObject({customerId:T.uuid(),decisionId:T.uuid(),offeringVersionId:T.uuid(),paywallVersionId:T.uuid(),variant:T.string().min(1).max(128)}).nullable()}),qA=T.strictObject({decisionId:T.uuid(),eventId:T.uuid()}),ha=T.strictObject({operationId:T.uuid(),customerId:T.uuid()}),ga=T.strictObject({scope:yc,operationId:T.uuid(),customerId:T.uuid(),confirmedAt:T.iso.datetime({offset:!0}).nullable(),initialExecutionAllowed:T.boolean(),instruction:sd,merchantTerms:pi.optional()}).refine(e=>e.operationId===e.instruction.operationId&&e.customerId===e.instruction.customerId&&(!e.merchantTerms||e.merchantTerms.request.operationId===e.operationId&&e.merchantTerms.request.subject.customerId===e.customerId&&e.merchantTerms.request.action===e.instruction.type&&e.merchantTerms.currency===e.instruction.currency&&Object.entries(e.scope).every(([t,n])=>e.merchantTerms.request.subject.scope[t]===n)),"Authority must refer to the original Customer and operation"),hc=jr,Zn=T.string().min(1).max(120),UA=T.string().regex(/^-?[0-9]+(?:\.[0-9]{1,6})?$/),BA=T.strictObject({revision:Zn,updatedAt:T.iso.datetime(),provider:T.literal("merchant"),items:T.array(T.strictObject({merchantProductId:Zn,productVersionId:T.uuid(),name:T.string().min(1).max(255),kind:T.enum(["subscription","credit_pack"]),merchantPriceId:Zn,currency:T.string().regex(/^[a-z]{3}$/),amountMinor:T.number().int().nonnegative().max(1e8),interval:T.enum(["one_time","month","year"]),intervalCount:T.literal(1),includedCredits:T.string().regex(/^[0-9]{1,18}(?:\.[0-9]{1,6})?$/),creditReset:T.enum(["none","month"]),creditPolicyId:Zn,available:T.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)}),VA=T.strictObject({customerId:T.uuid(),revision:T.string().min(1).max(128),observedAt:T.iso.datetime(),subscriptions:T.array(T.strictObject({merchantSubscriptionId:Zn,merchantProductId:Zn,productVersionId:T.uuid().nullable(),status:T.enum(["active","trialing","past_due","cancelled","expired"]),currentPeriodStartsAt:T.iso.datetime().nullable(),currentPeriodEndsAt:T.iso.datetime().nullable(),cancelAtPeriodEnd:T.boolean(),scheduledChange:T.strictObject({effectiveAt:T.iso.datetime(),merchantProductId:Zn}).nullable()})).max(100),purchaseHistory:T.strictObject({complete:T.boolean(),hasPaidPurchase:T.boolean(),lastPaidAt:T.iso.datetime().nullable()}),balances:T.array(T.strictObject({bucketId:Zn,key:Zn,available:UA,expiresAt:T.iso.datetime().nullable(),nextResetAt:T.iso.datetime().nullable()})).max(100)}),MO=T.strictObject({bridgeVersion:T.literal(gc),requestId:T.uuid(),command:T.string().min(1).max(64),scope:yc,error:T.strictObject({code:T.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:T.string().min(1).max(500),retryable:T.boolean(),recovery:T.string().min(1).max(80)})}),oo=T.strictObject({}),LA={"bridge.ping":T.strictObject({challenge:T.uuid()}),"bridge.describe":oo,"session.create":oo,"catalog.read":oo,"customer.commerce.read":oo,"presentation.resolve":oo,"presentation.report":qA,"purchase.execute":ha,"operation.read":ha,"subscription.change":ha,"refund.execute":ha},qO={"bridge.ping":T.strictObject({challenge:T.uuid()}),"bridge.describe":Fd,"session.create":FA,"catalog.read":BA,"customer.commerce.read":VA,"presentation.resolve":MA,"presentation.report":T.strictObject({queued:T.literal(!0)}),"purchase.execute":hc,"operation.read":cd,"subscription.change":hc,"refund.execute":hc},UO=T.strictObject({bridgeVersion:T.literal(gc),requestId:T.uuid(),scope:yc,command:kA,data:T.unknown()}).superRefine((e,t)=>{LA[e.command].safeParse(e.data).success||t.addIssue({code:"custom",path:["data"],message:"Invalid command data"})});import{z as Qe}from"zod";import{z as zA}from"zod";import{z as mi}from"zod";var qd=mi.enum(["stripe","apple","google","merchant"]),Ud=mi.enum(["membership","credit_pack","lifetime"]),LO=mi.enum(["active","grace","suspended","inactive","revoked"]),zO=mi.strictObject({currency:mi.string().regex(/^[A-Z]{3}$/),micros:mi.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var fi=zA.object({provider:qd,currency:Ie}).strict();var Pn=Qe.strictObject({internal_feature_id:Qe.uuid(),quantity:de.refine(e=>/[1-9]/.test(e)),properties:Ot,entityId:Qe.uuid().optional()}),Bd=Qe.strictObject({requirement:Pn,commerce:fi.optional(),paywallId:Qe.uuid().optional()}),$A=Qe.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),Ac=Qe.strictObject({productId:Qe.string().min(1),productVersionId:Qe.string().min(1),name:Qe.string().min(1).max(120),action:Qe.enum(["purchase","upgrade","addon","topup"]),membershipId:Qe.string().min(1).nullable(),currency:Ie,amountMinor:Qe.string().regex(/^(0|[1-9]\d{0,8})$/),interval:Qe.enum(["free","week","month","year","one_time"]),intervalCount:Qe.number().int().min(1).max(156)}),Vd=Qe.strictObject({subject:li,authority:Qe.enum(["longplay","merchant"]),observedAt:Qe.iso.datetime({offset:!0}),sourceRevision:Qe.string().min(1).max(128),requirementDigest:ui});function GA(e,t){return Yi({subject:li.parse(e),requirement:Pn.parse(t)})}var sr=Qe.strictObject({internal_feature_id:Qe.string().min(1),name:Qe.string().min(1).max(120),kind:Qe.enum(["access","metered","credit"]),quantity:de,allowed:Qe.boolean(),observation:Vd.optional(),reason:$A.nullable(),preview:Qe.strictObject({scenario:Qe.enum(["feature_flag","usage_limit"]),candidates:Qe.array(Ac).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"})}),eP=Qe.strictObject({paywallId:Qe.uuid(),requirement:Pn}),tP=Qe.strictObject({subject:li,requirement:Pn}),nP=sr.safeExtend({observation:Vd.extend({authority:Qe.literal("merchant")})});function Ld(e,t){let n=Pn.parse(e);return t.internal_feature_id===n.internal_feature_id&&t.quantity===n.quantity&&(!t.observation||t.observation.requirementDigest===GA(t.observation.subject,n))}import{z as hi}from"zod";var ya=hi.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"),aP=hi.object({amountCents:hi.number().int().min(0).max(1e8),currency:Ie,interval:hi.enum(["free","month","year"]),currencyOptions:hi.partialRecord(Ie,hi.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");import{z as F}from"zod";var KA=F.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Gd=F.enum(["single_use","continuous_use"]),bc=F.record(F.string(),F.union([F.string(),F.number(),F.boolean()]).transform(String).pipe(F.string())),zd=F.string().min(1).max(64).refine(e=>!e.includes("::")),Kd={credit_amount:F.number(),tier_behavior:F.never().optional(),tiers:F.never().optional()},Hd={credit_amount:F.never().optional(),tier_behavior:F.literal("graduated"),tiers:F.array(F.strictObject({to:F.union([F.number(),F.literal("inf")]),credit_amount:F.number()}))},HA=F.union([F.strictObject({match:bc,priority:F.number().int().optional(),...Kd}),F.strictObject({match:bc,priority:F.number().int().optional(),...Hd})]),QA=F.strictObject({match:bc,factor:F.number().positive().optional(),add:F.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),$d={metered_feature_id:F.string(),feature_amount:F.number().optional(),dimensions:F.record(zd,HA).optional(),multipliers:F.record(zd,QA).optional()},xc=F.union([F.strictObject({...$d,...Kd}),F.strictObject({...$d,...Hd})]),ba=F.number().min(-100),Qd=F.record(F.string(),F.strictObject({markup:ba})).nullish(),xa=F.record(F.string().regex(/.+\/.+/),F.strictObject({markup:ba.optional(),input_cost:F.number().min(0).optional(),output_cost:F.number().min(0).optional()})).nullish(),JA=F.strictObject({default_markup:ba.optional(),provider_markups:Qd,model_markups:xa}),uP=F.strictObject({schema:F.array(xc).optional(),markups:JA.optional()}),ZA=F.strictObject({filters:F.array(F.strictObject({property:F.string(),operator:F.string(),value:F.array(F.string())})),aggregate:F.strictObject({type:F.string(),property:F.string().nullable()}),usage_type:Gd}),Jd=F.strictObject({schema:F.array(xc).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.boolean().optional(),usage_type:Gd.default("single_use").overwrite(()=>"single_use"),default_markup:ba.optional(),provider_markups:Qd}),Sc=Jd.safeExtend({schema:F.array(xc).length(0)}),Aa={id:KA,name:F.string().min(1),display:F.strictObject({singular:F.string().optional(),plural:F.string().optional()}).nullish(),event_names:F.array(F.string()).default([]),model_markups:xa,stripe_meter:F.strictObject({id:F.string(),event_name:F.string()}).nullish(),stripe_product_id:F.string().nullish()},Ic=e=>F.discriminatedUnion("type",[F.strictObject({...Aa,...e,type:F.literal("boolean"),config:F.null()}),F.strictObject({...Aa,...e,type:F.literal("metered"),config:ZA}),F.strictObject({...Aa,...e,type:F.literal("credit_system"),config:Jd}),F.strictObject({...Aa,...e,type:F.literal("ai_credit_system"),config:Sc})]),lP=Ic({}),WA=F.strictObject({id:F.boolean(),type:F.boolean(),usage_type:F.boolean()}),YA={internal_id:F.uuid(),org_id:F.uuid(),created_at:F.number(),env:F.enum(["sandbox","live"]),archived:F.boolean(),project_id:F.uuid(),environment_id:F.uuid(),revision:F.number().int().nonnegative(),update_rules:WA},Zd=Ic(YA),dP=F.strictObject({rows:F.array(Zd).max(200),nextCursor:F.uuid().nullable()}),pP=F.strictObject({features:F.array(Zd).max(500),limited:F.boolean()}),mP=F.union([Ic({action:F.literal("save"),internal_id:F.uuid().nullable(),revision:F.number().int().nonnegative()}),F.strictObject({action:F.enum(["archive","restore","delete"]),internal_id:F.uuid(),revision:F.number().int().nonnegative()})]);import{z as yi}from"zod";import{z as gi}from"zod";var Wd=gi.number().int().min(0).max(1e8),ao=gi.strictObject({kind:gi.enum(["graduated","volume"]),tiers:gi.array(gi.strictObject({upTo:gi.number().int().min(1).max(1e4).nullable(),unitAmountMinor:Wd,flatAmountMinor:Wd.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 vc(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let n=e.pricing?ao.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 Sa(e){return vc({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}var XA=de.refine(e=>/[1-9]/.test(e)),Ia=yi.strictObject({units:XA,prices:yi.array(yi.strictObject({currency:Ie,amountMinor:yi.number().int().min(0).max(1e8),pricing:ao.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:yi.number().int().min(0).max(1e4),maximumQuantity:yi.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&&vc({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 Yd(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 Xd(e,t,n){if(!Number.isSafeInteger(n)||n<0||n>1e4)throw new Error("Invalid purchased quantity");let r=Yd(e)+Yd(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:"")}import{z as S}from"zod";import{z as te}from"zod";import{z as qt}from"zod";import{z as N}from"zod";function ep(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 va(e,t,n){return n===2?ep(ep(e+t)+"")%1e4/1e4:null}function eb(e){return e<=0?[]:new Array(e).fill(1/e)}function wa(e,t){return e>=t[0]&&e<t[1]}function tp(e,t){for(let[n,r]of t.entries())if(wa(e,r))return n;return-1}function np(e,t,n){t=t===void 0?1:t,t<0?t=0:t>1&&(t=1);let r=eb(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 rp(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 ip(e){try{return e()}catch{return!1}}function so(e){return typeof e=="string"?e:JSON.stringify(e)}function ln(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 tb(e){try{let t=e.replace(/([^\\])\//g,"$1\\/");return new RegExp(t)}catch{return}}function op(e,t){if(!t.length)return!1;let n=!1,r=!1;for(let i of t){let a=ib(e,i.type,i.pattern);if(i.include===!1){if(a)return!1}else n=!0,a&&(r=!0)}return r||!n}function nb(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 rb(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=>!nb(i[0],i[1],i[2]))}catch{return!1}}function ib(e,t,n){try{let r=new URL(e,"https://_");if(t==="regex"){let i=tb(n);return i?i.test(r.href)||i.test(r.href.substring(r.origin.length)):!1}else if(t==="simple")return rb(r,n);return!1}catch{return!1}}function wc(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 Oa(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 ap(e){for(let t of["overrides","groups"])if(Object.hasOwn(e,t))throw new TypeError(`Retired evaluation context field: ${t}`);Oa(e.savedGroups??{})}var sp=new Map,Oc=32,cp=new WeakMap,up=new WeakMap;function ob(e){return rr(or(new TextEncoder().encode(String(e))))}var Ca=e=>Array.isArray(e)?e.map(Ca):typeof e=="string"||typeof e=="number"?ob(e):null,Pa=e=>typeof e=="string"?e.toLowerCase():e;function fp(e){let t=cp.get(e);return t||(t=new Set(e),cp.set(e,t)),t}function ab(e){let t=up.get(e);return t||(t=new Set(e.map(Pa)),up.set(e,t)),t}function Ai(e){Oa(e);for(let t of Object.values(e)){let n=t?.type==="list"||t?.type==="hashed"?t.values:null;n&&n.length>=Oc&&fp(n)}return e}function on(e,t,n,r){n=n||{},r||Oa(n),r=r||new Set;for(let[i,a]of Object.entries(t))switch(i){case"$or":if(!mp(e,a,n,r))return!1;break;case"$nor":if(mp(e,a,n,r))return!1;break;case"$and":if(!db(e,a,n,r))return!1;break;case"$not":if(on(e,a,n,r))return!1;break;case"$savedGroup":if(!sb(e,a,n,r))return!1;break;default:if(!co(a,hp(e,i),n,!1,r))return!1}return!0}function sb(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=hp(e,c);return Fr(o.type==="hashed"?Ca(u):u,o.values)}return o.type==="condition"?!o.condition||typeof o.condition!="object"?!1:on(e,o.condition,n,s):!1}function hp(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 lp(e,t=!1){let n=`${e}${t?"/i":""}`,r=sp.get(n);return r||(r=new RegExp(e.replace(/([^\\])\//g,"$1\\/"),t?"i":void 0),sp.set(n,r)),r}function co(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)||!gp(e))return JSON.stringify(t)===JSON.stringify(e);let a=e;for(let o in a)if(!lb(o,t,a[o],n,i))return!1;return!0}function gp(e){let t=Object.keys(e);return t.length>0&&t.filter(n=>n[0]==="$").length===t.length}function cb(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 ub(e,t,n,r){if(!Array.isArray(e))return!1;let i=gp(t)?a=>co(t,a,n,!1,r):a=>on(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 Fr(e,t,n=!1){if(n){let i;if(t.length>=Oc){let a=ab(t);i=o=>{let s=Pa(o);return!(typeof s=="number"&&Number.isNaN(s))&&a.has(s)}}else i=a=>t.some(o=>Pa(a)===Pa(o));return Array.isArray(e)?e.some(a=>i(a)):i(e)}let r=t.length>=Oc?(i=>a=>i.has(a))(fp(t)):i=>t.includes(i);return Array.isArray(e)?e.some(i=>r(i)):r(e)}function dp(e){return e===void 0?[]:e&&typeof e=="object"&&(e.type==="list"||e.type==="hashed")&&Array.isArray(e.values)?e.values:null}function pp(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(co(t[a],e[s],n,r,i)){o=!0;break}if(!o)return!1}return!0}function lb(e,t,n,r,i=new Set){let a=t,o=n;switch(e){case"$veq":return ln(t)===ln(n);case"$vne":return ln(t)!==ln(n);case"$vgt":return ln(t)>ln(n);case"$vgte":return ln(t)>=ln(n);case"$vlt":return ln(t)<ln(n);case"$vlte":return ln(t)<=ln(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)?Fr(t,n):!1;case"$ini":return Array.isArray(n)?Fr(t,n,!0):!1;case"$inGroup":{let s=r[n],c=dp(s);return c===null?!1:Fr(s?.type==="hashed"?Ca(t):t,c)}case"$notInGroup":{let s=r[n],c=dp(s);return c===null?!1:!Fr(s?.type==="hashed"?Ca(t):t,c)}case"$nin":return Array.isArray(n)?!Fr(t,n):!1;case"$nini":return Array.isArray(n)?!Fr(t,n,!0):!1;case"$not":return!co(n,t,r,!1,i);case"$size":return Array.isArray(t)?co(n,t.length,r,!1,i):!1;case"$elemMatch":return ub(t,n,r,i);case"$all":return Array.isArray(n)?pp(t,n,r,!1,i):!1;case"$alli":return Array.isArray(n)?pp(t,n,r,!0,i):!1;case"$regex":try{return lp(n).test(t)}catch{return!1}case"$regexi":try{return lp(n,!0).test(t)}catch{return!1}case"$type":return cb(t)===n;default:return!1}}function mp(e,t,n,r){if(!t.length)return!0;for(let i of t)if(on(e,i,n,r))return!0;return!1}function db(e,t,n,r){for(let i of t)if(!on(e,i,n,r))return!1;return!0}function Pc(e){return ap(e),{context:e,stack:{evaluatedFeatures:new Set}}}function Cc(e){return{...e.attributes,...e.attributeOverrides}}function cr(e,t,n){let r=t||"id",i="",a=Cc(e);return a[r]&&(i=a[r]),!i&&n&&(a[n]&&(i=a[n]),i&&(r=n)),{hashAttribute:r,hashValue:i}}function Xe(e,t,n){e.context.log?.(t,n)}function _a(e,t){return t=t||0,`${e}__${t}`}function _c(e,t){return`${e}||${t}`}function pb(e,t,n){let r=e.stickyBucketAssignmentDocs;if(!r)return{};let{hashAttribute:i,hashValue:a}=cr(e,t),o=_c(i,so(a)),{hashAttribute:s,hashValue:c}=cr(e,n),u=c?_c(s,so(c)):null,l={};return u&&r[u]&&Object.assign(l,r[u].assignments||{}),r[o]&&Object.assign(l,r[o].assignments||{}),l}function yp({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=_a(t,n),c=pb(e,r,i);if(a>0)for(let p=0;p<a;p++){let m=_a(t,p);if(c[m]!==void 0)return{variation:-1,versionIsBlocked:!0}}let u=c[s];if(u===void 0)return{variation:-1};let l=o.findIndex(p=>p.key===u);return l<0?{variation:-1}:{variation:l}}function Ap(e,t,n,r){let i=_c(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 bp(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Ea(e,t){let n=Pc(t),r=Sp(e,null,n);return t.onExperimentEval?.(e,r),r}function Wn(e,t){return Rc(e,Pc(t))}function mb(e){return e.forcedVariations||{}}function xp(e,t,n){let{context:r}=e;if(r.trackedExperiments){let i=wp(t,n);if(r.trackedExperiments.has(i))return;r.trackedExperiments.add(i)}Ec(()=>r.onExperimentViewed?.(t,n))}function fb(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}Ec(()=>r.onFeatureUsage?.(t,n))}function Ec(e){try{let t=e();t&&typeof t.catch=="function"&&t.catch(()=>{})}catch{}}function Rc(e,t){let{context:n}=t;if(t.stack.evaluatedFeatures.has(e))return Xe(t,`evalFeature: circular dependency detected: ${t.stack.id} -> ${e}`,{from:t.stack.id,to:e}),ur(t,e,null,"cyclicPrerequisite");t.stack.evaluatedFeatures.add(e),t.stack.id=e;let r=n.features?.[e];for(let a of r?.rules??[])wc(a);let i=n.forcedFeatureValues;if(i&&i.has(e))return Xe(t,"Global override",{id:e,value:i.get(e)}),ur(t,e,i.get(e),"override");if(!r)return Xe(t,"Unknown feature",{id:e}),ur(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=Rc(u.id,t);if(l.source==="cyclicPrerequisite")return ur(t,e,null,"cyclicPrerequisite");let p={value:l.value};if(!on(p,u.condition||{},n.savedGroups||{})){if(u.gate)return Xe(t,"Feature blocked by prerequisite",{id:e,rule:o}),ur(t,e,null,"prerequisite");Xe(t,"Skip rule because prerequisite evaluation fails",{id:e,rule:o});continue e}}if(o.filters&&vp(o.filters,t)){Xe(t,"Skip rule because of filters",{id:e,rule:o});continue}if("force"in o){if(o.condition&&!Ip(o.condition,t)){Xe(t,"Skip rule because of condition ff",{id:e,rule:o});continue}if(!hb(t,o.seed||e,o.hashAttribute,n.saveStickyBucketAssignmentDoc&&!o.disableStickyBucketing?o.fallbackAttribute:void 0,o.range,o.coverage,o.hashVersion)){Xe(t,"Skip rule because user not included in rollout",{id:e,rule:o});continue}return Xe(t,"Force value from rule",{id:e,rule:o}),o.tracks&&o.tracks.forEach(u=>{xp(t,u.experiment,u.result)}),ur(t,e,o.force,"force",o.id)}if(!o.variations){Xe(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=Sp(s,e,t);if(n.onExperimentEval?.(s,c),c.inExperiment&&!c.passthrough)return ur(t,e,c.value,"experiment",o.id,s,c)}}return Xe(t,"Use default value",{id:e,value:r.defaultValue}),ur(t,e,r.defaultValue===void 0?null:r.defaultValue,"defaultValue")}function Sp(e,t,n){let{context:r}=n;wc(e);let i=e.key,a=e.variations.length;if(a<2)return Xe(n,"Invalid experiment",{id:i}),Mt(n,e,-1,!1,t);if(r.enabled===!1)return Xe(n,"Context disabled",{id:i}),Mt(n,e,-1,!1,t);if(e.urlPatterns&&!op(r.url||"",e.urlPatterns))return Xe(n,"Skip because of url targeting",{id:i}),Mt(n,e,-1,!1,t);let o=rp(i,r.url||"",a);if(o!==null)return Xe(n,"Force via querystring",{id:i,variation:o}),Mt(n,e,o,!1,t);let c=mb(r)[i];if(c!==void 0)return Xe(n,"Force via dev tools",{id:i,variation:c}),Mt(n,e,c,!1,t);if(e.active===!1)return Xe(n,"Skip because inactive",{id:i}),Mt(n,e,-1,!1,t);let{hashAttribute:u,hashValue:l}=cr(r,e.hashAttribute,r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0);if(!l)return Xe(n,"Skip because missing hashAttribute",{id:i}),Mt(n,e,-1,!1,t);let p=-1,m=!1,h=!1;if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{variation:R,versionIsBlocked:y}=yp(bp({context:r,expKey:e.key,expBucketVersion:e.bucketVersion,expHashAttribute:e.hashAttribute,expFallbackAttribute:e.fallbackAttribute,expMinBucketVersion:e.minBucketVersion,expMeta:e.meta}));m=R>=0,p=R,h=!!y}if(!m){if(e.filters&&vp(e.filters,n))return Xe(n,"Skip because of filters",{id:i}),Mt(n,e,-1,!1,t);if(e.include&&!ip(e.include))return Xe(n,"Skip because of include function",{id:i}),Mt(n,e,-1,!1,t);if(e.condition&&!Ip(e.condition,n))return Xe(n,"Skip because of condition exp",{id:i}),Mt(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=Rc(y.id,n);if(A.source==="cyclicPrerequisite")return Mt(n,e,-1,!1,t);let x={value:A.value};if(!on(x,y.condition||{},r.savedGroups||{}))return Xe(n,"Skip because prerequisite evaluation fails",{id:i}),Mt(n,e,-1,!1,t)}}}let d=va(e.seed||i,l,e.hashVersion??2);if(d===null)return Xe(n,"Skip because of invalid hash version",{id:i}),Mt(n,e,-1,!1,t);if(!m){let R=e.ranges||np(a,e.coverage===void 0?1:e.coverage,e.weights);p=tp(d,R)}if(h)return Xe(n,"Skip because sticky bucket version is blocked",{id:i}),Mt(n,e,-1,!1,t,void 0,!0);if(p<0)return Xe(n,"Skip because of coverage",{id:i}),Mt(n,e,-1,!1,t);if("force"in e)return Xe(n,"Force variation",{id:i,variation:e.force}),Mt(n,e,e.force===void 0?-1:e.force,!1,t);if(r.qaMode)return Xe(n,"Skip because QA mode",{id:i}),Mt(n,e,-1,!1,t);let g=Mt(n,e,p,!0,t,d,m);if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{changed:R,key:y,doc:A}=Ap(r,u,so(l),{[_a(e.key,e.bucketVersion)]:g.key});if(R){r.stickyBucketAssignmentDocs=r.stickyBucketAssignmentDocs||{},r.stickyBucketAssignmentDocs[y]=A;let x=r.saveStickyBucketAssignmentDoc;Ec(()=>x(A))}}return xp(n,e,g),Xe(n,"In experiment",{id:i,variation:g.variationId}),g}function ur(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"&&fb(e,t,s),s}function Ip(e,t){return on(Cc(t.context),e,t.context.savedGroups||{})}function vp(e,t){return e.some(n=>{let{hashValue:r}=cr(t.context,n.attribute);if(!r)return!0;let i=va(n.seed,r,n.hashVersion||2);return i===null?!0:!n.ranges.some(a=>wa(i,a))})}function hb(e,t,n,r,i,a,o){if(!i&&a===void 0)return!0;if(!i&&a===0)return!1;let{hashValue:s}=cr(e.context,n,r);if(!s)return!1;let c=va(t,s,o??2);return c===null?!1:i?wa(c,i):a!==void 0?c<=a:!0}function Mt(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}=cr(e.context,t.hashAttribute,e.context.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0),l=t.meta?.[n]??{},p=t.variations[0];for(let[h,d]of t.variations.entries())if(h===n){p=d;break}let m={key:l.key||""+n,featureId:i,inExperiment:s,hashUsed:r,variationId:n,value:p,hashAttribute:c,hashValue:u,stickyBucketUsed:!!o};return l.name&&(m.name=l.name),a!==void 0&&(m.bucket=a),l.passthrough&&(m.passthrough=l.passthrough),m}function wp(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.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"})}),wt=N.record(N.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"})}),OA=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=wt.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.strictObject({id:N.uuid(),attributeKey:N.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("$")&&!OA.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)}),PA=N.discriminatedUnion("type",[N.strictObject({type:N.literal("condition"),condition:Yt}),N.strictObject({type:N.literal("list"),attributeKey:N.string().min(1).max(128),values:N.array(N.union([N.string(),N.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 Hn(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 CA=N.record(N.uuid(),PA).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"&&Hn(o.condition).forEach(i),n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),oc=N.tuple([N.number().min(0).max(1),N.number().min(0).max(1)]).refine(([e,t])=>e<=t),qd=N.strictObject({attribute:N.string().optional(),seed:N.string().min(1),hashVersion:N.literal(2),ranges:N.array(oc).min(1).max(100)}),_A=N.strictObject({id:N.string().min(1).max(128),condition:Yt,gate:N.boolean().optional()}),ic={id:N.string().max(128).optional(),condition:Yt.optional(),parentConditions:N.array(_A).max(50).optional(),filters:N.array(qd).max(20).optional()},EA=N.union([N.strictObject({...ic}),N.strictObject({...ic,force:ve,coverage:N.number().min(0).max(1).optional(),range:oc.optional(),seed:N.string().min(1).optional(),hashAttribute:N.string().optional(),hashVersion:N.literal(2).optional()}),N.strictObject({...ic,type:N.literal("experiment-ref"),experimentId:N.uuid(),values:N.record(N.string().min(1),ve),meta:N.record(N.string().min(1),N.strictObject({passthrough:N.boolean()})).optional()})]),RA=N.strictObject({defaultValue:ve,rules:N.array(EA).max(100)}),bO=N.record(N.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),RA).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)}),kA=N.strictObject({name:N.string().max(80),reason:N.string().max(500),dateStarted:N.iso.datetime({offset:!0}),dateEnded:N.iso.datetime({offset:!0}).nullable(),coverage:N.number().min(0).max(1),variationWeights:N.array(N.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.array(N.strictObject({match:N.enum(["any","all","none"]),ids:N.array(N.uuid()).min(1)})).max(50),namespace:N.strictObject({id:N.uuid(),ranges:N.array(oc).min(1)}).nullable(),seed:N.string().min(1).max(128)}),jA=N.strictObject({key:N.string().min(1).max(128),name:N.string().min(1).max(80),hypothesis:N.string().max(2e3),status:N.enum(["draft","running","stopped"]),hashAttribute:N.string().min(1).max(128),fallbackAttribute:N.string().max(128).nullable(),hashVersion:N.literal(2),disableStickyBucketing:N.boolean(),bucketVersion:N.number().int().min(0).max(1e3),minBucketVersion:N.number().int().min(0).max(1e3),variations:N.array(N.strictObject({id:N.string().min(1),key:N.string().min(1),name:N.string().max(80),description:N.string().max(500)})).min(2).max(20),phases:N.array(kA).min(1).max(100),releasedVariationId:N.string().nullable(),excludeFromPayload:N.boolean(),statusSchedule:N.strictObject({startAt:N.iso.datetime({offset:!0}).nullable(),stopAt:N.iso.datetime({offset:!0}).nullable(),stopAfter:N.strictObject({value:N.number().int().positive().max(36500),unit:N.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 TA=jA.safeExtend({filters:N.array(qd).optional()}),NA=N.strictObject({experiments:N.record(N.uuid(),TA),savedGroups:CA}),$i=N.strictObject({attributeName:N.string(),attributeValue:N.string(),assignments:N.record(N.string(),N.string())}),xO=N.strictObject({snapshot:NA,attributes:wt,results:wt,stickyBucketAssignmentDocs:N.record(N.string(),$i)}),SO=N.strictObject({variantKey:N.string().nullable(),bucketVersion:N.number().int().min(0),source:N.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:N.number().min(0).max(1).optional(),stickyBucketUsed:N.boolean().optional(),hashUsed:N.boolean().optional()});function tr(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 DA=Tt.enum(["active","inactive"]),FA=Tt.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},wt),MA=Tt.strictObject({id:Tt.string().trim().min(1).max(255),name:Tt.string().trim().min(1).max(255),status:DA,metadata:FA}),CO=MA.extend({internal_id:Tt.uuid(),project_id:Tt.uuid(),environment_id:Tt.uuid(),created_at:Tt.iso.datetime({offset:!0}),updated_at:Tt.iso.datetime({offset:!0})}),Bd=Tt.union([Tt.strictObject({id:Tt.string().trim().min(1).max(255)}),Tt.strictObject({internalId:Tt.uuid()})]),_O=Tt.enum(["customer","merchandise","context"]),EO=Tt.enum(["system","stored","request"]),RO=Tt.enum(["customer","merchandise","mixed"]),Ud=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function ac(e,t={},n=new Set){if(tr(e).some(Ud))return!0;for(let r of Hn(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&Ud(i.attributeKey)||i?.type==="condition"&&ac(i.condition,t,n))return!0}return!1}import{z as qA}from"zod";var UA=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,In=qA.string().max(16).regex(UA,"\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 qO=te.enum(["draft","active","paused","archived"]),nr=te.discriminatedUnion("type",[te.object({type:te.literal("percent"),percentOff:te.number().min(1).max(100).multipleOf(.01)}).strict(),te.object({type:te.literal("amount"),amountOffCents:te.number().int().min(1).max(1e8),currency:Ie}).strict()]),sn=te.discriminatedUnion("type",[te.object({type:te.literal("once")}).strict(),te.object({type:te.literal("repeating"),months:te.number().int().min(1).max(36)}).strict(),te.object({type:te.literal("forever")}).strict()]),Vd=[te.object({type:te.literal("all")}).strict(),te.object({type:te.literal("plans"),planIds:te.array(te.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],BA=te.discriminatedUnion("type",[...Vd,te.strictObject({type:te.literal("merchandise"),scope:te.discriminatedUnion("type",[te.strictObject({type:te.literal("all")}),te.strictObject({type:te.literal("selected"),merchandiseIds:te.array(te.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),te.strictObject({type:te.literal("condition"),condition:Yt})])})]),sc=te.discriminatedUnion("type",[...Vd,te.strictObject({type:te.literal("merchandise"),scope:te.strictObject({type:te.enum(["all","selected","condition"])})})]),VA=te.strictObject({firstPurchaseOnly:te.boolean(),condition:Yt}),UO=te.object({name:te.string().trim().min(1).max(80),description:te.string().max(500),discount:nr,duration:sn,appliesTo:BA,eligibility:VA,selfClaimEnabled:te.boolean().default(!1),startsAt:te.iso.datetime().nullable(),endsAt:te.iso.datetime().nullable(),totalLimit:te.number().int().min(1).max(1e6).nullable(),perCustomerLimit:te.number().int().min(1).max(10),grantWindowHours:te.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=>!ac(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"]}),BO=te.object({code:te.string().trim().transform(e=>e.toUpperCase()).pipe(te.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:te.number().int().min(1).max(1e6).nullable(),expiresAt:te.iso.datetime().nullable(),firstPurchaseOnly:te.boolean(),minimumAmountCents:te.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 Gi=te.object({id:te.uuid(),couponId:te.uuid(),status:te.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:te.iso.datetime(),expiresAt:te.iso.datetime(),coupon:te.object({name:te.string(),discount:nr,duration:sn,appliesTo:sc}).strict()}).strict(),Ld=te.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var Hd=S.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),cc=S.string().regex(/^(0|[1-9]\d{0,14})$/),oi=S.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),LA=S.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),Ki=LA,Qn=xe.refine(e=>/[1-9]/.test(e)),zt=S.iso.datetime({offset:!0}),ua=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"))},zA=S.array(S.object({upTo:Qn.nullable(),unitAmountMinor:Hd,flatAmountMinor:S.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&&ua(t.upTo)>ua(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),$A=S.discriminatedUnion("kind",[S.object({kind:S.literal("flat"),units:Qn,unitAmountMinor:Hd}).strict(),S.object({kind:S.enum(["graduated","volume"]),units:Qn,tiers:zA}).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"),GA=S.strictObject({interval:S.enum(["month","year"]),count:S.number().int().min(1).max(12),anchor:S.enum(["membership","calendar"])}),Hi=S.object({currency:Ie,pricing:$A,billingCycle:GA.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var zd={requestId:S.uuid(),productVersionId:S.uuid(),internal_feature_id:S.uuid(),currency:Ie},Qd=S.strictObject({interval:S.enum(["hour","day","week","month"]),intervalCount:S.number().int().min(1).max(12),limit:S.number().int().min(1).max(1e6)}),Jd=S.discriminatedUnion("kind",[S.object({...zd,kind:S.literal("auto_topup"),threshold:Zo,quantity:Qn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Qd.optional()}).strict(),S.object({...zd,kind:S.literal("postpaid"),maxAmountMinorPerPeriod:Ki,maxOutstandingMinor:Ki}).strict()]),$d={productVersionId:S.uuid(),internal_feature_id:S.uuid(),currency:Ie},Zd=S.discriminatedUnion("kind",[S.object({...$d,kind:S.literal("auto_topup"),threshold:Zo,quantity:Qn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Qd.optional(),purchaseAmountMinor:Ki,purchaseUnits:Qn}).strict(),S.object({...$d,kind:S.literal("postpaid"),maxAmountMinorPerPeriod:Ki,maxOutstandingMinor:Ki,cashPrice:Hi}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),la=S.object({id:S.uuid(),terms:Zd,status:S.enum(["prepared","active","revoked","blocked"]),createdAt:zt,acceptedAt:zt.nullable(),effectiveAt:zt.nullable(),revokedAt:zt.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"),Wd=S.object({authorizationId:S.uuid(),terms:Zd,setupUrl:S.url().nullable()}).strict(),Yd=S.object({authorizationId:S.uuid(),accepted:S.literal(!0)}).strict(),Xd=S.object({authorizationId:S.uuid(),requestId:S.uuid()}).strict(),ep=S.object({internal_feature_id:S.uuid(),entityId:S.uuid().nullable(),interval:S.enum(["day","week","month","year"]),anchor:S.enum(["billing_cycle","utc"]).optional(),basis:S.enum(["usage","credits"]),filter:vt.optional(),limit:xe.nullable(),thresholds:S.array(S.number().positive().max(1)).max(8),includedThresholds:S.array(S.number().positive().max(1)).max(8).optional(),absoluteThresholds:S.array(Qn).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&&ua(t)>ua(i)}),"Notification thresholds must increase"),KA=ep.safeExtend({requestId:S.uuid()}),Gd={control:S.literal("overage"),requestId:S.uuid(),internal_feature_id:S.uuid(),entityId:S.uuid().nullable()},HA=S.discriminatedUnion("action",[S.strictObject({...Gd,action:S.literal("set"),allowed:S.boolean().nullable(),overageLimit:xe.nullable(),skipOverageBilling:S.boolean()}),S.strictObject({...Gd,action:S.literal("remove")})]),tp=S.union([KA,HA]),QA=S.strictObject({internal_feature_id:S.uuid(),entityId:S.uuid().nullable(),allowed:S.boolean().nullable(),overageLimit:xe.nullable(),skipOverageBilling:S.boolean(),interval:S.enum(["day","week","month","year"]),startsAt:zt,endsAt:zt,used:S.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:S.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:S.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),JA=S.object({internal_feature_id:S.uuid(),entityId:S.uuid().nullable(),interval:S.enum(["day","week","month","year"]),anchor:S.enum(["billing_cycle","utc"]).optional(),basis:S.enum(["usage","credits"]),filter:vt.optional(),startsAt:zt,endsAt:zt,used:Wt,reserved:Wt,limit:xe.nullable(),thresholds:S.array(S.number().positive().max(1)).max(8),notifiedThresholds:S.array(S.number().positive().max(1)).max(1024),includedThresholds:S.array(S.number().positive().max(1)).max(8).optional(),includedAllowance:S.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:S.array(S.number().positive().max(1)).max(1024).optional(),absoluteThresholds:S.array(Qn).max(8).optional(),notifiedAbsoluteThresholds:S.array(Qn).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"),ZA=S.object({authorizationId:S.uuid(),status:S.enum(["idle","pending","blocked"]),taskId:S.uuid().nullable(),invoiceId:S.uuid().nullable(),hostedInvoiceUrl:S.url().nullable(),purchaseCount:S.number().int().nonnegative(),purchaseWindowEndsAt:zt.nullable(),attemptCount:S.number().int().nonnegative(),failedAttemptCount:S.number().int().nonnegative(),suspendedAt:zt.nullable(),nextAttemptAt:zt.nullable(),failureReason:S.string().min(1).max(240).nullable()}).strict(),np=S.object({internal_feature_id:S.uuid().optional(),entityId:S.uuid().optional()}).strict(),uc=S.object({authorizations:S.array(la).max(100),limits:S.array(ep).max(100),overages:S.array(QA).max(100).optional(),windows:S.array(JA).max(200),autoTopups:S.array(ZA).max(100),limited:S.boolean()}).strict(),WA=S.object({id:S.uuid(),internal_feature_id:S.uuid(),productVersionId:S.uuid(),authorizationId:S.uuid(),entityId:S.uuid().nullable(),units:xe,amountMinor:oi,cashPrice:Hi}).strict(),Qi=S.object({id:S.uuid(),sourceKind:S.enum(["product","usage","manual"]),providerInvoiceId:S.string().min(1).max(240).nullable(),status:S.enum(["accruing","open","pending","paid","failed","void"]),currency:Ie,startsAt:zt.nullable(),endsAt:zt.nullable(),amountMinor:S.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:S.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:cc,paidAmountMinor:cc,refundedAmountMinor:cc,createdAt:zt,hostedInvoiceUrl:S.url().nullable(),adjustment:S.object({originalInvoiceId:S.uuid(),amountMinor:S.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:zt.nullable(),reason:S.string().min(1).max(500).optional()}).strict().nullable(),lines:S.array(WA).max(100),linesLimited:S.boolean()}).strict(),rp=S.object({invoiceId:S.uuid(),accepted:S.literal(!0)}).strict(),ip=S.strictObject({requestId:S.uuid(),originalInvoiceId:S.uuid(),amountMinor:S.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.string().trim().min(1).max(500)}),op=S.object({after:S.uuid().nullable(),limit:S.number().int().min(1).max(100)}).strict(),ap=S.object({rows:S.array(Qi).max(100),nextCursor:S.uuid().nullable()}).strict(),Kd=S.strictObject({id:S.string(),coupon:S.string(),start:S.number().nonnegative(),end:S.number().nullable()}),YA=S.strictObject({subscriptionId:S.string(),customerId:S.string(),accountId:S.string(),sourceItems:S.array(S.strictObject({id:S.string(),price_id:S.string(),quantity:S.number().int(),discounts:S.array(Kd).optional()})).max(100),items:S.array(S.strictObject({id:S.string(),price:S.string(),quantity:S.number().int(),discounts:S.array(S.strictObject({coupon:S.string().optional(),terms:S.strictObject({id:S.string(),name:S.string().optional(),percent_off:S.number().optional(),amount_off:S.number().optional(),currency:S.string().optional(),duration:S.enum(["once","forever","repeating"]),duration_in_months:S.number().optional()}).optional(),discount:S.string().optional(),receipt:Kd.optional()})).max(20)})).max(100)}),sp=S.strictObject({membershipId:S.uuid(),requestId:S.uuid(),grantIds:S.array(S.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),cp=S.strictObject({membershipId:S.uuid(),operationId:S.uuid(),status:S.enum(["pending","effective"]),execution:YA.nullable(),grants:S.array(S.strictObject({id:S.uuid(),couponId:S.uuid(),name:S.string(),discount:nr,duration:sn,startedAt:zt.nullable()})).max(20)});import{z as Ji}from"zod";var up=Ji.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),lp=Ji.number().int().min(1).max(1e3),da=Ji.object({cap:xe.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:Ji.number().positive().max(1e4).nullable(),cycles:Ji.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");import{z as rr}from"zod";var dp=rr.strictObject({itemKey:rr.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:rr.uuid(),includedAmount:rr.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:rr.number().int().min(0).max(1e4),terms:Yo,pricing:Vi.optional(),unitAmountMinor:rr.number().int().min(0).max(1e8),productId:rr.string().min(1).max(255).nullable(),priceId:rr.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{rd(e.includedAmount,e.terms.units,e.quantity),Wo({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"})}});import{z as ne}from"zod";var Cr=xe.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Zi=ne.string().min(1).max(120),pa=ne.enum(["cap","overflow"]),cn=(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"))},Wi=e=>{try{return e()}catch{return!1}},Yi=ne.discriminatedUnion("operation",[ne.object({operation:ne.literal("quote"),overageBehavior:pa.optional(),internal_feature_id:ne.uuid(),entityId:ne.uuid().optional(),quantity:Cr,properties:vt}).strict(),ne.object({operation:ne.literal("consume"),overageBehavior:pa.optional(),occurredAt:ne.iso.datetime({offset:!0}).optional(),internal_feature_id:ne.uuid(),entityId:ne.uuid().optional(),quantity:xe,properties:vt,idempotencyKey:Zi}).strict(),ne.object({operation:ne.literal("reserve"),occurredAt:ne.iso.datetime({offset:!0}).optional(),internal_feature_id:ne.uuid(),entityId:ne.uuid().optional(),quantity:Cr,properties:vt,idempotencyKey:Zi,expiresInSeconds:ne.number().int().min(1).max(86400)}).strict(),ne.object({operation:ne.literal("confirm"),operationId:ne.uuid(),quantity:Cr,properties:vt.optional(),idempotencyKey:Zi}).strict(),ne.object({operation:ne.literal("refund"),operationId:ne.uuid(),quantity:Cr,idempotencyKey:Zi}).strict(),ne.object({operation:ne.literal("release"),operationId:ne.uuid(),idempotencyKey:Zi}).strict()]),lc=ne.object({internal_credit_feature_id:ne.uuid().nullable(),internal_metered_feature_id:ne.uuid(),dimension:ne.string().min(1).max(64),counterKey:ne.string().min(1).max(240),cycleStart:ne.iso.datetime({offset:!0}),unitCost:xe,units:Cr,amount:Wt,tier:ne.number().int().min(1).max(12).nullable()}).strict(),_r=ne.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function pp(e,t){let n=e.reduce((r,i)=>r+cn(i.units,12),0n)-cn(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var mp=ne.discriminatedUnion("funding",[ne.strictObject({funding:ne.literal("balance"),sourceId:ne.uuid(),rolloverId:ne.uuid().nullable(),units:_r.refine(e=>/[1-9]/.test(e)),amount:Wt}),ne.strictObject({funding:ne.literal("unbilled"),units:_r.refine(e=>/[1-9]/.test(e))}),ne.object({funding:ne.literal("prepaid"),sourceId:ne.uuid(),units:Cr,amount:Wt,pricing:ne.array(lc).min(1).max(12)}).strict().refine(e=>Wi(()=>e.pricing.reduce((t,n)=>t+cn(n.units,6),0n)===cn(e.units,6)&&e.pricing.reduce((t,n)=>t+cn(n.amount,12),0n)===cn(e.amount,12)&&e.pricing.every(t=>cn(t.unitCost,6)*cn(t.units,6)===cn(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),ne.object({funding:ne.literal("postpaid"),invoiceLineId:ne.uuid().nullable(),units:Cr,authorizationId:ne.uuid()}).strict()]),ma=ne.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),fp=ne.object({allowed:ne.boolean(),internal_feature_id:ne.uuid(),quantity:xe,requestedQuantity:xe.optional(),overageBehavior:pa.optional(),reason:ma.nullable(),allocations:ne.array(mp).max(500)}).strict().refine(e=>Wi(()=>e.allowed?e.reason===null&&pp(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>Wi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&cn(e.requestedQuantity,6)>=cn(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Xi=ne.object({id:ne.uuid(),internal_feature_id:ne.uuid(),kind:ne.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:ne.uuid().nullable(),quantity:xe,requestedQuantity:xe.optional(),overageBehavior:pa.optional(),accepted:ne.boolean(),reason:ne.enum([...ma.options,"expired"]).nullable(),createdAt:ne.iso.datetime({offset:!0}),reservationStatus:ne.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:ne.iso.datetime({offset:!0}).nullable(),allocations:ne.array(mp).max(500)}).strict().refine(e=>Wi(()=>e.accepted?e.reason===null&&pp(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>Wi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&cn(e.requestedQuantity,6)>=cn(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");import{z as De}from"zod";var Er=De.iso.datetime({offset:!0}),gp=xe.refine(e=>/[1-9]/.test(e)),hp=De.strictObject({interval:up.exclude(["lifetime"]),count:lp}),XA=De.strictObject({action:De.literal("create"),requestId:De.uuid(),internal_feature_id:De.uuid(),entityId:De.uuid().nullable(),amount:gp.nullable(),expiresAt:Er.nullable(),reset:hp.nullable(),rollover:da.nullable(),nextResetAt:Er.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"),yp=De.discriminatedUnion("action",[XA,De.strictObject({action:De.literal("update"),requestId:De.uuid(),grantId:De.uuid(),revision:De.number().int().nonnegative(),amount:gp.nullable(),expiresAt:Er.nullable(),rollover:da.nullable(),nextResetAt:Er.nullable()}),De.strictObject({action:De.enum(["add","subtract","set_remaining"]),requestId:De.uuid(),grantId:De.uuid(),revision:De.number().int().nonnegative(),amount:xe}),De.strictObject({action:De.literal("revoke"),requestId:De.uuid(),grantId:De.uuid(),revision:De.number().int().nonnegative()})]),dc=De.strictObject({id:De.uuid(),internal_feature_id:De.uuid(),entityId:De.uuid().nullable(),amount:xe.nullable(),reset:hp.nullable(),rollover:da.nullable(),nextResetAt:Er.nullable(),startsAt:Er,expiresAt:Er.nullable(),revision:De.number().int().nonnegative(),revoked:De.boolean(),available:Wt,held:Wt,spent:Wt}),Ap=De.strictObject({customerId:De.uuid(),after:De.uuid().nullable(),limit:De.number().int().min(1).max(100)}),bp=De.strictObject({rows:De.array(dc).max(100),nextCursor:De.uuid().nullable()});import{z as ie}from"zod";var Dn=ie.iso.datetime({offset:!0}),xp=ie.strictObject({invoiceId:ie.uuid(),after:ie.string().min(1).max(180).nullable(),limit:ie.number().int().min(1).max(100)}),eb=ie.strictObject({kind:ie.literal("product"),key:ie.string(),productVersionId:ie.uuid(),productName:ie.string(),itemKey:ie.string(),entityId:ie.uuid().nullable(),quantity:ie.number().positive(),subtotalMinor:ie.string().regex(/^-?\d+$/),discountMinor:ie.string().regex(/^\d+$/),taxMinor:ie.string().regex(/^-?\d+$/).nullable(),totalMinor:ie.string().regex(/^-?\d+$/),startsAt:Dn.nullable(),endsAt:Dn.nullable(),providerLineId:ie.string().nullable(),providerItemId:ie.string()}),Sp=ie.strictObject({invoice:Qi,items:ie.array(ie.discriminatedUnion("kind",[eb,ie.strictObject({kind:ie.literal("invoice_credit"),key:ie.string(),internal_feature_id:ie.uuid(),internal_credit_feature_id:ie.uuid(),name:ie.string(),units:xe,reserved:xe,amountMinor:oi,grossAmountMinor:oi,creditsAppliedMinor:oi,properties:vt,cashPrice:Hi,providerItemId:ie.string().nullable(),creditProviderItemId:ie.string().nullable()}),ie.strictObject({kind:ie.literal("usage"),key:ie.string(),internal_feature_id:ie.uuid(),name:ie.string(),units:xe,reserved:xe,amountMinor:oi,cashPrice:Hi})])).max(100),nextCursor:ie.string().min(1).max(180).nullable()}),tb=ie.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),pc=ie.strictObject({from:Dn,to:Dn,entityId:ie.uuid().optional(),snapshotAt:Dn.nullable(),after:ie.strictObject({at:Dn,id:ie.uuid(),position:ie.number().int().nonnegative()}).nullable(),limit:ie.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"),Ip=ie.strictObject({customerId:ie.uuid(),entityId:ie.uuid().nullable(),from:Dn,to:Dn,snapshotAt:Dn,totals:ie.array(ie.strictObject({internal_credit_feature_id:ie.uuid(),name:ie.string(),consumed:Wt,refunded:Wt,net:tb})).max(1e3),rows:ie.array(ie.strictObject({operationId:ie.uuid(),position:ie.number().int().nonnegative(),kind:ie.enum(["consume","confirm","refund"]),originalId:ie.uuid().nullable(),occurredAt:Dn,internal_feature_id:ie.uuid(),entitlementName:ie.string(),sourceId:ie.uuid(),internal_credit_feature_id:ie.uuid(),creditName:ie.string(),units:_r,amount:Wt,pricing:ie.array(lc).max(12),properties:vt})).max(100),nextCursor:pc.shape.after});import{z as D}from"zod";import{z as vn}from"zod";var nb=vn.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),rb=vn.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),fa=vn.strictObject({internal_feature_id:vn.uuid(),entityId:vn.uuid().nullable()}),vp=fa.extend({quantity:xe,expectedRevision:vn.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:vn.string().min(1).max(120),properties:vt.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),eo=fa.extend({operationId:vn.uuid().nullable(),usage:xe,capacity:nb.nullable(),remaining:rb.nullable(),withinLimit:vn.boolean(),revision:vn.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:vn.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 $t=D.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),wn=D.iso.datetime({offset:!0}),ib=D.enum(["access","metered","credit"]),to={internal_feature_id:D.uuid(),key:Or,name:D.string().min(1).max(120),kind:ib},wp=D.object({customerId:D.uuid(),snapshotAt:wn,memberships:D.array(D.object({id:D.uuid(),productId:D.string().min(1).max(255),productVersionId:D.uuid(),billingProductVersionId:D.uuid(),version:D.number().int().positive(),key:D.string().min(1).max(64),name:D.string().min(1).max(120),groupId:D.string().max(255).nullable(),membershipType:D.enum(["main","addon"]),status:D.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:D.boolean(),accessEnabled:D.boolean(),renewalChange:D.object({productVersionId:D.uuid(),name:D.string().min(1).max(120),version:D.number().int().positive(),effectiveAt:wn,benefitsAppliedAt:wn.nullable(),timing:D.enum(["immediate","renewal"]),changeKind:D.enum(["plan","seats","quantity"]),feature:D.strictObject({internal_feature_id:D.uuid(),name:D.string().min(1).max(80),fromQuantity:D.number().int().min(0).max(1e4),toQuantity:D.number().int().min(0).max(1e4)}).optional(),seat:D.object({key:D.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:D.number().int().min(0).max(1e4),toQuantity:D.number().int().min(0).max(1e4)}).strict().nullable(),status:D.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.object({phase:D.enum(["paid","trial"]),startsAt:wn,endsAt:wn.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:D.boolean(),balances:D.array(D.object({...to,usageType:D.enum(["consumable","non_consumable"]).nullable(),accessible:D.boolean(),unlimited:D.boolean(),available:$t,held:$t,debt:$t,nextExpiresAt:wn.nullable(),usage:eo.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.boolean()}).strict(),Op=D.enum(["source","usage","transaction","invoice","debt","settlement"]),ga=D.object({at:wn,id:D.uuid(),type:Op}).strict(),Pp=D.object({type:Op.nullable(),resourceKey:Or.optional(),kind:D.enum(["purchase","refund"]).optional(),topup:D.boolean().optional(),from:D.iso.date().nullable(),to:D.iso.date().nullable(),after:ga.nullable(),limit:D.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),ai={id:D.uuid(),occurredAt:wn},ob=D.discriminatedUnion("type",[D.strictObject({...ai,type:D.literal("invoice"),status:D.string().min(1).max(80),paid:$t,refunded:$t,currency:Ie,externalId:D.string().nullable()}),D.object({...ai,...to,type:D.literal("source"),reason:D.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:$t,unlimited:D.boolean(),status:D.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:wn,expiresAt:wn.nullable(),orderId:D.uuid().nullable(),parentSourceId:D.uuid().nullable()}).strict(),D.object({...ai,type:D.literal("usage"),internal_feature_id:D.uuid(),name:D.string().min(1).max(120),kind:D.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:D.uuid().nullable(),quantity:xe,accepted:D.boolean(),reason:D.enum([...ma.options,"expired"]).nullable(),properties:vt,reservationStatus:D.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:wn.nullable(),charges:D.array(D.discriminatedUnion("funding",[D.strictObject({funding:D.literal("balance"),sourceId:D.uuid(),rolloverId:D.uuid().nullable(),units:_r,amount:$t}),D.strictObject({funding:D.literal("unbilled"),units:_r}),D.object({...to,funding:D.literal("prepaid"),amount:$t}).strict(),D.object({funding:D.literal("postpaid"),invoiceId:D.uuid(),invoiceLineId:D.uuid(),authorizationId:D.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.object({...ai,type:D.literal("transaction"),purpose:D.enum(["product","invoice"]),productVersionId:D.uuid().nullable(),productName:D.string().min(1).max(120).nullable(),productVersion:D.number().int().positive().nullable(),invoiceId:D.uuid().nullable(),orderId:D.uuid(),originalId:D.uuid().nullable(),kind:D.enum(["purchase","refund"]),amountMinor:D.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.object({...ai,...to,type:D.literal("debt"),sourceId:D.uuid(),transactionId:D.uuid(),amount:$t}).strict(),D.object({...ai,...to,type:D.literal("settlement"),sourceId:D.uuid(),debtId:D.uuid(),kind:D.enum(["payment","usage_refund","payment_return"]),amount:$t}).strict()]),Cp=D.object({customerId:D.uuid(),rows:D.array(ob).max(50),nextCursor:ga.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");import{z as fe}from"zod";var Ep=fe.object({customerId:fe.uuid()}).strict(),Rp=fe.discriminatedUnion("action",[fe.object({customerId:fe.uuid(),requestId:fe.uuid(),action:fe.literal("assign"),poolId:fe.uuid(),memberCustomerId:fe.uuid()}).strict(),fe.strictObject({customerId:fe.uuid(),requestId:fe.uuid(),action:fe.literal("assign_entity"),poolId:fe.uuid(),entityId:fe.uuid()}),fe.object({customerId:fe.uuid(),requestId:fe.uuid(),action:fe.literal("release"),poolId:fe.uuid(),slotId:fe.uuid()}).strict()]),no=fe.number().int().nonnegative(),mc=fe.iso.datetime({offset:!0}),fc=fe.strictObject({internalId:fe.uuid(),id:fe.string(),name:fe.string().nullable(),version:fe.number().int().positive()}),_p=fe.enum(["active","past_due"]),gc=fe.strictObject({customerId:fe.uuid(),licenses:fe.array(fe.strictObject({id:fe.uuid(),linkId:fe.uuid(),parent:fe.strictObject({customerProductId:fe.uuid(),status:_p,product:fc}),product:fc,planLicense:fe.strictObject({id:fe.uuid(),prepaidOnly:fe.boolean(),isCustom:fe.boolean()}).nullable(),granted:no,included:no,paidQuantity:no,usage:no,remaining:no,createdAt:mc}).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.array(fe.strictObject({id:fe.uuid(),linkId:fe.uuid(),status:_p,product:fc,entity:fe.strictObject({internalId:fe.uuid(),id:fe.string().nullable(),name:fe.string().nullable()}).nullable(),beneficiary:fe.strictObject({internalId:fe.uuid(),id:fe.string().nullable(),name:fe.string().nullable()}).nullable(),startedAt:mc.nullable(),endedAt:mc.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:fe.boolean()});import{z as me}from"zod";var ro=me.enum(["email","sms","voice","push"]),OP=me.enum(["resend","twilio","fcm","apns"]);var PP=me.string().regex(/^\+[1-9]\d{1,14}$/),ab=me.enum(["email_recipient","sms_segment","voice_second","push_device"]);var sb=me.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),cb=me.strictObject({subject:sb,html:me.string().min(1).max(131072).optional(),text:me.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),ub=me.strictObject({body:me.string().min(1).max(1600).refine(e=>e.trim().length>0)}),lb=me.strictObject({text:me.string().trim().min(1).max(4e3),language:me.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:me.number().int().min(1).max(900)}),db=me.record(me.string().min(1).max(64),me.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"),pb=me.strictObject({title:me.string().trim().min(1).max(200),body:me.string().trim().min(1).max(2e3),url:me.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:db.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),kp=me.discriminatedUnion("channel",[me.strictObject({channel:me.literal("email"),content:cb}),me.strictObject({channel:me.literal("sms"),content:ub}),me.strictObject({channel:me.literal("voice"),content:lb}),me.strictObject({channel:me.literal("push"),content:pb})]),jp=me.strictObject({requestId:me.uuid(),customerId:me.uuid(),connectionId:me.uuid().optional(),message:kp,expiresAt:me.iso.datetime({offset:!0})}),mb=me.array(me.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),fb=me.discriminatedUnion("kind",[me.strictObject({kind:me.literal("all")}),me.strictObject({kind:me.literal("customers"),customerIds:mb})]),CP=me.strictObject({name:me.string().trim().min(1).max(120),connectionId:me.uuid().optional(),message:kp,audience:fb,frequencyLimit:me.number().int().min(1).max(100)}),Tp=me.strictObject({requestId:me.uuid(),channel:ro,state:me.enum(["allowed","denied"]),expectedRevision:me.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),Np=me.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Dp=me.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),_P=me.strictObject({meter:ab,estimatedUnits:me.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:me.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});import{z as Ce}from"zod";import{z as re}from"zod";import{z as si}from"zod";var io=si.strictObject({internalFeatureId:si.uuid(),name:si.string().min(1).max(120),includedAmount:si.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:si.enum(["hour","day","week","month","year","lifetime"]),resetCount:si.number().int().min(1).max(100),terms:Yo});import{z as ct}from"zod";import{z as gb}from"zod";import{z as ci}from"zod";var Fp=ci.enum(["stripe","apple","google","merchant"]),Mp=ci.enum(["membership","credit_pack","lifetime"]),NP=ci.enum(["active","grace","suspended","inactive","revoked"]),DP=ci.strictObject({currency:ci.string().regex(/^[A-Z]{3}$/),micros:ci.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var ui=gb.object({provider:Fp,currency:Ie}).strict();var ir=ct.strictObject({internal_feature_id:ct.uuid(),quantity:xe.refine(e=>/[1-9]/.test(e)),properties:vt,entityId:ct.uuid().optional()}),qp=ct.strictObject({requirement:ir,commerce:ui.optional(),paywallId:ct.uuid().optional()}),hb=ct.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),hc=ct.strictObject({productId:ct.string().min(1),productVersionId:ct.string().min(1),name:ct.string().min(1).max(120),action:ct.enum(["purchase","upgrade","addon","topup"]),membershipId:ct.string().min(1).nullable(),currency:Ie,amountMinor:ct.string().regex(/^(0|[1-9]\d{0,8})$/),interval:ct.enum(["free","week","month","year","one_time"]),intervalCount:ct.number().int().min(1).max(156)}),Rr=ct.strictObject({internal_feature_id:ct.string().min(1),name:ct.string().min(1).max(120),kind:ct.enum(["access","metered","credit"]),quantity:xe,allowed:ct.boolean(),reason:hb.nullable(),preview:ct.strictObject({scenario:ct.enum(["feature_flag","usage_limit"]),candidates:ct.array(hc).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"})}),GP=ct.strictObject({paywallId:ct.uuid(),requirement:ir});var ya=re.object({plan:re.string().min(1).max(200).optional(),coupon:re.uuid().optional(),promotionCode:re.uuid().optional(),picker:re.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),ha=re.object({text:re.string().optional(),label:re.string().optional(),alt:re.string().optional(),html:re.string().max(32768).optional(),price:re.object({current:re.string(),original:re.string().nullable(),period:re.string()}).optional(),code:re.string().optional(),countdownAt:re.iso.datetime().optional(),planId:re.string().min(1).max(200).optional(),planVersionId:re.string().min(1).max(200).optional(),currency:Ie.optional(),couponId:re.uuid().optional(),offerId:re.uuid().optional(),unavailable:re.boolean().optional(),unavailableReason:re.string().optional(),missing:re.array(re.string()).optional()}).strict(),li=re.object({paywall:Rr.optional(),nodes:re.record(re.string(),re.object({base:ha,picker:re.string().optional(),byPlan:re.record(re.string(),ha).optional()}).strict()),plans:re.record(re.string(),re.object({id:re.string().min(1).max(200),versionId:re.string().min(1).max(200),available:re.boolean(),name:re.string(),price:re.string(),period:re.string(),currency:Ie.optional(),amountMinor:re.number().int().nonnegative().optional(),interval:re.enum(["free","week","month","year","one_time"]).optional(),intervalCount:re.number().int().positive().optional(),prepaid:re.array(io).max(100).optional()}).strict()),pickers:re.record(re.string(),re.object({options:re.array(re.string().min(1).max(200)).max(20),selected:re.string().min(1).max(200).nullable()}).strict()),quantities:re.record(re.string(),re.strictObject({minimum:re.number().int().nonnegative(),maximum:re.number().int().nonnegative(),step:re.number().int().positive(),value:re.number().int().nonnegative(),label:re.string(),available:re.boolean()})).optional(),diagnostics:re.array(re.object({nodeId:re.string(),message:re.string()}).strict())}).strict();function Up(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}import{z as I}from"zod";function yb(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function Bp(e){let t={};function n(r){var i;if(yb(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}import{z as Jn}from"zod";var Vp=Jn.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Aa=Jn.strictObject({tiers:Jn.array(Jn.strictObject({id:Vp,name:Jn.string().trim().min(1).max(80)})).min(1).max(8),assignments:Jn.array(Jn.strictObject({productVersionId:Jn.string().min(1).max(200),tierId:Vp,period:Jn.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 ba(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}import{z as ce}from"zod";var Ab=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],Lp=ce.enum(Ab),zp=ce.object({source:Lp,layout:ce.enum(["full","compact"]),resourceKey:Or.optional(),pageSize:ce.number().int().min(1).max(50),showSources:ce.boolean(),allowPurchase:ce.boolean(),outputs:ce.object({billing_adjustment:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:ce.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"})}),Rt=ce.string().max(2e3),$p=ce.object({id:ce.string().max(100),label:Rt,detail:ce.array(Rt).max(12),value:Rt.optional(),status:Rt.optional(),facts:ce.array(ce.object({label:Rt,value:Rt}).strict()).max(1e3),purchaseId:ce.uuid().optional(),invoiceUrl:ce.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:ce.array(ce.strictObject({action:ce.literal("invoice_open"),label:Rt})).max(1).optional(),membershipActions:ce.array(ce.object({value:ce.string().max(100),label:Rt}).strict()).max(3).optional()}).strict(),bb=ce.object({key:Or,name:Rt,spendable:Rt,reserved:Rt,available:Rt,expiry:Rt.nullable(),sources:ce.array($p).max(50),sourceCount:ce.number().int().nonnegative(),sourcePage:ce.number().int().positive(),hasNextSources:ce.boolean(),hasPreviousSources:ce.boolean()}).strict(),xb=ce.object({source:Lp,status:ce.enum(["idle","loading","ready","error"]),stale:ce.boolean(),preview:ce.boolean(),errorCode:ce.string().max(80).optional(),errorMessage:Rt.optional(),resources:ce.array(bb).max(500),rows:ce.array($p).max(50),hasNext:ce.boolean(),hasPrevious:ce.boolean(),page:ce.number().int().positive(),filter:ce.string().max(40),updatedAt:ce.iso.datetime().optional(),buyingId:ce.uuid().optional(),membershipBusy:ce.boolean().optional(),billingBusy:ce.boolean().optional(),membershipReview:ce.object({title:Rt,note:Rt,facts:ce.array(ce.object({label:Rt,value:Rt}).strict()).max(100)}).strict().optional(),membershipResult:Rt.optional()}).strict(),Gp=ce.object({nodes:ce.record(ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),xb)}).strict(),rC=ce.object({nodeId:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:ce.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.string().max(100).optional()}).strict();import{z as K}from"zod";var St={state:32,enumValues:64,derived:96,bindings:256,controls:64,timers:4,effects:8,depth:12,expressionNodes:2e3},Hp=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]),Nt=K.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/).refine(e=>!Hp.has(e),"Reserved UI identifier"),yc=K.union([K.string().max(2e3),K.number().finite(),K.boolean(),K.null()]),Sb=K.discriminatedUnion("type",[K.strictObject({type:K.literal("enum"),values:K.array(yc).min(1).max(St.enumValues),default:yc}),K.strictObject({type:K.literal("number"),min:K.number().finite(),max:K.number().finite(),step:K.number().finite().positive(),default:K.number().finite()}),K.strictObject({type:K.literal("text"),maxLength:K.number().int().min(0).max(2e3),default:K.string().max(2e3).nullable()}),K.strictObject({type:K.literal("boolean"),default:K.boolean()})]);function bc(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 Ib=Sb.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"}),bc(e,e.default)||t.addIssue({code:"custom",path:["default"],message:"UI default must match its state definition"})}),vb=["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 wb(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 jr=K.lazy(()=>K.union([yc,K.strictObject({ref:Nt}),K.strictObject({op:K.enum(vb),args:K.array(jr).max(St.expressionNodes)}).superRefine((e,t)=>{wb(e.op,e.args.length)||t.addIssue({code:"custom",path:["args"],message:"Invalid UI expression arity"})})]));function On(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function kr(e,t,n){if(!e||typeof e!="object")return!0;if(!On(e))return t.addIssue({code:"custom",path:n,message:"UI objects must be plain data"}),!1;for(let r of Object.keys(e)){if(Hp.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 di(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(!kr(a.value,t,a.path))return;if(On(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 aC=K.unknown().superRefine((e,t)=>{di(e,t,[],{nodes:0})}).pipe(jr),Ac=K.record(Nt,jr).refine(e=>Object.keys(e).length>0&&Object.keys(e).length<=St.state,"UI assignments need 1\u201332 state keys"),Ob=K.strictObject({target:Nt,property:K.enum(["text","visible","disabled","checked","value","class","aria-label","aria-selected","aria-checked","aria-valuetext","tabindex"]),expression:jr,className:Nt.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"})}),Pb=K.discriminatedUnion("type",[K.strictObject({type:K.literal("scroll_latch"),target:Nt,state:Nt}),K.strictObject({type:K.literal("input"),target:Nt,state:Nt,set:Ac.optional()}),K.strictObject({type:K.literal("action"),target:Nt,set:Ac}),K.strictObject({type:K.literal("carousel"),target:Nt,state:Nt,initialIndex:K.number().int().nonnegative().optional(),maxWidth:K.number().int().min(1).max(1e4).optional(),previousTarget:Nt.optional(),nextTarget:Nt.optional(),inactiveTargets:K.array(Nt).max(20).optional(),inactiveMaxWidth:K.number().int().min(1).max(1e4).optional()})]),Cb=K.strictObject({afterMs:K.number().int().min(0).max(6e4),set:Ac}),_b=K.strictObject({type:K.literal("mosaic_waves"),target:Nt,color:K.string().regex(/^#[0-9a-fA-F]{6}$/),hotColor:K.string().regex(/^#[0-9a-fA-F]{6}$/),enabled:jr.optional(),speed:K.number().min(0).max(4).optional(),pitch:K.number().min(.05).max(4).optional(),fill:K.number().min(.05).max(1).optional(),feather:K.number().min(0).max(1).optional(),warp:K.number().min(0).max(4).optional(),warpScale:K.number().min(0).max(32).optional(),detailScale:K.number().min(0).max(32).optional(),waveScale:K.number().min(0).max(32).optional(),falloff:K.number().min(.1).max(32).optional(),brightness:K.number().min(0).max(32).optional(),ambient:K.number().min(0).max(1).optional(),gamma:K.number().min(.05).max(8).optional(),vignette:K.number().min(0).max(1).optional(),opacity:K.number().min(0).max(1).optional()}),Eb=K.strictObject({type:K.literal("number_counter"),target:Nt,value:jr,prefix:K.string().max(20).optional(),format:K.enum(["number","short"]).optional()}),Rb=K.strictObject({state:K.record(Nt,Ib).refine(e=>Object.keys(e).length<=St.state,"Too many UI state keys").optional(),derived:K.record(Nt,jr).refine(e=>Object.keys(e).length<=St.derived,"Too many UI derived keys").optional(),bindings:K.array(Ob).max(St.bindings).optional(),controls:K.array(Pb).max(St.controls).optional(),timers:K.array(Cb).max(St.timers).optional(),effects:K.array(K.discriminatedUnion("type",[_b,Eb])).max(St.effects).optional(),clock:K.boolean().optional()});function kb(e,t){if(!kr(e,t,[])||!On(e))return;for(let[r,i]of[["state",St.state],["derived",St.derived]]){let a=e[r];if(!kr(a,t,[r]))return;if(On(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(!kr(i,t,["effects",r]))return}if(On(e.state))for(let[r,i]of Object.entries(e.state)){if(!kr(i,t,["state",r]))return;if(On(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(On(e.derived))for(let[r,i]of Object.entries(e.derived))di(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(!(!kr(o,t,[r,a])||!On(o))){if(r==="bindings")di(o.expression,t,[r,a,"expression"],n);else if(kr(o.set,t,[r,a,"set"])&&On(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))di(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())On(i)&&i.type==="number_counter"?di(i.value,t,["effects",r,"value"],n):On(i)&&i.enabled!==void 0&&di(i.enabled,t,["effects",r,"enabled"],n)}function Kp(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 Qp=K.unknown().superRefine(kb).pipe(Rb).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 Kp(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 Kp(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&&!bc(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"])});import{z as ot}from"zod";var jb=ot.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),xa=ot.discriminatedUnion("type",[ot.object({type:ot.literal("fixed"),productVersionId:ot.string().min(1).max(200)}).strict(),ot.object({type:ot.literal("picker"),pickerId:jb,allowedProductVersionIds:ot.array(ot.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")]),Tb=ot.strictObject({min:ot.number().finite().min(1).max(1800),max:ot.number().finite().min(1).max(1800),viewport:ot.number().finite().min(1).max(100)}).refine(e=>e.min<=e.max,"Desktop width range is reversed"),Jp={desktopWidth:Tb.optional(),mobile:ot.enum(["sheet","fullscreen"]).optional(),backdrop:ot.enum(["none","scrim","dim","strong-dim","blur"]).optional()},Pn=ot.discriminatedUnion("type",[ot.strictObject({type:ot.literal("modal"),size:ot.enum(["sm","md","lg"]),...Jp}),ot.strictObject({type:ot.literal("sheet"),size:ot.enum(["sm","md","lg"]),...Jp}),ot.strictObject({type:ot.literal("fullscreen")}),ot.strictObject({type:ot.literal("inline")})]);var Db=4,_n={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:32768,documentBytes:2e5},ao=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ue=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Fb=I.enum(["none","xs","sm","md","lg","xl"]),Mb=I.enum(["none","sm","md","lg","full"]),xc=I.string().regex(/^#[0-9a-fA-F]{6}$/),Ic=I.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"),Sc=I.union([Ic,I.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),I.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),I.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Zp=I.object({primary:xc,background:xc,text:xc,radius:Mb,font:I.enum(["system","serif","rounded","mono"]),fontAssets:I.object({family:I.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/),faces:I.array(I.object({url:Ic,weight:I.number().int().min(100).max(900).multipleOf(100),family:I.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/).optional()}).strict()).min(1).max(4)}).strict().optional()}).strict(),so=I.union([I.enum(["primary","text","muted","background","surface"]),I.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),Me=(e,t)=>I.number().int().min(e).max(t),Wp=I.union([I.enum(["fit","fill"]),Me(1,1200)]),qb=I.object({top:Me(0,200),right:Me(0,200),bottom:Me(0,200),left:Me(0,200)}).strict(),Ub=I.object({top:Me(-100,200),right:Me(-100,200),bottom:Me(-100,200),left:Me(-100,200)}).strict(),Yp=I.object({x:Me(0,100),y:Me(0,100)}).strict(),Bb=I.discriminatedUnion("type",[I.object({type:I.literal("color"),color:so}).strict(),I.object({type:I.literal("linear"),angle:Me(0,360),stops:I.array(I.object({color:so,at:Me(0,100)}).strict()).min(2).max(4)}).strict(),I.object({type:I.literal("image"),src:Sc,fit:I.enum(["cover","contain"]),position:Yp.optional()}).strict()]),Vb=I.discriminatedUnion("type",[I.object({type:I.literal("rect"),radius:I.union([Me(0,200),I.object({topLeft:Me(0,200),topRight:Me(0,200),bottomRight:Me(0,200),bottomLeft:Me(0,200)}).strict()])}).strict(),I.object({type:I.literal("pill")}).strict()]),Lb=I.object({width:Me(0,12),color:so,style:I.enum(["solid","dashed"])}).strict(),zb=I.object({x:Me(-40,40),y:Me(-40,40),blur:Me(0,80),spread:Me(-20,40),color:so}).strict(),$b=I.object({font:I.enum(["system","serif","rounded","mono"]),size:Me(8,96),weight:I.number().int().min(100).max(900).multipleOf(100),lineHeight:I.number().min(.8).max(3),letterSpacing:I.number().min(-5).max(20),color:so,align:I.enum(["start","center","end"]),italic:I.boolean(),decoration:I.enum(["none","underline","line-through"]),transform:I.enum(["none","uppercase"])}).strict().partial(),Tr=I.object({width:Wp,height:Wp,padding:qb,margin:Ub,gap:Me(0,120),grow:I.union([I.boolean(),I.number().min(0).max(12)]),background:Bb,opacity:I.number().min(0).max(1),clipContent:I.boolean(),shape:Vb,border:Lb,shadow:zb,text:$b}).strict().partial(),tn={id:ao,name:I.string().trim().min(1).max(60).optional(),hidden:I.boolean().optional(),style:Tr.optional(),fallback:Ue.optional()},Gb=I.object({...tn,type:I.literal("text"),productField:I.enum(["name","price","trial","period"]).optional(),feature:I.object({id:I.uuid(),field:I.enum(["name","allowance"])}).strict().optional(),text:Ue,variant:I.enum(["title","heading","body","caption"])}).strict(),Kb=I.object({...tn,type:I.literal("image"),src:Sc,localizedSrc:I.record(In,Sc).optional(),alt:Ue,aspect:I.enum(["auto","1:1","4:3","16:9","3:1"]),fit:I.enum(["cover","contain"]),position:Yp.optional()}).strict(),Hb=I.object({...tn,type:I.literal("button"),label:Ue,variant:I.enum(["primary","secondary","link"]),action:Ue,purpose:I.enum(["purchase","navigation","close"]).optional(),bind:ya.optional()}).strict(),Qb=I.object({...tn,type:I.literal("divider")}).strict(),Jb=I.object({...tn,type:I.literal("customer_data"),title:Ue,data:zp}).strict(),Zb=I.object({...tn,type:I.literal("spacer"),size:Fb}).strict(),Wb=I.object({...tn,type:I.literal("custom_html"),html:I.record(In,I.string().max(_n.customHtml)),css:I.string().max(_n.customCss),ui:Qp.optional()}).strict(),Yb=I.object({...tn,type:I.literal("price"),fallback:Ue,parts:I.object({current:Tr.optional(),original:Tr.optional(),period:Tr.optional()}).strict().optional()}).strict(),Xb=I.object({...tn,type:I.literal("coupon_code"),label:Ue,fallback:Ue}).strict(),ex=I.object({...tn,type:I.literal("countdown"),source:I.enum(["offer.ends_at","offer.expires_at","fixed"]),at:I.iso.datetime().optional(),granularity:I.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"),tx=I.object({...tn,type:I.literal("plan_picker"),label:Ue,fallback:Ue,planIds:I.array(I.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.string().min(1).max(200).optional(),grouping:Aa.safeExtend({monthLabel:Ue,yearLabel:Ue,unavailableLabel:Ue}).optional(),states:I.object({selected:Tr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!ba(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),nx=I.object({...tn,type:I.literal("quantity_picker"),bind:ya.optional(),label:Ue,fallback:Ue,internalFeatureId:I.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"),rx=I.discriminatedUnion("type",[I.object({type:I.literal("input"),label:Ue,keyboard:I.enum(["text","email","tel","url"]),maxLength:Me(1,500)}).strict(),I.object({type:I.literal("multiselect"),label:Ue,min:Me(0,50),max:Me(1,50)}).strict(),I.object({type:I.literal("select"),label:Ue,defaultIndex:Me(0,49),purpose:I.enum(["option","product","tier"]).optional(),pickerId:ao.optional(),selectedStyle:Tr.optional()}).strict(),I.object({type:I.literal("tabs"),label:Ue,defaultIndex:Me(0,49),purpose:I.literal("tier").optional()}).strict(),I.object({type:I.literal("toggle"),label:Ue,defaultEnabled:I.boolean()}).strict(),I.object({type:I.literal("carousel"),label:Ue}).strict()]),Cn={...tn,type:I.literal("stack"),direction:I.enum(["vertical","horizontal","overlay"]),align:I.enum(["start","center","end","stretch"]),justify:I.enum(["start","center","end","between"]),productSlot:I.object({index:Me(0,19),period:I.enum(["month","year"]).optional(),requireBinding:I.boolean().optional()}).strict().optional(),interaction:rx.optional(),states:I.object({selected:Tr.optional()}).strict().optional(),purpose:I.literal("benefits").optional(),purchaseAction:Ue.optional(),buttonVariant:I.enum(["primary","secondary","link"]).optional(),bind:ya.optional()},Xp=I.lazy(()=>I.object({...tn,type:Cn.type,direction:Cn.direction,align:Cn.align,justify:Cn.justify,children:I.array(ix).max(_n.children),productSlot:Cn.productSlot,interaction:Cn.interaction,states:Cn.states,purpose:Cn.purpose,purchaseAction:Cn.purchaseAction,buttonVariant:Cn.buttonVariant,bind:Cn.bind}).strict()),ix=I.lazy(()=>I.union([Xp,Gb,Kb,Hb,Qb,Zb,Wb,Yb,Xb,ex,tx,nx,Jb])),ox=I.union([I.string().max(500),I.number().finite(),I.boolean(),I.null()]),oo={id:Ue,event:Ue,properties:I.record(Ue,ox).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},ax=I.discriminatedUnion("type",[I.object({...oo,type:I.literal("navigate"),close:I.literal(!1),pageId:ao}).strict(),I.object({...oo,type:I.literal("event"),close:I.boolean()}).strict(),I.object({...oo,type:I.literal("close"),close:I.literal(!0)}).strict(),I.object({...oo,type:I.literal("open_url"),close:I.boolean(),url:Ic}).strict(),I.object({...oo,type:I.literal("claim_offer"),close:I.boolean(),couponId:I.uuid()}).strict()]),sx=I.object({defaultLocale:In,locales:I.record(In,I.record(Ue,I.string().max(_n.stringLength)))}).strict(),cx=I.enum(["popup","paywall","onboarding","page","banner"]);var ux=I.object({kind:I.literal("screen"),schemaVersion:I.literal(Db),name:I.string().trim().min(1).max(80),surface:cx,initialPageId:ao.optional(),presentation:Pn,theme:Zp,pages:I.array(I.object({id:ao,name:I.string().trim().min(1).max(60),root:Xp,theme:Zp.optional(),editorPosition:I.object({x:I.number().finite().min(-1e5).max(1e5),y:I.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(_n.pages),strings:sx,actions:I.array(ax).max(_n.actions)}).strict();function Gt(e,t){for(let n of e.pages)Zn(n.root,t)}var un=ux.superRefine((e,t)=>{let n=_n;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>_n.locales&&r(`\u6700\u591A ${_n.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;Gt(e,(l,m)=>{if(c++,m>_n.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 ${_n.depth} \u5C42`)});function Zn(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)Zn(i,t,n+1,e)}function Sa(e){let t=[],n=new Set;return Gt(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 lx(e,t,n){if(t.field==="html"){let r;return Gt(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=co(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 or(e){let t=Sa(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=>!lx(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 dx(e,t){let n=null;return Zn(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function co(e,t){for(let n of e.pages){let r=dx(n.root,t);if(r)return r}return null}import{z as Bt}from"zod";var It=Bt.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"),vc=Bt.strictObject({type:Bt.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:Bt.boolean(),enum:Bt.array(Bt.string().max(255)).min(1).max(100).optional()}),pi=vc.extend({type:Bt.enum([...vc.shape.type.options,"array"]),items:vc.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"})}),mi=pi.safeExtend({source:Bt.discriminatedUnion("type",[Bt.strictObject({type:Bt.literal("input")}),Bt.strictObject({type:Bt.literal("node")}),Bt.strictObject({type:Bt.enum(["parameter","attribute"]),key:It})])}),SC=Bt.record(It,mi),wc=Bt.record(It,It).refine(e=>Object.keys(e).length<=20);function hn(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=>hn(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&&Bt.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 Oc(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&&Oc(e.items,t.items)}function Ia(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(!hn(i,u))throw new Error(`Invalid variable value: ${r}`);n[r]=u}}return n}function fi(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 em(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"||!hn(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")}import{z as Nr}from"zod";var En=Nr.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"),Fn=Nr.discriminatedUnion("source",[Nr.strictObject({source:Nr.literal("literal"),value:ve}),Nr.strictObject({source:Nr.literal("variable"),key:Nr.string().min(1).max(255),path:En.optional()})]);function tm(e,t){if(!t)return e;for(let n of En.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 Pc(e,t){if(e.source==="literal")return structuredClone(e.value);let n=Ia(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(ve.parse(tm(n[e.key],e.path)))}function Cc(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&&!En.safeParse(r).success?null:{key:n,path:r}}function _c(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Gt(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(Up))]}function va(e){return _c(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function ln(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 ar=Ce.enum(["page","popup","banner"]),px=3e5,nm=Ce.strictObject({type:Ce.enum(["string","number","boolean","strings","json"]),nullable:Ce.boolean()}),mx=Ce.strictObject({inputs:Ce.record(Ue,nm.extend({required:Ce.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:Ce.record(Ue,nm).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),fx=Ce.strictObject({kind:ar,schemaVersion:Ce.literal(1),name:Ce.string().trim().min(1).max(80),screen:un,contract:mx}),wa=fx.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"]),ln(e)>px&&n("Content document exceeds its byte budget",[])});function gx(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 hx=wa.superRefine((e,t)=>{for(let n of va(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&&!gx(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}or(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),rm=Ce.strictObject({id:Ce.uuid(),kind:ar,projectId:Ce.uuid(),environmentId:Ce.uuid(),name:Ce.string(),revision:Ce.number().int().nonnegative(),status:Ce.enum(["draft","published","archived"]),publishedVersionId:Ce.uuid().nullable(),createdAt:Ce.iso.datetime({offset:!0}),updatedAt:Ce.iso.datetime({offset:!0})}),MC=rm.extend({draft:wa}),qC=Ce.strictObject({rows:Ce.array(rm).max(200),nextCursor:Ce.uuid().nullable()}),Ec=Ce.strictObject({id:Ce.uuid(),kind:ar,resourceId:Ce.uuid(),projectId:Ce.uuid(),environmentId:Ce.uuid(),version:Ce.number().int().positive(),sourceRevision:Ce.number().int().nonnegative(),document:hx,createdAt:Ce.iso.datetime({offset:!0})}),UC=Ec.omit({document:!0}),BC=Ce.discriminatedUnion("action",[Ce.strictObject({action:Ce.literal("create"),kind:ar,id:Ce.uuid(),document:wa}),Ce.strictObject({action:Ce.literal("save"),kind:ar,id:Ce.uuid(),revision:Ce.number().int().nonnegative(),document:wa}),Ce.strictObject({action:Ce.enum(["publish","archive"]),kind:ar,id:Ce.uuid(),revision:Ce.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"})});import{z as im}from"zod";var gi={funnelId:im.uuid().optional(),funnelVersionId:im.uuid().optional()};import{z as Oa}from"zod";var Pa=Oa.strictObject({runId:Oa.uuid(),bindingId:Oa.uuid(),receiptId:Oa.uuid()});import{z as at}from"zod";import{z as Be}from"zod";import{z as et}from"zod";var HC=et.discriminatedUnion("action",[et.strictObject({action:et.literal("create"),couponId:et.uuid(),productBindingId:et.uuid(),storeOfferId:et.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:et.enum(["introductory","promotional"])}),et.strictObject({action:et.literal("set_enabled"),id:et.uuid(),revision:et.number().int().nonnegative(),enabled:et.boolean()})]),QC=et.array(et.strictObject({id:et.uuid(),couponId:et.uuid(),productBindingId:et.uuid(),storeOfferId:et.string().min(1).max(255).nullable(),storeOfferType:et.enum(["introductory","promotional"]),enabled:et.boolean(),revision:et.number().int().nonnegative()})).max(500),hi=et.strictObject({offerKind:et.enum(["none","introductory","promotional"]),offerId:et.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:et.number().int().min(0).max(1e8),trialDays:et.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"})}),JC=et.record(et.uuid(),hi).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var Rc=Be.object({type:Be.literal("native_purchase"),receiptId:Be.uuid(),orderId:Be.uuid(),productVersionId:Be.uuid(),provider:Be.enum(["apple","google"]),productId:Be.string().min(1).max(255),productKind:Mp,replacement:Be.strictObject({sourceOrderId:Be.uuid(),sourceProductId:Be.string().min(1).max(255),policy:Be.enum(["apple_store","google_full_price"]),sourceAccountTokens:Be.array(Be.uuid()).max(50)}).nullable(),appAccountToken:Be.uuid().optional(),obfuscatedAccountId:Be.string().min(1).max(64).optional(),obfuscatedProfileId:Be.uuid().optional(),basePlanId:Be.string().min(1).max(255).optional(),offerId:Be.string().min(1).max(255).optional(),offerKind:Be.enum(["none","introductory","promotional"]),currency:Ie,catalogAmountMinor:Be.number().int().nonnegative().max(1e8),discountMinor:Be.number().int().nonnegative().max(1e8),trialDays:Be.number().int().min(1).max(730).nullable(),seatBundle:Be.array(Be.strictObject({key:Be.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:Be.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:Be.strictObject({offerId:Be.string().min(1).max(255),keyId:Be.string().min(1).max(255),nonce:Be.uuid(),signature:Be.string().min(1).max(1024),timestamp:Be.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"})});import{z as p}from"zod";import{z as _e}from"zod/v4";import{z as yx}from"zod/v4";var Ax=yx.registry(),{BillingInterval:om}=(()=>{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:bx}=(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),{withSpecDefault:xx}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(Ax),{COMMON:am}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:Sx}={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:Ix}=(e=>({COMMON_SET:new Set(e)}))(am),{hasNoDuplicateCurrencies:sm}={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:cm}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:vx}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(_e),{Infinite:wx}={Infinite:"inf"},{TierBehavior:Ox}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:um}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Px}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:Cx}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:_x}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Ex}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(_e),{ApiCreditTierSchema:lm}=(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),{VIOLATION_MESSAGES:Rx}={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:dm}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(_e),{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,dm),{InvoiceUsageEntrySchema:jx}=(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),{AttachDiscountSchema:pm}=(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),{CustomLineItemSchema:Tx}=(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),{UnixMsTimestampSchema:Nx}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(_e),{CreateInvoicePreviewLineSchema:Dx}=(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),{ReissueInvoiceParamsSchema:mm}=(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),{InvoiceModeParamsSchema:Dr}=(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),{InvoiceTemplateSchema:Fx}=(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),{BasePriceSchema:Mx}=((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,om,bx),{CURRENCY_CODES:qx}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(am,Sx,Ix),{ApiPriceProcessorsSchema:fm}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(_e,vx),{AllocatedBillingFieldSchema:Ux}=((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,Px),{CreditDimensionNameSchema:Bx}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(_e,Cx,_x),{ApiCreditMatchSchema:gm}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Ex),{findCreditTierViolations:Vx}=(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}}))(Rx),{ApiCreditMultiplierSchema:Lx}=((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,gm),{ProviderMarkupsSchema:zx}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(_e,dm),{InvoiceFeatureQuantitySchema:hm}=((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,um,jx),{CreateInvoicePreviewSchema:kc}=((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,Dx),{SUPPORTED_SET:$x}=(e=>({SUPPORTED_SET:new Set(e)}))(qx),{ApiCreditDimensionBaseSchema:Gx}=((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,gm),{refineGraduatedTiers:ym}=(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"]})}}))(Vx),{ApiFeatureMarkupsOverrideSchema:Kx}=((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,zx,kx),{isValidCurrencyCode:Hx}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))($x),{ApiCreditDimensionSchema:Qx}=((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,Gx,lm,ym),{CurrencyCodeSchema:Am}=((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,Hx),{AdditionalCurrencyTierSchema:Jx}=((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,Am),{ApiCreditSchemaItemBaseSchema:bm}=((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,Bx,Qx,Lx),{ApiFlatCreditSchemaItemSchema:Zx}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(bm,_e),{AdditionalCurrencyPriceSchema:Wx}=((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,Am),{AdditionalCurrencyTierArraySchema:Yx}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(_e,Jx,sm,cm),{ApiGraduatedCreditSchemaItemSchema:Xx}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(bm,_e,lm,ym),{AdditionalCurrencyPriceArraySchema:xm}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(_e,Wx,sm,cm),{ApiUsageTierWithCurrenciesSchema:eS}=((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,wx,Yx),{ApiCreditSchemaItemSchema:tS}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(_e,Xx,Zx),{BasePriceParamsSchema:nS}=((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."})}))(Mx,xx,_e,xm),{PlanItemPriceParamsSchema:rS}=((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,xm,eS,Ox,om,um,Ux),{ApiFeatureOverrideSchema:iS}=((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,tS,Kx),{InvoiceBasePriceParamsSchema:Sm}=((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()}))(nS,fm),{InvoiceItemPriceParamsSchema:oS}=((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()}))(rS,fm),{InvoiceLicenseQuantitySchema:aS}=((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,Sm,hm),{InvoiceCustomizeItemSchema:sS}=((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,oS,iS),{InvoiceCustomizeSchema:cS}=((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,Sm,sS),{InvoicePlanParamsSchema:uS}=((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,cS,hm,aS,pm),{CreateInvoiceParamsSchema:yi}=((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,uS,Tx,pm,Nx);var wm=p.strictObject({requestId:p.uuid(),predecessorOperationId:p.uuid().optional(),invoiceMode:Dr.optional(),entityId:p.uuid().optional(),billingSubscriptionId:p.uuid().optional(),newBillingSubscription:p.literal(!0).optional(),offerId:p.uuid().optional(),nativeOffer:hi.optional(),plans:p.array(p.strictObject({productVersionId:p.uuid(),seatQuantities:p.record(Ko,p.number().int().min(0).max(1e4)).optional(),featureQuantities:p.record(p.uuid(),p.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.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"),Mr=p.strictObject({operationId:p.uuid()}),Dt=p.number().int().min(0).max(1e8),lS=p.strictObject({lineId:p.uuid(),productVersionId:p.uuid(),productName:p.string().min(1).max(80),interval:p.enum(["free","week","month","year","one_time"]),intervalCount:p.number().int().min(1).max(156).optional(),baseAmountMinor:Dt,seats:p.array(p.strictObject({key:Ko,quantity:p.number().int().min(0).max(1e4),includedQuantity:p.number().int().min(0).max(1e4),maximumQuantity:p.number().int().min(0).max(1e4),unitAmountMinor:Dt})).max(20),prepaid:p.array(dp).max(100).optional(),catalogAmountMinor:Dt,trial:p.strictObject({days:p.number().int().min(1).max(730),cardRequired:p.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+Wo({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"),Om=p.string().regex(/^[A-Za-z0-9_-]{1,200}$/),dS=p.strictObject({id:Om,name:p.string().min(1).max(40),percent_off:p.number().gt(0).max(100).optional(),amount_off:p.number().int().positive().optional(),currency:p.string().regex(/^[a-z]{3}$/).optional(),duration:p.enum(["once","repeating","forever"]),duration_in_months:p.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"),pS=p.strictObject({subscriptionId:p.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:p.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:p.array(p.strictObject({id:p.string(),price_id:p.string(),quantity:p.number().int().nonnegative(),discounts:p.array(p.strictObject({id:p.string(),coupon:p.string(),start:p.number(),end:p.number().nullable()})).optional()})).min(1).max(100),prorationDate:p.number().int().nonnegative(),amountMinor:p.number().int().positive(),periodStartMs:p.number(),periodEndMs:p.number()}),Pm=p.strictObject({invoiceMode:Dr.optional(),append:pS.optional(),provider:p.literal("stripe"),executor:p.enum(["indiana","merchant"]),accountId:p.string().regex(/^acct_[A-Za-z0-9]+$/),mode:p.enum(["payment","subscription"]),lineItems:p.array(p.strictObject({price:p.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:p.number().int().min(1).max(1e4),priceId:p.uuid(),productName:p.string().min(1).max(80),amountMinor:p.number().int().min(0).max(1e8),currency:p.string().regex(/^[a-z]{3}$/),interval:p.enum(["week","month","year","one_off"]),intervalCount:p.number().int().min(1).max(52),slot:p.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:p.strictObject({mode:p.enum(["graduated","volume"]),tiers:p.array(p.strictObject({upTo:p.number().int().min(1).max(1e6).nullable(),unitAmountMinor:p.number().int().min(0).max(1e8),flatAmountMinor:p.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:p.array(p.strictObject({coupon:Om,terms:dS})).max(1),trialPeriodDays:p.number().int().min(1).max(730).nullable(),metadata:p.strictObject({grooveCheckoutId:p.uuid(),grooveCustomerId:p.uuid()}),expiresAt:p.iso.datetime({offset:!0})}),Ai=p.strictObject({operationId:p.uuid(),entityId:p.uuid().nullable(),billingSubscriptionId:p.uuid().nullable(),discount:p.strictObject({offerId:p.uuid(),couponId:p.uuid(),discount:nr,duration:sn,amountMinor:Dt,allocations:p.array(p.strictObject({productVersionId:p.uuid(),amountMinor:Dt})).min(1).max(20),expiresAt:p.iso.datetime({offset:!0})}).nullable(),charge:p.strictObject({effectiveAt:p.iso.datetime({offset:!0}),periodEndsAt:p.iso.datetime({offset:!0}),debitMinor:Dt,discountMinor:Dt,taxMinor:Dt,totalMinor:Dt}).nullable(),expiresAt:p.iso.datetime({offset:!0}),provider:p.enum(["stripe","apple","google","merchant"]),nativeOffer:hi.optional(),currency:Ie,lines:p.array(lS).min(1).max(20),catalogAmountMinor:Dt,automaticTax:p.boolean(),execution:p.union([Pm,Vo]).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"),bi=p.strictObject({operationId:p.uuid(),orderId:p.uuid(),append:p.boolean().optional(),invoiceMode:p.boolean().optional(),status:p.enum(["pending","complete","cancelled","failed"]),executor:p.enum(["indiana","merchant"]),checkoutUrl:p.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:p.union([Pm,Vo]).nullable(),currency:Ie,catalogAmountMinor:Dt,taxMinor:Dt,totalMinor:p.number().int().min(0).max(2e8).nullable(),quoteFinalized:p.boolean(),nativePurchase:Rc.nullable(),confirmedAt:p.iso.datetime({offset:!0}).nullable().optional(),quote:Ai.optional(),merchantExecution:vr.nullable().optional(),problem:Ui.nullable().optional(),authority:Go.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"),_a=p.strictObject({enabled:p.literal(!0),featureIds:p.array(p.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),Cm=p.strictObject({requestId:p.uuid(),invoiceMode:Dr.optional(),membershipId:p.uuid(),carryOverBalances:_a.optional(),carryOverUsages:_a.optional(),membershipIds:p.array(p.uuid()).min(1).max(20).optional(),prorationBehavior:p.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:p.enum(["immediate","renewal","store"]),change:p.discriminatedUnion("type",[p.strictObject({type:p.literal("plan"),productVersionId:p.uuid()}),p.strictObject({type:p.literal("seats"),licenseKey:Ko,quantity:p.number().int().min(0).max(1e4)}),p.strictObject({type:p.literal("quantity"),internal_feature_id:p.uuid(),quantity:p.number().int().min(0).max(1e4)}),p.strictObject({type:p.literal("cancel")}),p.strictObject({type:p.literal("uncancel")}),p.strictObject({type:p.literal("billing_cycle"),billingCycleAnchor:p.union([p.literal("now"),p.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"),Ca=p.string().regex(/^price_[A-Za-z0-9]+$/),Im=p.strictObject({grooveUpdateId:p.uuid(),grooveCustomerId:p.uuid()}),vm=p.strictObject({price:Ca.nullable(),priceId:p.uuid().optional(),quantity:p.number().int().min(0).max(1e4)}),_m=p.strictObject({provider:p.literal("stripe"),invoiceMode:Dr.optional(),executor:p.enum(["indiana","merchant"]),accountId:p.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:p.string().regex(/^sub_[A-Za-z0-9]+$/),action:p.enum(["update","cancel","schedule","release"]),update:p.strictObject({items:p.array(vm).max(20),remove:p.array(Ca).max(20),restoreItems:p.array(p.strictObject({price:Ca,quantity:p.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:p.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:p.number().int().positive().optional(),paymentBehavior:p.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:p.boolean().optional(),clearCancelAt:p.literal(!0).optional(),billingCycleAnchorNow:p.literal(!0).optional(),metadata:Im}).nullable(),cancel:p.strictObject({prorate:p.literal(!1),invoiceNow:p.literal(!1)}).nullable(),schedule:p.strictObject({currentItems:p.array(p.strictObject({price:Ca,quantity:p.number().int().min(0).max(1e4)})).max(20),nextItems:p.array(vm).min(1).max(20),switchAt:p.number().int().positive(),interval:p.enum(["week","month","year"]),intervalCount:p.number().int().min(1).max(52),resetBillingCycleAnchor:p.literal(!0).optional(),metadata:Im}).nullable(),release:p.strictObject({schedule:p.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:p.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"),Ea=p.strictObject({carryOverBalances:_a.optional(),carryOverUsages:_a.optional(),operationId:p.uuid(),membershipId:p.uuid(),productVersionId:p.uuid(),timing:p.enum(["immediate","renewal"]),effectiveAt:p.iso.datetime({offset:!0}),expiresAt:p.iso.datetime({offset:!0}),currency:Ie,creditMinor:Dt,debitMinor:Dt,discountMinor:Dt,taxMinor:Dt,totalMinor:Dt,retainedProductVersionIds:p.array(p.uuid()).max(19),execution:p.union([_m,Lo])}),mS=p.strictObject({operationId:p.uuid(),invoiceMode:p.boolean().optional(),membershipId:p.uuid(),productVersionId:p.uuid(),status:p.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:p.enum(["immediate","renewal"]),effectiveAt:p.iso.datetime({offset:!0}),checkoutUrl:p.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:p.enum(["indiana","merchant"]),execution:p.union([_m,Lo]).nullable(),confirmedAt:p.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:vr.nullable().optional(),problem:Ui.nullable().optional(),quote:Ea.optional(),authority:Go.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),fS=p.strictObject({operationId:p.uuid(),membershipId:p.uuid(),productVersionId:p.uuid(),timing:p.literal("store"),effectiveAt:p.null(),expiresAt:p.iso.datetime({offset:!0}),currency:Ie,creditMinor:p.null(),debitMinor:p.null(),discountMinor:p.null(),taxMinor:p.null(),totalMinor:p.null(),retainedProductVersionIds:p.array(p.uuid()).max(19),store:p.strictObject({provider:p.enum(["apple","google"]),productId:p.string().min(1).max(255),catalogAmountMinor:Dt,policy:p.enum(["apple_store","google_full_price"])})}),gS=p.strictObject({operationId:p.uuid(),membershipId:p.uuid(),productVersionId:p.uuid(),status:p.enum(["prepared","pending","effective","cancelled","failed"]),timing:p.literal("store"),effectiveAt:p.iso.datetime({offset:!0}).nullable(),checkoutUrl:p.null(),nativePurchase:Rc.nullable()}),Em=p.union([Ea,fS]),jc=p.union([mS,gS]),uo=p.number().int().positive().max(2e8),Fr=p.number().int().min(0).max(2e8),Rm=p.strictObject({requestId:p.uuid(),invoiceId:p.uuid(),mode:p.enum(["full","partial"]),amountMinor:uo.optional(),entitlementAction:p.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),km=p.strictObject({provider:p.literal("stripe"),executor:p.enum(["indiana","merchant"]),accountId:p.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:p.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:uo,currency:p.string().regex(/^[a-z]{3}$/),metadata:p.strictObject({indianaRefundId:p.uuid()}),idempotencyKey:p.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:p.array(p.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),Tc=p.strictObject({operationId:p.uuid(),invoiceId:p.uuid(),providerInvoiceId:p.string().min(1).max(200),currency:Ie,paidMinor:Fr,refundedMinor:Fr,pendingMinor:Fr,amountMinor:uo,mode:p.enum(["full","partial"]),entitlementAction:p.enum(["retain","revoke"]),revokes:p.strictObject({customerProductIds:p.array(p.uuid()).max(100),subscriptionIds:p.array(p.string().min(1).max(200)).max(20)}),execution:p.union([km,zo]),expiresAt:p.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"),Ra=p.strictObject({operationId:p.uuid(),invoiceId:p.uuid(),providerInvoiceId:p.string().min(1).max(200),status:p.enum(["quoted","pending","succeeded","failed","expired"]),executor:p.enum(["indiana","merchant"]),currency:Ie,amountMinor:uo,mode:p.enum(["full","partial"]),entitlementAction:p.enum(["retain","revoke"]),refundId:p.string().min(1).max(200).nullable(),quote:Tc.optional(),execution:p.union([km,zo]).nullable(),confirmedAt:p.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:vr.nullable().optional(),problem:Ui.nullable().optional(),authority:Go.optional(),failureReason:p.string().min(1).max(200).nullable(),createdAt:p.iso.datetime({offset:!0}),completedAt:p.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"),g_=p.strictObject({invoiceId:p.uuid(),currency:Ie,paidMinor:Fr,refundedMinor:Fr,pendingMinor:Fr,refundableMinor:Fr,executor:p.enum(["indiana","merchant"]).nullable(),canRefund:p.boolean(),operations:p.array(Ra).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),h_=p.strictObject({requestId:p.uuid(),mode:p.enum(["full","partial"]),amountMinor:uo.optional(),entitlementAction:p.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 jm=at.strictObject({requestId:at.uuid(),targets:at.array(at.strictObject({membershipId:at.uuid(),action:at.enum(["cancel","uncancel"]),timing:at.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"),ka=at.strictObject({batchId:at.uuid()}),hS=at.strictObject({operationId:at.uuid(),membershipIds:at.array(at.uuid()).min(1).max(20),provider:at.enum(["stripe","apple","google"]),action:at.enum(["cancel","uncancel"]),timing:at.enum(["immediate","renewal"]),status:at.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:Ea.nullable(),managementUrl:at.url().nullable(),failureCode:at.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),lo=at.strictObject({batchId:at.uuid(),ready:at.boolean(),status:at.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:at.iso.datetime({offset:!0}),acceptedAt:at.iso.datetime({offset:!0}).nullable(),groups:at.array(hS).min(1).max(100)});import{z as je}from"zod";var yS=je.string().trim().min(1).max(240),Nc={requestId:je.uuid(),reason:yS},ja=je.discriminatedUnion("action",[je.strictObject({...Nc,action:je.literal("start"),productVersionId:je.uuid(),entityId:je.uuid().optional(),days:je.number().int().min(1).max(730).optional()}),je.strictObject({...Nc,action:je.literal("extend"),membershipId:je.uuid(),days:je.number().int().min(1).max(730)}),je.strictObject({...Nc,action:je.literal("end"),membershipId:je.uuid()})]),Tm=je.strictObject({operationId:je.uuid()}),Nm=je.iso.datetime({offset:!0}),AS=je.strictObject({provider:je.literal("stripe"),executor:je.enum(["indiana","merchant"]),accountId:je.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:je.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:je.union([je.literal("now"),Nm]),prorationBehavior:je.literal("none")}),Dc=je.strictObject({operationId:je.uuid(),action:je.enum(["start","extend","end"]),status:je.enum(["pending","effective"]),managedBy:je.enum(["indiana","stripe"]),membershipIds:je.array(je.uuid()).min(1).max(20),endsAt:Nm.nullable(),execution:AS.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"),I_=je.strictObject({groupId:je.uuid(),productVersionId:je.uuid(),enabled:je.boolean()});import{z as We}from"zod";var Dm=We.strictObject({requestId:We.uuid(),currency:Ie,makeDefault:We.boolean()}),Fm=We.strictObject({setupId:We.uuid()}),bS=We.strictObject({provider:We.literal("stripe"),executor:We.literal("merchant"),accountId:We.string().regex(/^acct_[A-Za-z0-9]+$/),mode:We.literal("setup"),currency:We.string().regex(/^[a-z]{3}$/),customer:We.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:We.uuid(),metadata:We.strictObject({grooveProjectId:We.uuid(),grooveEnvironmentId:We.uuid(),grooveCustomerId:We.uuid(),groovePaymentSetupId:We.uuid()}),setDefaultPaymentMethod:We.boolean(),expiresAt:We.iso.datetime({offset:!0})}),Fc=We.strictObject({id:We.uuid(),provider:We.literal("stripe"),status:We.enum(["prepared","complete","expired"]),currency:Ie,makeDefault:We.boolean(),url:We.url().nullable(),createdAt:We.iso.datetime({offset:!0}),expiresAt:We.iso.datetime({offset:!0}),completedAt:We.iso.datetime({offset:!0}).nullable(),execution:bS.nullable()});import{z as Ft}from"zod";var Mm=Ft.union([Ft.string(),Ft.number(),Ft.boolean(),Ft.null()]),qm=Ft.strictObject({customerId:Ft.uuid()}),Um=Ft.strictObject({customerId:Ft.uuid(),provider:Ft.literal("stripe"),checkedAt:Ft.iso.datetime({offset:!0}),status:Ft.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Ft.number().int().nonnegative(),differences:Ft.array(Ft.strictObject({subscriptionId:Ft.string().startsWith("sub_"),itemId:Ft.string().nullable(),field:Ft.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Mm,actual:Mm})).max(1e4)});import{z as we}from"zod";var Ta=we.iso.datetime({offset:!0}),Na=we.strictObject({createdAt:Ta,id:we.uuid()}),Da=we.strictObject({customerId:we.uuid().optional(),entityId:we.uuid().optional(),productId:we.string().min(1).max(256).optional(),provider:we.enum(["stripe","apple","google","merchant","free"]).optional(),status:we.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:Na.optional(),limit:we.number().int().min(1).max(100).optional()}),Mc={id:we.uuid(),customerId:we.uuid(),entityId:we.uuid().nullable(),productId:we.string().min(1).max(256),productVersionId:we.uuid(),name:we.string().min(1).max(120),provider:we.enum(["stripe","apple","google","merchant","free"]),createdAt:Ta},xS=we.strictObject({...Mc,status:we.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:we.boolean(),billingSubscriptionId:we.uuid().nullable()}),SS=we.strictObject({...Mc,status:we.enum(["active","ended","refunded"]),orderId:we.uuid().nullable(),transactionId:we.uuid().nullable(),currency:Ie.nullable(),amountMinor:we.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),IS=we.strictObject({...Mc,status:we.enum(["blocked","resolved"]),conflict:we.strictObject({detectedAt:Ta,blockingMembershipIds:we.array(we.uuid()).min(1).max(100),transactionId:we.uuid()}),resolvedAt:Ta.nullable()}),Bm=Da.extend({status:we.enum(["blocked","resolved"]).optional()}),Vm=we.strictObject({customerId:we.uuid(),orderId:we.uuid()}),Lm=we.strictObject({orderId:we.uuid(),status:we.enum(["blocked","resolved"])}),zm=we.strictObject({items:we.array(xS).max(100),nextCursor:Na.nullable()}),$m=we.strictObject({items:we.array(SS).max(100),nextCursor:Na.nullable()}),Gm=we.strictObject({items:we.array(IS).max(100),nextCursor:Na.nullable()});import{z as nt}from"zod";var Km=nt.union([nt.strictObject({intent:nt.literal("read"),requestId:nt.uuid(),purchaseIntentId:nt.uuid()}),nt.strictObject({requestId:nt.uuid(),provider:nt.literal("apple"),purchaseIntentId:nt.uuid(),productId:nt.string().min(1).max(255).optional(),signedTransaction:nt.string().min(1).max(131072)}),nt.strictObject({requestId:nt.uuid(),provider:nt.literal("google"),purchaseIntentId:nt.uuid(),productId:nt.string().min(1).max(255).optional(),purchaseToken:nt.string().min(1).max(16384)})]),Hm=nt.strictObject({requestId:nt.uuid(),orderId:nt.uuid(),purchaseIntentId:nt.uuid(),status:nt.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:Ie,refunded:nt.boolean(),completion:nt.strictObject({transactionIds:nt.array(nt.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:nt.boolean()}).nullable()});import{z as V}from"zod";var Uc=V.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),vS=V.record(V.string(),V.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),wS=3,po=20,OS=wS*po,qc=V.strictObject({type:V.literal("product"),productId:Uc}),Qm={type:V.literal("group"),key:V.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:V.string().trim().min(1).max(80)},PS=V.discriminatedUnion("type",[qc,V.strictObject({...Qm,items:V.array(qc).max(po)})]),CS=V.discriminatedUnion("type",[qc,V.strictObject({...Qm,items:V.array(PS).max(po)})]),_S=V.array(CS).max(po).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>po||i>OS)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function Bc(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:Bc(t))}var xi=V.strictObject({lookupKey:V.string().trim().min(1).max(200),displayName:V.string().trim().min(1).max(1500),items:_S,metadata:vS}),ES=V.strictObject({product:V.record(V.string(),V.json()),prices:V.array(V.record(V.string(),V.json())),entitlements:V.array(V.record(V.string(),V.json())),freeTrials:V.array(V.record(V.string(),V.json())),licenses:V.array(V.record(V.string(),V.json()))}),Jm=xi.extend({id:V.uuid(),projectId:V.uuid(),environmentId:V.uuid(),state:V.enum(["active","archived"]),isCurrent:V.boolean(),revision:V.number().int().nonnegative(),publishedVersionId:V.uuid().nullable(),createdAt:V.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"})}),Zm=V.strictObject({id:V.uuid(),offeringId:V.uuid(),projectId:V.uuid(),environmentId:V.uuid(),version:V.number().int().positive(),document:xi,productEvidence:V.record(Uc,ES),createdAt:V.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=Bc(e.document);(!n.length||jS(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"})}),RS=V.strictObject({rows:V.array(Jm).max(200),versions:V.array(Zm).max(500)}),F_=V.discriminatedUnion("action",[V.strictObject({action:V.literal("create"),document:xi}),V.strictObject({action:V.literal("save"),id:V.uuid(),revision:V.number().int().nonnegative(),document:xi}),V.strictObject({action:V.enum(["publish","set_current","archive","restore"]),id:V.uuid(),revision:V.number().int().nonnegative()})]),M_=V.strictObject({record:Jm,version:Zm.nullable()}),Wm=V.discriminatedUnion("type",[V.strictObject({type:V.literal("current")}),V.strictObject({type:V.literal("id"),id:V.uuid()}),V.strictObject({type:V.literal("lookup_key"),lookupKey:V.string().min(1).max(200)}),V.strictObject({type:V.literal("version"),versionId:V.uuid()})]),kS=V.strictObject({internalId:Uc,id:V.string(),name:V.string().nullable(),version:V.number().int().positive(),archived:V.boolean()}),q_=RS.extend({products:V.array(kS).max(500),pagination:V.strictObject({rows:V.string().nullable(),versions:V.string().nullable(),products:V.string().nullable()}).optional()});function jS(e){let t=[];Bc(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}import{z as Fa}from"zod";var Ym=Fa.strictObject({id:Fa.uuid(),offeringId:Fa.uuid(),version:Fa.number().int().positive(),document:xi});import{z as Ct}from"zod";import{z as ye}from"zod";import{z as Si}from"zod";var Ma=Si.strictObject({items:Si.array(Si.strictObject({productVersionId:Si.string().min(1).max(200),label:Si.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:Si.string().min(1).max(200).nullable(),grouping:Aa.optional()});function Xm(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 Vc=ye.discriminatedUnion("type",[ye.strictObject({type:ye.literal("event"),event:ye.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),ye.strictObject({type:ye.literal("open_url"),url:ye.url().refine(e=>new URL(e).protocol==="https:")})]),TS=un,NS=ye.discriminatedUnion("type",[ye.object({type:ye.literal("checkout"),product:xa}).strict(),ye.object({type:ye.literal("close")}).strict(),ye.object({type:ye.literal("action"),action:Vc}).strict()]),Ii=ye.object({schemaVersion:ye.literal(3),kind:ye.literal("paywall"),name:ye.string().trim().min(1).max(80),presentation:Pn,requirement:ir.optional(),products:Ma,offeringVersionId:ye.uuid().nullable(),offeringId:ye.uuid(),screen:TS,buttons:ye.record(ye.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),NS)}).strict(),X_=Ii.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 FS(e))t.addIssue({code:"custom",message:r});for(let r of DS(e))t.addIssue({code:"custom",message:r});or(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 DS(e){let t=e.products.items.map(a=>a.productVersionId),n=Bp(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&&(!ba(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")),Gt(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"),Gt(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 FS(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),Zn(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 ef=ye.object({id:ye.uuid(),projectId:ye.uuid(),environmentId:ye.uuid(),revision:ye.number().int().nonnegative(),state:ye.enum(["active","archived"]),publishedVersionId:ye.uuid().nullable(),updatedAt:ye.iso.datetime({offset:!0}),draft:Ii}).strict(),e1=ye.object({rows:ye.array(ef).max(200),nextCursor:ye.uuid().nullable()}).strict(),t1=ef.omit({draft:!0}).extend({name:ye.string(),productCount:ye.number().int().nonnegative()}).strict(),n1=ye.discriminatedUnion("action",[ye.object({action:ye.literal("save"),id:ye.uuid().nullable(),revision:ye.number().int().nonnegative(),document:Ii}).strict(),ye.object({action:ye.enum(["publish","archive"]),id:ye.uuid(),revision:ye.number().int().nonnegative()}).strict()]),r1=ye.object({paywalls:ye.array(ye.object({id:ye.uuid(),paywallId:ye.uuid(),version:ye.number().int().positive(),name:ye.string().min(1).max(80),presentation:Pn,buttons:Ii.shape.buttons}).strict()).max(500),limited:ye.boolean()}).strict();import{z as Re}from"zod";import{z as Kt}from"zod";var vi=Kt.string().regex(/^[a-f0-9]{64}$/),MS=ha.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),tf=Kt.strictObject({couponDigests:Kt.record(Kt.uuid(),vi),variables:Kt.record(In,Kt.record(Kt.uuid(),Kt.partialRecord(Kt.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),Kt.string()))),locales:Kt.record(In,li.extend({nodes:Kt.record(Kt.string(),Kt.strictObject({base:MS})),plans:Kt.object({}).strict(),pickers:Kt.object({}).strict()}).omit({paywall:!0}))});import{z as Ve}from"zod";import{z as qa}from"zod";var Lc=qa.strictObject({eventsEnabled:qa.boolean(),experimentViewsEnabled:qa.boolean(),featureUsageEnabled:qa.boolean()}),l1=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function nf(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}import{z as $}from"zod";var zc=$.tuple([$.number().min(0).max(1),$.number().min(0).max(1)]).refine(([e,t])=>e<=t),qS=$.strictObject({attribute:$.string().optional(),seed:$.string(),hashVersion:$.literal(2),ranges:$.array(zc).max(100)}),US=$.strictObject({id:$.string().min(1).max(255),condition:Yt,gate:$.boolean().optional()}),BS=$.strictObject({key:$.string().optional(),name:$.string().optional(),passthrough:$.boolean().optional()}),rf={condition:Yt.optional(),parentConditions:$.array(US).max(100).optional(),weights:$.array($.number().min(0).max(1)).max(20).optional(),coverage:$.number().min(0).max(1).optional(),hashAttribute:$.string().optional(),fallbackAttribute:$.string().optional(),hashVersion:$.literal(2).optional(),disableStickyBucketing:$.boolean().optional(),bucketVersion:$.number().int().nonnegative().optional(),minBucketVersion:$.number().int().nonnegative().optional(),filters:$.array(qS).max(100).optional(),ranges:$.array(zc).max(20).optional(),meta:$.array(BS).max(20).optional(),seed:$.string().optional(),name:$.string().optional(),phase:$.string().optional()},wi=$.strictObject({...rf,key:$.string().min(1).max(255),variations:$.tuple([ve,ve]).rest(ve).refine(e=>e.length<=20),urlPatterns:$.array($.strictObject({include:$.boolean(),type:$.enum(["regex","simple"]),pattern:$.string()})).max(100).optional(),force:$.number().int().nonnegative().optional(),active:$.boolean().optional(),persistQueryString:$.boolean().optional()}),$c=$.strictObject({value:ve,variationId:$.number().int(),key:$.string(),name:$.string().optional(),bucket:$.number().optional(),passthrough:$.boolean().optional(),inExperiment:$.boolean(),hashUsed:$.boolean().optional(),hashAttribute:$.string(),hashValue:$.string(),featureId:$.string().nullable(),stickyBucketUsed:$.boolean().optional()}),VS=$.strictObject({...rf,id:$.string().max(255).optional(),force:ve.optional(),variations:$.array(ve).min(2).max(20).optional(),key:$.string().optional(),range:zc.optional(),tracks:$.array($.strictObject({experiment:wi,result:$c})).max(100).optional()}),LS=$.strictObject({defaultValue:ve.optional(),rules:$.array(VS).max(500).optional()}),mo=$.record($.string(),$.union([$.strictObject({type:$.literal("hashed"),attributeKey:$.string(),values:$.array($.string().regex(/^[a-f0-9]{64}$/))}),$.strictObject({type:$.literal("list"),attributeKey:$.string(),values:$.array($.union([$.string(),$.number()]))}),$.strictObject({type:$.literal("condition"),condition:Yt})])),yn=$.strictObject({scope:Ne,generation:$.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:$.iso.datetime({offset:!0}),expiresAt:$.iso.datetime({offset:!0}).nullable(),features:$.record($.string(),LS),savedGroups:mo,experiments:$.record($.uuid(),wi)});var fo=yn.extend({analyticsConfig:Lc,remoteFeatures:Ve.array(Ve.string().min(1).max(255)).max(500)}),Gc=fo.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"})}),of=Ve.strictObject({attributes:wt,features:Ve.array(Ve.string().min(1).max(255)).max(500).optional(),customerId:Ve.uuid().optional()}),zS=Ve.strictObject({value:ve,source:Ve.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:Ve.boolean(),off:Ve.boolean(),ruleId:Ve.string(),experimentResult:$c.optional()}),Ua=Ve.strictObject({generation:yn.shape.generation,evaluatedAt:yn.shape.evaluatedAt,expiresAt:yn.shape.expiresAt,features:Ve.record(Ve.string(),zS),merchandiseContext:Ve.strictObject({merchandiseId:Ve.uuid(),merchandise:wt}).optional()}),af=Ve.strictObject({customerId:Ve.uuid().optional(),events:Ve.array(Ve.strictObject({eventUuid:Ve.uuid(),timestamp:Ve.iso.datetime({offset:!0}),name:Ve.string().min(1).max(255),merchandise:Bd.optional(),properties:Ve.record(Ve.string(),ve).default({}),deviceId:Ve.string().min(1).max(255).optional(),sessionId:Ve.string().min(1).max(255).optional()})).min(1).max(100)}),sf=Ve.strictObject({inserted:Ve.number().int().nonnegative(),duplicates:Ve.number().int().nonnegative(),rejected:Ve.number().int().nonnegative(),skipped:Ve.number().int().nonnegative(),analyticsConfig:Lc});import{z as L}from"zod";import{z as $S}from"zod";var cf=$S.enum(["funnel-run/1","funnel-process/1"]),uf="funnel-process/1";function Kc(e,t=[]){let n=[];Gt(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(Sa(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 lf(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>lf(t)??[])}}function GS(e){let t=e.pages.map(i=>{let a=lf(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(Sa({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 df(e,t=[]){let n=un.parse(structuredClone(GS(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=Kc(n,t);if(i.length)throw new Error(i.join("; "));return n}import{z as Q}from"zod";import{z as M}from"zod";import{z as mt}from"zod";var Ba=mt.strictObject({schemaVersion:mt.literal(1),renderKey:mt.string().min(1).max(256),routeTemplate:mt.string().startsWith("/").max(2048),selectors:mt.array(mt.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:mt.array(mt.number().int().min(0)).min(1),absent:mt.array(mt.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"})}),pf=mt.strictObject({renderKey:mt.string().min(1).max(256),routeKey:mt.string().min(1).max(256),stateKey:mt.string().min(1).max(256),documentKey:mt.string().min(1).max(256),documentHash:mt.string().regex(/^[a-f0-9]{64}$/),compositionKey:mt.string().min(1).max(256),entryMode:mt.enum(["hard","soft"]),match:mt.strictObject({present:mt.array(mt.number().int().min(0)),absent:mt.array(mt.number().int().min(0))})});import{z as qr}from"zod";var KS=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],Hc="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",HS=qr.string().regex(new RegExp(`^${Hc}/${Hc}/${Hc}/manifest\\.json$`)),mf=qr.strictObject({kind:qr.literal("gcs-resumable"),url:qr.url(),bucket:qr.enum(KS),objectKey:HS,byteLength:qr.number().int().positive(),expiresAt:qr.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 yt=M.string().min(1).max(256),dn=M.string().regex(/^[a-f0-9]{64}$/),Va=M.strictObject({versionId:M.uuid(),manifestDigest:dn,sourceGraphDigest:dn,pageKey:yt,stateKey:yt,documentKey:yt,documentHash:dn,elementKey:yt.optional(),nodeId:yt.optional(),contentHash:dn.optional(),renderKey:yt.optional()}),ff=M.strictObject({pageKey:yt,documentKey:yt,expectedDocumentHash:dn,renderKey:yt.optional(),nodeId:yt,elementKey:yt,expectedContentHash:dn,property:M.enum(["text","fontSize","color"]),value:M.union([M.string().max(4e3),M.number().finite()])}),gf=M.strictObject({versionId:M.uuid(),manifestDigest:dn,sourceGraphDigest:dn,pageKey:yt,stateKey:yt,documentKey:yt,documentHash:dn,renderKey:yt.optional(),patches:M.array(ff.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),QS=/^[a-z][a-z0-9-]{0,39}$/,go=M.string().regex(QS),Jc=M.enum(["web","ios","android"]),T1=M.discriminatedUnion("action",[M.strictObject({action:M.literal("register"),requestId:M.uuid(),client:go,platform:Jc,label:M.string().trim().min(1).max(100),sha256:dn,bytes:M.number().int().min(1),transferBytes:M.number().int().min(1)}),M.strictObject({action:M.literal("complete"),versionId:M.uuid()}),M.strictObject({action:M.literal("current"),versionId:M.uuid(),expectedCurrent:M.uuid().nullable()}),M.strictObject({action:M.literal("delivery"),enabled:M.boolean()}),M.strictObject({action:M.literal("changes"),versionId:M.uuid(),experimentId:M.uuid(),variationId:yt,changesetId:M.uuid().nullable(),expectedRevision:dn.nullable(),editorUrl:M.string().url().max(2048),patches:M.array(ff).max(200)})]),Zc=M.strictObject({id:M.uuid(),projectId:M.uuid(),environmentId:M.uuid(),clientKey:go,platform:Jc,label:M.string(),sha256:dn,bytes:M.number().int().positive(),objectKey:M.string(),state:M.enum(["uploading","ready","rejected"]),isCurrent:M.boolean(),revision:M.number().int().nonnegative(),createdAt:M.string(),expiresAt:M.string(),readyAt:M.string().nullable(),summary:M.record(M.string(),M.json()),routeTree:M.json().nullable(),validation:M.record(M.string(),M.json())}),JS=M.strictObject({key:go,platform:Jc,currentId:M.uuid().nullable()}),N1=M.strictObject({rows:M.array(Zc).max(100),nextCursor:M.uuid().nullable(),clients:M.array(JS).max(20)}),Qc=M.strictObject({storedBytes:M.number().int().nonnegative(),reservedBytes:M.number().int().nonnegative(),chargedBytes:M.number().int().nonnegative(),versions:M.number().int().nonnegative(),objects:M.number().int().nonnegative(),orphanObjects:M.number().int().nonnegative(),missingReadyObjects:M.number().int().nonnegative(),unknownObjectSizes:M.number().int().nonnegative(),byteLimit:M.number().int().positive(),versionLimit:M.number().int().positive(),remainingBytes:M.number().int().nonnegative()}),D1=M.strictObject({asOf:M.iso.datetime({offset:!0}),reclamation:M.literal("manual-review-required"),buckets:M.strictObject({source:Qc,runtime:Qc,previews:Qc})}),F1=M.strictObject({version:Zc,actorId:M.uuid(),claims:M.record(M.string(),M.json())}),M1=M.strictObject({version:Zc,upload:mf.nullable()}),q1=M.object({format:M.literal("indiana-route-state-index"),schemaVersion:M.literal(3),routes:M.array(M.object({routeKey:yt,path:M.string(),documentKey:yt,documentHash:dn,initialStateKey:yt,initialRenderKey:yt})),renders:M.array(pf)}).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"})}),U1=M.strictObject({rows:M.array(M.object({id:M.uuid(),name:M.string(),status:M.string(),variations:M.array(M.object({id:yt,key:yt,name:M.string().optional()}).loose())}).loose()),limited:M.boolean()}),B1=M.strictObject({enabled:M.boolean(),allowedOrigins:M.array(M.string())});import{z as Oi}from"zod";var hf=Oi.strictObject({id:Oi.uuid(),name:Oi.string().trim().min(1).max(80),client:go,source:Va,event:Oi.enum(["screen_enter","button_click"]),cooldownSeconds:Oi.number().int().min(0).max(2592e3),behavior:Oi.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"})});import{z as Ke}from"zod";var Wc=ve,ZS=["parameters","answers","results","variables"];function Yc(e){return ZS.some(t=>e===t||e.startsWith(t+"."))}function Xc(e){let t={};for(let[r,i]of Object.entries(Ia(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])=>!Yc(r))),variables:t}}import{z as At}from"zod";var La=At.discriminatedUnion("kind",[At.object({kind:At.literal("ledger"),cursor:ga}).strict(),At.object({kind:At.literal("billing"),cursor:At.uuid()}).strict()]),WS=At.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),sr=At.record(At.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),At.union([At.string().max(500),At.boolean(),At.array(At.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),YS=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function eu(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>eu(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||YS.test(n)||eu(r,t+1)))}var XS=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,cr=At.record(WS,ve).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!eu(e)&&!XS.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var yf=At.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),za=At.array(At.object({variable:yf,componentId:yf,required:At.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"),Y1=At.object({bindings:za,answers:sr,values:At.record(At.string(),ve).optional()}).strict();import{z as e0}from"zod";var $a=e0.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var tu=Ke.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Af=Ke.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),bf=cr.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),nu=Ke.record(tu,Ke.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),t0=Fn,xf=Ke.strictObject({type:Ke.literal("external_task"),endpointId:Ke.uuid(),taskKey:tu,inputs:Ke.record(tu,t0).refine(e=>Object.keys(e).length<=20),outputs:nu}),Sf=Ke.strictObject({maxAttempts:Ke.number().int().min(1).max(5),retryDelaySeconds:Ke.number().int().min(1).max(30),backoff:Ke.enum(["fixed","exponential"]),requestTimeoutSeconds:Ke.number().int().min(1).max(10),timeoutSeconds:Ke.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var cE=Ke.strictObject({outcome:Ke.enum(["success","failure"]),data:bf});var uE=Ke.discriminatedUnion("operation",[Ke.strictObject({operation:Ke.literal("signal"),runId:Ke.uuid(),nodeId:Af,eventName:$a,eventId:Ke.uuid(),data:bf}),Ke.strictObject({operation:Ke.literal("read_results"),runId:Ke.uuid()})]),lE=Ke.strictObject({scope:Ne,runId:Ke.uuid(),eventId:Ke.uuid(),accepted:Ke.boolean()}),n0=Ke.record(Af,Wc),dE=Ke.strictObject({scope:Ne,runId:Ke.uuid(),results:n0});var Rn={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},If="00000000-0000-0000-0000-000000000000";import{z as Z}from"zod";import{z as Ye}from"zod";var yE=Ye.enum(["local","remote"]),ru=Ye.strictObject({port:Ye.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:ve.optional(),sticky:Ye.array(Ye.strictObject({expected:$i.nullable(),next:$i})).max(100),exposures:Ye.array(ve).max(100),features:Ye.array(ve).max(100)}),vf=Ye.strictObject({type:Ye.literal("evaluate"),receiptId:Ye.uuid(),environmentId:Ye.uuid(),policyRevision:Ye.number().int().nonnegative(),attributes:wt,sticky:Ye.record(Ye.string(),$i)}),wf=vf.extend({runId:Ye.uuid(),versionId:Ye.uuid(),nodeId:Ye.string().min(1).max(64),visit:Ye.number().int().nonnegative(),revision:Ye.number().int().nonnegative()}),iu=vf.omit({type:!0,receiptId:!0}).extend({type:Ye.literal("evaluate_segment")}),Of=Ye.strictObject({nodeId:Ye.string().min(1).max(64),result:ru}),Pf=iu.extend({runId:Ye.uuid(),versionId:Ye.uuid(),nodeId:Ye.string().min(1).max(64),visit:Ye.number().int().nonnegative(),revision:Ye.number().int().nonnegative(),parameters:cr,answers:sr,variables:Ye.record(Ye.string(),ve)});import{z as ue}from"zod";var ou=ue.array(ue.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"),Ga=ue.intersection(wt,ue.looseObject({tags:ou.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),Ka=ue.string().trim().max(80),Ha=ue.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),Qa=ue.union([ue.email().max(254),ue.literal("")]),Ja=ue.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),Cf=ue.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),_f=ue.object({externalUserId:Cf.optional(),name:Ka.default(""),email:Qa.default(""),phone:Ha.optional(),attributes:Ga.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),Ur=ue.discriminatedUnion("type",[ue.strictObject({type:ue.literal("id"),value:ue.uuid()}),ue.strictObject({type:ue.literal("externalUserId"),value:Cf})]),Pi=ue.strictObject({name:Ka.optional(),email:Qa.optional(),phone:Ha.optional(),attributes:Ga.optional(),fingerprint:Ja.optional()}),Za=e=>!e.customerData||e.customer?.type==="externalUserId",Wa="customerData requires an externalUserId customer",Ci=ue.object({id:ue.uuid(),externalUserId:ue.string().min(1).max(255).nullable(),name:Ka,email:Qa,phone:Ha.optional(),attributes:Ga,createdAt:ue.iso.datetime()}).strict(),Ef=ue.object({customer:Ci,changed:ue.boolean(),replayed:ue.boolean()}).strict(),r0=ue.discriminatedUnion("type",[ue.object({type:ue.literal("id"),value:ue.uuid()}).strict(),ue.object({type:ue.literal("externalUserId"),value:ue.string().trim().min(1).max(255)}).strict()]),i0=ue.object({name:Ka.optional(),email:Qa.optional(),phone:Ha.optional(),attributes:Ga.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:ue.array(ue.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:ue.strictObject({add:ou,remove:ou}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),au=ue.object({lookup:r0}).strict(),Rf=au.extend({requestId:ue.uuid(),patch:i0}).strict(),kf=ue.object({search:ue.string().trim().max(200).default(""),tag:ue.string().trim().max(40).default(""),planId:ue.string().max(200).default(""),versionId:ue.string().max(200).default(""),holdingStatus:ue.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:ue.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:ue.union([ue.iso.datetime(),ue.literal("")]).default(""),createdUntil:ue.union([ue.iso.datetime(),ue.literal("")]).default(""),offset:ue.coerce.number().int().min(0).max(1e5).default(0),limit:ue.coerce.number().int().min(1).max(100).default(50)}).strict(),jf=ue.object({customers:Ci.array(),hasMore:ue.boolean(),total:ue.number().int().nonnegative().nullable(),evaluatedAt:ue.iso.datetime()}).strict();var ho=Z.discriminatedUnion("type",[Z.strictObject({type:Z.literal("literal"),value:ve}),Z.strictObject({type:Z.literal("variable"),key:It,path:En.optional()}),Z.strictObject({type:Z.literal("feature"),featureKey:Z.string().min(1).max(128)})]),o0=Z.strictObject({requestId:Z.uuid(),decisionId:Z.uuid(),customerId:Z.uuid(),externalUserId:Z.string().min(1).max(255).nullable(),versionId:Z.uuid(),receiptId:Z.uuid(),value:ve}),a0={funnelId:Z.uuid(),requestId:Z.uuid(),customer:Ur,customerData:Pi.optional(),attributes:wt.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},EE=Z.discriminatedUnion("operation",[Z.strictObject({operation:Z.literal("decide"),...a0}).refine(Za,Wa),Z.strictObject({operation:Z.literal("read_decision"),decisionId:Z.uuid()}),Z.strictObject({operation:Z.literal("evaluate_decision"),decisionId:Z.uuid(),requestId:Z.uuid(),nodeId:Z.string().min(1).max(64),visit:Z.number().int().nonnegative(),revision:Z.number().int().nonnegative(),receiptId:Z.uuid(),policyRevision:Z.number().int().nonnegative(),generation:Z.string().min(1).max(256),result:ru}),Z.strictObject({operation:Z.literal("feature_config"),funnelId:Z.uuid()}),Z.strictObject({operation:Z.literal("commit_decision_segment"),decisionId:Z.uuid(),requestId:Z.uuid(),nodeId:Z.string().min(1).max(64),visit:Z.number().int().nonnegative(),revision:Z.number().int().nonnegative(),policyRevision:Z.number().int().nonnegative(),generation:Z.string().min(1).max(256),steps:Z.array(Of).max(32),boundary:Z.strictObject({nodeId:Z.string().min(1).max(64),visit:Z.number().int().nonnegative()}).optional()}),Z.strictObject({operation:Z.literal("segment_configuration"),funnelId:Z.uuid(),versionId:Z.uuid()}),Z.strictObject({operation:Z.literal("configuration"),funnelId:Z.uuid(),versionId:Z.uuid().optional()}),Z.strictObject({operation:Z.literal("local_configuration"),funnelId:Z.uuid()}),Z.strictObject({operation:Z.literal("report_used"),decisionId:Z.uuid(),eventId:Z.uuid(),occurredAt:Z.iso.datetime({offset:!0}),reference:Z.string().min(1).max(128).optional()})]),RE=Z.strictObject({scope:Ne,decisionId:Z.uuid(),requestId:Z.uuid(),status:Z.enum(["pending","completed","failed"]),decision:o0.nullable(),evaluation:Z.discriminatedUnion("type",[wf,Pf]).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"),kE=Z.strictObject({scope:Ne,decisionId:Z.uuid(),eventId:Z.uuid(),source:Z.literal("caller_reported")});import{z as Mt}from"zod";var Tf=Mt.strictObject({type:Mt.literal("bundle"),paywall:Fn.optional(),offering:Fn.optional(),coupons:Fn,data:Fn}),s0=e=>Mt.strictObject({type:Mt.literal(e),id:Mt.uuid()}),ME=Mt.strictObject({type:Mt.literal("bundle"),paywallVersionId:Mt.uuid().optional(),offeringVersionId:Mt.uuid().optional(),couponIds:Mt.array(Mt.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:ve});var qE=Mt.strictObject({type:Mt.literal("bundle"),offering:s0("offering_version").nullable(),paywall:Mt.strictObject({versionId:Mt.uuid(),paywallId:Mt.uuid(),offeringVersionId:Mt.uuid()}).nullable(),coupons:Mt.array(Gi).max(20),data:ve});import{z as kn}from"zod";import{z as An}from"zod";var Nf=An.union([An.string(),An.number().finite(),An.boolean(),An.null()]),c0=An.union([Nf,An.array(Nf).min(1).max(20)]),u0=An.record(En,c0).refine(e=>Object.keys(e).length<=10),Df=An.strictObject({path:En,type:An.enum(["string","number","boolean","strings"]),nullable:An.boolean().optional(),aggregation:An.enum(["count","exists"]).optional(),where:u0.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 l0=["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"],Ff=kn.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),d0=Fn,Mf=kn.discriminatedUnion("type",[xf,kn.strictObject({type:kn.literal("claim_offer"),coupon:Fn}),kn.strictObject({type:kn.literal("event"),event:Ff}),kn.strictObject({type:kn.literal("api"),operation:kn.enum(l0),inputs:kn.record(En,d0).refine(e=>Object.keys(e).length<=40),outputs:kn.record(Ff,Df).refine(e=>Object.keys(e).length<=20)})]);var ut=$a,p0=Q.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),pn={id:ut,name:Q.string().trim().min(1).max(80),position:Q.strictObject({x:Q.number().finite(),y:Q.number().finite()}).optional()},m0={success:ut,cancel:ut,unavailable:ut,failure:ut},su=Q.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),cu=Q.enum(["same_window","new_window"]),f0=Q.discriminatedUnion("type",[Q.strictObject({...pn,type:Q.literal("entry"),next:ut,triggers:Q.array(hf).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),Q.strictObject({...pn,type:Q.literal("screen"),screenId:ut,presentation:Pn,outputs:Q.record(ut,ut),offering:Q.discriminatedUnion("source",[Q.strictObject({source:Q.literal("variable"),key:It}),Q.strictObject({source:Q.literal("fixed"),versionId:Q.uuid()})]).optional()}),Q.strictObject({...pn,type:Q.literal("offering"),configuration:Q.discriminatedUnion("source",[Q.strictObject({source:Q.literal("fixed"),versionId:Q.uuid()}),Q.strictObject({source:Q.literal("feature"),featureKey:Q.string().min(1).max(128)})]),writes:Q.strictObject({value:It}),next:ut}),Q.strictObject({...pn,type:Q.literal("coupon"),couponId:Q.uuid(),writes:Q.strictObject({value:It}),next:ut}),Q.strictObject({...pn,type:Q.literal("coupons"),couponIds:Q.array(Q.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:Q.strictObject({value:It}),next:ut}),Q.strictObject({...pn,type:Q.literal("output"),value:Q.discriminatedUnion("type",[...ho.options,Tf,Q.strictObject({type:Q.literal("selection"),screenId:ut,offeringKey:It})])}),Q.strictObject({...pn,type:Q.literal("condition"),cases:Q.array(Q.strictObject({condition:Yt,target:ut})).min(1).max(50),default:ut}),Q.strictObject({...pn,type:Q.literal("feature"),featureKey:Q.string().min(1).max(128),writes:Q.strictObject({value:It}),next:ut}),Q.strictObject({...pn,type:Q.literal("split"),experimentId:Q.uuid(),applyPageExperiment:Q.literal(!0).optional(),routes:Q.record(p0,ut).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:ut}),Q.strictObject({...pn,type:Q.literal("action"),...m0,execution:Sf,action:Mf,writes:wc.optional()}),Q.strictObject({...pn,type:Q.literal("external_page"),appManifest:Va.optional(),url:su,openIn:cu,opened:ut,failed:ut}),Q.strictObject({...pn,type:Q.literal("end"),outcome:Q.enum(["completed","closed","ineligible","failed"]),output:ho.optional()}),Q.strictObject({...pn,type:Q.literal("wait"),writes:wc.optional(),wait:Q.discriminatedUnion("type",[Q.strictObject({type:Q.literal("duration"),delaySeconds:Q.number().int().min(1).max(2592e3),elapsed:ut}),Q.strictObject({type:Q.literal("event"),eventName:ut,outputs:nu,timeoutSeconds:Q.number().int().min(1).max(2592e3),received:ut,timeout:ut})])})]),uu=Q.strictObject({version:Q.literal(5),entry:ut,nodes:Q.array(f0).min(1).max(Rn.flowNodes)}),lu=uu.superRefine((e,t)=>{g0(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function Ya(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 g0(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>Rn.pages||e.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>Rn.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let l of e.nodes){for(let m of Ya(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 Ya(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 du={maxTransitions:1e4,runTimeoutSeconds:2592e3};function qf(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 tr(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]}import{z as q}from"zod";var _i=q.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Xa=e=>q.record(q.string(),ve).refine(t=>ln(t)<=e,"Funnel evidence exceeds its byte budget"),gR=q.enum(["local_segment","evaluation","presentation","timer","event","operation"]),mu=q.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),fu=q.discriminatedUnion("type",[q.strictObject({type:q.literal("flag"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("experiment"),id:q.uuid()}),q.strictObject({type:q.literal("saved_group"),id:q.uuid()}),q.strictObject({type:q.literal("config"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("constant"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("paywall_version"),id:q.uuid()}),q.strictObject({type:q.literal("offering_version"),id:q.uuid()}),q.strictObject({type:q.literal("reward"),id:q.uuid()})]),yo=q.strictObject({schemaVersion:q.literal(1),kind:mu,selector:fu.nullable(),context:Xa(131072),contract:q.strictObject({version:q.number().int().positive(),evaluator:q.string().min(1).max(128),policyRevision:q.number().int().nonnegative()})}).refine(e=>ln(e)<=131072,"Node input exceeds its byte budget"),Uf=q.strictObject({schemaVersion:q.literal(1),kind:mu,outcome:q.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:Xa(131072),route:q.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:Xa(131072)}).refine(e=>ln(e)<=131072,"Node result exceeds its byte budget"),hR=q.strictObject({schemaVersion:q.literal(1),operations:q.record(_i,q.strictObject({attempts:q.number().int().nonnegative(),maxAttempts:q.number().int().min(1).max(5),deadlineAt:q.iso.datetime({offset:!0}),retryAt:q.iso.datetime({offset:!0}).nullable(),error:q.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:q.strictObject({type:_i,id:q.uuid()}).nullable()}))}).refine(e=>ln(e)<=65536,"Execution state exceeds its byte budget"),Br={receiptId:q.uuid()},pu=q.iso.datetime({offset:!0}),yR=q.discriminatedUnion("type",[q.strictObject({type:q.literal("node_entered"),details:q.strictObject({kind:mu})}),q.strictObject({type:q.literal("presentation_shown"),details:q.strictObject({...Br,source:q.literal("client"),occurredAt:pu.optional()})}),q.strictObject({type:q.literal("decision_accepted"),details:q.strictObject(Br)}),q.strictObject({type:q.literal("signal_received"),details:q.strictObject({signalId:q.uuid(),nodeId:_i,eventName:_i,data:Xa(8192),source:q.literal("server"),occurredAt:pu})}),q.strictObject({type:q.literal("signal_consumed"),details:q.strictObject({...Br,signalId:q.uuid()})}),q.strictObject({type:q.literal("wait_elapsed"),details:q.strictObject(Br)}),q.strictObject({type:q.literal("wait_timeout"),details:q.strictObject(Br)}),q.strictObject({type:q.literal("operation_completed"),details:q.strictObject({...Br,operation:_i,reference:q.strictObject({type:_i,id:q.uuid()}).nullable()})}),q.strictObject({type:q.literal("execution_recovered"),details:q.strictObject({generation:q.number().int().positive(),reason:q.enum(["interrupted","expired_lease","delivery_failed"])})}),q.strictObject({type:q.literal("execution_failed"),details:q.strictObject({generation:q.number().int().positive(),code:q.string().regex(/^[a-z_]{1,64}$/)})}),q.strictObject({type:q.literal("run_completed"),details:q.strictObject({outcome:q.enum(["completed","ineligible","failed"])})}),q.strictObject({type:q.literal("run_closed"),details:q.strictObject({source:q.enum(["client","server","expiry"])})}),q.strictObject({type:q.literal("treatment_used"),details:q.strictObject({...Br,source:q.enum(["client","server"]),occurredAt:pu,reference:q.string().min(1).max(128).optional()})})]);var bn=L.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),h0=L.discriminatedUnion("type",[L.strictObject({id:bn,type:L.literal("owned"),publicData:tf.optional(),document:un.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.strictObject({id:bn,type:L.literal("paywall"),paywallVersionId:L.uuid()})]),gu={executionContract:cf.optional(),kind:L.literal("funnel"),schemaVersion:L.literal(4),screens:L.array(h0).max(Rn.pages),references:L.record(bn,fu).refine(e=>Object.keys(e).length<=500),inputs:L.array(L.strictObject({variable:bn,screenId:bn,componentId:bn,required:L.boolean()})).max(Rn.questions),variables:L.record(It,mi).refine(e=>Object.keys(e).length<=Rn.logicNodes),outputSchema:pi,execution:L.strictObject({runTimeoutSeconds:L.number().int().min(1).max(du.runTimeoutSeconds),maxTransitions:L.number().int().min(1).max(du.maxTransitions)})},MR=L.strictObject({...gu,graph:uu});function y0(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 ts(e){return Array.isArray(e)?e.some(ts):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===If:ts(n))}function A0(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=df(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&&!co(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}),y0(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"&&ts(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&ts(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function Bf(e,t){for(let{message:n,reason:r,path:i}of A0(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function Vf(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}or(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),Zn(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"&&!hn(e.outputSchema,d.output.value)&&n("Terminal output does not match outputSchema","output",h),d.type==="output"&&d.value.type==="literal"&&!hn(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&&!Oc(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 _c(v.document))(/^(input|params)\./.test(P)||P.startsWith("variables.")&&!Cc(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 Hn(v.condition))a("saved_group",P)||n("Conditions require explicit Saved Group references","savedGroup",h);for(let P of tr(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=>!hn({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=[...qf(d,c),...h?.type==="owned"?va(h.document).map(y=>Cc(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]:[]:Ya(_)).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"?co(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)Zn(d.root,()=>{l++});m+=g.document.actions.length}(l>Rn.components||m>Rn.actions||ln(e)>Rn.documentBytes)&&n("Funnel document exceeds its budget","budget")}var b0=L.strictObject({...gu,graph:lu}).superRefine(Vf),Ei=L.strictObject({...gu,graph:lu,displayName:L.string().trim().min(1).max(80)}).superRefine(Vf),qR=Ei.superRefine(Bf),UR=b0.superRefine(Bf),es=L.string().regex(kt),Ao={requestId:L.uuid(),nodeId:bn,visit:L.number().int().nonnegative(),revision:L.number().int().nonnegative(),customerToken:es.optional()},x0=L.discriminatedUnion("type",[L.strictObject({type:L.literal("screen"),output:bn,answers:sr,selection:L.record(bn,L.union([L.string().max(200),L.boolean(),L.number().int().min(0).max(1e4)])).optional()}),L.strictObject({type:L.literal("paywall_quote"),featureQuantities:L.record(L.uuid(),L.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100).optional(),actionId:bn,productVersionId:L.uuid(),offerId:L.uuid().optional(),nativeOffer:hi.optional(),predecessor:L.strictObject({operationId:L.uuid().nullable(),generation:L.number().int().positive()}).optional()}),L.strictObject({type:L.literal("paywall_confirm"),operationId:L.uuid()}),L.strictObject({type:L.literal("paywall_cancel"),operationId:L.uuid()}),L.strictObject({type:L.literal("client_action"),receiptId:L.uuid(),outcome:L.enum(["success","cancel","failure","opened","failed"])})]),S0=L.object({nodeId:bn,visit:L.number().int().nonnegative(),revision:L.number().int().nonnegative(),components:L.record(bn,L.object({resourceKey:L.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:L.number().int().min(1).max(1e5),after:La.nullable(),filter:L.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),Ot=L.discriminatedUnion("operation",[L.strictObject({operation:L.literal("start"),funnelId:L.uuid(),requestId:L.uuid(),customer:Ur.optional(),customerData:Pi.optional(),locale:L.string().min(1).max(35),parameters:cr}).refine(Za,Wa),L.strictObject({operation:L.literal("get"),settlementRequestId:L.uuid().optional(),data:S0.optional(),purchase:L.strictObject({receiptId:L.uuid(),operationId:L.uuid()}).optional(),customerToken:es.optional()}),L.strictObject({operation:L.literal("resume"),requestId:L.uuid(),customerToken:es.optional()}),L.strictObject({operation:L.literal("submit"),...Ao,input:x0}),L.strictObject({operation:L.literal("back"),...Ao}),L.strictObject({operation:L.literal("shown"),...Ao}),L.strictObject({operation:L.literal("close"),...Ao}),L.strictObject({operation:L.literal("commit_segment"),...Ao,policyRevision:L.number().int().nonnegative(),generation:L.string().min(1).max(256)}),L.strictObject({operation:L.literal("review"),receiptId:L.uuid().optional(),customerToken:es.optional()})]);function ns(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 Hn(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&&Yc(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)}}import{z as ae}from"zod";function Lf(e,t){let n=[],r={};Gt(e,i=>{if(i.hidden)return!1;if(i.type!=="quantity_picker")return;let a=i.bind?.plan?[i.bind.plan]:[];i.bind?.picker&&Gt(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(Gt(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}import{z as bo}from"zod";var $f=bo.object({defaultLocale:In,locales:bo.record(In,bo.object({name:bo.string().max(80),description:bo.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 I0=["customer_data","coupon_code"],Gf=ae.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),v0=ae.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),rs=(e,t)=>new Set(e.map(t)).size===e.length,w0=ae.strictObject({currency:Ie,amountMinor:ae.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),O0=ae.strictObject({featureId:ae.uuid(),name:ae.string().trim().min(1).max(120),allowance:ae.string().max(40).nullable(),access:ae.boolean()}),P0=ae.strictObject({stripe:ae.strictObject({prices:ae.array(w0).min(1).max(50)}).optional(),apple:ae.strictObject({productIds:ae.array(Gf).min(1).max(10)}).optional(),google:ae.strictObject({products:ae.array(ae.strictObject({productId:Gf,basePlanId:v0.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!rs(e.stripe.prices,n=>n.currency)||e.apple&&!rs(e.apple.productIds,n=>n)||e.google&&!rs(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),C0=ae.strictObject({name:ae.string().trim().min(1).max(80),interval:ae.enum(["free","week","month","year","one_time"]),intervalCount:ae.number().int().min(1).max(100),trial:ae.strictObject({days:ae.number().int().min(1).max(730),cardRequired:ae.boolean()}).nullable(),benefits:ae.array(O0).max(50).refine(e=>rs(e,t=>t.featureId),"Duplicate benefit"),channels:P0,prepaid:ae.array(io).max(100).optional()}),_0=ae.strictObject({digest:vi,content:ae.strictObject({discount:nr,duration:sn,appliesTo:sc,displayCopy:$f.nullable(),firstPurchaseOnly:ae.boolean(),qualificationRequired:ae.boolean(),startsAt:ae.iso.datetime().nullable(),endsAt:ae.iso.datetime().nullable(),grantWindowHours:ae.number().int().positive(),perCustomerLimit:ae.number().int().positive()})}),E0=ae.discriminatedUnion("type",[ae.strictObject({type:ae.literal("checkout"),product:xa}),ae.strictObject({type:ae.literal("close")}),ae.strictObject({type:ae.literal("action"),action:Vc})]),is=ae.strictObject({kind:ae.literal("paywall"),formatVersion:ae.literal(1),name:ae.string().trim().min(1).max(80),offeringVersionId:ae.uuid(),presentation:Pn,screen:un,products:Ma,catalog:ae.record(ae.uuid(),C0),buttons:ae.record(Ue,E0),coupons:ae.record(ae.uuid(),_0)}).superRefine((e,t)=>{let n=h=>t.addIssue({code:"custom",message:h}),{screen:r}=e;Lf(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),Kc(r,I0).forEach(n),or(r).some(h=>!h.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,o=new Set;Gt(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")}),Kf=ae.strictObject({state:ae.enum(["published","archived"]),controlRevision:ae.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:ae.uuid(),versions:ae.record(ae.uuid(),ae.strictObject({version:ae.number().int().positive(),artifact:ae.string().min(1),sourceDigest:ae.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},hu=Re.string().regex(/^[a-f0-9]{64}$/),yu=Re.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),bu=Ne.extend({environmentId:Re.uuid()}),Hf=Re.strictObject({features:Re.array(Re.string()).max(500),experiments:Re.record(Re.uuid(),Re.array(Re.string()).max(20)),savedGroups:Re.array(Re.string()).max(1e3)}),xu=Re.strictObject({kind:Re.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:Re.number().int().positive(),url:Re.string().min(1).max(2048),sha256:hu,byteLength:Re.number().int().positive().max(nn.maxArtifactBytes),generation:hu.optional()}),R0=Re.strictObject({state:Re.enum(["active","paused","archived"]),controlRevision:yu,evaluationMode:Re.enum(["local","remote"]),evaluationRevision:yu,currentVersionId:Re.uuid(),versions:Re.record(Re.uuid(),Re.strictObject({artifact:Re.string(),dependencies:Hf,definitionDigest:vi.optional(),couponDigests:Re.record(Re.uuid(),vi).optional()}))}),Su=Re.strictObject({kind:Re.literal("sdk_configuration"),schemaVersion:Re.literal(1),scope:bu,revision:yu,generation:hu,policy:Re.strictObject({refreshIntervalSeconds:Re.number().positive().max(15),maxControlAgeSeconds:Re.number().positive().max(60)}),gb:Re.strictObject({features:Re.string().nullable(),pageExperiments:Re.string().nullable()}),artifacts:Re.record(Re.string(),xu),funnels:Re.record(Re.uuid(),R0),paywalls:Re.record(Re.uuid(),Kf).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 Pt(e){if(Array.isArray(e))return`[${e.map(Pt).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)}:${Pt(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function Iu(e){return ni(ri(typeof e=="string"?new TextEncoder().encode(e):e))}function Qf(e){return Iu(Pt(e))}var Au=class extends Error{constructor(n,r){super(n);qe(this,"dependency",r)}};function Jf(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 Au(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=ns(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||!hn(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 Hn(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 Hf.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 Zf(e){return Ei.parse(e)}var Wf=Ct.strictObject({processContext:Pa.optional(),...gi,selector:Ct.discriminatedUnion("type",[Ct.strictObject({type:Ct.literal("paywall"),paywallId:Ct.uuid()}),Ct.strictObject({type:Ct.literal("version"),versionId:Ct.uuid()})]),customerId:Ct.uuid().optional(),commerce:ui,locale:Ct.string().min(1).max(35),requirement:ir.optional()}),xo=Ct.strictObject({id:Ct.uuid(),paywallId:Ct.uuid(),version:Ct.number().int().positive(),document:Ii.omit({requirement:!0,offeringId:!0}),offering:Ct.strictObject({id:Ct.uuid()}),content:Ct.strictObject({environmentId:Ct.uuid(),offeringVersionId:Ct.uuid(),artifact:xu.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:li,check:Rr.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"})}),Vr=Ct.strictObject(xo.shape).omit({document:!0,offering:!0}).extend({content:xo.shape.content.unwrap()});function Yf(e,t){let n=is.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 xo.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}})}import{z as Ht}from"zod";var Xf={requestId:Ht.uuid(),sourceId:Ht.uuid(),expectedAvailable:$t},eg=Ht.discriminatedUnion("action",[Ht.strictObject({...Xf,action:Ht.enum(["add","subtract","set_remaining"]),amount:xe}),Ht.strictObject({...Xf,action:Ht.literal("edit"),granted:xe,expiresAt:Ht.iso.datetime({offset:!0}).nullable(),nextResetAt:Ht.iso.datetime({offset:!0}).nullable(),expectedRevision:Ht.number().int().nonnegative()})]),vu=Ht.strictObject({sourceId:Ht.uuid(),available:$t,held:$t,spent:$t,adjustmentGrantId:Ht.uuid().nullable()}),tg=vu.extend({granted:$t,expiresAt:Ht.iso.datetime({offset:!0}).nullable(),nextResetAt:Ht.iso.datetime({offset:!0}).nullable(),revision:Ht.number().int().nonnegative()});import{z as mn}from"zod";var ng=mn.discriminatedUnion("action",[mn.object({action:mn.literal("upsert"),externalId:mn.string().min(1).max(128),name:mn.string().trim().min(1).max(80)}).strict(),mn.object({action:mn.literal("archive"),entityId:mn.uuid()}).strict()]),rg=mn.object({id:mn.uuid(),externalId:mn.string().min(1).max(128),name:mn.string().min(1).max(80),archived:mn.boolean()}).strict();import{z as Vt}from"zod";import{z as zr}from"zod";var og=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],ig=zr.string().regex(/.+\/.+/),wu=zr.number().min(-100),Lr=zr.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),k0=zr.strictObject({input:Lr,output:Lr,cache_read:Lr.optional(),cache_write:Lr.optional(),reasoning:Lr.optional(),input_audio:Lr.optional(),output_audio:Lr.optional()}),Ou=(e,t)=>zr.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),qk=zr.strictObject({defaultMarkup:wu,providerMarkups:Ou(zr.string().min(1),wu),modelMarkups:Ou(ig,wu),customModels:Ou(ig,k0.partial())});import{z as be}from"zod";var $r=be.iso.datetime({offset:!0}),ur=be.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),j0=be.discriminatedUnion("kind",[be.object({kind:be.literal("absolute"),from:$r,to:$r}).strict(),be.object({kind:be.literal("last_days"),days:be.union([be.literal(1),be.literal(7),be.literal(30),be.literal(90)])}).strict(),be.object({kind:be.literal("billing_cycles"),membershipId:be.uuid(),count:be.number().int().min(1).max(12),includeCurrent:be.boolean()}).strict()]),ag=be.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"),T0=be.object({key:be.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:be.array(be.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),Gr=be.object({range:j0,timezone:ag,filterBy:be.array(T0).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:be.enum(["hour","day","week","month"]),internal_feature_id:be.uuid().nullable(),entityId:be.uuid().nullable(),topN:be.number().int().min(1).max(50).nullable(),groupBy:be.union([be.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),be.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:be.object({bucket:$r,group:be.string().max(240),isOther:be.boolean(),internal_feature_id:be.uuid(),resourceId:be.uuid()}).strict().nullable(),limit:be.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)"})}),sg=be.object({from:$r,to:$r,interval:be.enum(["hour","day","week","month"]),timezone:ag,rows:be.array(be.object({bucket:$r,group:be.string().max(240),isOther:be.boolean(),internal_feature_id:be.uuid(),resourceId:be.uuid(),consumedUnits:ur,refundedUnits:ur,reservedUnits:ur,charged:ur,refunded:ur,reserved:ur,netUnits:ur,netCharged:ur}).strict()).max(100),nextCursor:be.object({bucket:$r,group:be.string().max(240),isOther:be.boolean(),internal_feature_id:be.uuid(),resourceId:be.uuid()}).strict().nullable()}).strict();var Ri=Vt.string().regex(/^(0|[1-9]\d{0,29})$/),cg=Vt.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),Pu=Vt.strictObject({bucket:Vt.iso.datetime({offset:!0}),group:Vt.string().max(240),isOther:Vt.boolean(),internal_feature_id:Vt.uuid()}),ug=Vt.strictObject({...Gr.shape,groupBy:Vt.union([Vt.enum(["customer","entity","entitlement"]),Vt.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Pu.nullable()}).superRefine((e,t)=>{let n=Gr.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),lg=Vt.strictObject({from:Vt.iso.datetime({offset:!0}),to:Vt.iso.datetime({offset:!0}),interval:Gr.shape.interval,timezone:Gr.shape.timezone,rows:Vt.array(Vt.strictObject({...Pu.shape,eventCount:Ri,units:cg,tokenEventCount:Ri,tokens:Vt.strictObject(Object.fromEntries(og.map(e=>[e,Ri]))),totalTokens:Ri,providerCostEventCount:Ri,providerCostUsd:cg,invalidTelemetryEventCount:Ri})).max(100),nextCursor:Pu.nullable()});import{z as bt}from"zod";var dg=bt.object({requestId:bt.uuid(),items:bt.array(bt.object({customerId:bt.uuid(),command:Yi.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"),pg=bt.object({batchId:bt.uuid(),after:bt.number().int().min(-1).max(999),limit:bt.number().int().min(1).max(100)}).strict(),mg=bt.object({batchId:bt.uuid(),status:bt.enum(["queued","complete"]),total:bt.number().int().min(1).max(1e3),processed:bt.number().int().min(0).max(1e3),items:bt.array(bt.object({position:bt.number().int().min(0).max(999),customerId:bt.uuid(),idempotencyKey:bt.string().min(1).max(120),status:bt.enum(["queued","accepted","rejected","failed"]),receipt:Xi.nullable(),errorCode:bt.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:bt.number().int().min(0).max(999).nullable()}).strict();import{z as k}from"zod";var N0=k.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),fg=k.enum(["draft","active","paused","archived"]),gg=k.string().min(1).max(256),hg=k.array(gg).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),D0=k.strictObject({duration:k.enum(["day","week","month","year"]),length:k.number().int().min(1).max(3660)}),F0=k.strictObject({internal_feature_id:k.uuid(),allowance:k.number().nonnegative().max(1e15).nullable(),expiry:D0.nullable()}),M0=k.discriminatedUnion("type",[k.strictObject({type:k.literal("feature_grant"),grants:k.array(F0).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),k.strictObject({type:k.literal("free_product"),productId:gg,duration:sn}),k.strictObject({type:k.literal("invoice_credits"),amount:k.number().positive().max(1e8),duration:sn,rollover:k.boolean(),productIds:hg})]),q0=k.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),yg=k.object({key:q0,name:k.string().trim().min(1).max(80),configuration:M0}).strict(),Ag=k.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),Cu=k.object({code:Ag,maxUses:k.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:k.boolean()}).strict(),bg=k.object({key:k.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:k.string().trim().min(1).max(80),rewardId:k.uuid(),redeemOn:k.enum(["customer_creation","checkout"]),receivedBy:k.enum(["referrer","all"]),maxRedemptions:k.number().int().min(1).max(1e6).nullable(),productIds:hg,excludeTrial:k.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),xg={id:k.uuid(),projectId:k.uuid(),environmentId:k.uuid(),revision:k.number().int().nonnegative(),status:fg,createdAt:k.iso.datetime({offset:!0}),updatedAt:k.iso.datetime({offset:!0})},U0=yg.extend(xg).strict(),B0=bg.safeExtend(xg).strict(),Yk=k.strictObject({id:k.uuid(),key:k.string(),name:k.string(),type:N0,status:fg}),Xk=k.discriminatedUnion("action",[k.object({action:k.literal("save"),id:k.uuid().nullable(),revision:k.number().int().nonnegative(),input:yg}).strict(),k.object({action:k.enum(["activate","pause","resume","archive","delete"]),id:k.uuid(),revision:k.number().int().nonnegative()}).strict()]),ej=k.discriminatedUnion("action",[k.object({action:k.literal("save"),id:k.uuid().nullable(),revision:k.number().int().nonnegative(),input:bg}).strict(),k.object({action:k.enum(["activate","pause","resume","archive","delete"]),id:k.uuid(),revision:k.number().int().nonnegative()}).strict()]),Sg=k.object({id:k.uuid(),rewardId:k.uuid(),programId:k.uuid().nullable(),customerId:k.uuid(),referrerId:k.uuid().nullable(),status:k.enum(["pending","applied","unavailable"]),result:k.record(k.string(),k.unknown()).nullable(),createdAt:k.iso.datetime({offset:!0})}).strict(),Ig=k.object({code:Ag,requestId:k.uuid()}).strict(),vg=k.strictObject({redemptionId:k.uuid(),currency:Ie,requestId:k.uuid(),accepted:k.literal(!0)}),V0=k.strictObject({type:k.literal("checkout"),orderId:k.uuid(),productVersionId:k.uuid(),currency:Ie,duration:sn,renewalAmountMinor:k.number().int().positive().max(1e8),status:k.enum(["created","pending","trialing","paid","cancelled","failed"]),url:k.url().nullable()}),wg=k.discriminatedUnion("type",[V0,k.strictObject({type:k.literal("subscription"),operationId:k.uuid(),membershipId:k.uuid(),productVersionId:k.uuid(),currency:Ie,duration:sn,renewalAmountMinor:k.number().int().positive().max(1e8),status:k.enum(["pending","running","applied","failed"])})]),Og=k.object({programId:k.uuid(),requestId:k.uuid()}).strict(),Pg=k.object({id:k.uuid(),programId:k.uuid(),code:Cu.shape.code,createdAt:k.iso.datetime({offset:!0})}).strict(),tj=k.object({rows:k.array(U0).max(100),nextCursor:k.uuid().nullable()}).strict(),nj=k.object({rows:k.array(B0).max(100),nextCursor:k.uuid().nullable()}).strict(),L0=Cu.extend({id:k.uuid(),redemptions:k.number().int().nonnegative()}).strict(),z0=k.strictObject({id:k.uuid(),programId:k.uuid().nullable(),customerId:k.uuid().nullable(),referrerId:k.uuid().nullable(),code:k.string().nullable(),status:k.enum(["pending","triggered","applied"]),createdAt:k.iso.datetime({offset:!0})}),rj=k.object({codes:k.array(L0).max(100),redemptions:k.array(z0).max(100),customers:k.record(k.uuid(),k.string()),codesCursor:k.uuid().nullable(),redemptionsCursor:k.uuid().nullable()}).strict(),ij=k.discriminatedUnion("action",[k.object({action:k.literal("create"),rewardId:k.uuid(),revision:k.number().int().nonnegative(),input:Cu}).strict(),k.object({action:k.literal("remove"),rewardId:k.uuid(),revision:k.number().int().nonnegative(),codeId:k.uuid()}).strict()]);import{z as w}from"zod";import{z as W}from"zod";var Mn={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},So=e=>new Set(e).size===e.length,_u=W.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),$0=W.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),Io=W.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"))),G0=W.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),Cg=W.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var _g=W.strictObject({id:W.uuid(),repo:$0,platform:W.enum(["github","gitlab","bitbucket"]),branches:W.array(Io).min(1).max(4).refine(So),workflow:W.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:W.array(W.uuid()).min(1).max(4).refine(So),include:W.array(Cg).min(1).max(16),exclude:W.array(Cg).max(16),methods:W.array(W.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(So),maxAgeHours:W.number().int().min(1).max(720)}),Eg=_g.extend({revision:W.number().int().positive()}),sj=W.strictObject({repository:_g,expectedRevision:W.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),Rg=W.strictObject({repositoryId:W.uuid(),branch:Io}),K0=W.array(_u).max(Mn.keys).refine(So),kg=W.strictObject({repository:Eg.omit({keyIds:!0}),branch:Io,keys:K0,keySetHash:W.string().regex(/^[a-f0-9]{64}$/)}),H0=W.strictObject({filePath:G0,startingLineNumber:W.number().int().min(1).max(1e7)}),Eu=W.strictObject({protocol:W.literal(1),repositoryId:W.uuid(),branch:Io,workflow:W.string().max(200),configurationRevision:W.number().int().positive(),keySetHash:W.string().regex(/^[a-f0-9]{64}$/),commit:W.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:W.uuid(),runNumber:W.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:W.number().int().min(1).max(1e4),scannerVersion:W.literal("1"),scannedAt:W.iso.datetime({offset:!0}),coverage:W.strictObject({complete:W.literal(!0),files:W.number().int().min(0).max(Mn.files),sourceBytes:W.number().int().min(0).max(Mn.sourceBytes),unresolvedCalls:W.number().int().min(0).max(1e6),unsupportedFiles:W.number().int().min(0).max(Mn.files)}),features:W.array(W.strictObject({key:_u,refs:W.array(H0).max(Mn.referencesPerKey)})).max(Mn.keys)}).superRefine((e,t)=>{So(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)>Mn.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),Ru=W.strictObject({scanId:W.uuid(),commit:W.string(),receivedAt:W.string(),references:W.number().int().nonnegative(),removedReferences:W.number().int().nonnegative()}),Q0=Ru.extend({repositoryId:W.uuid(),branch:Io,workflow:W.string(),digest:W.string(),configurationRevision:W.number().int().positive(),runNumber:W.number().int().positive(),runAttempt:W.number().int().positive(),scannedAt:W.string(),keySetHash:W.string(),coverage:Eu.shape.coverage}),J0=W.strictObject({repositories:W.array(Eg).max(Mn.repositories),scans:W.array(Q0).max(Mn.repositories*Mn.branches)}),Z0=W.strictObject({key:_u,references:W.number().int().nonnegative(),coveredTargets:W.number().int().nonnegative(),expiredTargets:W.number().int().nonnegative(),uncertainTargets:W.number().int().nonnegative()}),cj=W.strictObject({available:W.boolean().default(!0),settings:J0,expectedTargets:W.number().int().min(0).max(80),features:W.array(Z0).max(2001),truncated:W.boolean()});import{z as Ee}from"zod";var rn=Ee.string().min(1).max(200),os=Ee.iso.datetime({offset:!0}),vo=Ee.number().int().min(1).max(Number.MAX_SAFE_INTEGER),ku=Ee.number().int().min(0).max(1e12),Ng=Ee.number().int().min(1).max(1e12),jg={...Zt,type:Ee.literal("coupon.redeemed"),grantId:Ee.uuid()},Tg={...Zt,type:Ee.literal("usage.observed"),merchantTransactionId:rn,resource:rn,unit:rn,quantity:Ng},W0=Ee.strictObject({...Zt,type:Ee.literal("fulfillment.updated"),operationId:Ee.uuid(),merchantFulfillmentId:rn,status:Ee.enum(["pending","applied","failed"])}),Y0=Ee.strictObject({...Zt,type:Ee.literal("benefit.claimed"),merchantBenefitId:rn,resource:rn,unit:rn,quantity:Ng,expiresAt:os.nullable(),revision:vo}),X0=Ee.strictObject({...Zt,type:Ee.literal("benefit.closed"),merchantBenefitId:rn,status:Ee.enum(["failed","expired","canceled"]),revision:vo}),eI=Ee.strictObject({...Zt,type:Ee.literal("benefit.updated"),merchantBenefitId:rn,status:Ee.enum(["active","expired","revoked"]),remainingQuantity:ku.nullable(),expiresAt:os.nullable(),revision:vo}),tI=Ee.strictObject({...Zt,type:Ee.literal("authorization.updated"),merchantAuthorizationId:rn,kind:Ee.literal("auto_topup"),status:Ee.enum(["pending","effective","revoked","failed"]),termsReference:rn.nullable(),revision:vo}),nI=Ee.strictObject({...Zt,type:Ee.literal("balance.observed"),resource:rn,unit:rn,availableQuantity:ku,reservedQuantity:ku,periodStartsAt:os.nullable(),periodEndsAt:os.nullable(),revision:vo}),Dg=Ee.union([Ee.discriminatedUnion("type",[...Ml,W0,Y0,X0,eI,tI,nI]),Ee.strictObject({...jg,productVersionId:Ee.uuid(),subscriptionId:Ee.string().trim().min(1).max(255)}),Ee.strictObject({...jg,merchandiseId:Ee.uuid()}),Ee.strictObject({...Tg,operation:Ee.literal("consume")}),Ee.strictObject({...Tg,operation:Ee.literal("reverse"),reversalOf:rn})]),Fg=Ee.strictObject({id:Ee.uuid(),eventId:Ee.string().min(1).max(200),source:Ee.literal("merchant"),providerVerified:Ee.literal(!1),outcome:Ee.string().min(1).max(100)});import{z as oe}from"zod";var Mg=mm,rI=Mg.extend({invoice_id:Mg.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),ju=oe.strictObject({name:oe.string().trim().min(1).max(255),memo:oe.string().max(1e4).nullable().optional(),footer:oe.string().max(1e4).nullable().optional(),net_terms_days:oe.number().int().positive().nullable().optional()}),iI=ju.extend({id:oe.string().min(1).max(255),created_at:oe.number().nullable()}),qg=oe.strictObject({items:oe.array(iI).max(50),nextCursor:oe.uuid().nullable()}),gj=oe.discriminatedUnion("action",[oe.strictObject({action:oe.literal("create"),requestId:oe.uuid(),values:ju}),oe.strictObject({action:oe.literal("update"),id:oe.string().min(1).max(255),values:ju}),oe.strictObject({action:oe.literal("delete"),id:oe.string().min(1).max(255)})]),Ug=oe.discriminatedUnion("action",[oe.strictObject({action:oe.literal("create"),requestId:oe.uuid(),params:yi}),oe.strictObject({action:oe.enum(["finalize","send","pay","void"]),requestId:oe.uuid(),invoiceId:oe.uuid()}),oe.strictObject({action:oe.literal("reissue"),requestId:oe.uuid(),invoiceId:oe.uuid(),params:rI})]),Tu=oe.strictObject({id:oe.uuid(),customerId:oe.uuid(),providerInvoiceId:oe.string().nullable(),status:oe.enum(["draft","open","paid","void","uncollectible"]),currency:oe.string(),totalMinor:oe.string().regex(/^-?\d+$/),paidMinor:oe.string().regex(/^\d+$/),refundedMinor:oe.string().regex(/^\d+$/),hostedInvoiceUrl:oe.url().nullable(),createdAt:oe.number(),collectionMethod:oe.enum(["send_invoice","charge_automatically"]).nullable()}),Bg=Tu.extend({lines:oe.array(oe.strictObject({id:oe.uuid(),description:oe.string(),amountMinor:oe.string().regex(/^-?\d+$/),netAmountMinor:oe.string().regex(/^-?\d+$/),quantity:oe.number().nullable(),periodStart:oe.number().nullable(),periodEnd:oe.number().nullable()})).max(1e3)}),ki=oe.strictObject({taskId:oe.uuid(),status:oe.enum(["ready","running","done","dead"]),invoice:Tu.nullable(),errorCode:oe.string().nullable()}),Vg=oe.strictObject({items:oe.array(Tu).max(50),nextCursor:oe.uuid().nullable(),operations:oe.array(ki).max(50),operationsLimited:oe.boolean()});var oI=w.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"]),Lg={scope:Ne,permissions:w.array(oI),expiresAt:w.iso.datetime().nullable()},aT=w.discriminatedUnion("kind",[w.object({...Lg,kind:w.literal("server"),keyId:w.string().min(1)}),w.object({...Lg,kind:w.literal("customer"),customerId:w.string().min(1),identityKind:w.enum(["identified","guest"]),expiresAt:w.iso.datetime()})]),z=w.object({requestId:w.uuid(),scope:Ne}).strict(),aI=_f.safeExtend({fingerprint:Ja.optional()}).strict(),sI=z.extend({customer:Ci,created:w.boolean()});function zg(){return z.extend({offer:Gi.nullable(),reason:Ld.nullable()})}var O={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:jp,response:z.extend({message:w.object({messageId:w.uuid(),channel:ro,acceptedAt:w.iso.datetime({offset:!0}),status:w.enum(["accepted","sending","completed","canceled"]),replayed:w.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:w.strictObject({messageId:w.uuid()}),response:z.extend({message:w.object({id:w.uuid(),channel:ro,status:w.enum(["accepted","sending","completed","canceled"]),deliveries:w.array(w.object({id:w.uuid(),status:Np,attempts:w.number().int().nonnegative(),receipts:w.array(w.object({kind:Dp,occurredAt:w.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:Sl,response:z.extend({installation:Ir})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:Il,response:z.extend({installation:Ir})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:qo,response:z.extend({installation:Ir})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:w.strictObject({channel:ro}),response:z.extend({preference:Cs})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:Tp,response:z.extend({preference:Cs})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:w.strictObject({cursor:w.uuid().optional()}),response:z.extend({templates:qg})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:w.strictObject({customerId:w.uuid(),params:yi}),response:z.extend({preview:kc})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:w.strictObject({customerId:w.uuid(),requestId:w.uuid(),params:yi}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:z.extend({operation:ki})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:w.strictObject({customerId:w.uuid(),command:Ug}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:z.extend({operation:ki})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:w.strictObject({customerId:w.uuid(),taskId:w.uuid()}),response:z.extend({operation:ki})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:w.strictObject({customerId:w.uuid(),cursor:w.uuid().optional()}),response:z.extend({invoices:Vg})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:w.strictObject({customerId:w.uuid(),invoiceId:w.uuid()}),response:z.extend({invoice:Bg})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:Rg,response:z.extend({config:kg})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:Eu,response:z.extend({receipt:Ru})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:w.strictObject({}),response:z.extend({payload:fo})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:of,response:z.merge(Ua)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:af,response:z.merge(sf)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:w.strictObject({customerId:w.uuid(),sourceId:w.uuid()}),response:z.extend({balance:tg})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:w.strictObject({customerId:w.uuid(),command:eg}),response:z.extend({balance:vu})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:w.strictObject({internal_feature_id:w.uuid(),customerId:w.uuid().optional(),entityId:w.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:z.extend({internal_feature_id:w.uuid(),config:Ls,model_markups:Jo})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:w.strictObject({customerId:w.uuid(),query:fa}),response:z.extend({usage:eo})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:w.strictObject({customerId:w.uuid(),command:vp}),response:z.extend({usage:eo})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:w.strictObject({customerId:w.uuid(),command:yp}),response:z.extend({grant:dc})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:Ap,response:z.extend({grants:bp})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:w.union(Km.options.map(e=>e.extend({customerId:w.uuid().optional(),customerToken:w.string().regex(kt).optional()}))),response:z.extend({operation:Hm})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:Dm.extend({customerId:w.uuid().optional()}),response:z.extend({setup:Fc})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Fm.extend({customerId:w.uuid().optional()}),response:z.extend({setup:Fc})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:jm.safeExtend({customerId:w.uuid()}),response:z.extend({batch:lo})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:ka.extend({customerId:w.uuid()}),response:z.extend({batch:lo})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:ka.extend({customerId:w.uuid()}),response:z.extend({batch:lo})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:ka.extend({customerId:w.uuid()}),response:z.extend({batch:lo})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:w.discriminatedUnion("action",[ja.options[0].extend({customerId:w.uuid()}),ja.options[1].extend({customerId:w.uuid()}),ja.options[2].extend({customerId:w.uuid()})]),response:z.extend({trial:Dc})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Tm.extend({customerId:w.uuid()}),response:z.extend({trial:Dc})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:Da,response:z.extend({subscriptions:zm})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:Da,response:z.extend({purchases:$m})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:Bm,response:z.extend({conflicts:Gm})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:Vm,response:z.extend({resolution:Lm})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:qm,response:z.extend({verification:Um})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:wm.safeExtend({...gi,customerId:w.uuid().optional()}),response:z.extend({quote:Ai})},recordMerchantEvent:{method:"POST",path:"merchant/events/record",permission:"billing:write",audience:"server",request:Dg,response:z.extend({record:Fg})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Mr.extend({customerId:w.uuid().optional(),intent:w.enum(["confirm","cancel"]).optional()}),response:z.extend({operation:bi})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Mr.extend({customerId:w.uuid().optional()}),response:z.extend({operation:bi})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:Cm.safeExtend({customerId:w.uuid().optional()}),response:z.extend({quote:Em})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Mr.extend({customerId:w.uuid().optional(),intent:w.enum(["confirm","cancel"]).optional()}),response:z.extend({operation:jc})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Mr.extend({customerId:w.uuid().optional()}),response:z.extend({operation:jc})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:Rm.safeExtend({customerId:w.uuid()}),response:z.extend({quote:Tc})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Mr.extend({customerId:w.uuid()}),response:z.extend({operation:Ra})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Mr.extend({customerId:w.uuid()}),response:z.extend({operation:Ra})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:np,response:z.extend({controls:uc})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:Jd,response:z.extend({prepared:Wd})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:Yd,response:z.extend({authorization:la})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:sp,response:z.extend({coupons:cp})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Xd,response:z.extend({authorization:la})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:op,response:z.extend({invoices:ap})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:ip.extend({customerId:w.uuid()}),response:z.extend({operation:ki})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:rp,response:z.extend({invoice:Qi})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:w.object({customerId:w.uuid(),command:tp}).strict(),response:z.extend({controls:uc})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:w.object({customerId:w.uuid(),command:ng}).strict(),response:z.extend({entity:rg})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:w.strictObject({customerId:w.uuid().nullable(),query:ug}),response:z.extend({analytics:lg})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:w.object({customerId:w.uuid().nullable(),query:Gr}).strict(),response:z.extend({analytics:sg})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:dg,response:z.extend({batchId:w.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:pg,response:z.extend({batch:mg})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:qp.extend({customerId:w.string().min(1).optional()}),response:z.extend({check:Rr})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:w.strictObject({kind:ar,selector:w.discriminatedUnion("type",[w.strictObject({type:w.literal("resource"),id:w.uuid()}),w.strictObject({type:w.literal("version"),id:w.uuid()})]),customerId:w.string().min(1).optional()}),response:z.extend({content:Ec})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Wf,response:z.extend({paywall:Vr})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:w.strictObject({processContext:Pa.optional(),...gi,selector:Wm,customerId:w.string().min(1).optional(),commerce:ui,requirement:ir.optional()}),response:z.extend({offering:Ym,candidates:w.array(hc).max(20),availability:w.array(w.strictObject({productVersionId:w.uuid(),available:w.boolean(),reason:w.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:Rr.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:w.object({customerId:w.uuid().optional(),entityId:w.uuid().optional()}).strict(),response:z.extend({holdings:wp})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:w.object({customerId:w.uuid().optional(),query:Pp}).strict(),response:z.extend({ledger:Cp})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:xp.extend({customerId:w.uuid().optional()}),response:z.extend({detail:Sp})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:pc.safeExtend({customerId:w.uuid().optional()}),response:z.extend({statement:Ip})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:w.object({customerId:w.uuid().optional(),command:Yi.options[0]}).strict(),response:z.extend({quote:fp})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:w.strictObject({customerId:w.uuid(),command:w.union([w.strictObject({eventName:w.string().min(1),quantity:xe.optional(),properties:vt.optional(),entityId:w.uuid().optional(),idempotencyKey:w.string().min(1).max(120)}),w.strictObject({internal_feature_id:w.uuid(),quantity:xe.optional(),properties:vt.optional(),entityId:w.uuid().optional(),idempotencyKey:w.string().min(1).max(120)})])}),response:z.extend({receipts:w.array(Xi).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:w.object({customerId:w.uuid(),command:Yi.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:z.extend({receipt:Xi})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:Ig,response:z.extend({redemption:Sg})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:Og,response:z.extend({referralCode:Pg})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:vg,response:z.extend({checkout:wg})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:Ep,response:z.extend({seats:gc})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Rp,response:z.extend({seats:gc})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:aI,response:sI},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:au,response:z.extend({customer:Ci})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:kf,response:z.extend(jf.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:Rf,response:z.extend(Ef.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:w.object({customerId:w.uuid()}).strict(),response:z.extend(Wn.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:w.strictObject({}),response:z.extend(Wn.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:w.strictObject({customerId:w.uuid(),sessionId:w.uuid().optional()}),response:z.extend({revoked:w.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:w.strictObject({guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:Ja.optional()}),response:z.extend({customerId:w.uuid(),guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:w.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:w.strictObject({guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:z.extend(Wn.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:w.strictObject({guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:w.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:w.uuid()}),response:z.extend({customer:Ci,switched:w.boolean(),replayed:w.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:w.strictObject({code:w.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:w.uuid()}),response:zg()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:w.object({}).strict(),response:z.extend({offers:w.array(Gi)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:w.object({customerId:w.string().min(1).max(255).optional(),couponId:w.uuid(),...gi,requestId:w.uuid(),couponContentDigest:w.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:zg()}},sT={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};import{z as Nu}from"zod";var wo=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function Du(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 wo("Required GB Feature is unavailable");i=Kn(e.featureKey,t),o=i.value,Object.assign(r,fi(e,{value:o})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new wo("Required GB Experiment is unavailable");if(a=ca(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 wo("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:Kn(e.configuration.featureKey,t).value;o={type:"offering_version",id:Nu.uuid().parse(u)},Object.assign(r,fi(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,fi(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 $g(e,t,n){Nu.uuid().parse(e),Nu.number().int().nonnegative().parse(t);let r=ni(ri(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)}`}import{z as H}from"zod";var lr=H.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),cI=H.enum(["running","waiting","completed","closed","ineligible","failed"]),Fu=H.discriminatedUnion("type",[iu,H.strictObject({type:H.literal("wait"),receiptId:H.uuid(),kind:H.enum(["timer","event","operation"]),deadline:H.iso.datetime({offset:!0}).nullable(),eventName:lr.optional()}),H.strictObject({type:H.literal("open_url"),receiptId:H.uuid(),url:su,openIn:cu}),H.strictObject({type:H.literal("event"),receiptId:H.uuid(),event:lr})]),as=H.strictObject({type:H.literal("funnel"),id:H.uuid(),versionId:H.uuid()}),uI={id:lr,presentation:Pn,outputs:H.array(lr).max(250),inputs:za,values:H.record(H.string(),ve).optional(),offeringKey:It.optional(),capabilities:li,customerData:Gp,dataCursors:H.record(lr,La.nullable())},lI=H.strictObject({...uI,content:H.strictObject({type:H.literal("document"),document:un})}),Oo=H.strictObject({id:H.uuid(),source:as,revision:H.number().int().nonnegative(),visit:H.number().int().nonnegative(),nodeId:lr,nodeType:H.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:cI,stopped:H.boolean(),canBack:H.boolean(),authenticated:H.boolean(),locale:H.string().min(1).max(35),answers:sr,parameters:cr,variables:H.record(H.string(),ve),output:ve.nullable(),screen:lI.nullable(),paywall:H.strictObject({receiptId:H.uuid(),resolution:H.union([xo,Vr]),quote:Ai.nullable(),operation:bi.nullable(),purchaseRequestId:H.uuid().nullable(),selectionGeneration:H.number().int().nonnegative().optional(),canReselect:H.boolean().optional()}).nullable(),instruction:Fu.nullable(),pendingRequest:H.strictObject({requestId:H.uuid(),authenticationRequired:H.boolean()}).nullable(),runExpiresAt:H.iso.datetime({offset:!0}),credentialExpiresAt:H.iso.datetime({offset:!0}).nullable()}),ss=H.strictObject({scope:Ne,run:Oo,settlement:H.strictObject({requestId:H.uuid(),state:H.enum(["pending","unknown","settled"]),operationId:H.uuid().nullable(),receiptId:H.uuid().nullable().optional()}).optional(),purchase:H.strictObject({receiptId:H.uuid(),quote:Ai.nullable(),operation:bi.nullable(),canReselect:H.boolean().optional()}).optional(),review:H.strictObject({activeOperationId:H.uuid().nullable(),pages:H.array(H.strictObject({receiptId:H.uuid(),nodeId:lr,visit:H.number().int().nonnegative()})).max(100),page:H.strictObject({receiptId:H.uuid(),nodeId:lr,visit:H.number().int().nonnegative(),document:un,answers:sr,inputs:za,values:H.record(H.string(),ve).optional()}).nullable(),coupons:H.array(H.strictObject({grantId:H.uuid(),status:H.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:H.string().nullable()})).max(100),purchases:H.array(H.strictObject({receiptId:H.uuid(),operationId:H.uuid(),status:H.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:H.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:H.uuid().optional()}),Gg=ss.extend({run:Oo.extend({paywall:Oo.shape.paywall.unwrap().extend({resolution:Vr}).nullable()})});var Kg="X-Indiana-Server-Key";import{z as se}from"zod";import{z as Ae}from"zod";import{z as _t}from"zod";var dI=_t.strictObject({selector:_t.string().min(1).max(2048),action:_t.enum(["set","append","remove"]),attribute:_t.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:_t.string().max(5e4).optional(),parentSelector:_t.string().max(2048).optional(),insertBeforeSelector:_t.string().max(2048).optional()}),pI=_t.strictObject({variation:_t.string().min(1).max(128),description:_t.string().max(2e3).default(""),css:_t.string().max(1e5).default(""),js:_t.string().max(1e5).default(""),domMutations:_t.array(dI).max(200).default([]),iam:gf.optional(),renderGuard:Ba.optional()}),Mu=pI.omit({variation:!0,description:!0,iam:!0}),mI=wi.omit({variations:!0,active:!0}).extend({changeId:_t.string().regex(/^[a-f0-9]{64}$/),variations:_t.tuple([Mu,Mu]).rest(Mu).refine(e=>e.length<=20)}),Hg=_t.strictObject({trackExposures:_t.boolean(),environmentId:_t.uuid(),generation:_t.string().regex(/^[a-f0-9]{64}$/),experiments:_t.array(mI).max(100),savedGroups:mo});var Po=Ae.string().regex(/^[a-f0-9]{64}$/),VT=Ae.strictObject({iam:Po,executionContracts:Ae.union([Ae.tuple([Ae.literal("funnel-run/1")]),Ae.tuple([Ae.literal("funnel-process/1")])]).default(["funnel-run/1"])}),fI=Ae.strictObject({release:Po,render:Ba,button:Ae.strictObject({selector:Ae.string().min(1).max(512),elementKey:Ae.string().min(1).max(256),tag:Ae.enum(["button","a","input"])}).nullable()}),LT=Ae.strictObject({scope:Ne.extend({environmentId:Ae.uuid()}),release:Po,validatedAt:Ae.iso.datetime({offset:!0}),validUntil:Ae.iso.datetime({offset:!0}),entries:Ae.array(Ae.strictObject({id:Ae.uuid(),funnelId:Ae.uuid(),versionId:Ae.uuid(),event:Ae.enum(["screen_enter","button_click"]),target:fI})).max(4e3)}),Qg=Ae.strictObject({operation:Ae.literal("entry_start"),funnelId:Ae.uuid(),versionId:Ae.uuid(),entryId:Ae.uuid(),release:Po,requestId:Ae.uuid(),locale:Ae.string().min(1).max(35).default("en")}),Jg=Ae.strictObject({scope:Ne,suppressed:Ae.literal(!0),reason:Ae.enum(["frequency","in_progress"]),retryAt:Ae.iso.datetime({offset:!0}).nullable()}),zT=Ae.strictObject({experimentId:Ae.uuid(),splitNodeId:Ae.string().min(1).max(128)}),gI=Ae.strictObject({experimentId:Ae.uuid(),experimentKey:Ae.string().min(1).max(128),variationKey:Ae.string().min(1).max(128),inExperiment:Ae.boolean(),generation:Ae.string().min(1).max(256)}),Co=Ae.strictObject({operation:Ae.literal("page_experiments"),release:Po,usedReceiptIds:Ae.array(Ae.uuid()).max(20).default([]),customerToken:Ae.string().regex(kt).optional()}),Zg=Ae.strictObject({scope:Ne,runId:Ae.uuid(),assignments:Ae.array(gI.extend({receiptId:Ae.uuid()})).max(100),payload:Hg});var jn=se.literal(uf),hI=se.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),qu=se.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),Wg=se.discriminatedUnion("type",[se.strictObject({type:se.literal("guest"),guestToken:qu}),se.strictObject({type:se.literal("customer"),customer:Ur,customerData:Pi.optional()})]),Uu=se.strictObject({id:se.uuid(),runId:se.uuid(),customerId:se.uuid(),requestId:se.uuid(),acceptedAt:se.iso.datetime({offset:!0})}),yI=se.strictObject({participantId:se.uuid(),startedAs:se.enum(["guest","identified"]),binding:Uu.omit({runId:!0,requestId:!0}).nullable()}),AI=se.union([Fu,se.strictObject({type:se.literal("authentication_required"),reason:se.enum(["customer_required","customer_experiment_required"]),nodeId:se.string().min(1).max(64),visit:se.number().int().nonnegative()})]),bI=Oo.omit({authenticated:!0}).extend({identity:yI,instruction:AI.nullable()}),xI=se.discriminatedUnion("operation",[Ot.options[2].omit({customerToken:!0}),Ot.options[3].omit({customerToken:!0}),Ot.options[4].omit({customerToken:!0}),Ot.options[5].omit({customerToken:!0}),Ot.options[6].omit({customerToken:!0}),Ot.options[7].omit({customerToken:!0})]),cs={contract:jn,customerToken:se.string().regex(kt)},Yg={contract:jn,requestId:se.uuid(),runToken:hI,externalUserId:Ur.options[1].shape.value},Xg=se.discriminatedUnion("operation",[se.strictObject({contract:jn,operation:se.literal("describe")}),se.strictObject({contract:jn,operation:se.literal("start"),source:Wg,funnelId:Ot.options[0].shape.funnelId,requestId:se.uuid(),locale:Ot.options[0].shape.locale,parameters:Ot.options[0].shape.parameters}),Qg.omit({operation:!0}).extend({contract:jn,operation:se.literal("entry_start"),source:Wg}),se.strictObject({...Yg,operation:se.literal("bind_customer"),guestToken:qu,claimRequestId:se.uuid(),expectedBindingId:se.null()}),se.strictObject({...Yg,operation:se.literal("binding_status"),guestToken:qu.optional()}),Ot.options[1].omit({operation:!0,customerToken:!0}).extend({...cs,operation:se.literal("get"),settlementBindingId:se.uuid().nullable().optional()}),Ot.options[8].omit({operation:!0,customerToken:!0}).extend({...cs,operation:se.literal("review")}),Co.omit({customerToken:!0}).extend(cs),se.strictObject({...cs,operation:se.literal("command"),identity:se.strictObject({bindingId:se.uuid().nullable()}),command:xI})]),Bu=ss.omit({run:!0}).extend({contract:jn,run:bI,settlement:ss.shape.settlement.unwrap().extend({accepted:se.boolean().nullable().optional()}).optional()}),XT=Jg.extend({contract:jn}),eN=se.discriminatedUnion("operation",[Xg.options[1].omit({contract:!0,source:!0,requestId:!0}),Xg.options[2].omit({contract:!0,source:!0,requestId:!0})]),tN=Bu.extend({binding:Uu,outcome:se.enum(["bound","already_bound"]),replayed:se.boolean()}),nN=se.discriminatedUnion("state",[se.strictObject({contract:jn,scope:Ne,state:se.literal("not_accepted")}),se.strictObject({contract:jn,scope:Ne,state:se.literal("conflict")}),se.strictObject({contract:jn,scope:Ne,state:se.literal("bound"),binding:Uu})]),rN=se.strictObject({contract:jn,scope:Ne,keyId:se.uuid(),operations:se.array(se.string()).max(20)});import{z as Fe}from"zod";var ji=Fe.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),th=Fe.strictObject({entry:ji,nodes:Fe.array(Fe.strictObject({id:ji,type:Fe.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:Fe.record(Fe.string(),ji),writes:Fe.record(It,It),resources:Fe.strictObject({screenId:ji.optional(),paywallVersionId:Fe.uuid().optional(),couponId:Fe.uuid().optional(),couponIds:Fe.array(Fe.uuid()).max(20).optional(),experimentId:Fe.uuid().optional(),featureKey:Fe.string().optional(),offeringVersionId:Fe.uuid().optional()})})).min(1).max(500)}),eh={scope:Ne,funnelId:Fe.uuid(),versionId:Fe.uuid(),evaluationRevision:Fe.number().int().nonnegative(),expiresAt:Fe.iso.datetime({offset:!0}).nullable(),topology:th},us=Fe.discriminatedUnion("evaluationMode",[Fe.strictObject({...eh,evaluationMode:Fe.literal("local"),growth:yn,conditions:Fe.record(ji,Fe.array(Fe.strictObject({condition:Yt,port:Fe.string()})))}),Fe.strictObject({...eh,evaluationMode:Fe.literal("remote")})]),SI=us.options[0].extend({evaluation:Fe.strictObject({maxTransitions:Fe.number().int().min(1).max(1e4),variables:Fe.record(It,mi),outputSchema:pi,terminals:Fe.record(ji,Fe.strictObject({outcome:Fe.enum(["completed","closed","ineligible","failed"]),output:ho.nullable()}))})});function II(e){return th.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=Fe.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 Vu(e){let t=Ei.parse(e.document),n=e.evaluationMode==="local"?yn.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:II(t)};return us.parse(e.evaluationMode==="remote"?r:{...r,growth:ns(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 nh(e){let t=Vu(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=Ei.parse(e.document);return SI.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}]]}))}})}import{z as rt}from"zod";var rh=rt.string().regex(/^[a-f0-9]{64}$/),vI=wi.omit({variations:!0,active:!0}).extend({changeId:rh,variations:rt.array(rt.strictObject({urlRedirect:rt.string().max(2048)})).min(2).max(20)}),ih=rt.strictObject({environmentId:rt.uuid(),trackExposures:rt.boolean(),generation:rh,experiments:rt.array(vI).max(100),savedGroups:mo}),wI=rt.strictObject({eventUuid:rt.uuid(),timestamp:rt.iso.datetime({offset:!0}).optional(),deviceId:rt.string().min(1).max(128),sessionId:rt.string().min(1).max(128).optional(),url:rt.url().max(2048),pageTitle:rt.string().max(512).optional(),experimentKey:rt.string().min(1).max(255),variationKey:rt.string().min(1).max(64)}),hN=rt.strictObject({events:rt.array(wI).min(1).max(20)}),yN=rt.strictObject({inserted:rt.number().int().nonnegative(),duplicates:rt.number().int().nonnegative(),skipped:rt.number().int().nonnegative(),rejected:rt.array(rt.strictObject({index:rt.number().int().nonnegative(),reason:rt.string()}))});import{z as lt}from"zod";var zu=32,OI=522240;function $u(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 PI=lt.strictObject({nodeId:lt.string().min(1).max(64),visit:lt.number().int().nonnegative(),revision:lt.number().int().nonnegative()}),Lu=lt.record(lt.string(),ve),CI=lt.strictObject({id:lt.uuid(),nodeId:lt.string().min(1).max(64),visit:lt.number().int().nonnegative(),input:lt.strictObject({schemaVersion:yo.shape.schemaVersion,kind:yo.shape.kind,selector:yo.shape.selector,contract:yo.shape.contract}),context:Lu,removed:lt.array(lt.string()).max(100),attributes:Lu,removedAttributes:lt.array(lt.string()).max(100),result:Uf,offeringVersionId:lt.uuid().nullable(),events:lt.strictObject({entered:lt.string().regex(/^[1-9][0-9]{0,18}$/),decision:lt.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),vN=lt.strictObject({schemaVersion:lt.literal(1),mode:lt.enum(["local","remote"]),versionId:lt.uuid(),generation:lt.number().int().positive(),base:PI,context:Lu,steps:lt.array(CI).min(1).max(zu)}).refine(e=>ln(e)<=OI,"Segment exceeds its byte budget");var _I=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function _o(e){return Array.isArray(e)?e.some(_o):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&_o(n):!_I.test(t))}function oh(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=>_o(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"||_o(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"||_o(s.condition)||s.parentConditions?.length)?"customer_experiment_required":null}var Gu=class extends Error{constructor(n,r){super(r);qe(this,"code",n);this.name="FunnelLocalCalculationError"}},ah=(e,t)=>new Gu(e,t),EI=e=>({experiments:e.experiments,features:e.features});function RI(e,t=ah){let n=new Map(e.topology.nodes.map(o=>[o.id,o])),r=ii(e.growth.savedGroups),i=EI(e.growth);function a(o,s){if(!Object.hasOwn(e.growth.features,o))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Kn(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=Du({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=Du({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 kI(e,t){let n=us.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=RI(n,t);return(o,s)=>(i(),jI(a,o,s))}function jI(e,t,n){let r=wt.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 TI(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 sh(e,t,n,r=ah){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=>oh(t,R,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),d=R=>(f??(f=kI(e,r)),TI(f,R,{attributes:Xc({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:o,savedGroups:{}}),sticky:s}));for(let R=0;R<zu;R++){let y=a.get(u);if(!y||!$u(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"?Pc({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||!hn(t.outputSchema,A.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let v=[...c,{nodeId:u,result:A}];if(ln({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=fi(y,{value:P});em(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&&(!$u(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=Uo(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 Eo=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new b("INVALID_STATE","Installation sequence exhausted");return e+1},NI=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 qn(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 ch(e,t,n){let r=null,i=0,a=0,o=0,s=Promise.resolve(),c=!1;if(e&&(!n||Ne.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 NI(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=Ir.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(Pl(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=qn(x,Se=>Se),_;if(j.detachSeq!==null){let Se=j.detachSeq,ht=vl.parse(await g("detach",{sequence:Se,platform:x.platform}));try{let Je=await t.request("push/installations/detach",{...x.scope,...ht},"POST",{installationDetach:!0});if(!Je||typeof Je!="object"||!("installation"in Je))throw new b("INVALID_RESPONSE","Push detach acknowledgement is invalid");let Te=f(Je.installation);if(Te.bound||Te.identitySeq!==Se)throw new b("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(Je){if(Je instanceof b&&Je.status===404)_=Je;else if(!(Je instanceof b)||Je.status!==412)throw Je}_||qn(x,Je=>({...Je,detachSeq:Je.detachSeq===Se?null:Je.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&&qn(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=qn(j,Te=>P?Te:{...Te,addressSeq:Eo(Te.addressSeq)}),Se=await g(P?"recovery_confirm":"recovery_request",{...x,sequence:he.addressSeq,credentialDigest:await m(le),...P?{challenge:P}:{}}),ht=P?Ol.parse(Se):wl.parse(Se);if(l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let Je=await d(`push/installations/recovery/${P?"confirm":"request"}`,ht,le);if(l(_),X!==a||qn(j,Te=>Te).addressSeq!==he.addressSeq)throw new b("INVALID_STATE","Push observation changed during recovery");if(P){let Te=O.updatePushAddress.response.parse(Je),tt=f(Te.installation);if(!tt.bound||tt.identitySeq!==o||tt.addressSeq!==he.addressSeq||tt.connectionId!==x.connectionId||tt.addressStatus!=="active")throw new b("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return tt}if(!Je||typeof Je!="object"||!("recovery"in Je))throw new b("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return Ps.parse(Je.recovery)})}return{recoveryObserver(){u();let x={identity:i,observation:++a};return{async request(v){return Ps.parse(await A(v,x))},async confirm(v,P){return Ir.parse(await A(P,x,v))}}},identify(x){if(!e)return;o=qn(e,P=>({...P,identitySeq:Eo(P.identitySeq)})).identitySeq,r=x,i++,a++},reset(){if(e)try{qn(e,x=>{let v=Eo(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=qn(x,X=>{if(X.identitySeq!==P)throw new b("IDENTITY_CHANGED","A newer installation intent exists");return{...X,identitySeq:Eo(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=qn(j,Se=>({...Se,addressSeq:Eo(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||qn(j,Se=>Se).addressSeq!==X.addressSeq?null:f(le.response.parse(ke).installation)}}}}import{ZodError as DI}from"zod";function uh(e,t,n,r){try{return e.parse(t)}catch(i){throw r&&i instanceof DI?new b(n,r):i}}async function ge(e,t,n,r={},i){let a=typeof r=="function"?{}:r,o=uh(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):uh(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 lh(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 dh={name:"@tinkerlandai/longplay-sdk",version:"0.10.18",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 MI=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function qI(e){return e.replace(MI,"$1\uFFFD")}function Ju(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 xh(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 ph(e){let t;if(Array.isArray(e)){let n=e.map(Qe);if(n.length===2)return n}else if((t=xh(e))!=null){let n=Ju(t.next()),r=Ju(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 mh="0123456789ABCDEF",UI=/(?:%[0-9A-Fa-f]{2})+/g;function Un(e){return`%${mh[e>>4&15]}${mh[15&e]}`}function Sh(e,t,n=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?n&&e===32?"+":t(e)?Un(e):String.fromCharCode(e):e<=2047?Un(192|e>>6)+Un(128|63&e):e<=65535?Un(224|e>>12)+Un(128|e>>6&63)+Un(128|63&e):Un(240|e>>18)+Un(128|e>>12&63)+Un(128|e>>6&63)+Un(128|63&e)}function Zu(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function Wu(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(UI,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function jo(e){return e<=31||e>126}function BI(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return jo(e)}}function il(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return jo(e)}}function VI(e){return il(e)||e===39}function Yu(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return il(e)}}function fs(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 Yu(e)}}function fh(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 fs(n)}})(e)}}function Ih(e,t){return Sh(e=e||0,t)}function Bn(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+=Sh(o,t,n)}return i}function ol(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([Wu(i.slice(0,a),!0),Wu(i.slice(a+1),!0)])}if(n=r+1,r===e.length)break}return t}function Xu(e){let t="";for(let n=0;n<e.length;n++){let r=Bn(e[n][0],fh,!0),i=Bn(e[n][1],fh,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var LI=[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],zI=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],$I=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],GI=[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 KI(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[HI,QI,JI,gh]=[[[],"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 ZI(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 vh(e,t){for(let n=0;n<e.length;n+=2)if(t>=e[n]&&t<=e[n+1])return!0;return!1}function Ro(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 WI(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&&vh(GI,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&Ro(gh,t[i]);)i--;let a=n+1;for(;a<t.length&&Ro(gh,t[a]);)a++;if(!(i>=0&&a<t.length&&Ro(QI,t[i])&&Ro(JI,t[a])))return!1}return!0}var YI=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,XI=/\p{Script=Latin}/u;function ev(e){return!YI.test(e)||!XI.test(e)}var dr=36,ds=1,el=26,tv=38,nv=700,rv=72,iv=128,ov=2147483647;function hh(e){return String.fromCharCode(e+22+75*+(e<26))}function av(e,t,n){let r=0;for(e=n?Math.floor(e/nv):e>>1,e+=Math.floor(e/t);e>(dr-ds)*el>>1;r+=dr)e=Math.floor(e/(dr-ds));return Math.floor(r+(dr-ds+1)*e/(e+tv))}function sv(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=iv,o=0,s=rv;for(;r<t.length;){let c=ov;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=dr;;f+=dr){let g=f<=s?ds:f>=s+el?el:f-s;if(m<g)break;n+=hh(g+(m-g)%(dr-g)),m=Math.floor((m-g)/(dr-g))}n+=hh(m),s=av(o,r+1,r===i),o=0,r++}}o++,a++}return n}function Ku(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=Zu(e.charCodeAt(r));if(i>=t||i<0)return-1;n=n*t+i}return n}function yh(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function wh(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function Oh(e){return e.length===2&&wh(e.codePointAt(0),e.codePointAt(1))}function Ah(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function ft(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function Ph(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function tl(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=Zu(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+Zu(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 Ah(r)?null:Bn(r,jo)})(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)&&!vh(LI,m)||Ro(HI,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=ZI(m,f);if(g){l+=g;continue}let d=zI.indexOf(f);l+=d<0?m:$I[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(KI(u)||l&&(/^\p{Mark}/u.test(u)||!WI(u)||!ev(u)||u.startsWith("xn--")))return null;l&&(s[c]=`xn--${sv(u)}`)}return(i=s.join("."))!==""?i:null})(e.indexOf("%")===-1?e:Wu(e));return n===null||Ah(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(Ku(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=Ku(a[u]);if(l<0||l>255)return null;s+=l*(1<<8*(3-u))}let c=Ku(a[o-1]);return c<0||c>=256**(5-o)?null:(s+=c,s)})(n):n}}function nl(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 Ch(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 _h(e){return e.username!==""||e.password!==""}function Hu(e){return e.host===null||e.host===""||e.scheme==="file"}var E=0,U="",Oe="",Le=null,B,ps=!1,ms=!1,Kr=!1,gt;function fn(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,Oe="",Le=n||null,B=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},ps=!1,ms=!1,Kr=!1,gt=r||0;let i=cv;switch(r){case 3:case 4:i=gs;break;case 5:i=sl;break;case 6:i=Hr;break;case 7:i=pr;break;case 8:i=Vn}return i(G(e,E))!==1?B:null}function ee(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 Eh(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var cv=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 Oe=U.slice(E,n).toLowerCase(),E=n,uv(n<U.length?e:void 0)}else return gt?1:(--E,ee(t,e)?Rh(G(U,E)):0)},uv=e=>{let t=E;if(e===58){if(gt){if(ft(B.scheme)!==ft(Oe))return 0;if((_h(B)||B.port!==null)&&Oe==="file")return 0;if(B.scheme==="file"&&B.host==="")return 0}return B.scheme=Oe,gt?(B.port===Ph(B.scheme)&&(B.port=null),0):(Oe="",B.scheme==="file"?ee(t,e)?cl(G(U,E)):0:ft(B.scheme)&&Le!==null&&Le.scheme===B.scheme?ee(t,e)?lv(G(U,E)):0:ft(B.scheme)?ee(t,e)?pv(G(U,E)):0:G(U,E+1)===47?(E++,ee(t,e)?dv(G(U,E)):0):(B.path=[""],B.opaquePath=!0,ee(t,e)?jh(G(U,E)):0))}else return gt?1:(Oe="",E=-1,ee(t,e)?Rh(G(U,E)):0)},Rh=e=>{let t=E;return Le===null||Le.opaquePath&&e!==35?1:Le.opaquePath&&e===35?(B.scheme=Le.scheme,B.path=Le.path.slice(),B.opaquePath=Le.opaquePath,B.query=Le.query,B.fragment="",ee(t,e)?Vn(G(U,E)):0):Le.scheme==="file"?(E--,ee(t,e)?cl(G(U,E)):0):(E--,ee(t,e)?al(G(U,E)):0)},lv=e=>{let t=E;return e===47&&G(U,E+1)===47?(++E,ee(t,e)?ys(G(U,E)):0):(E--,ee(t,e)?al(G(U,E)):0)},dv=e=>{let t=E;return e===47?ee(t,e)?Ti(G(U,E)):0:(E--,ee(t,e)?Nn(G(U,E)):0)},al=e=>{let t=E;return B.scheme=Le.scheme,e===47||ft(B.scheme)&&e===92?ee(t,e)?bh(G(U,E)):0:(B.username=Le.username,B.password=Le.password,B.host=Le.host,B.port=Le.port,B.path=Le.path.slice(),B.query=Le.query,e===63?(B.query="",ee(t,e)?pr(G(U,E)):0):e===35?(B.fragment="",ee(t,e)?Vn(G(U,E)):0):e!=null?(B.query=null,B.path.pop(),E--,ee(t,e)?Nn(G(U,E)):0):ee(t,e)?al(G(U,E)):0)},bh=e=>{let t=E;return ft(B.scheme)&&(e===47||e===92)?ee(t,e)?ys(G(U,E)):0:e===47?ee(t,e)?Ti(G(U,E)):0:(B.username=Le.username,B.password=Le.password,B.host=Le.host,B.port=Le.port,E--,ee(t,e)?Nn(G(U,E)):0)},pv=e=>{let t=E;return e===47&&G(U,E+1)===47?E++:E--,ee(t,e)?ys(G(U,E)):0},ys=e=>{let t=E;return e!==47&&e!==92?(E--,ee(t,e)?Ti(G(U,E)):0):ee(t,e)?ys(G(U,E)):0},Ti=e=>{let t=E;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!ft(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&&ft(B.scheme))break;n+=Tn(r)}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?Ti(G(U,E)):0}if(e===64){ps&&(Oe=`%40${Oe}`),ps=!0;for(let n=0;n<Oe.length;n++){let r=Oe.codePointAt(n);if(r===58&&!ms){ms=!0;continue}let i=Ih(r,fs);ms?B.password+=i:B.username+=i,r!=null&&r>65535&&n++}return Oe="",ee(t,e)?Ti(G(U,E)):0}else return e==null||e===35||e===47||e===63||e===92&&ft(B.scheme)?ps&&Oe===""?1:(E-=Oe.length+1,Oe="",ee(t,e)?gs(G(U,E)):0):(Oe+=Eh(e),ee(t,e)?Ti(G(U,E)):0)},gs=e=>{let t=E;if(gt&&B.scheme==="file")return E--,ee(t,e)?ul(G(U,E)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!ft(B.scheme))){let n=E+Tn(e);for(e===91?Kr=!0:e===93&&(Kr=!1);n<U.length;){let r=G(U,n);if(r==null||!Kr&&r===58||r===35||r===47||r===63||r===92&&ft(B.scheme))break;r===91?Kr=!0:r===93&&(Kr=!1),n+=Tn(r)}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?gs(G(U,E)):0}else if(e===58&&!Kr){if(Oe===""||gt===4)return 1;let n=tl(Oe,!ft(B.scheme));return n===null?1:(B.host=nl(n),Oe="",ee(t,e)?sl(G(U,E)):0)}else if(e==null||e===35||e===47||e===63||e===92&&ft(B.scheme)){if(E--,ft(B.scheme)&&Oe==="")return 1;if(gt&&Oe===""&&(_h(B)||B.port!==null))return 1;let n=tl(Oe,!ft(B.scheme));return n===null?1:(B.host=nl(n),Oe="",gt?0:ee(t,e)?Hr(G(U,E)):0)}else return Oe+=Eh(e),ee(t,e)?gs(G(U,E)):0},sl=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 Oe+=U.slice(E,n),E=n-1,ee(t,e)?sl(G(U,E)):0}else if(gt||e==null||e===35||e===47||e===63||e===92&&ft(B.scheme)){if(Oe!==""){let n=parseInt(Oe,10);if(n>65535)return 1;if(B.port=n===Ph(B.scheme)?null:n,Oe="",gt)return 0}return gt?1:(E--,ee(t,e)?Hr(G(U,E)):0)}else return 1};function kh(e,t){let n=e.length-t;if(n<2)return!1;if(wh(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 cl=e=>{let t=E;return B.scheme="file",B.host="",e===47||e===92?ee(t,e)?mv(G(U,E)):0:Le?.scheme==="file"?(B.host=Le.host,B.path=Le.path.slice(),B.opaquePath=Le.opaquePath,B.query=Le.query,e===63?(B.query="",ee(t,e)?pr(G(U,E)):0):e===35?(B.fragment="",ee(t,e)?Vn(G(U,E)):0):e!=null?(B.query=null,kh(U,E)?B.path=[]:Ch(B),E--,ee(t,e)?Nn(G(U,E)):0):ee(t,e)?cl(G(U,E)):0):(E--,ee(t,e)?Nn(G(U,E)):0)},mv=e=>{let t=E;return e===47||e===92?ee(t,e)?ul(G(U,E)):0:(Le!==null&&Le.scheme==="file"&&(!kh(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})(Le.path[0])&&B.path.push(Le.path[0]),B.host=Le.host),E--,ee(t,e)?Nn(G(U,E)):0)},ul=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 Oe+=U.slice(E,n),E=n-1,ee(t,e)?ul(G(U,E)):0}else if(e==null||e===47||e===92||e===63||e===35){if(E--,!gt&&Oh(Oe))return ee(t,e)?Nn(G(U,E)):0;if(Oe==="")return B.host="",gt?0:ee(t,e)?Hr(G(U,E)):0;{let n=tl(Oe,!ft(B.scheme));return n===null?1:(n==="localhost"&&(n=""),B.host=nl(n),Oe="",gt?0:ee(t,e)?Hr(G(U,E)):0)}}return 1},Hr=e=>{let t=E;return ft(B.scheme)?(e!==92&&e!==47&&E--,ee(t,e)?Nn(G(U,E)):0):!gt&&e===63?(B.query="",ee(t,e)?pr(G(U,E)):0):!gt&&e===35?(B.fragment="",ee(t,e)?Vn(G(U,E)):0):e!=null?(e!==47&&E--,ee(t,e)?Nn(G(U,E)):0):(gt&&B.host===null&&B.path.push(""),ee(t,e)?Hr(G(U,E)):0)},Nn=e=>{let t=E;if(e!=null&&e!==47&&(!ft(B.scheme)||e!==92)&&(gt||e!==63&&e!==35)){let n=E+Tn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===47||ft(B.scheme)&&r===92||!gt&&(r===63||r===35))break;n+=Tn(r)}Oe+=Bn(U.slice(E,n),Yu),E=n,e=G(U,n)}if(e==null||e===47||ft(B.scheme)&&e===92||!gt&&(e===63||e===35)){let n=ft(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}})(Oe)?(Ch(B),e!==47&&!n&&B.path.push("")):yh(Oe)&&e!==47&&!n?B.path.push(""):yh(Oe)||(B.scheme==="file"&&B.path.length===0&&Oh(Oe)&&(Oe=`${Oe[0]}:`),B.path.push(Oe)),Oe="",e===63?(B.query="",ee(t,e)?pr(G(U,E)):0):e===35?(B.fragment="",ee(t,e)?Vn(G(U,E)):0):ee(t,e)?Nn(G(U,E)):0}else return Oe+=Ih(e,Yu),ee(t,e)?Nn(G(U,E)):0},jh=e=>{let t=E;if(e===63)return B.query="",ee(t,e)?pr(G(U,E)):0;if(e===35)return B.fragment="",ee(t,e)?Vn(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]+=Bn(r.slice(0,-1),jo)+"%20":B.path[0]+=Bn(r,jo),E=n,(e=G(U,n))===63)return B.query="",ee(t,e)?pr(G(U,E)):0;if(e===35)return B.fragment="",ee(t,e)?Vn(G(U,E)):0}return ee(t,e)?jh(G(U,E)):0},pr=e=>{let t=E,n=E;if(e!=null){if(gt)n=U.length;else{let i=U.indexOf("#",E);n=i===-1?U.length:i}let r=ft(B.scheme)?VI:il;B.query+=Bn(U.slice(E,n),r)}return E=n,G(U,n)===35&&!gt?(B.fragment="",ee(t,e)?Vn(G(U,E)):0):ee(t,e)?pr(G(U,E)):0},Vn=e=>{let t=E;return e!=null&&(B.fragment+=Bn(U.slice(E),BI),E=U.length),ee(t,e)?Vn(G(U,E)):0};function rl(e){if(e.opaquePath)return e.path[0];{let t="";for(let n of e.path)t+=`/${n}`;return t}}function Th(e){switch(e.scheme){case"blob":{let t=fn(rl(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":Th(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"),xn=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=fn(n,null,null,0),r==null))throw new TypeError(`Invalid base URL: ${n}`);let i=fn(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=fn(n,null,null,0),r==null)?!1:fn(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+=rl(n),n.query!==null&&(r+=`?${n.query}`),n.fragment!==null&&(r+=`#${n.fragment}`),r})(this[He].url)}set href(t){let n=fn(t=Qe(t),null,null,0);if(n==null)throw new TypeError(`Invalid URL: ${t}`);this[He].url=n,this[He].query&&Qu(this[He].query,n.query)}get origin(){return Th(this[He].url)}get protocol(){return`${this[He].url.scheme}:`}set protocol(t){fn(`${t=Qe(t)}:`,this[He].url,null,2)}get username(){return this[He].url.username}set username(t){t=Qe(t),Hu(this[He].url)||(function(r,i){r.username=Bn(i,fs)})(this[He].url,t)}get password(){return this[He].url.password}set password(t){t=Qe(t),Hu(this[He].url)||(function(r,i){r.password=Bn(i,fs)})(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||fn(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||fn(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];Hu(n)||(t?fn(t,n,null,5):n.port=null)}get pathname(){return rl(this[He].url)}set pathname(t){t=Qe(t);let{url:n}=this[He];n.opaquePath||(n.path=[],fn(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&&Qu(r,null);else{let i=t[0]==="?"?t.substring(1):t;n.query="",fn(i,n,null,7),r&&Qu(r,n.query)}}get searchParams(){let t=this[He],n=t.query;return n==null&&(n=t.query=(function(i,a){let o=new hs;return o[st].url=i,o[st].serialized=a==null,a&&(o[st].list=ol(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="",fn(r,n,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(xn.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var st=Symbol("URLSearchParamsImpl"),fv=Symbol.dispose||Symbol.for("dispose");function Qu(e,t){t?e[st].list=ol(t):e[st].list.length=0,e[st].serialized=t==null}function ls(e){if(e.url){let t=Xu(e.list);(function(r,i){r[He].url.query=i})(e.url,t||null),e.serialized=!0}}var gv=typeof Iterator<"u"?Iterator:Object,ko=class extends gv{constructor(t,n){super(),this[st]={ptr:t,map:n,index:0}}next(){let t=this[st];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}[fv](){}},hs=class{constructor(t){let n=this[st]={list:[],url:null,serialized:!0},r;if(Array.isArray(t))for(let i=0;i<t.length;i++)n.list.push(ph(t[i]));else if((r=xh(t))!=null){let i;for(;!(i=Ju(r.next())).done;)n.list.push(ph(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=qI(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=ol(i)}}get size(){return this[st].list.length}append(t,n){t=Qe(t),n=Qe(n),this[st].list.push([t,n]);let r=this[st];r.url&&r.serialized?(function(a,o){let s=a[He].url;s.query=s.query?`${s.query}&${o}`:o})(r.url,Xu([[t,n]])):ls(r)}delete(t,n){t=Qe(t),n=n!=null?Qe(n):void 0;let{list:r}=this[st],i=0;for(;i<r.length;)r[i][0]===t&&(n==null||r[i][1]===n)?r.splice(i,1):i++;ls(this[st])}get(t){t=Qe(t);let{list:n}=this[st];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[st];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[st];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[st],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&&ls(this[st])}sort(){this[st].list.sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0),ls(this[st])}forEach(t,n){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:r}=this[st];for(let i=0;i<r.length;i++)t.call(n,r[i][1],r[i][0],this)}entries(){return new ko(this[st],t=>t)}keys(){return new ko(this[st],t=>t[0])}values(){return new ko(this[st],t=>t[1])}toString(){return Xu(this[st].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(hs.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var mr="https://api.longplayai.com";function Nh(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=Wn.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 Dh=Symbol("IndianaNoContent");function fr(e,t,n=xn){let r=e.configuration?.scope,i=e.scope??(r&&{projectId:r.projectId,environment:r.environment}),a=i?Ne.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??mr);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??Nh(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((Te,tt)=>{ke=()=>tt(he()),le.signal.addEventListener("abort",ke,{once:!0})}),ht=setTimeout(()=>le.abort(),P.timeoutMs??c),Je=async()=>{let Te=await s(`${o.href.replace(/\/$/,"")}/api/v1/${A}`,{method:v,headers:{...P.headers,"Content-Type":"application/json",..._?{}:{Authorization:`Bearer ${j}`},[ks]:js.current,[kl]:dh.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 tt;try{tt=Te.status===204?Dh:await Te.json()}catch{throw le.signal.aborted?he():new b(Te.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",Te.status,Te.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(!Te.ok){let pt=Rs.safeParse(tt),Qt=pt.success&&(!$n.safeParse(pt.data.error.code).success||El(pt.data.error.code,Te.status)),Ar=Qt?pt.data.error.code:"HTTP_ERROR",br=Uo(Ar,Te.status,{retryAfter:Te.headers.get("Retry-After"),recovery:Qt?pt.data.error.recovery:void 0,reason:Qt?pt.data.error.reason:void 0});throw new b(Ar,Qt?pt.data.error.message:"Longplay request failed",Te.status,Te.headers.get("X-Request-Id")??(pt.success?pt.data.requestId:void 0),{...br,...pt.success&&pt.data.error.retryable===!1?{retryable:!1}:{},...br.retryAfterSeconds===void 0&&pt.success&&pt.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:pt.data.error.retryAfterSeconds}:{}})}if(Te.headers.get(ks)!==js.current)throw new b("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&tt!==Dh){let pt=tt&&typeof tt=="object"&&"scope"in tt?tt:tt&&typeof tt=="object"&&"configuration"in tt?tt.configuration:null;if(!pt||typeof pt!="object"||!("scope"in pt))throw new b("INVALID_RESPONSE","Response is missing its App/environment scope");let Qt=Ne.safeParse(pt.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 Jr=Te.headers.get("X-Indiana-Telemetry-Subject");if(Jr){if(!/^[a-f0-9]{64}$/.test(Jr))throw new b("INVALID_RESPONSE","Invalid telemetry identity");m!==Jr&&(m=Jr,t?.(m))}return tt};try{return await Promise.race([Je(),Se])}catch(Te){throw!_&&X!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):Te instanceof b?Te:new b(le.signal.aborted?"TIMEOUT":"NETWORK_ERROR",le.signal.aborted?"Longplay request timed out":"Unable to read the Longplay response")}finally{clearTimeout(ht),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=Ne.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 Fh(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(!kt.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 ze(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new b("INVALID_REQUEST","Customer requests use the verified session identity")}var hv={...O.readHoldings,request:O.readHoldings.request.omit({customerId:!0})};function Mh(e){return{async checkEntitlement(t){ze(t);let n=O.checkEntitlement;return ge(e,n,t)},async readHoldings(t={}){return ge(e,hv,t)}}}function qh(e){return{async readLedger(t){let n=O.readLedger;return ge(e,n,{query:t})},async readCreditStatement(t){ze(t);let n=O.readCreditStatement;return ge(e,n,t)},async quoteBalance(t){ze(t);let n=O.quoteBalance;return ge(e,n,{command:t})}}}function Uh(e){return{async setupPayment(t){ze(t);let n=O.setupPayment;return ge(e,n,t)},async readPaymentSetup(t){ze(t);let n=O.readPaymentSetup;return ge(e,n,t)},async readBillingInvoice(t){ze(t);let n=O.readBillingInvoice;return ge(e,n,t)},async readBillingControls(t={}){ze(t);let n=O.readBillingControls;return ge(e,n,t)},async prepareBillingAuthorization(t){ze(t);let n=O.prepareBillingAuthorization;return ge(e,n,t)},async confirmBillingAuthorization(t){ze(t);let n=O.confirmBillingAuthorization;return ge(e,n,t)},async setBillingCoupons(t){ze(t);let n=O.setBillingCoupons;return ge(e,n,t,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(t){ze(t);let n=O.revokeBillingAuthorization;return ge(e,n,t)},async listBillingInvoices(t={after:null,limit:25}){ze(t);let n=O.listBillingInvoices;return ge(e,n,t)},async confirmBillingAdjustment(t){ze(t);let n=O.confirmBillingAdjustment;return ge(e,n,t)}}}function Bh(e){return{async previewUpdate(t){ze(t);let n=O.previewUpdate;return ge(e,n,t)},async update(t){ze(t);let n=O.update;return ge(e,n,t)},async readSubscriptionUpdate(t){ze(t);let n=O.readSubscriptionUpdate;return ge(e,n,t)},async restoreNativePurchase(t){ze(t);let n=O.restoreNativePurchase;return ge(e,n,t)},async previewAttach(t){ze(t);let n=O.previewAttach;return ge(e,n,t)},async attach(t){ze(t);let n=O.attach;return ge(e,n,t)},async readSubscriptionOperation(t){ze(t);let n=O.readSubscriptionOperation;return ge(e,n,t)}}}function Vh(e){return{async redeemReward(t){return ze(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 ze(t),(await ge(e,O.claimRewardProduct,t,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(t){return ze(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 Lh(e){return{...Mh(e),...qh(e),...Uh(e),...Bh(e),...Vh(e)}}function zh(e){return{async resolveContent(t){ze(t);let n=O.resolveContent;return ge(e,n,t)},async resolvePaywall(t){ze(t);let n=O.resolvePaywall;return ge(e,n,t)},async resolveOffering(t){ze(t);let n=O.resolveOffering;return ge(e,n,t)}}}var ll=e=>new TextEncoder().encode(JSON.stringify(e)).length,$h=16384;function Gh(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&&!nf(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(ll({events:[y]})>$h)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=ll({events:[]});for(let _ of a.slice(0,Math.min(A,100))){let X=ll(_)+(x.length?1:0);if(x.length&&v+X>$h)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 dl(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:wt.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(Kn(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=Ua.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=wt.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?fo.parse(x):null,P=v??yn.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(Pt(le)!==Pt(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=ii(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=wt.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 Kh(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 yv(e){let t=Kh(e),{merchandiseId:n,merchandise:r,...i}=e;return{...i,...t?{merchandise:t}:{}}}function Hh(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 ht=Kh(Se);n.track(he,ke,ht?{merchandise:ht}:{})}catch(ht){R(ht)}},A=dl({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:yv(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()}}}import{z as Av}from"zod";function Qh(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=Av.object({funnelId:as.shape.id,funnelVersionId:as.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 Jh(e){let t=fr(e),n=t.request,r;try{r=ch(e.push,t,e.scope??e.configuration?.scope)}catch(s){throw t.dispose(),s}let i=Fh(t,()=>{o.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=Gh(n,i.isIdentified),o=Hh(n,i.isIdentified,a,e.scope,e.configuration);return{session:t.session,...lh(n,r),...Lh(n),...zh(n),forFunnel(s){return i.assertActive(),Qh(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 Ni(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)=>Ni(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)&&Ni(a,Reflect.get(t,i)))}function As(e,t){let n=Gg.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 Di=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function bs(e){let t=kt.test(e.apiKey);if(typeof window<"u"&&!t)throw new b("SERVER_ONLY","Funnel starts are issued by your backend");if(!t&&!Di.test(e.apiKey))throw new b("INVALID_TOKEN","A customer credential or server API key is required");return{async start(n){let r=Ot.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=fr({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||a.identify(e.apiKey);let o=As(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")||!Ni(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 pl(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 Zh(e,t,n){return new TextDecoder("utf-8",{fatal:!0}).decode(await pl(e,t,n))}function xs(e,t){let n=typeof e=="string"?new TextEncoder().encode(e):e;return n.byteLength===t.byteLength&&Iu(n)===t.sha256}async function Ss(e,t){let n=Vr.parse(t),{artifact:r,environmentId:i}=n.content,a=new xn(e.baseUrl??mr).origin,o=new xn(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 pl(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(!xs(f,r))throw new b("INVALID_RESPONSE","Public Paywall digest or size changed");return Yf(n,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(f)))})();try{return await Promise.race([l,u])}finally{clearTimeout(c)}}var Wh=(e,t)=>new b(e,t);var bv=3,xv=2e3;function Sv(e){return e instanceof TypeError||e instanceof b&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Iv(e){for(let t=1;;t++)try{return await e.refresh()}catch(n){if(t===bv||!Sv(n))throw n;await new Promise(r=>setTimeout(r,t*xv))}}async function ml(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=vv(e,t,o)}catch{i=null}return a??(a=e.snapshot?.generation??(await Iv(e)).generation),{advance:{policyRevision:r.policyRevision,generation:a},prediction:i}}function vv(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=Vu({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:yn.parse(o)}),c=wv(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 wv(e,t,n){return sh(e,t,n,Wh)}import{z as gn}from"zod";var Yh=Ot.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}),Xh=gn.strictObject({schemaVersion:gn.literal(1),scope:Ne,runId:gn.uuid(),funnelId:gn.uuid(),versionId:gn.uuid(),processBindingIds:gn.record(gn.uuid(),gn.uuid().nullable()).optional(),command:Yh.optional(),closeCommand:Yh.refine(e=>e.operation==="close").optional(),purchase:gn.strictObject({receiptId:gn.uuid(),operationId:gn.uuid(),generation:gn.number().int().nonnegative()}).optional(),closed:gn.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"),Is=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function ey(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:Xh.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(Is(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=Xh.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&&!Is(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&&!Is(f.closeCommand,m))throw Xt();return{...f,closeCommand:m,closed:!0}}if(!Is(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 ty(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??mr).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 ny(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||!Ni(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(!kt.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 gr(e){let{customerToken:t,...n}=e;return n}var Ov=e=>!(e instanceof b)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function ry({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:gr(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&&!Ov(v)&&(e&&await e.settle(y.requestId),A===t.generation&&R(y)),v}}function g(y){let A=Ot.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(gr(a))!==JSON.stringify(gr(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(gr(i))!==JSON.stringify(gr(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,ht=le?.receiptId??ke?.receiptId,Je=X?.selectionGeneration??u?.generation??0;if(e&&Se&&ht&&y.operation!=="review"&&(!t.view||A.run.revision>=t.view.revision)&&(v===void 0||v>=t.readSequence)&&(!u||Je>=u.generation)){let Te={receiptId:ht,operationId:Se,generation:Je},tt=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},Te,tt,j),t.assertCurrent(x),(!u||Te.generation>=u.generation)&&(v===void 0||v>=t.readSequence)&&(tt?u?.operationId===Te.operationId&&(u=void 0):u=Te)}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 hr(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"||!Di.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=fr({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),n=ny(e.funnelId,e.scope??e.configuration?.scope),r=e.session?.subscribeIdentity(u),i=null,a=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?ty(e):void 0),o=a&&ey(a),s=ry({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,ht)=>{he=()=>ht(X.reason),X.addEventListener("abort",he,{once:!0}),le=setTimeout(()=>ht(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"?Co.parse(j):Ot.parse(j);return t.requestWithCredential("funnels",_,e.runToken,{headers:e.serverKey&&!P?{[Kg]: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,_=As(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 ml(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;ml(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:$g(_.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(gr(A)):null},get pendingCommands(){return[s.pending,s.closing].filter(A=>A!==null).map(A=>structuredClone(gr(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 Ss(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=Zg.parse(await c(Co.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 iy(e){if(!kt.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=bs({...e,scope:e.scope,apiKey:e.customerToken});return{async start(n){let r=await t.start(n),i=hr({...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 oy(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 ay(e,t,n){if(e.operationId!==t.operationId||t.currency!==void 0&&e.currency!==t.currency)throw new b("INVALID_RESPONSE",n)}function sy(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 cy(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 uy(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 ly(e,t){if(!kt.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=fr(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 Ss(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&&(!oy(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 ay(he.operation,{operationId:v.operationId,currency:n.commerce.currency},"The purchase operation changed"),d(),o?.operationId!==v.operationId?structuredClone(he.operation):(s=cy(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 uy({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=Xm(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(),sy(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 dy(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 Pv=O.trackUsage.request.shape.command,Cv=O.trackUsage.response;function _v(e){let t=Ne.parse(e.scope),n=Jh({...e,scope:t}),r={...e,scope:t,session:n.session},i=dy(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 iy({...r,customerToken:s()})},resumeFunnel(c){return s(),hr({...r,runToken:c})},paywall(c){return ly(r,{...c,customerToken:s()})},async trackUsage(c){if(s(),!e.usageReporter)throw new b("INVALID_REQUEST","Configure your authenticated backend usageReporter");let u=Pv.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=Cv.parse(m);if(f.scope.projectId!==t.projectId||f.scope.environment!==t.environment)throw new b("INVALID_RESPONSE","Usage response scope differs");return f}}}import{z as jv}from"zod";import{z as To}from"zod";var Ev=To.record(To.string().regex(/^[a-f0-9]{64}$/),To.strictObject({at:To.number(),text:To.string()})),Qr=2*1048576,Rv=100;function kv(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function py(e,t){let n=t===void 0?kv():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),Rv)})]);return typeof g=="string"&&g.length<=Qr&&new TextEncoder().encode(g).byteLength<=Qr?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 Ev.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>Qr||new TextEncoder().encode(m).byteLength>Qr||(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>Qr)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>Qr||(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+_>Qr||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 Pe=(e,t)=>new b(e,t),yr=()=>performance.now(),my=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function Tv(e){let t=bu.parse(e.scope),n=new xn(e.origin??mr);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 Pe("INVALID_URL","Configuration requires a trusted HTTPS origin");let r=new Set([n.origin,...(e.assetOrigins??[]).map(Y=>{let J=new xn(Y);if(J.protocol!=="https:"||J.username||J.password||J.search||J.hash||J.pathname!=="/")throw Pe("INVALID_URL","Invalid configuration asset origin");return J.origin})]),i=e.fetch??globalThis.fetch.bind(globalThis),a=`/api/v1/configuration/${t.environmentId}`,o=`indiana:configuration:1:${n.origin}:${Pt(t)}`,s=py(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&&yr()<u&&Date.now()<l;function ht(){if(!Se())throw Pe("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Je(Y,J,de){if(!j.has(Y)){for(;j.size&&(j.size>=128||X+de>nn.maxCacheBytes);){let pe=j.entries().next().value;X-=pe[1].byteLength,j.delete(pe[0])}j.set(Y,{text:J,byteLength:de}),X+=de}}function Te(Y,J,de){return Zh(Y,J,{signal:de,error:pe=>Pe("INVALID_RESPONSE",pe==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function tt(Y){let J=new xn(Y,n);if(!r.has(J.origin)||J.username||J.password||J.hash||J.search)throw Pe("INVALID_URL","Configuration artifact origin is not trusted");return J.href}async function No(Y,J,de=!1){let pe=await i(tt(Y),{method:"GET",credentials:"omit",redirect:"error",cache:de?"default":"no-cache",signal:J,headers:{}});if(pe.status===429){let Xe=pe.headers.get("retry-after")??"";x=/^\d+$/.test(Xe)?Number(Xe)*1e3:Math.max(0,Date.parse(Xe)-Date.now())||15e3}if(!pe.ok&&pe.status!==304)throw Pe(`CONFIGURATION_HTTP_${pe.status}`,"Configuration synchronization failed");return pe}function Jr(Y,J,de){let pe=Date.parse(Y.headers.get("x-indiana-config-validated-at")??""),Xe=Date.parse(Y.headers.get("x-indiana-config-valid-until")??""),it=Date.parse(Y.headers.get("date")??""),$e=Y.headers.get("age"),on=$e!==null&&/^\d+(\.\d+)?$/.test($e)?Number($e)*1e3:NaN;if(![pe,Xe,it,on].every(Number.isFinite)||Xe<=pe||Xe-pe>nn.maxControlAgeMs||pe>it+1e3)throw Pe("INVALID_RESPONSE","Configuration freshness evidence is invalid");let qt=Math.min(Xe-pe,de.maxControlAgeSeconds*1e3,nn.maxControlAgeMs)-Math.max(on,it-pe,0)-(yr()-J);if(qt<=0)throw Pe("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return yr()+qt}function pt(){if(clearTimeout(y),clearTimeout(A),f||!v.size)return;Se()&&(A=setTimeout(()=>{Se()?pt():he()},Math.max(1,u-yr())),my(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))),my(y)}async function Qt(){if(f)throw Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(h)return h;let Y=g,J=new AbortController;R=J;let de=(async()=>{if(!le){le=!0;try{let Fo=await s.readManifest();if(Fo&&!c){let zn=Su.parse(JSON.parse(Fo));Pt(zn.scope)===Pt(t)&&(c=zn)}}catch{}}J.signal.throwIfAborted();let $e=c,on=yr(),Lt=await No(a,J.signal);Lt.status===304&&(!$e||!Lt.headers.has("x-indiana-config-validated-at")||!Lt.headers.has("x-indiana-config-valid-until")||!Lt.headers.has("age"))&&(Lt=await No(a,J.signal));let qt=Lt.status===304?$e:Su.parse(JSON.parse(await Te(Lt,nn.maxManifestBytes,J.signal))),{generation:Zr,...Wr}=qt,Ln=Lt.headers.get("etag");if(Pt(qt.scope)!==Pt(t)||Qf(Wr)!==Zr||Ln!==`"${Zr}"`&&Ln!==`W/"${Zr}"`)throw Pe("INVALID_RESPONSE","Configuration scope or content identity changed");if($e&&(qt.revision<$e.revision||qt.revision===$e.revision&&qt.generation!==$e.generation))throw Pe("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[Fo,zn]of Object.entries($e?.funnels??{})){let Sr=qt.funnels[Fo];if(Sr&&(Sr.controlRevision<zn.controlRevision||Sr.evaluationRevision<zn.evaluationRevision||Sr.controlRevision===zn.controlRevision&&Sr.state!==zn.state||Sr.evaluationRevision===zn.evaluationRevision&&Sr.evaluationMode!==zn.evaluationMode))throw Pe("INVALID_RESPONSE","Funnel control revision changed identity")}let xr=Jr(Lt,on,qt.policy);if(J.signal.throwIfAborted(),Y!==g)throw Pe("CONFIGURATION_DISPOSED","Configuration scope changed");return c=qt,u=xr,l=Date.now()+Math.max(0,xr-yr()),m=!1,d=0,x=0,s.writeManifest(Pt(qt)),he(),structuredClone(qt)})(),pe=setTimeout(()=>J.abort(Pe("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),nn.initializationMs),Xe=new Promise(($e,on)=>J.signal.addEventListener("abort",()=>on(J.signal.reason),{once:!0})),it=Promise.race([de,Xe]).catch($e=>{throw d++,($e instanceof jv.ZodError||$e instanceof SyntaxError||$e instanceof b&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes($e.code))&&(u=0,m=!0,he()),$e}).finally(()=>{clearTimeout(pe),h===it&&(h=void 0),pt()});return h=it,it}async function Ar(Y){let J=Y.sha256,de=Wr=>xs(Wr,Y);tt(Y.url);let pe=j.get(J);if(pe){if(pe.byteLength!==Y.byteLength)throw Pe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return j.delete(J),j.set(J,pe),pe.text}let Xe=_.get(J);if(Xe){if(Xe.byteLength!==Y.byteLength)throw Pe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return Xe.promise}let it=new AbortController;P.add(it);let $e=g,on=(async()=>{try{let xr=await s.readArtifact(J);if(xr&&de(xr)){if(it.signal.throwIfAborted(),f||$e!==g)throw Pe("CONFIGURATION_DISPOSED","Configuration scope changed");return Je(J,xr,Y.byteLength),xr}}catch{}it.signal.throwIfAborted();let Wr=await No(Y.url,it.signal,!0),Ln=await Te(Wr,Y.byteLength,it.signal);if(!de(Ln))throw Pe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(f||$e!==g)throw Pe("CONFIGURATION_DISPOSED","Configuration scope changed");return Je(J,Ln,Y.byteLength),s.writeArtifact(J,Ln),Ln})(),Lt=setTimeout(()=>it.abort(Pe("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),nn.initializationMs),qt=new Promise((Wr,Ln)=>it.signal.addEventListener("abort",()=>Ln(it.signal.reason),{once:!0})),Zr=Promise.race([on,qt]).finally(()=>{clearTimeout(Lt),P.delete(it),_.delete(J)});return _.set(J,{promise:Zr,byteLength:Y.byteLength}),Zr}async function br(){return Se()||await Qt(),ht(),c}async function Fi(Y){let J,de=new Promise((pe,Xe)=>{J=setTimeout(()=>Xe(Pe("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),nn.initializationMs)});try{return await Promise.race([Y(),de])}finally{clearTimeout(J)}}function Mi(Y,J){if(ht(),c?.generation!==Y.generation)throw Pe("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(J&&c.funnels[J]?.state!=="active")throw Pe("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function gl(Y){let J=Y.gb.features;if(!J)throw Pe("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let de=Y.artifacts[J];if(de.formatVersion!==1)throw Pe("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let pe=Gc.parse(JSON.parse(await Ar(de)));if(Pt(pe.scope)!==Pt({projectId:t.projectId,environment:t.environment})||pe.generation!==de.generation||pe.remoteFeatures.some(Xe=>Object.hasOwn(pe.features,Xe)))throw Pe("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return Mi(Y),{...pe,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,u-yr())).toISOString()}}async function hl(Y,J){let de=await br(),pe=de.funnels[Y];J&&(!pe||pe.evaluationMode==="local"&&!pe.versions[J])&&(h&&await h,de=await Qt()),Mi(de,Y);let Xe=de.funnels[Y];if(Xe.evaluationMode!=="local")throw Pe("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let it=J??Xe.currentVersionId,$e=Xe.versions[it];if(!$e)throw Pe("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(de.artifacts[$e.artifact].formatVersion!==3)throw Pe("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[on,Lt]=await Promise.all([Ar(de.artifacts[$e.artifact]).then(qt=>Zf(JSON.parse(qt))),Xe.evaluationMode==="local"?gl(de):void 0]);if(Lt&&Pt(Jf(on,Lt))!==Pt($e.dependencies))throw Pe("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return Mi(de,Y),{document:on,growth:Lt,versionId:it,control:structuredClone(Xe),manifest:structuredClone(de)}}async function yl(Y,J){try{return await hl(Y,J)}catch(de){if(!(de instanceof b)||!(de.code==="CONFIGURATION_CHANGED"||de.code==="CONFIGURATION_HTTP_404"&&Se()))throw de;let pe=c?.generation;if(h&&await h,await Qt(),de.code!=="CONFIGURATION_CHANGED"&&c?.generation===pe)throw de;return hl(Y,J)}}function vs(){m=!0,he(),Qt().catch(ke)}let Do=()=>{(typeof document>"u"||document.visibilityState==="visible")&&vs()};function fy(Y){if(f)throw Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return v.add(Y),v.size===1&&(typeof window<"u"&&(window.addEventListener("online",vs),window.addEventListener("focus",Do),document.addEventListener("visibilitychange",Do)),pt()),()=>{v.delete(Y),v.size||(clearTimeout(y),clearTimeout(A),Al())}}function Al(){typeof window<"u"&&(window.removeEventListener("online",vs),window.removeEventListener("focus",Do),document.removeEventListener("visibilitychange",Do))}return{scope:Object.freeze({...t}),refresh:Qt,subscribe:fy,assertFresh:ht,assertFeatures(Y){ht();let J=c.gb.features;if(!J)throw Pe("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(Y!==void 0&&c.artifacts[J].generation!==Y)throw Pe("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-yr()):0},async features(){return Fi(async()=>gl(await br()))},pageExperiments:()=>Fi(async()=>{let Y=await br(),J=Y.gb.pageExperiments;if(!J)throw Pe("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let de=Y.artifacts[J];if(de.formatVersion!==1)throw Pe("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let pe=ih.parse(JSON.parse(await Ar(de)));if(pe.environmentId!==t.environmentId||pe.generation!==de.generation)throw Pe("INVALID_RESPONSE","Page experiment scope or generation changed");return Mi(Y),pe}),funnel:(Y,J)=>Fi(()=>yl(Y,J)),paywall:(Y,J)=>Fi(async()=>{let de=await br(),pe=de.paywalls?.[Y];if(!pe||!J&&pe.state!=="published")throw Pe("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let Xe=J??pe.currentVersionId,it=pe.versions[Xe],$e=it&&de.artifacts[it.artifact];if(!$e||$e.kind!=="paywall"||$e.formatVersion!==1)throw Pe("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let on=is.parse(JSON.parse(await Ar($e)));return Mi(de),{document:on,versionId:Xe,version:it.version,control:structuredClone(pe),manifest:structuredClone(de)}}),async localFunnel(Y,J){let de=await Fi(()=>yl(Y,J));if(!de.growth)throw Pe("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:pe,remoteFeatures:Xe,...it}=de.growth;return nh({scope:{projectId:t.projectId,environment:t.environment},funnelId:Y,versionId:de.versionId,evaluationMode:"local",evaluationRevision:de.control.evaluationRevision,document:de.document,payload:it})},assertFunnel(Y,J,de){ht();let pe=c.funnels[Y];if(!pe||pe.state!=="active")throw Pe("FUNNEL_STOPPED","Funnel is paused or unavailable");if(pe.evaluationMode!=="local")throw Pe("EVALUATION_MODE","This Funnel now executes at Longplay");if(J!==void 0&&pe.controlRevision!==J)throw Pe("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(de!==void 0&&!pe.versions[de])throw Pe("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!f){f=!0,g++,u=0,R?.abort(Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(y),clearTimeout(A),Al(),he(),v.clear();for(let Y of P)Y.abort(Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));j.clear(),X=0}}}}async function Nv(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&&Pt(n)!==Pt(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=Di.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=bs({...e,scope:n,apiKey:e.credential}),o=s=>{let c=hr({...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 fl(e,...t){try{Promise.resolve(e?.(...t)).catch(()=>{})}catch{}}function Dv(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=Bu.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)fl(j,d.run);d.run.instruction?.type==="authentication_required"&&fl(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=hr({...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()}}}export{b as LongplayError,Tv as createConfigurationSync,dl as createFeatureClient,Dv as createFunnelProcess,Nv as createLocalFunnelClient,_v as createLongplayReactNative};
|
|
17
|
+
*/var ve=N.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"})}),Pt=N.record(N.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"})}),gb=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"]),nn=Pt.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.strictObject({id:N.uuid(),attributeKey:N.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("$")&&!gb.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)}),yb=N.discriminatedUnion("type",[N.strictObject({type:N.literal("condition"),condition:nn}),N.strictObject({type:N.literal("list"),attributeKey:N.string().min(1).max(128),values:N.array(N.union([N.string(),N.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 Yn(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 Ab=N.record(N.uuid(),yb).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"&&Yn(o.condition).forEach(i),n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),jc=N.tuple([N.number().min(0).max(1),N.number().min(0).max(1)]).refine(([e,t])=>e<=t),Op=N.strictObject({attribute:N.string().optional(),seed:N.string().min(1),hashVersion:N.literal(2),ranges:N.array(jc).min(1).max(100)}),bb=N.strictObject({id:N.string().min(1).max(128),condition:nn,gate:N.boolean().optional()}),kc={id:N.string().max(128).optional(),condition:nn.optional(),parentConditions:N.array(bb).max(50).optional(),filters:N.array(Op).max(20).optional()},xb=N.union([N.strictObject({...kc}),N.strictObject({...kc,force:ve,coverage:N.number().min(0).max(1).optional(),range:jc.optional(),seed:N.string().min(1).optional(),hashAttribute:N.string().optional(),hashVersion:N.literal(2).optional()}),N.strictObject({...kc,type:N.literal("experiment-ref"),experimentId:N.uuid(),values:N.record(N.string().min(1),ve),meta:N.record(N.string().min(1),N.strictObject({passthrough:N.boolean()})).optional()})]),Sb=N.strictObject({defaultValue:ve,rules:N.array(xb).max(100)}),ZP=N.record(N.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Sb).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)}),Ib=N.strictObject({name:N.string().max(80),reason:N.string().max(500),dateStarted:N.iso.datetime({offset:!0}),dateEnded:N.iso.datetime({offset:!0}).nullable(),coverage:N.number().min(0).max(1),variationWeights:N.array(N.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:nn,savedGroups:N.array(N.strictObject({match:N.enum(["any","all","none"]),ids:N.array(N.uuid()).min(1)})).max(50),namespace:N.strictObject({id:N.uuid(),ranges:N.array(jc).min(1)}).nullable(),seed:N.string().min(1).max(128)}),vb=N.strictObject({key:N.string().min(1).max(128),name:N.string().min(1).max(80),hypothesis:N.string().max(2e3),status:N.enum(["draft","running","stopped"]),hashAttribute:N.string().min(1).max(128),fallbackAttribute:N.string().max(128).nullable(),hashVersion:N.literal(2),disableStickyBucketing:N.boolean(),bucketVersion:N.number().int().min(0).max(1e3),minBucketVersion:N.number().int().min(0).max(1e3),variations:N.array(N.strictObject({id:N.string().min(1),key:N.string().min(1),name:N.string().max(80),description:N.string().max(500)})).min(2).max(20),phases:N.array(Ib).min(1).max(100),releasedVariationId:N.string().nullable(),excludeFromPayload:N.boolean(),statusSchedule:N.strictObject({startAt:N.iso.datetime({offset:!0}).nullable(),stopAt:N.iso.datetime({offset:!0}).nullable(),stopAfter:N.strictObject({value:N.number().int().positive().max(36500),unit:N.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 wb=vb.safeExtend({filters:N.array(Op).optional()}),Ob=N.strictObject({experiments:N.record(N.uuid(),wb),savedGroups:Ab}),uo=N.strictObject({attributeName:N.string(),attributeValue:N.string(),assignments:N.record(N.string(),N.string())}),WP=N.strictObject({snapshot:Ob,attributes:Pt,results:Pt,stickyBucketAssignmentDocs:N.record(N.string(),uo)}),YP=N.strictObject({variantKey:N.string().nullable(),bucketVersion:N.number().int().min(0),source:N.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:N.number().min(0).max(1).optional(),stickyBucketUsed:N.boolean().optional(),hashUsed:N.boolean().optional()});function lr(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 Pb=qt.enum(["active","inactive"]),Cb=qt.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},Pt),_b=qt.strictObject({id:qt.string().trim().min(1).max(255),name:qt.string().trim().min(1).max(255),status:Pb,metadata:Cb}),iC=_b.extend({internal_id:qt.uuid(),project_id:qt.uuid(),environment_id:qt.uuid(),created_at:qt.iso.datetime({offset:!0}),updated_at:qt.iso.datetime({offset:!0})}),Cp=qt.union([qt.strictObject({id:qt.string().trim().min(1).max(255)}),qt.strictObject({internalId:qt.uuid()})]),oC=qt.enum(["customer","merchandise","context"]),aC=qt.enum(["system","stored","request"]),sC=qt.enum(["customer","merchandise","mixed"]),Pp=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function Tc(e,t={},n=new Set){if(lr(e).some(Pp))return!0;for(let r of Yn(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&Pp(i.attributeKey)||i?.type==="condition"&&Tc(i.condition,t,n))return!0}return!1}import{z as Eb}from"zod";var Rb=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,Cn=Eb.string().max(16).regex(Rb,"\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 hC=te.enum(["draft","active","paused","archived"]),dr=te.discriminatedUnion("type",[te.object({type:te.literal("percent"),percentOff:te.number().min(1).max(100).multipleOf(.01)}).strict(),te.object({type:te.literal("amount"),amountOffCents:te.number().int().min(1).max(1e8),currency:Ie}).strict()]),dn=te.discriminatedUnion("type",[te.object({type:te.literal("once")}).strict(),te.object({type:te.literal("repeating"),months:te.number().int().min(1).max(36)}).strict(),te.object({type:te.literal("forever")}).strict()]),_p=[te.object({type:te.literal("all")}).strict(),te.object({type:te.literal("plans"),planIds:te.array(te.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],kb=te.discriminatedUnion("type",[..._p,te.strictObject({type:te.literal("merchandise"),scope:te.discriminatedUnion("type",[te.strictObject({type:te.literal("all")}),te.strictObject({type:te.literal("selected"),merchandiseIds:te.array(te.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),te.strictObject({type:te.literal("condition"),condition:nn})])})]),Nc=te.discriminatedUnion("type",[..._p,te.strictObject({type:te.literal("merchandise"),scope:te.strictObject({type:te.enum(["all","selected","condition"])})})]),jb=te.strictObject({firstPurchaseOnly:te.boolean(),condition:nn}),gC=te.object({name:te.string().trim().min(1).max(80),description:te.string().max(500),discount:dr,duration:dn,appliesTo:kb,eligibility:jb,selfClaimEnabled:te.boolean().default(!1),startsAt:te.iso.datetime().nullable(),endsAt:te.iso.datetime().nullable(),totalLimit:te.number().int().min(1).max(1e6).nullable(),perCustomerLimit:te.number().int().min(1).max(10),grantWindowHours:te.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=>!Tc(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"]}),yC=te.object({code:te.string().trim().transform(e=>e.toUpperCase()).pipe(te.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:te.number().int().min(1).max(1e6).nullable(),expiresAt:te.iso.datetime().nullable(),firstPurchaseOnly:te.boolean(),minimumAmountCents:te.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 lo=te.object({id:te.uuid(),couponId:te.uuid(),status:te.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:te.iso.datetime(),expiresAt:te.iso.datetime(),coupon:te.object({name:te.string(),discount:dr,duration:dn,appliesTo:Nc}).strict()}).strict(),Ep=te.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var Np=S.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),Dc=S.string().regex(/^(0|[1-9]\d{0,14})$/),bi=S.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),Tb=S.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),po=Tb,Xn=de.refine(e=>/[1-9]/.test(e)),Qt=S.iso.datetime({offset:!0}),Ra=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"))},Nb=S.array(S.object({upTo:Xn.nullable(),unitAmountMinor:Np,flatAmountMinor:S.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&&Ra(t.upTo)>Ra(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),Db=S.discriminatedUnion("kind",[S.object({kind:S.literal("flat"),units:Xn,unitAmountMinor:Np}).strict(),S.object({kind:S.enum(["graduated","volume"]),units:Xn,tiers:Nb}).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"),Fb=S.strictObject({interval:S.enum(["month","year"]),count:S.number().int().min(1).max(12),anchor:S.enum(["membership","calendar"])}),mo=S.object({currency:Ie,pricing:Db,billingCycle:Fb.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var Rp={requestId:S.uuid(),productVersionId:S.uuid(),internal_feature_id:S.uuid(),currency:Ie},Dp=S.strictObject({interval:S.enum(["hour","day","week","month"]),intervalCount:S.number().int().min(1).max(12),limit:S.number().int().min(1).max(1e6)}),Fp=S.discriminatedUnion("kind",[S.object({...Rp,kind:S.literal("auto_topup"),threshold:la,quantity:Xn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Dp.optional()}).strict(),S.object({...Rp,kind:S.literal("postpaid"),maxAmountMinorPerPeriod:po,maxOutstandingMinor:po}).strict()]),kp={productVersionId:S.uuid(),internal_feature_id:S.uuid(),currency:Ie},Mp=S.discriminatedUnion("kind",[S.object({...kp,kind:S.literal("auto_topup"),threshold:la,quantity:Xn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Dp.optional(),purchaseAmountMinor:po,purchaseUnits:Xn}).strict(),S.object({...kp,kind:S.literal("postpaid"),maxAmountMinorPerPeriod:po,maxOutstandingMinor:po,cashPrice:mo}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),ka=S.object({id:S.uuid(),terms:Mp,status:S.enum(["prepared","active","revoked","blocked"]),createdAt:Qt,acceptedAt:Qt.nullable(),effectiveAt:Qt.nullable(),revokedAt:Qt.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"),qp=S.object({authorizationId:S.uuid(),terms:Mp,setupUrl:S.url().nullable()}).strict(),Up=S.object({authorizationId:S.uuid(),accepted:S.literal(!0)}).strict(),Bp=S.object({authorizationId:S.uuid(),requestId:S.uuid()}).strict(),Vp=S.object({internal_feature_id:S.uuid(),entityId:S.uuid().nullable(),interval:S.enum(["day","week","month","year"]),anchor:S.enum(["billing_cycle","utc"]).optional(),basis:S.enum(["usage","credits"]),filter:Ot.optional(),limit:de.nullable(),thresholds:S.array(S.number().positive().max(1)).max(8),includedThresholds:S.array(S.number().positive().max(1)).max(8).optional(),absoluteThresholds:S.array(Xn).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&&Ra(t)>Ra(i)}),"Notification thresholds must increase"),Mb=Vp.safeExtend({requestId:S.uuid()}),jp={control:S.literal("overage"),requestId:S.uuid(),internal_feature_id:S.uuid(),entityId:S.uuid().nullable()},qb=S.discriminatedUnion("action",[S.strictObject({...jp,action:S.literal("set"),allowed:S.boolean().nullable(),overageLimit:de.nullable(),skipOverageBilling:S.boolean()}),S.strictObject({...jp,action:S.literal("remove")})]),Lp=S.union([Mb,qb]),Ub=S.strictObject({internal_feature_id:S.uuid(),entityId:S.uuid().nullable(),allowed:S.boolean().nullable(),overageLimit:de.nullable(),skipOverageBilling:S.boolean(),interval:S.enum(["day","week","month","year"]),startsAt:Qt,endsAt:Qt,used:S.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:S.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:S.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),Bb=S.object({internal_feature_id:S.uuid(),entityId:S.uuid().nullable(),interval:S.enum(["day","week","month","year"]),anchor:S.enum(["billing_cycle","utc"]).optional(),basis:S.enum(["usage","credits"]),filter:Ot.optional(),startsAt:Qt,endsAt:Qt,used:tn,reserved:tn,limit:de.nullable(),thresholds:S.array(S.number().positive().max(1)).max(8),notifiedThresholds:S.array(S.number().positive().max(1)).max(1024),includedThresholds:S.array(S.number().positive().max(1)).max(8).optional(),includedAllowance:S.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:S.array(S.number().positive().max(1)).max(1024).optional(),absoluteThresholds:S.array(Xn).max(8).optional(),notifiedAbsoluteThresholds:S.array(Xn).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||de.safeParse(e.used).success&&de.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),Vb=S.object({authorizationId:S.uuid(),status:S.enum(["idle","pending","blocked"]),taskId:S.uuid().nullable(),invoiceId:S.uuid().nullable(),hostedInvoiceUrl:S.url().nullable(),purchaseCount:S.number().int().nonnegative(),purchaseWindowEndsAt:Qt.nullable(),attemptCount:S.number().int().nonnegative(),failedAttemptCount:S.number().int().nonnegative(),suspendedAt:Qt.nullable(),nextAttemptAt:Qt.nullable(),failureReason:S.string().min(1).max(240).nullable()}).strict(),zp=S.object({internal_feature_id:S.uuid().optional(),entityId:S.uuid().optional()}).strict(),Fc=S.object({authorizations:S.array(ka).max(100),limits:S.array(Vp).max(100),overages:S.array(Ub).max(100).optional(),windows:S.array(Bb).max(200),autoTopups:S.array(Vb).max(100),limited:S.boolean()}).strict(),Lb=S.object({id:S.uuid(),internal_feature_id:S.uuid(),productVersionId:S.uuid(),authorizationId:S.uuid(),entityId:S.uuid().nullable(),units:de,amountMinor:bi,cashPrice:mo}).strict(),fo=S.object({id:S.uuid(),sourceKind:S.enum(["product","usage","manual"]),providerInvoiceId:S.string().min(1).max(240).nullable(),status:S.enum(["accruing","open","pending","paid","failed","void"]),currency:Ie,startsAt:Qt.nullable(),endsAt:Qt.nullable(),amountMinor:S.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:S.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:Dc,paidAmountMinor:Dc,refundedAmountMinor:Dc,createdAt:Qt,hostedInvoiceUrl:S.url().nullable(),adjustment:S.object({originalInvoiceId:S.uuid(),amountMinor:S.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:Qt.nullable(),reason:S.string().min(1).max(500).optional()}).strict().nullable(),lines:S.array(Lb).max(100),linesLimited:S.boolean()}).strict(),$p=S.object({invoiceId:S.uuid(),accepted:S.literal(!0)}).strict(),Gp=S.strictObject({requestId:S.uuid(),originalInvoiceId:S.uuid(),amountMinor:S.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.string().trim().min(1).max(500)}),Kp=S.object({after:S.uuid().nullable(),limit:S.number().int().min(1).max(100)}).strict(),Hp=S.object({rows:S.array(fo).max(100),nextCursor:S.uuid().nullable()}).strict(),Tp=S.strictObject({id:S.string(),coupon:S.string(),start:S.number().nonnegative(),end:S.number().nullable()}),zb=S.strictObject({subscriptionId:S.string(),customerId:S.string(),accountId:S.string(),sourceItems:S.array(S.strictObject({id:S.string(),price_id:S.string(),quantity:S.number().int(),discounts:S.array(Tp).optional()})).max(100),items:S.array(S.strictObject({id:S.string(),price:S.string(),quantity:S.number().int(),discounts:S.array(S.strictObject({coupon:S.string().optional(),terms:S.strictObject({id:S.string(),name:S.string().optional(),percent_off:S.number().optional(),amount_off:S.number().optional(),currency:S.string().optional(),duration:S.enum(["once","forever","repeating"]),duration_in_months:S.number().optional()}).optional(),discount:S.string().optional(),receipt:Tp.optional()})).max(20)})).max(100)}),Qp=S.strictObject({membershipId:S.uuid(),requestId:S.uuid(),grantIds:S.array(S.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),Jp=S.strictObject({membershipId:S.uuid(),operationId:S.uuid(),status:S.enum(["pending","effective"]),execution:zb.nullable(),grants:S.array(S.strictObject({id:S.uuid(),couponId:S.uuid(),name:S.string(),discount:dr,duration:dn,startedAt:Qt.nullable()})).max(20)});import{z as ho}from"zod";var Zp=ho.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),Wp=ho.number().int().min(1).max(1e3),ja=ho.object({cap:de.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:ho.number().positive().max(1e4).nullable(),cycles:ho.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");import{z as pr}from"zod";var Yp=pr.strictObject({itemKey:pr.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:pr.uuid(),includedAmount:pr.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:pr.number().int().min(0).max(1e4),terms:Ia,pricing:ao.optional(),unitAmountMinor:pr.number().int().min(0).max(1e8),productId:pr.string().min(1).max(255).nullable(),priceId:pr.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{Xd(e.includedAmount,e.terms.units,e.quantity),Sa({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"})}});import{z as ne}from"zod";var Mr=de.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),go=ne.string().min(1).max(120),Ta=ne.enum(["cap","overflow"]),pn=(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"))},yo=e=>{try{return e()}catch{return!1}},Ao=ne.discriminatedUnion("operation",[ne.object({operation:ne.literal("quote"),overageBehavior:Ta.optional(),internal_feature_id:ne.uuid(),entityId:ne.uuid().optional(),quantity:Mr,properties:Ot}).strict(),ne.object({operation:ne.literal("consume"),overageBehavior:Ta.optional(),occurredAt:ne.iso.datetime({offset:!0}).optional(),internal_feature_id:ne.uuid(),entityId:ne.uuid().optional(),quantity:de,properties:Ot,idempotencyKey:go}).strict(),ne.object({operation:ne.literal("reserve"),occurredAt:ne.iso.datetime({offset:!0}).optional(),internal_feature_id:ne.uuid(),entityId:ne.uuid().optional(),quantity:Mr,properties:Ot,idempotencyKey:go,expiresInSeconds:ne.number().int().min(1).max(86400)}).strict(),ne.object({operation:ne.literal("confirm"),operationId:ne.uuid(),quantity:Mr,properties:Ot.optional(),idempotencyKey:go}).strict(),ne.object({operation:ne.literal("refund"),operationId:ne.uuid(),quantity:Mr,idempotencyKey:go}).strict(),ne.object({operation:ne.literal("release"),operationId:ne.uuid(),idempotencyKey:go}).strict()]),Mc=ne.object({internal_credit_feature_id:ne.uuid().nullable(),internal_metered_feature_id:ne.uuid(),dimension:ne.string().min(1).max(64),counterKey:ne.string().min(1).max(240),cycleStart:ne.iso.datetime({offset:!0}),unitCost:de,units:Mr,amount:tn,tier:ne.number().int().min(1).max(12).nullable()}).strict(),qr=ne.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function Xp(e,t){let n=e.reduce((r,i)=>r+pn(i.units,12),0n)-pn(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var em=ne.discriminatedUnion("funding",[ne.strictObject({funding:ne.literal("balance"),sourceId:ne.uuid(),rolloverId:ne.uuid().nullable(),units:qr.refine(e=>/[1-9]/.test(e)),amount:tn}),ne.strictObject({funding:ne.literal("unbilled"),units:qr.refine(e=>/[1-9]/.test(e))}),ne.object({funding:ne.literal("prepaid"),sourceId:ne.uuid(),units:Mr,amount:tn,pricing:ne.array(Mc).min(1).max(12)}).strict().refine(e=>yo(()=>e.pricing.reduce((t,n)=>t+pn(n.units,6),0n)===pn(e.units,6)&&e.pricing.reduce((t,n)=>t+pn(n.amount,12),0n)===pn(e.amount,12)&&e.pricing.every(t=>pn(t.unitCost,6)*pn(t.units,6)===pn(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),ne.object({funding:ne.literal("postpaid"),invoiceLineId:ne.uuid().nullable(),units:Mr,authorizationId:ne.uuid()}).strict()]),Na=ne.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),tm=ne.object({allowed:ne.boolean(),internal_feature_id:ne.uuid(),quantity:de,requestedQuantity:de.optional(),overageBehavior:Ta.optional(),reason:Na.nullable(),allocations:ne.array(em).max(500)}).strict().refine(e=>yo(()=>e.allowed?e.reason===null&&Xp(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>yo(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&pn(e.requestedQuantity,6)>=pn(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),bo=ne.object({id:ne.uuid(),internal_feature_id:ne.uuid(),kind:ne.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:ne.uuid().nullable(),quantity:de,requestedQuantity:de.optional(),overageBehavior:Ta.optional(),accepted:ne.boolean(),reason:ne.enum([...Na.options,"expired"]).nullable(),createdAt:ne.iso.datetime({offset:!0}),reservationStatus:ne.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:ne.iso.datetime({offset:!0}).nullable(),allocations:ne.array(em).max(500)}).strict().refine(e=>yo(()=>e.accepted?e.reason===null&&Xp(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>yo(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&pn(e.requestedQuantity,6)>=pn(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");import{z as Fe}from"zod";var Ur=Fe.iso.datetime({offset:!0}),nm=de.refine(e=>/[1-9]/.test(e)),rm=Fe.strictObject({interval:Zp.exclude(["lifetime"]),count:Wp}),$b=Fe.strictObject({action:Fe.literal("create"),requestId:Fe.uuid(),internal_feature_id:Fe.uuid(),entityId:Fe.uuid().nullable(),amount:nm.nullable(),expiresAt:Ur.nullable(),reset:rm.nullable(),rollover:ja.nullable(),nextResetAt:Ur.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"),im=Fe.discriminatedUnion("action",[$b,Fe.strictObject({action:Fe.literal("update"),requestId:Fe.uuid(),grantId:Fe.uuid(),revision:Fe.number().int().nonnegative(),amount:nm.nullable(),expiresAt:Ur.nullable(),rollover:ja.nullable(),nextResetAt:Ur.nullable()}),Fe.strictObject({action:Fe.enum(["add","subtract","set_remaining"]),requestId:Fe.uuid(),grantId:Fe.uuid(),revision:Fe.number().int().nonnegative(),amount:de}),Fe.strictObject({action:Fe.literal("revoke"),requestId:Fe.uuid(),grantId:Fe.uuid(),revision:Fe.number().int().nonnegative()})]),qc=Fe.strictObject({id:Fe.uuid(),internal_feature_id:Fe.uuid(),entityId:Fe.uuid().nullable(),amount:de.nullable(),reset:rm.nullable(),rollover:ja.nullable(),nextResetAt:Ur.nullable(),startsAt:Ur,expiresAt:Ur.nullable(),revision:Fe.number().int().nonnegative(),revoked:Fe.boolean(),available:tn,held:tn,spent:tn}),om=Fe.strictObject({customerId:Fe.uuid(),after:Fe.uuid().nullable(),limit:Fe.number().int().min(1).max(100)}),am=Fe.strictObject({rows:Fe.array(qc).max(100),nextCursor:Fe.uuid().nullable()});import{z as ie}from"zod";var Bn=ie.iso.datetime({offset:!0}),sm=ie.strictObject({invoiceId:ie.uuid(),after:ie.string().min(1).max(180).nullable(),limit:ie.number().int().min(1).max(100)}),Gb=ie.strictObject({kind:ie.literal("product"),key:ie.string(),productVersionId:ie.uuid(),productName:ie.string(),itemKey:ie.string(),entityId:ie.uuid().nullable(),quantity:ie.number().positive(),subtotalMinor:ie.string().regex(/^-?\d+$/),discountMinor:ie.string().regex(/^\d+$/),taxMinor:ie.string().regex(/^-?\d+$/).nullable(),totalMinor:ie.string().regex(/^-?\d+$/),startsAt:Bn.nullable(),endsAt:Bn.nullable(),providerLineId:ie.string().nullable(),providerItemId:ie.string()}),cm=ie.strictObject({invoice:fo,items:ie.array(ie.discriminatedUnion("kind",[Gb,ie.strictObject({kind:ie.literal("invoice_credit"),key:ie.string(),internal_feature_id:ie.uuid(),internal_credit_feature_id:ie.uuid(),name:ie.string(),units:de,reserved:de,amountMinor:bi,grossAmountMinor:bi,creditsAppliedMinor:bi,properties:Ot,cashPrice:mo,providerItemId:ie.string().nullable(),creditProviderItemId:ie.string().nullable()}),ie.strictObject({kind:ie.literal("usage"),key:ie.string(),internal_feature_id:ie.uuid(),name:ie.string(),units:de,reserved:de,amountMinor:bi,cashPrice:mo})])).max(100),nextCursor:ie.string().min(1).max(180).nullable()}),Kb=ie.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),Uc=ie.strictObject({from:Bn,to:Bn,entityId:ie.uuid().optional(),snapshotAt:Bn.nullable(),after:ie.strictObject({at:Bn,id:ie.uuid(),position:ie.number().int().nonnegative()}).nullable(),limit:ie.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"),um=ie.strictObject({customerId:ie.uuid(),entityId:ie.uuid().nullable(),from:Bn,to:Bn,snapshotAt:Bn,totals:ie.array(ie.strictObject({internal_credit_feature_id:ie.uuid(),name:ie.string(),consumed:tn,refunded:tn,net:Kb})).max(1e3),rows:ie.array(ie.strictObject({operationId:ie.uuid(),position:ie.number().int().nonnegative(),kind:ie.enum(["consume","confirm","refund"]),originalId:ie.uuid().nullable(),occurredAt:Bn,internal_feature_id:ie.uuid(),entitlementName:ie.string(),sourceId:ie.uuid(),internal_credit_feature_id:ie.uuid(),creditName:ie.string(),units:qr,amount:tn,pricing:ie.array(Mc).max(12),properties:Ot})).max(100),nextCursor:Uc.shape.after});import{z as D}from"zod";import{z as _n}from"zod";var Hb=_n.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),Qb=_n.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),Da=_n.strictObject({internal_feature_id:_n.uuid(),entityId:_n.uuid().nullable()}),lm=Da.extend({quantity:de,expectedRevision:_n.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:_n.string().min(1).max(120),properties:Ot.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),xo=Da.extend({operationId:_n.uuid().nullable(),usage:de,capacity:Hb.nullable(),remaining:Qb.nullable(),withinLimit:_n.boolean(),revision:_n.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:_n.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 Jt=D.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),En=D.iso.datetime({offset:!0}),Jb=D.enum(["access","metered","credit"]),So={internal_feature_id:D.uuid(),key:Tr,name:D.string().min(1).max(120),kind:Jb},dm=D.object({customerId:D.uuid(),snapshotAt:En,memberships:D.array(D.object({id:D.uuid(),productId:D.string().min(1).max(255),productVersionId:D.uuid(),billingProductVersionId:D.uuid(),version:D.number().int().positive(),key:D.string().min(1).max(64),name:D.string().min(1).max(120),groupId:D.string().max(255).nullable(),membershipType:D.enum(["main","addon"]),status:D.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:D.boolean(),accessEnabled:D.boolean(),renewalChange:D.object({productVersionId:D.uuid(),name:D.string().min(1).max(120),version:D.number().int().positive(),effectiveAt:En,benefitsAppliedAt:En.nullable(),timing:D.enum(["immediate","renewal"]),changeKind:D.enum(["plan","seats","quantity"]),feature:D.strictObject({internal_feature_id:D.uuid(),name:D.string().min(1).max(80),fromQuantity:D.number().int().min(0).max(1e4),toQuantity:D.number().int().min(0).max(1e4)}).optional(),seat:D.object({key:D.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:D.number().int().min(0).max(1e4),toQuantity:D.number().int().min(0).max(1e4)}).strict().nullable(),status:D.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.object({phase:D.enum(["paid","trial"]),startsAt:En,endsAt:En.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:D.boolean(),balances:D.array(D.object({...So,usageType:D.enum(["consumable","non_consumable"]).nullable(),accessible:D.boolean(),unlimited:D.boolean(),available:Jt,held:Jt,debt:Jt,nextExpiresAt:En.nullable(),usage:xo.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.boolean()}).strict(),pm=D.enum(["source","usage","transaction","invoice","debt","settlement"]),Fa=D.object({at:En,id:D.uuid(),type:pm}).strict(),mm=D.object({type:pm.nullable(),resourceKey:Tr.optional(),kind:D.enum(["purchase","refund"]).optional(),topup:D.boolean().optional(),from:D.iso.date().nullable(),to:D.iso.date().nullable(),after:Fa.nullable(),limit:D.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),xi={id:D.uuid(),occurredAt:En},Zb=D.discriminatedUnion("type",[D.strictObject({...xi,type:D.literal("invoice"),status:D.string().min(1).max(80),paid:Jt,refunded:Jt,currency:Ie,externalId:D.string().nullable()}),D.object({...xi,...So,type:D.literal("source"),reason:D.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:Jt,unlimited:D.boolean(),status:D.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:En,expiresAt:En.nullable(),orderId:D.uuid().nullable(),parentSourceId:D.uuid().nullable()}).strict(),D.object({...xi,type:D.literal("usage"),internal_feature_id:D.uuid(),name:D.string().min(1).max(120),kind:D.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:D.uuid().nullable(),quantity:de,accepted:D.boolean(),reason:D.enum([...Na.options,"expired"]).nullable(),properties:Ot,reservationStatus:D.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:En.nullable(),charges:D.array(D.discriminatedUnion("funding",[D.strictObject({funding:D.literal("balance"),sourceId:D.uuid(),rolloverId:D.uuid().nullable(),units:qr,amount:Jt}),D.strictObject({funding:D.literal("unbilled"),units:qr}),D.object({...So,funding:D.literal("prepaid"),amount:Jt}).strict(),D.object({funding:D.literal("postpaid"),invoiceId:D.uuid(),invoiceLineId:D.uuid(),authorizationId:D.uuid(),units:de,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.object({...xi,type:D.literal("transaction"),purpose:D.enum(["product","invoice"]),productVersionId:D.uuid().nullable(),productName:D.string().min(1).max(120).nullable(),productVersion:D.number().int().positive().nullable(),invoiceId:D.uuid().nullable(),orderId:D.uuid(),originalId:D.uuid().nullable(),kind:D.enum(["purchase","refund"]),amountMinor:D.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.object({...xi,...So,type:D.literal("debt"),sourceId:D.uuid(),transactionId:D.uuid(),amount:Jt}).strict(),D.object({...xi,...So,type:D.literal("settlement"),sourceId:D.uuid(),debtId:D.uuid(),kind:D.enum(["payment","usage_refund","payment_return"]),amount:Jt}).strict()]),fm=D.object({customerId:D.uuid(),rows:D.array(Zb).max(50),nextCursor:Fa.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");import{z as he}from"zod";var gm=he.object({customerId:he.uuid()}).strict(),ym=he.discriminatedUnion("action",[he.object({customerId:he.uuid(),requestId:he.uuid(),action:he.literal("assign"),poolId:he.uuid(),memberCustomerId:he.uuid()}).strict(),he.strictObject({customerId:he.uuid(),requestId:he.uuid(),action:he.literal("assign_entity"),poolId:he.uuid(),entityId:he.uuid()}),he.object({customerId:he.uuid(),requestId:he.uuid(),action:he.literal("release"),poolId:he.uuid(),slotId:he.uuid()}).strict()]),Io=he.number().int().nonnegative(),Bc=he.iso.datetime({offset:!0}),Vc=he.strictObject({internalId:he.uuid(),id:he.string(),name:he.string().nullable(),version:he.number().int().positive()}),hm=he.enum(["active","past_due"]),Lc=he.strictObject({customerId:he.uuid(),licenses:he.array(he.strictObject({id:he.uuid(),linkId:he.uuid(),parent:he.strictObject({customerProductId:he.uuid(),status:hm,product:Vc}),product:Vc,planLicense:he.strictObject({id:he.uuid(),prepaidOnly:he.boolean(),isCustom:he.boolean()}).nullable(),granted:Io,included:Io,paidQuantity:Io,usage:Io,remaining:Io,createdAt:Bc}).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:he.array(he.strictObject({id:he.uuid(),linkId:he.uuid(),status:hm,product:Vc,entity:he.strictObject({internalId:he.uuid(),id:he.string().nullable(),name:he.string().nullable()}).nullable(),beneficiary:he.strictObject({internalId:he.uuid(),id:he.string().nullable(),name:he.string().nullable()}).nullable(),startedAt:Bc.nullable(),endedAt:Bc.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:he.boolean()});import{z as fe}from"zod";var vo=fe.enum(["email","sms","voice","push"]),n_=fe.enum(["resend","twilio","fcm","apns"]);var r_=fe.string().regex(/^\+[1-9]\d{1,14}$/),Wb=fe.enum(["email_recipient","sms_segment","voice_second","push_device"]);var Yb=fe.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),Xb=fe.strictObject({subject:Yb,html:fe.string().min(1).max(131072).optional(),text:fe.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),ex=fe.strictObject({body:fe.string().min(1).max(1600).refine(e=>e.trim().length>0)}),tx=fe.strictObject({text:fe.string().trim().min(1).max(4e3),language:fe.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:fe.number().int().min(1).max(900)}),nx=fe.record(fe.string().min(1).max(64),fe.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"),rx=fe.strictObject({title:fe.string().trim().min(1).max(200),body:fe.string().trim().min(1).max(2e3),url:fe.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:nx.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),Am=fe.discriminatedUnion("channel",[fe.strictObject({channel:fe.literal("email"),content:Xb}),fe.strictObject({channel:fe.literal("sms"),content:ex}),fe.strictObject({channel:fe.literal("voice"),content:tx}),fe.strictObject({channel:fe.literal("push"),content:rx})]),bm=fe.strictObject({requestId:fe.uuid(),customerId:fe.uuid(),connectionId:fe.uuid().optional(),message:Am,expiresAt:fe.iso.datetime({offset:!0})}),ix=fe.array(fe.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),ox=fe.discriminatedUnion("kind",[fe.strictObject({kind:fe.literal("all")}),fe.strictObject({kind:fe.literal("customers"),customerIds:ix})]),i_=fe.strictObject({name:fe.string().trim().min(1).max(120),connectionId:fe.uuid().optional(),message:Am,audience:ox,frequencyLimit:fe.number().int().min(1).max(100)}),xm=fe.strictObject({requestId:fe.uuid(),channel:vo,state:fe.enum(["allowed","denied"]),expectedRevision:fe.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),Sm=fe.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Im=fe.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),o_=fe.strictObject({meter:Wb,estimatedUnits:fe.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:fe.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});import{z as Ce}from"zod";import{z as re}from"zod";import{z as Si}from"zod";var wo=Si.strictObject({internalFeatureId:Si.uuid(),name:Si.string().min(1).max(120),includedAmount:Si.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:Si.enum(["hour","day","week","month","year","lifetime"]),resetCount:Si.number().int().min(1).max(100),terms:Ia});var qa=re.object({plan:re.string().min(1).max(200).optional(),coupon:re.uuid().optional(),promotionCode:re.uuid().optional(),picker:re.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),Ma=re.object({text:re.string().optional(),label:re.string().optional(),alt:re.string().optional(),html:re.string().max(32768).optional(),price:re.object({current:re.string(),original:re.string().nullable(),period:re.string()}).optional(),code:re.string().optional(),countdownAt:re.iso.datetime().optional(),planId:re.string().min(1).max(200).optional(),planVersionId:re.string().min(1).max(200).optional(),currency:Ie.optional(),couponId:re.uuid().optional(),offerId:re.uuid().optional(),unavailable:re.boolean().optional(),unavailableReason:re.string().optional(),missing:re.array(re.string()).optional()}).strict(),Ii=re.object({paywall:sr.optional(),nodes:re.record(re.string(),re.object({base:Ma,picker:re.string().optional(),byPlan:re.record(re.string(),Ma).optional()}).strict()),plans:re.record(re.string(),re.object({id:re.string().min(1).max(200),versionId:re.string().min(1).max(200),available:re.boolean(),name:re.string(),price:re.string(),period:re.string(),currency:Ie.optional(),amountMinor:re.number().int().nonnegative().optional(),interval:re.enum(["free","week","month","year","one_time"]).optional(),intervalCount:re.number().int().positive().optional(),prepaid:re.array(wo).max(100).optional()}).strict()),pickers:re.record(re.string(),re.object({options:re.array(re.string().min(1).max(200)).max(20),selected:re.string().min(1).max(200).nullable()}).strict()),quantities:re.record(re.string(),re.strictObject({minimum:re.number().int().nonnegative(),maximum:re.number().int().nonnegative(),step:re.number().int().positive(),value:re.number().int().nonnegative(),label:re.string(),available:re.boolean()})).optional(),diagnostics:re.array(re.object({nodeId:re.string(),message:re.string()}).strict())}).strict();function vm(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}import{z as I}from"zod";function ax(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function wm(e){let t={};function n(r){var i;if(ax(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}import{z as er}from"zod";var Om=er.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ua=er.strictObject({tiers:er.array(er.strictObject({id:Om,name:er.string().trim().min(1).max(80)})).min(1).max(8),assignments:er.array(er.strictObject({productVersionId:er.string().min(1).max(200),tierId:Om,period:er.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 Ba(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}import{z as ce}from"zod";var sx=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],Pm=ce.enum(sx),Cm=ce.object({source:Pm,layout:ce.enum(["full","compact"]),resourceKey:Tr.optional(),pageSize:ce.number().int().min(1).max(50),showSources:ce.boolean(),allowPurchase:ce.boolean(),outputs:ce.object({billing_adjustment:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:ce.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"})}),Tt=ce.string().max(2e3),_m=ce.object({id:ce.string().max(100),label:Tt,detail:ce.array(Tt).max(12),value:Tt.optional(),status:Tt.optional(),facts:ce.array(ce.object({label:Tt,value:Tt}).strict()).max(1e3),purchaseId:ce.uuid().optional(),invoiceUrl:ce.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:ce.array(ce.strictObject({action:ce.literal("invoice_open"),label:Tt})).max(1).optional(),membershipActions:ce.array(ce.object({value:ce.string().max(100),label:Tt}).strict()).max(3).optional()}).strict(),cx=ce.object({key:Tr,name:Tt,spendable:Tt,reserved:Tt,available:Tt,expiry:Tt.nullable(),sources:ce.array(_m).max(50),sourceCount:ce.number().int().nonnegative(),sourcePage:ce.number().int().positive(),hasNextSources:ce.boolean(),hasPreviousSources:ce.boolean()}).strict(),ux=ce.object({source:Pm,status:ce.enum(["idle","loading","ready","error"]),stale:ce.boolean(),preview:ce.boolean(),errorCode:ce.string().max(80).optional(),errorMessage:Tt.optional(),resources:ce.array(cx).max(500),rows:ce.array(_m).max(50),hasNext:ce.boolean(),hasPrevious:ce.boolean(),page:ce.number().int().positive(),filter:ce.string().max(40),updatedAt:ce.iso.datetime().optional(),buyingId:ce.uuid().optional(),membershipBusy:ce.boolean().optional(),billingBusy:ce.boolean().optional(),membershipReview:ce.object({title:Tt,note:Tt,facts:ce.array(ce.object({label:Tt,value:Tt}).strict()).max(100)}).strict().optional(),membershipResult:Tt.optional()}).strict(),Em=ce.object({nodes:ce.record(ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ux)}).strict(),x_=ce.object({nodeId:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:ce.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.string().max(100).optional()}).strict();import{z as K}from"zod";var vt={state:32,enumValues:64,derived:96,bindings:256,controls:64,timers:4,effects:8,depth:12,expressionNodes:2e3},km=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]),Ut=K.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/).refine(e=>!km.has(e),"Reserved UI identifier"),zc=K.union([K.string().max(2e3),K.number().finite(),K.boolean(),K.null()]),lx=K.discriminatedUnion("type",[K.strictObject({type:K.literal("enum"),values:K.array(zc).min(1).max(vt.enumValues),default:zc}),K.strictObject({type:K.literal("number"),min:K.number().finite(),max:K.number().finite(),step:K.number().finite().positive(),default:K.number().finite()}),K.strictObject({type:K.literal("text"),maxLength:K.number().int().min(0).max(2e3),default:K.string().max(2e3).nullable()}),K.strictObject({type:K.literal("boolean"),default:K.boolean()})]);function Gc(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 dx=lx.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"}),Gc(e,e.default)||t.addIssue({code:"custom",path:["default"],message:"UI default must match its state definition"})}),px=["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 mx(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 Vr=K.lazy(()=>K.union([zc,K.strictObject({ref:Ut}),K.strictObject({op:K.enum(px),args:K.array(Vr).max(vt.expressionNodes)}).superRefine((e,t)=>{mx(e.op,e.args.length)||t.addIssue({code:"custom",path:["args"],message:"Invalid UI expression arity"})})]));function Rn(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function Br(e,t,n){if(!e||typeof e!="object")return!0;if(!Rn(e))return t.addIssue({code:"custom",path:n,message:"UI objects must be plain data"}),!1;for(let r of Object.keys(e)){if(km.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 vi(e,t,n,r){let i=[{value:e,depth:1,path:n}];for(;i.length;){let a=i.pop();if(++r.nodes>vt.expressionNodes||a.depth>vt.depth){t.addIssue({code:"custom",path:a.path,message:"UI expression budget exceeded"});return}if(!Br(a.value,t,a.path))return;if(Rn(a.value)&&Array.isArray(a.value.args)){if(a.value.args.length>vt.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 v_=K.unknown().superRefine((e,t)=>{vi(e,t,[],{nodes:0})}).pipe(Vr),$c=K.record(Ut,Vr).refine(e=>Object.keys(e).length>0&&Object.keys(e).length<=vt.state,"UI assignments need 1\u201332 state keys"),fx=K.strictObject({target:Ut,property:K.enum(["text","visible","disabled","checked","value","class","aria-label","aria-selected","aria-checked","aria-valuetext","tabindex"]),expression:Vr,className:Ut.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"})}),hx=K.discriminatedUnion("type",[K.strictObject({type:K.literal("scroll_latch"),target:Ut,state:Ut}),K.strictObject({type:K.literal("input"),target:Ut,state:Ut,set:$c.optional()}),K.strictObject({type:K.literal("action"),target:Ut,set:$c}),K.strictObject({type:K.literal("carousel"),target:Ut,state:Ut,initialIndex:K.number().int().nonnegative().optional(),maxWidth:K.number().int().min(1).max(1e4).optional(),previousTarget:Ut.optional(),nextTarget:Ut.optional(),inactiveTargets:K.array(Ut).max(20).optional(),inactiveMaxWidth:K.number().int().min(1).max(1e4).optional()})]),gx=K.strictObject({afterMs:K.number().int().min(0).max(6e4),set:$c}),yx=K.strictObject({type:K.literal("mosaic_waves"),target:Ut,color:K.string().regex(/^#[0-9a-fA-F]{6}$/),hotColor:K.string().regex(/^#[0-9a-fA-F]{6}$/),enabled:Vr.optional(),speed:K.number().min(0).max(4).optional(),pitch:K.number().min(.05).max(4).optional(),fill:K.number().min(.05).max(1).optional(),feather:K.number().min(0).max(1).optional(),warp:K.number().min(0).max(4).optional(),warpScale:K.number().min(0).max(32).optional(),detailScale:K.number().min(0).max(32).optional(),waveScale:K.number().min(0).max(32).optional(),falloff:K.number().min(.1).max(32).optional(),brightness:K.number().min(0).max(32).optional(),ambient:K.number().min(0).max(1).optional(),gamma:K.number().min(.05).max(8).optional(),vignette:K.number().min(0).max(1).optional(),opacity:K.number().min(0).max(1).optional()}),Ax=K.strictObject({type:K.literal("number_counter"),target:Ut,value:Vr,prefix:K.string().max(20).optional(),format:K.enum(["number","short"]).optional()}),bx=K.strictObject({state:K.record(Ut,dx).refine(e=>Object.keys(e).length<=vt.state,"Too many UI state keys").optional(),derived:K.record(Ut,Vr).refine(e=>Object.keys(e).length<=vt.derived,"Too many UI derived keys").optional(),bindings:K.array(fx).max(vt.bindings).optional(),controls:K.array(hx).max(vt.controls).optional(),timers:K.array(gx).max(vt.timers).optional(),effects:K.array(K.discriminatedUnion("type",[yx,Ax])).max(vt.effects).optional(),clock:K.boolean().optional()});function xx(e,t){if(!Br(e,t,[])||!Rn(e))return;for(let[r,i]of[["state",vt.state],["derived",vt.derived]]){let a=e[r];if(!Br(a,t,[r]))return;if(Rn(a)&&Object.keys(a).length>i){t.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}}for(let[r,i]of[["bindings",vt.bindings],["controls",vt.controls],["timers",vt.timers],["effects",vt.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(!Br(i,t,["effects",r]))return}if(Rn(e.state))for(let[r,i]of Object.entries(e.state)){if(!Br(i,t,["state",r]))return;if(Rn(i)&&Array.isArray(i.values)&&i.values.length>vt.enumValues){t.addIssue({code:"custom",path:["state",r,"values"],message:"Too many UI enum values"});return}}let n={nodes:0};if(Rn(e.derived))for(let[r,i]of Object.entries(e.derived))vi(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(!(!Br(o,t,[r,a])||!Rn(o))){if(r==="bindings")vi(o.expression,t,[r,a,"expression"],n);else if(Br(o.set,t,[r,a,"set"])&&Rn(o.set)){if(Object.keys(o.set).length>vt.state){t.addIssue({code:"custom",path:[r,a,"set"],message:"Too many UI assignments"});return}for(let[s,c]of Object.entries(o.set))vi(c,t,[r,a,"set",s],n)}if(n.nodes>vt.expressionNodes)return}}}if(Array.isArray(e.effects))for(let[r,i]of e.effects.entries())Rn(i)&&i.type==="number_counter"?vi(i.value,t,["effects",r,"value"],n):Rn(i)&&i.enabled!==void 0&&vi(i.enabled,t,["effects",r,"enabled"],n)}function Rm(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 jm=K.unknown().superRefine(xx).pipe(bx).superRefine((e,t)=>{let n=e.state??{},r=e.derived??{},i=new Set([...Object.keys(n),...Object.keys(r)]),a=(h,d)=>{for(let g of Rm(h))i.has(g)||t.addIssue({code:"custom",path:d,message:`Unknown UI reference: ${g}`})};for(let[h,d]of Object.entries(e.derived??{}))Object.hasOwn(n,h)&&t.addIssue({code:"custom",path:["derived",h],message:"UI state and derived identifiers must be distinct"}),a(d,["derived",h]);let o=new Set,s=new Set,c=h=>{if(o.has(h))return!1;if(s.has(h))return!0;o.add(h);for(let d of Rm(r[h]))if(Object.hasOwn(r,d)&&!c(d))return!1;return o.delete(h),s.add(h),!0};for(let h of Object.keys(r))if(!c(h)){t.addIssue({code:"custom",path:["derived",h],message:"Cyclic UI derived references"});break}for(let[h,d]of(e.bindings??[]).entries())a(d.expression,["bindings",h,"expression"]);let u=new Set;for(let[h,d]of(e.effects??[]).entries())u.has(d.target)&&t.addIssue({code:"custom",path:["effects",h,"target"],message:"Effect targets must be unique"}),u.add(d.target),d.type==="number_counter"?(a(d.value,["effects",h,"value"]),typeof d.value=="number"&&Math.abs(d.value)>1e12&&t.addIssue({code:"custom",path:["effects",h,"value"],message:"Counter values must be within the display bound"})):d.enabled!==void 0&&a(d.enabled,["effects",h,"enabled"]);let l=(h,d)=>{for(let[g,R]of Object.entries(h))Object.hasOwn(n,g)||t.addIssue({code:"custom",path:[...d,g],message:"UI assignments can only update declared state"}),a(R,[...d,g])},p=new Set,m=new Set;for(let[h,d]of(e.controls??[]).entries()){if(d.type==="carousel"&&d.inactiveMaxWidth!==void 0&&d.inactiveTargets===void 0&&t.addIssue({code:"custom",path:["controls",h,"inactiveMaxWidth"],message:"Inactive width requires inactive article targets"}),d.type==="carousel")for(let g of d.inactiveTargets??[])(g===d.target||m.has(g))&&t.addIssue({code:"custom",path:["controls",h,"inactiveTargets"],message:"Inactive article targets must have one carousel owner"}),m.add(g);if(d.type==="carousel")for(let g of["previousTarget","nextTarget"]){let R=d[g];R!==void 0&&((R===d.target||p.has(R)||(e.controls??[]).some(y=>y.target===R))&&t.addIssue({code:"custom",path:["controls",h,g],message:"Carousel navigation needs a distinct, exclusive button target"}),p.add(R))}if(d.type!=="action"){let g=Object.hasOwn(n,d.state)?n[d.state]:void 0;(!g||d.type==="input"&&g.type==="enum"&&g.values.some(R=>typeof R!="string"))&&t.addIssue({code:"custom",path:["controls",h,"state"],message:"Control needs a supported declared UI state"}),d.type==="carousel"&&(g?.type!=="number"||!Number.isInteger(g.min)||g.min<0||!Number.isInteger(g.max)||g.step!==1||d.initialIndex!==void 0&&!Gc(g,d.initialIndex))&&t.addIssue({code:"custom",path:["controls",h],message:"Carousel needs bounded nonnegative integer index state"}),d.type==="scroll_latch"&&g?.type!=="boolean"&&t.addIssue({code:"custom",path:["controls",h,"state"],message:"Scroll latches require boolean UI state"})}(d.type==="input"||d.type==="action")&&d.set&&l(d.set,["controls",h,"set"])}for(let[h,d]of(e.timers??[]).entries())l(d.set,["timers",h,"set"])});import{z as ct}from"zod";var Sx=ct.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Va=ct.discriminatedUnion("type",[ct.object({type:ct.literal("fixed"),productVersionId:ct.string().min(1).max(200)}).strict(),ct.object({type:ct.literal("picker"),pickerId:Sx,allowedProductVersionIds:ct.array(ct.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")]),Ix=ct.strictObject({min:ct.number().finite().min(1).max(1800),max:ct.number().finite().min(1).max(1800),viewport:ct.number().finite().min(1).max(100)}).refine(e=>e.min<=e.max,"Desktop width range is reversed"),Tm={desktopWidth:Ix.optional(),mobile:ct.enum(["sheet","fullscreen"]).optional(),backdrop:ct.enum(["none","scrim","dim","strong-dim","blur"]).optional()},kn=ct.discriminatedUnion("type",[ct.strictObject({type:ct.literal("modal"),size:ct.enum(["sm","md","lg"]),...Tm}),ct.strictObject({type:ct.literal("sheet"),size:ct.enum(["sm","md","lg"]),...Tm}),ct.strictObject({type:ct.literal("fullscreen")}),ct.strictObject({type:ct.literal("inline")})]);var wx=4,Tn={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:32768,documentBytes:2e5},Po=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ve=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ox=I.enum(["none","xs","sm","md","lg","xl"]),Px=I.enum(["none","sm","md","lg","full"]),Kc=I.string().regex(/^#[0-9a-fA-F]{6}$/),Qc=I.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"),Hc=I.union([Qc,I.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),I.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),I.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Nm=I.object({primary:Kc,background:Kc,text:Kc,radius:Px,font:I.enum(["system","serif","rounded","mono"]),fontAssets:I.object({family:I.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/),faces:I.array(I.object({url:Qc,weight:I.number().int().min(100).max(900).multipleOf(100),family:I.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/).optional()}).strict()).min(1).max(4)}).strict().optional()}).strict(),Co=I.union([I.enum(["primary","text","muted","background","surface"]),I.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),Ue=(e,t)=>I.number().int().min(e).max(t),Dm=I.union([I.enum(["fit","fill"]),Ue(1,1200)]),Cx=I.object({top:Ue(0,200),right:Ue(0,200),bottom:Ue(0,200),left:Ue(0,200)}).strict(),_x=I.object({top:Ue(-100,200),right:Ue(-100,200),bottom:Ue(-100,200),left:Ue(-100,200)}).strict(),Fm=I.object({x:Ue(0,100),y:Ue(0,100)}).strict(),Ex=I.discriminatedUnion("type",[I.object({type:I.literal("color"),color:Co}).strict(),I.object({type:I.literal("linear"),angle:Ue(0,360),stops:I.array(I.object({color:Co,at:Ue(0,100)}).strict()).min(2).max(4)}).strict(),I.object({type:I.literal("image"),src:Hc,fit:I.enum(["cover","contain"]),position:Fm.optional()}).strict()]),Rx=I.discriminatedUnion("type",[I.object({type:I.literal("rect"),radius:I.union([Ue(0,200),I.object({topLeft:Ue(0,200),topRight:Ue(0,200),bottomRight:Ue(0,200),bottomLeft:Ue(0,200)}).strict()])}).strict(),I.object({type:I.literal("pill")}).strict()]),kx=I.object({width:Ue(0,12),color:Co,style:I.enum(["solid","dashed"])}).strict(),jx=I.object({x:Ue(-40,40),y:Ue(-40,40),blur:Ue(0,80),spread:Ue(-20,40),color:Co}).strict(),Tx=I.object({font:I.enum(["system","serif","rounded","mono"]),size:Ue(8,96),weight:I.number().int().min(100).max(900).multipleOf(100),lineHeight:I.number().min(.8).max(3),letterSpacing:I.number().min(-5).max(20),color:Co,align:I.enum(["start","center","end"]),italic:I.boolean(),decoration:I.enum(["none","underline","line-through"]),transform:I.enum(["none","uppercase"])}).strict().partial(),Lr=I.object({width:Dm,height:Dm,padding:Cx,margin:_x,gap:Ue(0,120),grow:I.union([I.boolean(),I.number().min(0).max(12)]),background:Ex,opacity:I.number().min(0).max(1),clipContent:I.boolean(),shape:Rx,border:kx,shadow:jx,text:Tx}).strict().partial(),an={id:Po,name:I.string().trim().min(1).max(60).optional(),hidden:I.boolean().optional(),style:Lr.optional(),fallback:Ve.optional()},Nx=I.object({...an,type:I.literal("text"),productField:I.enum(["name","price","trial","period"]).optional(),feature:I.object({id:I.uuid(),field:I.enum(["name","allowance"])}).strict().optional(),text:Ve,variant:I.enum(["title","heading","body","caption"])}).strict(),Dx=I.object({...an,type:I.literal("image"),src:Hc,localizedSrc:I.record(Cn,Hc).optional(),alt:Ve,aspect:I.enum(["auto","1:1","4:3","16:9","3:1"]),fit:I.enum(["cover","contain"]),position:Fm.optional()}).strict(),Fx=I.object({...an,type:I.literal("button"),label:Ve,variant:I.enum(["primary","secondary","link"]),action:Ve,purpose:I.enum(["purchase","navigation","close"]).optional(),bind:qa.optional()}).strict(),Mx=I.object({...an,type:I.literal("divider")}).strict(),qx=I.object({...an,type:I.literal("customer_data"),title:Ve,data:Cm}).strict(),Ux=I.object({...an,type:I.literal("spacer"),size:Ox}).strict(),Bx=I.object({...an,type:I.literal("custom_html"),html:I.record(Cn,I.string().max(Tn.customHtml)),css:I.string().max(Tn.customCss),ui:jm.optional()}).strict(),Vx=I.object({...an,type:I.literal("price"),fallback:Ve,parts:I.object({current:Lr.optional(),original:Lr.optional(),period:Lr.optional()}).strict().optional()}).strict(),Lx=I.object({...an,type:I.literal("coupon_code"),label:Ve,fallback:Ve}).strict(),zx=I.object({...an,type:I.literal("countdown"),source:I.enum(["offer.ends_at","offer.expires_at","fixed"]),at:I.iso.datetime().optional(),granularity:I.enum(["day","hour","minute","second"]),expired:Ve,fallback:Ve}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),$x=I.object({...an,type:I.literal("plan_picker"),label:Ve,fallback:Ve,planIds:I.array(I.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.string().min(1).max(200).optional(),grouping:Ua.safeExtend({monthLabel:Ve,yearLabel:Ve,unavailableLabel:Ve}).optional(),states:I.object({selected:Lr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!Ba(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),Gx=I.object({...an,type:I.literal("quantity_picker"),bind:qa.optional(),label:Ve,fallback:Ve,internalFeatureId:I.uuid(),minimumQuantity:Ue(0,1e4),maximumQuantity:Ue(0,1e4),defaultQuantity:Ue(0,1e4),step:Ue(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"),Kx=I.discriminatedUnion("type",[I.object({type:I.literal("input"),label:Ve,keyboard:I.enum(["text","email","tel","url"]),maxLength:Ue(1,500)}).strict(),I.object({type:I.literal("multiselect"),label:Ve,min:Ue(0,50),max:Ue(1,50)}).strict(),I.object({type:I.literal("select"),label:Ve,defaultIndex:Ue(0,49),purpose:I.enum(["option","product","tier"]).optional(),pickerId:Po.optional(),selectedStyle:Lr.optional()}).strict(),I.object({type:I.literal("tabs"),label:Ve,defaultIndex:Ue(0,49),purpose:I.literal("tier").optional()}).strict(),I.object({type:I.literal("toggle"),label:Ve,defaultEnabled:I.boolean()}).strict(),I.object({type:I.literal("carousel"),label:Ve}).strict()]),jn={...an,type:I.literal("stack"),direction:I.enum(["vertical","horizontal","overlay"]),align:I.enum(["start","center","end","stretch"]),justify:I.enum(["start","center","end","between"]),productSlot:I.object({index:Ue(0,19),period:I.enum(["month","year"]).optional(),requireBinding:I.boolean().optional()}).strict().optional(),interaction:Kx.optional(),states:I.object({selected:Lr.optional()}).strict().optional(),purpose:I.literal("benefits").optional(),purchaseAction:Ve.optional(),buttonVariant:I.enum(["primary","secondary","link"]).optional(),bind:qa.optional()},Mm=I.lazy(()=>I.object({...an,type:jn.type,direction:jn.direction,align:jn.align,justify:jn.justify,children:I.array(Hx).max(Tn.children),productSlot:jn.productSlot,interaction:jn.interaction,states:jn.states,purpose:jn.purpose,purchaseAction:jn.purchaseAction,buttonVariant:jn.buttonVariant,bind:jn.bind}).strict()),Hx=I.lazy(()=>I.union([Mm,Nx,Dx,Fx,Mx,Ux,Bx,Vx,Lx,zx,$x,Gx,qx])),Qx=I.union([I.string().max(500),I.number().finite(),I.boolean(),I.null()]),Oo={id:Ve,event:Ve,properties:I.record(Ve,Qx).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},Jx=I.discriminatedUnion("type",[I.object({...Oo,type:I.literal("navigate"),close:I.literal(!1),pageId:Po}).strict(),I.object({...Oo,type:I.literal("event"),close:I.boolean()}).strict(),I.object({...Oo,type:I.literal("close"),close:I.literal(!0)}).strict(),I.object({...Oo,type:I.literal("open_url"),close:I.boolean(),url:Qc}).strict(),I.object({...Oo,type:I.literal("claim_offer"),close:I.boolean(),couponId:I.uuid()}).strict()]),Zx=I.object({defaultLocale:Cn,locales:I.record(Cn,I.record(Ve,I.string().max(Tn.stringLength)))}).strict(),Wx=I.enum(["popup","paywall","onboarding","page","banner"]);var Yx=I.object({kind:I.literal("screen"),schemaVersion:I.literal(wx),name:I.string().trim().min(1).max(80),surface:Wx,initialPageId:Po.optional(),presentation:kn,theme:Nm,pages:I.array(I.object({id:Po,name:I.string().trim().min(1).max(60),root:Mm,theme:Nm.optional(),editorPosition:I.object({x:I.number().finite().min(-1e5).max(1e5),y:I.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(Tn.pages),strings:Zx,actions:I.array(Jx).max(Tn.actions)}).strict();function Zt(e,t){for(let n of e.pages)tr(n.root,t)}var mn=Yx.superRefine((e,t)=>{let n=Tn;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(p=>p.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>Tn.locales&&r(`\u6700\u591A ${Tn.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;Zt(e,(l,p)=>{if(c++,p>Tn.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 m of Object.keys(l.html))i.includes(m)||r(`\u81EA\u5B9A\u4E49 HTML ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${m}`);if(l.type==="image")for(let m of Object.keys(l.localizedSrc??{}))i.includes(m)||r(`\u56FE\u7247 ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${m}`)}),c>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),u&&r(`\u5C42\u7EA7\u6700\u591A ${Tn.depth} \u5C42`)});function tr(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)tr(i,t,n+1,e)}function La(e){let t=[],n=new Set;return Zt(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 Xx(e,t,n){if(t.field==="html"){let r;return Zt(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=_o(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 mr(e){let t=La(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=>!Xx(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 eS(e,t){let n=null;return tr(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function _o(e,t){for(let n of e.pages){let r=eS(n.root,t);if(r)return r}return null}import{z as $t}from"zod";var wt=$t.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"),Jc=$t.strictObject({type:$t.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:$t.boolean(),enum:$t.array($t.string().max(255)).min(1).max(100).optional()}),wi=Jc.extend({type:$t.enum([...Jc.shape.type.options,"array"]),items:Jc.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"})}),Oi=wi.safeExtend({source:$t.discriminatedUnion("type",[$t.strictObject({type:$t.literal("input")}),$t.strictObject({type:$t.literal("node")}),$t.strictObject({type:$t.enum(["parameter","attribute"]),key:wt})])}),q_=$t.record(wt,Oi),Zc=$t.record(wt,wt).refine(e=>Object.keys(e).length<=20);function xn(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=>xn(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&&$t.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 Wc(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&&Wc(e.items,t.items)}function za(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(!xn(i,u))throw new Error(`Invalid variable value: ${r}`);n[r]=u}}return n}function Pi(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 qm(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"||!xn(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")}import{z as zr}from"zod";var Nn=zr.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"),Vn=zr.discriminatedUnion("source",[zr.strictObject({source:zr.literal("literal"),value:ve}),zr.strictObject({source:zr.literal("variable"),key:zr.string().min(1).max(255),path:Nn.optional()})]);function Um(e,t){if(!t)return e;for(let n of Nn.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 Yc(e,t){if(e.source==="literal")return structuredClone(e.value);let n=za(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(ve.parse(Um(n[e.key],e.path)))}function Xc(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&&!Nn.safeParse(r).success?null:{key:n,path:r}}function eu(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Zt(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(vm))]}function $a(e){return eu(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function fn(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(/^-/,""),p=l.replace(".","").length,m=(l.includes(".")?l.indexOf("."):p)+Number(u),h=m<=0?2-m+p:m>=p?m:p+1;n+=h+(c.startsWith("-")?1:0)-s.length}}return n}var fr=Ce.enum(["page","popup","banner"]),tS=3e5,Bm=Ce.strictObject({type:Ce.enum(["string","number","boolean","strings","json"]),nullable:Ce.boolean()}),nS=Ce.strictObject({inputs:Ce.record(Ve,Bm.extend({required:Ce.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:Ce.record(Ve,Bm).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),rS=Ce.strictObject({kind:fr,schemaVersion:Ce.literal(1),name:Ce.string().trim().min(1).max(80),screen:mn,contract:nS}),Ga=rS.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"]),fn(e)>tS&&n("Content document exceeds its byte budget",[])});function iS(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 oS=Ga.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&&!iS(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}mr(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),Vm=Ce.strictObject({id:Ce.uuid(),kind:fr,projectId:Ce.uuid(),environmentId:Ce.uuid(),name:Ce.string(),revision:Ce.number().int().nonnegative(),status:Ce.enum(["draft","published","archived"]),publishedVersionId:Ce.uuid().nullable(),createdAt:Ce.iso.datetime({offset:!0}),updatedAt:Ce.iso.datetime({offset:!0})}),e1=Vm.extend({draft:Ga}),t1=Ce.strictObject({rows:Ce.array(Vm).max(200),nextCursor:Ce.uuid().nullable()}),tu=Ce.strictObject({id:Ce.uuid(),kind:fr,resourceId:Ce.uuid(),projectId:Ce.uuid(),environmentId:Ce.uuid(),version:Ce.number().int().positive(),sourceRevision:Ce.number().int().nonnegative(),document:oS,createdAt:Ce.iso.datetime({offset:!0})}),n1=tu.omit({document:!0}),r1=Ce.discriminatedUnion("action",[Ce.strictObject({action:Ce.literal("create"),kind:fr,id:Ce.uuid(),document:Ga}),Ce.strictObject({action:Ce.literal("save"),kind:fr,id:Ce.uuid(),revision:Ce.number().int().nonnegative(),document:Ga}),Ce.strictObject({action:Ce.enum(["publish","archive"]),kind:fr,id:Ce.uuid(),revision:Ce.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"})});import{z as Lm}from"zod";var Ci={funnelId:Lm.uuid().optional(),funnelVersionId:Lm.uuid().optional()};import{z as Ka}from"zod";var Ha=Ka.strictObject({runId:Ka.uuid(),bindingId:Ka.uuid(),receiptId:Ka.uuid()});import{z as ut}from"zod";import{z as Le}from"zod";import{z as rt}from"zod";var l1=rt.discriminatedUnion("action",[rt.strictObject({action:rt.literal("create"),couponId:rt.uuid(),productBindingId:rt.uuid(),storeOfferId:rt.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:rt.enum(["introductory","promotional"])}),rt.strictObject({action:rt.literal("set_enabled"),id:rt.uuid(),revision:rt.number().int().nonnegative(),enabled:rt.boolean()})]),d1=rt.array(rt.strictObject({id:rt.uuid(),couponId:rt.uuid(),productBindingId:rt.uuid(),storeOfferId:rt.string().min(1).max(255).nullable(),storeOfferType:rt.enum(["introductory","promotional"]),enabled:rt.boolean(),revision:rt.number().int().nonnegative()})).max(500),_i=rt.strictObject({offerKind:rt.enum(["none","introductory","promotional"]),offerId:rt.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:rt.number().int().min(0).max(1e8),trialDays:rt.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"})}),p1=rt.record(rt.uuid(),_i).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var nu=Le.object({type:Le.literal("native_purchase"),receiptId:Le.uuid(),orderId:Le.uuid(),productVersionId:Le.uuid(),provider:Le.enum(["apple","google"]),productId:Le.string().min(1).max(255),productKind:Ud,replacement:Le.strictObject({sourceOrderId:Le.uuid(),sourceProductId:Le.string().min(1).max(255),policy:Le.enum(["apple_store","google_full_price"]),sourceAccountTokens:Le.array(Le.uuid()).max(50)}).nullable(),appAccountToken:Le.uuid().optional(),obfuscatedAccountId:Le.string().min(1).max(64).optional(),obfuscatedProfileId:Le.uuid().optional(),basePlanId:Le.string().min(1).max(255).optional(),offerId:Le.string().min(1).max(255).optional(),offerKind:Le.enum(["none","introductory","promotional"]),currency:Ie,catalogAmountMinor:Le.number().int().nonnegative().max(1e8),discountMinor:Le.number().int().nonnegative().max(1e8),trialDays:Le.number().int().min(1).max(730).nullable(),seatBundle:Le.array(Le.strictObject({key:Le.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:Le.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:Le.strictObject({offerId:Le.string().min(1).max(255),keyId:Le.string().min(1).max(255),nonce:Le.uuid(),signature:Le.string().min(1).max(1024),timestamp:Le.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"})});import{z as f}from"zod";import{z as _e}from"zod/v4";import{z as aS}from"zod/v4";var sS=aS.registry(),{BillingInterval:zm}=(()=>{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:cS}=(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),{withSpecDefault:uS}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(sS),{COMMON:$m}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:lS}={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:dS}=(e=>({COMMON_SET:new Set(e)}))($m),{hasNoDuplicateCurrencies:Gm}={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:Km}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:pS}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(_e),{Infinite:mS}={Infinite:"inf"},{TierBehavior:fS}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:Hm}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:hS}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:gS}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:yS}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:AS}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(_e),{ApiCreditTierSchema:Qm}=(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),{VIOLATION_MESSAGES:bS}={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:Jm}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(_e),{ModelMarkupsSchema:xS}=((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,Jm),{InvoiceUsageEntrySchema:SS}=(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),{AttachDiscountSchema:Zm}=(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),{CustomLineItemSchema:IS}=(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),{UnixMsTimestampSchema:vS}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(_e),{CreateInvoicePreviewLineSchema:wS}=(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),{ReissueInvoiceParamsSchema:Wm}=(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),{InvoiceModeParamsSchema:$r}=(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),{InvoiceTemplateSchema:OS}=(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),{BasePriceSchema:PS}=((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,zm,cS),{CURRENCY_CODES:CS}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))($m,lS,dS),{ApiPriceProcessorsSchema:Ym}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(_e,pS),{AllocatedBillingFieldSchema:_S}=((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,hS),{CreditDimensionNameSchema:ES}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(_e,gS,yS),{ApiCreditMatchSchema:Xm}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(AS),{findCreditTierViolations:RS}=(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}}))(bS),{ApiCreditMultiplierSchema:kS}=((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,Xm),{ProviderMarkupsSchema:jS}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(_e,Jm),{InvoiceFeatureQuantitySchema:ef}=((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,Hm,SS),{CreateInvoicePreviewSchema:ru}=((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,wS),{SUPPORTED_SET:TS}=(e=>({SUPPORTED_SET:new Set(e)}))(CS),{ApiCreditDimensionBaseSchema:NS}=((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,Xm),{refineGraduatedTiers:tf}=(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"]})}}))(RS),{ApiFeatureMarkupsOverrideSchema:DS}=((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,jS,xS),{isValidCurrencyCode:FS}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(TS),{ApiCreditDimensionSchema:MS}=((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,NS,Qm,tf),{CurrencyCodeSchema:nf}=((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,FS),{AdditionalCurrencyTierSchema:qS}=((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,nf),{ApiCreditSchemaItemBaseSchema:rf}=((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,ES,MS,kS),{ApiFlatCreditSchemaItemSchema:US}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(rf,_e),{AdditionalCurrencyPriceSchema:BS}=((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,nf),{AdditionalCurrencyTierArraySchema:VS}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(_e,qS,Gm,Km),{ApiGraduatedCreditSchemaItemSchema:LS}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(rf,_e,Qm,tf),{AdditionalCurrencyPriceArraySchema:of}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(_e,BS,Gm,Km),{ApiUsageTierWithCurrenciesSchema:zS}=((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,mS,VS),{ApiCreditSchemaItemSchema:$S}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(_e,LS,US),{BasePriceParamsSchema:GS}=((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."})}))(PS,uS,_e,of),{PlanItemPriceParamsSchema:KS}=((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,of,zS,fS,zm,Hm,_S),{ApiFeatureOverrideSchema:HS}=((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,$S,DS),{InvoiceBasePriceParamsSchema:af}=((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()}))(GS,Ym),{InvoiceItemPriceParamsSchema:QS}=((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()}))(KS,Ym),{InvoiceLicenseQuantitySchema:JS}=((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,af,ef),{InvoiceCustomizeItemSchema:ZS}=((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,QS,HS),{InvoiceCustomizeSchema:WS}=((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,af,ZS),{InvoicePlanParamsSchema:YS}=((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,WS,ef,JS,Zm),{CreateInvoiceParamsSchema:Ei}=((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,YS,IS,Zm,vS);var uf=f.strictObject({requestId:f.uuid(),predecessorOperationId:f.uuid().optional(),invoiceMode:$r.optional(),entityId:f.uuid().optional(),billingSubscriptionId:f.uuid().optional(),newBillingSubscription:f.literal(!0).optional(),offerId:f.uuid().optional(),nativeOffer:_i.optional(),plans:f.array(f.strictObject({productVersionId:f.uuid(),seatQuantities:f.record(ya,f.number().int().min(0).max(1e4)).optional(),featureQuantities:f.record(f.uuid(),f.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:f.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"),Kr=f.strictObject({operationId:f.uuid()}),Bt=f.number().int().min(0).max(1e8),XS=f.strictObject({lineId:f.uuid(),productVersionId:f.uuid(),productName:f.string().min(1).max(80),interval:f.enum(["free","week","month","year","one_time"]),intervalCount:f.number().int().min(1).max(156).optional(),baseAmountMinor:Bt,seats:f.array(f.strictObject({key:ya,quantity:f.number().int().min(0).max(1e4),includedQuantity:f.number().int().min(0).max(1e4),maximumQuantity:f.number().int().min(0).max(1e4),unitAmountMinor:Bt})).max(20),prepaid:f.array(Yp).max(100).optional(),catalogAmountMinor:Bt,trial:Xi.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+Sa({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"),lf=f.string().regex(/^[A-Za-z0-9_-]{1,200}$/),e0=f.strictObject({id:lf,name:f.string().min(1).max(40),percent_off:f.number().gt(0).max(100).optional(),amount_off:f.number().int().positive().optional(),currency:f.string().regex(/^[a-z]{3}$/).optional(),duration:f.enum(["once","repeating","forever"]),duration_in_months:f.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"),t0=f.strictObject({subscriptionId:f.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:f.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:f.array(f.strictObject({id:f.string(),price_id:f.string(),quantity:f.number().int().nonnegative(),discounts:f.array(f.strictObject({id:f.string(),coupon:f.string(),start:f.number(),end:f.number().nullable()})).optional()})).min(1).max(100),prorationDate:f.number().int().nonnegative(),amountMinor:f.number().int().positive(),periodStartMs:f.number(),periodEndMs:f.number()}),df=f.strictObject({invoiceMode:$r.optional(),append:t0.optional(),provider:f.literal("stripe"),executor:f.enum(["indiana","merchant"]),accountId:f.string().regex(/^acct_[A-Za-z0-9]+$/),mode:f.enum(["payment","subscription"]),lineItems:f.array(f.strictObject({price:f.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:f.number().int().min(1).max(1e4),priceId:f.uuid(),productName:f.string().min(1).max(80),amountMinor:f.number().int().min(0).max(1e8),currency:f.string().regex(/^[a-z]{3}$/),interval:f.enum(["week","month","year","one_off"]),intervalCount:f.number().int().min(1).max(52),slot:f.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:f.strictObject({mode:f.enum(["graduated","volume"]),tiers:f.array(f.strictObject({upTo:f.number().int().min(1).max(1e6).nullable(),unitAmountMinor:f.number().int().min(0).max(1e8),flatAmountMinor:f.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:f.array(f.strictObject({coupon:lf,terms:e0})).max(1),trialPeriodDays:f.number().int().min(1).max(730).nullable(),metadata:f.strictObject({grooveCheckoutId:f.uuid(),grooveCustomerId:f.uuid()}),expiresAt:f.iso.datetime({offset:!0})}),Ri=f.strictObject({operationId:f.uuid(),merchantTerms:pi.optional(),entityId:f.uuid().nullable(),billingSubscriptionId:f.uuid().nullable(),discount:f.strictObject({offerId:f.uuid(),couponId:f.uuid(),discount:dr,duration:dn,amountMinor:Bt,allocations:f.array(f.strictObject({productVersionId:f.uuid(),amountMinor:Bt})).min(1).max(20),expiresAt:f.iso.datetime({offset:!0})}).nullable(),charge:f.strictObject({effectiveAt:f.iso.datetime({offset:!0}),periodEndsAt:f.iso.datetime({offset:!0}),debitMinor:Bt,discountMinor:Bt,taxMinor:Bt,totalMinor:Bt}).nullable(),expiresAt:f.iso.datetime({offset:!0}),provider:f.enum(["stripe","apple","google","merchant"]),nativeOffer:_i.optional(),currency:Ie,lines:f.array(XS).min(1).max(20),catalogAmountMinor:Bt,automaticTax:f.boolean(),execution:f.union([df,oa]).nullable()}).refine(e=>!e.merchantTerms||e.provider==="merchant"&&fa(e.merchantTerms,e.operationId,"purchase",e.currency)).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"),ki=f.strictObject({operationId:f.uuid(),orderId:f.uuid(),append:f.boolean().optional(),invoiceMode:f.boolean().optional(),status:f.enum(["pending","complete","cancelled","failed"]),executor:f.enum(["indiana","merchant"]),checkoutUrl:f.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:f.union([df,oa]).nullable(),currency:Ie,catalogAmountMinor:Bt,taxMinor:Bt,totalMinor:f.number().int().min(0).max(2e8).nullable(),quoteFinalized:f.boolean(),nativePurchase:nu.nullable(),confirmedAt:f.iso.datetime({offset:!0}).nullable().optional(),quote:Ri.optional(),merchantExecution:jr.nullable().optional(),problem:Wi.nullable().optional(),authority:ga.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=f.strictObject({enabled:f.literal(!0),featureIds:f.array(f.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),pf=f.strictObject({requestId:f.uuid(),invoiceMode:$r.optional(),membershipId:f.uuid(),carryOverBalances:Ja.optional(),carryOverUsages:Ja.optional(),membershipIds:f.array(f.uuid()).min(1).max(20).optional(),prorationBehavior:f.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:f.enum(["immediate","renewal","store"]),change:f.discriminatedUnion("type",[f.strictObject({type:f.literal("plan"),productVersionId:f.uuid()}),f.strictObject({type:f.literal("seats"),licenseKey:ya,quantity:f.number().int().min(0).max(1e4)}),f.strictObject({type:f.literal("quantity"),internal_feature_id:f.uuid(),quantity:f.number().int().min(0).max(1e4)}),f.strictObject({type:f.literal("cancel")}),f.strictObject({type:f.literal("uncancel")}),f.strictObject({type:f.literal("billing_cycle"),billingCycleAnchor:f.union([f.literal("now"),f.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"),Qa=f.string().regex(/^price_[A-Za-z0-9]+$/),sf=f.strictObject({grooveUpdateId:f.uuid(),grooveCustomerId:f.uuid()}),cf=f.strictObject({price:Qa.nullable(),priceId:f.uuid().optional(),quantity:f.number().int().min(0).max(1e4)}),mf=f.strictObject({provider:f.literal("stripe"),invoiceMode:$r.optional(),executor:f.enum(["indiana","merchant"]),accountId:f.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:f.string().regex(/^sub_[A-Za-z0-9]+$/),action:f.enum(["update","cancel","schedule","release"]),update:f.strictObject({items:f.array(cf).max(20),remove:f.array(Qa).max(20),restoreItems:f.array(f.strictObject({price:Qa,quantity:f.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:f.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:f.number().int().positive().optional(),paymentBehavior:f.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:f.boolean().optional(),clearCancelAt:f.literal(!0).optional(),billingCycleAnchorNow:f.literal(!0).optional(),metadata:sf}).nullable(),cancel:f.strictObject({prorate:f.literal(!1),invoiceNow:f.literal(!1)}).nullable(),schedule:f.strictObject({currentItems:f.array(f.strictObject({price:Qa,quantity:f.number().int().min(0).max(1e4)})).max(20),nextItems:f.array(cf).min(1).max(20),switchAt:f.number().int().positive(),interval:f.enum(["week","month","year"]),intervalCount:f.number().int().min(1).max(52),resetBillingCycleAnchor:f.literal(!0).optional(),metadata:sf}).nullable(),release:f.strictObject({schedule:f.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:f.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"),Za=f.strictObject({merchantTerms:pi.optional(),carryOverBalances:Ja.optional(),carryOverUsages:Ja.optional(),operationId:f.uuid(),membershipId:f.uuid(),productVersionId:f.uuid(),timing:f.enum(["immediate","renewal"]),effectiveAt:f.iso.datetime({offset:!0}),expiresAt:f.iso.datetime({offset:!0}),currency:Ie,creditMinor:Bt,debitMinor:Bt,discountMinor:Bt,taxMinor:Bt,totalMinor:Bt,retainedProductVersionIds:f.array(f.uuid()).max(19),execution:f.union([mf,nr])}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&fa(e.merchantTerms,e.operationId,"subscription_change",e.currency)),n0=f.strictObject({operationId:f.uuid(),invoiceMode:f.boolean().optional(),membershipId:f.uuid(),productVersionId:f.uuid(),status:f.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:f.enum(["immediate","renewal"]),effectiveAt:f.iso.datetime({offset:!0}),checkoutUrl:f.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:f.enum(["indiana","merchant"]),execution:f.union([mf,nr]).nullable(),confirmedAt:f.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:jr.nullable().optional(),problem:Wi.nullable().optional(),quote:Za.optional(),authority:ga.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),r0=f.strictObject({operationId:f.uuid(),membershipId:f.uuid(),productVersionId:f.uuid(),timing:f.literal("store"),effectiveAt:f.null(),expiresAt:f.iso.datetime({offset:!0}),currency:Ie,creditMinor:f.null(),debitMinor:f.null(),discountMinor:f.null(),taxMinor:f.null(),totalMinor:f.null(),retainedProductVersionIds:f.array(f.uuid()).max(19),store:f.strictObject({provider:f.enum(["apple","google"]),productId:f.string().min(1).max(255),catalogAmountMinor:Bt,policy:f.enum(["apple_store","google_full_price"])})}),i0=f.strictObject({operationId:f.uuid(),membershipId:f.uuid(),productVersionId:f.uuid(),status:f.enum(["prepared","pending","effective","cancelled","failed"]),timing:f.literal("store"),effectiveAt:f.iso.datetime({offset:!0}).nullable(),checkoutUrl:f.null(),nativePurchase:nu.nullable()}),ff=f.union([Za,r0]),iu=f.union([n0,i0]),ou=dc,Gr=da,hf=f.strictObject({requestId:f.uuid(),invoiceId:f.uuid(),...Nr.shape}).refine(to,"A partial refund states amountMinor; a full refund refunds the remaining amount"),gf=f.strictObject({provider:f.literal("stripe"),executor:f.enum(["indiana","merchant"]),accountId:f.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:f.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:ou,currency:f.string().regex(/^[a-z]{3}$/),metadata:f.strictObject({indianaRefundId:f.uuid()}),idempotencyKey:f.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:f.array(f.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),au=f.strictObject({operationId:f.uuid(),merchantTerms:pi.optional(),invoiceId:f.uuid(),providerInvoiceId:f.string().min(1).max(200),currency:Ie,paidMinor:Gr,refundedMinor:Gr,pendingMinor:Gr,amountMinor:ou,mode:f.enum(["full","partial"]),entitlementAction:f.enum(["retain","revoke"]),revokes:f.strictObject({customerProductIds:f.array(f.uuid()).max(100),subscriptionIds:f.array(f.string().min(1).max(200)).max(20)}),execution:f.union([gf,aa]),expiresAt:f.iso.datetime({offset:!0})}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&fa(e.merchantTerms,e.operationId,"refund",e.currency)).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"),Wa=f.strictObject({operationId:f.uuid(),invoiceId:f.uuid(),providerInvoiceId:f.string().min(1).max(200),status:f.enum(["quoted","pending","succeeded","failed","expired"]),executor:f.enum(["indiana","merchant"]),currency:Ie,amountMinor:ou,mode:f.enum(["full","partial"]),entitlementAction:f.enum(["retain","revoke"]),refundId:f.string().min(1).max(200).nullable(),quote:au.optional(),execution:f.union([gf,aa]).nullable(),confirmedAt:f.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:jr.nullable().optional(),problem:Wi.nullable().optional(),authority:ga.optional(),failureReason:f.string().min(1).max(200).nullable(),createdAt:f.iso.datetime({offset:!0}),completedAt:f.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"),D1=f.strictObject({invoiceId:f.uuid(),currency:Ie,paidMinor:Gr,refundedMinor:Gr,pendingMinor:Gr,refundableMinor:Gr,executor:f.enum(["indiana","merchant"]).nullable(),canRefund:f.boolean(),operations:f.array(Wa).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),F1=f.strictObject({requestId:f.uuid(),...Nr.shape}).refine(to,"A partial refund states amountMinor; a full refund refunds the remaining amount");var yf=ut.strictObject({requestId:ut.uuid(),targets:ut.array(ut.strictObject({membershipId:ut.uuid(),action:ut.enum(["cancel","uncancel"]),timing:ut.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"),Ya=ut.strictObject({batchId:ut.uuid()}),o0=ut.strictObject({operationId:ut.uuid(),membershipIds:ut.array(ut.uuid()).min(1).max(20),provider:ut.enum(["stripe","apple","google"]),action:ut.enum(["cancel","uncancel"]),timing:ut.enum(["immediate","renewal"]),status:ut.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:Za.nullable(),managementUrl:ut.url().nullable(),failureCode:ut.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),Eo=ut.strictObject({batchId:ut.uuid(),ready:ut.boolean(),status:ut.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:ut.iso.datetime({offset:!0}),acceptedAt:ut.iso.datetime({offset:!0}).nullable(),groups:ut.array(o0).min(1).max(100)});import{z as Te}from"zod";var a0=Te.string().trim().min(1).max(240),su={requestId:Te.uuid(),reason:a0},Xa=Te.discriminatedUnion("action",[Te.strictObject({...su,action:Te.literal("start"),productVersionId:Te.uuid(),entityId:Te.uuid().optional(),days:Te.number().int().min(1).max(730).optional()}),Te.strictObject({...su,action:Te.literal("extend"),membershipId:Te.uuid(),days:Te.number().int().min(1).max(730)}),Te.strictObject({...su,action:Te.literal("end"),membershipId:Te.uuid()})]),Af=Te.strictObject({operationId:Te.uuid()}),bf=Te.iso.datetime({offset:!0}),s0=Te.strictObject({provider:Te.literal("stripe"),executor:Te.enum(["indiana","merchant"]),accountId:Te.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:Te.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:Te.union([Te.literal("now"),bf]),prorationBehavior:Te.literal("none")}),cu=Te.strictObject({operationId:Te.uuid(),action:Te.enum(["start","extend","end"]),status:Te.enum(["pending","effective"]),managedBy:Te.enum(["indiana","stripe"]),membershipIds:Te.array(Te.uuid()).min(1).max(20),endsAt:bf.nullable(),execution:s0.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"),L1=Te.strictObject({groupId:Te.uuid(),productVersionId:Te.uuid(),enabled:Te.boolean()});import{z as et}from"zod";var xf=et.strictObject({requestId:et.uuid(),currency:Ie,makeDefault:et.boolean()}),Sf=et.strictObject({setupId:et.uuid()}),c0=et.strictObject({provider:et.literal("stripe"),executor:et.literal("merchant"),accountId:et.string().regex(/^acct_[A-Za-z0-9]+$/),mode:et.literal("setup"),currency:et.string().regex(/^[a-z]{3}$/),customer:et.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:et.uuid(),metadata:et.strictObject({grooveProjectId:et.uuid(),grooveEnvironmentId:et.uuid(),grooveCustomerId:et.uuid(),groovePaymentSetupId:et.uuid()}),setDefaultPaymentMethod:et.boolean(),expiresAt:et.iso.datetime({offset:!0})}),uu=et.strictObject({id:et.uuid(),provider:et.literal("stripe"),status:et.enum(["prepared","complete","expired"]),currency:Ie,makeDefault:et.boolean(),url:et.url().nullable(),createdAt:et.iso.datetime({offset:!0}),expiresAt:et.iso.datetime({offset:!0}),completedAt:et.iso.datetime({offset:!0}).nullable(),execution:c0.nullable()});import{z as Vt}from"zod";var If=Vt.union([Vt.string(),Vt.number(),Vt.boolean(),Vt.null()]),vf=Vt.strictObject({customerId:Vt.uuid()}),wf=Vt.strictObject({customerId:Vt.uuid(),provider:Vt.literal("stripe"),checkedAt:Vt.iso.datetime({offset:!0}),status:Vt.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Vt.number().int().nonnegative(),differences:Vt.array(Vt.strictObject({subscriptionId:Vt.string().startsWith("sub_"),itemId:Vt.string().nullable(),field:Vt.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:If,actual:If})).max(1e4)});import{z as we}from"zod";var es=we.iso.datetime({offset:!0}),ts=we.strictObject({createdAt:es,id:we.uuid()}),ns=we.strictObject({customerId:we.uuid().optional(),entityId:we.uuid().optional(),productId:we.string().min(1).max(256).optional(),provider:we.enum(["stripe","apple","google","merchant","free"]).optional(),status:we.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:ts.optional(),limit:we.number().int().min(1).max(100).optional()}),lu={id:we.uuid(),customerId:we.uuid(),entityId:we.uuid().nullable(),productId:we.string().min(1).max(256),productVersionId:we.uuid(),name:we.string().min(1).max(120),provider:we.enum(["stripe","apple","google","merchant","free"]),createdAt:es},u0=we.strictObject({...lu,status:we.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:we.boolean(),billingSubscriptionId:we.uuid().nullable()}),l0=we.strictObject({...lu,status:we.enum(["active","ended","refunded"]),orderId:we.uuid().nullable(),transactionId:we.uuid().nullable(),currency:Ie.nullable(),amountMinor:we.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),d0=we.strictObject({...lu,status:we.enum(["blocked","resolved"]),conflict:we.strictObject({detectedAt:es,blockingMembershipIds:we.array(we.uuid()).min(1).max(100),transactionId:we.uuid()}),resolvedAt:es.nullable()}),Of=ns.extend({status:we.enum(["blocked","resolved"]).optional()}),Pf=we.strictObject({customerId:we.uuid(),orderId:we.uuid()}),Cf=we.strictObject({orderId:we.uuid(),status:we.enum(["blocked","resolved"])}),_f=we.strictObject({items:we.array(u0).max(100),nextCursor:ts.nullable()}),Ef=we.strictObject({items:we.array(l0).max(100),nextCursor:ts.nullable()}),Rf=we.strictObject({items:we.array(d0).max(100),nextCursor:ts.nullable()});import{z as ot}from"zod";var kf=ot.union([ot.strictObject({intent:ot.literal("read"),requestId:ot.uuid(),purchaseIntentId:ot.uuid()}),ot.strictObject({requestId:ot.uuid(),provider:ot.literal("apple"),purchaseIntentId:ot.uuid(),productId:ot.string().min(1).max(255).optional(),signedTransaction:ot.string().min(1).max(131072)}),ot.strictObject({requestId:ot.uuid(),provider:ot.literal("google"),purchaseIntentId:ot.uuid(),productId:ot.string().min(1).max(255).optional(),purchaseToken:ot.string().min(1).max(16384)})]),jf=ot.strictObject({requestId:ot.uuid(),orderId:ot.uuid(),purchaseIntentId:ot.uuid(),status:ot.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:Ie,refunded:ot.boolean(),completion:ot.strictObject({transactionIds:ot.array(ot.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:ot.boolean()}).nullable()});import{z as L}from"zod";var pu=L.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),p0=L.record(L.string(),L.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),m0=3,Ro=20,f0=m0*Ro,du=L.strictObject({type:L.literal("product"),productId:pu}),Tf={type:L.literal("group"),key:L.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:L.string().trim().min(1).max(80)},h0=L.discriminatedUnion("type",[du,L.strictObject({...Tf,items:L.array(du).max(Ro)})]),g0=L.discriminatedUnion("type",[du,L.strictObject({...Tf,items:L.array(h0).max(Ro)})]),y0=L.array(g0).max(Ro).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>Ro||i>f0)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function mu(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:mu(t))}var ji=L.strictObject({lookupKey:L.string().trim().min(1).max(200),displayName:L.string().trim().min(1).max(1500),items:y0,metadata:p0}),A0=L.strictObject({product:L.record(L.string(),L.json()),prices:L.array(L.record(L.string(),L.json())),entitlements:L.array(L.record(L.string(),L.json())),freeTrials:L.array(L.record(L.string(),L.json())),licenses:L.array(L.record(L.string(),L.json()))}),Nf=ji.extend({id:L.uuid(),projectId:L.uuid(),environmentId:L.uuid(),state:L.enum(["active","archived"]),isCurrent:L.boolean(),revision:L.number().int().nonnegative(),publishedVersionId:L.uuid().nullable(),createdAt:L.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"})}),Df=L.strictObject({id:L.uuid(),offeringId:L.uuid(),projectId:L.uuid(),environmentId:L.uuid(),version:L.number().int().positive(),document:ji,productEvidence:L.record(pu,A0),createdAt:L.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=mu(e.document);(!n.length||S0(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"})}),b0=L.strictObject({rows:L.array(Nf).max(200),versions:L.array(Df).max(500)}),nE=L.discriminatedUnion("action",[L.strictObject({action:L.literal("create"),document:ji}),L.strictObject({action:L.literal("save"),id:L.uuid(),revision:L.number().int().nonnegative(),document:ji}),L.strictObject({action:L.enum(["publish","set_current","archive","restore"]),id:L.uuid(),revision:L.number().int().nonnegative()})]),rE=L.strictObject({record:Nf,version:Df.nullable()}),Ff=L.discriminatedUnion("type",[L.strictObject({type:L.literal("current")}),L.strictObject({type:L.literal("id"),id:L.uuid()}),L.strictObject({type:L.literal("lookup_key"),lookupKey:L.string().min(1).max(200)}),L.strictObject({type:L.literal("version"),versionId:L.uuid()})]),x0=L.strictObject({internalId:pu,id:L.string(),name:L.string().nullable(),version:L.number().int().positive(),archived:L.boolean()}),iE=b0.extend({products:L.array(x0).max(500),pagination:L.strictObject({rows:L.string().nullable(),versions:L.string().nullable(),products:L.string().nullable()}).optional()});function S0(e){let t=[];mu(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}import{z as rs}from"zod";var Mf=rs.strictObject({id:rs.uuid(),offeringId:rs.uuid(),version:rs.number().int().positive(),document:ji});import{z as Et}from"zod";import{z as Ae}from"zod";import{z as Ti}from"zod";var is=Ti.strictObject({items:Ti.array(Ti.strictObject({productVersionId:Ti.string().min(1).max(200),label:Ti.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:Ti.string().min(1).max(200).nullable(),grouping:Ua.optional()});function qf(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 fu=Ae.discriminatedUnion("type",[Ae.strictObject({type:Ae.literal("event"),event:Ae.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),Ae.strictObject({type:Ae.literal("open_url"),url:Ae.url().refine(e=>new URL(e).protocol==="https:")})]),I0=mn,v0=Ae.discriminatedUnion("type",[Ae.object({type:Ae.literal("checkout"),product:Va}).strict(),Ae.object({type:Ae.literal("close")}).strict(),Ae.object({type:Ae.literal("action"),action:fu}).strict()]),Ni=Ae.object({schemaVersion:Ae.literal(3),kind:Ae.literal("paywall"),name:Ae.string().trim().min(1).max(80),presentation:kn,requirement:Pn.optional(),products:is,offeringVersionId:Ae.uuid().nullable(),offeringId:Ae.uuid(),screen:I0,buttons:Ae.record(Ae.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),v0)}).strict(),bE=Ni.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 O0(e))t.addIssue({code:"custom",message:r});for(let r of w0(e))t.addIssue({code:"custom",message:r});mr(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 w0(e){let t=e.products.items.map(a=>a.productVersionId),n=wm(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&&(!Ba(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")),Zt(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"),Zt(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 O0(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),tr(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(m=>m.id===u);l?.type==="navigate"&&r.get(s.id).push(l.pageId);let p=e.buttons[u];s.id!==n.id&&p&&p.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 Uf=Ae.object({id:Ae.uuid(),projectId:Ae.uuid(),environmentId:Ae.uuid(),revision:Ae.number().int().nonnegative(),state:Ae.enum(["active","archived"]),publishedVersionId:Ae.uuid().nullable(),updatedAt:Ae.iso.datetime({offset:!0}),draft:Ni}).strict(),xE=Ae.object({rows:Ae.array(Uf).max(200),nextCursor:Ae.uuid().nullable()}).strict(),SE=Uf.omit({draft:!0}).extend({name:Ae.string(),productCount:Ae.number().int().nonnegative()}).strict(),IE=Ae.discriminatedUnion("action",[Ae.object({action:Ae.literal("save"),id:Ae.uuid().nullable(),revision:Ae.number().int().nonnegative(),document:Ni}).strict(),Ae.object({action:Ae.enum(["publish","archive"]),id:Ae.uuid(),revision:Ae.number().int().nonnegative()}).strict()]),vE=Ae.object({paywalls:Ae.array(Ae.object({id:Ae.uuid(),paywallId:Ae.uuid(),version:Ae.number().int().positive(),name:Ae.string().min(1).max(80),presentation:kn,buttons:Ni.shape.buttons}).strict()).max(500),limited:Ae.boolean()}).strict();import{z as Re}from"zod";import{z as Wt}from"zod";var Di=Wt.string().regex(/^[a-f0-9]{64}$/),P0=Ma.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),Bf=Wt.strictObject({couponDigests:Wt.record(Wt.uuid(),Di),variables:Wt.record(Cn,Wt.record(Wt.uuid(),Wt.partialRecord(Wt.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),Wt.string()))),locales:Wt.record(Cn,Ii.extend({nodes:Wt.record(Wt.string(),Wt.strictObject({base:P0})),plans:Wt.object({}).strict(),pickers:Wt.object({}).strict()}).omit({paywall:!0}))});import{z as ze}from"zod";import{z as os}from"zod";var hu=os.strictObject({eventsEnabled:os.boolean(),experimentViewsEnabled:os.boolean(),featureUsageEnabled:os.boolean()}),RE=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function Vf(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}import{z as $}from"zod";var gu=$.tuple([$.number().min(0).max(1),$.number().min(0).max(1)]).refine(([e,t])=>e<=t),C0=$.strictObject({attribute:$.string().optional(),seed:$.string(),hashVersion:$.literal(2),ranges:$.array(gu).max(100)}),_0=$.strictObject({id:$.string().min(1).max(255),condition:nn,gate:$.boolean().optional()}),E0=$.strictObject({key:$.string().optional(),name:$.string().optional(),passthrough:$.boolean().optional()}),Lf={condition:nn.optional(),parentConditions:$.array(_0).max(100).optional(),weights:$.array($.number().min(0).max(1)).max(20).optional(),coverage:$.number().min(0).max(1).optional(),hashAttribute:$.string().optional(),fallbackAttribute:$.string().optional(),hashVersion:$.literal(2).optional(),disableStickyBucketing:$.boolean().optional(),bucketVersion:$.number().int().nonnegative().optional(),minBucketVersion:$.number().int().nonnegative().optional(),filters:$.array(C0).max(100).optional(),ranges:$.array(gu).max(20).optional(),meta:$.array(E0).max(20).optional(),seed:$.string().optional(),name:$.string().optional(),phase:$.string().optional()},Fi=$.strictObject({...Lf,key:$.string().min(1).max(255),variations:$.tuple([ve,ve]).rest(ve).refine(e=>e.length<=20),urlPatterns:$.array($.strictObject({include:$.boolean(),type:$.enum(["regex","simple"]),pattern:$.string()})).max(100).optional(),force:$.number().int().nonnegative().optional(),active:$.boolean().optional(),persistQueryString:$.boolean().optional()}),yu=$.strictObject({value:ve,variationId:$.number().int(),key:$.string(),name:$.string().optional(),bucket:$.number().optional(),passthrough:$.boolean().optional(),inExperiment:$.boolean(),hashUsed:$.boolean().optional(),hashAttribute:$.string(),hashValue:$.string(),featureId:$.string().nullable(),stickyBucketUsed:$.boolean().optional()}),R0=$.strictObject({...Lf,id:$.string().max(255).optional(),force:ve.optional(),variations:$.array(ve).min(2).max(20).optional(),key:$.string().optional(),range:gu.optional(),tracks:$.array($.strictObject({experiment:Fi,result:yu})).max(100).optional()}),k0=$.strictObject({defaultValue:ve.optional(),rules:$.array(R0).max(500).optional()}),ko=$.record($.string(),$.union([$.strictObject({type:$.literal("hashed"),attributeKey:$.string(),values:$.array($.string().regex(/^[a-f0-9]{64}$/))}),$.strictObject({type:$.literal("list"),attributeKey:$.string(),values:$.array($.union([$.string(),$.number()]))}),$.strictObject({type:$.literal("condition"),condition:nn})])),Sn=$.strictObject({scope:De,generation:$.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:$.iso.datetime({offset:!0}),expiresAt:$.iso.datetime({offset:!0}).nullable(),features:$.record($.string(),k0),savedGroups:ko,experiments:$.record($.uuid(),Fi)});var jo=Sn.extend({analyticsConfig:hu,remoteFeatures:ze.array(ze.string().min(1).max(255)).max(500)}),Au=jo.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"})}),zf=ze.strictObject({attributes:Pt,features:ze.array(ze.string().min(1).max(255)).max(500).optional(),customerId:ze.uuid().optional()}),j0=ze.strictObject({value:ve,source:ze.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:ze.boolean(),off:ze.boolean(),ruleId:ze.string(),experimentResult:yu.optional()}),as=ze.strictObject({generation:Sn.shape.generation,evaluatedAt:Sn.shape.evaluatedAt,expiresAt:Sn.shape.expiresAt,features:ze.record(ze.string(),j0),merchandiseContext:ze.strictObject({merchandiseId:ze.uuid(),merchandise:Pt}).optional()}),$f=ze.strictObject({customerId:ze.uuid().optional(),events:ze.array(ze.strictObject({eventUuid:ze.uuid(),timestamp:ze.iso.datetime({offset:!0}),name:ze.string().min(1).max(255),merchandise:Cp.optional(),properties:ze.record(ze.string(),ve).default({}),deviceId:ze.string().min(1).max(255).optional(),sessionId:ze.string().min(1).max(255).optional()})).min(1).max(100)}),Gf=ze.strictObject({inserted:ze.number().int().nonnegative(),duplicates:ze.number().int().nonnegative(),rejected:ze.number().int().nonnegative(),skipped:ze.number().int().nonnegative(),analyticsConfig:hu});import{z}from"zod";import{z as T0}from"zod";var Kf=T0.enum(["funnel-run/1","funnel-process/1"]),Hf="funnel-process/1";function bu(e,t=[]){let n=[];Zt(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(La(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 Qf(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>Qf(t)??[])}}function N0(e){let t=e.pages.map(i=>{let a=Qf(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(La({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 Jf(e,t=[]){let n=mn.parse(structuredClone(N0(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=bu(n,t);if(i.length)throw new Error(i.join("; "));return n}import{z as Q}from"zod";import{z as M}from"zod";import{z as ht}from"zod";var ss=ht.strictObject({schemaVersion:ht.literal(1),renderKey:ht.string().min(1).max(256),routeTemplate:ht.string().startsWith("/").max(2048),selectors:ht.array(ht.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:ht.array(ht.number().int().min(0)).min(1),absent:ht.array(ht.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"})}),Zf=ht.strictObject({renderKey:ht.string().min(1).max(256),routeKey:ht.string().min(1).max(256),stateKey:ht.string().min(1).max(256),documentKey:ht.string().min(1).max(256),documentHash:ht.string().regex(/^[a-f0-9]{64}$/),compositionKey:ht.string().min(1).max(256),entryMode:ht.enum(["hard","soft"]),match:ht.strictObject({present:ht.array(ht.number().int().min(0)),absent:ht.array(ht.number().int().min(0))})});import{z as Hr}from"zod";var D0=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],xu="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",F0=Hr.string().regex(new RegExp(`^${xu}/${xu}/${xu}/manifest\\.json$`)),Wf=Hr.strictObject({kind:Hr.literal("gcs-resumable"),url:Hr.url(),bucket:Hr.enum(D0),objectKey:F0,byteLength:Hr.number().int().positive(),expiresAt:Hr.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.string().min(1).max(256),hn=M.string().regex(/^[a-f0-9]{64}$/),cs=M.strictObject({versionId:M.uuid(),manifestDigest:hn,sourceGraphDigest:hn,pageKey:bt,stateKey:bt,documentKey:bt,documentHash:hn,elementKey:bt.optional(),nodeId:bt.optional(),contentHash:hn.optional(),renderKey:bt.optional()}),Yf=M.strictObject({pageKey:bt,documentKey:bt,expectedDocumentHash:hn,renderKey:bt.optional(),nodeId:bt,elementKey:bt,expectedContentHash:hn,property:M.enum(["text","fontSize","color"]),value:M.union([M.string().max(4e3),M.number().finite()])}),Xf=M.strictObject({versionId:M.uuid(),manifestDigest:hn,sourceGraphDigest:hn,pageKey:bt,stateKey:bt,documentKey:bt,documentHash:hn,renderKey:bt.optional(),patches:M.array(Yf.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),M0=/^[a-z][a-z0-9-]{0,39}$/,To=M.string().regex(M0),Iu=M.enum(["web","ios","android"]),XE=M.discriminatedUnion("action",[M.strictObject({action:M.literal("register"),requestId:M.uuid(),client:To,platform:Iu,label:M.string().trim().min(1).max(100),sha256:hn,bytes:M.number().int().min(1),transferBytes:M.number().int().min(1)}),M.strictObject({action:M.literal("complete"),versionId:M.uuid()}),M.strictObject({action:M.literal("current"),versionId:M.uuid(),expectedCurrent:M.uuid().nullable()}),M.strictObject({action:M.literal("delivery"),enabled:M.boolean()}),M.strictObject({action:M.literal("changes"),versionId:M.uuid(),experimentId:M.uuid(),variationId:bt,changesetId:M.uuid().nullable(),expectedRevision:hn.nullable(),editorUrl:M.string().url().max(2048),patches:M.array(Yf).max(200)})]),vu=M.strictObject({id:M.uuid(),projectId:M.uuid(),environmentId:M.uuid(),clientKey:To,platform:Iu,label:M.string(),sha256:hn,bytes:M.number().int().positive(),objectKey:M.string(),state:M.enum(["uploading","ready","rejected"]),isCurrent:M.boolean(),revision:M.number().int().nonnegative(),createdAt:M.string(),expiresAt:M.string(),readyAt:M.string().nullable(),summary:M.record(M.string(),M.json()),routeTree:M.json().nullable(),validation:M.record(M.string(),M.json())}),q0=M.strictObject({key:To,platform:Iu,currentId:M.uuid().nullable()}),eR=M.strictObject({rows:M.array(vu).max(100),nextCursor:M.uuid().nullable(),clients:M.array(q0).max(20)}),Su=M.strictObject({storedBytes:M.number().int().nonnegative(),reservedBytes:M.number().int().nonnegative(),chargedBytes:M.number().int().nonnegative(),versions:M.number().int().nonnegative(),objects:M.number().int().nonnegative(),orphanObjects:M.number().int().nonnegative(),missingReadyObjects:M.number().int().nonnegative(),unknownObjectSizes:M.number().int().nonnegative(),byteLimit:M.number().int().positive(),versionLimit:M.number().int().positive(),remainingBytes:M.number().int().nonnegative()}),tR=M.strictObject({asOf:M.iso.datetime({offset:!0}),reclamation:M.literal("manual-review-required"),buckets:M.strictObject({source:Su,runtime:Su,previews:Su})}),nR=M.strictObject({version:vu,actorId:M.uuid(),claims:M.record(M.string(),M.json())}),rR=M.strictObject({version:vu,upload:Wf.nullable()}),iR=M.object({format:M.literal("indiana-route-state-index"),schemaVersion:M.literal(3),routes:M.array(M.object({routeKey:bt,path:M.string(),documentKey:bt,documentHash:hn,initialStateKey:bt,initialRenderKey:bt})),renders:M.array(Zf)}).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"})}),oR=M.strictObject({rows:M.array(M.object({id:M.uuid(),name:M.string(),status:M.string(),variations:M.array(M.object({id:bt,key:bt,name:M.string().optional()}).loose())}).loose()),limited:M.boolean()}),aR=M.strictObject({enabled:M.boolean(),allowedOrigins:M.array(M.string())});import{z as Mi}from"zod";var eh=Mi.strictObject({id:Mi.uuid(),name:Mi.string().trim().min(1).max(80),client:To,source:cs,event:Mi.enum(["screen_enter","button_click"]),cooldownSeconds:Mi.number().int().min(0).max(2592e3),behavior:Mi.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"})});import{z as Je}from"zod";var wu=ve,U0=["parameters","answers","results","variables"];function Ou(e){return U0.some(t=>e===t||e.startsWith(t+"."))}function Pu(e){let t={};for(let[r,i]of Object.entries(za(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])=>!Ou(r))),variables:t}}import{z as xt}from"zod";var us=xt.discriminatedUnion("kind",[xt.object({kind:xt.literal("ledger"),cursor:Fa}).strict(),xt.object({kind:xt.literal("billing"),cursor:xt.uuid()}).strict()]),B0=xt.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),hr=xt.record(xt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),xt.union([xt.string().max(500),xt.boolean(),xt.array(xt.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),V0=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function Cu(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>Cu(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||V0.test(n)||Cu(r,t+1)))}var L0=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,gr=xt.record(B0,ve).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!Cu(e)&&!L0.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var th=xt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ls=xt.array(xt.object({variable:th,componentId:th,required:xt.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"),AR=xt.object({bindings:ls,answers:hr,values:xt.record(xt.string(),ve).optional()}).strict();import{z as z0}from"zod";var ds=z0.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var _u=Je.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),nh=Je.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),rh=gr.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),Eu=Je.record(_u,Je.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),$0=Vn,ih=Je.strictObject({type:Je.literal("external_task"),endpointId:Je.uuid(),taskKey:_u,inputs:Je.record(_u,$0).refine(e=>Object.keys(e).length<=20),outputs:Eu}),oh=Je.strictObject({maxAttempts:Je.number().int().min(1).max(5),retryDelaySeconds:Je.number().int().min(1).max(30),backoff:Je.enum(["fixed","exponential"]),requestTimeoutSeconds:Je.number().int().min(1).max(10),timeoutSeconds:Je.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var _R=Je.strictObject({outcome:Je.enum(["success","failure"]),data:rh});var ER=Je.discriminatedUnion("operation",[Je.strictObject({operation:Je.literal("signal"),runId:Je.uuid(),nodeId:nh,eventName:ds,eventId:Je.uuid(),data:rh}),Je.strictObject({operation:Je.literal("read_results"),runId:Je.uuid()})]),RR=Je.strictObject({scope:De,runId:Je.uuid(),eventId:Je.uuid(),accepted:Je.boolean()}),G0=Je.record(nh,wu),kR=Je.strictObject({scope:De,runId:Je.uuid(),results:G0});var Dn={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},ah="00000000-0000-0000-0000-000000000000";import{z as Z}from"zod";import{z as tt}from"zod";var MR=tt.enum(["local","remote"]),Ru=tt.strictObject({port:tt.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:ve.optional(),sticky:tt.array(tt.strictObject({expected:uo.nullable(),next:uo})).max(100),exposures:tt.array(ve).max(100),features:tt.array(ve).max(100)}),sh=tt.strictObject({type:tt.literal("evaluate"),receiptId:tt.uuid(),environmentId:tt.uuid(),policyRevision:tt.number().int().nonnegative(),attributes:Pt,sticky:tt.record(tt.string(),uo)}),ch=sh.extend({runId:tt.uuid(),versionId:tt.uuid(),nodeId:tt.string().min(1).max(64),visit:tt.number().int().nonnegative(),revision:tt.number().int().nonnegative()}),ku=sh.omit({type:!0,receiptId:!0}).extend({type:tt.literal("evaluate_segment")}),uh=tt.strictObject({nodeId:tt.string().min(1).max(64),result:Ru}),lh=ku.extend({runId:tt.uuid(),versionId:tt.uuid(),nodeId:tt.string().min(1).max(64),visit:tt.number().int().nonnegative(),revision:tt.number().int().nonnegative(),parameters:gr,answers:hr,variables:tt.record(tt.string(),ve)});import{z as ue}from"zod";var ju=ue.array(ue.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"),ps=ue.intersection(Pt,ue.looseObject({tags:ju.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),ms=ue.string().trim().max(80),fs=ue.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),hs=ue.union([ue.email().max(254),ue.literal("")]),gs=ue.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),dh=ue.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),ph=ue.object({externalUserId:dh.optional(),name:ms.default(""),email:hs.default(""),phone:fs.optional(),attributes:ps.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),Qr=ue.discriminatedUnion("type",[ue.strictObject({type:ue.literal("id"),value:ue.uuid()}),ue.strictObject({type:ue.literal("externalUserId"),value:dh})]),qi=ue.strictObject({name:ms.optional(),email:hs.optional(),phone:fs.optional(),attributes:ps.optional(),fingerprint:gs.optional()}),ys=e=>!e.customerData||e.customer?.type==="externalUserId",As="customerData requires an externalUserId customer",Ui=ue.object({id:ue.uuid(),externalUserId:ue.string().min(1).max(255).nullable(),name:ms,email:hs,phone:fs.optional(),attributes:ps,createdAt:ue.iso.datetime()}).strict(),mh=ue.object({customer:Ui,changed:ue.boolean(),replayed:ue.boolean()}).strict(),K0=ue.discriminatedUnion("type",[ue.object({type:ue.literal("id"),value:ue.uuid()}).strict(),ue.object({type:ue.literal("externalUserId"),value:ue.string().trim().min(1).max(255)}).strict()]),H0=ue.object({name:ms.optional(),email:hs.optional(),phone:fs.optional(),attributes:ps.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:ue.array(ue.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:ue.strictObject({add:ju,remove:ju}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),Tu=ue.object({lookup:K0}).strict(),fh=Tu.extend({requestId:ue.uuid(),patch:H0}).strict(),hh=ue.object({search:ue.string().trim().max(200).default(""),tag:ue.string().trim().max(40).default(""),planId:ue.string().max(200).default(""),versionId:ue.string().max(200).default(""),holdingStatus:ue.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:ue.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:ue.union([ue.iso.datetime(),ue.literal("")]).default(""),createdUntil:ue.union([ue.iso.datetime(),ue.literal("")]).default(""),offset:ue.coerce.number().int().min(0).max(1e5).default(0),limit:ue.coerce.number().int().min(1).max(100).default(50)}).strict(),gh=ue.object({customers:Ui.array(),hasMore:ue.boolean(),total:ue.number().int().nonnegative().nullable(),evaluatedAt:ue.iso.datetime()}).strict();var No=Z.discriminatedUnion("type",[Z.strictObject({type:Z.literal("literal"),value:ve}),Z.strictObject({type:Z.literal("variable"),key:wt,path:Nn.optional()}),Z.strictObject({type:Z.literal("feature"),featureKey:Z.string().min(1).max(128)})]),Q0=Z.strictObject({requestId:Z.uuid(),decisionId:Z.uuid(),customerId:Z.uuid(),externalUserId:Z.string().min(1).max(255).nullable(),versionId:Z.uuid(),receiptId:Z.uuid(),value:ve}),J0={funnelId:Z.uuid(),requestId:Z.uuid(),customer:Qr,customerData:qi.optional(),attributes:Pt.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},JR=Z.discriminatedUnion("operation",[Z.strictObject({operation:Z.literal("decide"),...J0}).refine(ys,As),Z.strictObject({operation:Z.literal("read_decision"),decisionId:Z.uuid()}),Z.strictObject({operation:Z.literal("evaluate_decision"),decisionId:Z.uuid(),requestId:Z.uuid(),nodeId:Z.string().min(1).max(64),visit:Z.number().int().nonnegative(),revision:Z.number().int().nonnegative(),receiptId:Z.uuid(),policyRevision:Z.number().int().nonnegative(),generation:Z.string().min(1).max(256),result:Ru}),Z.strictObject({operation:Z.literal("feature_config"),funnelId:Z.uuid()}),Z.strictObject({operation:Z.literal("commit_decision_segment"),decisionId:Z.uuid(),requestId:Z.uuid(),nodeId:Z.string().min(1).max(64),visit:Z.number().int().nonnegative(),revision:Z.number().int().nonnegative(),policyRevision:Z.number().int().nonnegative(),generation:Z.string().min(1).max(256),steps:Z.array(uh).max(32),boundary:Z.strictObject({nodeId:Z.string().min(1).max(64),visit:Z.number().int().nonnegative()}).optional()}),Z.strictObject({operation:Z.literal("segment_configuration"),funnelId:Z.uuid(),versionId:Z.uuid()}),Z.strictObject({operation:Z.literal("configuration"),funnelId:Z.uuid(),versionId:Z.uuid().optional()}),Z.strictObject({operation:Z.literal("local_configuration"),funnelId:Z.uuid()}),Z.strictObject({operation:Z.literal("report_used"),decisionId:Z.uuid(),eventId:Z.uuid(),occurredAt:Z.iso.datetime({offset:!0}),reference:Z.string().min(1).max(128).optional()})]),ZR=Z.strictObject({scope:De,decisionId:Z.uuid(),requestId:Z.uuid(),status:Z.enum(["pending","completed","failed"]),decision:Q0.nullable(),evaluation:Z.discriminatedUnion("type",[ch,lh]).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"),WR=Z.strictObject({scope:De,decisionId:Z.uuid(),eventId:Z.uuid(),source:Z.literal("caller_reported")});import{z as Lt}from"zod";var yh=Lt.strictObject({type:Lt.literal("bundle"),paywall:Vn.optional(),offering:Vn.optional(),coupons:Vn,data:Vn}),Z0=e=>Lt.strictObject({type:Lt.literal(e),id:Lt.uuid()}),rk=Lt.strictObject({type:Lt.literal("bundle"),paywallVersionId:Lt.uuid().optional(),offeringVersionId:Lt.uuid().optional(),couponIds:Lt.array(Lt.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:ve});var ik=Lt.strictObject({type:Lt.literal("bundle"),offering:Z0("offering_version").nullable(),paywall:Lt.strictObject({versionId:Lt.uuid(),paywallId:Lt.uuid(),offeringVersionId:Lt.uuid()}).nullable(),coupons:Lt.array(lo).max(20),data:ve});import{z as Fn}from"zod";import{z as In}from"zod";var Ah=In.union([In.string(),In.number().finite(),In.boolean(),In.null()]),W0=In.union([Ah,In.array(Ah).min(1).max(20)]),Y0=In.record(Nn,W0).refine(e=>Object.keys(e).length<=10),bh=In.strictObject({path:Nn,type:In.enum(["string","number","boolean","strings"]),nullable:In.boolean().optional(),aggregation:In.enum(["count","exists"]).optional(),where:Y0.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 X0=["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"],xh=Fn.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),eI=Vn,Sh=Fn.discriminatedUnion("type",[ih,Fn.strictObject({type:Fn.literal("claim_offer"),coupon:Vn}),Fn.strictObject({type:Fn.literal("event"),event:xh}),Fn.strictObject({type:Fn.literal("api"),operation:Fn.enum(X0),inputs:Fn.record(Nn,eI).refine(e=>Object.keys(e).length<=40),outputs:Fn.record(xh,bh).refine(e=>Object.keys(e).length<=20)})]);var dt=ds,tI=Q.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),gn={id:dt,name:Q.string().trim().min(1).max(80),position:Q.strictObject({x:Q.number().finite(),y:Q.number().finite()}).optional()},nI={success:dt,cancel:dt,unavailable:dt,failure:dt},Nu=Q.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),Du=Q.enum(["same_window","new_window"]),rI=Q.discriminatedUnion("type",[Q.strictObject({...gn,type:Q.literal("entry"),next:dt,triggers:Q.array(eh).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),Q.strictObject({...gn,type:Q.literal("screen"),screenId:dt,presentation:kn,outputs:Q.record(dt,dt),offering:Q.discriminatedUnion("source",[Q.strictObject({source:Q.literal("variable"),key:wt}),Q.strictObject({source:Q.literal("fixed"),versionId:Q.uuid()})]).optional()}),Q.strictObject({...gn,type:Q.literal("offering"),configuration:Q.discriminatedUnion("source",[Q.strictObject({source:Q.literal("fixed"),versionId:Q.uuid()}),Q.strictObject({source:Q.literal("feature"),featureKey:Q.string().min(1).max(128)})]),writes:Q.strictObject({value:wt}),next:dt}),Q.strictObject({...gn,type:Q.literal("coupon"),couponId:Q.uuid(),writes:Q.strictObject({value:wt}),next:dt}),Q.strictObject({...gn,type:Q.literal("coupons"),couponIds:Q.array(Q.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:Q.strictObject({value:wt}),next:dt}),Q.strictObject({...gn,type:Q.literal("output"),value:Q.discriminatedUnion("type",[...No.options,yh,Q.strictObject({type:Q.literal("selection"),screenId:dt,offeringKey:wt})])}),Q.strictObject({...gn,type:Q.literal("condition"),cases:Q.array(Q.strictObject({condition:nn,target:dt})).min(1).max(50),default:dt}),Q.strictObject({...gn,type:Q.literal("feature"),featureKey:Q.string().min(1).max(128),writes:Q.strictObject({value:wt}),next:dt}),Q.strictObject({...gn,type:Q.literal("split"),experimentId:Q.uuid(),applyPageExperiment:Q.literal(!0).optional(),routes:Q.record(tI,dt).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:dt}),Q.strictObject({...gn,type:Q.literal("action"),...nI,execution:oh,action:Sh,writes:Zc.optional()}),Q.strictObject({...gn,type:Q.literal("external_page"),appManifest:cs.optional(),url:Nu,openIn:Du,opened:dt,failed:dt}),Q.strictObject({...gn,type:Q.literal("end"),outcome:Q.enum(["completed","closed","ineligible","failed"]),output:No.optional()}),Q.strictObject({...gn,type:Q.literal("wait"),writes:Zc.optional(),wait:Q.discriminatedUnion("type",[Q.strictObject({type:Q.literal("duration"),delaySeconds:Q.number().int().min(1).max(2592e3),elapsed:dt}),Q.strictObject({type:Q.literal("event"),eventName:dt,outputs:Eu,timeoutSeconds:Q.number().int().min(1).max(2592e3),received:dt,timeout:dt})])})]),Fu=Q.strictObject({version:Q.literal(5),entry:dt,nodes:Q.array(rI).min(1).max(Dn.flowNodes)}),Mu=Fu.superRefine((e,t)=>{iI(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function bs(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 iI(e,t){let n=[],r=new Map(e.nodes.map(l=>[l.id,l])),i=(l,p,m)=>{n.push(l),t?.({message:l,reason:p,path:m?["nodes",e.nodes.indexOf(m)]:[]})};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>Dn.pages||e.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>Dn.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let l of e.nodes){for(let p of bs(l))p===e.entry&&i("An entry cannot be a transition target","entryTarget",l),r.has(p)||i(`Missing target ${p}`,"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 p of bs(r.get(l)))u(p);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 qu={maxTransitions:1e4,runTimeoutSeconds:2592e3};function Ih(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 lr(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]}import{z as q}from"zod";var Bi=q.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),xs=e=>q.record(q.string(),ve).refine(t=>fn(t)<=e,"Funnel evidence exceeds its byte budget"),Dk=q.enum(["local_segment","evaluation","presentation","timer","event","operation"]),Bu=q.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Vu=q.discriminatedUnion("type",[q.strictObject({type:q.literal("flag"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("experiment"),id:q.uuid()}),q.strictObject({type:q.literal("saved_group"),id:q.uuid()}),q.strictObject({type:q.literal("config"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("constant"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("paywall_version"),id:q.uuid()}),q.strictObject({type:q.literal("offering_version"),id:q.uuid()}),q.strictObject({type:q.literal("reward"),id:q.uuid()})]),Do=q.strictObject({schemaVersion:q.literal(1),kind:Bu,selector:Vu.nullable(),context:xs(131072),contract:q.strictObject({version:q.number().int().positive(),evaluator:q.string().min(1).max(128),policyRevision:q.number().int().nonnegative()})}).refine(e=>fn(e)<=131072,"Node input exceeds its byte budget"),vh=q.strictObject({schemaVersion:q.literal(1),kind:Bu,outcome:q.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:xs(131072),route:q.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:xs(131072)}).refine(e=>fn(e)<=131072,"Node result exceeds its byte budget"),Fk=q.strictObject({schemaVersion:q.literal(1),operations:q.record(Bi,q.strictObject({attempts:q.number().int().nonnegative(),maxAttempts:q.number().int().min(1).max(5),deadlineAt:q.iso.datetime({offset:!0}),retryAt:q.iso.datetime({offset:!0}).nullable(),error:q.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:q.strictObject({type:Bi,id:q.uuid()}).nullable()}))}).refine(e=>fn(e)<=65536,"Execution state exceeds its byte budget"),Jr={receiptId:q.uuid()},Uu=q.iso.datetime({offset:!0}),Mk=q.discriminatedUnion("type",[q.strictObject({type:q.literal("node_entered"),details:q.strictObject({kind:Bu})}),q.strictObject({type:q.literal("presentation_shown"),details:q.strictObject({...Jr,source:q.literal("client"),occurredAt:Uu.optional()})}),q.strictObject({type:q.literal("decision_accepted"),details:q.strictObject(Jr)}),q.strictObject({type:q.literal("signal_received"),details:q.strictObject({signalId:q.uuid(),nodeId:Bi,eventName:Bi,data:xs(8192),source:q.literal("server"),occurredAt:Uu})}),q.strictObject({type:q.literal("signal_consumed"),details:q.strictObject({...Jr,signalId:q.uuid()})}),q.strictObject({type:q.literal("wait_elapsed"),details:q.strictObject(Jr)}),q.strictObject({type:q.literal("wait_timeout"),details:q.strictObject(Jr)}),q.strictObject({type:q.literal("operation_completed"),details:q.strictObject({...Jr,operation:Bi,reference:q.strictObject({type:Bi,id:q.uuid()}).nullable()})}),q.strictObject({type:q.literal("execution_recovered"),details:q.strictObject({generation:q.number().int().positive(),reason:q.enum(["interrupted","expired_lease","delivery_failed"])})}),q.strictObject({type:q.literal("execution_failed"),details:q.strictObject({generation:q.number().int().positive(),code:q.string().regex(/^[a-z_]{1,64}$/)})}),q.strictObject({type:q.literal("run_completed"),details:q.strictObject({outcome:q.enum(["completed","ineligible","failed"])})}),q.strictObject({type:q.literal("run_closed"),details:q.strictObject({source:q.enum(["client","server","expiry"])})}),q.strictObject({type:q.literal("treatment_used"),details:q.strictObject({...Jr,source:q.enum(["client","server"]),occurredAt:Uu,reference:q.string().min(1).max(128).optional()})})]);var vn=z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),oI=z.discriminatedUnion("type",[z.strictObject({id:vn,type:z.literal("owned"),publicData:Bf.optional(),document:mn.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")}),z.strictObject({id:vn,type:z.literal("paywall"),paywallVersionId:z.uuid()})]),Lu={executionContract:Kf.optional(),kind:z.literal("funnel"),schemaVersion:z.literal(4),screens:z.array(oI).max(Dn.pages),references:z.record(vn,Vu).refine(e=>Object.keys(e).length<=500),inputs:z.array(z.strictObject({variable:vn,screenId:vn,componentId:vn,required:z.boolean()})).max(Dn.questions),variables:z.record(wt,Oi).refine(e=>Object.keys(e).length<=Dn.logicNodes),outputSchema:wi,execution:z.strictObject({runTimeoutSeconds:z.number().int().min(1).max(qu.runTimeoutSeconds),maxTransitions:z.number().int().min(1).max(qu.maxTransitions)})},rj=z.strictObject({...Lu,graph:Fu});function aI(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 Is(e){return Array.isArray(e)?e.some(Is):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===ah:Is(n))}function sI(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=Jf(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&&!_o(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}),aI(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"&&Is(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&Is(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function wh(e,t){for(let{message:n,reason:r,path:i}of sI(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function Oh(e,t){let n=(h,d,g=[])=>t.addIssue({code:"custom",message:h,path:g,params:{reason:d}}),r=Object.values(e.references),i=new Map(e.screens.map(h=>[h.id,h])),a=(h,d)=>r.some(g=>g.type===h&&("id"in g?g.id:g.key)===d);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let o=e.graph.nodes.filter(h=>h.type==="screen");(o.length!==i.size||o.some(h=>!i.has(h.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(h=>c.some(d=>h!==d&&d.startsWith(h+".")))&&n("Variable paths must not overlap","variable");function u(h,d){Object.hasOwn(e.variables,h)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(d)]);let g=s.get(h)??new Set;g.add(d.id),s.set(h,g)}for(let[h,d]of e.graph.nodes.entries()){let g=["graph","nodes",h],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",g);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",g);for(let[v,C]of Object.entries(A)){u(C,d);let j=e.variables[C],_=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",g)}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",g);for(let C of d.couponIds)a("reward",C)||n("Coupons require Reward references","coupon",g)}if(d.type==="split"&&!a("experiment",d.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",g),d.type==="coupon"&&!a("reward",d.couponId)&&n("Coupon selectors require a Reward reference","coupon",g),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",g)}if(d.type==="offering"&&d.configuration.source==="fixed"&&!a("offering_version",d.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",g),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",g),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",g),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",g),v?.type==="paywall"&&d.offering&&n("Paywall owns its fixed Offering Version","offering",g),v?.type==="paywall"&&!a("paywall_version",v.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",g),v?.type==="owned"){let C=v.document.pages[0];if(!C){n("Owned screen requires a page","screen",g);continue}mr(v.document).some(_=>!_.complete)&&n("Owned screens require complete local content","translations",g);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",g),tr(C.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",g),_.type==="customer_data"&&Object.values(_.data.outputs??{}).some(X=>X!==void 0&&!j.has(X))&&n("Customer components require declared screen outcomes","componentOutput",g)})}}d.type==="end"&&["completed","ineligible"].includes(d.outcome)&&!d.output&&n("Completed and ineligible ends require a declared output","output",g),d.type==="end"&&d.output?.type==="literal"&&!xn(e.outputSchema,d.output.value)&&n("Terminal output does not match outputSchema","output",g),d.type==="output"&&d.value.type==="literal"&&!xn(e.outputSchema,d.value.value)&&n("Terminal output does not match outputSchema","output",g);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&&!Wc(v,e.outputSchema)&&n("Variable output does not match outputSchema","output",g)}if(d.type==="screen"){let v=i.get(d.screenId);if(v?.type==="owned")for(let C of eu(v.document))(/^(input|params)\./.test(C)||C.startsWith("variables.")&&!Xc(C.slice(10),c))&&n("Screen values must reference registered variables","variable",g)}if(d.type==="condition")for(let v of d.cases){for(let C of Yn(v.condition))a("saved_group",C)||n("Conditions require explicit Saved Group references","savedGroup",g);for(let C of lr(v.condition))C.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",g)}if(d.type==="output"&&d.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",g);for(let[v,C]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=>!xn({type:C,nullable:!1},X)||!a(C,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",[...g,"value",v])}else{let _=e.variables[j.key];(j.path||!_||_.nullable||(v==="coupons"?_.type!=="array"||_.items?.type!=="reward"||_.items.nullable:_.type!==C))&&n("Bundle binding type does not match its slot","output",g)}}}}for(let[h,d]of e.graph.nodes.entries()){let g=d.type==="screen"?i.get(d.screenId):void 0,R=[...Ih(d,c),...g?.type==="owned"?$a(g.document).map(y=>Xc(y,c)?.key??y):[]];for(let y of new Set(R)){let C=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]:[]:bs(_)).some(C):!1};var m=C;if(!Object.hasOwn(e.variables,y)){n("Consumed variable is undeclared","variable",["graph","nodes",h]);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||C(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",h])}}(new Set(e.inputs.map(h=>h.variable)).size!==e.inputs.length||new Set(e.inputs.map(h=>`${h.screenId}:${h.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[h,d]of e.inputs.entries()){e.variables[d.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",h]);let g=i.get(d.screenId),R=g?.type==="owned"?_o(g.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",h]),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",h]);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",h])}}for(let[h,d]of Object.entries(e.variables))d.enum&&d.type!=="string"&&n("Only string variables support enum","variable",["variables",h]),d.source.type==="input"&&!e.inputs.some(g=>g.variable===h)&&n("Input variable requires a component binding","inputBinding",["variables",h]);let l=0,p=0;for(let h of e.screens)if(h.type==="owned"){for(let d of h.document.pages)tr(d.root,()=>{l++});p+=h.document.actions.length}(l>Dn.components||p>Dn.actions||fn(e)>Dn.documentBytes)&&n("Funnel document exceeds its budget","budget")}var cI=z.strictObject({...Lu,graph:Mu}).superRefine(Oh),Vi=z.strictObject({...Lu,graph:Mu,displayName:z.string().trim().min(1).max(80)}).superRefine(Oh),ij=Vi.superRefine(wh),oj=cI.superRefine(wh),Ss=z.string().regex(Ft),Fo={requestId:z.uuid(),nodeId:vn,visit:z.number().int().nonnegative(),revision:z.number().int().nonnegative(),customerToken:Ss.optional()},uI=z.discriminatedUnion("type",[z.strictObject({type:z.literal("screen"),output:vn,answers:hr,selection:z.record(vn,z.union([z.string().max(200),z.boolean(),z.number().int().min(0).max(1e4)])).optional()}),z.strictObject({type:z.literal("paywall_quote"),featureQuantities:z.record(z.uuid(),z.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100).optional(),actionId:vn,productVersionId:z.uuid(),offerId:z.uuid().optional(),nativeOffer:_i.optional(),predecessor:z.strictObject({operationId:z.uuid().nullable(),generation:z.number().int().positive()}).optional()}),z.strictObject({type:z.literal("paywall_confirm"),operationId:z.uuid()}),z.strictObject({type:z.literal("paywall_cancel"),operationId:z.uuid()}),z.strictObject({type:z.literal("client_action"),receiptId:z.uuid(),outcome:z.enum(["success","cancel","failure","opened","failed"])})]),lI=z.object({nodeId:vn,visit:z.number().int().nonnegative(),revision:z.number().int().nonnegative(),components:z.record(vn,z.object({resourceKey:z.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:z.number().int().min(1).max(1e5),after:us.nullable(),filter:z.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),Ct=z.discriminatedUnion("operation",[z.strictObject({operation:z.literal("start"),funnelId:z.uuid(),requestId:z.uuid(),customer:Qr.optional(),customerData:qi.optional(),locale:z.string().min(1).max(35),parameters:gr}).refine(ys,As),z.strictObject({operation:z.literal("get"),settlementRequestId:z.uuid().optional(),data:lI.optional(),purchase:z.strictObject({receiptId:z.uuid(),operationId:z.uuid()}).optional(),customerToken:Ss.optional()}),z.strictObject({operation:z.literal("resume"),requestId:z.uuid(),customerToken:Ss.optional()}),z.strictObject({operation:z.literal("submit"),...Fo,input:uI}),z.strictObject({operation:z.literal("back"),...Fo}),z.strictObject({operation:z.literal("shown"),...Fo}),z.strictObject({operation:z.literal("close"),...Fo}),z.strictObject({operation:z.literal("commit_segment"),...Fo,policyRevision:z.number().int().nonnegative(),generation:z.string().min(1).max(256)}),z.strictObject({operation:z.literal("review"),receiptId:z.uuid().optional(),customerToken:Ss.optional()})]);function vs(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 g of Yn(d))l(g)}function l(d){if(i.has(d)||!Object.hasOwn(t.savedGroups,d))return;let g=t.savedGroups[d];g&&(i.add(d),c.set(d,g),a.push(()=>{!Array.isArray(g)&&g.type==="condition"&&u(g.condition)}))}function p(d){for(let g of["hashAttribute","fallbackAttribute"])if(d[g]!==void 0&&Ou(d[g]))throw new Error(`Funnel GB ${g} uses a reserved flow namespace`);u(d.condition);for(let g of d.parentConditions??[])m(g.id),u(g.condition)}function m(d,g=!1){let R=Object.hasOwn(t.features,d)?t.features[d]:void 0;if(!R){if(g)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??[]){p(y);for(let A of y.tracks??[])p(A.experiment)}}))}function h(d){let g=Object.hasOwn(t.experiments,d)?t.experiments[d]:void 0;if(!g)throw new Error("Required GB Experiment is unavailable");r.has(d)||(r.add(d),s.set(d,g),a.push(()=>p(g)))}for(let d of e.graph.nodes){d.type==="feature"&&m(d.featureKey,!0),d.type==="split"&&h(d.experimentId),d.type==="condition"&&d.cases.forEach(R=>u(R.condition)),d.type==="offering"&&d.configuration.source==="feature"&&m(d.configuration.featureKey,!0);let g=d.type==="output"?d.value:d.type==="end"?d.output:null;g?.type==="feature"&&m(g.featureKey,!0)}for(let d of a)d();return{...t,features:Object.fromEntries(o),experiments:Object.fromEntries(s),savedGroups:Object.fromEntries(c)}}import{z as ae}from"zod";function Ph(e,t){let n=[],r={};Zt(e,i=>{if(i.hidden)return!1;if(i.type!=="quantity_picker")return;let a=i.bind?.plan?[i.bind.plan]:[];i.bind?.picker&&Zt(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 Ch(e,t,n,r){let i=r.plans[t];if(!i?.available)throw new Error("Selected Product is unavailable");let a={};if(Zt(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}import{z as Mo}from"zod";var _h=Mo.object({defaultLocale:Cn,locales:Mo.record(Cn,Mo.object({name:Mo.string().max(80),description:Mo.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 dI=["customer_data","coupon_code"],Eh=ae.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),pI=ae.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),ws=(e,t)=>new Set(e.map(t)).size===e.length,mI=ae.strictObject({currency:Ie,amountMinor:ae.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),fI=ae.strictObject({featureId:ae.uuid(),name:ae.string().trim().min(1).max(120),allowance:ae.string().max(40).nullable(),access:ae.boolean()}),hI=ae.strictObject({stripe:ae.strictObject({prices:ae.array(mI).min(1).max(50)}).optional(),apple:ae.strictObject({productIds:ae.array(Eh).min(1).max(10)}).optional(),google:ae.strictObject({products:ae.array(ae.strictObject({productId:Eh,basePlanId:pI.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!ws(e.stripe.prices,n=>n.currency)||e.apple&&!ws(e.apple.productIds,n=>n)||e.google&&!ws(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),gI=ae.strictObject({name:ae.string().trim().min(1).max(80),interval:ae.enum(["free","week","month","year","one_time"]),intervalCount:ae.number().int().min(1).max(100),trial:ae.strictObject({days:ae.number().int().min(1).max(730),cardRequired:ae.boolean()}).nullable(),benefits:ae.array(fI).max(50).refine(e=>ws(e,t=>t.featureId),"Duplicate benefit"),channels:hI,prepaid:ae.array(wo).max(100).optional()}),yI=ae.strictObject({digest:Di,content:ae.strictObject({discount:dr,duration:dn,appliesTo:Nc,displayCopy:_h.nullable(),firstPurchaseOnly:ae.boolean(),qualificationRequired:ae.boolean(),startsAt:ae.iso.datetime().nullable(),endsAt:ae.iso.datetime().nullable(),grantWindowHours:ae.number().int().positive(),perCustomerLimit:ae.number().int().positive()})}),AI=ae.discriminatedUnion("type",[ae.strictObject({type:ae.literal("checkout"),product:Va}),ae.strictObject({type:ae.literal("close")}),ae.strictObject({type:ae.literal("action"),action:fu})]),Os=ae.strictObject({kind:ae.literal("paywall"),formatVersion:ae.literal(1),name:ae.string().trim().min(1).max(80),offeringVersionId:ae.uuid(),presentation:kn,screen:mn,products:is,catalog:ae.record(ae.uuid(),gI),buttons:ae.record(Ve,AI),coupons:ae.record(ae.uuid(),yI)}).superRefine((e,t)=>{let n=g=>t.addIssue({code:"custom",message:g}),{screen:r}=e;Ph(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),bu(r,dI).forEach(n),mr(r).some(g=>!g.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,o=new Set;Zt(r,g=>{let R="bind"in g?g.bind:void 0;R?.promotionCode&&n("Promotion codes must not be published"),R?.plan&&i.add(R.plan),R?.coupon&&a.add(R.coupon),g.type==="plan_picker"&&(g.planIds?.forEach(y=>i.add(y)),g.defaultPlan&&i.add(g.defaultPlan)),g.type==="text"&&g.feature&&o.add(g.feature.id)});let s=e.products.items.map(g=>g.productVersionId),c=Object.keys(e.catalog);(s.length!==c.length||s.some(g=>!Object.hasOwn(e.catalog,g)))&&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 g of i)u.has(g)||n("Screen references a Product that is not displayed");for(let g of Object.values(e.catalog))!g.channels.stripe&&!g.channels.apple&&!g.channels.google&&n("A displayed Product needs at least one sales channel");let l=new Set(Object.values(e.catalog).flatMap(g=>g.benefits.map(R=>R.featureId)));for(let g of o)l.has(g)||n("Feature text must read a displayed benefit");let p=r.actions.filter(g=>g.type!=="navigate");r.actions.some(g=>g.type!=="event"&&g.type!=="navigate")&&n("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==p.length||p.some(g=>!Object.hasOwn(e.buttons,g.id)))&&n("Buttons must match the screen's actions");let h=!1;for(let g of Object.values(e.buttons)){if(g.type!=="checkout")continue;h=!0,(g.product.type==="fixed"?[g.product.productVersionId]:g.product.allowedProductVersionIds).some(y=>!u.has(y))&&n("Checkout may only sell displayed Products")}h||n("A Paywall needs a checkout button");let d=Object.keys(e.coupons);(d.length!==a.size||d.some(g=>!a.has(g)))&&n("Coupons must be exactly the bound Coupons")}),Rh=ae.strictObject({state:ae.enum(["published","archived"]),controlRevision:ae.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:ae.uuid(),versions:ae.record(ae.uuid(),ae.strictObject({version:ae.number().int().positive(),artifact:ae.string().min(1),sourceDigest:ae.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var sn={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},zu=Re.string().regex(/^[a-f0-9]{64}$/),$u=Re.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Ku=De.extend({environmentId:Re.uuid()}),kh=Re.strictObject({features:Re.array(Re.string()).max(500),experiments:Re.record(Re.uuid(),Re.array(Re.string()).max(20)),savedGroups:Re.array(Re.string()).max(1e3)}),Hu=Re.strictObject({kind:Re.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:Re.number().int().positive(),url:Re.string().min(1).max(2048),sha256:zu,byteLength:Re.number().int().positive().max(sn.maxArtifactBytes),generation:zu.optional()}),bI=Re.strictObject({state:Re.enum(["active","paused","archived"]),controlRevision:$u,evaluationMode:Re.enum(["local","remote"]),evaluationRevision:$u,currentVersionId:Re.uuid(),versions:Re.record(Re.uuid(),Re.strictObject({artifact:Re.string(),dependencies:kh,definitionDigest:Di.optional(),couponDigests:Re.record(Re.uuid(),Di).optional()}))}),Qu=Re.strictObject({kind:Re.literal("sdk_configuration"),schemaVersion:Re.literal(1),scope:Ku,revision:$u,generation:zu,policy:Re.strictObject({refreshIntervalSeconds:Re.number().positive().max(15),maxControlAgeSeconds:Re.number().positive().max(60)}),gb:Re.strictObject({features:Re.string().nullable(),pageExperiments:Re.string().nullable()}),artifacts:Re.record(Re.string(),Hu),funnels:Re.record(Re.uuid(),bI),paywalls:Re.record(Re.uuid(),Rh).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 _t(e){if(Array.isArray(e))return`[${e.map(_t).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)}:${_t(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function Ju(e){return rr(or(typeof e=="string"?new TextEncoder().encode(e):e))}function jh(e){return Ju(_t(e))}var Gu=class extends Error{constructor(n,r){super(n);Be(this,"dependency",r)}};function Th(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,p)=>e.graph.nodes.find(m=>l==="experiment"?m.type==="split"&&m.experimentId===p:l==="feature"&&n(m)===p)?.name,i=(l,p,m=r(p.type,p.resource))=>new Gu(l,{...p,...m?{step:m}:{}});for(let l of Object.values(e.references)){let p=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(p)throw i("Funnel dependency is absent from GB public delivery",{reason:"unavailable",...p})}let a=vs(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),o=new Set(t.remoteFeatures);for(let l of e.graph.nodes){let p=n(l);if(!p)continue;let m=a.features[p],h=l.type==="feature"?e.variables[l.writes.value]:e.outputSchema,d={type:"feature",resource:p};if(!m||!h)throw i("Required public Feature declaration is unavailable",{reason:"unavailable",...d},l.name);if([m.defaultValue,...(m.rules??[]).flatMap(R=>[...Object.hasOwn(R,"force")?[R.force]:[],...R.variations??[],...(R.tracks??[]).flatMap(y=>y.experiment.variations)])].some(R=>R===void 0||!xn(h,R)))throw i("GB Feature values violate the Funnel type contract",{reason:"value_type",...d},l.name)}let s=new Set,c=(l,p)=>{for(let m of Yn(l)){if(s.has(m))continue;let h=t.savedGroups[m];if(!h)throw i("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:m},p);s.add(m),!Array.isArray(h)&&h.type==="condition"&&c(h.condition,p)}},u=(l,p)=>{if(o.has(l)||!t.features[l])throw i("Local Funnel requires public Local prerequisites",{reason:"unavailable",type:"feature",resource:l},p)};for(let l of e.graph.nodes)if(l.type==="condition")for(let p of l.cases)c(p.condition,l.name);for(let[l,p]of Object.entries(a.features)){let m=r("feature",l);for(let h of p.rules??[]){c(h.condition,m);for(let d of[...h.parentConditions??[],...(h.tracks??[]).flatMap(g=>g.experiment.parentConditions??[])])u(d.id,m),c(d.condition,m);for(let d of h.tracks??[])c(d.experiment.condition,m)}}for(let[l,p]of Object.entries(a.experiments)){let m=r("experiment",l);c(p.condition,m);for(let h of p.parentConditions??[])u(h.id,m),c(h.condition,m)}for(let l of e.graph.nodes)if(l.type==="split"){let p=a.experiments[l.experimentId],m={type:"experiment",resource:l.experimentId};if(!p)throw i("Local Funnel requires a public Experiment",{reason:"unavailable",...m},l.name);for(let h of p.variations)if(typeof h!="string"||!Object.hasOwn(l.routes,h))throw i("Experiment variation has no declared Funnel route",{reason:"variation_route",...m},l.name)}return kh.parse({features:Object.keys(a.features).sort(),experiments:Object.fromEntries(Object.entries(a.experiments).map(([l,p])=>[l,p.variations.map(String)])),savedGroups:[...s].sort()})}function Nh(e){return Vi.parse(e)}var Dh=Et.strictObject({processContext:Ha.optional(),...Ci,selector:Et.discriminatedUnion("type",[Et.strictObject({type:Et.literal("paywall"),paywallId:Et.uuid()}),Et.strictObject({type:Et.literal("version"),versionId:Et.uuid()})]),customerId:Et.uuid().optional(),commerce:fi,locale:Et.string().min(1).max(35),requirement:Pn.optional()}),qo=Et.strictObject({id:Et.uuid(),paywallId:Et.uuid(),version:Et.number().int().positive(),document:Ni.omit({requirement:!0,offeringId:!0}),offering:Et.strictObject({id:Et.uuid()}),content:Et.strictObject({environmentId:Et.uuid(),offeringVersionId:Et.uuid(),artifact:Hu.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:Ii,check:sr.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"})}),Zr=Et.strictObject(qo.shape).omit({document:!0,offering:!0}).extend({content:qo.shape.content.unwrap()});function Fh(e,t){let n=Os.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 qo.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}})}import{z as Yt}from"zod";var Mh={requestId:Yt.uuid(),sourceId:Yt.uuid(),expectedAvailable:Jt},qh=Yt.discriminatedUnion("action",[Yt.strictObject({...Mh,action:Yt.enum(["add","subtract","set_remaining"]),amount:de}),Yt.strictObject({...Mh,action:Yt.literal("edit"),granted:de,expiresAt:Yt.iso.datetime({offset:!0}).nullable(),nextResetAt:Yt.iso.datetime({offset:!0}).nullable(),expectedRevision:Yt.number().int().nonnegative()})]),Zu=Yt.strictObject({sourceId:Yt.uuid(),available:Jt,held:Jt,spent:Jt,adjustmentGrantId:Yt.uuid().nullable()}),Uh=Zu.extend({granted:Jt,expiresAt:Yt.iso.datetime({offset:!0}).nullable(),nextResetAt:Yt.iso.datetime({offset:!0}).nullable(),revision:Yt.number().int().nonnegative()});import{z as yn}from"zod";var Bh=yn.discriminatedUnion("action",[yn.object({action:yn.literal("upsert"),externalId:yn.string().min(1).max(128),name:yn.string().trim().min(1).max(80)}).strict(),yn.object({action:yn.literal("archive"),entityId:yn.uuid()}).strict()]),Vh=yn.object({id:yn.uuid(),externalId:yn.string().min(1).max(128),name:yn.string().min(1).max(80),archived:yn.boolean()}).strict();import{z as Gt}from"zod";import{z as Yr}from"zod";var zh=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],Lh=Yr.string().regex(/.+\/.+/),Wu=Yr.number().min(-100),Wr=Yr.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),xI=Yr.strictObject({input:Wr,output:Wr,cache_read:Wr.optional(),cache_write:Wr.optional(),reasoning:Wr.optional(),input_audio:Wr.optional(),output_audio:Wr.optional()}),Yu=(e,t)=>Yr.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),iT=Yr.strictObject({defaultMarkup:Wu,providerMarkups:Yu(Yr.string().min(1),Wu),modelMarkups:Yu(Lh,Wu),customModels:Yu(Lh,xI.partial())});import{z as xe}from"zod";var Xr=xe.iso.datetime({offset:!0}),yr=xe.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),SI=xe.discriminatedUnion("kind",[xe.object({kind:xe.literal("absolute"),from:Xr,to:Xr}).strict(),xe.object({kind:xe.literal("last_days"),days:xe.union([xe.literal(1),xe.literal(7),xe.literal(30),xe.literal(90)])}).strict(),xe.object({kind:xe.literal("billing_cycles"),membershipId:xe.uuid(),count:xe.number().int().min(1).max(12),includeCurrent:xe.boolean()}).strict()]),$h=xe.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"),II=xe.object({key:xe.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:xe.array(xe.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),ei=xe.object({range:SI,timezone:$h,filterBy:xe.array(II).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:xe.enum(["hour","day","week","month"]),internal_feature_id:xe.uuid().nullable(),entityId:xe.uuid().nullable(),topN:xe.number().int().min(1).max(50).nullable(),groupBy:xe.union([xe.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),xe.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:xe.object({bucket:Xr,group:xe.string().max(240),isOther:xe.boolean(),internal_feature_id:xe.uuid(),resourceId:xe.uuid()}).strict().nullable(),limit:xe.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)"})}),Gh=xe.object({from:Xr,to:Xr,interval:xe.enum(["hour","day","week","month"]),timezone:$h,rows:xe.array(xe.object({bucket:Xr,group:xe.string().max(240),isOther:xe.boolean(),internal_feature_id:xe.uuid(),resourceId:xe.uuid(),consumedUnits:yr,refundedUnits:yr,reservedUnits:yr,charged:yr,refunded:yr,reserved:yr,netUnits:yr,netCharged:yr}).strict()).max(100),nextCursor:xe.object({bucket:Xr,group:xe.string().max(240),isOther:xe.boolean(),internal_feature_id:xe.uuid(),resourceId:xe.uuid()}).strict().nullable()}).strict();var Li=Gt.string().regex(/^(0|[1-9]\d{0,29})$/),Kh=Gt.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),Xu=Gt.strictObject({bucket:Gt.iso.datetime({offset:!0}),group:Gt.string().max(240),isOther:Gt.boolean(),internal_feature_id:Gt.uuid()}),Hh=Gt.strictObject({...ei.shape,groupBy:Gt.union([Gt.enum(["customer","entity","entitlement"]),Gt.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Xu.nullable()}).superRefine((e,t)=>{let n=ei.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),Qh=Gt.strictObject({from:Gt.iso.datetime({offset:!0}),to:Gt.iso.datetime({offset:!0}),interval:ei.shape.interval,timezone:ei.shape.timezone,rows:Gt.array(Gt.strictObject({...Xu.shape,eventCount:Li,units:Kh,tokenEventCount:Li,tokens:Gt.strictObject(Object.fromEntries(zh.map(e=>[e,Li]))),totalTokens:Li,providerCostEventCount:Li,providerCostUsd:Kh,invalidTelemetryEventCount:Li})).max(100),nextCursor:Xu.nullable()});import{z as St}from"zod";var Jh=St.object({requestId:St.uuid(),items:St.array(St.object({customerId:St.uuid(),command:Ao.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"),Zh=St.object({batchId:St.uuid(),after:St.number().int().min(-1).max(999),limit:St.number().int().min(1).max(100)}).strict(),Wh=St.object({batchId:St.uuid(),status:St.enum(["queued","complete"]),total:St.number().int().min(1).max(1e3),processed:St.number().int().min(0).max(1e3),items:St.array(St.object({position:St.number().int().min(0).max(999),customerId:St.uuid(),idempotencyKey:St.string().min(1).max(120),status:St.enum(["queued","accepted","rejected","failed"]),receipt:bo.nullable(),errorCode:St.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:St.number().int().min(0).max(999).nullable()}).strict();import{z as k}from"zod";var vI=k.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),Yh=k.enum(["draft","active","paused","archived"]),Xh=k.string().min(1).max(256),eg=k.array(Xh).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),wI=k.strictObject({duration:k.enum(["day","week","month","year"]),length:k.number().int().min(1).max(3660)}),OI=k.strictObject({internal_feature_id:k.uuid(),allowance:k.number().nonnegative().max(1e15).nullable(),expiry:wI.nullable()}),PI=k.discriminatedUnion("type",[k.strictObject({type:k.literal("feature_grant"),grants:k.array(OI).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),k.strictObject({type:k.literal("free_product"),productId:Xh,duration:dn}),k.strictObject({type:k.literal("invoice_credits"),amount:k.number().positive().max(1e8),duration:dn,rollover:k.boolean(),productIds:eg})]),CI=k.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),tg=k.object({key:CI,name:k.string().trim().min(1).max(80),configuration:PI}).strict(),ng=k.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),el=k.object({code:ng,maxUses:k.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:k.boolean()}).strict(),rg=k.object({key:k.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:k.string().trim().min(1).max(80),rewardId:k.uuid(),redeemOn:k.enum(["customer_creation","checkout"]),receivedBy:k.enum(["referrer","all"]),maxRedemptions:k.number().int().min(1).max(1e6).nullable(),productIds:eg,excludeTrial:k.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),ig={id:k.uuid(),projectId:k.uuid(),environmentId:k.uuid(),revision:k.number().int().nonnegative(),status:Yh,createdAt:k.iso.datetime({offset:!0}),updatedAt:k.iso.datetime({offset:!0})},_I=tg.extend(ig).strict(),EI=rg.safeExtend(ig).strict(),AT=k.strictObject({id:k.uuid(),key:k.string(),name:k.string(),type:vI,status:Yh}),bT=k.discriminatedUnion("action",[k.object({action:k.literal("save"),id:k.uuid().nullable(),revision:k.number().int().nonnegative(),input:tg}).strict(),k.object({action:k.enum(["activate","pause","resume","archive","delete"]),id:k.uuid(),revision:k.number().int().nonnegative()}).strict()]),xT=k.discriminatedUnion("action",[k.object({action:k.literal("save"),id:k.uuid().nullable(),revision:k.number().int().nonnegative(),input:rg}).strict(),k.object({action:k.enum(["activate","pause","resume","archive","delete"]),id:k.uuid(),revision:k.number().int().nonnegative()}).strict()]),og=k.object({id:k.uuid(),rewardId:k.uuid(),programId:k.uuid().nullable(),customerId:k.uuid(),referrerId:k.uuid().nullable(),status:k.enum(["pending","applied","unavailable"]),result:k.record(k.string(),k.unknown()).nullable(),createdAt:k.iso.datetime({offset:!0})}).strict(),ag=k.object({code:ng,requestId:k.uuid()}).strict(),sg=k.strictObject({redemptionId:k.uuid(),currency:Ie,requestId:k.uuid(),accepted:k.literal(!0)}),RI=k.strictObject({type:k.literal("checkout"),orderId:k.uuid(),productVersionId:k.uuid(),currency:Ie,duration:dn,renewalAmountMinor:k.number().int().positive().max(1e8),status:k.enum(["created","pending","trialing","paid","cancelled","failed"]),url:k.url().nullable()}),cg=k.discriminatedUnion("type",[RI,k.strictObject({type:k.literal("subscription"),operationId:k.uuid(),membershipId:k.uuid(),productVersionId:k.uuid(),currency:Ie,duration:dn,renewalAmountMinor:k.number().int().positive().max(1e8),status:k.enum(["pending","running","applied","failed"])})]),ug=k.object({programId:k.uuid(),requestId:k.uuid()}).strict(),lg=k.object({id:k.uuid(),programId:k.uuid(),code:el.shape.code,createdAt:k.iso.datetime({offset:!0})}).strict(),ST=k.object({rows:k.array(_I).max(100),nextCursor:k.uuid().nullable()}).strict(),IT=k.object({rows:k.array(EI).max(100),nextCursor:k.uuid().nullable()}).strict(),kI=el.extend({id:k.uuid(),redemptions:k.number().int().nonnegative()}).strict(),jI=k.strictObject({id:k.uuid(),programId:k.uuid().nullable(),customerId:k.uuid().nullable(),referrerId:k.uuid().nullable(),code:k.string().nullable(),status:k.enum(["pending","triggered","applied"]),createdAt:k.iso.datetime({offset:!0})}),vT=k.object({codes:k.array(kI).max(100),redemptions:k.array(jI).max(100),customers:k.record(k.uuid(),k.string()),codesCursor:k.uuid().nullable(),redemptionsCursor:k.uuid().nullable()}).strict(),wT=k.discriminatedUnion("action",[k.object({action:k.literal("create"),rewardId:k.uuid(),revision:k.number().int().nonnegative(),input:el}).strict(),k.object({action:k.literal("remove"),rewardId:k.uuid(),revision:k.number().int().nonnegative(),codeId:k.uuid()}).strict()]);import{z as w}from"zod";import{z as W}from"zod";var Ln={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},Uo=e=>new Set(e).size===e.length,tl=W.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),TI=W.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),Bo=W.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"))),NI=W.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),dg=W.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var pg=W.strictObject({id:W.uuid(),repo:TI,platform:W.enum(["github","gitlab","bitbucket"]),branches:W.array(Bo).min(1).max(4).refine(Uo),workflow:W.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:W.array(W.uuid()).min(1).max(4).refine(Uo),include:W.array(dg).min(1).max(16),exclude:W.array(dg).max(16),methods:W.array(W.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(Uo),maxAgeHours:W.number().int().min(1).max(720)}),mg=pg.extend({revision:W.number().int().positive()}),CT=W.strictObject({repository:pg,expectedRevision:W.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),fg=W.strictObject({repositoryId:W.uuid(),branch:Bo}),DI=W.array(tl).max(Ln.keys).refine(Uo),hg=W.strictObject({repository:mg.omit({keyIds:!0}),branch:Bo,keys:DI,keySetHash:W.string().regex(/^[a-f0-9]{64}$/)}),FI=W.strictObject({filePath:NI,startingLineNumber:W.number().int().min(1).max(1e7)}),nl=W.strictObject({protocol:W.literal(1),repositoryId:W.uuid(),branch:Bo,workflow:W.string().max(200),configurationRevision:W.number().int().positive(),keySetHash:W.string().regex(/^[a-f0-9]{64}$/),commit:W.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:W.uuid(),runNumber:W.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:W.number().int().min(1).max(1e4),scannerVersion:W.literal("1"),scannedAt:W.iso.datetime({offset:!0}),coverage:W.strictObject({complete:W.literal(!0),files:W.number().int().min(0).max(Ln.files),sourceBytes:W.number().int().min(0).max(Ln.sourceBytes),unresolvedCalls:W.number().int().min(0).max(1e6),unsupportedFiles:W.number().int().min(0).max(Ln.files)}),features:W.array(W.strictObject({key:tl,refs:W.array(FI).max(Ln.referencesPerKey)})).max(Ln.keys)}).superRefine((e,t)=>{Uo(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)>Ln.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),rl=W.strictObject({scanId:W.uuid(),commit:W.string(),receivedAt:W.string(),references:W.number().int().nonnegative(),removedReferences:W.number().int().nonnegative()}),MI=rl.extend({repositoryId:W.uuid(),branch:Bo,workflow:W.string(),digest:W.string(),configurationRevision:W.number().int().positive(),runNumber:W.number().int().positive(),runAttempt:W.number().int().positive(),scannedAt:W.string(),keySetHash:W.string(),coverage:nl.shape.coverage}),qI=W.strictObject({repositories:W.array(mg).max(Ln.repositories),scans:W.array(MI).max(Ln.repositories*Ln.branches)}),UI=W.strictObject({key:tl,references:W.number().int().nonnegative(),coveredTargets:W.number().int().nonnegative(),expiredTargets:W.number().int().nonnegative(),uncertainTargets:W.number().int().nonnegative()}),_T=W.strictObject({available:W.boolean().default(!0),settings:qI,expectedTargets:W.number().int().min(0).max(80),features:W.array(UI).max(2001),truncated:W.boolean()});import{z as Ee}from"zod";var cn=Ee.string().min(1).max(200),Ps=Ee.iso.datetime({offset:!0}),Vo=Ee.number().int().min(1).max(Number.MAX_SAFE_INTEGER),il=Ee.number().int().min(0).max(1e12),Ag=Ee.number().int().min(1).max(1e12),gg={...Ht,type:Ee.literal("coupon.redeemed"),grantId:Ee.uuid()},yg={...Ht,type:Ee.literal("usage.observed"),merchantTransactionId:cn,resource:cn,unit:cn,quantity:Ag},BI=Ee.strictObject({...Ht,type:Ee.literal("fulfillment.updated"),operationId:Ee.uuid(),merchantFulfillmentId:cn,status:Ee.enum(["pending","applied","failed"])}),VI=Ee.strictObject({...Ht,type:Ee.literal("benefit.claimed"),merchantBenefitId:cn,resource:cn,unit:cn,quantity:Ag,expiresAt:Ps.nullable(),revision:Vo}),LI=Ee.strictObject({...Ht,type:Ee.literal("benefit.closed"),merchantBenefitId:cn,status:Ee.enum(["failed","expired","canceled"]),revision:Vo}),zI=Ee.strictObject({...Ht,type:Ee.literal("benefit.updated"),merchantBenefitId:cn,status:Ee.enum(["active","expired","revoked"]),remainingQuantity:il.nullable(),expiresAt:Ps.nullable(),revision:Vo}),$I=Ee.strictObject({...Ht,type:Ee.literal("authorization.updated"),merchantAuthorizationId:cn,kind:Ee.literal("auto_topup"),status:Ee.enum(["pending","effective","revoked","failed"]),termsReference:cn.nullable(),revision:Vo}),GI=Ee.strictObject({...Ht,type:Ee.literal("balance.observed"),resource:cn,unit:cn,availableQuantity:il,reservedQuantity:il,periodStartsAt:Ps.nullable(),periodEndsAt:Ps.nullable(),revision:Vo}),bg=Ee.union([Ee.discriminatedUnion("type",[...ld,BI,VI,LI,zI,$I,GI]),Ee.strictObject({...gg,productVersionId:Ee.uuid(),subscriptionId:Ee.string().trim().min(1).max(255)}),Ee.strictObject({...gg,merchandiseId:Ee.uuid()}),Ee.strictObject({...yg,operation:Ee.literal("consume")}),Ee.strictObject({...yg,operation:Ee.literal("reverse"),reversalOf:cn})]),xg=Ee.strictObject({id:Ee.uuid(),eventId:Ee.string().min(1).max(200),source:Ee.literal("merchant"),providerVerified:Ee.literal(!1),outcome:Ee.string().min(1).max(100)});import{z as oe}from"zod";var Sg=Wm,KI=Sg.extend({invoice_id:Sg.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),ol=oe.strictObject({name:oe.string().trim().min(1).max(255),memo:oe.string().max(1e4).nullable().optional(),footer:oe.string().max(1e4).nullable().optional(),net_terms_days:oe.number().int().positive().nullable().optional()}),HI=ol.extend({id:oe.string().min(1).max(255),created_at:oe.number().nullable()}),Ig=oe.strictObject({items:oe.array(HI).max(50),nextCursor:oe.uuid().nullable()}),DT=oe.discriminatedUnion("action",[oe.strictObject({action:oe.literal("create"),requestId:oe.uuid(),values:ol}),oe.strictObject({action:oe.literal("update"),id:oe.string().min(1).max(255),values:ol}),oe.strictObject({action:oe.literal("delete"),id:oe.string().min(1).max(255)})]),vg=oe.discriminatedUnion("action",[oe.strictObject({action:oe.literal("create"),requestId:oe.uuid(),params:Ei}),oe.strictObject({action:oe.enum(["finalize","send","pay","void"]),requestId:oe.uuid(),invoiceId:oe.uuid()}),oe.strictObject({action:oe.literal("reissue"),requestId:oe.uuid(),invoiceId:oe.uuid(),params:KI})]),al=oe.strictObject({id:oe.uuid(),customerId:oe.uuid(),providerInvoiceId:oe.string().nullable(),status:oe.enum(["draft","open","paid","void","uncollectible"]),currency:oe.string(),totalMinor:oe.string().regex(/^-?\d+$/),paidMinor:oe.string().regex(/^\d+$/),refundedMinor:oe.string().regex(/^\d+$/),hostedInvoiceUrl:oe.url().nullable(),createdAt:oe.number(),collectionMethod:oe.enum(["send_invoice","charge_automatically"]).nullable()}),wg=al.extend({lines:oe.array(oe.strictObject({id:oe.uuid(),description:oe.string(),amountMinor:oe.string().regex(/^-?\d+$/),netAmountMinor:oe.string().regex(/^-?\d+$/),quantity:oe.number().nullable(),periodStart:oe.number().nullable(),periodEnd:oe.number().nullable()})).max(1e3)}),zi=oe.strictObject({taskId:oe.uuid(),status:oe.enum(["ready","running","done","dead"]),invoice:al.nullable(),errorCode:oe.string().nullable()}),Og=oe.strictObject({items:oe.array(al).max(50),nextCursor:oe.uuid().nullable(),operations:oe.array(zi).max(50),operationsLimited:oe.boolean()});var QI=w.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"]),Pg={scope:De,permissions:w.array(QI),expiresAt:w.iso.datetime().nullable()},_N=w.discriminatedUnion("kind",[w.object({...Pg,kind:w.literal("server"),keyId:w.string().min(1)}),w.object({...Pg,kind:w.literal("customer"),customerId:w.string().min(1),identityKind:w.enum(["identified","guest"]),expiresAt:w.iso.datetime()})]),V=w.object({requestId:w.uuid(),scope:De}).strict(),JI=ph.safeExtend({fingerprint:gs.optional()}).strict(),ZI=V.extend({customer:Ui,created:w.boolean()});function Cg(){return V.extend({offer:lo.nullable(),reason:Ep.nullable()})}var O={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:bm,response:V.extend({message:w.object({messageId:w.uuid(),channel:vo,acceptedAt:w.iso.datetime({offset:!0}),status:w.enum(["accepted","sending","completed","canceled"]),replayed:w.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:w.strictObject({messageId:w.uuid()}),response:V.extend({message:w.object({id:w.uuid(),channel:vo,status:w.enum(["accepted","sending","completed","canceled"]),deliveries:w.array(w.object({id:w.uuid(),status:Sm,attempts:w.number().int().nonnegative(),receipts:w.array(w.object({kind:Im,occurredAt:w.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:Jl,response:V.extend({installation:kr})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:Zl,response:V.extend({installation:kr})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:na,response:V.extend({installation:kr})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:w.strictObject({channel:vo}),response:V.extend({preference:Js})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:xm,response:V.extend({preference:Js})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:w.strictObject({cursor:w.uuid().optional()}),response:V.extend({templates:Ig})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:w.strictObject({customerId:w.uuid(),params:Ei}),response:V.extend({preview:ru})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:w.strictObject({customerId:w.uuid(),requestId:w.uuid(),params:Ei}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:V.extend({operation:zi})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:w.strictObject({customerId:w.uuid(),command:vg}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:V.extend({operation:zi})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:w.strictObject({customerId:w.uuid(),taskId:w.uuid()}),response:V.extend({operation:zi})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:w.strictObject({customerId:w.uuid(),cursor:w.uuid().optional()}),response:V.extend({invoices:Og})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:w.strictObject({customerId:w.uuid(),invoiceId:w.uuid()}),response:V.extend({invoice:wg})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:fg,response:V.extend({config:hg})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:nl,response:V.extend({receipt:rl})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:w.strictObject({}),response:V.extend({payload:jo})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:zf,response:V.merge(as)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:$f,response:V.merge(Gf)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:w.strictObject({customerId:w.uuid(),sourceId:w.uuid()}),response:V.extend({balance:Uh})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:w.strictObject({customerId:w.uuid(),command:qh}),response:V.extend({balance:Zu})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:w.strictObject({internal_feature_id:w.uuid(),customerId:w.uuid().optional(),entityId:w.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:V.extend({internal_feature_id:w.uuid(),config:Sc,model_markups:xa})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:w.strictObject({customerId:w.uuid(),query:Da}),response:V.extend({usage:xo})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:w.strictObject({customerId:w.uuid(),command:lm}),response:V.extend({usage:xo})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:w.strictObject({customerId:w.uuid(),command:im}),response:V.extend({grant:qc})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:om,response:V.extend({grants:am})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:w.union(kf.options.map(e=>e.extend({customerId:w.uuid().optional(),customerToken:w.string().regex(Ft).optional()}))),response:V.extend({operation:jf})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:xf.extend({customerId:w.uuid().optional()}),response:V.extend({setup:uu})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Sf.extend({customerId:w.uuid().optional()}),response:V.extend({setup:uu})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:yf.safeExtend({customerId:w.uuid()}),response:V.extend({batch:Eo})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:Ya.extend({customerId:w.uuid()}),response:V.extend({batch:Eo})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:Ya.extend({customerId:w.uuid()}),response:V.extend({batch:Eo})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:Ya.extend({customerId:w.uuid()}),response:V.extend({batch:Eo})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:w.discriminatedUnion("action",[Xa.options[0].extend({customerId:w.uuid()}),Xa.options[1].extend({customerId:w.uuid()}),Xa.options[2].extend({customerId:w.uuid()})]),response:V.extend({trial:cu})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Af.extend({customerId:w.uuid()}),response:V.extend({trial:cu})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:ns,response:V.extend({subscriptions:_f})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:ns,response:V.extend({purchases:Ef})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:Of,response:V.extend({conflicts:Rf})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:Pf,response:V.extend({resolution:Cf})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:vf,response:V.extend({verification:wf})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:uf.safeExtend({...Ci,customerId:w.uuid().optional()}),response:V.extend({quote:Ri})},recordMerchantEvent:{method:"POST",path:"merchant/events/record",permission:"billing:write",audience:"server",request:bg,response:V.extend({record:xg})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Kr.extend({customerId:w.uuid().optional(),intent:w.enum(["confirm","cancel"]).optional(),merchantConfirmation:io.optional()}),response:V.extend({operation:ki})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Kr.extend({customerId:w.uuid().optional()}),response:V.extend({operation:ki})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:pf.safeExtend({customerId:w.uuid().optional()}),response:V.extend({quote:ff})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Kr.extend({customerId:w.uuid().optional(),intent:w.enum(["confirm","cancel"]).optional(),merchantConfirmation:io.optional()}),response:V.extend({operation:iu})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Kr.extend({customerId:w.uuid().optional()}),response:V.extend({operation:iu})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:hf.safeExtend({customerId:w.uuid()}),response:V.extend({quote:au})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Kr.extend({customerId:w.uuid(),merchantConfirmation:io.optional()}),response:V.extend({operation:Wa})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Kr.extend({customerId:w.uuid()}),response:V.extend({operation:Wa})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:zp,response:V.extend({controls:Fc})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:Fp,response:V.extend({prepared:qp})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:Up,response:V.extend({authorization:ka})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Qp,response:V.extend({coupons:Jp})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Bp,response:V.extend({authorization:ka})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:Kp,response:V.extend({invoices:Hp})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:Gp.extend({customerId:w.uuid()}),response:V.extend({operation:zi})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:$p,response:V.extend({invoice:fo})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:w.object({customerId:w.uuid(),command:Lp}).strict(),response:V.extend({controls:Fc})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:w.object({customerId:w.uuid(),command:Bh}).strict(),response:V.extend({entity:Vh})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:w.strictObject({customerId:w.uuid().nullable(),query:Hh}),response:V.extend({analytics:Qh})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:w.object({customerId:w.uuid().nullable(),query:ei}).strict(),response:V.extend({analytics:Gh})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:Jh,response:V.extend({batchId:w.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:Zh,response:V.extend({batch:Wh})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:Bd.extend({customerId:w.string().min(1).optional()}),response:V.extend({check:sr})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:w.strictObject({kind:fr,selector:w.discriminatedUnion("type",[w.strictObject({type:w.literal("resource"),id:w.uuid()}),w.strictObject({type:w.literal("version"),id:w.uuid()})]),customerId:w.string().min(1).optional()}),response:V.extend({content:tu})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Dh,response:V.extend({paywall:Zr})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:w.strictObject({processContext:Ha.optional(),...Ci,selector:Ff,customerId:w.string().min(1).optional(),commerce:fi,requirement:Pn.optional()}),response:V.extend({offering:Mf,candidates:w.array(Ac).max(20),availability:w.array(w.strictObject({productVersionId:w.uuid(),available:w.boolean(),reason:w.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:sr.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:w.object({customerId:w.uuid().optional(),entityId:w.uuid().optional()}).strict(),response:V.extend({holdings:dm})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:w.object({customerId:w.uuid().optional(),query:mm}).strict(),response:V.extend({ledger:fm})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:sm.extend({customerId:w.uuid().optional()}),response:V.extend({detail:cm})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:Uc.safeExtend({customerId:w.uuid().optional()}),response:V.extend({statement:um})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:w.object({customerId:w.uuid().optional(),command:Ao.options[0]}).strict(),response:V.extend({quote:tm})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:w.strictObject({customerId:w.uuid(),command:w.union([w.strictObject({eventName:w.string().min(1),quantity:de.optional(),properties:Ot.optional(),entityId:w.uuid().optional(),idempotencyKey:w.string().min(1).max(120)}),w.strictObject({internal_feature_id:w.uuid(),quantity:de.optional(),properties:Ot.optional(),entityId:w.uuid().optional(),idempotencyKey:w.string().min(1).max(120)})])}),response:V.extend({receipts:w.array(bo).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:w.object({customerId:w.uuid(),command:Ao.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:V.extend({receipt:bo})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:ag,response:V.extend({redemption:og})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:ug,response:V.extend({referralCode:lg})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:sg,response:V.extend({checkout:cg})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:gm,response:V.extend({seats:Lc})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:ym,response:V.extend({seats:Lc})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:JI,response:ZI},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Tu,response:V.extend({customer:Ui})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:hh,response:V.extend(gh.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:fh,response:V.extend(mh.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:w.object({customerId:w.uuid()}).strict(),response:V.extend(ar.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:w.strictObject({}),response:V.extend(ar.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:w.strictObject({customerId:w.uuid(),sessionId:w.uuid().optional()}),response:V.extend({revoked:w.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:w.strictObject({guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:gs.optional()}),response:V.extend({customerId:w.uuid(),guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:w.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:w.strictObject({guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:V.extend(ar.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:w.strictObject({guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:w.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:w.uuid()}),response:V.extend({customer:Ui,switched:w.boolean(),replayed:w.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:w.strictObject({code:w.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:w.uuid()}),response:Cg()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:w.object({}).strict(),response:V.extend({offers:w.array(lo)})},grantModelBenefit:{method:"POST",path:"benefits/model-usage/grant",permission:"offers:grant",audience:"server",request:kd,response:V.extend({operation:fc})},readModelBenefit:{method:"POST",path:"benefits/model-usage/read",permission:"offers:grant",audience:"server",request:jd,response:V.extend({operation:fc})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:w.object({customerId:w.string().min(1).max(255).optional(),couponId:w.uuid(),...Ci,requestId:w.uuid(),couponContentDigest:w.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:Cg()}},EN={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,grantModelBenefit:O.grantModelBenefit,readModelBenefit:O.readModelBenefit,redeemCoupon:O.redeemCoupon,redeemReward:O.redeemReward,createReferralCode:O.createReferralCode,claimRewardProduct:O.claimRewardProduct,readSeats:O.readSeats,manageSeat:O.manageSeat};import{z as sl}from"zod";var Lo=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function cl(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=>on(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 Lo("Required GB Feature is unavailable");i=Wn(e.featureKey,t),o=i.value,Object.assign(r,Pi(e,{value:o})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new Lo("Required GB Experiment is unavailable");if(a=Ea(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 Lo("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:Wn(e.configuration.featureKey,t).value;o={type:"offering_version",id:sl.uuid().parse(u)},Object.assign(r,Pi(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,Pi(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 _g(e,t,n){sl.uuid().parse(e),sl.number().int().nonnegative().parse(t);let r=rr(or(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)}`}import{z as H}from"zod";var Ar=H.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),WI=H.enum(["running","waiting","completed","closed","ineligible","failed"]),ul=H.discriminatedUnion("type",[ku,H.strictObject({type:H.literal("wait"),receiptId:H.uuid(),kind:H.enum(["timer","event","operation"]),deadline:H.iso.datetime({offset:!0}).nullable(),eventName:Ar.optional()}),H.strictObject({type:H.literal("open_url"),receiptId:H.uuid(),url:Nu,openIn:Du}),H.strictObject({type:H.literal("event"),receiptId:H.uuid(),event:Ar})]),Cs=H.strictObject({type:H.literal("funnel"),id:H.uuid(),versionId:H.uuid()}),YI={id:Ar,presentation:kn,outputs:H.array(Ar).max(250),inputs:ls,values:H.record(H.string(),ve).optional(),offeringKey:wt.optional(),capabilities:Ii,customerData:Em,dataCursors:H.record(Ar,us.nullable())},XI=H.strictObject({...YI,content:H.strictObject({type:H.literal("document"),document:mn})}),zo=H.strictObject({id:H.uuid(),source:Cs,revision:H.number().int().nonnegative(),visit:H.number().int().nonnegative(),nodeId:Ar,nodeType:H.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:WI,stopped:H.boolean(),canBack:H.boolean(),authenticated:H.boolean(),locale:H.string().min(1).max(35),answers:hr,parameters:gr,variables:H.record(H.string(),ve),output:ve.nullable(),screen:XI.nullable(),paywall:H.strictObject({receiptId:H.uuid(),resolution:H.union([qo,Zr]),quote:Ri.nullable(),operation:ki.nullable(),purchaseRequestId:H.uuid().nullable(),selectionGeneration:H.number().int().nonnegative().optional(),canReselect:H.boolean().optional()}).nullable(),instruction:ul.nullable(),pendingRequest:H.strictObject({requestId:H.uuid(),authenticationRequired:H.boolean()}).nullable(),runExpiresAt:H.iso.datetime({offset:!0}),credentialExpiresAt:H.iso.datetime({offset:!0}).nullable()}),_s=H.strictObject({scope:De,run:zo,settlement:H.strictObject({requestId:H.uuid(),state:H.enum(["pending","unknown","settled"]),operationId:H.uuid().nullable(),receiptId:H.uuid().nullable().optional()}).optional(),purchase:H.strictObject({receiptId:H.uuid(),quote:Ri.nullable(),operation:ki.nullable(),canReselect:H.boolean().optional()}).optional(),review:H.strictObject({activeOperationId:H.uuid().nullable(),pages:H.array(H.strictObject({receiptId:H.uuid(),nodeId:Ar,visit:H.number().int().nonnegative()})).max(100),page:H.strictObject({receiptId:H.uuid(),nodeId:Ar,visit:H.number().int().nonnegative(),document:mn,answers:hr,inputs:ls,values:H.record(H.string(),ve).optional()}).nullable(),coupons:H.array(H.strictObject({grantId:H.uuid(),status:H.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:H.string().nullable()})).max(100),purchases:H.array(H.strictObject({receiptId:H.uuid(),operationId:H.uuid(),status:H.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:H.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:H.uuid().optional()}),Eg=_s.extend({run:zo.extend({paywall:zo.shape.paywall.unwrap().extend({resolution:Zr}).nullable()})});var Rg="X-Indiana-Server-Key";import{z as se}from"zod";import{z as be}from"zod";import{z as Rt}from"zod";var ev=Rt.strictObject({selector:Rt.string().min(1).max(2048),action:Rt.enum(["set","append","remove"]),attribute:Rt.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:Rt.string().max(5e4).optional(),parentSelector:Rt.string().max(2048).optional(),insertBeforeSelector:Rt.string().max(2048).optional()}),tv=Rt.strictObject({variation:Rt.string().min(1).max(128),description:Rt.string().max(2e3).default(""),css:Rt.string().max(1e5).default(""),js:Rt.string().max(1e5).default(""),domMutations:Rt.array(ev).max(200).default([]),iam:Xf.optional(),renderGuard:ss.optional()}),ll=tv.omit({variation:!0,description:!0,iam:!0}),nv=Fi.omit({variations:!0,active:!0}).extend({changeId:Rt.string().regex(/^[a-f0-9]{64}$/),variations:Rt.tuple([ll,ll]).rest(ll).refine(e=>e.length<=20)}),kg=Rt.strictObject({trackExposures:Rt.boolean(),environmentId:Rt.uuid(),generation:Rt.string().regex(/^[a-f0-9]{64}$/),experiments:Rt.array(nv).max(100),savedGroups:ko});var $o=be.string().regex(/^[a-f0-9]{64}$/),uD=be.strictObject({iam:$o,executionContracts:be.union([be.tuple([be.literal("funnel-run/1")]),be.tuple([be.literal("funnel-process/1")])]).default(["funnel-run/1"])}),rv=be.strictObject({release:$o,render:ss,button:be.strictObject({selector:be.string().min(1).max(512),elementKey:be.string().min(1).max(256),tag:be.enum(["button","a","input"])}).nullable()}),lD=be.strictObject({scope:De.extend({environmentId:be.uuid()}),release:$o,validatedAt:be.iso.datetime({offset:!0}),validUntil:be.iso.datetime({offset:!0}),entries:be.array(be.strictObject({id:be.uuid(),funnelId:be.uuid(),versionId:be.uuid(),event:be.enum(["screen_enter","button_click"]),target:rv})).max(4e3)}),jg=be.strictObject({operation:be.literal("entry_start"),funnelId:be.uuid(),versionId:be.uuid(),entryId:be.uuid(),release:$o,requestId:be.uuid(),locale:be.string().min(1).max(35).default("en")}),Tg=be.strictObject({scope:De,suppressed:be.literal(!0),reason:be.enum(["frequency","in_progress"]),retryAt:be.iso.datetime({offset:!0}).nullable()}),dD=be.strictObject({experimentId:be.uuid(),splitNodeId:be.string().min(1).max(128)}),iv=be.strictObject({experimentId:be.uuid(),experimentKey:be.string().min(1).max(128),variationKey:be.string().min(1).max(128),inExperiment:be.boolean(),generation:be.string().min(1).max(256)}),Go=be.strictObject({operation:be.literal("page_experiments"),release:$o,usedReceiptIds:be.array(be.uuid()).max(20).default([]),customerToken:be.string().regex(Ft).optional()}),Ng=be.strictObject({scope:De,runId:be.uuid(),assignments:be.array(iv.extend({receiptId:be.uuid()})).max(100),payload:kg});var Mn=se.literal(Hf),ov=se.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),dl=se.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),Dg=se.discriminatedUnion("type",[se.strictObject({type:se.literal("guest"),guestToken:dl}),se.strictObject({type:se.literal("customer"),customer:Qr,customerData:qi.optional()})]),pl=se.strictObject({id:se.uuid(),runId:se.uuid(),customerId:se.uuid(),requestId:se.uuid(),acceptedAt:se.iso.datetime({offset:!0})}),av=se.strictObject({participantId:se.uuid(),startedAs:se.enum(["guest","identified"]),binding:pl.omit({runId:!0,requestId:!0}).nullable()}),sv=se.union([ul,se.strictObject({type:se.literal("authentication_required"),reason:se.enum(["customer_required","customer_experiment_required"]),nodeId:se.string().min(1).max(64),visit:se.number().int().nonnegative()})]),cv=zo.omit({authenticated:!0}).extend({identity:av,instruction:sv.nullable()}),uv=se.discriminatedUnion("operation",[Ct.options[2].omit({customerToken:!0}),Ct.options[3].omit({customerToken:!0}),Ct.options[4].omit({customerToken:!0}),Ct.options[5].omit({customerToken:!0}),Ct.options[6].omit({customerToken:!0}),Ct.options[7].omit({customerToken:!0})]),Es={contract:Mn,customerToken:se.string().regex(Ft)},Fg={contract:Mn,requestId:se.uuid(),runToken:ov,externalUserId:Qr.options[1].shape.value},Mg=se.discriminatedUnion("operation",[se.strictObject({contract:Mn,operation:se.literal("describe")}),se.strictObject({contract:Mn,operation:se.literal("start"),source:Dg,funnelId:Ct.options[0].shape.funnelId,requestId:se.uuid(),locale:Ct.options[0].shape.locale,parameters:Ct.options[0].shape.parameters}),jg.omit({operation:!0}).extend({contract:Mn,operation:se.literal("entry_start"),source:Dg}),se.strictObject({...Fg,operation:se.literal("bind_customer"),guestToken:dl,claimRequestId:se.uuid(),expectedBindingId:se.null()}),se.strictObject({...Fg,operation:se.literal("binding_status"),guestToken:dl.optional()}),Ct.options[1].omit({operation:!0,customerToken:!0}).extend({...Es,operation:se.literal("get"),settlementBindingId:se.uuid().nullable().optional()}),Ct.options[8].omit({operation:!0,customerToken:!0}).extend({...Es,operation:se.literal("review")}),Go.omit({customerToken:!0}).extend(Es),se.strictObject({...Es,operation:se.literal("command"),identity:se.strictObject({bindingId:se.uuid().nullable()}),command:uv})]),ml=_s.omit({run:!0}).extend({contract:Mn,run:cv,settlement:_s.shape.settlement.unwrap().extend({accepted:se.boolean().nullable().optional()}).optional()}),SD=Tg.extend({contract:Mn}),ID=se.discriminatedUnion("operation",[Mg.options[1].omit({contract:!0,source:!0,requestId:!0}),Mg.options[2].omit({contract:!0,source:!0,requestId:!0})]),vD=ml.extend({binding:pl,outcome:se.enum(["bound","already_bound"]),replayed:se.boolean()}),wD=se.discriminatedUnion("state",[se.strictObject({contract:Mn,scope:De,state:se.literal("not_accepted")}),se.strictObject({contract:Mn,scope:De,state:se.literal("conflict")}),se.strictObject({contract:Mn,scope:De,state:se.literal("bound"),binding:pl})]),OD=se.strictObject({contract:Mn,scope:De,keyId:se.uuid(),operations:se.array(se.string()).max(20)});import{z as Me}from"zod";var $i=Me.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ug=Me.strictObject({entry:$i,nodes:Me.array(Me.strictObject({id:$i,type:Me.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:Me.record(Me.string(),$i),writes:Me.record(wt,wt),resources:Me.strictObject({screenId:$i.optional(),paywallVersionId:Me.uuid().optional(),couponId:Me.uuid().optional(),couponIds:Me.array(Me.uuid()).max(20).optional(),experimentId:Me.uuid().optional(),featureKey:Me.string().optional(),offeringVersionId:Me.uuid().optional()})})).min(1).max(500)}),qg={scope:De,funnelId:Me.uuid(),versionId:Me.uuid(),evaluationRevision:Me.number().int().nonnegative(),expiresAt:Me.iso.datetime({offset:!0}).nullable(),topology:Ug},Rs=Me.discriminatedUnion("evaluationMode",[Me.strictObject({...qg,evaluationMode:Me.literal("local"),growth:Sn,conditions:Me.record($i,Me.array(Me.strictObject({condition:nn,port:Me.string()})))}),Me.strictObject({...qg,evaluationMode:Me.literal("remote")})]),lv=Rs.options[0].extend({evaluation:Me.strictObject({maxTransitions:Me.number().int().min(1).max(1e4),variables:Me.record(wt,Oi),outputSchema:wi,terminals:Me.record($i,Me.strictObject({outcome:Me.enum(["completed","closed","ineligible","failed"]),output:No.nullable()}))})});function dv(e){return Ug.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=Me.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 fl(e){let t=Vi.parse(e.document),n=e.evaluationMode==="local"?Sn.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:dv(t)};return Rs.parse(e.evaluationMode==="remote"?r:{...r,growth:vs(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 Bg(e){let t=fl(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=Vi.parse(e.document);return lv.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}]]}))}})}import{z as at}from"zod";var Vg=at.string().regex(/^[a-f0-9]{64}$/),pv=Fi.omit({variations:!0,active:!0}).extend({changeId:Vg,variations:at.array(at.strictObject({urlRedirect:at.string().max(2048)})).min(2).max(20)}),Lg=at.strictObject({environmentId:at.uuid(),trackExposures:at.boolean(),generation:Vg,experiments:at.array(pv).max(100),savedGroups:ko}),mv=at.strictObject({eventUuid:at.uuid(),timestamp:at.iso.datetime({offset:!0}).optional(),deviceId:at.string().min(1).max(128),sessionId:at.string().min(1).max(128).optional(),url:at.url().max(2048),pageTitle:at.string().max(512).optional(),experimentKey:at.string().min(1).max(255),variationKey:at.string().min(1).max(64)}),qD=at.strictObject({events:at.array(mv).min(1).max(20)}),UD=at.strictObject({inserted:at.number().int().nonnegative(),duplicates:at.number().int().nonnegative(),skipped:at.number().int().nonnegative(),rejected:at.array(at.strictObject({index:at.number().int().nonnegative(),reason:at.string()}))});import{z as pt}from"zod";var gl=32,fv=522240;function yl(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 hv=pt.strictObject({nodeId:pt.string().min(1).max(64),visit:pt.number().int().nonnegative(),revision:pt.number().int().nonnegative()}),hl=pt.record(pt.string(),ve),gv=pt.strictObject({id:pt.uuid(),nodeId:pt.string().min(1).max(64),visit:pt.number().int().nonnegative(),input:pt.strictObject({schemaVersion:Do.shape.schemaVersion,kind:Do.shape.kind,selector:Do.shape.selector,contract:Do.shape.contract}),context:hl,removed:pt.array(pt.string()).max(100),attributes:hl,removedAttributes:pt.array(pt.string()).max(100),result:vh,offeringVersionId:pt.uuid().nullable(),events:pt.strictObject({entered:pt.string().regex(/^[1-9][0-9]{0,18}$/),decision:pt.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),GD=pt.strictObject({schemaVersion:pt.literal(1),mode:pt.enum(["local","remote"]),versionId:pt.uuid(),generation:pt.number().int().positive(),base:hv,context:hl,steps:pt.array(gv).min(1).max(gl)}).refine(e=>fn(e)<=fv,"Segment exceeds its byte budget");var yv=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function Ko(e){return Array.isArray(e)?e.some(Ko):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&Ko(n):!yv.test(t))}function zg(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=>Ko(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"||Ko(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"||Ko(s.condition)||s.parentConditions?.length)?"customer_experiment_required":null}var Al=class extends Error{constructor(n,r){super(r);Be(this,"code",n);this.name="FunnelLocalCalculationError"}},$g=(e,t)=>new Al(e,t),Av=e=>({experiments:e.experiments,features:e.features});function bv(e,t=$g){let n=new Map(e.topology.nodes.map(o=>[o.id,o])),r=Ai(e.growth.savedGroups),i=Av(e.growth);function a(o,s){if(!Object.hasOwn(e.growth.features,o))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Wn(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 m=e.conditions[c.id];if(!m)throw t("INVALID_RESPONSE","Local condition rules are unavailable");u=cl({id:c.id,name:c.id,type:"condition",cases:m.map(h=>({condition:h.condition,target:c.outputs[h.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 h=cl({id:c.id,name:c.id,type:"split",experimentId:c.resources.experimentId,routes:c.outputs,notParticipating:c.outputs.notParticipating},s,i.experiments);l=h.value,u=h.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 p=c.outputs[u]??(u==="value"?c.id:void 0);if(!p)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:o,port:u,target:p,...l===void 0?{}:{value:l}}}}}function xv(e,t){let n=Rs.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=bv(n,t);return(o,s)=>(i(),Sv(a,o,s))}function Sv(e,t,n){let r=Pt.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 Iv(e,t,n){let r=[],i=[],a=[],o=e(t,{...n.attributes?{attributes:n.attributes}:{},stickyBucketAssignmentDocs:n.sticky,saveStickyBucketAssignmentDoc(s){let c=r.findIndex(p=>p.next.attributeName===s.attributeName&&p.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 Gg(e,t,n,r=$g){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,p=!1,m,h=R=>zg(t,R,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),d=R=>(m??(m=xv(e,r)),Iv(m,R,{attributes:Pu({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:o,savedGroups:{}}),sticky:s}));for(let R=0;R<gl;R++){let y=a.get(u);if(!y||!yl(y)||h(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 C=y.type==="end"?y.output:y.value;if(A=C?.type==="feature"?d(y.id):{...A,port:"value",value:C?.type==="literal"?C.value:C?.type==="variable"?Yc({source:"variable",key:C.key,...C.path?{path:C.path}:{}},{declarations:t.variables,answers:n.answers,results:o,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},C&&(A.value===void 0||!xn(t.outputSchema,A.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let v=[...c,{nodeId:u,result:A}];if(fn({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 C=y.type==="coupons"?y.couponIds.map(_=>({type:"reward",id:_})):y.type==="coupon"?{type:"reward",id:y.couponId}:A.value;if(C===void 0)throw r("INVALID_RESPONSE","Node output is missing");let j=Pi(y,{value:C});qm(t.variables,y,j),Object.assign(o,j)}for(let C of A.sticky)s[`${C.next.attributeName}||${C.next.attributeValue}`]=structuredClone(C.next);if(y.type==="end"||y.type==="output"){p=!0;break}if(!x)throw r("INVALID_RESPONSE","Local pure exit is unavailable");u=x,l++}let g=a.get(u);return{steps:c,...!p&&g&&(!yl(g)||h(g))?{boundary:{nodeId:u,visit:l}}:{}}}var b=class extends Error{constructor(n,r,i,a,o){super(r);Be(this,"code",n);Be(this,"status",i);Be(this,"requestId",a);Be(this,"commandRequestId");Be(this,"retryable");Be(this,"recovery");Be(this,"retryAfterSeconds");Be(this,"reason");this.name="IndianaError",this.reason=o?.reason;let s=ra(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 Ho=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new b("INVALID_STATE","Installation sequence exhausted");return e+1},vv=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 zn(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 Kg(e,t,n){let r=null,i=0,a=0,o=0,s=Promise.resolve(),c=!1;if(e&&(!n||De.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 p(x){let v=u();if(!v.sha256&&!globalThis.crypto?.subtle)throw new b("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let C=v.sha256?await v.sha256(Uint8Array.from(x,j=>j.charCodeAt(0))):await vv(x);if(!/^[a-f0-9]{64}$/.test(C))throw new b("INVALID_STATE","Push credential digest is invalid");return C}function m(x){let v=kr.parse(x);if(v.installationId.toLowerCase()!==u().installationId.toLowerCase())throw new b("INVALID_RESPONSE","Push response belongs to another installation");return v}async function h(x,v){let C=u(),j={installationId:C.installationId,publicKey:C.publicKey,issuedAt:new Date().toISOString(),...v},_=await C.sign(ed(x,C.scope,j));return{...j,signature:_}}let d=(x,v,C)=>t.requestWithCredential?t.requestWithCredential(x,v,C):t.request(x,v);async function g(){let x=u(),v=i,C=r?await(t.session?.access()??r):null,j=zn(x,Se=>Se),_;if(j.detachSeq!==null){let Se=j.detachSeq,At=Wl.parse(await h("detach",{sequence:Se,platform:x.platform}));try{let Ye=await t.request("push/installations/detach",{...x.scope,...At},"POST",{installationDetach:!0});if(!Ye||typeof Ye!="object"||!("installation"in Ye))throw new b("INVALID_RESPONSE","Push detach acknowledgement is invalid");let Ne=m(Ye.installation);if(Ne.bound||Ne.identitySeq!==Se)throw new b("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(Ye){if(Ye instanceof b&&Ye.status===404)_=Ye;else if(!(Ye instanceof b)||Ye.status!==412)throw Ye}_||zn(x,Ye=>({...Ye,detachSeq:Ye.detachSeq===Se?null:Ye.detachSeq}))}if(l(v),!C){if(_)throw _;return null}let X=O.bindPushInstallation,le=X.request.parse(await h("bind",{sequence:o,platform:x.platform,credentialDigest:await p(C)}));l(v);let ye=X.response.parse(await d(X.path,le,C));l(v);let ke=m(ye.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&&zn(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 C=O.readPushInstallation,j=C.request.parse(await h("read",{credentialDigest:await p(v)}));l(x);let _=C.response.parse(await d(C.path,j,v));return l(x),m(_.installation)}function y(x=g){let v=s.catch(()=>{}).then(x);return s=v,v.catch(C=>{try{e?.onError?.(C instanceof Error?C:new Error("Push synchronization failed"))}catch{}}),v}async function A(x,v,C){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 g(),l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let ye=zn(j,Ne=>C?Ne:{...Ne,addressSeq:Ho(Ne.addressSeq)}),Se=await h(C?"recovery_confirm":"recovery_request",{...x,sequence:ye.addressSeq,credentialDigest:await p(le),...C?{challenge:C}:{}}),At=C?Xl.parse(Se):Yl.parse(Se);if(l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let Ye=await d(`push/installations/recovery/${C?"confirm":"request"}`,At,le);if(l(_),X!==a||zn(j,Ne=>Ne).addressSeq!==ye.addressSeq)throw new b("INVALID_STATE","Push observation changed during recovery");if(C){let Ne=O.updatePushAddress.response.parse(Ye),it=m(Ne.installation);if(!it.bound||it.identitySeq!==o||it.addressSeq!==ye.addressSeq||it.connectionId!==x.connectionId||it.addressStatus!=="active")throw new b("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return it}if(!Ye||typeof Ye!="object"||!("recovery"in Ye))throw new b("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return Qs.parse(Ye.recovery)})}return{recoveryObserver(){u();let x={identity:i,observation:++a};return{async request(v){return Qs.parse(await A(v,x))},async confirm(v,C){return kr.parse(await A(C,x,v))}}},identify(x){if(!e)return;o=zn(e,C=>({...C,identitySeq:Ho(C.identitySeq)})).identitySeq,r=x,i++,a++},reset(){if(e)try{zn(e,x=>{let v=Ho(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,C=o;return a++,await y(async()=>{l(v);let j=await R();return l(v),o=zn(x,X=>{if(X.identitySeq!==C)throw new b("IDENTITY_CHANGED","A newer installation intent exists");return{...X,identitySeq:Ho(Math.max(X.identitySeq,j.identitySeq)),addressSeq:Math.max(X.addressSeq,j.addressSeq)}}).identitySeq,await g()})},tokenObserver(){u();let x=++a,v=i;return async C=>{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=zn(j,Se=>({...Se,addressSeq:Ho(Se.addressSeq)})),le=O.updatePushAddress,ye=le.request.parse(await h("address",{...C,sequence:X.addressSeq,credentialDigest:await p(_)}));if(l(v),x!==a)return null;let ke=await d(le.path,ye,_);return l(v),x!==a||zn(j,Se=>Se).addressSeq!==X.addressSeq?null:m(le.response.parse(ke).installation)}}}}import{ZodError as wv}from"zod";function Hg(e,t,n,r){try{return e.parse(t)}catch(i){throw r&&i instanceof wv?new b(n,r):i}}async function ge(e,t,n,r={},i){let a=typeof r=="function"?{}:r,o=Hg(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):Hg(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 Qg(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 Jg={name:"@tinkerlandai/longplay-sdk",version:"0.10.19-rc.3",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 We(e){return typeof e=="string"?e:String(e)}var Pv=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function Cv(e){return e.replace(Pv,"$1\uFFFD")}function Il(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 iy(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 Zg(e){let t;if(Array.isArray(e)){let n=e.map(We);if(n.length===2)return n}else if((t=iy(e))!=null){let n=Il(t.next()),r=Il(t.next());if(!n.done&&!r.done)return[We(n.value),We(r.value)]}throw new TypeError("Each query pair must be an iterable [name, value] tuple")}var Wg="0123456789ABCDEF",_v=/(?:%[0-9A-Fa-f]{2})+/g;function $n(e){return`%${Wg[e>>4&15]}${Wg[15&e]}`}function oy(e,t,n=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?n&&e===32?"+":t(e)?$n(e):String.fromCharCode(e):e<=2047?$n(192|e>>6)+$n(128|63&e):e<=65535?$n(224|e>>12)+$n(128|e>>6&63)+$n(128|63&e):$n(240|e>>18)+$n(128|e>>12&63)+$n(128|e>>6&63)+$n(128|63&e)}function vl(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function wl(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(_v,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function Zo(e){return e<=31||e>126}function Ev(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return Zo(e)}}function kl(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return Zo(e)}}function Rv(e){return kl(e)||e===39}function Ol(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return kl(e)}}function Ds(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 Ol(e)}}function Yg(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 Ds(n)}})(e)}}function ay(e,t){return oy(e=e||0,t)}function Gn(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+=oy(o,t,n)}return i}function jl(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([wl(i.slice(0,a),!0),wl(i.slice(a+1),!0)])}if(n=r+1,r===e.length)break}return t}function Pl(e){let t="";for(let n=0;n<e.length;n++){let r=Gn(e[n][0],Yg,!0),i=Gn(e[n][1],Yg,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var kv=[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],jv=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],Tv=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],Nv=[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 Dv(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[Fv,Mv,qv,Xg]=[[[],"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 Uv(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 sy(e,t){for(let n=0;n<e.length;n+=2)if(t>=e[n]&&t<=e[n+1])return!0;return!1}function Qo(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 Bv(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&&sy(Nv,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&Qo(Xg,t[i]);)i--;let a=n+1;for(;a<t.length&&Qo(Xg,t[a]);)a++;if(!(i>=0&&a<t.length&&Qo(Mv,t[i])&&Qo(qv,t[a])))return!1}return!0}var Vv=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,Lv=/\p{Script=Latin}/u;function zv(e){return!Vv.test(e)||!Lv.test(e)}var br=36,js=1,Cl=26,$v=38,Gv=700,Kv=72,Hv=128,Qv=2147483647;function ey(e){return String.fromCharCode(e+22+75*+(e<26))}function Jv(e,t,n){let r=0;for(e=n?Math.floor(e/Gv):e>>1,e+=Math.floor(e/t);e>(br-js)*Cl>>1;r+=br)e=Math.floor(e/(br-js));return Math.floor(r+(br-js+1)*e/(e+$v))}function Zv(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=Kv;for(;r<t.length;){let c=Qv;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 p=o;for(let m=br;;m+=br){let h=m<=s?js:m>=s+Cl?Cl:m-s;if(p<h)break;n+=ey(h+(p-h)%(br-h)),p=Math.floor((p-h)/(br-h))}n+=ey(p),s=Jv(o,r+1,r===i),o=0,r++}}o++,a++}return n}function bl(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=vl(e.charCodeAt(r));if(i>=t||i<0)return-1;n=n*t+i}return n}function ty(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function cy(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function uy(e){return e.length===2&&cy(e.codePointAt(0),e.codePointAt(1))}function ny(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function gt(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function ly(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function _l(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,p=0;for(;p<4&&(u=vl(c[s]))>=0;)l=(l<<4)+u,s++,p++;if(c[s]===46){if(p===0||o>6)return null;s-=p;let m=0;for(;c[s]!==void 0;){let h=0;if(m>0)if(c[s]===46&&m<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(h=10*h+vl(c[s]),h>255)return null;s++}i[o]=256*i[o]+h,m++,m%2==0&&o++}if(m!==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 ny(r)?null:Gn(r,Zo)})(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 p=l.codePointAt(0);if(/[\p{Cn}\p{Co}\p{Cs}\p{Noncharacter_Code_Point}]/u.test(l)&&!sy(kv,p)||Qo(Fv,p))return!0}return!1})(i))return null;let s=(i=(function(u){let l="";for(let p of u){let m=p.codePointAt(0);if(m!==8204&&m!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(p))continue;let h=Uv(p,m);if(h){l+=h;continue}let d=jv.indexOf(m);l+=d<0?p:Tv[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(Dv(u)||l&&(/^\p{Mark}/u.test(u)||!Bv(u)||!zv(u)||u.startsWith("xn--")))return null;l&&(s[c]=`xn--${Zv(u)}`)}return(i=s.join("."))!==""?i:null})(e.indexOf("%")===-1?e:wl(e));return n===null||ny(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(bl(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=bl(a[u]);if(l<0||l>255)return null;s+=l*(1<<8*(3-u))}let c=bl(a[o-1]);return c<0||c>=256**(5-o)?null:(s+=c,s)})(n):n}}function El(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,p=0;for(let m=0;m<s.length;++m)s[m]!==0?(p>l&&(c=u,l=p),u=-1,p=0):(u===-1&&(u=m),++p);return p>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 dy(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 py(e){return e.username!==""||e.password!==""}function xl(e){return e.host===null||e.host===""||e.scheme==="file"}var E=0,U="",Oe="",$e=null,B,Ts=!1,Ns=!1,ti=!1,yt;function An(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,Oe="",$e=n||null,B=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},Ts=!1,Ns=!1,ti=!1,yt=r||0;let i=Wv;switch(r){case 3:case 4:i=Fs;break;case 5:i=Nl;break;case 6:i=ni;break;case 7:i=xr;break;case 8:i=Kn}return i(G(e,E))!==1?B:null}function ee(e,t){return E+=E===e?qn(t):1,E<=U.length}function G(e,t){return t<e.length?e.codePointAt(t):void 0}function qn(e){return e!=null&&e>65535?2:1}function my(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var Wv=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 Oe=U.slice(E,n).toLowerCase(),E=n,Yv(n<U.length?e:void 0)}else return yt?1:(--E,ee(t,e)?fy(G(U,E)):0)},Yv=e=>{let t=E;if(e===58){if(yt){if(gt(B.scheme)!==gt(Oe))return 0;if((py(B)||B.port!==null)&&Oe==="file")return 0;if(B.scheme==="file"&&B.host==="")return 0}return B.scheme=Oe,yt?(B.port===ly(B.scheme)&&(B.port=null),0):(Oe="",B.scheme==="file"?ee(t,e)?Dl(G(U,E)):0:gt(B.scheme)&&$e!==null&&$e.scheme===B.scheme?ee(t,e)?Xv(G(U,E)):0:gt(B.scheme)?ee(t,e)?tw(G(U,E)):0:G(U,E+1)===47?(E++,ee(t,e)?ew(G(U,E)):0):(B.path=[""],B.opaquePath=!0,ee(t,e)?gy(G(U,E)):0))}else return yt?1:(Oe="",E=-1,ee(t,e)?fy(G(U,E)):0)},fy=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="",ee(t,e)?Kn(G(U,E)):0):$e.scheme==="file"?(E--,ee(t,e)?Dl(G(U,E)):0):(E--,ee(t,e)?Tl(G(U,E)):0)},Xv=e=>{let t=E;return e===47&&G(U,E+1)===47?(++E,ee(t,e)?qs(G(U,E)):0):(E--,ee(t,e)?Tl(G(U,E)):0)},ew=e=>{let t=E;return e===47?ee(t,e)?Gi(G(U,E)):0:(E--,ee(t,e)?Un(G(U,E)):0)},Tl=e=>{let t=E;return B.scheme=$e.scheme,e===47||gt(B.scheme)&&e===92?ee(t,e)?ry(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="",ee(t,e)?xr(G(U,E)):0):e===35?(B.fragment="",ee(t,e)?Kn(G(U,E)):0):e!=null?(B.query=null,B.path.pop(),E--,ee(t,e)?Un(G(U,E)):0):ee(t,e)?Tl(G(U,E)):0)},ry=e=>{let t=E;return gt(B.scheme)&&(e===47||e===92)?ee(t,e)?qs(G(U,E)):0:e===47?ee(t,e)?Gi(G(U,E)):0:(B.username=$e.username,B.password=$e.password,B.host=$e.host,B.port=$e.port,E--,ee(t,e)?Un(G(U,E)):0)},tw=e=>{let t=E;return e===47&&G(U,E+1)===47?E++:E--,ee(t,e)?qs(G(U,E)):0},qs=e=>{let t=E;return e!==47&&e!==92?(E--,ee(t,e)?Gi(G(U,E)):0):ee(t,e)?qs(G(U,E)):0},Gi=e=>{let t=E;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!gt(B.scheme))){let n=E+qn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===64||r===35||r===47||r===63||r===92&>(B.scheme))break;n+=qn(r)}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?Gi(G(U,E)):0}if(e===64){Ts&&(Oe=`%40${Oe}`),Ts=!0;for(let n=0;n<Oe.length;n++){let r=Oe.codePointAt(n);if(r===58&&!Ns){Ns=!0;continue}let i=ay(r,Ds);Ns?B.password+=i:B.username+=i,r!=null&&r>65535&&n++}return Oe="",ee(t,e)?Gi(G(U,E)):0}else return e==null||e===35||e===47||e===63||e===92&>(B.scheme)?Ts&&Oe===""?1:(E-=Oe.length+1,Oe="",ee(t,e)?Fs(G(U,E)):0):(Oe+=my(e),ee(t,e)?Gi(G(U,E)):0)},Fs=e=>{let t=E;if(yt&&B.scheme==="file")return E--,ee(t,e)?Fl(G(U,E)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!gt(B.scheme))){let n=E+qn(e);for(e===91?ti=!0:e===93&&(ti=!1);n<U.length;){let r=G(U,n);if(r==null||!ti&&r===58||r===35||r===47||r===63||r===92&>(B.scheme))break;r===91?ti=!0:r===93&&(ti=!1),n+=qn(r)}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?Fs(G(U,E)):0}else if(e===58&&!ti){if(Oe===""||yt===4)return 1;let n=_l(Oe,!gt(B.scheme));return n===null?1:(B.host=El(n),Oe="",ee(t,e)?Nl(G(U,E)):0)}else if(e==null||e===35||e===47||e===63||e===92&>(B.scheme)){if(E--,gt(B.scheme)&&Oe==="")return 1;if(yt&&Oe===""&&(py(B)||B.port!==null))return 1;let n=_l(Oe,!gt(B.scheme));return n===null?1:(B.host=El(n),Oe="",yt?0:ee(t,e)?ni(G(U,E)):0)}else return Oe+=my(e),ee(t,e)?Fs(G(U,E)):0},Nl=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 Oe+=U.slice(E,n),E=n-1,ee(t,e)?Nl(G(U,E)):0}else if(yt||e==null||e===35||e===47||e===63||e===92&>(B.scheme)){if(Oe!==""){let n=parseInt(Oe,10);if(n>65535)return 1;if(B.port=n===ly(B.scheme)?null:n,Oe="",yt)return 0}return yt?1:(E--,ee(t,e)?ni(G(U,E)):0)}else return 1};function hy(e,t){let n=e.length-t;if(n<2)return!1;if(cy(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?ee(t,e)?nw(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="",ee(t,e)?xr(G(U,E)):0):e===35?(B.fragment="",ee(t,e)?Kn(G(U,E)):0):e!=null?(B.query=null,hy(U,E)?B.path=[]:dy(B),E--,ee(t,e)?Un(G(U,E)):0):ee(t,e)?Dl(G(U,E)):0):(E--,ee(t,e)?Un(G(U,E)):0)},nw=e=>{let t=E;return e===47||e===92?ee(t,e)?Fl(G(U,E)):0:($e!==null&&$e.scheme==="file"&&(!hy(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--,ee(t,e)?Un(G(U,E)):0)},Fl=e=>{let t=E;if(e!=null&&e!==47&&e!==92&&e!==63&&e!==35){let n=E+qn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===47||r===92||r===63||r===35)break;n+=qn(r)}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?Fl(G(U,E)):0}else if(e==null||e===47||e===92||e===63||e===35){if(E--,!yt&&uy(Oe))return ee(t,e)?Un(G(U,E)):0;if(Oe==="")return B.host="",yt?0:ee(t,e)?ni(G(U,E)):0;{let n=_l(Oe,!gt(B.scheme));return n===null?1:(n==="localhost"&&(n=""),B.host=El(n),Oe="",yt?0:ee(t,e)?ni(G(U,E)):0)}}return 1},ni=e=>{let t=E;return gt(B.scheme)?(e!==92&&e!==47&&E--,ee(t,e)?Un(G(U,E)):0):!yt&&e===63?(B.query="",ee(t,e)?xr(G(U,E)):0):!yt&&e===35?(B.fragment="",ee(t,e)?Kn(G(U,E)):0):e!=null?(e!==47&&E--,ee(t,e)?Un(G(U,E)):0):(yt&&B.host===null&&B.path.push(""),ee(t,e)?ni(G(U,E)):0)},Un=e=>{let t=E;if(e!=null&&e!==47&&(!gt(B.scheme)||e!==92)&&(yt||e!==63&&e!==35)){let n=E+qn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===47||gt(B.scheme)&&r===92||!yt&&(r===63||r===35))break;n+=qn(r)}Oe+=Gn(U.slice(E,n),Ol),E=n,e=G(U,n)}if(e==null||e===47||gt(B.scheme)&&e===92||!yt&&(e===63||e===35)){let n=gt(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}})(Oe)?(dy(B),e!==47&&!n&&B.path.push("")):ty(Oe)&&e!==47&&!n?B.path.push(""):ty(Oe)||(B.scheme==="file"&&B.path.length===0&&uy(Oe)&&(Oe=`${Oe[0]}:`),B.path.push(Oe)),Oe="",e===63?(B.query="",ee(t,e)?xr(G(U,E)):0):e===35?(B.fragment="",ee(t,e)?Kn(G(U,E)):0):ee(t,e)?Un(G(U,E)):0}else return Oe+=ay(e,Ol),ee(t,e)?Un(G(U,E)):0},gy=e=>{let t=E;if(e===63)return B.query="",ee(t,e)?xr(G(U,E)):0;if(e===35)return B.fragment="",ee(t,e)?Kn(G(U,E)):0;if(e!=null){let n=E+qn(e);for(;n<U.length;){let i=G(U,n);if(i===63||i===35)break;n+=qn(i)}let r=U.slice(E,n);if(n<U.length&&r.charCodeAt(r.length-1)===32?B.path[0]+=Gn(r.slice(0,-1),Zo)+"%20":B.path[0]+=Gn(r,Zo),E=n,(e=G(U,n))===63)return B.query="",ee(t,e)?xr(G(U,E)):0;if(e===35)return B.fragment="",ee(t,e)?Kn(G(U,E)):0}return ee(t,e)?gy(G(U,E)):0},xr=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=gt(B.scheme)?Rv:kl;B.query+=Gn(U.slice(E,n),r)}return E=n,G(U,n)===35&&!yt?(B.fragment="",ee(t,e)?Kn(G(U,E)):0):ee(t,e)?xr(G(U,E)):0},Kn=e=>{let t=E;return e!=null&&(B.fragment+=Gn(U.slice(E),Ev),E=U.length),ee(t,e)?Kn(G(U,E)):0};function Rl(e){if(e.opaquePath)return e.path[0];{let t="";for(let n of e.path)t+=`/${n}`;return t}}function yy(e){switch(e.scheme){case"blob":{let t=An(Rl(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":yy(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 Ze=Symbol("URLImpl"),wn=class e{constructor(t,n){if(t===void 0&&n===void 0)throw new TypeError('The "url" argument must be specified.');t=We(t),n!=null&&(n=We(n));let r=null;if(n!=null&&(r=An(n,null,null,0),r==null))throw new TypeError(`Invalid base URL: ${n}`);let i=An(t,null,r,0);if(i==null)throw new TypeError(`Invalid URL: ${t}`);this[Ze]={url:i,query:null}}static createObjectURL(t){throw new TypeError("URL.createObjetURL is unsupported")}static revokeObjectURL(t){}static parse(t,n){t=We(t),n!==void 0&&(n=We(n));try{return new e(t,n)}catch{return null}}static canParse(t,n){t=We(t),n!==void 0&&(n=We(n));let r=null;return n!=null&&(r=An(n,null,null,0),r==null)?!1:An(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+=Rl(n),n.query!==null&&(r+=`?${n.query}`),n.fragment!==null&&(r+=`#${n.fragment}`),r})(this[Ze].url)}set href(t){let n=An(t=We(t),null,null,0);if(n==null)throw new TypeError(`Invalid URL: ${t}`);this[Ze].url=n,this[Ze].query&&Sl(this[Ze].query,n.query)}get origin(){return yy(this[Ze].url)}get protocol(){return`${this[Ze].url.scheme}:`}set protocol(t){An(`${t=We(t)}:`,this[Ze].url,null,2)}get username(){return this[Ze].url.username}set username(t){t=We(t),xl(this[Ze].url)||(function(r,i){r.username=Gn(i,Ds)})(this[Ze].url,t)}get password(){return this[Ze].url.password}set password(t){t=We(t),xl(this[Ze].url)||(function(r,i){r.password=Gn(i,Ds)})(this[Ze].url,t)}get host(){let{url:t}=this[Ze];return t.host==null?"":t.port==null?t.host:`${t.host}:${t.port}`}set host(t){t=We(t),this[Ze].url.opaquePath||An(t,this[Ze].url,null,3)}get hostname(){let{url:t}=this[Ze];return t.host!=null?t.host:""}set hostname(t){t=We(t),this[Ze].url.opaquePath||An(t,this[Ze].url,null,4)}get port(){let{url:t}=this[Ze];return t.port!=null?`${t.port}`:""}set port(t){t=We(t);let{url:n}=this[Ze];xl(n)||(t?An(t,n,null,5):n.port=null)}get pathname(){return Rl(this[Ze].url)}set pathname(t){t=We(t);let{url:n}=this[Ze];n.opaquePath||(n.path=[],An(t,n,null,6))}get search(){let{url:t}=this[Ze];return t.query?`?${t.query}`:""}set search(t){t=We(t);let{url:n,query:r}=this[Ze];if(!t)n.query=null,r&&Sl(r,null);else{let i=t[0]==="?"?t.substring(1):t;n.query="",An(i,n,null,7),r&&Sl(r,n.query)}}get searchParams(){let t=this[Ze],n=t.query;return n==null&&(n=t.query=(function(i,a){let o=new Ms;return o[lt].url=i,o[lt].serialized=a==null,a&&(o[lt].list=jl(a)),o})(this,t.url.query)),n}get hash(){let{url:t}=this[Ze];return t.fragment?`#${t.fragment}`:""}set hash(t){t=We(t);let{url:n}=this[Ze];if(!t)n.fragment=null;else{let r=t[0]==="#"?t.substring(1):t;n.fragment="",An(r,n,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(wn.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var lt=Symbol("URLSearchParamsImpl"),rw=Symbol.dispose||Symbol.for("dispose");function Sl(e,t){t?e[lt].list=jl(t):e[lt].list.length=0,e[lt].serialized=t==null}function ks(e){if(e.url){let t=Pl(e.list);(function(r,i){r[Ze].url.query=i})(e.url,t||null),e.serialized=!0}}var iw=typeof Iterator<"u"?Iterator:Object,Jo=class extends iw{constructor(t,n){super(),this[lt]={ptr:t,map:n,index:0}}next(){let t=this[lt];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}[rw](){}},Ms=class{constructor(t){let n=this[lt]={list:[],url:null,serialized:!0},r;if(Array.isArray(t))for(let i=0;i<t.length;i++)n.list.push(Zg(t[i]));else if((r=iy(t))!=null){let i;for(;!(i=Il(r.next())).done;)n.list.push(Zg(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=Cv(o),c=We(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=We(t);i=i[0]==="?"?i.substring(1):i,n.list=jl(i)}}get size(){return this[lt].list.length}append(t,n){t=We(t),n=We(n),this[lt].list.push([t,n]);let r=this[lt];r.url&&r.serialized?(function(a,o){let s=a[Ze].url;s.query=s.query?`${s.query}&${o}`:o})(r.url,Pl([[t,n]])):ks(r)}delete(t,n){t=We(t),n=n!=null?We(n):void 0;let{list:r}=this[lt],i=0;for(;i<r.length;)r[i][0]===t&&(n==null||r[i][1]===n)?r.splice(i,1):i++;ks(this[lt])}get(t){t=We(t);let{list:n}=this[lt];for(let r=0;r<n.length;r++)if(n[r][0]===t)return n[r][1];return null}getAll(t){t=We(t);let n=[],{list:r}=this[lt];for(let i=0;i<r.length;i++)r[i][0]===t&&n.push(r[i][1]);return n}has(t,n){t=We(t),n=n!=null?We(n):void 0;let{list:r}=this[lt];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=We(t),n=We(n);let{list:r}=this[lt],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&&ks(this[lt])}sort(){this[lt].list.sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0),ks(this[lt])}forEach(t,n){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:r}=this[lt];for(let i=0;i<r.length;i++)t.call(n,r[i][1],r[i][0],this)}entries(){return new Jo(this[lt],t=>t)}keys(){return new Jo(this[lt],t=>t[0])}values(){return new Jo(this[lt],t=>t[1])}toString(){return Pl(this[lt].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(Ms.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var Sr="https://api.longplayai.com";function Ay(e){let t,n=()=>typeof t=="string"?t:t?.accessToken,r=0,i,a=new Map,o=()=>{for(let p of[...a.keys()])try{p()}catch{}};function s(p){let m=++r;i=void 0,t=void 0;for(let h of[...a.values()])try{h?.()}catch{}m===r&&(t=p,o())}let c=()=>s();function u(p,m=!1){let h=ar.safeParse(p);if(!h.success||m&&Date.parse(h.data.expiresAt)<=Date.now()||Date.parse(h.data.refreshExpiresAt)<=Date.now()||Date.parse(h.data.refreshExpiresAt)<Date.parse(h.data.expiresAt))throw new b("INVALID_RESPONSE","Invalid customer session credentials");return h.data}async function l(){if(i)return i;let p=typeof t=="object"?t:void 0,m=r;if(!p||Date.parse(p.refreshExpiresAt)<=Date.now())throw p&&c(),new b("UNAUTHENTICATED","Customer authentication is required",401);let h=(async()=>{try{let d=await e(p.refreshToken);if(m!==r)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");let g=u(d,!0);if(g.customerId!==p.customerId||g.sessionId!==p.sessionId)throw new b("SCOPE_MISMATCH","Refresh changed the customer session");return t=g,{...g}}catch(d){throw m!==r?new b("IDENTITY_CHANGED","Customer identity changed during refresh"):(d instanceof b&&d.status===401&&c(),d)}})();i=h;try{return await h}finally{i===h&&(i=void 0)}}return{identify(p){let m=typeof p=="string"?p:u(p),h=typeof m=="string"?m:m.accessToken;if(!h.trim()||/\s/.test(h)||h.length>4096)throw new b("INVALID_TOKEN","A server-issued token is required");s(m)},reset:c,subscribeIdentity(p,m){return a.set(p,m),()=>{a.delete(p)}},access(){let p=typeof t=="object"?t:void 0;if(p&&Date.parse(p.expiresAt)<=Date.now()+3e4){let h=r;return l().then(()=>{let d=n();if(h!==r||!d)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");return d})}let m=n();if(!m)throw new b("NOT_IDENTIFIED","Identify a customer session before making a request");return m},peek:n,snapshot:()=>typeof t=="object"?{...t}:void 0,refresh:l}}var by=Symbol("IndianaNoContent");function Ir(e,t,n=wn){let r=e.configuration?.scope,i=e.scope??(r&&{projectId:r.projectId,environment:r.environment}),a=i?De.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??Sr);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,p=null,m=new Set,h=e.session??Ay(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:C,...j}=x;return j});function d(){l+=1,p=null;for(let A of m)A.abort();m.clear()}let g=h.subscribeIdentity(d);function R(){u||h.reset()}async function y(A,x={},v="POST",C={},j){let _=C.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;_||m.add(le);let ye=()=>!_&&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((Ne,it)=>{ke=()=>it(ye()),le.signal.addEventListener("abort",ke,{once:!0})}),At=setTimeout(()=>le.abort(),C.timeoutMs??c),Ye=async()=>{let Ne=await s(`${o.href.replace(/\/$/,"")}/api/v1/${A}`,{method:v,headers:{...C.headers,"Content-Type":"application/json",..._?{}:{Authorization:`Bearer ${j}`},[Xs]:ec.current,[od]:Jg.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",...C.keepalive?{keepalive:!0}:{}});if(le.signal.aborted)throw ye();let it;try{it=Ne.status===204?by:await Ne.json()}catch{throw le.signal.aborted?ye():new b(Ne.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",Ne.status,Ne.headers.get("X-Request-Id")??void 0)}if(le.signal.aborted)throw ye();if(!_&&X!==l)throw new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!Ne.ok){let ft=Ys.safeParse(it),Xt=ft.success&&(!Jn.safeParse(ft.data.error.code).success||rd(ft.data.error.code,Ne.status)),Cr=Xt?ft.data.error.code:"HTTP_ERROR",_r=ra(Cr,Ne.status,{retryAfter:Ne.headers.get("Retry-After"),recovery:Xt?ft.data.error.recovery:void 0,reason:Xt?ft.data.error.reason:void 0});throw new b(Cr,Xt?ft.data.error.message:"Longplay request failed",Ne.status,Ne.headers.get("X-Request-Id")??(ft.success?ft.data.requestId:void 0),{..._r,...ft.success&&ft.data.error.retryable===!1?{retryable:!1}:{},..._r.retryAfterSeconds===void 0&&ft.success&&ft.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:ft.data.error.retryAfterSeconds}:{}})}if(Ne.headers.get(Xs)!==ec.current)throw new b("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&it!==by){let ft=it&&typeof it=="object"&&"scope"in it?it:it&&typeof it=="object"&&"configuration"in it?it.configuration:null;if(!ft||typeof ft!="object"||!("scope"in ft))throw new b("INVALID_RESPONSE","Response is missing its App/environment scope");let Xt=De.safeParse(ft.scope);if(!Xt.success||Xt.data.projectId!==a.projectId||Xt.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let ii=Ne.headers.get("X-Indiana-Telemetry-Subject");if(ii){if(!/^[a-f0-9]{64}$/.test(ii))throw new b("INVALID_RESPONSE","Invalid telemetry identity");p!==ii&&(p=ii,t?.(p))}return it};try{return await Promise.race([Ye(),Se])}catch(Ne){throw!_&&X!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):Ne instanceof b?Ne: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),m.delete(le)}}return{session:h,requestWithCredential(A,x,v,C={}){return u?Promise.reject(new b("CLOSED","SDK client was destroyed")):y(A,x,"POST",C,v)},subjectKey:()=>p,identify(A){if(u)throw new b("CLOSED","SDK client was destroyed");if(a&&typeof A=="object"&&"scope"in A){let x=De.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")}h.identify(A)},reset:R,dispose(){u||(u=!0,g(),d())},request(A,x={},v="POST",C={}){if(u)return Promise.reject(new b("CLOSED","SDK client was destroyed"));if(C.installationDetach)return y(A,x,v,C);let j=l;try{let _=h.access(),X=le=>{if(j!==l)throw new b("IDENTITY_CHANGED","Customer identity changed before dispatch");return y(A,x,v,C,le)};return typeof _=="string"?X(_):_.then(X)}catch(_){return Promise.reject(_)}}}}function xy(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(!Ft.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 Ml(e,t,n,r){if(!Ld(e,t)||n!==void 0&&t.observation&&t.observation.subject.customerId!==n||r!==void 0&&t.observation!==void 0&&(t.observation.subject.scope.projectId!==r.projectId||t.observation.subject.scope.environment!==r.environment))throw new b("INVALID_RESPONSE","The access requirement or Customer changed");return t}function vr(e,t,n){if(e.requirement){if(!t)throw new b("INVALID_RESPONSE","The requested access check is missing");Ml(e.requirement,t,e.customerId,n)}}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 ow={...O.readHoldings,request:O.readHoldings.request.omit({customerId:!0})};function Sy(e){return{async checkEntitlement(t){Ge(t);let n=O.checkEntitlement,r=n.request.parse(t),i=await ge(e,n,r);return Ml(r.requirement,i.check,void 0,i.scope),i},async readHoldings(t={}){return ge(e,ow,t)}}}function Iy(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 vy(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 wy(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 Oy(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 Py(e){return{...Sy(e),...Iy(e),...vy(e),...wy(e),...Oy(e)}}function Cy(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,r=n.request.parse(t),i=await ge(e,n,r);return vr(r,i.paywall.check,i.scope),i},async resolveOffering(t){Ge(t);let n=O.resolveOffering,r=n.request.parse(t),i=await ge(e,n,r);return vr(r,i.check,i.scope),i}}}var ql=e=>new TextEncoder().encode(JSON.stringify(e)).length,_y=16384;function Ey(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,p().catch(()=>{}).finally(u)},5e3),typeof s=="object"&&"unref"in s&&s.unref())}function l(d,g={},R={}){if(c(),r&&Date.now()<r.until&&!Vf(r.config,d))return;h();let y=O.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:d,properties:g,...R}]}).events[0];if(ql({events:[y]})>_y)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 p(d=!1){if(c(),o)return o;let g=n,R=(async()=>{let y={inserted:0,duplicates:0,rejected:0,skipped:0},A=a.length;for(;A&&g===n;){let x=[],v=ql({events:[]});for(let _ of a.slice(0,Math.min(A,100))){let X=ql(_)+(x.length?1:0);if(x.length&&v+X>_y)break;x.push(_),v+=X}let C=O.trackEvents,j=await ge(e,C,{events:x},void 0,{keepalive:d});if(g!==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 m;function h(){if(m||typeof document>"u")return;let d=()=>{document.visibilityState==="hidden"&&t()&&a.length&&p(!0).catch(()=>{})};document.addEventListener("visibilitychange",d),m=()=>document.removeEventListener("visibilitychange",d)}return{rememberConfiguration:i,track:l,flush:p,reset(){n++,r=void 0,clearTimeout(s),s=void 0,a=[],o=null},detachVisibility(){m?.(),m=void 0}}}function Ul(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:Pt.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},p=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function m(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=>m(v.id,A))))}let h=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()?p():structuredClone(o.features[y]??p()):e.evaluateRemote&&(l.attributes?.merchandise||l.attributes?.merchandiseId)&&!o||m(y)?p():structuredClone(Wn(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],C=(async()=>{let j=as.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=Pt.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:C};try{await C}finally{s?.loading===C&&(s=null)}}function g(){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?jo.parse(x):null,C=v??Sn.parse(x);if(C.scope.projectId!==e.scope.projectId||C.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===C.generation){let{evaluatedAt:_,expiresAt:X,...le}=t,{evaluatedAt:ye,expiresAt:ke,...Se}=C;if(_t(le)!==_t(Se))throw new Error("Immutable Feature generation changed content");return t.evaluatedAt=C.evaluatedAt,t.expiresAt=C.expiresAt,u(),(!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())&&g(),structuredClone(t)}let j=new Set(v?.remoteFeatures??[]);if([...j].some(_=>Object.hasOwn(C.features,_)))throw new Error("Remote Feature definitions must not be delivered locally");return t&&"analyticsConfig"in t&&"analyticsConfig"in C&&!t.analyticsConfig.experimentViewsEnabled&&v?.analyticsConfig.experimentViewsEnabled&&l.trackedExperiments?.clear(),t=structuredClone(C),a=j,o=null,s=null,i++,l.features=t.features,l.savedGroups=Ai(t.savedGroups),l.trackedFeatureUsage={},u(),g(),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=Pt.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(),g()},evalFeature:h,isOn(y){return h(y).on},isOff(y){return h(y).off},getFeatureValue(y,A){let x=h(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 Ry(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 aw(e){let t=Ry(e),{merchandiseId:n,merchandise:r,...i}=e;return{...i,...t?{merchandise:t}:{}}}function ky(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,p=!1,m=async()=>{if(p||l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let ye=O.getFeatures,ke=i?{scope:{projectId:i.scope.projectId,environment:i.scope.environment},payload:await i.features()}:await ge(e,ye,{});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},h=await m(),d=!0,g,R=ye=>{try{u.onError?.(ye)}catch{}},y=(ye,ke,Se)=>{try{let At=Ry(Se);n.track(ye,ke,At?{merchandise:At}:{})}catch(At){R(At)}},A=Ul({assertUsable:i?.assertFeatures,scope:h.scope,attributes:u.attributes,onError:u.onError,load:async()=>d?(d=!1,h.payload):(await m()).payload,evaluateRemote:async ye=>{if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let ke=O.evaluateFeatures,Se=await ge(e,ke,{...ye,attributes:aw(ye.attributes)});if(Se.scope.projectId!==h.scope.projectId||Se.scope.environment!==h.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:(ye,ke,Se)=>y("Experiment Viewed",{experimentId:ye.key,variationId:ke.key},Se),onFeatureUsage:(ye,ke,Se)=>y("Feature Evaluated",{feature:ye,value:ke.value,source:ke.source,ruleId:ke.ruleId,...ke.experimentResult?{variationId:ke.experimentResult.key}:{}},Se)}),x=A.refresh;function v(){clearTimeout(g),!i&&(p||l!==a||!A.expiresAt||(g=setTimeout(()=>{C().catch(R)},Math.min(2147483647,Math.max(1e3,Date.parse(A.expiresAt)-Date.now()))),typeof g=="object"&&"unref"in g&&g.unref()))}async function C(){try{return await x()}finally{v()}}let j=()=>{p||C().catch(R)},_=A.subscribe(v),X=i?.subscribe(()=>{!p&&i.fresh&&C().catch(R)});function le(){p||(p=!0,clearTimeout(g),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(ye){throw le(),ye}return v(),!i&&typeof window<"u"&&window.addEventListener("focus",j),Object.assign(A,{refresh:C,destroy:le})}return{features:c,reset(u){a++,u();for(let l of o)l()}}}import{z as sw}from"zod";function jy(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=sw.object({funnelId:Cs.shape.id,funnelVersionId:Cs.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,c=s.request.parse(a(o)),u=await ge(e,s,c);return vr(c,u.check,u.scope),u},async resolvePaywall(o){let s=O.resolvePaywall,c=s.request.parse(a(o)),u=await ge(e,s,c);return vr(c,u.paywall.check,u.scope),u},async previewAttach(o){let s=O.previewAttach;return ge(e,s,a(o))}}}function Ty(e){let t=Ir(e),n=t.request,r;try{r=Kg(e.push,t,e.scope??e.configuration?.scope)}catch(s){throw t.dispose(),s}let i=xy(t,()=>{o.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=Ey(n,i.isIdentified),o=ky(n,i.isIdentified,a,e.scope,e.configuration);return{session:t.session,...Qg(n,r),...Py(n),...Cy(n),forFunnel(s){return i.assertActive(),jy(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 Ki(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)=>Ki(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)&&Ki(a,Reflect.get(t,i)))}function Us(e,t){let n=Eg.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 Hi=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function Bs(e){let t=Ft.test(e.apiKey);if(typeof window<"u"&&!t)throw new b("SERVER_ONLY","Funnel starts are issued by your backend");if(!t&&!Hi.test(e.apiKey))throw new b("INVALID_TOKEN","A customer credential or server API key is required");return{async start(n){let r=Ct.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=Ir({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||a.identify(e.apiKey);let o=Us(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")||!Ki(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 Bl(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((p,m)=>{s=()=>m(n.signal?.reason),n.signal?.addEventListener("abort",s,{once:!0}),n.signal?.aborted&&s()});try{for(;;){let p=await Promise.race([r.read(),c]);if(p.done){o=!0;break}if(a+=p.value.length,a>t)throw n.error("limit");i.push(p.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 p of i)u.set(p,l),l+=p.length;return u}async function Ny(e,t,n){return new TextDecoder("utf-8",{fatal:!0}).decode(await Bl(e,t,n))}function Vs(e,t){let n=typeof e=="string"?new TextEncoder().encode(e):e;return n.byteLength===t.byteLength&&Ju(n)===t.sha256}async function Ls(e,t){let n=Zr.parse(t),{artifact:r,environmentId:i}=n.content,a=new wn(e.baseUrl??Sr).origin,o=new wn(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((p,m)=>{c=setTimeout(()=>{let h=new b("TIMEOUT","Public Paywall read timed out");s.abort(h),m(h)},sn.initializationMs)}),l=(async()=>{let p=await(e.fetch??globalThis.fetch)(o,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:s.signal});if(s.signal.aborted&&(p.body?.cancel().catch(()=>{}),s.signal.throwIfAborted()),!p.ok||!p.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(p.headers.get("content-length"))>r.byteLength)throw p.body?.cancel().catch(()=>{}),new b("INVALID_RESPONSE","Public Paywall is unavailable");let m=await Bl(p,r.byteLength,{signal:s.signal,error:h=>new b("INVALID_RESPONSE",h==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!Vs(m,r))throw new b("INVALID_RESPONSE","Public Paywall digest or size changed");return Fh(n,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(m)))})();try{return await Promise.race([l,u])}finally{clearTimeout(c)}}var Dy=(e,t)=>new b(e,t);var cw=3,uw=2e3;function lw(e){return e instanceof TypeError||e instanceof b&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function dw(e){for(let t=1;;t++)try{return await e.refresh()}catch(n){if(t===cw||!lw(n))throw n;await new Promise(r=>setTimeout(r,t*uw))}}async function Vl(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=pw(e,t,o)}catch{i=null}return a??(a=e.snapshot?.generation??(await dw(e)).generation),{advance:{policyRevision:r.policyRevision,generation:a},prediction:i}}function pw(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=fl({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:Sn.parse(o)}),c=mw(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 mw(e,t,n){return Gg(e,t,n,Dy)}import{z as bn}from"zod";var Fy=Ct.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}),My=bn.strictObject({schemaVersion:bn.literal(1),scope:De,runId:bn.uuid(),funnelId:bn.uuid(),versionId:bn.uuid(),processBindingIds:bn.record(bn.uuid(),bn.uuid().nullable()).optional(),command:Fy.optional(),closeCommand:Fy.refine(e=>e.operation==="close").optional(),purchase:bn.strictObject({receiptId:bn.uuid(),operationId:bn.uuid(),generation:bn.number().int().nonnegative()}).optional(),closed:bn.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"),rn=()=>new b("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),zs=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function qy(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:My.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 p=await a();if(p.entry&&n!==null&&r(p.entry)!==n)throw rn();let m=u(p.entry,p.revision);if(zs(p.entry,m)){t=p.revision;return}let h=await e.write(p.revision,m);if(h!==null){if(!Number.isSafeInteger(h)||h<=p.revision)throw rn();t=h;return}}throw rn()}function c(u,l){if(!u||!l)return u;if(u.processBindingIds&&Object.hasOwn(u.processBindingIds,l)){let p={...u.processBindingIds};delete p[l],u={...u,processBindingIds:p}}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 rn();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=My.parse(u),p=l.command;return!p||n!==null&&r(l)!==n?Promise.reject(rn()):(n??(n=r(l)),o(()=>s((m,h)=>{if(m&&!zs(r(m),r(l)))throw rn();if(m&&l.processBindingIds){for(let[d,g]of Object.entries(l.processBindingIds))if(m.processBindingIds&&Object.hasOwn(m.processBindingIds,d)&&m.processBindingIds[d]!==g)throw rn();m={...m,processBindingIds:{...m.processBindingIds,...l.processBindingIds}}}if(!m){if(h!==t&&p.operation!=="close")throw rn();return l}if(!m.command)return{...m,command:p,...p.operation==="close"?{closed:!0}:{}};if(p.operation==="close"&&m.command.operation!=="close"){if(m.command.requestId===p.requestId||m.closeCommand&&!zs(m.closeCommand,p))throw rn();return{...m,closeCommand:p,closed:!0}}if(!zs(m.command,p))throw rn();return m})))},observePurchase(u,l,p,m){return o(()=>s((h,d)=>{if(!h&&d!==t||h&&r(h)!==r({...u,schemaVersion:1}))throw rn();if(h?.purchase&&h.purchase.generation>l.generation)return c(h,m);if(h?.purchase&&h.purchase.generation===l.generation&&h.purchase.operationId!==l.operationId)throw rn();return p?!h?.purchase||h.purchase.operationId!==l.operationId?c(h,m):c(h.command?{...h,purchase:void 0}:null,m):c({schemaVersion:1,...u,...h,purchase:l},m)}))},settle(u){return o(()=>s(l=>c(l,u)))}}}function Uy(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??Sr).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 By(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(p){if(n&&(n.projectId!==p.projectId||n.environment!==p.environment))throw new b("SCOPE_MISMATCH","Run scope changed");n??(n={...p})},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(p,m="Run identity changed during the request"){if(p!==i||s)throw new b("IDENTITY_CHANGED",m)},assertRun(p){if(r&&(p.id!==r.id||p.source.type!==r.source.type||p.source.id!==r.source.id||p.source.versionId!==r.source.versionId||p.locale!==r.locale||!Ki(p.parameters,r.parameters)))throw new b("INVALID_RESPONSE","Run version changed");if(e&&p.source.id!==e)throw new b("INVALID_RESPONSE","Run belongs to another Funnel")},publish(p,m,h,d,g){if(!(p.operation==="review"&&r&&r!==h&&m.run.revision<=r.revision)&&!(r&&m.run.revision===r.revision&&d!==void 0&&d<u)&&(p.operation==="review"&&!m.run.stopped&&["running","waiting"].includes(m.run.status)&&r&&m.run.nodeId===r.nodeId&&m.run.visit===r.visit&&m.run.revision===r.revision&&(m.run.screen=r.screen,(r.paywall?.quote?.operationId===m.review?.activeOperationId||!r.paywall?.quote&&m.review?.activeOperationId===null)&&(m.run.paywall=r.paywall)),!(r?.paywall&&m.run.paywall&&r.paywall.receiptId===m.run.paywall.receiptId&&(m.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||m.run.revision>=r.revision)r=m.run;else if(!g)return;if(r)for(let R of l)try{R(structuredClone(r))}catch{}}},identify(p){if(s)throw new b("IDENTITY_CHANGED","Controller was reset");if(!Ft.test(p))throw new b("INVALID_TOKEN","Customer credential required");o(),c=p},subscribe(p){return l.add(p),()=>l.delete(p)},reset(){s||(s=!0,o(),c=void 0,r=null,l.clear())}}}function wr(e){let{customerToken:t,...n}=e;return n}var fw=e=>!(e instanceof b)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function Vy({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,p=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();p.catch(()=>{});async function m(y){e&&await p;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:wr(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&&!fw(v)&&(e&&await e.settle(y.requestId),A===t.generation&&R(y)),v}}function h(y){let A=Ct.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 g(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(wr(a))!==JSON.stringify(wr(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(wr(i))!==JSON.stringify(wr(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=m(y);s[A]=x;let v=()=>{s[A]===x&&(s[A]=null)};return x.then(v,v),x}function g(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:p,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 C=y.operation==="get"?y.settlementRequestId:"requestId"in y&&y.operation!=="start"?y.requestId:void 0,j=C&&A.settlement?.state==="settled"&&A.run.pendingRequest?.requestId!==C&&(y.operation==="get"||!o||y.operation==="close"||!["running","waiting"].includes(A.run.status))?C: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,ye=le?.operation,ke=A.settlement&&(!X||X.purchaseRequestId===A.settlement.requestId)&&(!u||u.operationId===A.settlement.operationId)?A.settlement:void 0,Se=ye?.operationId??le?.quote?.operationId??ke?.operationId,At=le?.receiptId??ke?.receiptId,Ye=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||Ye>=u.generation)){let Ne={receiptId:At,operationId:Se,generation:Ye},it=ye?.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},Ne,it,j),t.assertCurrent(x),(!u||Ne.generation>=u.generation)&&(v===void 0||v>=t.readSequence)&&(it?u?.operationId===Ne.operationId&&(u=void 0):u=Ne)}else e&&j&&await e.settle(j);return t.assertCurrent(x),j?R(_):!1},stop(){o=!0},submit:h,settle:g,reset(){o=!0,i=null,a=null,u=void 0,l=null,s.close=null,c.clear(),s.command=null}}}function Or(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"||!Hi.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=Ir({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),n=By(e.funnelId,e.scope??e.configuration?.scope),r=e.session?.subscribeIdentity(u),i=null,a=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?Uy(e):void 0),o=a&&qy(a),s=Vy({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),C=n.customerToken??("customerToken"in A?A.customerToken:void 0);if(e.session){let X=n.signal,le,ye=()=>{},ke=new Promise((Se,At)=>{ye=()=>At(X.reason),X.addEventListener("abort",ye,{once:!0}),le=setTimeout(()=>At(new b("TIMEOUT","Longplay request timed out")),Math.max(1,v-performance.now()))});try{C=await Promise.race([Promise.resolve().then(()=>(n.assertCurrent(x),e.session.access())),ke])}finally{clearTimeout(le),X.removeEventListener("abort",ye)}}n.assertCurrent(x);let j={...A,...C?{customerToken:C}:{}},_=A.operation==="page_experiments"?Go.parse(j):Ct.parse(j);return t.requestWithCredential("funnels",_,e.runToken,{headers:e.serverKey&&!C?{[Rg]: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,C=()=>n.assertCurrent(v);o&&await s.ready,C();let j=n.view,_=Us(e,await c(A));if(A.operation==="review"&&!_.review)throw new b("INVALID_RESPONSE","Historical projection is missing");if(C(),_.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||(C(),["running","waiting"].includes(_.run.status)||s.stop(),n.publish(A,_,j,x,le)),_}let p=s.submit,m=null,h=new WeakMap;function d(A){let x=h.get(A);if(x)return x;let v=R(A);return h.set(A,v),v}let g=!1;async function R(A){let x=await A;if(x.run.instruction?.type!=="evaluate_segment")return x;if(m)return m;g=!0;let v=n.generation,C=(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 Vl(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 ye=!0;Vl(e.configuration,_).then(({prediction:ke})=>{ye&&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 p({operation:"commit_segment",requestId:_g(_.id,_.visit,`segment:${_.revision}`),nodeId:_.nodeId,visit:_.visit,revision:_.revision,...le})}finally{ye=!1,i=null}}}return x})();m=C;try{return await C}finally{m===C&&(m=null)}}let y={get configuration(){return g?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(wr(A)):null},get pendingCommands(){return[s.pending,s.closing].filter(A=>A!==null).map(A=>structuredClone(wr(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 Ls(e,A)},async pageExperiments(A,x=[]){let v=n.generation;n.assertCurrent(v);let C=n.view?.id;if(!C)throw new b("INVALID_REQUEST","Read the Run before its page experiments");let j=Ng.parse(await c(Go.parse({operation:"page_experiments",release:A,usedReceiptIds:x})));if(n.assertCurrent(v),j.runId!==C||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(p(s.pending)):d(p({operation:"resume",requestId:A})):Promise.reject(new b("INVALID_REQUEST","No interrupted command is available"))},submit(A){return d(p(A))},retry(){return s.closeFlight?s.closeFlight:s.closing?p(s.closing):s.closeRequested&&s.pending?y.settle(s.pending.requestId):s.inFlight?d(s.inFlight):s.pending?d(p(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 Ly(e){if(!Ft.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=Bs({...e,scope:e.scope,apiKey:e.customerToken});return{async start(n){let r=await t.start(n),i=Or({...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 zy(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 $y(e,t,n){if(e.operationId!==t.operationId||t.currency!==void 0&&e.currency!==t.currency)throw new b("INVALID_RESPONSE",n)}function Gy(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 Ky(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 Hy(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 Qy(e,t){if(!Ft.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=Ir(e);e.session||r.identify(t.customerToken);let i=null,a=!1,o=null,s=null,c=null,u=null,l=null,p=null,m=null,h=0;function d(){if(a)throw new b("IDENTITY_CHANGED","Paywall is closed")}async function g(){d();let x=O.resolvePaywall,v=await ge(r.request,x,{...n,selector:i?{type:"version",versionId:i.id}:n.selector});vr(n,v.paywall.check,v.scope);let C=await Ls(e,v.paywall);if(d(),t.paywallVersionId?C.id!==t.paywallVersionId:C.paywallId!==t.paywallId)throw new b("INVALID_RESPONSE","The requested Paywall changed");if(i&&(!zy(C,i)||C.paywallId!==i.paywallId))throw new b("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return i=C,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(m){if(p===x)return m;throw new b("COMMAND_PENDING","Wait for the original purchase command")}if(p&&p!==x)throw new b("COMMAND_PENDING","Read the original purchase before changing an uncertain command");p=x,h++}let C=p,j=h,_=x==="read"&&m===null,X=x==="read"?O.readSubscriptionOperation:O.attach,le=(async()=>{let ye=await ge(r.request,X,{operationId:v.operationId,...x==="read"?{}:{intent:x},...x==="confirm"&&v.merchantTerms?{merchantConfirmation:_d(v.merchantTerms)}:{}});return $y(ye.operation,{operationId:v.operationId,currency:n.commerce.currency},"The purchase operation changed"),d(),o?.operationId!==v.operationId?structuredClone(ye.operation):(s=Ky(s,ye.operation),(x!=="read"||_&&m===null)&&h===j&&p===C&&(p=null),structuredClone(s))})();if(x!=="read"){m=le;let ye=()=>{m===le&&(m=null)};le.then(ye,ye)}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 Hy({quote:o,operation:s,requestId:l,pending:u!==null||p!==null,destroyed:a})},get pendingCancellation(){return!a&&p==="cancel"},refresh:g,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 C=qf(v.product,x.selection,i.capabilities);if(!C)throw new b("PRODUCT_UNAVAILABLE","Choose an available Product");let j=Ch(i.document.screen,C,x.selection,i.capabilities),_=O.previewAttach.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,requestId:x.requestId,plans:[{productVersionId:C,...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||p||!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 ye=O.previewAttach,ke=await ge(r.request,ye,_);return d(),Gy(ke.quote,{productVersionId:C,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 g(),y}catch(x){throw y.destroy(),x}}function Jy(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 h=r;n&&e.nativeModule&&n.then(d=>e.nativeModule.reset(d,h)).catch(()=>{})}),l=e.nativeEvents?.(h=>{!n||!e.nativeModule||typeof h?.requestId!="string"||(async()=>{let d=await n;if(h.instanceId!==d)return;if(h.kind==="credential"){let y=r,A=null;try{if(!o&&h.revision===y){let x=await t.access();!o&&r===y&&(A=x)}}finally{await e.nativeModule.provideCredential(d,h.requestId,A)}return}let g=!1,R=r;try{if(o||h.revision!==R||!e.onNativeAction)throw c();await e.onNativeAction(h.action),g=!o&&r===R}finally{await e.nativeModule.acknowledge(d,h.requestId,g)}})().catch(()=>{})});async function p(h,d={}){let g=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=g.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 C=(async()=>{if(await g.identify(A,JSON.stringify({revision:R,credentials:y})),o||r!==R)throw await g.reset(A,R),c();i=R})();a={epoch:R,task:C}}let v=a;try{await v.task}finally{a===v&&(a=void 0)}}let x=await g.invoke(A,h,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 m(h,d){let g=await p(h,d);if(!g||typeof g!="object"||Array.isArray(g)||g.status!=="complete"&&g.status!=="dismissed")throw new b("INVALID_RESPONSE","Native presentation returned an invalid result");return g}return{showFunnel(h){return m("showFunnel",{runToken:h})},showPaywall(h){return m("showPaywall",h)},showContent(h){return m("showContent",h)},purchaseSubscription(h,d){return p("purchaseSubscription",{operationId:h,accepted:d})},switchSubscription(h,d){return p("switchSubscription",{operationId:h,accepted:d})},restorePurchases(){return p("restorePurchases")},manageSubscriptions(h){return p("manageSubscriptions",h?{productId:h}:{})},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 hw=O.trackUsage.request.shape.command,gw=O.trackUsage.response;function yw(e){let t=De.parse(e.scope),n=Ty({...e,scope:t}),r={...e,scope:t,session:n.session},i=Jy(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 Ly({...r,customerToken:s()})},resumeFunnel(c){return s(),Or({...r,runToken:c})},paywall(c){return Qy(r,{...c,customerToken:s()})},async trackUsage(c){if(s(),!e.usageReporter)throw new b("INVALID_REQUEST","Configure your authenticated backend usageReporter");let u=hw.parse(c),l=a,p;try{p=await e.usageReporter(u)}catch(h){throw l!==a?new b("IDENTITY_CHANGED","Customer identity changed during usage reporting"):h}if(l!==a)throw new b("IDENTITY_CHANGED","Customer identity changed during usage reporting");let m=gw.parse(p);if(m.scope.projectId!==t.projectId||m.scope.environment!==t.environment)throw new b("INVALID_RESPONSE","Usage response scope differs");return m}}}import{z as Sw}from"zod";import{z as Wo}from"zod";var Aw=Wo.record(Wo.string().regex(/^[a-f0-9]{64}$/),Wo.strictObject({at:Wo.number(),text:Wo.string()})),ri=2*1048576,bw=100;function xw(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Zy(e,t){let n=t===void 0?xw():t,r=new Map,i=0,a=!1,o=!1,s,c;async function u(p){if(!n)return null;let m;try{let h=await Promise.race([Promise.resolve().then(()=>n.getItem(p)),new Promise(d=>{m=setTimeout(()=>d(null),bw)})]);return typeof h=="string"&&h.length<=ri&&new TextEncoder().encode(h).byteLength<=ri?h:null}catch{return null}finally{clearTimeout(m)}}function l(){if(c)return c;let p=(async()=>{try{let m=await u(`${e}:artifacts`);if(m)return Aw.parse(JSON.parse(m))}catch{}return{}})();return c=p,p.finally(()=>{c===p&&(c=void 0)}),p}return{async readManifest(){return u(e)},writeManifest(p){!n||p.length>ri||new TextEncoder().encode(p).byteLength>ri||(s=p,!o&&(o=!0,Promise.resolve().then(async()=>{try{for(;s!==void 0;){let m=s;try{await n.setItem(e,m)}catch{}s===m&&(s=void 0)}}finally{o=!1}})))},async readArtifact(p){let m=(await l())[p],h=Date.now();return m&&h>=m.at&&h-m.at<=sn.retentionMs?m.text:void 0},writeArtifact(p,m){if(!n||m.length>ri)return;let h=r.get(p);if(h?.text===m||!h&&r.size>=128)return;let d=new TextEncoder().encode(m).byteLength;i-(h?.byteLength??0)+d>ri||(r.set(p,{text:m,byteLength:d}),i+=d-(h?.byteLength??0),!a&&(a=!0,Promise.resolve().then(async()=>{try{for(;r.size;){let g=new Map(r);try{let R={...await l()},y=Date.now();for(let[C,j]of g)R[C]={at:y,text:j.text};let A={},x=2,v=0;for(let[C,j]of Object.entries(R).sort(([,_],[,X])=>X.at-_.at)){if(j.at>y||y-j.at>sn.retentionMs)continue;let _=new TextEncoder().encode(JSON.stringify({[C]:j})).byteLength;x+_>ri||v>=128||(A[C]=j,x+=_,v++)}await n.setItem(`${e}:artifacts`,JSON.stringify(A))}catch{}finally{for(let[R,y]of g)r.get(R)===y&&(r.delete(R),i-=y.byteLength)}}}finally{a=!1}})))}}}var Pe=(e,t)=>new b(e,t),Pr=()=>performance.now(),Wy=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function Iw(e){let t=Ku.parse(e.scope),n=new wn(e.origin??Sr);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 Pe("INVALID_URL","Configuration requires a trusted HTTPS origin");let r=new Set([n.origin,...(e.assetOrigins??[]).map(Y=>{let J=new wn(Y);if(J.protocol!=="https:"||J.username||J.password||J.search||J.hash||J.pathname!=="/")throw Pe("INVALID_URL","Invalid configuration asset origin");return J.origin})]),i=e.fetch??globalThis.fetch.bind(globalThis),a=`/api/v1/configuration/${t.environmentId}`,o=`indiana:configuration:1:${n.origin}:${_t(t)}`,s=Zy(o,e.storage),c,u=0,l=0,p=!1,m=!1,h=0,d=0,g,R,y,A,x=0,v=new Set,C=new Set,j=new Map,_=new Map,X=0,le=!1;function ye(){for(let Y of v)try{Y()}catch{}}function ke(Y){try{e.onError?.(Y)}catch{}}let Se=()=>!m&&!p&&!!c&&Pr()<u&&Date.now()<l;function At(){if(!Se())throw Pe("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Ye(Y,J,pe){if(!j.has(Y)){for(;j.size&&(j.size>=128||X+pe>sn.maxCacheBytes);){let me=j.entries().next().value;X-=me[1].byteLength,j.delete(me[0])}j.set(Y,{text:J,byteLength:pe}),X+=pe}}function Ne(Y,J,pe){return Ny(Y,J,{signal:pe,error:me=>Pe("INVALID_RESPONSE",me==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function it(Y){let J=new wn(Y,n);if(!r.has(J.origin)||J.username||J.password||J.hash||J.search)throw Pe("INVALID_URL","Configuration artifact origin is not trusted");return J.href}async function Yo(Y,J,pe=!1){let me=await i(it(Y),{method:"GET",credentials:"omit",redirect:"error",cache:pe?"default":"no-cache",signal:J,headers:{}});if(me.status===429){let nt=me.headers.get("retry-after")??"";x=/^\d+$/.test(nt)?Number(nt)*1e3:Math.max(0,Date.parse(nt)-Date.now())||15e3}if(!me.ok&&me.status!==304)throw Pe(`CONFIGURATION_HTTP_${me.status}`,"Configuration synchronization failed");return me}function ii(Y,J,pe){let me=Date.parse(Y.headers.get("x-indiana-config-validated-at")??""),nt=Date.parse(Y.headers.get("x-indiana-config-valid-until")??""),st=Date.parse(Y.headers.get("date")??""),Ke=Y.headers.get("age"),un=Ke!==null&&/^\d+(\.\d+)?$/.test(Ke)?Number(Ke)*1e3:NaN;if(![me,nt,st,un].every(Number.isFinite)||nt<=me||nt-me>sn.maxControlAgeMs||me>st+1e3)throw Pe("INVALID_RESPONSE","Configuration freshness evidence is invalid");let zt=Math.min(nt-me,pe.maxControlAgeSeconds*1e3,sn.maxControlAgeMs)-Math.max(un,st-me,0)-(Pr()-J);if(zt<=0)throw Pe("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return Pr()+zt}function ft(){if(clearTimeout(y),clearTimeout(A),m||!v.size)return;Se()&&(A=setTimeout(()=>{Se()?ft():ye()},Math.max(1,u-Pr())),Wy(A));let Y=d?Math.min(15e3,1e3*2**Math.min(d-1,4)):Math.min(15e3,(c?.policy.refreshIntervalSeconds??15)*1e3);y=setTimeout(()=>{Xt().catch(ke)},Math.max(x,Y*(.8+Math.random()*.2))),Wy(y)}async function Xt(){if(m)throw Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(g)return g;let Y=h,J=new AbortController;R=J;let pe=(async()=>{if(!le){le=!0;try{let ea=await s.readManifest();if(ea&&!c){let Qn=Qu.parse(JSON.parse(ea));_t(Qn.scope)===_t(t)&&(c=Qn)}}catch{}}J.signal.throwIfAborted();let Ke=c,un=Pr(),Kt=await Yo(a,J.signal);Kt.status===304&&(!Ke||!Kt.headers.has("x-indiana-config-validated-at")||!Kt.headers.has("x-indiana-config-valid-until")||!Kt.headers.has("age"))&&(Kt=await Yo(a,J.signal));let zt=Kt.status===304?Ke:Qu.parse(JSON.parse(await Ne(Kt,sn.maxManifestBytes,J.signal))),{generation:oi,...ai}=zt,Hn=Kt.headers.get("etag");if(_t(zt.scope)!==_t(t)||jh(ai)!==oi||Hn!==`"${oi}"`&&Hn!==`W/"${oi}"`)throw Pe("INVALID_RESPONSE","Configuration scope or content identity changed");if(Ke&&(zt.revision<Ke.revision||zt.revision===Ke.revision&&zt.generation!==Ke.generation))throw Pe("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[ea,Qn]of Object.entries(Ke?.funnels??{})){let Rr=zt.funnels[ea];if(Rr&&(Rr.controlRevision<Qn.controlRevision||Rr.evaluationRevision<Qn.evaluationRevision||Rr.controlRevision===Qn.controlRevision&&Rr.state!==Qn.state||Rr.evaluationRevision===Qn.evaluationRevision&&Rr.evaluationMode!==Qn.evaluationMode))throw Pe("INVALID_RESPONSE","Funnel control revision changed identity")}let Er=ii(Kt,un,zt.policy);if(J.signal.throwIfAborted(),Y!==h)throw Pe("CONFIGURATION_DISPOSED","Configuration scope changed");return c=zt,u=Er,l=Date.now()+Math.max(0,Er-Pr()),p=!1,d=0,x=0,s.writeManifest(_t(zt)),ye(),structuredClone(zt)})(),me=setTimeout(()=>J.abort(Pe("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),sn.initializationMs),nt=new Promise((Ke,un)=>J.signal.addEventListener("abort",()=>un(J.signal.reason),{once:!0})),st=Promise.race([pe,nt]).catch(Ke=>{throw d++,(Ke instanceof Sw.ZodError||Ke instanceof SyntaxError||Ke instanceof b&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(Ke.code))&&(u=0,p=!0,ye()),Ke}).finally(()=>{clearTimeout(me),g===st&&(g=void 0),ft()});return g=st,st}async function Cr(Y){let J=Y.sha256,pe=ai=>Vs(ai,Y);it(Y.url);let me=j.get(J);if(me){if(me.byteLength!==Y.byteLength)throw Pe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return j.delete(J),j.set(J,me),me.text}let nt=_.get(J);if(nt){if(nt.byteLength!==Y.byteLength)throw Pe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return nt.promise}let st=new AbortController;C.add(st);let Ke=h,un=(async()=>{try{let Er=await s.readArtifact(J);if(Er&&pe(Er)){if(st.signal.throwIfAborted(),m||Ke!==h)throw Pe("CONFIGURATION_DISPOSED","Configuration scope changed");return Ye(J,Er,Y.byteLength),Er}}catch{}st.signal.throwIfAborted();let ai=await Yo(Y.url,st.signal,!0),Hn=await Ne(ai,Y.byteLength,st.signal);if(!pe(Hn))throw Pe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(m||Ke!==h)throw Pe("CONFIGURATION_DISPOSED","Configuration scope changed");return Ye(J,Hn,Y.byteLength),s.writeArtifact(J,Hn),Hn})(),Kt=setTimeout(()=>st.abort(Pe("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),sn.initializationMs),zt=new Promise((ai,Hn)=>st.signal.addEventListener("abort",()=>Hn(st.signal.reason),{once:!0})),oi=Promise.race([un,zt]).finally(()=>{clearTimeout(Kt),C.delete(st),_.delete(J)});return _.set(J,{promise:oi,byteLength:Y.byteLength}),oi}async function _r(){return Se()||await Xt(),At(),c}async function Qi(Y){let J,pe=new Promise((me,nt)=>{J=setTimeout(()=>nt(Pe("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),sn.initializationMs)});try{return await Promise.race([Y(),pe])}finally{clearTimeout(J)}}function Ji(Y,J){if(At(),c?.generation!==Y.generation)throw Pe("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(J&&c.funnels[J]?.state!=="active")throw Pe("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function zl(Y){let J=Y.gb.features;if(!J)throw Pe("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let pe=Y.artifacts[J];if(pe.formatVersion!==1)throw Pe("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let me=Au.parse(JSON.parse(await Cr(pe)));if(_t(me.scope)!==_t({projectId:t.projectId,environment:t.environment})||me.generation!==pe.generation||me.remoteFeatures.some(nt=>Object.hasOwn(me.features,nt)))throw Pe("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return Ji(Y),{...me,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,u-Pr())).toISOString()}}async function $l(Y,J){let pe=await _r(),me=pe.funnels[Y];J&&(!me||me.evaluationMode==="local"&&!me.versions[J])&&(g&&await g,pe=await Xt()),Ji(pe,Y);let nt=pe.funnels[Y];if(nt.evaluationMode!=="local")throw Pe("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let st=J??nt.currentVersionId,Ke=nt.versions[st];if(!Ke)throw Pe("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(pe.artifacts[Ke.artifact].formatVersion!==3)throw Pe("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[un,Kt]=await Promise.all([Cr(pe.artifacts[Ke.artifact]).then(zt=>Nh(JSON.parse(zt))),nt.evaluationMode==="local"?zl(pe):void 0]);if(Kt&&_t(Th(un,Kt))!==_t(Ke.dependencies))throw Pe("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return Ji(pe,Y),{document:un,growth:Kt,versionId:st,control:structuredClone(nt),manifest:structuredClone(pe)}}async function Gl(Y,J){try{return await $l(Y,J)}catch(pe){if(!(pe instanceof b)||!(pe.code==="CONFIGURATION_CHANGED"||pe.code==="CONFIGURATION_HTTP_404"&&Se()))throw pe;let me=c?.generation;if(g&&await g,await Xt(),pe.code!=="CONFIGURATION_CHANGED"&&c?.generation===me)throw pe;return $l(Y,J)}}function $s(){p=!0,ye(),Xt().catch(ke)}let Xo=()=>{(typeof document>"u"||document.visibilityState==="visible")&&$s()};function Yy(Y){if(m)throw Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return v.add(Y),v.size===1&&(typeof window<"u"&&(window.addEventListener("online",$s),window.addEventListener("focus",Xo),document.addEventListener("visibilitychange",Xo)),ft()),()=>{v.delete(Y),v.size||(clearTimeout(y),clearTimeout(A),Kl())}}function Kl(){typeof window<"u"&&(window.removeEventListener("online",$s),window.removeEventListener("focus",Xo),document.removeEventListener("visibilitychange",Xo))}return{scope:Object.freeze({...t}),refresh:Xt,subscribe:Yy,assertFresh:At,assertFeatures(Y){At();let J=c.gb.features;if(!J)throw Pe("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(Y!==void 0&&c.artifacts[J].generation!==Y)throw Pe("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-Pr()):0},async features(){return Qi(async()=>zl(await _r()))},pageExperiments:()=>Qi(async()=>{let Y=await _r(),J=Y.gb.pageExperiments;if(!J)throw Pe("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let pe=Y.artifacts[J];if(pe.formatVersion!==1)throw Pe("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let me=Lg.parse(JSON.parse(await Cr(pe)));if(me.environmentId!==t.environmentId||me.generation!==pe.generation)throw Pe("INVALID_RESPONSE","Page experiment scope or generation changed");return Ji(Y),me}),funnel:(Y,J)=>Qi(()=>Gl(Y,J)),paywall:(Y,J)=>Qi(async()=>{let pe=await _r(),me=pe.paywalls?.[Y];if(!me||!J&&me.state!=="published")throw Pe("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let nt=J??me.currentVersionId,st=me.versions[nt],Ke=st&&pe.artifacts[st.artifact];if(!Ke||Ke.kind!=="paywall"||Ke.formatVersion!==1)throw Pe("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let un=Os.parse(JSON.parse(await Cr(Ke)));return Ji(pe),{document:un,versionId:nt,version:st.version,control:structuredClone(me),manifest:structuredClone(pe)}}),async localFunnel(Y,J){let pe=await Qi(()=>Gl(Y,J));if(!pe.growth)throw Pe("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:me,remoteFeatures:nt,...st}=pe.growth;return Bg({scope:{projectId:t.projectId,environment:t.environment},funnelId:Y,versionId:pe.versionId,evaluationMode:"local",evaluationRevision:pe.control.evaluationRevision,document:pe.document,payload:st})},assertFunnel(Y,J,pe){At();let me=c.funnels[Y];if(!me||me.state!=="active")throw Pe("FUNNEL_STOPPED","Funnel is paused or unavailable");if(me.evaluationMode!=="local")throw Pe("EVALUATION_MODE","This Funnel now executes at Longplay");if(J!==void 0&&me.controlRevision!==J)throw Pe("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(pe!==void 0&&!me.versions[pe])throw Pe("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!m){m=!0,h++,u=0,R?.abort(Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(y),clearTimeout(A),Kl(),ye(),v.clear();for(let Y of C)Y.abort(Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));j.clear(),X=0}}}}async function vw(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&&_t(n)!==_t(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=Hi.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=Bs({...e,scope:n,apiKey:e.credential}),o=s=>{let c=Or({...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 Ll(e,...t){try{Promise.resolve(e?.(...t)).catch(()=>{})}catch{}}function ww(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(m){let h,d=new Promise((g,R)=>{h=setTimeout(()=>R(new b("TIMEOUT","Process bridge request timed out")),e.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(m),d])}finally{clearTimeout(h)}}function c(m){throw m instanceof b&&(m.status===401||m.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear()),m}function u(m,h){if(h!==r)throw new b("IDENTITY_CHANGED","Process was detached during a request");let d=ml.parse(m);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)Ll(j,d.run);d.run.instruction?.type==="authentication_required"&&Ll(e.onAuthenticationRequired,d.run)}d.settlement?.accepted!==void 0&&o.set(d.settlement.requestId,d.settlement.accepted);let{identity:g,instruction:R,...y}=d.run,{contract:A,settlement:x,...v}=d,C=x&&(({accepted:j,..._})=>_)(x);return{...v,run:{...y,authenticated:g.binding!==null,instruction:R?.type==="authentication_required"?null:R},...C?{settlement:C}:{}}}let l=m=>(a.has(m)||a.set(m,t?.run.identity.binding?.id??null),a.get(m));async function p(m){let h=r,d=t?.run.identity.binding?.id??null,g=y=>{if(d!==(t?.run.identity.binding?.id??null))throw y;return c(y)};if(m.operation==="page_experiments"){if(!e.adapter.pageExperiments)throw new b("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return s(()=>e.adapter.pageExperiments(m.release,m.usedReceiptIds)).catch(g)}let R;if(m.operation==="get"){let{operation:y,customerToken:A,...x}=m;R=await s(()=>e.adapter.get({...x,...x.settlementRequestId?{settlementBindingId:l(x.settlementRequestId)}:{}})).catch(g)}else if(m.operation==="review")R=await s(()=>e.adapter.review(m.receiptId)).catch(g);else{if(m.operation==="start")throw new b("INVALID_REQUEST","Use process.open for entry");{let{customerToken:y,...A}=m;R=await s(()=>e.adapter.command(A,l(A.requestId))).catch(g)}}return u(R,h)}return{get view(){return t?.run??null},get controller(){return n},async open(m){let h=r,d=await s(()=>e.adapter.open(m)).catch(c);if(u(d,h),!n){n=Or({...e,runToken:d.runToken,process:{request:p,binding:l,restore(y){for(let[A,x]of Object.entries(y))a.set(A,x)}}});let g=n,R=g.submit;g.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 g.settle?.(y.requestId),await g.get();let x=g.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 g of n.pendingCommands??[])a.has(g.requestId)&&a.get(g.requestId)!==(t?.run.identity.binding?.id??null)&&await n.settle?.(g.requestId);return{run:t.run,controller:n}},async syncIdentity(){let m=r;u(await s(()=>e.adapter.syncIdentity()).catch(c),m),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 t.run},async detach(){r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear(),await s(()=>e.adapter.detach())},forProcess(m){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:m}},subscribe(m){return i.add(m),()=>{i.delete(m)}},destroy(){r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear(),i.clear()}}}export{b as LongplayError,Iw as createConfigurationSync,Ul as createFeatureClient,ww as createFunnelProcess,vw as createLocalFunnelClient,yw as createLongplayReactNative};
|