@tinkerlandai/longplay-react-native 0.10.5 → 0.10.6
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 +4 -2
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +3 -4
- package/dist/index.d.ts +3 -4
- package/dist/index.js +2 -2
- package/native-sdk/android/assets/indiana/index.html +53 -47
- package/native-sdk/android/java/ai/tinkerland/indiana/SDKVersion.kt +1 -1
- package/native-sdk/android/resources/renderer-data-url.txt +1 -1
- package/native-sdk/ios/SDKVersion.swift +1 -1
- package/native-sdk/ios/WebView/index.html +53 -47
- package/native-sdk/ios/WebView/renderer-data-url.txt +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var ly=Object.defineProperty;var dy=(e,t,n)=>t in e?ly(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Ve=(e,t,n)=>dy(e,typeof t!="symbol"?t+"":t,n);import{z as hs}from"zod";var py=hs.enum(["sandbox","live"]),et=hs.object({projectId:hs.string().min(1),environment:py}).strict();import{z as $e}from"zod";var Di=$e.number().int().min(1).max(Number.MAX_SAFE_INTEGER),fl=$e.enum(["unknown","denied","provisional","granted"]),gl=$e.enum(["ios","android"]),Eo=$e.strictObject({installationId:$e.uuid(),publicKey:$e.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:$e.iso.datetime({offset:!0}),signature:$e.string().regex(/^[A-Za-z0-9_-]{86}$/)}),ys=$e.string().regex(/^[a-f0-9]{64}$/),hl=Eo.extend({sequence:Di,platform:gl,credentialDigest:ys}),yl=Eo.extend({credentialDigest:ys}),Al=Eo.extend({sequence:Di,platform:gl}),Ro=Eo.extend({sequence:Di,credentialDigest:ys,connectionId:$e.uuid().nullable(),kind:$e.enum(["fcm_token","apns_token"]).nullable(),token:$e.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:fl}),bl=Ro,xl=Ro.extend({challenge:$e.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),As=$e.strictObject({requested:$e.literal(!0),expiresAt:$e.iso.datetime({offset:!0})}),vr=$e.strictObject({installationId:$e.uuid(),bound:$e.boolean(),identitySeq:Di,bindingGeneration:Di,addressSeq:$e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:$e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:$e.uuid().nullable(),addressStatus:$e.enum(["active","invalid"]).nullable(),permission:fl}),bs=$e.strictObject({channel:$e.enum(["email","sms","voice","push"]),state:$e.enum(["unknown","allowed","denied"]),revision:$e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:$e.iso.datetime({offset:!0}).nullable()}),Ov=$e.strictObject({state:$e.enum(["allowed","denied"]),revision:$e.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function Sl(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 Ct}from"zod";var Bn=Ct.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"]),Pv=Ct.enum([...Bn.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),Ev=Ct.enum([...Bn.options,"stale_revision"]),xs=Ct.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"]),Ss=Ct.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),vl={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 Il={TIMEOUT:"recover_operation",NETWORK_ERROR:"recover_operation",HTTP_ERROR:"recover_operation",INVALID_RESPONSE:"recover_operation",NOT_IDENTIFIED:"authenticate",INVALID_TOKEN:"authenticate",INVALID_URL:"fix_request",INVALID_TIMEOUT:"fix_request",SERVER_ONLY:"fix_request",PROTOCOL_MISMATCH:"upgrade_sdk",IDENTITY_CHANGED:"reload_state",INVALID_STATE:"reload_state",EVENT_QUEUE_FULL:"retry_same_request",COMMAND_PENDING:"recover_operation",DECISION_PENDING:"recover_operation",DECISION_ACCEPTANCE_UNKNOWN:"recover_operation",RUN_RECONCILIATION_REQUIRED:"recover_operation",DECISION_FAILED:"contact_support",COMMAND_STORAGE_CONFLICT:"resolve_conflict",COMMAND_STORAGE_INVALID:"fix_request",CONFIGURATION_UNAVAILABLE:"check_availability",CONFIGURATION_EXPIRED:"reload_state",CONFIGURATION_CHANGED:"reload_state",CONFIGURATION_DISPOSED:"reload_state",UNSUPPORTED_SCHEMA:"upgrade_sdk",FUNNEL_STOPPED:"check_availability",PAYWALL_UNAVAILABLE:"check_availability",EVALUATION_MODE:"reload_state",SERVER_REQUIRED:"fix_request",STICKY_SAVE_FAILED:"retry_same_request",TRANSITION_LIMIT:"resolve_conflict",PRECONDITION_FAILED:"reload_state",PRODUCT_UNAVAILABLE:"fix_request",PURCHASE_HANDLER_REQUIRED:"fix_request",EVENT_HANDLER_REQUIRED:"fix_request",CLOSED:"fix_request",BRIDGE_UNAVAILABLE:"check_availability",INVALID_CONFIGURATION:"fix_request",NATIVE_OPERATION_FAILED:"contact_support",AI_PRICE_UNAVAILABLE:"fix_request",AI_USAGE_UNAVAILABLE:"recover_operation",AI_PROVIDER_ERROR:"check_availability",AI_BALANCE_REJECTED:"resolve_conflict"};function my(e,t){if(e==="CONFLICT"&&t===425)return{retryable:!0,recovery:"retry_same_request"};if(e==="CONFLICT"&&t===412)return{retryable:!1,recovery:"reload_state"};if(e==="INVALID_SERVER_RESPONSE")return{retryable:!1,recovery:"recover_operation"};if(e==="AMBIGUOUS_AUTHENTICATION")return{retryable:!1,recovery:"fix_request"};if(Object.hasOwn(Il,e)){let r=Il[e];return{retryable:r==="retry_same_request",recovery:r}}let n=Bn.safeParse(e);return n.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:vl[n.data].recovery}:{retryable:!1,recovery:"contact_support"}}function wl(e,t){let n=Bn.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):vl[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 fy(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 Ol=Ct.object({retryable:Ct.boolean(),recovery:xs,reason:Ss.optional(),retryAfterSeconds:Ct.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),Is=Ct.object({requestId:Ct.uuid().optional(),error:Ct.object({code:Ct.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:Ct.string(),...Ol.partial().shape})}),Rv=Ct.object({error:Is.shape.error.extend({requestId:Ct.uuid().optional()})}),kv=Ct.object({error:Ct.string(),code:Ct.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:Ct.uuid(),...Ol.shape});function ko(e,t,n={}){let r=my(e,t),i=n.reason==="RESULT_UNKNOWN"?"recover_operation":n.recovery??r.recovery,a=r.retryable&&n.retryable!==!1&&i!=="recover_operation",o=a?fy(n.retryAfter??null):void 0;return{...r,retryable:a,recovery:i,...o===void 0?{}:{retryAfterSeconds:o},...n.reason?{reason:n.reason}:{}}}var vs="X-Indiana-Protocol",_l="X-Indiana-SDK-Version";var ws={current:"0.10"};import{z as gy}from"zod";var hy=["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"],be=gy.enum(hy);import{z as _}from"zod";var Bt=_.string().min(1).max(200),Jt=_.iso.datetime({offset:!0}),At=_.number().int().nonnegative().max(1e8),jo=_.string().regex(/^[A-Z]{3}$/),yy=["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"],Cl=_.enum(yy),Pl=_.strictObject({priceId:_.uuid(),productVersionId:_.uuid(),productId:Bt,quantity:_.number().int().min(1).max(1e6),unitAmountMinor:At,totalMinor:At,interval:_.enum(["week","month","year","one_off"]),intervalCount:_.number().int().min(1).max(52),kind:_.enum(["fixed","prepaid","seat"]),tiers:_.strictObject({mode:_.enum(["graduated","volume"]),tiers:_.array(_.strictObject({upTo:_.number().int().positive().nullable(),unitAmountMinor:At,flatAmountMinor:At.optional()})).min(2).max(12)}).nullable()}),Ay=_.strictObject({grantId:_.uuid(),couponId:_.uuid(),amountMinor:At,terms:_.discriminatedUnion("type",[_.strictObject({type:_.literal("percent"),percentOff:_.number().gt(0).max(100)}),_.strictObject({type:_.literal("amount"),amountOffMinor:At,currency:jo})]),duration:_.discriminatedUnion("type",[_.strictObject({type:_.literal("once")}),_.strictObject({type:_.literal("forever")}),_.strictObject({type:_.literal("repeating"),months:_.number().int().min(1).max(36)})])}),Ps={provider:_.literal("merchant"),executor:_.literal("merchant"),operationId:_.uuid(),customerId:_.uuid(),configurationRevision:_.number().int().nonnegative(),connectionRevision:_.number().int().nonnegative(),currency:jo,expiresAt:Jt},To=_.strictObject({...Ps,type:_.literal("purchase"),mode:_.enum(["payment","subscription"]),lineItems:_.array(Pl).min(1).max(100),catalogAmountMinor:At,discount:Ay.nullable(),trialPeriodDays:_.number().int().min(1).max(730).nullable(),automaticTax:_.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"),No=_.strictObject({...Ps,type:_.literal("subscription_change"),subscriptionId:_.uuid(),merchantSubscriptionId:Bt,membershipId:_.uuid(),subscriptionAction:_.enum(["update","cancel","schedule","release"]),supersedesOperationId:_.uuid().nullable(),change:_.discriminatedUnion("type",[_.strictObject({type:_.literal("cancel")}),_.strictObject({type:_.literal("uncancel")}),_.strictObject({type:_.literal("plan"),productVersionId:_.uuid()}),_.strictObject({type:_.literal("seats"),licenseKey:Bt,quantity:_.number().int().nonnegative().max(1e6)}),_.strictObject({type:_.literal("quantity"),internal_feature_id:_.uuid(),quantity:_.number().int().nonnegative().max(1e6)}),_.strictObject({type:_.literal("billing_cycle"),billingCycleAnchor:_.union([_.literal("now"),_.number().int().positive()])})]),timing:_.enum(["immediate","renewal"]),effectiveAt:Jt,creditMinor:At,debitMinor:At,totalMinor:At,discountMinor:At,taxMinor:At,proration:_.enum(["none","create_prorations","always_invoice"]),lineItems:_.array(Pl.extend({quantity:_.number().int().nonnegative().max(1e6)})).max(100),removePriceIds:_.array(_.uuid()).max(100)}),Do=_.strictObject({...Ps,type:_.literal("refund"),invoiceId:_.uuid(),merchantInvoiceId:Bt,amountMinor:At.refine(e=>e>0),mode:_.enum(["full","partial"]),entitlementAction:_.enum(["retain","revoke"]),cancelSubscriptions:_.array(Bt).max(100)}),El=_.discriminatedUnion("type",[To,No,Do]);var Fi=_.strictObject({phase:_.enum(["execution","payment","fulfillment","recording"]),code:Bn,reason:Ss.optional(),recovery:xs,retryable:_.boolean()}).refine(e=>e.reason!=="RESULT_UNKNOWN"||!e.retryable&&e.recovery==="recover_operation","Unknown financial effects require recovery of the original operation"),Os={operationId:_.uuid(),customerId:_.uuid(),merchantExecutionId:Bt,fulfillmentStatus:_.enum(["not_started","pending","applied","failed","not_applicable"]),recordingStatus:_.enum(["not_ready","pending","accepted","failed"]),updatedAt:Jt,problem:Fi.nullable(),pollAfterMs:_.number().int().min(1e3).max(6e4).nullable()},wr=_.discriminatedUnion("type",[_.strictObject({...Os,type:_.literal("purchase"),merchantOrderId:Bt.nullable(),paymentStatus:_.enum(["not_started","pending","succeeded","not_required","failed","expired","unknown"]),checkoutUrl:_.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"),_.strictObject({...Os,type:_.literal("subscription_change"),status:_.enum(["pending","scheduled","applied","failed","unknown"]),merchantSubscriptionId:Bt,scheduledFor:Jt.nullable()}).refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"A scheduled change retains its future effective time"),_.strictObject({...Os,type:_.literal("refund"),status:_.enum(["pending","succeeded","failed","unknown"]),merchantRefundId:Bt.nullable()}).refine(e=>e.status!=="succeeded"||e.merchantRefundId!==null,"A successful refund retains its original merchant identity")]),Rl=_.discriminatedUnion("lookup",[_.strictObject({lookup:_.literal("found"),operationId:_.uuid(),customerId:_.uuid(),execution:wr,readAt:Jt}),_.strictObject({lookup:_.literal("not_received"),operationId:_.uuid(),customerId:_.uuid(),execution:_.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"),_s=_.strictObject({merchantSubscriptionId:Bt,revision:_.number().int().positive(),status:_.enum(["incomplete","trialing","active","past_due","canceled","unpaid","paused","incomplete_expired"]),periodStartsAt:Jt,periodEndsAt:Jt,cancelAtPeriodEnd:_.boolean(),hasDiscounts:_.boolean(),items:_.array(_.strictObject({merchantItemId:Bt,priceId:_.uuid(),quantity:_.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"),Cs=_.strictObject({merchantInvoiceId:Bt,currency:jo,subtotalMinor:At,discountMinor:At,taxMinor:At,totalMinor:At,paidMinor:At,periodStartsAt:Jt.nullable(),periodEndsAt:Jt.nullable(),lines:_.array(_.strictObject({merchantLineId:Bt,priceId:_.uuid(),quantity:_.number().int().nonnegative().max(1e6),subtotalMinor:_.number().int().min(-1e8).max(1e8),discountMinor:At,taxMinor:At,totalMinor:_.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"),Jr={provider:_.literal("merchant"),eventId:_.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),customerId:_.uuid(),occurredAt:Jt},kl=_.enum(["purchase.completed","purchase.closed","subscription.observed","subscription.change.completed","invoice.paid","refund.updated"]),jl=_.discriminatedUnion("type",[_.strictObject({...Jr,type:_.literal("purchase.completed"),operationId:_.uuid(),merchantOrderId:Bt,paymentStatus:_.enum(["paid","trialing","no_payment_required"]),invoice:Cs.nullable(),subscription:_s.nullable()}).refine(e=>e.paymentStatus!=="paid"||e.invoice!==null,"A paid purchase includes its Invoice"),_.strictObject({...Jr,type:_.literal("purchase.closed"),operationId:_.uuid(),status:_.enum(["failed","expired","canceled"])}),_.strictObject({...Jr,type:_.literal("subscription.observed"),operationId:_.uuid().nullable(),subscription:_s}),_.strictObject({...Jr,type:_.literal("subscription.change.completed"),operationId:_.uuid(),status:_.enum(["scheduled","applied"]),scheduledFor:Jt.nullable(),subscription:_s,invoice:Cs.nullable()}).refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"Scheduled and applied changes are distinct facts"),_.strictObject({...Jr,type:_.literal("invoice.paid"),merchantSubscriptionId:Bt,invoice:Cs}),_.strictObject({...Jr,type:_.literal("refund.updated"),operationId:_.uuid(),merchantRefundId:Bt,status:_.enum(["pending","succeeded","failed"]),amountMinor:At.refine(e=>e>0),currency:jo})]);import{z as R}from"zod";import{z as Or}from"zod";var Yt=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,Yn=Or.object({customerId:Or.uuid(),sessionId:Or.uuid(),accessToken:Or.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),refreshToken:Or.string().regex(/^gg_rt_[A-Za-z0-9_-]{43}$/),expiresAt:Or.iso.datetime(),refreshExpiresAt:Or.iso.datetime()});var Rs=3;var by=["session","catalog","customer_commerce","presentation","presentation_events","purchases","operation_status","billing_records","subscription_changes","refunds"],xy=R.enum(by);var Sy=R.enum(["bridge.ping","bridge.describe","session.create","catalog.read","customer.commerce.read","presentation.resolve","presentation.report","purchase.execute","operation.read","subscription.change","refund.execute"]),Nl=R.string().regex(/^[A-Za-z0-9_-]{1,64}$/),Iy=R.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(e=>"AEIMQUYcgkosw048".includes(e.at(-1)),"Use canonical base64url for a 32-byte key"),vy=R.strictObject({keyId:Nl,signingSecret:Iy}),wy=R.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),Dl=R.array(xy).max(10).refine(e=>new Set(e).size===e.length,"Capabilities must be unique"),Fl=R.strictObject({bridgeVersion:R.literal(Rs),projectId:R.uuid(),environmentId:R.uuid(),environment:R.enum(["sandbox","live"]),capabilities:Dl,catalog:R.enum(["endpoint","static","none"]),billingEvents:R.array(kl).max(6),profiles:R.array(Cl).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"})}),Ml=R.strictObject({origin:wy,requiredCapabilities:Dl}),Oy=R.strictObject({revision:R.number().int().nonnegative(),checkedAt:R.iso.datetime(),outcome:R.enum(["valid","unreachable","invalid","scope_mismatch","authentication_failed","credentials_missing"]),diagnostics:R.strictObject({ping:R.enum(["passed","failed","not_checked"]),authentication:R.enum(["passed","failed","not_checked"]),catalog:R.enum(["passed","failed","not_checked","static","unsupported"])}),manifest:Fl.nullable()}).superRefine((e,t)=>{e.outcome==="valid"!=(e.manifest!==null)&&t.addIssue({code:"custom",path:["manifest"],message:"Only a valid declaration carries a manifest"})}),$v=R.strictObject({projectId:R.uuid(),environmentId:R.uuid(),environment:R.enum(["sandbox","live"]),execution:R.enum(["indiana","record_only"]),accountId:R.string().nullable(),revision:R.number().int().nonnegative(),authentication:R.strictObject({keyId:Nl}).nullable(),secretStoreConfigured:R.boolean().optional(),connection:Ml.nullable(),check:Oy.nullable()});var Tl=R.strictObject({projectId:R.uuid(),environmentId:R.uuid()}),Kv=R.discriminatedUnion("action",[Tl.extend({action:R.literal("save"),revision:R.number().int().nonnegative(),connection:Ml,authentication:vy.optional()}),Tl.extend({action:R.literal("check"),revision:R.number().int().nonnegative()})]),ks=R.strictObject({projectId:R.uuid(),environmentId:R.uuid(),environment:R.enum(["sandbox","live"])});var _y=R.strictObject({nativeUserId:R.string().min(1).max(128),session:Yn.strict()}),Cy=R.strictObject({nativeUserId:R.string().min(1).max(128),presentation:R.strictObject({customerId:R.uuid(),decisionId:R.uuid(),offeringVersionId:R.uuid(),paywallVersionId:R.uuid(),variant:R.string().min(1).max(128)}).nullable()}),Py=R.strictObject({decisionId:R.uuid(),eventId:R.uuid()}),Fo=R.strictObject({operationId:R.uuid(),customerId:R.uuid()}),Mo=R.strictObject({scope:ks,operationId:R.uuid(),customerId:R.uuid(),confirmedAt:R.iso.datetime({offset:!0}).nullable(),initialExecutionAllowed:R.boolean(),instruction:El}).refine(e=>e.operationId===e.instruction.operationId&&e.customerId===e.instruction.customerId,"Authority must refer to the original Customer and operation"),Es=wr,Un=R.string().min(1).max(120),Ey=R.string().regex(/^-?[0-9]+(?:\.[0-9]{1,6})?$/),Ry=R.strictObject({revision:Un,updatedAt:R.iso.datetime(),provider:R.literal("merchant"),items:R.array(R.strictObject({merchantProductId:Un,productVersionId:R.uuid(),name:R.string().min(1).max(255),kind:R.enum(["subscription","credit_pack"]),merchantPriceId:Un,currency:R.string().regex(/^[a-z]{3}$/),amountMinor:R.number().int().nonnegative().max(1e8),interval:R.enum(["one_time","month","year"]),intervalCount:R.literal(1),includedCredits:R.string().regex(/^[0-9]{1,18}(?:\.[0-9]{1,6})?$/),creditReset:R.enum(["none","month"]),creditPolicyId:Un,available:R.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)}),ky=R.strictObject({customerId:R.uuid(),revision:R.string().min(1).max(128),observedAt:R.iso.datetime(),subscriptions:R.array(R.strictObject({merchantSubscriptionId:Un,merchantProductId:Un,productVersionId:R.uuid().nullable(),status:R.enum(["active","trialing","past_due","cancelled","expired"]),currentPeriodStartsAt:R.iso.datetime().nullable(),currentPeriodEndsAt:R.iso.datetime().nullable(),cancelAtPeriodEnd:R.boolean(),scheduledChange:R.strictObject({effectiveAt:R.iso.datetime(),merchantProductId:Un}).nullable()})).max(100),purchaseHistory:R.strictObject({complete:R.boolean(),hasPaidPurchase:R.boolean(),lastPaidAt:R.iso.datetime().nullable()}),balances:R.array(R.strictObject({bucketId:Un,key:Un,available:Ey,expiresAt:R.iso.datetime().nullable(),nextResetAt:R.iso.datetime().nullable()})).max(100)}),Gv=R.strictObject({bridgeVersion:R.literal(Rs),requestId:R.uuid(),command:R.string().min(1).max(64),scope:ks,error:R.strictObject({code:R.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:R.string().min(1).max(500),retryable:R.boolean(),recovery:R.string().min(1).max(80)})}),Mi=R.strictObject({}),jy={"bridge.ping":R.strictObject({challenge:R.uuid()}),"bridge.describe":Mi,"session.create":Mi,"catalog.read":Mi,"customer.commerce.read":Mi,"presentation.resolve":Mi,"presentation.report":Py,"purchase.execute":Fo,"operation.read":Fo,"subscription.change":Fo,"refund.execute":Fo},Hv={"bridge.ping":R.strictObject({challenge:R.uuid()}),"bridge.describe":Fl,"session.create":_y,"catalog.read":Ry,"customer.commerce.read":ky,"presentation.resolve":Cy,"presentation.report":R.strictObject({queued:R.literal(!0)}),"purchase.execute":Es,"operation.read":Rl,"subscription.change":Es,"refund.execute":Es},Qv=R.strictObject({bridgeVersion:R.literal(Rs),requestId:R.uuid(),scope:ks,command:Sy,data:R.unknown()}).superRefine((e,t)=>{jy[e.command].safeParse(e.data).success||t.addIssue({code:"custom",path:["data"],message:"Invalid command data"})});import{z as Zr}from"zod";var Vo=Zr.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"),Yv=Zr.object({amountCents:Zr.number().int().min(0).max(1e8),currency:be,interval:Zr.enum(["free","month","year"]),currencyOptions:Zr.partialRecord(be,Zr.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 Ty=F.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Bl=F.enum(["single_use","continuous_use"]),js=F.record(F.string(),F.union([F.string(),F.number(),F.boolean()]).transform(String).pipe(F.string())),Vl=F.string().min(1).max(64).refine(e=>!e.includes("::")),Ul={credit_amount:F.number(),tier_behavior:F.never().optional(),tiers:F.never().optional()},Ll={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()}))},Ny=F.union([F.strictObject({match:js,priority:F.number().int().optional(),...Ul}),F.strictObject({match:js,priority:F.number().int().optional(),...Ll})]),Dy=F.strictObject({match:js,factor:F.number().positive().optional(),add:F.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),ql={metered_feature_id:F.string(),feature_amount:F.number().optional(),dimensions:F.record(Vl,Ny).optional(),multipliers:F.record(Vl,Dy).optional()},Ts=F.union([F.strictObject({...ql,...Ul}),F.strictObject({...ql,...Ll})]),Bo=F.number().min(-100),zl=F.record(F.string(),F.strictObject({markup:Bo})).nullish(),Uo=F.record(F.string().regex(/.+\/.+/),F.strictObject({markup:Bo.optional(),input_cost:F.number().min(0).optional(),output_cost:F.number().min(0).optional()})).nullish(),Fy=F.strictObject({default_markup:Bo.optional(),provider_markups:zl,model_markups:Uo}),tw=F.strictObject({schema:F.array(Ts).optional(),markups:Fy.optional()}),My=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:Bl}),$l=F.strictObject({schema:F.array(Ts).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:Bl.default("single_use").overwrite(()=>"single_use"),default_markup:Bo.optional(),provider_markups:zl}),Ns=$l.safeExtend({schema:F.array(Ts).length(0)}),qo={id:Ty,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:Uo,stripe_meter:F.strictObject({id:F.string(),event_name:F.string()}).nullish(),stripe_product_id:F.string().nullish()},Ds=e=>F.discriminatedUnion("type",[F.strictObject({...qo,...e,type:F.literal("boolean"),config:F.null()}),F.strictObject({...qo,...e,type:F.literal("metered"),config:My}),F.strictObject({...qo,...e,type:F.literal("credit_system"),config:$l}),F.strictObject({...qo,...e,type:F.literal("ai_credit_system"),config:Ns})]),nw=Ds({}),Vy=F.strictObject({id:F.boolean(),type:F.boolean(),usage_type:F.boolean()}),qy={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:Vy},Kl=Ds(qy),rw=F.strictObject({rows:F.array(Kl).max(200),nextCursor:F.uuid().nullable()}),iw=F.strictObject({features:F.array(Kl).max(500),limited:F.boolean()}),ow=F.union([Ds({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 Xr}from"zod";import{z as ct}from"zod";var Zt=ct.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),Ae=ct.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),Lo=ct.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}),Fs=Ae.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),Gl=ct.string().min(1).max(64),_r=ct.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Hl=ct.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),xt=ct.record(Gl,ct.union([ct.string().max(120),ct.number().finite(),ct.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)]))),Ql=ct.record(Gl,ct.union([ct.string().max(120),ct.number().finite(),ct.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),Wr=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},Jl=ct.array(ct.object({upTo:Fs.nullable(),cost:Ae}).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&&Wr(t.upTo)>Wr(r))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),By=ct.object({key:Hl,match:Ql,priority:ct.number().int().default(0),cost:Ae.optional(),tiers:Jl.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),Uy=ct.object({key:Hl,match:Ql,factor:Fs.optional(),add:Lo.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"})),Ly=ct.object({units:Fs.default("1"),cost:Ae,tiers:Jl.optional(),dimensions:ct.array(By).max(12).optional(),multipliers:ct.array(Uy).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=Wr(e.units);for(let o of i)for(let s=0;s<1<<r.length;s++){let c=r.filter((p,g)=>s&1<<g);if(c.some((p,g)=>c.slice(g+1).some(f=>Object.keys(p.match).some(I=>f.match[I]!==void 0&&f.match[I]!==p.match[I]))))continue;let u=Wr(o),l=BigInt("1"),m=BigInt("0");for(let[p,g]of r.entries())s&1<<p&&(u*=Wr(g.factor??"1"),l*=BigInt("1000000"),m+=Wr(g.add??"0"));let x=(u+m*l)*BigInt("1000000"),A=l*a;(x<BigInt("0")||x%A!==BigInt("0")||x/A>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"})}}),cw=Ly.safeExtend({featureKey:_r});import{z as Yr}from"zod";var Zl=Yr.number().int().min(0).max(1e8),Vi=Yr.strictObject({kind:Yr.enum(["graduated","volume"]),tiers:Yr.array(Yr.strictObject({upTo:Yr.number().int().min(1).max(1e4).nullable(),unitAmountMinor:Zl,flatAmountMinor:Zl.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 Ms(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 zo(e){return Ms({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}var zy=Ae.refine(e=>/[1-9]/.test(e)),$o=Xr.strictObject({units:zy,prices:Xr.array(Xr.strictObject({currency:be,amountMinor:Xr.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:Xr.number().int().min(0).max(1e4),maximumQuantity:Xr.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&&Ms({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 Wl(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 Yl(e,t,n){if(!Number.isSafeInteger(n)||n<0||n>1e4)throw new Error("Invalid purchased quantity");let r=Wl(e)+Wl(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 h}from"zod";import{z as ne}from"zod";import{z as jt}from"zod";import{z as j}from"zod";function Xl(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 Ko(e,t,n){return n===2?Xl(Xl(e+t)+"")%1e4/1e4:null}function $y(e){return e<=0?[]:new Array(e).fill(1/e)}function Go(e,t){return e>=t[0]&&e<t[1]}function ed(e,t){for(let[n,r]of t.entries())if(Go(e,r))return n;return-1}function td(e,t,n){t=t===void 0?1:t,t<0?t=0:t>1&&(t=1);let r=$y(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 nd(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 rd(e){try{return e()}catch{return!1}}function qi(e){return typeof e=="string"?e:JSON.stringify(e)}function on(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 Ky(e){try{let t=e.replace(/([^\\])\//g,"$1\\/");return new RegExp(t)}catch{return}}function id(e,t){if(!t.length)return!1;let n=!1,r=!1;for(let i of t){let a=Qy(e,i.type,i.pattern);if(i.include===!1){if(a)return!1}else n=!0,a&&(r=!0)}return r||!n}function Gy(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 Hy(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=>!Gy(i[0],i[1],i[2]))}catch{return!1}}function Qy(e,t,n){try{let r=new URL(e,"https://_");if(t==="regex"){let i=Ky(n);return i?i.test(r.href)||i.test(r.href.substring(r.origin.length)):!1}else if(t==="simple")return Hy(r,n);return!1}catch{return!1}}function Vs(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 Ho(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 od(e){for(let t of["overrides","groups"])if(Object.hasOwn(e,t))throw new TypeError(`Retired evaluation context field: ${t}`);Ho(e.savedGroups??{})}var Jy=e=>e/2**32|0,Zy=e=>e>>>0;function ad(e,t,n,r){let i=Jy(n),a=Zy(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function sd(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var qs=e=>e?`"${e}" `:"";function Wy(e,t=""){if(typeof e!="number")throw new TypeError(qs(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(qs(t)+"expected integer >= 0, got "+e);return e}function Qo(e,t,n=""){if(sd(e)&&(t===void 0||e.length===t))return e;t!==void 0&&Wy(t,"length");let r=sd(e),i=t!==void 0?` of length ${t}`:"",a=r?`length=${e.length}`:`type=${typeof e}`,o=qs(n)+"expected Uint8Array"+i+", got "+a;throw r?new RangeError(o):new TypeError(o)}var Yy=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},cd=(e,t)=>{Yy(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 Bs(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function ud(e,t){Qo(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function Us(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Jo(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Sn(e,t){return e<<32-t|e>>>t}var Xy=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",eA=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function ei(e){if(Qo(e),Xy)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=eA[e[n]];return t}function tA(e,t,n="opts"){return cd(e,"defaults"),t!==void 0&&cd(t,n),Object.assign(Object.create(null),e,t)}function ld(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=tA({},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 dd=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function pd(e,t,n){return e&t^~e&n}function md(e,t,n){return e&t^e&n^t&n}var Zo=class{constructor(t,n,r,i){Ve(this,"blockLen");Ve(this,"outputLen");Ve(this,"canXOF",!1);Ve(this,"padOffset");Ve(this,"isLE");Ve(this,"buffer");Ve(this,"view");Ve(this,"finished",!1);Ve(this,"length",0);Ve(this,"pos",0);Ve(this,"destroyed",!1);this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(t),this.view=Jo(this.buffer)}update(t){Bs(this),Qo(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=Jo(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){Bs(this),ud(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)),ad(r,i-8,this.length*8,a),this.process(r,0),this.roundClean();let s=t===n?r:Jo(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()}},fd=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var nA=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]),Xn=new Uint32Array(64),Ls=class extends Zo{constructor(n,r){super(64,n,8,!1);Ve(this,"A",0);Ve(this,"B",0);Ve(this,"C",0);Ve(this,"D",0);Ve(this,"E",0);Ve(this,"F",0);Ve(this,"G",0);Ve(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 x=0;x<16;x++,r+=4)Xn[x]=n.getUint32(r,!1);for(let x=16;x<64;x++){let A=Xn[x-15],p=Xn[x-2],g=Sn(A,7)^Sn(A,18)^A>>>3,f=Sn(p,17)^Sn(p,19)^p>>>10;Xn[x]=f+Xn[x-7]+g+Xn[x-16]|0}let{A:i,B:a,C:o,D:s,E:c,F:u,G:l,H:m}=this;for(let x=0;x<64;x++){let A=Sn(c,6)^Sn(c,11)^Sn(c,25),p=m+A+pd(c,u,l)+nA[x]+Xn[x]|0,f=(Sn(i,2)^Sn(i,13)^Sn(i,22))+md(i,a,o)|0;m=l,l=u,u=c,c=s+p|0,s=o,o=a,a=i,i=p+f|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(){Us(Xn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Us(this.buffer)}},zs=class extends Ls{constructor(){super(32,fd)}};var ti=ld(()=>new zs,dd(1));var gd=new Map,$s=32,hd=new WeakMap,yd=new WeakMap;function rA(e){return ei(ti(new TextEncoder().encode(String(e))))}var Yo=e=>Array.isArray(e)?e.map(Yo):typeof e=="string"||typeof e=="number"?rA(e):null,Wo=e=>typeof e=="string"?e.toLowerCase():e;function Id(e){let t=hd.get(e);return t||(t=new Set(e),hd.set(e,t)),t}function iA(e){let t=yd.get(e);return t||(t=new Set(e.map(Wo)),yd.set(e,t)),t}function ni(e){Ho(e);for(let t of Object.values(e)){let n=t?.type==="list"||t?.type==="hashed"?t.values:null;n&&n.length>=$s&&Id(n)}return e}function Xt(e,t,n,r){n=n||{},r||Ho(n),r=r||new Set;for(let[i,a]of Object.entries(t))switch(i){case"$or":if(!Sd(e,a,n,r))return!1;break;case"$nor":if(Sd(e,a,n,r))return!1;break;case"$and":if(!uA(e,a,n,r))return!1;break;case"$not":if(Xt(e,a,n,r))return!1;break;case"$savedGroup":if(!oA(e,a,n,r))return!1;break;default:if(!Bi(a,vd(e,i),n,!1,r))return!1}return!0}function oA(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=vd(e,c);return Cr(o.type==="hashed"?Yo(u):u,o.values)}return o.type==="condition"?!o.condition||typeof o.condition!="object"?!1:Xt(e,o.condition,n,s):!1}function vd(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 Ad(e,t=!1){let n=`${e}${t?"/i":""}`,r=gd.get(n);return r||(r=new RegExp(e.replace(/([^\\])\//g,"$1\\/"),t?"i":void 0),gd.set(n,r)),r}function Bi(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)||!wd(e))return JSON.stringify(t)===JSON.stringify(e);let a=e;for(let o in a)if(!cA(o,t,a[o],n,i))return!1;return!0}function wd(e){let t=Object.keys(e);return t.length>0&&t.filter(n=>n[0]==="$").length===t.length}function aA(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 sA(e,t,n,r){if(!Array.isArray(e))return!1;let i=wd(t)?a=>Bi(t,a,n,!1,r):a=>Xt(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 Cr(e,t,n=!1){if(n){let i;if(t.length>=$s){let a=iA(t);i=o=>{let s=Wo(o);return!(typeof s=="number"&&Number.isNaN(s))&&a.has(s)}}else i=a=>t.some(o=>Wo(a)===Wo(o));return Array.isArray(e)?e.some(a=>i(a)):i(e)}let r=t.length>=$s?(i=>a=>i.has(a))(Id(t)):i=>t.includes(i);return Array.isArray(e)?e.some(i=>r(i)):r(e)}function bd(e){return e===void 0?[]:e&&typeof e=="object"&&(e.type==="list"||e.type==="hashed")&&Array.isArray(e.values)?e.values:null}function xd(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(Bi(t[a],e[s],n,r,i)){o=!0;break}if(!o)return!1}return!0}function cA(e,t,n,r,i=new Set){let a=t,o=n;switch(e){case"$veq":return on(t)===on(n);case"$vne":return on(t)!==on(n);case"$vgt":return on(t)>on(n);case"$vgte":return on(t)>=on(n);case"$vlt":return on(t)<on(n);case"$vlte":return on(t)<=on(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)?Cr(t,n):!1;case"$ini":return Array.isArray(n)?Cr(t,n,!0):!1;case"$inGroup":{let s=r[n],c=bd(s);return c===null?!1:Cr(s?.type==="hashed"?Yo(t):t,c)}case"$notInGroup":{let s=r[n],c=bd(s);return c===null?!1:!Cr(s?.type==="hashed"?Yo(t):t,c)}case"$nin":return Array.isArray(n)?!Cr(t,n):!1;case"$nini":return Array.isArray(n)?!Cr(t,n,!0):!1;case"$not":return!Bi(n,t,r,!1,i);case"$size":return Array.isArray(t)?Bi(n,t.length,r,!1,i):!1;case"$elemMatch":return sA(t,n,r,i);case"$all":return Array.isArray(n)?xd(t,n,r,!1,i):!1;case"$alli":return Array.isArray(n)?xd(t,n,r,!0,i):!1;case"$regex":try{return Ad(n).test(t)}catch{return!1}case"$regexi":try{return Ad(n,!0).test(t)}catch{return!1}case"$type":return aA(t)===n;default:return!1}}function Sd(e,t,n,r){if(!t.length)return!0;for(let i of t)if(Xt(e,i,n,r))return!0;return!1}function uA(e,t,n,r){for(let i of t)if(!Xt(e,i,n,r))return!1;return!0}function Ks(e){return od(e),{context:e,stack:{evaluatedFeatures:new Set}}}function Gs(e){return{...e.attributes,...e.attributeOverrides}}function er(e,t,n){let r=t||"id",i="",a=Gs(e);return a[r]&&(i=a[r]),!i&&n&&(a[n]&&(i=a[n]),i&&(r=n)),{hashAttribute:r,hashValue:i}}function Je(e,t,n){e.context.log?.(t,n)}function Xo(e,t){return t=t||0,`${e}__${t}`}function Hs(e,t){return`${e}||${t}`}function lA(e,t,n){let r=e.stickyBucketAssignmentDocs;if(!r)return{};let{hashAttribute:i,hashValue:a}=er(e,t),o=Hs(i,qi(a)),{hashAttribute:s,hashValue:c}=er(e,n),u=c?Hs(s,qi(c)):null,l={};return u&&r[u]&&Object.assign(l,r[u].assignments||{}),r[o]&&Object.assign(l,r[o].assignments||{}),l}function Od({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=Xo(t,n),c=lA(e,r,i);if(a>0)for(let m=0;m<a;m++){let x=Xo(t,m);if(c[x]!==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 _d(e,t,n,r){let i=Hs(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 Cd(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function ea(e,t){let n=Ks(t),r=Ed(e,null,n);return t.onExperimentEval?.(e,r),r}function Ln(e,t){return Js(e,Ks(t))}function dA(e){return e.forcedVariations||{}}function Pd(e,t,n){let{context:r}=e;if(r.trackedExperiments){let i=jd(t,n);if(r.trackedExperiments.has(i))return;r.trackedExperiments.add(i)}Qs(()=>r.onExperimentViewed?.(t,n))}function pA(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}Qs(()=>r.onFeatureUsage?.(t,n))}function Qs(e){try{let t=e();t&&typeof t.catch=="function"&&t.catch(()=>{})}catch{}}function Js(e,t){let{context:n}=t;if(t.stack.evaluatedFeatures.has(e))return Je(t,`evalFeature: circular dependency detected: ${t.stack.id} -> ${e}`,{from:t.stack.id,to:e}),tr(t,e,null,"cyclicPrerequisite");t.stack.evaluatedFeatures.add(e),t.stack.id=e;let r=n.features?.[e];for(let a of r?.rules??[])Vs(a);let i=n.forcedFeatureValues;if(i&&i.has(e))return Je(t,"Global override",{id:e,value:i.get(e)}),tr(t,e,i.get(e),"override");if(!r)return Je(t,"Unknown feature",{id:e}),tr(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=Js(u.id,t);if(l.source==="cyclicPrerequisite")return tr(t,e,null,"cyclicPrerequisite");let m={value:l.value};if(!Xt(m,u.condition||{},n.savedGroups||{})){if(u.gate)return Je(t,"Feature blocked by prerequisite",{id:e,rule:o}),tr(t,e,null,"prerequisite");Je(t,"Skip rule because prerequisite evaluation fails",{id:e,rule:o});continue e}}if(o.filters&&kd(o.filters,t)){Je(t,"Skip rule because of filters",{id:e,rule:o});continue}if("force"in o){if(o.condition&&!Rd(o.condition,t)){Je(t,"Skip rule because of condition ff",{id:e,rule:o});continue}if(!mA(t,o.seed||e,o.hashAttribute,n.saveStickyBucketAssignmentDoc&&!o.disableStickyBucketing?o.fallbackAttribute:void 0,o.range,o.coverage,o.hashVersion)){Je(t,"Skip rule because user not included in rollout",{id:e,rule:o});continue}return Je(t,"Force value from rule",{id:e,rule:o}),o.tracks&&o.tracks.forEach(u=>{Pd(t,u.experiment,u.result)}),tr(t,e,o.force,"force",o.id)}if(!o.variations){Je(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=Ed(s,e,t);if(n.onExperimentEval?.(s,c),c.inExperiment&&!c.passthrough)return tr(t,e,c.value,"experiment",o.id,s,c)}}return Je(t,"Use default value",{id:e,value:r.defaultValue}),tr(t,e,r.defaultValue===void 0?null:r.defaultValue,"defaultValue")}function Ed(e,t,n){let{context:r}=n;Vs(e);let i=e.key,a=e.variations.length;if(a<2)return Je(n,"Invalid experiment",{id:i}),kt(n,e,-1,!1,t);if(r.enabled===!1)return Je(n,"Context disabled",{id:i}),kt(n,e,-1,!1,t);if(e.urlPatterns&&!id(r.url||"",e.urlPatterns))return Je(n,"Skip because of url targeting",{id:i}),kt(n,e,-1,!1,t);let o=nd(i,r.url||"",a);if(o!==null)return Je(n,"Force via querystring",{id:i,variation:o}),kt(n,e,o,!1,t);let c=dA(r)[i];if(c!==void 0)return Je(n,"Force via dev tools",{id:i,variation:c}),kt(n,e,c,!1,t);if(e.active===!1)return Je(n,"Skip because inactive",{id:i}),kt(n,e,-1,!1,t);let{hashAttribute:u,hashValue:l}=er(r,e.hashAttribute,r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0);if(!l)return Je(n,"Skip because missing hashAttribute",{id:i}),kt(n,e,-1,!1,t);let m=-1,x=!1,A=!1;if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{variation:f,versionIsBlocked:I}=Od(Cd({context:r,expKey:e.key,expBucketVersion:e.bucketVersion,expHashAttribute:e.hashAttribute,expFallbackAttribute:e.fallbackAttribute,expMinBucketVersion:e.minBucketVersion,expMeta:e.meta}));x=f>=0,m=f,A=!!I}if(!x){if(e.filters&&kd(e.filters,n))return Je(n,"Skip because of filters",{id:i}),kt(n,e,-1,!1,t);if(e.include&&!rd(e.include))return Je(n,"Skip because of include function",{id:i}),kt(n,e,-1,!1,t);if(e.condition&&!Rd(e.condition,n))return Je(n,"Skip because of condition exp",{id:i}),kt(n,e,-1,!1,t);if(e.parentConditions){let f=new Set(n.stack.evaluatedFeatures);for(let I of e.parentConditions){n.stack.evaluatedFeatures=new Set(f);let y=Js(I.id,n);if(y.source==="cyclicPrerequisite")return kt(n,e,-1,!1,t);let P={value:y.value};if(!Xt(P,I.condition||{},r.savedGroups||{}))return Je(n,"Skip because prerequisite evaluation fails",{id:i}),kt(n,e,-1,!1,t)}}}let p=Ko(e.seed||i,l,e.hashVersion??2);if(p===null)return Je(n,"Skip because of invalid hash version",{id:i}),kt(n,e,-1,!1,t);if(!x){let f=e.ranges||td(a,e.coverage===void 0?1:e.coverage,e.weights);m=ed(p,f)}if(A)return Je(n,"Skip because sticky bucket version is blocked",{id:i}),kt(n,e,-1,!1,t,void 0,!0);if(m<0)return Je(n,"Skip because of coverage",{id:i}),kt(n,e,-1,!1,t);if("force"in e)return Je(n,"Force variation",{id:i,variation:e.force}),kt(n,e,e.force===void 0?-1:e.force,!1,t);if(r.qaMode)return Je(n,"Skip because QA mode",{id:i}),kt(n,e,-1,!1,t);let g=kt(n,e,m,!0,t,p,x);if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{changed:f,key:I,doc:y}=_d(r,u,qi(l),{[Xo(e.key,e.bucketVersion)]:g.key});if(f){r.stickyBucketAssignmentDocs=r.stickyBucketAssignmentDocs||{},r.stickyBucketAssignmentDocs[I]=y;let P=r.saveStickyBucketAssignmentDoc;Qs(()=>P(y))}}return Pd(n,e,g),Je(n,"In experiment",{id:i,variation:g.variationId}),g}function tr(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"&&pA(e,t,s),s}function Rd(e,t){return Xt(Gs(t.context),e,t.context.savedGroups||{})}function kd(e,t){return e.some(n=>{let{hashValue:r}=er(t.context,n.attribute);if(!r)return!0;let i=Ko(n.seed,r,n.hashVersion||2);return i===null?!0:!n.ranges.some(a=>Go(i,a))})}function mA(e,t,n,r,i,a,o){if(!i&&a===void 0)return!0;if(!i&&a===0)return!1;let{hashValue:s}=er(e.context,n,r);if(!s)return!1;let c=Ko(t,s,o??2);return c===null?!1:i?Go(c,i):a!==void 0?c<=a:!0}function kt(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}=er(e.context,t.hashAttribute,e.context.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0),l=t.meta?.[n]??{},m=t.variations[0];for(let[A,p]of t.variations.entries())if(A===n){m=p;break}let x={key:l.key||""+n,featureId:i,inExperiment:s,hashUsed:r,variationId:n,value:m,hashAttribute:c,hashValue:u,stickyBucketUsed:!!o};return l.name&&(x.name=l.name),a!==void 0&&(x.bucket=a),l.passthrough&&(x.passthrough=l.passthrough),x}function jd(e,t){return t.hashAttribute+t.hashValue+e.key+t.variationId}/*!
|
|
1
|
+
var Dh=Object.defineProperty;var Fh=(e,t,n)=>t in e?Dh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var De=(e,t,n)=>Fh(e,typeof t!="symbol"?t+"":t,n);import{z as os}from"zod";var Mh=os.enum(["sandbox","live"]),Ue=os.object({projectId:os.string().min(1),environment:Mh}).strict();import{z as Le}from"zod";var Oi=Le.number().int().min(1).max(Number.MAX_SAFE_INTEGER),Gu=Le.enum(["unknown","denied","provisional","granted"]),Ku=Le.enum(["ios","android"]),So=Le.strictObject({installationId:Le.uuid(),publicKey:Le.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:Le.iso.datetime({offset:!0}),signature:Le.string().regex(/^[A-Za-z0-9_-]{86}$/)}),as=Le.string().regex(/^[a-f0-9]{64}$/),Hu=So.extend({sequence:Oi,platform:Ku,credentialDigest:as}),Qu=So.extend({credentialDigest:as}),Ju=So.extend({sequence:Oi,platform:Ku}),xo=So.extend({sequence:Oi,credentialDigest:as,connectionId:Le.uuid().nullable(),kind:Le.enum(["fcm_token","apns_token"]).nullable(),token:Le.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:Gu}),Zu=xo,Wu=xo.extend({challenge:Le.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),ss=Le.strictObject({requested:Le.literal(!0),expiresAt:Le.iso.datetime({offset:!0})}),gr=Le.strictObject({installationId:Le.uuid(),bound:Le.boolean(),identitySeq:Oi,bindingGeneration:Oi,addressSeq:Le.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:Le.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:Le.uuid().nullable(),addressStatus:Le.enum(["active","invalid"]).nullable(),permission:Gu}),cs=Le.strictObject({channel:Le.enum(["email","sms","voice","push"]),state:Le.enum(["unknown","allowed","denied"]),revision:Le.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:Le.iso.datetime({offset:!0}).nullable()}),CI=Le.strictObject({state:Le.enum(["allowed","denied"]),revision:Le.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function Yu(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 It}from"zod";var Tn=It.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"]),RI=It.enum([...Tn.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),kI=It.enum([...Tn.options,"stale_revision"]),us=It.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"]),ls=It.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),el={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 Xu={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 qh(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(Xu,e)){let r=Xu[e];return{retryable:r==="retry_same_request",recovery:r}}let n=Tn.safeParse(e);return n.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:el[n.data].recovery}:{retryable:!1,recovery:"contact_support"}}function tl(e,t){let n=Tn.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):el[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 Vh(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 nl=It.object({retryable:It.boolean(),recovery:us,reason:ls.optional(),retryAfterSeconds:It.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),ds=It.object({requestId:It.uuid().optional(),error:It.object({code:It.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:It.string(),...nl.partial().shape})}),jI=It.object({error:ds.shape.error.extend({requestId:It.uuid().optional()})}),TI=It.object({error:It.string(),code:It.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:It.uuid(),...nl.shape});function Io(e,t,n={}){let r=qh(e,t),i=n.reason==="RESULT_UNKNOWN"?"recover_operation":n.recovery??r.recovery,a=r.retryable&&n.retryable!==!1&&i!=="recover_operation",o=a?Vh(n.retryAfter??null):void 0;return{...r,retryable:a,recovery:i,...o===void 0?{}:{retryAfterSeconds:o},...n.reason?{reason:n.reason}:{}}}var ps="X-Indiana-Protocol",rl="X-Indiana-SDK-Version";var ms={current:"0.10"};import{z as Bh}from"zod";var Uh=["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"],he=Bh.enum(Uh);import{z as _}from"zod";var Dt=_.string().min(1).max(200),Gt=_.iso.datetime({offset:!0}),mt=_.number().int().nonnegative().max(1e8),vo=_.string().regex(/^[A-Z]{3}$/),Lh=["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"],il=_.enum(Lh),ol=_.strictObject({priceId:_.uuid(),productVersionId:_.uuid(),productId:Dt,quantity:_.number().int().min(1).max(1e6),unitAmountMinor:mt,totalMinor:mt,interval:_.enum(["week","month","year","one_off"]),intervalCount:_.number().int().min(1).max(52),kind:_.enum(["fixed","prepaid","seat"]),tiers:_.strictObject({mode:_.enum(["graduated","volume"]),tiers:_.array(_.strictObject({upTo:_.number().int().positive().nullable(),unitAmountMinor:mt,flatAmountMinor:mt.optional()})).min(2).max(12)}).nullable()}),zh=_.strictObject({grantId:_.uuid(),couponId:_.uuid(),amountMinor:mt,terms:_.discriminatedUnion("type",[_.strictObject({type:_.literal("percent"),percentOff:_.number().gt(0).max(100)}),_.strictObject({type:_.literal("amount"),amountOffMinor:mt,currency:vo})]),duration:_.discriminatedUnion("type",[_.strictObject({type:_.literal("once")}),_.strictObject({type:_.literal("forever")}),_.strictObject({type:_.literal("repeating"),months:_.number().int().min(1).max(36)})])}),As={provider:_.literal("merchant"),executor:_.literal("merchant"),operationId:_.uuid(),customerId:_.uuid(),configurationRevision:_.number().int().nonnegative(),connectionRevision:_.number().int().nonnegative(),currency:vo,expiresAt:Gt},wo=_.strictObject({...As,type:_.literal("purchase"),mode:_.enum(["payment","subscription"]),lineItems:_.array(ol).min(1).max(100),catalogAmountMinor:mt,discount:zh.nullable(),trialPeriodDays:_.number().int().min(1).max(730).nullable(),automaticTax:_.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"),Oo=_.strictObject({...As,type:_.literal("subscription_change"),subscriptionId:_.uuid(),merchantSubscriptionId:Dt,membershipId:_.uuid(),subscriptionAction:_.enum(["update","cancel","schedule","release"]),supersedesOperationId:_.uuid().nullable(),change:_.discriminatedUnion("type",[_.strictObject({type:_.literal("cancel")}),_.strictObject({type:_.literal("uncancel")}),_.strictObject({type:_.literal("plan"),productVersionId:_.uuid()}),_.strictObject({type:_.literal("seats"),licenseKey:Dt,quantity:_.number().int().nonnegative().max(1e6)}),_.strictObject({type:_.literal("quantity"),internal_feature_id:_.uuid(),quantity:_.number().int().nonnegative().max(1e6)}),_.strictObject({type:_.literal("billing_cycle"),billingCycleAnchor:_.union([_.literal("now"),_.number().int().positive()])})]),timing:_.enum(["immediate","renewal"]),effectiveAt:Gt,creditMinor:mt,debitMinor:mt,totalMinor:mt,discountMinor:mt,taxMinor:mt,proration:_.enum(["none","create_prorations","always_invoice"]),lineItems:_.array(ol.extend({quantity:_.number().int().nonnegative().max(1e6)})).max(100),removePriceIds:_.array(_.uuid()).max(100)}),_o=_.strictObject({...As,type:_.literal("refund"),invoiceId:_.uuid(),merchantInvoiceId:Dt,amountMinor:mt.refine(e=>e>0),mode:_.enum(["full","partial"]),entitlementAction:_.enum(["retain","revoke"]),cancelSubscriptions:_.array(Dt).max(100)}),al=_.discriminatedUnion("type",[wo,Oo,_o]);var _i=_.strictObject({phase:_.enum(["execution","payment","fulfillment","recording"]),code:Tn,reason:ls.optional(),recovery:us,retryable:_.boolean()}).refine(e=>e.reason!=="RESULT_UNKNOWN"||!e.retryable&&e.recovery==="recover_operation","Unknown financial effects require recovery of the original operation"),fs={operationId:_.uuid(),customerId:_.uuid(),merchantExecutionId:Dt,fulfillmentStatus:_.enum(["not_started","pending","applied","failed","not_applicable"]),recordingStatus:_.enum(["not_ready","pending","accepted","failed"]),updatedAt:Gt,problem:_i.nullable(),pollAfterMs:_.number().int().min(1e3).max(6e4).nullable()},hr=_.discriminatedUnion("type",[_.strictObject({...fs,type:_.literal("purchase"),merchantOrderId:Dt.nullable(),paymentStatus:_.enum(["not_started","pending","succeeded","not_required","failed","expired","unknown"]),checkoutUrl:_.url().refine(e=>new URL(e).protocol==="https:").nullable(),checkoutExpiresAt:Gt.nullable()}).refine(e=>!e.checkoutUrl||["not_started","pending"].includes(e.paymentStatus)&&e.checkoutExpiresAt!==null,"Only an unfinished original purchase may expose its checkout"),_.strictObject({...fs,type:_.literal("subscription_change"),status:_.enum(["pending","scheduled","applied","failed","unknown"]),merchantSubscriptionId:Dt,scheduledFor:Gt.nullable()}).refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"A scheduled change retains its future effective time"),_.strictObject({...fs,type:_.literal("refund"),status:_.enum(["pending","succeeded","failed","unknown"]),merchantRefundId:Dt.nullable()}).refine(e=>e.status!=="succeeded"||e.merchantRefundId!==null,"A successful refund retains its original merchant identity")]),sl=_.discriminatedUnion("lookup",[_.strictObject({lookup:_.literal("found"),operationId:_.uuid(),customerId:_.uuid(),execution:hr,readAt:Gt}),_.strictObject({lookup:_.literal("not_received"),operationId:_.uuid(),customerId:_.uuid(),execution:_.null(),readAt:Gt})]).refine(e=>!e.execution||e.execution.operationId===e.operationId&&e.execution.customerId===e.customerId,"Lookup must retain the original Customer and operation"),gs=_.strictObject({merchantSubscriptionId:Dt,revision:_.number().int().positive(),status:_.enum(["incomplete","trialing","active","past_due","canceled","unpaid","paused","incomplete_expired"]),periodStartsAt:Gt,periodEndsAt:Gt,cancelAtPeriodEnd:_.boolean(),hasDiscounts:_.boolean(),items:_.array(_.strictObject({merchantItemId:Dt,priceId:_.uuid(),quantity:_.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"),hs=_.strictObject({merchantInvoiceId:Dt,currency:vo,subtotalMinor:mt,discountMinor:mt,taxMinor:mt,totalMinor:mt,paidMinor:mt,periodStartsAt:Gt.nullable(),periodEndsAt:Gt.nullable(),lines:_.array(_.strictObject({merchantLineId:Dt,priceId:_.uuid(),quantity:_.number().int().nonnegative().max(1e6),subtotalMinor:_.number().int().min(-1e8).max(1e8),discountMinor:mt,taxMinor:mt,totalMinor:_.number().int().min(-1e8).max(2e8),periodStartsAt:Gt.nullable(),periodEndsAt:Gt.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"),Vr={provider:_.literal("merchant"),eventId:_.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),customerId:_.uuid(),occurredAt:Gt},cl=_.enum(["purchase.completed","purchase.closed","subscription.observed","subscription.change.completed","invoice.paid","refund.updated"]),ul=_.discriminatedUnion("type",[_.strictObject({...Vr,type:_.literal("purchase.completed"),operationId:_.uuid(),merchantOrderId:Dt,paymentStatus:_.enum(["paid","trialing","no_payment_required"]),invoice:hs.nullable(),subscription:gs.nullable()}).refine(e=>e.paymentStatus!=="paid"||e.invoice!==null,"A paid purchase includes its Invoice"),_.strictObject({...Vr,type:_.literal("purchase.closed"),operationId:_.uuid(),status:_.enum(["failed","expired","canceled"])}),_.strictObject({...Vr,type:_.literal("subscription.observed"),operationId:_.uuid().nullable(),subscription:gs}),_.strictObject({...Vr,type:_.literal("subscription.change.completed"),operationId:_.uuid(),status:_.enum(["scheduled","applied"]),scheduledFor:Gt.nullable(),subscription:gs,invoice:hs.nullable()}).refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"Scheduled and applied changes are distinct facts"),_.strictObject({...Vr,type:_.literal("invoice.paid"),merchantSubscriptionId:Dt,invoice:hs}),_.strictObject({...Vr,type:_.literal("refund.updated"),operationId:_.uuid(),merchantRefundId:Dt,status:_.enum(["pending","succeeded","failed"]),amountMinor:mt.refine(e=>e>0),currency:vo})]);import{z as R}from"zod";import{z as Ar}from"zod";var Ft=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,Gn=Ar.object({customerId:Ar.uuid(),sessionId:Ar.uuid(),accessToken:Ar.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),refreshToken:Ar.string().regex(/^gg_rt_[A-Za-z0-9_-]{43}$/),expiresAt:Ar.iso.datetime(),refreshExpiresAt:Ar.iso.datetime()});var bs=3;var $h=["session","catalog","customer_commerce","presentation","presentation_events","purchases","operation_status","billing_records","subscription_changes","refunds"],Gh=R.enum($h);var Kh=R.enum(["bridge.ping","bridge.describe","session.create","catalog.read","customer.commerce.read","presentation.resolve","presentation.report","purchase.execute","operation.read","subscription.change","refund.execute"]),dl=R.string().regex(/^[A-Za-z0-9_-]{1,64}$/),Hh=R.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(e=>"AEIMQUYcgkosw048".includes(e.at(-1)),"Use canonical base64url for a 32-byte key"),Qh=R.strictObject({keyId:dl,signingSecret:Hh}),Jh=R.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),pl=R.array(Gh).max(10).refine(e=>new Set(e).size===e.length,"Capabilities must be unique"),ml=R.strictObject({bridgeVersion:R.literal(bs),projectId:R.uuid(),environmentId:R.uuid(),environment:R.enum(["sandbox","live"]),capabilities:pl,catalog:R.enum(["endpoint","static","none"]),billingEvents:R.array(cl).max(6),profiles:R.array(il).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"})}),fl=R.strictObject({origin:Jh,requiredCapabilities:pl}),Zh=R.strictObject({revision:R.number().int().nonnegative(),checkedAt:R.iso.datetime(),outcome:R.enum(["valid","unreachable","invalid","scope_mismatch","authentication_failed","credentials_missing"]),diagnostics:R.strictObject({ping:R.enum(["passed","failed","not_checked"]),authentication:R.enum(["passed","failed","not_checked"]),catalog:R.enum(["passed","failed","not_checked","static","unsupported"])}),manifest:ml.nullable()}).superRefine((e,t)=>{e.outcome==="valid"!=(e.manifest!==null)&&t.addIssue({code:"custom",path:["manifest"],message:"Only a valid declaration carries a manifest"})}),KI=R.strictObject({projectId:R.uuid(),environmentId:R.uuid(),environment:R.enum(["sandbox","live"]),execution:R.enum(["indiana","record_only"]),accountId:R.string().nullable(),revision:R.number().int().nonnegative(),authentication:R.strictObject({keyId:dl}).nullable(),secretStoreConfigured:R.boolean().optional(),connection:fl.nullable(),check:Zh.nullable()});var ll=R.strictObject({projectId:R.uuid(),environmentId:R.uuid()}),HI=R.discriminatedUnion("action",[ll.extend({action:R.literal("save"),revision:R.number().int().nonnegative(),connection:fl,authentication:Qh.optional()}),ll.extend({action:R.literal("check"),revision:R.number().int().nonnegative()})]),Ss=R.strictObject({projectId:R.uuid(),environmentId:R.uuid(),environment:R.enum(["sandbox","live"])});var Wh=R.strictObject({nativeUserId:R.string().min(1).max(128),session:Gn.strict()}),Yh=R.strictObject({nativeUserId:R.string().min(1).max(128),presentation:R.strictObject({customerId:R.uuid(),decisionId:R.uuid(),offeringVersionId:R.uuid(),paywallVersionId:R.uuid(),variant:R.string().min(1).max(128)}).nullable()}),Xh=R.strictObject({decisionId:R.uuid(),eventId:R.uuid()}),Co=R.strictObject({operationId:R.uuid(),customerId:R.uuid()}),Po=R.strictObject({scope:Ss,operationId:R.uuid(),customerId:R.uuid(),confirmedAt:R.iso.datetime({offset:!0}).nullable(),initialExecutionAllowed:R.boolean(),instruction:al}).refine(e=>e.operationId===e.instruction.operationId&&e.customerId===e.instruction.customerId,"Authority must refer to the original Customer and operation"),ys=hr,Nn=R.string().min(1).max(120),eA=R.string().regex(/^-?[0-9]+(?:\.[0-9]{1,6})?$/),tA=R.strictObject({revision:Nn,updatedAt:R.iso.datetime(),provider:R.literal("merchant"),items:R.array(R.strictObject({merchantProductId:Nn,productVersionId:R.uuid(),name:R.string().min(1).max(255),kind:R.enum(["subscription","credit_pack"]),merchantPriceId:Nn,currency:R.string().regex(/^[a-z]{3}$/),amountMinor:R.number().int().nonnegative().max(1e8),interval:R.enum(["one_time","month","year"]),intervalCount:R.literal(1),includedCredits:R.string().regex(/^[0-9]{1,18}(?:\.[0-9]{1,6})?$/),creditReset:R.enum(["none","month"]),creditPolicyId:Nn,available:R.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)}),nA=R.strictObject({customerId:R.uuid(),revision:R.string().min(1).max(128),observedAt:R.iso.datetime(),subscriptions:R.array(R.strictObject({merchantSubscriptionId:Nn,merchantProductId:Nn,productVersionId:R.uuid().nullable(),status:R.enum(["active","trialing","past_due","cancelled","expired"]),currentPeriodStartsAt:R.iso.datetime().nullable(),currentPeriodEndsAt:R.iso.datetime().nullable(),cancelAtPeriodEnd:R.boolean(),scheduledChange:R.strictObject({effectiveAt:R.iso.datetime(),merchantProductId:Nn}).nullable()})).max(100),purchaseHistory:R.strictObject({complete:R.boolean(),hasPaidPurchase:R.boolean(),lastPaidAt:R.iso.datetime().nullable()}),balances:R.array(R.strictObject({bucketId:Nn,key:Nn,available:eA,expiresAt:R.iso.datetime().nullable(),nextResetAt:R.iso.datetime().nullable()})).max(100)}),QI=R.strictObject({bridgeVersion:R.literal(bs),requestId:R.uuid(),command:R.string().min(1).max(64),scope:Ss,error:R.strictObject({code:R.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:R.string().min(1).max(500),retryable:R.boolean(),recovery:R.string().min(1).max(80)})}),Ci=R.strictObject({}),rA={"bridge.ping":R.strictObject({challenge:R.uuid()}),"bridge.describe":Ci,"session.create":Ci,"catalog.read":Ci,"customer.commerce.read":Ci,"presentation.resolve":Ci,"presentation.report":Xh,"purchase.execute":Co,"operation.read":Co,"subscription.change":Co,"refund.execute":Co},JI={"bridge.ping":R.strictObject({challenge:R.uuid()}),"bridge.describe":ml,"session.create":Wh,"catalog.read":tA,"customer.commerce.read":nA,"presentation.resolve":Yh,"presentation.report":R.strictObject({queued:R.literal(!0)}),"purchase.execute":ys,"operation.read":sl,"subscription.change":ys,"refund.execute":ys},ZI=R.strictObject({bridgeVersion:R.literal(bs),requestId:R.uuid(),scope:Ss,command:Kh,data:R.unknown()}).superRefine((e,t)=>{rA[e.command].safeParse(e.data).success||t.addIssue({code:"custom",path:["data"],message:"Invalid command data"})});import{z as Br}from"zod";var Eo=Br.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"),ev=Br.object({amountCents:Br.number().int().min(0).max(1e8),currency:he,interval:Br.enum(["free","month","year"]),currencyOptions:Br.partialRecord(he,Br.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 D}from"zod";var iA=D.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Al=D.enum(["single_use","continuous_use"]),xs=D.record(D.string(),D.union([D.string(),D.number(),D.boolean()]).transform(String).pipe(D.string())),gl=D.string().min(1).max(64).refine(e=>!e.includes("::")),yl={credit_amount:D.number(),tier_behavior:D.never().optional(),tiers:D.never().optional()},bl={credit_amount:D.never().optional(),tier_behavior:D.literal("graduated"),tiers:D.array(D.strictObject({to:D.union([D.number(),D.literal("inf")]),credit_amount:D.number()}))},oA=D.union([D.strictObject({match:xs,priority:D.number().int().optional(),...yl}),D.strictObject({match:xs,priority:D.number().int().optional(),...bl})]),aA=D.strictObject({match:xs,factor:D.number().positive().optional(),add:D.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),hl={metered_feature_id:D.string(),feature_amount:D.number().optional(),dimensions:D.record(gl,oA).optional(),multipliers:D.record(gl,aA).optional()},Is=D.union([D.strictObject({...hl,...yl}),D.strictObject({...hl,...bl})]),ko=D.number().min(-100),Sl=D.record(D.string(),D.strictObject({markup:ko})).nullish(),jo=D.record(D.string().regex(/.+\/.+/),D.strictObject({markup:ko.optional(),input_cost:D.number().min(0).optional(),output_cost:D.number().min(0).optional()})).nullish(),sA=D.strictObject({default_markup:ko.optional(),provider_markups:Sl,model_markups:jo}),rv=D.strictObject({schema:D.array(Is).optional(),markups:sA.optional()}),cA=D.strictObject({filters:D.array(D.strictObject({property:D.string(),operator:D.string(),value:D.array(D.string())})),aggregate:D.strictObject({type:D.string(),property:D.string().nullable()}),usage_type:Al}),xl=D.strictObject({schema:D.array(Is).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:D.boolean().optional(),usage_type:Al.default("single_use").overwrite(()=>"single_use"),default_markup:ko.optional(),provider_markups:Sl}),vs=xl.safeExtend({schema:D.array(Is).length(0)}),Ro={id:iA,name:D.string().min(1),display:D.strictObject({singular:D.string().optional(),plural:D.string().optional()}).nullish(),event_names:D.array(D.string()).default([]),model_markups:jo,stripe_meter:D.strictObject({id:D.string(),event_name:D.string()}).nullish(),stripe_product_id:D.string().nullish()},ws=e=>D.discriminatedUnion("type",[D.strictObject({...Ro,...e,type:D.literal("boolean"),config:D.null()}),D.strictObject({...Ro,...e,type:D.literal("metered"),config:cA}),D.strictObject({...Ro,...e,type:D.literal("credit_system"),config:xl}),D.strictObject({...Ro,...e,type:D.literal("ai_credit_system"),config:vs})]),iv=ws({}),uA=D.strictObject({id:D.boolean(),type:D.boolean(),usage_type:D.boolean()}),lA={internal_id:D.uuid(),org_id:D.uuid(),created_at:D.number(),env:D.enum(["sandbox","live"]),archived:D.boolean(),project_id:D.uuid(),environment_id:D.uuid(),revision:D.number().int().nonnegative(),update_rules:uA},Il=ws(lA),ov=D.strictObject({rows:D.array(Il).max(200),nextCursor:D.uuid().nullable()}),av=D.strictObject({features:D.array(Il).max(500),limited:D.boolean()}),sv=D.union([ws({action:D.literal("save"),internal_id:D.uuid().nullable(),revision:D.number().int().nonnegative()}),D.strictObject({action:D.enum(["archive","restore","delete"]),internal_id:D.uuid(),revision:D.number().int().nonnegative()})]);import{z as zr}from"zod";import{z as ot}from"zod";var Kt=ot.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),ge=ot.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),To=ot.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}),Os=ge.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),vl=ot.string().min(1).max(64),yr=ot.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),wl=ot.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),gt=ot.record(vl,ot.union([ot.string().max(120),ot.number().finite(),ot.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)]))),Ol=ot.record(vl,ot.union([ot.string().max(120),ot.number().finite(),ot.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),Ur=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},_l=ot.array(ot.object({upTo:Os.nullable(),cost:ge}).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&&Ur(t.upTo)>Ur(r))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),dA=ot.object({key:wl,match:Ol,priority:ot.number().int().default(0),cost:ge.optional(),tiers:_l.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),pA=ot.object({key:wl,match:Ol,factor:Os.optional(),add:To.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"})),mA=ot.object({units:Os.default("1"),cost:ge,tiers:_l.optional(),dimensions:ot.array(dA).max(12).optional(),multipliers:ot.array(pA).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=Ur(e.units);for(let o of i)for(let s=0;s<1<<r.length;s++){let c=r.filter((p,g)=>s&1<<g);if(c.some((p,g)=>c.slice(g+1).some(f=>Object.keys(p.match).some(I=>f.match[I]!==void 0&&f.match[I]!==p.match[I]))))continue;let u=Ur(o),l=BigInt("1"),m=BigInt("0");for(let[p,g]of r.entries())s&1<<p&&(u*=Ur(g.factor??"1"),l*=BigInt("1000000"),m+=Ur(g.add??"0"));let S=(u+m*l)*BigInt("1000000"),y=l*a;(S<BigInt("0")||S%y!==BigInt("0")||S/y>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"})}}),lv=mA.safeExtend({featureKey:yr});import{z as Lr}from"zod";var Cl=Lr.number().int().min(0).max(1e8),Pi=Lr.strictObject({kind:Lr.enum(["graduated","volume"]),tiers:Lr.array(Lr.strictObject({upTo:Lr.number().int().min(1).max(1e4).nullable(),unitAmountMinor:Cl,flatAmountMinor:Cl.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 _s(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let n=e.pricing?Pi.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 No(e){return _s({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}var fA=ge.refine(e=>/[1-9]/.test(e)),Do=zr.strictObject({units:fA,prices:zr.array(zr.strictObject({currency:he,amountMinor:zr.number().int().min(0).max(1e8),pricing:Pi.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:zr.number().int().min(0).max(1e4),maximumQuantity:zr.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&&_s({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 Pl(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 El(e,t,n){if(!Number.isSafeInteger(n)||n<0||n>1e4)throw new Error("Invalid purchased quantity");let r=Pl(e)+Pl(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 h}from"zod";import{z as X}from"zod";import{z as Ct}from"zod";import{z as j}from"zod";function Rl(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 Fo(e,t,n){return n===2?Rl(Rl(e+t)+"")%1e4/1e4:null}function gA(e){return e<=0?[]:new Array(e).fill(1/e)}function Mo(e,t){return e>=t[0]&&e<t[1]}function kl(e,t){for(let[n,r]of t.entries())if(Mo(e,r))return n;return-1}function jl(e,t,n){t=t===void 0?1:t,t<0?t=0:t>1&&(t=1);let r=gA(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 Tl(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 Nl(e){try{return e()}catch{return!1}}function Ei(e){return typeof e=="string"?e:JSON.stringify(e)}function Xt(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 hA(e){try{let t=e.replace(/([^\\])\//g,"$1\\/");return new RegExp(t)}catch{return}}function Dl(e,t){if(!t.length)return!1;let n=!1,r=!1;for(let i of t){let a=bA(e,i.type,i.pattern);if(i.include===!1){if(a)return!1}else n=!0,a&&(r=!0)}return r||!n}function AA(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 yA(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=>!AA(i[0],i[1],i[2]))}catch{return!1}}function bA(e,t,n){try{let r=new URL(e,"https://_");if(t==="regex"){let i=hA(n);return i?i.test(r.href)||i.test(r.href.substring(r.origin.length)):!1}else if(t==="simple")return yA(r,n);return!1}catch{return!1}}function Cs(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 qo(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 Fl(e){for(let t of["overrides","groups"])if(Object.hasOwn(e,t))throw new TypeError(`Retired evaluation context field: ${t}`);qo(e.savedGroups??{})}var SA=e=>e/2**32|0,xA=e=>e>>>0;function Ml(e,t,n,r){let i=SA(n),a=xA(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function ql(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var Ps=e=>e?`"${e}" `:"";function IA(e,t=""){if(typeof e!="number")throw new TypeError(Ps(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(Ps(t)+"expected integer >= 0, got "+e);return e}function Vo(e,t,n=""){if(ql(e)&&(t===void 0||e.length===t))return e;t!==void 0&&IA(t,"length");let r=ql(e),i=t!==void 0?` of length ${t}`:"",a=r?`length=${e.length}`:`type=${typeof e}`,o=Ps(n)+"expected Uint8Array"+i+", got "+a;throw r?new RangeError(o):new TypeError(o)}var vA=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},Vl=(e,t)=>{vA(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 Es(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function Bl(e,t){Vo(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function Rs(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Bo(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function fn(e,t){return e<<32-t|e>>>t}var wA=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",OA=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function $r(e){if(Vo(e),wA)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=OA[e[n]];return t}function _A(e,t,n="opts"){return Vl(e,"defaults"),t!==void 0&&Vl(t,n),Object.assign(Object.create(null),e,t)}function Ul(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=_A({},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 Ll=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function zl(e,t,n){return e&t^~e&n}function $l(e,t,n){return e&t^e&n^t&n}var Uo=class{constructor(t,n,r,i){De(this,"blockLen");De(this,"outputLen");De(this,"canXOF",!1);De(this,"padOffset");De(this,"isLE");De(this,"buffer");De(this,"view");De(this,"finished",!1);De(this,"length",0);De(this,"pos",0);De(this,"destroyed",!1);this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(t),this.view=Bo(this.buffer)}update(t){Es(this),Vo(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=Bo(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){Es(this),Bl(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)),Ml(r,i-8,this.length*8,a),this.process(r,0),this.roundClean();let s=t===n?r:Bo(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()}},Gl=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var CA=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]),Kn=new Uint32Array(64),ks=class extends Uo{constructor(n,r){super(64,n,8,!1);De(this,"A",0);De(this,"B",0);De(this,"C",0);De(this,"D",0);De(this,"E",0);De(this,"F",0);De(this,"G",0);De(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 S=0;S<16;S++,r+=4)Kn[S]=n.getUint32(r,!1);for(let S=16;S<64;S++){let y=Kn[S-15],p=Kn[S-2],g=fn(y,7)^fn(y,18)^y>>>3,f=fn(p,17)^fn(p,19)^p>>>10;Kn[S]=f+Kn[S-7]+g+Kn[S-16]|0}let{A:i,B:a,C:o,D:s,E:c,F:u,G:l,H:m}=this;for(let S=0;S<64;S++){let y=fn(c,6)^fn(c,11)^fn(c,25),p=m+y+zl(c,u,l)+CA[S]+Kn[S]|0,f=(fn(i,2)^fn(i,13)^fn(i,22))+$l(i,a,o)|0;m=l,l=u,u=c,c=s+p|0,s=o,o=a,a=i,i=p+f|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(){Rs(Kn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Rs(this.buffer)}},js=class extends ks{constructor(){super(32,Gl)}};var Gr=Ul(()=>new js,Ll(1));var Kl=new Map,Ts=32,Hl=new WeakMap,Ql=new WeakMap;function PA(e){return $r(Gr(new TextEncoder().encode(String(e))))}var zo=e=>Array.isArray(e)?e.map(zo):typeof e=="string"||typeof e=="number"?PA(e):null,Lo=e=>typeof e=="string"?e.toLowerCase():e;function Xl(e){let t=Hl.get(e);return t||(t=new Set(e),Hl.set(e,t)),t}function EA(e){let t=Ql.get(e);return t||(t=new Set(e.map(Lo)),Ql.set(e,t)),t}function Kr(e){qo(e);for(let t of Object.values(e)){let n=t?.type==="list"||t?.type==="hashed"?t.values:null;n&&n.length>=Ts&&Xl(n)}return e}function Qt(e,t,n,r){n=n||{},r||qo(n),r=r||new Set;for(let[i,a]of Object.entries(t))switch(i){case"$or":if(!Yl(e,a,n,r))return!1;break;case"$nor":if(Yl(e,a,n,r))return!1;break;case"$and":if(!NA(e,a,n,r))return!1;break;case"$not":if(Qt(e,a,n,r))return!1;break;case"$savedGroup":if(!RA(e,a,n,r))return!1;break;default:if(!Ri(a,ed(e,i),n,!1,r))return!1}return!0}function RA(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=ed(e,c);return br(o.type==="hashed"?zo(u):u,o.values)}return o.type==="condition"?!o.condition||typeof o.condition!="object"?!1:Qt(e,o.condition,n,s):!1}function ed(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 Jl(e,t=!1){let n=`${e}${t?"/i":""}`,r=Kl.get(n);return r||(r=new RegExp(e.replace(/([^\\])\//g,"$1\\/"),t?"i":void 0),Kl.set(n,r)),r}function Ri(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)||!td(e))return JSON.stringify(t)===JSON.stringify(e);let a=e;for(let o in a)if(!TA(o,t,a[o],n,i))return!1;return!0}function td(e){let t=Object.keys(e);return t.length>0&&t.filter(n=>n[0]==="$").length===t.length}function kA(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 jA(e,t,n,r){if(!Array.isArray(e))return!1;let i=td(t)?a=>Ri(t,a,n,!1,r):a=>Qt(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 br(e,t,n=!1){if(n){let i;if(t.length>=Ts){let a=EA(t);i=o=>{let s=Lo(o);return!(typeof s=="number"&&Number.isNaN(s))&&a.has(s)}}else i=a=>t.some(o=>Lo(a)===Lo(o));return Array.isArray(e)?e.some(a=>i(a)):i(e)}let r=t.length>=Ts?(i=>a=>i.has(a))(Xl(t)):i=>t.includes(i);return Array.isArray(e)?e.some(i=>r(i)):r(e)}function Zl(e){return e===void 0?[]:e&&typeof e=="object"&&(e.type==="list"||e.type==="hashed")&&Array.isArray(e.values)?e.values:null}function Wl(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(Ri(t[a],e[s],n,r,i)){o=!0;break}if(!o)return!1}return!0}function TA(e,t,n,r,i=new Set){let a=t,o=n;switch(e){case"$veq":return Xt(t)===Xt(n);case"$vne":return Xt(t)!==Xt(n);case"$vgt":return Xt(t)>Xt(n);case"$vgte":return Xt(t)>=Xt(n);case"$vlt":return Xt(t)<Xt(n);case"$vlte":return Xt(t)<=Xt(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)?br(t,n):!1;case"$ini":return Array.isArray(n)?br(t,n,!0):!1;case"$inGroup":{let s=r[n],c=Zl(s);return c===null?!1:br(s?.type==="hashed"?zo(t):t,c)}case"$notInGroup":{let s=r[n],c=Zl(s);return c===null?!1:!br(s?.type==="hashed"?zo(t):t,c)}case"$nin":return Array.isArray(n)?!br(t,n):!1;case"$nini":return Array.isArray(n)?!br(t,n,!0):!1;case"$not":return!Ri(n,t,r,!1,i);case"$size":return Array.isArray(t)?Ri(n,t.length,r,!1,i):!1;case"$elemMatch":return jA(t,n,r,i);case"$all":return Array.isArray(n)?Wl(t,n,r,!1,i):!1;case"$alli":return Array.isArray(n)?Wl(t,n,r,!0,i):!1;case"$regex":try{return Jl(n).test(t)}catch{return!1}case"$regexi":try{return Jl(n,!0).test(t)}catch{return!1}case"$type":return kA(t)===n;default:return!1}}function Yl(e,t,n,r){if(!t.length)return!0;for(let i of t)if(Qt(e,i,n,r))return!0;return!1}function NA(e,t,n,r){for(let i of t)if(!Qt(e,i,n,r))return!1;return!0}function Ns(e){return Fl(e),{context:e,stack:{evaluatedFeatures:new Set}}}function Ds(e){return{...e.attributes,...e.attributeOverrides}}function Hn(e,t,n){let r=t||"id",i="",a=Ds(e);return a[r]&&(i=a[r]),!i&&n&&(a[n]&&(i=a[n]),i&&(r=n)),{hashAttribute:r,hashValue:i}}function He(e,t,n){e.context.log?.(t,n)}function $o(e,t){return t=t||0,`${e}__${t}`}function Fs(e,t){return`${e}||${t}`}function DA(e,t,n){let r=e.stickyBucketAssignmentDocs;if(!r)return{};let{hashAttribute:i,hashValue:a}=Hn(e,t),o=Fs(i,Ei(a)),{hashAttribute:s,hashValue:c}=Hn(e,n),u=c?Fs(s,Ei(c)):null,l={};return u&&r[u]&&Object.assign(l,r[u].assignments||{}),r[o]&&Object.assign(l,r[o].assignments||{}),l}function nd({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=$o(t,n),c=DA(e,r,i);if(a>0)for(let m=0;m<a;m++){let S=$o(t,m);if(c[S]!==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 rd(e,t,n,r){let i=Fs(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 id(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Go(e,t){let n=Ns(t),r=ad(e,null,n);return t.onExperimentEval?.(e,r),r}function Dn(e,t){return qs(e,Ns(t))}function FA(e){return e.forcedVariations||{}}function od(e,t,n){let{context:r}=e;if(r.trackedExperiments){let i=ud(t,n);if(r.trackedExperiments.has(i))return;r.trackedExperiments.add(i)}Ms(()=>r.onExperimentViewed?.(t,n))}function MA(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}Ms(()=>r.onFeatureUsage?.(t,n))}function Ms(e){try{let t=e();t&&typeof t.catch=="function"&&t.catch(()=>{})}catch{}}function qs(e,t){let{context:n}=t;if(t.stack.evaluatedFeatures.has(e))return He(t,`evalFeature: circular dependency detected: ${t.stack.id} -> ${e}`,{from:t.stack.id,to:e}),Qn(t,e,null,"cyclicPrerequisite");t.stack.evaluatedFeatures.add(e),t.stack.id=e;let r=n.features?.[e];for(let a of r?.rules??[])Cs(a);let i=n.forcedFeatureValues;if(i&&i.has(e))return He(t,"Global override",{id:e,value:i.get(e)}),Qn(t,e,i.get(e),"override");if(!r)return He(t,"Unknown feature",{id:e}),Qn(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=qs(u.id,t);if(l.source==="cyclicPrerequisite")return Qn(t,e,null,"cyclicPrerequisite");let m={value:l.value};if(!Qt(m,u.condition||{},n.savedGroups||{})){if(u.gate)return He(t,"Feature blocked by prerequisite",{id:e,rule:o}),Qn(t,e,null,"prerequisite");He(t,"Skip rule because prerequisite evaluation fails",{id:e,rule:o});continue e}}if(o.filters&&cd(o.filters,t)){He(t,"Skip rule because of filters",{id:e,rule:o});continue}if("force"in o){if(o.condition&&!sd(o.condition,t)){He(t,"Skip rule because of condition ff",{id:e,rule:o});continue}if(!qA(t,o.seed||e,o.hashAttribute,n.saveStickyBucketAssignmentDoc&&!o.disableStickyBucketing?o.fallbackAttribute:void 0,o.range,o.coverage,o.hashVersion)){He(t,"Skip rule because user not included in rollout",{id:e,rule:o});continue}return He(t,"Force value from rule",{id:e,rule:o}),o.tracks&&o.tracks.forEach(u=>{od(t,u.experiment,u.result)}),Qn(t,e,o.force,"force",o.id)}if(!o.variations){He(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=ad(s,e,t);if(n.onExperimentEval?.(s,c),c.inExperiment&&!c.passthrough)return Qn(t,e,c.value,"experiment",o.id,s,c)}}return He(t,"Use default value",{id:e,value:r.defaultValue}),Qn(t,e,r.defaultValue===void 0?null:r.defaultValue,"defaultValue")}function ad(e,t,n){let{context:r}=n;Cs(e);let i=e.key,a=e.variations.length;if(a<2)return He(n,"Invalid experiment",{id:i}),_t(n,e,-1,!1,t);if(r.enabled===!1)return He(n,"Context disabled",{id:i}),_t(n,e,-1,!1,t);if(e.urlPatterns&&!Dl(r.url||"",e.urlPatterns))return He(n,"Skip because of url targeting",{id:i}),_t(n,e,-1,!1,t);let o=Tl(i,r.url||"",a);if(o!==null)return He(n,"Force via querystring",{id:i,variation:o}),_t(n,e,o,!1,t);let c=FA(r)[i];if(c!==void 0)return He(n,"Force via dev tools",{id:i,variation:c}),_t(n,e,c,!1,t);if(e.active===!1)return He(n,"Skip because inactive",{id:i}),_t(n,e,-1,!1,t);let{hashAttribute:u,hashValue:l}=Hn(r,e.hashAttribute,r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0);if(!l)return He(n,"Skip because missing hashAttribute",{id:i}),_t(n,e,-1,!1,t);let m=-1,S=!1,y=!1;if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{variation:f,versionIsBlocked:I}=nd(id({context:r,expKey:e.key,expBucketVersion:e.bucketVersion,expHashAttribute:e.hashAttribute,expFallbackAttribute:e.fallbackAttribute,expMinBucketVersion:e.minBucketVersion,expMeta:e.meta}));S=f>=0,m=f,y=!!I}if(!S){if(e.filters&&cd(e.filters,n))return He(n,"Skip because of filters",{id:i}),_t(n,e,-1,!1,t);if(e.include&&!Nl(e.include))return He(n,"Skip because of include function",{id:i}),_t(n,e,-1,!1,t);if(e.condition&&!sd(e.condition,n))return He(n,"Skip because of condition exp",{id:i}),_t(n,e,-1,!1,t);if(e.parentConditions){let f=new Set(n.stack.evaluatedFeatures);for(let I of e.parentConditions){n.stack.evaluatedFeatures=new Set(f);let A=qs(I.id,n);if(A.source==="cyclicPrerequisite")return _t(n,e,-1,!1,t);let P={value:A.value};if(!Qt(P,I.condition||{},r.savedGroups||{}))return He(n,"Skip because prerequisite evaluation fails",{id:i}),_t(n,e,-1,!1,t)}}}let p=Fo(e.seed||i,l,e.hashVersion??2);if(p===null)return He(n,"Skip because of invalid hash version",{id:i}),_t(n,e,-1,!1,t);if(!S){let f=e.ranges||jl(a,e.coverage===void 0?1:e.coverage,e.weights);m=kl(p,f)}if(y)return He(n,"Skip because sticky bucket version is blocked",{id:i}),_t(n,e,-1,!1,t,void 0,!0);if(m<0)return He(n,"Skip because of coverage",{id:i}),_t(n,e,-1,!1,t);if("force"in e)return He(n,"Force variation",{id:i,variation:e.force}),_t(n,e,e.force===void 0?-1:e.force,!1,t);if(r.qaMode)return He(n,"Skip because QA mode",{id:i}),_t(n,e,-1,!1,t);let g=_t(n,e,m,!0,t,p,S);if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{changed:f,key:I,doc:A}=rd(r,u,Ei(l),{[$o(e.key,e.bucketVersion)]:g.key});if(f){r.stickyBucketAssignmentDocs=r.stickyBucketAssignmentDocs||{},r.stickyBucketAssignmentDocs[I]=A;let P=r.saveStickyBucketAssignmentDoc;Ms(()=>P(A))}}return od(n,e,g),He(n,"In experiment",{id:i,variation:g.variationId}),g}function Qn(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"&&MA(e,t,s),s}function sd(e,t){return Qt(Ds(t.context),e,t.context.savedGroups||{})}function cd(e,t){return e.some(n=>{let{hashValue:r}=Hn(t.context,n.attribute);if(!r)return!0;let i=Fo(n.seed,r,n.hashVersion||2);return i===null?!0:!n.ranges.some(a=>Mo(i,a))})}function qA(e,t,n,r,i,a,o){if(!i&&a===void 0)return!0;if(!i&&a===0)return!1;let{hashValue:s}=Hn(e.context,n,r);if(!s)return!1;let c=Fo(t,s,o??2);return c===null?!1:i?Mo(c,i):a!==void 0?c<=a:!0}function _t(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}=Hn(e.context,t.hashAttribute,e.context.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0),l=t.meta?.[n]??{},m=t.variations[0];for(let[y,p]of t.variations.entries())if(y===n){m=p;break}let S={key:l.key||""+n,featureId:i,inExperiment:s,hashUsed:r,variationId:n,value:m,hashAttribute:c,hashValue:u,stickyBucketUsed:!!o};return l.name&&(S.name=l.name),a!==void 0&&(S.bucket=a),l.passthrough&&(S.passthrough=l.passthrough),S}function ud(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 xe=j.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"})}),St=j.record(j.string().min(1).max(128),xe).superRefine((e,t)=>{(!xe.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"})}),fA=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"]),Wt=St.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"&&!j.strictObject({id:j.uuid(),attributeKey:j.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("$")&&!fA.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)}),gA=j.discriminatedUnion("type",[j.strictObject({type:j.literal("condition"),condition:Wt}),j.strictObject({type:j.literal("list"),attributeKey:j.string().min(1).max(128),values:j.array(j.union([j.string(),j.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 zn(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 hA=j.record(j.uuid(),gA).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"&&zn(o.condition).forEach(i),n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),Ws=j.tuple([j.number().min(0).max(1),j.number().min(0).max(1)]).refine(([e,t])=>e<=t),Td=j.strictObject({attribute:j.string().optional(),seed:j.string().min(1),hashVersion:j.literal(2),ranges:j.array(Ws).min(1).max(100)}),yA=j.strictObject({id:j.string().min(1).max(128),condition:Wt,gate:j.boolean().optional()}),Zs={id:j.string().max(128).optional(),condition:Wt.optional(),parentConditions:j.array(yA).max(50).optional(),filters:j.array(Td).max(20).optional()},AA=j.union([j.strictObject({...Zs}),j.strictObject({...Zs,force:xe,coverage:j.number().min(0).max(1).optional(),range:Ws.optional(),seed:j.string().min(1).optional(),hashAttribute:j.string().optional(),hashVersion:j.literal(2).optional()}),j.strictObject({...Zs,type:j.literal("experiment-ref"),experimentId:j.uuid(),values:j.record(j.string().min(1),xe),meta:j.record(j.string().min(1),j.strictObject({passthrough:j.boolean()})).optional()})]),bA=j.strictObject({defaultValue:xe,rules:j.array(AA).max(100)}),iO=j.record(j.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),bA).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)}),xA=j.strictObject({name:j.string().max(80),reason:j.string().max(500),dateStarted:j.iso.datetime({offset:!0}),dateEnded:j.iso.datetime({offset:!0}).nullable(),coverage:j.number().min(0).max(1),variationWeights:j.array(j.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:Wt,savedGroups:j.array(j.strictObject({match:j.enum(["any","all","none"]),ids:j.array(j.uuid()).min(1)})).max(50),namespace:j.strictObject({id:j.uuid(),ranges:j.array(Ws).min(1)}).nullable(),seed:j.string().min(1).max(128)}),SA=j.strictObject({key:j.string().min(1).max(128),name:j.string().min(1).max(80),hypothesis:j.string().max(2e3),status:j.enum(["draft","running","stopped"]),hashAttribute:j.string().min(1).max(128),fallbackAttribute:j.string().max(128).nullable(),hashVersion:j.literal(2),disableStickyBucketing:j.boolean(),bucketVersion:j.number().int().min(0).max(1e3),minBucketVersion:j.number().int().min(0).max(1e3),variations:j.array(j.strictObject({id:j.string().min(1),key:j.string().min(1),name:j.string().max(80),description:j.string().max(500)})).min(2).max(20),phases:j.array(xA).min(1).max(100),releasedVariationId:j.string().nullable(),excludeFromPayload:j.boolean(),statusSchedule:j.strictObject({startAt:j.iso.datetime({offset:!0}).nullable(),stopAt:j.iso.datetime({offset:!0}).nullable(),stopAfter:j.strictObject({value:j.number().int().positive().max(36500),unit:j.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 IA=SA.safeExtend({filters:j.array(Td).optional()}),vA=j.strictObject({experiments:j.record(j.uuid(),IA),savedGroups:hA}),Ui=j.strictObject({attributeName:j.string(),attributeValue:j.string(),assignments:j.record(j.string(),j.string())}),oO=j.strictObject({snapshot:vA,attributes:St,results:St,stickyBucketAssignmentDocs:j.record(j.string(),Ui)}),aO=j.strictObject({variantKey:j.string().nullable(),bucketVersion:j.number().int().min(0),source:j.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:j.number().min(0).max(1).optional(),stickyBucketUsed:j.boolean().optional(),hashUsed:j.boolean().optional()});function nr(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 wA=jt.enum(["active","inactive"]),OA=jt.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},St),_A=jt.strictObject({id:jt.string().trim().min(1).max(255),name:jt.string().trim().min(1).max(255),status:wA,metadata:OA}),pO=_A.extend({internal_id:jt.uuid(),project_id:jt.uuid(),environment_id:jt.uuid(),created_at:jt.iso.datetime({offset:!0}),updated_at:jt.iso.datetime({offset:!0})}),Dd=jt.union([jt.strictObject({id:jt.string().trim().min(1).max(255)}),jt.strictObject({internalId:jt.uuid()})]),mO=jt.enum(["customer","merchandise","context"]),fO=jt.enum(["system","stored","request"]),gO=jt.enum(["customer","merchandise","mixed"]),Nd=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function Ys(e,t={},n=new Set){if(nr(e).some(Nd))return!0;for(let r of zn(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&Nd(i.attributeKey)||i?.type==="condition"&&Ys(i.condition,t,n))return!0}return!1}import{z as CA}from"zod";var PA=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,In=CA.string().max(16).regex(PA,"\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 vO=ne.enum(["draft","active","paused","archived"]),rr=ne.discriminatedUnion("type",[ne.object({type:ne.literal("percent"),percentOff:ne.number().min(1).max(100).multipleOf(.01)}).strict(),ne.object({type:ne.literal("amount"),amountOffCents:ne.number().int().min(1).max(1e8),currency:be}).strict()]),an=ne.discriminatedUnion("type",[ne.object({type:ne.literal("once")}).strict(),ne.object({type:ne.literal("repeating"),months:ne.number().int().min(1).max(36)}).strict(),ne.object({type:ne.literal("forever")}).strict()]),Fd=[ne.object({type:ne.literal("all")}).strict(),ne.object({type:ne.literal("plans"),planIds:ne.array(ne.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],EA=ne.discriminatedUnion("type",[...Fd,ne.strictObject({type:ne.literal("merchandise"),scope:ne.discriminatedUnion("type",[ne.strictObject({type:ne.literal("all")}),ne.strictObject({type:ne.literal("selected"),merchandiseIds:ne.array(ne.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),ne.strictObject({type:ne.literal("condition"),condition:Wt})])})]),Xs=ne.discriminatedUnion("type",[...Fd,ne.strictObject({type:ne.literal("merchandise"),scope:ne.strictObject({type:ne.enum(["all","selected","condition"])})})]),RA=ne.strictObject({firstPurchaseOnly:ne.boolean(),condition:Wt}),wO=ne.object({name:ne.string().trim().min(1).max(80),description:ne.string().max(500),discount:rr,duration:an,appliesTo:EA,eligibility:RA,selfClaimEnabled:ne.boolean().default(!1),startsAt:ne.iso.datetime().nullable(),endsAt:ne.iso.datetime().nullable(),totalLimit:ne.number().int().min(1).max(1e6).nullable(),perCustomerLimit:ne.number().int().min(1).max(10),grantWindowHours:ne.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=>!Ys(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"]}),OO=ne.object({code:ne.string().trim().transform(e=>e.toUpperCase()).pipe(ne.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:ne.number().int().min(1).max(1e6).nullable(),expiresAt:ne.iso.datetime().nullable(),firstPurchaseOnly:ne.boolean(),minimumAmountCents:ne.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:be.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var Li=ne.object({id:ne.uuid(),couponId:ne.uuid(),status:ne.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:ne.iso.datetime(),expiresAt:ne.iso.datetime(),coupon:ne.object({name:ne.string(),discount:rr,duration:an,appliesTo:Xs}).strict()}).strict(),Md=ne.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var Ld=h.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),ec=h.string().regex(/^(0|[1-9]\d{0,14})$/),ri=h.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),kA=h.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),zi=kA,$n=Ae.refine(e=>/[1-9]/.test(e)),Ut=h.iso.datetime({offset:!0}),ta=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"))},jA=h.array(h.object({upTo:$n.nullable(),unitAmountMinor:Ld,flatAmountMinor:h.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&&ta(t.upTo)>ta(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),TA=h.discriminatedUnion("kind",[h.object({kind:h.literal("flat"),units:$n,unitAmountMinor:Ld}).strict(),h.object({kind:h.enum(["graduated","volume"]),units:$n,tiers:jA}).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"),NA=h.strictObject({interval:h.enum(["month","year"]),count:h.number().int().min(1).max(12),anchor:h.enum(["membership","calendar"])}),$i=h.object({currency:be,pricing:TA,billingCycle:NA.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var Vd={requestId:h.uuid(),productVersionId:h.uuid(),internal_feature_id:h.uuid(),currency:be},zd=h.strictObject({interval:h.enum(["hour","day","week","month"]),intervalCount:h.number().int().min(1).max(12),limit:h.number().int().min(1).max(1e6)}),$d=h.discriminatedUnion("kind",[h.object({...Vd,kind:h.literal("auto_topup"),threshold:Lo,quantity:$n.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:zd.optional()}).strict(),h.object({...Vd,kind:h.literal("postpaid"),maxAmountMinorPerPeriod:zi,maxOutstandingMinor:zi}).strict()]),qd={productVersionId:h.uuid(),internal_feature_id:h.uuid(),currency:be},Kd=h.discriminatedUnion("kind",[h.object({...qd,kind:h.literal("auto_topup"),threshold:Lo,quantity:$n.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:zd.optional(),purchaseAmountMinor:zi,purchaseUnits:$n}).strict(),h.object({...qd,kind:h.literal("postpaid"),maxAmountMinorPerPeriod:zi,maxOutstandingMinor:zi,cashPrice:$i}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),na=h.object({id:h.uuid(),terms:Kd,status:h.enum(["prepared","active","revoked","blocked"]),createdAt:Ut,acceptedAt:Ut.nullable(),effectiveAt:Ut.nullable(),revokedAt:Ut.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"),Gd=h.object({authorizationId:h.uuid(),terms:Kd,setupUrl:h.url().nullable()}).strict(),Hd=h.object({authorizationId:h.uuid(),accepted:h.literal(!0)}).strict(),Qd=h.object({authorizationId:h.uuid(),requestId:h.uuid()}).strict(),Jd=h.object({internal_feature_id:h.uuid(),entityId:h.uuid().nullable(),interval:h.enum(["day","week","month","year"]),anchor:h.enum(["billing_cycle","utc"]).optional(),basis:h.enum(["usage","credits"]),filter:xt.optional(),limit:Ae.nullable(),thresholds:h.array(h.number().positive().max(1)).max(8),includedThresholds:h.array(h.number().positive().max(1)).max(8).optional(),absoluteThresholds:h.array($n).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&&ta(t)>ta(i)}),"Notification thresholds must increase"),DA=Jd.safeExtend({requestId:h.uuid()}),Bd={control:h.literal("overage"),requestId:h.uuid(),internal_feature_id:h.uuid(),entityId:h.uuid().nullable()},FA=h.discriminatedUnion("action",[h.strictObject({...Bd,action:h.literal("set"),allowed:h.boolean().nullable(),overageLimit:Ae.nullable(),skipOverageBilling:h.boolean()}),h.strictObject({...Bd,action:h.literal("remove")})]),Zd=h.union([DA,FA]),MA=h.strictObject({internal_feature_id:h.uuid(),entityId:h.uuid().nullable(),allowed:h.boolean().nullable(),overageLimit:Ae.nullable(),skipOverageBilling:h.boolean(),interval:h.enum(["day","week","month","year"]),startsAt:Ut,endsAt:Ut,used:h.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:h.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:h.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),VA=h.object({internal_feature_id:h.uuid(),entityId:h.uuid().nullable(),interval:h.enum(["day","week","month","year"]),anchor:h.enum(["billing_cycle","utc"]).optional(),basis:h.enum(["usage","credits"]),filter:xt.optional(),startsAt:Ut,endsAt:Ut,used:Zt,reserved:Zt,limit:Ae.nullable(),thresholds:h.array(h.number().positive().max(1)).max(8),notifiedThresholds:h.array(h.number().positive().max(1)).max(1024),includedThresholds:h.array(h.number().positive().max(1)).max(8).optional(),includedAllowance:h.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:h.array(h.number().positive().max(1)).max(1024).optional(),absoluteThresholds:h.array($n).max(8).optional(),notifiedAbsoluteThresholds:h.array($n).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||Ae.safeParse(e.used).success&&Ae.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),qA=h.object({authorizationId:h.uuid(),status:h.enum(["idle","pending","blocked"]),taskId:h.uuid().nullable(),invoiceId:h.uuid().nullable(),hostedInvoiceUrl:h.url().nullable(),purchaseCount:h.number().int().nonnegative(),purchaseWindowEndsAt:Ut.nullable(),attemptCount:h.number().int().nonnegative(),failedAttemptCount:h.number().int().nonnegative(),suspendedAt:Ut.nullable(),nextAttemptAt:Ut.nullable(),failureReason:h.string().min(1).max(240).nullable()}).strict(),Wd=h.object({internal_feature_id:h.uuid().optional(),entityId:h.uuid().optional()}).strict(),tc=h.object({authorizations:h.array(na).max(100),limits:h.array(Jd).max(100),overages:h.array(MA).max(100).optional(),windows:h.array(VA).max(200),autoTopups:h.array(qA).max(100),limited:h.boolean()}).strict(),BA=h.object({id:h.uuid(),internal_feature_id:h.uuid(),productVersionId:h.uuid(),authorizationId:h.uuid(),entityId:h.uuid().nullable(),units:Ae,amountMinor:ri,cashPrice:$i}).strict(),Ki=h.object({id:h.uuid(),sourceKind:h.enum(["product","usage","manual"]),providerInvoiceId:h.string().min(1).max(240).nullable(),status:h.enum(["accruing","open","pending","paid","failed","void"]),currency:be,startsAt:Ut.nullable(),endsAt:Ut.nullable(),amountMinor:h.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:h.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:ec,paidAmountMinor:ec,refundedAmountMinor:ec,createdAt:Ut,hostedInvoiceUrl:h.url().nullable(),adjustment:h.object({originalInvoiceId:h.uuid(),amountMinor:h.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:Ut.nullable(),reason:h.string().min(1).max(500).optional()}).strict().nullable(),lines:h.array(BA).max(100),linesLimited:h.boolean()}).strict(),Yd=h.object({invoiceId:h.uuid(),accepted:h.literal(!0)}).strict(),Xd=h.strictObject({requestId:h.uuid(),originalInvoiceId:h.uuid(),amountMinor:h.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:h.string().trim().min(1).max(500)}),ep=h.object({after:h.uuid().nullable(),limit:h.number().int().min(1).max(100)}).strict(),tp=h.object({rows:h.array(Ki).max(100),nextCursor:h.uuid().nullable()}).strict(),Ud=h.strictObject({id:h.string(),coupon:h.string(),start:h.number().nonnegative(),end:h.number().nullable()}),UA=h.strictObject({subscriptionId:h.string(),customerId:h.string(),accountId:h.string(),sourceItems:h.array(h.strictObject({id:h.string(),price_id:h.string(),quantity:h.number().int(),discounts:h.array(Ud).optional()})).max(100),items:h.array(h.strictObject({id:h.string(),price:h.string(),quantity:h.number().int(),discounts:h.array(h.strictObject({coupon:h.string().optional(),terms:h.strictObject({id:h.string(),name:h.string().optional(),percent_off:h.number().optional(),amount_off:h.number().optional(),currency:h.string().optional(),duration:h.enum(["once","forever","repeating"]),duration_in_months:h.number().optional()}).optional(),discount:h.string().optional(),receipt:Ud.optional()})).max(20)})).max(100)}),np=h.strictObject({membershipId:h.uuid(),requestId:h.uuid(),grantIds:h.array(h.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),rp=h.strictObject({membershipId:h.uuid(),operationId:h.uuid(),status:h.enum(["pending","effective"]),execution:UA.nullable(),grants:h.array(h.strictObject({id:h.uuid(),couponId:h.uuid(),name:h.string(),discount:rr,duration:an,startedAt:Ut.nullable()})).max(20)});import{z as Gi}from"zod";var ip=Gi.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),op=Gi.number().int().min(1).max(1e3),ra=Gi.object({cap:Ae.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:Gi.number().positive().max(1e4).nullable(),cycles:Gi.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 ir}from"zod";var ap=ir.strictObject({itemKey:ir.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:ir.uuid(),includedAmount:ir.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:ir.number().int().min(0).max(1e4),terms:$o,pricing:Vi.optional(),unitAmountMinor:ir.number().int().min(0).max(1e8),productId:ir.string().min(1).max(255).nullable(),priceId:ir.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{Yl(e.includedAmount,e.terms.units,e.quantity),zo({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 re}from"zod";var Pr=Ae.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Hi=re.string().min(1).max(120),ia=re.enum(["cap","overflow"]),sn=(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"))},Qi=e=>{try{return e()}catch{return!1}},Ji=re.discriminatedUnion("operation",[re.object({operation:re.literal("quote"),overageBehavior:ia.optional(),internal_feature_id:re.uuid(),entityId:re.uuid().optional(),quantity:Pr,properties:xt}).strict(),re.object({operation:re.literal("consume"),overageBehavior:ia.optional(),occurredAt:re.iso.datetime({offset:!0}).optional(),internal_feature_id:re.uuid(),entityId:re.uuid().optional(),quantity:Ae,properties:xt,idempotencyKey:Hi}).strict(),re.object({operation:re.literal("reserve"),occurredAt:re.iso.datetime({offset:!0}).optional(),internal_feature_id:re.uuid(),entityId:re.uuid().optional(),quantity:Pr,properties:xt,idempotencyKey:Hi,expiresInSeconds:re.number().int().min(1).max(86400)}).strict(),re.object({operation:re.literal("confirm"),operationId:re.uuid(),quantity:Pr,properties:xt.optional(),idempotencyKey:Hi}).strict(),re.object({operation:re.literal("refund"),operationId:re.uuid(),quantity:Pr,idempotencyKey:Hi}).strict(),re.object({operation:re.literal("release"),operationId:re.uuid(),idempotencyKey:Hi}).strict()]),nc=re.object({internal_credit_feature_id:re.uuid().nullable(),internal_metered_feature_id:re.uuid(),dimension:re.string().min(1).max(64),counterKey:re.string().min(1).max(240),cycleStart:re.iso.datetime({offset:!0}),unitCost:Ae,units:Pr,amount:Zt,tier:re.number().int().min(1).max(12).nullable()}).strict(),Er=re.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function sp(e,t){let n=e.reduce((r,i)=>r+sn(i.units,12),0n)-sn(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var cp=re.discriminatedUnion("funding",[re.strictObject({funding:re.literal("balance"),sourceId:re.uuid(),rolloverId:re.uuid().nullable(),units:Er.refine(e=>/[1-9]/.test(e)),amount:Zt}),re.strictObject({funding:re.literal("unbilled"),units:Er.refine(e=>/[1-9]/.test(e))}),re.object({funding:re.literal("prepaid"),sourceId:re.uuid(),units:Pr,amount:Zt,pricing:re.array(nc).min(1).max(12)}).strict().refine(e=>Qi(()=>e.pricing.reduce((t,n)=>t+sn(n.units,6),0n)===sn(e.units,6)&&e.pricing.reduce((t,n)=>t+sn(n.amount,12),0n)===sn(e.amount,12)&&e.pricing.every(t=>sn(t.unitCost,6)*sn(t.units,6)===sn(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),re.object({funding:re.literal("postpaid"),invoiceLineId:re.uuid().nullable(),units:Pr,authorizationId:re.uuid()}).strict()]),oa=re.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),up=re.object({allowed:re.boolean(),internal_feature_id:re.uuid(),quantity:Ae,requestedQuantity:Ae.optional(),overageBehavior:ia.optional(),reason:oa.nullable(),allocations:re.array(cp).max(500)}).strict().refine(e=>Qi(()=>e.allowed?e.reason===null&&sp(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>Qi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&sn(e.requestedQuantity,6)>=sn(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Zi=re.object({id:re.uuid(),internal_feature_id:re.uuid(),kind:re.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:re.uuid().nullable(),quantity:Ae,requestedQuantity:Ae.optional(),overageBehavior:ia.optional(),accepted:re.boolean(),reason:re.enum([...oa.options,"expired"]).nullable(),createdAt:re.iso.datetime({offset:!0}),reservationStatus:re.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:re.iso.datetime({offset:!0}).nullable(),allocations:re.array(cp).max(500)}).strict().refine(e=>Qi(()=>e.accepted?e.reason===null&&sp(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>Qi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&sn(e.requestedQuantity,6)>=sn(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 Te}from"zod";var Rr=Te.iso.datetime({offset:!0}),lp=Ae.refine(e=>/[1-9]/.test(e)),dp=Te.strictObject({interval:ip.exclude(["lifetime"]),count:op}),LA=Te.strictObject({action:Te.literal("create"),requestId:Te.uuid(),internal_feature_id:Te.uuid(),entityId:Te.uuid().nullable(),amount:lp.nullable(),expiresAt:Rr.nullable(),reset:dp.nullable(),rollover:ra.nullable(),nextResetAt:Rr.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"),pp=Te.discriminatedUnion("action",[LA,Te.strictObject({action:Te.literal("update"),requestId:Te.uuid(),grantId:Te.uuid(),revision:Te.number().int().nonnegative(),amount:lp.nullable(),expiresAt:Rr.nullable(),rollover:ra.nullable(),nextResetAt:Rr.nullable()}),Te.strictObject({action:Te.enum(["add","subtract","set_remaining"]),requestId:Te.uuid(),grantId:Te.uuid(),revision:Te.number().int().nonnegative(),amount:Ae}),Te.strictObject({action:Te.literal("revoke"),requestId:Te.uuid(),grantId:Te.uuid(),revision:Te.number().int().nonnegative()})]),rc=Te.strictObject({id:Te.uuid(),internal_feature_id:Te.uuid(),entityId:Te.uuid().nullable(),amount:Ae.nullable(),reset:dp.nullable(),rollover:ra.nullable(),nextResetAt:Rr.nullable(),startsAt:Rr,expiresAt:Rr.nullable(),revision:Te.number().int().nonnegative(),revoked:Te.boolean(),available:Zt,held:Zt,spent:Zt}),mp=Te.strictObject({customerId:Te.uuid(),after:Te.uuid().nullable(),limit:Te.number().int().min(1).max(100)}),fp=Te.strictObject({rows:Te.array(rc).max(100),nextCursor:Te.uuid().nullable()});import{z as oe}from"zod";var jn=oe.iso.datetime({offset:!0}),gp=oe.strictObject({invoiceId:oe.uuid(),after:oe.string().min(1).max(180).nullable(),limit:oe.number().int().min(1).max(100)}),zA=oe.strictObject({kind:oe.literal("product"),key:oe.string(),productVersionId:oe.uuid(),productName:oe.string(),itemKey:oe.string(),entityId:oe.uuid().nullable(),quantity:oe.number().positive(),subtotalMinor:oe.string().regex(/^-?\d+$/),discountMinor:oe.string().regex(/^\d+$/),taxMinor:oe.string().regex(/^-?\d+$/).nullable(),totalMinor:oe.string().regex(/^-?\d+$/),startsAt:jn.nullable(),endsAt:jn.nullable(),providerLineId:oe.string().nullable(),providerItemId:oe.string()}),hp=oe.strictObject({invoice:Ki,items:oe.array(oe.discriminatedUnion("kind",[zA,oe.strictObject({kind:oe.literal("invoice_credit"),key:oe.string(),internal_feature_id:oe.uuid(),internal_credit_feature_id:oe.uuid(),name:oe.string(),units:Ae,reserved:Ae,amountMinor:ri,grossAmountMinor:ri,creditsAppliedMinor:ri,properties:xt,cashPrice:$i,providerItemId:oe.string().nullable(),creditProviderItemId:oe.string().nullable()}),oe.strictObject({kind:oe.literal("usage"),key:oe.string(),internal_feature_id:oe.uuid(),name:oe.string(),units:Ae,reserved:Ae,amountMinor:ri,cashPrice:$i})])).max(100),nextCursor:oe.string().min(1).max(180).nullable()}),$A=oe.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),ic=oe.strictObject({from:jn,to:jn,entityId:oe.uuid().optional(),snapshotAt:jn.nullable(),after:oe.strictObject({at:jn,id:oe.uuid(),position:oe.number().int().nonnegative()}).nullable(),limit:oe.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"),yp=oe.strictObject({customerId:oe.uuid(),entityId:oe.uuid().nullable(),from:jn,to:jn,snapshotAt:jn,totals:oe.array(oe.strictObject({internal_credit_feature_id:oe.uuid(),name:oe.string(),consumed:Zt,refunded:Zt,net:$A})).max(1e3),rows:oe.array(oe.strictObject({operationId:oe.uuid(),position:oe.number().int().nonnegative(),kind:oe.enum(["consume","confirm","refund"]),originalId:oe.uuid().nullable(),occurredAt:jn,internal_feature_id:oe.uuid(),entitlementName:oe.string(),sourceId:oe.uuid(),internal_credit_feature_id:oe.uuid(),creditName:oe.string(),units:Er,amount:Zt,pricing:oe.array(nc).max(12),properties:xt})).max(100),nextCursor:ic.shape.after});import{z as T}from"zod";import{z as vn}from"zod";var KA=vn.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),GA=vn.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),aa=vn.strictObject({internal_feature_id:vn.uuid(),entityId:vn.uuid().nullable()}),Ap=aa.extend({quantity:Ae,expectedRevision:vn.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:vn.string().min(1).max(120),properties:xt.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),Wi=aa.extend({operationId:vn.uuid().nullable(),usage:Ae,capacity:KA.nullable(),remaining:GA.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 Lt=T.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),wn=T.iso.datetime({offset:!0}),HA=T.enum(["access","metered","credit"]),Yi={internal_feature_id:T.uuid(),key:_r,name:T.string().min(1).max(120),kind:HA},bp=T.object({customerId:T.uuid(),snapshotAt:wn,memberships:T.array(T.object({id:T.uuid(),productId:T.string().min(1).max(255),productVersionId:T.uuid(),billingProductVersionId:T.uuid(),version:T.number().int().positive(),key:T.string().min(1).max(64),name:T.string().min(1).max(120),groupId:T.string().max(255).nullable(),membershipType:T.enum(["main","addon"]),status:T.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:T.boolean(),accessEnabled:T.boolean(),renewalChange:T.object({productVersionId:T.uuid(),name:T.string().min(1).max(120),version:T.number().int().positive(),effectiveAt:wn,benefitsAppliedAt:wn.nullable(),timing:T.enum(["immediate","renewal"]),changeKind:T.enum(["plan","seats","quantity"]),feature:T.strictObject({internal_feature_id:T.uuid(),name:T.string().min(1).max(80),fromQuantity:T.number().int().min(0).max(1e4),toQuantity:T.number().int().min(0).max(1e4)}).optional(),seat:T.object({key:T.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:T.number().int().min(0).max(1e4),toQuantity:T.number().int().min(0).max(1e4)}).strict().nullable(),status:T.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:T.object({phase:T.enum(["paid","trial"]),startsAt:wn,endsAt:wn.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:T.boolean(),balances:T.array(T.object({...Yi,usageType:T.enum(["consumable","non_consumable"]).nullable(),accessible:T.boolean(),unlimited:T.boolean(),available:Lt,held:Lt,debt:Lt,nextExpiresAt:wn.nullable(),usage:Wi.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:T.boolean()}).strict(),xp=T.enum(["source","usage","transaction","invoice","debt","settlement"]),sa=T.object({at:wn,id:T.uuid(),type:xp}).strict(),Sp=T.object({type:xp.nullable(),resourceKey:_r.optional(),kind:T.enum(["purchase","refund"]).optional(),topup:T.boolean().optional(),from:T.iso.date().nullable(),to:T.iso.date().nullable(),after:sa.nullable(),limit:T.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),ii={id:T.uuid(),occurredAt:wn},QA=T.discriminatedUnion("type",[T.strictObject({...ii,type:T.literal("invoice"),status:T.string().min(1).max(80),paid:Lt,refunded:Lt,currency:be,externalId:T.string().nullable()}),T.object({...ii,...Yi,type:T.literal("source"),reason:T.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:Lt,unlimited:T.boolean(),status:T.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:wn,expiresAt:wn.nullable(),orderId:T.uuid().nullable(),parentSourceId:T.uuid().nullable()}).strict(),T.object({...ii,type:T.literal("usage"),internal_feature_id:T.uuid(),name:T.string().min(1).max(120),kind:T.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:T.uuid().nullable(),quantity:Ae,accepted:T.boolean(),reason:T.enum([...oa.options,"expired"]).nullable(),properties:xt,reservationStatus:T.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:wn.nullable(),charges:T.array(T.discriminatedUnion("funding",[T.strictObject({funding:T.literal("balance"),sourceId:T.uuid(),rolloverId:T.uuid().nullable(),units:Er,amount:Lt}),T.strictObject({funding:T.literal("unbilled"),units:Er}),T.object({...Yi,funding:T.literal("prepaid"),amount:Lt}).strict(),T.object({funding:T.literal("postpaid"),invoiceId:T.uuid(),invoiceLineId:T.uuid(),authorizationId:T.uuid(),units:Ae,currency:be}).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"),T.object({...ii,type:T.literal("transaction"),purpose:T.enum(["product","invoice"]),productVersionId:T.uuid().nullable(),productName:T.string().min(1).max(120).nullable(),productVersion:T.number().int().positive().nullable(),invoiceId:T.uuid().nullable(),orderId:T.uuid(),originalId:T.uuid().nullable(),kind:T.enum(["purchase","refund"]),amountMinor:T.number().int().nonnegative().max(2e8).nullable(),currency:be.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"),T.object({...ii,...Yi,type:T.literal("debt"),sourceId:T.uuid(),transactionId:T.uuid(),amount:Lt}).strict(),T.object({...ii,...Yi,type:T.literal("settlement"),sourceId:T.uuid(),debtId:T.uuid(),kind:T.enum(["payment","usage_refund","payment_return"]),amount:Lt}).strict()]),Ip=T.object({customerId:T.uuid(),rows:T.array(QA).max(50),nextCursor:sa.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 me}from"zod";var wp=me.object({customerId:me.uuid()}).strict(),Op=me.discriminatedUnion("action",[me.object({customerId:me.uuid(),requestId:me.uuid(),action:me.literal("assign"),poolId:me.uuid(),memberCustomerId:me.uuid()}).strict(),me.strictObject({customerId:me.uuid(),requestId:me.uuid(),action:me.literal("assign_entity"),poolId:me.uuid(),entityId:me.uuid()}),me.object({customerId:me.uuid(),requestId:me.uuid(),action:me.literal("release"),poolId:me.uuid(),slotId:me.uuid()}).strict()]),Xi=me.number().int().nonnegative(),oc=me.iso.datetime({offset:!0}),ac=me.strictObject({internalId:me.uuid(),id:me.string(),name:me.string().nullable(),version:me.number().int().positive()}),vp=me.enum(["active","past_due"]),sc=me.strictObject({customerId:me.uuid(),licenses:me.array(me.strictObject({id:me.uuid(),linkId:me.uuid(),parent:me.strictObject({customerProductId:me.uuid(),status:vp,product:ac}),product:ac,planLicense:me.strictObject({id:me.uuid(),prepaidOnly:me.boolean(),isCustom:me.boolean()}).nullable(),granted:Xi,included:Xi,paidQuantity:Xi,usage:Xi,remaining:Xi,createdAt:oc}).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:me.array(me.strictObject({id:me.uuid(),linkId:me.uuid(),status:vp,product:ac,entity:me.strictObject({internalId:me.uuid(),id:me.string().nullable(),name:me.string().nullable()}).nullable(),beneficiary:me.strictObject({internalId:me.uuid(),id:me.string().nullable(),name:me.string().nullable()}).nullable(),startedAt:oc.nullable(),endedAt:oc.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:me.boolean()});import{z as pe}from"zod";var eo=pe.enum(["email","sms","voice","push"]),l1=pe.enum(["resend","twilio","fcm","apns"]);var d1=pe.string().regex(/^\+[1-9]\d{1,14}$/),JA=pe.enum(["email_recipient","sms_segment","voice_second","push_device"]);var ZA=pe.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),WA=pe.strictObject({subject:ZA,html:pe.string().min(1).max(131072).optional(),text:pe.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),YA=pe.strictObject({body:pe.string().min(1).max(1600).refine(e=>e.trim().length>0)}),XA=pe.strictObject({text:pe.string().trim().min(1).max(4e3),language:pe.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:pe.number().int().min(1).max(900)}),eb=pe.record(pe.string().min(1).max(64),pe.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"),tb=pe.strictObject({title:pe.string().trim().min(1).max(200),body:pe.string().trim().min(1).max(2e3),url:pe.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:eb.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),_p=pe.discriminatedUnion("channel",[pe.strictObject({channel:pe.literal("email"),content:WA}),pe.strictObject({channel:pe.literal("sms"),content:YA}),pe.strictObject({channel:pe.literal("voice"),content:XA}),pe.strictObject({channel:pe.literal("push"),content:tb})]),Cp=pe.strictObject({requestId:pe.uuid(),customerId:pe.uuid(),connectionId:pe.uuid().optional(),message:_p,expiresAt:pe.iso.datetime({offset:!0})}),nb=pe.array(pe.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),rb=pe.discriminatedUnion("kind",[pe.strictObject({kind:pe.literal("all")}),pe.strictObject({kind:pe.literal("customers"),customerIds:nb})]),p1=pe.strictObject({name:pe.string().trim().min(1).max(120),connectionId:pe.uuid().optional(),message:_p,audience:rb,frequencyLimit:pe.number().int().min(1).max(100)}),Pp=pe.strictObject({requestId:pe.uuid(),channel:eo,state:pe.enum(["allowed","denied"]),expectedRevision:pe.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),Ep=pe.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Rp=pe.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),m1=pe.strictObject({meter:JA,estimatedUnits:pe.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:pe.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});import{z as _e}from"zod";import{z as ie}from"zod";import{z as oi}from"zod";var to=oi.strictObject({internalFeatureId:oi.uuid(),name:oi.string().min(1).max(120),includedAmount:oi.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:oi.enum(["hour","day","week","month","year","lifetime"]),resetCount:oi.number().int().min(1).max(100),terms:$o});import{z as ot}from"zod";import{z as ib}from"zod";import{z as ai}from"zod";var kp=ai.enum(["stripe","apple","google","merchant"]),jp=ai.enum(["membership","credit_pack","lifetime"]),b1=ai.enum(["active","grace","suspended","inactive","revoked"]),x1=ai.strictObject({currency:ai.string().regex(/^[A-Z]{3}$/),micros:ai.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var si=ib.object({provider:kp,currency:be}).strict();var or=ot.strictObject({internal_feature_id:ot.uuid(),quantity:Ae.refine(e=>/[1-9]/.test(e)),properties:xt,entityId:ot.uuid().optional()}),Tp=ot.strictObject({requirement:or,commerce:si.optional(),paywallId:ot.uuid().optional()}),ob=ot.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),cc=ot.strictObject({productId:ot.string().min(1),productVersionId:ot.string().min(1),name:ot.string().min(1).max(120),action:ot.enum(["purchase","upgrade","addon","topup"]),membershipId:ot.string().min(1).nullable(),currency:be,amountMinor:ot.string().regex(/^(0|[1-9]\d{0,8})$/),interval:ot.enum(["free","week","month","year","one_time"]),intervalCount:ot.number().int().min(1).max(156)}),kr=ot.strictObject({internal_feature_id:ot.string().min(1),name:ot.string().min(1).max(120),kind:ot.enum(["access","metered","credit"]),quantity:Ae,allowed:ot.boolean(),reason:ob.nullable(),preview:ot.strictObject({scenario:ot.enum(["feature_flag","usage_limit"]),candidates:ot.array(cc).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"})}),R1=ot.strictObject({paywallId:ot.uuid(),requirement:or});var ua=ie.object({plan:ie.string().min(1).max(200).optional(),coupon:ie.uuid().optional(),promotionCode:ie.uuid().optional(),picker:ie.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),ca=ie.object({text:ie.string().optional(),label:ie.string().optional(),alt:ie.string().optional(),html:ie.string().max(32768).optional(),price:ie.object({current:ie.string(),original:ie.string().nullable(),period:ie.string()}).optional(),code:ie.string().optional(),countdownAt:ie.iso.datetime().optional(),planId:ie.string().min(1).max(200).optional(),planVersionId:ie.string().min(1).max(200).optional(),currency:be.optional(),couponId:ie.uuid().optional(),offerId:ie.uuid().optional(),unavailable:ie.boolean().optional(),unavailableReason:ie.string().optional(),missing:ie.array(ie.string()).optional()}).strict(),ci=ie.object({paywall:kr.optional(),nodes:ie.record(ie.string(),ie.object({base:ca,picker:ie.string().optional(),byPlan:ie.record(ie.string(),ca).optional()}).strict()),plans:ie.record(ie.string(),ie.object({id:ie.string().min(1).max(200),versionId:ie.string().min(1).max(200),available:ie.boolean(),name:ie.string(),price:ie.string(),period:ie.string(),currency:be.optional(),amountMinor:ie.number().int().nonnegative().optional(),interval:ie.enum(["free","week","month","year","one_time"]).optional(),intervalCount:ie.number().int().positive().optional(),prepaid:ie.array(to).max(100).optional()}).strict()),pickers:ie.record(ie.string(),ie.object({options:ie.array(ie.string().min(1).max(200)).max(20),selected:ie.string().min(1).max(200).nullable()}).strict()),quantities:ie.record(ie.string(),ie.strictObject({minimum:ie.number().int().nonnegative(),maximum:ie.number().int().nonnegative(),step:ie.number().int().positive(),value:ie.number().int().nonnegative(),label:ie.string(),available:ie.boolean()})).optional(),diagnostics:ie.array(ie.object({nodeId:ie.string(),message:ie.string()}).strict())}).strict();function Np(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}import{z as S}from"zod";function ab(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function Dp(e){let t={};function n(r){var i;if(ab(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 Kn}from"zod";var Fp=Kn.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),la=Kn.strictObject({tiers:Kn.array(Kn.strictObject({id:Fp,name:Kn.string().trim().min(1).max(80)})).min(1).max(8),assignments:Kn.array(Kn.strictObject({productVersionId:Kn.string().min(1).max(200),tierId:Fp,period:Kn.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 da(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}import{z as ce}from"zod";var sb=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],Mp=ce.enum(sb),Vp=ce.object({source:Mp,layout:ce.enum(["full","compact"]),resourceKey:_r.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"})}),Pt=ce.string().max(2e3),qp=ce.object({id:ce.string().max(100),label:Pt,detail:ce.array(Pt).max(12),value:Pt.optional(),status:Pt.optional(),facts:ce.array(ce.object({label:Pt,value:Pt}).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:Pt})).max(1).optional(),membershipActions:ce.array(ce.object({value:ce.string().max(100),label:Pt}).strict()).max(3).optional()}).strict(),cb=ce.object({key:_r,name:Pt,spendable:Pt,reserved:Pt,available:Pt,expiry:Pt.nullable(),sources:ce.array(qp).max(50),sourceCount:ce.number().int().nonnegative(),sourcePage:ce.number().int().positive(),hasNextSources:ce.boolean(),hasPreviousSources:ce.boolean()}).strict(),ub=ce.object({source:Mp,status:ce.enum(["idle","loading","ready","error"]),stale:ce.boolean(),preview:ce.boolean(),errorCode:ce.string().max(80).optional(),errorMessage:Pt.optional(),resources:ce.array(cb).max(500),rows:ce.array(qp).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:Pt,note:Pt,facts:ce.array(ce.object({label:Pt,value:Pt}).strict()).max(100)}).strict().optional(),membershipResult:Pt.optional()}).strict(),Bp=ce.object({nodes:ce.record(ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ub)}).strict(),L1=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();var db=4,_n={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},ro=S.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Fe=S.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),pb=S.enum(["none","xs","sm","md","lg","xl"]),mb=S.enum(["none","sm","md","lg","full"]),uc=S.string().regex(/^#[0-9a-fA-F]{6}$/),zp=S.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"),lc=S.union([zp,S.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),S.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),S.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Up=S.object({primary:uc,background:uc,text:uc,radius:mb,font:S.enum(["system","serif","rounded","mono"])}).strict(),io=S.union([S.enum(["primary","text","muted","background","surface"]),S.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),De=(e,t)=>S.number().int().min(e).max(t),Lp=S.union([S.enum(["fit","fill"]),De(1,1200)]),fb=S.object({top:De(0,200),right:De(0,200),bottom:De(0,200),left:De(0,200)}).strict(),gb=S.object({top:De(-100,200),right:De(-100,200),bottom:De(-100,200),left:De(-100,200)}).strict(),$p=S.object({x:De(0,100),y:De(0,100)}).strict(),hb=S.discriminatedUnion("type",[S.object({type:S.literal("color"),color:io}).strict(),S.object({type:S.literal("linear"),angle:De(0,360),stops:S.array(S.object({color:io,at:De(0,100)}).strict()).min(2).max(4)}).strict(),S.object({type:S.literal("image"),src:lc,fit:S.enum(["cover","contain"]),position:$p.optional()}).strict()]),yb=S.discriminatedUnion("type",[S.object({type:S.literal("rect"),radius:S.union([De(0,200),S.object({topLeft:De(0,200),topRight:De(0,200),bottomRight:De(0,200),bottomLeft:De(0,200)}).strict()])}).strict(),S.object({type:S.literal("pill")}).strict()]),Ab=S.object({width:De(0,12),color:io,style:S.enum(["solid","dashed"])}).strict(),bb=S.object({x:De(-40,40),y:De(-40,40),blur:De(0,80),spread:De(-20,40),color:io}).strict(),xb=S.object({font:S.enum(["system","serif","rounded","mono"]),size:De(8,96),weight:S.number().int().min(100).max(900).multipleOf(100),lineHeight:S.number().min(.8).max(3),letterSpacing:S.number().min(-5).max(20),color:io,align:S.enum(["start","center","end"]),italic:S.boolean(),decoration:S.enum(["none","underline","line-through"]),transform:S.enum(["none","uppercase"])}).strict().partial(),jr=S.object({width:Lp,height:Lp,padding:fb,margin:gb,gap:De(0,120),grow:S.union([S.boolean(),S.number().min(0).max(12)]),background:hb,opacity:S.number().min(0).max(1),clipContent:S.boolean(),shape:yb,border:Ab,shadow:bb,text:xb}).strict().partial(),en={id:ro,name:S.string().trim().min(1).max(60).optional(),hidden:S.boolean().optional(),style:jr.optional(),fallback:Fe.optional()},Sb=S.object({...en,type:S.literal("text"),productField:S.enum(["name","price","trial","period"]).optional(),feature:S.object({id:S.uuid(),field:S.enum(["name","allowance"])}).strict().optional(),text:Fe,variant:S.enum(["title","heading","body","caption"])}).strict(),Ib=S.object({...en,type:S.literal("image"),src:lc,localizedSrc:S.record(In,lc).optional(),alt:Fe,aspect:S.enum(["auto","1:1","4:3","16:9","3:1"]),fit:S.enum(["cover","contain"]),position:$p.optional()}).strict(),vb=S.object({...en,type:S.literal("button"),label:Fe,variant:S.enum(["primary","secondary","link"]),action:Fe,purpose:S.enum(["purchase","navigation","close"]).optional(),bind:ua.optional()}).strict(),wb=S.object({...en,type:S.literal("divider")}).strict(),Ob=S.object({...en,type:S.literal("customer_data"),title:Fe,data:Vp}).strict(),_b=S.object({...en,type:S.literal("spacer"),size:pb}).strict(),Cb=S.object({...en,type:S.literal("custom_html"),html:S.record(In,S.string().max(_n.customHtml)),css:S.string().max(_n.customCss)}).strict(),Pb=S.object({...en,type:S.literal("price"),fallback:Fe,parts:S.object({current:jr.optional(),original:jr.optional(),period:jr.optional()}).strict().optional()}).strict(),Eb=S.object({...en,type:S.literal("coupon_code"),label:Fe,fallback:Fe}).strict(),Rb=S.object({...en,type:S.literal("countdown"),source:S.enum(["offer.ends_at","offer.expires_at","fixed"]),at:S.iso.datetime().optional(),granularity:S.enum(["day","hour","minute","second"]),expired:Fe,fallback:Fe}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),kb=S.object({...en,type:S.literal("plan_picker"),label:Fe,fallback:Fe,planIds:S.array(S.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:S.string().min(1).max(200).optional(),grouping:la.safeExtend({monthLabel:Fe,yearLabel:Fe,unavailableLabel:Fe}).optional(),states:S.object({selected:jr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!da(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),jb=S.object({...en,type:S.literal("quantity_picker"),bind:ua.optional(),label:Fe,fallback:Fe,internalFeatureId:S.uuid(),minimumQuantity:De(0,1e4),maximumQuantity:De(0,1e4),defaultQuantity:De(0,1e4),step:De(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"),Tb=S.discriminatedUnion("type",[S.object({type:S.literal("input"),label:Fe,keyboard:S.enum(["text","email","tel","url"]),maxLength:De(1,500)}).strict(),S.object({type:S.literal("multiselect"),label:Fe,min:De(0,50),max:De(1,50)}).strict(),S.object({type:S.literal("select"),label:Fe,defaultIndex:De(0,49),purpose:S.enum(["option","product","tier"]).optional(),pickerId:ro.optional(),selectedStyle:jr.optional()}).strict(),S.object({type:S.literal("tabs"),label:Fe,defaultIndex:De(0,49),purpose:S.literal("tier").optional()}).strict(),S.object({type:S.literal("toggle"),label:Fe,defaultEnabled:S.boolean()}).strict(),S.object({type:S.literal("carousel"),label:Fe}).strict()]),On={...en,type:S.literal("stack"),direction:S.enum(["vertical","horizontal","overlay"]),align:S.enum(["start","center","end","stretch"]),justify:S.enum(["start","center","end","between"]),productSlot:S.object({index:De(0,19),period:S.enum(["month","year"]).optional(),requireBinding:S.boolean().optional()}).strict().optional(),interaction:Tb.optional(),states:S.object({selected:jr.optional()}).strict().optional(),purpose:S.literal("benefits").optional(),purchaseAction:Fe.optional(),buttonVariant:S.enum(["primary","secondary","link"]).optional(),bind:ua.optional()},Kp=S.lazy(()=>S.object({...en,type:On.type,direction:On.direction,align:On.align,justify:On.justify,children:S.array(Nb).max(_n.children),productSlot:On.productSlot,interaction:On.interaction,states:On.states,purpose:On.purpose,purchaseAction:On.purchaseAction,buttonVariant:On.buttonVariant,bind:On.bind}).strict()),Nb=S.lazy(()=>S.union([Kp,Sb,Ib,vb,wb,_b,Cb,Pb,Eb,Rb,kb,jb,Ob])),Db=S.union([S.string().max(500),S.number().finite(),S.boolean(),S.null()]),no={id:Fe,event:Fe,properties:S.record(Fe,Db).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},Fb=S.discriminatedUnion("type",[S.object({...no,type:S.literal("navigate"),close:S.literal(!1),pageId:ro}).strict(),S.object({...no,type:S.literal("event"),close:S.boolean()}).strict(),S.object({...no,type:S.literal("close"),close:S.literal(!0)}).strict(),S.object({...no,type:S.literal("open_url"),close:S.boolean(),url:zp}).strict(),S.object({...no,type:S.literal("claim_offer"),close:S.boolean(),couponId:S.uuid()}).strict()]),Mb=S.object({defaultLocale:In,locales:S.record(In,S.record(Fe,S.string().max(_n.stringLength)))}).strict(),Vb=S.enum(["popup","paywall","onboarding","page","banner"]);var qb=S.discriminatedUnion("type",[S.object({type:S.literal("modal"),size:S.enum(["sm","md","lg"])}).strict(),S.object({type:S.literal("sheet"),size:S.enum(["sm","md","lg"])}).strict(),S.object({type:S.literal("fullscreen")}).strict(),S.object({type:S.literal("inline")}).strict()]);var Bb=S.object({kind:S.literal("screen"),schemaVersion:S.literal(db),name:S.string().trim().min(1).max(80),surface:Vb,initialPageId:ro.optional(),presentation:qb,theme:Up,pages:S.array(S.object({id:ro,name:S.string().trim().min(1).max(60),root:Kp,theme:Up.optional(),editorPosition:S.object({x:S.number().finite().min(-1e5).max(1e5),y:S.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(_n.pages),strings:Mb,actions:S.array(Fb).max(_n.actions)}).strict();function zt(e,t){for(let n of e.pages)Gn(n.root,t)}var cn=Bb.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;zt(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 x of Object.keys(l.html))i.includes(x)||r(`\u81EA\u5B9A\u4E49 HTML ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${x}`);if(l.type==="image")for(let x of Object.keys(l.localizedSrc??{}))i.includes(x)||r(`\u56FE\u7247 ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${x}`)}),c>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),u&&r(`\u5C42\u7EA7\u6700\u591A ${_n.depth} \u5C42`)});function Gn(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)Gn(i,t,n+1,e)}function pa(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 Ub(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=oo(e,t.nodeId);return r?.type==="image"?r.localizedSrc?.[n]??(n===e.strings.defaultLocale?r.src:void 0):void 0}return e.strings.locales[n]?.[t.key]}function ar(e){let t=pa(e).filter(r=>r.required);return Object.keys(e.strings.locales).sort((r,i)=>r===e.strings.defaultLocale?-1:i===e.strings.defaultLocale?1:0).map(r=>{let i=t.filter(a=>!Ub(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 Lb(e,t){let n=null;return Gn(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function oo(e,t){for(let n of e.pages){let r=Lb(n.root,t);if(r)return r}return null}import{z as Mt}from"zod";var bt=Mt.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"),dc=Mt.strictObject({type:Mt.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:Mt.boolean(),enum:Mt.array(Mt.string().max(255)).min(1).max(100).optional()}),ui=dc.extend({type:Mt.enum([...dc.shape.type.options,"array"]),items:dc.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"})}),li=ui.safeExtend({source:Mt.discriminatedUnion("type",[Mt.strictObject({type:Mt.literal("input")}),Mt.strictObject({type:Mt.literal("node")}),Mt.strictObject({type:Mt.enum(["parameter","attribute"]),key:bt})])}),X1=Mt.record(bt,li),pc=Mt.record(bt,bt).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&&Mt.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 mc(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&&mc(e.items,t.items)}function ma(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 di(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 Gp(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 Tr}from"zod";var Cn=Tr.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"),Tn=Tr.discriminatedUnion("source",[Tr.strictObject({source:Tr.literal("literal"),value:xe}),Tr.strictObject({source:Tr.literal("variable"),key:Tr.string().min(1).max(255),path:Cn.optional()})]);function Hp(e,t){if(!t)return e;for(let n of Cn.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 fc(e,t){if(e.source==="literal")return structuredClone(e.value);let n=ma(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(xe.parse(Hp(n[e.key],e.path)))}function gc(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&&!Cn.safeParse(r).success?null:{key:n,path:r}}function hc(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(Np))]}function fa(e){return hc(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function un(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,x=(l.includes(".")?l.indexOf("."):m)+Number(u),A=x<=0?2-x+m:x>=m?x:m+1;n+=A+(c.startsWith("-")?1:0)-s.length}}return n}var sr=_e.enum(["page","popup","banner"]),zb=3e5,Qp=_e.strictObject({type:_e.enum(["string","number","boolean","strings","json"]),nullable:_e.boolean()}),$b=_e.strictObject({inputs:_e.record(Fe,Qp.extend({required:_e.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:_e.record(Fe,Qp).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),Kb=_e.strictObject({kind:sr,schemaVersion:_e.literal(1),name:_e.string().trim().min(1).max(80),screen:cn,contract:$b}),ga=Kb.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"]),un(e)>zb&&n("Content document exceeds its byte budget",[])});function Gb(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 Hb=ga.superRefine((e,t)=>{for(let n of fa(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&&!Gb(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}ar(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),Jp=_e.strictObject({id:_e.uuid(),kind:sr,projectId:_e.uuid(),environmentId:_e.uuid(),name:_e.string(),revision:_e.number().int().nonnegative(),status:_e.enum(["draft","published","archived"]),publishedVersionId:_e.uuid().nullable(),createdAt:_e.iso.datetime({offset:!0}),updatedAt:_e.iso.datetime({offset:!0})}),g_=Jp.extend({draft:ga}),h_=_e.strictObject({rows:_e.array(Jp).max(200),nextCursor:_e.uuid().nullable()}),yc=_e.strictObject({id:_e.uuid(),kind:sr,resourceId:_e.uuid(),projectId:_e.uuid(),environmentId:_e.uuid(),version:_e.number().int().positive(),sourceRevision:_e.number().int().nonnegative(),document:Hb,createdAt:_e.iso.datetime({offset:!0})}),y_=yc.omit({document:!0}),A_=_e.discriminatedUnion("action",[_e.strictObject({action:_e.literal("create"),kind:sr,id:_e.uuid(),document:ga}),_e.strictObject({action:_e.literal("save"),kind:sr,id:_e.uuid(),revision:_e.number().int().nonnegative(),document:ga}),_e.strictObject({action:_e.enum(["publish","archive"]),kind:sr,id:_e.uuid(),revision:_e.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 Zp}from"zod";var pi={funnelId:Zp.uuid().optional(),funnelVersionId:Zp.uuid().optional()};import{z as rt}from"zod";import{z as Be}from"zod";import{z as Ye}from"zod";var v_=Ye.discriminatedUnion("action",[Ye.strictObject({action:Ye.literal("create"),couponId:Ye.uuid(),productBindingId:Ye.uuid(),storeOfferId:Ye.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:Ye.enum(["introductory","promotional"])}),Ye.strictObject({action:Ye.literal("set_enabled"),id:Ye.uuid(),revision:Ye.number().int().nonnegative(),enabled:Ye.boolean()})]),w_=Ye.array(Ye.strictObject({id:Ye.uuid(),couponId:Ye.uuid(),productBindingId:Ye.uuid(),storeOfferId:Ye.string().min(1).max(255).nullable(),storeOfferType:Ye.enum(["introductory","promotional"]),enabled:Ye.boolean(),revision:Ye.number().int().nonnegative()})).max(500),mi=Ye.strictObject({offerKind:Ye.enum(["none","introductory","promotional"]),offerId:Ye.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:Ye.number().int().min(0).max(1e8),trialDays:Ye.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"})}),O_=Ye.record(Ye.uuid(),mi).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var Ac=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:jp,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:be,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 d}from"zod";import{z as Ce}from"zod/v4";import{z as Qb}from"zod/v4";var Jb=Qb.registry(),{BillingInterval:Wp}=(()=>{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:Zb}=(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')."})})}))(Ce),{withSpecDefault:Wb}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(Jb),{COMMON:Yp}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:Yb}={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:Xb}=(e=>({COMMON_SET:new Set(e)}))(Yp),{hasNoDuplicateCurrencies:Xp}={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:em}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:ex}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(Ce),{Infinite:tx}={Infinite:"inf"},{TierBehavior:nx}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:tm}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:rx}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:ix}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:ox}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:ax}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(Ce),{ApiCreditTierSchema:nm}=(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."})})}))(Ce),{VIOLATION_MESSAGES:sx}={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:rm}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(Ce),{ModelMarkupsSchema:cx}=((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()}))(Ce,rm),{InvoiceUsageEntrySchema:ux}=(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()}))(Ce),{AttachDiscountSchema:im}=(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."})}))(Ce),{CustomLineItemSchema:lx}=(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."})})}))(Ce),{UnixMsTimestampSchema:dx}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(Ce),{CreateInvoicePreviewLineSchema:px}=(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()})}))(Ce),{ReissueInvoiceParamsSchema:om}=(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."})})}))(Ce),{InvoiceModeParamsSchema:Nr}=(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."})}))(Ce),{InvoiceTemplateSchema:mx}=(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."})})}))(Ce),{BasePriceSchema:fx}=((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."})})}))(Ce,Wp,Zb),{CURRENCY_CODES:gx}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(Yp,Yb,Xb),{ApiPriceProcessorsSchema:am}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(Ce,ex),{AllocatedBillingFieldSchema:hx}=((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'."})}))(Ce,rx),{CreditDimensionNameSchema:yx}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(Ce,ix,ox),{ApiCreditMatchSchema:sm}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(ax),{findCreditTierViolations:Ax}=(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}}))(sx),{ApiCreditMultiplierSchema:bx}=((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."})}))(Ce,sm),{ProviderMarkupsSchema:xx}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(Ce,rm),{InvoiceFeatureQuantitySchema:cm}=((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."})}))(Ce,tm,ux),{CreateInvoicePreviewSchema:bc}=((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()})}))(Ce,px),{SUPPORTED_SET:Sx}=(e=>({SUPPORTED_SET:new Set(e)}))(gx),{ApiCreditDimensionBaseSchema:Ix}=((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."})})}))(Ce,sm),{refineGraduatedTiers:um}=(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"]})}}))(Ax),{ApiFeatureMarkupsOverrideSchema:vx}=((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."})})}))(Ce,xx,cx),{isValidCurrencyCode:wx}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(Sx),{ApiCreditDimensionSchema:Ox}=((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()])}))(Ce,Ix,nm,um),{CurrencyCodeSchema:lm}=((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')."})}))(Ce,wx),{AdditionalCurrencyTierSchema:_x}=((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"]})}))(Ce,lm),{ApiCreditSchemaItemBaseSchema:dm}=((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."})})}))(Ce,yx,Ox,bx),{ApiFlatCreditSchemaItemSchema:Cx}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(dm,Ce),{AdditionalCurrencyPriceSchema:Px}=((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."})})}))(Ce,lm),{AdditionalCurrencyTierArraySchema:Ex}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(Ce,_x,Xp,em),{ApiGraduatedCreditSchemaItemSchema:Rx}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(dm,Ce,nm,um),{AdditionalCurrencyPriceArraySchema:pm}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(Ce,Px,Xp,em),{ApiUsageTierWithCurrenciesSchema:kx}=((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()}))}))(Ce,tx,Ex),{ApiCreditSchemaItemSchema:jx}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(Ce,Rx,Cx),{BasePriceParamsSchema:Tx}=((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."})}))(fx,Wb,Ce,pm),{PlanItemPriceParamsSchema:Nx}=((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."})})}))(Ce,pm,kx,nx,Wp,tm,hx),{ApiFeatureOverrideSchema:Dx}=((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."})})}))(Ce,jx,vx),{InvoiceBasePriceParamsSchema:mm}=((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()}))(Tx,am),{InvoiceItemPriceParamsSchema:Fx}=((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()}))(Nx,am),{InvoiceLicenseQuantitySchema:Mx}=((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()}))(Ce,mm,cm),{InvoiceCustomizeItemSchema:Vx}=((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()}))(Ce,Fx,Dx),{InvoiceCustomizeSchema:qx}=((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."})}))(Ce,mm,Vx),{InvoicePlanParamsSchema:Bx}=((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()}))(Ce,qx,cm,Mx,im),{CreateInvoiceParamsSchema:fi}=((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."})}))(Ce,Bx,lx,im,dx);var hm=d.strictObject({requestId:d.uuid(),predecessorOperationId:d.uuid().optional(),invoiceMode:Nr.optional(),entityId:d.uuid().optional(),billingSubscriptionId:d.uuid().optional(),newBillingSubscription:d.literal(!0).optional(),offerId:d.uuid().optional(),nativeOffer:mi.optional(),plans:d.array(d.strictObject({productVersionId:d.uuid(),seatQuantities:d.record(Vo,d.number().int().min(0).max(1e4)).optional(),featureQuantities:d.record(d.uuid(),d.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:d.enum(["stripe","apple","google","merchant"]),currency:be}).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"),Fr=d.strictObject({operationId:d.uuid()}),Tt=d.number().int().min(0).max(1e8),Ux=d.strictObject({lineId:d.uuid(),productVersionId:d.uuid(),productName:d.string().min(1).max(80),interval:d.enum(["free","week","month","year","one_time"]),intervalCount:d.number().int().min(1).max(156).optional(),baseAmountMinor:Tt,seats:d.array(d.strictObject({key:Vo,quantity:d.number().int().min(0).max(1e4),includedQuantity:d.number().int().min(0).max(1e4),maximumQuantity:d.number().int().min(0).max(1e4),unitAmountMinor:Tt})).max(20),prepaid:d.array(ap).max(100).optional(),catalogAmountMinor:Tt,trial:d.strictObject({days:d.number().int().min(1).max(730),cardRequired:d.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+zo({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"),ym=d.string().regex(/^[A-Za-z0-9_-]{1,200}$/),Lx=d.strictObject({id:ym,name:d.string().min(1).max(40),percent_off:d.number().gt(0).max(100).optional(),amount_off:d.number().int().positive().optional(),currency:d.string().regex(/^[a-z]{3}$/).optional(),duration:d.enum(["once","repeating","forever"]),duration_in_months:d.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"),zx=d.strictObject({subscriptionId:d.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:d.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:d.array(d.strictObject({id:d.string(),price_id:d.string(),quantity:d.number().int().nonnegative(),discounts:d.array(d.strictObject({id:d.string(),coupon:d.string(),start:d.number(),end:d.number().nullable()})).optional()})).min(1).max(100),prorationDate:d.number().int().nonnegative(),amountMinor:d.number().int().positive(),periodStartMs:d.number(),periodEndMs:d.number()}),Am=d.strictObject({invoiceMode:Nr.optional(),append:zx.optional(),provider:d.literal("stripe"),executor:d.enum(["indiana","merchant"]),accountId:d.string().regex(/^acct_[A-Za-z0-9]+$/),mode:d.enum(["payment","subscription"]),lineItems:d.array(d.strictObject({price:d.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:d.number().int().min(1).max(1e4),priceId:d.uuid(),productName:d.string().min(1).max(80),amountMinor:d.number().int().min(0).max(1e8),currency:d.string().regex(/^[a-z]{3}$/),interval:d.enum(["week","month","year","one_off"]),intervalCount:d.number().int().min(1).max(52),slot:d.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:d.strictObject({mode:d.enum(["graduated","volume"]),tiers:d.array(d.strictObject({upTo:d.number().int().min(1).max(1e6).nullable(),unitAmountMinor:d.number().int().min(0).max(1e8),flatAmountMinor:d.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:d.array(d.strictObject({coupon:ym,terms:Lx})).max(1),trialPeriodDays:d.number().int().min(1).max(730).nullable(),metadata:d.strictObject({grooveCheckoutId:d.uuid(),grooveCustomerId:d.uuid()}),expiresAt:d.iso.datetime({offset:!0})}),gi=d.strictObject({operationId:d.uuid(),entityId:d.uuid().nullable(),billingSubscriptionId:d.uuid().nullable(),discount:d.strictObject({offerId:d.uuid(),couponId:d.uuid(),discount:rr,duration:an,amountMinor:Tt,allocations:d.array(d.strictObject({productVersionId:d.uuid(),amountMinor:Tt})).min(1).max(20),expiresAt:d.iso.datetime({offset:!0})}).nullable(),charge:d.strictObject({effectiveAt:d.iso.datetime({offset:!0}),periodEndsAt:d.iso.datetime({offset:!0}),debitMinor:Tt,discountMinor:Tt,taxMinor:Tt,totalMinor:Tt}).nullable(),expiresAt:d.iso.datetime({offset:!0}),provider:d.enum(["stripe","apple","google","merchant"]),nativeOffer:mi.optional(),currency:be,lines:d.array(Ux).min(1).max(20),catalogAmountMinor:Tt,automaticTax:d.boolean(),execution:d.union([Am,To]).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"),hi=d.strictObject({operationId:d.uuid(),orderId:d.uuid(),append:d.boolean().optional(),invoiceMode:d.boolean().optional(),status:d.enum(["pending","complete","cancelled","failed"]),executor:d.enum(["indiana","merchant"]),checkoutUrl:d.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:d.union([Am,To]).nullable(),currency:be,catalogAmountMinor:Tt,taxMinor:Tt,totalMinor:d.number().int().min(0).max(2e8).nullable(),quoteFinalized:d.boolean(),nativePurchase:Ac.nullable(),confirmedAt:d.iso.datetime({offset:!0}).nullable().optional(),quote:gi.optional(),merchantExecution:wr.nullable().optional(),problem:Fi.nullable().optional(),authority:Mo.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"),ya=d.strictObject({enabled:d.literal(!0),featureIds:d.array(d.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),bm=d.strictObject({requestId:d.uuid(),invoiceMode:Nr.optional(),membershipId:d.uuid(),carryOverBalances:ya.optional(),carryOverUsages:ya.optional(),membershipIds:d.array(d.uuid()).min(1).max(20).optional(),prorationBehavior:d.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:d.enum(["immediate","renewal","store"]),change:d.discriminatedUnion("type",[d.strictObject({type:d.literal("plan"),productVersionId:d.uuid()}),d.strictObject({type:d.literal("seats"),licenseKey:Vo,quantity:d.number().int().min(0).max(1e4)}),d.strictObject({type:d.literal("quantity"),internal_feature_id:d.uuid(),quantity:d.number().int().min(0).max(1e4)}),d.strictObject({type:d.literal("cancel")}),d.strictObject({type:d.literal("uncancel")}),d.strictObject({type:d.literal("billing_cycle"),billingCycleAnchor:d.union([d.literal("now"),d.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"),ha=d.string().regex(/^price_[A-Za-z0-9]+$/),fm=d.strictObject({grooveUpdateId:d.uuid(),grooveCustomerId:d.uuid()}),gm=d.strictObject({price:ha.nullable(),priceId:d.uuid().optional(),quantity:d.number().int().min(0).max(1e4)}),xm=d.strictObject({provider:d.literal("stripe"),invoiceMode:Nr.optional(),executor:d.enum(["indiana","merchant"]),accountId:d.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:d.string().regex(/^sub_[A-Za-z0-9]+$/),action:d.enum(["update","cancel","schedule","release"]),update:d.strictObject({items:d.array(gm).max(20),remove:d.array(ha).max(20),restoreItems:d.array(d.strictObject({price:ha,quantity:d.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:d.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:d.number().int().positive().optional(),paymentBehavior:d.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:d.boolean().optional(),clearCancelAt:d.literal(!0).optional(),billingCycleAnchorNow:d.literal(!0).optional(),metadata:fm}).nullable(),cancel:d.strictObject({prorate:d.literal(!1),invoiceNow:d.literal(!1)}).nullable(),schedule:d.strictObject({currentItems:d.array(d.strictObject({price:ha,quantity:d.number().int().min(0).max(1e4)})).max(20),nextItems:d.array(gm).min(1).max(20),switchAt:d.number().int().positive(),interval:d.enum(["week","month","year"]),intervalCount:d.number().int().min(1).max(52),resetBillingCycleAnchor:d.literal(!0).optional(),metadata:fm}).nullable(),release:d.strictObject({schedule:d.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:d.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"),Aa=d.strictObject({carryOverBalances:ya.optional(),carryOverUsages:ya.optional(),operationId:d.uuid(),membershipId:d.uuid(),productVersionId:d.uuid(),timing:d.enum(["immediate","renewal"]),effectiveAt:d.iso.datetime({offset:!0}),expiresAt:d.iso.datetime({offset:!0}),currency:be,creditMinor:Tt,debitMinor:Tt,discountMinor:Tt,taxMinor:Tt,totalMinor:Tt,retainedProductVersionIds:d.array(d.uuid()).max(19),execution:d.union([xm,No])}),$x=d.strictObject({operationId:d.uuid(),invoiceMode:d.boolean().optional(),membershipId:d.uuid(),productVersionId:d.uuid(),status:d.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:d.enum(["immediate","renewal"]),effectiveAt:d.iso.datetime({offset:!0}),checkoutUrl:d.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:d.enum(["indiana","merchant"]),execution:d.union([xm,No]).nullable(),confirmedAt:d.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:wr.nullable().optional(),problem:Fi.nullable().optional(),quote:Aa.optional(),authority:Mo.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),Kx=d.strictObject({operationId:d.uuid(),membershipId:d.uuid(),productVersionId:d.uuid(),timing:d.literal("store"),effectiveAt:d.null(),expiresAt:d.iso.datetime({offset:!0}),currency:be,creditMinor:d.null(),debitMinor:d.null(),discountMinor:d.null(),taxMinor:d.null(),totalMinor:d.null(),retainedProductVersionIds:d.array(d.uuid()).max(19),store:d.strictObject({provider:d.enum(["apple","google"]),productId:d.string().min(1).max(255),catalogAmountMinor:Tt,policy:d.enum(["apple_store","google_full_price"])})}),Gx=d.strictObject({operationId:d.uuid(),membershipId:d.uuid(),productVersionId:d.uuid(),status:d.enum(["prepared","pending","effective","cancelled","failed"]),timing:d.literal("store"),effectiveAt:d.iso.datetime({offset:!0}).nullable(),checkoutUrl:d.null(),nativePurchase:Ac.nullable()}),Sm=d.union([Aa,Kx]),xc=d.union([$x,Gx]),ao=d.number().int().positive().max(2e8),Dr=d.number().int().min(0).max(2e8),Im=d.strictObject({requestId:d.uuid(),invoiceId:d.uuid(),mode:d.enum(["full","partial"]),amountMinor:ao.optional(),entitlementAction:d.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),vm=d.strictObject({provider:d.literal("stripe"),executor:d.enum(["indiana","merchant"]),accountId:d.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:d.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:ao,currency:d.string().regex(/^[a-z]{3}$/),metadata:d.strictObject({indianaRefundId:d.uuid()}),idempotencyKey:d.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:d.array(d.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),Sc=d.strictObject({operationId:d.uuid(),invoiceId:d.uuid(),providerInvoiceId:d.string().min(1).max(200),currency:be,paidMinor:Dr,refundedMinor:Dr,pendingMinor:Dr,amountMinor:ao,mode:d.enum(["full","partial"]),entitlementAction:d.enum(["retain","revoke"]),revokes:d.strictObject({customerProductIds:d.array(d.uuid()).max(100),subscriptionIds:d.array(d.string().min(1).max(200)).max(20)}),execution:d.union([vm,Do]),expiresAt:d.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"),ba=d.strictObject({operationId:d.uuid(),invoiceId:d.uuid(),providerInvoiceId:d.string().min(1).max(200),status:d.enum(["quoted","pending","succeeded","failed","expired"]),executor:d.enum(["indiana","merchant"]),currency:be,amountMinor:ao,mode:d.enum(["full","partial"]),entitlementAction:d.enum(["retain","revoke"]),refundId:d.string().min(1).max(200).nullable(),quote:Sc.optional(),execution:d.union([vm,Do]).nullable(),confirmedAt:d.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:wr.nullable().optional(),problem:Fi.nullable().optional(),authority:Mo.optional(),failureReason:d.string().min(1).max(200).nullable(),createdAt:d.iso.datetime({offset:!0}),completedAt:d.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"),K_=d.strictObject({invoiceId:d.uuid(),currency:be,paidMinor:Dr,refundedMinor:Dr,pendingMinor:Dr,refundableMinor:Dr,executor:d.enum(["indiana","merchant"]).nullable(),canRefund:d.boolean(),operations:d.array(ba).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),G_=d.strictObject({requestId:d.uuid(),mode:d.enum(["full","partial"]),amountMinor:ao.optional(),entitlementAction:d.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 wm=rt.strictObject({requestId:rt.uuid(),targets:rt.array(rt.strictObject({membershipId:rt.uuid(),action:rt.enum(["cancel","uncancel"]),timing:rt.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"),xa=rt.strictObject({batchId:rt.uuid()}),Hx=rt.strictObject({operationId:rt.uuid(),membershipIds:rt.array(rt.uuid()).min(1).max(20),provider:rt.enum(["stripe","apple","google"]),action:rt.enum(["cancel","uncancel"]),timing:rt.enum(["immediate","renewal"]),status:rt.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:Aa.nullable(),managementUrl:rt.url().nullable(),failureCode:rt.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),so=rt.strictObject({batchId:rt.uuid(),ready:rt.boolean(),status:rt.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:rt.iso.datetime({offset:!0}),acceptedAt:rt.iso.datetime({offset:!0}).nullable(),groups:rt.array(Hx).min(1).max(100)});import{z as ke}from"zod";var Qx=ke.string().trim().min(1).max(240),Ic={requestId:ke.uuid(),reason:Qx},Sa=ke.discriminatedUnion("action",[ke.strictObject({...Ic,action:ke.literal("start"),productVersionId:ke.uuid(),entityId:ke.uuid().optional(),days:ke.number().int().min(1).max(730).optional()}),ke.strictObject({...Ic,action:ke.literal("extend"),membershipId:ke.uuid(),days:ke.number().int().min(1).max(730)}),ke.strictObject({...Ic,action:ke.literal("end"),membershipId:ke.uuid()})]),Om=ke.strictObject({operationId:ke.uuid()}),_m=ke.iso.datetime({offset:!0}),Jx=ke.strictObject({provider:ke.literal("stripe"),executor:ke.enum(["indiana","merchant"]),accountId:ke.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:ke.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:ke.union([ke.literal("now"),_m]),prorationBehavior:ke.literal("none")}),vc=ke.strictObject({operationId:ke.uuid(),action:ke.enum(["start","extend","end"]),status:ke.enum(["pending","effective"]),managedBy:ke.enum(["indiana","stripe"]),membershipIds:ke.array(ke.uuid()).min(1).max(20),endsAt:_m.nullable(),execution:Jx.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"),Y_=ke.strictObject({groupId:ke.uuid(),productVersionId:ke.uuid(),enabled:ke.boolean()});import{z as Ze}from"zod";var Cm=Ze.strictObject({requestId:Ze.uuid(),currency:be,makeDefault:Ze.boolean()}),Pm=Ze.strictObject({setupId:Ze.uuid()}),Zx=Ze.strictObject({provider:Ze.literal("stripe"),executor:Ze.literal("merchant"),accountId:Ze.string().regex(/^acct_[A-Za-z0-9]+$/),mode:Ze.literal("setup"),currency:Ze.string().regex(/^[a-z]{3}$/),customer:Ze.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:Ze.uuid(),metadata:Ze.strictObject({grooveProjectId:Ze.uuid(),grooveEnvironmentId:Ze.uuid(),grooveCustomerId:Ze.uuid(),groovePaymentSetupId:Ze.uuid()}),setDefaultPaymentMethod:Ze.boolean(),expiresAt:Ze.iso.datetime({offset:!0})}),wc=Ze.strictObject({id:Ze.uuid(),provider:Ze.literal("stripe"),status:Ze.enum(["prepared","complete","expired"]),currency:be,makeDefault:Ze.boolean(),url:Ze.url().nullable(),createdAt:Ze.iso.datetime({offset:!0}),expiresAt:Ze.iso.datetime({offset:!0}),completedAt:Ze.iso.datetime({offset:!0}).nullable(),execution:Zx.nullable()});import{z as Nt}from"zod";var Em=Nt.union([Nt.string(),Nt.number(),Nt.boolean(),Nt.null()]),Rm=Nt.strictObject({customerId:Nt.uuid()}),km=Nt.strictObject({customerId:Nt.uuid(),provider:Nt.literal("stripe"),checkedAt:Nt.iso.datetime({offset:!0}),status:Nt.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Nt.number().int().nonnegative(),differences:Nt.array(Nt.strictObject({subscriptionId:Nt.string().startsWith("sub_"),itemId:Nt.string().nullable(),field:Nt.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Em,actual:Em})).max(1e4)});import{z as Se}from"zod";var Ia=Se.iso.datetime({offset:!0}),va=Se.strictObject({createdAt:Ia,id:Se.uuid()}),wa=Se.strictObject({customerId:Se.uuid().optional(),entityId:Se.uuid().optional(),productId:Se.string().min(1).max(256).optional(),provider:Se.enum(["stripe","apple","google","merchant","free"]).optional(),status:Se.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:va.optional(),limit:Se.number().int().min(1).max(100).optional()}),Oc={id:Se.uuid(),customerId:Se.uuid(),entityId:Se.uuid().nullable(),productId:Se.string().min(1).max(256),productVersionId:Se.uuid(),name:Se.string().min(1).max(120),provider:Se.enum(["stripe","apple","google","merchant","free"]),createdAt:Ia},Wx=Se.strictObject({...Oc,status:Se.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:Se.boolean(),billingSubscriptionId:Se.uuid().nullable()}),Yx=Se.strictObject({...Oc,status:Se.enum(["active","ended","refunded"]),orderId:Se.uuid().nullable(),transactionId:Se.uuid().nullable(),currency:be.nullable(),amountMinor:Se.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),Xx=Se.strictObject({...Oc,status:Se.enum(["blocked","resolved"]),conflict:Se.strictObject({detectedAt:Ia,blockingMembershipIds:Se.array(Se.uuid()).min(1).max(100),transactionId:Se.uuid()}),resolvedAt:Ia.nullable()}),jm=wa.extend({status:Se.enum(["blocked","resolved"]).optional()}),Tm=Se.strictObject({customerId:Se.uuid(),orderId:Se.uuid()}),Nm=Se.strictObject({orderId:Se.uuid(),status:Se.enum(["blocked","resolved"])}),Dm=Se.strictObject({items:Se.array(Wx).max(100),nextCursor:va.nullable()}),Fm=Se.strictObject({items:Se.array(Yx).max(100),nextCursor:va.nullable()}),Mm=Se.strictObject({items:Se.array(Xx).max(100),nextCursor:va.nullable()});import{z as tt}from"zod";var Vm=tt.union([tt.strictObject({intent:tt.literal("read"),requestId:tt.uuid(),purchaseIntentId:tt.uuid()}),tt.strictObject({requestId:tt.uuid(),provider:tt.literal("apple"),purchaseIntentId:tt.uuid(),productId:tt.string().min(1).max(255).optional(),signedTransaction:tt.string().min(1).max(131072)}),tt.strictObject({requestId:tt.uuid(),provider:tt.literal("google"),purchaseIntentId:tt.uuid(),productId:tt.string().min(1).max(255).optional(),purchaseToken:tt.string().min(1).max(16384)})]),qm=tt.strictObject({requestId:tt.uuid(),orderId:tt.uuid(),purchaseIntentId:tt.uuid(),status:tt.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:be,refunded:tt.boolean(),completion:tt.strictObject({transactionIds:tt.array(tt.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:tt.boolean()}).nullable()});import{z as $}from"zod";var Cc=$.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),eS=$.record($.string(),$.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),tS=3,co=20,nS=tS*co,_c=$.strictObject({type:$.literal("product"),productId:Cc}),Bm={type:$.literal("group"),key:$.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:$.string().trim().min(1).max(80)},rS=$.discriminatedUnion("type",[_c,$.strictObject({...Bm,items:$.array(_c).max(co)})]),iS=$.discriminatedUnion("type",[_c,$.strictObject({...Bm,items:$.array(rS).max(co)})]),oS=$.array(iS).max(co).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>co||i>nS)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function Pc(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:Pc(t))}var yi=$.strictObject({lookupKey:$.string().trim().min(1).max(200),displayName:$.string().trim().min(1).max(1500),items:oS,metadata:eS}),aS=$.strictObject({product:$.record($.string(),$.json()),prices:$.array($.record($.string(),$.json())),entitlements:$.array($.record($.string(),$.json())),freeTrials:$.array($.record($.string(),$.json())),licenses:$.array($.record($.string(),$.json()))}),Um=yi.extend({id:$.uuid(),projectId:$.uuid(),environmentId:$.uuid(),state:$.enum(["active","archived"]),isCurrent:$.boolean(),revision:$.number().int().nonnegative(),publishedVersionId:$.uuid().nullable(),createdAt:$.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"})}),Lm=$.strictObject({id:$.uuid(),offeringId:$.uuid(),projectId:$.uuid(),environmentId:$.uuid(),version:$.number().int().positive(),document:yi,productEvidence:$.record(Cc,aS),createdAt:$.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=Pc(e.document);(!n.length||uS(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"})}),sS=$.strictObject({rows:$.array(Um).max(200),versions:$.array(Lm).max(500)}),pC=$.discriminatedUnion("action",[$.strictObject({action:$.literal("create"),document:yi}),$.strictObject({action:$.literal("save"),id:$.uuid(),revision:$.number().int().nonnegative(),document:yi}),$.strictObject({action:$.enum(["publish","set_current","archive","restore"]),id:$.uuid(),revision:$.number().int().nonnegative()})]),mC=$.strictObject({record:Um,version:Lm.nullable()}),zm=$.discriminatedUnion("type",[$.strictObject({type:$.literal("current")}),$.strictObject({type:$.literal("id"),id:$.uuid()}),$.strictObject({type:$.literal("lookup_key"),lookupKey:$.string().min(1).max(200)}),$.strictObject({type:$.literal("version"),versionId:$.uuid()})]),cS=$.strictObject({internalId:Cc,id:$.string(),name:$.string().nullable(),version:$.number().int().positive(),archived:$.boolean()}),fC=sS.extend({products:$.array(cS).max(500),pagination:$.strictObject({rows:$.string().nullable(),versions:$.string().nullable(),products:$.string().nullable()}).optional()});function uS(e){let t=[];Pc(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 Oa}from"zod";var $m=Oa.strictObject({id:Oa.uuid(),offeringId:Oa.uuid(),version:Oa.number().int().positive(),document:yi});import{z as wt}from"zod";import{z as fe}from"zod";import{z as Ai}from"zod";var _a=Ai.strictObject({items:Ai.array(Ai.strictObject({productVersionId:Ai.string().min(1).max(200),label:Ai.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:Ai.string().min(1).max(200).nullable(),grouping:la.optional()});function Km(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}import{z as It}from"zod";var lS=It.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ca=It.discriminatedUnion("type",[It.object({type:It.literal("fixed"),productVersionId:It.string().min(1).max(200)}).strict(),It.object({type:It.literal("picker"),pickerId:lS,allowedProductVersionIds:It.array(It.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")]),Hn=It.discriminatedUnion("type",[It.object({type:It.literal("modal"),size:It.enum(["sm","md","lg"])}).strict(),It.object({type:It.literal("sheet"),size:It.enum(["sm","md","lg"])}).strict(),It.object({type:It.literal("fullscreen")}).strict(),It.object({type:It.literal("inline")}).strict()]);var Ec=fe.discriminatedUnion("type",[fe.strictObject({type:fe.literal("event"),event:fe.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),fe.strictObject({type:fe.literal("open_url"),url:fe.url().refine(e=>new URL(e).protocol==="https:")})]),dS=cn,pS=fe.discriminatedUnion("type",[fe.object({type:fe.literal("checkout"),product:Ca}).strict(),fe.object({type:fe.literal("close")}).strict(),fe.object({type:fe.literal("action"),action:Ec}).strict()]),bi=fe.object({schemaVersion:fe.literal(3),kind:fe.literal("paywall"),name:fe.string().trim().min(1).max(80),presentation:Hn,requirement:or.optional(),products:_a,offeringVersionId:fe.uuid().nullable(),offeringId:fe.uuid(),screen:dS,buttons:fe.record(fe.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),pS)}).strict(),kC=bi.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 mS(e))t.addIssue({code:"custom",message:r});ar(e.screen).some(r=>!r.complete)&&t.addIssue({code:"custom",message:"Paywall needs complete local content"}),(Object.keys(e.buttons).length!==e.screen.actions.filter(r=>r.type!=="navigate").length||e.screen.actions.some(r=>r.type!=="navigate"&&!Object.hasOwn(e.buttons,r.id)))&&t.addIssue({code:"custom",message:"Paywall buttons require matching node policies"}),Object.values(e.buttons).some(r=>r.type==="checkout")||t.addIssue({code:"custom",message:"A paywall requires a purchase or membership change button"})});function mS(e){let t=e.products.items.map(a=>a.productVersionId),n=Dp(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&&(!da(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 fS(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),Gn(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(x=>x.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 Gm=fe.object({id:fe.uuid(),projectId:fe.uuid(),environmentId:fe.uuid(),revision:fe.number().int().nonnegative(),state:fe.enum(["active","archived"]),publishedVersionId:fe.uuid().nullable(),updatedAt:fe.iso.datetime({offset:!0}),draft:bi}).strict(),jC=fe.object({rows:fe.array(Gm).max(200),nextCursor:fe.uuid().nullable()}).strict(),TC=Gm.omit({draft:!0}).extend({name:fe.string(),productCount:fe.number().int().nonnegative()}).strict(),NC=fe.discriminatedUnion("action",[fe.object({action:fe.literal("save"),id:fe.uuid().nullable(),revision:fe.number().int().nonnegative(),document:bi}).strict(),fe.object({action:fe.enum(["publish","archive"]),id:fe.uuid(),revision:fe.number().int().nonnegative()}).strict()]),DC=fe.object({paywalls:fe.array(fe.object({id:fe.uuid(),paywallId:fe.uuid(),version:fe.number().int().positive(),name:fe.string().min(1).max(80),presentation:Hn,buttons:bi.shape.buttons}).strict()).max(500),limited:fe.boolean()}).strict();import{z as Pe}from"zod";import{z as $t}from"zod";var xi=$t.string().regex(/^[a-f0-9]{64}$/),gS=ca.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),Hm=$t.strictObject({couponDigests:$t.record($t.uuid(),xi),variables:$t.record(In,$t.record($t.uuid(),$t.partialRecord($t.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),$t.string()))),locales:$t.record(In,ci.extend({nodes:$t.record($t.string(),$t.strictObject({base:gS})),plans:$t.object({}).strict(),pickers:$t.object({}).strict()}).omit({paywall:!0}))});import{z as Ue}from"zod";import{z as Pa}from"zod";var Rc=Pa.strictObject({eventsEnabled:Pa.boolean(),experimentViewsEnabled:Pa.boolean(),featureUsageEnabled:Pa.boolean()}),LC=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function Qm(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}import{z as G}from"zod";var kc=G.tuple([G.number().min(0).max(1),G.number().min(0).max(1)]).refine(([e,t])=>e<=t),hS=G.strictObject({attribute:G.string().optional(),seed:G.string(),hashVersion:G.literal(2),ranges:G.array(kc).max(100)}),yS=G.strictObject({id:G.string().min(1).max(255),condition:Wt,gate:G.boolean().optional()}),AS=G.strictObject({key:G.string().optional(),name:G.string().optional(),passthrough:G.boolean().optional()}),Jm={condition:Wt.optional(),parentConditions:G.array(yS).max(100).optional(),weights:G.array(G.number().min(0).max(1)).max(20).optional(),coverage:G.number().min(0).max(1).optional(),hashAttribute:G.string().optional(),fallbackAttribute:G.string().optional(),hashVersion:G.literal(2).optional(),disableStickyBucketing:G.boolean().optional(),bucketVersion:G.number().int().nonnegative().optional(),minBucketVersion:G.number().int().nonnegative().optional(),filters:G.array(hS).max(100).optional(),ranges:G.array(kc).max(20).optional(),meta:G.array(AS).max(20).optional(),seed:G.string().optional(),name:G.string().optional(),phase:G.string().optional()},Ea=G.strictObject({...Jm,key:G.string().min(1).max(255),variations:G.tuple([xe,xe]).rest(xe).refine(e=>e.length<=20),urlPatterns:G.array(G.strictObject({include:G.boolean(),type:G.enum(["regex","simple"]),pattern:G.string()})).max(100).optional(),force:G.number().int().nonnegative().optional(),active:G.boolean().optional(),persistQueryString:G.boolean().optional()}),jc=G.strictObject({value:xe,variationId:G.number().int(),key:G.string(),name:G.string().optional(),bucket:G.number().optional(),passthrough:G.boolean().optional(),inExperiment:G.boolean(),hashUsed:G.boolean().optional(),hashAttribute:G.string(),hashValue:G.string(),featureId:G.string().nullable(),stickyBucketUsed:G.boolean().optional()}),bS=G.strictObject({...Jm,id:G.string().max(255).optional(),force:xe.optional(),variations:G.array(xe).min(2).max(20).optional(),key:G.string().optional(),range:kc.optional(),tracks:G.array(G.strictObject({experiment:Ea,result:jc})).max(100).optional()}),xS=G.strictObject({defaultValue:xe.optional(),rules:G.array(bS).max(500).optional()}),Tc=G.record(G.string(),G.union([G.strictObject({type:G.literal("hashed"),attributeKey:G.string(),values:G.array(G.string().regex(/^[a-f0-9]{64}$/))}),G.strictObject({type:G.literal("list"),attributeKey:G.string(),values:G.array(G.union([G.string(),G.number()]))}),G.strictObject({type:G.literal("condition"),condition:Wt})])),yn=G.strictObject({scope:et,generation:G.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:G.iso.datetime({offset:!0}),expiresAt:G.iso.datetime({offset:!0}).nullable(),features:G.record(G.string(),xS),savedGroups:Tc,experiments:G.record(G.uuid(),Ea)});var uo=yn.extend({analyticsConfig:Rc,remoteFeatures:Ue.array(Ue.string().min(1).max(255)).max(500)}),Nc=uo.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"})}),Zm=Ue.strictObject({attributes:St,features:Ue.array(Ue.string().min(1).max(255)).max(500).optional(),customerId:Ue.uuid().optional()}),SS=Ue.strictObject({value:xe,source:Ue.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:Ue.boolean(),off:Ue.boolean(),ruleId:Ue.string(),experimentResult:jc.optional()}),Ra=Ue.strictObject({generation:yn.shape.generation,evaluatedAt:yn.shape.evaluatedAt,expiresAt:yn.shape.expiresAt,features:Ue.record(Ue.string(),SS),merchandiseContext:Ue.strictObject({merchandiseId:Ue.uuid(),merchandise:St}).optional()}),Wm=Ue.strictObject({customerId:Ue.uuid().optional(),events:Ue.array(Ue.strictObject({eventUuid:Ue.uuid(),timestamp:Ue.iso.datetime({offset:!0}),name:Ue.string().min(1).max(255),merchandise:Dd.optional(),properties:Ue.record(Ue.string(),xe).default({}),deviceId:Ue.string().min(1).max(255).optional(),sessionId:Ue.string().min(1).max(255).optional()})).min(1).max(100)}),Ym=Ue.strictObject({inserted:Ue.number().int().nonnegative(),duplicates:Ue.number().int().nonnegative(),rejected:Ue.number().int().nonnegative(),skipped:Ue.number().int().nonnegative(),analyticsConfig:Rc});import{z as K}from"zod";function Dc(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(pa(e).map(i=>i.key));for(let[i,a]of Object.entries(e.strings.locales))for(let o of Object.keys(a))r.has(o)||n.push(`Unused string ${o} must not be delivered (${i})`);return n}function Xm(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>Xm(t)??[])}}function IS(e){let t=e.pages.map(i=>{let a=Xm(i.root);return a?.type==="stack"?{...i,root:a}:{...i,root:{type:"stack",id:i.root.id,...i.root.name===void 0?{}:{name:i.root.name},direction:"vertical",align:"stretch",justify:"start",children:[]}}}),n=new Set(pa({pages:t}).map(i=>i.key)),r=Object.fromEntries(Object.entries(e.strings.locales).map(([i,a])=>[i,Object.fromEntries(Object.entries(a).filter(([o])=>n.has(o)))]));return{...e,pages:t,strings:{...e.strings,locales:r}}}function ef(e,t=[]){let n=cn.parse(structuredClone(IS(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=Dc(n,t);if(i.length)throw new Error(i.join("; "));return n}import{z as W}from"zod";import{z as M}from"zod";import{z as lt}from"zod";var rP=lt.strictObject({schemaVersion:lt.literal(1),renderKey:lt.string().min(1).max(256),routeTemplate:lt.string().startsWith("/").max(2048),selectors:lt.array(lt.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:lt.array(lt.number().int().min(0)).min(1),absent:lt.array(lt.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"})}),tf=lt.strictObject({renderKey:lt.string().min(1).max(256),routeKey:lt.string().min(1).max(256),stateKey:lt.string().min(1).max(256),documentKey:lt.string().min(1).max(256),documentHash:lt.string().regex(/^[a-f0-9]{64}$/),compositionKey:lt.string().min(1).max(256),entryMode:lt.enum(["hard","soft"]),match:lt.strictObject({present:lt.array(lt.number().int().min(0)),absent:lt.array(lt.number().int().min(0))})});import{z as Mr}from"zod";var vS=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],Fc="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",wS=Mr.string().regex(new RegExp(`^${Fc}/${Fc}/${Fc}/manifest\\.json$`)),nf=Mr.strictObject({kind:Mr.literal("gcs-resumable"),url:Mr.url(),bucket:Mr.enum(vS),objectKey:wS,byteLength:Mr.number().int().positive(),expiresAt:Mr.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 ft=M.string().min(1).max(256),ln=M.string().regex(/^[a-f0-9]{64}$/),ka=M.strictObject({versionId:M.uuid(),manifestDigest:ln,sourceGraphDigest:ln,pageKey:ft,stateKey:ft,documentKey:ft,documentHash:ln,elementKey:ft.optional(),nodeId:ft.optional(),contentHash:ln.optional(),renderKey:ft.optional()}),rf=M.strictObject({pageKey:ft,documentKey:ft,expectedDocumentHash:ln,renderKey:ft.optional(),nodeId:ft,elementKey:ft,expectedContentHash:ln,property:M.enum(["text","fontSize","color"]),value:M.union([M.string().max(4e3),M.number().finite()])}),lP=M.strictObject({versionId:M.uuid(),manifestDigest:ln,sourceGraphDigest:ln,pageKey:ft,stateKey:ft,documentKey:ft,documentHash:ln,renderKey:ft.optional(),patches:M.array(rf.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),OS=/^[a-z][a-z0-9-]{0,39}$/,lo=M.string().regex(OS),Vc=M.enum(["web","ios","android"]),dP=M.discriminatedUnion("action",[M.strictObject({action:M.literal("register"),requestId:M.uuid(),client:lo,platform:Vc,label:M.string().trim().min(1).max(100),sha256:ln,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:ft,changesetId:M.uuid().nullable(),expectedRevision:ln.nullable(),editorUrl:M.string().url().max(2048),patches:M.array(rf).max(200)})]),qc=M.strictObject({id:M.uuid(),projectId:M.uuid(),environmentId:M.uuid(),clientKey:lo,platform:Vc,label:M.string(),sha256:ln,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())}),_S=M.strictObject({key:lo,platform:Vc,currentId:M.uuid().nullable()}),pP=M.strictObject({rows:M.array(qc).max(100),nextCursor:M.uuid().nullable(),clients:M.array(_S).max(20)}),Mc=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()}),mP=M.strictObject({asOf:M.iso.datetime({offset:!0}),reclamation:M.literal("manual-review-required"),buckets:M.strictObject({source:Mc,runtime:Mc,previews:Mc})}),fP=M.strictObject({version:qc,actorId:M.uuid(),claims:M.record(M.string(),M.json())}),gP=M.strictObject({version:qc,upload:nf.nullable()}),hP=M.object({format:M.literal("indiana-route-state-index"),schemaVersion:M.literal(3),routes:M.array(M.object({routeKey:ft,path:M.string(),documentKey:ft,documentHash:ln,initialStateKey:ft,initialRenderKey:ft})),renders:M.array(tf)}).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"})}),yP=M.strictObject({rows:M.array(M.object({id:M.uuid(),name:M.string(),status:M.string(),variations:M.array(M.object({id:ft,key:ft,name:M.string().optional()}).loose())}).loose()),limited:M.boolean()}),AP=M.strictObject({enabled:M.boolean(),allowedOrigins:M.array(M.string())});import{z as Si}from"zod";var of=Si.strictObject({id:Si.uuid(),name:Si.string().trim().min(1).max(80),client:lo,source:ka,event:Si.enum(["screen_enter","button_click"]),cooldownSeconds:Si.number().int().min(0).max(2592e3),behavior:Si.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 Bc=xe,CS=["parameters","answers","results","variables"];function Uc(e){return CS.some(t=>e===t||e.startsWith(t+"."))}function Lc(e){let t={};for(let[r,i]of Object.entries(ma(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])=>!Uc(r))),variables:t}}import{z as gt}from"zod";var ja=gt.discriminatedUnion("kind",[gt.object({kind:gt.literal("ledger"),cursor:sa}).strict(),gt.object({kind:gt.literal("billing"),cursor:gt.uuid()}).strict()]),PS=gt.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),cr=gt.record(gt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),gt.union([gt.string().max(500),gt.boolean(),gt.array(gt.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),ES=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function zc(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>zc(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||ES.test(n)||zc(r,t+1)))}var RS=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,ur=gt.record(PS,xe).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!zc(e)&&!RS.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var af=gt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ta=gt.array(gt.object({variable:af,componentId:af,required:gt.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"),RP=gt.object({bindings:Ta,answers:cr,values:gt.record(gt.string(),xe).optional()}).strict();import{z as kS}from"zod";var Na=kS.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var $c=Ke.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),sf=Ke.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),cf=ur.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),Kc=Ke.record($c,Ke.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),jS=Tn,uf=Ke.strictObject({type:Ke.literal("external_task"),endpointId:Ke.uuid(),taskKey:$c,inputs:Ke.record($c,jS).refine(e=>Object.keys(e).length<=20),outputs:Kc}),lf=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 BP=Ke.strictObject({outcome:Ke.enum(["success","failure"]),data:cf});var UP=Ke.discriminatedUnion("operation",[Ke.strictObject({operation:Ke.literal("signal"),runId:Ke.uuid(),nodeId:sf,eventName:Na,eventId:Ke.uuid(),data:cf}),Ke.strictObject({operation:Ke.literal("read_results"),runId:Ke.uuid()})]),LP=Ke.strictObject({scope:et,runId:Ke.uuid(),eventId:Ke.uuid(),accepted:Ke.boolean()}),TS=Ke.record(sf,Bc),zP=Ke.strictObject({scope:et,runId:Ke.uuid(),results:TS});var Pn={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},df="00000000-0000-0000-0000-000000000000";import{z as Y}from"zod";import{z as We}from"zod";var JP=We.enum(["local","remote"]),Gc=We.strictObject({port:We.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:xe.optional(),sticky:We.array(We.strictObject({expected:Ui.nullable(),next:Ui})).max(100),exposures:We.array(xe).max(100),features:We.array(xe).max(100)}),pf=We.strictObject({type:We.literal("evaluate"),receiptId:We.uuid(),environmentId:We.uuid(),policyRevision:We.number().int().nonnegative(),attributes:St,sticky:We.record(We.string(),Ui)}),mf=pf.extend({runId:We.uuid(),versionId:We.uuid(),nodeId:We.string().min(1).max(64),visit:We.number().int().nonnegative(),revision:We.number().int().nonnegative()}),Hc=pf.omit({type:!0,receiptId:!0}).extend({type:We.literal("evaluate_segment")}),ff=We.strictObject({nodeId:We.string().min(1).max(64),result:Gc}),gf=Hc.extend({runId:We.uuid(),versionId:We.uuid(),nodeId:We.string().min(1).max(64),visit:We.number().int().nonnegative(),revision:We.number().int().nonnegative(),parameters:ur,answers:cr,variables:We.record(We.string(),xe)});import{z as ue}from"zod";var Qc=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"),Da=ue.intersection(St,ue.looseObject({tags:Qc.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),Fa=ue.string().trim().max(80),Ma=ue.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),Va=ue.union([ue.email().max(254),ue.literal("")]),qa=ue.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),hf=ue.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),yf=ue.object({externalUserId:hf.optional(),name:Fa.default(""),email:Va.default(""),phone:Ma.optional(),attributes:Da.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),Ba=ue.discriminatedUnion("type",[ue.strictObject({type:ue.literal("id"),value:ue.uuid()}),ue.strictObject({type:ue.literal("externalUserId"),value:hf})]),Ua=ue.strictObject({name:Fa.optional(),email:Va.optional(),phone:Ma.optional(),attributes:Da.optional(),fingerprint:qa.optional()}),La=e=>!e.customerData||e.customer?.type==="externalUserId",za="customerData requires an externalUserId customer",Ii=ue.object({id:ue.uuid(),externalUserId:ue.string().min(1).max(255).nullable(),name:Fa,email:Va,phone:Ma.optional(),attributes:Da,createdAt:ue.iso.datetime()}).strict(),Af=ue.object({customer:Ii,changed:ue.boolean(),replayed:ue.boolean()}).strict(),NS=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()]),DS=ue.object({name:Fa.optional(),email:Va.optional(),phone:Ma.optional(),attributes:Da.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:Qc,remove:Qc}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),Jc=ue.object({lookup:NS}).strict(),bf=Jc.extend({requestId:ue.uuid(),patch:DS}).strict(),xf=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(),Sf=ue.object({customers:Ii.array(),hasMore:ue.boolean(),total:ue.number().int().nonnegative().nullable(),evaluatedAt:ue.iso.datetime()}).strict();var po=Y.discriminatedUnion("type",[Y.strictObject({type:Y.literal("literal"),value:xe}),Y.strictObject({type:Y.literal("variable"),key:bt,path:Cn.optional()}),Y.strictObject({type:Y.literal("feature"),featureKey:Y.string().min(1).max(128)})]),FS=Y.strictObject({requestId:Y.uuid(),decisionId:Y.uuid(),customerId:Y.uuid(),externalUserId:Y.string().min(1).max(255).nullable(),versionId:Y.uuid(),receiptId:Y.uuid(),value:xe}),MS={funnelId:Y.uuid(),requestId:Y.uuid(),customer:Ba,customerData:Ua.optional(),attributes:St.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},sE=Y.discriminatedUnion("operation",[Y.strictObject({operation:Y.literal("decide"),...MS}).refine(La,za),Y.strictObject({operation:Y.literal("read_decision"),decisionId:Y.uuid()}),Y.strictObject({operation:Y.literal("evaluate_decision"),decisionId:Y.uuid(),requestId:Y.uuid(),nodeId:Y.string().min(1).max(64),visit:Y.number().int().nonnegative(),revision:Y.number().int().nonnegative(),receiptId:Y.uuid(),policyRevision:Y.number().int().nonnegative(),generation:Y.string().min(1).max(256),result:Gc}),Y.strictObject({operation:Y.literal("feature_config"),funnelId:Y.uuid()}),Y.strictObject({operation:Y.literal("commit_decision_segment"),decisionId:Y.uuid(),requestId:Y.uuid(),nodeId:Y.string().min(1).max(64),visit:Y.number().int().nonnegative(),revision:Y.number().int().nonnegative(),policyRevision:Y.number().int().nonnegative(),generation:Y.string().min(1).max(256),steps:Y.array(ff).max(32),boundary:Y.strictObject({nodeId:Y.string().min(1).max(64),visit:Y.number().int().nonnegative()}).optional()}),Y.strictObject({operation:Y.literal("segment_configuration"),funnelId:Y.uuid(),versionId:Y.uuid()}),Y.strictObject({operation:Y.literal("configuration"),funnelId:Y.uuid(),versionId:Y.uuid().optional()}),Y.strictObject({operation:Y.literal("local_configuration"),funnelId:Y.uuid()}),Y.strictObject({operation:Y.literal("report_used"),decisionId:Y.uuid(),eventId:Y.uuid(),occurredAt:Y.iso.datetime({offset:!0}),reference:Y.string().min(1).max(128).optional()})]),cE=Y.strictObject({scope:et,decisionId:Y.uuid(),requestId:Y.uuid(),status:Y.enum(["pending","completed","failed"]),decision:FS.nullable(),evaluation:Y.discriminatedUnion("type",[mf,gf]).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"),uE=Y.strictObject({scope:et,decisionId:Y.uuid(),eventId:Y.uuid(),source:Y.literal("caller_reported")});import{z as Dt}from"zod";var If=Dt.strictObject({type:Dt.literal("bundle"),paywall:Tn.optional(),offering:Tn.optional(),coupons:Tn,data:Tn}),VS=e=>Dt.strictObject({type:Dt.literal(e),id:Dt.uuid()}),gE=Dt.strictObject({type:Dt.literal("bundle"),paywallVersionId:Dt.uuid().optional(),offeringVersionId:Dt.uuid().optional(),couponIds:Dt.array(Dt.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:xe});var hE=Dt.strictObject({type:Dt.literal("bundle"),offering:VS("offering_version").nullable(),paywall:Dt.strictObject({versionId:Dt.uuid(),paywallId:Dt.uuid(),offeringVersionId:Dt.uuid()}).nullable(),coupons:Dt.array(Li).max(20),data:xe});import{z as En}from"zod";import{z as An}from"zod";var vf=An.union([An.string(),An.number().finite(),An.boolean(),An.null()]),qS=An.union([vf,An.array(vf).min(1).max(20)]),BS=An.record(Cn,qS).refine(e=>Object.keys(e).length<=10),wf=An.strictObject({path:Cn,type:An.enum(["string","number","boolean","strings"]),nullable:An.boolean().optional(),aggregation:An.enum(["count","exists"]).optional(),where:BS.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 US=["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"],Of=En.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),LS=Tn,_f=En.discriminatedUnion("type",[uf,En.strictObject({type:En.literal("claim_offer"),coupon:Tn}),En.strictObject({type:En.literal("event"),event:Of}),En.strictObject({type:En.literal("api"),operation:En.enum(US),inputs:En.record(Cn,LS).refine(e=>Object.keys(e).length<=40),outputs:En.record(Of,wf).refine(e=>Object.keys(e).length<=20)})]);var at=Na,zS=W.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),dn={id:at,name:W.string().trim().min(1).max(80),position:W.strictObject({x:W.number().finite(),y:W.number().finite()}).optional()},$S={success:at,cancel:at,unavailable:at,failure:at},Zc=W.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),Wc=W.enum(["same_window","new_window"]),KS=W.discriminatedUnion("type",[W.strictObject({...dn,type:W.literal("entry"),next:at,triggers:W.array(of).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),W.strictObject({...dn,type:W.literal("screen"),screenId:at,presentation:Hn,outputs:W.record(at,at),offering:W.discriminatedUnion("source",[W.strictObject({source:W.literal("variable"),key:bt}),W.strictObject({source:W.literal("fixed"),versionId:W.uuid()})]).optional()}),W.strictObject({...dn,type:W.literal("offering"),configuration:W.discriminatedUnion("source",[W.strictObject({source:W.literal("fixed"),versionId:W.uuid()}),W.strictObject({source:W.literal("feature"),featureKey:W.string().min(1).max(128)})]),writes:W.strictObject({value:bt}),next:at}),W.strictObject({...dn,type:W.literal("coupon"),couponId:W.uuid(),writes:W.strictObject({value:bt}),next:at}),W.strictObject({...dn,type:W.literal("coupons"),couponIds:W.array(W.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:W.strictObject({value:bt}),next:at}),W.strictObject({...dn,type:W.literal("output"),value:W.discriminatedUnion("type",[...po.options,If,W.strictObject({type:W.literal("selection"),screenId:at,offeringKey:bt})])}),W.strictObject({...dn,type:W.literal("condition"),cases:W.array(W.strictObject({condition:Wt,target:at})).min(1).max(50),default:at}),W.strictObject({...dn,type:W.literal("feature"),featureKey:W.string().min(1).max(128),writes:W.strictObject({value:bt}),next:at}),W.strictObject({...dn,type:W.literal("split"),experimentId:W.uuid(),applyPageExperiment:W.literal(!0).optional(),routes:W.record(zS,at).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:at}),W.strictObject({...dn,type:W.literal("action"),...$S,execution:lf,action:_f,writes:pc.optional()}),W.strictObject({...dn,type:W.literal("external_page"),appManifest:ka.optional(),url:Zc,openIn:Wc,opened:at,failed:at}),W.strictObject({...dn,type:W.literal("end"),outcome:W.enum(["completed","closed","ineligible","failed"]),output:po.optional()}),W.strictObject({...dn,type:W.literal("wait"),writes:pc.optional(),wait:W.discriminatedUnion("type",[W.strictObject({type:W.literal("duration"),delaySeconds:W.number().int().min(1).max(2592e3),elapsed:at}),W.strictObject({type:W.literal("event"),eventName:at,outputs:Kc,timeoutSeconds:W.number().int().min(1).max(2592e3),received:at,timeout:at})])})]),Yc=W.strictObject({version:W.literal(5),entry:at,nodes:W.array(KS).min(1).max(Pn.flowNodes)}),Xc=Yc.superRefine((e,t)=>{GS(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function $a(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 GS(e,t){let n=[],r=new Map(e.nodes.map(l=>[l.id,l])),i=(l,m,x)=>{n.push(l),t?.({message:l,reason:m,path:x?["nodes",e.nodes.indexOf(x)]:[]})};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>Pn.pages||e.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>Pn.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let l of e.nodes){for(let m of $a(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 $a(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 eu={maxTransitions:1e4,runTimeoutSeconds:2592e3};function Cf(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 nr(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 V}from"zod";var vi=V.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Ka=e=>V.record(V.string(),xe).refine(t=>un(t)<=e,"Funnel evidence exceeds its byte budget"),HE=V.enum(["local_segment","evaluation","presentation","timer","event","operation"]),nu=V.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),ru=V.discriminatedUnion("type",[V.strictObject({type:V.literal("flag"),key:V.string().min(1).max(128)}),V.strictObject({type:V.literal("experiment"),id:V.uuid()}),V.strictObject({type:V.literal("saved_group"),id:V.uuid()}),V.strictObject({type:V.literal("config"),key:V.string().min(1).max(128)}),V.strictObject({type:V.literal("constant"),key:V.string().min(1).max(128)}),V.strictObject({type:V.literal("paywall_version"),id:V.uuid()}),V.strictObject({type:V.literal("offering_version"),id:V.uuid()}),V.strictObject({type:V.literal("reward"),id:V.uuid()})]),mo=V.strictObject({schemaVersion:V.literal(1),kind:nu,selector:ru.nullable(),context:Ka(131072),contract:V.strictObject({version:V.number().int().positive(),evaluator:V.string().min(1).max(128),policyRevision:V.number().int().nonnegative()})}).refine(e=>un(e)<=131072,"Node input exceeds its byte budget"),Pf=V.strictObject({schemaVersion:V.literal(1),kind:nu,outcome:V.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:Ka(131072),route:V.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:Ka(131072)}).refine(e=>un(e)<=131072,"Node result exceeds its byte budget"),QE=V.strictObject({schemaVersion:V.literal(1),operations:V.record(vi,V.strictObject({attempts:V.number().int().nonnegative(),maxAttempts:V.number().int().min(1).max(5),deadlineAt:V.iso.datetime({offset:!0}),retryAt:V.iso.datetime({offset:!0}).nullable(),error:V.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:V.strictObject({type:vi,id:V.uuid()}).nullable()}))}).refine(e=>un(e)<=65536,"Execution state exceeds its byte budget"),Vr={receiptId:V.uuid()},tu=V.iso.datetime({offset:!0}),JE=V.discriminatedUnion("type",[V.strictObject({type:V.literal("node_entered"),details:V.strictObject({kind:nu})}),V.strictObject({type:V.literal("presentation_shown"),details:V.strictObject({...Vr,source:V.literal("client"),occurredAt:tu.optional()})}),V.strictObject({type:V.literal("decision_accepted"),details:V.strictObject(Vr)}),V.strictObject({type:V.literal("signal_received"),details:V.strictObject({signalId:V.uuid(),nodeId:vi,eventName:vi,data:Ka(8192),source:V.literal("server"),occurredAt:tu})}),V.strictObject({type:V.literal("signal_consumed"),details:V.strictObject({...Vr,signalId:V.uuid()})}),V.strictObject({type:V.literal("wait_elapsed"),details:V.strictObject(Vr)}),V.strictObject({type:V.literal("wait_timeout"),details:V.strictObject(Vr)}),V.strictObject({type:V.literal("operation_completed"),details:V.strictObject({...Vr,operation:vi,reference:V.strictObject({type:vi,id:V.uuid()}).nullable()})}),V.strictObject({type:V.literal("execution_recovered"),details:V.strictObject({generation:V.number().int().positive(),reason:V.enum(["interrupted","expired_lease","delivery_failed"])})}),V.strictObject({type:V.literal("execution_failed"),details:V.strictObject({generation:V.number().int().positive(),code:V.string().regex(/^[a-z_]{1,64}$/)})}),V.strictObject({type:V.literal("run_completed"),details:V.strictObject({outcome:V.enum(["completed","ineligible","failed"])})}),V.strictObject({type:V.literal("run_closed"),details:V.strictObject({source:V.enum(["client","server","expiry"])})}),V.strictObject({type:V.literal("treatment_used"),details:V.strictObject({...Vr,source:V.enum(["client","server"]),occurredAt:tu,reference:V.string().min(1).max(128).optional()})})]);var bn=K.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),HS=K.discriminatedUnion("type",[K.strictObject({id:bn,type:K.literal("owned"),publicData:Hm.optional(),document:cn.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")}),K.strictObject({id:bn,type:K.literal("paywall"),paywallVersionId:K.uuid()})]),iu={kind:K.literal("funnel"),schemaVersion:K.literal(4),screens:K.array(HS).max(Pn.pages),references:K.record(bn,ru).refine(e=>Object.keys(e).length<=500),inputs:K.array(K.strictObject({variable:bn,screenId:bn,componentId:bn,required:K.boolean()})).max(Pn.questions),variables:K.record(bt,li).refine(e=>Object.keys(e).length<=Pn.logicNodes),outputSchema:ui,execution:K.strictObject({runTimeoutSeconds:K.number().int().min(1).max(eu.runTimeoutSeconds),maxTransitions:K.number().int().min(1).max(eu.maxTransitions)})},fR=K.strictObject({...iu,graph:Yc});function QS(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 Ha(e){return Array.isArray(e)?e.some(Ha):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===df:Ha(n))}function JS(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=ef(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&&!oo(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}),QS(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"&&Ha(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&Ha(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function Ef(e,t){for(let{message:n,reason:r,path:i}of JS(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function Rf(e,t){let n=(A,p,g=[])=>t.addIssue({code:"custom",message:A,path:g,params:{reason:p}}),r=Object.values(e.references),i=new Map(e.screens.map(A=>[A.id,A])),a=(A,p)=>r.some(g=>g.type===A&&("id"in g?g.id:g.key)===p);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let o=e.graph.nodes.filter(A=>A.type==="screen");(o.length!==i.size||o.some(A=>!i.has(A.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(A=>c.some(p=>A!==p&&p.startsWith(A+".")))&&n("Variable paths must not overlap","variable");function u(A,p){Object.hasOwn(e.variables,A)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(p)]);let g=s.get(A)??new Set;g.add(p.id),s.set(A,g)}for(let[A,p]of e.graph.nodes.entries()){let g=["graph","nodes",A],f=p.type==="feature"?p.featureKey:p.type==="offering"&&p.configuration.source==="feature"?p.configuration.featureKey:p.type==="output"&&p.value.type==="feature"?p.value.featureKey:p.type==="end"&&p.output?.type==="feature"?p.output.featureKey:null;f&&!a("flag",f)&&n("Flag selectors require an explicit GB resource reference","feature",g);let I=p.type==="feature"||p.type==="offering"||p.type==="coupon"||p.type==="coupons"||p.type==="action"&&p.action.type==="api"?["value"]:p.type==="action"&&p.action.type==="external_task"?Object.keys(p.action.outputs):p.type==="wait"&&p.wait.type==="event"?Object.keys(p.wait.outputs):[],y="writes"in p?p.writes??{}:{};(I.length!==Object.keys(y).length||I.some(w=>!Object.hasOwn(y,w))||new Set(Object.values(y)).size!==Object.values(y).length)&&n("Node writes must map every named output exactly once","variable",g);for(let[w,k]of Object.entries(y)){u(k,p);let D=e.variables[k],L=p.type==="offering"?"offering_version":p.type==="coupon"?"reward":p.type==="action"&&p.action.type==="api"?"json":p.type==="action"&&p.action.type==="external_task"?p.action.outputs[w]:p.type==="wait"&&p.wait.type==="event"?p.wait.outputs[w]:void 0;(D?.source.type!=="node"||L&&D.type!==L)&&n("Node writer source or output type does not match declaration","variable",g)}if(p.type==="coupons"){let w=e.variables[p.writes.value];(w?.type!=="array"||w.items?.type!=="reward"||w.items.nullable||w.nullable)&&n("Coupons output requires a non-null Reward array","variable",g);for(let k of p.couponIds)a("reward",k)||n("Coupons require Reward references","coupon",g)}if(p.type==="split"&&!a("experiment",p.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",g),p.type==="coupon"&&!a("reward",p.couponId)&&n("Coupon selectors require a Reward reference","coupon",g),p.type==="action"&&p.action.type==="claim_offer"&&p.action.coupon.source==="literal"){let w=p.action.coupon.value;(!w||typeof w!="object"||Array.isArray(w)||w.type!=="reward"||typeof w.id!="string"||Object.keys(w).length!==2||!a("reward",w.id))&&n("Coupon claims require a Reward reference","coupon",g)}if(p.type==="offering"&&p.configuration.source==="fixed"&&!a("offering_version",p.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",g),p.type==="screen"&&p.offering?.source==="variable"&&e.variables[p.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",g),p.type==="action"&&p.action.type==="claim_offer"&&p.action.coupon.source==="variable"&&(e.variables[p.action.coupon.key]?.type!=="reward"||p.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",g),p.type==="screen"){let w=i.get(p.screenId);if(p.offering?.source==="fixed"&&!a("offering_version",p.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",g),w?.type==="paywall"&&p.offering&&n("Paywall owns its fixed Offering Version","offering",g),w?.type==="paywall"&&!a("paywall_version",w.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",g),w?.type==="owned"){let k=w.document.pages[0];if(!k){n("Owned screen requires a page","screen",g);continue}ar(w.document).some(L=>!L.complete)&&n("Owned screens require complete local content","translations",g);let D=new Set(w.document.actions.map(L=>L.id));(D.size!==Object.keys(p.outputs).length||Object.keys(p.outputs).some(L=>!D.has(L)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",g),Gn(k.root,L=>{!p.offering&&(L.type==="plan_picker"||(L.type==="stack"||L.type==="button")&&L.bind?.plan||L.type==="customer_data"&&["customer_plans","credit_packs"].includes(L.data.source))&&n("Product presentation requires an Offering Version","offering",g),L.type==="customer_data"&&Object.values(L.data.outputs??{}).some(he=>he!==void 0&&!D.has(he))&&n("Customer components require declared screen outcomes","componentOutput",g)})}}p.type==="end"&&["completed","ineligible"].includes(p.outcome)&&!p.output&&n("Completed and ineligible ends require a declared output","output",g),p.type==="end"&&p.output?.type==="literal"&&!hn(e.outputSchema,p.output.value)&&n("Terminal output does not match outputSchema","output",g),p.type==="output"&&p.value.type==="literal"&&!hn(e.outputSchema,p.value.value)&&n("Terminal output does not match outputSchema","output",g);let P=p.type==="output"?p.value:p.type==="end"?p.output:void 0;if(P?.type==="variable"&&!P.path){let w=e.variables[P.key];w&&!mc(w,e.outputSchema)&&n("Variable output does not match outputSchema","output",g)}if(p.type==="screen"){let w=i.get(p.screenId);if(w?.type==="owned")for(let k of hc(w.document))(/^(input|params)\./.test(k)||k.startsWith("variables.")&&!gc(k.slice(10),c))&&n("Screen values must reference registered variables","variable",g)}if(p.type==="condition")for(let w of p.cases){for(let k of zn(w.condition))a("saved_group",k)||n("Conditions require explicit Saved Group references","savedGroup",g);for(let k of nr(w.condition))k.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",g)}if(p.type==="output"&&p.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",g);for(let[w,k]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let D=p.value[w];if(D)if(D.source==="literal"){let L=w==="coupons"?D.value:[D.value];(!Array.isArray(L)||L.length>20||L.some(he=>!hn({type:k,nullable:!1},he)||!a(k,he.id))||w==="coupons"&&new Set(L.map(he=>he.id)).size!==L.length)&&n("Bundle requires distinct scoped resource references",w==="coupons"?"coupon":w==="paywall"?"paywall":"offering",[...g,"value",w])}else{let L=e.variables[D.key];(D.path||!L||L.nullable||(w==="coupons"?L.type!=="array"||L.items?.type!=="reward"||L.items.nullable:L.type!==k))&&n("Bundle binding type does not match its slot","output",g)}}}}for(let[A,p]of e.graph.nodes.entries()){let g=p.type==="screen"?i.get(p.screenId):void 0,f=[...Cf(p,c),...g?.type==="owned"?fa(g.document).map(I=>gc(I,c)?.key??I):[]];for(let I of new Set(f)){let k=function(D){if(D===p.id)return!0;if(w.has(D))return!1;w.add(D);let L=e.graph.nodes.find(we=>we.id===D);return L?(P.has(D)?L.type==="action"?[L.cancel,L.unavailable,L.failure]:L.type==="wait"&&L.wait.type==="event"?[L.wait.timeout]:[]:$a(L)).some(k):!1};var x=k;if(!Object.hasOwn(e.variables,I)){n("Consumed variable is undeclared","variable",["graph","nodes",A]);continue}let y=e.variables[I];if(p.type==="screen"&&y.source.type==="input"&&e.inputs.some(D=>D.screenId===p.screenId&&D.variable===I)||y.source.type==="parameter"||y.source.type==="attribute")continue;let P=y.source.type==="input"?new Set(e.inputs.filter(D=>D.variable===I&&D.required).flatMap(D=>o.filter(L=>L.screenId===D.screenId).map(L=>L.id))):s.get(I)??new Set,w=new Set;(!P.size||k(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",A])}}(new Set(e.inputs.map(A=>A.variable)).size!==e.inputs.length||new Set(e.inputs.map(A=>`${A.screenId}:${A.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[A,p]of e.inputs.entries()){e.variables[p.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",A]);let g=i.get(p.screenId),f=g?.type==="owned"?oo(g.document,p.componentId):null;if((f?.type!=="stack"||!f.interaction||!["input","toggle","select","multiselect","tabs"].includes(f.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",A]),f?.type==="stack"&&f.interaction){let I=f.interaction.type==="toggle"?"boolean":f.interaction.type==="multiselect"?"strings":"string";e.variables[p.variable]?.type!==I&&n("Input variable type does not match component","inputBinding",["inputs",A]);let y=e.variables[p.variable]?.enum;y&&!f.children.filter(P=>!P.hidden).every(P=>y.includes(P.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",A])}}for(let[A,p]of Object.entries(e.variables))p.enum&&p.type!=="string"&&n("Only string variables support enum","variable",["variables",A]),p.source.type==="input"&&!e.inputs.some(g=>g.variable===A)&&n("Input variable requires a component binding","inputBinding",["variables",A]);let l=0,m=0;for(let A of e.screens)if(A.type==="owned"){for(let p of A.document.pages)Gn(p.root,()=>{l++});m+=A.document.actions.length}(l>Pn.components||m>Pn.actions||un(e)>Pn.documentBytes)&&n("Funnel document exceeds its budget","budget")}var ZS=K.strictObject({...iu,graph:Xc}).superRefine(Rf),wi=K.strictObject({...iu,graph:Xc,displayName:K.string().trim().min(1).max(80)}).superRefine(Rf),gR=wi.superRefine(Ef),hR=ZS.superRefine(Ef),Ga=K.string().regex(Yt),fo={requestId:K.uuid(),nodeId:bn,visit:K.number().int().nonnegative(),revision:K.number().int().nonnegative(),customerToken:Ga.optional()},WS=K.discriminatedUnion("type",[K.strictObject({type:K.literal("screen"),output:bn,answers:cr,selection:K.record(bn,K.union([K.string().max(200),K.boolean(),K.number().int().min(0).max(1e4)])).optional()}),K.strictObject({type:K.literal("paywall_quote"),featureQuantities:K.record(K.uuid(),K.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100).optional(),actionId:bn,productVersionId:K.uuid(),offerId:K.uuid().optional(),nativeOffer:mi.optional(),predecessor:K.strictObject({operationId:K.uuid().nullable(),generation:K.number().int().positive()}).optional()}),K.strictObject({type:K.literal("paywall_confirm"),operationId:K.uuid()}),K.strictObject({type:K.literal("paywall_cancel"),operationId:K.uuid()}),K.strictObject({type:K.literal("client_action"),receiptId:K.uuid(),outcome:K.enum(["success","cancel","failure","opened","failed"])})]),YS=K.object({nodeId:bn,visit:K.number().int().nonnegative(),revision:K.number().int().nonnegative(),components:K.record(bn,K.object({resourceKey:K.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:K.number().int().min(1).max(1e5),after:ja.nullable(),filter:K.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),Qn=K.discriminatedUnion("operation",[K.strictObject({operation:K.literal("start"),funnelId:K.uuid(),requestId:K.uuid(),customer:Ba.optional(),customerData:Ua.optional(),locale:K.string().min(1).max(35),parameters:ur}).refine(La,za),K.strictObject({operation:K.literal("get"),settlementRequestId:K.uuid().optional(),data:YS.optional(),purchase:K.strictObject({receiptId:K.uuid(),operationId:K.uuid()}).optional(),customerToken:Ga.optional()}),K.strictObject({operation:K.literal("resume"),requestId:K.uuid(),customerToken:Ga.optional()}),K.strictObject({operation:K.literal("submit"),...fo,input:WS}),K.strictObject({operation:K.literal("back"),...fo}),K.strictObject({operation:K.literal("shown"),...fo}),K.strictObject({operation:K.literal("close"),...fo}),K.strictObject({operation:K.literal("commit_segment"),...fo,policyRevision:K.number().int().nonnegative(),generation:K.string().min(1).max(256)}),K.strictObject({operation:K.literal("review"),receiptId:K.uuid().optional(),customerToken:Ga.optional()})]);function Qa(e,t){let n=new Set,r=new Set,i=new Set,a=[],o=new Map,s=new Map,c=new Map;function u(p){for(let g of zn(p))l(g)}function l(p){if(i.has(p)||!Object.hasOwn(t.savedGroups,p))return;let g=t.savedGroups[p];g&&(i.add(p),c.set(p,g),a.push(()=>{!Array.isArray(g)&&g.type==="condition"&&u(g.condition)}))}function m(p){for(let g of["hashAttribute","fallbackAttribute"])if(p[g]!==void 0&&Uc(p[g]))throw new Error(`Funnel GB ${g} uses a reserved flow namespace`);u(p.condition);for(let g of p.parentConditions??[])x(g.id),u(g.condition)}function x(p,g=!1){let f=Object.hasOwn(t.features,p)?t.features[p]:void 0;if(!f){if(g)throw new Error("Required GB Feature is unavailable");return}n.has(p)||(n.add(p),o.set(p,f),a.push(()=>{for(let I of f.rules??[]){m(I);for(let y of I.tracks??[])m(y.experiment)}}))}function A(p){let g=Object.hasOwn(t.experiments,p)?t.experiments[p]:void 0;if(!g)throw new Error("Required GB Experiment is unavailable");r.has(p)||(r.add(p),s.set(p,g),a.push(()=>m(g)))}for(let p of e.graph.nodes){p.type==="feature"&&x(p.featureKey,!0),p.type==="split"&&A(p.experimentId),p.type==="condition"&&p.cases.forEach(f=>u(f.condition)),p.type==="offering"&&p.configuration.source==="feature"&&x(p.configuration.featureKey,!0);let g=p.type==="output"?p.value:p.type==="end"?p.output:null;g?.type==="feature"&&x(g.featureKey,!0)}for(let p of a)p();return{...t,features:Object.fromEntries(o),experiments:Object.fromEntries(s),savedGroups:Object.fromEntries(c)}}import{z as se}from"zod";function kf(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 jf(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 go}from"zod";var Tf=go.object({defaultLocale:In,locales:go.record(In,go.object({name:go.string().max(80),description:go.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 XS=["customer_data","coupon_code"],e0=se.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),Nf=se.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),Ja=(e,t)=>new Set(e.map(t)).size===e.length,t0=se.strictObject({currency:be,amountMinor:se.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),n0=se.strictObject({featureId:se.uuid(),name:se.string().trim().min(1).max(120),allowance:se.string().max(40).nullable(),access:se.boolean()}),r0=se.strictObject({stripe:se.strictObject({prices:se.array(t0).min(1).max(50)}).optional(),apple:se.strictObject({productIds:se.array(e0).min(1).max(10)}).optional(),google:se.strictObject({products:se.array(se.strictObject({productId:Nf,basePlanId:Nf.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!Ja(e.stripe.prices,n=>n.currency)||e.apple&&!Ja(e.apple.productIds,n=>n)||e.google&&!Ja(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),i0=se.strictObject({name:se.string().trim().min(1).max(80),interval:se.enum(["free","week","month","year","one_time"]),intervalCount:se.number().int().min(1).max(100),trial:se.strictObject({days:se.number().int().min(1).max(730),cardRequired:se.boolean()}).nullable(),benefits:se.array(n0).max(50).refine(e=>Ja(e,t=>t.featureId),"Duplicate benefit"),channels:r0,prepaid:se.array(to).max(100).optional()}),o0=se.strictObject({digest:xi,content:se.strictObject({discount:rr,duration:an,appliesTo:Xs,displayCopy:Tf.nullable(),firstPurchaseOnly:se.boolean(),qualificationRequired:se.boolean(),startsAt:se.iso.datetime().nullable(),endsAt:se.iso.datetime().nullable(),grantWindowHours:se.number().int().positive(),perCustomerLimit:se.number().int().positive()})}),a0=se.discriminatedUnion("type",[se.strictObject({type:se.literal("checkout"),product:Ca}),se.strictObject({type:se.literal("close")}),se.strictObject({type:se.literal("action"),action:Ec})]),Za=se.strictObject({kind:se.literal("paywall"),formatVersion:se.literal(1),name:se.string().trim().min(1).max(80),offeringVersionId:se.uuid(),presentation:Hn,screen:cn,products:_a,catalog:se.record(se.uuid(),i0),buttons:se.record(Fe,a0),coupons:se.record(se.uuid(),o0)}).superRefine((e,t)=>{let n=g=>t.addIssue({code:"custom",message:g}),{screen:r}=e;kf(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),Dc(r,XS).forEach(n),ar(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 f="bind"in g?g.bind:void 0;f?.promotionCode&&n("Promotion codes must not be published"),f?.plan&&i.add(f.plan),f?.coupon&&a.add(f.coupon),g.type==="plan_picker"&&(g.planIds?.forEach(I=>i.add(I)),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(f=>f.featureId)));for(let g of o)l.has(g)||n("Feature text must read a displayed benefit");let m=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!==m.length||m.some(g=>!Object.hasOwn(e.buttons,g.id)))&&n("Buttons must match the screen's actions");let A=!1;for(let g of Object.values(e.buttons)){if(g.type!=="checkout")continue;A=!0,(g.product.type==="fixed"?[g.product.productVersionId]:g.product.allowedProductVersionIds).some(I=>!u.has(I))&&n("Checkout may only sell displayed Products")}A||n("A Paywall needs a checkout button");let p=Object.keys(e.coupons);(p.length!==a.size||p.some(g=>!a.has(g)))&&n("Coupons must be exactly the bound Coupons")}),Df=se.strictObject({state:se.enum(["published","archived"]),controlRevision:se.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:se.uuid(),versions:se.record(se.uuid(),se.strictObject({version:se.number().int().positive(),artifact:se.string().min(1),sourceDigest:se.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var tn={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},ou=Pe.string().regex(/^[a-f0-9]{64}$/),au=Pe.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),cu=et.extend({environmentId:Pe.uuid()}),Ff=Pe.strictObject({features:Pe.array(Pe.string()).max(500),experiments:Pe.record(Pe.uuid(),Pe.array(Pe.string()).max(20)),savedGroups:Pe.array(Pe.string()).max(1e3)}),uu=Pe.strictObject({kind:Pe.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:Pe.number().int().positive(),url:Pe.string().min(1).max(2048),sha256:ou,byteLength:Pe.number().int().positive().max(tn.maxArtifactBytes),generation:ou.optional()}),s0=Pe.strictObject({state:Pe.enum(["active","paused","archived"]),controlRevision:au,evaluationMode:Pe.enum(["local","remote"]),evaluationRevision:au,currentVersionId:Pe.uuid(),versions:Pe.record(Pe.uuid(),Pe.strictObject({artifact:Pe.string(),dependencies:Ff,definitionDigest:xi.optional(),couponDigests:Pe.record(Pe.uuid(),xi).optional()}))}),lu=Pe.strictObject({kind:Pe.literal("sdk_configuration"),schemaVersion:Pe.literal(1),scope:cu,revision:au,generation:ou,policy:Pe.strictObject({refreshIntervalSeconds:Pe.number().positive().max(15),maxControlAgeSeconds:Pe.number().positive().max(60)}),gb:Pe.strictObject({features:Pe.string().nullable(),pageExperiments:Pe.string().nullable()}),artifacts:Pe.record(Pe.string(),uu),funnels:Pe.record(Pe.uuid(),s0),paywalls:Pe.record(Pe.uuid(),Df).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 vt(e){if(Array.isArray(e))return`[${e.map(vt).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)}:${vt(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function du(e){return ei(ti(typeof e=="string"?new TextEncoder().encode(e):e))}function Mf(e){return du(vt(e))}var su=class extends Error{constructor(n,r){super(n);Ve(this,"dependency",r)}};function Vf(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(x=>l==="experiment"?x.type==="split"&&x.experimentId===m:l==="feature"&&n(x)===m)?.name,i=(l,m,x=r(m.type,m.resource))=>new su(l,{...m,...x?{step:x}:{}});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=Qa(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 x=a.features[m],A=l.type==="feature"?e.variables[l.writes.value]:e.outputSchema,p={type:"feature",resource:m};if(!x||!A)throw i("Required public Feature declaration is unavailable",{reason:"unavailable",...p},l.name);if([x.defaultValue,...(x.rules??[]).flatMap(f=>[...Object.hasOwn(f,"force")?[f.force]:[],...f.variations??[],...(f.tracks??[]).flatMap(I=>I.experiment.variations)])].some(f=>f===void 0||!hn(A,f)))throw i("GB Feature values violate the Funnel type contract",{reason:"value_type",...p},l.name)}let s=new Set,c=(l,m)=>{for(let x of zn(l)){if(s.has(x))continue;let A=t.savedGroups[x];if(!A)throw i("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:x},m);s.add(x),!Array.isArray(A)&&A.type==="condition"&&c(A.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 x=r("feature",l);for(let A of m.rules??[]){c(A.condition,x);for(let p of[...A.parentConditions??[],...(A.tracks??[]).flatMap(g=>g.experiment.parentConditions??[])])u(p.id,x),c(p.condition,x);for(let p of A.tracks??[])c(p.experiment.condition,x)}}for(let[l,m]of Object.entries(a.experiments)){let x=r("experiment",l);c(m.condition,x);for(let A of m.parentConditions??[])u(A.id,x),c(A.condition,x)}for(let l of e.graph.nodes)if(l.type==="split"){let m=a.experiments[l.experimentId],x={type:"experiment",resource:l.experimentId};if(!m)throw i("Local Funnel requires a public Experiment",{reason:"unavailable",...x},l.name);for(let A of m.variations)if(typeof A!="string"||!Object.hasOwn(l.routes,A))throw i("Experiment variation has no declared Funnel route",{reason:"variation_route",...x},l.name)}return Ff.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 qf(e){return wi.parse(e)}var Bf=wt.strictObject({...pi,selector:wt.discriminatedUnion("type",[wt.strictObject({type:wt.literal("paywall"),paywallId:wt.uuid()}),wt.strictObject({type:wt.literal("version"),versionId:wt.uuid()})]),customerId:wt.uuid().optional(),commerce:si,locale:wt.string().min(1).max(35),requirement:or.optional()}),ho=wt.strictObject({id:wt.uuid(),paywallId:wt.uuid(),version:wt.number().int().positive(),document:bi.omit({requirement:!0,offeringId:!0}),offering:wt.strictObject({id:wt.uuid()}),content:wt.strictObject({environmentId:wt.uuid(),offeringVersionId:wt.uuid(),artifact:uu.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:ci,check:kr.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"})}),qr=wt.strictObject(ho.shape).omit({document:!0,offering:!0}).extend({content:ho.shape.content.unwrap()});function Uf(e,t){let n=Za.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 ho.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 Kt}from"zod";var Lf={requestId:Kt.uuid(),sourceId:Kt.uuid(),expectedAvailable:Lt},zf=Kt.discriminatedUnion("action",[Kt.strictObject({...Lf,action:Kt.enum(["add","subtract","set_remaining"]),amount:Ae}),Kt.strictObject({...Lf,action:Kt.literal("edit"),granted:Ae,expiresAt:Kt.iso.datetime({offset:!0}).nullable(),nextResetAt:Kt.iso.datetime({offset:!0}).nullable(),expectedRevision:Kt.number().int().nonnegative()})]),pu=Kt.strictObject({sourceId:Kt.uuid(),available:Lt,held:Lt,spent:Lt,adjustmentGrantId:Kt.uuid().nullable()}),$f=pu.extend({granted:Lt,expiresAt:Kt.iso.datetime({offset:!0}).nullable(),nextResetAt:Kt.iso.datetime({offset:!0}).nullable(),revision:Kt.number().int().nonnegative()});import{z as pn}from"zod";var Kf=pn.discriminatedUnion("action",[pn.object({action:pn.literal("upsert"),externalId:pn.string().min(1).max(128),name:pn.string().trim().min(1).max(80)}).strict(),pn.object({action:pn.literal("archive"),entityId:pn.uuid()}).strict()]),Gf=pn.object({id:pn.uuid(),externalId:pn.string().min(1).max(128),name:pn.string().min(1).max(80),archived:pn.boolean()}).strict();import{z as Vt}from"zod";import{z as Ur}from"zod";var Qf=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],Hf=Ur.string().regex(/.+\/.+/),mu=Ur.number().min(-100),Br=Ur.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),c0=Ur.strictObject({input:Br,output:Br,cache_read:Br.optional(),cache_write:Br.optional(),reasoning:Br.optional(),input_audio:Br.optional(),output_audio:Br.optional()}),fu=(e,t)=>Ur.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),fk=Ur.strictObject({defaultMarkup:mu,providerMarkups:fu(Ur.string().min(1),mu),modelMarkups:fu(Hf,mu),customModels:fu(Hf,c0.partial())});import{z as ye}from"zod";var Lr=ye.iso.datetime({offset:!0}),lr=ye.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),u0=ye.discriminatedUnion("kind",[ye.object({kind:ye.literal("absolute"),from:Lr,to:Lr}).strict(),ye.object({kind:ye.literal("last_days"),days:ye.union([ye.literal(1),ye.literal(7),ye.literal(30),ye.literal(90)])}).strict(),ye.object({kind:ye.literal("billing_cycles"),membershipId:ye.uuid(),count:ye.number().int().min(1).max(12),includeCurrent:ye.boolean()}).strict()]),Jf=ye.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"),l0=ye.object({key:ye.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:ye.array(ye.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),zr=ye.object({range:u0,timezone:Jf,filterBy:ye.array(l0).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:ye.enum(["hour","day","week","month"]),internal_feature_id:ye.uuid().nullable(),entityId:ye.uuid().nullable(),topN:ye.number().int().min(1).max(50).nullable(),groupBy:ye.union([ye.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),ye.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:ye.object({bucket:Lr,group:ye.string().max(240),isOther:ye.boolean(),internal_feature_id:ye.uuid(),resourceId:ye.uuid()}).strict().nullable(),limit:ye.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)"})}),Zf=ye.object({from:Lr,to:Lr,interval:ye.enum(["hour","day","week","month"]),timezone:Jf,rows:ye.array(ye.object({bucket:Lr,group:ye.string().max(240),isOther:ye.boolean(),internal_feature_id:ye.uuid(),resourceId:ye.uuid(),consumedUnits:lr,refundedUnits:lr,reservedUnits:lr,charged:lr,refunded:lr,reserved:lr,netUnits:lr,netCharged:lr}).strict()).max(100),nextCursor:ye.object({bucket:Lr,group:ye.string().max(240),isOther:ye.boolean(),internal_feature_id:ye.uuid(),resourceId:ye.uuid()}).strict().nullable()}).strict();var Oi=Vt.string().regex(/^(0|[1-9]\d{0,29})$/),Wf=Vt.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),gu=Vt.strictObject({bucket:Vt.iso.datetime({offset:!0}),group:Vt.string().max(240),isOther:Vt.boolean(),internal_feature_id:Vt.uuid()}),Yf=Vt.strictObject({...zr.shape,groupBy:Vt.union([Vt.enum(["customer","entity","entitlement"]),Vt.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:gu.nullable()}).superRefine((e,t)=>{let n=zr.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),Xf=Vt.strictObject({from:Vt.iso.datetime({offset:!0}),to:Vt.iso.datetime({offset:!0}),interval:zr.shape.interval,timezone:zr.shape.timezone,rows:Vt.array(Vt.strictObject({...gu.shape,eventCount:Oi,units:Wf,tokenEventCount:Oi,tokens:Vt.strictObject(Object.fromEntries(Qf.map(e=>[e,Oi]))),totalTokens:Oi,providerCostEventCount:Oi,providerCostUsd:Wf,invalidTelemetryEventCount:Oi})).max(100),nextCursor:gu.nullable()});import{z as ht}from"zod";var eg=ht.object({requestId:ht.uuid(),items:ht.array(ht.object({customerId:ht.uuid(),command:Ji.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"),tg=ht.object({batchId:ht.uuid(),after:ht.number().int().min(-1).max(999),limit:ht.number().int().min(1).max(100)}).strict(),ng=ht.object({batchId:ht.uuid(),status:ht.enum(["queued","complete"]),total:ht.number().int().min(1).max(1e3),processed:ht.number().int().min(0).max(1e3),items:ht.array(ht.object({position:ht.number().int().min(0).max(999),customerId:ht.uuid(),idempotencyKey:ht.string().min(1).max(120),status:ht.enum(["queued","accepted","rejected","failed"]),receipt:Zi.nullable(),errorCode:ht.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:ht.number().int().min(0).max(999).nullable()}).strict();import{z as E}from"zod";var d0=E.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),rg=E.enum(["draft","active","paused","archived"]),ig=E.string().min(1).max(256),og=E.array(ig).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),p0=E.strictObject({duration:E.enum(["day","week","month","year"]),length:E.number().int().min(1).max(3660)}),m0=E.strictObject({internal_feature_id:E.uuid(),allowance:E.number().nonnegative().max(1e15).nullable(),expiry:p0.nullable()}),f0=E.discriminatedUnion("type",[E.strictObject({type:E.literal("feature_grant"),grants:E.array(m0).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),E.strictObject({type:E.literal("free_product"),productId:ig,duration:an}),E.strictObject({type:E.literal("invoice_credits"),amount:E.number().positive().max(1e8),duration:an,rollover:E.boolean(),productIds:og})]),g0=E.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),ag=E.object({key:g0,name:E.string().trim().min(1).max(80),configuration:f0}).strict(),sg=E.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),hu=E.object({code:sg,maxUses:E.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:E.boolean()}).strict(),cg=E.object({key:E.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:E.string().trim().min(1).max(80),rewardId:E.uuid(),redeemOn:E.enum(["customer_creation","checkout"]),receivedBy:E.enum(["referrer","all"]),maxRedemptions:E.number().int().min(1).max(1e6).nullable(),productIds:og,excludeTrial:E.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),ug={id:E.uuid(),projectId:E.uuid(),environmentId:E.uuid(),revision:E.number().int().nonnegative(),status:rg,createdAt:E.iso.datetime({offset:!0}),updatedAt:E.iso.datetime({offset:!0})},h0=ag.extend(ug).strict(),y0=cg.safeExtend(ug).strict(),Pk=E.strictObject({id:E.uuid(),key:E.string(),name:E.string(),type:d0,status:rg}),Ek=E.discriminatedUnion("action",[E.object({action:E.literal("save"),id:E.uuid().nullable(),revision:E.number().int().nonnegative(),input:ag}).strict(),E.object({action:E.enum(["activate","pause","resume","archive","delete"]),id:E.uuid(),revision:E.number().int().nonnegative()}).strict()]),Rk=E.discriminatedUnion("action",[E.object({action:E.literal("save"),id:E.uuid().nullable(),revision:E.number().int().nonnegative(),input:cg}).strict(),E.object({action:E.enum(["activate","pause","resume","archive","delete"]),id:E.uuid(),revision:E.number().int().nonnegative()}).strict()]),lg=E.object({id:E.uuid(),rewardId:E.uuid(),programId:E.uuid().nullable(),customerId:E.uuid(),referrerId:E.uuid().nullable(),status:E.enum(["pending","applied","unavailable"]),result:E.record(E.string(),E.unknown()).nullable(),createdAt:E.iso.datetime({offset:!0})}).strict(),dg=E.object({code:sg,requestId:E.uuid()}).strict(),pg=E.strictObject({redemptionId:E.uuid(),currency:be,requestId:E.uuid(),accepted:E.literal(!0)}),A0=E.strictObject({type:E.literal("checkout"),orderId:E.uuid(),productVersionId:E.uuid(),currency:be,duration:an,renewalAmountMinor:E.number().int().positive().max(1e8),status:E.enum(["created","pending","trialing","paid","cancelled","failed"]),url:E.url().nullable()}),mg=E.discriminatedUnion("type",[A0,E.strictObject({type:E.literal("subscription"),operationId:E.uuid(),membershipId:E.uuid(),productVersionId:E.uuid(),currency:be,duration:an,renewalAmountMinor:E.number().int().positive().max(1e8),status:E.enum(["pending","running","applied","failed"])})]),fg=E.object({programId:E.uuid(),requestId:E.uuid()}).strict(),gg=E.object({id:E.uuid(),programId:E.uuid(),code:hu.shape.code,createdAt:E.iso.datetime({offset:!0})}).strict(),kk=E.object({rows:E.array(h0).max(100),nextCursor:E.uuid().nullable()}).strict(),jk=E.object({rows:E.array(y0).max(100),nextCursor:E.uuid().nullable()}).strict(),b0=hu.extend({id:E.uuid(),redemptions:E.number().int().nonnegative()}).strict(),x0=E.strictObject({id:E.uuid(),programId:E.uuid().nullable(),customerId:E.uuid().nullable(),referrerId:E.uuid().nullable(),code:E.string().nullable(),status:E.enum(["pending","triggered","applied"]),createdAt:E.iso.datetime({offset:!0})}),Tk=E.object({codes:E.array(b0).max(100),redemptions:E.array(x0).max(100),customers:E.record(E.uuid(),E.string()),codesCursor:E.uuid().nullable(),redemptionsCursor:E.uuid().nullable()}).strict(),Nk=E.discriminatedUnion("action",[E.object({action:E.literal("create"),rewardId:E.uuid(),revision:E.number().int().nonnegative(),input:hu}).strict(),E.object({action:E.literal("remove"),rewardId:E.uuid(),revision:E.number().int().nonnegative(),codeId:E.uuid()}).strict()]);import{z as v}from"zod";import{z as X}from"zod";var Nn={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},yo=e=>new Set(e).size===e.length,yu=X.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),S0=X.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),Ao=X.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"))),I0=X.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),hg=X.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var yg=X.strictObject({id:X.uuid(),repo:S0,platform:X.enum(["github","gitlab","bitbucket"]),branches:X.array(Ao).min(1).max(4).refine(yo),workflow:X.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:X.array(X.uuid()).min(1).max(4).refine(yo),include:X.array(hg).min(1).max(16),exclude:X.array(hg).max(16),methods:X.array(X.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(yo),maxAgeHours:X.number().int().min(1).max(720)}),Ag=yg.extend({revision:X.number().int().positive()}),Mk=X.strictObject({repository:yg,expectedRevision:X.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),bg=X.strictObject({repositoryId:X.uuid(),branch:Ao}),v0=X.array(yu).max(Nn.keys).refine(yo),xg=X.strictObject({repository:Ag.omit({keyIds:!0}),branch:Ao,keys:v0,keySetHash:X.string().regex(/^[a-f0-9]{64}$/)}),w0=X.strictObject({filePath:I0,startingLineNumber:X.number().int().min(1).max(1e7)}),Au=X.strictObject({protocol:X.literal(1),repositoryId:X.uuid(),branch:Ao,workflow:X.string().max(200),configurationRevision:X.number().int().positive(),keySetHash:X.string().regex(/^[a-f0-9]{64}$/),commit:X.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:X.uuid(),runNumber:X.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:X.number().int().min(1).max(1e4),scannerVersion:X.literal("1"),scannedAt:X.iso.datetime({offset:!0}),coverage:X.strictObject({complete:X.literal(!0),files:X.number().int().min(0).max(Nn.files),sourceBytes:X.number().int().min(0).max(Nn.sourceBytes),unresolvedCalls:X.number().int().min(0).max(1e6),unsupportedFiles:X.number().int().min(0).max(Nn.files)}),features:X.array(X.strictObject({key:yu,refs:X.array(w0).max(Nn.referencesPerKey)})).max(Nn.keys)}).superRefine((e,t)=>{yo(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)>Nn.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),bu=X.strictObject({scanId:X.uuid(),commit:X.string(),receivedAt:X.string(),references:X.number().int().nonnegative(),removedReferences:X.number().int().nonnegative()}),O0=bu.extend({repositoryId:X.uuid(),branch:Ao,workflow:X.string(),digest:X.string(),configurationRevision:X.number().int().positive(),runNumber:X.number().int().positive(),runAttempt:X.number().int().positive(),scannedAt:X.string(),keySetHash:X.string(),coverage:Au.shape.coverage}),_0=X.strictObject({repositories:X.array(Ag).max(Nn.repositories),scans:X.array(O0).max(Nn.repositories*Nn.branches)}),C0=X.strictObject({key:yu,references:X.number().int().nonnegative(),coveredTargets:X.number().int().nonnegative(),expiredTargets:X.number().int().nonnegative(),uncertainTargets:X.number().int().nonnegative()}),Vk=X.strictObject({available:X.boolean().default(!0),settings:_0,expectedTargets:X.number().int().min(0).max(80),features:X.array(C0).max(2001),truncated:X.boolean()});import{z as Ot}from"zod";var P0=Ot.enum(["checkout.session.completed","checkout.session.expired","checkout.session.async_payment_succeeded","checkout.session.async_payment_failed","customer.subscription.created","customer.subscription.updated","customer.subscription.deleted","customer.subscription.paused","customer.subscription.resumed","invoice.created","invoice.paid","customer.discount.created","customer.discount.updated","refund.created","refund.updated","refund.failed","charge.refunded"]),E0=Ot.strictObject({provider:Ot.literal("stripe"),accountId:Ot.string().regex(/^acct_[A-Za-z0-9]+$/),eventId:Ot.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),type:P0,occurredAt:Ot.number().int().positive().max(Number.MAX_SAFE_INTEGER),data:Ot.record(Ot.string(),Ot.unknown()).and(Ot.object({id:Ot.string().min(1).max(255),object:Ot.enum(["checkout.session","subscription","invoice","discount","refund","charge"]),livemode:Ot.boolean()}))}),Sg=Ot.union([E0,jl]),Ig=Ot.strictObject({id:Ot.uuid(),eventId:Ot.string().min(1).max(200),source:Ot.literal("merchant"),providerVerified:Ot.literal(!1),outcome:Ot.string().min(1).max(100)});import{z as Gt}from"zod";var wg={customerId:Gt.uuid(),eventId:Gt.string().trim().min(1).max(200),grantId:Gt.uuid(),occurredAt:Gt.iso.datetime({offset:!0})},Og=Gt.strictObject({...wg,productVersionId:Gt.uuid(),subscriptionId:Gt.string().trim().min(1).max(255)}),_g=Gt.strictObject({...wg,merchandiseId:Gt.uuid()}),Cg=Gt.union([Og,_g]),vg={id:Gt.uuid(),couponId:Gt.uuid(),status:Gt.literal("redeemed"),source:Gt.literal("merchant"),recordedAt:Gt.iso.datetime({offset:!0})},Pg=Gt.union([Og.extend(vg),_g.extend(vg)]);import{z as ae}from"zod";var Eg=om,R0=Eg.extend({invoice_id:Eg.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),xu=ae.strictObject({name:ae.string().trim().min(1).max(255),memo:ae.string().max(1e4).nullable().optional(),footer:ae.string().max(1e4).nullable().optional(),net_terms_days:ae.number().int().positive().nullable().optional()}),k0=xu.extend({id:ae.string().min(1).max(255),created_at:ae.number().nullable()}),Rg=ae.strictObject({items:ae.array(k0).max(50),nextCursor:ae.uuid().nullable()}),Hk=ae.discriminatedUnion("action",[ae.strictObject({action:ae.literal("create"),requestId:ae.uuid(),values:xu}),ae.strictObject({action:ae.literal("update"),id:ae.string().min(1).max(255),values:xu}),ae.strictObject({action:ae.literal("delete"),id:ae.string().min(1).max(255)})]),kg=ae.discriminatedUnion("action",[ae.strictObject({action:ae.literal("create"),requestId:ae.uuid(),params:fi}),ae.strictObject({action:ae.enum(["finalize","send","pay","void"]),requestId:ae.uuid(),invoiceId:ae.uuid()}),ae.strictObject({action:ae.literal("reissue"),requestId:ae.uuid(),invoiceId:ae.uuid(),params:R0})]),Su=ae.strictObject({id:ae.uuid(),customerId:ae.uuid(),providerInvoiceId:ae.string().nullable(),status:ae.enum(["draft","open","paid","void","uncollectible"]),currency:ae.string(),totalMinor:ae.string().regex(/^-?\d+$/),paidMinor:ae.string().regex(/^\d+$/),refundedMinor:ae.string().regex(/^\d+$/),hostedInvoiceUrl:ae.url().nullable(),createdAt:ae.number(),collectionMethod:ae.enum(["send_invoice","charge_automatically"]).nullable()}),jg=Su.extend({lines:ae.array(ae.strictObject({id:ae.uuid(),description:ae.string(),amountMinor:ae.string().regex(/^-?\d+$/),netAmountMinor:ae.string().regex(/^-?\d+$/),quantity:ae.number().nullable(),periodStart:ae.number().nullable(),periodEnd:ae.number().nullable()})).max(1e3)}),_i=ae.strictObject({taskId:ae.uuid(),status:ae.enum(["ready","running","done","dead"]),invoice:Su.nullable(),errorCode:ae.string().nullable()}),Tg=ae.strictObject({items:ae.array(Su).max(50),nextCursor:ae.uuid().nullable(),operations:ae.array(_i).max(50),operationsLimited:ae.boolean()});var j0=v.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"]),Ng={scope:et,permissions:v.array(j0),expiresAt:v.iso.datetime().nullable()},Vj=v.discriminatedUnion("kind",[v.object({...Ng,kind:v.literal("server"),keyId:v.string().min(1)}),v.object({...Ng,kind:v.literal("customer"),customerId:v.string().min(1),identityKind:v.enum(["identified","guest"]),expiresAt:v.iso.datetime()})]),z=v.object({requestId:v.uuid(),scope:et}).strict(),T0=yf.safeExtend({fingerprint:qa.optional()}).strict(),N0=z.extend({customer:Ii,created:v.boolean()});function Dg(){return z.extend({offer:Li.nullable(),reason:Md.nullable()})}var O={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:Cp,response:z.extend({message:v.object({messageId:v.uuid(),channel:eo,acceptedAt:v.iso.datetime({offset:!0}),status:v.enum(["accepted","sending","completed","canceled"]),replayed:v.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:v.strictObject({messageId:v.uuid()}),response:z.extend({message:v.object({id:v.uuid(),channel:eo,status:v.enum(["accepted","sending","completed","canceled"]),deliveries:v.array(v.object({id:v.uuid(),status:Ep,attempts:v.number().int().nonnegative(),receipts:v.array(v.object({kind:Rp,occurredAt:v.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:hl,response:z.extend({installation:vr})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:yl,response:z.extend({installation:vr})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:Ro,response:z.extend({installation:vr})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:v.strictObject({channel:eo}),response:z.extend({preference:bs})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:Pp,response:z.extend({preference:bs})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:v.strictObject({cursor:v.uuid().optional()}),response:z.extend({templates:Rg})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:v.strictObject({customerId:v.uuid(),params:fi}),response:z.extend({preview:bc})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:v.strictObject({customerId:v.uuid(),requestId:v.uuid(),params:fi}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:z.extend({operation:_i})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:v.strictObject({customerId:v.uuid(),command:kg}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:z.extend({operation:_i})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:v.strictObject({customerId:v.uuid(),taskId:v.uuid()}),response:z.extend({operation:_i})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:v.strictObject({customerId:v.uuid(),cursor:v.uuid().optional()}),response:z.extend({invoices:Tg})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:v.strictObject({customerId:v.uuid(),invoiceId:v.uuid()}),response:z.extend({invoice:jg})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:bg,response:z.extend({config:xg})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:Au,response:z.extend({receipt:bu})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:v.strictObject({}),response:z.extend({payload:uo})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:Zm,response:z.merge(Ra)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:Wm,response:z.merge(Ym)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:v.strictObject({customerId:v.uuid(),sourceId:v.uuid()}),response:z.extend({balance:$f})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:v.strictObject({customerId:v.uuid(),command:zf}),response:z.extend({balance:pu})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:v.strictObject({internal_feature_id:v.uuid(),customerId:v.uuid().optional(),entityId:v.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:z.extend({internal_feature_id:v.uuid(),config:Ns,model_markups:Uo})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:v.strictObject({customerId:v.uuid(),query:aa}),response:z.extend({usage:Wi})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:v.strictObject({customerId:v.uuid(),command:Ap}),response:z.extend({usage:Wi})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:v.strictObject({customerId:v.uuid(),command:pp}),response:z.extend({grant:rc})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:mp,response:z.extend({grants:fp})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:v.union(Vm.options.map(e=>e.extend({customerId:v.uuid().optional(),customerToken:v.string().regex(Yt).optional()}))),response:z.extend({operation:qm})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:Cm.extend({customerId:v.uuid().optional()}),response:z.extend({setup:wc})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Pm.extend({customerId:v.uuid().optional()}),response:z.extend({setup:wc})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:wm.safeExtend({customerId:v.uuid()}),response:z.extend({batch:so})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:xa.extend({customerId:v.uuid()}),response:z.extend({batch:so})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:xa.extend({customerId:v.uuid()}),response:z.extend({batch:so})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:xa.extend({customerId:v.uuid()}),response:z.extend({batch:so})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:v.discriminatedUnion("action",[Sa.options[0].extend({customerId:v.uuid()}),Sa.options[1].extend({customerId:v.uuid()}),Sa.options[2].extend({customerId:v.uuid()})]),response:z.extend({trial:vc})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Om.extend({customerId:v.uuid()}),response:z.extend({trial:vc})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:wa,response:z.extend({subscriptions:Dm})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:wa,response:z.extend({purchases:Fm})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:jm,response:z.extend({conflicts:Mm})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:Tm,response:z.extend({resolution:Nm})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:Rm,response:z.extend({verification:km})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:hm.safeExtend({...pi,customerId:v.uuid().optional()}),response:z.extend({quote:gi})},recordBillingEvent:{method:"POST",path:"billing/events/record",permission:"billing:write",audience:"server",request:Sg,response:z.extend({record:Ig})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Fr.extend({customerId:v.uuid().optional(),intent:v.enum(["confirm","cancel"]).optional()}),response:z.extend({operation:hi})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Fr.extend({customerId:v.uuid().optional()}),response:z.extend({operation:hi})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:bm.safeExtend({customerId:v.uuid().optional()}),response:z.extend({quote:Sm})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Fr.extend({customerId:v.uuid().optional(),intent:v.enum(["confirm","cancel"]).optional()}),response:z.extend({operation:xc})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Fr.extend({customerId:v.uuid().optional()}),response:z.extend({operation:xc})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:Im.safeExtend({customerId:v.uuid()}),response:z.extend({quote:Sc})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Fr.extend({customerId:v.uuid()}),response:z.extend({operation:ba})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Fr.extend({customerId:v.uuid()}),response:z.extend({operation:ba})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:Wd,response:z.extend({controls:tc})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:$d,response:z.extend({prepared:Gd})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:Hd,response:z.extend({authorization:na})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:np,response:z.extend({coupons:rp})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Qd,response:z.extend({authorization:na})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:ep,response:z.extend({invoices:tp})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:Xd.extend({customerId:v.uuid()}),response:z.extend({operation:_i})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:Yd,response:z.extend({invoice:Ki})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:v.object({customerId:v.uuid(),command:Zd}).strict(),response:z.extend({controls:tc})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:v.object({customerId:v.uuid(),command:Kf}).strict(),response:z.extend({entity:Gf})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:v.strictObject({customerId:v.uuid().nullable(),query:Yf}),response:z.extend({analytics:Xf})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:v.object({customerId:v.uuid().nullable(),query:zr}).strict(),response:z.extend({analytics:Zf})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:eg,response:z.extend({batchId:v.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:tg,response:z.extend({batch:ng})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:Tp.extend({customerId:v.string().min(1).optional()}),response:z.extend({check:kr})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:v.strictObject({kind:sr,selector:v.discriminatedUnion("type",[v.strictObject({type:v.literal("resource"),id:v.uuid()}),v.strictObject({type:v.literal("version"),id:v.uuid()})]),customerId:v.string().min(1).optional()}),response:z.extend({content:yc})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Bf,response:z.extend({paywall:qr})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:v.strictObject({...pi,selector:zm,customerId:v.string().min(1).optional(),commerce:si,requirement:or.optional()}),response:z.extend({offering:$m,candidates:v.array(cc).max(20),availability:v.array(v.strictObject({productVersionId:v.uuid(),available:v.boolean(),reason:v.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:kr.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:v.object({customerId:v.uuid().optional(),entityId:v.uuid().optional()}).strict(),response:z.extend({holdings:bp})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:v.object({customerId:v.uuid().optional(),query:Sp}).strict(),response:z.extend({ledger:Ip})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:gp.extend({customerId:v.uuid().optional()}),response:z.extend({detail:hp})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:ic.safeExtend({customerId:v.uuid().optional()}),response:z.extend({statement:yp})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:v.object({customerId:v.uuid().optional(),command:Ji.options[0]}).strict(),response:z.extend({quote:up})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:v.strictObject({customerId:v.uuid(),command:v.union([v.strictObject({eventName:v.string().min(1),quantity:Ae.optional(),properties:xt.optional(),entityId:v.uuid().optional(),idempotencyKey:v.string().min(1).max(120)}),v.strictObject({internal_feature_id:v.uuid(),quantity:Ae.optional(),properties:xt.optional(),entityId:v.uuid().optional(),idempotencyKey:v.string().min(1).max(120)})])}),response:z.extend({receipts:v.array(Zi).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:v.object({customerId:v.uuid(),command:Ji.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:z.extend({receipt:Zi})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:dg,response:z.extend({redemption:lg})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:fg,response:z.extend({referralCode:gg})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:pg,response:z.extend({checkout:mg})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:wp,response:z.extend({seats:sc})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Op,response:z.extend({seats:sc})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:T0,response:N0},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Jc,response:z.extend({customer:Ii})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:xf,response:z.extend(Sf.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:bf,response:z.extend(Af.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:v.object({customerId:v.uuid()}).strict(),response:z.extend(Yn.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:v.strictObject({}),response:z.extend(Yn.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:v.strictObject({customerId:v.uuid(),sessionId:v.uuid().optional()}),response:z.extend({revoked:v.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:v.strictObject({guestToken:v.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:qa.optional()}),response:z.extend({customerId:v.uuid(),guestToken:v.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:v.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:v.strictObject({guestToken:v.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:z.extend(Yn.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:v.strictObject({guestToken:v.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:v.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:v.uuid()}),response:z.extend({customer:Ii,switched:v.boolean(),replayed:v.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:v.strictObject({code:v.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:v.uuid()}),response:Dg()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:v.object({}).strict(),response:z.extend({offers:v.array(Li)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:v.object({customerId:v.string().min(1).max(255).optional(),couponId:v.uuid(),...pi,requestId:v.uuid(),couponContentDigest:v.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:Dg()},recordCouponRedemption:{method:"POST",path:"offers/redemptions",permission:"billing:write",audience:"server",request:Cg,response:z.extend({receipt:Pg})}},qj={recordBillingEvent:O.recordBillingEvent,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,recordCouponRedemption:O.recordCouponRedemption,redeemCoupon:O.redeemCoupon,redeemReward:O.redeemReward,createReferralCode:O.createReferralCode,claimRewardProduct:O.claimRewardProduct,readSeats:O.readSeats,manageSeat:O.manageSeat};import{z as Iu}from"zod";var bo=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function vu(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=>Xt(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 bo("Required GB Feature is unavailable");i=Ln(e.featureKey,t),o=i.value,Object.assign(r,di(e,{value:o})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new bo("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 bo("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:Ln(e.configuration.featureKey,t).value;o={type:"offering_version",id:Iu.uuid().parse(u)},Object.assign(r,di(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,di(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 Fg(e,t,n){Iu.uuid().parse(e),Iu.number().int().nonnegative().parse(t);let r=ei(ti(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 J}from"zod";var dr=J.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),D0=J.enum(["running","waiting","completed","closed","ineligible","failed"]),F0=J.discriminatedUnion("type",[Hc,J.strictObject({type:J.literal("wait"),receiptId:J.uuid(),kind:J.enum(["timer","event","operation"]),deadline:J.iso.datetime({offset:!0}).nullable(),eventName:dr.optional()}),J.strictObject({type:J.literal("open_url"),receiptId:J.uuid(),url:Zc,openIn:Wc}),J.strictObject({type:J.literal("event"),receiptId:J.uuid(),event:dr})]),Wa=J.strictObject({type:J.literal("funnel"),id:J.uuid(),versionId:J.uuid()}),M0={id:dr,presentation:Hn,outputs:J.array(dr).max(250),inputs:Ta,values:J.record(J.string(),xe).optional(),offeringKey:bt.optional(),capabilities:ci,customerData:Bp,dataCursors:J.record(dr,ja.nullable())},V0=J.strictObject({...M0,content:J.strictObject({type:J.literal("document"),document:cn})}),wu=J.strictObject({id:J.uuid(),source:Wa,revision:J.number().int().nonnegative(),visit:J.number().int().nonnegative(),nodeId:dr,nodeType:J.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:D0,stopped:J.boolean(),canBack:J.boolean(),authenticated:J.boolean(),locale:J.string().min(1).max(35),answers:cr,parameters:ur,variables:J.record(J.string(),xe),output:xe.nullable(),screen:V0.nullable(),paywall:J.strictObject({receiptId:J.uuid(),resolution:J.union([ho,qr]),quote:gi.nullable(),operation:hi.nullable(),purchaseRequestId:J.uuid().nullable(),selectionGeneration:J.number().int().nonnegative().optional(),canReselect:J.boolean().optional()}).nullable(),instruction:F0.nullable(),pendingRequest:J.strictObject({requestId:J.uuid(),authenticationRequired:J.boolean()}).nullable(),runExpiresAt:J.iso.datetime({offset:!0}),credentialExpiresAt:J.iso.datetime({offset:!0}).nullable()}),xo=J.strictObject({scope:et,run:wu,settlement:J.strictObject({requestId:J.uuid(),state:J.enum(["pending","unknown","settled"]),operationId:J.uuid().nullable(),receiptId:J.uuid().nullable().optional()}).optional(),purchase:J.strictObject({receiptId:J.uuid(),quote:gi.nullable(),operation:hi.nullable(),canReselect:J.boolean().optional()}).optional(),review:J.strictObject({activeOperationId:J.uuid().nullable(),pages:J.array(J.strictObject({receiptId:J.uuid(),nodeId:dr,visit:J.number().int().nonnegative()})).max(100),page:J.strictObject({receiptId:J.uuid(),nodeId:dr,visit:J.number().int().nonnegative(),document:cn,answers:cr,inputs:Ta,values:J.record(J.string(),xe).optional()}).nullable(),coupons:J.array(J.strictObject({grantId:J.uuid(),status:J.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:J.string().nullable()})).max(100),purchases:J.array(J.strictObject({receiptId:J.uuid(),operationId:J.uuid(),status:J.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:J.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:J.uuid().optional()}),Mg=xo.extend({run:wu.extend({paywall:wu.shape.paywall.unwrap().extend({resolution:qr}).nullable()})});var Vg="X-Indiana-Server-Key";import{z as Ne}from"zod";var Ci=Ne.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Bg=Ne.strictObject({entry:Ci,nodes:Ne.array(Ne.strictObject({id:Ci,type:Ne.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:Ne.record(Ne.string(),Ci),writes:Ne.record(bt,bt),resources:Ne.strictObject({screenId:Ci.optional(),paywallVersionId:Ne.uuid().optional(),couponId:Ne.uuid().optional(),couponIds:Ne.array(Ne.uuid()).max(20).optional(),experimentId:Ne.uuid().optional(),featureKey:Ne.string().optional(),offeringVersionId:Ne.uuid().optional()})})).min(1).max(500)}),qg={scope:et,funnelId:Ne.uuid(),versionId:Ne.uuid(),evaluationRevision:Ne.number().int().nonnegative(),expiresAt:Ne.iso.datetime({offset:!0}).nullable(),topology:Bg},Ya=Ne.discriminatedUnion("evaluationMode",[Ne.strictObject({...qg,evaluationMode:Ne.literal("local"),growth:yn,conditions:Ne.record(Ci,Ne.array(Ne.strictObject({condition:Wt,port:Ne.string()})))}),Ne.strictObject({...qg,evaluationMode:Ne.literal("remote")})]),q0=Ya.options[0].extend({evaluation:Ne.strictObject({maxTransitions:Ne.number().int().min(1).max(1e4),variables:Ne.record(bt,li),outputSchema:ui,terminals:Ne.record(Ci,Ne.strictObject({outcome:Ne.enum(["completed","closed","ineligible","failed"]),output:po.nullable()}))})});function B0(e){return Bg.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let n={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":n.next=t.next;break;case"screen":Object.assign(n,t.outputs),r.screenId=t.screenId;{let a=e.screens.find(o=>o.id===t.screenId);a?.type==="paywall"&&(r.paywallVersionId=a.paywallVersionId)}break;case"condition":t.cases.forEach((a,o)=>{n[`case:${o}`]=a.target}),n.default=t.default;break;case"split":Object.assign(n,t.routes),n.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let a of["success","cancel","unavailable","failure"])n[a]=t[a];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=Ne.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 Ou(e){let t=wi.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:B0(t)};return Ya.parse(e.evaluationMode==="remote"?r:{...r,growth:Qa(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 Ug(e){let t=Ou(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=wi.parse(e.document);return q0.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 nt}from"zod";var Lg=nt.string().regex(/^[a-f0-9]{64}$/),U0=Ea.omit({variations:!0,active:!0}).extend({changeId:Lg,variations:nt.array(nt.strictObject({urlRedirect:nt.string().max(2048)})).min(2).max(20)}),zg=nt.strictObject({environmentId:nt.uuid(),trackExposures:nt.boolean(),generation:Lg,experiments:nt.array(U0).max(100),savedGroups:Tc}),L0=nt.strictObject({eventUuid:nt.uuid(),timestamp:nt.iso.datetime({offset:!0}).optional(),deviceId:nt.string().min(1).max(128),sessionId:nt.string().min(1).max(128).optional(),url:nt.url().max(2048),pageTitle:nt.string().max(512).optional(),experimentKey:nt.string().min(1).max(255),variationKey:nt.string().min(1).max(64)}),xT=nt.strictObject({events:nt.array(L0).min(1).max(20)}),ST=nt.strictObject({inserted:nt.number().int().nonnegative(),duplicates:nt.number().int().nonnegative(),skipped:nt.number().int().nonnegative(),rejected:nt.array(nt.strictObject({index:nt.number().int().nonnegative(),reason:nt.string()}))});import{z as st}from"zod";var Cu=32,z0=522240;function Pu(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 $0=st.strictObject({nodeId:st.string().min(1).max(64),visit:st.number().int().nonnegative(),revision:st.number().int().nonnegative()}),_u=st.record(st.string(),xe),K0=st.strictObject({id:st.uuid(),nodeId:st.string().min(1).max(64),visit:st.number().int().nonnegative(),input:st.strictObject({schemaVersion:mo.shape.schemaVersion,kind:mo.shape.kind,selector:mo.shape.selector,contract:mo.shape.contract}),context:_u,removed:st.array(st.string()).max(100),attributes:_u,removedAttributes:st.array(st.string()).max(100),result:Pf,offeringVersionId:st.uuid().nullable(),events:st.strictObject({entered:st.string().regex(/^[1-9][0-9]{0,18}$/),decision:st.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),CT=st.strictObject({schemaVersion:st.literal(1),mode:st.enum(["local","remote"]),versionId:st.uuid(),generation:st.number().int().positive(),base:$0,context:_u,steps:st.array(K0).min(1).max(Cu)}).refine(e=>un(e)<=z0,"Segment exceeds its byte budget");var Eu=class extends Error{constructor(n,r){super(r);Ve(this,"code",n);this.name="FunnelLocalCalculationError"}},$g=(e,t)=>new Eu(e,t),G0=e=>({experiments:e.experiments,features:e.features});function H0(e,t=$g){let n=new Map(e.topology.nodes.map(o=>[o.id,o])),r=ni(e.growth.savedGroups),i=G0(e.growth);function a(o,s){if(!Object.hasOwn(e.growth.features,o))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Ln(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 x=e.conditions[c.id];if(!x)throw t("INVALID_RESPONSE","Local condition rules are unavailable");u=vu({id:c.id,name:c.id,type:"condition",cases:x.map(A=>({condition:A.condition,target:c.outputs[A.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 A=vu({id:c.id,name:c.id,type:"split",experimentId:c.resources.experimentId,routes:c.outputs,notParticipating:c.outputs.notParticipating},s,i.experiments);l=A.value,u=A.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 Q0(e,t){let n=Ya.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=H0(n,t);return(o,s)=>(i(),J0(a,o,s))}function J0(e,t,n){let r=St.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 Z0(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(xe.parse({key:s.key,variationId:c.variationId,keyUsed:c.key,hashAttribute:c.hashAttribute,hashValue:c.hashValue}))},onFeatureUsage(s,c){a.push(xe.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 Kg(e,t,n,r=$g){let i=n,a=new Map(t.graph.nodes.map(g=>[g.id,g])),o=structuredClone(n.variables),s=structuredClone(i.sticky),c=[],u=n.nodeId,l=n.visit,m=!1,x,A=g=>(x??(x=Q0(e,r)),Z0(x,g,{attributes:Lc({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:o,savedGroups:{}}),sticky:s}));for(let g=0;g<Cu;g++){let f=a.get(u);if(!f||!Pu(f))break;if(l>=t.execution.maxTransitions&&(l>t.execution.maxTransitions||f.type!=="end"&&f.type!=="output")){if(!c.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let I,y;if(["condition","feature","split"].includes(f.type)||f.type==="offering"&&f.configuration.source==="feature")I=A(f.id),f.type==="offering"&&(I.value={type:"offering_version",id:String(I.value)}),f.type==="condition"?y=I.port==="default"?f.default:f.cases[Number(I.port.slice(5))]?.target:f.type==="split"?y=I.port==="notParticipating"?f.notParticipating:f.routes[I.port]:(f.type==="feature"||f.type==="offering")&&(y=f.next);else if(I={port:"next",sticky:[],exposures:[],features:[]},(f.type==="entry"||f.type==="coupon"||f.type==="coupons")&&(y=f.next),f.type==="offering"&&f.configuration.source==="fixed"&&(I.value={type:"offering_version",id:f.configuration.versionId},y=f.next),f.type==="end"||f.type==="output"){let w=f.type==="end"?f.output:f.value;if(I=w?.type==="feature"?A(f.id):{...I,port:"value",value:w?.type==="literal"?w.value:w?.type==="variable"?fc({source:"variable",key:w.key,...w.path?{path:w.path}:{}},{declarations:t.variables,answers:n.answers,results:o,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},w&&(I.value===void 0||!hn(t.outputSchema,I.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let P=[...c,{nodeId:u,result:I}];if(un({steps:P})>6e4){if(!c.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(c.push({nodeId:u,result:I}),f.type==="feature"||f.type==="offering"||f.type==="coupon"||f.type==="coupons"){let w=f.type==="coupons"?f.couponIds.map(D=>({type:"reward",id:D})):f.type==="coupon"?{type:"reward",id:f.couponId}:I.value;if(w===void 0)throw r("INVALID_RESPONSE","Node output is missing");let k=di(f,{value:w});Gp(t.variables,f,k),Object.assign(o,k)}for(let w of I.sticky)s[`${w.next.attributeName}||${w.next.attributeValue}`]=structuredClone(w.next);if(f.type==="end"||f.type==="output"){m=!0;break}if(!y)throw r("INVALID_RESPONSE","Local pure exit is unavailable");u=y,l++}let p=a.get(u);return{steps:c,...!m&&p&&!Pu(p)?{boundary:{nodeId:u,visit:l}}:{}}}var b=class extends Error{constructor(n,r,i,a,o){super(r);Ve(this,"code",n);Ve(this,"status",i);Ve(this,"requestId",a);Ve(this,"retryable");Ve(this,"recovery");Ve(this,"retryAfterSeconds");Ve(this,"reason");this.name="IndianaError",this.reason=o?.reason;let s=ko(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 So=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new b("INVALID_STATE","Installation sequence exhausted");return e+1},W0=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 Jn(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 Gg(e,t,n){let r=null,i=0,a=0,o=0,s=Promise.resolve();if(e&&(!n||et.parse(e.scope).projectId!==n.projectId||e.scope.environment!==n.environment))throw new b("SCOPE_MISMATCH","Push installation belongs to another scope");let c=()=>{if(!e)throw new b("NOT_CONFIGURED","Configure this client's native Push host first");return e},u=y=>{if(y!==i)throw new b("IDENTITY_CHANGED","Identity changed during Push operation")};async function l(y){let P=c();if(!P.sha256&&!globalThis.crypto?.subtle)throw new b("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let w=P.sha256?await P.sha256(Uint8Array.from(y,k=>k.charCodeAt(0))):await W0(y);if(!/^[a-f0-9]{64}$/.test(w))throw new b("INVALID_STATE","Push credential digest is invalid");return w}function m(y){let P=vr.parse(y);if(P.installationId.toLowerCase()!==c().installationId.toLowerCase())throw new b("INVALID_RESPONSE","Push response belongs to another installation");return P}async function x(y,P){let w=c(),k={installationId:w.installationId,publicKey:w.publicKey,issuedAt:new Date().toISOString(),...P},D=await w.sign(Sl(y,w.scope,k));return{...k,signature:D}}let A=(y,P,w)=>t.requestWithCredential?t.requestWithCredential(y,P,w):t.request(y,P);async function p(){let y=c(),P=i,w=r?await(t.session?.access()??r):null,k=Jn(y,Oe=>Oe),D;if(k.detachSeq!==null){let Oe=k.detachSeq,qe=Al.parse(await x("detach",{sequence:Oe,platform:y.platform}));try{let je=await t.request("push/installations/detach",{...y.scope,...qe},"POST",{installationDetach:!0});if(!je||typeof je!="object"||!("installation"in je))throw new b("INVALID_RESPONSE","Push detach acknowledgement is invalid");let Ht=m(je.installation);if(Ht.bound||Ht.identitySeq!==Oe)throw new b("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(je){if(je instanceof b&&je.status===404)D=je;else if(!(je instanceof b)||je.status!==412)throw je}D||Jn(y,je=>({...je,detachSeq:je.detachSeq===Oe?null:je.detachSeq}))}if(u(P),!w){if(D)throw D;return null}let L=O.bindPushInstallation,he=L.request.parse(await x("bind",{sequence:o,platform:y.platform,credentialDigest:await l(w)}));u(P);let we=L.response.parse(await A(L.path,he,w));u(P);let Re=m(we.installation);if(!Re.bound||Re.identitySeq!==o)throw new b("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return D&&k.detachSeq!==null&&o>k.detachSeq&&Jn(y,Oe=>({...Oe,detachSeq:Oe.detachSeq===k.detachSeq?null:Oe.detachSeq})),Re}async function g(){c();let y=i,P=r?await(t.session?.access()??r):null;if(!P)throw new b("NOT_IDENTIFIED","Identify before reading this installation");let w=O.readPushInstallation,k=w.request.parse(await x("read",{credentialDigest:await l(P)}));u(y);let D=w.response.parse(await A(w.path,k,P));return u(y),m(D.installation)}function f(y=p){let P=s.catch(()=>{}).then(y);return s=P,P.catch(w=>{try{e?.onError?.(w instanceof Error?w:new Error("Push synchronization failed"))}catch{}}),P}async function I(y,P,w){let k=c(),D=P.identity,L=P.observation,he=r?await(t.session?.access()??r):null;if(u(D),L!==a)throw new b("INVALID_STATE","Push observation changed during recovery");if(!he)throw new b("NOT_IDENTIFIED","Identify before recovering a Push address");if(!y.connectionId||!y.kind||!y.token||!["granted","provisional"].includes(y.permission))throw new b("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await f(async()=>{if(u(D),await p(),u(D),L!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let we=Jn(k,Ht=>w?Ht:{...Ht,addressSeq:So(Ht.addressSeq)}),Oe=await x(w?"recovery_confirm":"recovery_request",{...y,sequence:we.addressSeq,credentialDigest:await l(he),...w?{challenge:w}:{}}),qe=w?xl.parse(Oe):bl.parse(Oe);if(u(D),L!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let je=await A(`push/installations/recovery/${w?"confirm":"request"}`,qe,he);if(u(D),L!==a||Jn(k,Ht=>Ht).addressSeq!==we.addressSeq)throw new b("INVALID_STATE","Push observation changed during recovery");if(w){let Ht=O.updatePushAddress.response.parse(je),Xe=m(Ht.installation);if(!Xe.bound||Xe.identitySeq!==o||Xe.addressSeq!==we.addressSeq||Xe.connectionId!==y.connectionId||Xe.addressStatus!=="active")throw new b("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return Xe}if(!je||typeof je!="object"||!("recovery"in je))throw new b("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return As.parse(je.recovery)})}return{recoveryObserver(){c();let y={identity:i,observation:++a};return{async request(P){return As.parse(await I(P,y))},async confirm(P,w){return vr.parse(await I(w,y,P))}}},identify(y){if(!e)return;o=Jn(e,w=>({...w,identitySeq:So(w.identitySeq)})).identitySeq,r=y,i++,a++},reset(){if(e)try{Jn(e,y=>{let P=So(y.identitySeq);return{...y,identitySeq:P,detachSeq:P}})}finally{r=null,i++,a++}},start(){e&&f()},async sync(){return await f()},read:g,async recover(){let y=c(),P=i,w=o;return a++,await f(async()=>{u(P);let k=await g();return u(P),o=Jn(y,L=>{if(L.identitySeq!==w)throw new b("IDENTITY_CHANGED","A newer installation intent exists");return{...L,identitySeq:So(Math.max(L.identitySeq,k.identitySeq)),addressSeq:Math.max(L.addressSeq,k.addressSeq)}}).identitySeq,await p()})},tokenObserver(){c();let y=++a,P=i;return async w=>{if(y!==a||P!==i)return null;let k=c(),D=r?await(t.session?.access()??r):null;if(!D)throw new b("NOT_IDENTIFIED","Identify before registering a Push token");if(await f(),u(P),y!==a)return null;let L=Jn(k,Oe=>({...Oe,addressSeq:So(Oe.addressSeq)})),he=O.updatePushAddress,we=he.request.parse(await x("address",{...w,sequence:L.addressSeq,credentialDigest:await l(D)}));if(u(P),y!==a)return null;let Re=he.response.parse(await A(he.path,we,D));return u(P),m(Re.installation)}}}}function Hg(e,t){return{messaging:{async preference(n){let r=O.readMessagingPreference;return r.response.parse(await e(r.path,r.request.parse({channel:n}))).preference},async setPreference(n){let r=O.setMessagingPreference;return r.response.parse(await e(r.path,r.request.parse(n))).preference}},push:{sync:t.sync,read:t.read,recover:t.recover,tokenObserver:t.tokenObserver,recoveryObserver:t.recoveryObserver,async preference(){let n=O.readMessagingPreference;return n.response.parse(await e(n.path,{channel:"push"})).preference},async setPreference(n){let r=O.setMessagingPreference;return r.response.parse(await e(r.path,r.request.parse({...n,channel:"push"}))).preference}}}}var Qg={name:"@tinkerlandai/longplay-sdk",version:"0.10.5",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",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 He(e){return typeof e=="string"?e:String(e)}var X0=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function eI(e){return e.replace(X0,"$1\uFFFD")}function Tu(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 rh(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 Jg(e){let t;if(Array.isArray(e)){let n=e.map(He);if(n.length===2)return n}else if((t=rh(e))!=null){let n=Tu(t.next()),r=Tu(t.next());if(!n.done&&!r.done)return[He(n.value),He(r.value)]}throw new TypeError("Each query pair must be an iterable [name, value] tuple")}var Zg="0123456789ABCDEF",tI=/(?:%[0-9A-Fa-f]{2})+/g;function Dn(e){return`%${Zg[e>>4&15]}${Zg[15&e]}`}function ih(e,t,n=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?n&&e===32?"+":t(e)?Dn(e):String.fromCharCode(e):e<=2047?Dn(192|e>>6)+Dn(128|63&e):e<=65535?Dn(224|e>>12)+Dn(128|e>>6&63)+Dn(128|63&e):Dn(240|e>>18)+Dn(128|e>>12&63)+Dn(128|e>>6&63)+Dn(128|63&e)}function Nu(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function Du(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(tI,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function wo(e){return e<=31||e>126}function nI(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return wo(e)}}function Lu(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return wo(e)}}function rI(e){return Lu(e)||e===39}function Fu(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return Lu(e)}}function rs(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 Fu(e)}}function Wg(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 rs(n)}})(e)}}function oh(e,t){return ih(e=e||0,t)}function Fn(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+=ih(o,t,n)}return i}function zu(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([Du(i.slice(0,a),!0),Du(i.slice(a+1),!0)])}if(n=r+1,r===e.length)break}return t}function Mu(e){let t="";for(let n=0;n<e.length;n++){let r=Fn(e[n][0],Wg,!0),i=Fn(e[n][1],Wg,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var iI=[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],oI=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],aI=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],sI=[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 cI(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[uI,lI,dI,Yg]=[[[],"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 pI(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 ah(e,t){for(let n=0;n<e.length;n+=2)if(t>=e[n]&&t<=e[n+1])return!0;return!1}function Io(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 mI(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&&ah(sI,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&Io(Yg,t[i]);)i--;let a=n+1;for(;a<t.length&&Io(Yg,t[a]);)a++;if(!(i>=0&&a<t.length&&Io(lI,t[i])&&Io(dI,t[a])))return!1}return!0}var fI=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,gI=/\p{Script=Latin}/u;function hI(e){return!fI.test(e)||!gI.test(e)}var pr=36,es=1,Vu=26,yI=38,AI=700,bI=72,xI=128,SI=2147483647;function Xg(e){return String.fromCharCode(e+22+75*+(e<26))}function II(e,t,n){let r=0;for(e=n?Math.floor(e/AI):e>>1,e+=Math.floor(e/t);e>(pr-es)*Vu>>1;r+=pr)e=Math.floor(e/(pr-es));return Math.floor(r+(pr-es+1)*e/(e+yI))}function vI(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=xI,o=0,s=bI;for(;r<t.length;){let c=SI;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 x=pr;;x+=pr){let A=x<=s?es:x>=s+Vu?Vu:x-s;if(m<A)break;n+=Xg(A+(m-A)%(pr-A)),m=Math.floor((m-A)/(pr-A))}n+=Xg(m),s=II(o,r+1,r===i),o=0,r++}}o++,a++}return n}function Ru(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=Nu(e.charCodeAt(r));if(i>=t||i<0)return-1;n=n*t+i}return n}function eh(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function sh(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function ch(e){return e.length===2&&sh(e.codePointAt(0),e.codePointAt(1))}function th(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function dt(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function uh(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function qu(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=Nu(c[s]))>=0;)l=(l<<4)+u,s++,m++;if(c[s]===46){if(m===0||o>6)return null;s-=m;let x=0;for(;c[s]!==void 0;){let A=0;if(x>0)if(c[s]===46&&x<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(A=10*A+Nu(c[s]),A>255)return null;s++}i[o]=256*i[o]+A,x++,x%2==0&&o++}if(x!==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 th(r)?null:Fn(r,wo)})(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)&&!ah(iI,m)||Io(uI,m))return!0}return!1})(i))return null;let s=(i=(function(u){let l="";for(let m of u){let x=m.codePointAt(0);if(x!==8204&&x!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(m))continue;let A=pI(m,x);if(A){l+=A;continue}let p=oI.indexOf(x);l+=p<0?m:aI[p]}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(cI(u)||l&&(/^\p{Mark}/u.test(u)||!mI(u)||!hI(u)||u.startsWith("xn--")))return null;l&&(s[c]=`xn--${vI(u)}`)}return(i=s.join("."))!==""?i:null})(e.indexOf("%")===-1?e:Du(e));return n===null||th(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(Ru(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=Ru(a[u]);if(l<0||l>255)return null;s+=l*(1<<8*(3-u))}let c=Ru(a[o-1]);return c<0||c>=256**(5-o)?null:(s+=c,s)})(n):n}}function Bu(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 x=0;x<s.length;++x)s[x]!==0?(m>l&&(c=u,l=m),u=-1,m=0):(u===-1&&(u=x),++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 lh(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 dh(e){return e.username!==""||e.password!==""}function ku(e){return e.host===null||e.host===""||e.scheme==="file"}var C=0,B="",Ie="",Le=null,U,ts=!1,ns=!1,$r=!1,pt;function mn(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),C=0,B=e,Ie="",Le=n||null,U=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},ts=!1,ns=!1,$r=!1,pt=r||0;let i=wI;switch(r){case 3:case 4:i=is;break;case 5:i=Ku;break;case 6:i=Kr;break;case 7:i=mr;break;case 8:i=Mn}return i(Q(e,C))!==1?U:null}function ee(e,t){return C+=C===e?Rn(t):1,C<=B.length}function Q(e,t){return t<e.length?e.codePointAt(t):void 0}function Rn(e){return e!=null&&e>65535?2:1}function ph(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var wI=e=>{let t=C;if(e!=null&&(e>=65&&e<=90||e>=97&&e<=122)){let n=C+1;for(e=B.charCodeAt(n);e===43||e===45||e===46||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57;)n++,e=B.charCodeAt(n);return Ie=B.slice(C,n).toLowerCase(),C=n,OI(n<B.length?e:void 0)}else return pt?1:(--C,ee(t,e)?mh(Q(B,C)):0)},OI=e=>{let t=C;if(e===58){if(pt){if(dt(U.scheme)!==dt(Ie))return 0;if((dh(U)||U.port!==null)&&Ie==="file")return 0;if(U.scheme==="file"&&U.host==="")return 0}return U.scheme=Ie,pt?(U.port===uh(U.scheme)&&(U.port=null),0):(Ie="",U.scheme==="file"?ee(t,e)?Gu(Q(B,C)):0:dt(U.scheme)&&Le!==null&&Le.scheme===U.scheme?ee(t,e)?_I(Q(B,C)):0:dt(U.scheme)?ee(t,e)?PI(Q(B,C)):0:Q(B,C+1)===47?(C++,ee(t,e)?CI(Q(B,C)):0):(U.path=[""],U.opaquePath=!0,ee(t,e)?gh(Q(B,C)):0))}else return pt?1:(Ie="",C=-1,ee(t,e)?mh(Q(B,C)):0)},mh=e=>{let t=C;return Le===null||Le.opaquePath&&e!==35?1:Le.opaquePath&&e===35?(U.scheme=Le.scheme,U.path=Le.path.slice(),U.opaquePath=Le.opaquePath,U.query=Le.query,U.fragment="",ee(t,e)?Mn(Q(B,C)):0):Le.scheme==="file"?(C--,ee(t,e)?Gu(Q(B,C)):0):(C--,ee(t,e)?$u(Q(B,C)):0)},_I=e=>{let t=C;return e===47&&Q(B,C+1)===47?(++C,ee(t,e)?as(Q(B,C)):0):(C--,ee(t,e)?$u(Q(B,C)):0)},CI=e=>{let t=C;return e===47?ee(t,e)?Pi(Q(B,C)):0:(C--,ee(t,e)?kn(Q(B,C)):0)},$u=e=>{let t=C;return U.scheme=Le.scheme,e===47||dt(U.scheme)&&e===92?ee(t,e)?nh(Q(B,C)):0:(U.username=Le.username,U.password=Le.password,U.host=Le.host,U.port=Le.port,U.path=Le.path.slice(),U.query=Le.query,e===63?(U.query="",ee(t,e)?mr(Q(B,C)):0):e===35?(U.fragment="",ee(t,e)?Mn(Q(B,C)):0):e!=null?(U.query=null,U.path.pop(),C--,ee(t,e)?kn(Q(B,C)):0):ee(t,e)?$u(Q(B,C)):0)},nh=e=>{let t=C;return dt(U.scheme)&&(e===47||e===92)?ee(t,e)?as(Q(B,C)):0:e===47?ee(t,e)?Pi(Q(B,C)):0:(U.username=Le.username,U.password=Le.password,U.host=Le.host,U.port=Le.port,C--,ee(t,e)?kn(Q(B,C)):0)},PI=e=>{let t=C;return e===47&&Q(B,C+1)===47?C++:C--,ee(t,e)?as(Q(B,C)):0},as=e=>{let t=C;return e!==47&&e!==92?(C--,ee(t,e)?Pi(Q(B,C)):0):ee(t,e)?as(Q(B,C)):0},Pi=e=>{let t=C;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!dt(U.scheme))){let n=C+Rn(e);for(;n<B.length;){let r=Q(B,n);if(r==null||r===64||r===35||r===47||r===63||r===92&&dt(U.scheme))break;n+=Rn(r)}return Ie+=B.slice(C,n),C=n-1,ee(t,e)?Pi(Q(B,C)):0}if(e===64){ts&&(Ie=`%40${Ie}`),ts=!0;for(let n=0;n<Ie.length;n++){let r=Ie.codePointAt(n);if(r===58&&!ns){ns=!0;continue}let i=oh(r,rs);ns?U.password+=i:U.username+=i,r!=null&&r>65535&&n++}return Ie="",ee(t,e)?Pi(Q(B,C)):0}else return e==null||e===35||e===47||e===63||e===92&&dt(U.scheme)?ts&&Ie===""?1:(C-=Ie.length+1,Ie="",ee(t,e)?is(Q(B,C)):0):(Ie+=ph(e),ee(t,e)?Pi(Q(B,C)):0)},is=e=>{let t=C;if(pt&&U.scheme==="file")return C--,ee(t,e)?Hu(Q(B,C)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!dt(U.scheme))){let n=C+Rn(e);for(e===91?$r=!0:e===93&&($r=!1);n<B.length;){let r=Q(B,n);if(r==null||!$r&&r===58||r===35||r===47||r===63||r===92&&dt(U.scheme))break;r===91?$r=!0:r===93&&($r=!1),n+=Rn(r)}return Ie+=B.slice(C,n),C=n-1,ee(t,e)?is(Q(B,C)):0}else if(e===58&&!$r){if(Ie===""||pt===4)return 1;let n=qu(Ie,!dt(U.scheme));return n===null?1:(U.host=Bu(n),Ie="",ee(t,e)?Ku(Q(B,C)):0)}else if(e==null||e===35||e===47||e===63||e===92&&dt(U.scheme)){if(C--,dt(U.scheme)&&Ie==="")return 1;if(pt&&Ie===""&&(dh(U)||U.port!==null))return 1;let n=qu(Ie,!dt(U.scheme));return n===null?1:(U.host=Bu(n),Ie="",pt?0:ee(t,e)?Kr(Q(B,C)):0)}else return Ie+=ph(e),ee(t,e)?is(Q(B,C)):0},Ku=e=>{let t=C;if(e!=null&&e>=48&&e<=57){let n=C+1;for(;n<B.length;){let r=B.charCodeAt(n);if(r<48||r>57)break;n++}return Ie+=B.slice(C,n),C=n-1,ee(t,e)?Ku(Q(B,C)):0}else if(pt||e==null||e===35||e===47||e===63||e===92&&dt(U.scheme)){if(Ie!==""){let n=parseInt(Ie,10);if(n>65535)return 1;if(U.port=n===uh(U.scheme)?null:n,Ie="",pt)return 0}return pt?1:(C--,ee(t,e)?Kr(Q(B,C)):0)}else return 1};function fh(e,t){let n=e.length-t;if(n<2)return!1;if(sh(Q(e,t),Q(e,t+1))){if(n===2)return!0;{let r=Q(e,t+2);return r===47||r===92||r===63||r===35}}else return!1}var Gu=e=>{let t=C;return U.scheme="file",U.host="",e===47||e===92?ee(t,e)?EI(Q(B,C)):0:Le?.scheme==="file"?(U.host=Le.host,U.path=Le.path.slice(),U.opaquePath=Le.opaquePath,U.query=Le.query,e===63?(U.query="",ee(t,e)?mr(Q(B,C)):0):e===35?(U.fragment="",ee(t,e)?Mn(Q(B,C)):0):e!=null?(U.query=null,fh(B,C)?U.path=[]:lh(U),C--,ee(t,e)?kn(Q(B,C)):0):ee(t,e)?Gu(Q(B,C)):0):(C--,ee(t,e)?kn(Q(B,C)):0)},EI=e=>{let t=C;return e===47||e===92?ee(t,e)?Hu(Q(B,C)):0:(Le!==null&&Le.scheme==="file"&&(!fh(B,C)&&(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])&&U.path.push(Le.path[0]),U.host=Le.host),C--,ee(t,e)?kn(Q(B,C)):0)},Hu=e=>{let t=C;if(e!=null&&e!==47&&e!==92&&e!==63&&e!==35){let n=C+Rn(e);for(;n<B.length;){let r=Q(B,n);if(r==null||r===47||r===92||r===63||r===35)break;n+=Rn(r)}return Ie+=B.slice(C,n),C=n-1,ee(t,e)?Hu(Q(B,C)):0}else if(e==null||e===47||e===92||e===63||e===35){if(C--,!pt&&ch(Ie))return ee(t,e)?kn(Q(B,C)):0;if(Ie==="")return U.host="",pt?0:ee(t,e)?Kr(Q(B,C)):0;{let n=qu(Ie,!dt(U.scheme));return n===null?1:(n==="localhost"&&(n=""),U.host=Bu(n),Ie="",pt?0:ee(t,e)?Kr(Q(B,C)):0)}}return 1},Kr=e=>{let t=C;return dt(U.scheme)?(e!==92&&e!==47&&C--,ee(t,e)?kn(Q(B,C)):0):!pt&&e===63?(U.query="",ee(t,e)?mr(Q(B,C)):0):!pt&&e===35?(U.fragment="",ee(t,e)?Mn(Q(B,C)):0):e!=null?(e!==47&&C--,ee(t,e)?kn(Q(B,C)):0):(pt&&U.host===null&&U.path.push(""),ee(t,e)?Kr(Q(B,C)):0)},kn=e=>{let t=C;if(e!=null&&e!==47&&(!dt(U.scheme)||e!==92)&&(pt||e!==63&&e!==35)){let n=C+Rn(e);for(;n<B.length;){let r=Q(B,n);if(r==null||r===47||dt(U.scheme)&&r===92||!pt&&(r===63||r===35))break;n+=Rn(r)}Ie+=Fn(B.slice(C,n),Fu),C=n,e=Q(B,n)}if(e==null||e===47||dt(U.scheme)&&e===92||!pt&&(e===63||e===35)){let n=dt(U.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}})(Ie)?(lh(U),e!==47&&!n&&U.path.push("")):eh(Ie)&&e!==47&&!n?U.path.push(""):eh(Ie)||(U.scheme==="file"&&U.path.length===0&&ch(Ie)&&(Ie=`${Ie[0]}:`),U.path.push(Ie)),Ie="",e===63?(U.query="",ee(t,e)?mr(Q(B,C)):0):e===35?(U.fragment="",ee(t,e)?Mn(Q(B,C)):0):ee(t,e)?kn(Q(B,C)):0}else return Ie+=oh(e,Fu),ee(t,e)?kn(Q(B,C)):0},gh=e=>{let t=C;if(e===63)return U.query="",ee(t,e)?mr(Q(B,C)):0;if(e===35)return U.fragment="",ee(t,e)?Mn(Q(B,C)):0;if(e!=null){let n=C+Rn(e);for(;n<B.length;){let i=Q(B,n);if(i===63||i===35)break;n+=Rn(i)}let r=B.slice(C,n);if(n<B.length&&r.charCodeAt(r.length-1)===32?U.path[0]+=Fn(r.slice(0,-1),wo)+"%20":U.path[0]+=Fn(r,wo),C=n,(e=Q(B,n))===63)return U.query="",ee(t,e)?mr(Q(B,C)):0;if(e===35)return U.fragment="",ee(t,e)?Mn(Q(B,C)):0}return ee(t,e)?gh(Q(B,C)):0},mr=e=>{let t=C,n=C;if(e!=null){if(pt)n=B.length;else{let i=B.indexOf("#",C);n=i===-1?B.length:i}let r=dt(U.scheme)?rI:Lu;U.query+=Fn(B.slice(C,n),r)}return C=n,Q(B,n)===35&&!pt?(U.fragment="",ee(t,e)?Mn(Q(B,C)):0):ee(t,e)?mr(Q(B,C)):0},Mn=e=>{let t=C;return e!=null&&(U.fragment+=Fn(B.slice(C),nI),C=B.length),ee(t,e)?Mn(Q(B,C)):0};function Uu(e){if(e.opaquePath)return e.path[0];{let t="";for(let n of e.path)t+=`/${n}`;return t}}function hh(e){switch(e.scheme){case"blob":{let t=mn(Uu(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":hh(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 Ge=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=He(t),n!=null&&(n=He(n));let r=null;if(n!=null&&(r=mn(n,null,null,0),r==null))throw new TypeError(`Invalid base URL: ${n}`);let i=mn(t,null,r,0);if(i==null)throw new TypeError(`Invalid URL: ${t}`);this[Ge]={url:i,query:null}}static createObjectURL(t){throw new TypeError("URL.createObjetURL is unsupported")}static revokeObjectURL(t){}static parse(t,n){t=He(t),n!==void 0&&(n=He(n));try{return new e(t,n)}catch{return null}}static canParse(t,n){t=He(t),n!==void 0&&(n=He(n));let r=null;return n!=null&&(r=mn(n,null,null,0),r==null)?!1:mn(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+=Uu(n),n.query!==null&&(r+=`?${n.query}`),n.fragment!==null&&(r+=`#${n.fragment}`),r})(this[Ge].url)}set href(t){let n=mn(t=He(t),null,null,0);if(n==null)throw new TypeError(`Invalid URL: ${t}`);this[Ge].url=n,this[Ge].query&&ju(this[Ge].query,n.query)}get origin(){return hh(this[Ge].url)}get protocol(){return`${this[Ge].url.scheme}:`}set protocol(t){mn(`${t=He(t)}:`,this[Ge].url,null,2)}get username(){return this[Ge].url.username}set username(t){t=He(t),ku(this[Ge].url)||(function(r,i){r.username=Fn(i,rs)})(this[Ge].url,t)}get password(){return this[Ge].url.password}set password(t){t=He(t),ku(this[Ge].url)||(function(r,i){r.password=Fn(i,rs)})(this[Ge].url,t)}get host(){let{url:t}=this[Ge];return t.host==null?"":t.port==null?t.host:`${t.host}:${t.port}`}set host(t){t=He(t),this[Ge].url.opaquePath||mn(t,this[Ge].url,null,3)}get hostname(){let{url:t}=this[Ge];return t.host!=null?t.host:""}set hostname(t){t=He(t),this[Ge].url.opaquePath||mn(t,this[Ge].url,null,4)}get port(){let{url:t}=this[Ge];return t.port!=null?`${t.port}`:""}set port(t){t=He(t);let{url:n}=this[Ge];ku(n)||(t?mn(t,n,null,5):n.port=null)}get pathname(){return Uu(this[Ge].url)}set pathname(t){t=He(t);let{url:n}=this[Ge];n.opaquePath||(n.path=[],mn(t,n,null,6))}get search(){let{url:t}=this[Ge];return t.query?`?${t.query}`:""}set search(t){t=He(t);let{url:n,query:r}=this[Ge];if(!t)n.query=null,r&&ju(r,null);else{let i=t[0]==="?"?t.substring(1):t;n.query="",mn(i,n,null,7),r&&ju(r,n.query)}}get searchParams(){let t=this[Ge],n=t.query;return n==null&&(n=t.query=(function(i,a){let o=new os;return o[it].url=i,o[it].serialized=a==null,a&&(o[it].list=zu(a)),o})(this,t.url.query)),n}get hash(){let{url:t}=this[Ge];return t.fragment?`#${t.fragment}`:""}set hash(t){t=He(t);let{url:n}=this[Ge];if(!t)n.fragment=null;else{let r=t[0]==="#"?t.substring(1):t;n.fragment="",mn(r,n,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(xn.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var it=Symbol("URLSearchParamsImpl"),RI=Symbol.dispose||Symbol.for("dispose");function ju(e,t){t?e[it].list=zu(t):e[it].list.length=0,e[it].serialized=t==null}function Xa(e){if(e.url){let t=Mu(e.list);(function(r,i){r[Ge].url.query=i})(e.url,t||null),e.serialized=!0}}var kI=typeof Iterator<"u"?Iterator:Object,vo=class extends kI{constructor(t,n){super(),this[it]={ptr:t,map:n,index:0}}next(){let t=this[it];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}[RI](){}},os=class{constructor(t){let n=this[it]={list:[],url:null,serialized:!0},r;if(Array.isArray(t))for(let i=0;i<t.length;i++)n.list.push(Jg(t[i]));else if((r=rh(t))!=null){let i;for(;!(i=Tu(r.next())).done;)n.list.push(Jg(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=eI(o),c=He(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=He(t);i=i[0]==="?"?i.substring(1):i,n.list=zu(i)}}get size(){return this[it].list.length}append(t,n){t=He(t),n=He(n),this[it].list.push([t,n]);let r=this[it];r.url&&r.serialized?(function(a,o){let s=a[Ge].url;s.query=s.query?`${s.query}&${o}`:o})(r.url,Mu([[t,n]])):Xa(r)}delete(t,n){t=He(t),n=n!=null?He(n):void 0;let{list:r}=this[it],i=0;for(;i<r.length;)r[i][0]===t&&(n==null||r[i][1]===n)?r.splice(i,1):i++;Xa(this[it])}get(t){t=He(t);let{list:n}=this[it];for(let r=0;r<n.length;r++)if(n[r][0]===t)return n[r][1];return null}getAll(t){t=He(t);let n=[],{list:r}=this[it];for(let i=0;i<r.length;i++)r[i][0]===t&&n.push(r[i][1]);return n}has(t,n){t=He(t),n=n!=null?He(n):void 0;let{list:r}=this[it];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=He(t),n=He(n);let{list:r}=this[it],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&&Xa(this[it])}sort(){this[it].list.sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0),Xa(this[it])}forEach(t,n){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:r}=this[it];for(let i=0;i<r.length;i++)t.call(n,r[i][1],r[i][0],this)}entries(){return new vo(this[it],t=>t)}keys(){return new vo(this[it],t=>t[0])}values(){return new vo(this[it],t=>t[1])}toString(){return Mu(this[it].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(os.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var fr="https://api.longplayai.com";function yh(e){let t,n,r=0,i,a=new Map,o=()=>{for(let m of[...a.keys()])try{m()}catch{}};function s(m,x){let A=++r;i=void 0,t=void 0,n=void 0;for(let p of[...a.values()])try{p?.()}catch{}A===r&&(t=m,n=x,o())}let c=()=>s();function u(m,x=!1){let A=Yn.safeParse(m);if(!A.success||x&&Date.parse(A.data.expiresAt)<=Date.now()||Date.parse(A.data.refreshExpiresAt)<=Date.now()||Date.parse(A.data.refreshExpiresAt)<Date.parse(A.data.expiresAt))throw new b("INVALID_RESPONSE","Invalid customer session credentials");return A.data}async function l(){if(i)return i;let m=t,x=r;if(!m||Date.parse(m.refreshExpiresAt)<=Date.now())throw m&&c(),new b("UNAUTHENTICATED","Customer authentication is required",401);let A=(async()=>{try{let p=await e(m.refreshToken);if(x!==r)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");let g=u(p,!0);if(g.customerId!==m.customerId||g.sessionId!==m.sessionId)throw new b("SCOPE_MISMATCH","Refresh changed the customer session");return t=g,n=g.accessToken,{...g}}catch(p){throw x!==r?new b("IDENTITY_CHANGED","Customer identity changed during refresh"):(p instanceof b&&p.status===401&&c(),p)}})();i=A;try{return await A}finally{i===A&&(i=void 0)}}return{identify(m){let x=typeof m=="string"?void 0:u(m),A=typeof m=="string"?m:x.accessToken;if(!A.trim()||/\s/.test(A)||A.length>4096)throw new b("INVALID_TOKEN","A server-issued token is required");s(x,A)},reset:c,subscribeIdentity(m,x){return a.set(m,x),()=>{a.delete(m)}},access(){if(t&&Date.parse(t.expiresAt)<=Date.now()+3e4)return l().then(()=>{if(!n)throw new b("NOT_IDENTIFIED","Customer authentication is required");return n});if(!n)throw new b("NOT_IDENTIFIED","Identify a customer session before making a request");return n},peek:()=>n,snapshot:()=>t&&{...t},refresh:l}}var Ah=Symbol("IndianaNoContent");function gr(e,t,n=xn){let r=e.configuration?.scope,i=e.scope??(r&&{projectId:r.projectId,environment:r.environment}),a=i?et.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??fr);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=null,l=0,m=null,x=new Set,A=e.session??yh(async y=>{let P=await I("customer-sessions/refresh",{},"POST",{},y);if(!P||typeof P!="object")throw new b("INVALID_RESPONSE","Invalid refresh response");let{requestId:w,scope:k,...D}=P;return D});function p(){l+=1,u=null,m=null;for(let y of x)y.abort();x.clear()}let g=A.subscribeIdentity(p);function f(){A.reset()}async function I(y,P={},w="POST",k={},D){let L=k.installationDetach===!0;if(L&&(y!=="push/installations/detach"||w!=="POST"))throw new b("INVALID_REQUEST","Installation authority only detaches this installation");if(!D&&!u&&!L)throw new b("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let he=l,we=new AbortController;L||x.add(we);let Re=()=>!L&&he!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new b("TIMEOUT","Longplay request timed out"),Oe,qe=new Promise((Xe,Ft)=>{Oe=()=>Ft(Re()),we.signal.addEventListener("abort",Oe,{once:!0})}),je=setTimeout(()=>we.abort(),c),Ht=async()=>{let Xe=await s(`${o.href.replace(/\/$/,"")}/api/v1/${y}`,{method:w,headers:{"Content-Type":"application/json",...L?{}:{Authorization:`Bearer ${D??u}`},[vs]:ws.current,[_l]:Qg.version,...a?{"X-Indiana-Project":a.projectId,"X-Indiana-Environment":a.environment}:{}},body:w==="POST"?JSON.stringify(P):void 0,signal:we.signal,credentials:"omit",cache:"no-store",redirect:"error",...k.keepalive?{keepalive:!0}:{}});if(we.signal.aborted)throw Re();let Ft;try{Ft=Xe.status===204?Ah:await Xe.json()}catch{throw we.signal.aborted?Re():new b(Xe.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",Xe.status,Xe.headers.get("X-Request-Id")??void 0)}if(we.signal.aborted)throw Re();if(!L&&he!==l)throw new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!Xe.ok){let ut=Is.safeParse(Ft),Qt=ut.success&&(!Bn.safeParse(ut.data.error.code).success||wl(ut.data.error.code,Xe.status)),br=Qt?ut.data.error.code:"HTTP_ERROR",xr=ko(br,Xe.status,{retryAfter:Xe.headers.get("Retry-After"),recovery:Qt?ut.data.error.recovery:void 0,reason:Qt?ut.data.error.reason:void 0});throw new b(br,Qt?ut.data.error.message:"Longplay request failed",Xe.status,Xe.headers.get("X-Request-Id")??(ut.success?ut.data.requestId:void 0),{...xr,...ut.success&&ut.data.error.retryable===!1?{retryable:!1}:{},...xr.retryAfterSeconds===void 0&&ut.success&&ut.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:ut.data.error.retryAfterSeconds}:{}})}if(Xe.headers.get(vs)!==ws.current)throw new b("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&Ft!==Ah){let ut=Ft&&typeof Ft=="object"&&"scope"in Ft?Ft:Ft&&typeof Ft=="object"&&"configuration"in Ft?Ft.configuration:null;if(!ut||typeof ut!="object"||!("scope"in ut))throw new b("INVALID_RESPONSE","Response is missing its App/environment scope");let Qt=et.safeParse(ut.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 Qr=Xe.headers.get("X-Indiana-Telemetry-Subject");if(Qr){if(!/^[a-f0-9]{64}$/.test(Qr))throw new b("INVALID_RESPONSE","Invalid telemetry identity");m!==Qr&&(m=Qr,t?.(m))}return Ft};try{return await Promise.race([Ht(),qe])}catch(Xe){throw!L&&he!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):Xe instanceof b?Xe:new b(we.signal.aborted?"TIMEOUT":"NETWORK_ERROR",we.signal.aborted?"Longplay request timed out":"Unable to read the Longplay response")}finally{clearTimeout(je),we.signal.removeEventListener("abort",Oe),x.delete(we)}}return{session:A,requestWithCredential(y,P,w){return I(y,P,"POST",{},w)},subjectKey:()=>m,identify(y){if(a&&typeof y=="object"&&"scope"in y){let P=et.safeParse(y.scope);if(!P.success||P.data.projectId!==a.projectId||P.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Customer session belongs to another App/environment")}A.identify(y),u=A.peek()??null},reset:f,dispose(){g(),p()},request(y,P={},w="POST",k={}){if(k.installationDetach)return I(y,P,w,k);let D=l;try{let L=A.access(),he=we=>{if(D!==l)throw new b("IDENTITY_CHANGED","Customer identity changed before dispatch");return I(y,P,w,k,we)};return typeof L=="string"?he(L):L.then(he)}catch(L){return Promise.reject(L)}}}}function bh(e,t,n={}){let r=!!e.session.peek(),i=new Set,a=o=>{for(let s of i)try{s(o)}catch{}};return e.session.subscribeIdentity(()=>{r=!!e.session.peek(),a(r),n.afterChange?.()},()=>{r=!1,t()}),{isIdentified:()=>r,methods:{subscribeIdentity(o){return i.add(o),()=>{i.delete(o)}},identify(o){let s=typeof o=="string"?o:o.accessToken;if(!Yt.test(s))throw new b("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(s),e.identify(o)},reset(){try{n.beforeReset?.()}finally{e.reset()}}}}}import{ZodError as jI}from"zod";function xh(e,t,n,r){try{return e.parse(t)}catch(i){throw r&&i instanceof jI?new b(n,r):i}}async function ge(e,t,n,r={},i){let a=typeof r=="function"?{}:r,o=xh(t.request,n,"INVALID_REQUEST",a.request),s=await e(t.path,o,t.method,i),c=typeof r=="function"?r:r.parseResponse;return c?c(t.response,s):xh(t.response,s,"INVALID_RESPONSE",a.response)}function ze(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new b("INVALID_REQUEST","Customer requests use the verified session identity")}function Sh(e){return{async checkEntitlement(t){ze(t);let n=O.checkEntitlement;return ge(e,n,t)},async readHoldings(t={}){let n=O.readHoldings;return ge(e,{...n,request:n.request.omit({customerId:!0})},t)}}}function Ih(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 vh(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 wh(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 Oh(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 _h(e){return{...Sh(e),...Ih(e),...vh(e),...wh(e),...Oh(e)}}function Ch(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 Ph=e=>new TextEncoder().encode(JSON.stringify(e)).length,Eh=16384;function Rh(e,t){let n=0,r,i=p=>{r={config:structuredClone(p),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(p,g={},f={}){if(c(),r&&Date.now()<r.until&&!Qm(r.config,p))return;A();let I=O.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:p,properties:g,...f}]}).events[0];if(Ph({events:[I]})>Eh)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(I)),u()}async function m(p=!1){if(c(),o)return o;let g=n,f=(async()=>{let I={inserted:0,duplicates:0,rejected:0,skipped:0},y=a.length;for(;y&&g===n;){let P=[];for(let D of a.slice(0,Math.min(y,100))){if(P.length&&Ph({events:[...P,D]})>Eh)break;P.push(D)}let w=O.trackEvents,k=await ge(e,w,{events:P},void 0,{keepalive:p});if(g!==n)throw new b("IDENTITY_CHANGED","Event identity changed during delivery");if(k.inserted+k.duplicates+k.rejected+k.skipped!==P.length)throw new b("INVALID_RESPONSE","Incomplete event acknowledgement");i(k.analyticsConfig),a.splice(0,P.length),y-=P.length,I.inserted+=k.inserted,I.duplicates+=k.duplicates,I.rejected+=k.rejected,I.skipped+=k.skipped}return I})();o=f;try{return await f}finally{o===f&&(o=null)}}let x;function A(){if(x||typeof document>"u")return;let p=()=>{document.visibilityState==="hidden"&&t()&&a.length&&m(!0).catch(()=>{})};document.addEventListener("visibilitychange",p),x=()=>document.removeEventListener("visibilitychange",p)}return{rememberConfiguration:i,track(p,g,f={}){return A(),l(p,g,f)},flush:m,reset(){n++,r=void 0,clearTimeout(s),s=void 0,a=[],o=null},detachVisibility(){x?.(),x=void 0}}}function Qu(e){let t=null,n=null,r=0,i=0,a=!1,o=new Set,s=null,c=null,u=new Set,l=()=>{for(let y of u)try{y()}catch{}},m={attributes:St.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(y,P)=>{!o.has(y)&&(!t||!("analyticsConfig"in t)||t.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(y,structuredClone(P),structuredClone(m.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(y,P)=>(!t||!("analyticsConfig"in t)||t.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(y),structuredClone(P),structuredClone(m.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?y=>e.saveStickyBucketAssignmentDoc(structuredClone(y)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},x=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function A(y,P=new Set){return o.has(y)?!s||!s.features[y]||["unknownFeature","cyclicPrerequisite"].includes(s.features[y].source):P.has(y)?!1:(P.add(y),(t?.features[y]?.rules??[]).some(w=>[...w.parentConditions??[],...(w.tracks??[]).flatMap(k=>k.experiment.parentConditions??[])].some(k=>A(k.id,P))))}let p=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 s?.expiresAt&&Date.parse(s.expiresAt)<=Date.now()&&(s=null,m.features=t.features),o.has(y)?!s||s.expiresAt&&Date.parse(s.expiresAt)<=Date.now()?x():structuredClone(s.features[y]??x()):e.evaluateRemote&&(m.attributes?.merchandise||m.attributes?.merchandiseId)&&!a||A(y)?x():structuredClone(Ln(y,m))};async function g(){if(!t||!o.size&&!m.attributes?.merchandise&&!m.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(o.size)throw new Error("Remote Feature evaluation requires a server loader");return}let y=i;if(c?.revision===y)return c.loading;let P=r,w=t,k=[...o],D=(async()=>{let L=Ra.parse(await e.evaluateRemote({attributes:structuredClone(m.attributes),features:k}));if(!(P!==r||y!==i||w!==t)){if(e.assertUsable?.(w.generation),L.generation!==w.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(k.some(he=>!Object.hasOwn(L.features,he))||Object.keys(L.features).some(he=>!o.has(he)))throw new Error("Invalid remote Feature results");if(m.attributes?.merchandise||m.attributes?.merchandiseId){if(!L.merchandiseContext)throw new Error("Server did not resolve merchandise context");m.attributes=St.parse({...m.attributes,...L.merchandiseContext}),a=!0}s=structuredClone(L),m.features={...w.features,...Object.fromEntries(Object.entries(s.features).map(([he,we])=>[he,{defaultValue:we.value}]))},l()}})();c={revision:y,loading:D};try{await D}finally{c?.loading===D&&(c=null)}}function f(){g().catch(y=>{try{e.onError?.(y)}catch{}})}async function I(){if(n)return n;let y=r,P=(async()=>{let w=await e.load(),k="remoteFeatures"in w?uo.parse(w):null,D=k??yn.parse(w);if(D.scope.projectId!==e.scope.projectId||D.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===D.generation){let{evaluatedAt:he,expiresAt:we,...Re}=t,{evaluatedAt:Oe,expiresAt:qe,...je}=D;if(vt(Re)!==vt(je))throw new Error("Immutable Feature generation changed content");return t.evaluatedAt=D.evaluatedAt,t.expiresAt=D.expiresAt,l(),(!s||s.expiresAt&&Date.parse(s.expiresAt)<=Date.now())&&f(),structuredClone(t)}let L=new Set(k?.remoteFeatures??[]);if([...L].some(he=>Object.hasOwn(D.features,he)))throw new Error("Remote Feature definitions must not be delivered locally");return t&&"analyticsConfig"in t&&"analyticsConfig"in D&&!t.analyticsConfig.experimentViewsEnabled&&k?.analyticsConfig.experimentViewsEnabled&&m.trackedExperiments?.clear(),t=structuredClone(D),o=L,s=null,c=null,i++,m.features=t.features,m.savedGroups=ni(t.savedGroups),m.trackedFeatureUsage={},l(),f(),structuredClone(t)})();n=P;try{return await P}finally{n===P&&(n=null)}}return{init:I,refresh:I,refreshRemote:g,get generation(){return t?.generation??null},get expiresAt(){return t?.expiresAt??null},subscribe(y){return u.add(y),()=>{u.delete(y)}},setAttributes(y){let P=St.parse(y);(m.attributes?.merchandise||m.attributes?.merchandiseId||y.merchandise||y.merchandiseId)&&m.trackedExperiments?.clear(),m.attributes=P,i++,a=!1,s=null,c=null,m.features=t?.features??{},m.trackedFeatureUsage={},l(),f()},evalFeature:p,isOn(y){return p(y).on},isOff(y){return p(y).off},getFeatureValue(y,P){let w=p(y).value;return structuredClone(w===null?P:w)},reset(){r++,i++,n=null,c=null,t=null,s=null,o.clear(),m.features={},m.savedGroups={},m.stickyBucketAssignmentDocs={},m.attributes={},m.trackedFeatureUsage={},m.trackedExperiments?.clear(),l()}}}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 TI(e){let t=kh(e),{merchandiseId:n,merchandise:r,...i}=e;return{...i,...t?{merchandise:t}:{}}}function jh(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,x=async()=>{if(m||l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let Re=O.getFeatures,Oe=i?{scope:{projectId:i.scope.projectId,environment:i.scope.environment},payload:await i.features()}:await ge(e,Re,{});if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");if(r&&(Oe.scope.projectId!==r.projectId||Oe.scope.environment!==r.environment))throw new b("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(Oe.payload.analyticsConfig),Oe},A=await x(),p=!0,g,f=Re=>{try{u.onError?.(Re)}catch{}},I=(Re,Oe,qe)=>{try{let je=kh(qe);n.track(Re,Oe,je?{merchandise:je}:{})}catch(je){f(je)}},y=Qu({assertUsable:i?.assertFeatures,scope:A.scope,attributes:u.attributes,onError:u.onError,load:async()=>p?(p=!1,A.payload):(await x()).payload,evaluateRemote:async Re=>{if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let Oe=O.evaluateFeatures,qe=await ge(e,Oe,{...Re,attributes:TI(Re.attributes)});if(qe.scope.projectId!==A.scope.projectId||qe.scope.environment!==A.scope.environment)throw new b("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:qe.generation,evaluatedAt:qe.evaluatedAt,expiresAt:qe.expiresAt,features:qe.features,...qe.merchandiseContext?{merchandiseContext:qe.merchandiseContext}:{}}},onExperimentViewed:(Re,Oe,qe)=>I("Experiment Viewed",{experimentId:Re.key,variationId:Oe.key},qe),onFeatureUsage:(Re,Oe,qe)=>I("Feature Evaluated",{feature:Re,value:Oe.value,source:Oe.source,ruleId:Oe.ruleId,...Oe.experimentResult?{variationId:Oe.experimentResult.key}:{}},qe)}),P=y.refresh;function w(){clearTimeout(g),!i&&(m||l!==a||!y.expiresAt||(g=setTimeout(()=>{k().catch(f)},Math.min(2147483647,Math.max(1e3,Date.parse(y.expiresAt)-Date.now()))),typeof g=="object"&&"unref"in g&&g.unref()))}async function k(){try{return await P()}finally{w()}}let D=()=>{m||k().catch(f)},L=y.subscribe(w),he=i?.subscribe(()=>{!m&&i.fresh&&k().catch(f)});function we(){m||(m=!0,clearTimeout(g),typeof window<"u"&&window.removeEventListener("focus",D),L(),he?.(),y.reset(),o.delete(we))}o.add(we);try{await y.init(),(u.attributes?.merchandise||u.attributes?.merchandiseId)&&await y.refreshRemote()}catch(Re){throw we(),Re}return w(),!i&&typeof window<"u"&&window.addEventListener("focus",D),Object.assign(y,{refresh:k,destroy:we})}return{features:c,reset(u){a++,u();for(let l of o)l()}}}import{z as NI}from"zod";function Th(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=NI.object({funnelId:Wa.shape.id,funnelVersionId:Wa.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 Nh(e){let t=gr(e),n=t.request,r=Gg(e.push,t,e.scope??e.configuration?.scope),i=bh(t,()=>{o.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start}),a=Rh(n,i.isIdentified),o=jh(n,i.isIdentified,a,e.scope,e.configuration);return{session:t.session,...Hg(n,r),..._h(n),...Ch(n),forFunnel(s){return Th(n,s)},async features(s={}){return o.features(s)},track(s,c,u={}){return a.track(s,c,u)},flush(){return a.flush()},...i.methods}}function Ei(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)=>Ei(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)&&Ei(a,Reflect.get(t,i)))}async function ss(e,t){let n=Mg.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 Ri=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function cs(e){let t=Yt.test(e.apiKey);if(typeof window<"u"&&!t)throw new b("SERVER_ONLY","Funnel starts are issued by your backend");if(!t&&!Ri.test(e.apiKey))throw new b("INVALID_TOKEN","A customer credential or server API key is required");let n=gr({...e,timeoutMs:e.timeoutMs??35e3});return e.session||n.identify(e.apiKey),{async start(r){let i=Qn.safeParse({...r,operation:"start"});if(!i.success||i.data.operation!=="start"||(t?i.data.customer!==void 0:i.data.customer===void 0))throw new b("INVALID_REQUEST","Invalid current Funnel start");let a=i.data,o=xo.safeParse(await ss(e,await n.request("funnels",a)));if(!o.success||!o.data.runToken)throw new b("INVALID_RESPONSE","Funnel start credentials are missing");let s=o.data;if(s.run.source.id!==a.funnelId||s.run.locale!==(a.locale??"en")||!Ei(s.run.parameters,a.parameters??{})||(a.customer?!s.customerId||a.customer.type==="id"&&s.customerId!==a.customer.value:s.customerId!==void 0))throw new b("INVALID_RESPONSE","Funnel start contract changed");return{...s,runToken:s.runToken}}}}async function Ju(e,t,n){if(Number(e.headers.get("content-length"))>t)throw n.error("limit");let r=e.body?.getReader();if(!r)throw n.error("missing");let i=[],a=0;try{for(;;){n.signal?.throwIfAborted();let c=await r.read();if(c.done)break;if(a+=c.value.length,a>t)throw n.error("limit");i.push(c.value)}}finally{await r.cancel().catch(()=>{})}n.signal?.throwIfAborted();let o=new Uint8Array(a),s=0;for(let c of i)o.set(c,s),s+=c.length;return o}async function Dh(e,t,n){return new TextDecoder("utf-8",{fatal:!0}).decode(await Ju(e,t,n))}function us(e,t){let n=typeof e=="string"?new TextEncoder().encode(e):e;return n.byteLength===t.byteLength&&du(n)===t.sha256}async function ls(e,t){let n=qr.parse(t),{artifact:r,environmentId:i}=n.content,a=new xn(e.baseUrl??fr).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=setTimeout(()=>s.abort(),tn.initializationMs);try{let u=await(e.fetch??globalThis.fetch)(o,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:s.signal});if(!u.ok||!u.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(u.headers.get("content-length"))>r.byteLength)throw new b("INVALID_RESPONSE","Public Paywall is unavailable");let l=await Ju(u,r.byteLength,{signal:s.signal,error:m=>new b("INVALID_RESPONSE",m==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!us(l,r))throw new b("INVALID_RESPONSE","Public Paywall digest or size changed");return Uf(n,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l)))}finally{clearTimeout(c)}}var Fh=(e,t)=>new b(e,t);async function Zu(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=DI(e,t,o)}catch{i=null}return a??(a=e.snapshot?.generation??(await e.refresh()).generation),{advance:{policyRevision:r.policyRevision,generation:a},prediction:i}}function DI(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=Ou({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=FI(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 FI(e,t,n){return Kg(e,t,n,Fh)}import{z as Vn}from"zod";var Mh=Qn.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}),Vh=Vn.strictObject({schemaVersion:Vn.literal(1),scope:et,runId:Vn.uuid(),funnelId:Vn.uuid(),versionId:Vn.uuid(),command:Mh.optional(),closeCommand:Mh.refine(e=>e.operation==="close").optional(),purchase:Vn.strictObject({receiptId:Vn.uuid(),operationId:Vn.uuid(),generation:Vn.number().int().nonnegative()}).optional(),closed:Vn.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"),nn=()=>new b("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),ds=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function qh(e){let t=0,n=null,r=c=>JSON.stringify([c.scope,c.runId,c.funnelId,c.versionId]),i=Promise.resolve();async function a(){let c=await e.read();if(!Number.isSafeInteger(c.revision)||c.revision<0)throw new b("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:c.revision,entry:c.entry===null?null:Vh.parse(c.entry)}}function o(c){let u=i.then(c);return i=u.catch(()=>{}),u}async function s(c){for(let u=0;u<4;u++){let l=await a();if(l.entry&&n!==null&&r(l.entry)!==n)throw nn();let m=c(l.entry,l.revision);if(ds(l.entry,m)){t=l.revision;return}let x=await e.write(l.revision,m);if(x!==null){if(!Number.isSafeInteger(x)||x<=l.revision)throw nn();t=x;return}}throw nn()}return{bind(c){let u=JSON.stringify([c.scope,c.runId,c.funnelId,c.versionId]);if(n!==null&&n!==u)throw nn();n=u},async load(){let c=await a();return t=c.revision,n=c.entry?r(c.entry):null,c.entry},retain(c){let u=Vh.parse(c),l=u.command;return!l||n!==null&&r(u)!==n?Promise.reject(nn()):(n??(n=r(u)),o(()=>s((m,x)=>{if(m&&!ds(r(m),r(u)))throw nn();if(!m){if(x!==t&&l.operation!=="close")throw nn();return u}if(!m.command)return{...m,command:l,...l.operation==="close"?{closed:!0}:{}};if(l.operation==="close"&&m.command.operation!=="close"){if(m.command.requestId===l.requestId||m.closeCommand&&!ds(m.closeCommand,l))throw nn();return{...m,closeCommand:l,closed:!0}}if(!ds(m.command,l))throw nn();return m})))},observePurchase(c,u,l){return o(()=>s((m,x)=>{if(!m&&x!==t||m&&r(m)!==r({...c,schemaVersion:1}))throw nn();if(m?.purchase&&m.purchase.generation>u.generation)return m;if(m?.purchase&&m.purchase.generation===u.generation&&m.purchase.operationId!==u.operationId)throw nn();return l?!m?.purchase||m.purchase.operationId!==u.operationId?m:m.command?{...m,purchase:void 0}:null:{schemaVersion:1,...c,...m,purchase:u}}))},settle(c){return o(()=>s(u=>u?u.command&&"requestId"in u.command&&u.command.requestId===c?u.closeCommand?{...u,command:u.closeCommand,closeCommand:void 0}:u.purchase?{...u,command:void 0}:null:u.closeCommand&&"requestId"in u.closeCommand&&u.closeCommand.requestId===c?{...u,closeCommand:void 0}:u:null))}}}function Bh(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??fr).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})}}import{z as ve}from"zod";import{z as mt}from"zod";var ps=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"})}),Uh=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 Wu}from"zod";var MI=Wu.enum(["sandbox","live"]),ki=Wu.object({projectId:Wu.string().min(1),environment:MI}).strict();import{z as _t}from"zod";import{z as q}from"zod";import{z as Gr}from"zod";var VI=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],Yu="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",qI=Gr.string().regex(new RegExp(`^${Yu}/${Yu}/${Yu}/manifest\\.json$`)),Lh=Gr.strictObject({kind:Gr.literal("gcs-resumable"),url:Gr.url(),bucket:Gr.enum(VI),objectKey:qI,byteLength:Gr.number().int().positive(),expiresAt:Gr.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=q.string().min(1).max(256),fn=q.string().regex(/^[a-f0-9]{64}$/),o2=q.strictObject({versionId:q.uuid(),manifestDigest:fn,sourceGraphDigest:fn,pageKey:yt,stateKey:yt,documentKey:yt,documentHash:fn,elementKey:yt.optional(),nodeId:yt.optional(),contentHash:fn.optional(),renderKey:yt.optional()}),zh=q.strictObject({pageKey:yt,documentKey:yt,expectedDocumentHash:fn,renderKey:yt.optional(),nodeId:yt,elementKey:yt,expectedContentHash:fn,property:q.enum(["text","fontSize","color"]),value:q.union([q.string().max(4e3),q.number().finite()])}),$h=q.strictObject({versionId:q.uuid(),manifestDigest:fn,sourceGraphDigest:fn,pageKey:yt,stateKey:yt,documentKey:yt,documentHash:fn,renderKey:yt.optional(),patches:q.array(zh.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),BI=/^[a-z][a-z0-9-]{0,39}$/,el=q.string().regex(BI),tl=q.enum(["web","ios","android"]),a2=q.discriminatedUnion("action",[q.strictObject({action:q.literal("register"),requestId:q.uuid(),client:el,platform:tl,label:q.string().trim().min(1).max(100),sha256:fn,bytes:q.number().int().min(1),transferBytes:q.number().int().min(1)}),q.strictObject({action:q.literal("complete"),versionId:q.uuid()}),q.strictObject({action:q.literal("current"),versionId:q.uuid(),expectedCurrent:q.uuid().nullable()}),q.strictObject({action:q.literal("delivery"),enabled:q.boolean()}),q.strictObject({action:q.literal("changes"),versionId:q.uuid(),experimentId:q.uuid(),variationId:yt,changesetId:q.uuid().nullable(),expectedRevision:fn.nullable(),editorUrl:q.string().url().max(2048),patches:q.array(zh).max(200)})]),nl=q.strictObject({id:q.uuid(),projectId:q.uuid(),environmentId:q.uuid(),clientKey:el,platform:tl,label:q.string(),sha256:fn,bytes:q.number().int().positive(),objectKey:q.string(),state:q.enum(["uploading","ready","rejected"]),isCurrent:q.boolean(),revision:q.number().int().nonnegative(),createdAt:q.string(),expiresAt:q.string(),readyAt:q.string().nullable(),summary:q.record(q.string(),q.json()),routeTree:q.json().nullable(),validation:q.record(q.string(),q.json())}),UI=q.strictObject({key:el,platform:tl,currentId:q.uuid().nullable()}),s2=q.strictObject({rows:q.array(nl).max(100),nextCursor:q.uuid().nullable(),clients:q.array(UI).max(20)}),Xu=q.strictObject({storedBytes:q.number().int().nonnegative(),reservedBytes:q.number().int().nonnegative(),chargedBytes:q.number().int().nonnegative(),versions:q.number().int().nonnegative(),objects:q.number().int().nonnegative(),orphanObjects:q.number().int().nonnegative(),missingReadyObjects:q.number().int().nonnegative(),unknownObjectSizes:q.number().int().nonnegative(),byteLimit:q.number().int().positive(),versionLimit:q.number().int().positive(),remainingBytes:q.number().int().nonnegative()}),c2=q.strictObject({asOf:q.iso.datetime({offset:!0}),reclamation:q.literal("manual-review-required"),buckets:q.strictObject({source:Xu,runtime:Xu,previews:Xu})}),u2=q.strictObject({version:nl,actorId:q.uuid(),claims:q.record(q.string(),q.json())}),l2=q.strictObject({version:nl,upload:Lh.nullable()}),d2=q.object({format:q.literal("indiana-route-state-index"),schemaVersion:q.literal(3),routes:q.array(q.object({routeKey:yt,path:q.string(),documentKey:yt,documentHash:fn,initialStateKey:yt,initialRenderKey:yt})),renders:q.array(Uh)}).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"})}),p2=q.strictObject({rows:q.array(q.object({id:q.uuid(),name:q.string(),status:q.string(),variations:q.array(q.object({id:yt,key:yt,name:q.string().optional()}).loose())}).loose()),limited:q.boolean()}),m2=q.strictObject({enabled:q.boolean(),allowedOrigins:q.array(q.string())});import{z as H}from"zod";import{z as N}from"zod";var gn=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"})}),il=N.record(N.string().min(1).max(128),gn).superRefine((e,t)=>{(!gn.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"})}),LI=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"]),hr=il.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("$")&&!LI.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)}),zI=N.discriminatedUnion("type",[N.strictObject({type:N.literal("condition"),condition:hr}),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 $I(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 KI=N.record(N.uuid(),zI).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"&&$I(o.condition).forEach(i),n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),ol=N.tuple([N.number().min(0).max(1),N.number().min(0).max(1)]).refine(([e,t])=>e<=t),Kh=N.strictObject({attribute:N.string().optional(),seed:N.string().min(1),hashVersion:N.literal(2),ranges:N.array(ol).min(1).max(100)}),GI=N.strictObject({id:N.string().min(1).max(128),condition:hr,gate:N.boolean().optional()}),rl={id:N.string().max(128).optional(),condition:hr.optional(),parentConditions:N.array(GI).max(50).optional(),filters:N.array(Kh).max(20).optional()},HI=N.union([N.strictObject({...rl}),N.strictObject({...rl,force:gn,coverage:N.number().min(0).max(1).optional(),range:ol.optional(),seed:N.string().min(1).optional(),hashAttribute:N.string().optional(),hashVersion:N.literal(2).optional()}),N.strictObject({...rl,type:N.literal("experiment-ref"),experimentId:N.uuid(),values:N.record(N.string().min(1),gn),meta:N.record(N.string().min(1),N.strictObject({passthrough:N.boolean()})).optional()})]),QI=N.strictObject({defaultValue:gn,rules:N.array(HI).max(100)}),h2=N.record(N.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),QI).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)}),JI=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:hr,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(ol).min(1)}).nullable(),seed:N.string().min(1).max(128)}),ZI=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(JI).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 WI=ZI.safeExtend({filters:N.array(Kh).optional()}),YI=N.strictObject({experiments:N.record(N.uuid(),WI),savedGroups:KI}),XI=N.strictObject({attributeName:N.string(),attributeValue:N.string(),assignments:N.record(N.string(),N.string())}),y2=N.strictObject({snapshot:YI,attributes:il,results:il,stickyBucketAssignmentDocs:N.record(N.string(),XI)}),A2=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()});var al=H.tuple([H.number().min(0).max(1),H.number().min(0).max(1)]).refine(([e,t])=>e<=t),ev=H.strictObject({attribute:H.string().optional(),seed:H.string(),hashVersion:H.literal(2),ranges:H.array(al).max(100)}),tv=H.strictObject({id:H.string().min(1).max(255),condition:hr,gate:H.boolean().optional()}),nv=H.strictObject({key:H.string().optional(),name:H.string().optional(),passthrough:H.boolean().optional()}),Gh={condition:hr.optional(),parentConditions:H.array(tv).max(100).optional(),weights:H.array(H.number().min(0).max(1)).max(20).optional(),coverage:H.number().min(0).max(1).optional(),hashAttribute:H.string().optional(),fallbackAttribute:H.string().optional(),hashVersion:H.literal(2).optional(),disableStickyBucketing:H.boolean().optional(),bucketVersion:H.number().int().nonnegative().optional(),minBucketVersion:H.number().int().nonnegative().optional(),filters:H.array(ev).max(100).optional(),ranges:H.array(al).max(20).optional(),meta:H.array(nv).max(20).optional(),seed:H.string().optional(),name:H.string().optional(),phase:H.string().optional()},ms=H.strictObject({...Gh,key:H.string().min(1).max(255),variations:H.tuple([gn,gn]).rest(gn).refine(e=>e.length<=20),urlPatterns:H.array(H.strictObject({include:H.boolean(),type:H.enum(["regex","simple"]),pattern:H.string()})).max(100).optional(),force:H.number().int().nonnegative().optional(),active:H.boolean().optional(),persistQueryString:H.boolean().optional()}),rv=H.strictObject({value:gn,variationId:H.number().int(),key:H.string(),name:H.string().optional(),bucket:H.number().optional(),passthrough:H.boolean().optional(),inExperiment:H.boolean(),hashUsed:H.boolean().optional(),hashAttribute:H.string(),hashValue:H.string(),featureId:H.string().nullable(),stickyBucketUsed:H.boolean().optional()}),iv=H.strictObject({...Gh,id:H.string().max(255).optional(),force:gn.optional(),variations:H.array(gn).min(2).max(20).optional(),key:H.string().optional(),range:al.optional(),tracks:H.array(H.strictObject({experiment:ms,result:rv})).max(100).optional()}),ov=H.strictObject({defaultValue:gn.optional(),rules:H.array(iv).max(500).optional()}),sl=H.record(H.string(),H.union([H.strictObject({type:H.literal("hashed"),attributeKey:H.string(),values:H.array(H.string().regex(/^[a-f0-9]{64}$/))}),H.strictObject({type:H.literal("list"),attributeKey:H.string(),values:H.array(H.union([H.string(),H.number()]))}),H.strictObject({type:H.literal("condition"),condition:hr})])),v2=H.strictObject({scope:ki,generation:H.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:H.iso.datetime({offset:!0}),expiresAt:H.iso.datetime({offset:!0}).nullable(),features:H.record(H.string(),ov),savedGroups:sl,experiments:H.record(H.uuid(),ms)});var av=_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()}),sv=_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(av).max(200).default([]),iam:$h.optional(),renderGuard:ps.optional()}),cl=sv.omit({variation:!0,description:!0,iam:!0}),cv=ms.omit({variations:!0,active:!0}).extend({changeId:_t.string().regex(/^[a-f0-9]{64}$/),variations:_t.tuple([cl,cl]).rest(cl).refine(e=>e.length<=20)}),Hh=_t.strictObject({trackExposures:_t.boolean(),environmentId:_t.uuid(),generation:_t.string().regex(/^[a-f0-9]{64}$/),experiments:_t.array(cv).max(100),savedGroups:sl});import{z as Hr}from"zod";var Qh=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,k2=Hr.object({customerId:Hr.uuid(),sessionId:Hr.uuid(),accessToken:Hr.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),refreshToken:Hr.string().regex(/^gg_rt_[A-Za-z0-9_-]{43}$/),expiresAt:Hr.iso.datetime(),refreshExpiresAt:Hr.iso.datetime()});var fs=ve.string().regex(/^[a-f0-9]{64}$/),uv=ve.strictObject({release:fs,render:ps,button:ve.strictObject({selector:ve.string().min(1).max(512),elementKey:ve.string().min(1).max(256),tag:ve.enum(["button","a","input"])}).nullable()}),V2=ve.strictObject({scope:ki.extend({environmentId:ve.uuid()}),release:fs,validatedAt:ve.iso.datetime({offset:!0}),validUntil:ve.iso.datetime({offset:!0}),entries:ve.array(ve.strictObject({id:ve.uuid(),funnelId:ve.uuid(),versionId:ve.uuid(),event:ve.enum(["screen_enter","button_click"]),target:uv})).max(4e3)}),q2=ve.strictObject({operation:ve.literal("entry_start"),funnelId:ve.uuid(),versionId:ve.uuid(),entryId:ve.uuid(),release:fs,requestId:ve.uuid(),locale:ve.string().min(1).max(35).default("en")}),B2=ve.strictObject({scope:ki,suppressed:ve.literal(!0),reason:ve.enum(["frequency","in_progress"]),retryAt:ve.iso.datetime({offset:!0}).nullable()}),U2=ve.strictObject({experimentId:ve.uuid(),splitNodeId:ve.string().min(1).max(128)}),lv=ve.strictObject({experimentId:ve.uuid(),experimentKey:ve.string().min(1).max(128),variationKey:ve.string().min(1).max(128),inExperiment:ve.boolean(),generation:ve.string().min(1).max(256)}),Jh=ve.strictObject({operation:ve.literal("page_experiments"),release:fs,usedReceiptIds:ve.array(ve.uuid()).max(20).default([]),customerToken:ve.string().regex(Qh).optional()}),Zh=ve.strictObject({scope:ki,runId:ve.uuid(),assignments:ve.array(lv.extend({receiptId:ve.uuid()})).max(100),payload:Hh});function Wh(e){let t=null,n=0,r=!1,i,a=0,o=new Set;return{get view(){return t},get generation(){return n},get disposed(){return r},get customerToken(){return i},get readSequence(){return a},nextRead(){return++a},assertCurrent(s,c="Run identity changed during the request"){if(s!==n||r)throw new b("IDENTITY_CHANGED",c)},assertRun(s){if(t&&(s.id!==t.id||s.source.type!==t.source.type||s.source.id!==t.source.id||s.source.versionId!==t.source.versionId||s.locale!==t.locale||!Ei(s.parameters,t.parameters)))throw new b("INVALID_RESPONSE","Run version changed");if(e&&s.source.id!==e)throw new b("INVALID_RESPONSE","Run belongs to another Funnel")},publish(s,c,u,l,m){if(!(s.operation==="review"&&t&&t!==u&&c.run.revision<=t.revision)&&!(t&&c.run.revision===t.revision&&l!==void 0&&l<a)&&(s.operation==="review"&&!c.run.stopped&&["running","waiting"].includes(c.run.status)&&t&&c.run.nodeId===t.nodeId&&c.run.visit===t.visit&&c.run.revision===t.revision&&(c.run.screen=t.screen,(t.paywall?.quote?.operationId===c.review?.activeOperationId||!t.paywall?.quote&&c.review?.activeOperationId===null)&&(c.run.paywall=t.paywall)),!(t?.paywall&&c.run.paywall&&t.paywall.receiptId===c.run.paywall.receiptId&&(c.run.paywall.selectionGeneration??0)<(t.paywall.selectionGeneration??0)))){if(!t||c.run.revision>=t.revision)t=c.run;else if(!m)return;if(t)for(let x of o)try{x(structuredClone(t))}catch{}}},identify(s){if(!Yt.test(s))throw new b("INVALID_TOKEN","Customer credential required");n++,i=s},subscribe(s){return o.add(s),()=>o.delete(s)},reset(){r=!0,n++,i=void 0,t=null,o.clear()}}}function yr(e){let{customerToken:t,...n}=e;return n}var dv=e=>!(e instanceof b)||e.status===void 0||e.status>=500||[401,425].includes(e.status);function Yh({options:e,journal:t,state:n,call:r}){let i=null,a=null,o=!1,s={command:null,close:null},c=!1,u,l=null,m=t?t.load().then(f=>{if(n.disposed)throw new b("IDENTITY_CHANGED","Controller was reset during command restoration");if(l=f,!f)return;if(e.scope&&(f.scope.projectId!==e.scope.projectId||f.scope.environment!==e.scope.environment))throw new b("SCOPE_MISMATCH","Pending command belongs to another scope");if(u=f.purchase,o=f.closed===!0,!f.command)return;let I=Qn.parse(f.command);if(I.operation==="start"||I.operation==="get"||I.operation==="review")throw new b("COMMAND_STORAGE_INVALID","Stored mutation required");i=I,f.closeCommand&&(a=f.closeCommand,o=!0),I.operation==="close"&&(o=!0),c=!0}):Promise.resolve();m.catch(()=>{});async function x(f=i){if(t&&await m,!f)throw new b("INVALID_REQUEST","No command is pending");let I=f,y=n.generation;if(t){if(!n.view||!e.scope)throw new b("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await t.retain({schemaVersion:1,scope:e.scope,runId:n.view.id,funnelId:n.view.source.id,versionId:n.view.source.versionId,command:yr(I)})}if(y!==n.generation||i!==I&&a!==I)throw new b("IDENTITY_CHANGED","Run changed before command dispatch");let P={...I,...n.customerToken?{customerToken:n.customerToken}:{}},w=c;c=!0;try{return await r(P,k=>{if(!k.settlement)throw new b("INVALID_RESPONSE","Exact command settlement is missing");if(k.settlement.requestId!==I.requestId)throw new b("INVALID_RESPONSE","Command settlement identity changed");if(y===n.generation&&(i===I||a===I)&&k.run.pendingRequest?.requestId!==I.requestId&&k.settlement.state==="settled"&&(!o||I.operation==="close"||k.settlement?.state==="settled"&&!["running","waiting"].includes(k.run.status))){let D=()=>y!==n.generation||i!==I&&a!==I?!1:(i===I&&(i=null),a===I&&(a=null),c=i!==null,l=null,!0);return t?t.settle(I.requestId).then(D):D()}return!1})}catch(k){throw y===n.generation&&i===I&&!w&&!dv(k)&&(t&&await t.settle(I.requestId),y===n.generation&&i===I&&(i=null,c=!1,l=null)),k}}function A(f){let I=Qn.parse(f);if(I.operation==="start"||I.operation==="get"||I.operation==="review")throw new b("INVALID_REQUEST","Mutation required");if(o&&I.operation!=="close"){if(i?.requestId===I.requestId)return g(I.requestId);throw new b("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(I.operation==="close"&&i?.operation!=="close"){if(o=!0,a&&JSON.stringify(yr(a))!==JSON.stringify(yr(I)))throw new b("COMMAND_PENDING","Retry the original Close");return a??(a=I),s.close?s.close:p(a,"close")}if(i){if(JSON.stringify(yr(i))!==JSON.stringify(yr(I)))throw new b("COMMAND_PENDING","Retry the original command before sending another");if(s.command)return s.command}else i=I,c=!1;return p(i,"command")}function p(f,I){let y=x(f);s[I]=y;let P=()=>{s[I]===y&&(s[I]=null)};return y.then(P,P),y}async function g(f){let I=await r({operation:"get",settlementRequestId:f,...n.customerToken?{customerToken:n.customerToken}:{}});if(I.settlement?.requestId!==f)throw new b("INVALID_RESPONSE","Exact command settlement is missing");return I.settlement.state==="settled"&&(t&&await t.settle(f),i?.requestId===f&&(i=null,c=!1),a?.requestId===f&&(a=null)),I}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(f){if(l&&(f.run.id!==l.runId||f.run.source.id!==l.funnelId||f.run.source.versionId!==l.versionId))throw new b("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},observePurchase(f,I,y,P){t?.bind({scope:I.scope,runId:I.run.id,funnelId:I.run.source.id,versionId:I.run.source.versionId}),t&&!e.scope&&(e.scope=I.scope);let w=I.run.paywall,k=w??I.purchase,D=k?.operation,L=I.settlement&&(!w||w.purchaseRequestId===I.settlement.requestId)&&(!u||u.operationId===I.settlement.operationId)?I.settlement:void 0,he=D?.operationId??k?.quote?.operationId??L?.operationId,we=k?.receiptId??L?.receiptId,Re=w?.selectionGeneration??u?.generation??0;if(t&&he&&we&&f.operation!=="review"&&(!n.view||I.run.revision>=n.view.revision)&&(P===void 0||P>=n.readSequence)&&(!u||Re>=u.generation)){let Oe={receiptId:we,operationId:he,generation:Re},qe=D?.status==="complete"||k?.canReselect===!0;return t.observePurchase({scope:I.scope,runId:I.run.id,funnelId:I.run.source.id,versionId:I.run.source.versionId},Oe,qe).then(()=>{n.assertCurrent(y),qe?u?.operationId===Oe.operationId&&(u=void 0):u=Oe})}},stop(){o=!0},submit:A,executePending:x,settle:g,reset(){i=null,a=null,s.close=null,c=!1,s.command=null}}}function ji(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"||!Ri.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=gr({...e,session:void 0,...e.serverKey?{fetch:(f,I)=>{let y=new Headers(I?.headers),P=typeof I?.body=="string"?JSON.parse(I.body):null;return P!==null&&typeof P=="object"&&"customerToken"in P&&typeof P.customerToken=="string"&&P.customerToken.length>0||y.set(Vg,e.serverKey),(e.fetch??globalThis.fetch)(f,{...I,headers:y})}}:{},...e.session?{fetch:async(f,I)=>{let y=await e.session.access(),P=typeof I?.body=="string"?JSON.parse(I.body):{};if(!P||typeof P!="object"||Array.isArray(P))throw new b("INVALID_REQUEST","Run command must be an object");return(e.fetch??globalThis.fetch)(f,{...I,body:JSON.stringify({...P,customerToken:y})})}}:{},timeoutMs:e.timeoutMs??35e3});t.identify(e.runToken);let n=Wh(e.funnelId),r=e.session?.subscribeIdentity(()=>{n.reset(),t.reset()}),i=null,a=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?Bh(e):void 0),o=a&&qh(a),s=Yh({options:e,journal:o,state:n,call:c});async function c(f,I,y){let P=n.generation,w=()=>n.assertCurrent(P);o&&await s.ready,w();let k=n.view,D=xo.parse(await ss(e,await t.request("funnels",Qn.parse(f))));if(f.operation==="review"&&!D.review)throw new b("INVALID_RESPONSE","Historical projection is missing");if(w(),D.runToken&&D.runToken!==e.runToken)throw new b("INVALID_RESPONSE","Run credential changed");let L=f.operation==="get"?f.settlementRequestId:"requestId"in f&&f.operation!=="start"?f.requestId:void 0;if(L&&D.settlement?.requestId!==L)throw new b("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");s.assertBinding(D),n.assertRun(D.run);let he=s.observePurchase(f,D,P,y);if(he&&await he,!D.run.stopped&&["running","waiting"].includes(D.run.status)&&f.operation==="get"&&f.settlementRequestId)return D;let we=I?.(D),Re=typeof we=="boolean"?we:we?await we:!1;return w(),["running","waiting"].includes(D.run.status)||s.stop(),n.publish(f,D,k,y,Re),D}let u=s.submit,l=null,m=new WeakMap;function x(f){let I=m.get(f);if(I)return I;let y=p(f);return m.set(f,y),y}let A=!1;async function p(f){let I=await f;if(I.run.instruction?.type!=="evaluate_segment")return I;if(l)return l;A=!0;let y=n.generation,P=(async()=>{for(let w=0;w<32&&I.run.instruction?.type==="evaluate_segment";w++){if(s.pending||s.closeRequested)return I;let k=I.run;if(I.run.instruction?.type==="evaluate_segment"){let{advance:L}=await Zu(e.configuration,k,{predict:!1});if(y!==n.generation)throw new b("IDENTITY_CHANGED","Run identity changed during segment calculation");if(s.pending||s.closeRequested)return I;if(n.view&&(n.view.revision!==k.revision||n.view.visit!==k.visit||n.view.nodeId!==k.nodeId))return c({operation:"get",...n.customerToken?{customerToken:n.customerToken}:{}});let he=!0;Zu(e.configuration,k).then(({prediction:we})=>{he&&y===n.generation&&!s.closeRequested&&n.view?.id===k.id&&!n.view.stopped&&n.view.nodeId===k.nodeId&&n.view.visit===k.visit&&n.view.revision===k.revision&&(i=we)}).catch(()=>{});try{I=await u({operation:"commit_segment",requestId:Fg(k.id,k.visit,`segment:${k.revision}`),nodeId:k.nodeId,visit:k.visit,revision:k.revision,...L})}finally{he=!1,i=null}}}return I})();l=P;try{return await P}finally{l===P&&(l=null)}}let g={get configuration(){return A?e.configuration:void 0},get configurationReady(){return!0},get view(){return n.view?structuredClone(n.view):null},get pendingCommand(){let f=s.closing??s.pending;return f?structuredClone(yr(f)):null},get pendingCommands(){return[s.pending,s.closing].filter(f=>f!==null).map(f=>structuredClone(yr(f)))},get pendingPurchase(){return s.purchase?structuredClone(s.purchase):null},get prediction(){let f=n.view;return i&&f&&!f.stopped&&["running","waiting"].includes(f.status)&&f.id===i.runId&&f.nodeId===i.from.nodeId&&f.visit===i.from.visit&&f.revision===i.from.revision&&!s.closeRequested?structuredClone(i):null},settle:s.settle,get webViewUrl(){return"bundled"},resolvePaywall(f){return ls(e,f)},async pageExperiments(f,I=[]){let y=n.generation;n.assertCurrent(y);let P=n.view?.id;if(!P)throw new b("INVALID_REQUEST","Read the Run before its page experiments");let w=Zh.parse(await t.request("funnels",Jh.parse({operation:"page_experiments",release:f,usedReceiptIds:I,...n.customerToken?{customerToken:n.customerToken}:{}})));if(n.assertCurrent(y),w.runId!==P||w.scope.projectId!==e.scope?.projectId||w.scope.environment!==e.scope?.environment)throw new b("SCOPE_MISMATCH","Page experiment Run changed");return w},review(f){return c({operation:"review",...f?{receiptId:f}:{},...n.customerToken?{customerToken:n.customerToken}:{}},void 0,n.nextRead())},async get(f,I){o&&await s.ready,I??(I=s.purchase&&{receiptId:s.purchase.receiptId,operationId:s.purchase.operationId});let y=n.nextRead();return x(c({operation:"get",...f?{data:f}:{},...I?{purchase:I}:{},...n.customerToken?{customerToken:n.customerToken}:{}},void 0,y))},resume(f=n.view?.pendingRequest?.requestId){return f?s.closeRequested?g.settle(f):s.pending?.requestId===f?x(u(s.pending)):x(u({operation:"resume",requestId:f})):Promise.reject(new b("INVALID_REQUEST","No interrupted command is available"))},submit(f){return x(u(f))},retry(){return s.closeFlight?s.closeFlight:s.closing?s.executePending(s.closing):s.closeRequested&&s.pending?g.settle(s.pending.requestId):s.inFlight?x(s.inFlight):s.pending?x(u(s.pending)):Promise.reject(new b("INVALID_REQUEST","No command is pending"))},identify(f){n.identify(f),i=null,t.identify(e.runToken)},subscribe:n.subscribe,reset(){r?.(),n.reset(),s.reset(),i=null,t.reset()}};return g}function Xh(e){if(!Yt.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=cs({...e,scope:e.scope,apiKey:e.customerToken});return{async start(n){let r=await t.start(n),i=ji({...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 ey(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 ty(e,t,n){if(e.operationId!==t.operationId||t.currency!==void 0&&e.currency!==t.currency)throw new b("INVALID_RESPONSE",n)}function ny(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 ry(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}async function iy(e,t){if(!Yt.test(t.customerToken))throw new b("INVALID_TOKEN","A verified Customer credential is required");let n=gr(e);if(!e.session)n.identify(t.customerToken);else if(e.session.peek()!==t.customerToken)throw new b("SCOPE_MISMATCH","Paywall credential does not match the shared session");let r=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}:{}}),i=null,a=!1,o=null,s=null,c=null,u=null,l=e.session?.subscribeIdentity(()=>{a=!0,n.dispose(),i=null,o=null,s=null,c=null});async function m(){if(a)throw new b("IDENTITY_CHANGED","Paywall is closed");let p=O.resolvePaywall,g=await ge(n.request,p,{...r,selector:i?{type:"version",versionId:i.id}:r.selector}),f={paywall:await ls(e,g.paywall)};if(a)throw new b("IDENTITY_CHANGED","Paywall is closed");if(t.paywallVersionId?f.paywall.id!==t.paywallVersionId:f.paywall.paywallId!==t.paywallId)throw new b("INVALID_RESPONSE","The requested Paywall changed");if(i&&(!ey(f.paywall,i)||f.paywall.paywallId!==i.paywallId))throw new b("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return i=f.paywall,structuredClone(i)}async function x(p){if(!o)throw new b("INVALID_REQUEST","A quoted purchase is required");let g=p==="read"?O.readSubscriptionOperation:O.attach,f=await ge(n.request,g,{operationId:o.operationId,...p==="read"?{}:{intent:p}});return ty(f.operation,{operationId:o.operationId,currency:r.commerce.currency},"The purchase operation changed"),s=ry(s,f.operation),structuredClone(s)}let A={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"},refresh:m,async preview(p){if(!i)throw new b("INVALID_REQUEST","Load the Paywall first");let g=i.document.buttons[p.actionId];if(g?.type!=="checkout")throw new b("INVALID_REQUEST","Choose an authored purchase action");let f=Km(g.product,p.selection,i.capabilities);if(!f)throw new b("PRODUCT_UNAVAILABLE","Choose an available Product");let I=jf(i.document.screen,f,p.selection,i.capabilities),y=O.previewAttach.request.parse({funnelId:r.funnelId,funnelVersionId:r.funnelVersionId,requestId:p.requestId,plans:[{productVersionId:f,...Object.keys(I).length?{featureQuantities:I}:{}}],provider:r.commerce.provider,currency:r.commerce.currency,...p.offerId?{offerId:p.offerId}:{},...p.nativeOffer?{nativeOffer:p.nativeOffer}:{}}),P=JSON.stringify(y);if(c&&c!==P&&(!s||s.status==="pending"))throw new b("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(c===P){if(u)return u;if(o)return structuredClone(o)}c=P;let w=(async()=>{let k=O.previewAttach,D=await ge(n.request,k,y);return ny(D.quote,{productVersionId:f,featureQuantities:I,currency:r.commerce.currency,provider:r.commerce.provider},"The purchase quote changed its selected Product or presentment"),o=D.quote,s=null,structuredClone(o)})();u=w;try{return await w}finally{u===w&&(u=null)}},confirm:()=>x("confirm"),cancel:()=>x("cancel"),read:()=>x("read"),destroy(){l?.(),a=!0,n.dispose(),i=null,o=null,s=null,c=null}};return await m(),A}function oy(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 A=r;n&&e.nativeModule&&n.then(p=>e.nativeModule.reset(p,A)).catch(()=>{})}),l=e.nativeEvents?.(A=>{!n||!e.nativeModule||typeof A?.requestId!="string"||(async()=>{let p=await n;if(A.instanceId!==p)return;if(A.kind==="credential"){let I=r,y=null;try{if(!o&&A.revision===I){let P=await t.access();!o&&r===I&&(y=P)}}finally{await e.nativeModule.provideCredential(p,A.requestId,y)}return}let g=!1,f=r;try{if(o||A.revision!==f||!e.onNativeAction)throw c();await e.onNativeAction(A.action),g=!o&&r===f}finally{await e.nativeModule.acknowledge(p,A.requestId,g)}})().catch(()=>{})});async function m(A,p={}){let g=s();if(t.snapshot()&&!e.nativeEvents)throw new b("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let f=r,I=await t.access();if(o||r!==f)throw c();if(!n){let w=g.create(JSON.stringify({baseUrl:e.baseUrl??"https://api.longplayai.com",scope:e.scope,timeout:(e.timeoutMs??15e3)/1e3,credentialEvents:!!e.nativeEvents}));n=w,w.catch(()=>{n===w&&(n=void 0)})}let y=await n;if(o||r!==f)throw c();if(i!==f){if(!a||a.epoch!==f){let k=(async()=>{if(await g.identify(y,JSON.stringify({revision:f,credentials:I})),o||r!==f)throw await g.reset(y,f),c();i=f})();a={epoch:f,task:k}}let w=a;try{await w.task}finally{a===w&&(a=void 0)}}let P=await g.invoke(y,A,JSON.stringify(p));if(o||r!==f)throw c();try{return JSON.parse(P)}catch{throw new b("INVALID_RESPONSE","Native host returned invalid JSON")}}async function x(A,p){let g=await m(A,p);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(A){return x("showFunnel",{runToken:A})},showPaywall(A){return x("showPaywall",A)},showContent(A){return x("showContent",A)},purchaseSubscription(A,p){return m("purchaseSubscription",{operationId:A,accepted:p})},switchSubscription(A,p){return m("switchSubscription",{operationId:A,accepted:p})},restorePurchases(){return m("restorePurchases")},manageSubscriptions(A){return m("manageSubscriptions",A?{productId:A}:{})},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,mv=O.trackUsage.response;function fv(e){let t=et.parse(e.scope),n=Nh({...e,scope:t}),r={...e,scope:t,session:n.session},i=0;n.subscribeIdentity(()=>{i++});let a=()=>{let o=n.session.peek();if(!o)throw new b("UNAUTHENTICATED","Identify the Customer first");return o};return{...n,native:oy(e,n.session),funnel(){return Xh({...r,customerToken:a()})},resumeFunnel(o){return a(),ji({...r,runToken:o})},paywall(o){return iy(r,{...o,customerToken:a()})},async trackUsage(o){if(!n.session.peek())throw new b("UNAUTHENTICATED","Identify the Customer first");if(!e.usageReporter)throw new b("INVALID_REQUEST","Configure your authenticated backend usageReporter");let s=pv.parse(o),c=i,u;try{u=await e.usageReporter(s)}catch(m){throw c!==i?new b("IDENTITY_CHANGED","Customer identity changed during usage reporting"):m}if(c!==i)throw new b("IDENTITY_CHANGED","Customer identity changed during usage reporting");let l=mv.parse(u);if(l.scope.projectId!==t.projectId||l.scope.environment!==t.environment)throw new b("INVALID_RESPONSE","Usage response scope differs");return l}}}import{z as Av}from"zod";import{z as Oo}from"zod";var gv=Oo.record(Oo.string().regex(/^[a-f0-9]{64}$/),Oo.strictObject({at:Oo.number(),text:Oo.string()})),ay=2*1048576,hv=100;function yv(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function sy(e,t){let n=t===void 0?yv():t,r=Promise.resolve();async function i(o){if(!n)return null;let s;try{return await Promise.race([Promise.resolve().then(()=>n.getItem(o)),new Promise(c=>{s=setTimeout(()=>c(null),hv)})])}catch{return null}finally{clearTimeout(s)}}async function a(){try{let o=await i(`${e}:artifacts`);if(o&&o.length<=ay)return gv.parse(JSON.parse(o))}catch{}return{}}return{async readManifest(){return i(e)},writeManifest(o){Promise.resolve().then(()=>n?.setItem(e,o)).catch(()=>{})},async readArtifact(o){let s=(await a())[o];return s&&Date.now()>=s.at&&Date.now()-s.at<=tn.retentionMs?s.text:void 0},writeArtifact(o,s){n&&(r=r.catch(()=>{}).then(async()=>{let c=await a(),u=Date.now();c[o]={at:u,text:s};let l={},m=2,x=0;for(let[A,p]of Object.entries(c).sort(([,g],[,f])=>f.at-g.at)){if(p.at>u||u-p.at>tn.retentionMs)continue;let g=new TextEncoder().encode(JSON.stringify({[A]:p})).byteLength;m+g>ay||x>=128||(l[A]=p,m+=g,x++)}await n.setItem(`${e}:artifacts`,JSON.stringify(l))}).catch(()=>{}))}}}var Ee=(e,t)=>new b(e,t),Ar=()=>performance.now(),cy=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function bv(e){let t=cu.parse(e.scope),n=new xn(e.origin??fr);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 Ee("INVALID_URL","Configuration requires a trusted HTTPS origin");let r=new Set([n.origin,...(e.assetOrigins??[]).map(te=>{let Z=new xn(te);if(Z.protocol!=="https:"||Z.username||Z.password||Z.search||Z.hash||Z.pathname!=="/")throw Ee("INVALID_URL","Invalid configuration asset origin");return Z.origin})]),i=e.fetch??globalThis.fetch.bind(globalThis),a=`/api/v1/configuration/${t.environmentId}`,o=`indiana:configuration:1:${n.origin}:${vt(t)}`,s=sy(o,e.storage),c,u=0,l=0,m=!1,x=!1,A=0,p=0,g,f,I,y,P=0,w=new Set,k=new Set,D=new Map,L=new Map,he=0,we=!1;function Re(){for(let te of w)try{te()}catch{}}function Oe(te){try{e.onError?.(te)}catch{}}let qe=()=>!x&&!m&&!!c&&Ar()<u&&Date.now()<l;function je(){if(!qe())throw Ee("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Ht(te,Z){let le=new TextEncoder().encode(Z).byteLength;if(!D.has(te)){for(;D.size&&(D.size>=128||he+le>tn.maxCacheBytes);){let de=D.entries().next().value;he-=new TextEncoder().encode(de[1]).byteLength,D.delete(de[0])}D.set(te,Z),he+=le}}function Xe(te,Z,le){return Dh(te,Z,{signal:le,error:de=>Ee("INVALID_RESPONSE",de==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function Ft(te){let Z=new xn(te,n);if(!r.has(Z.origin)||Z.username||Z.password||Z.hash||Z.search)throw Ee("INVALID_URL","Configuration artifact origin is not trusted");return Z.href}async function _o(te,Z,le=!1){let de=await i(Ft(te),{method:"GET",credentials:"omit",redirect:"error",cache:le?"default":"no-cache",signal:Z,headers:{}});if(de.status===429){let Me=de.headers.get("retry-after")??"";P=/^\d+$/.test(Me)?Number(Me)*1e3:Math.max(0,Date.parse(Me)-Date.now())||15e3}if(!de.ok&&de.status!==304)throw Ee(`CONFIGURATION_HTTP_${de.status}`,"Configuration synchronization failed");return de}function Qr(te,Z,le){let de=Date.parse(te.headers.get("x-indiana-config-validated-at")??""),Me=Date.parse(te.headers.get("x-indiana-config-valid-until")??""),Et=Date.parse(te.headers.get("date")??""),Qe=te.headers.get("age"),rn=Qe!==null&&/^\d+(\.\d+)?$/.test(Qe)?Number(Qe)*1e3:NaN;if(![de,Me,Et,rn].every(Number.isFinite)||Me<=de||Me-de>tn.maxControlAgeMs||de>Et+1e3)throw Ee("INVALID_RESPONSE","Configuration freshness evidence is invalid");let Rt=Math.min(Me-de,le.maxControlAgeSeconds*1e3,tn.maxControlAgeMs)-Math.max(rn,Et-de,0)-(Ar()-Z);if(Rt<=0)throw Ee("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return Ar()+Rt}function ut(){if(clearTimeout(I),clearTimeout(y),x||!w.size)return;qe()&&(y=setTimeout(()=>{qe()?ut():Re()},Math.max(1,u-Ar())),cy(y));let te=p?Math.min(15e3,1e3*2**Math.min(p-1,4)):Math.min(15e3,(c?.policy.refreshIntervalSeconds??15)*1e3);I=setTimeout(()=>{Qt().catch(Oe)},Math.max(P,te*(.8+Math.random()*.2))),cy(I)}async function Qt(){if(x)throw Ee("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(g)return g;let te=A,Z=new AbortController;f=Z;let le=(async()=>{if(!we){we=!0;try{let Po=await s.readManifest();if(Po&&!c){let qn=lu.parse(JSON.parse(Po));vt(qn.scope)===vt(t)&&(c=qn)}}catch{}}Z.signal.throwIfAborted();let Qe=c,rn=Ar(),qt=await _o(a,Z.signal);qt.status===304&&(!Qe||!qt.headers.has("x-indiana-config-validated-at")||!qt.headers.has("x-indiana-config-valid-until")||!qt.headers.has("age"))&&(qt=await _o(a,Z.signal));let Rt=qt.status===304?Qe:lu.parse(JSON.parse(await Xe(qt,tn.maxManifestBytes,Z.signal))),{generation:Zn,...Wn}=Rt,Sr=qt.headers.get("etag");if(vt(Rt.scope)!==vt(t)||Mf(Wn)!==Zn||Sr!==`"${Zn}"`&&Sr!==`W/"${Zn}"`)throw Ee("INVALID_RESPONSE","Configuration scope or content identity changed");if(Qe&&(Rt.revision<Qe.revision||Rt.revision===Qe.revision&&Rt.generation!==Qe.generation))throw Ee("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[Po,qn]of Object.entries(Qe?.funnels??{})){let Ir=Rt.funnels[Po];if(Ir&&(Ir.controlRevision<qn.controlRevision||Ir.evaluationRevision<qn.evaluationRevision||Ir.controlRevision===qn.controlRevision&&Ir.state!==qn.state||Ir.evaluationRevision===qn.evaluationRevision&&Ir.evaluationMode!==qn.evaluationMode))throw Ee("INVALID_RESPONSE","Funnel control revision changed identity")}let ml=Qr(qt,rn,Rt.policy);if(Z.signal.throwIfAborted(),te!==A)throw Ee("CONFIGURATION_DISPOSED","Configuration scope changed");return c=Rt,u=ml,l=Date.now()+Math.max(0,ml-Ar()),m=!1,p=0,P=0,s.writeManifest(vt(Rt)),Re(),structuredClone(Rt)})(),de=setTimeout(()=>Z.abort(Ee("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),tn.initializationMs),Me=new Promise((Qe,rn)=>Z.signal.addEventListener("abort",()=>rn(Z.signal.reason),{once:!0})),Et=Promise.race([le,Me]).catch(Qe=>{throw p++,(Qe instanceof Av.ZodError||Qe instanceof SyntaxError||Qe instanceof b&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(Qe.code))&&(u=0,m=!0,Re()),Qe}).finally(()=>{clearTimeout(de),g===Et&&(g=void 0),ut()});return g=Et,Et}async function br(te){let Z=te.sha256,le=Zn=>us(Zn,te);Ft(te.url);let de=D.get(Z);if(de&&le(de))return D.delete(Z),D.set(Z,de),de;if(L.has(Z))return L.get(Z);let Me=new AbortController;k.add(Me);let Et=A,Qe=(async()=>{try{let Sr=await s.readArtifact(Z);if(Sr&&le(Sr))return Ht(Z,Sr),Sr}catch{}Me.signal.throwIfAborted();let Zn=await _o(te.url,Me.signal,!0),Wn=await Xe(Zn,te.byteLength,Me.signal);if(!le(Wn))throw Ee("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(x||Et!==A)throw Ee("CONFIGURATION_DISPOSED","Configuration scope changed");return Ht(Z,Wn),s.writeArtifact(Z,Wn),Wn})(),rn=setTimeout(()=>Me.abort(Ee("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),tn.initializationMs),qt=new Promise((Zn,Wn)=>Me.signal.addEventListener("abort",()=>Wn(Me.signal.reason),{once:!0})),Rt=Promise.race([Qe,qt]).finally(()=>{clearTimeout(rn),k.delete(Me),L.delete(Z)});return L.set(Z,Rt),Rt}async function xr(){return qe()||await Qt(),je(),c}async function Ti(te){let Z,le=new Promise((de,Me)=>{Z=setTimeout(()=>Me(Ee("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),tn.initializationMs)});try{return await Promise.race([te(),le])}finally{clearTimeout(Z)}}function Ni(te,Z){if(je(),c?.generation!==te.generation)throw Ee("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(Z&&c.funnels[Z]?.state!=="active")throw Ee("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function ul(te){let Z=te.gb.features;if(!Z)throw Ee("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let le=te.artifacts[Z];if(le.formatVersion!==1)throw Ee("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let de=Nc.parse(JSON.parse(await br(le)));if(vt(de.scope)!==vt({projectId:t.projectId,environment:t.environment})||de.generation!==le.generation||de.remoteFeatures.some(Me=>Object.hasOwn(de.features,Me)))throw Ee("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return Ni(te),{...de,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,u-Ar())).toISOString()}}async function ll(te,Z){let le=await xr(),de=le.funnels[te];Z&&(!de||de.evaluationMode==="local"&&!de.versions[Z])&&(g&&await g,le=await Qt()),Ni(le,te);let Me=le.funnels[te];if(Me.evaluationMode!=="local")throw Ee("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let Et=Z??Me.currentVersionId,Qe=Me.versions[Et];if(!Qe)throw Ee("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(le.artifacts[Qe.artifact].formatVersion!==3)throw Ee("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[rn,qt]=await Promise.all([br(le.artifacts[Qe.artifact]).then(Rt=>qf(JSON.parse(Rt))),Me.evaluationMode==="local"?ul(le):void 0]);if(qt&&vt(Vf(rn,qt))!==vt(Qe.dependencies))throw Ee("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return Ni(le,te),{document:rn,growth:qt,versionId:Et,control:structuredClone(Me),manifest:structuredClone(le)}}async function dl(te,Z){try{return await ll(te,Z)}catch(le){if(!(le instanceof b)||!(le.code==="CONFIGURATION_CHANGED"||le.code==="CONFIGURATION_HTTP_404"&&qe()))throw le;let de=c?.generation;if(g&&await g,await Qt(),le.code!=="CONFIGURATION_CHANGED"&&c?.generation===de)throw le;return ll(te,Z)}}function gs(){m=!0,Re(),Qt().catch(Oe)}let Co=()=>{(typeof document>"u"||document.visibilityState==="visible")&&gs()};function uy(te){if(x)throw Ee("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return w.add(te),w.size===1&&(typeof window<"u"&&(window.addEventListener("online",gs),window.addEventListener("focus",Co),document.addEventListener("visibilitychange",Co)),ut()),()=>{w.delete(te),w.size||(clearTimeout(I),clearTimeout(y),pl())}}function pl(){typeof window<"u"&&(window.removeEventListener("online",gs),window.removeEventListener("focus",Co),document.removeEventListener("visibilitychange",Co))}return{scope:Object.freeze({...t}),refresh:Qt,subscribe:uy,assertFresh:je,assertFeatures(te){je();let Z=c.gb.features;if(!Z)throw Ee("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(te!==void 0&&c.artifacts[Z].generation!==te)throw Ee("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return qe()},get snapshot(){return c?structuredClone(c):null},get remainingMs(){return qe()?Math.max(0,u-Ar()):0},async features(){return Ti(async()=>ul(await xr()))},pageExperiments:()=>Ti(async()=>{let te=await xr(),Z=te.gb.pageExperiments;if(!Z)throw Ee("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let le=te.artifacts[Z];if(le.formatVersion!==1)throw Ee("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let de=zg.parse(JSON.parse(await br(le)));if(de.environmentId!==t.environmentId||de.generation!==le.generation)throw Ee("INVALID_RESPONSE","Page experiment scope or generation changed");return Ni(te),de}),funnel:(te,Z)=>Ti(()=>dl(te,Z)),paywall:(te,Z)=>Ti(async()=>{let le=await xr(),de=le.paywalls?.[te];if(!de||!Z&&de.state!=="published")throw Ee("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let Me=Z??de.currentVersionId,Et=de.versions[Me],Qe=Et&&le.artifacts[Et.artifact];if(!Qe||Qe.kind!=="paywall"||Qe.formatVersion!==1)throw Ee("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let rn=Za.parse(JSON.parse(await br(Qe)));return Ni(le),{document:rn,versionId:Me,version:Et.version,control:structuredClone(de),manifest:structuredClone(le)}}),async localFunnel(te,Z){let le=await Ti(()=>dl(te,Z));if(!le.growth)throw Ee("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:de,remoteFeatures:Me,...Et}=le.growth;return Ug({scope:{projectId:t.projectId,environment:t.environment},funnelId:te,versionId:le.versionId,evaluationMode:"local",evaluationRevision:le.control.evaluationRevision,document:le.document,payload:Et})},assertFunnel(te,Z,le){je();let de=c.funnels[te];if(!de||de.state!=="active")throw Ee("FUNNEL_STOPPED","Funnel is paused or unavailable");if(de.evaluationMode!=="local")throw Ee("EVALUATION_MODE","This Funnel now executes at Longplay");if(Z!==void 0&&de.controlRevision!==Z)throw Ee("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(le!==void 0&&!de.versions[le])throw Ee("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!x){x=!0,A++,u=0,f?.abort(Ee("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(I),clearTimeout(y),pl(),Re(),w.clear();for(let te of k)te.abort(Ee("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));D.clear(),he=0}}}}async function xv(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&&vt(n)!==vt(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=Ri.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=cs({...e,scope:n,apiKey:e.credential}),o=s=>{let c=ji({...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}}}}export{b as IndianaError,b as LongplayError,bv as createConfigurationSync,Qu as createFeatureClient,fv as createIndianaReactNative,xv as createLocalFunnelClient,fv as createLongplayReactNative};
|
|
17
|
+
*/var Ae=j.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"})}),ht=j.record(j.string().min(1).max(128),Ae).superRefine((e,t)=>{(!Ae.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"})}),VA=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"]),Ht=ht.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"&&!j.strictObject({id:j.uuid(),attributeKey:j.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("$")&&!VA.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)}),BA=j.discriminatedUnion("type",[j.strictObject({type:j.literal("condition"),condition:Ht}),j.strictObject({type:j.literal("list"),attributeKey:j.string().min(1).max(128),values:j.array(j.union([j.string(),j.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 Fn(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 UA=j.record(j.uuid(),BA).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"&&Fn(o.condition).forEach(i),n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),Bs=j.tuple([j.number().min(0).max(1),j.number().min(0).max(1)]).refine(([e,t])=>e<=t),ld=j.strictObject({attribute:j.string().optional(),seed:j.string().min(1),hashVersion:j.literal(2),ranges:j.array(Bs).min(1).max(100)}),LA=j.strictObject({id:j.string().min(1).max(128),condition:Ht,gate:j.boolean().optional()}),Vs={id:j.string().max(128).optional(),condition:Ht.optional(),parentConditions:j.array(LA).max(50).optional(),filters:j.array(ld).max(20).optional()},zA=j.union([j.strictObject({...Vs}),j.strictObject({...Vs,force:Ae,coverage:j.number().min(0).max(1).optional(),range:Bs.optional(),seed:j.string().min(1).optional(),hashAttribute:j.string().optional(),hashVersion:j.literal(2).optional()}),j.strictObject({...Vs,type:j.literal("experiment-ref"),experimentId:j.uuid(),values:j.record(j.string().min(1),Ae),meta:j.record(j.string().min(1),j.strictObject({passthrough:j.boolean()})).optional()})]),$A=j.strictObject({defaultValue:Ae,rules:j.array(zA).max(100)}),aw=j.record(j.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),$A).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)}),GA=j.strictObject({name:j.string().max(80),reason:j.string().max(500),dateStarted:j.iso.datetime({offset:!0}),dateEnded:j.iso.datetime({offset:!0}).nullable(),coverage:j.number().min(0).max(1),variationWeights:j.array(j.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:Ht,savedGroups:j.array(j.strictObject({match:j.enum(["any","all","none"]),ids:j.array(j.uuid()).min(1)})).max(50),namespace:j.strictObject({id:j.uuid(),ranges:j.array(Bs).min(1)}).nullable(),seed:j.string().min(1).max(128)}),KA=j.strictObject({key:j.string().min(1).max(128),name:j.string().min(1).max(80),hypothesis:j.string().max(2e3),status:j.enum(["draft","running","stopped"]),hashAttribute:j.string().min(1).max(128),fallbackAttribute:j.string().max(128).nullable(),hashVersion:j.literal(2),disableStickyBucketing:j.boolean(),bucketVersion:j.number().int().min(0).max(1e3),minBucketVersion:j.number().int().min(0).max(1e3),variations:j.array(j.strictObject({id:j.string().min(1),key:j.string().min(1),name:j.string().max(80),description:j.string().max(500)})).min(2).max(20),phases:j.array(GA).min(1).max(100),releasedVariationId:j.string().nullable(),excludeFromPayload:j.boolean(),statusSchedule:j.strictObject({startAt:j.iso.datetime({offset:!0}).nullable(),stopAt:j.iso.datetime({offset:!0}).nullable(),stopAfter:j.strictObject({value:j.number().int().positive().max(36500),unit:j.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 HA=KA.safeExtend({filters:j.array(ld).optional()}),QA=j.strictObject({experiments:j.record(j.uuid(),HA),savedGroups:UA}),ki=j.strictObject({attributeName:j.string(),attributeValue:j.string(),assignments:j.record(j.string(),j.string())}),sw=j.strictObject({snapshot:QA,attributes:ht,results:ht,stickyBucketAssignmentDocs:j.record(j.string(),ki)}),cw=j.strictObject({variantKey:j.string().nullable(),bucketVersion:j.number().int().min(0),source:j.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:j.number().min(0).max(1).optional(),stickyBucketUsed:j.boolean().optional(),hashUsed:j.boolean().optional()});function Jn(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 JA=Ct.enum(["active","inactive"]),ZA=Ct.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},ht),WA=Ct.strictObject({id:Ct.string().trim().min(1).max(255),name:Ct.string().trim().min(1).max(255),status:JA,metadata:ZA}),fw=WA.extend({internal_id:Ct.uuid(),project_id:Ct.uuid(),environment_id:Ct.uuid(),created_at:Ct.iso.datetime({offset:!0}),updated_at:Ct.iso.datetime({offset:!0})}),pd=Ct.union([Ct.strictObject({id:Ct.string().trim().min(1).max(255)}),Ct.strictObject({internalId:Ct.uuid()})]),gw=Ct.enum(["customer","merchandise","context"]),hw=Ct.enum(["system","stored","request"]),Aw=Ct.enum(["customer","merchandise","mixed"]),dd=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function Us(e,t={},n=new Set){if(Jn(e).some(dd))return!0;for(let r of Fn(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&dd(i.attributeKey)||i?.type==="condition"&&Us(i.condition,t,n))return!0}return!1}import{z as YA}from"zod";var XA=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,gn=YA.string().max(16).regex(XA,"\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 Ow=X.enum(["draft","active","paused","archived"]),Zn=X.discriminatedUnion("type",[X.object({type:X.literal("percent"),percentOff:X.number().min(1).max(100).multipleOf(.01)}).strict(),X.object({type:X.literal("amount"),amountOffCents:X.number().int().min(1).max(1e8),currency:he}).strict()]),en=X.discriminatedUnion("type",[X.object({type:X.literal("once")}).strict(),X.object({type:X.literal("repeating"),months:X.number().int().min(1).max(36)}).strict(),X.object({type:X.literal("forever")}).strict()]),md=[X.object({type:X.literal("all")}).strict(),X.object({type:X.literal("plans"),planIds:X.array(X.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],ey=X.discriminatedUnion("type",[...md,X.strictObject({type:X.literal("merchandise"),scope:X.discriminatedUnion("type",[X.strictObject({type:X.literal("all")}),X.strictObject({type:X.literal("selected"),merchandiseIds:X.array(X.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),X.strictObject({type:X.literal("condition"),condition:Ht})])})]),Ls=X.discriminatedUnion("type",[...md,X.strictObject({type:X.literal("merchandise"),scope:X.strictObject({type:X.enum(["all","selected","condition"])})})]),ty=X.strictObject({firstPurchaseOnly:X.boolean(),condition:Ht}),_w=X.object({name:X.string().trim().min(1).max(80),description:X.string().max(500),discount:Zn,duration:en,appliesTo:ey,eligibility:ty,selfClaimEnabled:X.boolean().default(!1),startsAt:X.iso.datetime().nullable(),endsAt:X.iso.datetime().nullable(),totalLimit:X.number().int().min(1).max(1e6).nullable(),perCustomerLimit:X.number().int().min(1).max(10),grantWindowHours:X.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=>!Us(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"]}),Cw=X.object({code:X.string().trim().transform(e=>e.toUpperCase()).pipe(X.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:X.number().int().min(1).max(1e6).nullable(),expiresAt:X.iso.datetime().nullable(),firstPurchaseOnly:X.boolean(),minimumAmountCents:X.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:he.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var ji=X.object({id:X.uuid(),couponId:X.uuid(),status:X.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:X.iso.datetime(),expiresAt:X.iso.datetime(),coupon:X.object({name:X.string(),discount:Zn,duration:en,appliesTo:Ls}).strict()}).strict(),fd=X.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var bd=h.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),zs=h.string().regex(/^(0|[1-9]\d{0,14})$/),Hr=h.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),ny=h.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),Ti=ny,Mn=ge.refine(e=>/[1-9]/.test(e)),Mt=h.iso.datetime({offset:!0}),Ko=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"))},ry=h.array(h.object({upTo:Mn.nullable(),unitAmountMinor:bd,flatAmountMinor:h.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&&Ko(t.upTo)>Ko(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),iy=h.discriminatedUnion("kind",[h.object({kind:h.literal("flat"),units:Mn,unitAmountMinor:bd}).strict(),h.object({kind:h.enum(["graduated","volume"]),units:Mn,tiers:ry}).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"),oy=h.strictObject({interval:h.enum(["month","year"]),count:h.number().int().min(1).max(12),anchor:h.enum(["membership","calendar"])}),Ni=h.object({currency:he,pricing:iy,billingCycle:oy.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var gd={requestId:h.uuid(),productVersionId:h.uuid(),internal_feature_id:h.uuid(),currency:he},Sd=h.strictObject({interval:h.enum(["hour","day","week","month"]),intervalCount:h.number().int().min(1).max(12),limit:h.number().int().min(1).max(1e6)}),xd=h.discriminatedUnion("kind",[h.object({...gd,kind:h.literal("auto_topup"),threshold:To,quantity:Mn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Sd.optional()}).strict(),h.object({...gd,kind:h.literal("postpaid"),maxAmountMinorPerPeriod:Ti,maxOutstandingMinor:Ti}).strict()]),hd={productVersionId:h.uuid(),internal_feature_id:h.uuid(),currency:he},Id=h.discriminatedUnion("kind",[h.object({...hd,kind:h.literal("auto_topup"),threshold:To,quantity:Mn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Sd.optional(),purchaseAmountMinor:Ti,purchaseUnits:Mn}).strict(),h.object({...hd,kind:h.literal("postpaid"),maxAmountMinorPerPeriod:Ti,maxOutstandingMinor:Ti,cashPrice:Ni}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),Ho=h.object({id:h.uuid(),terms:Id,status:h.enum(["prepared","active","revoked","blocked"]),createdAt:Mt,acceptedAt:Mt.nullable(),effectiveAt:Mt.nullable(),revokedAt:Mt.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"),vd=h.object({authorizationId:h.uuid(),terms:Id,setupUrl:h.url().nullable()}).strict(),wd=h.object({authorizationId:h.uuid(),accepted:h.literal(!0)}).strict(),Od=h.object({authorizationId:h.uuid(),requestId:h.uuid()}).strict(),_d=h.object({internal_feature_id:h.uuid(),entityId:h.uuid().nullable(),interval:h.enum(["day","week","month","year"]),anchor:h.enum(["billing_cycle","utc"]).optional(),basis:h.enum(["usage","credits"]),filter:gt.optional(),limit:ge.nullable(),thresholds:h.array(h.number().positive().max(1)).max(8),includedThresholds:h.array(h.number().positive().max(1)).max(8).optional(),absoluteThresholds:h.array(Mn).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&&Ko(t)>Ko(i)}),"Notification thresholds must increase"),ay=_d.safeExtend({requestId:h.uuid()}),Ad={control:h.literal("overage"),requestId:h.uuid(),internal_feature_id:h.uuid(),entityId:h.uuid().nullable()},sy=h.discriminatedUnion("action",[h.strictObject({...Ad,action:h.literal("set"),allowed:h.boolean().nullable(),overageLimit:ge.nullable(),skipOverageBilling:h.boolean()}),h.strictObject({...Ad,action:h.literal("remove")})]),Cd=h.union([ay,sy]),cy=h.strictObject({internal_feature_id:h.uuid(),entityId:h.uuid().nullable(),allowed:h.boolean().nullable(),overageLimit:ge.nullable(),skipOverageBilling:h.boolean(),interval:h.enum(["day","week","month","year"]),startsAt:Mt,endsAt:Mt,used:h.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:h.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:h.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),uy=h.object({internal_feature_id:h.uuid(),entityId:h.uuid().nullable(),interval:h.enum(["day","week","month","year"]),anchor:h.enum(["billing_cycle","utc"]).optional(),basis:h.enum(["usage","credits"]),filter:gt.optional(),startsAt:Mt,endsAt:Mt,used:Kt,reserved:Kt,limit:ge.nullable(),thresholds:h.array(h.number().positive().max(1)).max(8),notifiedThresholds:h.array(h.number().positive().max(1)).max(1024),includedThresholds:h.array(h.number().positive().max(1)).max(8).optional(),includedAllowance:h.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:h.array(h.number().positive().max(1)).max(1024).optional(),absoluteThresholds:h.array(Mn).max(8).optional(),notifiedAbsoluteThresholds:h.array(Mn).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||ge.safeParse(e.used).success&&ge.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),ly=h.object({authorizationId:h.uuid(),status:h.enum(["idle","pending","blocked"]),taskId:h.uuid().nullable(),invoiceId:h.uuid().nullable(),hostedInvoiceUrl:h.url().nullable(),purchaseCount:h.number().int().nonnegative(),purchaseWindowEndsAt:Mt.nullable(),attemptCount:h.number().int().nonnegative(),failedAttemptCount:h.number().int().nonnegative(),suspendedAt:Mt.nullable(),nextAttemptAt:Mt.nullable(),failureReason:h.string().min(1).max(240).nullable()}).strict(),Pd=h.object({internal_feature_id:h.uuid().optional(),entityId:h.uuid().optional()}).strict(),$s=h.object({authorizations:h.array(Ho).max(100),limits:h.array(_d).max(100),overages:h.array(cy).max(100).optional(),windows:h.array(uy).max(200),autoTopups:h.array(ly).max(100),limited:h.boolean()}).strict(),dy=h.object({id:h.uuid(),internal_feature_id:h.uuid(),productVersionId:h.uuid(),authorizationId:h.uuid(),entityId:h.uuid().nullable(),units:ge,amountMinor:Hr,cashPrice:Ni}).strict(),Di=h.object({id:h.uuid(),sourceKind:h.enum(["product","usage","manual"]),providerInvoiceId:h.string().min(1).max(240).nullable(),status:h.enum(["accruing","open","pending","paid","failed","void"]),currency:he,startsAt:Mt.nullable(),endsAt:Mt.nullable(),amountMinor:h.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:h.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:zs,paidAmountMinor:zs,refundedAmountMinor:zs,createdAt:Mt,hostedInvoiceUrl:h.url().nullable(),adjustment:h.object({originalInvoiceId:h.uuid(),amountMinor:h.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:Mt.nullable(),reason:h.string().min(1).max(500).optional()}).strict().nullable(),lines:h.array(dy).max(100),linesLimited:h.boolean()}).strict(),Ed=h.object({invoiceId:h.uuid(),accepted:h.literal(!0)}).strict(),Rd=h.strictObject({requestId:h.uuid(),originalInvoiceId:h.uuid(),amountMinor:h.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:h.string().trim().min(1).max(500)}),kd=h.object({after:h.uuid().nullable(),limit:h.number().int().min(1).max(100)}).strict(),jd=h.object({rows:h.array(Di).max(100),nextCursor:h.uuid().nullable()}).strict(),yd=h.strictObject({id:h.string(),coupon:h.string(),start:h.number().nonnegative(),end:h.number().nullable()}),py=h.strictObject({subscriptionId:h.string(),customerId:h.string(),accountId:h.string(),sourceItems:h.array(h.strictObject({id:h.string(),price_id:h.string(),quantity:h.number().int(),discounts:h.array(yd).optional()})).max(100),items:h.array(h.strictObject({id:h.string(),price:h.string(),quantity:h.number().int(),discounts:h.array(h.strictObject({coupon:h.string().optional(),terms:h.strictObject({id:h.string(),name:h.string().optional(),percent_off:h.number().optional(),amount_off:h.number().optional(),currency:h.string().optional(),duration:h.enum(["once","forever","repeating"]),duration_in_months:h.number().optional()}).optional(),discount:h.string().optional(),receipt:yd.optional()})).max(20)})).max(100)}),Td=h.strictObject({membershipId:h.uuid(),requestId:h.uuid(),grantIds:h.array(h.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),Nd=h.strictObject({membershipId:h.uuid(),operationId:h.uuid(),status:h.enum(["pending","effective"]),execution:py.nullable(),grants:h.array(h.strictObject({id:h.uuid(),couponId:h.uuid(),name:h.string(),discount:Zn,duration:en,startedAt:Mt.nullable()})).max(20)});import{z as Fi}from"zod";var Dd=Fi.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),Fd=Fi.number().int().min(1).max(1e3),Qo=Fi.object({cap:ge.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:Fi.number().positive().max(1e4).nullable(),cycles:Fi.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 Wn}from"zod";var Md=Wn.strictObject({itemKey:Wn.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:Wn.uuid(),includedAmount:Wn.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:Wn.number().int().min(0).max(1e4),terms:Do,pricing:Pi.optional(),unitAmountMinor:Wn.number().int().min(0).max(1e8),productId:Wn.string().min(1).max(255).nullable(),priceId:Wn.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{El(e.includedAmount,e.terms.units,e.quantity),No({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 ee}from"zod";var Sr=ge.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Mi=ee.string().min(1).max(120),Jo=ee.enum(["cap","overflow"]),tn=(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"))},qi=e=>{try{return e()}catch{return!1}},Vi=ee.discriminatedUnion("operation",[ee.object({operation:ee.literal("quote"),overageBehavior:Jo.optional(),internal_feature_id:ee.uuid(),entityId:ee.uuid().optional(),quantity:Sr,properties:gt}).strict(),ee.object({operation:ee.literal("consume"),overageBehavior:Jo.optional(),occurredAt:ee.iso.datetime({offset:!0}).optional(),internal_feature_id:ee.uuid(),entityId:ee.uuid().optional(),quantity:ge,properties:gt,idempotencyKey:Mi}).strict(),ee.object({operation:ee.literal("reserve"),occurredAt:ee.iso.datetime({offset:!0}).optional(),internal_feature_id:ee.uuid(),entityId:ee.uuid().optional(),quantity:Sr,properties:gt,idempotencyKey:Mi,expiresInSeconds:ee.number().int().min(1).max(86400)}).strict(),ee.object({operation:ee.literal("confirm"),operationId:ee.uuid(),quantity:Sr,properties:gt.optional(),idempotencyKey:Mi}).strict(),ee.object({operation:ee.literal("refund"),operationId:ee.uuid(),quantity:Sr,idempotencyKey:Mi}).strict(),ee.object({operation:ee.literal("release"),operationId:ee.uuid(),idempotencyKey:Mi}).strict()]),Gs=ee.object({internal_credit_feature_id:ee.uuid().nullable(),internal_metered_feature_id:ee.uuid(),dimension:ee.string().min(1).max(64),counterKey:ee.string().min(1).max(240),cycleStart:ee.iso.datetime({offset:!0}),unitCost:ge,units:Sr,amount:Kt,tier:ee.number().int().min(1).max(12).nullable()}).strict(),xr=ee.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function qd(e,t){let n=e.reduce((r,i)=>r+tn(i.units,12),0n)-tn(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var Vd=ee.discriminatedUnion("funding",[ee.strictObject({funding:ee.literal("balance"),sourceId:ee.uuid(),rolloverId:ee.uuid().nullable(),units:xr.refine(e=>/[1-9]/.test(e)),amount:Kt}),ee.strictObject({funding:ee.literal("unbilled"),units:xr.refine(e=>/[1-9]/.test(e))}),ee.object({funding:ee.literal("prepaid"),sourceId:ee.uuid(),units:Sr,amount:Kt,pricing:ee.array(Gs).min(1).max(12)}).strict().refine(e=>qi(()=>e.pricing.reduce((t,n)=>t+tn(n.units,6),0n)===tn(e.units,6)&&e.pricing.reduce((t,n)=>t+tn(n.amount,12),0n)===tn(e.amount,12)&&e.pricing.every(t=>tn(t.unitCost,6)*tn(t.units,6)===tn(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),ee.object({funding:ee.literal("postpaid"),invoiceLineId:ee.uuid().nullable(),units:Sr,authorizationId:ee.uuid()}).strict()]),Zo=ee.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),Bd=ee.object({allowed:ee.boolean(),internal_feature_id:ee.uuid(),quantity:ge,requestedQuantity:ge.optional(),overageBehavior:Jo.optional(),reason:Zo.nullable(),allocations:ee.array(Vd).max(500)}).strict().refine(e=>qi(()=>e.allowed?e.reason===null&&qd(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>qi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&tn(e.requestedQuantity,6)>=tn(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Bi=ee.object({id:ee.uuid(),internal_feature_id:ee.uuid(),kind:ee.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:ee.uuid().nullable(),quantity:ge,requestedQuantity:ge.optional(),overageBehavior:Jo.optional(),accepted:ee.boolean(),reason:ee.enum([...Zo.options,"expired"]).nullable(),createdAt:ee.iso.datetime({offset:!0}),reservationStatus:ee.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:ee.iso.datetime({offset:!0}).nullable(),allocations:ee.array(Vd).max(500)}).strict().refine(e=>qi(()=>e.accepted?e.reason===null&&qd(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>qi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&tn(e.requestedQuantity,6)>=tn(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 Re}from"zod";var Ir=Re.iso.datetime({offset:!0}),Ud=ge.refine(e=>/[1-9]/.test(e)),Ld=Re.strictObject({interval:Dd.exclude(["lifetime"]),count:Fd}),my=Re.strictObject({action:Re.literal("create"),requestId:Re.uuid(),internal_feature_id:Re.uuid(),entityId:Re.uuid().nullable(),amount:Ud.nullable(),expiresAt:Ir.nullable(),reset:Ld.nullable(),rollover:Qo.nullable(),nextResetAt:Ir.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"),zd=Re.discriminatedUnion("action",[my,Re.strictObject({action:Re.literal("update"),requestId:Re.uuid(),grantId:Re.uuid(),revision:Re.number().int().nonnegative(),amount:Ud.nullable(),expiresAt:Ir.nullable(),rollover:Qo.nullable(),nextResetAt:Ir.nullable()}),Re.strictObject({action:Re.enum(["add","subtract","set_remaining"]),requestId:Re.uuid(),grantId:Re.uuid(),revision:Re.number().int().nonnegative(),amount:ge}),Re.strictObject({action:Re.literal("revoke"),requestId:Re.uuid(),grantId:Re.uuid(),revision:Re.number().int().nonnegative()})]),Ks=Re.strictObject({id:Re.uuid(),internal_feature_id:Re.uuid(),entityId:Re.uuid().nullable(),amount:ge.nullable(),reset:Ld.nullable(),rollover:Qo.nullable(),nextResetAt:Ir.nullable(),startsAt:Ir,expiresAt:Ir.nullable(),revision:Re.number().int().nonnegative(),revoked:Re.boolean(),available:Kt,held:Kt,spent:Kt}),$d=Re.strictObject({customerId:Re.uuid(),after:Re.uuid().nullable(),limit:Re.number().int().min(1).max(100)}),Gd=Re.strictObject({rows:Re.array(Ks).max(100),nextCursor:Re.uuid().nullable()});import{z as ne}from"zod";var On=ne.iso.datetime({offset:!0}),Kd=ne.strictObject({invoiceId:ne.uuid(),after:ne.string().min(1).max(180).nullable(),limit:ne.number().int().min(1).max(100)}),fy=ne.strictObject({kind:ne.literal("product"),key:ne.string(),productVersionId:ne.uuid(),productName:ne.string(),itemKey:ne.string(),entityId:ne.uuid().nullable(),quantity:ne.number().positive(),subtotalMinor:ne.string().regex(/^-?\d+$/),discountMinor:ne.string().regex(/^\d+$/),taxMinor:ne.string().regex(/^-?\d+$/).nullable(),totalMinor:ne.string().regex(/^-?\d+$/),startsAt:On.nullable(),endsAt:On.nullable(),providerLineId:ne.string().nullable(),providerItemId:ne.string()}),Hd=ne.strictObject({invoice:Di,items:ne.array(ne.discriminatedUnion("kind",[fy,ne.strictObject({kind:ne.literal("invoice_credit"),key:ne.string(),internal_feature_id:ne.uuid(),internal_credit_feature_id:ne.uuid(),name:ne.string(),units:ge,reserved:ge,amountMinor:Hr,grossAmountMinor:Hr,creditsAppliedMinor:Hr,properties:gt,cashPrice:Ni,providerItemId:ne.string().nullable(),creditProviderItemId:ne.string().nullable()}),ne.strictObject({kind:ne.literal("usage"),key:ne.string(),internal_feature_id:ne.uuid(),name:ne.string(),units:ge,reserved:ge,amountMinor:Hr,cashPrice:Ni})])).max(100),nextCursor:ne.string().min(1).max(180).nullable()}),gy=ne.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),Hs=ne.strictObject({from:On,to:On,entityId:ne.uuid().optional(),snapshotAt:On.nullable(),after:ne.strictObject({at:On,id:ne.uuid(),position:ne.number().int().nonnegative()}).nullable(),limit:ne.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"),Qd=ne.strictObject({customerId:ne.uuid(),entityId:ne.uuid().nullable(),from:On,to:On,snapshotAt:On,totals:ne.array(ne.strictObject({internal_credit_feature_id:ne.uuid(),name:ne.string(),consumed:Kt,refunded:Kt,net:gy})).max(1e3),rows:ne.array(ne.strictObject({operationId:ne.uuid(),position:ne.number().int().nonnegative(),kind:ne.enum(["consume","confirm","refund"]),originalId:ne.uuid().nullable(),occurredAt:On,internal_feature_id:ne.uuid(),entitlementName:ne.string(),sourceId:ne.uuid(),internal_credit_feature_id:ne.uuid(),creditName:ne.string(),units:xr,amount:Kt,pricing:ne.array(Gs).max(12),properties:gt})).max(100),nextCursor:Hs.shape.after});import{z as T}from"zod";import{z as hn}from"zod";var hy=hn.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),Ay=hn.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),Wo=hn.strictObject({internal_feature_id:hn.uuid(),entityId:hn.uuid().nullable()}),Jd=Wo.extend({quantity:ge,expectedRevision:hn.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:hn.string().min(1).max(120),properties:gt.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),Ui=Wo.extend({operationId:hn.uuid().nullable(),usage:ge,capacity:hy.nullable(),remaining:Ay.nullable(),withinLimit:hn.boolean(),revision:hn.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:hn.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 qt=T.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),An=T.iso.datetime({offset:!0}),yy=T.enum(["access","metered","credit"]),Li={internal_feature_id:T.uuid(),key:yr,name:T.string().min(1).max(120),kind:yy},Zd=T.object({customerId:T.uuid(),snapshotAt:An,memberships:T.array(T.object({id:T.uuid(),productId:T.string().min(1).max(255),productVersionId:T.uuid(),billingProductVersionId:T.uuid(),version:T.number().int().positive(),key:T.string().min(1).max(64),name:T.string().min(1).max(120),groupId:T.string().max(255).nullable(),membershipType:T.enum(["main","addon"]),status:T.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:T.boolean(),accessEnabled:T.boolean(),renewalChange:T.object({productVersionId:T.uuid(),name:T.string().min(1).max(120),version:T.number().int().positive(),effectiveAt:An,benefitsAppliedAt:An.nullable(),timing:T.enum(["immediate","renewal"]),changeKind:T.enum(["plan","seats","quantity"]),feature:T.strictObject({internal_feature_id:T.uuid(),name:T.string().min(1).max(80),fromQuantity:T.number().int().min(0).max(1e4),toQuantity:T.number().int().min(0).max(1e4)}).optional(),seat:T.object({key:T.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:T.number().int().min(0).max(1e4),toQuantity:T.number().int().min(0).max(1e4)}).strict().nullable(),status:T.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:T.object({phase:T.enum(["paid","trial"]),startsAt:An,endsAt:An.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:T.boolean(),balances:T.array(T.object({...Li,usageType:T.enum(["consumable","non_consumable"]).nullable(),accessible:T.boolean(),unlimited:T.boolean(),available:qt,held:qt,debt:qt,nextExpiresAt:An.nullable(),usage:Ui.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:T.boolean()}).strict(),Wd=T.enum(["source","usage","transaction","invoice","debt","settlement"]),Yo=T.object({at:An,id:T.uuid(),type:Wd}).strict(),Yd=T.object({type:Wd.nullable(),resourceKey:yr.optional(),kind:T.enum(["purchase","refund"]).optional(),topup:T.boolean().optional(),from:T.iso.date().nullable(),to:T.iso.date().nullable(),after:Yo.nullable(),limit:T.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),Qr={id:T.uuid(),occurredAt:An},by=T.discriminatedUnion("type",[T.strictObject({...Qr,type:T.literal("invoice"),status:T.string().min(1).max(80),paid:qt,refunded:qt,currency:he,externalId:T.string().nullable()}),T.object({...Qr,...Li,type:T.literal("source"),reason:T.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:qt,unlimited:T.boolean(),status:T.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:An,expiresAt:An.nullable(),orderId:T.uuid().nullable(),parentSourceId:T.uuid().nullable()}).strict(),T.object({...Qr,type:T.literal("usage"),internal_feature_id:T.uuid(),name:T.string().min(1).max(120),kind:T.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:T.uuid().nullable(),quantity:ge,accepted:T.boolean(),reason:T.enum([...Zo.options,"expired"]).nullable(),properties:gt,reservationStatus:T.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:An.nullable(),charges:T.array(T.discriminatedUnion("funding",[T.strictObject({funding:T.literal("balance"),sourceId:T.uuid(),rolloverId:T.uuid().nullable(),units:xr,amount:qt}),T.strictObject({funding:T.literal("unbilled"),units:xr}),T.object({...Li,funding:T.literal("prepaid"),amount:qt}).strict(),T.object({funding:T.literal("postpaid"),invoiceId:T.uuid(),invoiceLineId:T.uuid(),authorizationId:T.uuid(),units:ge,currency:he}).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"),T.object({...Qr,type:T.literal("transaction"),purpose:T.enum(["product","invoice"]),productVersionId:T.uuid().nullable(),productName:T.string().min(1).max(120).nullable(),productVersion:T.number().int().positive().nullable(),invoiceId:T.uuid().nullable(),orderId:T.uuid(),originalId:T.uuid().nullable(),kind:T.enum(["purchase","refund"]),amountMinor:T.number().int().nonnegative().max(2e8).nullable(),currency:he.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"),T.object({...Qr,...Li,type:T.literal("debt"),sourceId:T.uuid(),transactionId:T.uuid(),amount:qt}).strict(),T.object({...Qr,...Li,type:T.literal("settlement"),sourceId:T.uuid(),debtId:T.uuid(),kind:T.enum(["payment","usage_refund","payment_return"]),amount:qt}).strict()]),Xd=T.object({customerId:T.uuid(),rows:T.array(by).max(50),nextCursor:Yo.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 le}from"zod";var tp=le.object({customerId:le.uuid()}).strict(),np=le.discriminatedUnion("action",[le.object({customerId:le.uuid(),requestId:le.uuid(),action:le.literal("assign"),poolId:le.uuid(),memberCustomerId:le.uuid()}).strict(),le.strictObject({customerId:le.uuid(),requestId:le.uuid(),action:le.literal("assign_entity"),poolId:le.uuid(),entityId:le.uuid()}),le.object({customerId:le.uuid(),requestId:le.uuid(),action:le.literal("release"),poolId:le.uuid(),slotId:le.uuid()}).strict()]),zi=le.number().int().nonnegative(),Qs=le.iso.datetime({offset:!0}),Js=le.strictObject({internalId:le.uuid(),id:le.string(),name:le.string().nullable(),version:le.number().int().positive()}),ep=le.enum(["active","past_due"]),Zs=le.strictObject({customerId:le.uuid(),licenses:le.array(le.strictObject({id:le.uuid(),linkId:le.uuid(),parent:le.strictObject({customerProductId:le.uuid(),status:ep,product:Js}),product:Js,planLicense:le.strictObject({id:le.uuid(),prepaidOnly:le.boolean(),isCustom:le.boolean()}).nullable(),granted:zi,included:zi,paidQuantity:zi,usage:zi,remaining:zi,createdAt:Qs}).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:le.array(le.strictObject({id:le.uuid(),linkId:le.uuid(),status:ep,product:Js,entity:le.strictObject({internalId:le.uuid(),id:le.string().nullable(),name:le.string().nullable()}).nullable(),beneficiary:le.strictObject({internalId:le.uuid(),id:le.string().nullable(),name:le.string().nullable()}).nullable(),startedAt:Qs.nullable(),endedAt:Qs.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:le.boolean()});import{z as ue}from"zod";var $i=ue.enum(["email","sms","voice","push"]),pO=ue.enum(["resend","twilio","fcm","apns"]);var mO=ue.string().regex(/^\+[1-9]\d{1,14}$/),Sy=ue.enum(["email_recipient","sms_segment","voice_second","push_device"]);var xy=ue.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),Iy=ue.strictObject({subject:xy,html:ue.string().min(1).max(131072).optional(),text:ue.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),vy=ue.strictObject({body:ue.string().min(1).max(1600).refine(e=>e.trim().length>0)}),wy=ue.strictObject({text:ue.string().trim().min(1).max(4e3),language:ue.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:ue.number().int().min(1).max(900)}),Oy=ue.record(ue.string().min(1).max(64),ue.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"),_y=ue.strictObject({title:ue.string().trim().min(1).max(200),body:ue.string().trim().min(1).max(2e3),url:ue.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:Oy.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),rp=ue.discriminatedUnion("channel",[ue.strictObject({channel:ue.literal("email"),content:Iy}),ue.strictObject({channel:ue.literal("sms"),content:vy}),ue.strictObject({channel:ue.literal("voice"),content:wy}),ue.strictObject({channel:ue.literal("push"),content:_y})]),ip=ue.strictObject({requestId:ue.uuid(),customerId:ue.uuid(),connectionId:ue.uuid().optional(),message:rp,expiresAt:ue.iso.datetime({offset:!0})}),Cy=ue.array(ue.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),Py=ue.discriminatedUnion("kind",[ue.strictObject({kind:ue.literal("all")}),ue.strictObject({kind:ue.literal("customers"),customerIds:Cy})]),fO=ue.strictObject({name:ue.string().trim().min(1).max(120),connectionId:ue.uuid().optional(),message:rp,audience:Py,frequencyLimit:ue.number().int().min(1).max(100)}),op=ue.strictObject({requestId:ue.uuid(),channel:$i,state:ue.enum(["allowed","denied"]),expectedRevision:ue.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),ap=ue.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),sp=ue.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),gO=ue.strictObject({meter:Sy,estimatedUnits:ue.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:ue.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});import{z as ve}from"zod";import{z as te}from"zod";import{z as Jr}from"zod";var Gi=Jr.strictObject({internalFeatureId:Jr.uuid(),name:Jr.string().min(1).max(120),includedAmount:Jr.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:Jr.enum(["hour","day","week","month","year","lifetime"]),resetCount:Jr.number().int().min(1).max(100),terms:Do});import{z as nt}from"zod";import{z as Ey}from"zod";import{z as Zr}from"zod";var cp=Zr.enum(["stripe","apple","google","merchant"]),up=Zr.enum(["membership","credit_pack","lifetime"]),xO=Zr.enum(["active","grace","suspended","inactive","revoked"]),IO=Zr.strictObject({currency:Zr.string().regex(/^[A-Z]{3}$/),micros:Zr.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var Wr=Ey.object({provider:cp,currency:he}).strict();var Yn=nt.strictObject({internal_feature_id:nt.uuid(),quantity:ge.refine(e=>/[1-9]/.test(e)),properties:gt,entityId:nt.uuid().optional()}),lp=nt.strictObject({requirement:Yn,commerce:Wr.optional(),paywallId:nt.uuid().optional()}),Ry=nt.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),Ws=nt.strictObject({productId:nt.string().min(1),productVersionId:nt.string().min(1),name:nt.string().min(1).max(120),action:nt.enum(["purchase","upgrade","addon","topup"]),membershipId:nt.string().min(1).nullable(),currency:he,amountMinor:nt.string().regex(/^(0|[1-9]\d{0,8})$/),interval:nt.enum(["free","week","month","year","one_time"]),intervalCount:nt.number().int().min(1).max(156)}),vr=nt.strictObject({internal_feature_id:nt.string().min(1),name:nt.string().min(1).max(120),kind:nt.enum(["access","metered","credit"]),quantity:ge,allowed:nt.boolean(),reason:Ry.nullable(),preview:nt.strictObject({scenario:nt.enum(["feature_flag","usage_limit"]),candidates:nt.array(Ws).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"})}),jO=nt.strictObject({paywallId:nt.uuid(),requirement:Yn});var ea=te.object({plan:te.string().min(1).max(200).optional(),coupon:te.uuid().optional(),promotionCode:te.uuid().optional(),picker:te.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),Xo=te.object({text:te.string().optional(),label:te.string().optional(),alt:te.string().optional(),html:te.string().max(32768).optional(),price:te.object({current:te.string(),original:te.string().nullable(),period:te.string()}).optional(),code:te.string().optional(),countdownAt:te.iso.datetime().optional(),planId:te.string().min(1).max(200).optional(),planVersionId:te.string().min(1).max(200).optional(),currency:he.optional(),couponId:te.uuid().optional(),offerId:te.uuid().optional(),unavailable:te.boolean().optional(),unavailableReason:te.string().optional(),missing:te.array(te.string()).optional()}).strict(),Yr=te.object({paywall:vr.optional(),nodes:te.record(te.string(),te.object({base:Xo,picker:te.string().optional(),byPlan:te.record(te.string(),Xo).optional()}).strict()),plans:te.record(te.string(),te.object({id:te.string().min(1).max(200),versionId:te.string().min(1).max(200),available:te.boolean(),name:te.string(),price:te.string(),period:te.string(),currency:he.optional(),amountMinor:te.number().int().nonnegative().optional(),interval:te.enum(["free","week","month","year","one_time"]).optional(),intervalCount:te.number().int().positive().optional(),prepaid:te.array(Gi).max(100).optional()}).strict()),pickers:te.record(te.string(),te.object({options:te.array(te.string().min(1).max(200)).max(20),selected:te.string().min(1).max(200).nullable()}).strict()),quantities:te.record(te.string(),te.strictObject({minimum:te.number().int().nonnegative(),maximum:te.number().int().nonnegative(),step:te.number().int().positive(),value:te.number().int().nonnegative(),label:te.string(),available:te.boolean()})).optional(),diagnostics:te.array(te.object({nodeId:te.string(),message:te.string()}).strict())}).strict();function dp(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}import{z as x}from"zod";function ky(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function pp(e){let t={};function n(r){var i;if(ky(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 qn}from"zod";var mp=qn.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ta=qn.strictObject({tiers:qn.array(qn.strictObject({id:mp,name:qn.string().trim().min(1).max(80)})).min(1).max(8),assignments:qn.array(qn.strictObject({productVersionId:qn.string().min(1).max(200),tierId:mp,period:qn.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 na(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}import{z as oe}from"zod";var jy=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],fp=oe.enum(jy),gp=oe.object({source:fp,layout:oe.enum(["full","compact"]),resourceKey:yr.optional(),pageSize:oe.number().int().min(1).max(50),showSources:oe.boolean(),allowPurchase:oe.boolean(),outputs:oe.object({billing_adjustment:oe.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:oe.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:oe.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:oe.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:oe.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:oe.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"})}),vt=oe.string().max(2e3),hp=oe.object({id:oe.string().max(100),label:vt,detail:oe.array(vt).max(12),value:vt.optional(),status:vt.optional(),facts:oe.array(oe.object({label:vt,value:vt}).strict()).max(1e3),purchaseId:oe.uuid().optional(),invoiceUrl:oe.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:oe.array(oe.strictObject({action:oe.literal("invoice_open"),label:vt})).max(1).optional(),membershipActions:oe.array(oe.object({value:oe.string().max(100),label:vt}).strict()).max(3).optional()}).strict(),Ty=oe.object({key:yr,name:vt,spendable:vt,reserved:vt,available:vt,expiry:vt.nullable(),sources:oe.array(hp).max(50),sourceCount:oe.number().int().nonnegative(),sourcePage:oe.number().int().positive(),hasNextSources:oe.boolean(),hasPreviousSources:oe.boolean()}).strict(),Ny=oe.object({source:fp,status:oe.enum(["idle","loading","ready","error"]),stale:oe.boolean(),preview:oe.boolean(),errorCode:oe.string().max(80).optional(),errorMessage:vt.optional(),resources:oe.array(Ty).max(500),rows:oe.array(hp).max(50),hasNext:oe.boolean(),hasPrevious:oe.boolean(),page:oe.number().int().positive(),filter:oe.string().max(40),updatedAt:oe.iso.datetime().optional(),buyingId:oe.uuid().optional(),membershipBusy:oe.boolean().optional(),billingBusy:oe.boolean().optional(),membershipReview:oe.object({title:vt,note:vt,facts:oe.array(oe.object({label:vt,value:vt}).strict()).max(100)}).strict().optional(),membershipResult:vt.optional()}).strict(),Ap=oe.object({nodes:oe.record(oe.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ny)}).strict(),$O=oe.object({nodeId:oe.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:oe.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:oe.string().max(100).optional()}).strict();var Fy=4,bn={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},Hi=x.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Te=x.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),My=x.enum(["none","xs","sm","md","lg","xl"]),qy=x.enum(["none","sm","md","lg","full"]),Ys=x.string().regex(/^#[0-9a-fA-F]{6}$/),Sp=x.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"),Xs=x.union([Sp,x.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),x.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),x.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),yp=x.object({primary:Ys,background:Ys,text:Ys,radius:qy,font:x.enum(["system","serif","rounded","mono"])}).strict(),Qi=x.union([x.enum(["primary","text","muted","background","surface"]),x.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),je=(e,t)=>x.number().int().min(e).max(t),bp=x.union([x.enum(["fit","fill"]),je(1,1200)]),Vy=x.object({top:je(0,200),right:je(0,200),bottom:je(0,200),left:je(0,200)}).strict(),By=x.object({top:je(-100,200),right:je(-100,200),bottom:je(-100,200),left:je(-100,200)}).strict(),xp=x.object({x:je(0,100),y:je(0,100)}).strict(),Uy=x.discriminatedUnion("type",[x.object({type:x.literal("color"),color:Qi}).strict(),x.object({type:x.literal("linear"),angle:je(0,360),stops:x.array(x.object({color:Qi,at:je(0,100)}).strict()).min(2).max(4)}).strict(),x.object({type:x.literal("image"),src:Xs,fit:x.enum(["cover","contain"]),position:xp.optional()}).strict()]),Ly=x.discriminatedUnion("type",[x.object({type:x.literal("rect"),radius:x.union([je(0,200),x.object({topLeft:je(0,200),topRight:je(0,200),bottomRight:je(0,200),bottomLeft:je(0,200)}).strict()])}).strict(),x.object({type:x.literal("pill")}).strict()]),zy=x.object({width:je(0,12),color:Qi,style:x.enum(["solid","dashed"])}).strict(),$y=x.object({x:je(-40,40),y:je(-40,40),blur:je(0,80),spread:je(-20,40),color:Qi}).strict(),Gy=x.object({font:x.enum(["system","serif","rounded","mono"]),size:je(8,96),weight:x.number().int().min(100).max(900).multipleOf(100),lineHeight:x.number().min(.8).max(3),letterSpacing:x.number().min(-5).max(20),color:Qi,align:x.enum(["start","center","end"]),italic:x.boolean(),decoration:x.enum(["none","underline","line-through"]),transform:x.enum(["none","uppercase"])}).strict().partial(),wr=x.object({width:bp,height:bp,padding:Vy,margin:By,gap:je(0,120),grow:x.union([x.boolean(),x.number().min(0).max(12)]),background:Uy,opacity:x.number().min(0).max(1),clipContent:x.boolean(),shape:Ly,border:zy,shadow:$y,text:Gy}).strict().partial(),Jt={id:Hi,name:x.string().trim().min(1).max(60).optional(),hidden:x.boolean().optional(),style:wr.optional(),fallback:Te.optional()},Ky=x.object({...Jt,type:x.literal("text"),productField:x.enum(["name","price","trial","period"]).optional(),feature:x.object({id:x.uuid(),field:x.enum(["name","allowance"])}).strict().optional(),text:Te,variant:x.enum(["title","heading","body","caption"])}).strict(),Hy=x.object({...Jt,type:x.literal("image"),src:Xs,localizedSrc:x.record(gn,Xs).optional(),alt:Te,aspect:x.enum(["auto","1:1","4:3","16:9","3:1"]),fit:x.enum(["cover","contain"]),position:xp.optional()}).strict(),Qy=x.object({...Jt,type:x.literal("button"),label:Te,variant:x.enum(["primary","secondary","link"]),action:Te,purpose:x.enum(["purchase","navigation","close"]).optional(),bind:ea.optional()}).strict(),Jy=x.object({...Jt,type:x.literal("divider")}).strict(),Zy=x.object({...Jt,type:x.literal("customer_data"),title:Te,data:gp}).strict(),Wy=x.object({...Jt,type:x.literal("spacer"),size:My}).strict(),Yy=x.object({...Jt,type:x.literal("custom_html"),html:x.record(gn,x.string().max(bn.customHtml)),css:x.string().max(bn.customCss)}).strict(),Xy=x.object({...Jt,type:x.literal("price"),fallback:Te,parts:x.object({current:wr.optional(),original:wr.optional(),period:wr.optional()}).strict().optional()}).strict(),eb=x.object({...Jt,type:x.literal("coupon_code"),label:Te,fallback:Te}).strict(),tb=x.object({...Jt,type:x.literal("countdown"),source:x.enum(["offer.ends_at","offer.expires_at","fixed"]),at:x.iso.datetime().optional(),granularity:x.enum(["day","hour","minute","second"]),expired:Te,fallback:Te}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),nb=x.object({...Jt,type:x.literal("plan_picker"),label:Te,fallback:Te,planIds:x.array(x.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:x.string().min(1).max(200).optional(),grouping:ta.safeExtend({monthLabel:Te,yearLabel:Te,unavailableLabel:Te}).optional(),states:x.object({selected:wr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!na(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),rb=x.object({...Jt,type:x.literal("quantity_picker"),bind:ea.optional(),label:Te,fallback:Te,internalFeatureId:x.uuid(),minimumQuantity:je(0,1e4),maximumQuantity:je(0,1e4),defaultQuantity:je(0,1e4),step:je(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"),ib=x.discriminatedUnion("type",[x.object({type:x.literal("input"),label:Te,keyboard:x.enum(["text","email","tel","url"]),maxLength:je(1,500)}).strict(),x.object({type:x.literal("multiselect"),label:Te,min:je(0,50),max:je(1,50)}).strict(),x.object({type:x.literal("select"),label:Te,defaultIndex:je(0,49),purpose:x.enum(["option","product","tier"]).optional(),pickerId:Hi.optional(),selectedStyle:wr.optional()}).strict(),x.object({type:x.literal("tabs"),label:Te,defaultIndex:je(0,49),purpose:x.literal("tier").optional()}).strict(),x.object({type:x.literal("toggle"),label:Te,defaultEnabled:x.boolean()}).strict(),x.object({type:x.literal("carousel"),label:Te}).strict()]),yn={...Jt,type:x.literal("stack"),direction:x.enum(["vertical","horizontal","overlay"]),align:x.enum(["start","center","end","stretch"]),justify:x.enum(["start","center","end","between"]),productSlot:x.object({index:je(0,19),period:x.enum(["month","year"]).optional(),requireBinding:x.boolean().optional()}).strict().optional(),interaction:ib.optional(),states:x.object({selected:wr.optional()}).strict().optional(),purpose:x.literal("benefits").optional(),purchaseAction:Te.optional(),buttonVariant:x.enum(["primary","secondary","link"]).optional(),bind:ea.optional()},Ip=x.lazy(()=>x.object({...Jt,type:yn.type,direction:yn.direction,align:yn.align,justify:yn.justify,children:x.array(ob).max(bn.children),productSlot:yn.productSlot,interaction:yn.interaction,states:yn.states,purpose:yn.purpose,purchaseAction:yn.purchaseAction,buttonVariant:yn.buttonVariant,bind:yn.bind}).strict()),ob=x.lazy(()=>x.union([Ip,Ky,Hy,Qy,Jy,Wy,Yy,Xy,eb,tb,nb,rb,Zy])),ab=x.union([x.string().max(500),x.number().finite(),x.boolean(),x.null()]),Ki={id:Te,event:Te,properties:x.record(Te,ab).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},sb=x.discriminatedUnion("type",[x.object({...Ki,type:x.literal("navigate"),close:x.literal(!1),pageId:Hi}).strict(),x.object({...Ki,type:x.literal("event"),close:x.boolean()}).strict(),x.object({...Ki,type:x.literal("close"),close:x.literal(!0)}).strict(),x.object({...Ki,type:x.literal("open_url"),close:x.boolean(),url:Sp}).strict(),x.object({...Ki,type:x.literal("claim_offer"),close:x.boolean(),couponId:x.uuid()}).strict()]),cb=x.object({defaultLocale:gn,locales:x.record(gn,x.record(Te,x.string().max(bn.stringLength)))}).strict(),ub=x.enum(["popup","paywall","onboarding","page","banner"]);var lb=x.discriminatedUnion("type",[x.object({type:x.literal("modal"),size:x.enum(["sm","md","lg"])}).strict(),x.object({type:x.literal("sheet"),size:x.enum(["sm","md","lg"])}).strict(),x.object({type:x.literal("fullscreen")}).strict(),x.object({type:x.literal("inline")}).strict()]);var db=x.object({kind:x.literal("screen"),schemaVersion:x.literal(Fy),name:x.string().trim().min(1).max(80),surface:ub,initialPageId:Hi.optional(),presentation:lb,theme:yp,pages:x.array(x.object({id:Hi,name:x.string().trim().min(1).max(60),root:Ip,theme:yp.optional(),editorPosition:x.object({x:x.number().finite().min(-1e5).max(1e5),y:x.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(bn.pages),strings:cb,actions:x.array(sb).max(bn.actions)}).strict();function Vt(e,t){for(let n of e.pages)Vn(n.root,t)}var nn=db.superRefine((e,t)=>{let n=bn;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>bn.locales&&r(`\u6700\u591A ${bn.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;Vt(e,(l,m)=>{if(c++,m>bn.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 S of Object.keys(l.html))i.includes(S)||r(`\u81EA\u5B9A\u4E49 HTML ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${S}`);if(l.type==="image")for(let S of Object.keys(l.localizedSrc??{}))i.includes(S)||r(`\u56FE\u7247 ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${S}`)}),c>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),u&&r(`\u5C42\u7EA7\u6700\u591A ${bn.depth} \u5C42`)});function Vn(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)Vn(i,t,n+1,e)}function ra(e){let t=[],n=new Set;return Vt(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 pb(e,t,n){if(t.field==="html"){let r;return Vt(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=Ji(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 Xn(e){let t=ra(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=>!pb(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 mb(e,t){let n=null;return Vn(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function Ji(e,t){for(let n of e.pages){let r=mb(n.root,t);if(r)return r}return null}import{z as jt}from"zod";var ft=jt.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"),ec=jt.strictObject({type:jt.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:jt.boolean(),enum:jt.array(jt.string().max(255)).min(1).max(100).optional()}),Xr=ec.extend({type:jt.enum([...ec.shape.type.options,"array"]),items:ec.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"})}),ei=Xr.safeExtend({source:jt.discriminatedUnion("type",[jt.strictObject({type:jt.literal("input")}),jt.strictObject({type:jt.literal("node")}),jt.strictObject({type:jt.enum(["parameter","attribute"]),key:ft})])}),t_=jt.record(ft,ei),tc=jt.record(ft,ft).refine(e=>Object.keys(e).length<=20);function un(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=>un(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&&jt.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 nc(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&&nc(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(!un(i,u))throw new Error(`Invalid variable value: ${r}`);n[r]=u}}return n}function ti(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 vp(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"||!un(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 Or}from"zod";var Sn=Or.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"),_n=Or.discriminatedUnion("source",[Or.strictObject({source:Or.literal("literal"),value:Ae}),Or.strictObject({source:Or.literal("variable"),key:Or.string().min(1).max(255),path:Sn.optional()})]);function wp(e,t){if(!t)return e;for(let n of Sn.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 rc(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(Ae.parse(wp(n[e.key],e.path)))}function ic(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&&!Sn.safeParse(r).success?null:{key:n,path:r}}function oc(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Vt(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(dp))]}function oa(e){return oc(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function rn(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,S=(l.includes(".")?l.indexOf("."):m)+Number(u),y=S<=0?2-S+m:S>=m?S:m+1;n+=y+(c.startsWith("-")?1:0)-s.length}}return n}var er=ve.enum(["page","popup","banner"]),fb=3e5,Op=ve.strictObject({type:ve.enum(["string","number","boolean","strings","json"]),nullable:ve.boolean()}),gb=ve.strictObject({inputs:ve.record(Te,Op.extend({required:ve.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:ve.record(Te,Op).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),hb=ve.strictObject({kind:er,schemaVersion:ve.literal(1),name:ve.string().trim().min(1).max(80),screen:nn,contract:gb}),aa=hb.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"]),rn(e)>fb&&n("Content document exceeds its byte budget",[])});function Ab(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 yb=aa.superRefine((e,t)=>{for(let n of oa(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&&!Ab(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}Xn(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),_p=ve.strictObject({id:ve.uuid(),kind:er,projectId:ve.uuid(),environmentId:ve.uuid(),name:ve.string(),revision:ve.number().int().nonnegative(),status:ve.enum(["draft","published","archived"]),publishedVersionId:ve.uuid().nullable(),createdAt:ve.iso.datetime({offset:!0}),updatedAt:ve.iso.datetime({offset:!0})}),A_=_p.extend({draft:aa}),y_=ve.strictObject({rows:ve.array(_p).max(200),nextCursor:ve.uuid().nullable()}),ac=ve.strictObject({id:ve.uuid(),kind:er,resourceId:ve.uuid(),projectId:ve.uuid(),environmentId:ve.uuid(),version:ve.number().int().positive(),sourceRevision:ve.number().int().nonnegative(),document:yb,createdAt:ve.iso.datetime({offset:!0})}),b_=ac.omit({document:!0}),S_=ve.discriminatedUnion("action",[ve.strictObject({action:ve.literal("create"),kind:er,id:ve.uuid(),document:aa}),ve.strictObject({action:ve.literal("save"),kind:er,id:ve.uuid(),revision:ve.number().int().nonnegative(),document:aa}),ve.strictObject({action:ve.enum(["publish","archive"]),kind:er,id:ve.uuid(),revision:ve.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 Cp}from"zod";var ni={funnelId:Cp.uuid().optional(),funnelVersionId:Cp.uuid().optional()};import{z as et}from"zod";import{z as Me}from"zod";import{z as Ze}from"zod";var O_=Ze.discriminatedUnion("action",[Ze.strictObject({action:Ze.literal("create"),couponId:Ze.uuid(),productBindingId:Ze.uuid(),storeOfferId:Ze.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:Ze.enum(["introductory","promotional"])}),Ze.strictObject({action:Ze.literal("set_enabled"),id:Ze.uuid(),revision:Ze.number().int().nonnegative(),enabled:Ze.boolean()})]),__=Ze.array(Ze.strictObject({id:Ze.uuid(),couponId:Ze.uuid(),productBindingId:Ze.uuid(),storeOfferId:Ze.string().min(1).max(255).nullable(),storeOfferType:Ze.enum(["introductory","promotional"]),enabled:Ze.boolean(),revision:Ze.number().int().nonnegative()})).max(500),ri=Ze.strictObject({offerKind:Ze.enum(["none","introductory","promotional"]),offerId:Ze.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:Ze.number().int().min(0).max(1e8),trialDays:Ze.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"})}),C_=Ze.record(Ze.uuid(),ri).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var sc=Me.object({type:Me.literal("native_purchase"),receiptId:Me.uuid(),orderId:Me.uuid(),productVersionId:Me.uuid(),provider:Me.enum(["apple","google"]),productId:Me.string().min(1).max(255),productKind:up,replacement:Me.strictObject({sourceOrderId:Me.uuid(),sourceProductId:Me.string().min(1).max(255),policy:Me.enum(["apple_store","google_full_price"]),sourceAccountTokens:Me.array(Me.uuid()).max(50)}).nullable(),appAccountToken:Me.uuid().optional(),obfuscatedAccountId:Me.string().min(1).max(64).optional(),obfuscatedProfileId:Me.uuid().optional(),basePlanId:Me.string().min(1).max(255).optional(),offerId:Me.string().min(1).max(255).optional(),offerKind:Me.enum(["none","introductory","promotional"]),currency:he,catalogAmountMinor:Me.number().int().nonnegative().max(1e8),discountMinor:Me.number().int().nonnegative().max(1e8),trialDays:Me.number().int().min(1).max(730).nullable(),seatBundle:Me.array(Me.strictObject({key:Me.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:Me.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:Me.strictObject({offerId:Me.string().min(1).max(255),keyId:Me.string().min(1).max(255),nonce:Me.uuid(),signature:Me.string().min(1).max(1024),timestamp:Me.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 d}from"zod";import{z as we}from"zod/v4";import{z as bb}from"zod/v4";var Sb=bb.registry(),{BillingInterval:Pp}=(()=>{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:xb}=(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')."})})}))(we),{withSpecDefault:Ib}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(Sb),{COMMON:Ep}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:vb}={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:wb}=(e=>({COMMON_SET:new Set(e)}))(Ep),{hasNoDuplicateCurrencies:Rp}={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:kp}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:Ob}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(we),{Infinite:_b}={Infinite:"inf"},{TierBehavior:Cb}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:jp}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Pb}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:Eb}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:Rb}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:kb}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(we),{ApiCreditTierSchema:Tp}=(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."})})}))(we),{VIOLATION_MESSAGES:jb}={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:Np}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(we),{ModelMarkupsSchema:Tb}=((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()}))(we,Np),{InvoiceUsageEntrySchema:Nb}=(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()}))(we),{AttachDiscountSchema:Dp}=(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."})}))(we),{CustomLineItemSchema:Db}=(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."})})}))(we),{UnixMsTimestampSchema:Fb}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(we),{CreateInvoicePreviewLineSchema:Mb}=(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()})}))(we),{ReissueInvoiceParamsSchema:Fp}=(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."})})}))(we),{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."})}))(we),{InvoiceTemplateSchema:qb}=(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."})})}))(we),{BasePriceSchema:Vb}=((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."})})}))(we,Pp,xb),{CURRENCY_CODES:Bb}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(Ep,vb,wb),{ApiPriceProcessorsSchema:Mp}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(we,Ob),{AllocatedBillingFieldSchema:Ub}=((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'."})}))(we,Pb),{CreditDimensionNameSchema:Lb}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(we,Eb,Rb),{ApiCreditMatchSchema:qp}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(kb),{findCreditTierViolations:zb}=(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}}))(jb),{ApiCreditMultiplierSchema:$b}=((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."})}))(we,qp),{ProviderMarkupsSchema:Gb}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(we,Np),{InvoiceFeatureQuantitySchema:Vp}=((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."})}))(we,jp,Nb),{CreateInvoicePreviewSchema:cc}=((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()})}))(we,Mb),{SUPPORTED_SET:Kb}=(e=>({SUPPORTED_SET:new Set(e)}))(Bb),{ApiCreditDimensionBaseSchema:Hb}=((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."})})}))(we,qp),{refineGraduatedTiers:Bp}=(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"]})}}))(zb),{ApiFeatureMarkupsOverrideSchema:Qb}=((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."})})}))(we,Gb,Tb),{isValidCurrencyCode:Jb}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(Kb),{ApiCreditDimensionSchema:Zb}=((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()])}))(we,Hb,Tp,Bp),{CurrencyCodeSchema:Up}=((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')."})}))(we,Jb),{AdditionalCurrencyTierSchema:Wb}=((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"]})}))(we,Up),{ApiCreditSchemaItemBaseSchema:Lp}=((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."})})}))(we,Lb,Zb,$b),{ApiFlatCreditSchemaItemSchema:Yb}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(Lp,we),{AdditionalCurrencyPriceSchema:Xb}=((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."})})}))(we,Up),{AdditionalCurrencyTierArraySchema:eS}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(we,Wb,Rp,kp),{ApiGraduatedCreditSchemaItemSchema:tS}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(Lp,we,Tp,Bp),{AdditionalCurrencyPriceArraySchema:zp}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(we,Xb,Rp,kp),{ApiUsageTierWithCurrenciesSchema:nS}=((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()}))}))(we,_b,eS),{ApiCreditSchemaItemSchema:rS}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(we,tS,Yb),{BasePriceParamsSchema:iS}=((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."})}))(Vb,Ib,we,zp),{PlanItemPriceParamsSchema:oS}=((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."})})}))(we,zp,nS,Cb,Pp,jp,Ub),{ApiFeatureOverrideSchema:aS}=((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."})})}))(we,rS,Qb),{InvoiceBasePriceParamsSchema:$p}=((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()}))(iS,Mp),{InvoiceItemPriceParamsSchema:sS}=((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()}))(oS,Mp),{InvoiceLicenseQuantitySchema:cS}=((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()}))(we,$p,Vp),{InvoiceCustomizeItemSchema:uS}=((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()}))(we,sS,aS),{InvoiceCustomizeSchema:lS}=((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."})}))(we,$p,uS),{InvoicePlanParamsSchema:dS}=((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()}))(we,lS,Vp,cS,Dp),{CreateInvoiceParamsSchema:ii}=((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."})}))(we,dS,Db,Dp,Fb);var Hp=d.strictObject({requestId:d.uuid(),predecessorOperationId:d.uuid().optional(),invoiceMode:_r.optional(),entityId:d.uuid().optional(),billingSubscriptionId:d.uuid().optional(),newBillingSubscription:d.literal(!0).optional(),offerId:d.uuid().optional(),nativeOffer:ri.optional(),plans:d.array(d.strictObject({productVersionId:d.uuid(),seatQuantities:d.record(Eo,d.number().int().min(0).max(1e4)).optional(),featureQuantities:d.record(d.uuid(),d.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:d.enum(["stripe","apple","google","merchant"]),currency:he}).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"),Pr=d.strictObject({operationId:d.uuid()}),Pt=d.number().int().min(0).max(1e8),pS=d.strictObject({lineId:d.uuid(),productVersionId:d.uuid(),productName:d.string().min(1).max(80),interval:d.enum(["free","week","month","year","one_time"]),intervalCount:d.number().int().min(1).max(156).optional(),baseAmountMinor:Pt,seats:d.array(d.strictObject({key:Eo,quantity:d.number().int().min(0).max(1e4),includedQuantity:d.number().int().min(0).max(1e4),maximumQuantity:d.number().int().min(0).max(1e4),unitAmountMinor:Pt})).max(20),prepaid:d.array(Md).max(100).optional(),catalogAmountMinor:Pt,trial:d.strictObject({days:d.number().int().min(1).max(730),cardRequired:d.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+No({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"),Qp=d.string().regex(/^[A-Za-z0-9_-]{1,200}$/),mS=d.strictObject({id:Qp,name:d.string().min(1).max(40),percent_off:d.number().gt(0).max(100).optional(),amount_off:d.number().int().positive().optional(),currency:d.string().regex(/^[a-z]{3}$/).optional(),duration:d.enum(["once","repeating","forever"]),duration_in_months:d.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"),fS=d.strictObject({subscriptionId:d.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:d.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:d.array(d.strictObject({id:d.string(),price_id:d.string(),quantity:d.number().int().nonnegative(),discounts:d.array(d.strictObject({id:d.string(),coupon:d.string(),start:d.number(),end:d.number().nullable()})).optional()})).min(1).max(100),prorationDate:d.number().int().nonnegative(),amountMinor:d.number().int().positive(),periodStartMs:d.number(),periodEndMs:d.number()}),Jp=d.strictObject({invoiceMode:_r.optional(),append:fS.optional(),provider:d.literal("stripe"),executor:d.enum(["indiana","merchant"]),accountId:d.string().regex(/^acct_[A-Za-z0-9]+$/),mode:d.enum(["payment","subscription"]),lineItems:d.array(d.strictObject({price:d.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:d.number().int().min(1).max(1e4),priceId:d.uuid(),productName:d.string().min(1).max(80),amountMinor:d.number().int().min(0).max(1e8),currency:d.string().regex(/^[a-z]{3}$/),interval:d.enum(["week","month","year","one_off"]),intervalCount:d.number().int().min(1).max(52),slot:d.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:d.strictObject({mode:d.enum(["graduated","volume"]),tiers:d.array(d.strictObject({upTo:d.number().int().min(1).max(1e6).nullable(),unitAmountMinor:d.number().int().min(0).max(1e8),flatAmountMinor:d.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:d.array(d.strictObject({coupon:Qp,terms:mS})).max(1),trialPeriodDays:d.number().int().min(1).max(730).nullable(),metadata:d.strictObject({grooveCheckoutId:d.uuid(),grooveCustomerId:d.uuid()}),expiresAt:d.iso.datetime({offset:!0})}),oi=d.strictObject({operationId:d.uuid(),entityId:d.uuid().nullable(),billingSubscriptionId:d.uuid().nullable(),discount:d.strictObject({offerId:d.uuid(),couponId:d.uuid(),discount:Zn,duration:en,amountMinor:Pt,allocations:d.array(d.strictObject({productVersionId:d.uuid(),amountMinor:Pt})).min(1).max(20),expiresAt:d.iso.datetime({offset:!0})}).nullable(),charge:d.strictObject({effectiveAt:d.iso.datetime({offset:!0}),periodEndsAt:d.iso.datetime({offset:!0}),debitMinor:Pt,discountMinor:Pt,taxMinor:Pt,totalMinor:Pt}).nullable(),expiresAt:d.iso.datetime({offset:!0}),provider:d.enum(["stripe","apple","google","merchant"]),nativeOffer:ri.optional(),currency:he,lines:d.array(pS).min(1).max(20),catalogAmountMinor:Pt,automaticTax:d.boolean(),execution:d.union([Jp,wo]).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"),ai=d.strictObject({operationId:d.uuid(),orderId:d.uuid(),append:d.boolean().optional(),invoiceMode:d.boolean().optional(),status:d.enum(["pending","complete","cancelled","failed"]),executor:d.enum(["indiana","merchant"]),checkoutUrl:d.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:d.union([Jp,wo]).nullable(),currency:he,catalogAmountMinor:Pt,taxMinor:Pt,totalMinor:d.number().int().min(0).max(2e8).nullable(),quoteFinalized:d.boolean(),nativePurchase:sc.nullable(),confirmedAt:d.iso.datetime({offset:!0}).nullable().optional(),quote:oi.optional(),merchantExecution:hr.nullable().optional(),problem:_i.nullable().optional(),authority:Po.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"),ca=d.strictObject({enabled:d.literal(!0),featureIds:d.array(d.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),Zp=d.strictObject({requestId:d.uuid(),invoiceMode:_r.optional(),membershipId:d.uuid(),carryOverBalances:ca.optional(),carryOverUsages:ca.optional(),membershipIds:d.array(d.uuid()).min(1).max(20).optional(),prorationBehavior:d.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:d.enum(["immediate","renewal","store"]),change:d.discriminatedUnion("type",[d.strictObject({type:d.literal("plan"),productVersionId:d.uuid()}),d.strictObject({type:d.literal("seats"),licenseKey:Eo,quantity:d.number().int().min(0).max(1e4)}),d.strictObject({type:d.literal("quantity"),internal_feature_id:d.uuid(),quantity:d.number().int().min(0).max(1e4)}),d.strictObject({type:d.literal("cancel")}),d.strictObject({type:d.literal("uncancel")}),d.strictObject({type:d.literal("billing_cycle"),billingCycleAnchor:d.union([d.literal("now"),d.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"),sa=d.string().regex(/^price_[A-Za-z0-9]+$/),Gp=d.strictObject({grooveUpdateId:d.uuid(),grooveCustomerId:d.uuid()}),Kp=d.strictObject({price:sa.nullable(),priceId:d.uuid().optional(),quantity:d.number().int().min(0).max(1e4)}),Wp=d.strictObject({provider:d.literal("stripe"),invoiceMode:_r.optional(),executor:d.enum(["indiana","merchant"]),accountId:d.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:d.string().regex(/^sub_[A-Za-z0-9]+$/),action:d.enum(["update","cancel","schedule","release"]),update:d.strictObject({items:d.array(Kp).max(20),remove:d.array(sa).max(20),restoreItems:d.array(d.strictObject({price:sa,quantity:d.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:d.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:d.number().int().positive().optional(),paymentBehavior:d.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:d.boolean().optional(),clearCancelAt:d.literal(!0).optional(),billingCycleAnchorNow:d.literal(!0).optional(),metadata:Gp}).nullable(),cancel:d.strictObject({prorate:d.literal(!1),invoiceNow:d.literal(!1)}).nullable(),schedule:d.strictObject({currentItems:d.array(d.strictObject({price:sa,quantity:d.number().int().min(0).max(1e4)})).max(20),nextItems:d.array(Kp).min(1).max(20),switchAt:d.number().int().positive(),interval:d.enum(["week","month","year"]),intervalCount:d.number().int().min(1).max(52),resetBillingCycleAnchor:d.literal(!0).optional(),metadata:Gp}).nullable(),release:d.strictObject({schedule:d.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:d.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"),ua=d.strictObject({carryOverBalances:ca.optional(),carryOverUsages:ca.optional(),operationId:d.uuid(),membershipId:d.uuid(),productVersionId:d.uuid(),timing:d.enum(["immediate","renewal"]),effectiveAt:d.iso.datetime({offset:!0}),expiresAt:d.iso.datetime({offset:!0}),currency:he,creditMinor:Pt,debitMinor:Pt,discountMinor:Pt,taxMinor:Pt,totalMinor:Pt,retainedProductVersionIds:d.array(d.uuid()).max(19),execution:d.union([Wp,Oo])}),gS=d.strictObject({operationId:d.uuid(),invoiceMode:d.boolean().optional(),membershipId:d.uuid(),productVersionId:d.uuid(),status:d.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:d.enum(["immediate","renewal"]),effectiveAt:d.iso.datetime({offset:!0}),checkoutUrl:d.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:d.enum(["indiana","merchant"]),execution:d.union([Wp,Oo]).nullable(),confirmedAt:d.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:hr.nullable().optional(),problem:_i.nullable().optional(),quote:ua.optional(),authority:Po.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),hS=d.strictObject({operationId:d.uuid(),membershipId:d.uuid(),productVersionId:d.uuid(),timing:d.literal("store"),effectiveAt:d.null(),expiresAt:d.iso.datetime({offset:!0}),currency:he,creditMinor:d.null(),debitMinor:d.null(),discountMinor:d.null(),taxMinor:d.null(),totalMinor:d.null(),retainedProductVersionIds:d.array(d.uuid()).max(19),store:d.strictObject({provider:d.enum(["apple","google"]),productId:d.string().min(1).max(255),catalogAmountMinor:Pt,policy:d.enum(["apple_store","google_full_price"])})}),AS=d.strictObject({operationId:d.uuid(),membershipId:d.uuid(),productVersionId:d.uuid(),status:d.enum(["prepared","pending","effective","cancelled","failed"]),timing:d.literal("store"),effectiveAt:d.iso.datetime({offset:!0}).nullable(),checkoutUrl:d.null(),nativePurchase:sc.nullable()}),Yp=d.union([ua,hS]),uc=d.union([gS,AS]),Zi=d.number().int().positive().max(2e8),Cr=d.number().int().min(0).max(2e8),Xp=d.strictObject({requestId:d.uuid(),invoiceId:d.uuid(),mode:d.enum(["full","partial"]),amountMinor:Zi.optional(),entitlementAction:d.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),em=d.strictObject({provider:d.literal("stripe"),executor:d.enum(["indiana","merchant"]),accountId:d.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:d.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:Zi,currency:d.string().regex(/^[a-z]{3}$/),metadata:d.strictObject({indianaRefundId:d.uuid()}),idempotencyKey:d.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:d.array(d.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),lc=d.strictObject({operationId:d.uuid(),invoiceId:d.uuid(),providerInvoiceId:d.string().min(1).max(200),currency:he,paidMinor:Cr,refundedMinor:Cr,pendingMinor:Cr,amountMinor:Zi,mode:d.enum(["full","partial"]),entitlementAction:d.enum(["retain","revoke"]),revokes:d.strictObject({customerProductIds:d.array(d.uuid()).max(100),subscriptionIds:d.array(d.string().min(1).max(200)).max(20)}),execution:d.union([em,_o]),expiresAt:d.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"),la=d.strictObject({operationId:d.uuid(),invoiceId:d.uuid(),providerInvoiceId:d.string().min(1).max(200),status:d.enum(["quoted","pending","succeeded","failed","expired"]),executor:d.enum(["indiana","merchant"]),currency:he,amountMinor:Zi,mode:d.enum(["full","partial"]),entitlementAction:d.enum(["retain","revoke"]),refundId:d.string().min(1).max(200).nullable(),quote:lc.optional(),execution:d.union([em,_o]).nullable(),confirmedAt:d.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:hr.nullable().optional(),problem:_i.nullable().optional(),authority:Po.optional(),failureReason:d.string().min(1).max(200).nullable(),createdAt:d.iso.datetime({offset:!0}),completedAt:d.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"),H_=d.strictObject({invoiceId:d.uuid(),currency:he,paidMinor:Cr,refundedMinor:Cr,pendingMinor:Cr,refundableMinor:Cr,executor:d.enum(["indiana","merchant"]).nullable(),canRefund:d.boolean(),operations:d.array(la).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),Q_=d.strictObject({requestId:d.uuid(),mode:d.enum(["full","partial"]),amountMinor:Zi.optional(),entitlementAction:d.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 tm=et.strictObject({requestId:et.uuid(),targets:et.array(et.strictObject({membershipId:et.uuid(),action:et.enum(["cancel","uncancel"]),timing:et.enum(["immediate","renewal"])}).refine(e=>e.action!=="uncancel"||e.timing==="immediate","Restoration is immediate")).min(1).max(100)}).refine(e=>new Set(e.targets.map(t=>t.membershipId)).size===e.targets.length,"Duplicate batch target"),da=et.strictObject({batchId:et.uuid()}),yS=et.strictObject({operationId:et.uuid(),membershipIds:et.array(et.uuid()).min(1).max(20),provider:et.enum(["stripe","apple","google"]),action:et.enum(["cancel","uncancel"]),timing:et.enum(["immediate","renewal"]),status:et.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:ua.nullable(),managementUrl:et.url().nullable(),failureCode:et.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),Wi=et.strictObject({batchId:et.uuid(),ready:et.boolean(),status:et.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:et.iso.datetime({offset:!0}),acceptedAt:et.iso.datetime({offset:!0}).nullable(),groups:et.array(yS).min(1).max(100)});import{z as Pe}from"zod";var bS=Pe.string().trim().min(1).max(240),dc={requestId:Pe.uuid(),reason:bS},pa=Pe.discriminatedUnion("action",[Pe.strictObject({...dc,action:Pe.literal("start"),productVersionId:Pe.uuid(),entityId:Pe.uuid().optional(),days:Pe.number().int().min(1).max(730).optional()}),Pe.strictObject({...dc,action:Pe.literal("extend"),membershipId:Pe.uuid(),days:Pe.number().int().min(1).max(730)}),Pe.strictObject({...dc,action:Pe.literal("end"),membershipId:Pe.uuid()})]),nm=Pe.strictObject({operationId:Pe.uuid()}),rm=Pe.iso.datetime({offset:!0}),SS=Pe.strictObject({provider:Pe.literal("stripe"),executor:Pe.enum(["indiana","merchant"]),accountId:Pe.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:Pe.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:Pe.union([Pe.literal("now"),rm]),prorationBehavior:Pe.literal("none")}),pc=Pe.strictObject({operationId:Pe.uuid(),action:Pe.enum(["start","extend","end"]),status:Pe.enum(["pending","effective"]),managedBy:Pe.enum(["indiana","stripe"]),membershipIds:Pe.array(Pe.uuid()).min(1).max(20),endsAt:rm.nullable(),execution:SS.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"),e1=Pe.strictObject({groupId:Pe.uuid(),productVersionId:Pe.uuid(),enabled:Pe.boolean()});import{z as Qe}from"zod";var im=Qe.strictObject({requestId:Qe.uuid(),currency:he,makeDefault:Qe.boolean()}),om=Qe.strictObject({setupId:Qe.uuid()}),xS=Qe.strictObject({provider:Qe.literal("stripe"),executor:Qe.literal("merchant"),accountId:Qe.string().regex(/^acct_[A-Za-z0-9]+$/),mode:Qe.literal("setup"),currency:Qe.string().regex(/^[a-z]{3}$/),customer:Qe.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:Qe.uuid(),metadata:Qe.strictObject({grooveProjectId:Qe.uuid(),grooveEnvironmentId:Qe.uuid(),grooveCustomerId:Qe.uuid(),groovePaymentSetupId:Qe.uuid()}),setDefaultPaymentMethod:Qe.boolean(),expiresAt:Qe.iso.datetime({offset:!0})}),mc=Qe.strictObject({id:Qe.uuid(),provider:Qe.literal("stripe"),status:Qe.enum(["prepared","complete","expired"]),currency:he,makeDefault:Qe.boolean(),url:Qe.url().nullable(),createdAt:Qe.iso.datetime({offset:!0}),expiresAt:Qe.iso.datetime({offset:!0}),completedAt:Qe.iso.datetime({offset:!0}).nullable(),execution:xS.nullable()});import{z as Et}from"zod";var am=Et.union([Et.string(),Et.number(),Et.boolean(),Et.null()]),sm=Et.strictObject({customerId:Et.uuid()}),cm=Et.strictObject({customerId:Et.uuid(),provider:Et.literal("stripe"),checkedAt:Et.iso.datetime({offset:!0}),status:Et.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Et.number().int().nonnegative(),differences:Et.array(Et.strictObject({subscriptionId:Et.string().startsWith("sub_"),itemId:Et.string().nullable(),field:Et.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:am,actual:am})).max(1e4)});import{z as ye}from"zod";var ma=ye.iso.datetime({offset:!0}),fa=ye.strictObject({createdAt:ma,id:ye.uuid()}),ga=ye.strictObject({customerId:ye.uuid().optional(),entityId:ye.uuid().optional(),productId:ye.string().min(1).max(256).optional(),provider:ye.enum(["stripe","apple","google","merchant","free"]).optional(),status:ye.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:fa.optional(),limit:ye.number().int().min(1).max(100).optional()}),fc={id:ye.uuid(),customerId:ye.uuid(),entityId:ye.uuid().nullable(),productId:ye.string().min(1).max(256),productVersionId:ye.uuid(),name:ye.string().min(1).max(120),provider:ye.enum(["stripe","apple","google","merchant","free"]),createdAt:ma},IS=ye.strictObject({...fc,status:ye.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:ye.boolean(),billingSubscriptionId:ye.uuid().nullable()}),vS=ye.strictObject({...fc,status:ye.enum(["active","ended","refunded"]),orderId:ye.uuid().nullable(),transactionId:ye.uuid().nullable(),currency:he.nullable(),amountMinor:ye.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),wS=ye.strictObject({...fc,status:ye.enum(["blocked","resolved"]),conflict:ye.strictObject({detectedAt:ma,blockingMembershipIds:ye.array(ye.uuid()).min(1).max(100),transactionId:ye.uuid()}),resolvedAt:ma.nullable()}),um=ga.extend({status:ye.enum(["blocked","resolved"]).optional()}),lm=ye.strictObject({customerId:ye.uuid(),orderId:ye.uuid()}),dm=ye.strictObject({orderId:ye.uuid(),status:ye.enum(["blocked","resolved"])}),pm=ye.strictObject({items:ye.array(IS).max(100),nextCursor:fa.nullable()}),mm=ye.strictObject({items:ye.array(vS).max(100),nextCursor:fa.nullable()}),fm=ye.strictObject({items:ye.array(wS).max(100),nextCursor:fa.nullable()});import{z as Ye}from"zod";var gm=Ye.union([Ye.strictObject({intent:Ye.literal("read"),requestId:Ye.uuid(),purchaseIntentId:Ye.uuid()}),Ye.strictObject({requestId:Ye.uuid(),provider:Ye.literal("apple"),purchaseIntentId:Ye.uuid(),productId:Ye.string().min(1).max(255).optional(),signedTransaction:Ye.string().min(1).max(131072)}),Ye.strictObject({requestId:Ye.uuid(),provider:Ye.literal("google"),purchaseIntentId:Ye.uuid(),productId:Ye.string().min(1).max(255).optional(),purchaseToken:Ye.string().min(1).max(16384)})]),hm=Ye.strictObject({requestId:Ye.uuid(),orderId:Ye.uuid(),purchaseIntentId:Ye.uuid(),status:Ye.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:he,refunded:Ye.boolean(),completion:Ye.strictObject({transactionIds:Ye.array(Ye.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:Ye.boolean()}).nullable()});import{z as L}from"zod";var hc=L.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),OS=L.record(L.string(),L.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),_S=3,Yi=20,CS=_S*Yi,gc=L.strictObject({type:L.literal("product"),productId:hc}),Am={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)},PS=L.discriminatedUnion("type",[gc,L.strictObject({...Am,items:L.array(gc).max(Yi)})]),ES=L.discriminatedUnion("type",[gc,L.strictObject({...Am,items:L.array(PS).max(Yi)})]),RS=L.array(ES).max(Yi).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>Yi||i>CS)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function Ac(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:Ac(t))}var si=L.strictObject({lookupKey:L.string().trim().min(1).max(200),displayName:L.string().trim().min(1).max(1500),items:RS,metadata:OS}),kS=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()))}),ym=si.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"})}),bm=L.strictObject({id:L.uuid(),offeringId:L.uuid(),projectId:L.uuid(),environmentId:L.uuid(),version:L.number().int().positive(),document:si,productEvidence:L.record(hc,kS),createdAt:L.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=Ac(e.document);(!n.length||NS(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"})}),jS=L.strictObject({rows:L.array(ym).max(200),versions:L.array(bm).max(500)}),f1=L.discriminatedUnion("action",[L.strictObject({action:L.literal("create"),document:si}),L.strictObject({action:L.literal("save"),id:L.uuid(),revision:L.number().int().nonnegative(),document:si}),L.strictObject({action:L.enum(["publish","set_current","archive","restore"]),id:L.uuid(),revision:L.number().int().nonnegative()})]),g1=L.strictObject({record:ym,version:bm.nullable()}),Sm=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()})]),TS=L.strictObject({internalId:hc,id:L.string(),name:L.string().nullable(),version:L.number().int().positive(),archived:L.boolean()}),h1=jS.extend({products:L.array(TS).max(500),pagination:L.strictObject({rows:L.string().nullable(),versions:L.string().nullable(),products:L.string().nullable()}).optional()});function NS(e){let t=[];Ac(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 ha}from"zod";var xm=ha.strictObject({id:ha.uuid(),offeringId:ha.uuid(),version:ha.number().int().positive(),document:si});import{z as bt}from"zod";import{z as de}from"zod";import{z as ci}from"zod";var Aa=ci.strictObject({items:ci.array(ci.strictObject({productVersionId:ci.string().min(1).max(200),label:ci.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:ci.string().min(1).max(200).nullable(),grouping:ta.optional()});function Im(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}import{z as At}from"zod";var DS=At.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ya=At.discriminatedUnion("type",[At.object({type:At.literal("fixed"),productVersionId:At.string().min(1).max(200)}).strict(),At.object({type:At.literal("picker"),pickerId:DS,allowedProductVersionIds:At.array(At.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")]),Bn=At.discriminatedUnion("type",[At.object({type:At.literal("modal"),size:At.enum(["sm","md","lg"])}).strict(),At.object({type:At.literal("sheet"),size:At.enum(["sm","md","lg"])}).strict(),At.object({type:At.literal("fullscreen")}).strict(),At.object({type:At.literal("inline")}).strict()]);var yc=de.discriminatedUnion("type",[de.strictObject({type:de.literal("event"),event:de.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),de.strictObject({type:de.literal("open_url"),url:de.url().refine(e=>new URL(e).protocol==="https:")})]),FS=nn,MS=de.discriminatedUnion("type",[de.object({type:de.literal("checkout"),product:ya}).strict(),de.object({type:de.literal("close")}).strict(),de.object({type:de.literal("action"),action:yc}).strict()]),ui=de.object({schemaVersion:de.literal(3),kind:de.literal("paywall"),name:de.string().trim().min(1).max(80),presentation:Bn,requirement:Yn.optional(),products:Aa,offeringVersionId:de.uuid().nullable(),offeringId:de.uuid(),screen:FS,buttons:de.record(de.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),MS)}).strict(),T1=ui.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 VS(e))t.addIssue({code:"custom",message:r});for(let r of qS(e))t.addIssue({code:"custom",message:r});Xn(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 qS(e){let t=e.products.items.map(a=>a.productVersionId),n=pp(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&&(!na(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")),Vt(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"),Vt(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 VS(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),Vn(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(S=>S.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 vm=de.object({id:de.uuid(),projectId:de.uuid(),environmentId:de.uuid(),revision:de.number().int().nonnegative(),state:de.enum(["active","archived"]),publishedVersionId:de.uuid().nullable(),updatedAt:de.iso.datetime({offset:!0}),draft:ui}).strict(),N1=de.object({rows:de.array(vm).max(200),nextCursor:de.uuid().nullable()}).strict(),D1=vm.omit({draft:!0}).extend({name:de.string(),productCount:de.number().int().nonnegative()}).strict(),F1=de.discriminatedUnion("action",[de.object({action:de.literal("save"),id:de.uuid().nullable(),revision:de.number().int().nonnegative(),document:ui}).strict(),de.object({action:de.enum(["publish","archive"]),id:de.uuid(),revision:de.number().int().nonnegative()}).strict()]),M1=de.object({paywalls:de.array(de.object({id:de.uuid(),paywallId:de.uuid(),version:de.number().int().positive(),name:de.string().min(1).max(80),presentation:Bn,buttons:ui.shape.buttons}).strict()).max(500),limited:de.boolean()}).strict();import{z as Oe}from"zod";import{z as Bt}from"zod";var li=Bt.string().regex(/^[a-f0-9]{64}$/),BS=Xo.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),wm=Bt.strictObject({couponDigests:Bt.record(Bt.uuid(),li),variables:Bt.record(gn,Bt.record(Bt.uuid(),Bt.partialRecord(Bt.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),Bt.string()))),locales:Bt.record(gn,Yr.extend({nodes:Bt.record(Bt.string(),Bt.strictObject({base:BS})),plans:Bt.object({}).strict(),pickers:Bt.object({}).strict()}).omit({paywall:!0}))});import{z as qe}from"zod";import{z as ba}from"zod";var bc=ba.strictObject({eventsEnabled:ba.boolean(),experimentViewsEnabled:ba.boolean(),featureUsageEnabled:ba.boolean()}),$1=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function Om(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}import{z as $}from"zod";var Sc=$.tuple([$.number().min(0).max(1),$.number().min(0).max(1)]).refine(([e,t])=>e<=t),US=$.strictObject({attribute:$.string().optional(),seed:$.string(),hashVersion:$.literal(2),ranges:$.array(Sc).max(100)}),LS=$.strictObject({id:$.string().min(1).max(255),condition:Ht,gate:$.boolean().optional()}),zS=$.strictObject({key:$.string().optional(),name:$.string().optional(),passthrough:$.boolean().optional()}),_m={condition:Ht.optional(),parentConditions:$.array(LS).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(US).max(100).optional(),ranges:$.array(Sc).max(20).optional(),meta:$.array(zS).max(20).optional(),seed:$.string().optional(),name:$.string().optional(),phase:$.string().optional()},di=$.strictObject({..._m,key:$.string().min(1).max(255),variations:$.tuple([Ae,Ae]).rest(Ae).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()}),xc=$.strictObject({value:Ae,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()}),$S=$.strictObject({..._m,id:$.string().max(255).optional(),force:Ae.optional(),variations:$.array(Ae).min(2).max(20).optional(),key:$.string().optional(),range:Sc.optional(),tracks:$.array($.strictObject({experiment:di,result:xc})).max(100).optional()}),GS=$.strictObject({defaultValue:Ae.optional(),rules:$.array($S).max(500).optional()}),Xi=$.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:Ht})])),ln=$.strictObject({scope:Ue,generation:$.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:$.iso.datetime({offset:!0}),expiresAt:$.iso.datetime({offset:!0}).nullable(),features:$.record($.string(),GS),savedGroups:Xi,experiments:$.record($.uuid(),di)});var eo=ln.extend({analyticsConfig:bc,remoteFeatures:qe.array(qe.string().min(1).max(255)).max(500)}),Ic=eo.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"})}),Cm=qe.strictObject({attributes:ht,features:qe.array(qe.string().min(1).max(255)).max(500).optional(),customerId:qe.uuid().optional()}),KS=qe.strictObject({value:Ae,source:qe.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:qe.boolean(),off:qe.boolean(),ruleId:qe.string(),experimentResult:xc.optional()}),Sa=qe.strictObject({generation:ln.shape.generation,evaluatedAt:ln.shape.evaluatedAt,expiresAt:ln.shape.expiresAt,features:qe.record(qe.string(),KS),merchandiseContext:qe.strictObject({merchandiseId:qe.uuid(),merchandise:ht}).optional()}),Pm=qe.strictObject({customerId:qe.uuid().optional(),events:qe.array(qe.strictObject({eventUuid:qe.uuid(),timestamp:qe.iso.datetime({offset:!0}),name:qe.string().min(1).max(255),merchandise:pd.optional(),properties:qe.record(qe.string(),Ae).default({}),deviceId:qe.string().min(1).max(255).optional(),sessionId:qe.string().min(1).max(255).optional()})).min(1).max(100)}),Em=qe.strictObject({inserted:qe.number().int().nonnegative(),duplicates:qe.number().int().nonnegative(),rejected:qe.number().int().nonnegative(),skipped:qe.number().int().nonnegative(),analyticsConfig:bc});import{z}from"zod";function vc(e,t=[]){let n=[];Vt(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(ra(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 Rm(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>Rm(t)??[])}}function HS(e){let t=e.pages.map(i=>{let a=Rm(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(ra({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 km(e,t=[]){let n=nn.parse(structuredClone(HS(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=vc(n,t);if(i.length)throw new Error(i.join("; "));return n}import{z as Q}from"zod";import{z as F}from"zod";import{z as st}from"zod";var xa=st.strictObject({schemaVersion:st.literal(1),renderKey:st.string().min(1).max(256),routeTemplate:st.string().startsWith("/").max(2048),selectors:st.array(st.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:st.array(st.number().int().min(0)).min(1),absent:st.array(st.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"})}),jm=st.strictObject({renderKey:st.string().min(1).max(256),routeKey:st.string().min(1).max(256),stateKey:st.string().min(1).max(256),documentKey:st.string().min(1).max(256),documentHash:st.string().regex(/^[a-f0-9]{64}$/),compositionKey:st.string().min(1).max(256),entryMode:st.enum(["hard","soft"]),match:st.strictObject({present:st.array(st.number().int().min(0)),absent:st.array(st.number().int().min(0))})});import{z as Er}from"zod";var QS=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],wc="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",JS=Er.string().regex(new RegExp(`^${wc}/${wc}/${wc}/manifest\\.json$`)),Tm=Er.strictObject({kind:Er.literal("gcs-resumable"),url:Er.url(),bucket:Er.enum(QS),objectKey:JS,byteLength:Er.number().int().positive(),expiresAt:Er.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 lt=F.string().min(1).max(256),on=F.string().regex(/^[a-f0-9]{64}$/),Ia=F.strictObject({versionId:F.uuid(),manifestDigest:on,sourceGraphDigest:on,pageKey:lt,stateKey:lt,documentKey:lt,documentHash:on,elementKey:lt.optional(),nodeId:lt.optional(),contentHash:on.optional(),renderKey:lt.optional()}),Nm=F.strictObject({pageKey:lt,documentKey:lt,expectedDocumentHash:on,renderKey:lt.optional(),nodeId:lt,elementKey:lt,expectedContentHash:on,property:F.enum(["text","fontSize","color"]),value:F.union([F.string().max(4e3),F.number().finite()])}),Dm=F.strictObject({versionId:F.uuid(),manifestDigest:on,sourceGraphDigest:on,pageKey:lt,stateKey:lt,documentKey:lt,documentHash:on,renderKey:lt.optional(),patches:F.array(Nm.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),ZS=/^[a-z][a-z0-9-]{0,39}$/,to=F.string().regex(ZS),_c=F.enum(["web","ios","android"]),dC=F.discriminatedUnion("action",[F.strictObject({action:F.literal("register"),requestId:F.uuid(),client:to,platform:_c,label:F.string().trim().min(1).max(100),sha256:on,bytes:F.number().int().min(1),transferBytes:F.number().int().min(1)}),F.strictObject({action:F.literal("complete"),versionId:F.uuid()}),F.strictObject({action:F.literal("current"),versionId:F.uuid(),expectedCurrent:F.uuid().nullable()}),F.strictObject({action:F.literal("delivery"),enabled:F.boolean()}),F.strictObject({action:F.literal("changes"),versionId:F.uuid(),experimentId:F.uuid(),variationId:lt,changesetId:F.uuid().nullable(),expectedRevision:on.nullable(),editorUrl:F.string().url().max(2048),patches:F.array(Nm).max(200)})]),Cc=F.strictObject({id:F.uuid(),projectId:F.uuid(),environmentId:F.uuid(),clientKey:to,platform:_c,label:F.string(),sha256:on,bytes:F.number().int().positive(),objectKey:F.string(),state:F.enum(["uploading","ready","rejected"]),isCurrent:F.boolean(),revision:F.number().int().nonnegative(),createdAt:F.string(),expiresAt:F.string(),readyAt:F.string().nullable(),summary:F.record(F.string(),F.json()),routeTree:F.json().nullable(),validation:F.record(F.string(),F.json())}),WS=F.strictObject({key:to,platform:_c,currentId:F.uuid().nullable()}),pC=F.strictObject({rows:F.array(Cc).max(100),nextCursor:F.uuid().nullable(),clients:F.array(WS).max(20)}),Oc=F.strictObject({storedBytes:F.number().int().nonnegative(),reservedBytes:F.number().int().nonnegative(),chargedBytes:F.number().int().nonnegative(),versions:F.number().int().nonnegative(),objects:F.number().int().nonnegative(),orphanObjects:F.number().int().nonnegative(),missingReadyObjects:F.number().int().nonnegative(),unknownObjectSizes:F.number().int().nonnegative(),byteLimit:F.number().int().positive(),versionLimit:F.number().int().positive(),remainingBytes:F.number().int().nonnegative()}),mC=F.strictObject({asOf:F.iso.datetime({offset:!0}),reclamation:F.literal("manual-review-required"),buckets:F.strictObject({source:Oc,runtime:Oc,previews:Oc})}),fC=F.strictObject({version:Cc,actorId:F.uuid(),claims:F.record(F.string(),F.json())}),gC=F.strictObject({version:Cc,upload:Tm.nullable()}),hC=F.object({format:F.literal("indiana-route-state-index"),schemaVersion:F.literal(3),routes:F.array(F.object({routeKey:lt,path:F.string(),documentKey:lt,documentHash:on,initialStateKey:lt,initialRenderKey:lt})),renders:F.array(jm)}).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"})}),AC=F.strictObject({rows:F.array(F.object({id:F.uuid(),name:F.string(),status:F.string(),variations:F.array(F.object({id:lt,key:lt,name:F.string().optional()}).loose())}).loose()),limited:F.boolean()}),yC=F.strictObject({enabled:F.boolean(),allowedOrigins:F.array(F.string())});import{z as pi}from"zod";var Fm=pi.strictObject({id:pi.uuid(),name:pi.string().trim().min(1).max(80),client:to,source:Ia,event:pi.enum(["screen_enter","button_click"]),cooldownSeconds:pi.number().int().min(0).max(2592e3),behavior:pi.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 ze}from"zod";var Pc=Ae,YS=["parameters","answers","results","variables"];function Ec(e){return YS.some(t=>e===t||e.startsWith(t+"."))}function Rc(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])=>!Ec(r))),variables:t}}import{z as dt}from"zod";var va=dt.discriminatedUnion("kind",[dt.object({kind:dt.literal("ledger"),cursor:Yo}).strict(),dt.object({kind:dt.literal("billing"),cursor:dt.uuid()}).strict()]),XS=dt.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),tr=dt.record(dt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),dt.union([dt.string().max(500),dt.boolean(),dt.array(dt.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),ex=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function kc(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>kc(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||ex.test(n)||kc(r,t+1)))}var tx=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,nr=dt.record(XS,Ae).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!kc(e)&&!tx.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var Mm=dt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),wa=dt.array(dt.object({variable:Mm,componentId:Mm,required:dt.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"),RC=dt.object({bindings:wa,answers:tr,values:dt.record(dt.string(),Ae).optional()}).strict();import{z as nx}from"zod";var Oa=nx.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var jc=ze.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),qm=ze.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),Vm=nr.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),Tc=ze.record(jc,ze.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),rx=_n,Bm=ze.strictObject({type:ze.literal("external_task"),endpointId:ze.uuid(),taskKey:jc,inputs:ze.record(jc,rx).refine(e=>Object.keys(e).length<=20),outputs:Tc}),Um=ze.strictObject({maxAttempts:ze.number().int().min(1).max(5),retryDelaySeconds:ze.number().int().min(1).max(30),backoff:ze.enum(["fixed","exponential"]),requestTimeoutSeconds:ze.number().int().min(1).max(10),timeoutSeconds:ze.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var BC=ze.strictObject({outcome:ze.enum(["success","failure"]),data:Vm});var UC=ze.discriminatedUnion("operation",[ze.strictObject({operation:ze.literal("signal"),runId:ze.uuid(),nodeId:qm,eventName:Oa,eventId:ze.uuid(),data:Vm}),ze.strictObject({operation:ze.literal("read_results"),runId:ze.uuid()})]),LC=ze.strictObject({scope:Ue,runId:ze.uuid(),eventId:ze.uuid(),accepted:ze.boolean()}),ix=ze.record(qm,Pc),zC=ze.strictObject({scope:Ue,runId:ze.uuid(),results:ix});var xn={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},Lm="00000000-0000-0000-0000-000000000000";import{z as J}from"zod";import{z as Je}from"zod";var JC=Je.enum(["local","remote"]),Nc=Je.strictObject({port:Je.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:Ae.optional(),sticky:Je.array(Je.strictObject({expected:ki.nullable(),next:ki})).max(100),exposures:Je.array(Ae).max(100),features:Je.array(Ae).max(100)}),zm=Je.strictObject({type:Je.literal("evaluate"),receiptId:Je.uuid(),environmentId:Je.uuid(),policyRevision:Je.number().int().nonnegative(),attributes:ht,sticky:Je.record(Je.string(),ki)}),$m=zm.extend({runId:Je.uuid(),versionId:Je.uuid(),nodeId:Je.string().min(1).max(64),visit:Je.number().int().nonnegative(),revision:Je.number().int().nonnegative()}),Dc=zm.omit({type:!0,receiptId:!0}).extend({type:Je.literal("evaluate_segment")}),Gm=Je.strictObject({nodeId:Je.string().min(1).max(64),result:Nc}),Km=Dc.extend({runId:Je.uuid(),versionId:Je.uuid(),nodeId:Je.string().min(1).max(64),visit:Je.number().int().nonnegative(),revision:Je.number().int().nonnegative(),parameters:nr,answers:tr,variables:Je.record(Je.string(),Ae)});import{z as ae}from"zod";var Fc=ae.array(ae.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"),_a=ae.intersection(ht,ae.looseObject({tags:Fc.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),Ca=ae.string().trim().max(80),Pa=ae.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),Ea=ae.union([ae.email().max(254),ae.literal("")]),Ra=ae.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),Hm=ae.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),Qm=ae.object({externalUserId:Hm.optional(),name:Ca.default(""),email:Ea.default(""),phone:Pa.optional(),attributes:_a.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),ka=ae.discriminatedUnion("type",[ae.strictObject({type:ae.literal("id"),value:ae.uuid()}),ae.strictObject({type:ae.literal("externalUserId"),value:Hm})]),ja=ae.strictObject({name:Ca.optional(),email:Ea.optional(),phone:Pa.optional(),attributes:_a.optional(),fingerprint:Ra.optional()}),Ta=e=>!e.customerData||e.customer?.type==="externalUserId",Na="customerData requires an externalUserId customer",mi=ae.object({id:ae.uuid(),externalUserId:ae.string().min(1).max(255).nullable(),name:Ca,email:Ea,phone:Pa.optional(),attributes:_a,createdAt:ae.iso.datetime()}).strict(),Jm=ae.object({customer:mi,changed:ae.boolean(),replayed:ae.boolean()}).strict(),ox=ae.discriminatedUnion("type",[ae.object({type:ae.literal("id"),value:ae.uuid()}).strict(),ae.object({type:ae.literal("externalUserId"),value:ae.string().trim().min(1).max(255)}).strict()]),ax=ae.object({name:Ca.optional(),email:Ea.optional(),phone:Pa.optional(),attributes:_a.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:ae.array(ae.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:ae.strictObject({add:Fc,remove:Fc}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),Mc=ae.object({lookup:ox}).strict(),Zm=Mc.extend({requestId:ae.uuid(),patch:ax}).strict(),Wm=ae.object({search:ae.string().trim().max(200).default(""),tag:ae.string().trim().max(40).default(""),planId:ae.string().max(200).default(""),versionId:ae.string().max(200).default(""),holdingStatus:ae.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:ae.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:ae.union([ae.iso.datetime(),ae.literal("")]).default(""),createdUntil:ae.union([ae.iso.datetime(),ae.literal("")]).default(""),offset:ae.coerce.number().int().min(0).max(1e5).default(0),limit:ae.coerce.number().int().min(1).max(100).default(50)}).strict(),Ym=ae.object({customers:mi.array(),hasMore:ae.boolean(),total:ae.number().int().nonnegative().nullable(),evaluatedAt:ae.iso.datetime()}).strict();var no=J.discriminatedUnion("type",[J.strictObject({type:J.literal("literal"),value:Ae}),J.strictObject({type:J.literal("variable"),key:ft,path:Sn.optional()}),J.strictObject({type:J.literal("feature"),featureKey:J.string().min(1).max(128)})]),sx=J.strictObject({requestId:J.uuid(),decisionId:J.uuid(),customerId:J.uuid(),externalUserId:J.string().min(1).max(255).nullable(),versionId:J.uuid(),receiptId:J.uuid(),value:Ae}),cx={funnelId:J.uuid(),requestId:J.uuid(),customer:ka,customerData:ja.optional(),attributes:ht.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},sP=J.discriminatedUnion("operation",[J.strictObject({operation:J.literal("decide"),...cx}).refine(Ta,Na),J.strictObject({operation:J.literal("read_decision"),decisionId:J.uuid()}),J.strictObject({operation:J.literal("evaluate_decision"),decisionId:J.uuid(),requestId:J.uuid(),nodeId:J.string().min(1).max(64),visit:J.number().int().nonnegative(),revision:J.number().int().nonnegative(),receiptId:J.uuid(),policyRevision:J.number().int().nonnegative(),generation:J.string().min(1).max(256),result:Nc}),J.strictObject({operation:J.literal("feature_config"),funnelId:J.uuid()}),J.strictObject({operation:J.literal("commit_decision_segment"),decisionId:J.uuid(),requestId:J.uuid(),nodeId:J.string().min(1).max(64),visit:J.number().int().nonnegative(),revision:J.number().int().nonnegative(),policyRevision:J.number().int().nonnegative(),generation:J.string().min(1).max(256),steps:J.array(Gm).max(32),boundary:J.strictObject({nodeId:J.string().min(1).max(64),visit:J.number().int().nonnegative()}).optional()}),J.strictObject({operation:J.literal("segment_configuration"),funnelId:J.uuid(),versionId:J.uuid()}),J.strictObject({operation:J.literal("configuration"),funnelId:J.uuid(),versionId:J.uuid().optional()}),J.strictObject({operation:J.literal("local_configuration"),funnelId:J.uuid()}),J.strictObject({operation:J.literal("report_used"),decisionId:J.uuid(),eventId:J.uuid(),occurredAt:J.iso.datetime({offset:!0}),reference:J.string().min(1).max(128).optional()})]),cP=J.strictObject({scope:Ue,decisionId:J.uuid(),requestId:J.uuid(),status:J.enum(["pending","completed","failed"]),decision:sx.nullable(),evaluation:J.discriminatedUnion("type",[$m,Km]).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"),uP=J.strictObject({scope:Ue,decisionId:J.uuid(),eventId:J.uuid(),source:J.literal("caller_reported")});import{z as Rt}from"zod";var Xm=Rt.strictObject({type:Rt.literal("bundle"),paywall:_n.optional(),offering:_n.optional(),coupons:_n,data:_n}),ux=e=>Rt.strictObject({type:Rt.literal(e),id:Rt.uuid()}),gP=Rt.strictObject({type:Rt.literal("bundle"),paywallVersionId:Rt.uuid().optional(),offeringVersionId:Rt.uuid().optional(),couponIds:Rt.array(Rt.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:Ae});var hP=Rt.strictObject({type:Rt.literal("bundle"),offering:ux("offering_version").nullable(),paywall:Rt.strictObject({versionId:Rt.uuid(),paywallId:Rt.uuid(),offeringVersionId:Rt.uuid()}).nullable(),coupons:Rt.array(ji).max(20),data:Ae});import{z as In}from"zod";import{z as dn}from"zod";var ef=dn.union([dn.string(),dn.number().finite(),dn.boolean(),dn.null()]),lx=dn.union([ef,dn.array(ef).min(1).max(20)]),dx=dn.record(Sn,lx).refine(e=>Object.keys(e).length<=10),tf=dn.strictObject({path:Sn,type:dn.enum(["string","number","boolean","strings"]),nullable:dn.boolean().optional(),aggregation:dn.enum(["count","exists"]).optional(),where:dx.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 px=["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"],nf=In.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),mx=_n,rf=In.discriminatedUnion("type",[Bm,In.strictObject({type:In.literal("claim_offer"),coupon:_n}),In.strictObject({type:In.literal("event"),event:nf}),In.strictObject({type:In.literal("api"),operation:In.enum(px),inputs:In.record(Sn,mx).refine(e=>Object.keys(e).length<=40),outputs:In.record(nf,tf).refine(e=>Object.keys(e).length<=20)})]);var rt=Oa,fx=Q.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),an={id:rt,name:Q.string().trim().min(1).max(80),position:Q.strictObject({x:Q.number().finite(),y:Q.number().finite()}).optional()},gx={success:rt,cancel:rt,unavailable:rt,failure:rt},qc=Q.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),Vc=Q.enum(["same_window","new_window"]),hx=Q.discriminatedUnion("type",[Q.strictObject({...an,type:Q.literal("entry"),next:rt,triggers:Q.array(Fm).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),Q.strictObject({...an,type:Q.literal("screen"),screenId:rt,presentation:Bn,outputs:Q.record(rt,rt),offering:Q.discriminatedUnion("source",[Q.strictObject({source:Q.literal("variable"),key:ft}),Q.strictObject({source:Q.literal("fixed"),versionId:Q.uuid()})]).optional()}),Q.strictObject({...an,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:ft}),next:rt}),Q.strictObject({...an,type:Q.literal("coupon"),couponId:Q.uuid(),writes:Q.strictObject({value:ft}),next:rt}),Q.strictObject({...an,type:Q.literal("coupons"),couponIds:Q.array(Q.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:Q.strictObject({value:ft}),next:rt}),Q.strictObject({...an,type:Q.literal("output"),value:Q.discriminatedUnion("type",[...no.options,Xm,Q.strictObject({type:Q.literal("selection"),screenId:rt,offeringKey:ft})])}),Q.strictObject({...an,type:Q.literal("condition"),cases:Q.array(Q.strictObject({condition:Ht,target:rt})).min(1).max(50),default:rt}),Q.strictObject({...an,type:Q.literal("feature"),featureKey:Q.string().min(1).max(128),writes:Q.strictObject({value:ft}),next:rt}),Q.strictObject({...an,type:Q.literal("split"),experimentId:Q.uuid(),applyPageExperiment:Q.literal(!0).optional(),routes:Q.record(fx,rt).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:rt}),Q.strictObject({...an,type:Q.literal("action"),...gx,execution:Um,action:rf,writes:tc.optional()}),Q.strictObject({...an,type:Q.literal("external_page"),appManifest:Ia.optional(),url:qc,openIn:Vc,opened:rt,failed:rt}),Q.strictObject({...an,type:Q.literal("end"),outcome:Q.enum(["completed","closed","ineligible","failed"]),output:no.optional()}),Q.strictObject({...an,type:Q.literal("wait"),writes:tc.optional(),wait:Q.discriminatedUnion("type",[Q.strictObject({type:Q.literal("duration"),delaySeconds:Q.number().int().min(1).max(2592e3),elapsed:rt}),Q.strictObject({type:Q.literal("event"),eventName:rt,outputs:Tc,timeoutSeconds:Q.number().int().min(1).max(2592e3),received:rt,timeout:rt})])})]),Bc=Q.strictObject({version:Q.literal(5),entry:rt,nodes:Q.array(hx).min(1).max(xn.flowNodes)}),Uc=Bc.superRefine((e,t)=>{Ax(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function Da(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 Ax(e,t){let n=[],r=new Map(e.nodes.map(l=>[l.id,l])),i=(l,m,S)=>{n.push(l),t?.({message:l,reason:m,path:S?["nodes",e.nodes.indexOf(S)]:[]})};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>xn.pages||e.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>xn.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let l of e.nodes){for(let m of Da(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 Da(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 Lc={maxTransitions:1e4,runTimeoutSeconds:2592e3};function of(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 Jn(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 M}from"zod";var fi=M.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Fa=e=>M.record(M.string(),Ae).refine(t=>rn(t)<=e,"Funnel evidence exceeds its byte budget"),HP=M.enum(["local_segment","evaluation","presentation","timer","event","operation"]),$c=M.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Gc=M.discriminatedUnion("type",[M.strictObject({type:M.literal("flag"),key:M.string().min(1).max(128)}),M.strictObject({type:M.literal("experiment"),id:M.uuid()}),M.strictObject({type:M.literal("saved_group"),id:M.uuid()}),M.strictObject({type:M.literal("config"),key:M.string().min(1).max(128)}),M.strictObject({type:M.literal("constant"),key:M.string().min(1).max(128)}),M.strictObject({type:M.literal("paywall_version"),id:M.uuid()}),M.strictObject({type:M.literal("offering_version"),id:M.uuid()}),M.strictObject({type:M.literal("reward"),id:M.uuid()})]),ro=M.strictObject({schemaVersion:M.literal(1),kind:$c,selector:Gc.nullable(),context:Fa(131072),contract:M.strictObject({version:M.number().int().positive(),evaluator:M.string().min(1).max(128),policyRevision:M.number().int().nonnegative()})}).refine(e=>rn(e)<=131072,"Node input exceeds its byte budget"),af=M.strictObject({schemaVersion:M.literal(1),kind:$c,outcome:M.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:Fa(131072),route:M.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:Fa(131072)}).refine(e=>rn(e)<=131072,"Node result exceeds its byte budget"),QP=M.strictObject({schemaVersion:M.literal(1),operations:M.record(fi,M.strictObject({attempts:M.number().int().nonnegative(),maxAttempts:M.number().int().min(1).max(5),deadlineAt:M.iso.datetime({offset:!0}),retryAt:M.iso.datetime({offset:!0}).nullable(),error:M.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:M.strictObject({type:fi,id:M.uuid()}).nullable()}))}).refine(e=>rn(e)<=65536,"Execution state exceeds its byte budget"),Rr={receiptId:M.uuid()},zc=M.iso.datetime({offset:!0}),JP=M.discriminatedUnion("type",[M.strictObject({type:M.literal("node_entered"),details:M.strictObject({kind:$c})}),M.strictObject({type:M.literal("presentation_shown"),details:M.strictObject({...Rr,source:M.literal("client"),occurredAt:zc.optional()})}),M.strictObject({type:M.literal("decision_accepted"),details:M.strictObject(Rr)}),M.strictObject({type:M.literal("signal_received"),details:M.strictObject({signalId:M.uuid(),nodeId:fi,eventName:fi,data:Fa(8192),source:M.literal("server"),occurredAt:zc})}),M.strictObject({type:M.literal("signal_consumed"),details:M.strictObject({...Rr,signalId:M.uuid()})}),M.strictObject({type:M.literal("wait_elapsed"),details:M.strictObject(Rr)}),M.strictObject({type:M.literal("wait_timeout"),details:M.strictObject(Rr)}),M.strictObject({type:M.literal("operation_completed"),details:M.strictObject({...Rr,operation:fi,reference:M.strictObject({type:fi,id:M.uuid()}).nullable()})}),M.strictObject({type:M.literal("execution_recovered"),details:M.strictObject({generation:M.number().int().positive(),reason:M.enum(["interrupted","expired_lease","delivery_failed"])})}),M.strictObject({type:M.literal("execution_failed"),details:M.strictObject({generation:M.number().int().positive(),code:M.string().regex(/^[a-z_]{1,64}$/)})}),M.strictObject({type:M.literal("run_completed"),details:M.strictObject({outcome:M.enum(["completed","ineligible","failed"])})}),M.strictObject({type:M.literal("run_closed"),details:M.strictObject({source:M.enum(["client","server","expiry"])})}),M.strictObject({type:M.literal("treatment_used"),details:M.strictObject({...Rr,source:M.enum(["client","server"]),occurredAt:zc,reference:M.string().min(1).max(128).optional()})})]);var pn=z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),yx=z.discriminatedUnion("type",[z.strictObject({id:pn,type:z.literal("owned"),publicData:wm.optional(),document:nn.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:pn,type:z.literal("paywall"),paywallVersionId:z.uuid()})]),Kc={kind:z.literal("funnel"),schemaVersion:z.literal(4),screens:z.array(yx).max(xn.pages),references:z.record(pn,Gc).refine(e=>Object.keys(e).length<=500),inputs:z.array(z.strictObject({variable:pn,screenId:pn,componentId:pn,required:z.boolean()})).max(xn.questions),variables:z.record(ft,ei).refine(e=>Object.keys(e).length<=xn.logicNodes),outputSchema:Xr,execution:z.strictObject({runTimeoutSeconds:z.number().int().min(1).max(Lc.runTimeoutSeconds),maxTransitions:z.number().int().min(1).max(Lc.maxTransitions)})},fE=z.strictObject({...Kc,graph:Bc});function bx(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 qa(e){return Array.isArray(e)?e.some(qa):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===Lm:qa(n))}function Sx(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=km(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&&!Ji(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}),bx(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"&&qa(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&qa(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function sf(e,t){for(let{message:n,reason:r,path:i}of Sx(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function cf(e,t){let n=(y,p,g=[])=>t.addIssue({code:"custom",message:y,path:g,params:{reason:p}}),r=Object.values(e.references),i=new Map(e.screens.map(y=>[y.id,y])),a=(y,p)=>r.some(g=>g.type===y&&("id"in g?g.id:g.key)===p);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let o=e.graph.nodes.filter(y=>y.type==="screen");(o.length!==i.size||o.some(y=>!i.has(y.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(y=>c.some(p=>y!==p&&p.startsWith(y+".")))&&n("Variable paths must not overlap","variable");function u(y,p){Object.hasOwn(e.variables,y)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(p)]);let g=s.get(y)??new Set;g.add(p.id),s.set(y,g)}for(let[y,p]of e.graph.nodes.entries()){let g=["graph","nodes",y],f=p.type==="feature"?p.featureKey:p.type==="offering"&&p.configuration.source==="feature"?p.configuration.featureKey:p.type==="output"&&p.value.type==="feature"?p.value.featureKey:p.type==="end"&&p.output?.type==="feature"?p.output.featureKey:null;f&&!a("flag",f)&&n("Flag selectors require an explicit GB resource reference","feature",g);let I=p.type==="feature"||p.type==="offering"||p.type==="coupon"||p.type==="coupons"||p.type==="action"&&p.action.type==="api"?["value"]:p.type==="action"&&p.action.type==="external_task"?Object.keys(p.action.outputs):p.type==="wait"&&p.wait.type==="event"?Object.keys(p.wait.outputs):[],A="writes"in p?p.writes??{}:{};(I.length!==Object.keys(A).length||I.some(w=>!Object.hasOwn(A,w))||new Set(Object.values(A)).size!==Object.values(A).length)&&n("Node writes must map every named output exactly once","variable",g);for(let[w,k]of Object.entries(A)){u(k,p);let N=e.variables[k],B=p.type==="offering"?"offering_version":p.type==="coupon"?"reward":p.type==="action"&&p.action.type==="api"?"json":p.type==="action"&&p.action.type==="external_task"?p.action.outputs[w]:p.type==="wait"&&p.wait.type==="event"?p.wait.outputs[w]:void 0;(N?.source.type!=="node"||B&&N.type!==B)&&n("Node writer source or output type does not match declaration","variable",g)}if(p.type==="coupons"){let w=e.variables[p.writes.value];(w?.type!=="array"||w.items?.type!=="reward"||w.items.nullable||w.nullable)&&n("Coupons output requires a non-null Reward array","variable",g);for(let k of p.couponIds)a("reward",k)||n("Coupons require Reward references","coupon",g)}if(p.type==="split"&&!a("experiment",p.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",g),p.type==="coupon"&&!a("reward",p.couponId)&&n("Coupon selectors require a Reward reference","coupon",g),p.type==="action"&&p.action.type==="claim_offer"&&p.action.coupon.source==="literal"){let w=p.action.coupon.value;(!w||typeof w!="object"||Array.isArray(w)||w.type!=="reward"||typeof w.id!="string"||Object.keys(w).length!==2||!a("reward",w.id))&&n("Coupon claims require a Reward reference","coupon",g)}if(p.type==="offering"&&p.configuration.source==="fixed"&&!a("offering_version",p.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",g),p.type==="screen"&&p.offering?.source==="variable"&&e.variables[p.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",g),p.type==="action"&&p.action.type==="claim_offer"&&p.action.coupon.source==="variable"&&(e.variables[p.action.coupon.key]?.type!=="reward"||p.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",g),p.type==="screen"){let w=i.get(p.screenId);if(p.offering?.source==="fixed"&&!a("offering_version",p.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",g),w?.type==="paywall"&&p.offering&&n("Paywall owns its fixed Offering Version","offering",g),w?.type==="paywall"&&!a("paywall_version",w.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",g),w?.type==="owned"){let k=w.document.pages[0];if(!k){n("Owned screen requires a page","screen",g);continue}Xn(w.document).some(B=>!B.complete)&&n("Owned screens require complete local content","translations",g);let N=new Set(w.document.actions.map(B=>B.id));(N.size!==Object.keys(p.outputs).length||Object.keys(p.outputs).some(B=>!N.has(B)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",g),Vn(k.root,B=>{!p.offering&&(B.type==="plan_picker"||(B.type==="stack"||B.type==="button")&&B.bind?.plan||B.type==="customer_data"&&["customer_plans","credit_packs"].includes(B.data.source))&&n("Product presentation requires an Offering Version","offering",g),B.type==="customer_data"&&Object.values(B.data.outputs??{}).some(me=>me!==void 0&&!N.has(me))&&n("Customer components require declared screen outcomes","componentOutput",g)})}}p.type==="end"&&["completed","ineligible"].includes(p.outcome)&&!p.output&&n("Completed and ineligible ends require a declared output","output",g),p.type==="end"&&p.output?.type==="literal"&&!un(e.outputSchema,p.output.value)&&n("Terminal output does not match outputSchema","output",g),p.type==="output"&&p.value.type==="literal"&&!un(e.outputSchema,p.value.value)&&n("Terminal output does not match outputSchema","output",g);let P=p.type==="output"?p.value:p.type==="end"?p.output:void 0;if(P?.type==="variable"&&!P.path){let w=e.variables[P.key];w&&!nc(w,e.outputSchema)&&n("Variable output does not match outputSchema","output",g)}if(p.type==="screen"){let w=i.get(p.screenId);if(w?.type==="owned")for(let k of oc(w.document))(/^(input|params)\./.test(k)||k.startsWith("variables.")&&!ic(k.slice(10),c))&&n("Screen values must reference registered variables","variable",g)}if(p.type==="condition")for(let w of p.cases){for(let k of Fn(w.condition))a("saved_group",k)||n("Conditions require explicit Saved Group references","savedGroup",g);for(let k of Jn(w.condition))k.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",g)}if(p.type==="output"&&p.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",g);for(let[w,k]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let N=p.value[w];if(N)if(N.source==="literal"){let B=w==="coupons"?N.value:[N.value];(!Array.isArray(B)||B.length>20||B.some(me=>!un({type:k,nullable:!1},me)||!a(k,me.id))||w==="coupons"&&new Set(B.map(me=>me.id)).size!==B.length)&&n("Bundle requires distinct scoped resource references",w==="coupons"?"coupon":w==="paywall"?"paywall":"offering",[...g,"value",w])}else{let B=e.variables[N.key];(N.path||!B||B.nullable||(w==="coupons"?B.type!=="array"||B.items?.type!=="reward"||B.items.nullable:B.type!==k))&&n("Bundle binding type does not match its slot","output",g)}}}}for(let[y,p]of e.graph.nodes.entries()){let g=p.type==="screen"?i.get(p.screenId):void 0,f=[...of(p,c),...g?.type==="owned"?oa(g.document).map(I=>ic(I,c)?.key??I):[]];for(let I of new Set(f)){let k=function(N){if(N===p.id)return!0;if(w.has(N))return!1;w.add(N);let B=e.graph.nodes.find(xe=>xe.id===N);return B?(P.has(N)?B.type==="action"?[B.cancel,B.unavailable,B.failure]:B.type==="wait"&&B.wait.type==="event"?[B.wait.timeout]:[]:Da(B)).some(k):!1};var S=k;if(!Object.hasOwn(e.variables,I)){n("Consumed variable is undeclared","variable",["graph","nodes",y]);continue}let A=e.variables[I];if(p.type==="screen"&&A.source.type==="input"&&e.inputs.some(N=>N.screenId===p.screenId&&N.variable===I)||A.source.type==="parameter"||A.source.type==="attribute")continue;let P=A.source.type==="input"?new Set(e.inputs.filter(N=>N.variable===I&&N.required).flatMap(N=>o.filter(B=>B.screenId===N.screenId).map(B=>B.id))):s.get(I)??new Set,w=new Set;(!P.size||k(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",y])}}(new Set(e.inputs.map(y=>y.variable)).size!==e.inputs.length||new Set(e.inputs.map(y=>`${y.screenId}:${y.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[y,p]of e.inputs.entries()){e.variables[p.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",y]);let g=i.get(p.screenId),f=g?.type==="owned"?Ji(g.document,p.componentId):null;if((f?.type!=="stack"||!f.interaction||!["input","toggle","select","multiselect","tabs"].includes(f.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",y]),f?.type==="stack"&&f.interaction){let I=f.interaction.type==="toggle"?"boolean":f.interaction.type==="multiselect"?"strings":"string";e.variables[p.variable]?.type!==I&&n("Input variable type does not match component","inputBinding",["inputs",y]);let A=e.variables[p.variable]?.enum;A&&!f.children.filter(P=>!P.hidden).every(P=>A.includes(P.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",y])}}for(let[y,p]of Object.entries(e.variables))p.enum&&p.type!=="string"&&n("Only string variables support enum","variable",["variables",y]),p.source.type==="input"&&!e.inputs.some(g=>g.variable===y)&&n("Input variable requires a component binding","inputBinding",["variables",y]);let l=0,m=0;for(let y of e.screens)if(y.type==="owned"){for(let p of y.document.pages)Vn(p.root,()=>{l++});m+=y.document.actions.length}(l>xn.components||m>xn.actions||rn(e)>xn.documentBytes)&&n("Funnel document exceeds its budget","budget")}var xx=z.strictObject({...Kc,graph:Uc}).superRefine(cf),gi=z.strictObject({...Kc,graph:Uc,displayName:z.string().trim().min(1).max(80)}).superRefine(cf),gE=gi.superRefine(sf),hE=xx.superRefine(sf),Ma=z.string().regex(Ft),io={requestId:z.uuid(),nodeId:pn,visit:z.number().int().nonnegative(),revision:z.number().int().nonnegative(),customerToken:Ma.optional()},Ix=z.discriminatedUnion("type",[z.strictObject({type:z.literal("screen"),output:pn,answers:tr,selection:z.record(pn,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:pn,productVersionId:z.uuid(),offerId:z.uuid().optional(),nativeOffer:ri.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"])})]),vx=z.object({nodeId:pn,visit:z.number().int().nonnegative(),revision:z.number().int().nonnegative(),components:z.record(pn,z.object({resourceKey:z.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:z.number().int().min(1).max(1e5),after:va.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(),Un=z.discriminatedUnion("operation",[z.strictObject({operation:z.literal("start"),funnelId:z.uuid(),requestId:z.uuid(),customer:ka.optional(),customerData:ja.optional(),locale:z.string().min(1).max(35),parameters:nr}).refine(Ta,Na),z.strictObject({operation:z.literal("get"),settlementRequestId:z.uuid().optional(),data:vx.optional(),purchase:z.strictObject({receiptId:z.uuid(),operationId:z.uuid()}).optional(),customerToken:Ma.optional()}),z.strictObject({operation:z.literal("resume"),requestId:z.uuid(),customerToken:Ma.optional()}),z.strictObject({operation:z.literal("submit"),...io,input:Ix}),z.strictObject({operation:z.literal("back"),...io}),z.strictObject({operation:z.literal("shown"),...io}),z.strictObject({operation:z.literal("close"),...io}),z.strictObject({operation:z.literal("commit_segment"),...io,policyRevision:z.number().int().nonnegative(),generation:z.string().min(1).max(256)}),z.strictObject({operation:z.literal("review"),receiptId:z.uuid().optional(),customerToken:Ma.optional()})]);function Va(e,t){let n=new Set,r=new Set,i=new Set,a=[],o=new Map,s=new Map,c=new Map;function u(p){for(let g of Fn(p))l(g)}function l(p){if(i.has(p)||!Object.hasOwn(t.savedGroups,p))return;let g=t.savedGroups[p];g&&(i.add(p),c.set(p,g),a.push(()=>{!Array.isArray(g)&&g.type==="condition"&&u(g.condition)}))}function m(p){for(let g of["hashAttribute","fallbackAttribute"])if(p[g]!==void 0&&Ec(p[g]))throw new Error(`Funnel GB ${g} uses a reserved flow namespace`);u(p.condition);for(let g of p.parentConditions??[])S(g.id),u(g.condition)}function S(p,g=!1){let f=Object.hasOwn(t.features,p)?t.features[p]:void 0;if(!f){if(g)throw new Error("Required GB Feature is unavailable");return}n.has(p)||(n.add(p),o.set(p,f),a.push(()=>{for(let I of f.rules??[]){m(I);for(let A of I.tracks??[])m(A.experiment)}}))}function y(p){let g=Object.hasOwn(t.experiments,p)?t.experiments[p]:void 0;if(!g)throw new Error("Required GB Experiment is unavailable");r.has(p)||(r.add(p),s.set(p,g),a.push(()=>m(g)))}for(let p of e.graph.nodes){p.type==="feature"&&S(p.featureKey,!0),p.type==="split"&&y(p.experimentId),p.type==="condition"&&p.cases.forEach(f=>u(f.condition)),p.type==="offering"&&p.configuration.source==="feature"&&S(p.configuration.featureKey,!0);let g=p.type==="output"?p.value:p.type==="end"?p.output:null;g?.type==="feature"&&S(g.featureKey,!0)}for(let p of a)p();return{...t,features:Object.fromEntries(o),experiments:Object.fromEntries(s),savedGroups:Object.fromEntries(c)}}import{z as ie}from"zod";function uf(e,t){let n=[],r={};Vt(e,i=>{if(i.hidden)return!1;if(i.type!=="quantity_picker")return;let a=i.bind?.plan?[i.bind.plan]:[];i.bind?.picker&&Vt(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 lf(e,t,n,r){let i=r.plans[t];if(!i?.available)throw new Error("Selected Product is unavailable");let a={};if(Vt(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 oo}from"zod";var df=oo.object({defaultLocale:gn,locales:oo.record(gn,oo.object({name:oo.string().max(80),description:oo.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 wx=["customer_data","coupon_code"],Ox=ie.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),pf=ie.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),Ba=(e,t)=>new Set(e.map(t)).size===e.length,_x=ie.strictObject({currency:he,amountMinor:ie.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),Cx=ie.strictObject({featureId:ie.uuid(),name:ie.string().trim().min(1).max(120),allowance:ie.string().max(40).nullable(),access:ie.boolean()}),Px=ie.strictObject({stripe:ie.strictObject({prices:ie.array(_x).min(1).max(50)}).optional(),apple:ie.strictObject({productIds:ie.array(Ox).min(1).max(10)}).optional(),google:ie.strictObject({products:ie.array(ie.strictObject({productId:pf,basePlanId:pf.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!Ba(e.stripe.prices,n=>n.currency)||e.apple&&!Ba(e.apple.productIds,n=>n)||e.google&&!Ba(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),Ex=ie.strictObject({name:ie.string().trim().min(1).max(80),interval:ie.enum(["free","week","month","year","one_time"]),intervalCount:ie.number().int().min(1).max(100),trial:ie.strictObject({days:ie.number().int().min(1).max(730),cardRequired:ie.boolean()}).nullable(),benefits:ie.array(Cx).max(50).refine(e=>Ba(e,t=>t.featureId),"Duplicate benefit"),channels:Px,prepaid:ie.array(Gi).max(100).optional()}),Rx=ie.strictObject({digest:li,content:ie.strictObject({discount:Zn,duration:en,appliesTo:Ls,displayCopy:df.nullable(),firstPurchaseOnly:ie.boolean(),qualificationRequired:ie.boolean(),startsAt:ie.iso.datetime().nullable(),endsAt:ie.iso.datetime().nullable(),grantWindowHours:ie.number().int().positive(),perCustomerLimit:ie.number().int().positive()})}),kx=ie.discriminatedUnion("type",[ie.strictObject({type:ie.literal("checkout"),product:ya}),ie.strictObject({type:ie.literal("close")}),ie.strictObject({type:ie.literal("action"),action:yc})]),Ua=ie.strictObject({kind:ie.literal("paywall"),formatVersion:ie.literal(1),name:ie.string().trim().min(1).max(80),offeringVersionId:ie.uuid(),presentation:Bn,screen:nn,products:Aa,catalog:ie.record(ie.uuid(),Ex),buttons:ie.record(Te,kx),coupons:ie.record(ie.uuid(),Rx)}).superRefine((e,t)=>{let n=g=>t.addIssue({code:"custom",message:g}),{screen:r}=e;uf(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),vc(r,wx).forEach(n),Xn(r).some(g=>!g.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,o=new Set;Vt(r,g=>{let f="bind"in g?g.bind:void 0;f?.promotionCode&&n("Promotion codes must not be published"),f?.plan&&i.add(f.plan),f?.coupon&&a.add(f.coupon),g.type==="plan_picker"&&(g.planIds?.forEach(I=>i.add(I)),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(f=>f.featureId)));for(let g of o)l.has(g)||n("Feature text must read a displayed benefit");let m=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!==m.length||m.some(g=>!Object.hasOwn(e.buttons,g.id)))&&n("Buttons must match the screen's actions");let y=!1;for(let g of Object.values(e.buttons)){if(g.type!=="checkout")continue;y=!0,(g.product.type==="fixed"?[g.product.productVersionId]:g.product.allowedProductVersionIds).some(I=>!u.has(I))&&n("Checkout may only sell displayed Products")}y||n("A Paywall needs a checkout button");let p=Object.keys(e.coupons);(p.length!==a.size||p.some(g=>!a.has(g)))&&n("Coupons must be exactly the bound Coupons")}),mf=ie.strictObject({state:ie.enum(["published","archived"]),controlRevision:ie.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:ie.uuid(),versions:ie.record(ie.uuid(),ie.strictObject({version:ie.number().int().positive(),artifact:ie.string().min(1),sourceDigest:ie.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var Zt={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},Hc=Oe.string().regex(/^[a-f0-9]{64}$/),Qc=Oe.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Zc=Ue.extend({environmentId:Oe.uuid()}),ff=Oe.strictObject({features:Oe.array(Oe.string()).max(500),experiments:Oe.record(Oe.uuid(),Oe.array(Oe.string()).max(20)),savedGroups:Oe.array(Oe.string()).max(1e3)}),Wc=Oe.strictObject({kind:Oe.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:Oe.number().int().positive(),url:Oe.string().min(1).max(2048),sha256:Hc,byteLength:Oe.number().int().positive().max(Zt.maxArtifactBytes),generation:Hc.optional()}),jx=Oe.strictObject({state:Oe.enum(["active","paused","archived"]),controlRevision:Qc,evaluationMode:Oe.enum(["local","remote"]),evaluationRevision:Qc,currentVersionId:Oe.uuid(),versions:Oe.record(Oe.uuid(),Oe.strictObject({artifact:Oe.string(),dependencies:ff,definitionDigest:li.optional(),couponDigests:Oe.record(Oe.uuid(),li).optional()}))}),Yc=Oe.strictObject({kind:Oe.literal("sdk_configuration"),schemaVersion:Oe.literal(1),scope:Zc,revision:Qc,generation:Hc,policy:Oe.strictObject({refreshIntervalSeconds:Oe.number().positive().max(15),maxControlAgeSeconds:Oe.number().positive().max(60)}),gb:Oe.strictObject({features:Oe.string().nullable(),pageExperiments:Oe.string().nullable()}),artifacts:Oe.record(Oe.string(),Wc),funnels:Oe.record(Oe.uuid(),jx),paywalls:Oe.record(Oe.uuid(),mf).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 yt(e){if(Array.isArray(e))return`[${e.map(yt).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)}:${yt(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function Xc(e){return $r(Gr(typeof e=="string"?new TextEncoder().encode(e):e))}function gf(e){return Xc(yt(e))}var Jc=class extends Error{constructor(n,r){super(n);De(this,"dependency",r)}};function hf(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(S=>l==="experiment"?S.type==="split"&&S.experimentId===m:l==="feature"&&n(S)===m)?.name,i=(l,m,S=r(m.type,m.resource))=>new Jc(l,{...m,...S?{step:S}:{}});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=Va(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 S=a.features[m],y=l.type==="feature"?e.variables[l.writes.value]:e.outputSchema,p={type:"feature",resource:m};if(!S||!y)throw i("Required public Feature declaration is unavailable",{reason:"unavailable",...p},l.name);if([S.defaultValue,...(S.rules??[]).flatMap(f=>[...Object.hasOwn(f,"force")?[f.force]:[],...f.variations??[],...(f.tracks??[]).flatMap(I=>I.experiment.variations)])].some(f=>f===void 0||!un(y,f)))throw i("GB Feature values violate the Funnel type contract",{reason:"value_type",...p},l.name)}let s=new Set,c=(l,m)=>{for(let S of Fn(l)){if(s.has(S))continue;let y=t.savedGroups[S];if(!y)throw i("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:S},m);s.add(S),!Array.isArray(y)&&y.type==="condition"&&c(y.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 S=r("feature",l);for(let y of m.rules??[]){c(y.condition,S);for(let p of[...y.parentConditions??[],...(y.tracks??[]).flatMap(g=>g.experiment.parentConditions??[])])u(p.id,S),c(p.condition,S);for(let p of y.tracks??[])c(p.experiment.condition,S)}}for(let[l,m]of Object.entries(a.experiments)){let S=r("experiment",l);c(m.condition,S);for(let y of m.parentConditions??[])u(y.id,S),c(y.condition,S)}for(let l of e.graph.nodes)if(l.type==="split"){let m=a.experiments[l.experimentId],S={type:"experiment",resource:l.experimentId};if(!m)throw i("Local Funnel requires a public Experiment",{reason:"unavailable",...S},l.name);for(let y of m.variations)if(typeof y!="string"||!Object.hasOwn(l.routes,y))throw i("Experiment variation has no declared Funnel route",{reason:"variation_route",...S},l.name)}return ff.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 Af(e){return gi.parse(e)}var yf=bt.strictObject({...ni,selector:bt.discriminatedUnion("type",[bt.strictObject({type:bt.literal("paywall"),paywallId:bt.uuid()}),bt.strictObject({type:bt.literal("version"),versionId:bt.uuid()})]),customerId:bt.uuid().optional(),commerce:Wr,locale:bt.string().min(1).max(35),requirement:Yn.optional()}),ao=bt.strictObject({id:bt.uuid(),paywallId:bt.uuid(),version:bt.number().int().positive(),document:ui.omit({requirement:!0,offeringId:!0}),offering:bt.strictObject({id:bt.uuid()}),content:bt.strictObject({environmentId:bt.uuid(),offeringVersionId:bt.uuid(),artifact:Wc.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:Yr,check:vr.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"})}),kr=bt.strictObject(ao.shape).omit({document:!0,offering:!0}).extend({content:ao.shape.content.unwrap()});function bf(e,t){let n=Ua.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 ao.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 Ut}from"zod";var Sf={requestId:Ut.uuid(),sourceId:Ut.uuid(),expectedAvailable:qt},xf=Ut.discriminatedUnion("action",[Ut.strictObject({...Sf,action:Ut.enum(["add","subtract","set_remaining"]),amount:ge}),Ut.strictObject({...Sf,action:Ut.literal("edit"),granted:ge,expiresAt:Ut.iso.datetime({offset:!0}).nullable(),nextResetAt:Ut.iso.datetime({offset:!0}).nullable(),expectedRevision:Ut.number().int().nonnegative()})]),eu=Ut.strictObject({sourceId:Ut.uuid(),available:qt,held:qt,spent:qt,adjustmentGrantId:Ut.uuid().nullable()}),If=eu.extend({granted:qt,expiresAt:Ut.iso.datetime({offset:!0}).nullable(),nextResetAt:Ut.iso.datetime({offset:!0}).nullable(),revision:Ut.number().int().nonnegative()});import{z as sn}from"zod";var vf=sn.discriminatedUnion("action",[sn.object({action:sn.literal("upsert"),externalId:sn.string().min(1).max(128),name:sn.string().trim().min(1).max(80)}).strict(),sn.object({action:sn.literal("archive"),entityId:sn.uuid()}).strict()]),wf=sn.object({id:sn.uuid(),externalId:sn.string().min(1).max(128),name:sn.string().min(1).max(80),archived:sn.boolean()}).strict();import{z as Tt}from"zod";import{z as Tr}from"zod";var _f=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],Of=Tr.string().regex(/.+\/.+/),tu=Tr.number().min(-100),jr=Tr.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),Tx=Tr.strictObject({input:jr,output:jr,cache_read:jr.optional(),cache_write:jr.optional(),reasoning:jr.optional(),input_audio:jr.optional(),output_audio:jr.optional()}),nu=(e,t)=>Tr.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),fR=Tr.strictObject({defaultMarkup:tu,providerMarkups:nu(Tr.string().min(1),tu),modelMarkups:nu(Of,tu),customModels:nu(Of,Tx.partial())});import{z as fe}from"zod";var Nr=fe.iso.datetime({offset:!0}),rr=fe.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),Nx=fe.discriminatedUnion("kind",[fe.object({kind:fe.literal("absolute"),from:Nr,to:Nr}).strict(),fe.object({kind:fe.literal("last_days"),days:fe.union([fe.literal(1),fe.literal(7),fe.literal(30),fe.literal(90)])}).strict(),fe.object({kind:fe.literal("billing_cycles"),membershipId:fe.uuid(),count:fe.number().int().min(1).max(12),includeCurrent:fe.boolean()}).strict()]),Cf=fe.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"),Dx=fe.object({key:fe.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:fe.array(fe.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),Dr=fe.object({range:Nx,timezone:Cf,filterBy:fe.array(Dx).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:fe.enum(["hour","day","week","month"]),internal_feature_id:fe.uuid().nullable(),entityId:fe.uuid().nullable(),topN:fe.number().int().min(1).max(50).nullable(),groupBy:fe.union([fe.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),fe.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:fe.object({bucket:Nr,group:fe.string().max(240),isOther:fe.boolean(),internal_feature_id:fe.uuid(),resourceId:fe.uuid()}).strict().nullable(),limit:fe.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)"})}),Pf=fe.object({from:Nr,to:Nr,interval:fe.enum(["hour","day","week","month"]),timezone:Cf,rows:fe.array(fe.object({bucket:Nr,group:fe.string().max(240),isOther:fe.boolean(),internal_feature_id:fe.uuid(),resourceId:fe.uuid(),consumedUnits:rr,refundedUnits:rr,reservedUnits:rr,charged:rr,refunded:rr,reserved:rr,netUnits:rr,netCharged:rr}).strict()).max(100),nextCursor:fe.object({bucket:Nr,group:fe.string().max(240),isOther:fe.boolean(),internal_feature_id:fe.uuid(),resourceId:fe.uuid()}).strict().nullable()}).strict();var hi=Tt.string().regex(/^(0|[1-9]\d{0,29})$/),Ef=Tt.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),ru=Tt.strictObject({bucket:Tt.iso.datetime({offset:!0}),group:Tt.string().max(240),isOther:Tt.boolean(),internal_feature_id:Tt.uuid()}),Rf=Tt.strictObject({...Dr.shape,groupBy:Tt.union([Tt.enum(["customer","entity","entitlement"]),Tt.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:ru.nullable()}).superRefine((e,t)=>{let n=Dr.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),kf=Tt.strictObject({from:Tt.iso.datetime({offset:!0}),to:Tt.iso.datetime({offset:!0}),interval:Dr.shape.interval,timezone:Dr.shape.timezone,rows:Tt.array(Tt.strictObject({...ru.shape,eventCount:hi,units:Ef,tokenEventCount:hi,tokens:Tt.strictObject(Object.fromEntries(_f.map(e=>[e,hi]))),totalTokens:hi,providerCostEventCount:hi,providerCostUsd:Ef,invalidTelemetryEventCount:hi})).max(100),nextCursor:ru.nullable()});import{z as pt}from"zod";var jf=pt.object({requestId:pt.uuid(),items:pt.array(pt.object({customerId:pt.uuid(),command:Vi.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"),Tf=pt.object({batchId:pt.uuid(),after:pt.number().int().min(-1).max(999),limit:pt.number().int().min(1).max(100)}).strict(),Nf=pt.object({batchId:pt.uuid(),status:pt.enum(["queued","complete"]),total:pt.number().int().min(1).max(1e3),processed:pt.number().int().min(0).max(1e3),items:pt.array(pt.object({position:pt.number().int().min(0).max(999),customerId:pt.uuid(),idempotencyKey:pt.string().min(1).max(120),status:pt.enum(["queued","accepted","rejected","failed"]),receipt:Bi.nullable(),errorCode:pt.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:pt.number().int().min(0).max(999).nullable()}).strict();import{z as E}from"zod";var Fx=E.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),Df=E.enum(["draft","active","paused","archived"]),Ff=E.string().min(1).max(256),Mf=E.array(Ff).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),Mx=E.strictObject({duration:E.enum(["day","week","month","year"]),length:E.number().int().min(1).max(3660)}),qx=E.strictObject({internal_feature_id:E.uuid(),allowance:E.number().nonnegative().max(1e15).nullable(),expiry:Mx.nullable()}),Vx=E.discriminatedUnion("type",[E.strictObject({type:E.literal("feature_grant"),grants:E.array(qx).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),E.strictObject({type:E.literal("free_product"),productId:Ff,duration:en}),E.strictObject({type:E.literal("invoice_credits"),amount:E.number().positive().max(1e8),duration:en,rollover:E.boolean(),productIds:Mf})]),Bx=E.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),qf=E.object({key:Bx,name:E.string().trim().min(1).max(80),configuration:Vx}).strict(),Vf=E.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),iu=E.object({code:Vf,maxUses:E.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:E.boolean()}).strict(),Bf=E.object({key:E.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:E.string().trim().min(1).max(80),rewardId:E.uuid(),redeemOn:E.enum(["customer_creation","checkout"]),receivedBy:E.enum(["referrer","all"]),maxRedemptions:E.number().int().min(1).max(1e6).nullable(),productIds:Mf,excludeTrial:E.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),Uf={id:E.uuid(),projectId:E.uuid(),environmentId:E.uuid(),revision:E.number().int().nonnegative(),status:Df,createdAt:E.iso.datetime({offset:!0}),updatedAt:E.iso.datetime({offset:!0})},Ux=qf.extend(Uf).strict(),Lx=Bf.safeExtend(Uf).strict(),PR=E.strictObject({id:E.uuid(),key:E.string(),name:E.string(),type:Fx,status:Df}),ER=E.discriminatedUnion("action",[E.object({action:E.literal("save"),id:E.uuid().nullable(),revision:E.number().int().nonnegative(),input:qf}).strict(),E.object({action:E.enum(["activate","pause","resume","archive","delete"]),id:E.uuid(),revision:E.number().int().nonnegative()}).strict()]),RR=E.discriminatedUnion("action",[E.object({action:E.literal("save"),id:E.uuid().nullable(),revision:E.number().int().nonnegative(),input:Bf}).strict(),E.object({action:E.enum(["activate","pause","resume","archive","delete"]),id:E.uuid(),revision:E.number().int().nonnegative()}).strict()]),Lf=E.object({id:E.uuid(),rewardId:E.uuid(),programId:E.uuid().nullable(),customerId:E.uuid(),referrerId:E.uuid().nullable(),status:E.enum(["pending","applied","unavailable"]),result:E.record(E.string(),E.unknown()).nullable(),createdAt:E.iso.datetime({offset:!0})}).strict(),zf=E.object({code:Vf,requestId:E.uuid()}).strict(),$f=E.strictObject({redemptionId:E.uuid(),currency:he,requestId:E.uuid(),accepted:E.literal(!0)}),zx=E.strictObject({type:E.literal("checkout"),orderId:E.uuid(),productVersionId:E.uuid(),currency:he,duration:en,renewalAmountMinor:E.number().int().positive().max(1e8),status:E.enum(["created","pending","trialing","paid","cancelled","failed"]),url:E.url().nullable()}),Gf=E.discriminatedUnion("type",[zx,E.strictObject({type:E.literal("subscription"),operationId:E.uuid(),membershipId:E.uuid(),productVersionId:E.uuid(),currency:he,duration:en,renewalAmountMinor:E.number().int().positive().max(1e8),status:E.enum(["pending","running","applied","failed"])})]),Kf=E.object({programId:E.uuid(),requestId:E.uuid()}).strict(),Hf=E.object({id:E.uuid(),programId:E.uuid(),code:iu.shape.code,createdAt:E.iso.datetime({offset:!0})}).strict(),kR=E.object({rows:E.array(Ux).max(100),nextCursor:E.uuid().nullable()}).strict(),jR=E.object({rows:E.array(Lx).max(100),nextCursor:E.uuid().nullable()}).strict(),$x=iu.extend({id:E.uuid(),redemptions:E.number().int().nonnegative()}).strict(),Gx=E.strictObject({id:E.uuid(),programId:E.uuid().nullable(),customerId:E.uuid().nullable(),referrerId:E.uuid().nullable(),code:E.string().nullable(),status:E.enum(["pending","triggered","applied"]),createdAt:E.iso.datetime({offset:!0})}),TR=E.object({codes:E.array($x).max(100),redemptions:E.array(Gx).max(100),customers:E.record(E.uuid(),E.string()),codesCursor:E.uuid().nullable(),redemptionsCursor:E.uuid().nullable()}).strict(),NR=E.discriminatedUnion("action",[E.object({action:E.literal("create"),rewardId:E.uuid(),revision:E.number().int().nonnegative(),input:iu}).strict(),E.object({action:E.literal("remove"),rewardId:E.uuid(),revision:E.number().int().nonnegative(),codeId:E.uuid()}).strict()]);import{z as v}from"zod";import{z as Z}from"zod";var Cn={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},so=e=>new Set(e).size===e.length,ou=Z.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),Kx=Z.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),co=Z.string().min(1).max(200).regex(/^[a-zA-Z0-9_./-]+$/).refine(e=>!e.includes("..")&&!e.endsWith(".")&&!e.split("/").some(t=>!t||t.startsWith(".")||t.endsWith(".lock"))),Hx=Z.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),Qf=Z.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var Jf=Z.strictObject({id:Z.uuid(),repo:Kx,platform:Z.enum(["github","gitlab","bitbucket"]),branches:Z.array(co).min(1).max(4).refine(so),workflow:Z.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:Z.array(Z.uuid()).min(1).max(4).refine(so),include:Z.array(Qf).min(1).max(16),exclude:Z.array(Qf).max(16),methods:Z.array(Z.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(so),maxAgeHours:Z.number().int().min(1).max(720)}),Zf=Jf.extend({revision:Z.number().int().positive()}),MR=Z.strictObject({repository:Jf,expectedRevision:Z.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),Wf=Z.strictObject({repositoryId:Z.uuid(),branch:co}),Qx=Z.array(ou).max(Cn.keys).refine(so),Yf=Z.strictObject({repository:Zf.omit({keyIds:!0}),branch:co,keys:Qx,keySetHash:Z.string().regex(/^[a-f0-9]{64}$/)}),Jx=Z.strictObject({filePath:Hx,startingLineNumber:Z.number().int().min(1).max(1e7)}),au=Z.strictObject({protocol:Z.literal(1),repositoryId:Z.uuid(),branch:co,workflow:Z.string().max(200),configurationRevision:Z.number().int().positive(),keySetHash:Z.string().regex(/^[a-f0-9]{64}$/),commit:Z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:Z.uuid(),runNumber:Z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:Z.number().int().min(1).max(1e4),scannerVersion:Z.literal("1"),scannedAt:Z.iso.datetime({offset:!0}),coverage:Z.strictObject({complete:Z.literal(!0),files:Z.number().int().min(0).max(Cn.files),sourceBytes:Z.number().int().min(0).max(Cn.sourceBytes),unresolvedCalls:Z.number().int().min(0).max(1e6),unsupportedFiles:Z.number().int().min(0).max(Cn.files)}),features:Z.array(Z.strictObject({key:ou,refs:Z.array(Jx).max(Cn.referencesPerKey)})).max(Cn.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)>Cn.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),su=Z.strictObject({scanId:Z.uuid(),commit:Z.string(),receivedAt:Z.string(),references:Z.number().int().nonnegative(),removedReferences:Z.number().int().nonnegative()}),Zx=su.extend({repositoryId:Z.uuid(),branch:co,workflow:Z.string(),digest:Z.string(),configurationRevision:Z.number().int().positive(),runNumber:Z.number().int().positive(),runAttempt:Z.number().int().positive(),scannedAt:Z.string(),keySetHash:Z.string(),coverage:au.shape.coverage}),Wx=Z.strictObject({repositories:Z.array(Zf).max(Cn.repositories),scans:Z.array(Zx).max(Cn.repositories*Cn.branches)}),Yx=Z.strictObject({key:ou,references:Z.number().int().nonnegative(),coveredTargets:Z.number().int().nonnegative(),expiredTargets:Z.number().int().nonnegative(),uncertainTargets:Z.number().int().nonnegative()}),qR=Z.strictObject({available:Z.boolean().default(!0),settings:Wx,expectedTargets:Z.number().int().min(0).max(80),features:Z.array(Yx).max(2001),truncated:Z.boolean()});import{z as St}from"zod";var Xx=St.enum(["checkout.session.completed","checkout.session.expired","checkout.session.async_payment_succeeded","checkout.session.async_payment_failed","customer.subscription.created","customer.subscription.updated","customer.subscription.deleted","customer.subscription.paused","customer.subscription.resumed","invoice.created","invoice.paid","customer.discount.created","customer.discount.updated","refund.created","refund.updated","refund.failed","charge.refunded"]),e0=St.strictObject({provider:St.literal("stripe"),accountId:St.string().regex(/^acct_[A-Za-z0-9]+$/),eventId:St.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),type:Xx,occurredAt:St.number().int().positive().max(Number.MAX_SAFE_INTEGER),data:St.record(St.string(),St.unknown()).and(St.object({id:St.string().min(1).max(255),object:St.enum(["checkout.session","subscription","invoice","discount","refund","charge"]),livemode:St.boolean()}))}),Xf=St.union([e0,ul]),eg=St.strictObject({id:St.uuid(),eventId:St.string().min(1).max(200),source:St.literal("merchant"),providerVerified:St.literal(!1),outcome:St.string().min(1).max(100)});import{z as Lt}from"zod";var ng={customerId:Lt.uuid(),eventId:Lt.string().trim().min(1).max(200),grantId:Lt.uuid(),occurredAt:Lt.iso.datetime({offset:!0})},rg=Lt.strictObject({...ng,productVersionId:Lt.uuid(),subscriptionId:Lt.string().trim().min(1).max(255)}),ig=Lt.strictObject({...ng,merchandiseId:Lt.uuid()}),og=Lt.union([rg,ig]),tg={id:Lt.uuid(),couponId:Lt.uuid(),status:Lt.literal("redeemed"),source:Lt.literal("merchant"),recordedAt:Lt.iso.datetime({offset:!0})},ag=Lt.union([rg.extend(tg),ig.extend(tg)]);import{z as re}from"zod";var sg=Fp,t0=sg.extend({invoice_id:sg.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),cu=re.strictObject({name:re.string().trim().min(1).max(255),memo:re.string().max(1e4).nullable().optional(),footer:re.string().max(1e4).nullable().optional(),net_terms_days:re.number().int().positive().nullable().optional()}),n0=cu.extend({id:re.string().min(1).max(255),created_at:re.number().nullable()}),cg=re.strictObject({items:re.array(n0).max(50),nextCursor:re.uuid().nullable()}),HR=re.discriminatedUnion("action",[re.strictObject({action:re.literal("create"),requestId:re.uuid(),values:cu}),re.strictObject({action:re.literal("update"),id:re.string().min(1).max(255),values:cu}),re.strictObject({action:re.literal("delete"),id:re.string().min(1).max(255)})]),ug=re.discriminatedUnion("action",[re.strictObject({action:re.literal("create"),requestId:re.uuid(),params:ii}),re.strictObject({action:re.enum(["finalize","send","pay","void"]),requestId:re.uuid(),invoiceId:re.uuid()}),re.strictObject({action:re.literal("reissue"),requestId:re.uuid(),invoiceId:re.uuid(),params:t0})]),uu=re.strictObject({id:re.uuid(),customerId:re.uuid(),providerInvoiceId:re.string().nullable(),status:re.enum(["draft","open","paid","void","uncollectible"]),currency:re.string(),totalMinor:re.string().regex(/^-?\d+$/),paidMinor:re.string().regex(/^\d+$/),refundedMinor:re.string().regex(/^\d+$/),hostedInvoiceUrl:re.url().nullable(),createdAt:re.number(),collectionMethod:re.enum(["send_invoice","charge_automatically"]).nullable()}),lg=uu.extend({lines:re.array(re.strictObject({id:re.uuid(),description:re.string(),amountMinor:re.string().regex(/^-?\d+$/),netAmountMinor:re.string().regex(/^-?\d+$/),quantity:re.number().nullable(),periodStart:re.number().nullable(),periodEnd:re.number().nullable()})).max(1e3)}),Ai=re.strictObject({taskId:re.uuid(),status:re.enum(["ready","running","done","dead"]),invoice:uu.nullable(),errorCode:re.string().nullable()}),dg=re.strictObject({items:re.array(uu).max(50),nextCursor:re.uuid().nullable(),operations:re.array(Ai).max(50),operationsLimited:re.boolean()});var r0=v.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:Ue,permissions:v.array(r0),expiresAt:v.iso.datetime().nullable()},qk=v.discriminatedUnion("kind",[v.object({...pg,kind:v.literal("server"),keyId:v.string().min(1)}),v.object({...pg,kind:v.literal("customer"),customerId:v.string().min(1),identityKind:v.enum(["identified","guest"]),expiresAt:v.iso.datetime()})]),U=v.object({requestId:v.uuid(),scope:Ue}).strict(),i0=Qm.safeExtend({fingerprint:Ra.optional()}).strict(),o0=U.extend({customer:mi,created:v.boolean()});function mg(){return U.extend({offer:ji.nullable(),reason:fd.nullable()})}var O={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:ip,response:U.extend({message:v.object({messageId:v.uuid(),channel:$i,acceptedAt:v.iso.datetime({offset:!0}),status:v.enum(["accepted","sending","completed","canceled"]),replayed:v.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:v.strictObject({messageId:v.uuid()}),response:U.extend({message:v.object({id:v.uuid(),channel:$i,status:v.enum(["accepted","sending","completed","canceled"]),deliveries:v.array(v.object({id:v.uuid(),status:ap,attempts:v.number().int().nonnegative(),receipts:v.array(v.object({kind:sp,occurredAt:v.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:Hu,response:U.extend({installation:gr})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:Qu,response:U.extend({installation:gr})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:xo,response:U.extend({installation:gr})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:v.strictObject({channel:$i}),response:U.extend({preference:cs})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:op,response:U.extend({preference:cs})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:v.strictObject({cursor:v.uuid().optional()}),response:U.extend({templates:cg})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:v.strictObject({customerId:v.uuid(),params:ii}),response:U.extend({preview:cc})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:v.strictObject({customerId:v.uuid(),requestId:v.uuid(),params:ii}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:U.extend({operation:Ai})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:v.strictObject({customerId:v.uuid(),command:ug}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:U.extend({operation:Ai})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:v.strictObject({customerId:v.uuid(),taskId:v.uuid()}),response:U.extend({operation:Ai})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:v.strictObject({customerId:v.uuid(),cursor:v.uuid().optional()}),response:U.extend({invoices:dg})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:v.strictObject({customerId:v.uuid(),invoiceId:v.uuid()}),response:U.extend({invoice:lg})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:Wf,response:U.extend({config:Yf})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:au,response:U.extend({receipt:su})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:v.strictObject({}),response:U.extend({payload:eo})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:Cm,response:U.merge(Sa)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:Pm,response:U.merge(Em)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:v.strictObject({customerId:v.uuid(),sourceId:v.uuid()}),response:U.extend({balance:If})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:v.strictObject({customerId:v.uuid(),command:xf}),response:U.extend({balance:eu})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:v.strictObject({internal_feature_id:v.uuid(),customerId:v.uuid().optional(),entityId:v.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:U.extend({internal_feature_id:v.uuid(),config:vs,model_markups:jo})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:v.strictObject({customerId:v.uuid(),query:Wo}),response:U.extend({usage:Ui})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:v.strictObject({customerId:v.uuid(),command:Jd}),response:U.extend({usage:Ui})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:v.strictObject({customerId:v.uuid(),command:zd}),response:U.extend({grant:Ks})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:$d,response:U.extend({grants:Gd})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:v.union(gm.options.map(e=>e.extend({customerId:v.uuid().optional(),customerToken:v.string().regex(Ft).optional()}))),response:U.extend({operation:hm})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:im.extend({customerId:v.uuid().optional()}),response:U.extend({setup:mc})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:om.extend({customerId:v.uuid().optional()}),response:U.extend({setup:mc})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:tm.safeExtend({customerId:v.uuid()}),response:U.extend({batch:Wi})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:da.extend({customerId:v.uuid()}),response:U.extend({batch:Wi})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:da.extend({customerId:v.uuid()}),response:U.extend({batch:Wi})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:da.extend({customerId:v.uuid()}),response:U.extend({batch:Wi})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:v.discriminatedUnion("action",[pa.options[0].extend({customerId:v.uuid()}),pa.options[1].extend({customerId:v.uuid()}),pa.options[2].extend({customerId:v.uuid()})]),response:U.extend({trial:pc})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:nm.extend({customerId:v.uuid()}),response:U.extend({trial:pc})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:ga,response:U.extend({subscriptions:pm})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:ga,response:U.extend({purchases:mm})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:um,response:U.extend({conflicts:fm})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:lm,response:U.extend({resolution:dm})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:sm,response:U.extend({verification:cm})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:Hp.safeExtend({...ni,customerId:v.uuid().optional()}),response:U.extend({quote:oi})},recordBillingEvent:{method:"POST",path:"billing/events/record",permission:"billing:write",audience:"server",request:Xf,response:U.extend({record:eg})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Pr.extend({customerId:v.uuid().optional(),intent:v.enum(["confirm","cancel"]).optional()}),response:U.extend({operation:ai})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Pr.extend({customerId:v.uuid().optional()}),response:U.extend({operation:ai})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:Zp.safeExtend({customerId:v.uuid().optional()}),response:U.extend({quote:Yp})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Pr.extend({customerId:v.uuid().optional(),intent:v.enum(["confirm","cancel"]).optional()}),response:U.extend({operation:uc})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Pr.extend({customerId:v.uuid().optional()}),response:U.extend({operation:uc})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:Xp.safeExtend({customerId:v.uuid()}),response:U.extend({quote:lc})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Pr.extend({customerId:v.uuid()}),response:U.extend({operation:la})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Pr.extend({customerId:v.uuid()}),response:U.extend({operation:la})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:Pd,response:U.extend({controls:$s})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:xd,response:U.extend({prepared:vd})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:wd,response:U.extend({authorization:Ho})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Td,response:U.extend({coupons:Nd})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Od,response:U.extend({authorization:Ho})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:kd,response:U.extend({invoices:jd})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:Rd.extend({customerId:v.uuid()}),response:U.extend({operation:Ai})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:Ed,response:U.extend({invoice:Di})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:v.object({customerId:v.uuid(),command:Cd}).strict(),response:U.extend({controls:$s})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:v.object({customerId:v.uuid(),command:vf}).strict(),response:U.extend({entity:wf})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:v.strictObject({customerId:v.uuid().nullable(),query:Rf}),response:U.extend({analytics:kf})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:v.object({customerId:v.uuid().nullable(),query:Dr}).strict(),response:U.extend({analytics:Pf})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:jf,response:U.extend({batchId:v.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:Tf,response:U.extend({batch:Nf})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:lp.extend({customerId:v.string().min(1).optional()}),response:U.extend({check:vr})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:v.strictObject({kind:er,selector:v.discriminatedUnion("type",[v.strictObject({type:v.literal("resource"),id:v.uuid()}),v.strictObject({type:v.literal("version"),id:v.uuid()})]),customerId:v.string().min(1).optional()}),response:U.extend({content:ac})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:yf,response:U.extend({paywall:kr})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:v.strictObject({...ni,selector:Sm,customerId:v.string().min(1).optional(),commerce:Wr,requirement:Yn.optional()}),response:U.extend({offering:xm,candidates:v.array(Ws).max(20),availability:v.array(v.strictObject({productVersionId:v.uuid(),available:v.boolean(),reason:v.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:vr.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:v.object({customerId:v.uuid().optional(),entityId:v.uuid().optional()}).strict(),response:U.extend({holdings:Zd})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:v.object({customerId:v.uuid().optional(),query:Yd}).strict(),response:U.extend({ledger:Xd})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:Kd.extend({customerId:v.uuid().optional()}),response:U.extend({detail:Hd})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:Hs.safeExtend({customerId:v.uuid().optional()}),response:U.extend({statement:Qd})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:v.object({customerId:v.uuid().optional(),command:Vi.options[0]}).strict(),response:U.extend({quote:Bd})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:v.strictObject({customerId:v.uuid(),command:v.union([v.strictObject({eventName:v.string().min(1),quantity:ge.optional(),properties:gt.optional(),entityId:v.uuid().optional(),idempotencyKey:v.string().min(1).max(120)}),v.strictObject({internal_feature_id:v.uuid(),quantity:ge.optional(),properties:gt.optional(),entityId:v.uuid().optional(),idempotencyKey:v.string().min(1).max(120)})])}),response:U.extend({receipts:v.array(Bi).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:v.object({customerId:v.uuid(),command:Vi.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:U.extend({receipt:Bi})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:zf,response:U.extend({redemption:Lf})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:Kf,response:U.extend({referralCode:Hf})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:$f,response:U.extend({checkout:Gf})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:tp,response:U.extend({seats:Zs})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:np,response:U.extend({seats:Zs})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:i0,response:o0},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Mc,response:U.extend({customer:mi})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:Wm,response:U.extend(Ym.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:Zm,response:U.extend(Jm.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:v.object({customerId:v.uuid()}).strict(),response:U.extend(Gn.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:v.strictObject({}),response:U.extend(Gn.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:v.strictObject({customerId:v.uuid(),sessionId:v.uuid().optional()}),response:U.extend({revoked:v.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:v.strictObject({guestToken:v.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:Ra.optional()}),response:U.extend({customerId:v.uuid(),guestToken:v.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:v.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:v.strictObject({guestToken:v.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:U.extend(Gn.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:v.strictObject({guestToken:v.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:v.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:v.uuid()}),response:U.extend({customer:mi,switched:v.boolean(),replayed:v.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:v.strictObject({code:v.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:v.uuid()}),response:mg()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:v.object({}).strict(),response:U.extend({offers:v.array(ji)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:v.object({customerId:v.string().min(1).max(255).optional(),couponId:v.uuid(),...ni,requestId:v.uuid(),couponContentDigest:v.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:mg()},recordCouponRedemption:{method:"POST",path:"offers/redemptions",permission:"billing:write",audience:"server",request:og,response:U.extend({receipt:ag})}},Vk={recordBillingEvent:O.recordBillingEvent,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,recordCouponRedemption:O.recordCouponRedemption,redeemCoupon:O.redeemCoupon,redeemReward:O.redeemReward,createReferralCode:O.createReferralCode,claimRewardProduct:O.claimRewardProduct,readSeats:O.readSeats,manageSeat:O.manageSeat};import{z as lu}from"zod";var uo=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=>Qt(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 uo("Required GB Feature is unavailable");i=Dn(e.featureKey,t),o=i.value,Object.assign(r,ti(e,{value:o})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new uo("Required GB Experiment is unavailable");if(a=Go(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 uo("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:Dn(e.configuration.featureKey,t).value;o={type:"offering_version",id:lu.uuid().parse(u)},Object.assign(r,ti(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,ti(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 fg(e,t,n){lu.uuid().parse(e),lu.number().int().nonnegative().parse(t);let r=$r(Gr(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 K}from"zod";var ir=K.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),a0=K.enum(["running","waiting","completed","closed","ineligible","failed"]),s0=K.discriminatedUnion("type",[Dc,K.strictObject({type:K.literal("wait"),receiptId:K.uuid(),kind:K.enum(["timer","event","operation"]),deadline:K.iso.datetime({offset:!0}).nullable(),eventName:ir.optional()}),K.strictObject({type:K.literal("open_url"),receiptId:K.uuid(),url:qc,openIn:Vc}),K.strictObject({type:K.literal("event"),receiptId:K.uuid(),event:ir})]),La=K.strictObject({type:K.literal("funnel"),id:K.uuid(),versionId:K.uuid()}),c0={id:ir,presentation:Bn,outputs:K.array(ir).max(250),inputs:wa,values:K.record(K.string(),Ae).optional(),offeringKey:ft.optional(),capabilities:Yr,customerData:Ap,dataCursors:K.record(ir,va.nullable())},u0=K.strictObject({...c0,content:K.strictObject({type:K.literal("document"),document:nn})}),pu=K.strictObject({id:K.uuid(),source:La,revision:K.number().int().nonnegative(),visit:K.number().int().nonnegative(),nodeId:ir,nodeType:K.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:a0,stopped:K.boolean(),canBack:K.boolean(),authenticated:K.boolean(),locale:K.string().min(1).max(35),answers:tr,parameters:nr,variables:K.record(K.string(),Ae),output:Ae.nullable(),screen:u0.nullable(),paywall:K.strictObject({receiptId:K.uuid(),resolution:K.union([ao,kr]),quote:oi.nullable(),operation:ai.nullable(),purchaseRequestId:K.uuid().nullable(),selectionGeneration:K.number().int().nonnegative().optional(),canReselect:K.boolean().optional()}).nullable(),instruction:s0.nullable(),pendingRequest:K.strictObject({requestId:K.uuid(),authenticationRequired:K.boolean()}).nullable(),runExpiresAt:K.iso.datetime({offset:!0}),credentialExpiresAt:K.iso.datetime({offset:!0}).nullable()}),lo=K.strictObject({scope:Ue,run:pu,settlement:K.strictObject({requestId:K.uuid(),state:K.enum(["pending","unknown","settled"]),operationId:K.uuid().nullable(),receiptId:K.uuid().nullable().optional()}).optional(),purchase:K.strictObject({receiptId:K.uuid(),quote:oi.nullable(),operation:ai.nullable(),canReselect:K.boolean().optional()}).optional(),review:K.strictObject({activeOperationId:K.uuid().nullable(),pages:K.array(K.strictObject({receiptId:K.uuid(),nodeId:ir,visit:K.number().int().nonnegative()})).max(100),page:K.strictObject({receiptId:K.uuid(),nodeId:ir,visit:K.number().int().nonnegative(),document:nn,answers:tr,inputs:wa,values:K.record(K.string(),Ae).optional()}).nullable(),coupons:K.array(K.strictObject({grantId:K.uuid(),status:K.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:K.string().nullable()})).max(100),purchases:K.array(K.strictObject({receiptId:K.uuid(),operationId:K.uuid(),status:K.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:K.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:K.uuid().optional()}),gg=lo.extend({run:pu.extend({paywall:pu.shape.paywall.unwrap().extend({resolution:kr}).nullable()})});var hg="X-Indiana-Server-Key";import{z as ke}from"zod";var yi=ke.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),yg=ke.strictObject({entry:yi,nodes:ke.array(ke.strictObject({id:yi,type:ke.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:ke.record(ke.string(),yi),writes:ke.record(ft,ft),resources:ke.strictObject({screenId:yi.optional(),paywallVersionId:ke.uuid().optional(),couponId:ke.uuid().optional(),couponIds:ke.array(ke.uuid()).max(20).optional(),experimentId:ke.uuid().optional(),featureKey:ke.string().optional(),offeringVersionId:ke.uuid().optional()})})).min(1).max(500)}),Ag={scope:Ue,funnelId:ke.uuid(),versionId:ke.uuid(),evaluationRevision:ke.number().int().nonnegative(),expiresAt:ke.iso.datetime({offset:!0}).nullable(),topology:yg},za=ke.discriminatedUnion("evaluationMode",[ke.strictObject({...Ag,evaluationMode:ke.literal("local"),growth:ln,conditions:ke.record(yi,ke.array(ke.strictObject({condition:Ht,port:ke.string()})))}),ke.strictObject({...Ag,evaluationMode:ke.literal("remote")})]),l0=za.options[0].extend({evaluation:ke.strictObject({maxTransitions:ke.number().int().min(1).max(1e4),variables:ke.record(ft,ei),outputSchema:Xr,terminals:ke.record(yi,ke.strictObject({outcome:ke.enum(["completed","closed","ineligible","failed"]),output:no.nullable()}))})});function d0(e){return yg.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=ke.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 mu(e){let t=gi.parse(e.document),n=e.evaluationMode==="local"?ln.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:d0(t)};return za.parse(e.evaluationMode==="remote"?r:{...r,growth:Va(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=mu(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=gi.parse(e.document);return l0.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 Xe}from"zod";var Sg=Xe.string().regex(/^[a-f0-9]{64}$/),p0=di.omit({variations:!0,active:!0}).extend({changeId:Sg,variations:Xe.array(Xe.strictObject({urlRedirect:Xe.string().max(2048)})).min(2).max(20)}),xg=Xe.strictObject({environmentId:Xe.uuid(),trackExposures:Xe.boolean(),generation:Sg,experiments:Xe.array(p0).max(100),savedGroups:Xi}),m0=Xe.strictObject({eventUuid:Xe.uuid(),timestamp:Xe.iso.datetime({offset:!0}).optional(),deviceId:Xe.string().min(1).max(128),sessionId:Xe.string().min(1).max(128).optional(),url:Xe.url().max(2048),pageTitle:Xe.string().max(512).optional(),experimentKey:Xe.string().min(1).max(255),variationKey:Xe.string().min(1).max(64)}),Sj=Xe.strictObject({events:Xe.array(m0).min(1).max(20)}),xj=Xe.strictObject({inserted:Xe.number().int().nonnegative(),duplicates:Xe.number().int().nonnegative(),skipped:Xe.number().int().nonnegative(),rejected:Xe.array(Xe.strictObject({index:Xe.number().int().nonnegative(),reason:Xe.string()}))});import{z as xt}from"zod";var f0=xt.strictObject({selector:xt.string().min(1).max(2048),action:xt.enum(["set","append","remove"]),attribute:xt.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:xt.string().max(5e4).optional(),parentSelector:xt.string().max(2048).optional(),insertBeforeSelector:xt.string().max(2048).optional()}),g0=xt.strictObject({variation:xt.string().min(1).max(128),description:xt.string().max(2e3).default(""),css:xt.string().max(1e5).default(""),js:xt.string().max(1e5).default(""),domMutations:xt.array(f0).max(200).default([]),iam:Dm.optional(),renderGuard:xa.optional()}),fu=g0.omit({variation:!0,description:!0,iam:!0}),h0=di.omit({variations:!0,active:!0}).extend({changeId:xt.string().regex(/^[a-f0-9]{64}$/),variations:xt.tuple([fu,fu]).rest(fu).refine(e=>e.length<=20)}),Ig=xt.strictObject({trackExposures:xt.boolean(),environmentId:xt.uuid(),generation:xt.string().regex(/^[a-f0-9]{64}$/),experiments:xt.array(h0).max(100),savedGroups:Xi});import{z as it}from"zod";var hu=32,A0=522240;function Au(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 y0=it.strictObject({nodeId:it.string().min(1).max(64),visit:it.number().int().nonnegative(),revision:it.number().int().nonnegative()}),gu=it.record(it.string(),Ae),b0=it.strictObject({id:it.uuid(),nodeId:it.string().min(1).max(64),visit:it.number().int().nonnegative(),input:it.strictObject({schemaVersion:ro.shape.schemaVersion,kind:ro.shape.kind,selector:ro.shape.selector,contract:ro.shape.contract}),context:gu,removed:it.array(it.string()).max(100),attributes:gu,removedAttributes:it.array(it.string()).max(100),result:af,offeringVersionId:it.uuid().nullable(),events:it.strictObject({entered:it.string().regex(/^[1-9][0-9]{0,18}$/),decision:it.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),jj=it.strictObject({schemaVersion:it.literal(1),mode:it.enum(["local","remote"]),versionId:it.uuid(),generation:it.number().int().positive(),base:y0,context:gu,steps:it.array(b0).min(1).max(hu)}).refine(e=>rn(e)<=A0,"Segment exceeds its byte budget");var yu=class extends Error{constructor(n,r){super(r);De(this,"code",n);this.name="FunnelLocalCalculationError"}},vg=(e,t)=>new yu(e,t),S0=e=>({experiments:e.experiments,features:e.features});function x0(e,t=vg){let n=new Map(e.topology.nodes.map(o=>[o.id,o])),r=Kr(e.growth.savedGroups),i=S0(e.growth);function a(o,s){if(!Object.hasOwn(e.growth.features,o))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Dn(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 S=e.conditions[c.id];if(!S)throw t("INVALID_RESPONSE","Local condition rules are unavailable");u=du({id:c.id,name:c.id,type:"condition",cases:S.map(y=>({condition:y.condition,target:c.outputs[y.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 y=du({id:c.id,name:c.id,type:"split",experimentId:c.resources.experimentId,routes:c.outputs,notParticipating:c.outputs.notParticipating},s,i.experiments);l=y.value,u=y.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 I0(e,t){let n=za.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=x0(n,t);return(o,s)=>(i(),v0(a,o,s))}function v0(e,t,n){let r=ht.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 w0(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(Ae.parse({key:s.key,variationId:c.variationId,keyUsed:c.key,hashAttribute:c.hashAttribute,hashValue:c.hashValue}))},onFeatureUsage(s,c){a.push(Ae.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 wg(e,t,n,r=vg){let i=n,a=new Map(t.graph.nodes.map(g=>[g.id,g])),o=structuredClone(n.variables),s=structuredClone(i.sticky),c=[],u=n.nodeId,l=n.visit,m=!1,S,y=g=>(S??(S=I0(e,r)),w0(S,g,{attributes:Rc({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:o,savedGroups:{}}),sticky:s}));for(let g=0;g<hu;g++){let f=a.get(u);if(!f||!Au(f))break;if(l>=t.execution.maxTransitions&&(l>t.execution.maxTransitions||f.type!=="end"&&f.type!=="output")){if(!c.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let I,A;if(["condition","feature","split"].includes(f.type)||f.type==="offering"&&f.configuration.source==="feature")I=y(f.id),f.type==="offering"&&(I.value={type:"offering_version",id:String(I.value)}),f.type==="condition"?A=I.port==="default"?f.default:f.cases[Number(I.port.slice(5))]?.target:f.type==="split"?A=I.port==="notParticipating"?f.notParticipating:f.routes[I.port]:(f.type==="feature"||f.type==="offering")&&(A=f.next);else if(I={port:"next",sticky:[],exposures:[],features:[]},(f.type==="entry"||f.type==="coupon"||f.type==="coupons")&&(A=f.next),f.type==="offering"&&f.configuration.source==="fixed"&&(I.value={type:"offering_version",id:f.configuration.versionId},A=f.next),f.type==="end"||f.type==="output"){let w=f.type==="end"?f.output:f.value;if(I=w?.type==="feature"?y(f.id):{...I,port:"value",value:w?.type==="literal"?w.value:w?.type==="variable"?rc({source:"variable",key:w.key,...w.path?{path:w.path}:{}},{declarations:t.variables,answers:n.answers,results:o,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},w&&(I.value===void 0||!un(t.outputSchema,I.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let P=[...c,{nodeId:u,result:I}];if(rn({steps:P})>6e4){if(!c.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(c.push({nodeId:u,result:I}),f.type==="feature"||f.type==="offering"||f.type==="coupon"||f.type==="coupons"){let w=f.type==="coupons"?f.couponIds.map(N=>({type:"reward",id:N})):f.type==="coupon"?{type:"reward",id:f.couponId}:I.value;if(w===void 0)throw r("INVALID_RESPONSE","Node output is missing");let k=ti(f,{value:w});vp(t.variables,f,k),Object.assign(o,k)}for(let w of I.sticky)s[`${w.next.attributeName}||${w.next.attributeValue}`]=structuredClone(w.next);if(f.type==="end"||f.type==="output"){m=!0;break}if(!A)throw r("INVALID_RESPONSE","Local pure exit is unavailable");u=A,l++}let p=a.get(u);return{steps:c,...!m&&p&&!Au(p)?{boundary:{nodeId:u,visit:l}}:{}}}import{z as be}from"zod";var $a=be.string().regex(/^[a-f0-9]{64}$/),O0=be.strictObject({release:$a,render:xa,button:be.strictObject({selector:be.string().min(1).max(512),elementKey:be.string().min(1).max(256),tag:be.enum(["button","a","input"])}).nullable()}),Zj=be.strictObject({scope:Ue.extend({environmentId:be.uuid()}),release:$a,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:O0})).max(4e3)}),Wj=be.strictObject({operation:be.literal("entry_start"),funnelId:be.uuid(),versionId:be.uuid(),entryId:be.uuid(),release:$a,requestId:be.uuid(),locale:be.string().min(1).max(35).default("en")}),Yj=be.strictObject({scope:Ue,suppressed:be.literal(!0),reason:be.enum(["frequency","in_progress"]),retryAt:be.iso.datetime({offset:!0}).nullable()}),Xj=be.strictObject({experimentId:be.uuid(),splitNodeId:be.string().min(1).max(128)}),_0=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)}),Og=be.strictObject({operation:be.literal("page_experiments"),release:$a,usedReceiptIds:be.array(be.uuid()).max(20).default([]),customerToken:be.string().regex(Ft).optional()}),_g=be.strictObject({scope:Ue,runId:be.uuid(),assignments:be.array(_0.extend({receiptId:be.uuid()})).max(100),payload:Ig});var b=class extends Error{constructor(n,r,i,a,o){super(r);De(this,"code",n);De(this,"status",i);De(this,"requestId",a);De(this,"retryable");De(this,"recovery");De(this,"retryAfterSeconds");De(this,"reason");this.name="IndianaError",this.reason=o?.reason;let s=Io(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 po=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new b("INVALID_STATE","Installation sequence exhausted");return e+1},C0=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 Ln(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 Cg(e,t,n){let r=null,i=0,a=0,o=0,s=Promise.resolve();if(e&&(!n||Ue.parse(e.scope).projectId!==n.projectId||e.scope.environment!==n.environment))throw new b("SCOPE_MISMATCH","Push installation belongs to another scope");let c=()=>{if(!e)throw new b("NOT_CONFIGURED","Configure this client's native Push host first");return e},u=A=>{if(A!==i)throw new b("IDENTITY_CHANGED","Identity changed during Push operation")};async function l(A){let P=c();if(!P.sha256&&!globalThis.crypto?.subtle)throw new b("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let w=P.sha256?await P.sha256(Uint8Array.from(A,k=>k.charCodeAt(0))):await C0(A);if(!/^[a-f0-9]{64}$/.test(w))throw new b("INVALID_STATE","Push credential digest is invalid");return w}function m(A){let P=gr.parse(A);if(P.installationId.toLowerCase()!==c().installationId.toLowerCase())throw new b("INVALID_RESPONSE","Push response belongs to another installation");return P}async function S(A,P){let w=c(),k={installationId:w.installationId,publicKey:w.publicKey,issuedAt:new Date().toISOString(),...P},N=await w.sign(Yu(A,w.scope,k));return{...k,signature:N}}let y=(A,P,w)=>t.requestWithCredential?t.requestWithCredential(A,P,w):t.request(A,P);async function p(){let A=c(),P=i,w=r?await(t.session?.access()??r):null,k=Ln(A,Ie=>Ie),N;if(k.detachSeq!==null){let Ie=k.detachSeq,Fe=Ju.parse(await S("detach",{sequence:Ie,platform:A.platform}));try{let Ee=await t.request("push/installations/detach",{...A.scope,...Fe},"POST",{installationDetach:!0});if(!Ee||typeof Ee!="object"||!("installation"in Ee))throw new b("INVALID_RESPONSE","Push detach acknowledgement is invalid");let zt=m(Ee.installation);if(zt.bound||zt.identitySeq!==Ie)throw new b("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(Ee){if(Ee instanceof b&&Ee.status===404)N=Ee;else if(!(Ee instanceof b)||Ee.status!==412)throw Ee}N||Ln(A,Ee=>({...Ee,detachSeq:Ee.detachSeq===Ie?null:Ee.detachSeq}))}if(u(P),!w){if(N)throw N;return null}let B=O.bindPushInstallation,me=B.request.parse(await S("bind",{sequence:o,platform:A.platform,credentialDigest:await l(w)}));u(P);let xe=B.response.parse(await y(B.path,me,w));u(P);let Ce=m(xe.installation);if(!Ce.bound||Ce.identitySeq!==o)throw new b("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return N&&k.detachSeq!==null&&o>k.detachSeq&&Ln(A,Ie=>({...Ie,detachSeq:Ie.detachSeq===k.detachSeq?null:Ie.detachSeq})),Ce}async function g(){c();let A=i,P=r?await(t.session?.access()??r):null;if(!P)throw new b("NOT_IDENTIFIED","Identify before reading this installation");let w=O.readPushInstallation,k=w.request.parse(await S("read",{credentialDigest:await l(P)}));u(A);let N=w.response.parse(await y(w.path,k,P));return u(A),m(N.installation)}function f(A=p){let P=s.catch(()=>{}).then(A);return s=P,P.catch(w=>{try{e?.onError?.(w instanceof Error?w:new Error("Push synchronization failed"))}catch{}}),P}async function I(A,P,w){let k=c(),N=P.identity,B=P.observation,me=r?await(t.session?.access()??r):null;if(u(N),B!==a)throw new b("INVALID_STATE","Push observation changed during recovery");if(!me)throw new b("NOT_IDENTIFIED","Identify before recovering a Push address");if(!A.connectionId||!A.kind||!A.token||!["granted","provisional"].includes(A.permission))throw new b("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await f(async()=>{if(u(N),await p(),u(N),B!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let xe=Ln(k,zt=>w?zt:{...zt,addressSeq:po(zt.addressSeq)}),Ie=await S(w?"recovery_confirm":"recovery_request",{...A,sequence:xe.addressSeq,credentialDigest:await l(me),...w?{challenge:w}:{}}),Fe=w?Wu.parse(Ie):Zu.parse(Ie);if(u(N),B!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let Ee=await y(`push/installations/recovery/${w?"confirm":"request"}`,Fe,me);if(u(N),B!==a||Ln(k,zt=>zt).addressSeq!==xe.addressSeq)throw new b("INVALID_STATE","Push observation changed during recovery");if(w){let zt=O.updatePushAddress.response.parse(Ee),We=m(zt.installation);if(!We.bound||We.identitySeq!==o||We.addressSeq!==xe.addressSeq||We.connectionId!==A.connectionId||We.addressStatus!=="active")throw new b("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return We}if(!Ee||typeof Ee!="object"||!("recovery"in Ee))throw new b("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return ss.parse(Ee.recovery)})}return{recoveryObserver(){c();let A={identity:i,observation:++a};return{async request(P){return ss.parse(await I(P,A))},async confirm(P,w){return gr.parse(await I(w,A,P))}}},identify(A){if(!e)return;o=Ln(e,w=>({...w,identitySeq:po(w.identitySeq)})).identitySeq,r=A,i++,a++},reset(){if(e)try{Ln(e,A=>{let P=po(A.identitySeq);return{...A,identitySeq:P,detachSeq:P}})}finally{r=null,i++,a++}},start(){e&&f()},async sync(){return await f()},read:g,async recover(){let A=c(),P=i,w=o;return a++,await f(async()=>{u(P);let k=await g();return u(P),o=Ln(A,B=>{if(B.identitySeq!==w)throw new b("IDENTITY_CHANGED","A newer installation intent exists");return{...B,identitySeq:po(Math.max(B.identitySeq,k.identitySeq)),addressSeq:Math.max(B.addressSeq,k.addressSeq)}}).identitySeq,await p()})},tokenObserver(){c();let A=++a,P=i;return async w=>{if(A!==a||P!==i)return null;let k=c(),N=r?await(t.session?.access()??r):null;if(!N)throw new b("NOT_IDENTIFIED","Identify before registering a Push token");if(await f(),u(P),A!==a)return null;let B=Ln(k,Ie=>({...Ie,addressSeq:po(Ie.addressSeq)})),me=O.updatePushAddress,xe=me.request.parse(await S("address",{...w,sequence:B.addressSeq,credentialDigest:await l(N)}));if(u(P),A!==a)return null;let Ce=me.response.parse(await y(me.path,xe,N));return u(P),m(Ce.installation)}}}}function Pg(e,t){return{messaging:{async preference(n){let r=O.readMessagingPreference;return r.response.parse(await e(r.path,r.request.parse({channel:n}))).preference},async setPreference(n){let r=O.setMessagingPreference;return r.response.parse(await e(r.path,r.request.parse(n))).preference}},push:{sync:t.sync,read:t.read,recover:t.recover,tokenObserver:t.tokenObserver,recoveryObserver:t.recoveryObserver,async preference(){let n=O.readMessagingPreference;return n.response.parse(await e(n.path,{channel:"push"})).preference},async setPreference(n){let r=O.setMessagingPreference;return r.response.parse(await e(r.path,r.request.parse({...n,channel:"push"}))).preference}}}}var Eg={name:"@tinkerlandai/longplay-sdk",version:"0.10.6",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",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 Ge(e){return typeof e=="string"?e:String(e)}var E0=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function R0(e){return e.replace(E0,"$1\uFFFD")}function Iu(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 qg(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 Rg(e){let t;if(Array.isArray(e)){let n=e.map(Ge);if(n.length===2)return n}else if((t=qg(e))!=null){let n=Iu(t.next()),r=Iu(t.next());if(!n.done&&!r.done)return[Ge(n.value),Ge(r.value)]}throw new TypeError("Each query pair must be an iterable [name, value] tuple")}var kg="0123456789ABCDEF",k0=/(?:%[0-9A-Fa-f]{2})+/g;function Pn(e){return`%${kg[e>>4&15]}${kg[15&e]}`}function Vg(e,t,n=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?n&&e===32?"+":t(e)?Pn(e):String.fromCharCode(e):e<=2047?Pn(192|e>>6)+Pn(128|63&e):e<=65535?Pn(224|e>>12)+Pn(128|e>>6&63)+Pn(128|63&e):Pn(240|e>>18)+Pn(128|e>>12&63)+Pn(128|e>>6&63)+Pn(128|63&e)}function vu(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(k0,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function go(e){return e<=31||e>126}function j0(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return go(e)}}function ku(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return go(e)}}function T0(e){return ku(e)||e===39}function Ou(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return ku(e)}}function Ja(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 Ou(e)}}function jg(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 Ja(n)}})(e)}}function Bg(e,t){return Vg(e=e||0,t)}function En(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+=Vg(o,t,n)}return i}function ju(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 _u(e){let t="";for(let n=0;n<e.length;n++){let r=En(e[n][0],jg,!0),i=En(e[n][1],jg,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var N0=[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],D0=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],F0=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],M0=[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 q0(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[V0,B0,U0,Tg]=[[[],"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 L0(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 Ug(e,t){for(let n=0;n<e.length;n+=2)if(t>=e[n]&&t<=e[n+1])return!0;return!1}function mo(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 z0(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&&Ug(M0,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&mo(Tg,t[i]);)i--;let a=n+1;for(;a<t.length&&mo(Tg,t[a]);)a++;if(!(i>=0&&a<t.length&&mo(B0,t[i])&&mo(U0,t[a])))return!1}return!0}var $0=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,G0=/\p{Script=Latin}/u;function K0(e){return!$0.test(e)||!G0.test(e)}var or=36,Ka=1,Cu=26,H0=38,Q0=700,J0=72,Z0=128,W0=2147483647;function Ng(e){return String.fromCharCode(e+22+75*+(e<26))}function Y0(e,t,n){let r=0;for(e=n?Math.floor(e/Q0):e>>1,e+=Math.floor(e/t);e>(or-Ka)*Cu>>1;r+=or)e=Math.floor(e/(or-Ka));return Math.floor(r+(or-Ka+1)*e/(e+H0))}function X0(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=Z0,o=0,s=J0;for(;r<t.length;){let c=W0;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 S=or;;S+=or){let y=S<=s?Ka:S>=s+Cu?Cu:S-s;if(m<y)break;n+=Ng(y+(m-y)%(or-y)),m=Math.floor((m-y)/(or-y))}n+=Ng(m),s=Y0(o,r+1,r===i),o=0,r++}}o++,a++}return n}function bu(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=vu(e.charCodeAt(r));if(i>=t||i<0)return-1;n=n*t+i}return n}function Dg(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function Lg(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function zg(e){return e.length===2&&Lg(e.codePointAt(0),e.codePointAt(1))}function Fg(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function ct(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function $g(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function Pu(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=vu(c[s]))>=0;)l=(l<<4)+u,s++,m++;if(c[s]===46){if(m===0||o>6)return null;s-=m;let S=0;for(;c[s]!==void 0;){let y=0;if(S>0)if(c[s]===46&&S<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(y=10*y+vu(c[s]),y>255)return null;s++}i[o]=256*i[o]+y,S++,S%2==0&&o++}if(S!==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 Fg(r)?null:En(r,go)})(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)&&!Ug(N0,m)||mo(V0,m))return!0}return!1})(i))return null;let s=(i=(function(u){let l="";for(let m of u){let S=m.codePointAt(0);if(S!==8204&&S!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(m))continue;let y=L0(m,S);if(y){l+=y;continue}let p=D0.indexOf(S);l+=p<0?m:F0[p]}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(q0(u)||l&&(/^\p{Mark}/u.test(u)||!z0(u)||!K0(u)||u.startsWith("xn--")))return null;l&&(s[c]=`xn--${X0(u)}`)}return(i=s.join("."))!==""?i:null})(e.indexOf("%")===-1?e:wu(e));return n===null||Fg(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(bu(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=bu(a[u]);if(l<0||l>255)return null;s+=l*(1<<8*(3-u))}let c=bu(a[o-1]);return c<0||c>=256**(5-o)?null:(s+=c,s)})(n):n}}function Eu(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 S=0;S<s.length;++S)s[S]!==0?(m>l&&(c=u,l=m),u=-1,m=0):(u===-1&&(u=S),++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 Gg(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 Kg(e){return e.username!==""||e.password!==""}function Su(e){return e.host===null||e.host===""||e.scheme==="file"}var C=0,q="",Se="",Ve=null,V,Ha=!1,Qa=!1,Fr=!1,ut;function cn(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),C=0,q=e,Se="",Ve=n||null,V=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},Ha=!1,Qa=!1,Fr=!1,ut=r||0;let i=eI;switch(r){case 3:case 4:i=Za;break;case 5:i=Nu;break;case 6:i=Mr;break;case 7:i=ar;break;case 8:i=Rn}return i(G(e,C))!==1?V:null}function W(e,t){return C+=C===e?vn(t):1,C<=q.length}function G(e,t){return t<e.length?e.codePointAt(t):void 0}function vn(e){return e!=null&&e>65535?2:1}function Hg(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var eI=e=>{let t=C;if(e!=null&&(e>=65&&e<=90||e>=97&&e<=122)){let n=C+1;for(e=q.charCodeAt(n);e===43||e===45||e===46||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57;)n++,e=q.charCodeAt(n);return Se=q.slice(C,n).toLowerCase(),C=n,tI(n<q.length?e:void 0)}else return ut?1:(--C,W(t,e)?Qg(G(q,C)):0)},tI=e=>{let t=C;if(e===58){if(ut){if(ct(V.scheme)!==ct(Se))return 0;if((Kg(V)||V.port!==null)&&Se==="file")return 0;if(V.scheme==="file"&&V.host==="")return 0}return V.scheme=Se,ut?(V.port===$g(V.scheme)&&(V.port=null),0):(Se="",V.scheme==="file"?W(t,e)?Du(G(q,C)):0:ct(V.scheme)&&Ve!==null&&Ve.scheme===V.scheme?W(t,e)?nI(G(q,C)):0:ct(V.scheme)?W(t,e)?iI(G(q,C)):0:G(q,C+1)===47?(C++,W(t,e)?rI(G(q,C)):0):(V.path=[""],V.opaquePath=!0,W(t,e)?Zg(G(q,C)):0))}else return ut?1:(Se="",C=-1,W(t,e)?Qg(G(q,C)):0)},Qg=e=>{let t=C;return Ve===null||Ve.opaquePath&&e!==35?1:Ve.opaquePath&&e===35?(V.scheme=Ve.scheme,V.path=Ve.path.slice(),V.opaquePath=Ve.opaquePath,V.query=Ve.query,V.fragment="",W(t,e)?Rn(G(q,C)):0):Ve.scheme==="file"?(C--,W(t,e)?Du(G(q,C)):0):(C--,W(t,e)?Tu(G(q,C)):0)},nI=e=>{let t=C;return e===47&&G(q,C+1)===47?(++C,W(t,e)?Ya(G(q,C)):0):(C--,W(t,e)?Tu(G(q,C)):0)},rI=e=>{let t=C;return e===47?W(t,e)?bi(G(q,C)):0:(C--,W(t,e)?wn(G(q,C)):0)},Tu=e=>{let t=C;return V.scheme=Ve.scheme,e===47||ct(V.scheme)&&e===92?W(t,e)?Mg(G(q,C)):0:(V.username=Ve.username,V.password=Ve.password,V.host=Ve.host,V.port=Ve.port,V.path=Ve.path.slice(),V.query=Ve.query,e===63?(V.query="",W(t,e)?ar(G(q,C)):0):e===35?(V.fragment="",W(t,e)?Rn(G(q,C)):0):e!=null?(V.query=null,V.path.pop(),C--,W(t,e)?wn(G(q,C)):0):W(t,e)?Tu(G(q,C)):0)},Mg=e=>{let t=C;return ct(V.scheme)&&(e===47||e===92)?W(t,e)?Ya(G(q,C)):0:e===47?W(t,e)?bi(G(q,C)):0:(V.username=Ve.username,V.password=Ve.password,V.host=Ve.host,V.port=Ve.port,C--,W(t,e)?wn(G(q,C)):0)},iI=e=>{let t=C;return e===47&&G(q,C+1)===47?C++:C--,W(t,e)?Ya(G(q,C)):0},Ya=e=>{let t=C;return e!==47&&e!==92?(C--,W(t,e)?bi(G(q,C)):0):W(t,e)?Ya(G(q,C)):0},bi=e=>{let t=C;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!ct(V.scheme))){let n=C+vn(e);for(;n<q.length;){let r=G(q,n);if(r==null||r===64||r===35||r===47||r===63||r===92&&ct(V.scheme))break;n+=vn(r)}return Se+=q.slice(C,n),C=n-1,W(t,e)?bi(G(q,C)):0}if(e===64){Ha&&(Se=`%40${Se}`),Ha=!0;for(let n=0;n<Se.length;n++){let r=Se.codePointAt(n);if(r===58&&!Qa){Qa=!0;continue}let i=Bg(r,Ja);Qa?V.password+=i:V.username+=i,r!=null&&r>65535&&n++}return Se="",W(t,e)?bi(G(q,C)):0}else return e==null||e===35||e===47||e===63||e===92&&ct(V.scheme)?Ha&&Se===""?1:(C-=Se.length+1,Se="",W(t,e)?Za(G(q,C)):0):(Se+=Hg(e),W(t,e)?bi(G(q,C)):0)},Za=e=>{let t=C;if(ut&&V.scheme==="file")return C--,W(t,e)?Fu(G(q,C)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!ct(V.scheme))){let n=C+vn(e);for(e===91?Fr=!0:e===93&&(Fr=!1);n<q.length;){let r=G(q,n);if(r==null||!Fr&&r===58||r===35||r===47||r===63||r===92&&ct(V.scheme))break;r===91?Fr=!0:r===93&&(Fr=!1),n+=vn(r)}return Se+=q.slice(C,n),C=n-1,W(t,e)?Za(G(q,C)):0}else if(e===58&&!Fr){if(Se===""||ut===4)return 1;let n=Pu(Se,!ct(V.scheme));return n===null?1:(V.host=Eu(n),Se="",W(t,e)?Nu(G(q,C)):0)}else if(e==null||e===35||e===47||e===63||e===92&&ct(V.scheme)){if(C--,ct(V.scheme)&&Se==="")return 1;if(ut&&Se===""&&(Kg(V)||V.port!==null))return 1;let n=Pu(Se,!ct(V.scheme));return n===null?1:(V.host=Eu(n),Se="",ut?0:W(t,e)?Mr(G(q,C)):0)}else return Se+=Hg(e),W(t,e)?Za(G(q,C)):0},Nu=e=>{let t=C;if(e!=null&&e>=48&&e<=57){let n=C+1;for(;n<q.length;){let r=q.charCodeAt(n);if(r<48||r>57)break;n++}return Se+=q.slice(C,n),C=n-1,W(t,e)?Nu(G(q,C)):0}else if(ut||e==null||e===35||e===47||e===63||e===92&&ct(V.scheme)){if(Se!==""){let n=parseInt(Se,10);if(n>65535)return 1;if(V.port=n===$g(V.scheme)?null:n,Se="",ut)return 0}return ut?1:(C--,W(t,e)?Mr(G(q,C)):0)}else return 1};function Jg(e,t){let n=e.length-t;if(n<2)return!1;if(Lg(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 Du=e=>{let t=C;return V.scheme="file",V.host="",e===47||e===92?W(t,e)?oI(G(q,C)):0:Ve?.scheme==="file"?(V.host=Ve.host,V.path=Ve.path.slice(),V.opaquePath=Ve.opaquePath,V.query=Ve.query,e===63?(V.query="",W(t,e)?ar(G(q,C)):0):e===35?(V.fragment="",W(t,e)?Rn(G(q,C)):0):e!=null?(V.query=null,Jg(q,C)?V.path=[]:Gg(V),C--,W(t,e)?wn(G(q,C)):0):W(t,e)?Du(G(q,C)):0):(C--,W(t,e)?wn(G(q,C)):0)},oI=e=>{let t=C;return e===47||e===92?W(t,e)?Fu(G(q,C)):0:(Ve!==null&&Ve.scheme==="file"&&(!Jg(q,C)&&(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})(Ve.path[0])&&V.path.push(Ve.path[0]),V.host=Ve.host),C--,W(t,e)?wn(G(q,C)):0)},Fu=e=>{let t=C;if(e!=null&&e!==47&&e!==92&&e!==63&&e!==35){let n=C+vn(e);for(;n<q.length;){let r=G(q,n);if(r==null||r===47||r===92||r===63||r===35)break;n+=vn(r)}return Se+=q.slice(C,n),C=n-1,W(t,e)?Fu(G(q,C)):0}else if(e==null||e===47||e===92||e===63||e===35){if(C--,!ut&&zg(Se))return W(t,e)?wn(G(q,C)):0;if(Se==="")return V.host="",ut?0:W(t,e)?Mr(G(q,C)):0;{let n=Pu(Se,!ct(V.scheme));return n===null?1:(n==="localhost"&&(n=""),V.host=Eu(n),Se="",ut?0:W(t,e)?Mr(G(q,C)):0)}}return 1},Mr=e=>{let t=C;return ct(V.scheme)?(e!==92&&e!==47&&C--,W(t,e)?wn(G(q,C)):0):!ut&&e===63?(V.query="",W(t,e)?ar(G(q,C)):0):!ut&&e===35?(V.fragment="",W(t,e)?Rn(G(q,C)):0):e!=null?(e!==47&&C--,W(t,e)?wn(G(q,C)):0):(ut&&V.host===null&&V.path.push(""),W(t,e)?Mr(G(q,C)):0)},wn=e=>{let t=C;if(e!=null&&e!==47&&(!ct(V.scheme)||e!==92)&&(ut||e!==63&&e!==35)){let n=C+vn(e);for(;n<q.length;){let r=G(q,n);if(r==null||r===47||ct(V.scheme)&&r===92||!ut&&(r===63||r===35))break;n+=vn(r)}Se+=En(q.slice(C,n),Ou),C=n,e=G(q,n)}if(e==null||e===47||ct(V.scheme)&&e===92||!ut&&(e===63||e===35)){let n=ct(V.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}})(Se)?(Gg(V),e!==47&&!n&&V.path.push("")):Dg(Se)&&e!==47&&!n?V.path.push(""):Dg(Se)||(V.scheme==="file"&&V.path.length===0&&zg(Se)&&(Se=`${Se[0]}:`),V.path.push(Se)),Se="",e===63?(V.query="",W(t,e)?ar(G(q,C)):0):e===35?(V.fragment="",W(t,e)?Rn(G(q,C)):0):W(t,e)?wn(G(q,C)):0}else return Se+=Bg(e,Ou),W(t,e)?wn(G(q,C)):0},Zg=e=>{let t=C;if(e===63)return V.query="",W(t,e)?ar(G(q,C)):0;if(e===35)return V.fragment="",W(t,e)?Rn(G(q,C)):0;if(e!=null){let n=C+vn(e);for(;n<q.length;){let i=G(q,n);if(i===63||i===35)break;n+=vn(i)}let r=q.slice(C,n);if(n<q.length&&r.charCodeAt(r.length-1)===32?V.path[0]+=En(r.slice(0,-1),go)+"%20":V.path[0]+=En(r,go),C=n,(e=G(q,n))===63)return V.query="",W(t,e)?ar(G(q,C)):0;if(e===35)return V.fragment="",W(t,e)?Rn(G(q,C)):0}return W(t,e)?Zg(G(q,C)):0},ar=e=>{let t=C,n=C;if(e!=null){if(ut)n=q.length;else{let i=q.indexOf("#",C);n=i===-1?q.length:i}let r=ct(V.scheme)?T0:ku;V.query+=En(q.slice(C,n),r)}return C=n,G(q,n)===35&&!ut?(V.fragment="",W(t,e)?Rn(G(q,C)):0):W(t,e)?ar(G(q,C)):0},Rn=e=>{let t=C;return e!=null&&(V.fragment+=En(q.slice(C),j0),C=q.length),W(t,e)?Rn(G(q,C)):0};function Ru(e){if(e.opaquePath)return e.path[0];{let t="";for(let n of e.path)t+=`/${n}`;return t}}function Wg(e){switch(e.scheme){case"blob":{let t=cn(Ru(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":Wg(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 $e=Symbol("URLImpl"),mn=class e{constructor(t,n){if(t===void 0&&n===void 0)throw new TypeError('The "url" argument must be specified.');t=Ge(t),n!=null&&(n=Ge(n));let r=null;if(n!=null&&(r=cn(n,null,null,0),r==null))throw new TypeError(`Invalid base URL: ${n}`);let i=cn(t,null,r,0);if(i==null)throw new TypeError(`Invalid URL: ${t}`);this[$e]={url:i,query:null}}static createObjectURL(t){throw new TypeError("URL.createObjetURL is unsupported")}static revokeObjectURL(t){}static parse(t,n){t=Ge(t),n!==void 0&&(n=Ge(n));try{return new e(t,n)}catch{return null}}static canParse(t,n){t=Ge(t),n!==void 0&&(n=Ge(n));let r=null;return n!=null&&(r=cn(n,null,null,0),r==null)?!1:cn(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+=Ru(n),n.query!==null&&(r+=`?${n.query}`),n.fragment!==null&&(r+=`#${n.fragment}`),r})(this[$e].url)}set href(t){let n=cn(t=Ge(t),null,null,0);if(n==null)throw new TypeError(`Invalid URL: ${t}`);this[$e].url=n,this[$e].query&&xu(this[$e].query,n.query)}get origin(){return Wg(this[$e].url)}get protocol(){return`${this[$e].url.scheme}:`}set protocol(t){cn(`${t=Ge(t)}:`,this[$e].url,null,2)}get username(){return this[$e].url.username}set username(t){t=Ge(t),Su(this[$e].url)||(function(r,i){r.username=En(i,Ja)})(this[$e].url,t)}get password(){return this[$e].url.password}set password(t){t=Ge(t),Su(this[$e].url)||(function(r,i){r.password=En(i,Ja)})(this[$e].url,t)}get host(){let{url:t}=this[$e];return t.host==null?"":t.port==null?t.host:`${t.host}:${t.port}`}set host(t){t=Ge(t),this[$e].url.opaquePath||cn(t,this[$e].url,null,3)}get hostname(){let{url:t}=this[$e];return t.host!=null?t.host:""}set hostname(t){t=Ge(t),this[$e].url.opaquePath||cn(t,this[$e].url,null,4)}get port(){let{url:t}=this[$e];return t.port!=null?`${t.port}`:""}set port(t){t=Ge(t);let{url:n}=this[$e];Su(n)||(t?cn(t,n,null,5):n.port=null)}get pathname(){return Ru(this[$e].url)}set pathname(t){t=Ge(t);let{url:n}=this[$e];n.opaquePath||(n.path=[],cn(t,n,null,6))}get search(){let{url:t}=this[$e];return t.query?`?${t.query}`:""}set search(t){t=Ge(t);let{url:n,query:r}=this[$e];if(!t)n.query=null,r&&xu(r,null);else{let i=t[0]==="?"?t.substring(1):t;n.query="",cn(i,n,null,7),r&&xu(r,n.query)}}get searchParams(){let t=this[$e],n=t.query;return n==null&&(n=t.query=(function(i,a){let o=new Wa;return o[tt].url=i,o[tt].serialized=a==null,a&&(o[tt].list=ju(a)),o})(this,t.url.query)),n}get hash(){let{url:t}=this[$e];return t.fragment?`#${t.fragment}`:""}set hash(t){t=Ge(t);let{url:n}=this[$e];if(!t)n.fragment=null;else{let r=t[0]==="#"?t.substring(1):t;n.fragment="",cn(r,n,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(mn.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var tt=Symbol("URLSearchParamsImpl"),aI=Symbol.dispose||Symbol.for("dispose");function xu(e,t){t?e[tt].list=ju(t):e[tt].list.length=0,e[tt].serialized=t==null}function Ga(e){if(e.url){let t=_u(e.list);(function(r,i){r[$e].url.query=i})(e.url,t||null),e.serialized=!0}}var sI=typeof Iterator<"u"?Iterator:Object,fo=class extends sI{constructor(t,n){super(),this[tt]={ptr:t,map:n,index:0}}next(){let t=this[tt];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}[aI](){}},Wa=class{constructor(t){let n=this[tt]={list:[],url:null,serialized:!0},r;if(Array.isArray(t))for(let i=0;i<t.length;i++)n.list.push(Rg(t[i]));else if((r=qg(t))!=null){let i;for(;!(i=Iu(r.next())).done;)n.list.push(Rg(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=R0(o),c=Ge(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=Ge(t);i=i[0]==="?"?i.substring(1):i,n.list=ju(i)}}get size(){return this[tt].list.length}append(t,n){t=Ge(t),n=Ge(n),this[tt].list.push([t,n]);let r=this[tt];r.url&&r.serialized?(function(a,o){let s=a[$e].url;s.query=s.query?`${s.query}&${o}`:o})(r.url,_u([[t,n]])):Ga(r)}delete(t,n){t=Ge(t),n=n!=null?Ge(n):void 0;let{list:r}=this[tt],i=0;for(;i<r.length;)r[i][0]===t&&(n==null||r[i][1]===n)?r.splice(i,1):i++;Ga(this[tt])}get(t){t=Ge(t);let{list:n}=this[tt];for(let r=0;r<n.length;r++)if(n[r][0]===t)return n[r][1];return null}getAll(t){t=Ge(t);let n=[],{list:r}=this[tt];for(let i=0;i<r.length;i++)r[i][0]===t&&n.push(r[i][1]);return n}has(t,n){t=Ge(t),n=n!=null?Ge(n):void 0;let{list:r}=this[tt];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=Ge(t),n=Ge(n);let{list:r}=this[tt],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&&Ga(this[tt])}sort(){this[tt].list.sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0),Ga(this[tt])}forEach(t,n){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:r}=this[tt];for(let i=0;i<r.length;i++)t.call(n,r[i][1],r[i][0],this)}entries(){return new fo(this[tt],t=>t)}keys(){return new fo(this[tt],t=>t[0])}values(){return new fo(this[tt],t=>t[1])}toString(){return _u(this[tt].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(Wa.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var sr="https://api.longplayai.com";function Yg(e){let t,n,r=0,i,a=new Map,o=()=>{for(let m of[...a.keys()])try{m()}catch{}};function s(m,S){let y=++r;i=void 0,t=void 0,n=void 0;for(let p of[...a.values()])try{p?.()}catch{}y===r&&(t=m,n=S,o())}let c=()=>s();function u(m,S=!1){let y=Gn.safeParse(m);if(!y.success||S&&Date.parse(y.data.expiresAt)<=Date.now()||Date.parse(y.data.refreshExpiresAt)<=Date.now()||Date.parse(y.data.refreshExpiresAt)<Date.parse(y.data.expiresAt))throw new b("INVALID_RESPONSE","Invalid customer session credentials");return y.data}async function l(){if(i)return i;let m=t,S=r;if(!m||Date.parse(m.refreshExpiresAt)<=Date.now())throw m&&c(),new b("UNAUTHENTICATED","Customer authentication is required",401);let y=(async()=>{try{let p=await e(m.refreshToken);if(S!==r)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");let g=u(p,!0);if(g.customerId!==m.customerId||g.sessionId!==m.sessionId)throw new b("SCOPE_MISMATCH","Refresh changed the customer session");return t=g,n=g.accessToken,{...g}}catch(p){throw S!==r?new b("IDENTITY_CHANGED","Customer identity changed during refresh"):(p instanceof b&&p.status===401&&c(),p)}})();i=y;try{return await y}finally{i===y&&(i=void 0)}}return{identify(m){let S=typeof m=="string"?void 0:u(m),y=typeof m=="string"?m:S.accessToken;if(!y.trim()||/\s/.test(y)||y.length>4096)throw new b("INVALID_TOKEN","A server-issued token is required");s(S,y)},reset:c,subscribeIdentity(m,S){return a.set(m,S),()=>{a.delete(m)}},access(){if(t&&Date.parse(t.expiresAt)<=Date.now()+3e4)return l().then(()=>{if(!n)throw new b("NOT_IDENTIFIED","Customer authentication is required");return n});if(!n)throw new b("NOT_IDENTIFIED","Identify a customer session before making a request");return n},peek:()=>n,snapshot:()=>t&&{...t},refresh:l}}var Xg=Symbol("IndianaNoContent");function cr(e,t,n=mn){let r=e.configuration?.scope,i=e.scope??(r&&{projectId:r.projectId,environment:r.environment}),a=i?Ue.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=null,l=0,m=null,S=new Set,y=e.session??Yg(async A=>{let P=await I("customer-sessions/refresh",{},"POST",{},A);if(!P||typeof P!="object")throw new b("INVALID_RESPONSE","Invalid refresh response");let{requestId:w,scope:k,...N}=P;return N});function p(){l+=1,u=null,m=null;for(let A of S)A.abort();S.clear()}let g=y.subscribeIdentity(p);function f(){y.reset()}async function I(A,P={},w="POST",k={},N){let B=k.installationDetach===!0;if(B&&(A!=="push/installations/detach"||w!=="POST"))throw new b("INVALID_REQUEST","Installation authority only detaches this installation");if(!N&&!u&&!B)throw new b("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let me=l,xe=new AbortController;B||S.add(xe);let Ce=()=>!B&&me!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new b("TIMEOUT","Longplay request timed out"),Ie,Fe=new Promise((We,kt)=>{Ie=()=>kt(Ce()),xe.signal.addEventListener("abort",Ie,{once:!0})}),Ee=setTimeout(()=>xe.abort(),c),zt=async()=>{let We=await s(`${o.href.replace(/\/$/,"")}/api/v1/${A}`,{method:w,headers:{"Content-Type":"application/json",...B?{}:{Authorization:`Bearer ${N??u}`},[ps]:ms.current,[rl]:Eg.version,...a?{"X-Indiana-Project":a.projectId,"X-Indiana-Environment":a.environment}:{}},body:w==="POST"?JSON.stringify(P):void 0,signal:xe.signal,credentials:"omit",cache:"no-store",redirect:"error",...k.keepalive?{keepalive:!0}:{}});if(xe.signal.aborted)throw Ce();let kt;try{kt=We.status===204?Xg:await We.json()}catch{throw xe.signal.aborted?Ce():new b(We.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",We.status,We.headers.get("X-Request-Id")??void 0)}if(xe.signal.aborted)throw Ce();if(!B&&me!==l)throw new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!We.ok){let at=ds.safeParse(kt),$t=at.success&&(!Tn.safeParse(at.data.error.code).success||tl(at.data.error.code,We.status)),dr=$t?at.data.error.code:"HTTP_ERROR",pr=Io(dr,We.status,{retryAfter:We.headers.get("Retry-After"),recovery:$t?at.data.error.recovery:void 0,reason:$t?at.data.error.reason:void 0});throw new b(dr,$t?at.data.error.message:"Longplay request failed",We.status,We.headers.get("X-Request-Id")??(at.success?at.data.requestId:void 0),{...pr,...at.success&&at.data.error.retryable===!1?{retryable:!1}:{},...pr.retryAfterSeconds===void 0&&at.success&&at.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:at.data.error.retryAfterSeconds}:{}})}if(We.headers.get(ps)!==ms.current)throw new b("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&kt!==Xg){let at=kt&&typeof kt=="object"&&"scope"in kt?kt:kt&&typeof kt=="object"&&"configuration"in kt?kt.configuration:null;if(!at||typeof at!="object"||!("scope"in at))throw new b("INVALID_RESPONSE","Response is missing its App/environment scope");let $t=Ue.safeParse(at.scope);if(!$t.success||$t.data.projectId!==a.projectId||$t.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let qr=We.headers.get("X-Indiana-Telemetry-Subject");if(qr){if(!/^[a-f0-9]{64}$/.test(qr))throw new b("INVALID_RESPONSE","Invalid telemetry identity");m!==qr&&(m=qr,t?.(m))}return kt};try{return await Promise.race([zt(),Fe])}catch(We){throw!B&&me!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):We instanceof b?We:new b(xe.signal.aborted?"TIMEOUT":"NETWORK_ERROR",xe.signal.aborted?"Longplay request timed out":"Unable to read the Longplay response")}finally{clearTimeout(Ee),xe.signal.removeEventListener("abort",Ie),S.delete(xe)}}return{session:y,requestWithCredential(A,P,w){return I(A,P,"POST",{},w)},subjectKey:()=>m,identify(A){if(a&&typeof A=="object"&&"scope"in A){let P=Ue.safeParse(A.scope);if(!P.success||P.data.projectId!==a.projectId||P.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Customer session belongs to another App/environment")}y.identify(A),u=y.peek()??null},reset:f,dispose(){g(),p()},request(A,P={},w="POST",k={}){if(k.installationDetach)return I(A,P,w,k);let N=l;try{let B=y.access(),me=xe=>{if(N!==l)throw new b("IDENTITY_CHANGED","Customer identity changed before dispatch");return I(A,P,w,k,xe)};return typeof B=="string"?me(B):B.then(me)}catch(B){return Promise.reject(B)}}}}function eh(e,t,n={}){let r=!!e.session.peek(),i=new Set,a=o=>{for(let s of i)try{s(o)}catch{}};return e.session.subscribeIdentity(()=>{r=!!e.session.peek(),a(r),n.afterChange?.()},()=>{r=!1,t()}),{isIdentified:()=>r,methods:{subscribeIdentity(o){return i.add(o),()=>{i.delete(o)}},identify(o){let s=typeof o=="string"?o:o.accessToken;if(!Ft.test(s))throw new b("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(s),e.identify(o)},reset(){try{n.beforeReset?.()}finally{e.reset()}}}}}import{ZodError as cI}from"zod";function th(e,t,n,r){try{return e.parse(t)}catch(i){throw r&&i instanceof cI?new b(n,r):i}}async function pe(e,t,n,r={},i){let a=typeof r=="function"?{}:r,o=th(t.request,n,"INVALID_REQUEST",a.request),s=await e(t.path,o,t.method,i),c=typeof r=="function"?r:r.parseResponse;return c?c(t.response,s):th(t.response,s,"INVALID_RESPONSE",a.response)}function Be(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new b("INVALID_REQUEST","Customer requests use the verified session identity")}function nh(e){return{async checkEntitlement(t){Be(t);let n=O.checkEntitlement;return pe(e,n,t)},async readHoldings(t={}){let n=O.readHoldings;return pe(e,{...n,request:n.request.omit({customerId:!0})},t)}}}function rh(e){return{async readLedger(t){let n=O.readLedger;return pe(e,n,{query:t})},async readCreditStatement(t){Be(t);let n=O.readCreditStatement;return pe(e,n,t)},async quoteBalance(t){Be(t);let n=O.quoteBalance;return pe(e,n,{command:t})}}}function ih(e){return{async setupPayment(t){Be(t);let n=O.setupPayment;return pe(e,n,t)},async readPaymentSetup(t){Be(t);let n=O.readPaymentSetup;return pe(e,n,t)},async readBillingInvoice(t){Be(t);let n=O.readBillingInvoice;return pe(e,n,t)},async readBillingControls(t={}){Be(t);let n=O.readBillingControls;return pe(e,n,t)},async prepareBillingAuthorization(t){Be(t);let n=O.prepareBillingAuthorization;return pe(e,n,t)},async confirmBillingAuthorization(t){Be(t);let n=O.confirmBillingAuthorization;return pe(e,n,t)},async setBillingCoupons(t){Be(t);let n=O.setBillingCoupons;return pe(e,n,t,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(t){Be(t);let n=O.revokeBillingAuthorization;return pe(e,n,t)},async listBillingInvoices(t={after:null,limit:25}){Be(t);let n=O.listBillingInvoices;return pe(e,n,t)},async confirmBillingAdjustment(t){Be(t);let n=O.confirmBillingAdjustment;return pe(e,n,t)}}}function oh(e){return{async previewUpdate(t){Be(t);let n=O.previewUpdate;return pe(e,n,t)},async update(t){Be(t);let n=O.update;return pe(e,n,t)},async readSubscriptionUpdate(t){Be(t);let n=O.readSubscriptionUpdate;return pe(e,n,t)},async restoreNativePurchase(t){Be(t);let n=O.restoreNativePurchase;return pe(e,n,t)},async previewAttach(t){Be(t);let n=O.previewAttach;return pe(e,n,t)},async attach(t){Be(t);let n=O.attach;return pe(e,n,t)},async readSubscriptionOperation(t){Be(t);let n=O.readSubscriptionOperation;return pe(e,n,t)}}}function ah(e){return{async redeemReward(t){return Be(t),(await pe(e,O.redeemReward,{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(t){return Be(t),(await pe(e,O.claimRewardProduct,t,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(t){return Be(t),(await pe(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 pe(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 pe(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 pe(e,O.listOffers,{},{response:"Invalid offers response"})).offers}}}function sh(e){return{...nh(e),...rh(e),...ih(e),...oh(e),...ah(e)}}function ch(e){return{async resolveContent(t){Be(t);let n=O.resolveContent;return pe(e,n,t)},async resolvePaywall(t){Be(t);let n=O.resolvePaywall;return pe(e,n,t)},async resolveOffering(t){Be(t);let n=O.resolveOffering;return pe(e,n,t)}}}var uh=e=>new TextEncoder().encode(JSON.stringify(e)).length,lh=16384;function dh(e,t){let n=0,r,i=p=>{r={config:structuredClone(p),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(p,g={},f={}){if(c(),r&&Date.now()<r.until&&!Om(r.config,p))return;y();let I=O.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:p,properties:g,...f}]}).events[0];if(uh({events:[I]})>lh)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(I)),u()}async function m(p=!1){if(c(),o)return o;let g=n,f=(async()=>{let I={inserted:0,duplicates:0,rejected:0,skipped:0},A=a.length;for(;A&&g===n;){let P=[];for(let N of a.slice(0,Math.min(A,100))){if(P.length&&uh({events:[...P,N]})>lh)break;P.push(N)}let w=O.trackEvents,k=await pe(e,w,{events:P},void 0,{keepalive:p});if(g!==n)throw new b("IDENTITY_CHANGED","Event identity changed during delivery");if(k.inserted+k.duplicates+k.rejected+k.skipped!==P.length)throw new b("INVALID_RESPONSE","Incomplete event acknowledgement");i(k.analyticsConfig),a.splice(0,P.length),A-=P.length,I.inserted+=k.inserted,I.duplicates+=k.duplicates,I.rejected+=k.rejected,I.skipped+=k.skipped}return I})();o=f;try{return await f}finally{o===f&&(o=null)}}let S;function y(){if(S||typeof document>"u")return;let p=()=>{document.visibilityState==="hidden"&&t()&&a.length&&m(!0).catch(()=>{})};document.addEventListener("visibilitychange",p),S=()=>document.removeEventListener("visibilitychange",p)}return{rememberConfiguration:i,track(p,g,f={}){return y(),l(p,g,f)},flush:m,reset(){n++,r=void 0,clearTimeout(s),s=void 0,a=[],o=null},detachVisibility(){S?.(),S=void 0}}}function Mu(e){let t=null,n=null,r=0,i=0,a=!1,o=new Set,s=null,c=null,u=new Set,l=()=>{for(let A of u)try{A()}catch{}},m={attributes:ht.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(A,P)=>{!o.has(A)&&(!t||!("analyticsConfig"in t)||t.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(A,structuredClone(P),structuredClone(m.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(A,P)=>(!t||!("analyticsConfig"in t)||t.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(A),structuredClone(P),structuredClone(m.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?A=>e.saveStickyBucketAssignmentDoc(structuredClone(A)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},S=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function y(A,P=new Set){return o.has(A)?!s||!s.features[A]||["unknownFeature","cyclicPrerequisite"].includes(s.features[A].source):P.has(A)?!1:(P.add(A),(t?.features[A]?.rules??[]).some(w=>[...w.parentConditions??[],...(w.tracks??[]).flatMap(k=>k.experiment.parentConditions??[])].some(k=>y(k.id,P))))}let p=A=>{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 s?.expiresAt&&Date.parse(s.expiresAt)<=Date.now()&&(s=null,m.features=t.features),o.has(A)?!s||s.expiresAt&&Date.parse(s.expiresAt)<=Date.now()?S():structuredClone(s.features[A]??S()):e.evaluateRemote&&(m.attributes?.merchandise||m.attributes?.merchandiseId)&&!a||y(A)?S():structuredClone(Dn(A,m))};async function g(){if(!t||!o.size&&!m.attributes?.merchandise&&!m.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(o.size)throw new Error("Remote Feature evaluation requires a server loader");return}let A=i;if(c?.revision===A)return c.loading;let P=r,w=t,k=[...o],N=(async()=>{let B=Sa.parse(await e.evaluateRemote({attributes:structuredClone(m.attributes),features:k}));if(!(P!==r||A!==i||w!==t)){if(e.assertUsable?.(w.generation),B.generation!==w.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(k.some(me=>!Object.hasOwn(B.features,me))||Object.keys(B.features).some(me=>!o.has(me)))throw new Error("Invalid remote Feature results");if(m.attributes?.merchandise||m.attributes?.merchandiseId){if(!B.merchandiseContext)throw new Error("Server did not resolve merchandise context");m.attributes=ht.parse({...m.attributes,...B.merchandiseContext}),a=!0}s=structuredClone(B),m.features={...w.features,...Object.fromEntries(Object.entries(s.features).map(([me,xe])=>[me,{defaultValue:xe.value}]))},l()}})();c={revision:A,loading:N};try{await N}finally{c?.loading===N&&(c=null)}}function f(){g().catch(A=>{try{e.onError?.(A)}catch{}})}async function I(){if(n)return n;let A=r,P=(async()=>{let w=await e.load(),k="remoteFeatures"in w?eo.parse(w):null,N=k??ln.parse(w);if(N.scope.projectId!==e.scope.projectId||N.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(A!==r)throw new Error("Feature client was reset");if(e.assertUsable&&t?.generation===N.generation){let{evaluatedAt:me,expiresAt:xe,...Ce}=t,{evaluatedAt:Ie,expiresAt:Fe,...Ee}=N;if(yt(Ce)!==yt(Ee))throw new Error("Immutable Feature generation changed content");return t.evaluatedAt=N.evaluatedAt,t.expiresAt=N.expiresAt,l(),(!s||s.expiresAt&&Date.parse(s.expiresAt)<=Date.now())&&f(),structuredClone(t)}let B=new Set(k?.remoteFeatures??[]);if([...B].some(me=>Object.hasOwn(N.features,me)))throw new Error("Remote Feature definitions must not be delivered locally");return t&&"analyticsConfig"in t&&"analyticsConfig"in N&&!t.analyticsConfig.experimentViewsEnabled&&k?.analyticsConfig.experimentViewsEnabled&&m.trackedExperiments?.clear(),t=structuredClone(N),o=B,s=null,c=null,i++,m.features=t.features,m.savedGroups=Kr(t.savedGroups),m.trackedFeatureUsage={},l(),f(),structuredClone(t)})();n=P;try{return await P}finally{n===P&&(n=null)}}return{init:I,refresh:I,refreshRemote:g,get generation(){return t?.generation??null},get expiresAt(){return t?.expiresAt??null},subscribe(A){return u.add(A),()=>{u.delete(A)}},setAttributes(A){let P=ht.parse(A);(m.attributes?.merchandise||m.attributes?.merchandiseId||A.merchandise||A.merchandiseId)&&m.trackedExperiments?.clear(),m.attributes=P,i++,a=!1,s=null,c=null,m.features=t?.features??{},m.trackedFeatureUsage={},l(),f()},evalFeature:p,isOn(A){return p(A).on},isOff(A){return p(A).off},getFeatureValue(A,P){let w=p(A).value;return structuredClone(w===null?P:w)},reset(){r++,i++,n=null,c=null,t=null,s=null,o.clear(),m.features={},m.savedGroups={},m.stickyBucketAssignmentDocs={},m.attributes={},m.trackedFeatureUsage={},m.trackedExperiments?.clear(),l()}}}function ph(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 uI(e){let t=ph(e),{merchandiseId:n,merchandise:r,...i}=e;return{...i,...t?{merchandise:t}:{}}}function mh(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,S=async()=>{if(m||l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let Ce=O.getFeatures,Ie=i?{scope:{projectId:i.scope.projectId,environment:i.scope.environment},payload:await i.features()}:await pe(e,Ce,{});if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");if(r&&(Ie.scope.projectId!==r.projectId||Ie.scope.environment!==r.environment))throw new b("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(Ie.payload.analyticsConfig),Ie},y=await S(),p=!0,g,f=Ce=>{try{u.onError?.(Ce)}catch{}},I=(Ce,Ie,Fe)=>{try{let Ee=ph(Fe);n.track(Ce,Ie,Ee?{merchandise:Ee}:{})}catch(Ee){f(Ee)}},A=Mu({assertUsable:i?.assertFeatures,scope:y.scope,attributes:u.attributes,onError:u.onError,load:async()=>p?(p=!1,y.payload):(await S()).payload,evaluateRemote:async Ce=>{if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let Ie=O.evaluateFeatures,Fe=await pe(e,Ie,{...Ce,attributes:uI(Ce.attributes)});if(Fe.scope.projectId!==y.scope.projectId||Fe.scope.environment!==y.scope.environment)throw new b("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:Fe.generation,evaluatedAt:Fe.evaluatedAt,expiresAt:Fe.expiresAt,features:Fe.features,...Fe.merchandiseContext?{merchandiseContext:Fe.merchandiseContext}:{}}},onExperimentViewed:(Ce,Ie,Fe)=>I("Experiment Viewed",{experimentId:Ce.key,variationId:Ie.key},Fe),onFeatureUsage:(Ce,Ie,Fe)=>I("Feature Evaluated",{feature:Ce,value:Ie.value,source:Ie.source,ruleId:Ie.ruleId,...Ie.experimentResult?{variationId:Ie.experimentResult.key}:{}},Fe)}),P=A.refresh;function w(){clearTimeout(g),!i&&(m||l!==a||!A.expiresAt||(g=setTimeout(()=>{k().catch(f)},Math.min(2147483647,Math.max(1e3,Date.parse(A.expiresAt)-Date.now()))),typeof g=="object"&&"unref"in g&&g.unref()))}async function k(){try{return await P()}finally{w()}}let N=()=>{m||k().catch(f)},B=A.subscribe(w),me=i?.subscribe(()=>{!m&&i.fresh&&k().catch(f)});function xe(){m||(m=!0,clearTimeout(g),typeof window<"u"&&window.removeEventListener("focus",N),B(),me?.(),A.reset(),o.delete(xe))}o.add(xe);try{await A.init(),(u.attributes?.merchandise||u.attributes?.merchandiseId)&&await A.refreshRemote()}catch(Ce){throw xe(),Ce}return w(),!i&&typeof window<"u"&&window.addEventListener("focus",N),Object.assign(A,{refresh:k,destroy:xe})}return{features:c,reset(u){a++,u();for(let l of o)l()}}}import{z as lI}from"zod";function fh(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=lI.object({funnelId:La.shape.id,funnelVersionId:La.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 pe(e,c,a({couponId:o,requestId:s}));return{offer:u.offer,reason:u.reason}},async resolveOffering(o){let s=O.resolveOffering;return pe(e,s,a(o))},async resolvePaywall(o){let s=O.resolvePaywall;return pe(e,s,a(o))},async previewAttach(o){let s=O.previewAttach;return pe(e,s,a(o))}}}function gh(e){let t=cr(e),n=t.request,r=Cg(e.push,t,e.scope??e.configuration?.scope),i=eh(t,()=>{o.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start}),a=dh(n,i.isIdentified),o=mh(n,i.isIdentified,a,e.scope,e.configuration);return{session:t.session,...Pg(n,r),...sh(n),...ch(n),forFunnel(s){return fh(n,s)},async features(s={}){return o.features(s)},track(s,c,u={}){return a.track(s,c,u)},flush(){return a.flush()},...i.methods}}function Si(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)=>Si(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)&&Si(a,Reflect.get(t,i)))}async function Xa(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 xi=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function es(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&&!xi.test(e.apiKey))throw new b("INVALID_TOKEN","A customer credential or server API key is required");let n=cr({...e,timeoutMs:e.timeoutMs??35e3});return e.session||n.identify(e.apiKey),{async start(r){let i=Un.safeParse({...r,operation:"start"});if(!i.success||i.data.operation!=="start"||(t?i.data.customer!==void 0:i.data.customer===void 0))throw new b("INVALID_REQUEST","Invalid current Funnel start");let a=i.data,o=lo.safeParse(await Xa(e,await n.request("funnels",a)));if(!o.success||!o.data.runToken)throw new b("INVALID_RESPONSE","Funnel start credentials are missing");let s=o.data;if(s.run.source.id!==a.funnelId||s.run.locale!==(a.locale??"en")||!Si(s.run.parameters,a.parameters??{})||(a.customer?!s.customerId||a.customer.type==="id"&&s.customerId!==a.customer.value:s.customerId!==void 0))throw new b("INVALID_RESPONSE","Funnel start contract changed");return{...s,runToken:s.runToken}}}}async function qu(e,t,n){if(Number(e.headers.get("content-length"))>t)throw n.error("limit");let r=e.body?.getReader();if(!r)throw n.error("missing");let i=[],a=0;try{for(;;){n.signal?.throwIfAborted();let c=await r.read();if(c.done)break;if(a+=c.value.length,a>t)throw n.error("limit");i.push(c.value)}}finally{await r.cancel().catch(()=>{})}n.signal?.throwIfAborted();let o=new Uint8Array(a),s=0;for(let c of i)o.set(c,s),s+=c.length;return o}async function hh(e,t,n){return new TextDecoder("utf-8",{fatal:!0}).decode(await qu(e,t,n))}function ts(e,t){let n=typeof e=="string"?new TextEncoder().encode(e):e;return n.byteLength===t.byteLength&&Xc(n)===t.sha256}async function ns(e,t){let n=kr.parse(t),{artifact:r,environmentId:i}=n.content,a=new mn(e.baseUrl??sr).origin,o=new mn(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=setTimeout(()=>s.abort(),Zt.initializationMs);try{let u=await(e.fetch??globalThis.fetch)(o,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:s.signal});if(!u.ok||!u.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(u.headers.get("content-length"))>r.byteLength)throw new b("INVALID_RESPONSE","Public Paywall is unavailable");let l=await qu(u,r.byteLength,{signal:s.signal,error:m=>new b("INVALID_RESPONSE",m==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!ts(l,r))throw new b("INVALID_RESPONSE","Public Paywall digest or size changed");return bf(n,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l)))}finally{clearTimeout(c)}}var Ah=(e,t)=>new b(e,t);async function Vu(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=dI(e,t,o)}catch{i=null}return a??(a=e.snapshot?.generation??(await e.refresh()).generation),{advance:{policyRevision:r.policyRevision,generation:a},prediction:i}}function dI(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=mu({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:ln.parse(o)}),c=pI(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 pI(e,t,n){return wg(e,t,n,Ah)}import{z as kn}from"zod";var yh=Un.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}),bh=kn.strictObject({schemaVersion:kn.literal(1),scope:Ue,runId:kn.uuid(),funnelId:kn.uuid(),versionId:kn.uuid(),command:yh.optional(),closeCommand:yh.refine(e=>e.operation==="close").optional(),purchase:kn.strictObject({receiptId:kn.uuid(),operationId:kn.uuid(),generation:kn.number().int().nonnegative()}).optional(),closed:kn.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"),Wt=()=>new b("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),rs=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Sh(e){let t=0,n=null,r=c=>JSON.stringify([c.scope,c.runId,c.funnelId,c.versionId]),i=Promise.resolve();async function a(){let c=await e.read();if(!Number.isSafeInteger(c.revision)||c.revision<0)throw new b("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:c.revision,entry:c.entry===null?null:bh.parse(c.entry)}}function o(c){let u=i.then(c);return i=u.catch(()=>{}),u}async function s(c){for(let u=0;u<4;u++){let l=await a();if(l.entry&&n!==null&&r(l.entry)!==n)throw Wt();let m=c(l.entry,l.revision);if(rs(l.entry,m)){t=l.revision;return}let S=await e.write(l.revision,m);if(S!==null){if(!Number.isSafeInteger(S)||S<=l.revision)throw Wt();t=S;return}}throw Wt()}return{bind(c){let u=JSON.stringify([c.scope,c.runId,c.funnelId,c.versionId]);if(n!==null&&n!==u)throw Wt();n=u},async load(){let c=await a();return t=c.revision,n=c.entry?r(c.entry):null,c.entry},retain(c){let u=bh.parse(c),l=u.command;return!l||n!==null&&r(u)!==n?Promise.reject(Wt()):(n??(n=r(u)),o(()=>s((m,S)=>{if(m&&!rs(r(m),r(u)))throw Wt();if(!m){if(S!==t&&l.operation!=="close")throw Wt();return u}if(!m.command)return{...m,command:l,...l.operation==="close"?{closed:!0}:{}};if(l.operation==="close"&&m.command.operation!=="close"){if(m.command.requestId===l.requestId||m.closeCommand&&!rs(m.closeCommand,l))throw Wt();return{...m,closeCommand:l,closed:!0}}if(!rs(m.command,l))throw Wt();return m})))},observePurchase(c,u,l){return o(()=>s((m,S)=>{if(!m&&S!==t||m&&r(m)!==r({...c,schemaVersion:1}))throw Wt();if(m?.purchase&&m.purchase.generation>u.generation)return m;if(m?.purchase&&m.purchase.generation===u.generation&&m.purchase.operationId!==u.operationId)throw Wt();return l?!m?.purchase||m.purchase.operationId!==u.operationId?m:m.command?{...m,purchase:void 0}:null:{schemaVersion:1,...c,...m,purchase:u}}))},settle(c){return o(()=>s(u=>u?u.command&&"requestId"in u.command&&u.command.requestId===c?u.closeCommand?{...u,command:u.closeCommand,closeCommand:void 0}:u.purchase?{...u,command:void 0}:null:u.closeCommand&&"requestId"in u.closeCommand&&u.closeCommand.requestId===c?{...u,closeCommand:void 0}:u:null))}}}function xh(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 Ih(e){let t=null,n=0,r=!1,i,a=0,o=new Set;return{get view(){return t},get generation(){return n},get disposed(){return r},get customerToken(){return i},get readSequence(){return a},nextRead(){return++a},assertCurrent(s,c="Run identity changed during the request"){if(s!==n||r)throw new b("IDENTITY_CHANGED",c)},assertRun(s){if(t&&(s.id!==t.id||s.source.type!==t.source.type||s.source.id!==t.source.id||s.source.versionId!==t.source.versionId||s.locale!==t.locale||!Si(s.parameters,t.parameters)))throw new b("INVALID_RESPONSE","Run version changed");if(e&&s.source.id!==e)throw new b("INVALID_RESPONSE","Run belongs to another Funnel")},publish(s,c,u,l,m){if(!(s.operation==="review"&&t&&t!==u&&c.run.revision<=t.revision)&&!(t&&c.run.revision===t.revision&&l!==void 0&&l<a)&&(s.operation==="review"&&!c.run.stopped&&["running","waiting"].includes(c.run.status)&&t&&c.run.nodeId===t.nodeId&&c.run.visit===t.visit&&c.run.revision===t.revision&&(c.run.screen=t.screen,(t.paywall?.quote?.operationId===c.review?.activeOperationId||!t.paywall?.quote&&c.review?.activeOperationId===null)&&(c.run.paywall=t.paywall)),!(t?.paywall&&c.run.paywall&&t.paywall.receiptId===c.run.paywall.receiptId&&(c.run.paywall.selectionGeneration??0)<(t.paywall.selectionGeneration??0)))){if(!t||c.run.revision>=t.revision)t=c.run;else if(!m)return;if(t)for(let S of o)try{S(structuredClone(t))}catch{}}},identify(s){if(!Ft.test(s))throw new b("INVALID_TOKEN","Customer credential required");n++,i=s},subscribe(s){return o.add(s),()=>o.delete(s)},reset(){r=!0,n++,i=void 0,t=null,o.clear()}}}function ur(e){let{customerToken:t,...n}=e;return n}var mI=e=>!(e instanceof b)||e.status===void 0||e.status>=500||[401,425].includes(e.status);function vh({options:e,journal:t,state:n,call:r}){let i=null,a=null,o=!1,s={command:null,close:null},c=!1,u,l=null,m=t?t.load().then(f=>{if(n.disposed)throw new b("IDENTITY_CHANGED","Controller was reset during command restoration");if(l=f,!f)return;if(e.scope&&(f.scope.projectId!==e.scope.projectId||f.scope.environment!==e.scope.environment))throw new b("SCOPE_MISMATCH","Pending command belongs to another scope");if(u=f.purchase,o=f.closed===!0,!f.command)return;let I=Un.parse(f.command);if(I.operation==="start"||I.operation==="get"||I.operation==="review")throw new b("COMMAND_STORAGE_INVALID","Stored mutation required");i=I,f.closeCommand&&(a=f.closeCommand,o=!0),I.operation==="close"&&(o=!0),c=!0}):Promise.resolve();m.catch(()=>{});async function S(f=i){if(t&&await m,!f)throw new b("INVALID_REQUEST","No command is pending");let I=f,A=n.generation;if(t){if(!n.view||!e.scope)throw new b("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await t.retain({schemaVersion:1,scope:e.scope,runId:n.view.id,funnelId:n.view.source.id,versionId:n.view.source.versionId,command:ur(I)})}if(A!==n.generation||i!==I&&a!==I)throw new b("IDENTITY_CHANGED","Run changed before command dispatch");let P={...I,...n.customerToken?{customerToken:n.customerToken}:{}},w=c;c=!0;try{return await r(P,k=>{if(!k.settlement)throw new b("INVALID_RESPONSE","Exact command settlement is missing");if(k.settlement.requestId!==I.requestId)throw new b("INVALID_RESPONSE","Command settlement identity changed");if(A===n.generation&&(i===I||a===I)&&k.run.pendingRequest?.requestId!==I.requestId&&k.settlement.state==="settled"&&(!o||I.operation==="close"||k.settlement?.state==="settled"&&!["running","waiting"].includes(k.run.status))){let N=()=>A!==n.generation||i!==I&&a!==I?!1:(i===I&&(i=null),a===I&&(a=null),c=i!==null,l=null,!0);return t?t.settle(I.requestId).then(N):N()}return!1})}catch(k){throw A===n.generation&&i===I&&!w&&!mI(k)&&(t&&await t.settle(I.requestId),A===n.generation&&i===I&&(i=null,c=!1,l=null)),k}}function y(f){let I=Un.parse(f);if(I.operation==="start"||I.operation==="get"||I.operation==="review")throw new b("INVALID_REQUEST","Mutation required");if(o&&I.operation!=="close"){if(i?.requestId===I.requestId)return g(I.requestId);throw new b("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(I.operation==="close"&&i?.operation!=="close"){if(o=!0,a&&JSON.stringify(ur(a))!==JSON.stringify(ur(I)))throw new b("COMMAND_PENDING","Retry the original Close");return a??(a=I),s.close?s.close:p(a,"close")}if(i){if(JSON.stringify(ur(i))!==JSON.stringify(ur(I)))throw new b("COMMAND_PENDING","Retry the original command before sending another");if(s.command)return s.command}else i=I,c=!1;return p(i,"command")}function p(f,I){let A=S(f);s[I]=A;let P=()=>{s[I]===A&&(s[I]=null)};return A.then(P,P),A}async function g(f){let I=await r({operation:"get",settlementRequestId:f,...n.customerToken?{customerToken:n.customerToken}:{}});if(I.settlement?.requestId!==f)throw new b("INVALID_RESPONSE","Exact command settlement is missing");return I.settlement.state==="settled"&&(t&&await t.settle(f),i?.requestId===f&&(i=null,c=!1),a?.requestId===f&&(a=null)),I}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(f){if(l&&(f.run.id!==l.runId||f.run.source.id!==l.funnelId||f.run.source.versionId!==l.versionId))throw new b("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},observePurchase(f,I,A,P){t?.bind({scope:I.scope,runId:I.run.id,funnelId:I.run.source.id,versionId:I.run.source.versionId}),t&&!e.scope&&(e.scope=I.scope);let w=I.run.paywall,k=w??I.purchase,N=k?.operation,B=I.settlement&&(!w||w.purchaseRequestId===I.settlement.requestId)&&(!u||u.operationId===I.settlement.operationId)?I.settlement:void 0,me=N?.operationId??k?.quote?.operationId??B?.operationId,xe=k?.receiptId??B?.receiptId,Ce=w?.selectionGeneration??u?.generation??0;if(t&&me&&xe&&f.operation!=="review"&&(!n.view||I.run.revision>=n.view.revision)&&(P===void 0||P>=n.readSequence)&&(!u||Ce>=u.generation)){let Ie={receiptId:xe,operationId:me,generation:Ce},Fe=N?.status==="complete"||k?.canReselect===!0;return t.observePurchase({scope:I.scope,runId:I.run.id,funnelId:I.run.source.id,versionId:I.run.source.versionId},Ie,Fe).then(()=>{n.assertCurrent(A),Fe?u?.operationId===Ie.operationId&&(u=void 0):u=Ie})}},stop(){o=!0},submit:y,executePending:S,settle:g,reset(){i=null,a=null,s.close=null,c=!1,s.command=null}}}function Ii(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"||!xi.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=cr({...e,session:void 0,...e.serverKey?{fetch:(f,I)=>{let A=new Headers(I?.headers),P=typeof I?.body=="string"?JSON.parse(I.body):null;return P!==null&&typeof P=="object"&&"customerToken"in P&&typeof P.customerToken=="string"&&P.customerToken.length>0||A.set(hg,e.serverKey),(e.fetch??globalThis.fetch)(f,{...I,headers:A})}}:{},...e.session?{fetch:async(f,I)=>{let A=await e.session.access(),P=typeof I?.body=="string"?JSON.parse(I.body):{};if(!P||typeof P!="object"||Array.isArray(P))throw new b("INVALID_REQUEST","Run command must be an object");return(e.fetch??globalThis.fetch)(f,{...I,body:JSON.stringify({...P,customerToken:A})})}}:{},timeoutMs:e.timeoutMs??35e3});t.identify(e.runToken);let n=Ih(e.funnelId),r=e.session?.subscribeIdentity(()=>{n.reset(),t.reset()}),i=null,a=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?xh(e):void 0),o=a&&Sh(a),s=vh({options:e,journal:o,state:n,call:c});async function c(f,I,A){let P=n.generation,w=()=>n.assertCurrent(P);o&&await s.ready,w();let k=n.view,N=lo.parse(await Xa(e,await t.request("funnels",Un.parse(f))));if(f.operation==="review"&&!N.review)throw new b("INVALID_RESPONSE","Historical projection is missing");if(w(),N.runToken&&N.runToken!==e.runToken)throw new b("INVALID_RESPONSE","Run credential changed");let B=f.operation==="get"?f.settlementRequestId:"requestId"in f&&f.operation!=="start"?f.requestId:void 0;if(B&&N.settlement?.requestId!==B)throw new b("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");s.assertBinding(N),n.assertRun(N.run);let me=s.observePurchase(f,N,P,A);if(me&&await me,!N.run.stopped&&["running","waiting"].includes(N.run.status)&&f.operation==="get"&&f.settlementRequestId)return N;let xe=I?.(N),Ce=typeof xe=="boolean"?xe:xe?await xe:!1;return w(),["running","waiting"].includes(N.run.status)||s.stop(),n.publish(f,N,k,A,Ce),N}let u=s.submit,l=null,m=new WeakMap;function S(f){let I=m.get(f);if(I)return I;let A=p(f);return m.set(f,A),A}let y=!1;async function p(f){let I=await f;if(I.run.instruction?.type!=="evaluate_segment")return I;if(l)return l;y=!0;let A=n.generation,P=(async()=>{for(let w=0;w<32&&I.run.instruction?.type==="evaluate_segment";w++){if(s.pending||s.closeRequested)return I;let k=I.run;if(I.run.instruction?.type==="evaluate_segment"){let{advance:B}=await Vu(e.configuration,k,{predict:!1});if(A!==n.generation)throw new b("IDENTITY_CHANGED","Run identity changed during segment calculation");if(s.pending||s.closeRequested)return I;if(n.view&&(n.view.revision!==k.revision||n.view.visit!==k.visit||n.view.nodeId!==k.nodeId))return c({operation:"get",...n.customerToken?{customerToken:n.customerToken}:{}});let me=!0;Vu(e.configuration,k).then(({prediction:xe})=>{me&&A===n.generation&&!s.closeRequested&&n.view?.id===k.id&&!n.view.stopped&&n.view.nodeId===k.nodeId&&n.view.visit===k.visit&&n.view.revision===k.revision&&(i=xe)}).catch(()=>{});try{I=await u({operation:"commit_segment",requestId:fg(k.id,k.visit,`segment:${k.revision}`),nodeId:k.nodeId,visit:k.visit,revision:k.revision,...B})}finally{me=!1,i=null}}}return I})();l=P;try{return await P}finally{l===P&&(l=null)}}let g={get configuration(){return y?e.configuration:void 0},get configurationReady(){return!0},get view(){return n.view?structuredClone(n.view):null},get pendingCommand(){let f=s.closing??s.pending;return f?structuredClone(ur(f)):null},get pendingCommands(){return[s.pending,s.closing].filter(f=>f!==null).map(f=>structuredClone(ur(f)))},get pendingPurchase(){return s.purchase?structuredClone(s.purchase):null},get prediction(){let f=n.view;return i&&f&&!f.stopped&&["running","waiting"].includes(f.status)&&f.id===i.runId&&f.nodeId===i.from.nodeId&&f.visit===i.from.visit&&f.revision===i.from.revision&&!s.closeRequested?structuredClone(i):null},settle:s.settle,get webViewUrl(){return"bundled"},resolvePaywall(f){return ns(e,f)},async pageExperiments(f,I=[]){let A=n.generation;n.assertCurrent(A);let P=n.view?.id;if(!P)throw new b("INVALID_REQUEST","Read the Run before its page experiments");let w=_g.parse(await t.request("funnels",Og.parse({operation:"page_experiments",release:f,usedReceiptIds:I,...n.customerToken?{customerToken:n.customerToken}:{}})));if(n.assertCurrent(A),w.runId!==P||w.scope.projectId!==e.scope?.projectId||w.scope.environment!==e.scope?.environment)throw new b("SCOPE_MISMATCH","Page experiment Run changed");return w},review(f){return c({operation:"review",...f?{receiptId:f}:{},...n.customerToken?{customerToken:n.customerToken}:{}},void 0,n.nextRead())},async get(f,I){o&&await s.ready,I??(I=s.purchase&&{receiptId:s.purchase.receiptId,operationId:s.purchase.operationId});let A=n.nextRead();return S(c({operation:"get",...f?{data:f}:{},...I?{purchase:I}:{},...n.customerToken?{customerToken:n.customerToken}:{}},void 0,A))},resume(f=n.view?.pendingRequest?.requestId){return f?s.closeRequested?g.settle(f):s.pending?.requestId===f?S(u(s.pending)):S(u({operation:"resume",requestId:f})):Promise.reject(new b("INVALID_REQUEST","No interrupted command is available"))},submit(f){return S(u(f))},retry(){return s.closeFlight?s.closeFlight:s.closing?s.executePending(s.closing):s.closeRequested&&s.pending?g.settle(s.pending.requestId):s.inFlight?S(s.inFlight):s.pending?S(u(s.pending)):Promise.reject(new b("INVALID_REQUEST","No command is pending"))},identify(f){n.identify(f),i=null,t.identify(e.runToken)},subscribe:n.subscribe,reset(){r?.(),n.reset(),s.reset(),i=null,t.reset()}};return g}function wh(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=es({...e,scope:e.scope,apiKey:e.customerToken});return{async start(n){let r=await t.start(n),i=Ii({...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 Oh(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 _h(e,t,n){if(e.operationId!==t.operationId||t.currency!==void 0&&e.currency!==t.currency)throw new b("INVALID_RESPONSE",n)}function Ch(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 Ph(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}async function Eh(e,t){if(!Ft.test(t.customerToken))throw new b("INVALID_TOKEN","A verified Customer credential is required");let n=cr(e);if(!e.session)n.identify(t.customerToken);else if(e.session.peek()!==t.customerToken)throw new b("SCOPE_MISMATCH","Paywall credential does not match the shared session");let r=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}:{}}),i=null,a=!1,o=null,s=null,c=null,u=null,l=e.session?.subscribeIdentity(()=>{a=!0,n.dispose(),i=null,o=null,s=null,c=null});async function m(){if(a)throw new b("IDENTITY_CHANGED","Paywall is closed");let p=O.resolvePaywall,g=await pe(n.request,p,{...r,selector:i?{type:"version",versionId:i.id}:r.selector}),f={paywall:await ns(e,g.paywall)};if(a)throw new b("IDENTITY_CHANGED","Paywall is closed");if(t.paywallVersionId?f.paywall.id!==t.paywallVersionId:f.paywall.paywallId!==t.paywallId)throw new b("INVALID_RESPONSE","The requested Paywall changed");if(i&&(!Oh(f.paywall,i)||f.paywall.paywallId!==i.paywallId))throw new b("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return i=f.paywall,structuredClone(i)}async function S(p){if(!o)throw new b("INVALID_REQUEST","A quoted purchase is required");let g=p==="read"?O.readSubscriptionOperation:O.attach,f=await pe(n.request,g,{operationId:o.operationId,...p==="read"?{}:{intent:p}});return _h(f.operation,{operationId:o.operationId,currency:r.commerce.currency},"The purchase operation changed"),s=Ph(s,f.operation),structuredClone(s)}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"},refresh:m,async preview(p){if(!i)throw new b("INVALID_REQUEST","Load the Paywall first");let g=i.document.buttons[p.actionId];if(g?.type!=="checkout")throw new b("INVALID_REQUEST","Choose an authored purchase action");let f=Im(g.product,p.selection,i.capabilities);if(!f)throw new b("PRODUCT_UNAVAILABLE","Choose an available Product");let I=lf(i.document.screen,f,p.selection,i.capabilities),A=O.previewAttach.request.parse({funnelId:r.funnelId,funnelVersionId:r.funnelVersionId,requestId:p.requestId,plans:[{productVersionId:f,...Object.keys(I).length?{featureQuantities:I}:{}}],provider:r.commerce.provider,currency:r.commerce.currency,...p.offerId?{offerId:p.offerId}:{},...p.nativeOffer?{nativeOffer:p.nativeOffer}:{}}),P=JSON.stringify(A);if(c&&c!==P&&(!s||s.status==="pending"))throw new b("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(c===P){if(u)return u;if(o)return structuredClone(o)}c=P;let w=(async()=>{let k=O.previewAttach,N=await pe(n.request,k,A);return Ch(N.quote,{productVersionId:f,featureQuantities:I,currency:r.commerce.currency,provider:r.commerce.provider},"The purchase quote changed its selected Product or presentment"),o=N.quote,s=null,structuredClone(o)})();u=w;try{return await w}finally{u===w&&(u=null)}},confirm:()=>S("confirm"),cancel:()=>S("cancel"),read:()=>S("read"),destroy(){l?.(),a=!0,n.dispose(),i=null,o=null,s=null,c=null}};return await m(),y}function Rh(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 y=r;n&&e.nativeModule&&n.then(p=>e.nativeModule.reset(p,y)).catch(()=>{})}),l=e.nativeEvents?.(y=>{!n||!e.nativeModule||typeof y?.requestId!="string"||(async()=>{let p=await n;if(y.instanceId!==p)return;if(y.kind==="credential"){let I=r,A=null;try{if(!o&&y.revision===I){let P=await t.access();!o&&r===I&&(A=P)}}finally{await e.nativeModule.provideCredential(p,y.requestId,A)}return}let g=!1,f=r;try{if(o||y.revision!==f||!e.onNativeAction)throw c();await e.onNativeAction(y.action),g=!o&&r===f}finally{await e.nativeModule.acknowledge(p,y.requestId,g)}})().catch(()=>{})});async function m(y,p={}){let g=s();if(t.snapshot()&&!e.nativeEvents)throw new b("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let f=r,I=await t.access();if(o||r!==f)throw c();if(!n){let w=g.create(JSON.stringify({baseUrl:e.baseUrl??"https://api.longplayai.com",scope:e.scope,timeout:(e.timeoutMs??15e3)/1e3,credentialEvents:!!e.nativeEvents}));n=w,w.catch(()=>{n===w&&(n=void 0)})}let A=await n;if(o||r!==f)throw c();if(i!==f){if(!a||a.epoch!==f){let k=(async()=>{if(await g.identify(A,JSON.stringify({revision:f,credentials:I})),o||r!==f)throw await g.reset(A,f),c();i=f})();a={epoch:f,task:k}}let w=a;try{await w.task}finally{a===w&&(a=void 0)}}let P=await g.invoke(A,y,JSON.stringify(p));if(o||r!==f)throw c();try{return JSON.parse(P)}catch{throw new b("INVALID_RESPONSE","Native host returned invalid JSON")}}async function S(y,p){let g=await m(y,p);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(y){return S("showFunnel",{runToken:y})},showPaywall(y){return S("showPaywall",y)},showContent(y){return S("showContent",y)},purchaseSubscription(y,p){return m("purchaseSubscription",{operationId:y,accepted:p})},switchSubscription(y,p){return m("switchSubscription",{operationId:y,accepted:p})},restorePurchases(){return m("restorePurchases")},manageSubscriptions(y){return m("manageSubscriptions",y?{productId:y}:{})},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 fI=O.trackUsage.request.shape.command,gI=O.trackUsage.response;function hI(e){let t=Ue.parse(e.scope),n=gh({...e,scope:t}),r={...e,scope:t,session:n.session},i=0;n.subscribeIdentity(()=>{i++});let a=()=>{let o=n.session.peek();if(!o)throw new b("UNAUTHENTICATED","Identify the Customer first");return o};return{...n,native:Rh(e,n.session),funnel(){return wh({...r,customerToken:a()})},resumeFunnel(o){return a(),Ii({...r,runToken:o})},paywall(o){return Eh(r,{...o,customerToken:a()})},async trackUsage(o){if(!n.session.peek())throw new b("UNAUTHENTICATED","Identify the Customer first");if(!e.usageReporter)throw new b("INVALID_REQUEST","Configure your authenticated backend usageReporter");let s=fI.parse(o),c=i,u;try{u=await e.usageReporter(s)}catch(m){throw c!==i?new b("IDENTITY_CHANGED","Customer identity changed during usage reporting"):m}if(c!==i)throw new b("IDENTITY_CHANGED","Customer identity changed during usage reporting");let l=gI.parse(u);if(l.scope.projectId!==t.projectId||l.scope.environment!==t.environment)throw new b("INVALID_RESPONSE","Usage response scope differs");return l}}}import{z as SI}from"zod";import{z as ho}from"zod";var AI=ho.record(ho.string().regex(/^[a-f0-9]{64}$/),ho.strictObject({at:ho.number(),text:ho.string()})),kh=2*1048576,yI=100;function bI(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function jh(e,t){let n=t===void 0?bI():t,r=Promise.resolve();async function i(o){if(!n)return null;let s;try{return await Promise.race([Promise.resolve().then(()=>n.getItem(o)),new Promise(c=>{s=setTimeout(()=>c(null),yI)})])}catch{return null}finally{clearTimeout(s)}}async function a(){try{let o=await i(`${e}:artifacts`);if(o&&o.length<=kh)return AI.parse(JSON.parse(o))}catch{}return{}}return{async readManifest(){return i(e)},writeManifest(o){Promise.resolve().then(()=>n?.setItem(e,o)).catch(()=>{})},async readArtifact(o){let s=(await a())[o];return s&&Date.now()>=s.at&&Date.now()-s.at<=Zt.retentionMs?s.text:void 0},writeArtifact(o,s){n&&(r=r.catch(()=>{}).then(async()=>{let c=await a(),u=Date.now();c[o]={at:u,text:s};let l={},m=2,S=0;for(let[y,p]of Object.entries(c).sort(([,g],[,f])=>f.at-g.at)){if(p.at>u||u-p.at>Zt.retentionMs)continue;let g=new TextEncoder().encode(JSON.stringify({[y]:p})).byteLength;m+g>kh||S>=128||(l[y]=p,m+=g,S++)}await n.setItem(`${e}:artifacts`,JSON.stringify(l))}).catch(()=>{}))}}}var _e=(e,t)=>new b(e,t),lr=()=>performance.now(),Th=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function xI(e){let t=Zc.parse(e.scope),n=new mn(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 _e("INVALID_URL","Configuration requires a trusted HTTPS origin");let r=new Set([n.origin,...(e.assetOrigins??[]).map(Y=>{let H=new mn(Y);if(H.protocol!=="https:"||H.username||H.password||H.search||H.hash||H.pathname!=="/")throw _e("INVALID_URL","Invalid configuration asset origin");return H.origin})]),i=e.fetch??globalThis.fetch.bind(globalThis),a=`/api/v1/configuration/${t.environmentId}`,o=`indiana:configuration:1:${n.origin}:${yt(t)}`,s=jh(o,e.storage),c,u=0,l=0,m=!1,S=!1,y=0,p=0,g,f,I,A,P=0,w=new Set,k=new Set,N=new Map,B=new Map,me=0,xe=!1;function Ce(){for(let Y of w)try{Y()}catch{}}function Ie(Y){try{e.onError?.(Y)}catch{}}let Fe=()=>!S&&!m&&!!c&&lr()<u&&Date.now()<l;function Ee(){if(!Fe())throw _e("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function zt(Y,H){let se=new TextEncoder().encode(H).byteLength;if(!N.has(Y)){for(;N.size&&(N.size>=128||me+se>Zt.maxCacheBytes);){let ce=N.entries().next().value;me-=new TextEncoder().encode(ce[1]).byteLength,N.delete(ce[0])}N.set(Y,H),me+=se}}function We(Y,H,se){return hh(Y,H,{signal:se,error:ce=>_e("INVALID_RESPONSE",ce==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function kt(Y){let H=new mn(Y,n);if(!r.has(H.origin)||H.username||H.password||H.hash||H.search)throw _e("INVALID_URL","Configuration artifact origin is not trusted");return H.href}async function Ao(Y,H,se=!1){let ce=await i(kt(Y),{method:"GET",credentials:"omit",redirect:"error",cache:se?"default":"no-cache",signal:H,headers:{}});if(ce.status===429){let Ne=ce.headers.get("retry-after")??"";P=/^\d+$/.test(Ne)?Number(Ne)*1e3:Math.max(0,Date.parse(Ne)-Date.now())||15e3}if(!ce.ok&&ce.status!==304)throw _e(`CONFIGURATION_HTTP_${ce.status}`,"Configuration synchronization failed");return ce}function qr(Y,H,se){let ce=Date.parse(Y.headers.get("x-indiana-config-validated-at")??""),Ne=Date.parse(Y.headers.get("x-indiana-config-valid-until")??""),wt=Date.parse(Y.headers.get("date")??""),Ke=Y.headers.get("age"),Yt=Ke!==null&&/^\d+(\.\d+)?$/.test(Ke)?Number(Ke)*1e3:NaN;if(![ce,Ne,wt,Yt].every(Number.isFinite)||Ne<=ce||Ne-ce>Zt.maxControlAgeMs||ce>wt+1e3)throw _e("INVALID_RESPONSE","Configuration freshness evidence is invalid");let Ot=Math.min(Ne-ce,se.maxControlAgeSeconds*1e3,Zt.maxControlAgeMs)-Math.max(Yt,wt-ce,0)-(lr()-H);if(Ot<=0)throw _e("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return lr()+Ot}function at(){if(clearTimeout(I),clearTimeout(A),S||!w.size)return;Fe()&&(A=setTimeout(()=>{Fe()?at():Ce()},Math.max(1,u-lr())),Th(A));let Y=p?Math.min(15e3,1e3*2**Math.min(p-1,4)):Math.min(15e3,(c?.policy.refreshIntervalSeconds??15)*1e3);I=setTimeout(()=>{$t().catch(Ie)},Math.max(P,Y*(.8+Math.random()*.2))),Th(I)}async function $t(){if(S)throw _e("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(g)return g;let Y=y,H=new AbortController;f=H;let se=(async()=>{if(!xe){xe=!0;try{let bo=await s.readManifest();if(bo&&!c){let jn=Yc.parse(JSON.parse(bo));yt(jn.scope)===yt(t)&&(c=jn)}}catch{}}H.signal.throwIfAborted();let Ke=c,Yt=lr(),Nt=await Ao(a,H.signal);Nt.status===304&&(!Ke||!Nt.headers.has("x-indiana-config-validated-at")||!Nt.headers.has("x-indiana-config-valid-until")||!Nt.headers.has("age"))&&(Nt=await Ao(a,H.signal));let Ot=Nt.status===304?Ke:Yc.parse(JSON.parse(await We(Nt,Zt.maxManifestBytes,H.signal))),{generation:zn,...$n}=Ot,mr=Nt.headers.get("etag");if(yt(Ot.scope)!==yt(t)||gf($n)!==zn||mr!==`"${zn}"`&&mr!==`W/"${zn}"`)throw _e("INVALID_RESPONSE","Configuration scope or content identity changed");if(Ke&&(Ot.revision<Ke.revision||Ot.revision===Ke.revision&&Ot.generation!==Ke.generation))throw _e("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[bo,jn]of Object.entries(Ke?.funnels??{})){let fr=Ot.funnels[bo];if(fr&&(fr.controlRevision<jn.controlRevision||fr.evaluationRevision<jn.evaluationRevision||fr.controlRevision===jn.controlRevision&&fr.state!==jn.state||fr.evaluationRevision===jn.evaluationRevision&&fr.evaluationMode!==jn.evaluationMode))throw _e("INVALID_RESPONSE","Funnel control revision changed identity")}let $u=qr(Nt,Yt,Ot.policy);if(H.signal.throwIfAborted(),Y!==y)throw _e("CONFIGURATION_DISPOSED","Configuration scope changed");return c=Ot,u=$u,l=Date.now()+Math.max(0,$u-lr()),m=!1,p=0,P=0,s.writeManifest(yt(Ot)),Ce(),structuredClone(Ot)})(),ce=setTimeout(()=>H.abort(_e("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Zt.initializationMs),Ne=new Promise((Ke,Yt)=>H.signal.addEventListener("abort",()=>Yt(H.signal.reason),{once:!0})),wt=Promise.race([se,Ne]).catch(Ke=>{throw p++,(Ke instanceof SI.ZodError||Ke instanceof SyntaxError||Ke instanceof b&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(Ke.code))&&(u=0,m=!0,Ce()),Ke}).finally(()=>{clearTimeout(ce),g===wt&&(g=void 0),at()});return g=wt,wt}async function dr(Y){let H=Y.sha256,se=zn=>ts(zn,Y);kt(Y.url);let ce=N.get(H);if(ce&&se(ce))return N.delete(H),N.set(H,ce),ce;if(B.has(H))return B.get(H);let Ne=new AbortController;k.add(Ne);let wt=y,Ke=(async()=>{try{let mr=await s.readArtifact(H);if(mr&&se(mr))return zt(H,mr),mr}catch{}Ne.signal.throwIfAborted();let zn=await Ao(Y.url,Ne.signal,!0),$n=await We(zn,Y.byteLength,Ne.signal);if(!se($n))throw _e("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(S||wt!==y)throw _e("CONFIGURATION_DISPOSED","Configuration scope changed");return zt(H,$n),s.writeArtifact(H,$n),$n})(),Yt=setTimeout(()=>Ne.abort(_e("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),Zt.initializationMs),Nt=new Promise((zn,$n)=>Ne.signal.addEventListener("abort",()=>$n(Ne.signal.reason),{once:!0})),Ot=Promise.race([Ke,Nt]).finally(()=>{clearTimeout(Yt),k.delete(Ne),B.delete(H)});return B.set(H,Ot),Ot}async function pr(){return Fe()||await $t(),Ee(),c}async function vi(Y){let H,se=new Promise((ce,Ne)=>{H=setTimeout(()=>Ne(_e("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Zt.initializationMs)});try{return await Promise.race([Y(),se])}finally{clearTimeout(H)}}function wi(Y,H){if(Ee(),c?.generation!==Y.generation)throw _e("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(H&&c.funnels[H]?.state!=="active")throw _e("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Bu(Y){let H=Y.gb.features;if(!H)throw _e("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let se=Y.artifacts[H];if(se.formatVersion!==1)throw _e("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let ce=Ic.parse(JSON.parse(await dr(se)));if(yt(ce.scope)!==yt({projectId:t.projectId,environment:t.environment})||ce.generation!==se.generation||ce.remoteFeatures.some(Ne=>Object.hasOwn(ce.features,Ne)))throw _e("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return wi(Y),{...ce,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,u-lr())).toISOString()}}async function Uu(Y,H){let se=await pr(),ce=se.funnels[Y];H&&(!ce||ce.evaluationMode==="local"&&!ce.versions[H])&&(g&&await g,se=await $t()),wi(se,Y);let Ne=se.funnels[Y];if(Ne.evaluationMode!=="local")throw _e("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let wt=H??Ne.currentVersionId,Ke=Ne.versions[wt];if(!Ke)throw _e("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(se.artifacts[Ke.artifact].formatVersion!==3)throw _e("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[Yt,Nt]=await Promise.all([dr(se.artifacts[Ke.artifact]).then(Ot=>Af(JSON.parse(Ot))),Ne.evaluationMode==="local"?Bu(se):void 0]);if(Nt&&yt(hf(Yt,Nt))!==yt(Ke.dependencies))throw _e("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return wi(se,Y),{document:Yt,growth:Nt,versionId:wt,control:structuredClone(Ne),manifest:structuredClone(se)}}async function Lu(Y,H){try{return await Uu(Y,H)}catch(se){if(!(se instanceof b)||!(se.code==="CONFIGURATION_CHANGED"||se.code==="CONFIGURATION_HTTP_404"&&Fe()))throw se;let ce=c?.generation;if(g&&await g,await $t(),se.code!=="CONFIGURATION_CHANGED"&&c?.generation===ce)throw se;return Uu(Y,H)}}function is(){m=!0,Ce(),$t().catch(Ie)}let yo=()=>{(typeof document>"u"||document.visibilityState==="visible")&&is()};function Nh(Y){if(S)throw _e("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return w.add(Y),w.size===1&&(typeof window<"u"&&(window.addEventListener("online",is),window.addEventListener("focus",yo),document.addEventListener("visibilitychange",yo)),at()),()=>{w.delete(Y),w.size||(clearTimeout(I),clearTimeout(A),zu())}}function zu(){typeof window<"u"&&(window.removeEventListener("online",is),window.removeEventListener("focus",yo),document.removeEventListener("visibilitychange",yo))}return{scope:Object.freeze({...t}),refresh:$t,subscribe:Nh,assertFresh:Ee,assertFeatures(Y){Ee();let H=c.gb.features;if(!H)throw _e("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(Y!==void 0&&c.artifacts[H].generation!==Y)throw _e("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return Fe()},get snapshot(){return c?structuredClone(c):null},get remainingMs(){return Fe()?Math.max(0,u-lr()):0},async features(){return vi(async()=>Bu(await pr()))},pageExperiments:()=>vi(async()=>{let Y=await pr(),H=Y.gb.pageExperiments;if(!H)throw _e("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let se=Y.artifacts[H];if(se.formatVersion!==1)throw _e("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let ce=xg.parse(JSON.parse(await dr(se)));if(ce.environmentId!==t.environmentId||ce.generation!==se.generation)throw _e("INVALID_RESPONSE","Page experiment scope or generation changed");return wi(Y),ce}),funnel:(Y,H)=>vi(()=>Lu(Y,H)),paywall:(Y,H)=>vi(async()=>{let se=await pr(),ce=se.paywalls?.[Y];if(!ce||!H&&ce.state!=="published")throw _e("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let Ne=H??ce.currentVersionId,wt=ce.versions[Ne],Ke=wt&&se.artifacts[wt.artifact];if(!Ke||Ke.kind!=="paywall"||Ke.formatVersion!==1)throw _e("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let Yt=Ua.parse(JSON.parse(await dr(Ke)));return wi(se),{document:Yt,versionId:Ne,version:wt.version,control:structuredClone(ce),manifest:structuredClone(se)}}),async localFunnel(Y,H){let se=await vi(()=>Lu(Y,H));if(!se.growth)throw _e("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:ce,remoteFeatures:Ne,...wt}=se.growth;return bg({scope:{projectId:t.projectId,environment:t.environment},funnelId:Y,versionId:se.versionId,evaluationMode:"local",evaluationRevision:se.control.evaluationRevision,document:se.document,payload:wt})},assertFunnel(Y,H,se){Ee();let ce=c.funnels[Y];if(!ce||ce.state!=="active")throw _e("FUNNEL_STOPPED","Funnel is paused or unavailable");if(ce.evaluationMode!=="local")throw _e("EVALUATION_MODE","This Funnel now executes at Longplay");if(H!==void 0&&ce.controlRevision!==H)throw _e("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(se!==void 0&&!ce.versions[se])throw _e("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!S){S=!0,y++,u=0,f?.abort(_e("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(I),clearTimeout(A),zu(),Ce(),w.clear();for(let Y of k)Y.abort(_e("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));N.clear(),me=0}}}}async function II(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&&yt(n)!==yt(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=xi.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=es({...e,scope:n,apiKey:e.credential}),o=s=>{let c=Ii({...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}}}}export{b as LongplayError,xI as createConfigurationSync,Mu as createFeatureClient,II as createLocalFunnelClient,hI as createLongplayReactNative};
|