@tinkerlandai/longplay-react-native 0.10.16-rc.1 → 0.10.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js
CHANGED
|
@@ -14,4 +14,4 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
|
14
14
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
15
15
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
16
16
|
SOFTWARE.
|
|
17
|
-
*/var ve=N.json().superRefine((e,t)=>{let n=0;function r(i,a){if(++n>1e4||a>20){t.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof i=="string"&&(i.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(i))&&t.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(i))i.forEach(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))(o.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(o)||["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved JSON property"}),r(s,a+1)}r(e,0),new TextEncoder().encode(JSON.stringify(e)).byteLength>65536&&t.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),vt=N.record(N.string().min(1).max(128),ve).superRefine((e,t)=>{(!ve.safeParse(e).success||Object.keys(e).length>128||new TextEncoder().encode(JSON.stringify(e)).byteLength>65536||["__proto__","constructor","prototype"].some(n=>Object.hasOwn(e,n)))&&t.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),bA=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),Yt=vt.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("$")&&!bA.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)}),xA=N.discriminatedUnion("type",[N.strictObject({type:N.literal("condition"),condition:Yt}),N.strictObject({type:N.literal("list"),attributeKey:N.string().min(1).max(128),values:N.array(N.union([N.string(),N.number().finite()])).max(1e5)})]).refine(e=>e.type!=="list"||new TextEncoder().encode(JSON.stringify(e.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function Kn(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 SA=N.record(N.uuid(),xA).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"&&Kn(o.condition).forEach(i),n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),rc=N.tuple([N.number().min(0).max(1),N.number().min(0).max(1)]).refine(([e,t])=>e<=t),Dd=N.strictObject({attribute:N.string().optional(),seed:N.string().min(1),hashVersion:N.literal(2),ranges:N.array(rc).min(1).max(100)}),IA=N.strictObject({id:N.string().min(1).max(128),condition:Yt,gate:N.boolean().optional()}),nc={id:N.string().max(128).optional(),condition:Yt.optional(),parentConditions:N.array(IA).max(50).optional(),filters:N.array(Dd).max(20).optional()},vA=N.union([N.strictObject({...nc}),N.strictObject({...nc,force:ve,coverage:N.number().min(0).max(1).optional(),range:rc.optional(),seed:N.string().min(1).optional(),hashAttribute:N.string().optional(),hashVersion:N.literal(2).optional()}),N.strictObject({...nc,type:N.literal("experiment-ref"),experimentId:N.uuid(),values:N.record(N.string().min(1),ve),meta:N.record(N.string().min(1),N.strictObject({passthrough:N.boolean()})).optional()})]),wA=N.strictObject({defaultValue:ve,rules:N.array(vA).max(100)}),oO=N.record(N.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),wA).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)}),OA=N.strictObject({name:N.string().max(80),reason:N.string().max(500),dateStarted:N.iso.datetime({offset:!0}),dateEnded:N.iso.datetime({offset:!0}).nullable(),coverage:N.number().min(0).max(1),variationWeights:N.array(N.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:Yt,savedGroups:N.array(N.strictObject({match:N.enum(["any","all","none"]),ids:N.array(N.uuid()).min(1)})).max(50),namespace:N.strictObject({id:N.uuid(),ranges:N.array(rc).min(1)}).nullable(),seed:N.string().min(1).max(128)}),PA=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(OA).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 CA=PA.safeExtend({filters:N.array(Dd).optional()}),_A=N.strictObject({experiments:N.record(N.uuid(),CA),savedGroups:SA}),$i=N.strictObject({attributeName:N.string(),attributeValue:N.string(),assignments:N.record(N.string(),N.string())}),aO=N.strictObject({snapshot:_A,attributes:vt,results:vt,stickyBucketAssignmentDocs:N.record(N.string(),$i)}),sO=N.strictObject({variantKey:N.string().nullable(),bucketVersion:N.number().int().min(0),source:N.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:N.number().min(0).max(1).optional(),stickyBucketUsed:N.boolean().optional(),hashUsed:N.boolean().optional()});function er(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 EA=Tt.enum(["active","inactive"]),RA=Tt.preprocess((e,t)=>{let n=0;function r(i,a){if(!(++n>1e4||a>20)){if(Array.isArray(i))i.forEach(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))["__proto__","constructor","prototype"].includes(o)&&t.addIssue({code:"custom",message:"Reserved merchandise attribute"}),r(s,a+1)}}return r(e,0),e},vt),kA=Tt.strictObject({id:Tt.string().trim().min(1).max(255),name:Tt.string().trim().min(1).max(255),status:EA,metadata:RA}),mO=kA.extend({internal_id:Tt.uuid(),project_id:Tt.uuid(),environment_id:Tt.uuid(),created_at:Tt.iso.datetime({offset:!0}),updated_at:Tt.iso.datetime({offset:!0})}),Md=Tt.union([Tt.strictObject({id:Tt.string().trim().min(1).max(255)}),Tt.strictObject({internalId:Tt.uuid()})]),fO=Tt.enum(["customer","merchandise","context"]),gO=Tt.enum(["system","stored","request"]),hO=Tt.enum(["customer","merchandise","mixed"]),Fd=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function ic(e,t={},n=new Set){if(er(e).some(Fd))return!0;for(let r of Kn(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&Fd(i.attributeKey)||i?.type==="condition"&&ic(i.condition,t,n))return!0}return!1}import{z as jA}from"zod";var TA=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,Sn=jA.string().max(16).regex(TA,"\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 wO=te.enum(["draft","active","paused","archived"]),tr=te.discriminatedUnion("type",[te.object({type:te.literal("percent"),percentOff:te.number().min(1).max(100).multipleOf(.01)}).strict(),te.object({type:te.literal("amount"),amountOffCents:te.number().int().min(1).max(1e8),currency:Ie}).strict()]),an=te.discriminatedUnion("type",[te.object({type:te.literal("once")}).strict(),te.object({type:te.literal("repeating"),months:te.number().int().min(1).max(36)}).strict(),te.object({type:te.literal("forever")}).strict()]),qd=[te.object({type:te.literal("all")}).strict(),te.object({type:te.literal("plans"),planIds:te.array(te.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],NA=te.discriminatedUnion("type",[...qd,te.strictObject({type:te.literal("merchandise"),scope:te.discriminatedUnion("type",[te.strictObject({type:te.literal("all")}),te.strictObject({type:te.literal("selected"),merchandiseIds:te.array(te.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),te.strictObject({type:te.literal("condition"),condition:Yt})])})]),oc=te.discriminatedUnion("type",[...qd,te.strictObject({type:te.literal("merchandise"),scope:te.strictObject({type:te.enum(["all","selected","condition"])})})]),DA=te.strictObject({firstPurchaseOnly:te.boolean(),condition:Yt}),OO=te.object({name:te.string().trim().min(1).max(80),description:te.string().max(500),discount:tr,duration:an,appliesTo:NA,eligibility:DA,selfClaimEnabled:te.boolean().default(!1),startsAt:te.iso.datetime().nullable(),endsAt:te.iso.datetime().nullable(),totalLimit:te.number().int().min(1).max(1e6).nullable(),perCustomerLimit:te.number().int().min(1).max(10),grantWindowHours:te.number().int().min(1).max(2160)}).strict().refine(e=>!e.startsAt||!e.endsAt||Date.parse(e.endsAt)>Date.parse(e.startsAt),{message:"\u7ED3\u675F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u5F00\u59CB\u65F6\u95F4",path:["endsAt"]}).refine(e=>!ic(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"]}),PO=te.object({code:te.string().trim().transform(e=>e.toUpperCase()).pipe(te.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/,"\u4F18\u60E0\u7801\u53EA\u80FD\u7528 3\u201332 \u4F4D\u5B57\u6BCD\u3001\u6570\u5B57\u3001- \u548C _\uFF0C\u4EE5\u5B57\u6BCD\u6216\u6570\u5B57\u5F00\u5934")),maxRedemptions:te.number().int().min(1).max(1e6).nullable(),expiresAt:te.iso.datetime().nullable(),firstPurchaseOnly:te.boolean(),minimumAmountCents:te.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:Ie.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var Gi=te.object({id:te.uuid(),couponId:te.uuid(),status:te.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:te.iso.datetime(),expiresAt:te.iso.datetime(),coupon:te.object({name:te.string(),discount:tr,duration:an,appliesTo:oc}).strict()}).strict(),Ud=te.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var $d=S.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),ac=S.string().regex(/^(0|[1-9]\d{0,14})$/),oi=S.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),FA=S.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),Ki=FA,Hn=xe.refine(e=>/[1-9]/.test(e)),zt=S.iso.datetime({offset:!0}),ca=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"))},MA=S.array(S.object({upTo:Hn.nullable(),unitAmountMinor:$d,flatAmountMinor:S.number().int().min(0).max(1e8).optional()}).strict()).min(1).max(12).refine(e=>{try{return e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let r=e[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&ca(t.upTo)>ca(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),qA=S.discriminatedUnion("kind",[S.object({kind:S.literal("flat"),units:Hn,unitAmountMinor:$d}).strict(),S.object({kind:S.enum(["graduated","volume"]),units:Hn,tiers:MA}).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"),UA=S.strictObject({interval:S.enum(["month","year"]),count:S.number().int().min(1).max(12),anchor:S.enum(["membership","calendar"])}),Hi=S.object({currency:Ie,pricing:qA,billingCycle:UA.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var Bd={requestId:S.uuid(),productVersionId:S.uuid(),internal_feature_id:S.uuid(),currency:Ie},Gd=S.strictObject({interval:S.enum(["hour","day","week","month"]),intervalCount:S.number().int().min(1).max(12),limit:S.number().int().min(1).max(1e6)}),Kd=S.discriminatedUnion("kind",[S.object({...Bd,kind:S.literal("auto_topup"),threshold:Jo,quantity:Hn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Gd.optional()}).strict(),S.object({...Bd,kind:S.literal("postpaid"),maxAmountMinorPerPeriod:Ki,maxOutstandingMinor:Ki}).strict()]),Vd={productVersionId:S.uuid(),internal_feature_id:S.uuid(),currency:Ie},Hd=S.discriminatedUnion("kind",[S.object({...Vd,kind:S.literal("auto_topup"),threshold:Jo,quantity:Hn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Gd.optional(),purchaseAmountMinor:Ki,purchaseUnits:Hn}).strict(),S.object({...Vd,kind:S.literal("postpaid"),maxAmountMinorPerPeriod:Ki,maxOutstandingMinor:Ki,cashPrice:Hi}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),ua=S.object({id:S.uuid(),terms:Hd,status:S.enum(["prepared","active","revoked","blocked"]),createdAt:zt,acceptedAt:zt.nullable(),effectiveAt:zt.nullable(),revokedAt:zt.nullable()}).strict().refine(e=>(e.status==="prepared"?e.acceptedAt===null:!0)&&(e.status==="active"?e.acceptedAt!==null&&e.effectiveAt!==null:!0)&&(e.status==="revoked"?e.revokedAt!==null:e.revokedAt===null),"Authorization consent and revocation must be explicit"),Qd=S.object({authorizationId:S.uuid(),terms:Hd,setupUrl:S.url().nullable()}).strict(),Jd=S.object({authorizationId:S.uuid(),accepted:S.literal(!0)}).strict(),Zd=S.object({authorizationId:S.uuid(),requestId:S.uuid()}).strict(),Wd=S.object({internal_feature_id:S.uuid(),entityId:S.uuid().nullable(),interval:S.enum(["day","week","month","year"]),anchor:S.enum(["billing_cycle","utc"]).optional(),basis:S.enum(["usage","credits"]),filter:It.optional(),limit:xe.nullable(),thresholds:S.array(S.number().positive().max(1)).max(8),includedThresholds:S.array(S.number().positive().max(1)).max(8).optional(),absoluteThresholds:S.array(Hn).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&&ca(t)>ca(i)}),"Notification thresholds must increase"),BA=Wd.safeExtend({requestId:S.uuid()}),Ld={control:S.literal("overage"),requestId:S.uuid(),internal_feature_id:S.uuid(),entityId:S.uuid().nullable()},VA=S.discriminatedUnion("action",[S.strictObject({...Ld,action:S.literal("set"),allowed:S.boolean().nullable(),overageLimit:xe.nullable(),skipOverageBilling:S.boolean()}),S.strictObject({...Ld,action:S.literal("remove")})]),Yd=S.union([BA,VA]),LA=S.strictObject({internal_feature_id:S.uuid(),entityId:S.uuid().nullable(),allowed:S.boolean().nullable(),overageLimit:xe.nullable(),skipOverageBilling:S.boolean(),interval:S.enum(["day","week","month","year"]),startsAt:zt,endsAt:zt,used:S.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:S.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:S.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),zA=S.object({internal_feature_id:S.uuid(),entityId:S.uuid().nullable(),interval:S.enum(["day","week","month","year"]),anchor:S.enum(["billing_cycle","utc"]).optional(),basis:S.enum(["usage","credits"]),filter:It.optional(),startsAt:zt,endsAt:zt,used:Wt,reserved:Wt,limit:xe.nullable(),thresholds:S.array(S.number().positive().max(1)).max(8),notifiedThresholds:S.array(S.number().positive().max(1)).max(1024),includedThresholds:S.array(S.number().positive().max(1)).max(8).optional(),includedAllowance:S.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:S.array(S.number().positive().max(1)).max(1024).optional(),absoluteThresholds:S.array(Hn).max(8).optional(),notifiedAbsoluteThresholds:S.array(Hn).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||xe.safeParse(e.used).success&&xe.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),$A=S.object({authorizationId:S.uuid(),status:S.enum(["idle","pending","blocked"]),taskId:S.uuid().nullable(),invoiceId:S.uuid().nullable(),hostedInvoiceUrl:S.url().nullable(),purchaseCount:S.number().int().nonnegative(),purchaseWindowEndsAt:zt.nullable(),attemptCount:S.number().int().nonnegative(),failedAttemptCount:S.number().int().nonnegative(),suspendedAt:zt.nullable(),nextAttemptAt:zt.nullable(),failureReason:S.string().min(1).max(240).nullable()}).strict(),Xd=S.object({internal_feature_id:S.uuid().optional(),entityId:S.uuid().optional()}).strict(),sc=S.object({authorizations:S.array(ua).max(100),limits:S.array(Wd).max(100),overages:S.array(LA).max(100).optional(),windows:S.array(zA).max(200),autoTopups:S.array($A).max(100),limited:S.boolean()}).strict(),GA=S.object({id:S.uuid(),internal_feature_id:S.uuid(),productVersionId:S.uuid(),authorizationId:S.uuid(),entityId:S.uuid().nullable(),units:xe,amountMinor:oi,cashPrice:Hi}).strict(),Qi=S.object({id:S.uuid(),sourceKind:S.enum(["product","usage","manual"]),providerInvoiceId:S.string().min(1).max(240).nullable(),status:S.enum(["accruing","open","pending","paid","failed","void"]),currency:Ie,startsAt:zt.nullable(),endsAt:zt.nullable(),amountMinor:S.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:S.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:ac,paidAmountMinor:ac,refundedAmountMinor:ac,createdAt:zt,hostedInvoiceUrl:S.url().nullable(),adjustment:S.object({originalInvoiceId:S.uuid(),amountMinor:S.string().regex(/^-?(0|[1-9]\d{0,8})$/).refine(e=>e!=="-0"&&/^-?(0|[1-9]\d{0,8})$/.test(e)&&BigInt(e)>=-200000000n&&BigInt(e)<=200000000n,"Invoice adjustment exceeds the bounded minor amount"),acceptedAt:zt.nullable(),reason:S.string().min(1).max(500).optional()}).strict().nullable(),lines:S.array(GA).max(100),linesLimited:S.boolean()}).strict(),ep=S.object({invoiceId:S.uuid(),accepted:S.literal(!0)}).strict(),tp=S.strictObject({requestId:S.uuid(),originalInvoiceId:S.uuid(),amountMinor:S.string().regex(/^[1-9]\d{0,8}$/).refine(e=>/^[1-9]\d{0,8}$/.test(e)&&BigInt(e)<=200000000n,"Supplemental amount exceeds the bounded minor amount"),reason:S.string().trim().min(1).max(500)}),np=S.object({after:S.uuid().nullable(),limit:S.number().int().min(1).max(100)}).strict(),rp=S.object({rows:S.array(Qi).max(100),nextCursor:S.uuid().nullable()}).strict(),zd=S.strictObject({id:S.string(),coupon:S.string(),start:S.number().nonnegative(),end:S.number().nullable()}),KA=S.strictObject({subscriptionId:S.string(),customerId:S.string(),accountId:S.string(),sourceItems:S.array(S.strictObject({id:S.string(),price_id:S.string(),quantity:S.number().int(),discounts:S.array(zd).optional()})).max(100),items:S.array(S.strictObject({id:S.string(),price:S.string(),quantity:S.number().int(),discounts:S.array(S.strictObject({coupon:S.string().optional(),terms:S.strictObject({id:S.string(),name:S.string().optional(),percent_off:S.number().optional(),amount_off:S.number().optional(),currency:S.string().optional(),duration:S.enum(["once","forever","repeating"]),duration_in_months:S.number().optional()}).optional(),discount:S.string().optional(),receipt:zd.optional()})).max(20)})).max(100)}),ip=S.strictObject({membershipId:S.uuid(),requestId:S.uuid(),grantIds:S.array(S.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),op=S.strictObject({membershipId:S.uuid(),operationId:S.uuid(),status:S.enum(["pending","effective"]),execution:KA.nullable(),grants:S.array(S.strictObject({id:S.uuid(),couponId:S.uuid(),name:S.string(),discount:tr,duration:an,startedAt:zt.nullable()})).max(20)});import{z as Ji}from"zod";var ap=Ji.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),sp=Ji.number().int().min(1).max(1e3),la=Ji.object({cap:xe.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:Ji.number().positive().max(1e4).nullable(),cycles:Ji.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");import{z as nr}from"zod";var cp=nr.strictObject({itemKey:nr.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:nr.uuid(),includedAmount:nr.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:nr.number().int().min(0).max(1e4),terms:Wo,pricing:Vi.optional(),unitAmountMinor:nr.number().int().min(0).max(1e8),productId:nr.string().min(1).max(255).nullable(),priceId:nr.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{ed(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 ne}from"zod";var Pr=xe.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Zi=ne.string().min(1).max(120),da=ne.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"))},Wi=e=>{try{return e()}catch{return!1}},Yi=ne.discriminatedUnion("operation",[ne.object({operation:ne.literal("quote"),overageBehavior:da.optional(),internal_feature_id:ne.uuid(),entityId:ne.uuid().optional(),quantity:Pr,properties:It}).strict(),ne.object({operation:ne.literal("consume"),overageBehavior:da.optional(),occurredAt:ne.iso.datetime({offset:!0}).optional(),internal_feature_id:ne.uuid(),entityId:ne.uuid().optional(),quantity:xe,properties:It,idempotencyKey:Zi}).strict(),ne.object({operation:ne.literal("reserve"),occurredAt:ne.iso.datetime({offset:!0}).optional(),internal_feature_id:ne.uuid(),entityId:ne.uuid().optional(),quantity:Pr,properties:It,idempotencyKey:Zi,expiresInSeconds:ne.number().int().min(1).max(86400)}).strict(),ne.object({operation:ne.literal("confirm"),operationId:ne.uuid(),quantity:Pr,properties:It.optional(),idempotencyKey:Zi}).strict(),ne.object({operation:ne.literal("refund"),operationId:ne.uuid(),quantity:Pr,idempotencyKey:Zi}).strict(),ne.object({operation:ne.literal("release"),operationId:ne.uuid(),idempotencyKey:Zi}).strict()]),cc=ne.object({internal_credit_feature_id:ne.uuid().nullable(),internal_metered_feature_id:ne.uuid(),dimension:ne.string().min(1).max(64),counterKey:ne.string().min(1).max(240),cycleStart:ne.iso.datetime({offset:!0}),unitCost:xe,units:Pr,amount:Wt,tier:ne.number().int().min(1).max(12).nullable()}).strict(),Cr=ne.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function up(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 lp=ne.discriminatedUnion("funding",[ne.strictObject({funding:ne.literal("balance"),sourceId:ne.uuid(),rolloverId:ne.uuid().nullable(),units:Cr.refine(e=>/[1-9]/.test(e)),amount:Wt}),ne.strictObject({funding:ne.literal("unbilled"),units:Cr.refine(e=>/[1-9]/.test(e))}),ne.object({funding:ne.literal("prepaid"),sourceId:ne.uuid(),units:Pr,amount:Wt,pricing:ne.array(cc).min(1).max(12)}).strict().refine(e=>Wi(()=>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"),ne.object({funding:ne.literal("postpaid"),invoiceLineId:ne.uuid().nullable(),units:Pr,authorizationId:ne.uuid()}).strict()]),pa=ne.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),dp=ne.object({allowed:ne.boolean(),internal_feature_id:ne.uuid(),quantity:xe,requestedQuantity:xe.optional(),overageBehavior:da.optional(),reason:pa.nullable(),allocations:ne.array(lp).max(500)}).strict().refine(e=>Wi(()=>e.allowed?e.reason===null&&up(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>Wi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&sn(e.requestedQuantity,6)>=sn(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Xi=ne.object({id:ne.uuid(),internal_feature_id:ne.uuid(),kind:ne.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:ne.uuid().nullable(),quantity:xe,requestedQuantity:xe.optional(),overageBehavior:da.optional(),accepted:ne.boolean(),reason:ne.enum([...pa.options,"expired"]).nullable(),createdAt:ne.iso.datetime({offset:!0}),reservationStatus:ne.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:ne.iso.datetime({offset:!0}).nullable(),allocations:ne.array(lp).max(500)}).strict().refine(e=>Wi(()=>e.accepted?e.reason===null&&up(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>Wi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&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 Ne}from"zod";var _r=Ne.iso.datetime({offset:!0}),pp=xe.refine(e=>/[1-9]/.test(e)),mp=Ne.strictObject({interval:ap.exclude(["lifetime"]),count:sp}),HA=Ne.strictObject({action:Ne.literal("create"),requestId:Ne.uuid(),internal_feature_id:Ne.uuid(),entityId:Ne.uuid().nullable(),amount:pp.nullable(),expiresAt:_r.nullable(),reset:mp.nullable(),rollover:la.nullable(),nextResetAt:_r.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"),fp=Ne.discriminatedUnion("action",[HA,Ne.strictObject({action:Ne.literal("update"),requestId:Ne.uuid(),grantId:Ne.uuid(),revision:Ne.number().int().nonnegative(),amount:pp.nullable(),expiresAt:_r.nullable(),rollover:la.nullable(),nextResetAt:_r.nullable()}),Ne.strictObject({action:Ne.enum(["add","subtract","set_remaining"]),requestId:Ne.uuid(),grantId:Ne.uuid(),revision:Ne.number().int().nonnegative(),amount:xe}),Ne.strictObject({action:Ne.literal("revoke"),requestId:Ne.uuid(),grantId:Ne.uuid(),revision:Ne.number().int().nonnegative()})]),uc=Ne.strictObject({id:Ne.uuid(),internal_feature_id:Ne.uuid(),entityId:Ne.uuid().nullable(),amount:xe.nullable(),reset:mp.nullable(),rollover:la.nullable(),nextResetAt:_r.nullable(),startsAt:_r,expiresAt:_r.nullable(),revision:Ne.number().int().nonnegative(),revoked:Ne.boolean(),available:Wt,held:Wt,spent:Wt}),gp=Ne.strictObject({customerId:Ne.uuid(),after:Ne.uuid().nullable(),limit:Ne.number().int().min(1).max(100)}),hp=Ne.strictObject({rows:Ne.array(uc).max(100),nextCursor:Ne.uuid().nullable()});import{z as ie}from"zod";var Nn=ie.iso.datetime({offset:!0}),yp=ie.strictObject({invoiceId:ie.uuid(),after:ie.string().min(1).max(180).nullable(),limit:ie.number().int().min(1).max(100)}),QA=ie.strictObject({kind:ie.literal("product"),key:ie.string(),productVersionId:ie.uuid(),productName:ie.string(),itemKey:ie.string(),entityId:ie.uuid().nullable(),quantity:ie.number().positive(),subtotalMinor:ie.string().regex(/^-?\d+$/),discountMinor:ie.string().regex(/^\d+$/),taxMinor:ie.string().regex(/^-?\d+$/).nullable(),totalMinor:ie.string().regex(/^-?\d+$/),startsAt:Nn.nullable(),endsAt:Nn.nullable(),providerLineId:ie.string().nullable(),providerItemId:ie.string()}),Ap=ie.strictObject({invoice:Qi,items:ie.array(ie.discriminatedUnion("kind",[QA,ie.strictObject({kind:ie.literal("invoice_credit"),key:ie.string(),internal_feature_id:ie.uuid(),internal_credit_feature_id:ie.uuid(),name:ie.string(),units:xe,reserved:xe,amountMinor:oi,grossAmountMinor:oi,creditsAppliedMinor:oi,properties:It,cashPrice:Hi,providerItemId:ie.string().nullable(),creditProviderItemId:ie.string().nullable()}),ie.strictObject({kind:ie.literal("usage"),key:ie.string(),internal_feature_id:ie.uuid(),name:ie.string(),units:xe,reserved:xe,amountMinor:oi,cashPrice:Hi})])).max(100),nextCursor:ie.string().min(1).max(180).nullable()}),JA=ie.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),lc=ie.strictObject({from:Nn,to:Nn,entityId:ie.uuid().optional(),snapshotAt:Nn.nullable(),after:ie.strictObject({at:Nn,id:ie.uuid(),position:ie.number().int().nonnegative()}).nullable(),limit:ie.number().int().min(1).max(100)}).refine(e=>Date.parse(e.from)<Date.parse(e.to)&&Date.parse(e.to)-Date.parse(e.from)<=366*864e5,"Statement range must be positive and at most 366 days").refine(e=>e.after===null||e.snapshotAt!==null,"A cursor requires the original snapshot time"),bp=ie.strictObject({customerId:ie.uuid(),entityId:ie.uuid().nullable(),from:Nn,to:Nn,snapshotAt:Nn,totals:ie.array(ie.strictObject({internal_credit_feature_id:ie.uuid(),name:ie.string(),consumed:Wt,refunded:Wt,net:JA})).max(1e3),rows:ie.array(ie.strictObject({operationId:ie.uuid(),position:ie.number().int().nonnegative(),kind:ie.enum(["consume","confirm","refund"]),originalId:ie.uuid().nullable(),occurredAt:Nn,internal_feature_id:ie.uuid(),entitlementName:ie.string(),sourceId:ie.uuid(),internal_credit_feature_id:ie.uuid(),creditName:ie.string(),units:Cr,amount:Wt,pricing:ie.array(cc).max(12),properties:It})).max(100),nextCursor:lc.shape.after});import{z as D}from"zod";import{z as In}from"zod";var ZA=In.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),WA=In.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),ma=In.strictObject({internal_feature_id:In.uuid(),entityId:In.uuid().nullable()}),xp=ma.extend({quantity:xe,expectedRevision:In.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:In.string().min(1).max(120),properties:It.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),eo=ma.extend({operationId:In.uuid().nullable(),usage:xe,capacity:ZA.nullable(),remaining:WA.nullable(),withinLimit:In.boolean(),revision:In.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:In.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let n=r=>{let i=r.startsWith("-"),[a,o=""]=(i?r.slice(1):r).split(".");if(a===void 0||a==="")throw new Error("Invalid decimal value");return(i?-1n:1n)*(BigInt(a)*10n**12n+BigInt(o.padEnd(12,"0")))};(e.capacity===null!=(e.remaining===null)||(e.capacity===null?!e.withinLimit:e.remaining===null||n(e.remaining)!==n(e.capacity)-n(e.usage)||e.withinLimit!==n(e.remaining)>=0n)||e.revision===0!=(e.operationId===null)||e.operationId===null!=(e.updatedAt===null))&&t.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var $t=D.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),vn=D.iso.datetime({offset:!0}),YA=D.enum(["access","metered","credit"]),to={internal_feature_id:D.uuid(),key:wr,name:D.string().min(1).max(120),kind:YA},Sp=D.object({customerId:D.uuid(),snapshotAt:vn,memberships:D.array(D.object({id:D.uuid(),productId:D.string().min(1).max(255),productVersionId:D.uuid(),billingProductVersionId:D.uuid(),version:D.number().int().positive(),key:D.string().min(1).max(64),name:D.string().min(1).max(120),groupId:D.string().max(255).nullable(),membershipType:D.enum(["main","addon"]),status:D.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:D.boolean(),accessEnabled:D.boolean(),renewalChange:D.object({productVersionId:D.uuid(),name:D.string().min(1).max(120),version:D.number().int().positive(),effectiveAt:vn,benefitsAppliedAt:vn.nullable(),timing:D.enum(["immediate","renewal"]),changeKind:D.enum(["plan","seats","quantity"]),feature:D.strictObject({internal_feature_id:D.uuid(),name:D.string().min(1).max(80),fromQuantity:D.number().int().min(0).max(1e4),toQuantity:D.number().int().min(0).max(1e4)}).optional(),seat:D.object({key:D.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:D.number().int().min(0).max(1e4),toQuantity:D.number().int().min(0).max(1e4)}).strict().nullable(),status:D.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(e=>e.changeKind==="seats"==(e.seat!==null)&&e.changeKind==="quantity"==(e.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:D.object({phase:D.enum(["paid","trial"]),startsAt:vn,endsAt:vn.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:D.boolean(),balances:D.array(D.object({...to,usageType:D.enum(["consumable","non_consumable"]).nullable(),accessible:D.boolean(),unlimited:D.boolean(),available:$t,held:$t,debt:$t,nextExpiresAt:vn.nullable(),usage:eo.nullable()}).strict().refine(e=>e.kind==="metered"==(e.usageType!==null)&&(e.accessible||e.available==="0"&&e.held==="0")&&(e.usageType==="non_consumable"?e.usage!==null&&e.usage.internal_feature_id===e.internal_feature_id&&e.unlimited===(e.usage.capacity===null)&&e.available===(e.usage.remaining===null||e.usage.remaining.startsWith("-")?"0":e.usage.remaining)&&e.held==="0"&&e.debt==="0":e.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:D.boolean()}).strict(),Ip=D.enum(["source","usage","transaction","invoice","debt","settlement"]),fa=D.object({at:vn,id:D.uuid(),type:Ip}).strict(),vp=D.object({type:Ip.nullable(),resourceKey:wr.optional(),kind:D.enum(["purchase","refund"]).optional(),topup:D.boolean().optional(),from:D.iso.date().nullable(),to:D.iso.date().nullable(),after:fa.nullable(),limit:D.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),ai={id:D.uuid(),occurredAt:vn},XA=D.discriminatedUnion("type",[D.strictObject({...ai,type:D.literal("invoice"),status:D.string().min(1).max(80),paid:$t,refunded:$t,currency:Ie,externalId:D.string().nullable()}),D.object({...ai,...to,type:D.literal("source"),reason:D.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:$t,unlimited:D.boolean(),status:D.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:vn,expiresAt:vn.nullable(),orderId:D.uuid().nullable(),parentSourceId:D.uuid().nullable()}).strict(),D.object({...ai,type:D.literal("usage"),internal_feature_id:D.uuid(),name:D.string().min(1).max(120),kind:D.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:D.uuid().nullable(),quantity:xe,accepted:D.boolean(),reason:D.enum([...pa.options,"expired"]).nullable(),properties:It,reservationStatus:D.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:vn.nullable(),charges:D.array(D.discriminatedUnion("funding",[D.strictObject({funding:D.literal("balance"),sourceId:D.uuid(),rolloverId:D.uuid().nullable(),units:Cr,amount:$t}),D.strictObject({funding:D.literal("unbilled"),units:Cr}),D.object({...to,funding:D.literal("prepaid"),amount:$t}).strict(),D.object({funding:D.literal("postpaid"),invoiceId:D.uuid(),invoiceLineId:D.uuid(),authorizationId:D.uuid(),units:xe,currency:Ie}).strict()])).max(500)}).strict().refine(e=>(e.kind==="set_usage"||e.kind==="consume"&&e.quantity==="0"?e.accepted&&e.reason===null&&e.charges.length===0&&e.reservationStatus===null:e.accepted?e.reason===null&&e.charges.length>0:e.reason!==null&&e.charges.length===0)&&e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),D.object({...ai,type:D.literal("transaction"),purpose:D.enum(["product","invoice"]),productVersionId:D.uuid().nullable(),productName:D.string().min(1).max(120).nullable(),productVersion:D.number().int().positive().nullable(),invoiceId:D.uuid().nullable(),orderId:D.uuid(),originalId:D.uuid().nullable(),kind:D.enum(["purchase","refund"]),amountMinor:D.number().int().nonnegative().max(2e8).nullable(),currency:Ie.nullable()}).strict().refine(e=>e.currency===null==(e.amountMinor===null)&&(e.purpose==="product"?e.productVersionId!==null&&e.productName!==null&&e.productVersion!==null&&e.invoiceId===null:e.productVersionId===null&&e.productName===null&&e.productVersion===null&&e.invoiceId!==null)&&e.kind==="refund"==(e.originalId!==null)&&(e.kind!=="refund"||e.amountMinor===null||e.amountMinor>0),"Payment fact provenance is incomplete"),D.object({...ai,...to,type:D.literal("debt"),sourceId:D.uuid(),transactionId:D.uuid(),amount:$t}).strict(),D.object({...ai,...to,type:D.literal("settlement"),sourceId:D.uuid(),debtId:D.uuid(),kind:D.enum(["payment","usage_refund","payment_return"]),amount:$t}).strict()]),wp=D.object({customerId:D.uuid(),rows:D.array(XA).max(50),nextCursor:fa.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");import{z as fe}from"zod";var Pp=fe.object({customerId:fe.uuid()}).strict(),Cp=fe.discriminatedUnion("action",[fe.object({customerId:fe.uuid(),requestId:fe.uuid(),action:fe.literal("assign"),poolId:fe.uuid(),memberCustomerId:fe.uuid()}).strict(),fe.strictObject({customerId:fe.uuid(),requestId:fe.uuid(),action:fe.literal("assign_entity"),poolId:fe.uuid(),entityId:fe.uuid()}),fe.object({customerId:fe.uuid(),requestId:fe.uuid(),action:fe.literal("release"),poolId:fe.uuid(),slotId:fe.uuid()}).strict()]),no=fe.number().int().nonnegative(),dc=fe.iso.datetime({offset:!0}),pc=fe.strictObject({internalId:fe.uuid(),id:fe.string(),name:fe.string().nullable(),version:fe.number().int().positive()}),Op=fe.enum(["active","past_due"]),mc=fe.strictObject({customerId:fe.uuid(),licenses:fe.array(fe.strictObject({id:fe.uuid(),linkId:fe.uuid(),parent:fe.strictObject({customerProductId:fe.uuid(),status:Op,product:pc}),product:pc,planLicense:fe.strictObject({id:fe.uuid(),prepaidOnly:fe.boolean(),isCustom:fe.boolean()}).nullable(),granted:no,included:no,paidQuantity:no,usage:no,remaining:no,createdAt:dc}).refine(e=>e.granted===e.included+e.paidQuantity&&e.granted===e.usage+e.remaining,"Granted seats are included plus paid, and usage plus remaining")).max(2e3),assignments:fe.array(fe.strictObject({id:fe.uuid(),linkId:fe.uuid(),status:Op,product:pc,entity:fe.strictObject({internalId:fe.uuid(),id:fe.string().nullable(),name:fe.string().nullable()}).nullable(),beneficiary:fe.strictObject({internalId:fe.uuid(),id:fe.string().nullable(),name:fe.string().nullable()}).nullable(),startedAt:dc.nullable(),endedAt:dc.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:fe.boolean()});import{z as me}from"zod";var ro=me.enum(["email","sms","voice","push"]),dP=me.enum(["resend","twilio","fcm","apns"]);var pP=me.string().regex(/^\+[1-9]\d{1,14}$/),eb=me.enum(["email_recipient","sms_segment","voice_second","push_device"]);var tb=me.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),nb=me.strictObject({subject:tb,html:me.string().min(1).max(131072).optional(),text:me.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),rb=me.strictObject({body:me.string().min(1).max(1600).refine(e=>e.trim().length>0)}),ib=me.strictObject({text:me.string().trim().min(1).max(4e3),language:me.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:me.number().int().min(1).max(900)}),ob=me.record(me.string().min(1).max(64),me.string().max(256)).refine(e=>Object.keys(e).length<=20&&Object.keys(e).every(t=>!/^(?:indiana_|google\.|gcm\.)/i.test(t)&&t!=="aps"),"Push data contains reserved fields or too many entries"),ab=me.strictObject({title:me.string().trim().min(1).max(200),body:me.string().trim().min(1).max(2e3),url:me.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:ob.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),_p=me.discriminatedUnion("channel",[me.strictObject({channel:me.literal("email"),content:nb}),me.strictObject({channel:me.literal("sms"),content:rb}),me.strictObject({channel:me.literal("voice"),content:ib}),me.strictObject({channel:me.literal("push"),content:ab})]),Ep=me.strictObject({requestId:me.uuid(),customerId:me.uuid(),connectionId:me.uuid().optional(),message:_p,expiresAt:me.iso.datetime({offset:!0})}),sb=me.array(me.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),cb=me.discriminatedUnion("kind",[me.strictObject({kind:me.literal("all")}),me.strictObject({kind:me.literal("customers"),customerIds:sb})]),mP=me.strictObject({name:me.string().trim().min(1).max(120),connectionId:me.uuid().optional(),message:_p,audience:cb,frequencyLimit:me.number().int().min(1).max(100)}),Rp=me.strictObject({requestId:me.uuid(),channel:ro,state:me.enum(["allowed","denied"]),expectedRevision:me.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),kp=me.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),jp=me.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),fP=me.strictObject({meter:eb,estimatedUnits:me.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:me.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});import{z as Ce}from"zod";import{z as re}from"zod";import{z as si}from"zod";var io=si.strictObject({internalFeatureId:si.uuid(),name:si.string().min(1).max(120),includedAmount:si.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:si.enum(["hour","day","week","month","year","lifetime"]),resetCount:si.number().int().min(1).max(100),terms:Wo});import{z as st}from"zod";import{z as ub}from"zod";import{z as ci}from"zod";var Tp=ci.enum(["stripe","apple","google","merchant"]),Np=ci.enum(["membership","credit_pack","lifetime"]),xP=ci.enum(["active","grace","suspended","inactive","revoked"]),SP=ci.strictObject({currency:ci.string().regex(/^[A-Z]{3}$/),micros:ci.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var ui=ub.object({provider:Tp,currency:Ie}).strict();var rr=st.strictObject({internal_feature_id:st.uuid(),quantity:xe.refine(e=>/[1-9]/.test(e)),properties:It,entityId:st.uuid().optional()}),Dp=st.strictObject({requirement:rr,commerce:ui.optional(),paywallId:st.uuid().optional()}),lb=st.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),fc=st.strictObject({productId:st.string().min(1),productVersionId:st.string().min(1),name:st.string().min(1).max(120),action:st.enum(["purchase","upgrade","addon","topup"]),membershipId:st.string().min(1).nullable(),currency:Ie,amountMinor:st.string().regex(/^(0|[1-9]\d{0,8})$/),interval:st.enum(["free","week","month","year","one_time"]),intervalCount:st.number().int().min(1).max(156)}),Er=st.strictObject({internal_feature_id:st.string().min(1),name:st.string().min(1).max(120),kind:st.enum(["access","metered","credit"]),quantity:xe,allowed:st.boolean(),reason:lb.nullable(),preview:st.strictObject({scenario:st.enum(["feature_flag","usage_limit"]),candidates:st.array(fc).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"})}),kP=st.strictObject({paywallId:st.uuid(),requirement:rr});var ha=re.object({plan:re.string().min(1).max(200).optional(),coupon:re.uuid().optional(),promotionCode:re.uuid().optional(),picker:re.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),ga=re.object({text:re.string().optional(),label:re.string().optional(),alt:re.string().optional(),html:re.string().max(32768).optional(),price:re.object({current:re.string(),original:re.string().nullable(),period:re.string()}).optional(),code:re.string().optional(),countdownAt:re.iso.datetime().optional(),planId:re.string().min(1).max(200).optional(),planVersionId:re.string().min(1).max(200).optional(),currency:Ie.optional(),couponId:re.uuid().optional(),offerId:re.uuid().optional(),unavailable:re.boolean().optional(),unavailableReason:re.string().optional(),missing:re.array(re.string()).optional()}).strict(),li=re.object({paywall:Er.optional(),nodes:re.record(re.string(),re.object({base:ga,picker:re.string().optional(),byPlan:re.record(re.string(),ga).optional()}).strict()),plans:re.record(re.string(),re.object({id:re.string().min(1).max(200),versionId:re.string().min(1).max(200),available:re.boolean(),name:re.string(),price:re.string(),period:re.string(),currency:Ie.optional(),amountMinor:re.number().int().nonnegative().optional(),interval:re.enum(["free","week","month","year","one_time"]).optional(),intervalCount:re.number().int().positive().optional(),prepaid:re.array(io).max(100).optional()}).strict()),pickers:re.record(re.string(),re.object({options:re.array(re.string().min(1).max(200)).max(20),selected:re.string().min(1).max(200).nullable()}).strict()),quantities:re.record(re.string(),re.strictObject({minimum:re.number().int().nonnegative(),maximum:re.number().int().nonnegative(),step:re.number().int().positive(),value:re.number().int().nonnegative(),label:re.string(),available:re.boolean()})).optional(),diagnostics:re.array(re.object({nodeId:re.string(),message:re.string()}).strict())}).strict();function Fp(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}import{z as I}from"zod";function db(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function Mp(e){let t={};function n(r){var i;if(db(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 qp=Qn.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ya=Qn.strictObject({tiers:Qn.array(Qn.strictObject({id:qp,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:qp,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 Aa(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}import{z as ce}from"zod";var pb=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],Up=ce.enum(pb),Bp=ce.object({source:Up,layout:ce.enum(["full","compact"]),resourceKey:wr.optional(),pageSize:ce.number().int().min(1).max(50),showSources:ce.boolean(),allowPurchase:ce.boolean(),outputs:ce.object({billing_adjustment:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((e,t)=>{(e.outputs?.billing_authorization||e.outputs?.billing_adjustment)&&e.source!=="billing_controls"&&t.addIssue({code:"custom",message:"Payment authorization routes belong to the billing controls component."}),e.resourceKey&&!["credit_balance","credit_transactions"].includes(e.source)&&t.addIssue({code:"custom",message:"\u8FD9\u4E2A\u6570\u636E\u6E90\u4E0D\u80FD\u7ED1\u5B9A\u79EF\u5206\u8D44\u6E90\u3002"}),e.showSources&&e.source!=="credit_balance"&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u4F59\u989D\u53EF\u4EE5\u5C55\u5F00\u6765\u6E90\u3002"}),e.allowPurchase&&!["credit_packs","customer_plans","membership"].includes(e.source)&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u5305\u3001\u5957\u9910\u4E0E\u4F1A\u5458\u7EC4\u4EF6\u53EF\u4EE5\u542F\u7528\u4EA4\u6613\u3002"})}),Rt=ce.string().max(2e3),Vp=ce.object({id:ce.string().max(100),label:Rt,detail:ce.array(Rt).max(12),value:Rt.optional(),status:Rt.optional(),facts:ce.array(ce.object({label:Rt,value:Rt}).strict()).max(1e3),purchaseId:ce.uuid().optional(),invoiceUrl:ce.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:ce.array(ce.strictObject({action:ce.literal("invoice_open"),label:Rt})).max(1).optional(),membershipActions:ce.array(ce.object({value:ce.string().max(100),label:Rt}).strict()).max(3).optional()}).strict(),mb=ce.object({key:wr,name:Rt,spendable:Rt,reserved:Rt,available:Rt,expiry:Rt.nullable(),sources:ce.array(Vp).max(50),sourceCount:ce.number().int().nonnegative(),sourcePage:ce.number().int().positive(),hasNextSources:ce.boolean(),hasPreviousSources:ce.boolean()}).strict(),fb=ce.object({source:Up,status:ce.enum(["idle","loading","ready","error"]),stale:ce.boolean(),preview:ce.boolean(),errorCode:ce.string().max(80).optional(),errorMessage:Rt.optional(),resources:ce.array(mb).max(500),rows:ce.array(Vp).max(50),hasNext:ce.boolean(),hasPrevious:ce.boolean(),page:ce.number().int().positive(),filter:ce.string().max(40),updatedAt:ce.iso.datetime().optional(),buyingId:ce.uuid().optional(),membershipBusy:ce.boolean().optional(),billingBusy:ce.boolean().optional(),membershipReview:ce.object({title:Rt,note:Rt,facts:ce.array(ce.object({label:Rt,value:Rt}).strict()).max(100)}).strict().optional(),membershipResult:Rt.optional()}).strict(),Lp=ce.object({nodes:ce.record(ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),fb)}).strict(),zP=ce.object({nodeId:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:ce.enum(["refresh","next","previous","filter","buy_pack","billing_portal","billing_authorization","billing_adjustment","invoice_open","membership_preview","membership_confirm","membership_dismiss","sources_next","sources_previous"]),value:ce.string().max(100).optional()}).strict();import{z as K}from"zod";var xt={state:32,enumValues:64,derived:96,bindings:256,controls:64,timers:4,effects:8,depth:12,expressionNodes:2e3},$p=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]),Nt=K.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/).refine(e=>!$p.has(e),"Reserved UI identifier"),gc=K.union([K.string().max(2e3),K.number().finite(),K.boolean(),K.null()]),gb=K.discriminatedUnion("type",[K.strictObject({type:K.literal("enum"),values:K.array(gc).min(1).max(xt.enumValues),default:gc}),K.strictObject({type:K.literal("number"),min:K.number().finite(),max:K.number().finite(),step:K.number().finite().positive(),default:K.number().finite()}),K.strictObject({type:K.literal("text"),maxLength:K.number().int().min(0).max(2e3),default:K.string().max(2e3).nullable()}),K.strictObject({type:K.literal("boolean"),default:K.boolean()})]);function yc(e,t){if(e.type==="enum")return e.values.some(r=>r===t);if(e.type==="boolean")return typeof t=="boolean";if(e.type==="text")return t===null||typeof t=="string"&&t.length<=e.maxLength;if(typeof t!="number"||!Number.isFinite(t)||t<e.min||t>e.max)return!1;let n=(t-e.min)/e.step;return Number.isFinite(n)&&Math.abs(n-Math.round(n))<=Math.min(1e-7,Math.max(1,Math.abs(n))*Number.EPSILON*8)}var hb=gb.superRefine((e,t)=>{e.type==="enum"&&new Set(e.values).size!==e.values.length&&t.addIssue({code:"custom",path:["values"],message:"UI enum values must be unique"}),e.type==="number"&&e.min>e.max&&t.addIssue({code:"custom",path:["max"],message:"UI number range is reversed"}),yc(e,e.default)||t.addIssue({code:"custom",path:["default"],message:"UI default must match its state definition"})}),yb=["add","sub","mul","div","min","max","round","floor","eq","ne","gt","gte","lt","lte","and","or","not","if","concat","number","parse_number","money","lookup","now","duration"];function Ab(e,t){return e==="now"?t===0:e==="concat"?!0:e==="lookup"?t>=4&&t%2===0:e==="if"?t===3:["sub","div","eq","ne","gt","gte","lt","lte"].includes(e)?t===2:["round","floor","not","number","parse_number","money","duration"].includes(e)?t===1:t>=1}var kr=K.lazy(()=>K.union([gc,K.strictObject({ref:Nt}),K.strictObject({op:K.enum(yb),args:K.array(kr).max(xt.expressionNodes)}).superRefine((e,t)=>{Ab(e.op,e.args.length)||t.addIssue({code:"custom",path:["args"],message:"Invalid UI expression arity"})})]));function wn(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function Rr(e,t,n){if(!e||typeof e!="object")return!0;if(!wn(e))return t.addIssue({code:"custom",path:n,message:"UI objects must be plain data"}),!1;for(let r of Object.keys(e)){if($p.has(r))return t.addIssue({code:"custom",path:[...n,r],message:"Reserved UI object key"}),!1;let i=Object.getOwnPropertyDescriptor(e,r);if(i&&!Object.hasOwn(i,"value"))return t.addIssue({code:"custom",path:[...n,r],message:"UI objects cannot contain accessors"}),!1}return!0}function di(e,t,n,r){let i=[{value:e,depth:1,path:n}];for(;i.length;){let a=i.pop();if(++r.nodes>xt.expressionNodes||a.depth>xt.depth){t.addIssue({code:"custom",path:a.path,message:"UI expression budget exceeded"});return}if(!Rr(a.value,t,a.path))return;if(wn(a.value)&&Array.isArray(a.value.args)){if(a.value.args.length>xt.expressionNodes){t.addIssue({code:"custom",path:[...a.path,"args"],message:"UI expression budget exceeded"});return}for(let o=a.value.args.length-1;o>=0;o--)i.push({value:a.value.args[o],depth:a.depth+1,path:[...a.path,"args",o]})}}}var KP=K.unknown().superRefine((e,t)=>{di(e,t,[],{nodes:0})}).pipe(kr),hc=K.record(Nt,kr).refine(e=>Object.keys(e).length>0&&Object.keys(e).length<=xt.state,"UI assignments need 1\u201332 state keys"),bb=K.strictObject({target:Nt,property:K.enum(["text","visible","disabled","checked","value","class","aria-label","aria-selected","aria-checked","aria-valuetext","tabindex"]),expression:kr,className:Nt.optional()}).superRefine((e,t)=>{e.property==="class"!=(e.className!==void 0)&&t.addIssue({code:"custom",path:["className"],message:"Only class bindings require a safe className"})}),xb=K.discriminatedUnion("type",[K.strictObject({type:K.literal("scroll_latch"),target:Nt,state:Nt}),K.strictObject({type:K.literal("input"),target:Nt,state:Nt,set:hc.optional()}),K.strictObject({type:K.literal("action"),target:Nt,set:hc}),K.strictObject({type:K.literal("carousel"),target:Nt,state:Nt,initialIndex:K.number().int().nonnegative().optional(),maxWidth:K.number().int().min(1).max(1e4).optional(),previousTarget:Nt.optional(),nextTarget:Nt.optional(),inactiveTargets:K.array(Nt).max(20).optional(),inactiveMaxWidth:K.number().int().min(1).max(1e4).optional()})]),Sb=K.strictObject({afterMs:K.number().int().min(0).max(6e4),set:hc}),Ib=K.strictObject({type:K.literal("mosaic_waves"),target:Nt,color:K.string().regex(/^#[0-9a-fA-F]{6}$/),hotColor:K.string().regex(/^#[0-9a-fA-F]{6}$/),enabled:kr.optional(),speed:K.number().min(0).max(4).optional(),pitch:K.number().min(.05).max(4).optional(),fill:K.number().min(.05).max(1).optional(),feather:K.number().min(0).max(1).optional(),warp:K.number().min(0).max(4).optional(),warpScale:K.number().min(0).max(32).optional(),detailScale:K.number().min(0).max(32).optional(),waveScale:K.number().min(0).max(32).optional(),falloff:K.number().min(.1).max(32).optional(),brightness:K.number().min(0).max(32).optional(),ambient:K.number().min(0).max(1).optional(),gamma:K.number().min(.05).max(8).optional(),vignette:K.number().min(0).max(1).optional(),opacity:K.number().min(0).max(1).optional()}),vb=K.strictObject({type:K.literal("number_counter"),target:Nt,value:kr,prefix:K.string().max(20).optional(),format:K.enum(["number","short"]).optional()}),wb=K.strictObject({state:K.record(Nt,hb).refine(e=>Object.keys(e).length<=xt.state,"Too many UI state keys").optional(),derived:K.record(Nt,kr).refine(e=>Object.keys(e).length<=xt.derived,"Too many UI derived keys").optional(),bindings:K.array(bb).max(xt.bindings).optional(),controls:K.array(xb).max(xt.controls).optional(),timers:K.array(Sb).max(xt.timers).optional(),effects:K.array(K.discriminatedUnion("type",[Ib,vb])).max(xt.effects).optional(),clock:K.boolean().optional()});function Ob(e,t){if(!Rr(e,t,[])||!wn(e))return;for(let[r,i]of[["state",xt.state],["derived",xt.derived]]){let a=e[r];if(!Rr(a,t,[r]))return;if(wn(a)&&Object.keys(a).length>i){t.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}}for(let[r,i]of[["bindings",xt.bindings],["controls",xt.controls],["timers",xt.timers],["effects",xt.effects]])if(Array.isArray(e[r])&&e[r].length>i){t.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}if(Array.isArray(e.effects)){for(let[r,i]of e.effects.entries())if(!Rr(i,t,["effects",r]))return}if(wn(e.state))for(let[r,i]of Object.entries(e.state)){if(!Rr(i,t,["state",r]))return;if(wn(i)&&Array.isArray(i.values)&&i.values.length>xt.enumValues){t.addIssue({code:"custom",path:["state",r,"values"],message:"Too many UI enum values"});return}}let n={nodes:0};if(wn(e.derived))for(let[r,i]of Object.entries(e.derived))di(i,t,["derived",r],n);for(let r of["bindings","controls","timers"]){let i=e[r];if(Array.isArray(i)){for(let[a,o]of i.entries())if(!(!Rr(o,t,[r,a])||!wn(o))){if(r==="bindings")di(o.expression,t,[r,a,"expression"],n);else if(Rr(o.set,t,[r,a,"set"])&&wn(o.set)){if(Object.keys(o.set).length>xt.state){t.addIssue({code:"custom",path:[r,a,"set"],message:"Too many UI assignments"});return}for(let[s,c]of Object.entries(o.set))di(c,t,[r,a,"set",s],n)}if(n.nodes>xt.expressionNodes)return}}}if(Array.isArray(e.effects))for(let[r,i]of e.effects.entries())wn(i)&&i.type==="number_counter"?di(i.value,t,["effects",r,"value"],n):wn(i)&&i.enabled!==void 0&&di(i.enabled,t,["effects",r,"enabled"],n)}function zp(e){let t=[],n=[e];for(;n.length;){let r=n.pop();!r||typeof r!="object"||("ref"in r?t.push(r.ref):n.push(...r.args))}return t}var Gp=K.unknown().superRefine(Ob).pipe(wb).superRefine((e,t)=>{let n=e.state??{},r=e.derived??{},i=new Set([...Object.keys(n),...Object.keys(r)]),a=(g,d)=>{for(let h of zp(g))i.has(h)||t.addIssue({code:"custom",path:d,message:`Unknown UI reference: ${h}`})};for(let[g,d]of Object.entries(e.derived??{}))Object.hasOwn(n,g)&&t.addIssue({code:"custom",path:["derived",g],message:"UI state and derived identifiers must be distinct"}),a(d,["derived",g]);let o=new Set,s=new Set,c=g=>{if(o.has(g))return!1;if(s.has(g))return!0;o.add(g);for(let d of zp(r[g]))if(Object.hasOwn(r,d)&&!c(d))return!1;return o.delete(g),s.add(g),!0};for(let g of Object.keys(r))if(!c(g)){t.addIssue({code:"custom",path:["derived",g],message:"Cyclic UI derived references"});break}for(let[g,d]of(e.bindings??[]).entries())a(d.expression,["bindings",g,"expression"]);let u=new Set;for(let[g,d]of(e.effects??[]).entries())u.has(d.target)&&t.addIssue({code:"custom",path:["effects",g,"target"],message:"Effect targets must be unique"}),u.add(d.target),d.type==="number_counter"?(a(d.value,["effects",g,"value"]),typeof d.value=="number"&&Math.abs(d.value)>1e12&&t.addIssue({code:"custom",path:["effects",g,"value"],message:"Counter values must be within the display bound"})):d.enabled!==void 0&&a(d.enabled,["effects",g,"enabled"]);let l=(g,d)=>{for(let[h,R]of Object.entries(g))Object.hasOwn(n,h)||t.addIssue({code:"custom",path:[...d,h],message:"UI assignments can only update declared state"}),a(R,[...d,h])},m=new Set,f=new Set;for(let[g,d]of(e.controls??[]).entries()){if(d.type==="carousel"&&d.inactiveMaxWidth!==void 0&&d.inactiveTargets===void 0&&t.addIssue({code:"custom",path:["controls",g,"inactiveMaxWidth"],message:"Inactive width requires inactive article targets"}),d.type==="carousel")for(let h of d.inactiveTargets??[])(h===d.target||f.has(h))&&t.addIssue({code:"custom",path:["controls",g,"inactiveTargets"],message:"Inactive article targets must have one carousel owner"}),f.add(h);if(d.type==="carousel")for(let h of["previousTarget","nextTarget"]){let R=d[h];R!==void 0&&((R===d.target||m.has(R)||(e.controls??[]).some(y=>y.target===R))&&t.addIssue({code:"custom",path:["controls",g,h],message:"Carousel navigation needs a distinct, exclusive button target"}),m.add(R))}if(d.type!=="action"){let h=Object.hasOwn(n,d.state)?n[d.state]:void 0;(!h||d.type==="input"&&h.type==="enum"&&h.values.some(R=>typeof R!="string"))&&t.addIssue({code:"custom",path:["controls",g,"state"],message:"Control needs a supported declared UI state"}),d.type==="carousel"&&(h?.type!=="number"||!Number.isInteger(h.min)||h.min<0||!Number.isInteger(h.max)||h.step!==1||d.initialIndex!==void 0&&!yc(h,d.initialIndex))&&t.addIssue({code:"custom",path:["controls",g],message:"Carousel needs bounded nonnegative integer index state"}),d.type==="scroll_latch"&&h?.type!=="boolean"&&t.addIssue({code:"custom",path:["controls",g,"state"],message:"Scroll latches require boolean UI state"})}(d.type==="input"||d.type==="action")&&d.set&&l(d.set,["controls",g,"set"])}for(let[g,d]of(e.timers??[]).entries())l(d.set,["timers",g,"set"])});import{z as it}from"zod";var Pb=it.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ba=it.discriminatedUnion("type",[it.object({type:it.literal("fixed"),productVersionId:it.string().min(1).max(200)}).strict(),it.object({type:it.literal("picker"),pickerId:Pb,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")]),Cb=it.strictObject({min:it.number().finite().min(1).max(1800),max:it.number().finite().min(1).max(1800),viewport:it.number().finite().min(1).max(100)}).refine(e=>e.min<=e.max,"Desktop width range is reversed"),Kp={desktopWidth:Cb.optional(),mobile:it.enum(["sheet","fullscreen"]).optional(),backdrop:it.enum(["none","scrim","dim","strong-dim","blur"]).optional()},On=it.discriminatedUnion("type",[it.strictObject({type:it.literal("modal"),size:it.enum(["sm","md","lg"]),...Kp}),it.strictObject({type:it.literal("sheet"),size:it.enum(["sm","md","lg"]),...Kp}),it.strictObject({type:it.literal("fullscreen")}),it.strictObject({type:it.literal("inline")})]);var Eb=4,Cn={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:32768,documentBytes:2e5},ao=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),qe=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Rb=I.enum(["none","xs","sm","md","lg","xl"]),kb=I.enum(["none","sm","md","lg","full"]),Ac=I.string().regex(/^#[0-9a-fA-F]{6}$/),xc=I.string().max(2048).refine(e=>{try{let t=new URL(e);return t.protocol==="https:"&&t.hostname.length>0}catch{return!1}},"\u53EA\u652F\u6301 https \u94FE\u63A5"),bc=I.union([xc,I.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),I.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),I.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Hp=I.object({primary:Ac,background:Ac,text:Ac,radius:kb,font:I.enum(["system","serif","rounded","mono"]),fontAssets:I.object({family:I.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/),faces:I.array(I.object({url:xc,weight:I.number().int().min(100).max(900).multipleOf(100),family:I.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/).optional()}).strict()).min(1).max(4)}).strict().optional()}).strict(),so=I.union([I.enum(["primary","text","muted","background","surface"]),I.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),Fe=(e,t)=>I.number().int().min(e).max(t),Qp=I.union([I.enum(["fit","fill"]),Fe(1,1200)]),jb=I.object({top:Fe(0,200),right:Fe(0,200),bottom:Fe(0,200),left:Fe(0,200)}).strict(),Tb=I.object({top:Fe(-100,200),right:Fe(-100,200),bottom:Fe(-100,200),left:Fe(-100,200)}).strict(),Jp=I.object({x:Fe(0,100),y:Fe(0,100)}).strict(),Nb=I.discriminatedUnion("type",[I.object({type:I.literal("color"),color:so}).strict(),I.object({type:I.literal("linear"),angle:Fe(0,360),stops:I.array(I.object({color:so,at:Fe(0,100)}).strict()).min(2).max(4)}).strict(),I.object({type:I.literal("image"),src:bc,fit:I.enum(["cover","contain"]),position:Jp.optional()}).strict()]),Db=I.discriminatedUnion("type",[I.object({type:I.literal("rect"),radius:I.union([Fe(0,200),I.object({topLeft:Fe(0,200),topRight:Fe(0,200),bottomRight:Fe(0,200),bottomLeft:Fe(0,200)}).strict()])}).strict(),I.object({type:I.literal("pill")}).strict()]),Fb=I.object({width:Fe(0,12),color:so,style:I.enum(["solid","dashed"])}).strict(),Mb=I.object({x:Fe(-40,40),y:Fe(-40,40),blur:Fe(0,80),spread:Fe(-20,40),color:so}).strict(),qb=I.object({font:I.enum(["system","serif","rounded","mono"]),size:Fe(8,96),weight:I.number().int().min(100).max(900).multipleOf(100),lineHeight:I.number().min(.8).max(3),letterSpacing:I.number().min(-5).max(20),color:so,align:I.enum(["start","center","end"]),italic:I.boolean(),decoration:I.enum(["none","underline","line-through"]),transform:I.enum(["none","uppercase"])}).strict().partial(),jr=I.object({width:Qp,height:Qp,padding:jb,margin:Tb,gap:Fe(0,120),grow:I.union([I.boolean(),I.number().min(0).max(12)]),background:Nb,opacity:I.number().min(0).max(1),clipContent:I.boolean(),shape:Db,border:Fb,shadow:Mb,text:qb}).strict().partial(),tn={id:ao,name:I.string().trim().min(1).max(60).optional(),hidden:I.boolean().optional(),style:jr.optional(),fallback:qe.optional()},Ub=I.object({...tn,type:I.literal("text"),productField:I.enum(["name","price","trial","period"]).optional(),feature:I.object({id:I.uuid(),field:I.enum(["name","allowance"])}).strict().optional(),text:qe,variant:I.enum(["title","heading","body","caption"])}).strict(),Bb=I.object({...tn,type:I.literal("image"),src:bc,localizedSrc:I.record(Sn,bc).optional(),alt:qe,aspect:I.enum(["auto","1:1","4:3","16:9","3:1"]),fit:I.enum(["cover","contain"]),position:Jp.optional()}).strict(),Vb=I.object({...tn,type:I.literal("button"),label:qe,variant:I.enum(["primary","secondary","link"]),action:qe,purpose:I.enum(["purchase","navigation","close"]).optional(),bind:ha.optional()}).strict(),Lb=I.object({...tn,type:I.literal("divider")}).strict(),zb=I.object({...tn,type:I.literal("customer_data"),title:qe,data:Bp}).strict(),$b=I.object({...tn,type:I.literal("spacer"),size:Rb}).strict(),Gb=I.object({...tn,type:I.literal("custom_html"),html:I.record(Sn,I.string().max(Cn.customHtml)),css:I.string().max(Cn.customCss),ui:Gp.optional()}).strict(),Kb=I.object({...tn,type:I.literal("price"),fallback:qe,parts:I.object({current:jr.optional(),original:jr.optional(),period:jr.optional()}).strict().optional()}).strict(),Hb=I.object({...tn,type:I.literal("coupon_code"),label:qe,fallback:qe}).strict(),Qb=I.object({...tn,type:I.literal("countdown"),source:I.enum(["offer.ends_at","offer.expires_at","fixed"]),at:I.iso.datetime().optional(),granularity:I.enum(["day","hour","minute","second"]),expired:qe,fallback:qe}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),Jb=I.object({...tn,type:I.literal("plan_picker"),label:qe,fallback:qe,planIds:I.array(I.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:I.string().min(1).max(200).optional(),grouping:ya.safeExtend({monthLabel:qe,yearLabel:qe,unavailableLabel:qe}).optional(),states:I.object({selected:jr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!Aa(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),Zb=I.object({...tn,type:I.literal("quantity_picker"),bind:ha.optional(),label:qe,fallback:qe,internalFeatureId:I.uuid(),minimumQuantity:Fe(0,1e4),maximumQuantity:Fe(0,1e4),defaultQuantity:Fe(0,1e4),step:Fe(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"),Wb=I.discriminatedUnion("type",[I.object({type:I.literal("input"),label:qe,keyboard:I.enum(["text","email","tel","url"]),maxLength:Fe(1,500)}).strict(),I.object({type:I.literal("multiselect"),label:qe,min:Fe(0,50),max:Fe(1,50)}).strict(),I.object({type:I.literal("select"),label:qe,defaultIndex:Fe(0,49),purpose:I.enum(["option","product","tier"]).optional(),pickerId:ao.optional(),selectedStyle:jr.optional()}).strict(),I.object({type:I.literal("tabs"),label:qe,defaultIndex:Fe(0,49),purpose:I.literal("tier").optional()}).strict(),I.object({type:I.literal("toggle"),label:qe,defaultEnabled:I.boolean()}).strict(),I.object({type:I.literal("carousel"),label:qe}).strict()]),Pn={...tn,type:I.literal("stack"),direction:I.enum(["vertical","horizontal","overlay"]),align:I.enum(["start","center","end","stretch"]),justify:I.enum(["start","center","end","between"]),productSlot:I.object({index:Fe(0,19),period:I.enum(["month","year"]).optional(),requireBinding:I.boolean().optional()}).strict().optional(),interaction:Wb.optional(),states:I.object({selected:jr.optional()}).strict().optional(),purpose:I.literal("benefits").optional(),purchaseAction:qe.optional(),buttonVariant:I.enum(["primary","secondary","link"]).optional(),bind:ha.optional()},Zp=I.lazy(()=>I.object({...tn,type:Pn.type,direction:Pn.direction,align:Pn.align,justify:Pn.justify,children:I.array(Yb).max(Cn.children),productSlot:Pn.productSlot,interaction:Pn.interaction,states:Pn.states,purpose:Pn.purpose,purchaseAction:Pn.purchaseAction,buttonVariant:Pn.buttonVariant,bind:Pn.bind}).strict()),Yb=I.lazy(()=>I.union([Zp,Ub,Bb,Vb,Lb,$b,Gb,Kb,Hb,Qb,Jb,Zb,zb])),Xb=I.union([I.string().max(500),I.number().finite(),I.boolean(),I.null()]),oo={id:qe,event:qe,properties:I.record(qe,Xb).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},ex=I.discriminatedUnion("type",[I.object({...oo,type:I.literal("navigate"),close:I.literal(!1),pageId:ao}).strict(),I.object({...oo,type:I.literal("event"),close:I.boolean()}).strict(),I.object({...oo,type:I.literal("close"),close:I.literal(!0)}).strict(),I.object({...oo,type:I.literal("open_url"),close:I.boolean(),url:xc}).strict(),I.object({...oo,type:I.literal("claim_offer"),close:I.boolean(),couponId:I.uuid()}).strict()]),tx=I.object({defaultLocale:Sn,locales:I.record(Sn,I.record(qe,I.string().max(Cn.stringLength)))}).strict(),nx=I.enum(["popup","paywall","onboarding","page","banner"]);var rx=I.object({kind:I.literal("screen"),schemaVersion:I.literal(Eb),name:I.string().trim().min(1).max(80),surface:nx,initialPageId:ao.optional(),presentation:On,theme:Hp,pages:I.array(I.object({id:ao,name:I.string().trim().min(1).max(60),root:Zp,theme:Hp.optional(),editorPosition:I.object({x:I.number().finite().min(-1e5).max(1e5),y:I.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(Cn.pages),strings:tx,actions:I.array(ex).max(Cn.actions)}).strict();function Gt(e,t){for(let n of e.pages)Jn(n.root,t)}var cn=rx.superRefine((e,t)=>{let n=Cn;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>Cn.locales&&r(`\u6700\u591A ${Cn.locales} \u79CD\u8BED\u8A00`);let a=new Set;for(let l of e.actions)a.has(l.id)&&r(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${l.id}`),a.add(l.id);let o=new Set;for(let l of e.pages)["next","back"].includes(l.id)&&r(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${l.id}`),o.has(l.id)&&r(`\u9875\u9762 id \u91CD\u590D\uFF1A${l.id}`),o.add(l.id);let s=new Set,c=0,u=!1;Gt(e,(l,m)=>{if(c++,m>Cn.depth&&(u=!0),s.has(l.id)&&r(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${l.id}`),s.add(l.id),l.type==="button"&&!a.has(l.action)&&r(`\u6309\u94AE ${l.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${l.action}`),l.type==="custom_html")for(let f of Object.keys(l.html))i.includes(f)||r(`\u81EA\u5B9A\u4E49 HTML ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${f}`);if(l.type==="image")for(let f of Object.keys(l.localizedSrc??{}))i.includes(f)||r(`\u56FE\u7247 ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${f}`)}),c>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),u&&r(`\u5C42\u7EA7\u6700\u591A ${Cn.depth} \u5C42`)});function Jn(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)Jn(i,t,n+1,e)}function xa(e){let t=[],n=new Set;return Gt(e,r=>{let i=(a,o,s)=>{n.has(a)||(n.add(a),t.push({key:a,nodeId:r.id,nodeType:r.type,field:o,required:s}))};r.type==="stack"&&r.interaction&&i(r.interaction.label,"label",!0),r.fallback&&i(r.fallback,"text",!0),r.type==="text"&&i(r.text,"text",!0),r.type==="customer_data"&&i(r.title,"title",!0),(r.type==="plan_picker"||r.type==="quantity_picker"||r.type==="coupon_code")&&i(r.label,"label",!0),r.type==="plan_picker"&&r.grouping&&(i(r.grouping.monthLabel,"label",!0),i(r.grouping.yearLabel,"label",!0),i(r.grouping.unavailableLabel,"text",!0)),r.type==="countdown"&&i(r.expired,"text",!0),r.type==="button"&&i(r.label,"label",!0),r.type==="image"&&(i(`image:${r.id}`,"src",!1),i(r.alt,"alt",!1)),r.type==="custom_html"&&i(`html:${r.id}`,"html",!0)}),t}function ix(e,t,n){if(t.field==="html"){let r;return Gt(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=co(e,t.nodeId);return r?.type==="image"?r.localizedSrc?.[n]??(n===e.strings.defaultLocale?r.src:void 0):void 0}return e.strings.locales[n]?.[t.key]}function ir(e){let t=xa(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=>!ix(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 ox(e,t){let n=null;return Jn(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function co(e,t){for(let n of e.pages){let r=ox(n.root,t);if(r)return r}return null}import{z as Bt}from"zod";var St=Bt.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/).refine(e=>e.split(".").every(t=>t.length>0&&!["__proto__","constructor","prototype"].includes(t)),"Reserved or empty variable path"),Sc=Bt.strictObject({type:Bt.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:Bt.boolean(),enum:Bt.array(Bt.string().max(255)).min(1).max(100).optional()}),pi=Sc.extend({type:Bt.enum([...Sc.shape.type.options,"array"]),items:Sc.optional()}).superRefine((e,t)=>{(e.type==="array"!=!!e.items||e.enum&&e.type!=="string"||e.items?.enum&&e.items.type!=="string")&&t.addIssue({code:"custom",message:"Array requires items; only strings support enum"})}),mi=pi.safeExtend({source:Bt.discriminatedUnion("type",[Bt.strictObject({type:Bt.literal("input")}),Bt.strictObject({type:Bt.literal("node")}),Bt.strictObject({type:Bt.enum(["parameter","attribute"]),key:St})])}),sC=Bt.record(St,mi),Ic=Bt.record(St,St).refine(e=>Object.keys(e).length<=20);function gn(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=>gn(e.items,n)):["offering_version","reward","paywall_version"].includes(e.type)?typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===2&&t.type===e.type&&Bt.uuid().safeParse(t.id).success:e.type==="json"||(e.type==="strings"?Array.isArray(t)&&t.every(n=>typeof n=="string"):typeof t===e.type):!1}function vc(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&&vc(e.items,t.items)}function Sa(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(!gn(i,u))throw new Error(`Invalid variable value: ${r}`);n[r]=u}}return n}function fi(e,t){let n={};for(let[r,i]of Object.entries(e.writes??{})){if(!Object.hasOwn(t,r))throw new Error(`Node output is missing: ${r}`);if(Object.hasOwn(n,i))throw new Error("Node outputs cannot overwrite one another");n[i]=t[r]}return n}function Wp(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"||!gn(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 _n=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"),Dn=Tr.discriminatedUnion("source",[Tr.strictObject({source:Tr.literal("literal"),value:ve}),Tr.strictObject({source:Tr.literal("variable"),key:Tr.string().min(1).max(255),path:_n.optional()})]);function Yp(e,t){if(!t)return e;for(let n of _n.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 wc(e,t){if(e.source==="literal")return structuredClone(e.value);let n=Sa(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(ve.parse(Yp(n[e.key],e.path)))}function Oc(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&&!_n.safeParse(r).success?null:{key:n,path:r}}function Pc(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Gt(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(Fp))]}function Ia(e){return Pc(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,f=(l.includes(".")?l.indexOf("."):m)+Number(u),g=f<=0?2-f+m:f>=m?f:m+1;n+=g+(c.startsWith("-")?1:0)-s.length}}return n}var or=Ce.enum(["page","popup","banner"]),ax=3e5,Xp=Ce.strictObject({type:Ce.enum(["string","number","boolean","strings","json"]),nullable:Ce.boolean()}),sx=Ce.strictObject({inputs:Ce.record(qe,Xp.extend({required:Ce.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:Ce.record(qe,Xp).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),cx=Ce.strictObject({kind:or,schemaVersion:Ce.literal(1),name:Ce.string().trim().min(1).max(80),screen:cn,contract:sx}),va=cx.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)>ax&&n("Content document exceeds its byte budget",[])});function ux(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 lx=va.superRefine((e,t)=>{for(let n of Ia(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&&!ux(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}ir(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),em=Ce.strictObject({id:Ce.uuid(),kind:or,projectId:Ce.uuid(),environmentId:Ce.uuid(),name:Ce.string(),revision:Ce.number().int().nonnegative(),status:Ce.enum(["draft","published","archived"]),publishedVersionId:Ce.uuid().nullable(),createdAt:Ce.iso.datetime({offset:!0}),updatedAt:Ce.iso.datetime({offset:!0})}),vC=em.extend({draft:va}),wC=Ce.strictObject({rows:Ce.array(em).max(200),nextCursor:Ce.uuid().nullable()}),Cc=Ce.strictObject({id:Ce.uuid(),kind:or,resourceId:Ce.uuid(),projectId:Ce.uuid(),environmentId:Ce.uuid(),version:Ce.number().int().positive(),sourceRevision:Ce.number().int().nonnegative(),document:lx,createdAt:Ce.iso.datetime({offset:!0})}),OC=Cc.omit({document:!0}),PC=Ce.discriminatedUnion("action",[Ce.strictObject({action:Ce.literal("create"),kind:or,id:Ce.uuid(),document:va}),Ce.strictObject({action:Ce.literal("save"),kind:or,id:Ce.uuid(),revision:Ce.number().int().nonnegative(),document:va}),Ce.strictObject({action:Ce.enum(["publish","archive"]),kind:or,id:Ce.uuid(),revision:Ce.number().int().nonnegative()})]).superRefine((e,t)=>{"document"in e&&e.document.kind!==e.kind&&t.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});import{z as tm}from"zod";var gi={funnelId:tm.uuid().optional(),funnelVersionId:tm.uuid().optional()};import{z as wa}from"zod";var Oa=wa.strictObject({runId:wa.uuid(),bindingId:wa.uuid(),receiptId:wa.uuid()});import{z as ot}from"zod";import{z as Ue}from"zod";import{z as Xe}from"zod";var TC=Xe.discriminatedUnion("action",[Xe.strictObject({action:Xe.literal("create"),couponId:Xe.uuid(),productBindingId:Xe.uuid(),storeOfferId:Xe.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:Xe.enum(["introductory","promotional"])}),Xe.strictObject({action:Xe.literal("set_enabled"),id:Xe.uuid(),revision:Xe.number().int().nonnegative(),enabled:Xe.boolean()})]),NC=Xe.array(Xe.strictObject({id:Xe.uuid(),couponId:Xe.uuid(),productBindingId:Xe.uuid(),storeOfferId:Xe.string().min(1).max(255).nullable(),storeOfferType:Xe.enum(["introductory","promotional"]),enabled:Xe.boolean(),revision:Xe.number().int().nonnegative()})).max(500),hi=Xe.strictObject({offerKind:Xe.enum(["none","introductory","promotional"]),offerId:Xe.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:Xe.number().int().min(0).max(1e8),trialDays:Xe.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"})}),DC=Xe.record(Xe.uuid(),hi).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var _c=Ue.object({type:Ue.literal("native_purchase"),receiptId:Ue.uuid(),orderId:Ue.uuid(),productVersionId:Ue.uuid(),provider:Ue.enum(["apple","google"]),productId:Ue.string().min(1).max(255),productKind:Np,replacement:Ue.strictObject({sourceOrderId:Ue.uuid(),sourceProductId:Ue.string().min(1).max(255),policy:Ue.enum(["apple_store","google_full_price"]),sourceAccountTokens:Ue.array(Ue.uuid()).max(50)}).nullable(),appAccountToken:Ue.uuid().optional(),obfuscatedAccountId:Ue.string().min(1).max(64).optional(),obfuscatedProfileId:Ue.uuid().optional(),basePlanId:Ue.string().min(1).max(255).optional(),offerId:Ue.string().min(1).max(255).optional(),offerKind:Ue.enum(["none","introductory","promotional"]),currency:Ie,catalogAmountMinor:Ue.number().int().nonnegative().max(1e8),discountMinor:Ue.number().int().nonnegative().max(1e8),trialDays:Ue.number().int().min(1).max(730).nullable(),seatBundle:Ue.array(Ue.strictObject({key:Ue.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:Ue.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:Ue.strictObject({offerId:Ue.string().min(1).max(255),keyId:Ue.string().min(1).max(255),nonce:Ue.uuid(),signature:Ue.string().min(1).max(1024),timestamp:Ue.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,t)=>{let n=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(n?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!n&&e.productKind==="membership"&&e.basePlanId===void 0||e.discountMinor>e.catalogAmountMinor||new Set(e.seatBundle.map(i=>i.key)).size!==e.seatBundle.length||e.trialDays!==null&&(e.discountMinor!==0||e.offerKind==="none")||e.offerKind==="none"&&e.discountMinor!==0||(n?!e.appAccountToken||e.obfuscatedAccountId!==void 0||e.obfuscatedProfileId!==void 0||e.basePlanId!==void 0||e.offerKind==="promotional"!=(e.applePromotionalOffer!==null)||e.offerKind==="promotional"!=(e.offerId!==void 0)||e.applePromotionalOffer!==null&&e.applePromotionalOffer.offerId!==e.offerId:e.appAccountToken!==void 0||!e.obfuscatedAccountId||!e.obfuscatedProfileId||e.applePromotionalOffer!==null||e.offerKind==="none"!=(e.offerId===void 0)))&&t.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});import{z as p}from"zod";import{z as _e}from"zod/v4";import{z as dx}from"zod/v4";var px=dx.registry(),{BillingInterval:nm}=(()=>{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:mx}=(e=>({DisplaySchema:e.object({primary_text:e.string().meta({description:"Main display text (e.g. '$10' or '100 messages')."}),secondary_text:e.string().optional().meta({description:"Secondary display text (e.g. 'per month' or 'then $0.5 per 100')."})})}))(_e),{withSpecDefault:fx}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(px),{COMMON:rm}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:gx}={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:hx}=(e=>({COMMON_SET:new Set(e)}))(rm),{hasNoDuplicateCurrencies:im}={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:om}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:yx}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(_e),{Infinite:Ax}={Infinite:"inf"},{TierBehavior:bx}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:am}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:xx}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:Sx}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:Ix}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:vx}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(_e),{ApiCreditTierSchema:sm}=(e=>({ApiCreditTierSchema:e.object({to:e.union([e.number().positive(),e.enum(["inf"])]).meta({description:"Inclusive upper usage boundary for this graduated tier. The final tier must be 'inf'."}),credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group within this tier."})})}))(_e),{VIOLATION_MESSAGES:wx}={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:cm}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(_e),{ModelMarkupsSchema:Ox}=((e,t)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),t.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(_e,cm),{InvoiceUsageEntrySchema:Px}=(e=>({InvoiceUsageEntrySchema:e.object({feature_id:e.string().meta({description:"The metered feature whose units are being converted."}),quantity:e.number().nonnegative().meta({description:"Billable units of the metered feature. Converted to the credit-system feature through its rate card."}),properties:e.record(e.string(),e.unknown()).optional().meta({description:"Event properties used to pick the rate card dimension and multipliers."})}).strict()}))(_e),{AttachDiscountSchema:um}=(e=>({AttachDiscountSchema:e.object({reward_id:e.string().optional().meta({description:"The ID of the reward to apply as a discount."}),promotion_code:e.string().optional().meta({description:"The promotion code to apply as a discount."})}).refine(n=>n.reward_id||n.promotion_code,{message:"Either reward_id or promotion_code must be provided."}).meta({title:"AttachDiscount",description:"A discount to apply. Can be either a reward ID or a promotion code."})}))(_e),{CustomLineItemSchema:Cx}=(e=>({CustomLineItemSchema:e.object({amount:e.number().meta({description:"Amount in dollars for this line item (e.g. 10.50). Can be negative for credits."}),description:e.string().meta({description:"Description for the line item."})})}))(_e),{UnixMsTimestampSchema:_x}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(_e),{CreateInvoicePreviewLineSchema:Ex}=(e=>({CreateInvoicePreviewLineSchema:e.object({plan_id:e.string().nullable(),feature_id:e.string().nullable(),description:e.string(),amount:e.number(),amount_after_discounts:e.number(),quantity:e.number().nullable(),prorated:e.boolean(),period_start:e.number().nullable(),period_end:e.number().nullable()})}))(_e),{ReissueInvoiceParamsSchema:lm}=(e=>({ReissueInvoiceParamsSchema:e.object({invoice_id:e.string().meta({description:"The Autumn invoice ID to void and replace.",example:"inv_2b3c4d5e6f7g8h"}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer and memo are applied to the replacement invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the replacement invoice. Defaults to the original invoice's due date; required when that date has already passed."}),update_customer_email:e.email().optional().meta({description:"Updates the customer's billing email before the replacement is issued, so Stripe sends the new invoice to this address."})})}))(_e),{InvoiceModeParamsSchema: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."})}))(_e),{InvoiceTemplateSchema:Rx}=(e=>({InvoiceTemplateSchema:e.object({id:e.string().meta({description:"Unique identifier for the invoice template."}),name:e.string().meta({description:"User-defined name to distinguish this template when sending an invoice."}),footer:e.string().optional().meta({description:"Footer text rendered on the invoice, typically bank details so customers can pay directly."}),memo:e.string().optional().meta({description:"Memo shown near the top of the invoice (Stripe invoice description), e.g. a contact line for payment questions."}),net_terms_days:e.number().int().positive().optional().meta({description:"Default number of days the customer has to pay before the invoice is due. Overridable when sending."}),created_at:e.number().optional().meta({description:"Timestamp (ms) when the template was created."})})}))(_e),{BasePriceSchema:kx}=((e,t,n)=>({BasePriceSchema:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),interval:e.enum(t).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),display:n.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(_e,nm,mx),{CURRENCY_CODES:jx}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(rm,gx,hx),{ApiPriceProcessorsSchema:dm}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(_e,yx),{AllocatedBillingFieldSchema:Tx}=((e,t)=>({AllocatedBillingFieldSchema:e.enum(t).optional().meta({internal:!0,description:"How an allocated usage_based price bills mid-cycle quantity changes. 'arrear' (default) bills at period end. 'prorated_legacy' is only returned for prices still on the legacy immediate-proration behavior; omit it to migrate the price to 'arrear'."})}))(_e,xx),{CreditDimensionNameSchema:Nx}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(_e,Sx,Ix),{ApiCreditMatchSchema:pm}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(vx),{findCreditTierViolations:Dx}=(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}}))(wx),{ApiCreditMultiplierSchema:Fx}=((e,t)=>({ApiCreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional().meta({description:"Multiplies the matched rate. All matching multipliers stack."}),add:e.number().optional().meta({description:"Added to the rate after every factor is applied, in credits per billing-unit group."})}).strict().refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(_e,pm),{ProviderMarkupsSchema:Mx}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(_e,cm),{InvoiceFeatureQuantitySchema:mm}=((e,t,n)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(t).meta({description:"Which of the feature's prices to use: 'prepaid' or 'usage_based'."}),quantity:e.number().nonnegative().optional().meta({description:"Billable feature units in total, exclusive of any included usage. Not per seat or per entity. For a credit-system feature this is the number of credits."}),usage:e.array(n).optional().meta({description:"For credit-system features: billable units of the source features, converted through the credit rate card. Mutually exclusive with quantity."}),prorate:e.boolean().optional().meta({description:"Whether to prorate this line against period_start / period_end. Defaults to true for prepaid and false for usage-based."})}).strict().refine(i=>i.quantity!==void 0!=(i.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(_e,am,Px),{CreateInvoicePreviewSchema:Ec}=((e,t)=>({CreateInvoicePreviewSchema:e.object({currency:e.string(),lines:e.array(t),subtotal:e.number(),discount_total:e.number(),tax:e.object({total:e.number(),amount_inclusive:e.number(),amount_exclusive:e.number(),status:e.enum(["complete","incomplete"])}).nullable(),total:e.number(),due_date:e.number().nullable()})}))(_e,Ex),{SUPPORTED_SET:qx}=(e=>({SUPPORTED_SET:new Set(e)}))(jx),{ApiCreditDimensionBaseSchema:Ux}=((e,t)=>({ApiCreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(_e,pm),{refineGraduatedTiers:fm}=(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"]})}}))(Dx),{ApiFeatureMarkupsOverrideSchema:Bx}=((e,t,n)=>({ApiFeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional().meta({description:"Default percentage markup for customers on this plan. Use -100 to make usage free."}),provider_markups:t.meta({description:"Per-provider markup percentages for customers on this plan."}),model_markups:n.meta({description:"Per-model markup overrides for customers on this plan."})})}))(_e,Mx,Ox),{isValidCurrencyCode:Vx}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(qx),{ApiCreditDimensionSchema:Lx}=((e,t,n,r)=>({ApiCreditDimensionSchema:e.union([t.extend({tier_behavior:e.literal("graduated"),tiers:e.array(n).min(1)}).strict().superRefine(r),t.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(_e,Ux,sm,fm),{CurrencyCodeSchema:gm}=((e,t)=>({CurrencyCodeSchema:e.string().refine(t,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(_e,Vx),{AdditionalCurrencyTierSchema:zx}=((e,t)=>({AdditionalCurrencyTierSchema:e.object({currency:t,amount:e.number().optional().meta({description:"Per-unit amount for this tier in this currency."}),flat_amount:e.number().optional().meta({description:"Flat amount for this tier in this currency, if the tier uses one."})}).refine(r=>r.amount!==void 0||r.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(_e,gm),{ApiCreditSchemaItemBaseSchema:hm}=((e,t,n,r)=>({ApiCreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string().nonempty().meta({description:"ID of the metered feature that draws from this credit system."}),billing_units:e.number().positive().optional().meta({description:"Number of metered-feature units priced together. Defaults to one when omitted."}),dimensions:e.record(t,n).optional().meta({description:"Named rates chosen by event properties. The most specific match sets the rate; with no match the item's own rate applies."}),multipliers:e.record(t,r).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(_e,Nx,Lx,Fx),{ApiFlatCreditSchemaItemSchema:$x}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(hm,_e),{AdditionalCurrencyPriceSchema:Gx}=((e,t)=>({AdditionalCurrencyPriceSchema:e.object({currency:t,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(_e,gm),{AdditionalCurrencyTierArraySchema:Kx}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(_e,zx,im,om),{ApiGraduatedCreditSchemaItemSchema:Hx}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(hm,_e,sm,fm),{AdditionalCurrencyPriceArraySchema:ym}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(_e,Gx,im,om),{ApiUsageTierWithCurrenciesSchema:Qx}=((e,t,n)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:n.optional().meta({description:"Per-currency amounts for this tier. Tier boundaries ('to') are shared across all currencies."})}).refine(i=>i.amount!==void 0||i.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(i=>({...i,amount:i.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:n.optional()}))}))(_e,Ax,Kx),{ApiCreditSchemaItemSchema:Jx}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(_e,Hx,$x),{BasePriceParamsSchema:Zx}=((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."})}))(kx,fx,_e,ym),{PlanItemPriceParamsSchema:Wx}=((e,t,n,r,i,a,o)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(c=>c??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:t.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(i).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(a).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:o,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(_e,ym,Qx,bx,nm,am,Tx),{ApiFeatureOverrideSchema:Yx}=((e,t,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(t).optional().meta({description:"For credit system features: replaces the feature's credit_schema entirely for customers on this plan."}),markups:n.optional().meta({description:"For AI credit system features: replaces the feature's markup chain entirely for customers on this plan. An unset level means no markup at that level rather than inheriting the feature's."})})}))(_e,Jx,Bx),{InvoiceBasePriceParamsSchema:Am}=((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()}))(Zx,dm),{InvoiceItemPriceParamsSchema:Xx}=((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()}))(Wx,dm),{InvoiceLicenseQuantitySchema:eS}=((e,t,n)=>({InvoiceLicenseQuantitySchema:e.object({license_plan_id:e.string().meta({description:"The license plan linked to the parent plan."}),quantity:e.number().int().nonnegative().meta({description:"Billable seats, exclusive of any included seats."}),customize:e.object({price:t.nullable().optional()}).strict().optional().meta({description:"Override the license's per-seat price on this invoice."}),feature_quantities:e.array(n).optional().meta({description:"Feature charges priced through the license plan."}),prorate:e.boolean().optional().meta({description:"Whether to prorate seat charges against period_start / period_end. Defaults to true."})}).strict()}))(_e,Am,mm),{InvoiceCustomizeItemSchema:tS}=((e,t,n)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:t.optional().meta({description:"Pricing to use for this feature on this invoice."}),feature_override:n.pick({credit_schema:!0}).strict().optional().meta({description:"For credit-system features: a credit rate card to use when converting `usage` on this invoice."})}).strict()}))(_e,Xx,Yx),{InvoiceCustomizeSchema:nS}=((e,t,n)=>({InvoiceCustomizeSchema:e.object({price:t.nullable().optional().meta({description:"Override the plan's base price for this invoice. Pass null or an amount of 0 to omit the base price line."}),items:e.array(n).optional().meta({description:"Override feature pricing for this invoice. Only pricing fields are accepted; grants, resets and rollovers are not part of an invoice."})}).strict().meta({title:"InvoiceCustomize",description:"Pricing overrides applied to this invoice only. The catalog and the customer's plan are not changed."})}))(_e,Am,tS),{InvoicePlanParamsSchema:rS}=((e,t,n,r,i)=>({InvoicePlanParamsSchema:e.object({plan_id:e.string().meta({description:"The catalog plan (or variant) whose pricing to use."}),version:e.number().optional().meta({description:"Plan version. Defaults to the active version."}),customize:t.optional(),feature_quantities:e.array(n).optional(),license_quantities:e.array(r).optional(),discounts:e.array(i).optional().meta({description:"Discounts applied only to this plan's lines."}),prorate:e.boolean().optional().meta({description:"Whether to prorate the base price against period_start / period_end. Defaults to true."})}).strict()}))(_e,nS,mm,eS,um),{CreateInvoiceParamsSchema:yi}=((e,t,n,r,i)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(t).optional(),custom_line_items:e.array(n).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(r).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:i.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start \u2192 period_end against one price interval starting at period_start."}),period_end:i.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(o=>o.period_start===void 0==(o.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(o=>o.period_start===void 0||o.period_end===void 0||o.period_end>o.period_start,{message:"period_end must be after period_start."})}))(_e,rS,Cx,um,_x);var Sm=p.strictObject({requestId:p.uuid(),predecessorOperationId:p.uuid().optional(),invoiceMode:Nr.optional(),entityId:p.uuid().optional(),billingSubscriptionId:p.uuid().optional(),newBillingSubscription:p.literal(!0).optional(),offerId:p.uuid().optional(),nativeOffer:hi.optional(),plans:p.array(p.strictObject({productVersionId:p.uuid(),seatQuantities:p.record(Go,p.number().int().min(0).max(1e4)).optional(),featureQuantities:p.record(p.uuid(),p.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100,"At most 100 feature quantities").optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Plan versions must be unique"),provider:p.enum(["stripe","apple","google","merchant"]),currency:Ie}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||["apple","google"].includes(e.provider)&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||["stripe","merchant"].includes(e.provider)&&!e.billingSubscriptionId,"A new billing subscription has no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),Fr=p.strictObject({operationId:p.uuid()}),Dt=p.number().int().min(0).max(1e8),iS=p.strictObject({lineId:p.uuid(),productVersionId:p.uuid(),productName:p.string().min(1).max(80),interval:p.enum(["free","week","month","year","one_time"]),intervalCount:p.number().int().min(1).max(156).optional(),baseAmountMinor:Dt,seats:p.array(p.strictObject({key:Go,quantity:p.number().int().min(0).max(1e4),includedQuantity:p.number().int().min(0).max(1e4),maximumQuantity:p.number().int().min(0).max(1e4),unitAmountMinor:Dt})).max(20),prepaid:p.array(cp).max(100).optional(),catalogAmountMinor:Dt,trial:p.strictObject({days:p.number().int().min(1).max(730),cardRequired:p.boolean()}).nullable()}).refine(e=>new Set(e.seats.map(t=>t.key)).size===e.seats.length&&e.seats.every(t=>t.quantity>=t.includedQuantity&&t.quantity<=t.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((t,n)=>t+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((t,n)=>t+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"),Im=p.string().regex(/^[A-Za-z0-9_-]{1,200}$/),oS=p.strictObject({id:Im,name:p.string().min(1).max(40),percent_off:p.number().gt(0).max(100).optional(),amount_off:p.number().int().positive().optional(),currency:p.string().regex(/^[a-z]{3}$/).optional(),duration:p.enum(["once","repeating","forever"]),duration_in_months:p.number().int().min(1).max(36).optional()}).refine(e=>e.percent_off===void 0!=(e.amount_off===void 0)&&e.amount_off===void 0==(e.currency===void 0)&&e.duration==="repeating"==(e.duration_in_months!==void 0),"A Stripe coupon has one percentage or amount and months only when repeating"),aS=p.strictObject({subscriptionId:p.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:p.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:p.array(p.strictObject({id:p.string(),price_id:p.string(),quantity:p.number().int().nonnegative(),discounts:p.array(p.strictObject({id:p.string(),coupon:p.string(),start:p.number(),end:p.number().nullable()})).optional()})).min(1).max(100),prorationDate:p.number().int().nonnegative(),amountMinor:p.number().int().positive(),periodStartMs:p.number(),periodEndMs:p.number()}),vm=p.strictObject({invoiceMode:Nr.optional(),append:aS.optional(),provider:p.literal("stripe"),executor:p.enum(["indiana","merchant"]),accountId:p.string().regex(/^acct_[A-Za-z0-9]+$/),mode:p.enum(["payment","subscription"]),lineItems:p.array(p.strictObject({price:p.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:p.number().int().min(1).max(1e4),priceId:p.uuid(),productName:p.string().min(1).max(80),amountMinor:p.number().int().min(0).max(1e8),currency:p.string().regex(/^[a-z]{3}$/),interval:p.enum(["week","month","year","one_off"]),intervalCount:p.number().int().min(1).max(52),slot:p.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:p.strictObject({mode:p.enum(["graduated","volume"]),tiers:p.array(p.strictObject({upTo:p.number().int().min(1).max(1e6).nullable(),unitAmountMinor:p.number().int().min(0).max(1e8),flatAmountMinor:p.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:p.array(p.strictObject({coupon:Im,terms:oS})).max(1),trialPeriodDays:p.number().int().min(1).max(730).nullable(),metadata:p.strictObject({grooveCheckoutId:p.uuid(),grooveCustomerId:p.uuid()}),expiresAt:p.iso.datetime({offset:!0})}),Ai=p.strictObject({operationId:p.uuid(),entityId:p.uuid().nullable(),billingSubscriptionId:p.uuid().nullable(),discount:p.strictObject({offerId:p.uuid(),couponId:p.uuid(),discount:tr,duration:an,amountMinor:Dt,allocations:p.array(p.strictObject({productVersionId:p.uuid(),amountMinor:Dt})).min(1).max(20),expiresAt:p.iso.datetime({offset:!0})}).nullable(),charge:p.strictObject({effectiveAt:p.iso.datetime({offset:!0}),periodEndsAt:p.iso.datetime({offset:!0}),debitMinor:Dt,discountMinor:Dt,taxMinor:Dt,totalMinor:Dt}).nullable(),expiresAt:p.iso.datetime({offset:!0}),provider:p.enum(["stripe","apple","google","merchant"]),nativeOffer:hi.optional(),currency:Ie,lines:p.array(iS).min(1).max(20),catalogAmountMinor:Dt,automaticTax:p.boolean(),execution:p.union([vm,Bo]).nullable()}).refine(e=>e.provider==="merchant"?e.execution?.provider==="merchant"&&e.execution.operationId===e.operationId&&e.execution.catalogAmountMinor===e.catalogAmountMinor&&e.execution.currency===e.currency&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&e.execution.discount?.grantId===e.discount?.offerId:e.provider==="stripe"?e.execution?.provider!=="merchant"&&(e.lines[0]?.trial?.cardRequired===!1&&!e.execution?.invoiceMode?.enabled?e.execution===null&&e.discount===null:e.execution!==null&&e.execution.metadata.grooveCheckoutId===e.operationId&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.mode===(e.lines.some(t=>!["one_time","free"].includes(t.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(t=>t.price!==null))&&e.execution.discounts.every(t=>t.coupon===t.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(t=>e.discount!==null&&(t.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&t.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${t.terms.amount_off}`&&t.terms.amount_off===e.discount.discount.amountOffCents&&t.terms.currency?.toUpperCase()===e.currency&&t.terms.duration==="once"))):e.execution===null,"Stripe execution must carry the quote identity, expiry, mode, trial and held coupon").refine(e=>(!e.discount||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.discount.duration.type==="once")&&e.discount.amountMinor<=e.catalogAmountMinor&&e.discount.allocations.length===e.lines.length&&e.discount.allocations.every((t,n)=>{let r=e.lines[n];return r!==void 0&&t.productVersionId===r.productVersionId&&t.amountMinor<=r.catalogAmountMinor})&&e.discount.allocations.reduce((t,n)=>t+n.amountMinor,0)===e.discount.amountMinor)&&(["stripe","merchant"].includes(e.provider)?e.nativeOffer===void 0:e.nativeOffer!==void 0&&e.lines.length===1&&e.nativeOffer.discountMinor<=e.catalogAmountMinor&&e.nativeOffer.trialDays===(e.lines[0]?.trial?.days??null)&&(!e.discount||e.nativeOffer.discountMinor===e.discount.amountMinor))&&(!e.charge||e.billingSubscriptionId!==null&&e.charge.totalMinor===e.charge.debitMinor-e.charge.discountMinor+e.charge.taxMinor&&e.charge.discountMinor<=e.charge.debitMinor&&Date.parse(e.charge.periodEndsAt)>Date.parse(e.charge.effectiveAt))&&new Set(e.lines.map(t=>t.lineId)).size===e.lines.length&&e.lines.reduce((t,n)=>t+n.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),bi=p.strictObject({operationId:p.uuid(),orderId:p.uuid(),append:p.boolean().optional(),invoiceMode:p.boolean().optional(),status:p.enum(["pending","complete","cancelled","failed"]),executor:p.enum(["indiana","merchant"]),checkoutUrl:p.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:p.union([vm,Bo]).nullable(),currency:Ie,catalogAmountMinor:Dt,taxMinor:Dt,totalMinor:p.number().int().min(0).max(2e8).nullable(),quoteFinalized:p.boolean(),nativePurchase:_c.nullable(),confirmedAt:p.iso.datetime({offset:!0}).nullable().optional(),quote:Ai.optional(),merchantExecution:Ir.nullable().optional(),problem:Ui.nullable().optional(),authority:$o.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=p.strictObject({enabled:p.literal(!0),featureIds:p.array(p.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),wm=p.strictObject({requestId:p.uuid(),invoiceMode:Nr.optional(),membershipId:p.uuid(),carryOverBalances:Ca.optional(),carryOverUsages:Ca.optional(),membershipIds:p.array(p.uuid()).min(1).max(20).optional(),prorationBehavior:p.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:p.enum(["immediate","renewal","store"]),change:p.discriminatedUnion("type",[p.strictObject({type:p.literal("plan"),productVersionId:p.uuid()}),p.strictObject({type:p.literal("seats"),licenseKey:Go,quantity:p.number().int().min(0).max(1e4)}),p.strictObject({type:p.literal("quantity"),internal_feature_id:p.uuid(),quantity:p.number().int().min(0).max(1e4)}),p.strictObject({type:p.literal("cancel")}),p.strictObject({type:p.literal("uncancel")}),p.strictObject({type:p.literal("billing_cycle"),billingCycleAnchor:p.union([p.literal("now"),p.number().int().positive().max(0xe677d21fdbff)])})])}).refine(e=>e.timing!=="store"||e.change.type==="plan","Store timing applies to a native plan replacement").refine(e=>e.change.type!=="billing_cycle"||e.timing===(e.change.billingCycleAnchor==="now"?"immediate":"renewal"),"Use immediate for now and renewal for a future millisecond anchor").refine(e=>!e.membershipIds||["cancel","uncancel"].includes(e.change.type)&&e.membershipIds.includes(e.membershipId)&&new Set(e.membershipIds).size===e.membershipIds.length,"Grouped actions require unique cancel/uncancel targets including the primary membership").refine(e=>!e.carryOverBalances&&!e.carryOverUsages||e.change.type==="plan"&&e.timing==="immediate","Carry applies only to immediate upgrades").refine(e=>!e.prorationBehavior||e.change.type==="quantity","prorationBehavior applies to prepaid quantity changes"),Pa=p.string().regex(/^price_[A-Za-z0-9]+$/),bm=p.strictObject({grooveUpdateId:p.uuid(),grooveCustomerId:p.uuid()}),xm=p.strictObject({price:Pa.nullable(),priceId:p.uuid().optional(),quantity:p.number().int().min(0).max(1e4)}),Om=p.strictObject({provider:p.literal("stripe"),invoiceMode:Nr.optional(),executor:p.enum(["indiana","merchant"]),accountId:p.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:p.string().regex(/^sub_[A-Za-z0-9]+$/),action:p.enum(["update","cancel","schedule","release"]),update:p.strictObject({items:p.array(xm).max(20),remove:p.array(Pa).max(20),restoreItems:p.array(p.strictObject({price:Pa,quantity:p.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:p.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:p.number().int().positive().optional(),paymentBehavior:p.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:p.boolean().optional(),clearCancelAt:p.literal(!0).optional(),billingCycleAnchorNow:p.literal(!0).optional(),metadata:bm}).nullable(),cancel:p.strictObject({prorate:p.literal(!1),invoiceNow:p.literal(!1)}).nullable(),schedule:p.strictObject({currentItems:p.array(p.strictObject({price:Pa,quantity:p.number().int().min(0).max(1e4)})).max(20),nextItems:p.array(xm).min(1).max(20),switchAt:p.number().int().positive(),interval:p.enum(["week","month","year"]),intervalCount:p.number().int().min(1).max(52),resetBillingCycleAnchor:p.literal(!0).optional(),metadata:bm}).nullable(),release:p.strictObject({schedule:p.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:p.iso.datetime({offset:!0})}).refine(e=>["update","cancel","schedule","release"].every(t=>e[t]!==null==(e.action===t))&&(e.executor==="indiana"||[...e.update?.items??[],...e.schedule?.nextItems??[]].every(t=>t.price!==null)),"Stripe update execution carries exactly its action, with bound Prices for the merchant"),_a=p.strictObject({carryOverBalances:Ca.optional(),carryOverUsages:Ca.optional(),operationId:p.uuid(),membershipId:p.uuid(),productVersionId:p.uuid(),timing:p.enum(["immediate","renewal"]),effectiveAt:p.iso.datetime({offset:!0}),expiresAt:p.iso.datetime({offset:!0}),currency:Ie,creditMinor:Dt,debitMinor:Dt,discountMinor:Dt,taxMinor:Dt,totalMinor:Dt,retainedProductVersionIds:p.array(p.uuid()).max(19),execution:p.union([Om,Vo])}),sS=p.strictObject({operationId:p.uuid(),invoiceMode:p.boolean().optional(),membershipId:p.uuid(),productVersionId:p.uuid(),status:p.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:p.enum(["immediate","renewal"]),effectiveAt:p.iso.datetime({offset:!0}),checkoutUrl:p.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:p.enum(["indiana","merchant"]),execution:p.union([Om,Vo]).nullable(),confirmedAt:p.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Ir.nullable().optional(),problem:Ui.nullable().optional(),quote:_a.optional(),authority:$o.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),cS=p.strictObject({operationId:p.uuid(),membershipId:p.uuid(),productVersionId:p.uuid(),timing:p.literal("store"),effectiveAt:p.null(),expiresAt:p.iso.datetime({offset:!0}),currency:Ie,creditMinor:p.null(),debitMinor:p.null(),discountMinor:p.null(),taxMinor:p.null(),totalMinor:p.null(),retainedProductVersionIds:p.array(p.uuid()).max(19),store:p.strictObject({provider:p.enum(["apple","google"]),productId:p.string().min(1).max(255),catalogAmountMinor:Dt,policy:p.enum(["apple_store","google_full_price"])})}),uS=p.strictObject({operationId:p.uuid(),membershipId:p.uuid(),productVersionId:p.uuid(),status:p.enum(["prepared","pending","effective","cancelled","failed"]),timing:p.literal("store"),effectiveAt:p.iso.datetime({offset:!0}).nullable(),checkoutUrl:p.null(),nativePurchase:_c.nullable()}),Pm=p.union([_a,cS]),Rc=p.union([sS,uS]),uo=p.number().int().positive().max(2e8),Dr=p.number().int().min(0).max(2e8),Cm=p.strictObject({requestId:p.uuid(),invoiceId:p.uuid(),mode:p.enum(["full","partial"]),amountMinor:uo.optional(),entitlementAction:p.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),_m=p.strictObject({provider:p.literal("stripe"),executor:p.enum(["indiana","merchant"]),accountId:p.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:p.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:uo,currency:p.string().regex(/^[a-z]{3}$/),metadata:p.strictObject({indianaRefundId:p.uuid()}),idempotencyKey:p.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:p.array(p.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),kc=p.strictObject({operationId:p.uuid(),invoiceId:p.uuid(),providerInvoiceId:p.string().min(1).max(200),currency:Ie,paidMinor:Dr,refundedMinor:Dr,pendingMinor:Dr,amountMinor:uo,mode:p.enum(["full","partial"]),entitlementAction:p.enum(["retain","revoke"]),revokes:p.strictObject({customerProductIds:p.array(p.uuid()).max(100),subscriptionIds:p.array(p.string().min(1).max(200)).max(20)}),execution:p.union([_m,Lo]),expiresAt:p.iso.datetime({offset:!0})}).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&(e.execution.provider==="merchant"?e.execution.merchantInvoiceId===e.providerInvoiceId&&e.execution.operationId===e.operationId&&e.execution.currency===e.currency:e.execution.invoice===e.providerInvoiceId&&e.execution.metadata.indianaRefundId===e.operationId&&e.execution.currency===e.currency.toLowerCase())&&(e.entitlementAction==="revoke"||e.revokes.customerProductIds.length===0&&e.revokes.subscriptionIds.length===0),"Refund quote must stay within the refundable amount and match its execution"),Ea=p.strictObject({operationId:p.uuid(),invoiceId:p.uuid(),providerInvoiceId:p.string().min(1).max(200),status:p.enum(["quoted","pending","succeeded","failed","expired"]),executor:p.enum(["indiana","merchant"]),currency:Ie,amountMinor:uo,mode:p.enum(["full","partial"]),entitlementAction:p.enum(["retain","revoke"]),refundId:p.string().min(1).max(200).nullable(),quote:kc.optional(),execution:p.union([_m,Lo]).nullable(),confirmedAt:p.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Ir.nullable().optional(),problem:Ui.nullable().optional(),authority:$o.optional(),failureReason:p.string().min(1).max(200).nullable(),createdAt:p.iso.datetime({offset:!0}),completedAt:p.iso.datetime({offset:!0}).nullable()}).refine(e=>(e.execution===null||e.executor==="merchant"&&e.status==="quoted")&&(e.status!=="succeeded"||e.refundId!==null),"Only quoted record-only refunds carry instructions; a succeeded refund names its Stripe refund"),t_=p.strictObject({invoiceId:p.uuid(),currency:Ie,paidMinor:Dr,refundedMinor:Dr,pendingMinor:Dr,refundableMinor:Dr,executor:p.enum(["indiana","merchant"]).nullable(),canRefund:p.boolean(),operations:p.array(Ea).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),n_=p.strictObject({requestId:p.uuid(),mode:p.enum(["full","partial"]),amountMinor:uo.optional(),entitlementAction:p.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount");var Em=ot.strictObject({requestId:ot.uuid(),targets:ot.array(ot.strictObject({membershipId:ot.uuid(),action:ot.enum(["cancel","uncancel"]),timing:ot.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"),Ra=ot.strictObject({batchId:ot.uuid()}),lS=ot.strictObject({operationId:ot.uuid(),membershipIds:ot.array(ot.uuid()).min(1).max(20),provider:ot.enum(["stripe","apple","google"]),action:ot.enum(["cancel","uncancel"]),timing:ot.enum(["immediate","renewal"]),status:ot.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:_a.nullable(),managementUrl:ot.url().nullable(),failureCode:ot.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),lo=ot.strictObject({batchId:ot.uuid(),ready:ot.boolean(),status:ot.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:ot.iso.datetime({offset:!0}),acceptedAt:ot.iso.datetime({offset:!0}).nullable(),groups:ot.array(lS).min(1).max(100)});import{z as ke}from"zod";var dS=ke.string().trim().min(1).max(240),jc={requestId:ke.uuid(),reason:dS},ka=ke.discriminatedUnion("action",[ke.strictObject({...jc,action:ke.literal("start"),productVersionId:ke.uuid(),entityId:ke.uuid().optional(),days:ke.number().int().min(1).max(730).optional()}),ke.strictObject({...jc,action:ke.literal("extend"),membershipId:ke.uuid(),days:ke.number().int().min(1).max(730)}),ke.strictObject({...jc,action:ke.literal("end"),membershipId:ke.uuid()})]),Rm=ke.strictObject({operationId:ke.uuid()}),km=ke.iso.datetime({offset:!0}),pS=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"),km]),prorationBehavior:ke.literal("none")}),Tc=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:km.nullable(),execution:pS.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"),c_=ke.strictObject({groupId:ke.uuid(),productVersionId:ke.uuid(),enabled:ke.boolean()});import{z as Ze}from"zod";var jm=Ze.strictObject({requestId:Ze.uuid(),currency:Ie,makeDefault:Ze.boolean()}),Tm=Ze.strictObject({setupId:Ze.uuid()}),mS=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})}),Nc=Ze.strictObject({id:Ze.uuid(),provider:Ze.literal("stripe"),status:Ze.enum(["prepared","complete","expired"]),currency:Ie,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:mS.nullable()});import{z as Ft}from"zod";var Nm=Ft.union([Ft.string(),Ft.number(),Ft.boolean(),Ft.null()]),Dm=Ft.strictObject({customerId:Ft.uuid()}),Fm=Ft.strictObject({customerId:Ft.uuid(),provider:Ft.literal("stripe"),checkedAt:Ft.iso.datetime({offset:!0}),status:Ft.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Ft.number().int().nonnegative(),differences:Ft.array(Ft.strictObject({subscriptionId:Ft.string().startsWith("sub_"),itemId:Ft.string().nullable(),field:Ft.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Nm,actual:Nm})).max(1e4)});import{z as we}from"zod";var ja=we.iso.datetime({offset:!0}),Ta=we.strictObject({createdAt:ja,id:we.uuid()}),Na=we.strictObject({customerId:we.uuid().optional(),entityId:we.uuid().optional(),productId:we.string().min(1).max(256).optional(),provider:we.enum(["stripe","apple","google","merchant","free"]).optional(),status:we.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:Ta.optional(),limit:we.number().int().min(1).max(100).optional()}),Dc={id:we.uuid(),customerId:we.uuid(),entityId:we.uuid().nullable(),productId:we.string().min(1).max(256),productVersionId:we.uuid(),name:we.string().min(1).max(120),provider:we.enum(["stripe","apple","google","merchant","free"]),createdAt:ja},fS=we.strictObject({...Dc,status:we.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:we.boolean(),billingSubscriptionId:we.uuid().nullable()}),gS=we.strictObject({...Dc,status:we.enum(["active","ended","refunded"]),orderId:we.uuid().nullable(),transactionId:we.uuid().nullable(),currency:Ie.nullable(),amountMinor:we.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),hS=we.strictObject({...Dc,status:we.enum(["blocked","resolved"]),conflict:we.strictObject({detectedAt:ja,blockingMembershipIds:we.array(we.uuid()).min(1).max(100),transactionId:we.uuid()}),resolvedAt:ja.nullable()}),Mm=Na.extend({status:we.enum(["blocked","resolved"]).optional()}),qm=we.strictObject({customerId:we.uuid(),orderId:we.uuid()}),Um=we.strictObject({orderId:we.uuid(),status:we.enum(["blocked","resolved"])}),Bm=we.strictObject({items:we.array(fS).max(100),nextCursor:Ta.nullable()}),Vm=we.strictObject({items:we.array(gS).max(100),nextCursor:Ta.nullable()}),Lm=we.strictObject({items:we.array(hS).max(100),nextCursor:Ta.nullable()});import{z as tt}from"zod";var zm=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)})]),$m=tt.strictObject({requestId:tt.uuid(),orderId:tt.uuid(),purchaseIntentId:tt.uuid(),status:tt.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:Ie,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 L}from"zod";var Mc=L.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),yS=L.record(L.string(),L.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),AS=3,po=20,bS=AS*po,Fc=L.strictObject({type:L.literal("product"),productId:Mc}),Gm={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)},xS=L.discriminatedUnion("type",[Fc,L.strictObject({...Gm,items:L.array(Fc).max(po)})]),SS=L.discriminatedUnion("type",[Fc,L.strictObject({...Gm,items:L.array(xS).max(po)})]),IS=L.array(SS).max(po).superRefine((e,t)=>{let n=new Set,r=new Set,i=0;function a(o){for(let s of o){i++;let c=s.type==="product"?n:r,u=s.type==="product"?s.productId:s.key;c.has(u)&&t.addIssue({code:"custom",message:s.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),c.add(u),s.type==="group"&&a(s.items)}}a(e),(n.size>po||i>bS)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function qc(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:qc(t))}var xi=L.strictObject({lookupKey:L.string().trim().min(1).max(200),displayName:L.string().trim().min(1).max(1500),items:IS,metadata:yS}),vS=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()))}),Km=xi.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"})}),Hm=L.strictObject({id:L.uuid(),offeringId:L.uuid(),projectId:L.uuid(),environmentId:L.uuid(),version:L.number().int().positive(),document:xi,productEvidence:L.record(Mc,vS),createdAt:L.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=qc(e.document);(!n.length||PS(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"})}),wS=L.strictObject({rows:L.array(Km).max(200),versions:L.array(Hm).max(500)}),I_=L.discriminatedUnion("action",[L.strictObject({action:L.literal("create"),document:xi}),L.strictObject({action:L.literal("save"),id:L.uuid(),revision:L.number().int().nonnegative(),document:xi}),L.strictObject({action:L.enum(["publish","set_current","archive","restore"]),id:L.uuid(),revision:L.number().int().nonnegative()})]),v_=L.strictObject({record:Km,version:Hm.nullable()}),Qm=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()})]),OS=L.strictObject({internalId:Mc,id:L.string(),name:L.string().nullable(),version:L.number().int().positive(),archived:L.boolean()}),w_=wS.extend({products:L.array(OS).max(500),pagination:L.strictObject({rows:L.string().nullable(),versions:L.string().nullable(),products:L.string().nullable()}).optional()});function PS(e){let t=[];qc(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 Da}from"zod";var Jm=Da.strictObject({id:Da.uuid(),offeringId:Da.uuid(),version:Da.number().int().positive(),document:xi});import{z as Pt}from"zod";import{z as ye}from"zod";import{z as Si}from"zod";var Fa=Si.strictObject({items:Si.array(Si.strictObject({productVersionId:Si.string().min(1).max(200),label:Si.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:Si.string().min(1).max(200).nullable(),grouping:ya.optional()});function Zm(e,t,n){let r=e.type==="fixed"?e.productVersionId:t[e.pickerId];return typeof r!="string"||!Object.values(n.plans).some(i=>i.versionId===r&&i.available)||e.type==="picker"&&(!e.allowedProductVersionIds.includes(r)||!n.pickers[e.pickerId]?.options.includes(r))?null:r}var Uc=ye.discriminatedUnion("type",[ye.strictObject({type:ye.literal("event"),event:ye.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),ye.strictObject({type:ye.literal("open_url"),url:ye.url().refine(e=>new URL(e).protocol==="https:")})]),CS=cn,_S=ye.discriminatedUnion("type",[ye.object({type:ye.literal("checkout"),product:ba}).strict(),ye.object({type:ye.literal("close")}).strict(),ye.object({type:ye.literal("action"),action:Uc}).strict()]),Ii=ye.object({schemaVersion:ye.literal(3),kind:ye.literal("paywall"),name:ye.string().trim().min(1).max(80),presentation:On,requirement:rr.optional(),products:Fa,offeringVersionId:ye.uuid().nullable(),offeringId:ye.uuid(),screen:CS,buttons:ye.record(ye.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),_S)}).strict(),U_=Ii.superRefine((e,t)=>{(e.screen.surface!=="paywall"||e.screen.actions.some(r=>!["event","navigate"].includes(r.type)||r.close))&&t.addIssue({code:"custom",message:"Paywall screen is incomplete"});for(let r of RS(e))t.addIssue({code:"custom",message:r});for(let r of ES(e))t.addIssue({code:"custom",message:r});ir(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 ES(e){let t=e.products.items.map(a=>a.productVersionId),n=Mp(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&&(!Aa(e.products.grouping,t)||e.products.grouping.tiers.some(a=>!e.products.grouping.assignments.some(o=>o.tierId===a.id)))&&i.push("grouping");for(let a of Object.values(e.buttons))if(a.type==="checkout"){let o=a.product;if(o.type==="fixed")r.add(o.productVersionId);else{o.allowedProductVersionIds.forEach(u=>r.add(u));let s=!1,c=n[o.pickerId];c&&(s=!0,(o.allowedProductVersionIds.some(u=>!c.ids.includes(u))||c.ids.some(u=>!o.allowedProductVersionIds.includes(u)))&&i.push("picker")),Gt(e.screen,u=>{if(u.id!==o.pickerId||u.type!=="plan_picker")return;s=!0,(JSON.stringify(u.planIds)!==JSON.stringify(t)||JSON.stringify(o.allowedProductVersionIds)!==JSON.stringify(t)||u.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let l=u.grouping?{tiers:u.grouping.tiers,assignments:u.grouping.assignments}:void 0;JSON.stringify(l)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),s||i.push("picker")}}return(!r.size||[...r].some(a=>!t.includes(a)))&&i.push("purchase"),Gt(e.screen,a=>{a.type==="stack"&&a.productSlot&&!a.bind?.plan&&i.push(`productBinding:${a.id}`),(a.type==="stack"||a.type==="button")&&a.bind?.plan&&!t.includes(a.bind.plan)&&i.push("binding"),a.type==="plan_picker"&&(!a.planIds?.length||a.planIds.some(o=>!t.includes(o)))&&i.push("binding")}),[...new Set(i)]}function RS(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),Jn(s.root,c=>{let u=c.type==="button"?c.action:c.type==="stack"?c.purchaseAction:void 0;if(u){let l=e.screen.actions.find(f=>f.id===u);l?.type==="navigate"&&r.get(s.id).push(l.pageId);let m=e.buttons[u];s.id!==n.id&&m&&m.type!=="close"&&t.push(`purchaseScreen:${c.id}`)}s.id!==n.id&&(c.type==="plan_picker"||c.type==="stack"&&c.productSlot)&&t.push(`packageScreen:${c.id}`)});let i=new Set;function a(s){if(!i.has(s)){i.add(s);for(let c of r.get(s)??[])a(c)}}let o=e.screen.initialPageId??e.screen.pages[0]?.id;o?a(o):t.push("initialPage");for(let s of e.screen.pages)i.has(s.id)||t.push(`unreachableScreen:${s.id}`);return[...new Set(t)]}var Wm=ye.object({id:ye.uuid(),projectId:ye.uuid(),environmentId:ye.uuid(),revision:ye.number().int().nonnegative(),state:ye.enum(["active","archived"]),publishedVersionId:ye.uuid().nullable(),updatedAt:ye.iso.datetime({offset:!0}),draft:Ii}).strict(),B_=ye.object({rows:ye.array(Wm).max(200),nextCursor:ye.uuid().nullable()}).strict(),V_=Wm.omit({draft:!0}).extend({name:ye.string(),productCount:ye.number().int().nonnegative()}).strict(),L_=ye.discriminatedUnion("action",[ye.object({action:ye.literal("save"),id:ye.uuid().nullable(),revision:ye.number().int().nonnegative(),document:Ii}).strict(),ye.object({action:ye.enum(["publish","archive"]),id:ye.uuid(),revision:ye.number().int().nonnegative()}).strict()]),z_=ye.object({paywalls:ye.array(ye.object({id:ye.uuid(),paywallId:ye.uuid(),version:ye.number().int().positive(),name:ye.string().min(1).max(80),presentation:On,buttons:Ii.shape.buttons}).strict()).max(500),limited:ye.boolean()}).strict();import{z as Ee}from"zod";import{z as Kt}from"zod";var vi=Kt.string().regex(/^[a-f0-9]{64}$/),kS=ga.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),Ym=Kt.strictObject({couponDigests:Kt.record(Kt.uuid(),vi),variables:Kt.record(Sn,Kt.record(Kt.uuid(),Kt.partialRecord(Kt.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),Kt.string()))),locales:Kt.record(Sn,li.extend({nodes:Kt.record(Kt.string(),Kt.strictObject({base:kS})),plans:Kt.object({}).strict(),pickers:Kt.object({}).strict()}).omit({paywall:!0}))});import{z as Be}from"zod";import{z as Ma}from"zod";var Bc=Ma.strictObject({eventsEnabled:Ma.boolean(),experimentViewsEnabled:Ma.boolean(),featureUsageEnabled:Ma.boolean()}),Z_=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function Xm(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}import{z as $}from"zod";var Vc=$.tuple([$.number().min(0).max(1),$.number().min(0).max(1)]).refine(([e,t])=>e<=t),jS=$.strictObject({attribute:$.string().optional(),seed:$.string(),hashVersion:$.literal(2),ranges:$.array(Vc).max(100)}),TS=$.strictObject({id:$.string().min(1).max(255),condition:Yt,gate:$.boolean().optional()}),NS=$.strictObject({key:$.string().optional(),name:$.string().optional(),passthrough:$.boolean().optional()}),ef={condition:Yt.optional(),parentConditions:$.array(TS).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(jS).max(100).optional(),ranges:$.array(Vc).max(20).optional(),meta:$.array(NS).max(20).optional(),seed:$.string().optional(),name:$.string().optional(),phase:$.string().optional()},wi=$.strictObject({...ef,key:$.string().min(1).max(255),variations:$.tuple([ve,ve]).rest(ve).refine(e=>e.length<=20),urlPatterns:$.array($.strictObject({include:$.boolean(),type:$.enum(["regex","simple"]),pattern:$.string()})).max(100).optional(),force:$.number().int().nonnegative().optional(),active:$.boolean().optional(),persistQueryString:$.boolean().optional()}),Lc=$.strictObject({value:ve,variationId:$.number().int(),key:$.string(),name:$.string().optional(),bucket:$.number().optional(),passthrough:$.boolean().optional(),inExperiment:$.boolean(),hashUsed:$.boolean().optional(),hashAttribute:$.string(),hashValue:$.string(),featureId:$.string().nullable(),stickyBucketUsed:$.boolean().optional()}),DS=$.strictObject({...ef,id:$.string().max(255).optional(),force:ve.optional(),variations:$.array(ve).min(2).max(20).optional(),key:$.string().optional(),range:Vc.optional(),tracks:$.array($.strictObject({experiment:wi,result:Lc})).max(100).optional()}),FS=$.strictObject({defaultValue:ve.optional(),rules:$.array(DS).max(500).optional()}),mo=$.record($.string(),$.union([$.strictObject({type:$.literal("hashed"),attributeKey:$.string(),values:$.array($.string().regex(/^[a-f0-9]{64}$/))}),$.strictObject({type:$.literal("list"),attributeKey:$.string(),values:$.array($.union([$.string(),$.number()]))}),$.strictObject({type:$.literal("condition"),condition:Yt})])),hn=$.strictObject({scope:Te,generation:$.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:$.iso.datetime({offset:!0}),expiresAt:$.iso.datetime({offset:!0}).nullable(),features:$.record($.string(),FS),savedGroups:mo,experiments:$.record($.uuid(),wi)});var fo=hn.extend({analyticsConfig:Bc,remoteFeatures:Be.array(Be.string().min(1).max(255)).max(500)}),zc=fo.omit({evaluatedAt:!0,expiresAt:!0}).superRefine((e,t)=>{for(let n of e.remoteFeatures)Object.hasOwn(e.features,n)&&t.addIssue({code:"custom",path:["features",n],message:"Remote Feature definitions cannot be public"});for(let[n,r]of Object.entries(e.savedGroups))r.type==="list"&&t.addIssue({code:"custom",path:["savedGroups",n],message:"Raw Saved Group lists cannot be public"})}),tf=Be.strictObject({attributes:vt,features:Be.array(Be.string().min(1).max(255)).max(500).optional(),customerId:Be.uuid().optional()}),MS=Be.strictObject({value:ve,source:Be.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:Be.boolean(),off:Be.boolean(),ruleId:Be.string(),experimentResult:Lc.optional()}),qa=Be.strictObject({generation:hn.shape.generation,evaluatedAt:hn.shape.evaluatedAt,expiresAt:hn.shape.expiresAt,features:Be.record(Be.string(),MS),merchandiseContext:Be.strictObject({merchandiseId:Be.uuid(),merchandise:vt}).optional()}),nf=Be.strictObject({customerId:Be.uuid().optional(),events:Be.array(Be.strictObject({eventUuid:Be.uuid(),timestamp:Be.iso.datetime({offset:!0}),name:Be.string().min(1).max(255),merchandise:Md.optional(),properties:Be.record(Be.string(),ve).default({}),deviceId:Be.string().min(1).max(255).optional(),sessionId:Be.string().min(1).max(255).optional()})).min(1).max(100)}),rf=Be.strictObject({inserted:Be.number().int().nonnegative(),duplicates:Be.number().int().nonnegative(),rejected:Be.number().int().nonnegative(),skipped:Be.number().int().nonnegative(),analyticsConfig:Bc});import{z}from"zod";import{z as qS}from"zod";var of=qS.enum(["funnel-run/1","funnel-process/1"]),af="funnel-process/1";function $c(e,t=[]){let n=[];Gt(e,i=>{i.hidden&&n.push("Hidden components must not be delivered"),t.includes(i.type)&&n.push(`Node type ${i.type} cannot be delivered`)});let r=new Set(xa(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 sf(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>sf(t)??[])}}function US(e){let t=e.pages.map(i=>{let a=sf(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(xa({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 cf(e,t=[]){let n=cn.parse(structuredClone(US(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=$c(n,t);if(i.length)throw new Error(i.join("; "));return n}import{z as Q}from"zod";import{z as M}from"zod";import{z as pt}from"zod";var Ua=pt.strictObject({schemaVersion:pt.literal(1),renderKey:pt.string().min(1).max(256),routeTemplate:pt.string().startsWith("/").max(2048),selectors:pt.array(pt.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:pt.array(pt.number().int().min(0)).min(1),absent:pt.array(pt.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"})}),uf=pt.strictObject({renderKey:pt.string().min(1).max(256),routeKey:pt.string().min(1).max(256),stateKey:pt.string().min(1).max(256),documentKey:pt.string().min(1).max(256),documentHash:pt.string().regex(/^[a-f0-9]{64}$/),compositionKey:pt.string().min(1).max(256),entryMode:pt.enum(["hard","soft"]),match:pt.strictObject({present:pt.array(pt.number().int().min(0)),absent:pt.array(pt.number().int().min(0))})});import{z as Mr}from"zod";var BS=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],Gc="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",VS=Mr.string().regex(new RegExp(`^${Gc}/${Gc}/${Gc}/manifest\\.json$`)),lf=Mr.strictObject({kind:Mr.literal("gcs-resumable"),url:Mr.url(),bucket:Mr.enum(BS),objectKey:VS,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 ht=M.string().min(1).max(256),ln=M.string().regex(/^[a-f0-9]{64}$/),Ba=M.strictObject({versionId:M.uuid(),manifestDigest:ln,sourceGraphDigest:ln,pageKey:ht,stateKey:ht,documentKey:ht,documentHash:ln,elementKey:ht.optional(),nodeId:ht.optional(),contentHash:ln.optional(),renderKey:ht.optional()}),df=M.strictObject({pageKey:ht,documentKey:ht,expectedDocumentHash:ln,renderKey:ht.optional(),nodeId:ht,elementKey:ht,expectedContentHash:ln,property:M.enum(["text","fontSize","color"]),value:M.union([M.string().max(4e3),M.number().finite()])}),pf=M.strictObject({versionId:M.uuid(),manifestDigest:ln,sourceGraphDigest:ln,pageKey:ht,stateKey:ht,documentKey:ht,documentHash:ln,renderKey:ht.optional(),patches:M.array(df.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),LS=/^[a-z][a-z0-9-]{0,39}$/,go=M.string().regex(LS),Hc=M.enum(["web","ios","android"]),b1=M.discriminatedUnion("action",[M.strictObject({action:M.literal("register"),requestId:M.uuid(),client:go,platform:Hc,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:ht,changesetId:M.uuid().nullable(),expectedRevision:ln.nullable(),editorUrl:M.string().url().max(2048),patches:M.array(df).max(200)})]),Qc=M.strictObject({id:M.uuid(),projectId:M.uuid(),environmentId:M.uuid(),clientKey:go,platform:Hc,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())}),zS=M.strictObject({key:go,platform:Hc,currentId:M.uuid().nullable()}),x1=M.strictObject({rows:M.array(Qc).max(100),nextCursor:M.uuid().nullable(),clients:M.array(zS).max(20)}),Kc=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()}),S1=M.strictObject({asOf:M.iso.datetime({offset:!0}),reclamation:M.literal("manual-review-required"),buckets:M.strictObject({source:Kc,runtime:Kc,previews:Kc})}),I1=M.strictObject({version:Qc,actorId:M.uuid(),claims:M.record(M.string(),M.json())}),v1=M.strictObject({version:Qc,upload:lf.nullable()}),w1=M.object({format:M.literal("indiana-route-state-index"),schemaVersion:M.literal(3),routes:M.array(M.object({routeKey:ht,path:M.string(),documentKey:ht,documentHash:ln,initialStateKey:ht,initialRenderKey:ht})),renders:M.array(uf)}).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"})}),O1=M.strictObject({rows:M.array(M.object({id:M.uuid(),name:M.string(),status:M.string(),variations:M.array(M.object({id:ht,key:ht,name:M.string().optional()}).loose())}).loose()),limited:M.boolean()}),P1=M.strictObject({enabled:M.boolean(),allowedOrigins:M.array(M.string())});import{z as Oi}from"zod";var mf=Oi.strictObject({id:Oi.uuid(),name:Oi.string().trim().min(1).max(80),client:go,source:Ba,event:Oi.enum(["screen_enter","button_click"]),cooldownSeconds:Oi.number().int().min(0).max(2592e3),behavior:Oi.literal("observe")}).superRefine((e,t)=>{e.event==="button_click"&&(!e.source.nodeId||!e.source.elementKey)&&t.addIssue({code:"custom",path:["source"],message:"Choose a uniquely bound button"})});import{z as Ge}from"zod";var Jc=ve,$S=["parameters","answers","results","variables"];function Zc(e){return $S.some(t=>e===t||e.startsWith(t+"."))}function Wc(e){let t={};for(let[r,i]of Object.entries(Sa(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])=>!Zc(r))),variables:t}}import{z as yt}from"zod";var Va=yt.discriminatedUnion("kind",[yt.object({kind:yt.literal("ledger"),cursor:fa}).strict(),yt.object({kind:yt.literal("billing"),cursor:yt.uuid()}).strict()]),GS=yt.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ar=yt.record(yt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),yt.union([yt.string().max(500),yt.boolean(),yt.array(yt.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),KS=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function Yc(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>Yc(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||KS.test(n)||Yc(r,t+1)))}var HS=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,sr=yt.record(GS,ve).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!Yc(e)&&!HS.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var ff=yt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),La=yt.array(yt.object({variable:ff,componentId:ff,required:yt.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"),q1=yt.object({bindings:La,answers:ar,values:yt.record(yt.string(),ve).optional()}).strict();import{z as QS}from"zod";var za=QS.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var Xc=Ge.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),gf=Ge.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),hf=sr.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),eu=Ge.record(Xc,Ge.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),JS=Dn,yf=Ge.strictObject({type:Ge.literal("external_task"),endpointId:Ge.uuid(),taskKey:Xc,inputs:Ge.record(Xc,JS).refine(e=>Object.keys(e).length<=20),outputs:eu}),Af=Ge.strictObject({maxAttempts:Ge.number().int().min(1).max(5),retryDelaySeconds:Ge.number().int().min(1).max(30),backoff:Ge.enum(["fixed","exponential"]),requestTimeoutSeconds:Ge.number().int().min(1).max(10),timeoutSeconds:Ge.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var Q1=Ge.strictObject({outcome:Ge.enum(["success","failure"]),data:hf});var J1=Ge.discriminatedUnion("operation",[Ge.strictObject({operation:Ge.literal("signal"),runId:Ge.uuid(),nodeId:gf,eventName:za,eventId:Ge.uuid(),data:hf}),Ge.strictObject({operation:Ge.literal("read_results"),runId:Ge.uuid()})]),Z1=Ge.strictObject({scope:Te,runId:Ge.uuid(),eventId:Ge.uuid(),accepted:Ge.boolean()}),ZS=Ge.record(gf,Jc),W1=Ge.strictObject({scope:Te,runId:Ge.uuid(),results:ZS});var En={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},bf="00000000-0000-0000-0000-000000000000";import{z as Z}from"zod";import{z as We}from"zod";var rE=We.enum(["local","remote"]),tu=We.strictObject({port:We.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:ve.optional(),sticky:We.array(We.strictObject({expected:$i.nullable(),next:$i})).max(100),exposures:We.array(ve).max(100),features:We.array(ve).max(100)}),xf=We.strictObject({type:We.literal("evaluate"),receiptId:We.uuid(),environmentId:We.uuid(),policyRevision:We.number().int().nonnegative(),attributes:vt,sticky:We.record(We.string(),$i)}),Sf=xf.extend({runId:We.uuid(),versionId:We.uuid(),nodeId:We.string().min(1).max(64),visit:We.number().int().nonnegative(),revision:We.number().int().nonnegative()}),nu=xf.omit({type:!0,receiptId:!0}).extend({type:We.literal("evaluate_segment")}),If=We.strictObject({nodeId:We.string().min(1).max(64),result:tu}),vf=nu.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:sr,answers:ar,variables:We.record(We.string(),ve)});import{z as ue}from"zod";var ru=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"),$a=ue.intersection(vt,ue.looseObject({tags:ru.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),Ga=ue.string().trim().max(80),Ka=ue.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),Ha=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"),wf=ue.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),Of=ue.object({externalUserId:wf.optional(),name:Ga.default(""),email:Ha.default(""),phone:Ka.optional(),attributes:$a.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),qr=ue.discriminatedUnion("type",[ue.strictObject({type:ue.literal("id"),value:ue.uuid()}),ue.strictObject({type:ue.literal("externalUserId"),value:wf})]),Pi=ue.strictObject({name:Ga.optional(),email:Ha.optional(),phone:Ka.optional(),attributes:$a.optional(),fingerprint:Qa.optional()}),Ja=e=>!e.customerData||e.customer?.type==="externalUserId",Za="customerData requires an externalUserId customer",Ci=ue.object({id:ue.uuid(),externalUserId:ue.string().min(1).max(255).nullable(),name:Ga,email:Ha,phone:Ka.optional(),attributes:$a,createdAt:ue.iso.datetime()}).strict(),Pf=ue.object({customer:Ci,changed:ue.boolean(),replayed:ue.boolean()}).strict(),WS=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()]),YS=ue.object({name:Ga.optional(),email:Ha.optional(),phone:Ka.optional(),attributes:$a.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:ru,remove:ru}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),iu=ue.object({lookup:WS}).strict(),Cf=iu.extend({requestId:ue.uuid(),patch:YS}).strict(),_f=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(),Ef=ue.object({customers:Ci.array(),hasMore:ue.boolean(),total:ue.number().int().nonnegative().nullable(),evaluatedAt:ue.iso.datetime()}).strict();var ho=Z.discriminatedUnion("type",[Z.strictObject({type:Z.literal("literal"),value:ve}),Z.strictObject({type:Z.literal("variable"),key:St,path:_n.optional()}),Z.strictObject({type:Z.literal("feature"),featureKey:Z.string().min(1).max(128)})]),XS=Z.strictObject({requestId:Z.uuid(),decisionId:Z.uuid(),customerId:Z.uuid(),externalUserId:Z.string().min(1).max(255).nullable(),versionId:Z.uuid(),receiptId:Z.uuid(),value:ve}),e0={funnelId:Z.uuid(),requestId:Z.uuid(),customer:qr,customerData:Pi.optional(),attributes:vt.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},gE=Z.discriminatedUnion("operation",[Z.strictObject({operation:Z.literal("decide"),...e0}).refine(Ja,Za),Z.strictObject({operation:Z.literal("read_decision"),decisionId:Z.uuid()}),Z.strictObject({operation:Z.literal("evaluate_decision"),decisionId:Z.uuid(),requestId:Z.uuid(),nodeId:Z.string().min(1).max(64),visit:Z.number().int().nonnegative(),revision:Z.number().int().nonnegative(),receiptId:Z.uuid(),policyRevision:Z.number().int().nonnegative(),generation:Z.string().min(1).max(256),result:tu}),Z.strictObject({operation:Z.literal("feature_config"),funnelId:Z.uuid()}),Z.strictObject({operation:Z.literal("commit_decision_segment"),decisionId:Z.uuid(),requestId:Z.uuid(),nodeId:Z.string().min(1).max(64),visit:Z.number().int().nonnegative(),revision:Z.number().int().nonnegative(),policyRevision:Z.number().int().nonnegative(),generation:Z.string().min(1).max(256),steps:Z.array(If).max(32),boundary:Z.strictObject({nodeId:Z.string().min(1).max(64),visit:Z.number().int().nonnegative()}).optional()}),Z.strictObject({operation:Z.literal("segment_configuration"),funnelId:Z.uuid(),versionId:Z.uuid()}),Z.strictObject({operation:Z.literal("configuration"),funnelId:Z.uuid(),versionId:Z.uuid().optional()}),Z.strictObject({operation:Z.literal("local_configuration"),funnelId:Z.uuid()}),Z.strictObject({operation:Z.literal("report_used"),decisionId:Z.uuid(),eventId:Z.uuid(),occurredAt:Z.iso.datetime({offset:!0}),reference:Z.string().min(1).max(128).optional()})]),hE=Z.strictObject({scope:Te,decisionId:Z.uuid(),requestId:Z.uuid(),status:Z.enum(["pending","completed","failed"]),decision:XS.nullable(),evaluation:Z.discriminatedUnion("type",[Sf,vf]).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"),yE=Z.strictObject({scope:Te,decisionId:Z.uuid(),eventId:Z.uuid(),source:Z.literal("caller_reported")});import{z as Mt}from"zod";var Rf=Mt.strictObject({type:Mt.literal("bundle"),paywall:Dn.optional(),offering:Dn.optional(),coupons:Dn,data:Dn}),t0=e=>Mt.strictObject({type:Mt.literal(e),id:Mt.uuid()}),vE=Mt.strictObject({type:Mt.literal("bundle"),paywallVersionId:Mt.uuid().optional(),offeringVersionId:Mt.uuid().optional(),couponIds:Mt.array(Mt.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:ve});var wE=Mt.strictObject({type:Mt.literal("bundle"),offering:t0("offering_version").nullable(),paywall:Mt.strictObject({versionId:Mt.uuid(),paywallId:Mt.uuid(),offeringVersionId:Mt.uuid()}).nullable(),coupons:Mt.array(Gi).max(20),data:ve});import{z as Rn}from"zod";import{z as yn}from"zod";var kf=yn.union([yn.string(),yn.number().finite(),yn.boolean(),yn.null()]),n0=yn.union([kf,yn.array(kf).min(1).max(20)]),r0=yn.record(_n,n0).refine(e=>Object.keys(e).length<=10),jf=yn.strictObject({path:_n,type:yn.enum(["string","number","boolean","strings"]),nullable:yn.boolean().optional(),aggregation:yn.enum(["count","exists"]).optional(),where:r0.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 i0=["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"],Tf=Rn.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),o0=Dn,Nf=Rn.discriminatedUnion("type",[yf,Rn.strictObject({type:Rn.literal("claim_offer"),coupon:Dn}),Rn.strictObject({type:Rn.literal("event"),event:Tf}),Rn.strictObject({type:Rn.literal("api"),operation:Rn.enum(i0),inputs:Rn.record(_n,o0).refine(e=>Object.keys(e).length<=40),outputs:Rn.record(Tf,jf).refine(e=>Object.keys(e).length<=20)})]);var ct=za,a0=Q.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),dn={id:ct,name:Q.string().trim().min(1).max(80),position:Q.strictObject({x:Q.number().finite(),y:Q.number().finite()}).optional()},s0={success:ct,cancel:ct,unavailable:ct,failure:ct},ou=Q.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),au=Q.enum(["same_window","new_window"]),c0=Q.discriminatedUnion("type",[Q.strictObject({...dn,type:Q.literal("entry"),next:ct,triggers:Q.array(mf).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),Q.strictObject({...dn,type:Q.literal("screen"),screenId:ct,presentation:On,outputs:Q.record(ct,ct),offering:Q.discriminatedUnion("source",[Q.strictObject({source:Q.literal("variable"),key:St}),Q.strictObject({source:Q.literal("fixed"),versionId:Q.uuid()})]).optional()}),Q.strictObject({...dn,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:St}),next:ct}),Q.strictObject({...dn,type:Q.literal("coupon"),couponId:Q.uuid(),writes:Q.strictObject({value:St}),next:ct}),Q.strictObject({...dn,type:Q.literal("coupons"),couponIds:Q.array(Q.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:Q.strictObject({value:St}),next:ct}),Q.strictObject({...dn,type:Q.literal("output"),value:Q.discriminatedUnion("type",[...ho.options,Rf,Q.strictObject({type:Q.literal("selection"),screenId:ct,offeringKey:St})])}),Q.strictObject({...dn,type:Q.literal("condition"),cases:Q.array(Q.strictObject({condition:Yt,target:ct})).min(1).max(50),default:ct}),Q.strictObject({...dn,type:Q.literal("feature"),featureKey:Q.string().min(1).max(128),writes:Q.strictObject({value:St}),next:ct}),Q.strictObject({...dn,type:Q.literal("split"),experimentId:Q.uuid(),applyPageExperiment:Q.literal(!0).optional(),routes:Q.record(a0,ct).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:ct}),Q.strictObject({...dn,type:Q.literal("action"),...s0,execution:Af,action:Nf,writes:Ic.optional()}),Q.strictObject({...dn,type:Q.literal("external_page"),appManifest:Ba.optional(),url:ou,openIn:au,opened:ct,failed:ct}),Q.strictObject({...dn,type:Q.literal("end"),outcome:Q.enum(["completed","closed","ineligible","failed"]),output:ho.optional()}),Q.strictObject({...dn,type:Q.literal("wait"),writes:Ic.optional(),wait:Q.discriminatedUnion("type",[Q.strictObject({type:Q.literal("duration"),delaySeconds:Q.number().int().min(1).max(2592e3),elapsed:ct}),Q.strictObject({type:Q.literal("event"),eventName:ct,outputs:eu,timeoutSeconds:Q.number().int().min(1).max(2592e3),received:ct,timeout:ct})])})]),su=Q.strictObject({version:Q.literal(5),entry:ct,nodes:Q.array(c0).min(1).max(En.flowNodes)}),cu=su.superRefine((e,t)=>{u0(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function Wa(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 u0(e,t){let n=[],r=new Map(e.nodes.map(l=>[l.id,l])),i=(l,m,f)=>{n.push(l),t?.({message:l,reason:m,path:f?["nodes",e.nodes.indexOf(f)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(l=>l.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(l=>l.type==="screen").length>En.pages||e.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>En.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let l of e.nodes){for(let m of Wa(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 Wa(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 uu={maxTransitions:1e4,runTimeoutSeconds:2592e3};function Df(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 er(c.condition))u.startsWith("variables.")&&a(u.slice(10),!0)}if(e.type==="screen"&&e.offering?.source==="variable"&&a(e.offering.key),e.type==="action"&&(e.action.type==="api"||e.action.type==="external_task"))for(let s of Object.values(e.action.inputs))s.source==="variable"&&a(s.key);e.type==="action"&&e.action.type==="claim_offer"&&e.action.coupon.source==="variable"&&a(e.action.coupon.key);let o=e.type==="output"?e.value:e.type==="end"?e.output:null;if(o?.type==="variable"&&a(o.key),o?.type==="bundle")for(let s of[o.paywall,o.offering,o.coupons,o.data])s?.source==="variable"&&a(s.key);return o?.type==="selection"&&a(o.offeringKey),[...i]}import{z as q}from"zod";var _i=q.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Ya=e=>q.record(q.string(),ve).refine(t=>un(t)<=e,"Funnel evidence exceeds its byte budget"),tR=q.enum(["local_segment","evaluation","presentation","timer","event","operation"]),du=q.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),pu=q.discriminatedUnion("type",[q.strictObject({type:q.literal("flag"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("experiment"),id:q.uuid()}),q.strictObject({type:q.literal("saved_group"),id:q.uuid()}),q.strictObject({type:q.literal("config"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("constant"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("paywall_version"),id:q.uuid()}),q.strictObject({type:q.literal("offering_version"),id:q.uuid()}),q.strictObject({type:q.literal("reward"),id:q.uuid()})]),yo=q.strictObject({schemaVersion:q.literal(1),kind:du,selector:pu.nullable(),context:Ya(131072),contract:q.strictObject({version:q.number().int().positive(),evaluator:q.string().min(1).max(128),policyRevision:q.number().int().nonnegative()})}).refine(e=>un(e)<=131072,"Node input exceeds its byte budget"),Ff=q.strictObject({schemaVersion:q.literal(1),kind:du,outcome:q.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:Ya(131072),route:q.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:Ya(131072)}).refine(e=>un(e)<=131072,"Node result exceeds its byte budget"),nR=q.strictObject({schemaVersion:q.literal(1),operations:q.record(_i,q.strictObject({attempts:q.number().int().nonnegative(),maxAttempts:q.number().int().min(1).max(5),deadlineAt:q.iso.datetime({offset:!0}),retryAt:q.iso.datetime({offset:!0}).nullable(),error:q.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:q.strictObject({type:_i,id:q.uuid()}).nullable()}))}).refine(e=>un(e)<=65536,"Execution state exceeds its byte budget"),Ur={receiptId:q.uuid()},lu=q.iso.datetime({offset:!0}),rR=q.discriminatedUnion("type",[q.strictObject({type:q.literal("node_entered"),details:q.strictObject({kind:du})}),q.strictObject({type:q.literal("presentation_shown"),details:q.strictObject({...Ur,source:q.literal("client"),occurredAt:lu.optional()})}),q.strictObject({type:q.literal("decision_accepted"),details:q.strictObject(Ur)}),q.strictObject({type:q.literal("signal_received"),details:q.strictObject({signalId:q.uuid(),nodeId:_i,eventName:_i,data:Ya(8192),source:q.literal("server"),occurredAt:lu})}),q.strictObject({type:q.literal("signal_consumed"),details:q.strictObject({...Ur,signalId:q.uuid()})}),q.strictObject({type:q.literal("wait_elapsed"),details:q.strictObject(Ur)}),q.strictObject({type:q.literal("wait_timeout"),details:q.strictObject(Ur)}),q.strictObject({type:q.literal("operation_completed"),details:q.strictObject({...Ur,operation:_i,reference:q.strictObject({type:_i,id:q.uuid()}).nullable()})}),q.strictObject({type:q.literal("execution_recovered"),details:q.strictObject({generation:q.number().int().positive(),reason:q.enum(["interrupted","expired_lease","delivery_failed"])})}),q.strictObject({type:q.literal("execution_failed"),details:q.strictObject({generation:q.number().int().positive(),code:q.string().regex(/^[a-z_]{1,64}$/)})}),q.strictObject({type:q.literal("run_completed"),details:q.strictObject({outcome:q.enum(["completed","ineligible","failed"])})}),q.strictObject({type:q.literal("run_closed"),details:q.strictObject({source:q.enum(["client","server","expiry"])})}),q.strictObject({type:q.literal("treatment_used"),details:q.strictObject({...Ur,source:q.enum(["client","server"]),occurredAt:lu,reference:q.string().min(1).max(128).optional()})})]);var An=z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),l0=z.discriminatedUnion("type",[z.strictObject({id:An,type:z.literal("owned"),publicData:Ym.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")}),z.strictObject({id:An,type:z.literal("paywall"),paywallVersionId:z.uuid()})]),mu={executionContract:of.optional(),kind:z.literal("funnel"),schemaVersion:z.literal(4),screens:z.array(l0).max(En.pages),references:z.record(An,pu).refine(e=>Object.keys(e).length<=500),inputs:z.array(z.strictObject({variable:An,screenId:An,componentId:An,required:z.boolean()})).max(En.questions),variables:z.record(St,mi).refine(e=>Object.keys(e).length<=En.logicNodes),outputSchema:pi,execution:z.strictObject({runTimeoutSeconds:z.number().int().min(1).max(uu.runTimeoutSeconds),maxTransitions:z.number().int().min(1).max(uu.maxTransitions)})},vR=z.strictObject({...mu,graph:su});function d0(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 es(e){return Array.isArray(e)?e.some(es):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===bf:es(n))}function p0(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=cf(i.document)}catch(o){t.push({message:o instanceof Error?o.message:"Screen cannot be delivered",reason:"screen",path:["screens",r,"document"]});continue}for(let[o,s]of e.inputs.entries())s.screenId===i.id&&!co(a,s.componentId)&&t.push({message:`Local Funnel input ${s.variable} targets hidden component ${s.componentId} on screen ${s.screenId}`,reason:"inputBinding",path:["inputs",o]})}for(let[r,i]of e.graph.nodes.entries()){let a=["graph","nodes",r],o=i.type==="screen"?e.screens.find(s=>s.id===i.screenId):void 0;o?.type==="owned"&&(o.document.actions.some(s=>typeof s.properties.templateKey=="string"&&s.properties.templateKey.startsWith("popup-coupon-"))&&t.push({message:"Funnel screens claim Coupons through a Claim Coupon step",reason:"coupon",path:a}),d0(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"&&es(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&es(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function Mf(e,t){for(let{message:n,reason:r,path:i}of p0(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function qf(e,t){let n=(g,d,h=[])=>t.addIssue({code:"custom",message:g,path:h,params:{reason:d}}),r=Object.values(e.references),i=new Map(e.screens.map(g=>[g.id,g])),a=(g,d)=>r.some(h=>h.type===g&&("id"in h?h.id:h.key)===d);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let o=e.graph.nodes.filter(g=>g.type==="screen");(o.length!==i.size||o.some(g=>!i.has(g.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(g=>c.some(d=>g!==d&&d.startsWith(g+".")))&&n("Variable paths must not overlap","variable");function u(g,d){Object.hasOwn(e.variables,g)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(d)]);let h=s.get(g)??new Set;h.add(d.id),s.set(g,h)}for(let[g,d]of e.graph.nodes.entries()){let h=["graph","nodes",g],R=d.type==="feature"?d.featureKey:d.type==="offering"&&d.configuration.source==="feature"?d.configuration.featureKey:d.type==="output"&&d.value.type==="feature"?d.value.featureKey:d.type==="end"&&d.output?.type==="feature"?d.output.featureKey:null;R&&!a("flag",R)&&n("Flag selectors require an explicit GB resource reference","feature",h);let y=d.type==="feature"||d.type==="offering"||d.type==="coupon"||d.type==="coupons"||d.type==="action"&&d.action.type==="api"?["value"]:d.type==="action"&&d.action.type==="external_task"?Object.keys(d.action.outputs):d.type==="wait"&&d.wait.type==="event"?Object.keys(d.wait.outputs):[],A="writes"in d?d.writes??{}:{};(y.length!==Object.keys(A).length||y.some(v=>!Object.hasOwn(A,v))||new Set(Object.values(A)).size!==Object.values(A).length)&&n("Node writes must map every named output exactly once","variable",h);for(let[v,P]of Object.entries(A)){u(P,d);let j=e.variables[P],_=d.type==="offering"?"offering_version":d.type==="coupon"?"reward":d.type==="action"&&d.action.type==="api"?"json":d.type==="action"&&d.action.type==="external_task"?d.action.outputs[v]:d.type==="wait"&&d.wait.type==="event"?d.wait.outputs[v]:void 0;(j?.source.type!=="node"||_&&j.type!==_)&&n("Node writer source or output type does not match declaration","variable",h)}if(d.type==="coupons"){let v=e.variables[d.writes.value];(v?.type!=="array"||v.items?.type!=="reward"||v.items.nullable||v.nullable)&&n("Coupons output requires a non-null Reward array","variable",h);for(let P of d.couponIds)a("reward",P)||n("Coupons require Reward references","coupon",h)}if(d.type==="split"&&!a("experiment",d.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",h),d.type==="coupon"&&!a("reward",d.couponId)&&n("Coupon selectors require a Reward reference","coupon",h),d.type==="action"&&d.action.type==="claim_offer"&&d.action.coupon.source==="literal"){let v=d.action.coupon.value;(!v||typeof v!="object"||Array.isArray(v)||v.type!=="reward"||typeof v.id!="string"||Object.keys(v).length!==2||!a("reward",v.id))&&n("Coupon claims require a Reward reference","coupon",h)}if(d.type==="offering"&&d.configuration.source==="fixed"&&!a("offering_version",d.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",h),d.type==="screen"&&d.offering?.source==="variable"&&e.variables[d.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",h),d.type==="action"&&d.action.type==="claim_offer"&&d.action.coupon.source==="variable"&&(e.variables[d.action.coupon.key]?.type!=="reward"||d.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",h),d.type==="screen"){let v=i.get(d.screenId);if(d.offering?.source==="fixed"&&!a("offering_version",d.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",h),v?.type==="paywall"&&d.offering&&n("Paywall owns its fixed Offering Version","offering",h),v?.type==="paywall"&&!a("paywall_version",v.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",h),v?.type==="owned"){let P=v.document.pages[0];if(!P){n("Owned screen requires a page","screen",h);continue}ir(v.document).some(_=>!_.complete)&&n("Owned screens require complete local content","translations",h);let j=new Set(v.document.actions.map(_=>_.id));(j.size!==Object.keys(d.outputs).length||Object.keys(d.outputs).some(_=>!j.has(_)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",h),Jn(P.root,_=>{!d.offering&&(_.type==="plan_picker"||(_.type==="stack"||_.type==="button")&&_.bind?.plan||_.type==="customer_data"&&["customer_plans","credit_packs"].includes(_.data.source))&&n("Product presentation requires an Offering Version","offering",h),_.type==="customer_data"&&Object.values(_.data.outputs??{}).some(X=>X!==void 0&&!j.has(X))&&n("Customer components require declared screen outcomes","componentOutput",h)})}}d.type==="end"&&["completed","ineligible"].includes(d.outcome)&&!d.output&&n("Completed and ineligible ends require a declared output","output",h),d.type==="end"&&d.output?.type==="literal"&&!gn(e.outputSchema,d.output.value)&&n("Terminal output does not match outputSchema","output",h),d.type==="output"&&d.value.type==="literal"&&!gn(e.outputSchema,d.value.value)&&n("Terminal output does not match outputSchema","output",h);let x=d.type==="output"?d.value:d.type==="end"?d.output:void 0;if(x?.type==="variable"&&!x.path){let v=e.variables[x.key];v&&!vc(v,e.outputSchema)&&n("Variable output does not match outputSchema","output",h)}if(d.type==="screen"){let v=i.get(d.screenId);if(v?.type==="owned")for(let P of Pc(v.document))(/^(input|params)\./.test(P)||P.startsWith("variables.")&&!Oc(P.slice(10),c))&&n("Screen values must reference registered variables","variable",h)}if(d.type==="condition")for(let v of d.cases){for(let P of Kn(v.condition))a("saved_group",P)||n("Conditions require explicit Saved Group references","savedGroup",h);for(let P of er(v.condition))P.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",h)}if(d.type==="output"&&d.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",h);for(let[v,P]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let j=d.value[v];if(j)if(j.source==="literal"){let _=v==="coupons"?j.value:[j.value];(!Array.isArray(_)||_.length>20||_.some(X=>!gn({type:P,nullable:!1},X)||!a(P,X.id))||v==="coupons"&&new Set(_.map(X=>X.id)).size!==_.length)&&n("Bundle requires distinct scoped resource references",v==="coupons"?"coupon":v==="paywall"?"paywall":"offering",[...h,"value",v])}else{let _=e.variables[j.key];(j.path||!_||_.nullable||(v==="coupons"?_.type!=="array"||_.items?.type!=="reward"||_.items.nullable:_.type!==P))&&n("Bundle binding type does not match its slot","output",h)}}}}for(let[g,d]of e.graph.nodes.entries()){let h=d.type==="screen"?i.get(d.screenId):void 0,R=[...Df(d,c),...h?.type==="owned"?Ia(h.document).map(y=>Oc(y,c)?.key??y):[]];for(let y of new Set(R)){let P=function(j){if(j===d.id)return!0;if(v.has(j))return!1;v.add(j);let _=e.graph.nodes.find(le=>le.id===j);return _?(x.has(j)?_.type==="action"?[_.cancel,_.unavailable,_.failure]:_.type==="wait"&&_.wait.type==="event"?[_.wait.timeout]:[]:Wa(_)).some(P):!1};var f=P;if(!Object.hasOwn(e.variables,y)){n("Consumed variable is undeclared","variable",["graph","nodes",g]);continue}let A=e.variables[y];if(d.type==="screen"&&A.source.type==="input"&&e.inputs.some(j=>j.screenId===d.screenId&&j.variable===y)||A.source.type==="parameter"||A.source.type==="attribute")continue;let x=A.source.type==="input"?new Set(e.inputs.filter(j=>j.variable===y&&j.required).flatMap(j=>o.filter(_=>_.screenId===j.screenId).map(_=>_.id))):s.get(y)??new Set,v=new Set;(!x.size||P(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",g])}}(new Set(e.inputs.map(g=>g.variable)).size!==e.inputs.length||new Set(e.inputs.map(g=>`${g.screenId}:${g.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[g,d]of e.inputs.entries()){e.variables[d.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",g]);let h=i.get(d.screenId),R=h?.type==="owned"?co(h.document,d.componentId):null;if((R?.type!=="stack"||!R.interaction||!["input","toggle","select","multiselect","tabs"].includes(R.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",g]),R?.type==="stack"&&R.interaction){let y=R.interaction.type==="toggle"?"boolean":R.interaction.type==="multiselect"?"strings":"string";e.variables[d.variable]?.type!==y&&n("Input variable type does not match component","inputBinding",["inputs",g]);let A=e.variables[d.variable]?.enum;A&&!R.children.filter(x=>!x.hidden).every(x=>A.includes(x.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",g])}}for(let[g,d]of Object.entries(e.variables))d.enum&&d.type!=="string"&&n("Only string variables support enum","variable",["variables",g]),d.source.type==="input"&&!e.inputs.some(h=>h.variable===g)&&n("Input variable requires a component binding","inputBinding",["variables",g]);let l=0,m=0;for(let g of e.screens)if(g.type==="owned"){for(let d of g.document.pages)Jn(d.root,()=>{l++});m+=g.document.actions.length}(l>En.components||m>En.actions||un(e)>En.documentBytes)&&n("Funnel document exceeds its budget","budget")}var m0=z.strictObject({...mu,graph:cu}).superRefine(qf),Ei=z.strictObject({...mu,graph:cu,displayName:z.string().trim().min(1).max(80)}).superRefine(qf),wR=Ei.superRefine(Mf),OR=m0.superRefine(Mf),Xa=z.string().regex(kt),Ao={requestId:z.uuid(),nodeId:An,visit:z.number().int().nonnegative(),revision:z.number().int().nonnegative(),customerToken:Xa.optional()},f0=z.discriminatedUnion("type",[z.strictObject({type:z.literal("screen"),output:An,answers:ar,selection:z.record(An,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:An,productVersionId:z.uuid(),offerId:z.uuid().optional(),nativeOffer:hi.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"])})]),g0=z.object({nodeId:An,visit:z.number().int().nonnegative(),revision:z.number().int().nonnegative(),components:z.record(An,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(),wt=z.discriminatedUnion("operation",[z.strictObject({operation:z.literal("start"),funnelId:z.uuid(),requestId:z.uuid(),customer:qr.optional(),customerData:Pi.optional(),locale:z.string().min(1).max(35),parameters:sr}).refine(Ja,Za),z.strictObject({operation:z.literal("get"),settlementRequestId:z.uuid().optional(),data:g0.optional(),purchase:z.strictObject({receiptId:z.uuid(),operationId:z.uuid()}).optional(),customerToken:Xa.optional()}),z.strictObject({operation:z.literal("resume"),requestId:z.uuid(),customerToken:Xa.optional()}),z.strictObject({operation:z.literal("submit"),...Ao,input:f0}),z.strictObject({operation:z.literal("back"),...Ao}),z.strictObject({operation:z.literal("shown"),...Ao}),z.strictObject({operation:z.literal("close"),...Ao}),z.strictObject({operation:z.literal("commit_segment"),...Ao,policyRevision:z.number().int().nonnegative(),generation:z.string().min(1).max(256)}),z.strictObject({operation:z.literal("review"),receiptId:z.uuid().optional(),customerToken:Xa.optional()})]);function ts(e,t){let n=new Set,r=new Set,i=new Set,a=[],o=new Map,s=new Map,c=new Map;function u(d){for(let h of Kn(d))l(h)}function l(d){if(i.has(d)||!Object.hasOwn(t.savedGroups,d))return;let h=t.savedGroups[d];h&&(i.add(d),c.set(d,h),a.push(()=>{!Array.isArray(h)&&h.type==="condition"&&u(h.condition)}))}function m(d){for(let h of["hashAttribute","fallbackAttribute"])if(d[h]!==void 0&&Zc(d[h]))throw new Error(`Funnel GB ${h} uses a reserved flow namespace`);u(d.condition);for(let h of d.parentConditions??[])f(h.id),u(h.condition)}function f(d,h=!1){let R=Object.hasOwn(t.features,d)?t.features[d]:void 0;if(!R){if(h)throw new Error("Required GB Feature is unavailable");return}n.has(d)||(n.add(d),o.set(d,R),a.push(()=>{for(let y of R.rules??[]){m(y);for(let A of y.tracks??[])m(A.experiment)}}))}function g(d){let h=Object.hasOwn(t.experiments,d)?t.experiments[d]:void 0;if(!h)throw new Error("Required GB Experiment is unavailable");r.has(d)||(r.add(d),s.set(d,h),a.push(()=>m(h)))}for(let d of e.graph.nodes){d.type==="feature"&&f(d.featureKey,!0),d.type==="split"&&g(d.experimentId),d.type==="condition"&&d.cases.forEach(R=>u(R.condition)),d.type==="offering"&&d.configuration.source==="feature"&&f(d.configuration.featureKey,!0);let h=d.type==="output"?d.value:d.type==="end"?d.output:null;h?.type==="feature"&&f(h.featureKey,!0)}for(let d of a)d();return{...t,features:Object.fromEntries(o),experiments:Object.fromEntries(s),savedGroups:Object.fromEntries(c)}}import{z as ae}from"zod";function Uf(e,t){let n=[],r={};Gt(e,i=>{if(i.hidden)return!1;if(i.type!=="quantity_picker")return;let a=i.bind?.plan?[i.bind.plan]:[];i.bind?.picker&&Gt(e,o=>{if(o.type==="plan_picker"&&o.id===i.bind?.picker&&a.push(...o.planIds??[]),o.type==="stack"&&o.interaction?.type==="select"&&o.interaction.pickerId===i.bind?.picker)for(let s of o.children)s.type==="stack"&&s.bind?.plan&&a.push(s.bind.plan)}),a.length||n.push(`Quantity control ${i.id} needs a Product binding`);for(let o of new Set(a)){let s=t[o]?.prepaid?.find(u=>u.internalFeatureId===i.internalFeatureId)?.terms,c=r[o]??(r[o]=new Set);(!s||c.has(i.internalFeatureId)||i.minimumQuantity<s.minimumQuantity||i.maximumQuantity>s.maximumQuantity)&&n.push(`Quantity control ${i.id} must match its Product's prepaid Feature and bounds`),c.add(i.internalFeatureId)}});for(let[i,a]of Object.entries(t))for(let o of a.prepaid??[])r[i]?.has(o.internalFeatureId)||n.push(`Product ${i} needs a quantity control for ${o.internalFeatureId}`);return n}function Bf(e,t,n,r){let i=r.plans[t];if(!i?.available)throw new Error("Selected Product is unavailable");let a={};if(Gt(e,o=>{if(o.hidden)return!1;if(o.type!=="quantity_picker"||o.hidden||(o.bind?.plan??(o.bind?.picker?n[o.bind.picker]:void 0))!==t)return;let c=i.prepaid?.find(l=>l.internalFeatureId===o.internalFeatureId)?.terms,u=n[o.id];if(!c||typeof u!="number"||!Number.isSafeInteger(u)||u<Math.max(c.minimumQuantity,o.minimumQuantity)||u>Math.min(c.maximumQuantity,o.maximumQuantity)||(u-o.minimumQuantity)%o.step!==0||a[o.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");a[o.internalFeatureId]=u}),(i.prepaid??[]).some(o=>a[o.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return a}import{z as bo}from"zod";var Vf=bo.object({defaultLocale:Sn,locales:bo.record(Sn,bo.object({name:bo.string().max(80),description:bo.string().max(500)}).strict())}).strict().superRefine((e,t)=>{let n=Object.keys(e.locales);(!n.length||n.length>20||!e.locales[e.defaultLocale])&&t.addIssue({code:"custom",message:"Invalid content languages"}),new TextEncoder().encode(JSON.stringify(e)).length>5e4&&t.addIssue({code:"custom",message:"Content exceeds 50 KB"})});var h0=["customer_data","coupon_code"],Lf=ae.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),y0=ae.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),ns=(e,t)=>new Set(e.map(t)).size===e.length,A0=ae.strictObject({currency:Ie,amountMinor:ae.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),b0=ae.strictObject({featureId:ae.uuid(),name:ae.string().trim().min(1).max(120),allowance:ae.string().max(40).nullable(),access:ae.boolean()}),x0=ae.strictObject({stripe:ae.strictObject({prices:ae.array(A0).min(1).max(50)}).optional(),apple:ae.strictObject({productIds:ae.array(Lf).min(1).max(10)}).optional(),google:ae.strictObject({products:ae.array(ae.strictObject({productId:Lf,basePlanId:y0.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!ns(e.stripe.prices,n=>n.currency)||e.apple&&!ns(e.apple.productIds,n=>n)||e.google&&!ns(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),S0=ae.strictObject({name:ae.string().trim().min(1).max(80),interval:ae.enum(["free","week","month","year","one_time"]),intervalCount:ae.number().int().min(1).max(100),trial:ae.strictObject({days:ae.number().int().min(1).max(730),cardRequired:ae.boolean()}).nullable(),benefits:ae.array(b0).max(50).refine(e=>ns(e,t=>t.featureId),"Duplicate benefit"),channels:x0,prepaid:ae.array(io).max(100).optional()}),I0=ae.strictObject({digest:vi,content:ae.strictObject({discount:tr,duration:an,appliesTo:oc,displayCopy:Vf.nullable(),firstPurchaseOnly:ae.boolean(),qualificationRequired:ae.boolean(),startsAt:ae.iso.datetime().nullable(),endsAt:ae.iso.datetime().nullable(),grantWindowHours:ae.number().int().positive(),perCustomerLimit:ae.number().int().positive()})}),v0=ae.discriminatedUnion("type",[ae.strictObject({type:ae.literal("checkout"),product:ba}),ae.strictObject({type:ae.literal("close")}),ae.strictObject({type:ae.literal("action"),action:Uc})]),rs=ae.strictObject({kind:ae.literal("paywall"),formatVersion:ae.literal(1),name:ae.string().trim().min(1).max(80),offeringVersionId:ae.uuid(),presentation:On,screen:cn,products:Fa,catalog:ae.record(ae.uuid(),S0),buttons:ae.record(qe,v0),coupons:ae.record(ae.uuid(),I0)}).superRefine((e,t)=>{let n=h=>t.addIssue({code:"custom",message:h}),{screen:r}=e;Uf(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),$c(r,h0).forEach(n),ir(r).some(h=>!h.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,o=new Set;Gt(r,h=>{let R="bind"in h?h.bind:void 0;R?.promotionCode&&n("Promotion codes must not be published"),R?.plan&&i.add(R.plan),R?.coupon&&a.add(R.coupon),h.type==="plan_picker"&&(h.planIds?.forEach(y=>i.add(y)),h.defaultPlan&&i.add(h.defaultPlan)),h.type==="text"&&h.feature&&o.add(h.feature.id)});let s=e.products.items.map(h=>h.productVersionId),c=Object.keys(e.catalog);(s.length!==c.length||s.some(h=>!Object.hasOwn(e.catalog,h)))&&n("Catalog must contain exactly the displayed Products");let u=new Set(s);e.products.defaultProductVersionId!==null&&!u.has(e.products.defaultProductVersionId)&&n("Default Product must be displayed");for(let h of i)u.has(h)||n("Screen references a Product that is not displayed");for(let h of Object.values(e.catalog))!h.channels.stripe&&!h.channels.apple&&!h.channels.google&&n("A displayed Product needs at least one sales channel");let l=new Set(Object.values(e.catalog).flatMap(h=>h.benefits.map(R=>R.featureId)));for(let h of o)l.has(h)||n("Feature text must read a displayed benefit");let m=r.actions.filter(h=>h.type!=="navigate");r.actions.some(h=>h.type!=="event"&&h.type!=="navigate")&&n("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==m.length||m.some(h=>!Object.hasOwn(e.buttons,h.id)))&&n("Buttons must match the screen's actions");let g=!1;for(let h of Object.values(e.buttons)){if(h.type!=="checkout")continue;g=!0,(h.product.type==="fixed"?[h.product.productVersionId]:h.product.allowedProductVersionIds).some(y=>!u.has(y))&&n("Checkout may only sell displayed Products")}g||n("A Paywall needs a checkout button");let d=Object.keys(e.coupons);(d.length!==a.size||d.some(h=>!a.has(h)))&&n("Coupons must be exactly the bound Coupons")}),zf=ae.strictObject({state:ae.enum(["published","archived"]),controlRevision:ae.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:ae.uuid(),versions:ae.record(ae.uuid(),ae.strictObject({version:ae.number().int().positive(),artifact:ae.string().min(1),sourceDigest:ae.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var nn={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},fu=Ee.string().regex(/^[a-f0-9]{64}$/),gu=Ee.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),yu=Te.extend({environmentId:Ee.uuid()}),$f=Ee.strictObject({features:Ee.array(Ee.string()).max(500),experiments:Ee.record(Ee.uuid(),Ee.array(Ee.string()).max(20)),savedGroups:Ee.array(Ee.string()).max(1e3)}),Au=Ee.strictObject({kind:Ee.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:Ee.number().int().positive(),url:Ee.string().min(1).max(2048),sha256:fu,byteLength:Ee.number().int().positive().max(nn.maxArtifactBytes),generation:fu.optional()}),w0=Ee.strictObject({state:Ee.enum(["active","paused","archived"]),controlRevision:gu,evaluationMode:Ee.enum(["local","remote"]),evaluationRevision:gu,currentVersionId:Ee.uuid(),versions:Ee.record(Ee.uuid(),Ee.strictObject({artifact:Ee.string(),dependencies:$f,definitionDigest:vi.optional(),couponDigests:Ee.record(Ee.uuid(),vi).optional()}))}),bu=Ee.strictObject({kind:Ee.literal("sdk_configuration"),schemaVersion:Ee.literal(1),scope:yu,revision:gu,generation:fu,policy:Ee.strictObject({refreshIntervalSeconds:Ee.number().positive().max(15),maxControlAgeSeconds:Ee.number().positive().max(60)}),gb:Ee.strictObject({features:Ee.string().nullable(),pageExperiments:Ee.string().nullable()}),artifacts:Ee.record(Ee.string(),Au),funnels:Ee.record(Ee.uuid(),w0),paywalls:Ee.record(Ee.uuid(),zf).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 Ot(e){if(Array.isArray(e))return`[${e.map(Ot).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)}:${Ot(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function xu(e){return ni(ri(typeof e=="string"?new TextEncoder().encode(e):e))}function Gf(e){return xu(Ot(e))}var hu=class extends Error{constructor(n,r){super(n);Me(this,"dependency",r)}};function Kf(e,t){let n=l=>l.type==="feature"?l.featureKey:l.type==="end"&&l.output?.type==="feature"?l.output.featureKey:l.type==="output"&&l.value.type==="feature"?l.value.featureKey:void 0,r=(l,m)=>e.graph.nodes.find(f=>l==="experiment"?f.type==="split"&&f.experimentId===m:l==="feature"&&n(f)===m)?.name,i=(l,m,f=r(m.type,m.resource))=>new hu(l,{...m,...f?{step:f}:{}});for(let l of Object.values(e.references)){let m=l.type==="flag"?!Object.hasOwn(t.features,l.key)||t.remoteFeatures.includes(l.key)?{type:"feature",resource:l.key}:null:l.type==="experiment"?Object.hasOwn(t.experiments,l.id)?null:{type:"experiment",resource:l.id}:l.type==="saved_group"&&!Object.hasOwn(t.savedGroups,l.id)?{type:"saved_group",resource:l.id}:null;if(m)throw i("Funnel dependency is absent from GB public delivery",{reason:"unavailable",...m})}let a=ts(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),o=new Set(t.remoteFeatures);for(let l of e.graph.nodes){let m=n(l);if(!m)continue;let f=a.features[m],g=l.type==="feature"?e.variables[l.writes.value]:e.outputSchema,d={type:"feature",resource:m};if(!f||!g)throw i("Required public Feature declaration is unavailable",{reason:"unavailable",...d},l.name);if([f.defaultValue,...(f.rules??[]).flatMap(R=>[...Object.hasOwn(R,"force")?[R.force]:[],...R.variations??[],...(R.tracks??[]).flatMap(y=>y.experiment.variations)])].some(R=>R===void 0||!gn(g,R)))throw i("GB Feature values violate the Funnel type contract",{reason:"value_type",...d},l.name)}let s=new Set,c=(l,m)=>{for(let f of Kn(l)){if(s.has(f))continue;let g=t.savedGroups[f];if(!g)throw i("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:f},m);s.add(f),!Array.isArray(g)&&g.type==="condition"&&c(g.condition,m)}},u=(l,m)=>{if(o.has(l)||!t.features[l])throw i("Local Funnel requires public Local prerequisites",{reason:"unavailable",type:"feature",resource:l},m)};for(let l of e.graph.nodes)if(l.type==="condition")for(let m of l.cases)c(m.condition,l.name);for(let[l,m]of Object.entries(a.features)){let f=r("feature",l);for(let g of m.rules??[]){c(g.condition,f);for(let d of[...g.parentConditions??[],...(g.tracks??[]).flatMap(h=>h.experiment.parentConditions??[])])u(d.id,f),c(d.condition,f);for(let d of g.tracks??[])c(d.experiment.condition,f)}}for(let[l,m]of Object.entries(a.experiments)){let f=r("experiment",l);c(m.condition,f);for(let g of m.parentConditions??[])u(g.id,f),c(g.condition,f)}for(let l of e.graph.nodes)if(l.type==="split"){let m=a.experiments[l.experimentId],f={type:"experiment",resource:l.experimentId};if(!m)throw i("Local Funnel requires a public Experiment",{reason:"unavailable",...f},l.name);for(let g of m.variations)if(typeof g!="string"||!Object.hasOwn(l.routes,g))throw i("Experiment variation has no declared Funnel route",{reason:"variation_route",...f},l.name)}return $f.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 Hf(e){return Ei.parse(e)}var Qf=Pt.strictObject({processContext:Oa.optional(),...gi,selector:Pt.discriminatedUnion("type",[Pt.strictObject({type:Pt.literal("paywall"),paywallId:Pt.uuid()}),Pt.strictObject({type:Pt.literal("version"),versionId:Pt.uuid()})]),customerId:Pt.uuid().optional(),commerce:ui,locale:Pt.string().min(1).max(35),requirement:rr.optional()}),xo=Pt.strictObject({id:Pt.uuid(),paywallId:Pt.uuid(),version:Pt.number().int().positive(),document:Ii.omit({requirement:!0,offeringId:!0}),offering:Pt.strictObject({id:Pt.uuid()}),content:Pt.strictObject({environmentId:Pt.uuid(),offeringVersionId:Pt.uuid(),artifact:Au.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:li,check:Er.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"})}),Br=Pt.strictObject(xo.shape).omit({document:!0,offering:!0}).extend({content:xo.shape.content.unwrap()});function Jf(e,t){let n=rs.parse(t);if(n.offeringVersionId!==e.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");let r=structuredClone(e.capabilities);for(let[i,a]of Object.entries(n.catalog)){let o=r.plans[i],s=a.channels.stripe?.prices.find(c=>c.currency===o?.currency);o&&s&&Object.assign(o,{amountMinor:s.amountMinor,interval:a.interval,intervalCount:a.intervalCount,...a.prepaid?.length?{prepaid:a.prepaid}:{}})}return xo.parse({...e,capabilities:r,document:{schemaVersion:3,kind:n.kind,name:n.name,presentation:n.presentation,products:n.products,offeringVersionId:n.offeringVersionId,screen:n.screen,buttons:n.buttons},offering:{id:n.offeringVersionId}})}import{z as Ht}from"zod";var Zf={requestId:Ht.uuid(),sourceId:Ht.uuid(),expectedAvailable:$t},Wf=Ht.discriminatedUnion("action",[Ht.strictObject({...Zf,action:Ht.enum(["add","subtract","set_remaining"]),amount:xe}),Ht.strictObject({...Zf,action:Ht.literal("edit"),granted:xe,expiresAt:Ht.iso.datetime({offset:!0}).nullable(),nextResetAt:Ht.iso.datetime({offset:!0}).nullable(),expectedRevision:Ht.number().int().nonnegative()})]),Su=Ht.strictObject({sourceId:Ht.uuid(),available:$t,held:$t,spent:$t,adjustmentGrantId:Ht.uuid().nullable()}),Yf=Su.extend({granted:$t,expiresAt:Ht.iso.datetime({offset:!0}).nullable(),nextResetAt:Ht.iso.datetime({offset:!0}).nullable(),revision:Ht.number().int().nonnegative()});import{z as pn}from"zod";var Xf=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()]),eg=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 Lr}from"zod";var ng=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],tg=Lr.string().regex(/.+\/.+/),Iu=Lr.number().min(-100),Vr=Lr.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),O0=Lr.strictObject({input:Vr,output:Vr,cache_read:Vr.optional(),cache_write:Vr.optional(),reasoning:Vr.optional(),input_audio:Vr.optional(),output_audio:Vr.optional()}),vu=(e,t)=>Lr.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),wk=Lr.strictObject({defaultMarkup:Iu,providerMarkups:vu(Lr.string().min(1),Iu),modelMarkups:vu(tg,Iu),customModels:vu(tg,O0.partial())});import{z as be}from"zod";var zr=be.iso.datetime({offset:!0}),cr=be.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),P0=be.discriminatedUnion("kind",[be.object({kind:be.literal("absolute"),from:zr,to:zr}).strict(),be.object({kind:be.literal("last_days"),days:be.union([be.literal(1),be.literal(7),be.literal(30),be.literal(90)])}).strict(),be.object({kind:be.literal("billing_cycles"),membershipId:be.uuid(),count:be.number().int().min(1).max(12),includeCurrent:be.boolean()}).strict()]),rg=be.string().max(100).refine(e=>{if(e!=="UTC"&&!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+\-]+)+$/.test(e))return!1;try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Use an IANA timezone"),C0=be.object({key:be.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:be.array(be.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),$r=be.object({range:P0,timezone:rg,filterBy:be.array(C0).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:be.enum(["hour","day","week","month"]),internal_feature_id:be.uuid().nullable(),entityId:be.uuid().nullable(),topN:be.number().int().min(1).max(50).nullable(),groupBy:be.union([be.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),be.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:be.object({bucket:zr,group:be.string().max(240),isOther:be.boolean(),internal_feature_id:be.uuid(),resourceId:be.uuid()}).strict().nullable(),limit:be.number().int().min(1).max(100)}).strict().superRefine((e,t)=>{if(e.range.kind!=="absolute"){e.interval==="hour"&&e.range.kind==="last_days"&&e.range.days>31&&t.addIssue({code:"custom",message:"Hourly reports are bounded to 31 days"});return}let n=Date.parse(e.range.to)-Date.parse(e.range.from);(n<=0||n>366*864e5||e.interval==="hour"&&n>31*864e5)&&t.addIssue({code:"custom",message:"Reporting range must be positive and bounded (31 days hourly, 366 days otherwise)"})}),ig=be.object({from:zr,to:zr,interval:be.enum(["hour","day","week","month"]),timezone:rg,rows:be.array(be.object({bucket:zr,group:be.string().max(240),isOther:be.boolean(),internal_feature_id:be.uuid(),resourceId:be.uuid(),consumedUnits:cr,refundedUnits:cr,reservedUnits:cr,charged:cr,refunded:cr,reserved:cr,netUnits:cr,netCharged:cr}).strict()).max(100),nextCursor:be.object({bucket:zr,group:be.string().max(240),isOther:be.boolean(),internal_feature_id:be.uuid(),resourceId:be.uuid()}).strict().nullable()}).strict();var Ri=Vt.string().regex(/^(0|[1-9]\d{0,29})$/),og=Vt.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),wu=Vt.strictObject({bucket:Vt.iso.datetime({offset:!0}),group:Vt.string().max(240),isOther:Vt.boolean(),internal_feature_id:Vt.uuid()}),ag=Vt.strictObject({...$r.shape,groupBy:Vt.union([Vt.enum(["customer","entity","entitlement"]),Vt.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:wu.nullable()}).superRefine((e,t)=>{let n=$r.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),sg=Vt.strictObject({from:Vt.iso.datetime({offset:!0}),to:Vt.iso.datetime({offset:!0}),interval:$r.shape.interval,timezone:$r.shape.timezone,rows:Vt.array(Vt.strictObject({...wu.shape,eventCount:Ri,units:og,tokenEventCount:Ri,tokens:Vt.strictObject(Object.fromEntries(ng.map(e=>[e,Ri]))),totalTokens:Ri,providerCostEventCount:Ri,providerCostUsd:og,invalidTelemetryEventCount:Ri})).max(100),nextCursor:wu.nullable()});import{z as At}from"zod";var cg=At.object({requestId:At.uuid(),items:At.array(At.object({customerId:At.uuid(),command:Yi.options[1]}).strict()).min(1).max(1e3)}).strict().refine(e=>new Set(e.items.map(t=>t.customerId+":"+t.command.idempotencyKey)).size===e.items.length,"Each logical event must appear once in a batch"),ug=At.object({batchId:At.uuid(),after:At.number().int().min(-1).max(999),limit:At.number().int().min(1).max(100)}).strict(),lg=At.object({batchId:At.uuid(),status:At.enum(["queued","complete"]),total:At.number().int().min(1).max(1e3),processed:At.number().int().min(0).max(1e3),items:At.array(At.object({position:At.number().int().min(0).max(999),customerId:At.uuid(),idempotencyKey:At.string().min(1).max(120),status:At.enum(["queued","accepted","rejected","failed"]),receipt:Xi.nullable(),errorCode:At.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:At.number().int().min(0).max(999).nullable()}).strict();import{z as k}from"zod";var _0=k.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),dg=k.enum(["draft","active","paused","archived"]),pg=k.string().min(1).max(256),mg=k.array(pg).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),E0=k.strictObject({duration:k.enum(["day","week","month","year"]),length:k.number().int().min(1).max(3660)}),R0=k.strictObject({internal_feature_id:k.uuid(),allowance:k.number().nonnegative().max(1e15).nullable(),expiry:E0.nullable()}),k0=k.discriminatedUnion("type",[k.strictObject({type:k.literal("feature_grant"),grants:k.array(R0).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),k.strictObject({type:k.literal("free_product"),productId:pg,duration:an}),k.strictObject({type:k.literal("invoice_credits"),amount:k.number().positive().max(1e8),duration:an,rollover:k.boolean(),productIds:mg})]),j0=k.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),fg=k.object({key:j0,name:k.string().trim().min(1).max(80),configuration:k0}).strict(),gg=k.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),Ou=k.object({code:gg,maxUses:k.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:k.boolean()}).strict(),hg=k.object({key:k.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:k.string().trim().min(1).max(80),rewardId:k.uuid(),redeemOn:k.enum(["customer_creation","checkout"]),receivedBy:k.enum(["referrer","all"]),maxRedemptions:k.number().int().min(1).max(1e6).nullable(),productIds:mg,excludeTrial:k.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),yg={id:k.uuid(),projectId:k.uuid(),environmentId:k.uuid(),revision:k.number().int().nonnegative(),status:dg,createdAt:k.iso.datetime({offset:!0}),updatedAt:k.iso.datetime({offset:!0})},T0=fg.extend(yg).strict(),N0=hg.safeExtend(yg).strict(),qk=k.strictObject({id:k.uuid(),key:k.string(),name:k.string(),type:_0,status:dg}),Uk=k.discriminatedUnion("action",[k.object({action:k.literal("save"),id:k.uuid().nullable(),revision:k.number().int().nonnegative(),input:fg}).strict(),k.object({action:k.enum(["activate","pause","resume","archive","delete"]),id:k.uuid(),revision:k.number().int().nonnegative()}).strict()]),Bk=k.discriminatedUnion("action",[k.object({action:k.literal("save"),id:k.uuid().nullable(),revision:k.number().int().nonnegative(),input:hg}).strict(),k.object({action:k.enum(["activate","pause","resume","archive","delete"]),id:k.uuid(),revision:k.number().int().nonnegative()}).strict()]),Ag=k.object({id:k.uuid(),rewardId:k.uuid(),programId:k.uuid().nullable(),customerId:k.uuid(),referrerId:k.uuid().nullable(),status:k.enum(["pending","applied","unavailable"]),result:k.record(k.string(),k.unknown()).nullable(),createdAt:k.iso.datetime({offset:!0})}).strict(),bg=k.object({code:gg,requestId:k.uuid()}).strict(),xg=k.strictObject({redemptionId:k.uuid(),currency:Ie,requestId:k.uuid(),accepted:k.literal(!0)}),D0=k.strictObject({type:k.literal("checkout"),orderId:k.uuid(),productVersionId:k.uuid(),currency:Ie,duration:an,renewalAmountMinor:k.number().int().positive().max(1e8),status:k.enum(["created","pending","trialing","paid","cancelled","failed"]),url:k.url().nullable()}),Sg=k.discriminatedUnion("type",[D0,k.strictObject({type:k.literal("subscription"),operationId:k.uuid(),membershipId:k.uuid(),productVersionId:k.uuid(),currency:Ie,duration:an,renewalAmountMinor:k.number().int().positive().max(1e8),status:k.enum(["pending","running","applied","failed"])})]),Ig=k.object({programId:k.uuid(),requestId:k.uuid()}).strict(),vg=k.object({id:k.uuid(),programId:k.uuid(),code:Ou.shape.code,createdAt:k.iso.datetime({offset:!0})}).strict(),Vk=k.object({rows:k.array(T0).max(100),nextCursor:k.uuid().nullable()}).strict(),Lk=k.object({rows:k.array(N0).max(100),nextCursor:k.uuid().nullable()}).strict(),F0=Ou.extend({id:k.uuid(),redemptions:k.number().int().nonnegative()}).strict(),M0=k.strictObject({id:k.uuid(),programId:k.uuid().nullable(),customerId:k.uuid().nullable(),referrerId:k.uuid().nullable(),code:k.string().nullable(),status:k.enum(["pending","triggered","applied"]),createdAt:k.iso.datetime({offset:!0})}),zk=k.object({codes:k.array(F0).max(100),redemptions:k.array(M0).max(100),customers:k.record(k.uuid(),k.string()),codesCursor:k.uuid().nullable(),redemptionsCursor:k.uuid().nullable()}).strict(),$k=k.discriminatedUnion("action",[k.object({action:k.literal("create"),rewardId:k.uuid(),revision:k.number().int().nonnegative(),input:Ou}).strict(),k.object({action:k.literal("remove"),rewardId:k.uuid(),revision:k.number().int().nonnegative(),codeId:k.uuid()}).strict()]);import{z as w}from"zod";import{z as W}from"zod";var Fn={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},So=e=>new Set(e).size===e.length,Pu=W.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),q0=W.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),Io=W.string().min(1).max(200).regex(/^[a-zA-Z0-9_./-]+$/).refine(e=>!e.includes("..")&&!e.endsWith(".")&&!e.split("/").some(t=>!t||t.startsWith(".")||t.endsWith(".lock"))),U0=W.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),wg=W.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var Og=W.strictObject({id:W.uuid(),repo:q0,platform:W.enum(["github","gitlab","bitbucket"]),branches:W.array(Io).min(1).max(4).refine(So),workflow:W.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:W.array(W.uuid()).min(1).max(4).refine(So),include:W.array(wg).min(1).max(16),exclude:W.array(wg).max(16),methods:W.array(W.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(So),maxAgeHours:W.number().int().min(1).max(720)}),Pg=Og.extend({revision:W.number().int().positive()}),Hk=W.strictObject({repository:Og,expectedRevision:W.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),Cg=W.strictObject({repositoryId:W.uuid(),branch:Io}),B0=W.array(Pu).max(Fn.keys).refine(So),_g=W.strictObject({repository:Pg.omit({keyIds:!0}),branch:Io,keys:B0,keySetHash:W.string().regex(/^[a-f0-9]{64}$/)}),V0=W.strictObject({filePath:U0,startingLineNumber:W.number().int().min(1).max(1e7)}),Cu=W.strictObject({protocol:W.literal(1),repositoryId:W.uuid(),branch:Io,workflow:W.string().max(200),configurationRevision:W.number().int().positive(),keySetHash:W.string().regex(/^[a-f0-9]{64}$/),commit:W.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:W.uuid(),runNumber:W.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:W.number().int().min(1).max(1e4),scannerVersion:W.literal("1"),scannedAt:W.iso.datetime({offset:!0}),coverage:W.strictObject({complete:W.literal(!0),files:W.number().int().min(0).max(Fn.files),sourceBytes:W.number().int().min(0).max(Fn.sourceBytes),unresolvedCalls:W.number().int().min(0).max(1e6),unsupportedFiles:W.number().int().min(0).max(Fn.files)}),features:W.array(W.strictObject({key:Pu,refs:W.array(V0).max(Fn.referencesPerKey)})).max(Fn.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)>Fn.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),_u=W.strictObject({scanId:W.uuid(),commit:W.string(),receivedAt:W.string(),references:W.number().int().nonnegative(),removedReferences:W.number().int().nonnegative()}),L0=_u.extend({repositoryId:W.uuid(),branch:Io,workflow:W.string(),digest:W.string(),configurationRevision:W.number().int().positive(),runNumber:W.number().int().positive(),runAttempt:W.number().int().positive(),scannedAt:W.string(),keySetHash:W.string(),coverage:Cu.shape.coverage}),z0=W.strictObject({repositories:W.array(Pg).max(Fn.repositories),scans:W.array(L0).max(Fn.repositories*Fn.branches)}),$0=W.strictObject({key:Pu,references:W.number().int().nonnegative(),coveredTargets:W.number().int().nonnegative(),expiredTargets:W.number().int().nonnegative(),uncertainTargets:W.number().int().nonnegative()}),Qk=W.strictObject({available:W.boolean().default(!0),settings:z0,expectedTargets:W.number().int().min(0).max(80),features:W.array($0).max(2001),truncated:W.boolean()});import{z as Ct}from"zod";var G0=Ct.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"]),K0=Ct.strictObject({provider:Ct.literal("stripe"),accountId:Ct.string().regex(/^acct_[A-Za-z0-9]+$/),eventId:Ct.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),type:G0,occurredAt:Ct.number().int().positive().max(Number.MAX_SAFE_INTEGER),data:Ct.record(Ct.string(),Ct.unknown()).and(Ct.object({id:Ct.string().min(1).max(255),object:Ct.enum(["checkout.session","subscription","invoice","discount","refund","charge"]),livemode:Ct.boolean()}))}),Eg=Ct.union([K0,Nl]),Rg=Ct.strictObject({id:Ct.uuid(),eventId:Ct.string().min(1).max(200),source:Ct.literal("merchant"),providerVerified:Ct.literal(!1),outcome:Ct.string().min(1).max(100)});import{z as Qt}from"zod";var jg={customerId:Qt.uuid(),eventId:Qt.string().trim().min(1).max(200),grantId:Qt.uuid(),occurredAt:Qt.iso.datetime({offset:!0})},Tg=Qt.strictObject({...jg,productVersionId:Qt.uuid(),subscriptionId:Qt.string().trim().min(1).max(255)}),Ng=Qt.strictObject({...jg,merchandiseId:Qt.uuid()}),Dg=Qt.union([Tg,Ng]),kg={id:Qt.uuid(),couponId:Qt.uuid(),status:Qt.literal("redeemed"),source:Qt.literal("merchant"),recordedAt:Qt.iso.datetime({offset:!0})},Fg=Qt.union([Tg.extend(kg),Ng.extend(kg)]);import{z as oe}from"zod";var Mg=lm,H0=Mg.extend({invoice_id:Mg.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),Eu=oe.strictObject({name:oe.string().trim().min(1).max(255),memo:oe.string().max(1e4).nullable().optional(),footer:oe.string().max(1e4).nullable().optional(),net_terms_days:oe.number().int().positive().nullable().optional()}),Q0=Eu.extend({id:oe.string().min(1).max(255),created_at:oe.number().nullable()}),qg=oe.strictObject({items:oe.array(Q0).max(50),nextCursor:oe.uuid().nullable()}),rj=oe.discriminatedUnion("action",[oe.strictObject({action:oe.literal("create"),requestId:oe.uuid(),values:Eu}),oe.strictObject({action:oe.literal("update"),id:oe.string().min(1).max(255),values:Eu}),oe.strictObject({action:oe.literal("delete"),id:oe.string().min(1).max(255)})]),Ug=oe.discriminatedUnion("action",[oe.strictObject({action:oe.literal("create"),requestId:oe.uuid(),params:yi}),oe.strictObject({action:oe.enum(["finalize","send","pay","void"]),requestId:oe.uuid(),invoiceId:oe.uuid()}),oe.strictObject({action:oe.literal("reissue"),requestId:oe.uuid(),invoiceId:oe.uuid(),params:H0})]),Ru=oe.strictObject({id:oe.uuid(),customerId:oe.uuid(),providerInvoiceId:oe.string().nullable(),status:oe.enum(["draft","open","paid","void","uncollectible"]),currency:oe.string(),totalMinor:oe.string().regex(/^-?\d+$/),paidMinor:oe.string().regex(/^\d+$/),refundedMinor:oe.string().regex(/^\d+$/),hostedInvoiceUrl:oe.url().nullable(),createdAt:oe.number(),collectionMethod:oe.enum(["send_invoice","charge_automatically"]).nullable()}),Bg=Ru.extend({lines:oe.array(oe.strictObject({id:oe.uuid(),description:oe.string(),amountMinor:oe.string().regex(/^-?\d+$/),netAmountMinor:oe.string().regex(/^-?\d+$/),quantity:oe.number().nullable(),periodStart:oe.number().nullable(),periodEnd:oe.number().nullable()})).max(1e3)}),ki=oe.strictObject({taskId:oe.uuid(),status:oe.enum(["ready","running","done","dead"]),invoice:Ru.nullable(),errorCode:oe.string().nullable()}),Vg=oe.strictObject({items:oe.array(Ru).max(50),nextCursor:oe.uuid().nullable(),operations:oe.array(ki).max(50),operationsLimited:oe.boolean()});var J0=w.enum(["customers:read","customers:write","entitlements:read","content:read","sessions:create","funnels:run","offers:resolve","offers:grant","billing:read","billing:write","credits:read","credits:consume","credits:manage","features:read","events:write","messaging:write","code-references:read","code-references:write","app-manifests:write"]),Lg={scope:Te,permissions:w.array(J0),expiresAt:w.iso.datetime().nullable()},Jj=w.discriminatedUnion("kind",[w.object({...Lg,kind:w.literal("server"),keyId:w.string().min(1)}),w.object({...Lg,kind:w.literal("customer"),customerId:w.string().min(1),identityKind:w.enum(["identified","guest"]),expiresAt:w.iso.datetime()})]),V=w.object({requestId:w.uuid(),scope:Te}).strict(),Z0=Of.safeExtend({fingerprint:Qa.optional()}).strict(),W0=V.extend({customer:Ci,created:w.boolean()});function zg(){return V.extend({offer:Gi.nullable(),reason:Ud.nullable()})}var O={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:Ep,response:V.extend({message:w.object({messageId:w.uuid(),channel:ro,acceptedAt:w.iso.datetime({offset:!0}),status:w.enum(["accepted","sending","completed","canceled"]),replayed:w.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:w.strictObject({messageId:w.uuid()}),response:V.extend({message:w.object({id:w.uuid(),channel:ro,status:w.enum(["accepted","sending","completed","canceled"]),deliveries:w.array(w.object({id:w.uuid(),status:kp,attempts:w.number().int().nonnegative(),receipts:w.array(w.object({kind:jp,occurredAt:w.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:Al,response:V.extend({installation:Sr})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:bl,response:V.extend({installation:Sr})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:Mo,response:V.extend({installation:Sr})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:w.strictObject({channel:ro}),response:V.extend({preference:Os})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:Rp,response:V.extend({preference:Os})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:w.strictObject({cursor:w.uuid().optional()}),response:V.extend({templates:qg})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:w.strictObject({customerId:w.uuid(),params:yi}),response:V.extend({preview:Ec})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:w.strictObject({customerId:w.uuid(),requestId:w.uuid(),params:yi}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:V.extend({operation:ki})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:w.strictObject({customerId:w.uuid(),command:Ug}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:V.extend({operation:ki})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:w.strictObject({customerId:w.uuid(),taskId:w.uuid()}),response:V.extend({operation:ki})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:w.strictObject({customerId:w.uuid(),cursor:w.uuid().optional()}),response:V.extend({invoices:Vg})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:w.strictObject({customerId:w.uuid(),invoiceId:w.uuid()}),response:V.extend({invoice:Bg})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:Cg,response:V.extend({config:_g})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:Cu,response:V.extend({receipt:_u})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:w.strictObject({}),response:V.extend({payload:fo})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:tf,response:V.merge(qa)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:nf,response:V.merge(rf)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:w.strictObject({customerId:w.uuid(),sourceId:w.uuid()}),response:V.extend({balance:Yf})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:w.strictObject({customerId:w.uuid(),command:Wf}),response:V.extend({balance:Su})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:w.strictObject({internal_feature_id:w.uuid(),customerId:w.uuid().optional(),entityId:w.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:V.extend({internal_feature_id:w.uuid(),config:Bs,model_markups:Qo})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:w.strictObject({customerId:w.uuid(),query:ma}),response:V.extend({usage:eo})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:w.strictObject({customerId:w.uuid(),command:xp}),response:V.extend({usage:eo})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:w.strictObject({customerId:w.uuid(),command:fp}),response:V.extend({grant:uc})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:gp,response:V.extend({grants:hp})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:w.union(zm.options.map(e=>e.extend({customerId:w.uuid().optional(),customerToken:w.string().regex(kt).optional()}))),response:V.extend({operation:$m})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:jm.extend({customerId:w.uuid().optional()}),response:V.extend({setup:Nc})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Tm.extend({customerId:w.uuid().optional()}),response:V.extend({setup:Nc})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:Em.safeExtend({customerId:w.uuid()}),response:V.extend({batch:lo})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:Ra.extend({customerId:w.uuid()}),response:V.extend({batch:lo})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:Ra.extend({customerId:w.uuid()}),response:V.extend({batch:lo})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:Ra.extend({customerId:w.uuid()}),response:V.extend({batch:lo})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:w.discriminatedUnion("action",[ka.options[0].extend({customerId:w.uuid()}),ka.options[1].extend({customerId:w.uuid()}),ka.options[2].extend({customerId:w.uuid()})]),response:V.extend({trial:Tc})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Rm.extend({customerId:w.uuid()}),response:V.extend({trial:Tc})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:Na,response:V.extend({subscriptions:Bm})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:Na,response:V.extend({purchases:Vm})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:Mm,response:V.extend({conflicts:Lm})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:qm,response:V.extend({resolution:Um})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:Dm,response:V.extend({verification:Fm})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:Sm.safeExtend({...gi,customerId:w.uuid().optional()}),response:V.extend({quote:Ai})},recordBillingEvent:{method:"POST",path:"billing/events/record",permission:"billing:write",audience:"server",request:Eg,response:V.extend({record:Rg})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Fr.extend({customerId:w.uuid().optional(),intent:w.enum(["confirm","cancel"]).optional()}),response:V.extend({operation:bi})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Fr.extend({customerId:w.uuid().optional()}),response:V.extend({operation:bi})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:wm.safeExtend({customerId:w.uuid().optional()}),response:V.extend({quote:Pm})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Fr.extend({customerId:w.uuid().optional(),intent:w.enum(["confirm","cancel"]).optional()}),response:V.extend({operation:Rc})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Fr.extend({customerId:w.uuid().optional()}),response:V.extend({operation:Rc})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:Cm.safeExtend({customerId:w.uuid()}),response:V.extend({quote:kc})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Fr.extend({customerId:w.uuid()}),response:V.extend({operation:Ea})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Fr.extend({customerId:w.uuid()}),response:V.extend({operation:Ea})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:Xd,response:V.extend({controls:sc})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:Kd,response:V.extend({prepared:Qd})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:Jd,response:V.extend({authorization:ua})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:ip,response:V.extend({coupons:op})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Zd,response:V.extend({authorization:ua})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:np,response:V.extend({invoices:rp})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:tp.extend({customerId:w.uuid()}),response:V.extend({operation:ki})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:ep,response:V.extend({invoice:Qi})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:w.object({customerId:w.uuid(),command:Yd}).strict(),response:V.extend({controls:sc})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:w.object({customerId:w.uuid(),command:Xf}).strict(),response:V.extend({entity:eg})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:w.strictObject({customerId:w.uuid().nullable(),query:ag}),response:V.extend({analytics:sg})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:w.object({customerId:w.uuid().nullable(),query:$r}).strict(),response:V.extend({analytics:ig})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:cg,response:V.extend({batchId:w.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:ug,response:V.extend({batch:lg})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:Dp.extend({customerId:w.string().min(1).optional()}),response:V.extend({check:Er})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:w.strictObject({kind:or,selector:w.discriminatedUnion("type",[w.strictObject({type:w.literal("resource"),id:w.uuid()}),w.strictObject({type:w.literal("version"),id:w.uuid()})]),customerId:w.string().min(1).optional()}),response:V.extend({content:Cc})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Qf,response:V.extend({paywall:Br})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:w.strictObject({processContext:Oa.optional(),...gi,selector:Qm,customerId:w.string().min(1).optional(),commerce:ui,requirement:rr.optional()}),response:V.extend({offering:Jm,candidates:w.array(fc).max(20),availability:w.array(w.strictObject({productVersionId:w.uuid(),available:w.boolean(),reason:w.enum(["platform_binding_missing","commercial_runtime_pending","commerce_not_configured","currency_mismatch","product_unavailable","already_attached","attach_in_progress","already_scheduled","subscription_change_required","purchase_conflict"]).nullable()})).max(20),check:Er.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:w.object({customerId:w.uuid().optional(),entityId:w.uuid().optional()}).strict(),response:V.extend({holdings:Sp})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:w.object({customerId:w.uuid().optional(),query:vp}).strict(),response:V.extend({ledger:wp})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:yp.extend({customerId:w.uuid().optional()}),response:V.extend({detail:Ap})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:lc.safeExtend({customerId:w.uuid().optional()}),response:V.extend({statement:bp})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:w.object({customerId:w.uuid().optional(),command:Yi.options[0]}).strict(),response:V.extend({quote:dp})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:w.strictObject({customerId:w.uuid(),command:w.union([w.strictObject({eventName:w.string().min(1),quantity:xe.optional(),properties:It.optional(),entityId:w.uuid().optional(),idempotencyKey:w.string().min(1).max(120)}),w.strictObject({internal_feature_id:w.uuid(),quantity:xe.optional(),properties:It.optional(),entityId:w.uuid().optional(),idempotencyKey:w.string().min(1).max(120)})])}),response:V.extend({receipts:w.array(Xi).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:w.object({customerId:w.uuid(),command:Yi.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:V.extend({receipt:Xi})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:bg,response:V.extend({redemption:Ag})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:Ig,response:V.extend({referralCode:vg})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:xg,response:V.extend({checkout:Sg})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:Pp,response:V.extend({seats:mc})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Cp,response:V.extend({seats:mc})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:Z0,response:W0},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:iu,response:V.extend({customer:Ci})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:_f,response:V.extend(Ef.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:Cf,response:V.extend(Pf.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:w.object({customerId:w.uuid()}).strict(),response:V.extend(Zn.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:w.strictObject({}),response:V.extend(Zn.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:w.strictObject({customerId:w.uuid(),sessionId:w.uuid().optional()}),response:V.extend({revoked:w.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:w.strictObject({guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:Qa.optional()}),response:V.extend({customerId:w.uuid(),guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:w.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:w.strictObject({guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:V.extend(Zn.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:w.strictObject({guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:w.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:w.uuid()}),response:V.extend({customer:Ci,switched:w.boolean(),replayed:w.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:w.strictObject({code:w.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:w.uuid()}),response:zg()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:w.object({}).strict(),response:V.extend({offers:w.array(Gi)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:w.object({customerId:w.string().min(1).max(255).optional(),couponId:w.uuid(),...gi,requestId:w.uuid(),couponContentDigest:w.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:zg()},recordCouponRedemption:{method:"POST",path:"offers/redemptions",permission:"billing:write",audience:"server",request:Dg,response:V.extend({receipt:Fg})}},Zj={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 ku}from"zod";var vo=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function ju(e,t,n){let r={},i,a,o,s="next",c;switch(e.type){case"entry":c=e.next;break;case"condition":{let u=e.cases.findIndex(l=>en(t.attributes??{},l.condition,t.savedGroups??{}));s=u<0?"default":`case:${u}`,c=u<0?e.default:e.cases[u].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new vo("Required GB Feature is unavailable");i=Gn(e.featureKey,t),o=i.value,Object.assign(r,fi(e,{value:o})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new vo("Required GB Experiment is unavailable");if(a=sa(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 vo("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:Gn(e.configuration.featureKey,t).value;o={type:"offering_version",id:ku.uuid().parse(u)},Object.assign(r,fi(e,{value:o})),c=e.next;break}case"coupon":case"coupons":o=e.type==="coupons"?e.couponIds.map(u=>({type:"reward",id:u})):{type:"reward",id:e.couponId},Object.assign(r,fi(e,{value:o})),c=e.next;break}return{port:s,target:c,projections:r,...o===void 0?{}:{value:o},...i?{feature:i}:{},...a?{experiment:a}:{}}}function $g(e,t,n){ku.uuid().parse(e),ku.number().int().nonnegative().parse(t);let r=ni(ri(new TextEncoder().encode(JSON.stringify([e,t,n])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}import{z as H}from"zod";var ur=H.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Y0=H.enum(["running","waiting","completed","closed","ineligible","failed"]),Tu=H.discriminatedUnion("type",[nu,H.strictObject({type:H.literal("wait"),receiptId:H.uuid(),kind:H.enum(["timer","event","operation"]),deadline:H.iso.datetime({offset:!0}).nullable(),eventName:ur.optional()}),H.strictObject({type:H.literal("open_url"),receiptId:H.uuid(),url:ou,openIn:au}),H.strictObject({type:H.literal("event"),receiptId:H.uuid(),event:ur})]),is=H.strictObject({type:H.literal("funnel"),id:H.uuid(),versionId:H.uuid()}),X0={id:ur,presentation:On,outputs:H.array(ur).max(250),inputs:La,values:H.record(H.string(),ve).optional(),offeringKey:St.optional(),capabilities:li,customerData:Lp,dataCursors:H.record(ur,Va.nullable())},eI=H.strictObject({...X0,content:H.strictObject({type:H.literal("document"),document:cn})}),wo=H.strictObject({id:H.uuid(),source:is,revision:H.number().int().nonnegative(),visit:H.number().int().nonnegative(),nodeId:ur,nodeType:H.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:Y0,stopped:H.boolean(),canBack:H.boolean(),authenticated:H.boolean(),locale:H.string().min(1).max(35),answers:ar,parameters:sr,variables:H.record(H.string(),ve),output:ve.nullable(),screen:eI.nullable(),paywall:H.strictObject({receiptId:H.uuid(),resolution:H.union([xo,Br]),quote:Ai.nullable(),operation:bi.nullable(),purchaseRequestId:H.uuid().nullable(),selectionGeneration:H.number().int().nonnegative().optional(),canReselect:H.boolean().optional()}).nullable(),instruction:Tu.nullable(),pendingRequest:H.strictObject({requestId:H.uuid(),authenticationRequired:H.boolean()}).nullable(),runExpiresAt:H.iso.datetime({offset:!0}),credentialExpiresAt:H.iso.datetime({offset:!0}).nullable()}),os=H.strictObject({scope:Te,run:wo,settlement:H.strictObject({requestId:H.uuid(),state:H.enum(["pending","unknown","settled"]),operationId:H.uuid().nullable(),receiptId:H.uuid().nullable().optional()}).optional(),purchase:H.strictObject({receiptId:H.uuid(),quote:Ai.nullable(),operation:bi.nullable(),canReselect:H.boolean().optional()}).optional(),review:H.strictObject({activeOperationId:H.uuid().nullable(),pages:H.array(H.strictObject({receiptId:H.uuid(),nodeId:ur,visit:H.number().int().nonnegative()})).max(100),page:H.strictObject({receiptId:H.uuid(),nodeId:ur,visit:H.number().int().nonnegative(),document:cn,answers:ar,inputs:La,values:H.record(H.string(),ve).optional()}).nullable(),coupons:H.array(H.strictObject({grantId:H.uuid(),status:H.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:H.string().nullable()})).max(100),purchases:H.array(H.strictObject({receiptId:H.uuid(),operationId:H.uuid(),status:H.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:H.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:H.uuid().optional()}),Gg=os.extend({run:wo.extend({paywall:wo.shape.paywall.unwrap().extend({resolution:Br}).nullable()})});var Kg="X-Indiana-Server-Key";import{z as se}from"zod";import{z as Ae}from"zod";import{z as _t}from"zod";var tI=_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()}),nI=_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(tI).max(200).default([]),iam:pf.optional(),renderGuard:Ua.optional()}),Nu=nI.omit({variation:!0,description:!0,iam:!0}),rI=wi.omit({variations:!0,active:!0}).extend({changeId:_t.string().regex(/^[a-f0-9]{64}$/),variations:_t.tuple([Nu,Nu]).rest(Nu).refine(e=>e.length<=20)}),Hg=_t.strictObject({trackExposures:_t.boolean(),environmentId:_t.uuid(),generation:_t.string().regex(/^[a-f0-9]{64}$/),experiments:_t.array(rI).max(100),savedGroups:mo});var Oo=Ae.string().regex(/^[a-f0-9]{64}$/),RT=Ae.strictObject({iam:Oo,executionContracts:Ae.union([Ae.tuple([Ae.literal("funnel-run/1")]),Ae.tuple([Ae.literal("funnel-process/1")])]).default(["funnel-run/1"])}),iI=Ae.strictObject({release:Oo,render:Ua,button:Ae.strictObject({selector:Ae.string().min(1).max(512),elementKey:Ae.string().min(1).max(256),tag:Ae.enum(["button","a","input"])}).nullable()}),kT=Ae.strictObject({scope:Te.extend({environmentId:Ae.uuid()}),release:Oo,validatedAt:Ae.iso.datetime({offset:!0}),validUntil:Ae.iso.datetime({offset:!0}),entries:Ae.array(Ae.strictObject({id:Ae.uuid(),funnelId:Ae.uuid(),versionId:Ae.uuid(),event:Ae.enum(["screen_enter","button_click"]),target:iI})).max(4e3)}),Qg=Ae.strictObject({operation:Ae.literal("entry_start"),funnelId:Ae.uuid(),versionId:Ae.uuid(),entryId:Ae.uuid(),release:Oo,requestId:Ae.uuid(),locale:Ae.string().min(1).max(35).default("en")}),Jg=Ae.strictObject({scope:Te,suppressed:Ae.literal(!0),reason:Ae.enum(["frequency","in_progress"]),retryAt:Ae.iso.datetime({offset:!0}).nullable()}),jT=Ae.strictObject({experimentId:Ae.uuid(),splitNodeId:Ae.string().min(1).max(128)}),oI=Ae.strictObject({experimentId:Ae.uuid(),experimentKey:Ae.string().min(1).max(128),variationKey:Ae.string().min(1).max(128),inExperiment:Ae.boolean(),generation:Ae.string().min(1).max(256)}),Po=Ae.strictObject({operation:Ae.literal("page_experiments"),release:Oo,usedReceiptIds:Ae.array(Ae.uuid()).max(20).default([]),customerToken:Ae.string().regex(kt).optional()}),Zg=Ae.strictObject({scope:Te,runId:Ae.uuid(),assignments:Ae.array(oI.extend({receiptId:Ae.uuid()})).max(100),payload:Hg});var kn=se.literal(af),aI=se.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),Du=se.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),Wg=se.discriminatedUnion("type",[se.strictObject({type:se.literal("guest"),guestToken:Du}),se.strictObject({type:se.literal("customer"),customer:qr,customerData:Pi.optional()})]),Fu=se.strictObject({id:se.uuid(),runId:se.uuid(),customerId:se.uuid(),requestId:se.uuid(),acceptedAt:se.iso.datetime({offset:!0})}),sI=se.strictObject({participantId:se.uuid(),startedAs:se.enum(["guest","identified"]),binding:Fu.omit({runId:!0,requestId:!0}).nullable()}),cI=se.union([Tu,se.strictObject({type:se.literal("authentication_required"),reason:se.enum(["customer_required","customer_experiment_required"]),nodeId:se.string().min(1).max(64),visit:se.number().int().nonnegative()})]),uI=wo.omit({authenticated:!0}).extend({identity:sI,instruction:cI.nullable()}),lI=se.discriminatedUnion("operation",[wt.options[2].omit({customerToken:!0}),wt.options[3].omit({customerToken:!0}),wt.options[4].omit({customerToken:!0}),wt.options[5].omit({customerToken:!0}),wt.options[6].omit({customerToken:!0}),wt.options[7].omit({customerToken:!0})]),as={contract:kn,customerToken:se.string().regex(kt)},Yg={contract:kn,requestId:se.uuid(),runToken:aI,externalUserId:qr.options[1].shape.value},Xg=se.discriminatedUnion("operation",[se.strictObject({contract:kn,operation:se.literal("describe")}),se.strictObject({contract:kn,operation:se.literal("start"),source:Wg,funnelId:wt.options[0].shape.funnelId,requestId:se.uuid(),locale:wt.options[0].shape.locale,parameters:wt.options[0].shape.parameters}),Qg.omit({operation:!0}).extend({contract:kn,operation:se.literal("entry_start"),source:Wg}),se.strictObject({...Yg,operation:se.literal("bind_customer"),guestToken:Du,claimRequestId:se.uuid(),expectedBindingId:se.null()}),se.strictObject({...Yg,operation:se.literal("binding_status"),guestToken:Du.optional()}),wt.options[1].omit({operation:!0,customerToken:!0}).extend({...as,operation:se.literal("get"),settlementBindingId:se.uuid().nullable().optional()}),wt.options[8].omit({operation:!0,customerToken:!0}).extend({...as,operation:se.literal("review")}),Po.omit({customerToken:!0}).extend(as),se.strictObject({...as,operation:se.literal("command"),identity:se.strictObject({bindingId:se.uuid().nullable()}),command:lI})]),Mu=os.omit({run:!0}).extend({contract:kn,run:uI,settlement:os.shape.settlement.unwrap().extend({accepted:se.boolean().nullable().optional()}).optional()}),LT=Jg.extend({contract:kn}),zT=se.discriminatedUnion("operation",[Xg.options[1].omit({contract:!0,source:!0,requestId:!0}),Xg.options[2].omit({contract:!0,source:!0,requestId:!0})]),$T=Mu.extend({binding:Fu,outcome:se.enum(["bound","already_bound"]),replayed:se.boolean()}),GT=se.discriminatedUnion("state",[se.strictObject({contract:kn,scope:Te,state:se.literal("not_accepted")}),se.strictObject({contract:kn,scope:Te,state:se.literal("conflict")}),se.strictObject({contract:kn,scope:Te,state:se.literal("bound"),binding:Fu})]),KT=se.strictObject({contract:kn,scope:Te,keyId:se.uuid(),operations:se.array(se.string()).max(20)});import{z as De}from"zod";var ji=De.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),th=De.strictObject({entry:ji,nodes:De.array(De.strictObject({id:ji,type:De.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:De.record(De.string(),ji),writes:De.record(St,St),resources:De.strictObject({screenId:ji.optional(),paywallVersionId:De.uuid().optional(),couponId:De.uuid().optional(),couponIds:De.array(De.uuid()).max(20).optional(),experimentId:De.uuid().optional(),featureKey:De.string().optional(),offeringVersionId:De.uuid().optional()})})).min(1).max(500)}),eh={scope:Te,funnelId:De.uuid(),versionId:De.uuid(),evaluationRevision:De.number().int().nonnegative(),expiresAt:De.iso.datetime({offset:!0}).nullable(),topology:th},ss=De.discriminatedUnion("evaluationMode",[De.strictObject({...eh,evaluationMode:De.literal("local"),growth:hn,conditions:De.record(ji,De.array(De.strictObject({condition:Yt,port:De.string()})))}),De.strictObject({...eh,evaluationMode:De.literal("remote")})]),dI=ss.options[0].extend({evaluation:De.strictObject({maxTransitions:De.number().int().min(1).max(1e4),variables:De.record(St,mi),outputSchema:pi,terminals:De.record(ji,De.strictObject({outcome:De.enum(["completed","closed","ineligible","failed"]),output:ho.nullable()}))})});function pI(e){return th.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let n={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":n.next=t.next;break;case"screen":Object.assign(n,t.outputs),r.screenId=t.screenId;{let a=e.screens.find(o=>o.id===t.screenId);a?.type==="paywall"&&(r.paywallVersionId=a.paywallVersionId)}break;case"condition":t.cases.forEach((a,o)=>{n[`case:${o}`]=a.target}),n.default=t.default;break;case"split":Object.assign(n,t.routes),n.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let a of["success","cancel","unavailable","failure"])n[a]=t[a];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=De.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 qu(e){let t=Ei.parse(e.document),n=e.evaluationMode==="local"?hn.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:pI(t)};return ss.parse(e.evaluationMode==="remote"?r:{...r,growth:ts(t,n),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((a,o)=>({condition:a.condition,port:`case:${o}`}))]))})}function nh(e){let t=qu(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=Ei.parse(e.document);return dI.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 rh=nt.string().regex(/^[a-f0-9]{64}$/),mI=wi.omit({variations:!0,active:!0}).extend({changeId:rh,variations:nt.array(nt.strictObject({urlRedirect:nt.string().max(2048)})).min(2).max(20)}),ih=nt.strictObject({environmentId:nt.uuid(),trackExposures:nt.boolean(),generation:rh,experiments:nt.array(mI).max(100),savedGroups:mo}),fI=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)}),oN=nt.strictObject({events:nt.array(fI).min(1).max(20)}),aN=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 ut}from"zod";var Bu=32,gI=522240;function Vu(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 hI=ut.strictObject({nodeId:ut.string().min(1).max(64),visit:ut.number().int().nonnegative(),revision:ut.number().int().nonnegative()}),Uu=ut.record(ut.string(),ve),yI=ut.strictObject({id:ut.uuid(),nodeId:ut.string().min(1).max(64),visit:ut.number().int().nonnegative(),input:ut.strictObject({schemaVersion:yo.shape.schemaVersion,kind:yo.shape.kind,selector:yo.shape.selector,contract:yo.shape.contract}),context:Uu,removed:ut.array(ut.string()).max(100),attributes:Uu,removedAttributes:ut.array(ut.string()).max(100),result:Ff,offeringVersionId:ut.uuid().nullable(),events:ut.strictObject({entered:ut.string().regex(/^[1-9][0-9]{0,18}$/),decision:ut.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),pN=ut.strictObject({schemaVersion:ut.literal(1),mode:ut.enum(["local","remote"]),versionId:ut.uuid(),generation:ut.number().int().positive(),base:hI,context:Uu,steps:ut.array(yI).min(1).max(Bu)}).refine(e=>un(e)<=gI,"Segment exceeds its byte budget");var AI=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function Co(e){return Array.isArray(e)?e.some(Co):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&Co(n):!AI.test(t))}function oh(e,t,n,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(s=>s.id===t.screenId&&s.type==="paywall")))return"customer_required";let i=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(i&&["bundle","selection","offering"].includes(i.type)||t.type==="condition"&&t.cases.some(s=>Co(s.condition)))return"customer_required";let a=JSON.stringify([t,t.type==="screen"?e.screens.find(s=>s.id===t.screenId):null]);for(let[s,c]of Object.entries(e.variables))if(c.source.type==="attribute"&&c.source.key!=="funnelParticipantId"&&(a.includes(`variables.${s}`)||a.includes(JSON.stringify(s))))return"customer_required";if(t.type==="split"){let s=n.experiments?.[t.experimentId];if((s?.hashAttribute??"id")!=="funnelParticipantId"||Co(s?.condition)||s?.parentConditions?.length)return"customer_experiment_required"}let o=t.type==="feature"?t.featureKey:i?.type==="feature"?i.featureKey:void 0;return o&&n.features?.[o]?.rules?.some(s=>(s.hashAttribute??"id")!=="funnelParticipantId"||Co(s.condition)||s.parentConditions?.length)?"customer_experiment_required":null}var Lu=class extends Error{constructor(n,r){super(r);Me(this,"code",n);this.name="FunnelLocalCalculationError"}},ah=(e,t)=>new Lu(e,t),bI=e=>({experiments:e.experiments,features:e.features});function xI(e,t=ah){let n=new Map(e.topology.nodes.map(o=>[o.id,o])),r=ii(e.growth.savedGroups),i=bI(e.growth);function a(o,s){if(!Object.hasOwn(e.growth.features,o))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Gn(o,s).value}return{nodes:n,savedGroups:r,features:i.features,feature:a,evaluate(o,s){let c=n.get(o);if(!c)throw t("NOT_FOUND","Funnel node is unavailable");let u,l;if(c.type==="condition"){let f=e.conditions[c.id];if(!f)throw t("INVALID_RESPONSE","Local condition rules are unavailable");u=ju({id:c.id,name:c.id,type:"condition",cases:f.map(g=>({condition:g.condition,target:c.outputs[g.port]})),default:c.outputs.default},s,i.experiments).port}else if(c.type==="feature"){if(!c.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");l=a(c.resources.featureKey,s),u="next"}else if(c.type==="split"){if(!(c.resources.experimentId?e.growth.experiments[c.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let g=ju({id:c.id,name:c.id,type:"split",experimentId:c.resources.experimentId,routes:c.outputs,notParticipating:c.outputs.notParticipating},s,i.experiments);l=g.value,u=g.port}else if(["offering","end","output"].includes(c.type)&&c.resources.featureKey)l=a(c.resources.featureKey,s),u=c.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let m=c.outputs[u]??(u==="value"?c.id:void 0);if(!m)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:o,port:u,target:m,...l===void 0?{}:{value:l}}}}}function SI(e,t){let n=ss.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=xI(n,t);return(o,s)=>(i(),II(a,o,s))}function II(e,t,n){let r=vt.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 vI(e,t,n){let r=[],i=[],a=[],o=e(t,{...n.attributes?{attributes:n.attributes}:{},stickyBucketAssignmentDocs:n.sticky,saveStickyBucketAssignmentDoc(s){let c=r.findIndex(m=>m.next.attributeName===s.attributeName&&m.next.attributeValue===s.attributeValue),u=s.attributeName+"||"+s.attributeValue,l={expected:n.sticky[u]??null,next:s};c<0?r.push(l):r[c]=l},onExperimentViewed(s,c){c.inExperiment&&c.hashUsed&&!c.passthrough&&i.push(ve.parse({key:s.key,variationId:c.variationId,keyUsed:c.key,hashAttribute:c.hashAttribute,hashValue:c.hashValue}))},onFeatureUsage(s,c){a.push(ve.parse({feature:s,value:c.value,source:c.source,...c.ruleId?{ruleId:c.ruleId}:{}}))}});return{port:o.port,...o.value===void 0?{}:{value:o.value},sticky:r,exposures:i,features:a}}function sh(e,t,n,r=ah){let i=n,a=new Map(t.graph.nodes.map(R=>[R.id,R])),o=structuredClone(n.variables),s=structuredClone(i.sticky),c=[],u=n.nodeId,l=n.visit,m=!1,f,g=R=>oh(t,R,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),d=R=>(f??(f=SI(e,r)),vI(f,R,{attributes:Wc({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:o,savedGroups:{}}),sticky:s}));for(let R=0;R<Bu;R++){let y=a.get(u);if(!y||!Vu(y)||g(y))break;if(l>=t.execution.maxTransitions&&(l>t.execution.maxTransitions||y.type!=="end"&&y.type!=="output")){if(!c.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let A,x;if(["condition","feature","split"].includes(y.type)||y.type==="offering"&&y.configuration.source==="feature")A=d(y.id),y.type==="offering"&&(A.value={type:"offering_version",id:String(A.value)}),y.type==="condition"?x=A.port==="default"?y.default:y.cases[Number(A.port.slice(5))]?.target:y.type==="split"?x=A.port==="notParticipating"?y.notParticipating:y.routes[A.port]:(y.type==="feature"||y.type==="offering")&&(x=y.next);else if(A={port:"next",sticky:[],exposures:[],features:[]},(y.type==="entry"||y.type==="coupon"||y.type==="coupons")&&(x=y.next),y.type==="offering"&&y.configuration.source==="fixed"&&(A.value={type:"offering_version",id:y.configuration.versionId},x=y.next),y.type==="end"||y.type==="output"){let P=y.type==="end"?y.output:y.value;if(A=P?.type==="feature"?d(y.id):{...A,port:"value",value:P?.type==="literal"?P.value:P?.type==="variable"?wc({source:"variable",key:P.key,...P.path?{path:P.path}:{}},{declarations:t.variables,answers:n.answers,results:o,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},P&&(A.value===void 0||!gn(t.outputSchema,A.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let v=[...c,{nodeId:u,result:A}];if(un({steps:v})>6e4){if(!c.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(c.push({nodeId:u,result:A}),y.type==="feature"||y.type==="offering"||y.type==="coupon"||y.type==="coupons"){let P=y.type==="coupons"?y.couponIds.map(_=>({type:"reward",id:_})):y.type==="coupon"?{type:"reward",id:y.couponId}:A.value;if(P===void 0)throw r("INVALID_RESPONSE","Node output is missing");let j=fi(y,{value:P});Wp(t.variables,y,j),Object.assign(o,j)}for(let P of A.sticky)s[`${P.next.attributeName}||${P.next.attributeValue}`]=structuredClone(P.next);if(y.type==="end"||y.type==="output"){m=!0;break}if(!x)throw r("INVALID_RESPONSE","Local pure exit is unavailable");u=x,l++}let h=a.get(u);return{steps:c,...!m&&h&&(!Vu(h)||g(h))?{boundary:{nodeId:u,visit:l}}:{}}}var b=class extends Error{constructor(n,r,i,a,o){super(r);Me(this,"code",n);Me(this,"status",i);Me(this,"requestId",a);Me(this,"commandRequestId");Me(this,"retryable");Me(this,"recovery");Me(this,"retryAfterSeconds");Me(this,"reason");this.name="IndianaError",this.reason=o?.reason;let s=qo(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 _o=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new b("INVALID_STATE","Installation sequence exhausted");return e+1},wI=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 Mn(e,t){return e.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new b("INVALID_STATE","Installation journal is invalid");return t({...n})})}function ch(e,t,n){let r=null,i=0,a=0,o=0,s=Promise.resolve(),c=!1;if(e&&(!n||Te.parse(e.scope).projectId!==n.projectId||e.scope.environment!==n.environment))throw new b("SCOPE_MISMATCH","Push installation belongs to another scope");let u=()=>{if(c)throw new b("CLOSED","SDK client was destroyed");if(!e)throw new b("NOT_CONFIGURED","Configure this client's native Push host first");return e},l=x=>{if(x!==i)throw new b("IDENTITY_CHANGED","Identity changed during Push operation")};async function m(x){let v=u();if(!v.sha256&&!globalThis.crypto?.subtle)throw new b("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let P=v.sha256?await v.sha256(Uint8Array.from(x,j=>j.charCodeAt(0))):await wI(x);if(!/^[a-f0-9]{64}$/.test(P))throw new b("INVALID_STATE","Push credential digest is invalid");return P}function f(x){let v=Sr.parse(x);if(v.installationId.toLowerCase()!==u().installationId.toLowerCase())throw new b("INVALID_RESPONSE","Push response belongs to another installation");return v}async function g(x,v){let P=u(),j={installationId:P.installationId,publicKey:P.publicKey,issuedAt:new Date().toISOString(),...v},_=await P.sign(vl(x,P.scope,j));return{...j,signature:_}}let d=(x,v,P)=>t.requestWithCredential?t.requestWithCredential(x,v,P):t.request(x,v);async function h(){let x=u(),v=i,P=r?await(t.session?.access()??r):null,j=Mn(x,Se=>Se),_;if(j.detachSeq!==null){let Se=j.detachSeq,gt=xl.parse(await g("detach",{sequence:Se,platform:x.platform}));try{let Qe=await t.request("push/installations/detach",{...x.scope,...gt},"POST",{installationDetach:!0});if(!Qe||typeof Qe!="object"||!("installation"in Qe))throw new b("INVALID_RESPONSE","Push detach acknowledgement is invalid");let je=f(Qe.installation);if(je.bound||je.identitySeq!==Se)throw new b("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(Qe){if(Qe instanceof b&&Qe.status===404)_=Qe;else if(!(Qe instanceof b)||Qe.status!==412)throw Qe}_||Mn(x,Qe=>({...Qe,detachSeq:Qe.detachSeq===Se?null:Qe.detachSeq}))}if(l(v),!P){if(_)throw _;return null}let X=O.bindPushInstallation,le=X.request.parse(await g("bind",{sequence:o,platform:x.platform,credentialDigest:await m(P)}));l(v);let he=X.response.parse(await d(X.path,le,P));l(v);let Re=f(he.installation);if(!Re.bound||Re.identitySeq!==o)throw new b("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return _&&j.detachSeq!==null&&o>j.detachSeq&&Mn(x,Se=>({...Se,detachSeq:Se.detachSeq===j.detachSeq?null:Se.detachSeq})),Re}async function R(){u();let x=i,v=r?await(t.session?.access()??r):null;if(!v)throw new b("NOT_IDENTIFIED","Identify before reading this installation");let P=O.readPushInstallation,j=P.request.parse(await g("read",{credentialDigest:await m(v)}));l(x);let _=P.response.parse(await d(P.path,j,v));return l(x),f(_.installation)}function y(x=h){let v=s.catch(()=>{}).then(x);return s=v,v.catch(P=>{try{e?.onError?.(P instanceof Error?P:new Error("Push synchronization failed"))}catch{}}),v}async function A(x,v,P){let j=u(),_=v.identity,X=v.observation,le=r?await(t.session?.access()??r):null;if(l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");if(!le)throw new b("NOT_IDENTIFIED","Identify before recovering a Push address");if(!x.connectionId||!x.kind||!x.token||!["granted","provisional"].includes(x.permission))throw new b("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await y(async()=>{if(l(_),await h(),l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let he=Mn(j,je=>P?je:{...je,addressSeq:_o(je.addressSeq)}),Se=await g(P?"recovery_confirm":"recovery_request",{...x,sequence:he.addressSeq,credentialDigest:await m(le),...P?{challenge:P}:{}}),gt=P?Il.parse(Se):Sl.parse(Se);if(l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let Qe=await d(`push/installations/recovery/${P?"confirm":"request"}`,gt,le);if(l(_),X!==a||Mn(j,je=>je).addressSeq!==he.addressSeq)throw new b("INVALID_STATE","Push observation changed during recovery");if(P){let je=O.updatePushAddress.response.parse(Qe),et=f(je.installation);if(!et.bound||et.identitySeq!==o||et.addressSeq!==he.addressSeq||et.connectionId!==x.connectionId||et.addressStatus!=="active")throw new b("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return et}if(!Qe||typeof Qe!="object"||!("recovery"in Qe))throw new b("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return ws.parse(Qe.recovery)})}return{recoveryObserver(){u();let x={identity:i,observation:++a};return{async request(v){return ws.parse(await A(v,x))},async confirm(v,P){return Sr.parse(await A(P,x,v))}}},identify(x){if(!e)return;o=Mn(e,P=>({...P,identitySeq:_o(P.identitySeq)})).identitySeq,r=x,i++,a++},reset(){if(e)try{Mn(e,x=>{let v=_o(x.identitySeq);return{...x,identitySeq:v,detachSeq:v}})}finally{r=null,i++,a++}},start(){e&&!c&&y()},destroy(){c=!0,r=null,i++,a++},async sync(){return await y()},read:R,async recover(){let x=u(),v=i,P=o;return a++,await y(async()=>{l(v);let j=await R();return l(v),o=Mn(x,X=>{if(X.identitySeq!==P)throw new b("IDENTITY_CHANGED","A newer installation intent exists");return{...X,identitySeq:_o(Math.max(X.identitySeq,j.identitySeq)),addressSeq:Math.max(X.addressSeq,j.addressSeq)}}).identitySeq,await h()})},tokenObserver(){u();let x=++a,v=i;return async P=>{if(x!==a||v!==i)return null;let j=u(),_=r?await(t.session?.access()??r):null;if(!_)throw new b("NOT_IDENTIFIED","Identify before registering a Push token");if(await y(),l(v),x!==a)return null;let X=Mn(j,Se=>({...Se,addressSeq:_o(Se.addressSeq)})),le=O.updatePushAddress,he=le.request.parse(await g("address",{...P,sequence:X.addressSeq,credentialDigest:await m(_)}));if(l(v),x!==a)return null;let Re=await d(le.path,he,_);return l(v),x!==a||Mn(j,Se=>Se).addressSeq!==X.addressSeq?null:f(le.response.parse(Re).installation)}}}}import{ZodError as OI}from"zod";function uh(e,t,n,r){try{return e.parse(t)}catch(i){throw r&&i instanceof OI?new b(n,r):i}}async function ge(e,t,n,r={},i){let a=typeof r=="function"?{}:r,o=uh(t.request,n,"INVALID_REQUEST",a.request);try{let s=await e(t.path,o,t.method,i),c=typeof r=="function"?r:r.parseResponse;return c?c(t.response,s):uh(t.response,s,"INVALID_RESPONSE",a.response)}catch(s){throw s instanceof b&&o!==null&&typeof o=="object"&&"requestId"in o&&typeof o.requestId=="string"&&(s.commandRequestId??(s.commandRequestId=o.requestId)),s}}function lh(e,t){let n={async preference(r){let i=O.readMessagingPreference;return(await ge(e,i,{channel:r})).preference},async setPreference(r){let i=O.setMessagingPreference;return(await ge(e,i,r)).preference}};return{messaging:n,push:{sync:t.sync,read:t.read,recover:t.recover,tokenObserver:t.tokenObserver,recoveryObserver:t.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return n.setPreference({...r,channel:"push"})}}}}var dh={name:"@tinkerlandai/longplay-sdk",version:"0.10.16-rc.1",description:"Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit && tsc --noEmit -p tsconfig.test.json",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};function He(e){return typeof e=="string"?e:String(e)}var CI=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function _I(e){return e.replace(CI,"$1\uFFFD")}function Ku(e,t){if(typeof e!="object"||e==null){let n="";throw n+="The provided value is not an object",new TypeError(n)}return e}function xh(e){if(e!=null&&(typeof e=="object"||typeof e=="function")){let t=e[Symbol.iterator];if(t==null)return;if(typeof t!="function")throw new TypeError("The provided value is not iterable");let n=t.call(e);if(!n||typeof n!="object")throw new TypeError("Result of the Symbol.iterator method is not an object");return n}}function ph(e){let t;if(Array.isArray(e)){let n=e.map(He);if(n.length===2)return n}else if((t=xh(e))!=null){let n=Ku(t.next()),r=Ku(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 mh="0123456789ABCDEF",EI=/(?:%[0-9A-Fa-f]{2})+/g;function qn(e){return`%${mh[e>>4&15]}${mh[15&e]}`}function Sh(e,t,n=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?n&&e===32?"+":t(e)?qn(e):String.fromCharCode(e):e<=2047?qn(192|e>>6)+qn(128|63&e):e<=65535?qn(224|e>>12)+qn(128|e>>6&63)+qn(128|63&e):qn(240|e>>18)+qn(128|e>>12&63)+qn(128|e>>6&63)+qn(128|63&e)}function Hu(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function Qu(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(EI,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function ko(e){return e<=31||e>126}function RI(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return ko(e)}}function tl(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return ko(e)}}function kI(e){return tl(e)||e===39}function Ju(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return tl(e)}}function ps(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 Ju(e)}}function fh(e){switch(e){case 33:case 39:case 40:case 41:case 126:return!0;default:return(function(n){switch(n){case 36:case 37:case 38:case 43:case 44:return!0;default:return ps(n)}})(e)}}function Ih(e,t){return Sh(e=e||0,t)}function Un(e,t,n=!1){let r=0;for(;r<e.length;r++){let a=e.charCodeAt(r);if(a>=128||n&&a===32||t(a))break}if(r===e.length)return e;let i=e.slice(0,r);for(;r<e.length;r++){let a=e.charCodeAt(r),o=a;if(a>=55296&&a<=56319&&r+1<e.length){let s=e.charCodeAt(r+1);s>=56320&&s<=57343&&(o=(a-55296<<10)+s-56320+65536,r++)}i+=Sh(o,t,n)}return i}function nl(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([Qu(i.slice(0,a),!0),Qu(i.slice(a+1),!0)])}if(n=r+1,r===e.length)break}return t}function Zu(e){let t="";for(let n=0;n<e.length;n++){let r=Un(e[n][0],fh,!0),i=Un(e[n][1],fh,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var jI=[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],TI=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],NI=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],DI=[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 FI(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[MI,qI,UI,gh]=[[[],"0,6,7,8,m,w,10,1b,1d,1f,72,73,7k,8k,dt,2rk","AAAAAAAAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAA/AAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAADAAABwfwAAAAAAAMADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhAAAAQAAAAAAAAQCAAABAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgACAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAP///////////////wAAAAAAAAAAAAAAAAAAAAA="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAEF9+P/+BwAAAMAA//8AAPz/////BlADAAAAAJwAAPz///8AAADA//H/5+X8AAAAAAAAAAAA/P///wcAAAAAAAAAAAAAPv0vAD0BAABA/gAA/5/5/f8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8g+N8B+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAYAAAAAAAAAAAAAD/////CwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANgAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/HgwAAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAP3////+BwAAAMDu//////////////8vAADAAJwAAP3///8AAADg////////AAAAAAAAAAAA/P///wcAAAAAAAAAAAAA////Ab0H//9H/gAA/9////8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL/G//8T+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAfgAAAAAAAAAAAAD+////DwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANwAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/Hg4AAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"0,3,4,5,6,7,8,9,a,b,c,d,e,f,g,j,n,o,p,q,r,s,t,w,18,19,1c,4m,4o,4p,4q,4r,6z,72,73,75,76,77,7e,7h,7i,7j,7k,7l,7m,7n,7o,7p,7q,7r,7s,7t,7u,7v,7w,7x,7y,7z,8k,9t,a2,a3,a7,cc,cv,cx,cy,d6,dc,dd,de,dg,dh,di,dk,dl,2rk,2rl","AAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAD//////////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD4AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/v////+/tgAAAAAAAAAAAP8XAAAAAAD4//8AAAEAAAAAAAAAAAAAAMCfnz0AAACAAgAAAP///wcAAAAAAAAAAAAAwP8BAAAAAAAA+A8gAADA++8+AAAAAAAOAAAAAAAAgP8AAAAAAPz///v///8HAAAAAAAAFP4h/gAMAAAAAgAAAAAAABAeIAAADAAAQAYAAAAAAAAQhjkCAAAAIwAGAAAAAAAAEL4hAAAMAAD8AgAAAAAAAJAeIGAADAAAAAQAAAAAAAAAASAAAAAAAAARAAAAAAAA0ME9YAAMAAAAAgAAAAAAAJBAMAAADAAAAAMAAAAAAAAYHiAAAAwAAAACAAAAAAAAAAAEXAAAAAAAAAAAAAAA8geAfwAAAAAAAAAAAAAAAPIfAH8AAAAAAAAAAAADAACgAgAAAAAAAP5/3+D//v///x9AAAAAAAAAAAAAAAAA4P1mAAAAwwEAHgBkIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAAAAMAAAADAAAAAwAAAAAAAAAsD9A/g8gAAAAAAC4AAAAAAAAAAAAAAAAAABgAAAAAAIAAAAAAAAAAAAAAAAAAIcBBA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAJAAAAAAAAQH/lH/ifAAAAAAAA//////8//w8AAA8AAAAAANAXBAAAAAD4DwADAAAAPDsAAAAAAABAowMAAAAAAADwzwAAAAAAAAAAAAAAAAAAAAAAAAD3//0hEAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////wDIAAAAfAAAAAAAAB/8AAAAAAAAAAAAAAAA/////wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAwAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAA/////wAAAAAAPAAAAAAAAAAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAID3PwAAAMAAAAAAAAAAAAAAAwBECAAAYBAAAAAAAAAAAAAAAAAAAAAAAAAwAAAA//8DgAAAAADAPwAAgP8DAAAAAAAHAAAAAADIMwAAAAAgAAAAAAAAAAB+ZgAIEAAAAAAAEAAAAAAAAJ3BAgAAAAAwQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICEAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8AAP//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAMAHAAAAAAAAAAAAAAAAAAAAAG7wAAAAAACHAAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAPAAAAAAAAAAAD4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAAAAAAAAA/AAAAAAAAAAAwP8BAAAAAAA8AAAAAAAAAAAAAAAAAAAAAgAAAAAAAP9/AAAAAAAZgAMAAAAAAHgGBAAAAAAAAAAHAAAAgO8fAAAAAAAAAAgAAwAAAAAAwH8AngAAAAAAAAAAAAAAgNNAAgAAAAAAAAAAAAAAAAAAAAAAAID4BwAAAwAAAAAAABgBAAAAwB8fAAAAAAAAAAD4AUAFAAYAAAAAAAAAAAAA/1wAAEAAAAAAAAAAAAAA+IUNAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8sAEAADAAAAAAAAAAAAAA+KcBAAAAAAAAAAAAAAAAKL8AAAAAAAAAAAAAAACgvA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgP8GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFgIAAAAAAAAAAAAAAAAAAAAAADwDAEAAAD+BwAAAAD4eYAAfg4AAAAAAPx/AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf78AAAAAAAAAAAAA/P///G0AAAAAAAAAAAAAAAAAAAB+tL8AAAAAAAAAAACjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAAwAAAAAAwAcFAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//4H/PwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMD/4wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHwAAAAAAAAB/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAgAcAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGAPAAAAAAAAAAAAAAD//////z///38AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAD+P/nDwAAADwAAAAAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////9/+P//////HyAAEAAA+P7/AAAAAAAAAAAAAH////nbBwAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASMAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAADwDwAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAA////////////////AAAAAAAAAAAAAAAAAAAAAP///////////////////////////////////////wAA"]].map(function([t,n,r]){return[t,n.split(",").map(i=>parseInt(i,36)),Uint8Array.from(atob(r),i=>i.charCodeAt(0))]});function BI(e,t){return t===931||t===1010||t===120531||t===120589||t===120647||t===120705||t===120763?"\u03C3":t>=5112&&t<=5117?String.fromCodePoint(t-8):t>=43888&&t<=43967?String.fromCodePoint(t-38864):t>=93856&&t<=93880?String.fromCodePoint(t+27):t===837||t===890||t>=8064&&t<=8111||t>=8114&&t<=8188?e.normalize("NFD").replace(/\u0345/g,"\u03B9").normalize("NFC").toLowerCase():""}function vh(e,t){for(let n=0;n<e.length;n+=2)if(t>=e[n]&&t<=e[n+1])return!0;return!1}function Eo(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 VI(e){let t=Array.from(e,n=>n.codePointAt(0));for(let n=0;n<t.length;n++){let r=t[n];if(r!==8204&&r!==8205||n>0&&vh(DI,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&Eo(gh,t[i]);)i--;let a=n+1;for(;a<t.length&&Eo(gh,t[a]);)a++;if(!(i>=0&&a<t.length&&Eo(qI,t[i])&&Eo(UI,t[a])))return!1}return!0}var LI=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,zI=/\p{Script=Latin}/u;function $I(e){return!LI.test(e)||!zI.test(e)}var lr=36,us=1,Wu=26,GI=38,KI=700,HI=72,QI=128,JI=2147483647;function hh(e){return String.fromCharCode(e+22+75*+(e<26))}function ZI(e,t,n){let r=0;for(e=n?Math.floor(e/KI):e>>1,e+=Math.floor(e/t);e>(lr-us)*Wu>>1;r+=lr)e=Math.floor(e/(lr-us));return Math.floor(r+(lr-us+1)*e/(e+GI))}function WI(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=QI,o=0,s=HI;for(;r<t.length;){let c=JI;for(let u=0;u<t.length;u++){let l=t[u];l>=a&&l<c&&(c=l)}o+=(c-a)*(r+1),a=c;for(let u=0;u<t.length;u++){let l=t[u];if(l<a&&o++,l===a){let m=o;for(let f=lr;;f+=lr){let g=f<=s?us:f>=s+Wu?Wu:f-s;if(m<g)break;n+=hh(g+(m-g)%(lr-g)),m=Math.floor((m-g)/(lr-g))}n+=hh(m),s=ZI(o,r+1,r===i),o=0,r++}}o++,a++}return n}function zu(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=Hu(e.charCodeAt(r));if(i>=t||i<0)return-1;n=n*t+i}return n}function yh(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function wh(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function Oh(e){return e.length===2&&wh(e.codePointAt(0),e.codePointAt(1))}function Ah(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function mt(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function Ph(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function Yu(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=Hu(c[s]))>=0;)l=(l<<4)+u,s++,m++;if(c[s]===46){if(m===0||o>6)return null;s-=m;let f=0;for(;c[s]!==void 0;){let g=0;if(f>0)if(c[s]===46&&f<4)s++;else return null;if(c[s]==null||c[s]<48||c[s]>57)return null;for(;c[s]>=48&&c[s]<=57;){if(g=10*g+Hu(c[s]),g>255)return null;s++}i[o]=256*i[o]+g,f++,f%2==0&&o++}if(f!==4)return null;break}else if(c[s]===58){if(c[++s]===void 0)return null}else if(c[s]!==void 0)return null;i[o]=l,o++}if(a!==null){let u=o-a;for(o=7;o!==0&&u>0;){let l=i[a+u-1];i[a+u-1]=i[o],i[o]=l,o--,u--}}else if(a===null&&o!==8)return null;return i})(e.substring(1,e.length-1)):null;if(t)return(function(r){return Ah(r)?null:Un(r,ko)})(e);{let n=(function(i){let a=!1,o=!1;for(let c=0;c<i.length;c++){let u=i.charCodeAt(c);if(u<=32||u===37||u===127)return null;if(u>=128){a=!0;break}u>=65&&u<=90&&(o=!0)}if(!a)return i!==""?o?i.toLowerCase():i:null;if((function(u){for(let l of u){let m=l.codePointAt(0);if(/[\p{Cn}\p{Co}\p{Cs}\p{Noncharacter_Code_Point}]/u.test(l)&&!vh(jI,m)||Eo(MI,m))return!0}return!1})(i))return null;let s=(i=(function(u){let l="";for(let m of u){let f=m.codePointAt(0);if(f!==8204&&f!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(m))continue;let g=BI(m,f);if(g){l+=g;continue}let d=TI.indexOf(f);l+=d<0?m:NI[d]}return l})(i).normalize("NFKC").replace(/[\u3002\uff0e\uff61]/g,".").toLowerCase()).split(".");for(let c=0;c<s.length;c++){let u=s[c];if(u==="")continue;let l=/[^\0-\x7f]/.test(u);if(FI(u)||l&&(/^\p{Mark}/u.test(u)||!VI(u)||!$I(u)||u.startsWith("xn--")))return null;l&&(s[c]=`xn--${WI(u)}`)}return(i=s.join("."))!==""?i:null})(e.indexOf("%")===-1?e:Qu(e));return n===null||Ah(n)?null:(function(i){let a=i.length,o=i.lastIndexOf(".",a-2)+1;if(i.charCodeAt(a-1)===46&&a--,a<=o)return!1;if(zu(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=zu(a[u]);if(l<0||l>255)return null;s+=l*(1<<8*(3-u))}let c=zu(a[o-1]);return c<0||c>=256**(5-o)?null:(s+=c,s)})(n):n}}function Xu(e){return typeof e=="number"?(function(n){let i="";return i+=`${(n>>>24&255).toString(10)}.`,i+=`${(n>>>16&255).toString(10)}.`,i+=`${(n>>>8&255).toString(10)}.`,i+=(n&255).toString(10),i})(e):Array.isArray(e)?`[${(function(n){let r=(function(s){let c=-1,u=-1,l=1,m=0;for(let f=0;f<s.length;++f)s[f]!==0?(m>l&&(c=u,l=m),u=-1,m=0):(u===-1&&(u=f),++m);return m>l?u:c})(n),i="",a=!1;for(let o=0;o<=7;++o)if(!(a&&n[o]===0)){if(a&&(a=!1),r===o){i+=o===0?"::":":",a=!0;continue}i+=n[o].toString(16),o!==7&&(i+=":")}return i})(e)}]`:e}function Ch(e){e.path.length>0&&(e.path.length!==1||e.scheme!=="file"||!(function(n){return/^[A-Za-z]:$/u.test(n)})(e.path[0]))&&e.path.pop()}function _h(e){return e.username!==""||e.password!==""}function $u(e){return e.host===null||e.host===""||e.scheme==="file"}var E=0,U="",Oe="",Ve=null,B,ls=!1,ds=!1,Gr=!1,ft;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),E=0,U=e,Oe="",Ve=n||null,B=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},ls=!1,ds=!1,Gr=!1,ft=r||0;let i=YI;switch(r){case 3:case 4:i=ms;break;case 5:i=il;break;case 6:i=Kr;break;case 7:i=dr;break;case 8:i=Bn}return i(G(e,E))!==1?B:null}function ee(e,t){return E+=E===e?jn(t):1,E<=U.length}function G(e,t){return t<e.length?e.codePointAt(t):void 0}function jn(e){return e!=null&&e>65535?2:1}function Eh(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var YI=e=>{let t=E;if(e!=null&&(e>=65&&e<=90||e>=97&&e<=122)){let n=E+1;for(e=U.charCodeAt(n);e===43||e===45||e===46||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57;)n++,e=U.charCodeAt(n);return Oe=U.slice(E,n).toLowerCase(),E=n,XI(n<U.length?e:void 0)}else return ft?1:(--E,ee(t,e)?Rh(G(U,E)):0)},XI=e=>{let t=E;if(e===58){if(ft){if(mt(B.scheme)!==mt(Oe))return 0;if((_h(B)||B.port!==null)&&Oe==="file")return 0;if(B.scheme==="file"&&B.host==="")return 0}return B.scheme=Oe,ft?(B.port===Ph(B.scheme)&&(B.port=null),0):(Oe="",B.scheme==="file"?ee(t,e)?ol(G(U,E)):0:mt(B.scheme)&&Ve!==null&&Ve.scheme===B.scheme?ee(t,e)?ev(G(U,E)):0:mt(B.scheme)?ee(t,e)?nv(G(U,E)):0:G(U,E+1)===47?(E++,ee(t,e)?tv(G(U,E)):0):(B.path=[""],B.opaquePath=!0,ee(t,e)?jh(G(U,E)):0))}else return ft?1:(Oe="",E=-1,ee(t,e)?Rh(G(U,E)):0)},Rh=e=>{let t=E;return Ve===null||Ve.opaquePath&&e!==35?1:Ve.opaquePath&&e===35?(B.scheme=Ve.scheme,B.path=Ve.path.slice(),B.opaquePath=Ve.opaquePath,B.query=Ve.query,B.fragment="",ee(t,e)?Bn(G(U,E)):0):Ve.scheme==="file"?(E--,ee(t,e)?ol(G(U,E)):0):(E--,ee(t,e)?rl(G(U,E)):0)},ev=e=>{let t=E;return e===47&&G(U,E+1)===47?(++E,ee(t,e)?gs(G(U,E)):0):(E--,ee(t,e)?rl(G(U,E)):0)},tv=e=>{let t=E;return e===47?ee(t,e)?Ti(G(U,E)):0:(E--,ee(t,e)?Tn(G(U,E)):0)},rl=e=>{let t=E;return B.scheme=Ve.scheme,e===47||mt(B.scheme)&&e===92?ee(t,e)?bh(G(U,E)):0:(B.username=Ve.username,B.password=Ve.password,B.host=Ve.host,B.port=Ve.port,B.path=Ve.path.slice(),B.query=Ve.query,e===63?(B.query="",ee(t,e)?dr(G(U,E)):0):e===35?(B.fragment="",ee(t,e)?Bn(G(U,E)):0):e!=null?(B.query=null,B.path.pop(),E--,ee(t,e)?Tn(G(U,E)):0):ee(t,e)?rl(G(U,E)):0)},bh=e=>{let t=E;return mt(B.scheme)&&(e===47||e===92)?ee(t,e)?gs(G(U,E)):0:e===47?ee(t,e)?Ti(G(U,E)):0:(B.username=Ve.username,B.password=Ve.password,B.host=Ve.host,B.port=Ve.port,E--,ee(t,e)?Tn(G(U,E)):0)},nv=e=>{let t=E;return e===47&&G(U,E+1)===47?E++:E--,ee(t,e)?gs(G(U,E)):0},gs=e=>{let t=E;return e!==47&&e!==92?(E--,ee(t,e)?Ti(G(U,E)):0):ee(t,e)?gs(G(U,E)):0},Ti=e=>{let t=E;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!mt(B.scheme))){let n=E+jn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===64||r===35||r===47||r===63||r===92&&mt(B.scheme))break;n+=jn(r)}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?Ti(G(U,E)):0}if(e===64){ls&&(Oe=`%40${Oe}`),ls=!0;for(let n=0;n<Oe.length;n++){let r=Oe.codePointAt(n);if(r===58&&!ds){ds=!0;continue}let i=Ih(r,ps);ds?B.password+=i:B.username+=i,r!=null&&r>65535&&n++}return Oe="",ee(t,e)?Ti(G(U,E)):0}else return e==null||e===35||e===47||e===63||e===92&&mt(B.scheme)?ls&&Oe===""?1:(E-=Oe.length+1,Oe="",ee(t,e)?ms(G(U,E)):0):(Oe+=Eh(e),ee(t,e)?Ti(G(U,E)):0)},ms=e=>{let t=E;if(ft&&B.scheme==="file")return E--,ee(t,e)?al(G(U,E)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!mt(B.scheme))){let n=E+jn(e);for(e===91?Gr=!0:e===93&&(Gr=!1);n<U.length;){let r=G(U,n);if(r==null||!Gr&&r===58||r===35||r===47||r===63||r===92&&mt(B.scheme))break;r===91?Gr=!0:r===93&&(Gr=!1),n+=jn(r)}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?ms(G(U,E)):0}else if(e===58&&!Gr){if(Oe===""||ft===4)return 1;let n=Yu(Oe,!mt(B.scheme));return n===null?1:(B.host=Xu(n),Oe="",ee(t,e)?il(G(U,E)):0)}else if(e==null||e===35||e===47||e===63||e===92&&mt(B.scheme)){if(E--,mt(B.scheme)&&Oe==="")return 1;if(ft&&Oe===""&&(_h(B)||B.port!==null))return 1;let n=Yu(Oe,!mt(B.scheme));return n===null?1:(B.host=Xu(n),Oe="",ft?0:ee(t,e)?Kr(G(U,E)):0)}else return Oe+=Eh(e),ee(t,e)?ms(G(U,E)):0},il=e=>{let t=E;if(e!=null&&e>=48&&e<=57){let n=E+1;for(;n<U.length;){let r=U.charCodeAt(n);if(r<48||r>57)break;n++}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?il(G(U,E)):0}else if(ft||e==null||e===35||e===47||e===63||e===92&&mt(B.scheme)){if(Oe!==""){let n=parseInt(Oe,10);if(n>65535)return 1;if(B.port=n===Ph(B.scheme)?null:n,Oe="",ft)return 0}return ft?1:(E--,ee(t,e)?Kr(G(U,E)):0)}else return 1};function kh(e,t){let n=e.length-t;if(n<2)return!1;if(wh(G(e,t),G(e,t+1))){if(n===2)return!0;{let r=G(e,t+2);return r===47||r===92||r===63||r===35}}else return!1}var ol=e=>{let t=E;return B.scheme="file",B.host="",e===47||e===92?ee(t,e)?rv(G(U,E)):0:Ve?.scheme==="file"?(B.host=Ve.host,B.path=Ve.path.slice(),B.opaquePath=Ve.opaquePath,B.query=Ve.query,e===63?(B.query="",ee(t,e)?dr(G(U,E)):0):e===35?(B.fragment="",ee(t,e)?Bn(G(U,E)):0):e!=null?(B.query=null,kh(U,E)?B.path=[]:Ch(B),E--,ee(t,e)?Tn(G(U,E)):0):ee(t,e)?ol(G(U,E)):0):(E--,ee(t,e)?Tn(G(U,E)):0)},rv=e=>{let t=E;return e===47||e===92?ee(t,e)?al(G(U,E)):0:(Ve!==null&&Ve.scheme==="file"&&(!kh(U,E)&&(function(r){if(r.length===2){let i=r.codePointAt(0),a=r.codePointAt(1);return(i>=65&&i<=90||i>=97&&i<=122)&&a===58}else return!1})(Ve.path[0])&&B.path.push(Ve.path[0]),B.host=Ve.host),E--,ee(t,e)?Tn(G(U,E)):0)},al=e=>{let t=E;if(e!=null&&e!==47&&e!==92&&e!==63&&e!==35){let n=E+jn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===47||r===92||r===63||r===35)break;n+=jn(r)}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?al(G(U,E)):0}else if(e==null||e===47||e===92||e===63||e===35){if(E--,!ft&&Oh(Oe))return ee(t,e)?Tn(G(U,E)):0;if(Oe==="")return B.host="",ft?0:ee(t,e)?Kr(G(U,E)):0;{let n=Yu(Oe,!mt(B.scheme));return n===null?1:(n==="localhost"&&(n=""),B.host=Xu(n),Oe="",ft?0:ee(t,e)?Kr(G(U,E)):0)}}return 1},Kr=e=>{let t=E;return mt(B.scheme)?(e!==92&&e!==47&&E--,ee(t,e)?Tn(G(U,E)):0):!ft&&e===63?(B.query="",ee(t,e)?dr(G(U,E)):0):!ft&&e===35?(B.fragment="",ee(t,e)?Bn(G(U,E)):0):e!=null?(e!==47&&E--,ee(t,e)?Tn(G(U,E)):0):(ft&&B.host===null&&B.path.push(""),ee(t,e)?Kr(G(U,E)):0)},Tn=e=>{let t=E;if(e!=null&&e!==47&&(!mt(B.scheme)||e!==92)&&(ft||e!==63&&e!==35)){let n=E+jn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===47||mt(B.scheme)&&r===92||!ft&&(r===63||r===35))break;n+=jn(r)}Oe+=Un(U.slice(E,n),Ju),E=n,e=G(U,n)}if(e==null||e===47||mt(B.scheme)&&e===92||!ft&&(e===63||e===35)){let n=mt(B.scheme)&&e===92;return(function(i){switch(i){case"..":case"%2e.":case"%2E.":case".%2e":case".%2E":case"%2e%2e":case"%2E%2e":case"%2e%2E":case"%2E%2E":return!0;default:return!1}})(Oe)?(Ch(B),e!==47&&!n&&B.path.push("")):yh(Oe)&&e!==47&&!n?B.path.push(""):yh(Oe)||(B.scheme==="file"&&B.path.length===0&&Oh(Oe)&&(Oe=`${Oe[0]}:`),B.path.push(Oe)),Oe="",e===63?(B.query="",ee(t,e)?dr(G(U,E)):0):e===35?(B.fragment="",ee(t,e)?Bn(G(U,E)):0):ee(t,e)?Tn(G(U,E)):0}else return Oe+=Ih(e,Ju),ee(t,e)?Tn(G(U,E)):0},jh=e=>{let t=E;if(e===63)return B.query="",ee(t,e)?dr(G(U,E)):0;if(e===35)return B.fragment="",ee(t,e)?Bn(G(U,E)):0;if(e!=null){let n=E+jn(e);for(;n<U.length;){let i=G(U,n);if(i===63||i===35)break;n+=jn(i)}let r=U.slice(E,n);if(n<U.length&&r.charCodeAt(r.length-1)===32?B.path[0]+=Un(r.slice(0,-1),ko)+"%20":B.path[0]+=Un(r,ko),E=n,(e=G(U,n))===63)return B.query="",ee(t,e)?dr(G(U,E)):0;if(e===35)return B.fragment="",ee(t,e)?Bn(G(U,E)):0}return ee(t,e)?jh(G(U,E)):0},dr=e=>{let t=E,n=E;if(e!=null){if(ft)n=U.length;else{let i=U.indexOf("#",E);n=i===-1?U.length:i}let r=mt(B.scheme)?kI:tl;B.query+=Un(U.slice(E,n),r)}return E=n,G(U,n)===35&&!ft?(B.fragment="",ee(t,e)?Bn(G(U,E)):0):ee(t,e)?dr(G(U,E)):0},Bn=e=>{let t=E;return e!=null&&(B.fragment+=Un(U.slice(E),RI),E=U.length),ee(t,e)?Bn(G(U,E)):0};function el(e){if(e.opaquePath)return e.path[0];{let t="";for(let n of e.path)t+=`/${n}`;return t}}function Th(e){switch(e.scheme){case"blob":{let t=mn(el(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":Th(t)}case"ftp":case"http":case"https":case"ws":case"wss":return(function(n){let r=`${n.scheme}://`;return r+=n.host,n.port!==null&&(r+=`:${n.port}`),r})(e);default:return"null"}}var Ke=Symbol("URLImpl"),bn=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[Ke]={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+=el(n),n.query!==null&&(r+=`?${n.query}`),n.fragment!==null&&(r+=`#${n.fragment}`),r})(this[Ke].url)}set href(t){let n=mn(t=He(t),null,null,0);if(n==null)throw new TypeError(`Invalid URL: ${t}`);this[Ke].url=n,this[Ke].query&&Gu(this[Ke].query,n.query)}get origin(){return Th(this[Ke].url)}get protocol(){return`${this[Ke].url.scheme}:`}set protocol(t){mn(`${t=He(t)}:`,this[Ke].url,null,2)}get username(){return this[Ke].url.username}set username(t){t=He(t),$u(this[Ke].url)||(function(r,i){r.username=Un(i,ps)})(this[Ke].url,t)}get password(){return this[Ke].url.password}set password(t){t=He(t),$u(this[Ke].url)||(function(r,i){r.password=Un(i,ps)})(this[Ke].url,t)}get host(){let{url:t}=this[Ke];return t.host==null?"":t.port==null?t.host:`${t.host}:${t.port}`}set host(t){t=He(t),this[Ke].url.opaquePath||mn(t,this[Ke].url,null,3)}get hostname(){let{url:t}=this[Ke];return t.host!=null?t.host:""}set hostname(t){t=He(t),this[Ke].url.opaquePath||mn(t,this[Ke].url,null,4)}get port(){let{url:t}=this[Ke];return t.port!=null?`${t.port}`:""}set port(t){t=He(t);let{url:n}=this[Ke];$u(n)||(t?mn(t,n,null,5):n.port=null)}get pathname(){return el(this[Ke].url)}set pathname(t){t=He(t);let{url:n}=this[Ke];n.opaquePath||(n.path=[],mn(t,n,null,6))}get search(){let{url:t}=this[Ke];return t.query?`?${t.query}`:""}set search(t){t=He(t);let{url:n,query:r}=this[Ke];if(!t)n.query=null,r&&Gu(r,null);else{let i=t[0]==="?"?t.substring(1):t;n.query="",mn(i,n,null,7),r&&Gu(r,n.query)}}get searchParams(){let t=this[Ke],n=t.query;return n==null&&(n=t.query=(function(i,a){let o=new fs;return o[at].url=i,o[at].serialized=a==null,a&&(o[at].list=nl(a)),o})(this,t.url.query)),n}get hash(){let{url:t}=this[Ke];return t.fragment?`#${t.fragment}`:""}set hash(t){t=He(t);let{url:n}=this[Ke];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(bn.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var at=Symbol("URLSearchParamsImpl"),iv=Symbol.dispose||Symbol.for("dispose");function Gu(e,t){t?e[at].list=nl(t):e[at].list.length=0,e[at].serialized=t==null}function cs(e){if(e.url){let t=Zu(e.list);(function(r,i){r[Ke].url.query=i})(e.url,t||null),e.serialized=!0}}var ov=typeof Iterator<"u"?Iterator:Object,Ro=class extends ov{constructor(t,n){super(),this[at]={ptr:t,map:n,index:0}}next(){let t=this[at];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}[iv](){}},fs=class{constructor(t){let n=this[at]={list:[],url:null,serialized:!0},r;if(Array.isArray(t))for(let i=0;i<t.length;i++)n.list.push(ph(t[i]));else if((r=xh(t))!=null){let i;for(;!(i=Ku(r.next())).done;)n.list.push(ph(i.value))}else if((typeof t=="object"||typeof t=="function")&&t!=null){let i=Object.keys(t);for(let a=0;a<i.length;a++){let o=i[a],s=_I(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=nl(i)}}get size(){return this[at].list.length}append(t,n){t=He(t),n=He(n),this[at].list.push([t,n]);let r=this[at];r.url&&r.serialized?(function(a,o){let s=a[Ke].url;s.query=s.query?`${s.query}&${o}`:o})(r.url,Zu([[t,n]])):cs(r)}delete(t,n){t=He(t),n=n!=null?He(n):void 0;let{list:r}=this[at],i=0;for(;i<r.length;)r[i][0]===t&&(n==null||r[i][1]===n)?r.splice(i,1):i++;cs(this[at])}get(t){t=He(t);let{list:n}=this[at];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[at];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[at];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[at],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&&cs(this[at])}sort(){this[at].list.sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0),cs(this[at])}forEach(t,n){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:r}=this[at];for(let i=0;i<r.length;i++)t.call(n,r[i][1],r[i][0],this)}entries(){return new Ro(this[at],t=>t)}keys(){return new Ro(this[at],t=>t[0])}values(){return new Ro(this[at],t=>t[1])}toString(){return Zu(this[at].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(fs.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var pr="https://api.longplayai.com";function Nh(e){let t,n=()=>typeof t=="string"?t:t?.accessToken,r=0,i,a=new Map,o=()=>{for(let m of[...a.keys()])try{m()}catch{}};function s(m){let f=++r;i=void 0,t=void 0;for(let g of[...a.values()])try{g?.()}catch{}f===r&&(t=m,o())}let c=()=>s();function u(m,f=!1){let g=Zn.safeParse(m);if(!g.success||f&&Date.parse(g.data.expiresAt)<=Date.now()||Date.parse(g.data.refreshExpiresAt)<=Date.now()||Date.parse(g.data.refreshExpiresAt)<Date.parse(g.data.expiresAt))throw new b("INVALID_RESPONSE","Invalid customer session credentials");return g.data}async function l(){if(i)return i;let m=typeof t=="object"?t:void 0,f=r;if(!m||Date.parse(m.refreshExpiresAt)<=Date.now())throw m&&c(),new b("UNAUTHENTICATED","Customer authentication is required",401);let g=(async()=>{try{let d=await e(m.refreshToken);if(f!==r)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");let h=u(d,!0);if(h.customerId!==m.customerId||h.sessionId!==m.sessionId)throw new b("SCOPE_MISMATCH","Refresh changed the customer session");return t=h,{...h}}catch(d){throw f!==r?new b("IDENTITY_CHANGED","Customer identity changed during refresh"):(d instanceof b&&d.status===401&&c(),d)}})();i=g;try{return await g}finally{i===g&&(i=void 0)}}return{identify(m){let f=typeof m=="string"?m:u(m),g=typeof f=="string"?f:f.accessToken;if(!g.trim()||/\s/.test(g)||g.length>4096)throw new b("INVALID_TOKEN","A server-issued token is required");s(f)},reset:c,subscribeIdentity(m,f){return a.set(m,f),()=>{a.delete(m)}},access(){let m=typeof t=="object"?t:void 0;if(m&&Date.parse(m.expiresAt)<=Date.now()+3e4){let g=r;return l().then(()=>{let d=n();if(g!==r||!d)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");return d})}let f=n();if(!f)throw new b("NOT_IDENTIFIED","Identify a customer session before making a request");return f},peek:n,snapshot:()=>typeof t=="object"?{...t}:void 0,refresh:l}}var Dh=Symbol("IndianaNoContent");function mr(e,t,n=bn){let r=e.configuration?.scope,i=e.scope??(r&&{projectId:r.projectId,environment:r.environment}),a=i?Te.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??pr);if(o.username||o.password||o.search||o.hash)throw new b("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(o.protocol!=="https:"&&!(o.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(o.hostname)))throw new b("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let s=e.fetch??globalThis.fetch.bind(globalThis),c=e.timeoutMs??1e4;if(!Number.isFinite(c)||c<1||c>12e4)throw new b("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let u=!1,l=0,m=null,f=new Set,g=e.session??Nh(async A=>{let x=await y("customer-sessions/refresh",{},"POST",{},A);if(!x||typeof x!="object")throw new b("INVALID_RESPONSE","Invalid refresh response");let{requestId:v,scope:P,...j}=x;return j});function d(){l+=1,m=null;for(let A of f)A.abort();f.clear()}let h=g.subscribeIdentity(d);function R(){u||g.reset()}async function y(A,x={},v="POST",P={},j){let _=P.installationDetach===!0;if(_&&(A!=="push/installations/detach"||v!=="POST"))throw new b("INVALID_REQUEST","Installation authority only detaches this installation");if(!j&&!_)throw new b("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let X=l,le=new AbortController;_||f.add(le);let he=()=>!_&&X!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new b("TIMEOUT","Longplay request timed out"),Re,Se=new Promise((je,et)=>{Re=()=>et(he()),le.signal.addEventListener("abort",Re,{once:!0})}),gt=setTimeout(()=>le.abort(),P.timeoutMs??c),Qe=async()=>{let je=await s(`${o.href.replace(/\/$/,"")}/api/v1/${A}`,{method:v,headers:{...P.headers,"Content-Type":"application/json",..._?{}:{Authorization:`Bearer ${j}`},[Es]:Rs.current,[_l]:dh.version,...a?{"X-Indiana-Project":a.projectId,"X-Indiana-Environment":a.environment}:{}},body:v==="POST"?JSON.stringify(x):void 0,signal:le.signal,credentials:"omit",cache:"no-store",redirect:"error",...P.keepalive?{keepalive:!0}:{}});if(le.signal.aborted)throw he();let et;try{et=je.status===204?Dh:await je.json()}catch{throw le.signal.aborted?he():new b(je.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",je.status,je.headers.get("X-Request-Id")??void 0)}if(le.signal.aborted)throw he();if(!_&&X!==l)throw new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!je.ok){let dt=_s.safeParse(et),Jt=dt.success&&(!zn.safeParse(dt.data.error.code).success||Pl(dt.data.error.code,je.status)),yr=Jt?dt.data.error.code:"HTTP_ERROR",Ar=qo(yr,je.status,{retryAfter:je.headers.get("Retry-After"),recovery:Jt?dt.data.error.recovery:void 0,reason:Jt?dt.data.error.reason:void 0});throw new b(yr,Jt?dt.data.error.message:"Longplay request failed",je.status,je.headers.get("X-Request-Id")??(dt.success?dt.data.requestId:void 0),{...Ar,...dt.success&&dt.data.error.retryable===!1?{retryable:!1}:{},...Ar.retryAfterSeconds===void 0&&dt.success&&dt.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:dt.data.error.retryAfterSeconds}:{}})}if(je.headers.get(Es)!==Rs.current)throw new b("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&et!==Dh){let dt=et&&typeof et=="object"&&"scope"in et?et:et&&typeof et=="object"&&"configuration"in et?et.configuration:null;if(!dt||typeof dt!="object"||!("scope"in dt))throw new b("INVALID_RESPONSE","Response is missing its App/environment scope");let Jt=Te.safeParse(dt.scope);if(!Jt.success||Jt.data.projectId!==a.projectId||Jt.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let Qr=je.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 et};try{return await Promise.race([Qe(),Se])}catch(je){throw!_&&X!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):je instanceof b?je:new b(le.signal.aborted?"TIMEOUT":"NETWORK_ERROR",le.signal.aborted?"Longplay request timed out":"Unable to read the Longplay response")}finally{clearTimeout(gt),le.signal.removeEventListener("abort",Re),f.delete(le)}}return{session:g,requestWithCredential(A,x,v,P={}){return u?Promise.reject(new b("CLOSED","SDK client was destroyed")):y(A,x,"POST",P,v)},subjectKey:()=>m,identify(A){if(u)throw new b("CLOSED","SDK client was destroyed");if(a&&typeof A=="object"&&"scope"in A){let x=Te.safeParse(A.scope);if(!x.success||x.data.projectId!==a.projectId||x.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Customer session belongs to another App/environment")}g.identify(A)},reset:R,dispose(){u||(u=!0,h(),d())},request(A,x={},v="POST",P={}){if(u)return Promise.reject(new b("CLOSED","SDK client was destroyed"));if(P.installationDetach)return y(A,x,v,P);let j=l;try{let _=g.access(),X=le=>{if(j!==l)throw new b("IDENTITY_CHANGED","Customer identity changed before dispatch");return y(A,x,v,P,le)};return typeof _=="string"?X(_):_.then(X)}catch(_){return Promise.reject(_)}}}}function Fh(e,t,n={}){let r=!1;function i(){if(r)throw new b("CLOSED","SDK client was destroyed")}let a=new Set,o=c=>{for(let u of a)try{u(c)}catch{}},s=e.session.subscribeIdentity(()=>{o(!!e.session.peek()),n.afterChange?.()},()=>{t()});return{assertActive:i,isIdentified:()=>!r&&!!e.session.peek(),methods:{subscribeIdentity(c){return i(),a.add(c),()=>{a.delete(c)}},identify(c){i();let u=typeof c=="string"?c:c.accessToken;if(!kt.test(u))throw new b("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(u),e.identify(c)},reset(){if(!r)try{n.beforeReset?.()}finally{e.reset()}},destroy(){if(!r){r=!0,s(),a.clear();try{n.beforeDestroy?.(),t()}finally{e.dispose()}}}}}}function Le(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new b("INVALID_REQUEST","Customer requests use the verified session identity")}var av={...O.readHoldings,request:O.readHoldings.request.omit({customerId:!0})};function Mh(e){return{async checkEntitlement(t){Le(t);let n=O.checkEntitlement;return ge(e,n,t)},async readHoldings(t={}){return ge(e,av,t)}}}function qh(e){return{async readLedger(t){let n=O.readLedger;return ge(e,n,{query:t})},async readCreditStatement(t){Le(t);let n=O.readCreditStatement;return ge(e,n,t)},async quoteBalance(t){Le(t);let n=O.quoteBalance;return ge(e,n,{command:t})}}}function Uh(e){return{async setupPayment(t){Le(t);let n=O.setupPayment;return ge(e,n,t)},async readPaymentSetup(t){Le(t);let n=O.readPaymentSetup;return ge(e,n,t)},async readBillingInvoice(t){Le(t);let n=O.readBillingInvoice;return ge(e,n,t)},async readBillingControls(t={}){Le(t);let n=O.readBillingControls;return ge(e,n,t)},async prepareBillingAuthorization(t){Le(t);let n=O.prepareBillingAuthorization;return ge(e,n,t)},async confirmBillingAuthorization(t){Le(t);let n=O.confirmBillingAuthorization;return ge(e,n,t)},async setBillingCoupons(t){Le(t);let n=O.setBillingCoupons;return ge(e,n,t,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(t){Le(t);let n=O.revokeBillingAuthorization;return ge(e,n,t)},async listBillingInvoices(t={after:null,limit:25}){Le(t);let n=O.listBillingInvoices;return ge(e,n,t)},async confirmBillingAdjustment(t){Le(t);let n=O.confirmBillingAdjustment;return ge(e,n,t)}}}function Bh(e){return{async previewUpdate(t){Le(t);let n=O.previewUpdate;return ge(e,n,t)},async update(t){Le(t);let n=O.update;return ge(e,n,t)},async readSubscriptionUpdate(t){Le(t);let n=O.readSubscriptionUpdate;return ge(e,n,t)},async restoreNativePurchase(t){Le(t);let n=O.restoreNativePurchase;return ge(e,n,t)},async previewAttach(t){Le(t);let n=O.previewAttach;return ge(e,n,t)},async attach(t){Le(t);let n=O.attach;return ge(e,n,t)},async readSubscriptionOperation(t){Le(t);let n=O.readSubscriptionOperation;return ge(e,n,t)}}}function Vh(e){return{async redeemReward(t){return Le(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 Le(t),(await ge(e,O.claimRewardProduct,t,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(t){return Le(t),(await ge(e,O.createReferralCode,{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(t,n=crypto.randomUUID()){let r=await ge(e,O.redeemCoupon,{code:t,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(t,n=crypto.randomUUID()){let r=await ge(e,O.grantOffer,{couponId:t,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await ge(e,O.listOffers,{},{response:"Invalid offers response"})).offers}}}function Lh(e){return{...Mh(e),...qh(e),...Uh(e),...Bh(e),...Vh(e)}}function zh(e){return{async resolveContent(t){Le(t);let n=O.resolveContent;return ge(e,n,t)},async resolvePaywall(t){Le(t);let n=O.resolvePaywall;return ge(e,n,t)},async resolveOffering(t){Le(t);let n=O.resolveOffering;return ge(e,n,t)}}}var sl=e=>new TextEncoder().encode(JSON.stringify(e)).length,$h=16384;function Gh(e,t){let n=0,r,i=d=>{r={config:structuredClone(d),until:Date.now()+3e4}},a=[],o=null,s;function c(){if(!t())throw new b("NOT_IDENTIFIED","Call identify before using Features or events")}function u(){s||!a.length||(s=setTimeout(()=>{s=void 0,m().catch(()=>{}).finally(u)},5e3),typeof s=="object"&&"unref"in s&&s.unref())}function l(d,h={},R={}){if(c(),r&&Date.now()<r.until&&!Xm(r.config,d))return;g();let y=O.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:d,properties:h,...R}]}).events[0];if(sl({events:[y]})>$h)throw new b("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new b("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(y)),u()}async function m(d=!1){if(c(),o)return o;let h=n,R=(async()=>{let y={inserted:0,duplicates:0,rejected:0,skipped:0},A=a.length;for(;A&&h===n;){let x=[],v=sl({events:[]});for(let _ of a.slice(0,Math.min(A,100))){let X=sl(_)+(x.length?1:0);if(x.length&&v+X>$h)break;x.push(_),v+=X}let P=O.trackEvents,j=await ge(e,P,{events:x},void 0,{keepalive:d});if(h!==n)throw new b("IDENTITY_CHANGED","Event identity changed during delivery");if(j.inserted+j.duplicates+j.rejected+j.skipped!==x.length)throw new b("INVALID_RESPONSE","Incomplete event acknowledgement");i(j.analyticsConfig),a.splice(0,x.length),A-=x.length,y.inserted+=j.inserted,y.duplicates+=j.duplicates,y.rejected+=j.rejected,y.skipped+=j.skipped}return y})();o=R;try{return await R}finally{o===R&&(o=null)}}let f;function g(){if(f||typeof document>"u")return;let d=()=>{document.visibilityState==="hidden"&&t()&&a.length&&m(!0).catch(()=>{})};document.addEventListener("visibilitychange",d),f=()=>document.removeEventListener("visibilitychange",d)}return{rememberConfiguration:i,track:l,flush:m,reset(){n++,r=void 0,clearTimeout(s),s=void 0,a=[],o=null},detachVisibility(){f?.(),f=void 0}}}function cl(e){let t=null,n=null,r=0,i=0,a=new Set,o=null,s=null,c=new Set,u=()=>{for(let y of c)try{y()}catch{}},l={attributes:vt.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(y,A)=>{!a.has(y)&&(!t||!("analyticsConfig"in t)||t.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(y,structuredClone(A),structuredClone(l.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(y,A)=>(!t||!("analyticsConfig"in t)||t.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(y),structuredClone(A),structuredClone(l.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?y=>e.saveStickyBucketAssignmentDoc(structuredClone(y)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},m=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function f(y,A=new Set){return a.has(y)?!o||!o.features[y]||["unknownFeature","cyclicPrerequisite"].includes(o.features[y].source):A.has(y)?!1:(A.add(y),(t?.features[y]?.rules??[]).some(x=>[...x.parentConditions??[],...(x.tracks??[]).flatMap(v=>v.experiment.parentConditions??[])].some(v=>f(v.id,A))))}let g=y=>{if(e.assertUsable?.(t?.generation),!t)throw new Error("Initialize the Feature client before evaluation");if(t.expiresAt&&Date.parse(t.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return o?.expiresAt&&Date.parse(o.expiresAt)<=Date.now()&&(o=null,l.features=t.features),a.has(y)?!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now()?m():structuredClone(o.features[y]??m()):e.evaluateRemote&&(l.attributes?.merchandise||l.attributes?.merchandiseId)&&!o||f(y)?m():structuredClone(Gn(y,l))};async function d(){if(!t||!a.size&&!l.attributes?.merchandise&&!l.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(a.size)throw new Error("Remote Feature evaluation requires a server loader");return}let y=i;if(s?.revision===y)return s.loading;let A=r,x=t,v=[...a],P=(async()=>{let j=qa.parse(await e.evaluateRemote({attributes:structuredClone(l.attributes),features:v}));if(!(A!==r||y!==i||x!==t)){if(e.assertUsable?.(x.generation),j.generation!==x.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(v.some(_=>!Object.hasOwn(j.features,_))||Object.keys(j.features).some(_=>!a.has(_)))throw new Error("Invalid remote Feature results");if(l.attributes?.merchandise||l.attributes?.merchandiseId){if(!j.merchandiseContext)throw new Error("Server did not resolve merchandise context");l.attributes=vt.parse({...l.attributes,...j.merchandiseContext})}o=structuredClone(j),l.features={...x.features,...Object.fromEntries(Object.entries(o.features).map(([_,X])=>[_,{defaultValue:X.value}]))},u()}})();s={revision:y,loading:P};try{await P}finally{s?.loading===P&&(s=null)}}function h(){d().catch(y=>{try{e.onError?.(y)}catch{}})}async function R(){if(n)return n;let y=r,A=(async()=>{let x=await e.load(),v="remoteFeatures"in x?fo.parse(x):null,P=v??hn.parse(x);if(P.scope.projectId!==e.scope.projectId||P.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(y!==r)throw new Error("Feature client was reset");if(e.assertUsable&&t?.generation===P.generation){let{evaluatedAt:_,expiresAt:X,...le}=t,{evaluatedAt:he,expiresAt:Re,...Se}=P;if(Ot(le)!==Ot(Se))throw new Error("Immutable Feature generation changed content");return t.evaluatedAt=P.evaluatedAt,t.expiresAt=P.expiresAt,u(),(!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())&&h(),structuredClone(t)}let j=new Set(v?.remoteFeatures??[]);if([...j].some(_=>Object.hasOwn(P.features,_)))throw new Error("Remote Feature definitions must not be delivered locally");return t&&"analyticsConfig"in t&&"analyticsConfig"in P&&!t.analyticsConfig.experimentViewsEnabled&&v?.analyticsConfig.experimentViewsEnabled&&l.trackedExperiments?.clear(),t=structuredClone(P),a=j,o=null,s=null,i++,l.features=t.features,l.savedGroups=ii(t.savedGroups),l.trackedFeatureUsage={},u(),h(),structuredClone(t)})();n=A;try{return await A}finally{n===A&&(n=null)}}return{init:R,refresh:R,refreshRemote:d,get generation(){return t?.generation??null},get expiresAt(){return t?.expiresAt??null},subscribe(y){return c.add(y),()=>{c.delete(y)}},setAttributes(y){let A=vt.parse(y);(l.attributes?.merchandise||l.attributes?.merchandiseId||y.merchandise||y.merchandiseId)&&l.trackedExperiments?.clear(),l.attributes=A,i++,o=null,s=null,l.features=t?.features??{},l.trackedFeatureUsage={},u(),h()},evalFeature:g,isOn(y){return g(y).on},isOff(y){return g(y).off},getFeatureValue(y,A){let x=g(y).value;return structuredClone(x===null?A:x)},reset(){r++,i++,n=null,s=null,t=null,o=null,a.clear(),l.features={},l.savedGroups={},l.stickyBucketAssignmentDocs={},l.attributes={},l.trackedFeatureUsage={},l.trackedExperiments?.clear(),u()}}}function Kh(e){let t=e.merchandise;if(typeof e.merchandiseId=="string")return{internalId:e.merchandiseId};if(!(!t||typeof t!="object"||Array.isArray(t))){if(typeof t.internalId=="string")return{internalId:t.internalId};if(typeof t.externalId=="string")return{id:t.externalId};if(typeof t.id=="string")return{id:t.id}}}function sv(e){let t=Kh(e),{merchandiseId:n,merchandise:r,...i}=e;return{...i,...t?{merchandise:t}:{}}}function Hh(e,t,n,r,i){if(i&&r&&(i.scope.projectId!==r.projectId||i.scope.environment!==r.environment))throw new b("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,o=new Set;function s(){if(!t())throw new b("NOT_IDENTIFIED","Call identify before using Features or events")}async function c(u={}){i||s();let l=a,m=!1,f=async()=>{if(m||l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let he=O.getFeatures,Re=i?{scope:{projectId:i.scope.projectId,environment:i.scope.environment},payload:await i.features()}:await ge(e,he,{});if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");if(r&&(Re.scope.projectId!==r.projectId||Re.scope.environment!==r.environment))throw new b("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(Re.payload.analyticsConfig),Re},g=await f(),d=!0,h,R=he=>{try{u.onError?.(he)}catch{}},y=(he,Re,Se)=>{try{let gt=Kh(Se);n.track(he,Re,gt?{merchandise:gt}:{})}catch(gt){R(gt)}},A=cl({assertUsable:i?.assertFeatures,scope:g.scope,attributes:u.attributes,onError:u.onError,load:async()=>d?(d=!1,g.payload):(await f()).payload,evaluateRemote:async he=>{if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let Re=O.evaluateFeatures,Se=await ge(e,Re,{...he,attributes:sv(he.attributes)});if(Se.scope.projectId!==g.scope.projectId||Se.scope.environment!==g.scope.environment)throw new b("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:Se.generation,evaluatedAt:Se.evaluatedAt,expiresAt:Se.expiresAt,features:Se.features,...Se.merchandiseContext?{merchandiseContext:Se.merchandiseContext}:{}}},onExperimentViewed:(he,Re,Se)=>y("Experiment Viewed",{experimentId:he.key,variationId:Re.key},Se),onFeatureUsage:(he,Re,Se)=>y("Feature Evaluated",{feature:he,value:Re.value,source:Re.source,ruleId:Re.ruleId,...Re.experimentResult?{variationId:Re.experimentResult.key}:{}},Se)}),x=A.refresh;function v(){clearTimeout(h),!i&&(m||l!==a||!A.expiresAt||(h=setTimeout(()=>{P().catch(R)},Math.min(2147483647,Math.max(1e3,Date.parse(A.expiresAt)-Date.now()))),typeof h=="object"&&"unref"in h&&h.unref()))}async function P(){try{return await x()}finally{v()}}let j=()=>{m||P().catch(R)},_=A.subscribe(v),X=i?.subscribe(()=>{!m&&i.fresh&&P().catch(R)});function le(){m||(m=!0,clearTimeout(h),typeof window<"u"&&window.removeEventListener("focus",j),_(),X?.(),A.reset(),o.delete(le))}o.add(le);try{await A.init(),(u.attributes?.merchandise||u.attributes?.merchandiseId)&&await A.refreshRemote()}catch(he){throw le(),he}return v(),!i&&typeof window<"u"&&window.addEventListener("focus",j),Object.assign(A,{refresh:P,destroy:le})}return{features:c,reset(u){a++,u();for(let l of o)l()}}}import{z as cv}from"zod";function Qh(e,t){let n="source"in t?{funnelId:t.source.id,funnelVersionId:t.source.versionId}:"versionId"in t?{funnelId:t.funnelId,funnelVersionId:t.versionId}:t,r=cv.object({funnelId:is.shape.id,funnelVersionId:is.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new b("INVALID_REQUEST","A valid Funnel source is required");let i=Object.freeze(r.data);function a(o){if("customerId"in o)throw new b("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in o&&o.funnelId!==void 0&&o.funnelId!==i.funnelId||"funnelVersionId"in o&&o.funnelVersionId!==void 0&&o.funnelVersionId!==i.funnelVersionId)throw new b("SCOPE_MISMATCH","The original Funnel source cannot change");return{...o,...i}}return{async claimCoupon(o,s=crypto.randomUUID()){let c=O.grantOffer,u=await ge(e,c,a({couponId:o,requestId:s}));return{offer:u.offer,reason:u.reason}},async resolveOffering(o){let s=O.resolveOffering;return ge(e,s,a(o))},async resolvePaywall(o){let s=O.resolvePaywall;return ge(e,s,a(o))},async previewAttach(o){let s=O.previewAttach;return ge(e,s,a(o))}}}function Jh(e){let t=mr(e),n=t.request,r;try{r=ch(e.push,t,e.scope??e.configuration?.scope)}catch(s){throw t.dispose(),s}let i=Fh(t,()=>{o.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=Gh(n,i.isIdentified),o=Hh(n,i.isIdentified,a,e.scope,e.configuration);return{session:t.session,...lh(n,r),...Lh(n),...zh(n),forFunnel(s){return i.assertActive(),Qh(n,s)},async features(s={}){return i.assertActive(),o.features(s)},track(s,c,u={}){return a.track(s,c,u)},flush(){return a.flush()},...i.methods}}function Ni(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,a)=>Ni(i,t[a]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let n=Object.entries(e),r=Object.entries(t);return n.length===r.length&&n.every(([i,a])=>Object.hasOwn(t,i)&&Ni(a,Reflect.get(t,i)))}function hs(e,t){let n=Gg.safeParse(t);if(!n.success)throw new b("INVALID_RESPONSE","Funnel response contract changed");let r=n.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new b("SCOPE_MISMATCH","Funnel scope changed");return r}var Di=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function ys(e){let t=kt.test(e.apiKey);if(typeof window<"u"&&!t)throw new b("SERVER_ONLY","Funnel starts are issued by your backend");if(!t&&!Di.test(e.apiKey))throw new b("INVALID_TOKEN","A customer credential or server API key is required");return{async start(n){let r=wt.safeParse({...n,operation:"start"});if(!r.success||r.data.operation!=="start"||(t?r.data.customer!==void 0:r.data.customer===void 0))throw new b("INVALID_REQUEST","Invalid current Funnel start");let i=r.data,a=mr({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||a.identify(e.apiKey);let o=hs(e,await a.request("funnels",i));if(!o.runToken)throw new b("INVALID_RESPONSE","Funnel start credentials are missing");if(o.run.source.id!==i.funnelId||o.run.locale!==(i.locale??"en")||!Ni(o.run.parameters,i.parameters??{})||(i.customer?!o.customerId||i.customer.type==="id"&&o.customerId!==i.customer.value:o.customerId!==void 0))throw new b("INVALID_RESPONSE","Funnel start contract changed");return{...o,runToken:o.runToken}}finally{a.dispose()}}}}async function ul(e,t,n){if(Number(e.headers.get("content-length"))>t)throw e.body?.cancel().catch(()=>{}),n.error("limit");let r=e.body?.getReader();if(!r)throw n.error("missing");let i=[],a=0,o=!1,s=()=>{},c=new Promise((m,f)=>{s=()=>f(n.signal?.reason),n.signal?.addEventListener("abort",s,{once:!0}),n.signal?.aborted&&s()});try{for(;;){let m=await Promise.race([r.read(),c]);if(m.done){o=!0;break}if(a+=m.value.length,a>t)throw n.error("limit");i.push(m.value)}}finally{n.signal?.removeEventListener("abort",s),o||r.cancel().catch(()=>{}),r.releaseLock()}n.signal?.throwIfAborted();let u=new Uint8Array(a),l=0;for(let m of i)u.set(m,l),l+=m.length;return u}async function Zh(e,t,n){return new TextDecoder("utf-8",{fatal:!0}).decode(await ul(e,t,n))}function As(e,t){let n=typeof e=="string"?new TextEncoder().encode(e):e;return n.byteLength===t.byteLength&&xu(n)===t.sha256}async function bs(e,t){let n=Br.parse(t),{artifact:r,environmentId:i}=n.content,a=new bn(e.baseUrl??pr).origin,o=new bn(r.url,a);if(o.origin!==a||o.username||o.password||o.search||o.hash||o.pathname!==`/api/v1/configuration/${i}/artifacts/${r.sha256}`)throw new b("INVALID_RESPONSE","Public Paywall locator is not trusted");let s=new AbortController,c,u=new Promise((m,f)=>{c=setTimeout(()=>{let g=new b("TIMEOUT","Public Paywall read timed out");s.abort(g),f(g)},nn.initializationMs)}),l=(async()=>{let m=await(e.fetch??globalThis.fetch)(o,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:s.signal});if(s.signal.aborted&&(m.body?.cancel().catch(()=>{}),s.signal.throwIfAborted()),!m.ok||!m.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(m.headers.get("content-length"))>r.byteLength)throw m.body?.cancel().catch(()=>{}),new b("INVALID_RESPONSE","Public Paywall is unavailable");let f=await ul(m,r.byteLength,{signal:s.signal,error:g=>new b("INVALID_RESPONSE",g==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!As(f,r))throw new b("INVALID_RESPONSE","Public Paywall digest or size changed");return Jf(n,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(f)))})();try{return await Promise.race([l,u])}finally{clearTimeout(c)}}var Wh=(e,t)=>new b(e,t);async function ll(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=uv(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 uv(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=qu({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:hn.parse(o)}),c=lv(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 lv(e,t,n){return sh(e,t,n,Wh)}import{z as fn}from"zod";var Yh=wt.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new b("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),Xh=fn.strictObject({schemaVersion:fn.literal(1),scope:Te,runId:fn.uuid(),funnelId:fn.uuid(),versionId:fn.uuid(),processBindingIds:fn.record(fn.uuid(),fn.uuid().nullable()).optional(),command:Yh.optional(),closeCommand:Yh.refine(e=>e.operation==="close").optional(),purchase:fn.strictObject({receiptId:fn.uuid(),operationId:fn.uuid(),generation:fn.number().int().nonnegative()}).optional(),closed:fn.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),Xt=()=>new b("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),xs=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function ey(e){let t=0,n=null,r=u=>JSON.stringify([u.scope,u.runId,u.funnelId,u.versionId]),i=Promise.resolve();async function a(){let u=await e.read();if(!Number.isSafeInteger(u.revision)||u.revision<0)throw new b("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:u.revision,entry:u.entry===null?null:Xh.parse(u.entry)}}function o(u){let l=i.then(u);return i=l.catch(()=>{}),l}async function s(u){for(let l=0;l<4;l++){let m=await a();if(m.entry&&n!==null&&r(m.entry)!==n)throw Xt();let f=u(m.entry,m.revision);if(xs(m.entry,f)){t=m.revision;return}let g=await e.write(m.revision,f);if(g!==null){if(!Number.isSafeInteger(g)||g<=m.revision)throw Xt();t=g;return}}throw Xt()}function c(u,l){if(!u||!l)return u;if(u.processBindingIds&&Object.hasOwn(u.processBindingIds,l)){let m={...u.processBindingIds};delete m[l],u={...u,processBindingIds:m}}return u.command?.requestId===l?u.closeCommand?{...u,command:u.closeCommand,closeCommand:void 0}:u.purchase?{...u,command:void 0}:null:u.closeCommand?.requestId===l?{...u,closeCommand:void 0}:u}return{bind(u){let l=JSON.stringify([u.scope,u.runId,u.funnelId,u.versionId]);if(n!==null&&n!==l)throw Xt();n=l},async load(){let u=await a();return t=u.revision,n=u.entry?r(u.entry):null,u.entry},retain(u){let l=Xh.parse(u),m=l.command;return!m||n!==null&&r(l)!==n?Promise.reject(Xt()):(n??(n=r(l)),o(()=>s((f,g)=>{if(f&&!xs(r(f),r(l)))throw Xt();if(f&&l.processBindingIds){for(let[d,h]of Object.entries(l.processBindingIds))if(f.processBindingIds&&Object.hasOwn(f.processBindingIds,d)&&f.processBindingIds[d]!==h)throw Xt();f={...f,processBindingIds:{...f.processBindingIds,...l.processBindingIds}}}if(!f){if(g!==t&&m.operation!=="close")throw Xt();return l}if(!f.command)return{...f,command:m,...m.operation==="close"?{closed:!0}:{}};if(m.operation==="close"&&f.command.operation!=="close"){if(f.command.requestId===m.requestId||f.closeCommand&&!xs(f.closeCommand,m))throw Xt();return{...f,closeCommand:m,closed:!0}}if(!xs(f.command,m))throw Xt();return f})))},observePurchase(u,l,m,f){return o(()=>s((g,d)=>{if(!g&&d!==t||g&&r(g)!==r({...u,schemaVersion:1}))throw Xt();if(g?.purchase&&g.purchase.generation>l.generation)return c(g,f);if(g?.purchase&&g.purchase.generation===l.generation&&g.purchase.operationId!==l.operationId)throw Xt();return m?!g?.purchase||g.purchase.operationId!==l.operationId?c(g,f):c(g.command?{...g,purchase:void 0}:null,f):c({schemaVersion:1,...u,...g,purchase:l},f)}))},settle(u){return o(()=>s(l=>c(l,u)))}}}function ty(e){let t,n,r=()=>new b("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,n=e.locks??globalThis.navigator?.locks,!t||!n||!globalThis.crypto?.subtle)throw r();let s=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??pr).href,e.runToken])),c=new Uint8Array(await crypto.subtle.digest("SHA-256",s));return"indiana.funnel.commands.v1."+Array.from(c,u=>u.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function a(s){try{let c=await i;return await n.request(c,{mode:"exclusive"},()=>s(c))}catch(c){throw c instanceof b?c:r()}}function o(s){let c=t.getItem(s);if(c===null)return{revision:0,entry:null};if(c.length>1048576)throw r();let u=JSON.parse(c);if(!u||typeof u!="object"||!("revision"in u)||!("entry"in u)||!Number.isSafeInteger(u.revision)||Number(u.revision)<0)throw r();return{revision:Number(u.revision),entry:u.entry}}return{read:()=>a(o),write:(s,c)=>a(u=>{if(o(u).revision!==s)return null;if(!Number.isSafeInteger(s+1))throw r();return t.setItem(u,JSON.stringify({revision:s+1,entry:c})),s+1})}}function ny(e,t){let n=t&&{...t},r=null,i=0,a=new AbortController;function o(){i++,a.abort(new b("IDENTITY_CHANGED","Run identity changed")),a=new AbortController}let s=!1,c,u=0,l=new Set;return{get scope(){return n},bindScope(m){if(n&&(n.projectId!==m.projectId||n.environment!==m.environment))throw new b("SCOPE_MISMATCH","Run scope changed");n??(n={...m})},get view(){return r},get generation(){return i},get signal(){return a.signal},get disposed(){return s},get customerToken(){return c},get readSequence(){return u},nextRead(){return++u},assertCurrent(m,f="Run identity changed during the request"){if(m!==i||s)throw new b("IDENTITY_CHANGED",f)},assertRun(m){if(r&&(m.id!==r.id||m.source.type!==r.source.type||m.source.id!==r.source.id||m.source.versionId!==r.source.versionId||m.locale!==r.locale||!Ni(m.parameters,r.parameters)))throw new b("INVALID_RESPONSE","Run version changed");if(e&&m.source.id!==e)throw new b("INVALID_RESPONSE","Run belongs to another Funnel")},publish(m,f,g,d,h){if(!(m.operation==="review"&&r&&r!==g&&f.run.revision<=r.revision)&&!(r&&f.run.revision===r.revision&&d!==void 0&&d<u)&&(m.operation==="review"&&!f.run.stopped&&["running","waiting"].includes(f.run.status)&&r&&f.run.nodeId===r.nodeId&&f.run.visit===r.visit&&f.run.revision===r.revision&&(f.run.screen=r.screen,(r.paywall?.quote?.operationId===f.review?.activeOperationId||!r.paywall?.quote&&f.review?.activeOperationId===null)&&(f.run.paywall=r.paywall)),!(r?.paywall&&f.run.paywall&&r.paywall.receiptId===f.run.paywall.receiptId&&(f.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||f.run.revision>=r.revision)r=f.run;else if(!h)return;if(r)for(let R of l)try{R(structuredClone(r))}catch{}}},identify(m){if(s)throw new b("IDENTITY_CHANGED","Controller was reset");if(!kt.test(m))throw new b("INVALID_TOKEN","Customer credential required");o(),c=m},subscribe(m){return l.add(m),()=>l.delete(m)},reset(){s||(s=!0,o(),c=void 0,r=null,l.clear())}}}function fr(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)||e.recovery==="recover_operation";function ry({journal:e,state:t,call:n,processIdentity:r}){let i=null,a=null,o=!1,s={command:null,close:null},c=new Set,u,l=null,m=e?e.load().then(y=>{if(t.disposed)throw new b("IDENTITY_CHANGED","Controller was reset during command restoration");if(l=y,!y)return;if(r){if([y.command,y.closeCommand].some(x=>x&&!Object.hasOwn(y.processBindingIds??{},x.requestId)))throw new b("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(y.processBindingIds??{})}if(t.scope&&(y.scope.projectId!==t.scope.projectId||y.scope.environment!==t.scope.environment))throw new b("SCOPE_MISMATCH","Pending command belongs to another scope");if(u=y.purchase,o=y.closed===!0,!y.command)return;let A=y.command;i=A.operation==="close"?null:A,a=A.operation==="close"?A:y.closeCommand?.operation==="close"?y.closeCommand:null,a&&(o=!0);for(let x of[i,a])x&&c.add(x.requestId)}):Promise.resolve();m.catch(()=>{});async function f(y){e&&await m;let A=t.generation;if(e){if(!t.view||!t.scope)throw new b("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:fr(y),...r?{processBindingIds:{[y.requestId]:r.binding(y.requestId)}}:{}})}if(A!==t.generation||i!==y&&a!==y)throw new b("IDENTITY_CHANGED","Run changed before command dispatch");let x=c.has(y.requestId);c.add(y.requestId);try{return await n(y)}catch(v){throw A===t.generation&&(i===y||a===y)&&!x&&!dv(v)&&(e&&await e.settle(y.requestId),A===t.generation&&R(y)),v}}function g(y){let A=wt.parse(y);if(A.operation==="start"||A.operation==="get"||A.operation==="review")throw new b("INVALID_REQUEST","Mutation required");if(o&&A.operation!=="close"){if(i?.requestId===A.requestId)return h(A.requestId);throw new b("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(A.operation==="close"){if(i?.requestId===A.requestId)throw new b("INVALID_REQUEST","Close requires its own request identity");if(o=!0,a&&JSON.stringify(fr(a))!==JSON.stringify(fr(A)))throw new b("COMMAND_PENDING","Retry the original Close");return a??(a=A),s.close?s.close:d(a,"close")}if(i){if(JSON.stringify(fr(i))!==JSON.stringify(fr(A)))throw new b("COMMAND_PENDING","Retry the original command before sending another");if(s.command)return s.command}else i=A;return d(i,"command")}function d(y,A){let x=f(y);s[A]=x;let v=()=>{s[A]===x&&(s[A]=null)};return x.then(v,v),x}function h(y){return n({operation:"get",settlementRequestId:y})}function R(y){return!y||i!==y&&a!==y?!1:(i===y&&(i=null),a===y&&(a=null),c.delete(y.requestId),!i&&!a&&(l=null),!0)}return{ready:m,get pending(){return i},get closing(){return a},get closeRequested(){return o},get inFlight(){return s.command},get closeFlight(){return s.close},get purchase(){return u},assertBinding(y){if(l&&(y.run.id!==l.runId||y.run.source.id!==l.funnelId||y.run.source.versionId!==l.versionId))throw new b("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(y,A,x,v){let P=y.operation==="get"?y.settlementRequestId:"requestId"in y&&y.operation!=="start"?y.requestId:void 0,j=P&&A.settlement?.state==="settled"&&A.run.pendingRequest?.requestId!==P&&(y.operation==="get"||!o||y.operation==="close"||!["running","waiting"].includes(A.run.status))?P:void 0,_=i?.requestId===j?i:a?.requestId===j?a:void 0;e?.bind({scope:A.scope,runId:A.run.id,funnelId:A.run.source.id,versionId:A.run.source.versionId});let X=A.run.paywall,le=X??A.purchase,he=le?.operation,Re=A.settlement&&(!X||X.purchaseRequestId===A.settlement.requestId)&&(!u||u.operationId===A.settlement.operationId)?A.settlement:void 0,Se=he?.operationId??le?.quote?.operationId??Re?.operationId,gt=le?.receiptId??Re?.receiptId,Qe=X?.selectionGeneration??u?.generation??0;if(e&&Se&>&&y.operation!=="review"&&(!t.view||A.run.revision>=t.view.revision)&&(v===void 0||v>=t.readSequence)&&(!u||Qe>=u.generation)){let je={receiptId:gt,operationId:Se,generation:Qe},et=he?.status==="complete"||le?.canReselect===!0;await e.observePurchase({scope:A.scope,runId:A.run.id,funnelId:A.run.source.id,versionId:A.run.source.versionId},je,et,j),t.assertCurrent(x),(!u||je.generation>=u.generation)&&(v===void 0||v>=t.readSequence)&&(et?u?.operationId===je.operationId&&(u=void 0):u=je)}else e&&j&&await e.settle(j);return t.assertCurrent(x),j?R(_):!1},stop(){o=!0},submit:g,settle:h,reset(){o=!0,i=null,a=null,u=void 0,l=null,s.close=null,c.clear(),s.command=null}}}function gr(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new b("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!Di.test(e.serverKey)))throw new b("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new b("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let t=mr({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),n=ny(e.funnelId,e.scope??e.configuration?.scope),r=e.session?.subscribeIdentity(u),i=null,a=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?ty(e):void 0),o=a&&ey(a),s=ry({journal:o,state:n,call:l,processIdentity:e.process});async function c(A){if(e.process)return e.process.request(A);let x=n.generation;n.assertCurrent(x);let v=performance.now()+(e.timeoutMs??35e3),P=n.customerToken??("customerToken"in A?A.customerToken:void 0);if(e.session){let X=n.signal,le,he=()=>{},Re=new Promise((Se,gt)=>{he=()=>gt(X.reason),X.addEventListener("abort",he,{once:!0}),le=setTimeout(()=>gt(new b("TIMEOUT","Longplay request timed out")),Math.max(1,v-performance.now()))});try{P=await Promise.race([Promise.resolve().then(()=>(n.assertCurrent(x),e.session.access())),Re])}finally{clearTimeout(le),X.removeEventListener("abort",he)}}n.assertCurrent(x);let j={...A,...P?{customerToken:P}:{}},_=A.operation==="page_experiments"?Po.parse(j):wt.parse(j);return t.requestWithCredential("funnels",_,e.runToken,{headers:e.serverKey&&!P?{[Kg]:e.serverKey}:void 0,timeoutMs:Math.max(1,v-performance.now())})}function u(){r?.(),n.reset(),s.reset(),i=null,t.dispose()}async function l(A,x){let v=n.generation,P=()=>n.assertCurrent(v);o&&await s.ready,P();let j=n.view,_=hs(e,await c(A));if(A.operation==="review"&&!_.review)throw new b("INVALID_RESPONSE","Historical projection is missing");if(P(),_.runToken&&_.runToken!==e.runToken)throw new b("INVALID_RESPONSE","Run credential changed");let X=A.operation==="get"?A.settlementRequestId:"requestId"in A&&A.operation!=="start"?A.requestId:void 0;if(X&&_.settlement?.requestId!==X)throw new b("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");s.assertBinding(_),n.assertRun(_.run),n.bindScope(_.scope);let le=await s.observe(A,_,v,x);return!_.run.stopped&&["running","waiting"].includes(_.run.status)&&A.operation==="get"&&A.settlementRequestId||(P(),["running","waiting"].includes(_.run.status)||s.stop(),n.publish(A,_,j,x,le)),_}let m=s.submit,f=null,g=new WeakMap;function d(A){let x=g.get(A);if(x)return x;let v=R(A);return g.set(A,v),v}let h=!1;async function R(A){let x=await A;if(x.run.instruction?.type!=="evaluate_segment")return x;if(f)return f;h=!0;let v=n.generation,P=(async()=>{for(let j=0;j<32&&x.run.instruction?.type==="evaluate_segment";j++){if(s.pending||s.closeRequested)return x;let _=x.run;if(x.run.instruction?.type==="evaluate_segment"){let{advance:le}=await ll(e.configuration,_,{predict:!1});if(v!==n.generation)throw new b("IDENTITY_CHANGED","Run identity changed during segment calculation");if(s.pending||s.closeRequested)return x;if(n.view&&(n.view.revision!==_.revision||n.view.visit!==_.visit||n.view.nodeId!==_.nodeId))return l({operation:"get"});let he=!0;ll(e.configuration,_).then(({prediction:Re})=>{he&&v===n.generation&&!s.closeRequested&&n.view?.id===_.id&&!n.view.stopped&&n.view.nodeId===_.nodeId&&n.view.visit===_.visit&&n.view.revision===_.revision&&(i=Re)}).catch(()=>{});try{x=await m({operation:"commit_segment",requestId:$g(_.id,_.visit,`segment:${_.revision}`),nodeId:_.nodeId,visit:_.visit,revision:_.revision,...le})}finally{he=!1,i=null}}}return x})();f=P;try{return await P}finally{f===P&&(f=null)}}let y={get configuration(){return h?e.configuration:void 0},get configurationReady(){return!0},get view(){return n.view?structuredClone(n.view):null},get pendingCommand(){let A=s.closing??s.pending;return A?structuredClone(fr(A)):null},get pendingCommands(){return[s.pending,s.closing].filter(A=>A!==null).map(A=>structuredClone(fr(A)))},get pendingPurchase(){return s.purchase?structuredClone(s.purchase):null},get hasDurableJournal(){return o!==void 0},get prediction(){let A=n.view;return i&&A&&!A.stopped&&["running","waiting"].includes(A.status)&&A.id===i.runId&&A.nodeId===i.from.nodeId&&A.visit===i.from.visit&&A.revision===i.from.revision&&!s.closeRequested?structuredClone(i):null},settle:s.settle,get webViewUrl(){return"bundled"},resolvePaywall(A){return bs(e,A)},async pageExperiments(A,x=[]){let v=n.generation;n.assertCurrent(v);let P=n.view?.id;if(!P)throw new b("INVALID_REQUEST","Read the Run before its page experiments");let j=Zg.parse(await c(Po.parse({operation:"page_experiments",release:A,usedReceiptIds:x})));if(n.assertCurrent(v),j.runId!==P||j.scope.projectId!==n.scope?.projectId||j.scope.environment!==n.scope?.environment)throw new b("SCOPE_MISMATCH","Page experiment Run changed");return j},review(A){return l({operation:"review",...A?{receiptId:A}:{}},n.nextRead())},async get(A,x){o&&await s.ready,x??(x=s.purchase&&{receiptId:s.purchase.receiptId,operationId:s.purchase.operationId});let v=n.nextRead();return d(l({operation:"get",...A?{data:A}:{},...x?{purchase:x}:{}},v))},resume(A=n.view?.pendingRequest?.requestId){return A?s.closeRequested?y.settle(A):s.pending?.requestId===A?d(m(s.pending)):d(m({operation:"resume",requestId:A})):Promise.reject(new b("INVALID_REQUEST","No interrupted command is available"))},submit(A){return d(m(A))},retry(){return s.closeFlight?s.closeFlight:s.closing?m(s.closing):s.closeRequested&&s.pending?y.settle(s.pending.requestId):s.inFlight?d(s.inFlight):s.pending?d(m(s.pending)):Promise.reject(new b("INVALID_REQUEST","No command is pending"))},identify(A){n.identify(A),i=null,t.reset()},subscribe:n.subscribe,reset:u};return y}function iy(e){if(!kt.test(e.customerToken))throw new b("INVALID_TOKEN","A customer credential is required");if(!e.scope)throw new b("INVALID_REQUEST","An explicit App and environment scope is required");let t=ys({...e,scope:e.scope,apiKey:e.customerToken});return{async start(n){let r=await t.start(n),i=gr({...e,runToken:r.runToken});i.identify(e.customerToken);let a=r.run.instruction?.type==="evaluate_segment"?await i.get():r;return{...r,...a,controller:i}}}}function oy(e,t){let n=r=>"document"in r?r.offering.id:r.content.offeringVersionId;return e.id===t.id&&n(e)===n(t)&&e.content?.artifact.sha256===t.content?.artifact.sha256}function ay(e,t,n){if(e.operationId!==t.operationId||t.currency!==void 0&&e.currency!==t.currency)throw new b("INVALID_RESPONSE",n)}function sy(e,t,n){let r=Object.fromEntries((e.lines[0]?.prepaid??[]).map(i=>[i.internal_feature_id,i.quantity]));if(t.featureQuantities&&(Object.keys(r).length!==Object.keys(t.featureQuantities).length||Object.entries(t.featureQuantities).some(([i,a])=>r[i]!==a)))throw new b("INVALID_RESPONSE","The purchase quote changed its selected quantities");if(e.lines.length!==1||e.lines[0].productVersionId!==t.productVersionId||t.currency!==void 0&&e.currency!==t.currency||t.provider!==void 0&&e.provider!==t.provider&&!(t.provider==="stripe"&&e.provider==="merchant"&&e.execution?.provider==="merchant"))throw new b("INVALID_RESPONSE",n)}function cy(e,t,n=!1){return!e||e.operationId!==t?.operationId?t:e.status==="complete"&&t.status!=="complete"||e.status!=="pending"&&(t.status==="pending"||n&&t.status!=="complete")?e:t}function uy(e){let{quote:t,operation:n,requestId:r}=e,a={type:"recover",operationId:n?.operationId??t?.operationId??null,requestId:r};if(e.destroyed||e.pending)return a;if(!n)return t?{type:"cancel",operationId:t.operationId}:a;let o=n.merchantExecution;if(o?.type==="purchase"){if(["succeeded","not_required"].includes(o.paymentStatus))return!["applied","not_applicable"].includes(o.fulfillmentStatus)||n.problem?.phase==="fulfillment"||o.problem?.phase==="fulfillment"?{type:"fulfillment",operationId:n.operationId}:{type:o.recordingStatus==="accepted"&&n.status==="complete"?"complete":"recording",operationId:n.operationId};if(n.status==="pending"&&n.checkoutUrl&&o.checkoutUrl===n.checkoutUrl&&o.checkoutExpiresAt&&Date.parse(o.checkoutExpiresAt)>Date.now()&&["not_started","pending"].includes(o.paymentStatus))return{type:"checkout",operationId:n.operationId,checkoutUrl:n.checkoutUrl}}let s=[n.problem,o?.problem],c=s.every(u=>!u||u.phase==="execution"&&u.reason!=="RESULT_UNKNOWN");return!s.some(Boolean)&&n.status==="complete"&&n.executor!=="merchant"?{type:"complete",operationId:n.operationId}:c&&e.canReselect!==!1&&["cancelled","failed"].includes(n.status)&&!n.checkoutUrl&&!n.execution&&!n.nativePurchase&&(n.executor!=="merchant"?!n.confirmedAt&&(n.status==="cancelled"||!n.quoteFinalized):!o&&!n.quoteFinalized||o?.type==="purchase"&&["failed","expired"].includes(o.paymentStatus)&&o.fulfillmentStatus==="not_applicable"&&o.recordingStatus==="accepted")?{type:"native",operationId:n.operationId}:n.status==="pending"&&c&&!n.quoteFinalized&&!o&&!n.checkoutUrl&&!n.execution&&!n.nativePurchase?{type:"cancel",operationId:n.operationId}:a}async function ly(e,t){if(!kt.test(t.customerToken))throw new b("INVALID_TOKEN","A verified Customer credential is required");if(e.session&&e.session.peek()!==t.customerToken)throw new b("SCOPE_MISMATCH","Paywall credential does not match the shared session");let n=O.resolvePaywall.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale,...t.requirement?{requirement:t.requirement}:{}}),r=mr(e);e.session||r.identify(t.customerToken);let i=null,a=!1,o=null,s=null,c=null,u=null,l=null,m=null,f=null,g=0;function d(){if(a)throw new b("IDENTITY_CHANGED","Paywall is closed")}async function h(){d();let x=O.resolvePaywall,v=await ge(r.request,x,{...n,selector:i?{type:"version",versionId:i.id}:n.selector}),P=await bs(e,v.paywall);if(d(),t.paywallVersionId?P.id!==t.paywallVersionId:P.paywallId!==t.paywallId)throw new b("INVALID_RESPONSE","The requested Paywall changed");if(i&&(!oy(P,i)||P.paywallId!==i.paywallId))throw new b("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return i=P,structuredClone(i)}async function R(x){if(d(),u&&x!=="read")throw new b("COMMAND_PENDING","Wait for the original quote");if(!o)throw new b("INVALID_REQUEST","A quoted purchase is required");let v=o;if(x!=="read"){if(f){if(m===x)return f;throw new b("COMMAND_PENDING","Wait for the original purchase command")}if(m&&m!==x)throw new b("COMMAND_PENDING","Read the original purchase before changing an uncertain command");m=x,g++}let P=m,j=g,_=x==="read"&&f===null,X=x==="read"?O.readSubscriptionOperation:O.attach,le=(async()=>{let he=await ge(r.request,X,{operationId:v.operationId,...x==="read"?{}:{intent:x}});return ay(he.operation,{operationId:v.operationId,currency:n.commerce.currency},"The purchase operation changed"),d(),o?.operationId!==v.operationId?structuredClone(he.operation):(s=cy(s,he.operation),(x!=="read"||_&&f===null)&&g===j&&m===P&&(m=null),structuredClone(s))})();if(x!=="read"){f=le;let he=()=>{f===le&&(f=null)};le.then(he,he)}return le}let y={get view(){return i?structuredClone(i):null},get quote(){return o?structuredClone(o):null},get operation(){return s?structuredClone(s):null},get webViewUrl(){return"bundled"},get recovery(){return uy({quote:o,operation:s,requestId:l,pending:u!==null||m!==null,destroyed:a})},get pendingCancellation(){return!a&&m==="cancel"},refresh:h,async preview(x){if(d(),!i)throw new b("INVALID_REQUEST","Load the Paywall first");let v=i.document.buttons[x.actionId];if(v?.type!=="checkout")throw new b("INVALID_REQUEST","Choose an authored purchase action");let P=Zm(v.product,x.selection,i.capabilities);if(!P)throw new b("PRODUCT_UNAVAILABLE","Choose an available Product");let j=Bf(i.document.screen,P,x.selection,i.capabilities),_=O.previewAttach.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,requestId:x.requestId,plans:[{productVersionId:P,...Object.keys(j).length?{featureQuantities:j}:{}}],provider:n.commerce.provider,currency:n.commerce.currency,...x.offerId?{offerId:x.offerId}:{},...x.nativeOffer?{nativeOffer:x.nativeOffer}:{}}),X=JSON.stringify(_);if(c&&c!==X&&(u||m||!s||s.status==="pending"))throw new b("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(c===X){if(u)return u;if(o)return structuredClone(o)}c!==X&&(o=null,s=null),c=X,l=_.requestId;let le=(async()=>{let he=O.previewAttach,Re=await ge(r.request,he,_);return d(),sy(Re.quote,{productVersionId:P,featureQuantities:j,currency:n.commerce.currency,provider:n.commerce.provider},"The purchase quote changed its selected Product or presentment"),o=Re.quote,s=null,structuredClone(o)})();u=le;try{return await le}finally{u===le&&(u=null)}},confirm:()=>R("confirm"),cancel:()=>R("cancel"),read:()=>R("read"),destroy(){a||(a=!0,A?.(),r.dispose(),i=null,o=null,s=null,c=null,l=null)}},A=e.session?.subscribeIdentity(y.destroy);try{return await h(),y}catch(x){throw y.destroy(),x}}function dy(e,t){let n,r=0,i=-1,a,o=!1,s=()=>{if(o)throw new b("CLOSED","Native host was destroyed");if(!e.nativeModule)throw new b("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return e.nativeModule},c=()=>new b("IDENTITY_CHANGED","Customer identity changed during the native operation"),u=t.subscribeIdentity(()=>{r++,i=-1;let g=r;n&&e.nativeModule&&n.then(d=>e.nativeModule.reset(d,g)).catch(()=>{})}),l=e.nativeEvents?.(g=>{!n||!e.nativeModule||typeof g?.requestId!="string"||(async()=>{let d=await n;if(g.instanceId!==d)return;if(g.kind==="credential"){let y=r,A=null;try{if(!o&&g.revision===y){let x=await t.access();!o&&r===y&&(A=x)}}finally{await e.nativeModule.provideCredential(d,g.requestId,A)}return}let h=!1,R=r;try{if(o||g.revision!==R||!e.onNativeAction)throw c();await e.onNativeAction(g.action),h=!o&&r===R}finally{await e.nativeModule.acknowledge(d,g.requestId,h)}})().catch(()=>{})});async function m(g,d={}){let h=s();if(t.snapshot()&&!e.nativeEvents)throw new b("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let R=r,y=await t.access();if(o||r!==R)throw c();if(!n){let v=h.create(JSON.stringify({baseUrl:e.baseUrl??"https://api.longplayai.com",scope:e.scope,timeout:(e.timeoutMs??15e3)/1e3,credentialEvents:!!e.nativeEvents}));n=v,v.catch(()=>{n===v&&(n=void 0)})}let A=await n;if(o||r!==R)throw c();if(i!==R){if(!a||a.epoch!==R){let P=(async()=>{if(await h.identify(A,JSON.stringify({revision:R,credentials:y})),o||r!==R)throw await h.reset(A,R),c();i=R})();a={epoch:R,task:P}}let v=a;try{await v.task}finally{a===v&&(a=void 0)}}let x=await h.invoke(A,g,JSON.stringify(d));if(o||r!==R)throw c();try{return JSON.parse(x)}catch{throw new b("INVALID_RESPONSE","Native host returned invalid JSON")}}async function f(g,d){let h=await m(g,d);if(!h||typeof h!="object"||Array.isArray(h)||h.status!=="complete"&&h.status!=="dismissed")throw new b("INVALID_RESPONSE","Native presentation returned an invalid result");return h}return{showFunnel(g){return f("showFunnel",{runToken:g})},showPaywall(g){return f("showPaywall",g)},showContent(g){return f("showContent",g)},purchaseSubscription(g,d){return m("purchaseSubscription",{operationId:g,accepted:d})},switchSubscription(g,d){return m("switchSubscription",{operationId:g,accepted:d})},restorePurchases(){return m("restorePurchases")},manageSubscriptions(g){return m("manageSubscriptions",g?{productId:g}:{})},async dismiss(){r++,i=-1,n&&await s().reset(await n,r)},async destroy(){o||(o=!0,r++,u(),l?.(),n&&e.nativeModule&&await e.nativeModule.destroy(await n))}}}var pv=O.trackUsage.request.shape.command,mv=O.trackUsage.response;function fv(e){let t=Te.parse(e.scope),n=Jh({...e,scope:t}),r={...e,scope:t,session:n.session},i=dy(e,n.session),a=0,o=!1;n.subscribeIdentity(()=>{a++});let s=()=>{if(o)throw new b("CLOSED","SDK client was destroyed");let c=n.session.peek();if(!c)throw new b("UNAUTHENTICATED","Identify the Customer first");return c};return{...n,native:i,async destroy(){o||(o=!0,a++,n.destroy(),await i.destroy())},funnel(){return iy({...r,customerToken:s()})},resumeFunnel(c){return s(),gr({...r,runToken:c})},paywall(c){return ly(r,{...c,customerToken:s()})},async trackUsage(c){if(s(),!e.usageReporter)throw new b("INVALID_REQUEST","Configure your authenticated backend usageReporter");let u=pv.parse(c),l=a,m;try{m=await e.usageReporter(u)}catch(g){throw l!==a?new b("IDENTITY_CHANGED","Customer identity changed during usage reporting"):g}if(l!==a)throw new b("IDENTITY_CHANGED","Customer identity changed during usage reporting");let f=mv.parse(m);if(f.scope.projectId!==t.projectId||f.scope.environment!==t.environment)throw new b("INVALID_RESPONSE","Usage response scope differs");return f}}}import{z as Av}from"zod";import{z as jo}from"zod";var gv=jo.record(jo.string().regex(/^[a-f0-9]{64}$/),jo.strictObject({at:jo.number(),text:jo.string()})),Hr=2*1048576,hv=100;function yv(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function py(e,t){let n=t===void 0?yv():t,r=new Map,i=0,a=!1,o=!1,s,c;async function u(m){if(!n)return null;let f;try{let g=await Promise.race([Promise.resolve().then(()=>n.getItem(m)),new Promise(d=>{f=setTimeout(()=>d(null),hv)})]);return typeof g=="string"&&g.length<=Hr&&new TextEncoder().encode(g).byteLength<=Hr?g:null}catch{return null}finally{clearTimeout(f)}}function l(){if(c)return c;let m=(async()=>{try{let f=await u(`${e}:artifacts`);if(f)return gv.parse(JSON.parse(f))}catch{}return{}})();return c=m,m.finally(()=>{c===m&&(c=void 0)}),m}return{async readManifest(){return u(e)},writeManifest(m){!n||m.length>Hr||new TextEncoder().encode(m).byteLength>Hr||(s=m,!o&&(o=!0,Promise.resolve().then(async()=>{try{for(;s!==void 0;){let f=s;try{await n.setItem(e,f)}catch{}s===f&&(s=void 0)}}finally{o=!1}})))},async readArtifact(m){let f=(await l())[m],g=Date.now();return f&&g>=f.at&&g-f.at<=nn.retentionMs?f.text:void 0},writeArtifact(m,f){if(!n||f.length>Hr)return;let g=r.get(m);if(g?.text===f||!g&&r.size>=128)return;let d=new TextEncoder().encode(f).byteLength;i-(g?.byteLength??0)+d>Hr||(r.set(m,{text:f,byteLength:d}),i+=d-(g?.byteLength??0),!a&&(a=!0,Promise.resolve().then(async()=>{try{for(;r.size;){let h=new Map(r);try{let R={...await l()},y=Date.now();for(let[P,j]of h)R[P]={at:y,text:j.text};let A={},x=2,v=0;for(let[P,j]of Object.entries(R).sort(([,_],[,X])=>X.at-_.at)){if(j.at>y||y-j.at>nn.retentionMs)continue;let _=new TextEncoder().encode(JSON.stringify({[P]:j})).byteLength;x+_>Hr||v>=128||(A[P]=j,x+=_,v++)}await n.setItem(`${e}:artifacts`,JSON.stringify(A))}catch{}finally{for(let[R,y]of h)r.get(R)===y&&(r.delete(R),i-=y.byteLength)}}}finally{a=!1}})))}}}var Pe=(e,t)=>new b(e,t),hr=()=>performance.now(),my=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function bv(e){let t=yu.parse(e.scope),n=new bn(e.origin??pr);if(n.username||n.password||n.search||n.hash||n.pathname!=="/"||n.protocol!=="https:"&&!(n.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(n.hostname)))throw Pe("INVALID_URL","Configuration requires a trusted HTTPS origin");let r=new Set([n.origin,...(e.assetOrigins??[]).map(Y=>{let J=new bn(Y);if(J.protocol!=="https:"||J.username||J.password||J.search||J.hash||J.pathname!=="/")throw Pe("INVALID_URL","Invalid configuration asset origin");return J.origin})]),i=e.fetch??globalThis.fetch.bind(globalThis),a=`/api/v1/configuration/${t.environmentId}`,o=`indiana:configuration:1:${n.origin}:${Ot(t)}`,s=py(o,e.storage),c,u=0,l=0,m=!1,f=!1,g=0,d=0,h,R,y,A,x=0,v=new Set,P=new Set,j=new Map,_=new Map,X=0,le=!1;function he(){for(let Y of v)try{Y()}catch{}}function Re(Y){try{e.onError?.(Y)}catch{}}let Se=()=>!f&&!m&&!!c&&hr()<u&&Date.now()<l;function gt(){if(!Se())throw Pe("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Qe(Y,J,de){if(!j.has(Y)){for(;j.size&&(j.size>=128||X+de>nn.maxCacheBytes);){let pe=j.entries().next().value;X-=pe[1].byteLength,j.delete(pe[0])}j.set(Y,{text:J,byteLength:de}),X+=de}}function je(Y,J,de){return Zh(Y,J,{signal:de,error:pe=>Pe("INVALID_RESPONSE",pe==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function et(Y){let J=new bn(Y,n);if(!r.has(J.origin)||J.username||J.password||J.hash||J.search)throw Pe("INVALID_URL","Configuration artifact origin is not trusted");return J.href}async function To(Y,J,de=!1){let pe=await i(et(Y),{method:"GET",credentials:"omit",redirect:"error",cache:de?"default":"no-cache",signal:J,headers:{}});if(pe.status===429){let Ye=pe.headers.get("retry-after")??"";x=/^\d+$/.test(Ye)?Number(Ye)*1e3:Math.max(0,Date.parse(Ye)-Date.now())||15e3}if(!pe.ok&&pe.status!==304)throw Pe(`CONFIGURATION_HTTP_${pe.status}`,"Configuration synchronization failed");return pe}function Qr(Y,J,de){let pe=Date.parse(Y.headers.get("x-indiana-config-validated-at")??""),Ye=Date.parse(Y.headers.get("x-indiana-config-valid-until")??""),rt=Date.parse(Y.headers.get("date")??""),ze=Y.headers.get("age"),rn=ze!==null&&/^\d+(\.\d+)?$/.test(ze)?Number(ze)*1e3:NaN;if(![pe,Ye,rt,rn].every(Number.isFinite)||Ye<=pe||Ye-pe>nn.maxControlAgeMs||pe>rt+1e3)throw Pe("INVALID_RESPONSE","Configuration freshness evidence is invalid");let qt=Math.min(Ye-pe,de.maxControlAgeSeconds*1e3,nn.maxControlAgeMs)-Math.max(rn,rt-pe,0)-(hr()-J);if(qt<=0)throw Pe("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return hr()+qt}function dt(){if(clearTimeout(y),clearTimeout(A),f||!v.size)return;Se()&&(A=setTimeout(()=>{Se()?dt():he()},Math.max(1,u-hr())),my(A));let Y=d?Math.min(15e3,1e3*2**Math.min(d-1,4)):Math.min(15e3,(c?.policy.refreshIntervalSeconds??15)*1e3);y=setTimeout(()=>{Jt().catch(Re)},Math.max(x,Y*(.8+Math.random()*.2))),my(y)}async function Jt(){if(f)throw Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(h)return h;let Y=g,J=new AbortController;R=J;let de=(async()=>{if(!le){le=!0;try{let Do=await s.readManifest();if(Do&&!c){let Ln=bu.parse(JSON.parse(Do));Ot(Ln.scope)===Ot(t)&&(c=Ln)}}catch{}}J.signal.throwIfAborted();let ze=c,rn=hr(),Lt=await To(a,J.signal);Lt.status===304&&(!ze||!Lt.headers.has("x-indiana-config-validated-at")||!Lt.headers.has("x-indiana-config-valid-until")||!Lt.headers.has("age"))&&(Lt=await To(a,J.signal));let qt=Lt.status===304?ze:bu.parse(JSON.parse(await je(Lt,nn.maxManifestBytes,J.signal))),{generation:Jr,...Zr}=qt,Vn=Lt.headers.get("etag");if(Ot(qt.scope)!==Ot(t)||Gf(Zr)!==Jr||Vn!==`"${Jr}"`&&Vn!==`W/"${Jr}"`)throw Pe("INVALID_RESPONSE","Configuration scope or content identity changed");if(ze&&(qt.revision<ze.revision||qt.revision===ze.revision&&qt.generation!==ze.generation))throw Pe("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[Do,Ln]of Object.entries(ze?.funnels??{})){let xr=qt.funnels[Do];if(xr&&(xr.controlRevision<Ln.controlRevision||xr.evaluationRevision<Ln.evaluationRevision||xr.controlRevision===Ln.controlRevision&&xr.state!==Ln.state||xr.evaluationRevision===Ln.evaluationRevision&&xr.evaluationMode!==Ln.evaluationMode))throw Pe("INVALID_RESPONSE","Funnel control revision changed identity")}let br=Qr(Lt,rn,qt.policy);if(J.signal.throwIfAborted(),Y!==g)throw Pe("CONFIGURATION_DISPOSED","Configuration scope changed");return c=qt,u=br,l=Date.now()+Math.max(0,br-hr()),m=!1,d=0,x=0,s.writeManifest(Ot(qt)),he(),structuredClone(qt)})(),pe=setTimeout(()=>J.abort(Pe("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),nn.initializationMs),Ye=new Promise((ze,rn)=>J.signal.addEventListener("abort",()=>rn(J.signal.reason),{once:!0})),rt=Promise.race([de,Ye]).catch(ze=>{throw d++,(ze instanceof Av.ZodError||ze instanceof SyntaxError||ze instanceof b&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(ze.code))&&(u=0,m=!0,he()),ze}).finally(()=>{clearTimeout(pe),h===rt&&(h=void 0),dt()});return h=rt,rt}async function yr(Y){let J=Y.sha256,de=Zr=>As(Zr,Y);et(Y.url);let pe=j.get(J);if(pe){if(pe.byteLength!==Y.byteLength)throw Pe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return j.delete(J),j.set(J,pe),pe.text}let Ye=_.get(J);if(Ye){if(Ye.byteLength!==Y.byteLength)throw Pe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return Ye.promise}let rt=new AbortController;P.add(rt);let ze=g,rn=(async()=>{try{let br=await s.readArtifact(J);if(br&&de(br)){if(rt.signal.throwIfAborted(),f||ze!==g)throw Pe("CONFIGURATION_DISPOSED","Configuration scope changed");return Qe(J,br,Y.byteLength),br}}catch{}rt.signal.throwIfAborted();let Zr=await To(Y.url,rt.signal,!0),Vn=await je(Zr,Y.byteLength,rt.signal);if(!de(Vn))throw Pe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(f||ze!==g)throw Pe("CONFIGURATION_DISPOSED","Configuration scope changed");return Qe(J,Vn,Y.byteLength),s.writeArtifact(J,Vn),Vn})(),Lt=setTimeout(()=>rt.abort(Pe("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),nn.initializationMs),qt=new Promise((Zr,Vn)=>rt.signal.addEventListener("abort",()=>Vn(rt.signal.reason),{once:!0})),Jr=Promise.race([rn,qt]).finally(()=>{clearTimeout(Lt),P.delete(rt),_.delete(J)});return _.set(J,{promise:Jr,byteLength:Y.byteLength}),Jr}async function Ar(){return Se()||await Jt(),gt(),c}async function Fi(Y){let J,de=new Promise((pe,Ye)=>{J=setTimeout(()=>Ye(Pe("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),nn.initializationMs)});try{return await Promise.race([Y(),de])}finally{clearTimeout(J)}}function Mi(Y,J){if(gt(),c?.generation!==Y.generation)throw Pe("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(J&&c.funnels[J]?.state!=="active")throw Pe("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function pl(Y){let J=Y.gb.features;if(!J)throw Pe("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let de=Y.artifacts[J];if(de.formatVersion!==1)throw Pe("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let pe=zc.parse(JSON.parse(await yr(de)));if(Ot(pe.scope)!==Ot({projectId:t.projectId,environment:t.environment})||pe.generation!==de.generation||pe.remoteFeatures.some(Ye=>Object.hasOwn(pe.features,Ye)))throw Pe("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return Mi(Y),{...pe,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,u-hr())).toISOString()}}async function ml(Y,J){let de=await Ar(),pe=de.funnels[Y];J&&(!pe||pe.evaluationMode==="local"&&!pe.versions[J])&&(h&&await h,de=await Jt()),Mi(de,Y);let Ye=de.funnels[Y];if(Ye.evaluationMode!=="local")throw Pe("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let rt=J??Ye.currentVersionId,ze=Ye.versions[rt];if(!ze)throw Pe("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(de.artifacts[ze.artifact].formatVersion!==3)throw Pe("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[rn,Lt]=await Promise.all([yr(de.artifacts[ze.artifact]).then(qt=>Hf(JSON.parse(qt))),Ye.evaluationMode==="local"?pl(de):void 0]);if(Lt&&Ot(Kf(rn,Lt))!==Ot(ze.dependencies))throw Pe("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return Mi(de,Y),{document:rn,growth:Lt,versionId:rt,control:structuredClone(Ye),manifest:structuredClone(de)}}async function fl(Y,J){try{return await ml(Y,J)}catch(de){if(!(de instanceof b)||!(de.code==="CONFIGURATION_CHANGED"||de.code==="CONFIGURATION_HTTP_404"&&Se()))throw de;let pe=c?.generation;if(h&&await h,await Jt(),de.code!=="CONFIGURATION_CHANGED"&&c?.generation===pe)throw de;return ml(Y,J)}}function Ss(){m=!0,he(),Jt().catch(Re)}let No=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Ss()};function fy(Y){if(f)throw Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return v.add(Y),v.size===1&&(typeof window<"u"&&(window.addEventListener("online",Ss),window.addEventListener("focus",No),document.addEventListener("visibilitychange",No)),dt()),()=>{v.delete(Y),v.size||(clearTimeout(y),clearTimeout(A),gl())}}function gl(){typeof window<"u"&&(window.removeEventListener("online",Ss),window.removeEventListener("focus",No),document.removeEventListener("visibilitychange",No))}return{scope:Object.freeze({...t}),refresh:Jt,subscribe:fy,assertFresh:gt,assertFeatures(Y){gt();let J=c.gb.features;if(!J)throw Pe("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(Y!==void 0&&c.artifacts[J].generation!==Y)throw Pe("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return Se()},get snapshot(){return c?structuredClone(c):null},get remainingMs(){return Se()?Math.max(0,u-hr()):0},async features(){return Fi(async()=>pl(await Ar()))},pageExperiments:()=>Fi(async()=>{let Y=await Ar(),J=Y.gb.pageExperiments;if(!J)throw Pe("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let de=Y.artifacts[J];if(de.formatVersion!==1)throw Pe("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let pe=ih.parse(JSON.parse(await yr(de)));if(pe.environmentId!==t.environmentId||pe.generation!==de.generation)throw Pe("INVALID_RESPONSE","Page experiment scope or generation changed");return Mi(Y),pe}),funnel:(Y,J)=>Fi(()=>fl(Y,J)),paywall:(Y,J)=>Fi(async()=>{let de=await Ar(),pe=de.paywalls?.[Y];if(!pe||!J&&pe.state!=="published")throw Pe("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let Ye=J??pe.currentVersionId,rt=pe.versions[Ye],ze=rt&&de.artifacts[rt.artifact];if(!ze||ze.kind!=="paywall"||ze.formatVersion!==1)throw Pe("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let rn=rs.parse(JSON.parse(await yr(ze)));return Mi(de),{document:rn,versionId:Ye,version:rt.version,control:structuredClone(pe),manifest:structuredClone(de)}}),async localFunnel(Y,J){let de=await Fi(()=>fl(Y,J));if(!de.growth)throw Pe("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:pe,remoteFeatures:Ye,...rt}=de.growth;return nh({scope:{projectId:t.projectId,environment:t.environment},funnelId:Y,versionId:de.versionId,evaluationMode:"local",evaluationRevision:de.control.evaluationRevision,document:de.document,payload:rt})},assertFunnel(Y,J,de){gt();let pe=c.funnels[Y];if(!pe||pe.state!=="active")throw Pe("FUNNEL_STOPPED","Funnel is paused or unavailable");if(pe.evaluationMode!=="local")throw Pe("EVALUATION_MODE","This Funnel now executes at Longplay");if(J!==void 0&&pe.controlRevision!==J)throw Pe("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(de!==void 0&&!pe.versions[de])throw Pe("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!f){f=!0,g++,u=0,R?.abort(Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(y),clearTimeout(A),gl(),he(),v.clear();for(let Y of P)Y.abort(Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));j.clear(),X=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&&Ot(n)!==Ot(e.scope))throw new b("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await t.funnel(e.funnelId)).control.evaluationMode!=="local")throw new b("EVALUATION_MODE","This Funnel uses Remote evaluation");let i=Di.test(e.credential);if(i?!e.customerId:e.customerId!==void 0)throw new b("INVALID_REQUEST","Only Server-Key starts name their Customer");let a=ys({...e,scope:n,apiKey:e.credential}),o=s=>{let c=gr({...e,scope:n,runToken:s,...i?{serverKey:e.credential}:{}});return i||c.identify(e.credential),c};return{async start(s){let c=await a.start({...s,funnelId:e.funnelId,...i?{customer:{type:"id",value:e.customerId}}:{}}),u=o(c.runToken),l=await u.get();return{...c,...l,controller:u}},async restore(s){let c=o(s),u=await c.get();if(u.run.source.id!==e.funnelId)throw c.reset(),new b("SCOPE_MISMATCH","Run belongs to another Funnel");return{...u,runToken:s,controller:c}}}}function dl(e,...t){try{Promise.resolve(e?.(...t)).catch(()=>{})}catch{}}function Sv(e){if(!e.scope)throw new b("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(e.session!==void 0)throw new b("INVALID_CONFIGURATION","The merchant process adapter owns the session");let t=null,n,r=0,i=new Set,a=new Map,o=new Map;async function s(f){let g,d=new Promise((h,R)=>{g=setTimeout(()=>R(new b("TIMEOUT","Process bridge request timed out")),e.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(f),d])}finally{clearTimeout(g)}}function c(f){throw f instanceof b&&(f.status===401||f.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear()),f}function u(f,g){if(g!==r)throw new b("IDENTITY_CHANGED","Process was detached during a request");let d=Mu.parse(f);if(d.scope.projectId!==e.scope.projectId||d.scope.environment!==e.scope.environment)throw new b("SCOPE_MISMATCH","Process response belongs to another App/environment");if(t&&(t.run.id!==d.run.id||t.run.source.versionId!==d.run.source.versionId||t.run.source.id!==d.run.source.id||t.run.runExpiresAt!==d.run.runExpiresAt||t.run.identity.startedAs!==d.run.identity.startedAs||t.run.identity.participantId!==d.run.identity.participantId||t.run.identity.binding&&d.run.identity.binding&&t.run.identity.binding.id!==d.run.identity.binding.id))throw new b("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!t||d.run.revision>=t.run.revision){if(t?.run.identity.binding&&!d.run.identity.binding)throw new b("INVALID_RESPONSE","The process lost its Customer binding");t=d;for(let j of i)dl(j,d.run);d.run.instruction?.type==="authentication_required"&&dl(e.onAuthenticationRequired,d.run)}d.settlement?.accepted!==void 0&&o.set(d.settlement.requestId,d.settlement.accepted);let{identity:h,instruction:R,...y}=d.run,{contract:A,settlement:x,...v}=d,P=x&&(({accepted:j,..._})=>_)(x);return{...v,run:{...y,authenticated:h.binding!==null,instruction:R?.type==="authentication_required"?null:R},...P?{settlement:P}:{}}}let l=f=>(a.has(f)||a.set(f,t?.run.identity.binding?.id??null),a.get(f));async function m(f){let g=r,d=t?.run.identity.binding?.id??null,h=y=>{if(d!==(t?.run.identity.binding?.id??null))throw y;return c(y)};if(f.operation==="page_experiments"){if(!e.adapter.pageExperiments)throw new b("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return s(()=>e.adapter.pageExperiments(f.release,f.usedReceiptIds)).catch(h)}let R;if(f.operation==="get"){let{operation:y,customerToken:A,...x}=f;R=await s(()=>e.adapter.get({...x,...x.settlementRequestId?{settlementBindingId:l(x.settlementRequestId)}:{}})).catch(h)}else if(f.operation==="review")R=await s(()=>e.adapter.review(f.receiptId)).catch(h);else{if(f.operation==="start")throw new b("INVALID_REQUEST","Use process.open for entry");{let{customerToken:y,...A}=f;R=await s(()=>e.adapter.command(A,l(A.requestId))).catch(h)}}return u(R,g)}return{get view(){return t?.run??null},get controller(){return n},async open(f){let g=r,d=await s(()=>e.adapter.open(f)).catch(c);if(u(d,g),!n){n=gr({...e,runToken:d.runToken,process:{request:m,binding:l,restore(y){for(let[A,x]of Object.entries(y))a.set(A,x)}}});let h=n,R=h.submit;h.submit=async y=>{try{return await R(y)}catch(A){if(!(A instanceof b)||A.reason!=="IDENTITY_CONTEXT_CHANGED"||y.operation!=="submit"||y.input.type!=="screen"||a.get(y.requestId)!==null)throw A;await h.settle?.(y.requestId),await h.get();let x=h.view;if(o.get(y.requestId)!==!1||!x||x.id!==t?.run.id||x.nodeId!==y.nodeId||x.visit!==y.visit||!t?.run.identity.binding)throw A;return R({...y,requestId:crypto.randomUUID(),revision:x.revision})}}}await n.get();for(let h of n.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(t?.run.identity.binding?.id??null)&&await n.settle?.(h.requestId);return{run:t.run,controller:n}},async syncIdentity(){let f=r;u(await s(()=>e.adapter.syncIdentity()).catch(c),f),await n?.get();for(let g of n?.pendingCommands??[])a.has(g.requestId)&&a.get(g.requestId)!==(t?.run.identity.binding?.id??null)&&await n?.settle?.(g.requestId);return t.run},async detach(){r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear(),await s(()=>e.adapter.detach())},forProcess(f){if(!t?.run.identity.binding)throw new b("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:t.run.id,bindingId:t.run.identity.binding.id,receiptId:f}},subscribe(f){return i.add(f),()=>{i.delete(f)}},destroy(){r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear(),i.clear()}}}export{b as LongplayError,bv as createConfigurationSync,cl as createFeatureClient,Sv as createFunnelProcess,xv as createLocalFunnelClient,fv as createLongplayReactNative};
|
|
17
|
+
*/var ve=N.json().superRefine((e,t)=>{let n=0;function r(i,a){if(++n>1e4||a>20){t.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof i=="string"&&(i.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(i))&&t.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(i))i.forEach(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))(o.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(o)||["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved JSON property"}),r(s,a+1)}r(e,0),new TextEncoder().encode(JSON.stringify(e)).byteLength>65536&&t.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),vt=N.record(N.string().min(1).max(128),ve).superRefine((e,t)=>{(!ve.safeParse(e).success||Object.keys(e).length>128||new TextEncoder().encode(JSON.stringify(e)).byteLength>65536||["__proto__","constructor","prototype"].some(n=>Object.hasOwn(e,n)))&&t.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),bA=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),Yt=vt.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("$")&&!bA.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)}),xA=N.discriminatedUnion("type",[N.strictObject({type:N.literal("condition"),condition:Yt}),N.strictObject({type:N.literal("list"),attributeKey:N.string().min(1).max(128),values:N.array(N.union([N.string(),N.number().finite()])).max(1e5)})]).refine(e=>e.type!=="list"||new TextEncoder().encode(JSON.stringify(e.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function Kn(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 SA=N.record(N.uuid(),xA).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"&&Kn(o.condition).forEach(i),n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),rc=N.tuple([N.number().min(0).max(1),N.number().min(0).max(1)]).refine(([e,t])=>e<=t),Dd=N.strictObject({attribute:N.string().optional(),seed:N.string().min(1),hashVersion:N.literal(2),ranges:N.array(rc).min(1).max(100)}),IA=N.strictObject({id:N.string().min(1).max(128),condition:Yt,gate:N.boolean().optional()}),nc={id:N.string().max(128).optional(),condition:Yt.optional(),parentConditions:N.array(IA).max(50).optional(),filters:N.array(Dd).max(20).optional()},vA=N.union([N.strictObject({...nc}),N.strictObject({...nc,force:ve,coverage:N.number().min(0).max(1).optional(),range:rc.optional(),seed:N.string().min(1).optional(),hashAttribute:N.string().optional(),hashVersion:N.literal(2).optional()}),N.strictObject({...nc,type:N.literal("experiment-ref"),experimentId:N.uuid(),values:N.record(N.string().min(1),ve),meta:N.record(N.string().min(1),N.strictObject({passthrough:N.boolean()})).optional()})]),wA=N.strictObject({defaultValue:ve,rules:N.array(vA).max(100)}),oO=N.record(N.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),wA).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)}),OA=N.strictObject({name:N.string().max(80),reason:N.string().max(500),dateStarted:N.iso.datetime({offset:!0}),dateEnded:N.iso.datetime({offset:!0}).nullable(),coverage:N.number().min(0).max(1),variationWeights:N.array(N.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:Yt,savedGroups:N.array(N.strictObject({match:N.enum(["any","all","none"]),ids:N.array(N.uuid()).min(1)})).max(50),namespace:N.strictObject({id:N.uuid(),ranges:N.array(rc).min(1)}).nullable(),seed:N.string().min(1).max(128)}),PA=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(OA).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 CA=PA.safeExtend({filters:N.array(Dd).optional()}),_A=N.strictObject({experiments:N.record(N.uuid(),CA),savedGroups:SA}),$i=N.strictObject({attributeName:N.string(),attributeValue:N.string(),assignments:N.record(N.string(),N.string())}),aO=N.strictObject({snapshot:_A,attributes:vt,results:vt,stickyBucketAssignmentDocs:N.record(N.string(),$i)}),sO=N.strictObject({variantKey:N.string().nullable(),bucketVersion:N.number().int().min(0),source:N.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:N.number().min(0).max(1).optional(),stickyBucketUsed:N.boolean().optional(),hashUsed:N.boolean().optional()});function er(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 EA=Tt.enum(["active","inactive"]),RA=Tt.preprocess((e,t)=>{let n=0;function r(i,a){if(!(++n>1e4||a>20)){if(Array.isArray(i))i.forEach(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))["__proto__","constructor","prototype"].includes(o)&&t.addIssue({code:"custom",message:"Reserved merchandise attribute"}),r(s,a+1)}}return r(e,0),e},vt),kA=Tt.strictObject({id:Tt.string().trim().min(1).max(255),name:Tt.string().trim().min(1).max(255),status:EA,metadata:RA}),mO=kA.extend({internal_id:Tt.uuid(),project_id:Tt.uuid(),environment_id:Tt.uuid(),created_at:Tt.iso.datetime({offset:!0}),updated_at:Tt.iso.datetime({offset:!0})}),Md=Tt.union([Tt.strictObject({id:Tt.string().trim().min(1).max(255)}),Tt.strictObject({internalId:Tt.uuid()})]),fO=Tt.enum(["customer","merchandise","context"]),gO=Tt.enum(["system","stored","request"]),hO=Tt.enum(["customer","merchandise","mixed"]),Fd=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function ic(e,t={},n=new Set){if(er(e).some(Fd))return!0;for(let r of Kn(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&Fd(i.attributeKey)||i?.type==="condition"&&ic(i.condition,t,n))return!0}return!1}import{z as jA}from"zod";var TA=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,Sn=jA.string().max(16).regex(TA,"\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 wO=te.enum(["draft","active","paused","archived"]),tr=te.discriminatedUnion("type",[te.object({type:te.literal("percent"),percentOff:te.number().min(1).max(100).multipleOf(.01)}).strict(),te.object({type:te.literal("amount"),amountOffCents:te.number().int().min(1).max(1e8),currency:Ie}).strict()]),an=te.discriminatedUnion("type",[te.object({type:te.literal("once")}).strict(),te.object({type:te.literal("repeating"),months:te.number().int().min(1).max(36)}).strict(),te.object({type:te.literal("forever")}).strict()]),qd=[te.object({type:te.literal("all")}).strict(),te.object({type:te.literal("plans"),planIds:te.array(te.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],NA=te.discriminatedUnion("type",[...qd,te.strictObject({type:te.literal("merchandise"),scope:te.discriminatedUnion("type",[te.strictObject({type:te.literal("all")}),te.strictObject({type:te.literal("selected"),merchandiseIds:te.array(te.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),te.strictObject({type:te.literal("condition"),condition:Yt})])})]),oc=te.discriminatedUnion("type",[...qd,te.strictObject({type:te.literal("merchandise"),scope:te.strictObject({type:te.enum(["all","selected","condition"])})})]),DA=te.strictObject({firstPurchaseOnly:te.boolean(),condition:Yt}),OO=te.object({name:te.string().trim().min(1).max(80),description:te.string().max(500),discount:tr,duration:an,appliesTo:NA,eligibility:DA,selfClaimEnabled:te.boolean().default(!1),startsAt:te.iso.datetime().nullable(),endsAt:te.iso.datetime().nullable(),totalLimit:te.number().int().min(1).max(1e6).nullable(),perCustomerLimit:te.number().int().min(1).max(10),grantWindowHours:te.number().int().min(1).max(2160)}).strict().refine(e=>!e.startsAt||!e.endsAt||Date.parse(e.endsAt)>Date.parse(e.startsAt),{message:"\u7ED3\u675F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u5F00\u59CB\u65F6\u95F4",path:["endsAt"]}).refine(e=>!ic(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"]}),PO=te.object({code:te.string().trim().transform(e=>e.toUpperCase()).pipe(te.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/,"\u4F18\u60E0\u7801\u53EA\u80FD\u7528 3\u201332 \u4F4D\u5B57\u6BCD\u3001\u6570\u5B57\u3001- \u548C _\uFF0C\u4EE5\u5B57\u6BCD\u6216\u6570\u5B57\u5F00\u5934")),maxRedemptions:te.number().int().min(1).max(1e6).nullable(),expiresAt:te.iso.datetime().nullable(),firstPurchaseOnly:te.boolean(),minimumAmountCents:te.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:Ie.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var Gi=te.object({id:te.uuid(),couponId:te.uuid(),status:te.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:te.iso.datetime(),expiresAt:te.iso.datetime(),coupon:te.object({name:te.string(),discount:tr,duration:an,appliesTo:oc}).strict()}).strict(),Ud=te.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var $d=S.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),ac=S.string().regex(/^(0|[1-9]\d{0,14})$/),oi=S.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),FA=S.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),Ki=FA,Hn=xe.refine(e=>/[1-9]/.test(e)),zt=S.iso.datetime({offset:!0}),ca=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"))},MA=S.array(S.object({upTo:Hn.nullable(),unitAmountMinor:$d,flatAmountMinor:S.number().int().min(0).max(1e8).optional()}).strict()).min(1).max(12).refine(e=>{try{return e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let r=e[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&ca(t.upTo)>ca(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),qA=S.discriminatedUnion("kind",[S.object({kind:S.literal("flat"),units:Hn,unitAmountMinor:$d}).strict(),S.object({kind:S.enum(["graduated","volume"]),units:Hn,tiers:MA}).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"),UA=S.strictObject({interval:S.enum(["month","year"]),count:S.number().int().min(1).max(12),anchor:S.enum(["membership","calendar"])}),Hi=S.object({currency:Ie,pricing:qA,billingCycle:UA.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var Bd={requestId:S.uuid(),productVersionId:S.uuid(),internal_feature_id:S.uuid(),currency:Ie},Gd=S.strictObject({interval:S.enum(["hour","day","week","month"]),intervalCount:S.number().int().min(1).max(12),limit:S.number().int().min(1).max(1e6)}),Kd=S.discriminatedUnion("kind",[S.object({...Bd,kind:S.literal("auto_topup"),threshold:Jo,quantity:Hn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Gd.optional()}).strict(),S.object({...Bd,kind:S.literal("postpaid"),maxAmountMinorPerPeriod:Ki,maxOutstandingMinor:Ki}).strict()]),Vd={productVersionId:S.uuid(),internal_feature_id:S.uuid(),currency:Ie},Hd=S.discriminatedUnion("kind",[S.object({...Vd,kind:S.literal("auto_topup"),threshold:Jo,quantity:Hn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Gd.optional(),purchaseAmountMinor:Ki,purchaseUnits:Hn}).strict(),S.object({...Vd,kind:S.literal("postpaid"),maxAmountMinorPerPeriod:Ki,maxOutstandingMinor:Ki,cashPrice:Hi}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),ua=S.object({id:S.uuid(),terms:Hd,status:S.enum(["prepared","active","revoked","blocked"]),createdAt:zt,acceptedAt:zt.nullable(),effectiveAt:zt.nullable(),revokedAt:zt.nullable()}).strict().refine(e=>(e.status==="prepared"?e.acceptedAt===null:!0)&&(e.status==="active"?e.acceptedAt!==null&&e.effectiveAt!==null:!0)&&(e.status==="revoked"?e.revokedAt!==null:e.revokedAt===null),"Authorization consent and revocation must be explicit"),Qd=S.object({authorizationId:S.uuid(),terms:Hd,setupUrl:S.url().nullable()}).strict(),Jd=S.object({authorizationId:S.uuid(),accepted:S.literal(!0)}).strict(),Zd=S.object({authorizationId:S.uuid(),requestId:S.uuid()}).strict(),Wd=S.object({internal_feature_id:S.uuid(),entityId:S.uuid().nullable(),interval:S.enum(["day","week","month","year"]),anchor:S.enum(["billing_cycle","utc"]).optional(),basis:S.enum(["usage","credits"]),filter:It.optional(),limit:xe.nullable(),thresholds:S.array(S.number().positive().max(1)).max(8),includedThresholds:S.array(S.number().positive().max(1)).max(8).optional(),absoluteThresholds:S.array(Hn).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&&ca(t)>ca(i)}),"Notification thresholds must increase"),BA=Wd.safeExtend({requestId:S.uuid()}),Ld={control:S.literal("overage"),requestId:S.uuid(),internal_feature_id:S.uuid(),entityId:S.uuid().nullable()},VA=S.discriminatedUnion("action",[S.strictObject({...Ld,action:S.literal("set"),allowed:S.boolean().nullable(),overageLimit:xe.nullable(),skipOverageBilling:S.boolean()}),S.strictObject({...Ld,action:S.literal("remove")})]),Yd=S.union([BA,VA]),LA=S.strictObject({internal_feature_id:S.uuid(),entityId:S.uuid().nullable(),allowed:S.boolean().nullable(),overageLimit:xe.nullable(),skipOverageBilling:S.boolean(),interval:S.enum(["day","week","month","year"]),startsAt:zt,endsAt:zt,used:S.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:S.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:S.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),zA=S.object({internal_feature_id:S.uuid(),entityId:S.uuid().nullable(),interval:S.enum(["day","week","month","year"]),anchor:S.enum(["billing_cycle","utc"]).optional(),basis:S.enum(["usage","credits"]),filter:It.optional(),startsAt:zt,endsAt:zt,used:Wt,reserved:Wt,limit:xe.nullable(),thresholds:S.array(S.number().positive().max(1)).max(8),notifiedThresholds:S.array(S.number().positive().max(1)).max(1024),includedThresholds:S.array(S.number().positive().max(1)).max(8).optional(),includedAllowance:S.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:S.array(S.number().positive().max(1)).max(1024).optional(),absoluteThresholds:S.array(Hn).max(8).optional(),notifiedAbsoluteThresholds:S.array(Hn).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||xe.safeParse(e.used).success&&xe.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),$A=S.object({authorizationId:S.uuid(),status:S.enum(["idle","pending","blocked"]),taskId:S.uuid().nullable(),invoiceId:S.uuid().nullable(),hostedInvoiceUrl:S.url().nullable(),purchaseCount:S.number().int().nonnegative(),purchaseWindowEndsAt:zt.nullable(),attemptCount:S.number().int().nonnegative(),failedAttemptCount:S.number().int().nonnegative(),suspendedAt:zt.nullable(),nextAttemptAt:zt.nullable(),failureReason:S.string().min(1).max(240).nullable()}).strict(),Xd=S.object({internal_feature_id:S.uuid().optional(),entityId:S.uuid().optional()}).strict(),sc=S.object({authorizations:S.array(ua).max(100),limits:S.array(Wd).max(100),overages:S.array(LA).max(100).optional(),windows:S.array(zA).max(200),autoTopups:S.array($A).max(100),limited:S.boolean()}).strict(),GA=S.object({id:S.uuid(),internal_feature_id:S.uuid(),productVersionId:S.uuid(),authorizationId:S.uuid(),entityId:S.uuid().nullable(),units:xe,amountMinor:oi,cashPrice:Hi}).strict(),Qi=S.object({id:S.uuid(),sourceKind:S.enum(["product","usage","manual"]),providerInvoiceId:S.string().min(1).max(240).nullable(),status:S.enum(["accruing","open","pending","paid","failed","void"]),currency:Ie,startsAt:zt.nullable(),endsAt:zt.nullable(),amountMinor:S.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:S.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:ac,paidAmountMinor:ac,refundedAmountMinor:ac,createdAt:zt,hostedInvoiceUrl:S.url().nullable(),adjustment:S.object({originalInvoiceId:S.uuid(),amountMinor:S.string().regex(/^-?(0|[1-9]\d{0,8})$/).refine(e=>e!=="-0"&&/^-?(0|[1-9]\d{0,8})$/.test(e)&&BigInt(e)>=-200000000n&&BigInt(e)<=200000000n,"Invoice adjustment exceeds the bounded minor amount"),acceptedAt:zt.nullable(),reason:S.string().min(1).max(500).optional()}).strict().nullable(),lines:S.array(GA).max(100),linesLimited:S.boolean()}).strict(),ep=S.object({invoiceId:S.uuid(),accepted:S.literal(!0)}).strict(),tp=S.strictObject({requestId:S.uuid(),originalInvoiceId:S.uuid(),amountMinor:S.string().regex(/^[1-9]\d{0,8}$/).refine(e=>/^[1-9]\d{0,8}$/.test(e)&&BigInt(e)<=200000000n,"Supplemental amount exceeds the bounded minor amount"),reason:S.string().trim().min(1).max(500)}),np=S.object({after:S.uuid().nullable(),limit:S.number().int().min(1).max(100)}).strict(),rp=S.object({rows:S.array(Qi).max(100),nextCursor:S.uuid().nullable()}).strict(),zd=S.strictObject({id:S.string(),coupon:S.string(),start:S.number().nonnegative(),end:S.number().nullable()}),KA=S.strictObject({subscriptionId:S.string(),customerId:S.string(),accountId:S.string(),sourceItems:S.array(S.strictObject({id:S.string(),price_id:S.string(),quantity:S.number().int(),discounts:S.array(zd).optional()})).max(100),items:S.array(S.strictObject({id:S.string(),price:S.string(),quantity:S.number().int(),discounts:S.array(S.strictObject({coupon:S.string().optional(),terms:S.strictObject({id:S.string(),name:S.string().optional(),percent_off:S.number().optional(),amount_off:S.number().optional(),currency:S.string().optional(),duration:S.enum(["once","forever","repeating"]),duration_in_months:S.number().optional()}).optional(),discount:S.string().optional(),receipt:zd.optional()})).max(20)})).max(100)}),ip=S.strictObject({membershipId:S.uuid(),requestId:S.uuid(),grantIds:S.array(S.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),op=S.strictObject({membershipId:S.uuid(),operationId:S.uuid(),status:S.enum(["pending","effective"]),execution:KA.nullable(),grants:S.array(S.strictObject({id:S.uuid(),couponId:S.uuid(),name:S.string(),discount:tr,duration:an,startedAt:zt.nullable()})).max(20)});import{z as Ji}from"zod";var ap=Ji.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),sp=Ji.number().int().min(1).max(1e3),la=Ji.object({cap:xe.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:Ji.number().positive().max(1e4).nullable(),cycles:Ji.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");import{z as nr}from"zod";var cp=nr.strictObject({itemKey:nr.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:nr.uuid(),includedAmount:nr.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:nr.number().int().min(0).max(1e4),terms:Wo,pricing:Vi.optional(),unitAmountMinor:nr.number().int().min(0).max(1e8),productId:nr.string().min(1).max(255).nullable(),priceId:nr.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{ed(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 ne}from"zod";var Pr=xe.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Zi=ne.string().min(1).max(120),da=ne.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"))},Wi=e=>{try{return e()}catch{return!1}},Yi=ne.discriminatedUnion("operation",[ne.object({operation:ne.literal("quote"),overageBehavior:da.optional(),internal_feature_id:ne.uuid(),entityId:ne.uuid().optional(),quantity:Pr,properties:It}).strict(),ne.object({operation:ne.literal("consume"),overageBehavior:da.optional(),occurredAt:ne.iso.datetime({offset:!0}).optional(),internal_feature_id:ne.uuid(),entityId:ne.uuid().optional(),quantity:xe,properties:It,idempotencyKey:Zi}).strict(),ne.object({operation:ne.literal("reserve"),occurredAt:ne.iso.datetime({offset:!0}).optional(),internal_feature_id:ne.uuid(),entityId:ne.uuid().optional(),quantity:Pr,properties:It,idempotencyKey:Zi,expiresInSeconds:ne.number().int().min(1).max(86400)}).strict(),ne.object({operation:ne.literal("confirm"),operationId:ne.uuid(),quantity:Pr,properties:It.optional(),idempotencyKey:Zi}).strict(),ne.object({operation:ne.literal("refund"),operationId:ne.uuid(),quantity:Pr,idempotencyKey:Zi}).strict(),ne.object({operation:ne.literal("release"),operationId:ne.uuid(),idempotencyKey:Zi}).strict()]),cc=ne.object({internal_credit_feature_id:ne.uuid().nullable(),internal_metered_feature_id:ne.uuid(),dimension:ne.string().min(1).max(64),counterKey:ne.string().min(1).max(240),cycleStart:ne.iso.datetime({offset:!0}),unitCost:xe,units:Pr,amount:Wt,tier:ne.number().int().min(1).max(12).nullable()}).strict(),Cr=ne.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function up(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 lp=ne.discriminatedUnion("funding",[ne.strictObject({funding:ne.literal("balance"),sourceId:ne.uuid(),rolloverId:ne.uuid().nullable(),units:Cr.refine(e=>/[1-9]/.test(e)),amount:Wt}),ne.strictObject({funding:ne.literal("unbilled"),units:Cr.refine(e=>/[1-9]/.test(e))}),ne.object({funding:ne.literal("prepaid"),sourceId:ne.uuid(),units:Pr,amount:Wt,pricing:ne.array(cc).min(1).max(12)}).strict().refine(e=>Wi(()=>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"),ne.object({funding:ne.literal("postpaid"),invoiceLineId:ne.uuid().nullable(),units:Pr,authorizationId:ne.uuid()}).strict()]),pa=ne.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),dp=ne.object({allowed:ne.boolean(),internal_feature_id:ne.uuid(),quantity:xe,requestedQuantity:xe.optional(),overageBehavior:da.optional(),reason:pa.nullable(),allocations:ne.array(lp).max(500)}).strict().refine(e=>Wi(()=>e.allowed?e.reason===null&&up(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>Wi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&sn(e.requestedQuantity,6)>=sn(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Xi=ne.object({id:ne.uuid(),internal_feature_id:ne.uuid(),kind:ne.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:ne.uuid().nullable(),quantity:xe,requestedQuantity:xe.optional(),overageBehavior:da.optional(),accepted:ne.boolean(),reason:ne.enum([...pa.options,"expired"]).nullable(),createdAt:ne.iso.datetime({offset:!0}),reservationStatus:ne.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:ne.iso.datetime({offset:!0}).nullable(),allocations:ne.array(lp).max(500)}).strict().refine(e=>Wi(()=>e.accepted?e.reason===null&&up(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>Wi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&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 Ne}from"zod";var _r=Ne.iso.datetime({offset:!0}),pp=xe.refine(e=>/[1-9]/.test(e)),mp=Ne.strictObject({interval:ap.exclude(["lifetime"]),count:sp}),HA=Ne.strictObject({action:Ne.literal("create"),requestId:Ne.uuid(),internal_feature_id:Ne.uuid(),entityId:Ne.uuid().nullable(),amount:pp.nullable(),expiresAt:_r.nullable(),reset:mp.nullable(),rollover:la.nullable(),nextResetAt:_r.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"),fp=Ne.discriminatedUnion("action",[HA,Ne.strictObject({action:Ne.literal("update"),requestId:Ne.uuid(),grantId:Ne.uuid(),revision:Ne.number().int().nonnegative(),amount:pp.nullable(),expiresAt:_r.nullable(),rollover:la.nullable(),nextResetAt:_r.nullable()}),Ne.strictObject({action:Ne.enum(["add","subtract","set_remaining"]),requestId:Ne.uuid(),grantId:Ne.uuid(),revision:Ne.number().int().nonnegative(),amount:xe}),Ne.strictObject({action:Ne.literal("revoke"),requestId:Ne.uuid(),grantId:Ne.uuid(),revision:Ne.number().int().nonnegative()})]),uc=Ne.strictObject({id:Ne.uuid(),internal_feature_id:Ne.uuid(),entityId:Ne.uuid().nullable(),amount:xe.nullable(),reset:mp.nullable(),rollover:la.nullable(),nextResetAt:_r.nullable(),startsAt:_r,expiresAt:_r.nullable(),revision:Ne.number().int().nonnegative(),revoked:Ne.boolean(),available:Wt,held:Wt,spent:Wt}),gp=Ne.strictObject({customerId:Ne.uuid(),after:Ne.uuid().nullable(),limit:Ne.number().int().min(1).max(100)}),hp=Ne.strictObject({rows:Ne.array(uc).max(100),nextCursor:Ne.uuid().nullable()});import{z as ie}from"zod";var Nn=ie.iso.datetime({offset:!0}),yp=ie.strictObject({invoiceId:ie.uuid(),after:ie.string().min(1).max(180).nullable(),limit:ie.number().int().min(1).max(100)}),QA=ie.strictObject({kind:ie.literal("product"),key:ie.string(),productVersionId:ie.uuid(),productName:ie.string(),itemKey:ie.string(),entityId:ie.uuid().nullable(),quantity:ie.number().positive(),subtotalMinor:ie.string().regex(/^-?\d+$/),discountMinor:ie.string().regex(/^\d+$/),taxMinor:ie.string().regex(/^-?\d+$/).nullable(),totalMinor:ie.string().regex(/^-?\d+$/),startsAt:Nn.nullable(),endsAt:Nn.nullable(),providerLineId:ie.string().nullable(),providerItemId:ie.string()}),Ap=ie.strictObject({invoice:Qi,items:ie.array(ie.discriminatedUnion("kind",[QA,ie.strictObject({kind:ie.literal("invoice_credit"),key:ie.string(),internal_feature_id:ie.uuid(),internal_credit_feature_id:ie.uuid(),name:ie.string(),units:xe,reserved:xe,amountMinor:oi,grossAmountMinor:oi,creditsAppliedMinor:oi,properties:It,cashPrice:Hi,providerItemId:ie.string().nullable(),creditProviderItemId:ie.string().nullable()}),ie.strictObject({kind:ie.literal("usage"),key:ie.string(),internal_feature_id:ie.uuid(),name:ie.string(),units:xe,reserved:xe,amountMinor:oi,cashPrice:Hi})])).max(100),nextCursor:ie.string().min(1).max(180).nullable()}),JA=ie.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),lc=ie.strictObject({from:Nn,to:Nn,entityId:ie.uuid().optional(),snapshotAt:Nn.nullable(),after:ie.strictObject({at:Nn,id:ie.uuid(),position:ie.number().int().nonnegative()}).nullable(),limit:ie.number().int().min(1).max(100)}).refine(e=>Date.parse(e.from)<Date.parse(e.to)&&Date.parse(e.to)-Date.parse(e.from)<=366*864e5,"Statement range must be positive and at most 366 days").refine(e=>e.after===null||e.snapshotAt!==null,"A cursor requires the original snapshot time"),bp=ie.strictObject({customerId:ie.uuid(),entityId:ie.uuid().nullable(),from:Nn,to:Nn,snapshotAt:Nn,totals:ie.array(ie.strictObject({internal_credit_feature_id:ie.uuid(),name:ie.string(),consumed:Wt,refunded:Wt,net:JA})).max(1e3),rows:ie.array(ie.strictObject({operationId:ie.uuid(),position:ie.number().int().nonnegative(),kind:ie.enum(["consume","confirm","refund"]),originalId:ie.uuid().nullable(),occurredAt:Nn,internal_feature_id:ie.uuid(),entitlementName:ie.string(),sourceId:ie.uuid(),internal_credit_feature_id:ie.uuid(),creditName:ie.string(),units:Cr,amount:Wt,pricing:ie.array(cc).max(12),properties:It})).max(100),nextCursor:lc.shape.after});import{z as D}from"zod";import{z as In}from"zod";var ZA=In.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),WA=In.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),ma=In.strictObject({internal_feature_id:In.uuid(),entityId:In.uuid().nullable()}),xp=ma.extend({quantity:xe,expectedRevision:In.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:In.string().min(1).max(120),properties:It.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),eo=ma.extend({operationId:In.uuid().nullable(),usage:xe,capacity:ZA.nullable(),remaining:WA.nullable(),withinLimit:In.boolean(),revision:In.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:In.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let n=r=>{let i=r.startsWith("-"),[a,o=""]=(i?r.slice(1):r).split(".");if(a===void 0||a==="")throw new Error("Invalid decimal value");return(i?-1n:1n)*(BigInt(a)*10n**12n+BigInt(o.padEnd(12,"0")))};(e.capacity===null!=(e.remaining===null)||(e.capacity===null?!e.withinLimit:e.remaining===null||n(e.remaining)!==n(e.capacity)-n(e.usage)||e.withinLimit!==n(e.remaining)>=0n)||e.revision===0!=(e.operationId===null)||e.operationId===null!=(e.updatedAt===null))&&t.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var $t=D.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),vn=D.iso.datetime({offset:!0}),YA=D.enum(["access","metered","credit"]),to={internal_feature_id:D.uuid(),key:wr,name:D.string().min(1).max(120),kind:YA},Sp=D.object({customerId:D.uuid(),snapshotAt:vn,memberships:D.array(D.object({id:D.uuid(),productId:D.string().min(1).max(255),productVersionId:D.uuid(),billingProductVersionId:D.uuid(),version:D.number().int().positive(),key:D.string().min(1).max(64),name:D.string().min(1).max(120),groupId:D.string().max(255).nullable(),membershipType:D.enum(["main","addon"]),status:D.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:D.boolean(),accessEnabled:D.boolean(),renewalChange:D.object({productVersionId:D.uuid(),name:D.string().min(1).max(120),version:D.number().int().positive(),effectiveAt:vn,benefitsAppliedAt:vn.nullable(),timing:D.enum(["immediate","renewal"]),changeKind:D.enum(["plan","seats","quantity"]),feature:D.strictObject({internal_feature_id:D.uuid(),name:D.string().min(1).max(80),fromQuantity:D.number().int().min(0).max(1e4),toQuantity:D.number().int().min(0).max(1e4)}).optional(),seat:D.object({key:D.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:D.number().int().min(0).max(1e4),toQuantity:D.number().int().min(0).max(1e4)}).strict().nullable(),status:D.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(e=>e.changeKind==="seats"==(e.seat!==null)&&e.changeKind==="quantity"==(e.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:D.object({phase:D.enum(["paid","trial"]),startsAt:vn,endsAt:vn.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:D.boolean(),balances:D.array(D.object({...to,usageType:D.enum(["consumable","non_consumable"]).nullable(),accessible:D.boolean(),unlimited:D.boolean(),available:$t,held:$t,debt:$t,nextExpiresAt:vn.nullable(),usage:eo.nullable()}).strict().refine(e=>e.kind==="metered"==(e.usageType!==null)&&(e.accessible||e.available==="0"&&e.held==="0")&&(e.usageType==="non_consumable"?e.usage!==null&&e.usage.internal_feature_id===e.internal_feature_id&&e.unlimited===(e.usage.capacity===null)&&e.available===(e.usage.remaining===null||e.usage.remaining.startsWith("-")?"0":e.usage.remaining)&&e.held==="0"&&e.debt==="0":e.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:D.boolean()}).strict(),Ip=D.enum(["source","usage","transaction","invoice","debt","settlement"]),fa=D.object({at:vn,id:D.uuid(),type:Ip}).strict(),vp=D.object({type:Ip.nullable(),resourceKey:wr.optional(),kind:D.enum(["purchase","refund"]).optional(),topup:D.boolean().optional(),from:D.iso.date().nullable(),to:D.iso.date().nullable(),after:fa.nullable(),limit:D.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),ai={id:D.uuid(),occurredAt:vn},XA=D.discriminatedUnion("type",[D.strictObject({...ai,type:D.literal("invoice"),status:D.string().min(1).max(80),paid:$t,refunded:$t,currency:Ie,externalId:D.string().nullable()}),D.object({...ai,...to,type:D.literal("source"),reason:D.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:$t,unlimited:D.boolean(),status:D.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:vn,expiresAt:vn.nullable(),orderId:D.uuid().nullable(),parentSourceId:D.uuid().nullable()}).strict(),D.object({...ai,type:D.literal("usage"),internal_feature_id:D.uuid(),name:D.string().min(1).max(120),kind:D.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:D.uuid().nullable(),quantity:xe,accepted:D.boolean(),reason:D.enum([...pa.options,"expired"]).nullable(),properties:It,reservationStatus:D.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:vn.nullable(),charges:D.array(D.discriminatedUnion("funding",[D.strictObject({funding:D.literal("balance"),sourceId:D.uuid(),rolloverId:D.uuid().nullable(),units:Cr,amount:$t}),D.strictObject({funding:D.literal("unbilled"),units:Cr}),D.object({...to,funding:D.literal("prepaid"),amount:$t}).strict(),D.object({funding:D.literal("postpaid"),invoiceId:D.uuid(),invoiceLineId:D.uuid(),authorizationId:D.uuid(),units:xe,currency:Ie}).strict()])).max(500)}).strict().refine(e=>(e.kind==="set_usage"||e.kind==="consume"&&e.quantity==="0"?e.accepted&&e.reason===null&&e.charges.length===0&&e.reservationStatus===null:e.accepted?e.reason===null&&e.charges.length>0:e.reason!==null&&e.charges.length===0)&&e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),D.object({...ai,type:D.literal("transaction"),purpose:D.enum(["product","invoice"]),productVersionId:D.uuid().nullable(),productName:D.string().min(1).max(120).nullable(),productVersion:D.number().int().positive().nullable(),invoiceId:D.uuid().nullable(),orderId:D.uuid(),originalId:D.uuid().nullable(),kind:D.enum(["purchase","refund"]),amountMinor:D.number().int().nonnegative().max(2e8).nullable(),currency:Ie.nullable()}).strict().refine(e=>e.currency===null==(e.amountMinor===null)&&(e.purpose==="product"?e.productVersionId!==null&&e.productName!==null&&e.productVersion!==null&&e.invoiceId===null:e.productVersionId===null&&e.productName===null&&e.productVersion===null&&e.invoiceId!==null)&&e.kind==="refund"==(e.originalId!==null)&&(e.kind!=="refund"||e.amountMinor===null||e.amountMinor>0),"Payment fact provenance is incomplete"),D.object({...ai,...to,type:D.literal("debt"),sourceId:D.uuid(),transactionId:D.uuid(),amount:$t}).strict(),D.object({...ai,...to,type:D.literal("settlement"),sourceId:D.uuid(),debtId:D.uuid(),kind:D.enum(["payment","usage_refund","payment_return"]),amount:$t}).strict()]),wp=D.object({customerId:D.uuid(),rows:D.array(XA).max(50),nextCursor:fa.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");import{z as fe}from"zod";var Pp=fe.object({customerId:fe.uuid()}).strict(),Cp=fe.discriminatedUnion("action",[fe.object({customerId:fe.uuid(),requestId:fe.uuid(),action:fe.literal("assign"),poolId:fe.uuid(),memberCustomerId:fe.uuid()}).strict(),fe.strictObject({customerId:fe.uuid(),requestId:fe.uuid(),action:fe.literal("assign_entity"),poolId:fe.uuid(),entityId:fe.uuid()}),fe.object({customerId:fe.uuid(),requestId:fe.uuid(),action:fe.literal("release"),poolId:fe.uuid(),slotId:fe.uuid()}).strict()]),no=fe.number().int().nonnegative(),dc=fe.iso.datetime({offset:!0}),pc=fe.strictObject({internalId:fe.uuid(),id:fe.string(),name:fe.string().nullable(),version:fe.number().int().positive()}),Op=fe.enum(["active","past_due"]),mc=fe.strictObject({customerId:fe.uuid(),licenses:fe.array(fe.strictObject({id:fe.uuid(),linkId:fe.uuid(),parent:fe.strictObject({customerProductId:fe.uuid(),status:Op,product:pc}),product:pc,planLicense:fe.strictObject({id:fe.uuid(),prepaidOnly:fe.boolean(),isCustom:fe.boolean()}).nullable(),granted:no,included:no,paidQuantity:no,usage:no,remaining:no,createdAt:dc}).refine(e=>e.granted===e.included+e.paidQuantity&&e.granted===e.usage+e.remaining,"Granted seats are included plus paid, and usage plus remaining")).max(2e3),assignments:fe.array(fe.strictObject({id:fe.uuid(),linkId:fe.uuid(),status:Op,product:pc,entity:fe.strictObject({internalId:fe.uuid(),id:fe.string().nullable(),name:fe.string().nullable()}).nullable(),beneficiary:fe.strictObject({internalId:fe.uuid(),id:fe.string().nullable(),name:fe.string().nullable()}).nullable(),startedAt:dc.nullable(),endedAt:dc.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:fe.boolean()});import{z as me}from"zod";var ro=me.enum(["email","sms","voice","push"]),dP=me.enum(["resend","twilio","fcm","apns"]);var pP=me.string().regex(/^\+[1-9]\d{1,14}$/),eb=me.enum(["email_recipient","sms_segment","voice_second","push_device"]);var tb=me.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),nb=me.strictObject({subject:tb,html:me.string().min(1).max(131072).optional(),text:me.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),rb=me.strictObject({body:me.string().min(1).max(1600).refine(e=>e.trim().length>0)}),ib=me.strictObject({text:me.string().trim().min(1).max(4e3),language:me.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:me.number().int().min(1).max(900)}),ob=me.record(me.string().min(1).max(64),me.string().max(256)).refine(e=>Object.keys(e).length<=20&&Object.keys(e).every(t=>!/^(?:indiana_|google\.|gcm\.)/i.test(t)&&t!=="aps"),"Push data contains reserved fields or too many entries"),ab=me.strictObject({title:me.string().trim().min(1).max(200),body:me.string().trim().min(1).max(2e3),url:me.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:ob.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),_p=me.discriminatedUnion("channel",[me.strictObject({channel:me.literal("email"),content:nb}),me.strictObject({channel:me.literal("sms"),content:rb}),me.strictObject({channel:me.literal("voice"),content:ib}),me.strictObject({channel:me.literal("push"),content:ab})]),Ep=me.strictObject({requestId:me.uuid(),customerId:me.uuid(),connectionId:me.uuid().optional(),message:_p,expiresAt:me.iso.datetime({offset:!0})}),sb=me.array(me.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),cb=me.discriminatedUnion("kind",[me.strictObject({kind:me.literal("all")}),me.strictObject({kind:me.literal("customers"),customerIds:sb})]),mP=me.strictObject({name:me.string().trim().min(1).max(120),connectionId:me.uuid().optional(),message:_p,audience:cb,frequencyLimit:me.number().int().min(1).max(100)}),Rp=me.strictObject({requestId:me.uuid(),channel:ro,state:me.enum(["allowed","denied"]),expectedRevision:me.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),kp=me.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),jp=me.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),fP=me.strictObject({meter:eb,estimatedUnits:me.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:me.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});import{z as Ce}from"zod";import{z as re}from"zod";import{z as si}from"zod";var io=si.strictObject({internalFeatureId:si.uuid(),name:si.string().min(1).max(120),includedAmount:si.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:si.enum(["hour","day","week","month","year","lifetime"]),resetCount:si.number().int().min(1).max(100),terms:Wo});import{z as st}from"zod";import{z as ub}from"zod";import{z as ci}from"zod";var Tp=ci.enum(["stripe","apple","google","merchant"]),Np=ci.enum(["membership","credit_pack","lifetime"]),xP=ci.enum(["active","grace","suspended","inactive","revoked"]),SP=ci.strictObject({currency:ci.string().regex(/^[A-Z]{3}$/),micros:ci.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var ui=ub.object({provider:Tp,currency:Ie}).strict();var rr=st.strictObject({internal_feature_id:st.uuid(),quantity:xe.refine(e=>/[1-9]/.test(e)),properties:It,entityId:st.uuid().optional()}),Dp=st.strictObject({requirement:rr,commerce:ui.optional(),paywallId:st.uuid().optional()}),lb=st.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),fc=st.strictObject({productId:st.string().min(1),productVersionId:st.string().min(1),name:st.string().min(1).max(120),action:st.enum(["purchase","upgrade","addon","topup"]),membershipId:st.string().min(1).nullable(),currency:Ie,amountMinor:st.string().regex(/^(0|[1-9]\d{0,8})$/),interval:st.enum(["free","week","month","year","one_time"]),intervalCount:st.number().int().min(1).max(156)}),Er=st.strictObject({internal_feature_id:st.string().min(1),name:st.string().min(1).max(120),kind:st.enum(["access","metered","credit"]),quantity:xe,allowed:st.boolean(),reason:lb.nullable(),preview:st.strictObject({scenario:st.enum(["feature_flag","usage_limit"]),candidates:st.array(fc).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"})}),kP=st.strictObject({paywallId:st.uuid(),requirement:rr});var ha=re.object({plan:re.string().min(1).max(200).optional(),coupon:re.uuid().optional(),promotionCode:re.uuid().optional(),picker:re.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),ga=re.object({text:re.string().optional(),label:re.string().optional(),alt:re.string().optional(),html:re.string().max(32768).optional(),price:re.object({current:re.string(),original:re.string().nullable(),period:re.string()}).optional(),code:re.string().optional(),countdownAt:re.iso.datetime().optional(),planId:re.string().min(1).max(200).optional(),planVersionId:re.string().min(1).max(200).optional(),currency:Ie.optional(),couponId:re.uuid().optional(),offerId:re.uuid().optional(),unavailable:re.boolean().optional(),unavailableReason:re.string().optional(),missing:re.array(re.string()).optional()}).strict(),li=re.object({paywall:Er.optional(),nodes:re.record(re.string(),re.object({base:ga,picker:re.string().optional(),byPlan:re.record(re.string(),ga).optional()}).strict()),plans:re.record(re.string(),re.object({id:re.string().min(1).max(200),versionId:re.string().min(1).max(200),available:re.boolean(),name:re.string(),price:re.string(),period:re.string(),currency:Ie.optional(),amountMinor:re.number().int().nonnegative().optional(),interval:re.enum(["free","week","month","year","one_time"]).optional(),intervalCount:re.number().int().positive().optional(),prepaid:re.array(io).max(100).optional()}).strict()),pickers:re.record(re.string(),re.object({options:re.array(re.string().min(1).max(200)).max(20),selected:re.string().min(1).max(200).nullable()}).strict()),quantities:re.record(re.string(),re.strictObject({minimum:re.number().int().nonnegative(),maximum:re.number().int().nonnegative(),step:re.number().int().positive(),value:re.number().int().nonnegative(),label:re.string(),available:re.boolean()})).optional(),diagnostics:re.array(re.object({nodeId:re.string(),message:re.string()}).strict())}).strict();function Fp(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}import{z as I}from"zod";function db(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function Mp(e){let t={};function n(r){var i;if(db(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 qp=Qn.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ya=Qn.strictObject({tiers:Qn.array(Qn.strictObject({id:qp,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:qp,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 Aa(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}import{z as ce}from"zod";var pb=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],Up=ce.enum(pb),Bp=ce.object({source:Up,layout:ce.enum(["full","compact"]),resourceKey:wr.optional(),pageSize:ce.number().int().min(1).max(50),showSources:ce.boolean(),allowPurchase:ce.boolean(),outputs:ce.object({billing_adjustment:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((e,t)=>{(e.outputs?.billing_authorization||e.outputs?.billing_adjustment)&&e.source!=="billing_controls"&&t.addIssue({code:"custom",message:"Payment authorization routes belong to the billing controls component."}),e.resourceKey&&!["credit_balance","credit_transactions"].includes(e.source)&&t.addIssue({code:"custom",message:"\u8FD9\u4E2A\u6570\u636E\u6E90\u4E0D\u80FD\u7ED1\u5B9A\u79EF\u5206\u8D44\u6E90\u3002"}),e.showSources&&e.source!=="credit_balance"&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u4F59\u989D\u53EF\u4EE5\u5C55\u5F00\u6765\u6E90\u3002"}),e.allowPurchase&&!["credit_packs","customer_plans","membership"].includes(e.source)&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u5305\u3001\u5957\u9910\u4E0E\u4F1A\u5458\u7EC4\u4EF6\u53EF\u4EE5\u542F\u7528\u4EA4\u6613\u3002"})}),Rt=ce.string().max(2e3),Vp=ce.object({id:ce.string().max(100),label:Rt,detail:ce.array(Rt).max(12),value:Rt.optional(),status:Rt.optional(),facts:ce.array(ce.object({label:Rt,value:Rt}).strict()).max(1e3),purchaseId:ce.uuid().optional(),invoiceUrl:ce.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:ce.array(ce.strictObject({action:ce.literal("invoice_open"),label:Rt})).max(1).optional(),membershipActions:ce.array(ce.object({value:ce.string().max(100),label:Rt}).strict()).max(3).optional()}).strict(),mb=ce.object({key:wr,name:Rt,spendable:Rt,reserved:Rt,available:Rt,expiry:Rt.nullable(),sources:ce.array(Vp).max(50),sourceCount:ce.number().int().nonnegative(),sourcePage:ce.number().int().positive(),hasNextSources:ce.boolean(),hasPreviousSources:ce.boolean()}).strict(),fb=ce.object({source:Up,status:ce.enum(["idle","loading","ready","error"]),stale:ce.boolean(),preview:ce.boolean(),errorCode:ce.string().max(80).optional(),errorMessage:Rt.optional(),resources:ce.array(mb).max(500),rows:ce.array(Vp).max(50),hasNext:ce.boolean(),hasPrevious:ce.boolean(),page:ce.number().int().positive(),filter:ce.string().max(40),updatedAt:ce.iso.datetime().optional(),buyingId:ce.uuid().optional(),membershipBusy:ce.boolean().optional(),billingBusy:ce.boolean().optional(),membershipReview:ce.object({title:Rt,note:Rt,facts:ce.array(ce.object({label:Rt,value:Rt}).strict()).max(100)}).strict().optional(),membershipResult:Rt.optional()}).strict(),Lp=ce.object({nodes:ce.record(ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),fb)}).strict(),zP=ce.object({nodeId:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:ce.enum(["refresh","next","previous","filter","buy_pack","billing_portal","billing_authorization","billing_adjustment","invoice_open","membership_preview","membership_confirm","membership_dismiss","sources_next","sources_previous"]),value:ce.string().max(100).optional()}).strict();import{z as K}from"zod";var xt={state:32,enumValues:64,derived:96,bindings:256,controls:64,timers:4,effects:8,depth:12,expressionNodes:2e3},$p=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]),Nt=K.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/).refine(e=>!$p.has(e),"Reserved UI identifier"),gc=K.union([K.string().max(2e3),K.number().finite(),K.boolean(),K.null()]),gb=K.discriminatedUnion("type",[K.strictObject({type:K.literal("enum"),values:K.array(gc).min(1).max(xt.enumValues),default:gc}),K.strictObject({type:K.literal("number"),min:K.number().finite(),max:K.number().finite(),step:K.number().finite().positive(),default:K.number().finite()}),K.strictObject({type:K.literal("text"),maxLength:K.number().int().min(0).max(2e3),default:K.string().max(2e3).nullable()}),K.strictObject({type:K.literal("boolean"),default:K.boolean()})]);function yc(e,t){if(e.type==="enum")return e.values.some(r=>r===t);if(e.type==="boolean")return typeof t=="boolean";if(e.type==="text")return t===null||typeof t=="string"&&t.length<=e.maxLength;if(typeof t!="number"||!Number.isFinite(t)||t<e.min||t>e.max)return!1;let n=(t-e.min)/e.step;return Number.isFinite(n)&&Math.abs(n-Math.round(n))<=Math.min(1e-7,Math.max(1,Math.abs(n))*Number.EPSILON*8)}var hb=gb.superRefine((e,t)=>{e.type==="enum"&&new Set(e.values).size!==e.values.length&&t.addIssue({code:"custom",path:["values"],message:"UI enum values must be unique"}),e.type==="number"&&e.min>e.max&&t.addIssue({code:"custom",path:["max"],message:"UI number range is reversed"}),yc(e,e.default)||t.addIssue({code:"custom",path:["default"],message:"UI default must match its state definition"})}),yb=["add","sub","mul","div","min","max","round","floor","eq","ne","gt","gte","lt","lte","and","or","not","if","concat","number","parse_number","money","lookup","now","duration"];function Ab(e,t){return e==="now"?t===0:e==="concat"?!0:e==="lookup"?t>=4&&t%2===0:e==="if"?t===3:["sub","div","eq","ne","gt","gte","lt","lte"].includes(e)?t===2:["round","floor","not","number","parse_number","money","duration"].includes(e)?t===1:t>=1}var kr=K.lazy(()=>K.union([gc,K.strictObject({ref:Nt}),K.strictObject({op:K.enum(yb),args:K.array(kr).max(xt.expressionNodes)}).superRefine((e,t)=>{Ab(e.op,e.args.length)||t.addIssue({code:"custom",path:["args"],message:"Invalid UI expression arity"})})]));function wn(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function Rr(e,t,n){if(!e||typeof e!="object")return!0;if(!wn(e))return t.addIssue({code:"custom",path:n,message:"UI objects must be plain data"}),!1;for(let r of Object.keys(e)){if($p.has(r))return t.addIssue({code:"custom",path:[...n,r],message:"Reserved UI object key"}),!1;let i=Object.getOwnPropertyDescriptor(e,r);if(i&&!Object.hasOwn(i,"value"))return t.addIssue({code:"custom",path:[...n,r],message:"UI objects cannot contain accessors"}),!1}return!0}function di(e,t,n,r){let i=[{value:e,depth:1,path:n}];for(;i.length;){let a=i.pop();if(++r.nodes>xt.expressionNodes||a.depth>xt.depth){t.addIssue({code:"custom",path:a.path,message:"UI expression budget exceeded"});return}if(!Rr(a.value,t,a.path))return;if(wn(a.value)&&Array.isArray(a.value.args)){if(a.value.args.length>xt.expressionNodes){t.addIssue({code:"custom",path:[...a.path,"args"],message:"UI expression budget exceeded"});return}for(let o=a.value.args.length-1;o>=0;o--)i.push({value:a.value.args[o],depth:a.depth+1,path:[...a.path,"args",o]})}}}var KP=K.unknown().superRefine((e,t)=>{di(e,t,[],{nodes:0})}).pipe(kr),hc=K.record(Nt,kr).refine(e=>Object.keys(e).length>0&&Object.keys(e).length<=xt.state,"UI assignments need 1\u201332 state keys"),bb=K.strictObject({target:Nt,property:K.enum(["text","visible","disabled","checked","value","class","aria-label","aria-selected","aria-checked","aria-valuetext","tabindex"]),expression:kr,className:Nt.optional()}).superRefine((e,t)=>{e.property==="class"!=(e.className!==void 0)&&t.addIssue({code:"custom",path:["className"],message:"Only class bindings require a safe className"})}),xb=K.discriminatedUnion("type",[K.strictObject({type:K.literal("scroll_latch"),target:Nt,state:Nt}),K.strictObject({type:K.literal("input"),target:Nt,state:Nt,set:hc.optional()}),K.strictObject({type:K.literal("action"),target:Nt,set:hc}),K.strictObject({type:K.literal("carousel"),target:Nt,state:Nt,initialIndex:K.number().int().nonnegative().optional(),maxWidth:K.number().int().min(1).max(1e4).optional(),previousTarget:Nt.optional(),nextTarget:Nt.optional(),inactiveTargets:K.array(Nt).max(20).optional(),inactiveMaxWidth:K.number().int().min(1).max(1e4).optional()})]),Sb=K.strictObject({afterMs:K.number().int().min(0).max(6e4),set:hc}),Ib=K.strictObject({type:K.literal("mosaic_waves"),target:Nt,color:K.string().regex(/^#[0-9a-fA-F]{6}$/),hotColor:K.string().regex(/^#[0-9a-fA-F]{6}$/),enabled:kr.optional(),speed:K.number().min(0).max(4).optional(),pitch:K.number().min(.05).max(4).optional(),fill:K.number().min(.05).max(1).optional(),feather:K.number().min(0).max(1).optional(),warp:K.number().min(0).max(4).optional(),warpScale:K.number().min(0).max(32).optional(),detailScale:K.number().min(0).max(32).optional(),waveScale:K.number().min(0).max(32).optional(),falloff:K.number().min(.1).max(32).optional(),brightness:K.number().min(0).max(32).optional(),ambient:K.number().min(0).max(1).optional(),gamma:K.number().min(.05).max(8).optional(),vignette:K.number().min(0).max(1).optional(),opacity:K.number().min(0).max(1).optional()}),vb=K.strictObject({type:K.literal("number_counter"),target:Nt,value:kr,prefix:K.string().max(20).optional(),format:K.enum(["number","short"]).optional()}),wb=K.strictObject({state:K.record(Nt,hb).refine(e=>Object.keys(e).length<=xt.state,"Too many UI state keys").optional(),derived:K.record(Nt,kr).refine(e=>Object.keys(e).length<=xt.derived,"Too many UI derived keys").optional(),bindings:K.array(bb).max(xt.bindings).optional(),controls:K.array(xb).max(xt.controls).optional(),timers:K.array(Sb).max(xt.timers).optional(),effects:K.array(K.discriminatedUnion("type",[Ib,vb])).max(xt.effects).optional(),clock:K.boolean().optional()});function Ob(e,t){if(!Rr(e,t,[])||!wn(e))return;for(let[r,i]of[["state",xt.state],["derived",xt.derived]]){let a=e[r];if(!Rr(a,t,[r]))return;if(wn(a)&&Object.keys(a).length>i){t.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}}for(let[r,i]of[["bindings",xt.bindings],["controls",xt.controls],["timers",xt.timers],["effects",xt.effects]])if(Array.isArray(e[r])&&e[r].length>i){t.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}if(Array.isArray(e.effects)){for(let[r,i]of e.effects.entries())if(!Rr(i,t,["effects",r]))return}if(wn(e.state))for(let[r,i]of Object.entries(e.state)){if(!Rr(i,t,["state",r]))return;if(wn(i)&&Array.isArray(i.values)&&i.values.length>xt.enumValues){t.addIssue({code:"custom",path:["state",r,"values"],message:"Too many UI enum values"});return}}let n={nodes:0};if(wn(e.derived))for(let[r,i]of Object.entries(e.derived))di(i,t,["derived",r],n);for(let r of["bindings","controls","timers"]){let i=e[r];if(Array.isArray(i)){for(let[a,o]of i.entries())if(!(!Rr(o,t,[r,a])||!wn(o))){if(r==="bindings")di(o.expression,t,[r,a,"expression"],n);else if(Rr(o.set,t,[r,a,"set"])&&wn(o.set)){if(Object.keys(o.set).length>xt.state){t.addIssue({code:"custom",path:[r,a,"set"],message:"Too many UI assignments"});return}for(let[s,c]of Object.entries(o.set))di(c,t,[r,a,"set",s],n)}if(n.nodes>xt.expressionNodes)return}}}if(Array.isArray(e.effects))for(let[r,i]of e.effects.entries())wn(i)&&i.type==="number_counter"?di(i.value,t,["effects",r,"value"],n):wn(i)&&i.enabled!==void 0&&di(i.enabled,t,["effects",r,"enabled"],n)}function zp(e){let t=[],n=[e];for(;n.length;){let r=n.pop();!r||typeof r!="object"||("ref"in r?t.push(r.ref):n.push(...r.args))}return t}var Gp=K.unknown().superRefine(Ob).pipe(wb).superRefine((e,t)=>{let n=e.state??{},r=e.derived??{},i=new Set([...Object.keys(n),...Object.keys(r)]),a=(g,d)=>{for(let h of zp(g))i.has(h)||t.addIssue({code:"custom",path:d,message:`Unknown UI reference: ${h}`})};for(let[g,d]of Object.entries(e.derived??{}))Object.hasOwn(n,g)&&t.addIssue({code:"custom",path:["derived",g],message:"UI state and derived identifiers must be distinct"}),a(d,["derived",g]);let o=new Set,s=new Set,c=g=>{if(o.has(g))return!1;if(s.has(g))return!0;o.add(g);for(let d of zp(r[g]))if(Object.hasOwn(r,d)&&!c(d))return!1;return o.delete(g),s.add(g),!0};for(let g of Object.keys(r))if(!c(g)){t.addIssue({code:"custom",path:["derived",g],message:"Cyclic UI derived references"});break}for(let[g,d]of(e.bindings??[]).entries())a(d.expression,["bindings",g,"expression"]);let u=new Set;for(let[g,d]of(e.effects??[]).entries())u.has(d.target)&&t.addIssue({code:"custom",path:["effects",g,"target"],message:"Effect targets must be unique"}),u.add(d.target),d.type==="number_counter"?(a(d.value,["effects",g,"value"]),typeof d.value=="number"&&Math.abs(d.value)>1e12&&t.addIssue({code:"custom",path:["effects",g,"value"],message:"Counter values must be within the display bound"})):d.enabled!==void 0&&a(d.enabled,["effects",g,"enabled"]);let l=(g,d)=>{for(let[h,R]of Object.entries(g))Object.hasOwn(n,h)||t.addIssue({code:"custom",path:[...d,h],message:"UI assignments can only update declared state"}),a(R,[...d,h])},m=new Set,f=new Set;for(let[g,d]of(e.controls??[]).entries()){if(d.type==="carousel"&&d.inactiveMaxWidth!==void 0&&d.inactiveTargets===void 0&&t.addIssue({code:"custom",path:["controls",g,"inactiveMaxWidth"],message:"Inactive width requires inactive article targets"}),d.type==="carousel")for(let h of d.inactiveTargets??[])(h===d.target||f.has(h))&&t.addIssue({code:"custom",path:["controls",g,"inactiveTargets"],message:"Inactive article targets must have one carousel owner"}),f.add(h);if(d.type==="carousel")for(let h of["previousTarget","nextTarget"]){let R=d[h];R!==void 0&&((R===d.target||m.has(R)||(e.controls??[]).some(y=>y.target===R))&&t.addIssue({code:"custom",path:["controls",g,h],message:"Carousel navigation needs a distinct, exclusive button target"}),m.add(R))}if(d.type!=="action"){let h=Object.hasOwn(n,d.state)?n[d.state]:void 0;(!h||d.type==="input"&&h.type==="enum"&&h.values.some(R=>typeof R!="string"))&&t.addIssue({code:"custom",path:["controls",g,"state"],message:"Control needs a supported declared UI state"}),d.type==="carousel"&&(h?.type!=="number"||!Number.isInteger(h.min)||h.min<0||!Number.isInteger(h.max)||h.step!==1||d.initialIndex!==void 0&&!yc(h,d.initialIndex))&&t.addIssue({code:"custom",path:["controls",g],message:"Carousel needs bounded nonnegative integer index state"}),d.type==="scroll_latch"&&h?.type!=="boolean"&&t.addIssue({code:"custom",path:["controls",g,"state"],message:"Scroll latches require boolean UI state"})}(d.type==="input"||d.type==="action")&&d.set&&l(d.set,["controls",g,"set"])}for(let[g,d]of(e.timers??[]).entries())l(d.set,["timers",g,"set"])});import{z as it}from"zod";var Pb=it.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ba=it.discriminatedUnion("type",[it.object({type:it.literal("fixed"),productVersionId:it.string().min(1).max(200)}).strict(),it.object({type:it.literal("picker"),pickerId:Pb,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")]),Cb=it.strictObject({min:it.number().finite().min(1).max(1800),max:it.number().finite().min(1).max(1800),viewport:it.number().finite().min(1).max(100)}).refine(e=>e.min<=e.max,"Desktop width range is reversed"),Kp={desktopWidth:Cb.optional(),mobile:it.enum(["sheet","fullscreen"]).optional(),backdrop:it.enum(["none","scrim","dim","strong-dim","blur"]).optional()},On=it.discriminatedUnion("type",[it.strictObject({type:it.literal("modal"),size:it.enum(["sm","md","lg"]),...Kp}),it.strictObject({type:it.literal("sheet"),size:it.enum(["sm","md","lg"]),...Kp}),it.strictObject({type:it.literal("fullscreen")}),it.strictObject({type:it.literal("inline")})]);var Eb=4,Cn={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:32768,documentBytes:2e5},ao=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),qe=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Rb=I.enum(["none","xs","sm","md","lg","xl"]),kb=I.enum(["none","sm","md","lg","full"]),Ac=I.string().regex(/^#[0-9a-fA-F]{6}$/),xc=I.string().max(2048).refine(e=>{try{let t=new URL(e);return t.protocol==="https:"&&t.hostname.length>0}catch{return!1}},"\u53EA\u652F\u6301 https \u94FE\u63A5"),bc=I.union([xc,I.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),I.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),I.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Hp=I.object({primary:Ac,background:Ac,text:Ac,radius:kb,font:I.enum(["system","serif","rounded","mono"]),fontAssets:I.object({family:I.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/),faces:I.array(I.object({url:xc,weight:I.number().int().min(100).max(900).multipleOf(100),family:I.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/).optional()}).strict()).min(1).max(4)}).strict().optional()}).strict(),so=I.union([I.enum(["primary","text","muted","background","surface"]),I.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),Fe=(e,t)=>I.number().int().min(e).max(t),Qp=I.union([I.enum(["fit","fill"]),Fe(1,1200)]),jb=I.object({top:Fe(0,200),right:Fe(0,200),bottom:Fe(0,200),left:Fe(0,200)}).strict(),Tb=I.object({top:Fe(-100,200),right:Fe(-100,200),bottom:Fe(-100,200),left:Fe(-100,200)}).strict(),Jp=I.object({x:Fe(0,100),y:Fe(0,100)}).strict(),Nb=I.discriminatedUnion("type",[I.object({type:I.literal("color"),color:so}).strict(),I.object({type:I.literal("linear"),angle:Fe(0,360),stops:I.array(I.object({color:so,at:Fe(0,100)}).strict()).min(2).max(4)}).strict(),I.object({type:I.literal("image"),src:bc,fit:I.enum(["cover","contain"]),position:Jp.optional()}).strict()]),Db=I.discriminatedUnion("type",[I.object({type:I.literal("rect"),radius:I.union([Fe(0,200),I.object({topLeft:Fe(0,200),topRight:Fe(0,200),bottomRight:Fe(0,200),bottomLeft:Fe(0,200)}).strict()])}).strict(),I.object({type:I.literal("pill")}).strict()]),Fb=I.object({width:Fe(0,12),color:so,style:I.enum(["solid","dashed"])}).strict(),Mb=I.object({x:Fe(-40,40),y:Fe(-40,40),blur:Fe(0,80),spread:Fe(-20,40),color:so}).strict(),qb=I.object({font:I.enum(["system","serif","rounded","mono"]),size:Fe(8,96),weight:I.number().int().min(100).max(900).multipleOf(100),lineHeight:I.number().min(.8).max(3),letterSpacing:I.number().min(-5).max(20),color:so,align:I.enum(["start","center","end"]),italic:I.boolean(),decoration:I.enum(["none","underline","line-through"]),transform:I.enum(["none","uppercase"])}).strict().partial(),jr=I.object({width:Qp,height:Qp,padding:jb,margin:Tb,gap:Fe(0,120),grow:I.union([I.boolean(),I.number().min(0).max(12)]),background:Nb,opacity:I.number().min(0).max(1),clipContent:I.boolean(),shape:Db,border:Fb,shadow:Mb,text:qb}).strict().partial(),tn={id:ao,name:I.string().trim().min(1).max(60).optional(),hidden:I.boolean().optional(),style:jr.optional(),fallback:qe.optional()},Ub=I.object({...tn,type:I.literal("text"),productField:I.enum(["name","price","trial","period"]).optional(),feature:I.object({id:I.uuid(),field:I.enum(["name","allowance"])}).strict().optional(),text:qe,variant:I.enum(["title","heading","body","caption"])}).strict(),Bb=I.object({...tn,type:I.literal("image"),src:bc,localizedSrc:I.record(Sn,bc).optional(),alt:qe,aspect:I.enum(["auto","1:1","4:3","16:9","3:1"]),fit:I.enum(["cover","contain"]),position:Jp.optional()}).strict(),Vb=I.object({...tn,type:I.literal("button"),label:qe,variant:I.enum(["primary","secondary","link"]),action:qe,purpose:I.enum(["purchase","navigation","close"]).optional(),bind:ha.optional()}).strict(),Lb=I.object({...tn,type:I.literal("divider")}).strict(),zb=I.object({...tn,type:I.literal("customer_data"),title:qe,data:Bp}).strict(),$b=I.object({...tn,type:I.literal("spacer"),size:Rb}).strict(),Gb=I.object({...tn,type:I.literal("custom_html"),html:I.record(Sn,I.string().max(Cn.customHtml)),css:I.string().max(Cn.customCss),ui:Gp.optional()}).strict(),Kb=I.object({...tn,type:I.literal("price"),fallback:qe,parts:I.object({current:jr.optional(),original:jr.optional(),period:jr.optional()}).strict().optional()}).strict(),Hb=I.object({...tn,type:I.literal("coupon_code"),label:qe,fallback:qe}).strict(),Qb=I.object({...tn,type:I.literal("countdown"),source:I.enum(["offer.ends_at","offer.expires_at","fixed"]),at:I.iso.datetime().optional(),granularity:I.enum(["day","hour","minute","second"]),expired:qe,fallback:qe}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),Jb=I.object({...tn,type:I.literal("plan_picker"),label:qe,fallback:qe,planIds:I.array(I.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:I.string().min(1).max(200).optional(),grouping:ya.safeExtend({monthLabel:qe,yearLabel:qe,unavailableLabel:qe}).optional(),states:I.object({selected:jr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!Aa(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),Zb=I.object({...tn,type:I.literal("quantity_picker"),bind:ha.optional(),label:qe,fallback:qe,internalFeatureId:I.uuid(),minimumQuantity:Fe(0,1e4),maximumQuantity:Fe(0,1e4),defaultQuantity:Fe(0,1e4),step:Fe(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"),Wb=I.discriminatedUnion("type",[I.object({type:I.literal("input"),label:qe,keyboard:I.enum(["text","email","tel","url"]),maxLength:Fe(1,500)}).strict(),I.object({type:I.literal("multiselect"),label:qe,min:Fe(0,50),max:Fe(1,50)}).strict(),I.object({type:I.literal("select"),label:qe,defaultIndex:Fe(0,49),purpose:I.enum(["option","product","tier"]).optional(),pickerId:ao.optional(),selectedStyle:jr.optional()}).strict(),I.object({type:I.literal("tabs"),label:qe,defaultIndex:Fe(0,49),purpose:I.literal("tier").optional()}).strict(),I.object({type:I.literal("toggle"),label:qe,defaultEnabled:I.boolean()}).strict(),I.object({type:I.literal("carousel"),label:qe}).strict()]),Pn={...tn,type:I.literal("stack"),direction:I.enum(["vertical","horizontal","overlay"]),align:I.enum(["start","center","end","stretch"]),justify:I.enum(["start","center","end","between"]),productSlot:I.object({index:Fe(0,19),period:I.enum(["month","year"]).optional(),requireBinding:I.boolean().optional()}).strict().optional(),interaction:Wb.optional(),states:I.object({selected:jr.optional()}).strict().optional(),purpose:I.literal("benefits").optional(),purchaseAction:qe.optional(),buttonVariant:I.enum(["primary","secondary","link"]).optional(),bind:ha.optional()},Zp=I.lazy(()=>I.object({...tn,type:Pn.type,direction:Pn.direction,align:Pn.align,justify:Pn.justify,children:I.array(Yb).max(Cn.children),productSlot:Pn.productSlot,interaction:Pn.interaction,states:Pn.states,purpose:Pn.purpose,purchaseAction:Pn.purchaseAction,buttonVariant:Pn.buttonVariant,bind:Pn.bind}).strict()),Yb=I.lazy(()=>I.union([Zp,Ub,Bb,Vb,Lb,$b,Gb,Kb,Hb,Qb,Jb,Zb,zb])),Xb=I.union([I.string().max(500),I.number().finite(),I.boolean(),I.null()]),oo={id:qe,event:qe,properties:I.record(qe,Xb).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},ex=I.discriminatedUnion("type",[I.object({...oo,type:I.literal("navigate"),close:I.literal(!1),pageId:ao}).strict(),I.object({...oo,type:I.literal("event"),close:I.boolean()}).strict(),I.object({...oo,type:I.literal("close"),close:I.literal(!0)}).strict(),I.object({...oo,type:I.literal("open_url"),close:I.boolean(),url:xc}).strict(),I.object({...oo,type:I.literal("claim_offer"),close:I.boolean(),couponId:I.uuid()}).strict()]),tx=I.object({defaultLocale:Sn,locales:I.record(Sn,I.record(qe,I.string().max(Cn.stringLength)))}).strict(),nx=I.enum(["popup","paywall","onboarding","page","banner"]);var rx=I.object({kind:I.literal("screen"),schemaVersion:I.literal(Eb),name:I.string().trim().min(1).max(80),surface:nx,initialPageId:ao.optional(),presentation:On,theme:Hp,pages:I.array(I.object({id:ao,name:I.string().trim().min(1).max(60),root:Zp,theme:Hp.optional(),editorPosition:I.object({x:I.number().finite().min(-1e5).max(1e5),y:I.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(Cn.pages),strings:tx,actions:I.array(ex).max(Cn.actions)}).strict();function Gt(e,t){for(let n of e.pages)Jn(n.root,t)}var cn=rx.superRefine((e,t)=>{let n=Cn;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>Cn.locales&&r(`\u6700\u591A ${Cn.locales} \u79CD\u8BED\u8A00`);let a=new Set;for(let l of e.actions)a.has(l.id)&&r(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${l.id}`),a.add(l.id);let o=new Set;for(let l of e.pages)["next","back"].includes(l.id)&&r(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${l.id}`),o.has(l.id)&&r(`\u9875\u9762 id \u91CD\u590D\uFF1A${l.id}`),o.add(l.id);let s=new Set,c=0,u=!1;Gt(e,(l,m)=>{if(c++,m>Cn.depth&&(u=!0),s.has(l.id)&&r(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${l.id}`),s.add(l.id),l.type==="button"&&!a.has(l.action)&&r(`\u6309\u94AE ${l.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${l.action}`),l.type==="custom_html")for(let f of Object.keys(l.html))i.includes(f)||r(`\u81EA\u5B9A\u4E49 HTML ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${f}`);if(l.type==="image")for(let f of Object.keys(l.localizedSrc??{}))i.includes(f)||r(`\u56FE\u7247 ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${f}`)}),c>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),u&&r(`\u5C42\u7EA7\u6700\u591A ${Cn.depth} \u5C42`)});function Jn(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)Jn(i,t,n+1,e)}function xa(e){let t=[],n=new Set;return Gt(e,r=>{let i=(a,o,s)=>{n.has(a)||(n.add(a),t.push({key:a,nodeId:r.id,nodeType:r.type,field:o,required:s}))};r.type==="stack"&&r.interaction&&i(r.interaction.label,"label",!0),r.fallback&&i(r.fallback,"text",!0),r.type==="text"&&i(r.text,"text",!0),r.type==="customer_data"&&i(r.title,"title",!0),(r.type==="plan_picker"||r.type==="quantity_picker"||r.type==="coupon_code")&&i(r.label,"label",!0),r.type==="plan_picker"&&r.grouping&&(i(r.grouping.monthLabel,"label",!0),i(r.grouping.yearLabel,"label",!0),i(r.grouping.unavailableLabel,"text",!0)),r.type==="countdown"&&i(r.expired,"text",!0),r.type==="button"&&i(r.label,"label",!0),r.type==="image"&&(i(`image:${r.id}`,"src",!1),i(r.alt,"alt",!1)),r.type==="custom_html"&&i(`html:${r.id}`,"html",!0)}),t}function ix(e,t,n){if(t.field==="html"){let r;return Gt(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=co(e,t.nodeId);return r?.type==="image"?r.localizedSrc?.[n]??(n===e.strings.defaultLocale?r.src:void 0):void 0}return e.strings.locales[n]?.[t.key]}function ir(e){let t=xa(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=>!ix(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 ox(e,t){let n=null;return Jn(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function co(e,t){for(let n of e.pages){let r=ox(n.root,t);if(r)return r}return null}import{z as Bt}from"zod";var St=Bt.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/).refine(e=>e.split(".").every(t=>t.length>0&&!["__proto__","constructor","prototype"].includes(t)),"Reserved or empty variable path"),Sc=Bt.strictObject({type:Bt.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:Bt.boolean(),enum:Bt.array(Bt.string().max(255)).min(1).max(100).optional()}),pi=Sc.extend({type:Bt.enum([...Sc.shape.type.options,"array"]),items:Sc.optional()}).superRefine((e,t)=>{(e.type==="array"!=!!e.items||e.enum&&e.type!=="string"||e.items?.enum&&e.items.type!=="string")&&t.addIssue({code:"custom",message:"Array requires items; only strings support enum"})}),mi=pi.safeExtend({source:Bt.discriminatedUnion("type",[Bt.strictObject({type:Bt.literal("input")}),Bt.strictObject({type:Bt.literal("node")}),Bt.strictObject({type:Bt.enum(["parameter","attribute"]),key:St})])}),sC=Bt.record(St,mi),Ic=Bt.record(St,St).refine(e=>Object.keys(e).length<=20);function gn(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=>gn(e.items,n)):["offering_version","reward","paywall_version"].includes(e.type)?typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===2&&t.type===e.type&&Bt.uuid().safeParse(t.id).success:e.type==="json"||(e.type==="strings"?Array.isArray(t)&&t.every(n=>typeof n=="string"):typeof t===e.type):!1}function vc(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&&vc(e.items,t.items)}function Sa(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(!gn(i,u))throw new Error(`Invalid variable value: ${r}`);n[r]=u}}return n}function fi(e,t){let n={};for(let[r,i]of Object.entries(e.writes??{})){if(!Object.hasOwn(t,r))throw new Error(`Node output is missing: ${r}`);if(Object.hasOwn(n,i))throw new Error("Node outputs cannot overwrite one another");n[i]=t[r]}return n}function Wp(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"||!gn(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 _n=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"),Dn=Tr.discriminatedUnion("source",[Tr.strictObject({source:Tr.literal("literal"),value:ve}),Tr.strictObject({source:Tr.literal("variable"),key:Tr.string().min(1).max(255),path:_n.optional()})]);function Yp(e,t){if(!t)return e;for(let n of _n.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 wc(e,t){if(e.source==="literal")return structuredClone(e.value);let n=Sa(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(ve.parse(Yp(n[e.key],e.path)))}function Oc(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&&!_n.safeParse(r).success?null:{key:n,path:r}}function Pc(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Gt(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(Fp))]}function Ia(e){return Pc(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,f=(l.includes(".")?l.indexOf("."):m)+Number(u),g=f<=0?2-f+m:f>=m?f:m+1;n+=g+(c.startsWith("-")?1:0)-s.length}}return n}var or=Ce.enum(["page","popup","banner"]),ax=3e5,Xp=Ce.strictObject({type:Ce.enum(["string","number","boolean","strings","json"]),nullable:Ce.boolean()}),sx=Ce.strictObject({inputs:Ce.record(qe,Xp.extend({required:Ce.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:Ce.record(qe,Xp).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),cx=Ce.strictObject({kind:or,schemaVersion:Ce.literal(1),name:Ce.string().trim().min(1).max(80),screen:cn,contract:sx}),va=cx.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)>ax&&n("Content document exceeds its byte budget",[])});function ux(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 lx=va.superRefine((e,t)=>{for(let n of Ia(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&&!ux(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}ir(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),em=Ce.strictObject({id:Ce.uuid(),kind:or,projectId:Ce.uuid(),environmentId:Ce.uuid(),name:Ce.string(),revision:Ce.number().int().nonnegative(),status:Ce.enum(["draft","published","archived"]),publishedVersionId:Ce.uuid().nullable(),createdAt:Ce.iso.datetime({offset:!0}),updatedAt:Ce.iso.datetime({offset:!0})}),vC=em.extend({draft:va}),wC=Ce.strictObject({rows:Ce.array(em).max(200),nextCursor:Ce.uuid().nullable()}),Cc=Ce.strictObject({id:Ce.uuid(),kind:or,resourceId:Ce.uuid(),projectId:Ce.uuid(),environmentId:Ce.uuid(),version:Ce.number().int().positive(),sourceRevision:Ce.number().int().nonnegative(),document:lx,createdAt:Ce.iso.datetime({offset:!0})}),OC=Cc.omit({document:!0}),PC=Ce.discriminatedUnion("action",[Ce.strictObject({action:Ce.literal("create"),kind:or,id:Ce.uuid(),document:va}),Ce.strictObject({action:Ce.literal("save"),kind:or,id:Ce.uuid(),revision:Ce.number().int().nonnegative(),document:va}),Ce.strictObject({action:Ce.enum(["publish","archive"]),kind:or,id:Ce.uuid(),revision:Ce.number().int().nonnegative()})]).superRefine((e,t)=>{"document"in e&&e.document.kind!==e.kind&&t.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});import{z as tm}from"zod";var gi={funnelId:tm.uuid().optional(),funnelVersionId:tm.uuid().optional()};import{z as wa}from"zod";var Oa=wa.strictObject({runId:wa.uuid(),bindingId:wa.uuid(),receiptId:wa.uuid()});import{z as ot}from"zod";import{z as Ue}from"zod";import{z as Xe}from"zod";var TC=Xe.discriminatedUnion("action",[Xe.strictObject({action:Xe.literal("create"),couponId:Xe.uuid(),productBindingId:Xe.uuid(),storeOfferId:Xe.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:Xe.enum(["introductory","promotional"])}),Xe.strictObject({action:Xe.literal("set_enabled"),id:Xe.uuid(),revision:Xe.number().int().nonnegative(),enabled:Xe.boolean()})]),NC=Xe.array(Xe.strictObject({id:Xe.uuid(),couponId:Xe.uuid(),productBindingId:Xe.uuid(),storeOfferId:Xe.string().min(1).max(255).nullable(),storeOfferType:Xe.enum(["introductory","promotional"]),enabled:Xe.boolean(),revision:Xe.number().int().nonnegative()})).max(500),hi=Xe.strictObject({offerKind:Xe.enum(["none","introductory","promotional"]),offerId:Xe.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:Xe.number().int().min(0).max(1e8),trialDays:Xe.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"})}),DC=Xe.record(Xe.uuid(),hi).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var _c=Ue.object({type:Ue.literal("native_purchase"),receiptId:Ue.uuid(),orderId:Ue.uuid(),productVersionId:Ue.uuid(),provider:Ue.enum(["apple","google"]),productId:Ue.string().min(1).max(255),productKind:Np,replacement:Ue.strictObject({sourceOrderId:Ue.uuid(),sourceProductId:Ue.string().min(1).max(255),policy:Ue.enum(["apple_store","google_full_price"]),sourceAccountTokens:Ue.array(Ue.uuid()).max(50)}).nullable(),appAccountToken:Ue.uuid().optional(),obfuscatedAccountId:Ue.string().min(1).max(64).optional(),obfuscatedProfileId:Ue.uuid().optional(),basePlanId:Ue.string().min(1).max(255).optional(),offerId:Ue.string().min(1).max(255).optional(),offerKind:Ue.enum(["none","introductory","promotional"]),currency:Ie,catalogAmountMinor:Ue.number().int().nonnegative().max(1e8),discountMinor:Ue.number().int().nonnegative().max(1e8),trialDays:Ue.number().int().min(1).max(730).nullable(),seatBundle:Ue.array(Ue.strictObject({key:Ue.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:Ue.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:Ue.strictObject({offerId:Ue.string().min(1).max(255),keyId:Ue.string().min(1).max(255),nonce:Ue.uuid(),signature:Ue.string().min(1).max(1024),timestamp:Ue.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,t)=>{let n=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(n?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!n&&e.productKind==="membership"&&e.basePlanId===void 0||e.discountMinor>e.catalogAmountMinor||new Set(e.seatBundle.map(i=>i.key)).size!==e.seatBundle.length||e.trialDays!==null&&(e.discountMinor!==0||e.offerKind==="none")||e.offerKind==="none"&&e.discountMinor!==0||(n?!e.appAccountToken||e.obfuscatedAccountId!==void 0||e.obfuscatedProfileId!==void 0||e.basePlanId!==void 0||e.offerKind==="promotional"!=(e.applePromotionalOffer!==null)||e.offerKind==="promotional"!=(e.offerId!==void 0)||e.applePromotionalOffer!==null&&e.applePromotionalOffer.offerId!==e.offerId:e.appAccountToken!==void 0||!e.obfuscatedAccountId||!e.obfuscatedProfileId||e.applePromotionalOffer!==null||e.offerKind==="none"!=(e.offerId===void 0)))&&t.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});import{z as p}from"zod";import{z as _e}from"zod/v4";import{z as dx}from"zod/v4";var px=dx.registry(),{BillingInterval:nm}=(()=>{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:mx}=(e=>({DisplaySchema:e.object({primary_text:e.string().meta({description:"Main display text (e.g. '$10' or '100 messages')."}),secondary_text:e.string().optional().meta({description:"Secondary display text (e.g. 'per month' or 'then $0.5 per 100')."})})}))(_e),{withSpecDefault:fx}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(px),{COMMON:rm}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:gx}={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:hx}=(e=>({COMMON_SET:new Set(e)}))(rm),{hasNoDuplicateCurrencies:im}={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:om}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:yx}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(_e),{Infinite:Ax}={Infinite:"inf"},{TierBehavior:bx}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:am}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:xx}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:Sx}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:Ix}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:vx}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(_e),{ApiCreditTierSchema:sm}=(e=>({ApiCreditTierSchema:e.object({to:e.union([e.number().positive(),e.enum(["inf"])]).meta({description:"Inclusive upper usage boundary for this graduated tier. The final tier must be 'inf'."}),credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group within this tier."})})}))(_e),{VIOLATION_MESSAGES:wx}={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:cm}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(_e),{ModelMarkupsSchema:Ox}=((e,t)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),t.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(_e,cm),{InvoiceUsageEntrySchema:Px}=(e=>({InvoiceUsageEntrySchema:e.object({feature_id:e.string().meta({description:"The metered feature whose units are being converted."}),quantity:e.number().nonnegative().meta({description:"Billable units of the metered feature. Converted to the credit-system feature through its rate card."}),properties:e.record(e.string(),e.unknown()).optional().meta({description:"Event properties used to pick the rate card dimension and multipliers."})}).strict()}))(_e),{AttachDiscountSchema:um}=(e=>({AttachDiscountSchema:e.object({reward_id:e.string().optional().meta({description:"The ID of the reward to apply as a discount."}),promotion_code:e.string().optional().meta({description:"The promotion code to apply as a discount."})}).refine(n=>n.reward_id||n.promotion_code,{message:"Either reward_id or promotion_code must be provided."}).meta({title:"AttachDiscount",description:"A discount to apply. Can be either a reward ID or a promotion code."})}))(_e),{CustomLineItemSchema:Cx}=(e=>({CustomLineItemSchema:e.object({amount:e.number().meta({description:"Amount in dollars for this line item (e.g. 10.50). Can be negative for credits."}),description:e.string().meta({description:"Description for the line item."})})}))(_e),{UnixMsTimestampSchema:_x}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(_e),{CreateInvoicePreviewLineSchema:Ex}=(e=>({CreateInvoicePreviewLineSchema:e.object({plan_id:e.string().nullable(),feature_id:e.string().nullable(),description:e.string(),amount:e.number(),amount_after_discounts:e.number(),quantity:e.number().nullable(),prorated:e.boolean(),period_start:e.number().nullable(),period_end:e.number().nullable()})}))(_e),{ReissueInvoiceParamsSchema:lm}=(e=>({ReissueInvoiceParamsSchema:e.object({invoice_id:e.string().meta({description:"The Autumn invoice ID to void and replace.",example:"inv_2b3c4d5e6f7g8h"}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer and memo are applied to the replacement invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the replacement invoice. Defaults to the original invoice's due date; required when that date has already passed."}),update_customer_email:e.email().optional().meta({description:"Updates the customer's billing email before the replacement is issued, so Stripe sends the new invoice to this address."})})}))(_e),{InvoiceModeParamsSchema: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."})}))(_e),{InvoiceTemplateSchema:Rx}=(e=>({InvoiceTemplateSchema:e.object({id:e.string().meta({description:"Unique identifier for the invoice template."}),name:e.string().meta({description:"User-defined name to distinguish this template when sending an invoice."}),footer:e.string().optional().meta({description:"Footer text rendered on the invoice, typically bank details so customers can pay directly."}),memo:e.string().optional().meta({description:"Memo shown near the top of the invoice (Stripe invoice description), e.g. a contact line for payment questions."}),net_terms_days:e.number().int().positive().optional().meta({description:"Default number of days the customer has to pay before the invoice is due. Overridable when sending."}),created_at:e.number().optional().meta({description:"Timestamp (ms) when the template was created."})})}))(_e),{BasePriceSchema:kx}=((e,t,n)=>({BasePriceSchema:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),interval:e.enum(t).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),display:n.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(_e,nm,mx),{CURRENCY_CODES:jx}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(rm,gx,hx),{ApiPriceProcessorsSchema:dm}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(_e,yx),{AllocatedBillingFieldSchema:Tx}=((e,t)=>({AllocatedBillingFieldSchema:e.enum(t).optional().meta({internal:!0,description:"How an allocated usage_based price bills mid-cycle quantity changes. 'arrear' (default) bills at period end. 'prorated_legacy' is only returned for prices still on the legacy immediate-proration behavior; omit it to migrate the price to 'arrear'."})}))(_e,xx),{CreditDimensionNameSchema:Nx}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(_e,Sx,Ix),{ApiCreditMatchSchema:pm}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(vx),{findCreditTierViolations:Dx}=(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}}))(wx),{ApiCreditMultiplierSchema:Fx}=((e,t)=>({ApiCreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional().meta({description:"Multiplies the matched rate. All matching multipliers stack."}),add:e.number().optional().meta({description:"Added to the rate after every factor is applied, in credits per billing-unit group."})}).strict().refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(_e,pm),{ProviderMarkupsSchema:Mx}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(_e,cm),{InvoiceFeatureQuantitySchema:mm}=((e,t,n)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(t).meta({description:"Which of the feature's prices to use: 'prepaid' or 'usage_based'."}),quantity:e.number().nonnegative().optional().meta({description:"Billable feature units in total, exclusive of any included usage. Not per seat or per entity. For a credit-system feature this is the number of credits."}),usage:e.array(n).optional().meta({description:"For credit-system features: billable units of the source features, converted through the credit rate card. Mutually exclusive with quantity."}),prorate:e.boolean().optional().meta({description:"Whether to prorate this line against period_start / period_end. Defaults to true for prepaid and false for usage-based."})}).strict().refine(i=>i.quantity!==void 0!=(i.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(_e,am,Px),{CreateInvoicePreviewSchema:Ec}=((e,t)=>({CreateInvoicePreviewSchema:e.object({currency:e.string(),lines:e.array(t),subtotal:e.number(),discount_total:e.number(),tax:e.object({total:e.number(),amount_inclusive:e.number(),amount_exclusive:e.number(),status:e.enum(["complete","incomplete"])}).nullable(),total:e.number(),due_date:e.number().nullable()})}))(_e,Ex),{SUPPORTED_SET:qx}=(e=>({SUPPORTED_SET:new Set(e)}))(jx),{ApiCreditDimensionBaseSchema:Ux}=((e,t)=>({ApiCreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(_e,pm),{refineGraduatedTiers:fm}=(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"]})}}))(Dx),{ApiFeatureMarkupsOverrideSchema:Bx}=((e,t,n)=>({ApiFeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional().meta({description:"Default percentage markup for customers on this plan. Use -100 to make usage free."}),provider_markups:t.meta({description:"Per-provider markup percentages for customers on this plan."}),model_markups:n.meta({description:"Per-model markup overrides for customers on this plan."})})}))(_e,Mx,Ox),{isValidCurrencyCode:Vx}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(qx),{ApiCreditDimensionSchema:Lx}=((e,t,n,r)=>({ApiCreditDimensionSchema:e.union([t.extend({tier_behavior:e.literal("graduated"),tiers:e.array(n).min(1)}).strict().superRefine(r),t.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(_e,Ux,sm,fm),{CurrencyCodeSchema:gm}=((e,t)=>({CurrencyCodeSchema:e.string().refine(t,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(_e,Vx),{AdditionalCurrencyTierSchema:zx}=((e,t)=>({AdditionalCurrencyTierSchema:e.object({currency:t,amount:e.number().optional().meta({description:"Per-unit amount for this tier in this currency."}),flat_amount:e.number().optional().meta({description:"Flat amount for this tier in this currency, if the tier uses one."})}).refine(r=>r.amount!==void 0||r.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(_e,gm),{ApiCreditSchemaItemBaseSchema:hm}=((e,t,n,r)=>({ApiCreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string().nonempty().meta({description:"ID of the metered feature that draws from this credit system."}),billing_units:e.number().positive().optional().meta({description:"Number of metered-feature units priced together. Defaults to one when omitted."}),dimensions:e.record(t,n).optional().meta({description:"Named rates chosen by event properties. The most specific match sets the rate; with no match the item's own rate applies."}),multipliers:e.record(t,r).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(_e,Nx,Lx,Fx),{ApiFlatCreditSchemaItemSchema:$x}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(hm,_e),{AdditionalCurrencyPriceSchema:Gx}=((e,t)=>({AdditionalCurrencyPriceSchema:e.object({currency:t,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(_e,gm),{AdditionalCurrencyTierArraySchema:Kx}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(_e,zx,im,om),{ApiGraduatedCreditSchemaItemSchema:Hx}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(hm,_e,sm,fm),{AdditionalCurrencyPriceArraySchema:ym}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(_e,Gx,im,om),{ApiUsageTierWithCurrenciesSchema:Qx}=((e,t,n)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:n.optional().meta({description:"Per-currency amounts for this tier. Tier boundaries ('to') are shared across all currencies."})}).refine(i=>i.amount!==void 0||i.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(i=>({...i,amount:i.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:n.optional()}))}))(_e,Ax,Kx),{ApiCreditSchemaItemSchema:Jx}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(_e,Hx,$x),{BasePriceParamsSchema:Zx}=((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."})}))(kx,fx,_e,ym),{PlanItemPriceParamsSchema:Wx}=((e,t,n,r,i,a,o)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(c=>c??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:t.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(i).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(a).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:o,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(_e,ym,Qx,bx,nm,am,Tx),{ApiFeatureOverrideSchema:Yx}=((e,t,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(t).optional().meta({description:"For credit system features: replaces the feature's credit_schema entirely for customers on this plan."}),markups:n.optional().meta({description:"For AI credit system features: replaces the feature's markup chain entirely for customers on this plan. An unset level means no markup at that level rather than inheriting the feature's."})})}))(_e,Jx,Bx),{InvoiceBasePriceParamsSchema:Am}=((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()}))(Zx,dm),{InvoiceItemPriceParamsSchema:Xx}=((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()}))(Wx,dm),{InvoiceLicenseQuantitySchema:eS}=((e,t,n)=>({InvoiceLicenseQuantitySchema:e.object({license_plan_id:e.string().meta({description:"The license plan linked to the parent plan."}),quantity:e.number().int().nonnegative().meta({description:"Billable seats, exclusive of any included seats."}),customize:e.object({price:t.nullable().optional()}).strict().optional().meta({description:"Override the license's per-seat price on this invoice."}),feature_quantities:e.array(n).optional().meta({description:"Feature charges priced through the license plan."}),prorate:e.boolean().optional().meta({description:"Whether to prorate seat charges against period_start / period_end. Defaults to true."})}).strict()}))(_e,Am,mm),{InvoiceCustomizeItemSchema:tS}=((e,t,n)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:t.optional().meta({description:"Pricing to use for this feature on this invoice."}),feature_override:n.pick({credit_schema:!0}).strict().optional().meta({description:"For credit-system features: a credit rate card to use when converting `usage` on this invoice."})}).strict()}))(_e,Xx,Yx),{InvoiceCustomizeSchema:nS}=((e,t,n)=>({InvoiceCustomizeSchema:e.object({price:t.nullable().optional().meta({description:"Override the plan's base price for this invoice. Pass null or an amount of 0 to omit the base price line."}),items:e.array(n).optional().meta({description:"Override feature pricing for this invoice. Only pricing fields are accepted; grants, resets and rollovers are not part of an invoice."})}).strict().meta({title:"InvoiceCustomize",description:"Pricing overrides applied to this invoice only. The catalog and the customer's plan are not changed."})}))(_e,Am,tS),{InvoicePlanParamsSchema:rS}=((e,t,n,r,i)=>({InvoicePlanParamsSchema:e.object({plan_id:e.string().meta({description:"The catalog plan (or variant) whose pricing to use."}),version:e.number().optional().meta({description:"Plan version. Defaults to the active version."}),customize:t.optional(),feature_quantities:e.array(n).optional(),license_quantities:e.array(r).optional(),discounts:e.array(i).optional().meta({description:"Discounts applied only to this plan's lines."}),prorate:e.boolean().optional().meta({description:"Whether to prorate the base price against period_start / period_end. Defaults to true."})}).strict()}))(_e,nS,mm,eS,um),{CreateInvoiceParamsSchema:yi}=((e,t,n,r,i)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(t).optional(),custom_line_items:e.array(n).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(r).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:i.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start \u2192 period_end against one price interval starting at period_start."}),period_end:i.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(o=>o.period_start===void 0==(o.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(o=>o.period_start===void 0||o.period_end===void 0||o.period_end>o.period_start,{message:"period_end must be after period_start."})}))(_e,rS,Cx,um,_x);var Sm=p.strictObject({requestId:p.uuid(),predecessorOperationId:p.uuid().optional(),invoiceMode:Nr.optional(),entityId:p.uuid().optional(),billingSubscriptionId:p.uuid().optional(),newBillingSubscription:p.literal(!0).optional(),offerId:p.uuid().optional(),nativeOffer:hi.optional(),plans:p.array(p.strictObject({productVersionId:p.uuid(),seatQuantities:p.record(Go,p.number().int().min(0).max(1e4)).optional(),featureQuantities:p.record(p.uuid(),p.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100,"At most 100 feature quantities").optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Plan versions must be unique"),provider:p.enum(["stripe","apple","google","merchant"]),currency:Ie}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||["apple","google"].includes(e.provider)&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||["stripe","merchant"].includes(e.provider)&&!e.billingSubscriptionId,"A new billing subscription has no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),Fr=p.strictObject({operationId:p.uuid()}),Dt=p.number().int().min(0).max(1e8),iS=p.strictObject({lineId:p.uuid(),productVersionId:p.uuid(),productName:p.string().min(1).max(80),interval:p.enum(["free","week","month","year","one_time"]),intervalCount:p.number().int().min(1).max(156).optional(),baseAmountMinor:Dt,seats:p.array(p.strictObject({key:Go,quantity:p.number().int().min(0).max(1e4),includedQuantity:p.number().int().min(0).max(1e4),maximumQuantity:p.number().int().min(0).max(1e4),unitAmountMinor:Dt})).max(20),prepaid:p.array(cp).max(100).optional(),catalogAmountMinor:Dt,trial:p.strictObject({days:p.number().int().min(1).max(730),cardRequired:p.boolean()}).nullable()}).refine(e=>new Set(e.seats.map(t=>t.key)).size===e.seats.length&&e.seats.every(t=>t.quantity>=t.includedQuantity&&t.quantity<=t.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((t,n)=>t+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((t,n)=>t+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"),Im=p.string().regex(/^[A-Za-z0-9_-]{1,200}$/),oS=p.strictObject({id:Im,name:p.string().min(1).max(40),percent_off:p.number().gt(0).max(100).optional(),amount_off:p.number().int().positive().optional(),currency:p.string().regex(/^[a-z]{3}$/).optional(),duration:p.enum(["once","repeating","forever"]),duration_in_months:p.number().int().min(1).max(36).optional()}).refine(e=>e.percent_off===void 0!=(e.amount_off===void 0)&&e.amount_off===void 0==(e.currency===void 0)&&e.duration==="repeating"==(e.duration_in_months!==void 0),"A Stripe coupon has one percentage or amount and months only when repeating"),aS=p.strictObject({subscriptionId:p.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:p.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:p.array(p.strictObject({id:p.string(),price_id:p.string(),quantity:p.number().int().nonnegative(),discounts:p.array(p.strictObject({id:p.string(),coupon:p.string(),start:p.number(),end:p.number().nullable()})).optional()})).min(1).max(100),prorationDate:p.number().int().nonnegative(),amountMinor:p.number().int().positive(),periodStartMs:p.number(),periodEndMs:p.number()}),vm=p.strictObject({invoiceMode:Nr.optional(),append:aS.optional(),provider:p.literal("stripe"),executor:p.enum(["indiana","merchant"]),accountId:p.string().regex(/^acct_[A-Za-z0-9]+$/),mode:p.enum(["payment","subscription"]),lineItems:p.array(p.strictObject({price:p.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:p.number().int().min(1).max(1e4),priceId:p.uuid(),productName:p.string().min(1).max(80),amountMinor:p.number().int().min(0).max(1e8),currency:p.string().regex(/^[a-z]{3}$/),interval:p.enum(["week","month","year","one_off"]),intervalCount:p.number().int().min(1).max(52),slot:p.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:p.strictObject({mode:p.enum(["graduated","volume"]),tiers:p.array(p.strictObject({upTo:p.number().int().min(1).max(1e6).nullable(),unitAmountMinor:p.number().int().min(0).max(1e8),flatAmountMinor:p.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:p.array(p.strictObject({coupon:Im,terms:oS})).max(1),trialPeriodDays:p.number().int().min(1).max(730).nullable(),metadata:p.strictObject({grooveCheckoutId:p.uuid(),grooveCustomerId:p.uuid()}),expiresAt:p.iso.datetime({offset:!0})}),Ai=p.strictObject({operationId:p.uuid(),entityId:p.uuid().nullable(),billingSubscriptionId:p.uuid().nullable(),discount:p.strictObject({offerId:p.uuid(),couponId:p.uuid(),discount:tr,duration:an,amountMinor:Dt,allocations:p.array(p.strictObject({productVersionId:p.uuid(),amountMinor:Dt})).min(1).max(20),expiresAt:p.iso.datetime({offset:!0})}).nullable(),charge:p.strictObject({effectiveAt:p.iso.datetime({offset:!0}),periodEndsAt:p.iso.datetime({offset:!0}),debitMinor:Dt,discountMinor:Dt,taxMinor:Dt,totalMinor:Dt}).nullable(),expiresAt:p.iso.datetime({offset:!0}),provider:p.enum(["stripe","apple","google","merchant"]),nativeOffer:hi.optional(),currency:Ie,lines:p.array(iS).min(1).max(20),catalogAmountMinor:Dt,automaticTax:p.boolean(),execution:p.union([vm,Bo]).nullable()}).refine(e=>e.provider==="merchant"?e.execution?.provider==="merchant"&&e.execution.operationId===e.operationId&&e.execution.catalogAmountMinor===e.catalogAmountMinor&&e.execution.currency===e.currency&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&e.execution.discount?.grantId===e.discount?.offerId:e.provider==="stripe"?e.execution?.provider!=="merchant"&&(e.lines[0]?.trial?.cardRequired===!1&&!e.execution?.invoiceMode?.enabled?e.execution===null&&e.discount===null:e.execution!==null&&e.execution.metadata.grooveCheckoutId===e.operationId&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.mode===(e.lines.some(t=>!["one_time","free"].includes(t.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(t=>t.price!==null))&&e.execution.discounts.every(t=>t.coupon===t.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(t=>e.discount!==null&&(t.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&t.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${t.terms.amount_off}`&&t.terms.amount_off===e.discount.discount.amountOffCents&&t.terms.currency?.toUpperCase()===e.currency&&t.terms.duration==="once"))):e.execution===null,"Stripe execution must carry the quote identity, expiry, mode, trial and held coupon").refine(e=>(!e.discount||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.discount.duration.type==="once")&&e.discount.amountMinor<=e.catalogAmountMinor&&e.discount.allocations.length===e.lines.length&&e.discount.allocations.every((t,n)=>{let r=e.lines[n];return r!==void 0&&t.productVersionId===r.productVersionId&&t.amountMinor<=r.catalogAmountMinor})&&e.discount.allocations.reduce((t,n)=>t+n.amountMinor,0)===e.discount.amountMinor)&&(["stripe","merchant"].includes(e.provider)?e.nativeOffer===void 0:e.nativeOffer!==void 0&&e.lines.length===1&&e.nativeOffer.discountMinor<=e.catalogAmountMinor&&e.nativeOffer.trialDays===(e.lines[0]?.trial?.days??null)&&(!e.discount||e.nativeOffer.discountMinor===e.discount.amountMinor))&&(!e.charge||e.billingSubscriptionId!==null&&e.charge.totalMinor===e.charge.debitMinor-e.charge.discountMinor+e.charge.taxMinor&&e.charge.discountMinor<=e.charge.debitMinor&&Date.parse(e.charge.periodEndsAt)>Date.parse(e.charge.effectiveAt))&&new Set(e.lines.map(t=>t.lineId)).size===e.lines.length&&e.lines.reduce((t,n)=>t+n.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),bi=p.strictObject({operationId:p.uuid(),orderId:p.uuid(),append:p.boolean().optional(),invoiceMode:p.boolean().optional(),status:p.enum(["pending","complete","cancelled","failed"]),executor:p.enum(["indiana","merchant"]),checkoutUrl:p.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:p.union([vm,Bo]).nullable(),currency:Ie,catalogAmountMinor:Dt,taxMinor:Dt,totalMinor:p.number().int().min(0).max(2e8).nullable(),quoteFinalized:p.boolean(),nativePurchase:_c.nullable(),confirmedAt:p.iso.datetime({offset:!0}).nullable().optional(),quote:Ai.optional(),merchantExecution:Ir.nullable().optional(),problem:Ui.nullable().optional(),authority:$o.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=p.strictObject({enabled:p.literal(!0),featureIds:p.array(p.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),wm=p.strictObject({requestId:p.uuid(),invoiceMode:Nr.optional(),membershipId:p.uuid(),carryOverBalances:Ca.optional(),carryOverUsages:Ca.optional(),membershipIds:p.array(p.uuid()).min(1).max(20).optional(),prorationBehavior:p.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:p.enum(["immediate","renewal","store"]),change:p.discriminatedUnion("type",[p.strictObject({type:p.literal("plan"),productVersionId:p.uuid()}),p.strictObject({type:p.literal("seats"),licenseKey:Go,quantity:p.number().int().min(0).max(1e4)}),p.strictObject({type:p.literal("quantity"),internal_feature_id:p.uuid(),quantity:p.number().int().min(0).max(1e4)}),p.strictObject({type:p.literal("cancel")}),p.strictObject({type:p.literal("uncancel")}),p.strictObject({type:p.literal("billing_cycle"),billingCycleAnchor:p.union([p.literal("now"),p.number().int().positive().max(0xe677d21fdbff)])})])}).refine(e=>e.timing!=="store"||e.change.type==="plan","Store timing applies to a native plan replacement").refine(e=>e.change.type!=="billing_cycle"||e.timing===(e.change.billingCycleAnchor==="now"?"immediate":"renewal"),"Use immediate for now and renewal for a future millisecond anchor").refine(e=>!e.membershipIds||["cancel","uncancel"].includes(e.change.type)&&e.membershipIds.includes(e.membershipId)&&new Set(e.membershipIds).size===e.membershipIds.length,"Grouped actions require unique cancel/uncancel targets including the primary membership").refine(e=>!e.carryOverBalances&&!e.carryOverUsages||e.change.type==="plan"&&e.timing==="immediate","Carry applies only to immediate upgrades").refine(e=>!e.prorationBehavior||e.change.type==="quantity","prorationBehavior applies to prepaid quantity changes"),Pa=p.string().regex(/^price_[A-Za-z0-9]+$/),bm=p.strictObject({grooveUpdateId:p.uuid(),grooveCustomerId:p.uuid()}),xm=p.strictObject({price:Pa.nullable(),priceId:p.uuid().optional(),quantity:p.number().int().min(0).max(1e4)}),Om=p.strictObject({provider:p.literal("stripe"),invoiceMode:Nr.optional(),executor:p.enum(["indiana","merchant"]),accountId:p.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:p.string().regex(/^sub_[A-Za-z0-9]+$/),action:p.enum(["update","cancel","schedule","release"]),update:p.strictObject({items:p.array(xm).max(20),remove:p.array(Pa).max(20),restoreItems:p.array(p.strictObject({price:Pa,quantity:p.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:p.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:p.number().int().positive().optional(),paymentBehavior:p.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:p.boolean().optional(),clearCancelAt:p.literal(!0).optional(),billingCycleAnchorNow:p.literal(!0).optional(),metadata:bm}).nullable(),cancel:p.strictObject({prorate:p.literal(!1),invoiceNow:p.literal(!1)}).nullable(),schedule:p.strictObject({currentItems:p.array(p.strictObject({price:Pa,quantity:p.number().int().min(0).max(1e4)})).max(20),nextItems:p.array(xm).min(1).max(20),switchAt:p.number().int().positive(),interval:p.enum(["week","month","year"]),intervalCount:p.number().int().min(1).max(52),resetBillingCycleAnchor:p.literal(!0).optional(),metadata:bm}).nullable(),release:p.strictObject({schedule:p.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:p.iso.datetime({offset:!0})}).refine(e=>["update","cancel","schedule","release"].every(t=>e[t]!==null==(e.action===t))&&(e.executor==="indiana"||[...e.update?.items??[],...e.schedule?.nextItems??[]].every(t=>t.price!==null)),"Stripe update execution carries exactly its action, with bound Prices for the merchant"),_a=p.strictObject({carryOverBalances:Ca.optional(),carryOverUsages:Ca.optional(),operationId:p.uuid(),membershipId:p.uuid(),productVersionId:p.uuid(),timing:p.enum(["immediate","renewal"]),effectiveAt:p.iso.datetime({offset:!0}),expiresAt:p.iso.datetime({offset:!0}),currency:Ie,creditMinor:Dt,debitMinor:Dt,discountMinor:Dt,taxMinor:Dt,totalMinor:Dt,retainedProductVersionIds:p.array(p.uuid()).max(19),execution:p.union([Om,Vo])}),sS=p.strictObject({operationId:p.uuid(),invoiceMode:p.boolean().optional(),membershipId:p.uuid(),productVersionId:p.uuid(),status:p.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:p.enum(["immediate","renewal"]),effectiveAt:p.iso.datetime({offset:!0}),checkoutUrl:p.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:p.enum(["indiana","merchant"]),execution:p.union([Om,Vo]).nullable(),confirmedAt:p.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Ir.nullable().optional(),problem:Ui.nullable().optional(),quote:_a.optional(),authority:$o.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),cS=p.strictObject({operationId:p.uuid(),membershipId:p.uuid(),productVersionId:p.uuid(),timing:p.literal("store"),effectiveAt:p.null(),expiresAt:p.iso.datetime({offset:!0}),currency:Ie,creditMinor:p.null(),debitMinor:p.null(),discountMinor:p.null(),taxMinor:p.null(),totalMinor:p.null(),retainedProductVersionIds:p.array(p.uuid()).max(19),store:p.strictObject({provider:p.enum(["apple","google"]),productId:p.string().min(1).max(255),catalogAmountMinor:Dt,policy:p.enum(["apple_store","google_full_price"])})}),uS=p.strictObject({operationId:p.uuid(),membershipId:p.uuid(),productVersionId:p.uuid(),status:p.enum(["prepared","pending","effective","cancelled","failed"]),timing:p.literal("store"),effectiveAt:p.iso.datetime({offset:!0}).nullable(),checkoutUrl:p.null(),nativePurchase:_c.nullable()}),Pm=p.union([_a,cS]),Rc=p.union([sS,uS]),uo=p.number().int().positive().max(2e8),Dr=p.number().int().min(0).max(2e8),Cm=p.strictObject({requestId:p.uuid(),invoiceId:p.uuid(),mode:p.enum(["full","partial"]),amountMinor:uo.optional(),entitlementAction:p.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),_m=p.strictObject({provider:p.literal("stripe"),executor:p.enum(["indiana","merchant"]),accountId:p.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:p.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:uo,currency:p.string().regex(/^[a-z]{3}$/),metadata:p.strictObject({indianaRefundId:p.uuid()}),idempotencyKey:p.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:p.array(p.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),kc=p.strictObject({operationId:p.uuid(),invoiceId:p.uuid(),providerInvoiceId:p.string().min(1).max(200),currency:Ie,paidMinor:Dr,refundedMinor:Dr,pendingMinor:Dr,amountMinor:uo,mode:p.enum(["full","partial"]),entitlementAction:p.enum(["retain","revoke"]),revokes:p.strictObject({customerProductIds:p.array(p.uuid()).max(100),subscriptionIds:p.array(p.string().min(1).max(200)).max(20)}),execution:p.union([_m,Lo]),expiresAt:p.iso.datetime({offset:!0})}).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&(e.execution.provider==="merchant"?e.execution.merchantInvoiceId===e.providerInvoiceId&&e.execution.operationId===e.operationId&&e.execution.currency===e.currency:e.execution.invoice===e.providerInvoiceId&&e.execution.metadata.indianaRefundId===e.operationId&&e.execution.currency===e.currency.toLowerCase())&&(e.entitlementAction==="revoke"||e.revokes.customerProductIds.length===0&&e.revokes.subscriptionIds.length===0),"Refund quote must stay within the refundable amount and match its execution"),Ea=p.strictObject({operationId:p.uuid(),invoiceId:p.uuid(),providerInvoiceId:p.string().min(1).max(200),status:p.enum(["quoted","pending","succeeded","failed","expired"]),executor:p.enum(["indiana","merchant"]),currency:Ie,amountMinor:uo,mode:p.enum(["full","partial"]),entitlementAction:p.enum(["retain","revoke"]),refundId:p.string().min(1).max(200).nullable(),quote:kc.optional(),execution:p.union([_m,Lo]).nullable(),confirmedAt:p.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Ir.nullable().optional(),problem:Ui.nullable().optional(),authority:$o.optional(),failureReason:p.string().min(1).max(200).nullable(),createdAt:p.iso.datetime({offset:!0}),completedAt:p.iso.datetime({offset:!0}).nullable()}).refine(e=>(e.execution===null||e.executor==="merchant"&&e.status==="quoted")&&(e.status!=="succeeded"||e.refundId!==null),"Only quoted record-only refunds carry instructions; a succeeded refund names its Stripe refund"),t_=p.strictObject({invoiceId:p.uuid(),currency:Ie,paidMinor:Dr,refundedMinor:Dr,pendingMinor:Dr,refundableMinor:Dr,executor:p.enum(["indiana","merchant"]).nullable(),canRefund:p.boolean(),operations:p.array(Ea).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),n_=p.strictObject({requestId:p.uuid(),mode:p.enum(["full","partial"]),amountMinor:uo.optional(),entitlementAction:p.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount");var Em=ot.strictObject({requestId:ot.uuid(),targets:ot.array(ot.strictObject({membershipId:ot.uuid(),action:ot.enum(["cancel","uncancel"]),timing:ot.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"),Ra=ot.strictObject({batchId:ot.uuid()}),lS=ot.strictObject({operationId:ot.uuid(),membershipIds:ot.array(ot.uuid()).min(1).max(20),provider:ot.enum(["stripe","apple","google"]),action:ot.enum(["cancel","uncancel"]),timing:ot.enum(["immediate","renewal"]),status:ot.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:_a.nullable(),managementUrl:ot.url().nullable(),failureCode:ot.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),lo=ot.strictObject({batchId:ot.uuid(),ready:ot.boolean(),status:ot.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:ot.iso.datetime({offset:!0}),acceptedAt:ot.iso.datetime({offset:!0}).nullable(),groups:ot.array(lS).min(1).max(100)});import{z as ke}from"zod";var dS=ke.string().trim().min(1).max(240),jc={requestId:ke.uuid(),reason:dS},ka=ke.discriminatedUnion("action",[ke.strictObject({...jc,action:ke.literal("start"),productVersionId:ke.uuid(),entityId:ke.uuid().optional(),days:ke.number().int().min(1).max(730).optional()}),ke.strictObject({...jc,action:ke.literal("extend"),membershipId:ke.uuid(),days:ke.number().int().min(1).max(730)}),ke.strictObject({...jc,action:ke.literal("end"),membershipId:ke.uuid()})]),Rm=ke.strictObject({operationId:ke.uuid()}),km=ke.iso.datetime({offset:!0}),pS=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"),km]),prorationBehavior:ke.literal("none")}),Tc=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:km.nullable(),execution:pS.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"),c_=ke.strictObject({groupId:ke.uuid(),productVersionId:ke.uuid(),enabled:ke.boolean()});import{z as Ze}from"zod";var jm=Ze.strictObject({requestId:Ze.uuid(),currency:Ie,makeDefault:Ze.boolean()}),Tm=Ze.strictObject({setupId:Ze.uuid()}),mS=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})}),Nc=Ze.strictObject({id:Ze.uuid(),provider:Ze.literal("stripe"),status:Ze.enum(["prepared","complete","expired"]),currency:Ie,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:mS.nullable()});import{z as Ft}from"zod";var Nm=Ft.union([Ft.string(),Ft.number(),Ft.boolean(),Ft.null()]),Dm=Ft.strictObject({customerId:Ft.uuid()}),Fm=Ft.strictObject({customerId:Ft.uuid(),provider:Ft.literal("stripe"),checkedAt:Ft.iso.datetime({offset:!0}),status:Ft.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Ft.number().int().nonnegative(),differences:Ft.array(Ft.strictObject({subscriptionId:Ft.string().startsWith("sub_"),itemId:Ft.string().nullable(),field:Ft.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Nm,actual:Nm})).max(1e4)});import{z as we}from"zod";var ja=we.iso.datetime({offset:!0}),Ta=we.strictObject({createdAt:ja,id:we.uuid()}),Na=we.strictObject({customerId:we.uuid().optional(),entityId:we.uuid().optional(),productId:we.string().min(1).max(256).optional(),provider:we.enum(["stripe","apple","google","merchant","free"]).optional(),status:we.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:Ta.optional(),limit:we.number().int().min(1).max(100).optional()}),Dc={id:we.uuid(),customerId:we.uuid(),entityId:we.uuid().nullable(),productId:we.string().min(1).max(256),productVersionId:we.uuid(),name:we.string().min(1).max(120),provider:we.enum(["stripe","apple","google","merchant","free"]),createdAt:ja},fS=we.strictObject({...Dc,status:we.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:we.boolean(),billingSubscriptionId:we.uuid().nullable()}),gS=we.strictObject({...Dc,status:we.enum(["active","ended","refunded"]),orderId:we.uuid().nullable(),transactionId:we.uuid().nullable(),currency:Ie.nullable(),amountMinor:we.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),hS=we.strictObject({...Dc,status:we.enum(["blocked","resolved"]),conflict:we.strictObject({detectedAt:ja,blockingMembershipIds:we.array(we.uuid()).min(1).max(100),transactionId:we.uuid()}),resolvedAt:ja.nullable()}),Mm=Na.extend({status:we.enum(["blocked","resolved"]).optional()}),qm=we.strictObject({customerId:we.uuid(),orderId:we.uuid()}),Um=we.strictObject({orderId:we.uuid(),status:we.enum(["blocked","resolved"])}),Bm=we.strictObject({items:we.array(fS).max(100),nextCursor:Ta.nullable()}),Vm=we.strictObject({items:we.array(gS).max(100),nextCursor:Ta.nullable()}),Lm=we.strictObject({items:we.array(hS).max(100),nextCursor:Ta.nullable()});import{z as tt}from"zod";var zm=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)})]),$m=tt.strictObject({requestId:tt.uuid(),orderId:tt.uuid(),purchaseIntentId:tt.uuid(),status:tt.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:Ie,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 L}from"zod";var Mc=L.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),yS=L.record(L.string(),L.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),AS=3,po=20,bS=AS*po,Fc=L.strictObject({type:L.literal("product"),productId:Mc}),Gm={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)},xS=L.discriminatedUnion("type",[Fc,L.strictObject({...Gm,items:L.array(Fc).max(po)})]),SS=L.discriminatedUnion("type",[Fc,L.strictObject({...Gm,items:L.array(xS).max(po)})]),IS=L.array(SS).max(po).superRefine((e,t)=>{let n=new Set,r=new Set,i=0;function a(o){for(let s of o){i++;let c=s.type==="product"?n:r,u=s.type==="product"?s.productId:s.key;c.has(u)&&t.addIssue({code:"custom",message:s.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),c.add(u),s.type==="group"&&a(s.items)}}a(e),(n.size>po||i>bS)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function qc(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:qc(t))}var xi=L.strictObject({lookupKey:L.string().trim().min(1).max(200),displayName:L.string().trim().min(1).max(1500),items:IS,metadata:yS}),vS=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()))}),Km=xi.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"})}),Hm=L.strictObject({id:L.uuid(),offeringId:L.uuid(),projectId:L.uuid(),environmentId:L.uuid(),version:L.number().int().positive(),document:xi,productEvidence:L.record(Mc,vS),createdAt:L.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=qc(e.document);(!n.length||PS(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"})}),wS=L.strictObject({rows:L.array(Km).max(200),versions:L.array(Hm).max(500)}),I_=L.discriminatedUnion("action",[L.strictObject({action:L.literal("create"),document:xi}),L.strictObject({action:L.literal("save"),id:L.uuid(),revision:L.number().int().nonnegative(),document:xi}),L.strictObject({action:L.enum(["publish","set_current","archive","restore"]),id:L.uuid(),revision:L.number().int().nonnegative()})]),v_=L.strictObject({record:Km,version:Hm.nullable()}),Qm=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()})]),OS=L.strictObject({internalId:Mc,id:L.string(),name:L.string().nullable(),version:L.number().int().positive(),archived:L.boolean()}),w_=wS.extend({products:L.array(OS).max(500),pagination:L.strictObject({rows:L.string().nullable(),versions:L.string().nullable(),products:L.string().nullable()}).optional()});function PS(e){let t=[];qc(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 Da}from"zod";var Jm=Da.strictObject({id:Da.uuid(),offeringId:Da.uuid(),version:Da.number().int().positive(),document:xi});import{z as Pt}from"zod";import{z as ye}from"zod";import{z as Si}from"zod";var Fa=Si.strictObject({items:Si.array(Si.strictObject({productVersionId:Si.string().min(1).max(200),label:Si.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:Si.string().min(1).max(200).nullable(),grouping:ya.optional()});function Zm(e,t,n){let r=e.type==="fixed"?e.productVersionId:t[e.pickerId];return typeof r!="string"||!Object.values(n.plans).some(i=>i.versionId===r&&i.available)||e.type==="picker"&&(!e.allowedProductVersionIds.includes(r)||!n.pickers[e.pickerId]?.options.includes(r))?null:r}var Uc=ye.discriminatedUnion("type",[ye.strictObject({type:ye.literal("event"),event:ye.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),ye.strictObject({type:ye.literal("open_url"),url:ye.url().refine(e=>new URL(e).protocol==="https:")})]),CS=cn,_S=ye.discriminatedUnion("type",[ye.object({type:ye.literal("checkout"),product:ba}).strict(),ye.object({type:ye.literal("close")}).strict(),ye.object({type:ye.literal("action"),action:Uc}).strict()]),Ii=ye.object({schemaVersion:ye.literal(3),kind:ye.literal("paywall"),name:ye.string().trim().min(1).max(80),presentation:On,requirement:rr.optional(),products:Fa,offeringVersionId:ye.uuid().nullable(),offeringId:ye.uuid(),screen:CS,buttons:ye.record(ye.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),_S)}).strict(),U_=Ii.superRefine((e,t)=>{(e.screen.surface!=="paywall"||e.screen.actions.some(r=>!["event","navigate"].includes(r.type)||r.close))&&t.addIssue({code:"custom",message:"Paywall screen is incomplete"});for(let r of RS(e))t.addIssue({code:"custom",message:r});for(let r of ES(e))t.addIssue({code:"custom",message:r});ir(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 ES(e){let t=e.products.items.map(a=>a.productVersionId),n=Mp(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&&(!Aa(e.products.grouping,t)||e.products.grouping.tiers.some(a=>!e.products.grouping.assignments.some(o=>o.tierId===a.id)))&&i.push("grouping");for(let a of Object.values(e.buttons))if(a.type==="checkout"){let o=a.product;if(o.type==="fixed")r.add(o.productVersionId);else{o.allowedProductVersionIds.forEach(u=>r.add(u));let s=!1,c=n[o.pickerId];c&&(s=!0,(o.allowedProductVersionIds.some(u=>!c.ids.includes(u))||c.ids.some(u=>!o.allowedProductVersionIds.includes(u)))&&i.push("picker")),Gt(e.screen,u=>{if(u.id!==o.pickerId||u.type!=="plan_picker")return;s=!0,(JSON.stringify(u.planIds)!==JSON.stringify(t)||JSON.stringify(o.allowedProductVersionIds)!==JSON.stringify(t)||u.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let l=u.grouping?{tiers:u.grouping.tiers,assignments:u.grouping.assignments}:void 0;JSON.stringify(l)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),s||i.push("picker")}}return(!r.size||[...r].some(a=>!t.includes(a)))&&i.push("purchase"),Gt(e.screen,a=>{a.type==="stack"&&a.productSlot&&!a.bind?.plan&&i.push(`productBinding:${a.id}`),(a.type==="stack"||a.type==="button")&&a.bind?.plan&&!t.includes(a.bind.plan)&&i.push("binding"),a.type==="plan_picker"&&(!a.planIds?.length||a.planIds.some(o=>!t.includes(o)))&&i.push("binding")}),[...new Set(i)]}function RS(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),Jn(s.root,c=>{let u=c.type==="button"?c.action:c.type==="stack"?c.purchaseAction:void 0;if(u){let l=e.screen.actions.find(f=>f.id===u);l?.type==="navigate"&&r.get(s.id).push(l.pageId);let m=e.buttons[u];s.id!==n.id&&m&&m.type!=="close"&&t.push(`purchaseScreen:${c.id}`)}s.id!==n.id&&(c.type==="plan_picker"||c.type==="stack"&&c.productSlot)&&t.push(`packageScreen:${c.id}`)});let i=new Set;function a(s){if(!i.has(s)){i.add(s);for(let c of r.get(s)??[])a(c)}}let o=e.screen.initialPageId??e.screen.pages[0]?.id;o?a(o):t.push("initialPage");for(let s of e.screen.pages)i.has(s.id)||t.push(`unreachableScreen:${s.id}`);return[...new Set(t)]}var Wm=ye.object({id:ye.uuid(),projectId:ye.uuid(),environmentId:ye.uuid(),revision:ye.number().int().nonnegative(),state:ye.enum(["active","archived"]),publishedVersionId:ye.uuid().nullable(),updatedAt:ye.iso.datetime({offset:!0}),draft:Ii}).strict(),B_=ye.object({rows:ye.array(Wm).max(200),nextCursor:ye.uuid().nullable()}).strict(),V_=Wm.omit({draft:!0}).extend({name:ye.string(),productCount:ye.number().int().nonnegative()}).strict(),L_=ye.discriminatedUnion("action",[ye.object({action:ye.literal("save"),id:ye.uuid().nullable(),revision:ye.number().int().nonnegative(),document:Ii}).strict(),ye.object({action:ye.enum(["publish","archive"]),id:ye.uuid(),revision:ye.number().int().nonnegative()}).strict()]),z_=ye.object({paywalls:ye.array(ye.object({id:ye.uuid(),paywallId:ye.uuid(),version:ye.number().int().positive(),name:ye.string().min(1).max(80),presentation:On,buttons:Ii.shape.buttons}).strict()).max(500),limited:ye.boolean()}).strict();import{z as Ee}from"zod";import{z as Kt}from"zod";var vi=Kt.string().regex(/^[a-f0-9]{64}$/),kS=ga.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),Ym=Kt.strictObject({couponDigests:Kt.record(Kt.uuid(),vi),variables:Kt.record(Sn,Kt.record(Kt.uuid(),Kt.partialRecord(Kt.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),Kt.string()))),locales:Kt.record(Sn,li.extend({nodes:Kt.record(Kt.string(),Kt.strictObject({base:kS})),plans:Kt.object({}).strict(),pickers:Kt.object({}).strict()}).omit({paywall:!0}))});import{z as Be}from"zod";import{z as Ma}from"zod";var Bc=Ma.strictObject({eventsEnabled:Ma.boolean(),experimentViewsEnabled:Ma.boolean(),featureUsageEnabled:Ma.boolean()}),Z_=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function Xm(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}import{z as $}from"zod";var Vc=$.tuple([$.number().min(0).max(1),$.number().min(0).max(1)]).refine(([e,t])=>e<=t),jS=$.strictObject({attribute:$.string().optional(),seed:$.string(),hashVersion:$.literal(2),ranges:$.array(Vc).max(100)}),TS=$.strictObject({id:$.string().min(1).max(255),condition:Yt,gate:$.boolean().optional()}),NS=$.strictObject({key:$.string().optional(),name:$.string().optional(),passthrough:$.boolean().optional()}),ef={condition:Yt.optional(),parentConditions:$.array(TS).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(jS).max(100).optional(),ranges:$.array(Vc).max(20).optional(),meta:$.array(NS).max(20).optional(),seed:$.string().optional(),name:$.string().optional(),phase:$.string().optional()},wi=$.strictObject({...ef,key:$.string().min(1).max(255),variations:$.tuple([ve,ve]).rest(ve).refine(e=>e.length<=20),urlPatterns:$.array($.strictObject({include:$.boolean(),type:$.enum(["regex","simple"]),pattern:$.string()})).max(100).optional(),force:$.number().int().nonnegative().optional(),active:$.boolean().optional(),persistQueryString:$.boolean().optional()}),Lc=$.strictObject({value:ve,variationId:$.number().int(),key:$.string(),name:$.string().optional(),bucket:$.number().optional(),passthrough:$.boolean().optional(),inExperiment:$.boolean(),hashUsed:$.boolean().optional(),hashAttribute:$.string(),hashValue:$.string(),featureId:$.string().nullable(),stickyBucketUsed:$.boolean().optional()}),DS=$.strictObject({...ef,id:$.string().max(255).optional(),force:ve.optional(),variations:$.array(ve).min(2).max(20).optional(),key:$.string().optional(),range:Vc.optional(),tracks:$.array($.strictObject({experiment:wi,result:Lc})).max(100).optional()}),FS=$.strictObject({defaultValue:ve.optional(),rules:$.array(DS).max(500).optional()}),mo=$.record($.string(),$.union([$.strictObject({type:$.literal("hashed"),attributeKey:$.string(),values:$.array($.string().regex(/^[a-f0-9]{64}$/))}),$.strictObject({type:$.literal("list"),attributeKey:$.string(),values:$.array($.union([$.string(),$.number()]))}),$.strictObject({type:$.literal("condition"),condition:Yt})])),hn=$.strictObject({scope:Te,generation:$.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:$.iso.datetime({offset:!0}),expiresAt:$.iso.datetime({offset:!0}).nullable(),features:$.record($.string(),FS),savedGroups:mo,experiments:$.record($.uuid(),wi)});var fo=hn.extend({analyticsConfig:Bc,remoteFeatures:Be.array(Be.string().min(1).max(255)).max(500)}),zc=fo.omit({evaluatedAt:!0,expiresAt:!0}).superRefine((e,t)=>{for(let n of e.remoteFeatures)Object.hasOwn(e.features,n)&&t.addIssue({code:"custom",path:["features",n],message:"Remote Feature definitions cannot be public"});for(let[n,r]of Object.entries(e.savedGroups))r.type==="list"&&t.addIssue({code:"custom",path:["savedGroups",n],message:"Raw Saved Group lists cannot be public"})}),tf=Be.strictObject({attributes:vt,features:Be.array(Be.string().min(1).max(255)).max(500).optional(),customerId:Be.uuid().optional()}),MS=Be.strictObject({value:ve,source:Be.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:Be.boolean(),off:Be.boolean(),ruleId:Be.string(),experimentResult:Lc.optional()}),qa=Be.strictObject({generation:hn.shape.generation,evaluatedAt:hn.shape.evaluatedAt,expiresAt:hn.shape.expiresAt,features:Be.record(Be.string(),MS),merchandiseContext:Be.strictObject({merchandiseId:Be.uuid(),merchandise:vt}).optional()}),nf=Be.strictObject({customerId:Be.uuid().optional(),events:Be.array(Be.strictObject({eventUuid:Be.uuid(),timestamp:Be.iso.datetime({offset:!0}),name:Be.string().min(1).max(255),merchandise:Md.optional(),properties:Be.record(Be.string(),ve).default({}),deviceId:Be.string().min(1).max(255).optional(),sessionId:Be.string().min(1).max(255).optional()})).min(1).max(100)}),rf=Be.strictObject({inserted:Be.number().int().nonnegative(),duplicates:Be.number().int().nonnegative(),rejected:Be.number().int().nonnegative(),skipped:Be.number().int().nonnegative(),analyticsConfig:Bc});import{z}from"zod";import{z as qS}from"zod";var of=qS.enum(["funnel-run/1","funnel-process/1"]),af="funnel-process/1";function $c(e,t=[]){let n=[];Gt(e,i=>{i.hidden&&n.push("Hidden components must not be delivered"),t.includes(i.type)&&n.push(`Node type ${i.type} cannot be delivered`)});let r=new Set(xa(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 sf(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>sf(t)??[])}}function US(e){let t=e.pages.map(i=>{let a=sf(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(xa({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 cf(e,t=[]){let n=cn.parse(structuredClone(US(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=$c(n,t);if(i.length)throw new Error(i.join("; "));return n}import{z as Q}from"zod";import{z as M}from"zod";import{z as pt}from"zod";var Ua=pt.strictObject({schemaVersion:pt.literal(1),renderKey:pt.string().min(1).max(256),routeTemplate:pt.string().startsWith("/").max(2048),selectors:pt.array(pt.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:pt.array(pt.number().int().min(0)).min(1),absent:pt.array(pt.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"})}),uf=pt.strictObject({renderKey:pt.string().min(1).max(256),routeKey:pt.string().min(1).max(256),stateKey:pt.string().min(1).max(256),documentKey:pt.string().min(1).max(256),documentHash:pt.string().regex(/^[a-f0-9]{64}$/),compositionKey:pt.string().min(1).max(256),entryMode:pt.enum(["hard","soft"]),match:pt.strictObject({present:pt.array(pt.number().int().min(0)),absent:pt.array(pt.number().int().min(0))})});import{z as Mr}from"zod";var BS=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],Gc="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",VS=Mr.string().regex(new RegExp(`^${Gc}/${Gc}/${Gc}/manifest\\.json$`)),lf=Mr.strictObject({kind:Mr.literal("gcs-resumable"),url:Mr.url(),bucket:Mr.enum(BS),objectKey:VS,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 ht=M.string().min(1).max(256),ln=M.string().regex(/^[a-f0-9]{64}$/),Ba=M.strictObject({versionId:M.uuid(),manifestDigest:ln,sourceGraphDigest:ln,pageKey:ht,stateKey:ht,documentKey:ht,documentHash:ln,elementKey:ht.optional(),nodeId:ht.optional(),contentHash:ln.optional(),renderKey:ht.optional()}),df=M.strictObject({pageKey:ht,documentKey:ht,expectedDocumentHash:ln,renderKey:ht.optional(),nodeId:ht,elementKey:ht,expectedContentHash:ln,property:M.enum(["text","fontSize","color"]),value:M.union([M.string().max(4e3),M.number().finite()])}),pf=M.strictObject({versionId:M.uuid(),manifestDigest:ln,sourceGraphDigest:ln,pageKey:ht,stateKey:ht,documentKey:ht,documentHash:ln,renderKey:ht.optional(),patches:M.array(df.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),LS=/^[a-z][a-z0-9-]{0,39}$/,go=M.string().regex(LS),Hc=M.enum(["web","ios","android"]),b1=M.discriminatedUnion("action",[M.strictObject({action:M.literal("register"),requestId:M.uuid(),client:go,platform:Hc,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:ht,changesetId:M.uuid().nullable(),expectedRevision:ln.nullable(),editorUrl:M.string().url().max(2048),patches:M.array(df).max(200)})]),Qc=M.strictObject({id:M.uuid(),projectId:M.uuid(),environmentId:M.uuid(),clientKey:go,platform:Hc,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())}),zS=M.strictObject({key:go,platform:Hc,currentId:M.uuid().nullable()}),x1=M.strictObject({rows:M.array(Qc).max(100),nextCursor:M.uuid().nullable(),clients:M.array(zS).max(20)}),Kc=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()}),S1=M.strictObject({asOf:M.iso.datetime({offset:!0}),reclamation:M.literal("manual-review-required"),buckets:M.strictObject({source:Kc,runtime:Kc,previews:Kc})}),I1=M.strictObject({version:Qc,actorId:M.uuid(),claims:M.record(M.string(),M.json())}),v1=M.strictObject({version:Qc,upload:lf.nullable()}),w1=M.object({format:M.literal("indiana-route-state-index"),schemaVersion:M.literal(3),routes:M.array(M.object({routeKey:ht,path:M.string(),documentKey:ht,documentHash:ln,initialStateKey:ht,initialRenderKey:ht})),renders:M.array(uf)}).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"})}),O1=M.strictObject({rows:M.array(M.object({id:M.uuid(),name:M.string(),status:M.string(),variations:M.array(M.object({id:ht,key:ht,name:M.string().optional()}).loose())}).loose()),limited:M.boolean()}),P1=M.strictObject({enabled:M.boolean(),allowedOrigins:M.array(M.string())});import{z as Oi}from"zod";var mf=Oi.strictObject({id:Oi.uuid(),name:Oi.string().trim().min(1).max(80),client:go,source:Ba,event:Oi.enum(["screen_enter","button_click"]),cooldownSeconds:Oi.number().int().min(0).max(2592e3),behavior:Oi.literal("observe")}).superRefine((e,t)=>{e.event==="button_click"&&(!e.source.nodeId||!e.source.elementKey)&&t.addIssue({code:"custom",path:["source"],message:"Choose a uniquely bound button"})});import{z as Ge}from"zod";var Jc=ve,$S=["parameters","answers","results","variables"];function Zc(e){return $S.some(t=>e===t||e.startsWith(t+"."))}function Wc(e){let t={};for(let[r,i]of Object.entries(Sa(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])=>!Zc(r))),variables:t}}import{z as yt}from"zod";var Va=yt.discriminatedUnion("kind",[yt.object({kind:yt.literal("ledger"),cursor:fa}).strict(),yt.object({kind:yt.literal("billing"),cursor:yt.uuid()}).strict()]),GS=yt.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ar=yt.record(yt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),yt.union([yt.string().max(500),yt.boolean(),yt.array(yt.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),KS=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function Yc(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>Yc(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||KS.test(n)||Yc(r,t+1)))}var HS=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,sr=yt.record(GS,ve).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!Yc(e)&&!HS.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var ff=yt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),La=yt.array(yt.object({variable:ff,componentId:ff,required:yt.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"),q1=yt.object({bindings:La,answers:ar,values:yt.record(yt.string(),ve).optional()}).strict();import{z as QS}from"zod";var za=QS.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var Xc=Ge.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),gf=Ge.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),hf=sr.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),eu=Ge.record(Xc,Ge.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),JS=Dn,yf=Ge.strictObject({type:Ge.literal("external_task"),endpointId:Ge.uuid(),taskKey:Xc,inputs:Ge.record(Xc,JS).refine(e=>Object.keys(e).length<=20),outputs:eu}),Af=Ge.strictObject({maxAttempts:Ge.number().int().min(1).max(5),retryDelaySeconds:Ge.number().int().min(1).max(30),backoff:Ge.enum(["fixed","exponential"]),requestTimeoutSeconds:Ge.number().int().min(1).max(10),timeoutSeconds:Ge.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var Q1=Ge.strictObject({outcome:Ge.enum(["success","failure"]),data:hf});var J1=Ge.discriminatedUnion("operation",[Ge.strictObject({operation:Ge.literal("signal"),runId:Ge.uuid(),nodeId:gf,eventName:za,eventId:Ge.uuid(),data:hf}),Ge.strictObject({operation:Ge.literal("read_results"),runId:Ge.uuid()})]),Z1=Ge.strictObject({scope:Te,runId:Ge.uuid(),eventId:Ge.uuid(),accepted:Ge.boolean()}),ZS=Ge.record(gf,Jc),W1=Ge.strictObject({scope:Te,runId:Ge.uuid(),results:ZS});var En={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},bf="00000000-0000-0000-0000-000000000000";import{z as Z}from"zod";import{z as We}from"zod";var rE=We.enum(["local","remote"]),tu=We.strictObject({port:We.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:ve.optional(),sticky:We.array(We.strictObject({expected:$i.nullable(),next:$i})).max(100),exposures:We.array(ve).max(100),features:We.array(ve).max(100)}),xf=We.strictObject({type:We.literal("evaluate"),receiptId:We.uuid(),environmentId:We.uuid(),policyRevision:We.number().int().nonnegative(),attributes:vt,sticky:We.record(We.string(),$i)}),Sf=xf.extend({runId:We.uuid(),versionId:We.uuid(),nodeId:We.string().min(1).max(64),visit:We.number().int().nonnegative(),revision:We.number().int().nonnegative()}),nu=xf.omit({type:!0,receiptId:!0}).extend({type:We.literal("evaluate_segment")}),If=We.strictObject({nodeId:We.string().min(1).max(64),result:tu}),vf=nu.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:sr,answers:ar,variables:We.record(We.string(),ve)});import{z as ue}from"zod";var ru=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"),$a=ue.intersection(vt,ue.looseObject({tags:ru.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),Ga=ue.string().trim().max(80),Ka=ue.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),Ha=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"),wf=ue.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),Of=ue.object({externalUserId:wf.optional(),name:Ga.default(""),email:Ha.default(""),phone:Ka.optional(),attributes:$a.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),qr=ue.discriminatedUnion("type",[ue.strictObject({type:ue.literal("id"),value:ue.uuid()}),ue.strictObject({type:ue.literal("externalUserId"),value:wf})]),Pi=ue.strictObject({name:Ga.optional(),email:Ha.optional(),phone:Ka.optional(),attributes:$a.optional(),fingerprint:Qa.optional()}),Ja=e=>!e.customerData||e.customer?.type==="externalUserId",Za="customerData requires an externalUserId customer",Ci=ue.object({id:ue.uuid(),externalUserId:ue.string().min(1).max(255).nullable(),name:Ga,email:Ha,phone:Ka.optional(),attributes:$a,createdAt:ue.iso.datetime()}).strict(),Pf=ue.object({customer:Ci,changed:ue.boolean(),replayed:ue.boolean()}).strict(),WS=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()]),YS=ue.object({name:Ga.optional(),email:Ha.optional(),phone:Ka.optional(),attributes:$a.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:ru,remove:ru}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),iu=ue.object({lookup:WS}).strict(),Cf=iu.extend({requestId:ue.uuid(),patch:YS}).strict(),_f=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(),Ef=ue.object({customers:Ci.array(),hasMore:ue.boolean(),total:ue.number().int().nonnegative().nullable(),evaluatedAt:ue.iso.datetime()}).strict();var ho=Z.discriminatedUnion("type",[Z.strictObject({type:Z.literal("literal"),value:ve}),Z.strictObject({type:Z.literal("variable"),key:St,path:_n.optional()}),Z.strictObject({type:Z.literal("feature"),featureKey:Z.string().min(1).max(128)})]),XS=Z.strictObject({requestId:Z.uuid(),decisionId:Z.uuid(),customerId:Z.uuid(),externalUserId:Z.string().min(1).max(255).nullable(),versionId:Z.uuid(),receiptId:Z.uuid(),value:ve}),e0={funnelId:Z.uuid(),requestId:Z.uuid(),customer:qr,customerData:Pi.optional(),attributes:vt.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},gE=Z.discriminatedUnion("operation",[Z.strictObject({operation:Z.literal("decide"),...e0}).refine(Ja,Za),Z.strictObject({operation:Z.literal("read_decision"),decisionId:Z.uuid()}),Z.strictObject({operation:Z.literal("evaluate_decision"),decisionId:Z.uuid(),requestId:Z.uuid(),nodeId:Z.string().min(1).max(64),visit:Z.number().int().nonnegative(),revision:Z.number().int().nonnegative(),receiptId:Z.uuid(),policyRevision:Z.number().int().nonnegative(),generation:Z.string().min(1).max(256),result:tu}),Z.strictObject({operation:Z.literal("feature_config"),funnelId:Z.uuid()}),Z.strictObject({operation:Z.literal("commit_decision_segment"),decisionId:Z.uuid(),requestId:Z.uuid(),nodeId:Z.string().min(1).max(64),visit:Z.number().int().nonnegative(),revision:Z.number().int().nonnegative(),policyRevision:Z.number().int().nonnegative(),generation:Z.string().min(1).max(256),steps:Z.array(If).max(32),boundary:Z.strictObject({nodeId:Z.string().min(1).max(64),visit:Z.number().int().nonnegative()}).optional()}),Z.strictObject({operation:Z.literal("segment_configuration"),funnelId:Z.uuid(),versionId:Z.uuid()}),Z.strictObject({operation:Z.literal("configuration"),funnelId:Z.uuid(),versionId:Z.uuid().optional()}),Z.strictObject({operation:Z.literal("local_configuration"),funnelId:Z.uuid()}),Z.strictObject({operation:Z.literal("report_used"),decisionId:Z.uuid(),eventId:Z.uuid(),occurredAt:Z.iso.datetime({offset:!0}),reference:Z.string().min(1).max(128).optional()})]),hE=Z.strictObject({scope:Te,decisionId:Z.uuid(),requestId:Z.uuid(),status:Z.enum(["pending","completed","failed"]),decision:XS.nullable(),evaluation:Z.discriminatedUnion("type",[Sf,vf]).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"),yE=Z.strictObject({scope:Te,decisionId:Z.uuid(),eventId:Z.uuid(),source:Z.literal("caller_reported")});import{z as Mt}from"zod";var Rf=Mt.strictObject({type:Mt.literal("bundle"),paywall:Dn.optional(),offering:Dn.optional(),coupons:Dn,data:Dn}),t0=e=>Mt.strictObject({type:Mt.literal(e),id:Mt.uuid()}),vE=Mt.strictObject({type:Mt.literal("bundle"),paywallVersionId:Mt.uuid().optional(),offeringVersionId:Mt.uuid().optional(),couponIds:Mt.array(Mt.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:ve});var wE=Mt.strictObject({type:Mt.literal("bundle"),offering:t0("offering_version").nullable(),paywall:Mt.strictObject({versionId:Mt.uuid(),paywallId:Mt.uuid(),offeringVersionId:Mt.uuid()}).nullable(),coupons:Mt.array(Gi).max(20),data:ve});import{z as Rn}from"zod";import{z as yn}from"zod";var kf=yn.union([yn.string(),yn.number().finite(),yn.boolean(),yn.null()]),n0=yn.union([kf,yn.array(kf).min(1).max(20)]),r0=yn.record(_n,n0).refine(e=>Object.keys(e).length<=10),jf=yn.strictObject({path:_n,type:yn.enum(["string","number","boolean","strings"]),nullable:yn.boolean().optional(),aggregation:yn.enum(["count","exists"]).optional(),where:r0.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 i0=["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"],Tf=Rn.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),o0=Dn,Nf=Rn.discriminatedUnion("type",[yf,Rn.strictObject({type:Rn.literal("claim_offer"),coupon:Dn}),Rn.strictObject({type:Rn.literal("event"),event:Tf}),Rn.strictObject({type:Rn.literal("api"),operation:Rn.enum(i0),inputs:Rn.record(_n,o0).refine(e=>Object.keys(e).length<=40),outputs:Rn.record(Tf,jf).refine(e=>Object.keys(e).length<=20)})]);var ct=za,a0=Q.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),dn={id:ct,name:Q.string().trim().min(1).max(80),position:Q.strictObject({x:Q.number().finite(),y:Q.number().finite()}).optional()},s0={success:ct,cancel:ct,unavailable:ct,failure:ct},ou=Q.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),au=Q.enum(["same_window","new_window"]),c0=Q.discriminatedUnion("type",[Q.strictObject({...dn,type:Q.literal("entry"),next:ct,triggers:Q.array(mf).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),Q.strictObject({...dn,type:Q.literal("screen"),screenId:ct,presentation:On,outputs:Q.record(ct,ct),offering:Q.discriminatedUnion("source",[Q.strictObject({source:Q.literal("variable"),key:St}),Q.strictObject({source:Q.literal("fixed"),versionId:Q.uuid()})]).optional()}),Q.strictObject({...dn,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:St}),next:ct}),Q.strictObject({...dn,type:Q.literal("coupon"),couponId:Q.uuid(),writes:Q.strictObject({value:St}),next:ct}),Q.strictObject({...dn,type:Q.literal("coupons"),couponIds:Q.array(Q.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:Q.strictObject({value:St}),next:ct}),Q.strictObject({...dn,type:Q.literal("output"),value:Q.discriminatedUnion("type",[...ho.options,Rf,Q.strictObject({type:Q.literal("selection"),screenId:ct,offeringKey:St})])}),Q.strictObject({...dn,type:Q.literal("condition"),cases:Q.array(Q.strictObject({condition:Yt,target:ct})).min(1).max(50),default:ct}),Q.strictObject({...dn,type:Q.literal("feature"),featureKey:Q.string().min(1).max(128),writes:Q.strictObject({value:St}),next:ct}),Q.strictObject({...dn,type:Q.literal("split"),experimentId:Q.uuid(),applyPageExperiment:Q.literal(!0).optional(),routes:Q.record(a0,ct).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:ct}),Q.strictObject({...dn,type:Q.literal("action"),...s0,execution:Af,action:Nf,writes:Ic.optional()}),Q.strictObject({...dn,type:Q.literal("external_page"),appManifest:Ba.optional(),url:ou,openIn:au,opened:ct,failed:ct}),Q.strictObject({...dn,type:Q.literal("end"),outcome:Q.enum(["completed","closed","ineligible","failed"]),output:ho.optional()}),Q.strictObject({...dn,type:Q.literal("wait"),writes:Ic.optional(),wait:Q.discriminatedUnion("type",[Q.strictObject({type:Q.literal("duration"),delaySeconds:Q.number().int().min(1).max(2592e3),elapsed:ct}),Q.strictObject({type:Q.literal("event"),eventName:ct,outputs:eu,timeoutSeconds:Q.number().int().min(1).max(2592e3),received:ct,timeout:ct})])})]),su=Q.strictObject({version:Q.literal(5),entry:ct,nodes:Q.array(c0).min(1).max(En.flowNodes)}),cu=su.superRefine((e,t)=>{u0(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function Wa(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 u0(e,t){let n=[],r=new Map(e.nodes.map(l=>[l.id,l])),i=(l,m,f)=>{n.push(l),t?.({message:l,reason:m,path:f?["nodes",e.nodes.indexOf(f)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(l=>l.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(l=>l.type==="screen").length>En.pages||e.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>En.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let l of e.nodes){for(let m of Wa(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 Wa(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 uu={maxTransitions:1e4,runTimeoutSeconds:2592e3};function Df(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 er(c.condition))u.startsWith("variables.")&&a(u.slice(10),!0)}if(e.type==="screen"&&e.offering?.source==="variable"&&a(e.offering.key),e.type==="action"&&(e.action.type==="api"||e.action.type==="external_task"))for(let s of Object.values(e.action.inputs))s.source==="variable"&&a(s.key);e.type==="action"&&e.action.type==="claim_offer"&&e.action.coupon.source==="variable"&&a(e.action.coupon.key);let o=e.type==="output"?e.value:e.type==="end"?e.output:null;if(o?.type==="variable"&&a(o.key),o?.type==="bundle")for(let s of[o.paywall,o.offering,o.coupons,o.data])s?.source==="variable"&&a(s.key);return o?.type==="selection"&&a(o.offeringKey),[...i]}import{z as q}from"zod";var _i=q.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Ya=e=>q.record(q.string(),ve).refine(t=>un(t)<=e,"Funnel evidence exceeds its byte budget"),tR=q.enum(["local_segment","evaluation","presentation","timer","event","operation"]),du=q.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),pu=q.discriminatedUnion("type",[q.strictObject({type:q.literal("flag"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("experiment"),id:q.uuid()}),q.strictObject({type:q.literal("saved_group"),id:q.uuid()}),q.strictObject({type:q.literal("config"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("constant"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("paywall_version"),id:q.uuid()}),q.strictObject({type:q.literal("offering_version"),id:q.uuid()}),q.strictObject({type:q.literal("reward"),id:q.uuid()})]),yo=q.strictObject({schemaVersion:q.literal(1),kind:du,selector:pu.nullable(),context:Ya(131072),contract:q.strictObject({version:q.number().int().positive(),evaluator:q.string().min(1).max(128),policyRevision:q.number().int().nonnegative()})}).refine(e=>un(e)<=131072,"Node input exceeds its byte budget"),Ff=q.strictObject({schemaVersion:q.literal(1),kind:du,outcome:q.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:Ya(131072),route:q.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:Ya(131072)}).refine(e=>un(e)<=131072,"Node result exceeds its byte budget"),nR=q.strictObject({schemaVersion:q.literal(1),operations:q.record(_i,q.strictObject({attempts:q.number().int().nonnegative(),maxAttempts:q.number().int().min(1).max(5),deadlineAt:q.iso.datetime({offset:!0}),retryAt:q.iso.datetime({offset:!0}).nullable(),error:q.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:q.strictObject({type:_i,id:q.uuid()}).nullable()}))}).refine(e=>un(e)<=65536,"Execution state exceeds its byte budget"),Ur={receiptId:q.uuid()},lu=q.iso.datetime({offset:!0}),rR=q.discriminatedUnion("type",[q.strictObject({type:q.literal("node_entered"),details:q.strictObject({kind:du})}),q.strictObject({type:q.literal("presentation_shown"),details:q.strictObject({...Ur,source:q.literal("client"),occurredAt:lu.optional()})}),q.strictObject({type:q.literal("decision_accepted"),details:q.strictObject(Ur)}),q.strictObject({type:q.literal("signal_received"),details:q.strictObject({signalId:q.uuid(),nodeId:_i,eventName:_i,data:Ya(8192),source:q.literal("server"),occurredAt:lu})}),q.strictObject({type:q.literal("signal_consumed"),details:q.strictObject({...Ur,signalId:q.uuid()})}),q.strictObject({type:q.literal("wait_elapsed"),details:q.strictObject(Ur)}),q.strictObject({type:q.literal("wait_timeout"),details:q.strictObject(Ur)}),q.strictObject({type:q.literal("operation_completed"),details:q.strictObject({...Ur,operation:_i,reference:q.strictObject({type:_i,id:q.uuid()}).nullable()})}),q.strictObject({type:q.literal("execution_recovered"),details:q.strictObject({generation:q.number().int().positive(),reason:q.enum(["interrupted","expired_lease","delivery_failed"])})}),q.strictObject({type:q.literal("execution_failed"),details:q.strictObject({generation:q.number().int().positive(),code:q.string().regex(/^[a-z_]{1,64}$/)})}),q.strictObject({type:q.literal("run_completed"),details:q.strictObject({outcome:q.enum(["completed","ineligible","failed"])})}),q.strictObject({type:q.literal("run_closed"),details:q.strictObject({source:q.enum(["client","server","expiry"])})}),q.strictObject({type:q.literal("treatment_used"),details:q.strictObject({...Ur,source:q.enum(["client","server"]),occurredAt:lu,reference:q.string().min(1).max(128).optional()})})]);var An=z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),l0=z.discriminatedUnion("type",[z.strictObject({id:An,type:z.literal("owned"),publicData:Ym.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")}),z.strictObject({id:An,type:z.literal("paywall"),paywallVersionId:z.uuid()})]),mu={executionContract:of.optional(),kind:z.literal("funnel"),schemaVersion:z.literal(4),screens:z.array(l0).max(En.pages),references:z.record(An,pu).refine(e=>Object.keys(e).length<=500),inputs:z.array(z.strictObject({variable:An,screenId:An,componentId:An,required:z.boolean()})).max(En.questions),variables:z.record(St,mi).refine(e=>Object.keys(e).length<=En.logicNodes),outputSchema:pi,execution:z.strictObject({runTimeoutSeconds:z.number().int().min(1).max(uu.runTimeoutSeconds),maxTransitions:z.number().int().min(1).max(uu.maxTransitions)})},vR=z.strictObject({...mu,graph:su});function d0(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 es(e){return Array.isArray(e)?e.some(es):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===bf:es(n))}function p0(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=cf(i.document)}catch(o){t.push({message:o instanceof Error?o.message:"Screen cannot be delivered",reason:"screen",path:["screens",r,"document"]});continue}for(let[o,s]of e.inputs.entries())s.screenId===i.id&&!co(a,s.componentId)&&t.push({message:`Local Funnel input ${s.variable} targets hidden component ${s.componentId} on screen ${s.screenId}`,reason:"inputBinding",path:["inputs",o]})}for(let[r,i]of e.graph.nodes.entries()){let a=["graph","nodes",r],o=i.type==="screen"?e.screens.find(s=>s.id===i.screenId):void 0;o?.type==="owned"&&(o.document.actions.some(s=>typeof s.properties.templateKey=="string"&&s.properties.templateKey.startsWith("popup-coupon-"))&&t.push({message:"Funnel screens claim Coupons through a Claim Coupon step",reason:"coupon",path:a}),d0(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"&&es(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&es(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function Mf(e,t){for(let{message:n,reason:r,path:i}of p0(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function qf(e,t){let n=(g,d,h=[])=>t.addIssue({code:"custom",message:g,path:h,params:{reason:d}}),r=Object.values(e.references),i=new Map(e.screens.map(g=>[g.id,g])),a=(g,d)=>r.some(h=>h.type===g&&("id"in h?h.id:h.key)===d);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let o=e.graph.nodes.filter(g=>g.type==="screen");(o.length!==i.size||o.some(g=>!i.has(g.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(g=>c.some(d=>g!==d&&d.startsWith(g+".")))&&n("Variable paths must not overlap","variable");function u(g,d){Object.hasOwn(e.variables,g)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(d)]);let h=s.get(g)??new Set;h.add(d.id),s.set(g,h)}for(let[g,d]of e.graph.nodes.entries()){let h=["graph","nodes",g],R=d.type==="feature"?d.featureKey:d.type==="offering"&&d.configuration.source==="feature"?d.configuration.featureKey:d.type==="output"&&d.value.type==="feature"?d.value.featureKey:d.type==="end"&&d.output?.type==="feature"?d.output.featureKey:null;R&&!a("flag",R)&&n("Flag selectors require an explicit GB resource reference","feature",h);let y=d.type==="feature"||d.type==="offering"||d.type==="coupon"||d.type==="coupons"||d.type==="action"&&d.action.type==="api"?["value"]:d.type==="action"&&d.action.type==="external_task"?Object.keys(d.action.outputs):d.type==="wait"&&d.wait.type==="event"?Object.keys(d.wait.outputs):[],A="writes"in d?d.writes??{}:{};(y.length!==Object.keys(A).length||y.some(v=>!Object.hasOwn(A,v))||new Set(Object.values(A)).size!==Object.values(A).length)&&n("Node writes must map every named output exactly once","variable",h);for(let[v,P]of Object.entries(A)){u(P,d);let j=e.variables[P],_=d.type==="offering"?"offering_version":d.type==="coupon"?"reward":d.type==="action"&&d.action.type==="api"?"json":d.type==="action"&&d.action.type==="external_task"?d.action.outputs[v]:d.type==="wait"&&d.wait.type==="event"?d.wait.outputs[v]:void 0;(j?.source.type!=="node"||_&&j.type!==_)&&n("Node writer source or output type does not match declaration","variable",h)}if(d.type==="coupons"){let v=e.variables[d.writes.value];(v?.type!=="array"||v.items?.type!=="reward"||v.items.nullable||v.nullable)&&n("Coupons output requires a non-null Reward array","variable",h);for(let P of d.couponIds)a("reward",P)||n("Coupons require Reward references","coupon",h)}if(d.type==="split"&&!a("experiment",d.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",h),d.type==="coupon"&&!a("reward",d.couponId)&&n("Coupon selectors require a Reward reference","coupon",h),d.type==="action"&&d.action.type==="claim_offer"&&d.action.coupon.source==="literal"){let v=d.action.coupon.value;(!v||typeof v!="object"||Array.isArray(v)||v.type!=="reward"||typeof v.id!="string"||Object.keys(v).length!==2||!a("reward",v.id))&&n("Coupon claims require a Reward reference","coupon",h)}if(d.type==="offering"&&d.configuration.source==="fixed"&&!a("offering_version",d.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",h),d.type==="screen"&&d.offering?.source==="variable"&&e.variables[d.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",h),d.type==="action"&&d.action.type==="claim_offer"&&d.action.coupon.source==="variable"&&(e.variables[d.action.coupon.key]?.type!=="reward"||d.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",h),d.type==="screen"){let v=i.get(d.screenId);if(d.offering?.source==="fixed"&&!a("offering_version",d.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",h),v?.type==="paywall"&&d.offering&&n("Paywall owns its fixed Offering Version","offering",h),v?.type==="paywall"&&!a("paywall_version",v.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",h),v?.type==="owned"){let P=v.document.pages[0];if(!P){n("Owned screen requires a page","screen",h);continue}ir(v.document).some(_=>!_.complete)&&n("Owned screens require complete local content","translations",h);let j=new Set(v.document.actions.map(_=>_.id));(j.size!==Object.keys(d.outputs).length||Object.keys(d.outputs).some(_=>!j.has(_)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",h),Jn(P.root,_=>{!d.offering&&(_.type==="plan_picker"||(_.type==="stack"||_.type==="button")&&_.bind?.plan||_.type==="customer_data"&&["customer_plans","credit_packs"].includes(_.data.source))&&n("Product presentation requires an Offering Version","offering",h),_.type==="customer_data"&&Object.values(_.data.outputs??{}).some(X=>X!==void 0&&!j.has(X))&&n("Customer components require declared screen outcomes","componentOutput",h)})}}d.type==="end"&&["completed","ineligible"].includes(d.outcome)&&!d.output&&n("Completed and ineligible ends require a declared output","output",h),d.type==="end"&&d.output?.type==="literal"&&!gn(e.outputSchema,d.output.value)&&n("Terminal output does not match outputSchema","output",h),d.type==="output"&&d.value.type==="literal"&&!gn(e.outputSchema,d.value.value)&&n("Terminal output does not match outputSchema","output",h);let x=d.type==="output"?d.value:d.type==="end"?d.output:void 0;if(x?.type==="variable"&&!x.path){let v=e.variables[x.key];v&&!vc(v,e.outputSchema)&&n("Variable output does not match outputSchema","output",h)}if(d.type==="screen"){let v=i.get(d.screenId);if(v?.type==="owned")for(let P of Pc(v.document))(/^(input|params)\./.test(P)||P.startsWith("variables.")&&!Oc(P.slice(10),c))&&n("Screen values must reference registered variables","variable",h)}if(d.type==="condition")for(let v of d.cases){for(let P of Kn(v.condition))a("saved_group",P)||n("Conditions require explicit Saved Group references","savedGroup",h);for(let P of er(v.condition))P.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",h)}if(d.type==="output"&&d.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",h);for(let[v,P]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let j=d.value[v];if(j)if(j.source==="literal"){let _=v==="coupons"?j.value:[j.value];(!Array.isArray(_)||_.length>20||_.some(X=>!gn({type:P,nullable:!1},X)||!a(P,X.id))||v==="coupons"&&new Set(_.map(X=>X.id)).size!==_.length)&&n("Bundle requires distinct scoped resource references",v==="coupons"?"coupon":v==="paywall"?"paywall":"offering",[...h,"value",v])}else{let _=e.variables[j.key];(j.path||!_||_.nullable||(v==="coupons"?_.type!=="array"||_.items?.type!=="reward"||_.items.nullable:_.type!==P))&&n("Bundle binding type does not match its slot","output",h)}}}}for(let[g,d]of e.graph.nodes.entries()){let h=d.type==="screen"?i.get(d.screenId):void 0,R=[...Df(d,c),...h?.type==="owned"?Ia(h.document).map(y=>Oc(y,c)?.key??y):[]];for(let y of new Set(R)){let P=function(j){if(j===d.id)return!0;if(v.has(j))return!1;v.add(j);let _=e.graph.nodes.find(le=>le.id===j);return _?(x.has(j)?_.type==="action"?[_.cancel,_.unavailable,_.failure]:_.type==="wait"&&_.wait.type==="event"?[_.wait.timeout]:[]:Wa(_)).some(P):!1};var f=P;if(!Object.hasOwn(e.variables,y)){n("Consumed variable is undeclared","variable",["graph","nodes",g]);continue}let A=e.variables[y];if(d.type==="screen"&&A.source.type==="input"&&e.inputs.some(j=>j.screenId===d.screenId&&j.variable===y)||A.source.type==="parameter"||A.source.type==="attribute")continue;let x=A.source.type==="input"?new Set(e.inputs.filter(j=>j.variable===y&&j.required).flatMap(j=>o.filter(_=>_.screenId===j.screenId).map(_=>_.id))):s.get(y)??new Set,v=new Set;(!x.size||P(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",g])}}(new Set(e.inputs.map(g=>g.variable)).size!==e.inputs.length||new Set(e.inputs.map(g=>`${g.screenId}:${g.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[g,d]of e.inputs.entries()){e.variables[d.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",g]);let h=i.get(d.screenId),R=h?.type==="owned"?co(h.document,d.componentId):null;if((R?.type!=="stack"||!R.interaction||!["input","toggle","select","multiselect","tabs"].includes(R.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",g]),R?.type==="stack"&&R.interaction){let y=R.interaction.type==="toggle"?"boolean":R.interaction.type==="multiselect"?"strings":"string";e.variables[d.variable]?.type!==y&&n("Input variable type does not match component","inputBinding",["inputs",g]);let A=e.variables[d.variable]?.enum;A&&!R.children.filter(x=>!x.hidden).every(x=>A.includes(x.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",g])}}for(let[g,d]of Object.entries(e.variables))d.enum&&d.type!=="string"&&n("Only string variables support enum","variable",["variables",g]),d.source.type==="input"&&!e.inputs.some(h=>h.variable===g)&&n("Input variable requires a component binding","inputBinding",["variables",g]);let l=0,m=0;for(let g of e.screens)if(g.type==="owned"){for(let d of g.document.pages)Jn(d.root,()=>{l++});m+=g.document.actions.length}(l>En.components||m>En.actions||un(e)>En.documentBytes)&&n("Funnel document exceeds its budget","budget")}var m0=z.strictObject({...mu,graph:cu}).superRefine(qf),Ei=z.strictObject({...mu,graph:cu,displayName:z.string().trim().min(1).max(80)}).superRefine(qf),wR=Ei.superRefine(Mf),OR=m0.superRefine(Mf),Xa=z.string().regex(kt),Ao={requestId:z.uuid(),nodeId:An,visit:z.number().int().nonnegative(),revision:z.number().int().nonnegative(),customerToken:Xa.optional()},f0=z.discriminatedUnion("type",[z.strictObject({type:z.literal("screen"),output:An,answers:ar,selection:z.record(An,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:An,productVersionId:z.uuid(),offerId:z.uuid().optional(),nativeOffer:hi.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"])})]),g0=z.object({nodeId:An,visit:z.number().int().nonnegative(),revision:z.number().int().nonnegative(),components:z.record(An,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(),wt=z.discriminatedUnion("operation",[z.strictObject({operation:z.literal("start"),funnelId:z.uuid(),requestId:z.uuid(),customer:qr.optional(),customerData:Pi.optional(),locale:z.string().min(1).max(35),parameters:sr}).refine(Ja,Za),z.strictObject({operation:z.literal("get"),settlementRequestId:z.uuid().optional(),data:g0.optional(),purchase:z.strictObject({receiptId:z.uuid(),operationId:z.uuid()}).optional(),customerToken:Xa.optional()}),z.strictObject({operation:z.literal("resume"),requestId:z.uuid(),customerToken:Xa.optional()}),z.strictObject({operation:z.literal("submit"),...Ao,input:f0}),z.strictObject({operation:z.literal("back"),...Ao}),z.strictObject({operation:z.literal("shown"),...Ao}),z.strictObject({operation:z.literal("close"),...Ao}),z.strictObject({operation:z.literal("commit_segment"),...Ao,policyRevision:z.number().int().nonnegative(),generation:z.string().min(1).max(256)}),z.strictObject({operation:z.literal("review"),receiptId:z.uuid().optional(),customerToken:Xa.optional()})]);function ts(e,t){let n=new Set,r=new Set,i=new Set,a=[],o=new Map,s=new Map,c=new Map;function u(d){for(let h of Kn(d))l(h)}function l(d){if(i.has(d)||!Object.hasOwn(t.savedGroups,d))return;let h=t.savedGroups[d];h&&(i.add(d),c.set(d,h),a.push(()=>{!Array.isArray(h)&&h.type==="condition"&&u(h.condition)}))}function m(d){for(let h of["hashAttribute","fallbackAttribute"])if(d[h]!==void 0&&Zc(d[h]))throw new Error(`Funnel GB ${h} uses a reserved flow namespace`);u(d.condition);for(let h of d.parentConditions??[])f(h.id),u(h.condition)}function f(d,h=!1){let R=Object.hasOwn(t.features,d)?t.features[d]:void 0;if(!R){if(h)throw new Error("Required GB Feature is unavailable");return}n.has(d)||(n.add(d),o.set(d,R),a.push(()=>{for(let y of R.rules??[]){m(y);for(let A of y.tracks??[])m(A.experiment)}}))}function g(d){let h=Object.hasOwn(t.experiments,d)?t.experiments[d]:void 0;if(!h)throw new Error("Required GB Experiment is unavailable");r.has(d)||(r.add(d),s.set(d,h),a.push(()=>m(h)))}for(let d of e.graph.nodes){d.type==="feature"&&f(d.featureKey,!0),d.type==="split"&&g(d.experimentId),d.type==="condition"&&d.cases.forEach(R=>u(R.condition)),d.type==="offering"&&d.configuration.source==="feature"&&f(d.configuration.featureKey,!0);let h=d.type==="output"?d.value:d.type==="end"?d.output:null;h?.type==="feature"&&f(h.featureKey,!0)}for(let d of a)d();return{...t,features:Object.fromEntries(o),experiments:Object.fromEntries(s),savedGroups:Object.fromEntries(c)}}import{z as ae}from"zod";function Uf(e,t){let n=[],r={};Gt(e,i=>{if(i.hidden)return!1;if(i.type!=="quantity_picker")return;let a=i.bind?.plan?[i.bind.plan]:[];i.bind?.picker&&Gt(e,o=>{if(o.type==="plan_picker"&&o.id===i.bind?.picker&&a.push(...o.planIds??[]),o.type==="stack"&&o.interaction?.type==="select"&&o.interaction.pickerId===i.bind?.picker)for(let s of o.children)s.type==="stack"&&s.bind?.plan&&a.push(s.bind.plan)}),a.length||n.push(`Quantity control ${i.id} needs a Product binding`);for(let o of new Set(a)){let s=t[o]?.prepaid?.find(u=>u.internalFeatureId===i.internalFeatureId)?.terms,c=r[o]??(r[o]=new Set);(!s||c.has(i.internalFeatureId)||i.minimumQuantity<s.minimumQuantity||i.maximumQuantity>s.maximumQuantity)&&n.push(`Quantity control ${i.id} must match its Product's prepaid Feature and bounds`),c.add(i.internalFeatureId)}});for(let[i,a]of Object.entries(t))for(let o of a.prepaid??[])r[i]?.has(o.internalFeatureId)||n.push(`Product ${i} needs a quantity control for ${o.internalFeatureId}`);return n}function Bf(e,t,n,r){let i=r.plans[t];if(!i?.available)throw new Error("Selected Product is unavailable");let a={};if(Gt(e,o=>{if(o.hidden)return!1;if(o.type!=="quantity_picker"||o.hidden||(o.bind?.plan??(o.bind?.picker?n[o.bind.picker]:void 0))!==t)return;let c=i.prepaid?.find(l=>l.internalFeatureId===o.internalFeatureId)?.terms,u=n[o.id];if(!c||typeof u!="number"||!Number.isSafeInteger(u)||u<Math.max(c.minimumQuantity,o.minimumQuantity)||u>Math.min(c.maximumQuantity,o.maximumQuantity)||(u-o.minimumQuantity)%o.step!==0||a[o.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");a[o.internalFeatureId]=u}),(i.prepaid??[]).some(o=>a[o.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return a}import{z as bo}from"zod";var Vf=bo.object({defaultLocale:Sn,locales:bo.record(Sn,bo.object({name:bo.string().max(80),description:bo.string().max(500)}).strict())}).strict().superRefine((e,t)=>{let n=Object.keys(e.locales);(!n.length||n.length>20||!e.locales[e.defaultLocale])&&t.addIssue({code:"custom",message:"Invalid content languages"}),new TextEncoder().encode(JSON.stringify(e)).length>5e4&&t.addIssue({code:"custom",message:"Content exceeds 50 KB"})});var h0=["customer_data","coupon_code"],Lf=ae.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),y0=ae.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),ns=(e,t)=>new Set(e.map(t)).size===e.length,A0=ae.strictObject({currency:Ie,amountMinor:ae.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),b0=ae.strictObject({featureId:ae.uuid(),name:ae.string().trim().min(1).max(120),allowance:ae.string().max(40).nullable(),access:ae.boolean()}),x0=ae.strictObject({stripe:ae.strictObject({prices:ae.array(A0).min(1).max(50)}).optional(),apple:ae.strictObject({productIds:ae.array(Lf).min(1).max(10)}).optional(),google:ae.strictObject({products:ae.array(ae.strictObject({productId:Lf,basePlanId:y0.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!ns(e.stripe.prices,n=>n.currency)||e.apple&&!ns(e.apple.productIds,n=>n)||e.google&&!ns(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),S0=ae.strictObject({name:ae.string().trim().min(1).max(80),interval:ae.enum(["free","week","month","year","one_time"]),intervalCount:ae.number().int().min(1).max(100),trial:ae.strictObject({days:ae.number().int().min(1).max(730),cardRequired:ae.boolean()}).nullable(),benefits:ae.array(b0).max(50).refine(e=>ns(e,t=>t.featureId),"Duplicate benefit"),channels:x0,prepaid:ae.array(io).max(100).optional()}),I0=ae.strictObject({digest:vi,content:ae.strictObject({discount:tr,duration:an,appliesTo:oc,displayCopy:Vf.nullable(),firstPurchaseOnly:ae.boolean(),qualificationRequired:ae.boolean(),startsAt:ae.iso.datetime().nullable(),endsAt:ae.iso.datetime().nullable(),grantWindowHours:ae.number().int().positive(),perCustomerLimit:ae.number().int().positive()})}),v0=ae.discriminatedUnion("type",[ae.strictObject({type:ae.literal("checkout"),product:ba}),ae.strictObject({type:ae.literal("close")}),ae.strictObject({type:ae.literal("action"),action:Uc})]),rs=ae.strictObject({kind:ae.literal("paywall"),formatVersion:ae.literal(1),name:ae.string().trim().min(1).max(80),offeringVersionId:ae.uuid(),presentation:On,screen:cn,products:Fa,catalog:ae.record(ae.uuid(),S0),buttons:ae.record(qe,v0),coupons:ae.record(ae.uuid(),I0)}).superRefine((e,t)=>{let n=h=>t.addIssue({code:"custom",message:h}),{screen:r}=e;Uf(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),$c(r,h0).forEach(n),ir(r).some(h=>!h.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,o=new Set;Gt(r,h=>{let R="bind"in h?h.bind:void 0;R?.promotionCode&&n("Promotion codes must not be published"),R?.plan&&i.add(R.plan),R?.coupon&&a.add(R.coupon),h.type==="plan_picker"&&(h.planIds?.forEach(y=>i.add(y)),h.defaultPlan&&i.add(h.defaultPlan)),h.type==="text"&&h.feature&&o.add(h.feature.id)});let s=e.products.items.map(h=>h.productVersionId),c=Object.keys(e.catalog);(s.length!==c.length||s.some(h=>!Object.hasOwn(e.catalog,h)))&&n("Catalog must contain exactly the displayed Products");let u=new Set(s);e.products.defaultProductVersionId!==null&&!u.has(e.products.defaultProductVersionId)&&n("Default Product must be displayed");for(let h of i)u.has(h)||n("Screen references a Product that is not displayed");for(let h of Object.values(e.catalog))!h.channels.stripe&&!h.channels.apple&&!h.channels.google&&n("A displayed Product needs at least one sales channel");let l=new Set(Object.values(e.catalog).flatMap(h=>h.benefits.map(R=>R.featureId)));for(let h of o)l.has(h)||n("Feature text must read a displayed benefit");let m=r.actions.filter(h=>h.type!=="navigate");r.actions.some(h=>h.type!=="event"&&h.type!=="navigate")&&n("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==m.length||m.some(h=>!Object.hasOwn(e.buttons,h.id)))&&n("Buttons must match the screen's actions");let g=!1;for(let h of Object.values(e.buttons)){if(h.type!=="checkout")continue;g=!0,(h.product.type==="fixed"?[h.product.productVersionId]:h.product.allowedProductVersionIds).some(y=>!u.has(y))&&n("Checkout may only sell displayed Products")}g||n("A Paywall needs a checkout button");let d=Object.keys(e.coupons);(d.length!==a.size||d.some(h=>!a.has(h)))&&n("Coupons must be exactly the bound Coupons")}),zf=ae.strictObject({state:ae.enum(["published","archived"]),controlRevision:ae.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:ae.uuid(),versions:ae.record(ae.uuid(),ae.strictObject({version:ae.number().int().positive(),artifact:ae.string().min(1),sourceDigest:ae.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var nn={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},fu=Ee.string().regex(/^[a-f0-9]{64}$/),gu=Ee.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),yu=Te.extend({environmentId:Ee.uuid()}),$f=Ee.strictObject({features:Ee.array(Ee.string()).max(500),experiments:Ee.record(Ee.uuid(),Ee.array(Ee.string()).max(20)),savedGroups:Ee.array(Ee.string()).max(1e3)}),Au=Ee.strictObject({kind:Ee.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:Ee.number().int().positive(),url:Ee.string().min(1).max(2048),sha256:fu,byteLength:Ee.number().int().positive().max(nn.maxArtifactBytes),generation:fu.optional()}),w0=Ee.strictObject({state:Ee.enum(["active","paused","archived"]),controlRevision:gu,evaluationMode:Ee.enum(["local","remote"]),evaluationRevision:gu,currentVersionId:Ee.uuid(),versions:Ee.record(Ee.uuid(),Ee.strictObject({artifact:Ee.string(),dependencies:$f,definitionDigest:vi.optional(),couponDigests:Ee.record(Ee.uuid(),vi).optional()}))}),bu=Ee.strictObject({kind:Ee.literal("sdk_configuration"),schemaVersion:Ee.literal(1),scope:yu,revision:gu,generation:fu,policy:Ee.strictObject({refreshIntervalSeconds:Ee.number().positive().max(15),maxControlAgeSeconds:Ee.number().positive().max(60)}),gb:Ee.strictObject({features:Ee.string().nullable(),pageExperiments:Ee.string().nullable()}),artifacts:Ee.record(Ee.string(),Au),funnels:Ee.record(Ee.uuid(),w0),paywalls:Ee.record(Ee.uuid(),zf).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 Ot(e){if(Array.isArray(e))return`[${e.map(Ot).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)}:${Ot(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function xu(e){return ni(ri(typeof e=="string"?new TextEncoder().encode(e):e))}function Gf(e){return xu(Ot(e))}var hu=class extends Error{constructor(n,r){super(n);Me(this,"dependency",r)}};function Kf(e,t){let n=l=>l.type==="feature"?l.featureKey:l.type==="end"&&l.output?.type==="feature"?l.output.featureKey:l.type==="output"&&l.value.type==="feature"?l.value.featureKey:void 0,r=(l,m)=>e.graph.nodes.find(f=>l==="experiment"?f.type==="split"&&f.experimentId===m:l==="feature"&&n(f)===m)?.name,i=(l,m,f=r(m.type,m.resource))=>new hu(l,{...m,...f?{step:f}:{}});for(let l of Object.values(e.references)){let m=l.type==="flag"?!Object.hasOwn(t.features,l.key)||t.remoteFeatures.includes(l.key)?{type:"feature",resource:l.key}:null:l.type==="experiment"?Object.hasOwn(t.experiments,l.id)?null:{type:"experiment",resource:l.id}:l.type==="saved_group"&&!Object.hasOwn(t.savedGroups,l.id)?{type:"saved_group",resource:l.id}:null;if(m)throw i("Funnel dependency is absent from GB public delivery",{reason:"unavailable",...m})}let a=ts(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),o=new Set(t.remoteFeatures);for(let l of e.graph.nodes){let m=n(l);if(!m)continue;let f=a.features[m],g=l.type==="feature"?e.variables[l.writes.value]:e.outputSchema,d={type:"feature",resource:m};if(!f||!g)throw i("Required public Feature declaration is unavailable",{reason:"unavailable",...d},l.name);if([f.defaultValue,...(f.rules??[]).flatMap(R=>[...Object.hasOwn(R,"force")?[R.force]:[],...R.variations??[],...(R.tracks??[]).flatMap(y=>y.experiment.variations)])].some(R=>R===void 0||!gn(g,R)))throw i("GB Feature values violate the Funnel type contract",{reason:"value_type",...d},l.name)}let s=new Set,c=(l,m)=>{for(let f of Kn(l)){if(s.has(f))continue;let g=t.savedGroups[f];if(!g)throw i("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:f},m);s.add(f),!Array.isArray(g)&&g.type==="condition"&&c(g.condition,m)}},u=(l,m)=>{if(o.has(l)||!t.features[l])throw i("Local Funnel requires public Local prerequisites",{reason:"unavailable",type:"feature",resource:l},m)};for(let l of e.graph.nodes)if(l.type==="condition")for(let m of l.cases)c(m.condition,l.name);for(let[l,m]of Object.entries(a.features)){let f=r("feature",l);for(let g of m.rules??[]){c(g.condition,f);for(let d of[...g.parentConditions??[],...(g.tracks??[]).flatMap(h=>h.experiment.parentConditions??[])])u(d.id,f),c(d.condition,f);for(let d of g.tracks??[])c(d.experiment.condition,f)}}for(let[l,m]of Object.entries(a.experiments)){let f=r("experiment",l);c(m.condition,f);for(let g of m.parentConditions??[])u(g.id,f),c(g.condition,f)}for(let l of e.graph.nodes)if(l.type==="split"){let m=a.experiments[l.experimentId],f={type:"experiment",resource:l.experimentId};if(!m)throw i("Local Funnel requires a public Experiment",{reason:"unavailable",...f},l.name);for(let g of m.variations)if(typeof g!="string"||!Object.hasOwn(l.routes,g))throw i("Experiment variation has no declared Funnel route",{reason:"variation_route",...f},l.name)}return $f.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 Hf(e){return Ei.parse(e)}var Qf=Pt.strictObject({processContext:Oa.optional(),...gi,selector:Pt.discriminatedUnion("type",[Pt.strictObject({type:Pt.literal("paywall"),paywallId:Pt.uuid()}),Pt.strictObject({type:Pt.literal("version"),versionId:Pt.uuid()})]),customerId:Pt.uuid().optional(),commerce:ui,locale:Pt.string().min(1).max(35),requirement:rr.optional()}),xo=Pt.strictObject({id:Pt.uuid(),paywallId:Pt.uuid(),version:Pt.number().int().positive(),document:Ii.omit({requirement:!0,offeringId:!0}),offering:Pt.strictObject({id:Pt.uuid()}),content:Pt.strictObject({environmentId:Pt.uuid(),offeringVersionId:Pt.uuid(),artifact:Au.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:li,check:Er.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"})}),Br=Pt.strictObject(xo.shape).omit({document:!0,offering:!0}).extend({content:xo.shape.content.unwrap()});function Jf(e,t){let n=rs.parse(t);if(n.offeringVersionId!==e.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");let r=structuredClone(e.capabilities);for(let[i,a]of Object.entries(n.catalog)){let o=r.plans[i],s=a.channels.stripe?.prices.find(c=>c.currency===o?.currency);o&&s&&Object.assign(o,{amountMinor:s.amountMinor,interval:a.interval,intervalCount:a.intervalCount,...a.prepaid?.length?{prepaid:a.prepaid}:{}})}return xo.parse({...e,capabilities:r,document:{schemaVersion:3,kind:n.kind,name:n.name,presentation:n.presentation,products:n.products,offeringVersionId:n.offeringVersionId,screen:n.screen,buttons:n.buttons},offering:{id:n.offeringVersionId}})}import{z as Ht}from"zod";var Zf={requestId:Ht.uuid(),sourceId:Ht.uuid(),expectedAvailable:$t},Wf=Ht.discriminatedUnion("action",[Ht.strictObject({...Zf,action:Ht.enum(["add","subtract","set_remaining"]),amount:xe}),Ht.strictObject({...Zf,action:Ht.literal("edit"),granted:xe,expiresAt:Ht.iso.datetime({offset:!0}).nullable(),nextResetAt:Ht.iso.datetime({offset:!0}).nullable(),expectedRevision:Ht.number().int().nonnegative()})]),Su=Ht.strictObject({sourceId:Ht.uuid(),available:$t,held:$t,spent:$t,adjustmentGrantId:Ht.uuid().nullable()}),Yf=Su.extend({granted:$t,expiresAt:Ht.iso.datetime({offset:!0}).nullable(),nextResetAt:Ht.iso.datetime({offset:!0}).nullable(),revision:Ht.number().int().nonnegative()});import{z as pn}from"zod";var Xf=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()]),eg=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 Lr}from"zod";var ng=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],tg=Lr.string().regex(/.+\/.+/),Iu=Lr.number().min(-100),Vr=Lr.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),O0=Lr.strictObject({input:Vr,output:Vr,cache_read:Vr.optional(),cache_write:Vr.optional(),reasoning:Vr.optional(),input_audio:Vr.optional(),output_audio:Vr.optional()}),vu=(e,t)=>Lr.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),wk=Lr.strictObject({defaultMarkup:Iu,providerMarkups:vu(Lr.string().min(1),Iu),modelMarkups:vu(tg,Iu),customModels:vu(tg,O0.partial())});import{z as be}from"zod";var zr=be.iso.datetime({offset:!0}),cr=be.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),P0=be.discriminatedUnion("kind",[be.object({kind:be.literal("absolute"),from:zr,to:zr}).strict(),be.object({kind:be.literal("last_days"),days:be.union([be.literal(1),be.literal(7),be.literal(30),be.literal(90)])}).strict(),be.object({kind:be.literal("billing_cycles"),membershipId:be.uuid(),count:be.number().int().min(1).max(12),includeCurrent:be.boolean()}).strict()]),rg=be.string().max(100).refine(e=>{if(e!=="UTC"&&!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+\-]+)+$/.test(e))return!1;try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Use an IANA timezone"),C0=be.object({key:be.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:be.array(be.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),$r=be.object({range:P0,timezone:rg,filterBy:be.array(C0).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:be.enum(["hour","day","week","month"]),internal_feature_id:be.uuid().nullable(),entityId:be.uuid().nullable(),topN:be.number().int().min(1).max(50).nullable(),groupBy:be.union([be.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),be.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:be.object({bucket:zr,group:be.string().max(240),isOther:be.boolean(),internal_feature_id:be.uuid(),resourceId:be.uuid()}).strict().nullable(),limit:be.number().int().min(1).max(100)}).strict().superRefine((e,t)=>{if(e.range.kind!=="absolute"){e.interval==="hour"&&e.range.kind==="last_days"&&e.range.days>31&&t.addIssue({code:"custom",message:"Hourly reports are bounded to 31 days"});return}let n=Date.parse(e.range.to)-Date.parse(e.range.from);(n<=0||n>366*864e5||e.interval==="hour"&&n>31*864e5)&&t.addIssue({code:"custom",message:"Reporting range must be positive and bounded (31 days hourly, 366 days otherwise)"})}),ig=be.object({from:zr,to:zr,interval:be.enum(["hour","day","week","month"]),timezone:rg,rows:be.array(be.object({bucket:zr,group:be.string().max(240),isOther:be.boolean(),internal_feature_id:be.uuid(),resourceId:be.uuid(),consumedUnits:cr,refundedUnits:cr,reservedUnits:cr,charged:cr,refunded:cr,reserved:cr,netUnits:cr,netCharged:cr}).strict()).max(100),nextCursor:be.object({bucket:zr,group:be.string().max(240),isOther:be.boolean(),internal_feature_id:be.uuid(),resourceId:be.uuid()}).strict().nullable()}).strict();var Ri=Vt.string().regex(/^(0|[1-9]\d{0,29})$/),og=Vt.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),wu=Vt.strictObject({bucket:Vt.iso.datetime({offset:!0}),group:Vt.string().max(240),isOther:Vt.boolean(),internal_feature_id:Vt.uuid()}),ag=Vt.strictObject({...$r.shape,groupBy:Vt.union([Vt.enum(["customer","entity","entitlement"]),Vt.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:wu.nullable()}).superRefine((e,t)=>{let n=$r.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),sg=Vt.strictObject({from:Vt.iso.datetime({offset:!0}),to:Vt.iso.datetime({offset:!0}),interval:$r.shape.interval,timezone:$r.shape.timezone,rows:Vt.array(Vt.strictObject({...wu.shape,eventCount:Ri,units:og,tokenEventCount:Ri,tokens:Vt.strictObject(Object.fromEntries(ng.map(e=>[e,Ri]))),totalTokens:Ri,providerCostEventCount:Ri,providerCostUsd:og,invalidTelemetryEventCount:Ri})).max(100),nextCursor:wu.nullable()});import{z as At}from"zod";var cg=At.object({requestId:At.uuid(),items:At.array(At.object({customerId:At.uuid(),command:Yi.options[1]}).strict()).min(1).max(1e3)}).strict().refine(e=>new Set(e.items.map(t=>t.customerId+":"+t.command.idempotencyKey)).size===e.items.length,"Each logical event must appear once in a batch"),ug=At.object({batchId:At.uuid(),after:At.number().int().min(-1).max(999),limit:At.number().int().min(1).max(100)}).strict(),lg=At.object({batchId:At.uuid(),status:At.enum(["queued","complete"]),total:At.number().int().min(1).max(1e3),processed:At.number().int().min(0).max(1e3),items:At.array(At.object({position:At.number().int().min(0).max(999),customerId:At.uuid(),idempotencyKey:At.string().min(1).max(120),status:At.enum(["queued","accepted","rejected","failed"]),receipt:Xi.nullable(),errorCode:At.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:At.number().int().min(0).max(999).nullable()}).strict();import{z as k}from"zod";var _0=k.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),dg=k.enum(["draft","active","paused","archived"]),pg=k.string().min(1).max(256),mg=k.array(pg).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),E0=k.strictObject({duration:k.enum(["day","week","month","year"]),length:k.number().int().min(1).max(3660)}),R0=k.strictObject({internal_feature_id:k.uuid(),allowance:k.number().nonnegative().max(1e15).nullable(),expiry:E0.nullable()}),k0=k.discriminatedUnion("type",[k.strictObject({type:k.literal("feature_grant"),grants:k.array(R0).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),k.strictObject({type:k.literal("free_product"),productId:pg,duration:an}),k.strictObject({type:k.literal("invoice_credits"),amount:k.number().positive().max(1e8),duration:an,rollover:k.boolean(),productIds:mg})]),j0=k.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),fg=k.object({key:j0,name:k.string().trim().min(1).max(80),configuration:k0}).strict(),gg=k.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),Ou=k.object({code:gg,maxUses:k.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:k.boolean()}).strict(),hg=k.object({key:k.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:k.string().trim().min(1).max(80),rewardId:k.uuid(),redeemOn:k.enum(["customer_creation","checkout"]),receivedBy:k.enum(["referrer","all"]),maxRedemptions:k.number().int().min(1).max(1e6).nullable(),productIds:mg,excludeTrial:k.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),yg={id:k.uuid(),projectId:k.uuid(),environmentId:k.uuid(),revision:k.number().int().nonnegative(),status:dg,createdAt:k.iso.datetime({offset:!0}),updatedAt:k.iso.datetime({offset:!0})},T0=fg.extend(yg).strict(),N0=hg.safeExtend(yg).strict(),qk=k.strictObject({id:k.uuid(),key:k.string(),name:k.string(),type:_0,status:dg}),Uk=k.discriminatedUnion("action",[k.object({action:k.literal("save"),id:k.uuid().nullable(),revision:k.number().int().nonnegative(),input:fg}).strict(),k.object({action:k.enum(["activate","pause","resume","archive","delete"]),id:k.uuid(),revision:k.number().int().nonnegative()}).strict()]),Bk=k.discriminatedUnion("action",[k.object({action:k.literal("save"),id:k.uuid().nullable(),revision:k.number().int().nonnegative(),input:hg}).strict(),k.object({action:k.enum(["activate","pause","resume","archive","delete"]),id:k.uuid(),revision:k.number().int().nonnegative()}).strict()]),Ag=k.object({id:k.uuid(),rewardId:k.uuid(),programId:k.uuid().nullable(),customerId:k.uuid(),referrerId:k.uuid().nullable(),status:k.enum(["pending","applied","unavailable"]),result:k.record(k.string(),k.unknown()).nullable(),createdAt:k.iso.datetime({offset:!0})}).strict(),bg=k.object({code:gg,requestId:k.uuid()}).strict(),xg=k.strictObject({redemptionId:k.uuid(),currency:Ie,requestId:k.uuid(),accepted:k.literal(!0)}),D0=k.strictObject({type:k.literal("checkout"),orderId:k.uuid(),productVersionId:k.uuid(),currency:Ie,duration:an,renewalAmountMinor:k.number().int().positive().max(1e8),status:k.enum(["created","pending","trialing","paid","cancelled","failed"]),url:k.url().nullable()}),Sg=k.discriminatedUnion("type",[D0,k.strictObject({type:k.literal("subscription"),operationId:k.uuid(),membershipId:k.uuid(),productVersionId:k.uuid(),currency:Ie,duration:an,renewalAmountMinor:k.number().int().positive().max(1e8),status:k.enum(["pending","running","applied","failed"])})]),Ig=k.object({programId:k.uuid(),requestId:k.uuid()}).strict(),vg=k.object({id:k.uuid(),programId:k.uuid(),code:Ou.shape.code,createdAt:k.iso.datetime({offset:!0})}).strict(),Vk=k.object({rows:k.array(T0).max(100),nextCursor:k.uuid().nullable()}).strict(),Lk=k.object({rows:k.array(N0).max(100),nextCursor:k.uuid().nullable()}).strict(),F0=Ou.extend({id:k.uuid(),redemptions:k.number().int().nonnegative()}).strict(),M0=k.strictObject({id:k.uuid(),programId:k.uuid().nullable(),customerId:k.uuid().nullable(),referrerId:k.uuid().nullable(),code:k.string().nullable(),status:k.enum(["pending","triggered","applied"]),createdAt:k.iso.datetime({offset:!0})}),zk=k.object({codes:k.array(F0).max(100),redemptions:k.array(M0).max(100),customers:k.record(k.uuid(),k.string()),codesCursor:k.uuid().nullable(),redemptionsCursor:k.uuid().nullable()}).strict(),$k=k.discriminatedUnion("action",[k.object({action:k.literal("create"),rewardId:k.uuid(),revision:k.number().int().nonnegative(),input:Ou}).strict(),k.object({action:k.literal("remove"),rewardId:k.uuid(),revision:k.number().int().nonnegative(),codeId:k.uuid()}).strict()]);import{z as w}from"zod";import{z as W}from"zod";var Fn={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},So=e=>new Set(e).size===e.length,Pu=W.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),q0=W.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),Io=W.string().min(1).max(200).regex(/^[a-zA-Z0-9_./-]+$/).refine(e=>!e.includes("..")&&!e.endsWith(".")&&!e.split("/").some(t=>!t||t.startsWith(".")||t.endsWith(".lock"))),U0=W.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),wg=W.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var Og=W.strictObject({id:W.uuid(),repo:q0,platform:W.enum(["github","gitlab","bitbucket"]),branches:W.array(Io).min(1).max(4).refine(So),workflow:W.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:W.array(W.uuid()).min(1).max(4).refine(So),include:W.array(wg).min(1).max(16),exclude:W.array(wg).max(16),methods:W.array(W.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(So),maxAgeHours:W.number().int().min(1).max(720)}),Pg=Og.extend({revision:W.number().int().positive()}),Hk=W.strictObject({repository:Og,expectedRevision:W.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),Cg=W.strictObject({repositoryId:W.uuid(),branch:Io}),B0=W.array(Pu).max(Fn.keys).refine(So),_g=W.strictObject({repository:Pg.omit({keyIds:!0}),branch:Io,keys:B0,keySetHash:W.string().regex(/^[a-f0-9]{64}$/)}),V0=W.strictObject({filePath:U0,startingLineNumber:W.number().int().min(1).max(1e7)}),Cu=W.strictObject({protocol:W.literal(1),repositoryId:W.uuid(),branch:Io,workflow:W.string().max(200),configurationRevision:W.number().int().positive(),keySetHash:W.string().regex(/^[a-f0-9]{64}$/),commit:W.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:W.uuid(),runNumber:W.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:W.number().int().min(1).max(1e4),scannerVersion:W.literal("1"),scannedAt:W.iso.datetime({offset:!0}),coverage:W.strictObject({complete:W.literal(!0),files:W.number().int().min(0).max(Fn.files),sourceBytes:W.number().int().min(0).max(Fn.sourceBytes),unresolvedCalls:W.number().int().min(0).max(1e6),unsupportedFiles:W.number().int().min(0).max(Fn.files)}),features:W.array(W.strictObject({key:Pu,refs:W.array(V0).max(Fn.referencesPerKey)})).max(Fn.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)>Fn.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),_u=W.strictObject({scanId:W.uuid(),commit:W.string(),receivedAt:W.string(),references:W.number().int().nonnegative(),removedReferences:W.number().int().nonnegative()}),L0=_u.extend({repositoryId:W.uuid(),branch:Io,workflow:W.string(),digest:W.string(),configurationRevision:W.number().int().positive(),runNumber:W.number().int().positive(),runAttempt:W.number().int().positive(),scannedAt:W.string(),keySetHash:W.string(),coverage:Cu.shape.coverage}),z0=W.strictObject({repositories:W.array(Pg).max(Fn.repositories),scans:W.array(L0).max(Fn.repositories*Fn.branches)}),$0=W.strictObject({key:Pu,references:W.number().int().nonnegative(),coveredTargets:W.number().int().nonnegative(),expiredTargets:W.number().int().nonnegative(),uncertainTargets:W.number().int().nonnegative()}),Qk=W.strictObject({available:W.boolean().default(!0),settings:z0,expectedTargets:W.number().int().min(0).max(80),features:W.array($0).max(2001),truncated:W.boolean()});import{z as Ct}from"zod";var G0=Ct.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"]),K0=Ct.strictObject({provider:Ct.literal("stripe"),accountId:Ct.string().regex(/^acct_[A-Za-z0-9]+$/),eventId:Ct.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),type:G0,occurredAt:Ct.number().int().positive().max(Number.MAX_SAFE_INTEGER),data:Ct.record(Ct.string(),Ct.unknown()).and(Ct.object({id:Ct.string().min(1).max(255),object:Ct.enum(["checkout.session","subscription","invoice","discount","refund","charge"]),livemode:Ct.boolean()}))}),Eg=Ct.union([K0,Nl]),Rg=Ct.strictObject({id:Ct.uuid(),eventId:Ct.string().min(1).max(200),source:Ct.literal("merchant"),providerVerified:Ct.literal(!1),outcome:Ct.string().min(1).max(100)});import{z as Qt}from"zod";var jg={customerId:Qt.uuid(),eventId:Qt.string().trim().min(1).max(200),grantId:Qt.uuid(),occurredAt:Qt.iso.datetime({offset:!0})},Tg=Qt.strictObject({...jg,productVersionId:Qt.uuid(),subscriptionId:Qt.string().trim().min(1).max(255)}),Ng=Qt.strictObject({...jg,merchandiseId:Qt.uuid()}),Dg=Qt.union([Tg,Ng]),kg={id:Qt.uuid(),couponId:Qt.uuid(),status:Qt.literal("redeemed"),source:Qt.literal("merchant"),recordedAt:Qt.iso.datetime({offset:!0})},Fg=Qt.union([Tg.extend(kg),Ng.extend(kg)]);import{z as oe}from"zod";var Mg=lm,H0=Mg.extend({invoice_id:Mg.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),Eu=oe.strictObject({name:oe.string().trim().min(1).max(255),memo:oe.string().max(1e4).nullable().optional(),footer:oe.string().max(1e4).nullable().optional(),net_terms_days:oe.number().int().positive().nullable().optional()}),Q0=Eu.extend({id:oe.string().min(1).max(255),created_at:oe.number().nullable()}),qg=oe.strictObject({items:oe.array(Q0).max(50),nextCursor:oe.uuid().nullable()}),rj=oe.discriminatedUnion("action",[oe.strictObject({action:oe.literal("create"),requestId:oe.uuid(),values:Eu}),oe.strictObject({action:oe.literal("update"),id:oe.string().min(1).max(255),values:Eu}),oe.strictObject({action:oe.literal("delete"),id:oe.string().min(1).max(255)})]),Ug=oe.discriminatedUnion("action",[oe.strictObject({action:oe.literal("create"),requestId:oe.uuid(),params:yi}),oe.strictObject({action:oe.enum(["finalize","send","pay","void"]),requestId:oe.uuid(),invoiceId:oe.uuid()}),oe.strictObject({action:oe.literal("reissue"),requestId:oe.uuid(),invoiceId:oe.uuid(),params:H0})]),Ru=oe.strictObject({id:oe.uuid(),customerId:oe.uuid(),providerInvoiceId:oe.string().nullable(),status:oe.enum(["draft","open","paid","void","uncollectible"]),currency:oe.string(),totalMinor:oe.string().regex(/^-?\d+$/),paidMinor:oe.string().regex(/^\d+$/),refundedMinor:oe.string().regex(/^\d+$/),hostedInvoiceUrl:oe.url().nullable(),createdAt:oe.number(),collectionMethod:oe.enum(["send_invoice","charge_automatically"]).nullable()}),Bg=Ru.extend({lines:oe.array(oe.strictObject({id:oe.uuid(),description:oe.string(),amountMinor:oe.string().regex(/^-?\d+$/),netAmountMinor:oe.string().regex(/^-?\d+$/),quantity:oe.number().nullable(),periodStart:oe.number().nullable(),periodEnd:oe.number().nullable()})).max(1e3)}),ki=oe.strictObject({taskId:oe.uuid(),status:oe.enum(["ready","running","done","dead"]),invoice:Ru.nullable(),errorCode:oe.string().nullable()}),Vg=oe.strictObject({items:oe.array(Ru).max(50),nextCursor:oe.uuid().nullable(),operations:oe.array(ki).max(50),operationsLimited:oe.boolean()});var J0=w.enum(["customers:read","customers:write","entitlements:read","content:read","sessions:create","funnels:run","offers:resolve","offers:grant","billing:read","billing:write","credits:read","credits:consume","credits:manage","features:read","events:write","messaging:write","code-references:read","code-references:write","app-manifests:write"]),Lg={scope:Te,permissions:w.array(J0),expiresAt:w.iso.datetime().nullable()},Jj=w.discriminatedUnion("kind",[w.object({...Lg,kind:w.literal("server"),keyId:w.string().min(1)}),w.object({...Lg,kind:w.literal("customer"),customerId:w.string().min(1),identityKind:w.enum(["identified","guest"]),expiresAt:w.iso.datetime()})]),V=w.object({requestId:w.uuid(),scope:Te}).strict(),Z0=Of.safeExtend({fingerprint:Qa.optional()}).strict(),W0=V.extend({customer:Ci,created:w.boolean()});function zg(){return V.extend({offer:Gi.nullable(),reason:Ud.nullable()})}var O={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:Ep,response:V.extend({message:w.object({messageId:w.uuid(),channel:ro,acceptedAt:w.iso.datetime({offset:!0}),status:w.enum(["accepted","sending","completed","canceled"]),replayed:w.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:w.strictObject({messageId:w.uuid()}),response:V.extend({message:w.object({id:w.uuid(),channel:ro,status:w.enum(["accepted","sending","completed","canceled"]),deliveries:w.array(w.object({id:w.uuid(),status:kp,attempts:w.number().int().nonnegative(),receipts:w.array(w.object({kind:jp,occurredAt:w.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:Al,response:V.extend({installation:Sr})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:bl,response:V.extend({installation:Sr})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:Mo,response:V.extend({installation:Sr})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:w.strictObject({channel:ro}),response:V.extend({preference:Os})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:Rp,response:V.extend({preference:Os})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:w.strictObject({cursor:w.uuid().optional()}),response:V.extend({templates:qg})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:w.strictObject({customerId:w.uuid(),params:yi}),response:V.extend({preview:Ec})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:w.strictObject({customerId:w.uuid(),requestId:w.uuid(),params:yi}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:V.extend({operation:ki})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:w.strictObject({customerId:w.uuid(),command:Ug}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:V.extend({operation:ki})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:w.strictObject({customerId:w.uuid(),taskId:w.uuid()}),response:V.extend({operation:ki})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:w.strictObject({customerId:w.uuid(),cursor:w.uuid().optional()}),response:V.extend({invoices:Vg})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:w.strictObject({customerId:w.uuid(),invoiceId:w.uuid()}),response:V.extend({invoice:Bg})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:Cg,response:V.extend({config:_g})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:Cu,response:V.extend({receipt:_u})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:w.strictObject({}),response:V.extend({payload:fo})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:tf,response:V.merge(qa)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:nf,response:V.merge(rf)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:w.strictObject({customerId:w.uuid(),sourceId:w.uuid()}),response:V.extend({balance:Yf})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:w.strictObject({customerId:w.uuid(),command:Wf}),response:V.extend({balance:Su})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:w.strictObject({internal_feature_id:w.uuid(),customerId:w.uuid().optional(),entityId:w.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:V.extend({internal_feature_id:w.uuid(),config:Bs,model_markups:Qo})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:w.strictObject({customerId:w.uuid(),query:ma}),response:V.extend({usage:eo})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:w.strictObject({customerId:w.uuid(),command:xp}),response:V.extend({usage:eo})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:w.strictObject({customerId:w.uuid(),command:fp}),response:V.extend({grant:uc})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:gp,response:V.extend({grants:hp})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:w.union(zm.options.map(e=>e.extend({customerId:w.uuid().optional(),customerToken:w.string().regex(kt).optional()}))),response:V.extend({operation:$m})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:jm.extend({customerId:w.uuid().optional()}),response:V.extend({setup:Nc})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Tm.extend({customerId:w.uuid().optional()}),response:V.extend({setup:Nc})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:Em.safeExtend({customerId:w.uuid()}),response:V.extend({batch:lo})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:Ra.extend({customerId:w.uuid()}),response:V.extend({batch:lo})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:Ra.extend({customerId:w.uuid()}),response:V.extend({batch:lo})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:Ra.extend({customerId:w.uuid()}),response:V.extend({batch:lo})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:w.discriminatedUnion("action",[ka.options[0].extend({customerId:w.uuid()}),ka.options[1].extend({customerId:w.uuid()}),ka.options[2].extend({customerId:w.uuid()})]),response:V.extend({trial:Tc})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Rm.extend({customerId:w.uuid()}),response:V.extend({trial:Tc})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:Na,response:V.extend({subscriptions:Bm})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:Na,response:V.extend({purchases:Vm})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:Mm,response:V.extend({conflicts:Lm})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:qm,response:V.extend({resolution:Um})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:Dm,response:V.extend({verification:Fm})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:Sm.safeExtend({...gi,customerId:w.uuid().optional()}),response:V.extend({quote:Ai})},recordBillingEvent:{method:"POST",path:"billing/events/record",permission:"billing:write",audience:"server",request:Eg,response:V.extend({record:Rg})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Fr.extend({customerId:w.uuid().optional(),intent:w.enum(["confirm","cancel"]).optional()}),response:V.extend({operation:bi})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Fr.extend({customerId:w.uuid().optional()}),response:V.extend({operation:bi})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:wm.safeExtend({customerId:w.uuid().optional()}),response:V.extend({quote:Pm})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Fr.extend({customerId:w.uuid().optional(),intent:w.enum(["confirm","cancel"]).optional()}),response:V.extend({operation:Rc})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Fr.extend({customerId:w.uuid().optional()}),response:V.extend({operation:Rc})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:Cm.safeExtend({customerId:w.uuid()}),response:V.extend({quote:kc})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Fr.extend({customerId:w.uuid()}),response:V.extend({operation:Ea})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Fr.extend({customerId:w.uuid()}),response:V.extend({operation:Ea})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:Xd,response:V.extend({controls:sc})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:Kd,response:V.extend({prepared:Qd})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:Jd,response:V.extend({authorization:ua})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:ip,response:V.extend({coupons:op})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Zd,response:V.extend({authorization:ua})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:np,response:V.extend({invoices:rp})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:tp.extend({customerId:w.uuid()}),response:V.extend({operation:ki})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:ep,response:V.extend({invoice:Qi})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:w.object({customerId:w.uuid(),command:Yd}).strict(),response:V.extend({controls:sc})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:w.object({customerId:w.uuid(),command:Xf}).strict(),response:V.extend({entity:eg})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:w.strictObject({customerId:w.uuid().nullable(),query:ag}),response:V.extend({analytics:sg})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:w.object({customerId:w.uuid().nullable(),query:$r}).strict(),response:V.extend({analytics:ig})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:cg,response:V.extend({batchId:w.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:ug,response:V.extend({batch:lg})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:Dp.extend({customerId:w.string().min(1).optional()}),response:V.extend({check:Er})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:w.strictObject({kind:or,selector:w.discriminatedUnion("type",[w.strictObject({type:w.literal("resource"),id:w.uuid()}),w.strictObject({type:w.literal("version"),id:w.uuid()})]),customerId:w.string().min(1).optional()}),response:V.extend({content:Cc})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Qf,response:V.extend({paywall:Br})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:w.strictObject({processContext:Oa.optional(),...gi,selector:Qm,customerId:w.string().min(1).optional(),commerce:ui,requirement:rr.optional()}),response:V.extend({offering:Jm,candidates:w.array(fc).max(20),availability:w.array(w.strictObject({productVersionId:w.uuid(),available:w.boolean(),reason:w.enum(["platform_binding_missing","commercial_runtime_pending","commerce_not_configured","currency_mismatch","product_unavailable","already_attached","attach_in_progress","already_scheduled","subscription_change_required","purchase_conflict"]).nullable()})).max(20),check:Er.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:w.object({customerId:w.uuid().optional(),entityId:w.uuid().optional()}).strict(),response:V.extend({holdings:Sp})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:w.object({customerId:w.uuid().optional(),query:vp}).strict(),response:V.extend({ledger:wp})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:yp.extend({customerId:w.uuid().optional()}),response:V.extend({detail:Ap})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:lc.safeExtend({customerId:w.uuid().optional()}),response:V.extend({statement:bp})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:w.object({customerId:w.uuid().optional(),command:Yi.options[0]}).strict(),response:V.extend({quote:dp})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:w.strictObject({customerId:w.uuid(),command:w.union([w.strictObject({eventName:w.string().min(1),quantity:xe.optional(),properties:It.optional(),entityId:w.uuid().optional(),idempotencyKey:w.string().min(1).max(120)}),w.strictObject({internal_feature_id:w.uuid(),quantity:xe.optional(),properties:It.optional(),entityId:w.uuid().optional(),idempotencyKey:w.string().min(1).max(120)})])}),response:V.extend({receipts:w.array(Xi).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:w.object({customerId:w.uuid(),command:Yi.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:V.extend({receipt:Xi})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:bg,response:V.extend({redemption:Ag})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:Ig,response:V.extend({referralCode:vg})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:xg,response:V.extend({checkout:Sg})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:Pp,response:V.extend({seats:mc})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Cp,response:V.extend({seats:mc})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:Z0,response:W0},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:iu,response:V.extend({customer:Ci})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:_f,response:V.extend(Ef.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:Cf,response:V.extend(Pf.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:w.object({customerId:w.uuid()}).strict(),response:V.extend(Zn.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:w.strictObject({}),response:V.extend(Zn.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:w.strictObject({customerId:w.uuid(),sessionId:w.uuid().optional()}),response:V.extend({revoked:w.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:w.strictObject({guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:Qa.optional()}),response:V.extend({customerId:w.uuid(),guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:w.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:w.strictObject({guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:V.extend(Zn.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:w.strictObject({guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:w.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:w.uuid()}),response:V.extend({customer:Ci,switched:w.boolean(),replayed:w.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:w.strictObject({code:w.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:w.uuid()}),response:zg()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:w.object({}).strict(),response:V.extend({offers:w.array(Gi)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:w.object({customerId:w.string().min(1).max(255).optional(),couponId:w.uuid(),...gi,requestId:w.uuid(),couponContentDigest:w.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:zg()},recordCouponRedemption:{method:"POST",path:"offers/redemptions",permission:"billing:write",audience:"server",request:Dg,response:V.extend({receipt:Fg})}},Zj={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 ku}from"zod";var vo=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function ju(e,t,n){let r={},i,a,o,s="next",c;switch(e.type){case"entry":c=e.next;break;case"condition":{let u=e.cases.findIndex(l=>en(t.attributes??{},l.condition,t.savedGroups??{}));s=u<0?"default":`case:${u}`,c=u<0?e.default:e.cases[u].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new vo("Required GB Feature is unavailable");i=Gn(e.featureKey,t),o=i.value,Object.assign(r,fi(e,{value:o})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new vo("Required GB Experiment is unavailable");if(a=sa(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 vo("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:Gn(e.configuration.featureKey,t).value;o={type:"offering_version",id:ku.uuid().parse(u)},Object.assign(r,fi(e,{value:o})),c=e.next;break}case"coupon":case"coupons":o=e.type==="coupons"?e.couponIds.map(u=>({type:"reward",id:u})):{type:"reward",id:e.couponId},Object.assign(r,fi(e,{value:o})),c=e.next;break}return{port:s,target:c,projections:r,...o===void 0?{}:{value:o},...i?{feature:i}:{},...a?{experiment:a}:{}}}function $g(e,t,n){ku.uuid().parse(e),ku.number().int().nonnegative().parse(t);let r=ni(ri(new TextEncoder().encode(JSON.stringify([e,t,n])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}import{z as H}from"zod";var ur=H.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Y0=H.enum(["running","waiting","completed","closed","ineligible","failed"]),Tu=H.discriminatedUnion("type",[nu,H.strictObject({type:H.literal("wait"),receiptId:H.uuid(),kind:H.enum(["timer","event","operation"]),deadline:H.iso.datetime({offset:!0}).nullable(),eventName:ur.optional()}),H.strictObject({type:H.literal("open_url"),receiptId:H.uuid(),url:ou,openIn:au}),H.strictObject({type:H.literal("event"),receiptId:H.uuid(),event:ur})]),is=H.strictObject({type:H.literal("funnel"),id:H.uuid(),versionId:H.uuid()}),X0={id:ur,presentation:On,outputs:H.array(ur).max(250),inputs:La,values:H.record(H.string(),ve).optional(),offeringKey:St.optional(),capabilities:li,customerData:Lp,dataCursors:H.record(ur,Va.nullable())},eI=H.strictObject({...X0,content:H.strictObject({type:H.literal("document"),document:cn})}),wo=H.strictObject({id:H.uuid(),source:is,revision:H.number().int().nonnegative(),visit:H.number().int().nonnegative(),nodeId:ur,nodeType:H.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:Y0,stopped:H.boolean(),canBack:H.boolean(),authenticated:H.boolean(),locale:H.string().min(1).max(35),answers:ar,parameters:sr,variables:H.record(H.string(),ve),output:ve.nullable(),screen:eI.nullable(),paywall:H.strictObject({receiptId:H.uuid(),resolution:H.union([xo,Br]),quote:Ai.nullable(),operation:bi.nullable(),purchaseRequestId:H.uuid().nullable(),selectionGeneration:H.number().int().nonnegative().optional(),canReselect:H.boolean().optional()}).nullable(),instruction:Tu.nullable(),pendingRequest:H.strictObject({requestId:H.uuid(),authenticationRequired:H.boolean()}).nullable(),runExpiresAt:H.iso.datetime({offset:!0}),credentialExpiresAt:H.iso.datetime({offset:!0}).nullable()}),os=H.strictObject({scope:Te,run:wo,settlement:H.strictObject({requestId:H.uuid(),state:H.enum(["pending","unknown","settled"]),operationId:H.uuid().nullable(),receiptId:H.uuid().nullable().optional()}).optional(),purchase:H.strictObject({receiptId:H.uuid(),quote:Ai.nullable(),operation:bi.nullable(),canReselect:H.boolean().optional()}).optional(),review:H.strictObject({activeOperationId:H.uuid().nullable(),pages:H.array(H.strictObject({receiptId:H.uuid(),nodeId:ur,visit:H.number().int().nonnegative()})).max(100),page:H.strictObject({receiptId:H.uuid(),nodeId:ur,visit:H.number().int().nonnegative(),document:cn,answers:ar,inputs:La,values:H.record(H.string(),ve).optional()}).nullable(),coupons:H.array(H.strictObject({grantId:H.uuid(),status:H.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:H.string().nullable()})).max(100),purchases:H.array(H.strictObject({receiptId:H.uuid(),operationId:H.uuid(),status:H.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:H.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:H.uuid().optional()}),Gg=os.extend({run:wo.extend({paywall:wo.shape.paywall.unwrap().extend({resolution:Br}).nullable()})});var Kg="X-Indiana-Server-Key";import{z as se}from"zod";import{z as Ae}from"zod";import{z as _t}from"zod";var tI=_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()}),nI=_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(tI).max(200).default([]),iam:pf.optional(),renderGuard:Ua.optional()}),Nu=nI.omit({variation:!0,description:!0,iam:!0}),rI=wi.omit({variations:!0,active:!0}).extend({changeId:_t.string().regex(/^[a-f0-9]{64}$/),variations:_t.tuple([Nu,Nu]).rest(Nu).refine(e=>e.length<=20)}),Hg=_t.strictObject({trackExposures:_t.boolean(),environmentId:_t.uuid(),generation:_t.string().regex(/^[a-f0-9]{64}$/),experiments:_t.array(rI).max(100),savedGroups:mo});var Oo=Ae.string().regex(/^[a-f0-9]{64}$/),RT=Ae.strictObject({iam:Oo,executionContracts:Ae.union([Ae.tuple([Ae.literal("funnel-run/1")]),Ae.tuple([Ae.literal("funnel-process/1")])]).default(["funnel-run/1"])}),iI=Ae.strictObject({release:Oo,render:Ua,button:Ae.strictObject({selector:Ae.string().min(1).max(512),elementKey:Ae.string().min(1).max(256),tag:Ae.enum(["button","a","input"])}).nullable()}),kT=Ae.strictObject({scope:Te.extend({environmentId:Ae.uuid()}),release:Oo,validatedAt:Ae.iso.datetime({offset:!0}),validUntil:Ae.iso.datetime({offset:!0}),entries:Ae.array(Ae.strictObject({id:Ae.uuid(),funnelId:Ae.uuid(),versionId:Ae.uuid(),event:Ae.enum(["screen_enter","button_click"]),target:iI})).max(4e3)}),Qg=Ae.strictObject({operation:Ae.literal("entry_start"),funnelId:Ae.uuid(),versionId:Ae.uuid(),entryId:Ae.uuid(),release:Oo,requestId:Ae.uuid(),locale:Ae.string().min(1).max(35).default("en")}),Jg=Ae.strictObject({scope:Te,suppressed:Ae.literal(!0),reason:Ae.enum(["frequency","in_progress"]),retryAt:Ae.iso.datetime({offset:!0}).nullable()}),jT=Ae.strictObject({experimentId:Ae.uuid(),splitNodeId:Ae.string().min(1).max(128)}),oI=Ae.strictObject({experimentId:Ae.uuid(),experimentKey:Ae.string().min(1).max(128),variationKey:Ae.string().min(1).max(128),inExperiment:Ae.boolean(),generation:Ae.string().min(1).max(256)}),Po=Ae.strictObject({operation:Ae.literal("page_experiments"),release:Oo,usedReceiptIds:Ae.array(Ae.uuid()).max(20).default([]),customerToken:Ae.string().regex(kt).optional()}),Zg=Ae.strictObject({scope:Te,runId:Ae.uuid(),assignments:Ae.array(oI.extend({receiptId:Ae.uuid()})).max(100),payload:Hg});var kn=se.literal(af),aI=se.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),Du=se.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),Wg=se.discriminatedUnion("type",[se.strictObject({type:se.literal("guest"),guestToken:Du}),se.strictObject({type:se.literal("customer"),customer:qr,customerData:Pi.optional()})]),Fu=se.strictObject({id:se.uuid(),runId:se.uuid(),customerId:se.uuid(),requestId:se.uuid(),acceptedAt:se.iso.datetime({offset:!0})}),sI=se.strictObject({participantId:se.uuid(),startedAs:se.enum(["guest","identified"]),binding:Fu.omit({runId:!0,requestId:!0}).nullable()}),cI=se.union([Tu,se.strictObject({type:se.literal("authentication_required"),reason:se.enum(["customer_required","customer_experiment_required"]),nodeId:se.string().min(1).max(64),visit:se.number().int().nonnegative()})]),uI=wo.omit({authenticated:!0}).extend({identity:sI,instruction:cI.nullable()}),lI=se.discriminatedUnion("operation",[wt.options[2].omit({customerToken:!0}),wt.options[3].omit({customerToken:!0}),wt.options[4].omit({customerToken:!0}),wt.options[5].omit({customerToken:!0}),wt.options[6].omit({customerToken:!0}),wt.options[7].omit({customerToken:!0})]),as={contract:kn,customerToken:se.string().regex(kt)},Yg={contract:kn,requestId:se.uuid(),runToken:aI,externalUserId:qr.options[1].shape.value},Xg=se.discriminatedUnion("operation",[se.strictObject({contract:kn,operation:se.literal("describe")}),se.strictObject({contract:kn,operation:se.literal("start"),source:Wg,funnelId:wt.options[0].shape.funnelId,requestId:se.uuid(),locale:wt.options[0].shape.locale,parameters:wt.options[0].shape.parameters}),Qg.omit({operation:!0}).extend({contract:kn,operation:se.literal("entry_start"),source:Wg}),se.strictObject({...Yg,operation:se.literal("bind_customer"),guestToken:Du,claimRequestId:se.uuid(),expectedBindingId:se.null()}),se.strictObject({...Yg,operation:se.literal("binding_status"),guestToken:Du.optional()}),wt.options[1].omit({operation:!0,customerToken:!0}).extend({...as,operation:se.literal("get"),settlementBindingId:se.uuid().nullable().optional()}),wt.options[8].omit({operation:!0,customerToken:!0}).extend({...as,operation:se.literal("review")}),Po.omit({customerToken:!0}).extend(as),se.strictObject({...as,operation:se.literal("command"),identity:se.strictObject({bindingId:se.uuid().nullable()}),command:lI})]),Mu=os.omit({run:!0}).extend({contract:kn,run:uI,settlement:os.shape.settlement.unwrap().extend({accepted:se.boolean().nullable().optional()}).optional()}),LT=Jg.extend({contract:kn}),zT=se.discriminatedUnion("operation",[Xg.options[1].omit({contract:!0,source:!0,requestId:!0}),Xg.options[2].omit({contract:!0,source:!0,requestId:!0})]),$T=Mu.extend({binding:Fu,outcome:se.enum(["bound","already_bound"]),replayed:se.boolean()}),GT=se.discriminatedUnion("state",[se.strictObject({contract:kn,scope:Te,state:se.literal("not_accepted")}),se.strictObject({contract:kn,scope:Te,state:se.literal("conflict")}),se.strictObject({contract:kn,scope:Te,state:se.literal("bound"),binding:Fu})]),KT=se.strictObject({contract:kn,scope:Te,keyId:se.uuid(),operations:se.array(se.string()).max(20)});import{z as De}from"zod";var ji=De.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),th=De.strictObject({entry:ji,nodes:De.array(De.strictObject({id:ji,type:De.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:De.record(De.string(),ji),writes:De.record(St,St),resources:De.strictObject({screenId:ji.optional(),paywallVersionId:De.uuid().optional(),couponId:De.uuid().optional(),couponIds:De.array(De.uuid()).max(20).optional(),experimentId:De.uuid().optional(),featureKey:De.string().optional(),offeringVersionId:De.uuid().optional()})})).min(1).max(500)}),eh={scope:Te,funnelId:De.uuid(),versionId:De.uuid(),evaluationRevision:De.number().int().nonnegative(),expiresAt:De.iso.datetime({offset:!0}).nullable(),topology:th},ss=De.discriminatedUnion("evaluationMode",[De.strictObject({...eh,evaluationMode:De.literal("local"),growth:hn,conditions:De.record(ji,De.array(De.strictObject({condition:Yt,port:De.string()})))}),De.strictObject({...eh,evaluationMode:De.literal("remote")})]),dI=ss.options[0].extend({evaluation:De.strictObject({maxTransitions:De.number().int().min(1).max(1e4),variables:De.record(St,mi),outputSchema:pi,terminals:De.record(ji,De.strictObject({outcome:De.enum(["completed","closed","ineligible","failed"]),output:ho.nullable()}))})});function pI(e){return th.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let n={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":n.next=t.next;break;case"screen":Object.assign(n,t.outputs),r.screenId=t.screenId;{let a=e.screens.find(o=>o.id===t.screenId);a?.type==="paywall"&&(r.paywallVersionId=a.paywallVersionId)}break;case"condition":t.cases.forEach((a,o)=>{n[`case:${o}`]=a.target}),n.default=t.default;break;case"split":Object.assign(n,t.routes),n.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let a of["success","cancel","unavailable","failure"])n[a]=t[a];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=De.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 qu(e){let t=Ei.parse(e.document),n=e.evaluationMode==="local"?hn.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:pI(t)};return ss.parse(e.evaluationMode==="remote"?r:{...r,growth:ts(t,n),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((a,o)=>({condition:a.condition,port:`case:${o}`}))]))})}function nh(e){let t=qu(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=Ei.parse(e.document);return dI.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 rh=nt.string().regex(/^[a-f0-9]{64}$/),mI=wi.omit({variations:!0,active:!0}).extend({changeId:rh,variations:nt.array(nt.strictObject({urlRedirect:nt.string().max(2048)})).min(2).max(20)}),ih=nt.strictObject({environmentId:nt.uuid(),trackExposures:nt.boolean(),generation:rh,experiments:nt.array(mI).max(100),savedGroups:mo}),fI=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)}),oN=nt.strictObject({events:nt.array(fI).min(1).max(20)}),aN=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 ut}from"zod";var Bu=32,gI=522240;function Vu(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 hI=ut.strictObject({nodeId:ut.string().min(1).max(64),visit:ut.number().int().nonnegative(),revision:ut.number().int().nonnegative()}),Uu=ut.record(ut.string(),ve),yI=ut.strictObject({id:ut.uuid(),nodeId:ut.string().min(1).max(64),visit:ut.number().int().nonnegative(),input:ut.strictObject({schemaVersion:yo.shape.schemaVersion,kind:yo.shape.kind,selector:yo.shape.selector,contract:yo.shape.contract}),context:Uu,removed:ut.array(ut.string()).max(100),attributes:Uu,removedAttributes:ut.array(ut.string()).max(100),result:Ff,offeringVersionId:ut.uuid().nullable(),events:ut.strictObject({entered:ut.string().regex(/^[1-9][0-9]{0,18}$/),decision:ut.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),pN=ut.strictObject({schemaVersion:ut.literal(1),mode:ut.enum(["local","remote"]),versionId:ut.uuid(),generation:ut.number().int().positive(),base:hI,context:Uu,steps:ut.array(yI).min(1).max(Bu)}).refine(e=>un(e)<=gI,"Segment exceeds its byte budget");var AI=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function Co(e){return Array.isArray(e)?e.some(Co):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&Co(n):!AI.test(t))}function oh(e,t,n,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(s=>s.id===t.screenId&&s.type==="paywall")))return"customer_required";let i=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(i&&["bundle","selection","offering"].includes(i.type)||t.type==="condition"&&t.cases.some(s=>Co(s.condition)))return"customer_required";let a=JSON.stringify([t,t.type==="screen"?e.screens.find(s=>s.id===t.screenId):null]);for(let[s,c]of Object.entries(e.variables))if(c.source.type==="attribute"&&c.source.key!=="funnelParticipantId"&&(a.includes(`variables.${s}`)||a.includes(JSON.stringify(s))))return"customer_required";if(t.type==="split"){let s=n.experiments?.[t.experimentId];if((s?.hashAttribute??"id")!=="funnelParticipantId"||Co(s?.condition)||s?.parentConditions?.length)return"customer_experiment_required"}let o=t.type==="feature"?t.featureKey:i?.type==="feature"?i.featureKey:void 0;return o&&n.features?.[o]?.rules?.some(s=>(s.hashAttribute??"id")!=="funnelParticipantId"||Co(s.condition)||s.parentConditions?.length)?"customer_experiment_required":null}var Lu=class extends Error{constructor(n,r){super(r);Me(this,"code",n);this.name="FunnelLocalCalculationError"}},ah=(e,t)=>new Lu(e,t),bI=e=>({experiments:e.experiments,features:e.features});function xI(e,t=ah){let n=new Map(e.topology.nodes.map(o=>[o.id,o])),r=ii(e.growth.savedGroups),i=bI(e.growth);function a(o,s){if(!Object.hasOwn(e.growth.features,o))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Gn(o,s).value}return{nodes:n,savedGroups:r,features:i.features,feature:a,evaluate(o,s){let c=n.get(o);if(!c)throw t("NOT_FOUND","Funnel node is unavailable");let u,l;if(c.type==="condition"){let f=e.conditions[c.id];if(!f)throw t("INVALID_RESPONSE","Local condition rules are unavailable");u=ju({id:c.id,name:c.id,type:"condition",cases:f.map(g=>({condition:g.condition,target:c.outputs[g.port]})),default:c.outputs.default},s,i.experiments).port}else if(c.type==="feature"){if(!c.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");l=a(c.resources.featureKey,s),u="next"}else if(c.type==="split"){if(!(c.resources.experimentId?e.growth.experiments[c.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let g=ju({id:c.id,name:c.id,type:"split",experimentId:c.resources.experimentId,routes:c.outputs,notParticipating:c.outputs.notParticipating},s,i.experiments);l=g.value,u=g.port}else if(["offering","end","output"].includes(c.type)&&c.resources.featureKey)l=a(c.resources.featureKey,s),u=c.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let m=c.outputs[u]??(u==="value"?c.id:void 0);if(!m)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:o,port:u,target:m,...l===void 0?{}:{value:l}}}}}function SI(e,t){let n=ss.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=xI(n,t);return(o,s)=>(i(),II(a,o,s))}function II(e,t,n){let r=vt.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 vI(e,t,n){let r=[],i=[],a=[],o=e(t,{...n.attributes?{attributes:n.attributes}:{},stickyBucketAssignmentDocs:n.sticky,saveStickyBucketAssignmentDoc(s){let c=r.findIndex(m=>m.next.attributeName===s.attributeName&&m.next.attributeValue===s.attributeValue),u=s.attributeName+"||"+s.attributeValue,l={expected:n.sticky[u]??null,next:s};c<0?r.push(l):r[c]=l},onExperimentViewed(s,c){c.inExperiment&&c.hashUsed&&!c.passthrough&&i.push(ve.parse({key:s.key,variationId:c.variationId,keyUsed:c.key,hashAttribute:c.hashAttribute,hashValue:c.hashValue}))},onFeatureUsage(s,c){a.push(ve.parse({feature:s,value:c.value,source:c.source,...c.ruleId?{ruleId:c.ruleId}:{}}))}});return{port:o.port,...o.value===void 0?{}:{value:o.value},sticky:r,exposures:i,features:a}}function sh(e,t,n,r=ah){let i=n,a=new Map(t.graph.nodes.map(R=>[R.id,R])),o=structuredClone(n.variables),s=structuredClone(i.sticky),c=[],u=n.nodeId,l=n.visit,m=!1,f,g=R=>oh(t,R,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),d=R=>(f??(f=SI(e,r)),vI(f,R,{attributes:Wc({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:o,savedGroups:{}}),sticky:s}));for(let R=0;R<Bu;R++){let y=a.get(u);if(!y||!Vu(y)||g(y))break;if(l>=t.execution.maxTransitions&&(l>t.execution.maxTransitions||y.type!=="end"&&y.type!=="output")){if(!c.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let A,x;if(["condition","feature","split"].includes(y.type)||y.type==="offering"&&y.configuration.source==="feature")A=d(y.id),y.type==="offering"&&(A.value={type:"offering_version",id:String(A.value)}),y.type==="condition"?x=A.port==="default"?y.default:y.cases[Number(A.port.slice(5))]?.target:y.type==="split"?x=A.port==="notParticipating"?y.notParticipating:y.routes[A.port]:(y.type==="feature"||y.type==="offering")&&(x=y.next);else if(A={port:"next",sticky:[],exposures:[],features:[]},(y.type==="entry"||y.type==="coupon"||y.type==="coupons")&&(x=y.next),y.type==="offering"&&y.configuration.source==="fixed"&&(A.value={type:"offering_version",id:y.configuration.versionId},x=y.next),y.type==="end"||y.type==="output"){let P=y.type==="end"?y.output:y.value;if(A=P?.type==="feature"?d(y.id):{...A,port:"value",value:P?.type==="literal"?P.value:P?.type==="variable"?wc({source:"variable",key:P.key,...P.path?{path:P.path}:{}},{declarations:t.variables,answers:n.answers,results:o,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},P&&(A.value===void 0||!gn(t.outputSchema,A.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let v=[...c,{nodeId:u,result:A}];if(un({steps:v})>6e4){if(!c.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(c.push({nodeId:u,result:A}),y.type==="feature"||y.type==="offering"||y.type==="coupon"||y.type==="coupons"){let P=y.type==="coupons"?y.couponIds.map(_=>({type:"reward",id:_})):y.type==="coupon"?{type:"reward",id:y.couponId}:A.value;if(P===void 0)throw r("INVALID_RESPONSE","Node output is missing");let j=fi(y,{value:P});Wp(t.variables,y,j),Object.assign(o,j)}for(let P of A.sticky)s[`${P.next.attributeName}||${P.next.attributeValue}`]=structuredClone(P.next);if(y.type==="end"||y.type==="output"){m=!0;break}if(!x)throw r("INVALID_RESPONSE","Local pure exit is unavailable");u=x,l++}let h=a.get(u);return{steps:c,...!m&&h&&(!Vu(h)||g(h))?{boundary:{nodeId:u,visit:l}}:{}}}var b=class extends Error{constructor(n,r,i,a,o){super(r);Me(this,"code",n);Me(this,"status",i);Me(this,"requestId",a);Me(this,"commandRequestId");Me(this,"retryable");Me(this,"recovery");Me(this,"retryAfterSeconds");Me(this,"reason");this.name="IndianaError",this.reason=o?.reason;let s=qo(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 _o=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new b("INVALID_STATE","Installation sequence exhausted");return e+1},wI=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 Mn(e,t){return e.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new b("INVALID_STATE","Installation journal is invalid");return t({...n})})}function ch(e,t,n){let r=null,i=0,a=0,o=0,s=Promise.resolve(),c=!1;if(e&&(!n||Te.parse(e.scope).projectId!==n.projectId||e.scope.environment!==n.environment))throw new b("SCOPE_MISMATCH","Push installation belongs to another scope");let u=()=>{if(c)throw new b("CLOSED","SDK client was destroyed");if(!e)throw new b("NOT_CONFIGURED","Configure this client's native Push host first");return e},l=x=>{if(x!==i)throw new b("IDENTITY_CHANGED","Identity changed during Push operation")};async function m(x){let v=u();if(!v.sha256&&!globalThis.crypto?.subtle)throw new b("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let P=v.sha256?await v.sha256(Uint8Array.from(x,j=>j.charCodeAt(0))):await wI(x);if(!/^[a-f0-9]{64}$/.test(P))throw new b("INVALID_STATE","Push credential digest is invalid");return P}function f(x){let v=Sr.parse(x);if(v.installationId.toLowerCase()!==u().installationId.toLowerCase())throw new b("INVALID_RESPONSE","Push response belongs to another installation");return v}async function g(x,v){let P=u(),j={installationId:P.installationId,publicKey:P.publicKey,issuedAt:new Date().toISOString(),...v},_=await P.sign(vl(x,P.scope,j));return{...j,signature:_}}let d=(x,v,P)=>t.requestWithCredential?t.requestWithCredential(x,v,P):t.request(x,v);async function h(){let x=u(),v=i,P=r?await(t.session?.access()??r):null,j=Mn(x,Se=>Se),_;if(j.detachSeq!==null){let Se=j.detachSeq,gt=xl.parse(await g("detach",{sequence:Se,platform:x.platform}));try{let Qe=await t.request("push/installations/detach",{...x.scope,...gt},"POST",{installationDetach:!0});if(!Qe||typeof Qe!="object"||!("installation"in Qe))throw new b("INVALID_RESPONSE","Push detach acknowledgement is invalid");let je=f(Qe.installation);if(je.bound||je.identitySeq!==Se)throw new b("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(Qe){if(Qe instanceof b&&Qe.status===404)_=Qe;else if(!(Qe instanceof b)||Qe.status!==412)throw Qe}_||Mn(x,Qe=>({...Qe,detachSeq:Qe.detachSeq===Se?null:Qe.detachSeq}))}if(l(v),!P){if(_)throw _;return null}let X=O.bindPushInstallation,le=X.request.parse(await g("bind",{sequence:o,platform:x.platform,credentialDigest:await m(P)}));l(v);let he=X.response.parse(await d(X.path,le,P));l(v);let Re=f(he.installation);if(!Re.bound||Re.identitySeq!==o)throw new b("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return _&&j.detachSeq!==null&&o>j.detachSeq&&Mn(x,Se=>({...Se,detachSeq:Se.detachSeq===j.detachSeq?null:Se.detachSeq})),Re}async function R(){u();let x=i,v=r?await(t.session?.access()??r):null;if(!v)throw new b("NOT_IDENTIFIED","Identify before reading this installation");let P=O.readPushInstallation,j=P.request.parse(await g("read",{credentialDigest:await m(v)}));l(x);let _=P.response.parse(await d(P.path,j,v));return l(x),f(_.installation)}function y(x=h){let v=s.catch(()=>{}).then(x);return s=v,v.catch(P=>{try{e?.onError?.(P instanceof Error?P:new Error("Push synchronization failed"))}catch{}}),v}async function A(x,v,P){let j=u(),_=v.identity,X=v.observation,le=r?await(t.session?.access()??r):null;if(l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");if(!le)throw new b("NOT_IDENTIFIED","Identify before recovering a Push address");if(!x.connectionId||!x.kind||!x.token||!["granted","provisional"].includes(x.permission))throw new b("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await y(async()=>{if(l(_),await h(),l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let he=Mn(j,je=>P?je:{...je,addressSeq:_o(je.addressSeq)}),Se=await g(P?"recovery_confirm":"recovery_request",{...x,sequence:he.addressSeq,credentialDigest:await m(le),...P?{challenge:P}:{}}),gt=P?Il.parse(Se):Sl.parse(Se);if(l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let Qe=await d(`push/installations/recovery/${P?"confirm":"request"}`,gt,le);if(l(_),X!==a||Mn(j,je=>je).addressSeq!==he.addressSeq)throw new b("INVALID_STATE","Push observation changed during recovery");if(P){let je=O.updatePushAddress.response.parse(Qe),et=f(je.installation);if(!et.bound||et.identitySeq!==o||et.addressSeq!==he.addressSeq||et.connectionId!==x.connectionId||et.addressStatus!=="active")throw new b("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return et}if(!Qe||typeof Qe!="object"||!("recovery"in Qe))throw new b("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return ws.parse(Qe.recovery)})}return{recoveryObserver(){u();let x={identity:i,observation:++a};return{async request(v){return ws.parse(await A(v,x))},async confirm(v,P){return Sr.parse(await A(P,x,v))}}},identify(x){if(!e)return;o=Mn(e,P=>({...P,identitySeq:_o(P.identitySeq)})).identitySeq,r=x,i++,a++},reset(){if(e)try{Mn(e,x=>{let v=_o(x.identitySeq);return{...x,identitySeq:v,detachSeq:v}})}finally{r=null,i++,a++}},start(){e&&!c&&y()},destroy(){c=!0,r=null,i++,a++},async sync(){return await y()},read:R,async recover(){let x=u(),v=i,P=o;return a++,await y(async()=>{l(v);let j=await R();return l(v),o=Mn(x,X=>{if(X.identitySeq!==P)throw new b("IDENTITY_CHANGED","A newer installation intent exists");return{...X,identitySeq:_o(Math.max(X.identitySeq,j.identitySeq)),addressSeq:Math.max(X.addressSeq,j.addressSeq)}}).identitySeq,await h()})},tokenObserver(){u();let x=++a,v=i;return async P=>{if(x!==a||v!==i)return null;let j=u(),_=r?await(t.session?.access()??r):null;if(!_)throw new b("NOT_IDENTIFIED","Identify before registering a Push token");if(await y(),l(v),x!==a)return null;let X=Mn(j,Se=>({...Se,addressSeq:_o(Se.addressSeq)})),le=O.updatePushAddress,he=le.request.parse(await g("address",{...P,sequence:X.addressSeq,credentialDigest:await m(_)}));if(l(v),x!==a)return null;let Re=await d(le.path,he,_);return l(v),x!==a||Mn(j,Se=>Se).addressSeq!==X.addressSeq?null:f(le.response.parse(Re).installation)}}}}import{ZodError as OI}from"zod";function uh(e,t,n,r){try{return e.parse(t)}catch(i){throw r&&i instanceof OI?new b(n,r):i}}async function ge(e,t,n,r={},i){let a=typeof r=="function"?{}:r,o=uh(t.request,n,"INVALID_REQUEST",a.request);try{let s=await e(t.path,o,t.method,i),c=typeof r=="function"?r:r.parseResponse;return c?c(t.response,s):uh(t.response,s,"INVALID_RESPONSE",a.response)}catch(s){throw s instanceof b&&o!==null&&typeof o=="object"&&"requestId"in o&&typeof o.requestId=="string"&&(s.commandRequestId??(s.commandRequestId=o.requestId)),s}}function lh(e,t){let n={async preference(r){let i=O.readMessagingPreference;return(await ge(e,i,{channel:r})).preference},async setPreference(r){let i=O.setMessagingPreference;return(await ge(e,i,r)).preference}};return{messaging:n,push:{sync:t.sync,read:t.read,recover:t.recover,tokenObserver:t.tokenObserver,recoveryObserver:t.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return n.setPreference({...r,channel:"push"})}}}}var dh={name:"@tinkerlandai/longplay-sdk",version:"0.10.16",description:"Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit && tsc --noEmit -p tsconfig.test.json",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};function He(e){return typeof e=="string"?e:String(e)}var CI=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function _I(e){return e.replace(CI,"$1\uFFFD")}function Ku(e,t){if(typeof e!="object"||e==null){let n="";throw n+="The provided value is not an object",new TypeError(n)}return e}function xh(e){if(e!=null&&(typeof e=="object"||typeof e=="function")){let t=e[Symbol.iterator];if(t==null)return;if(typeof t!="function")throw new TypeError("The provided value is not iterable");let n=t.call(e);if(!n||typeof n!="object")throw new TypeError("Result of the Symbol.iterator method is not an object");return n}}function ph(e){let t;if(Array.isArray(e)){let n=e.map(He);if(n.length===2)return n}else if((t=xh(e))!=null){let n=Ku(t.next()),r=Ku(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 mh="0123456789ABCDEF",EI=/(?:%[0-9A-Fa-f]{2})+/g;function qn(e){return`%${mh[e>>4&15]}${mh[15&e]}`}function Sh(e,t,n=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?n&&e===32?"+":t(e)?qn(e):String.fromCharCode(e):e<=2047?qn(192|e>>6)+qn(128|63&e):e<=65535?qn(224|e>>12)+qn(128|e>>6&63)+qn(128|63&e):qn(240|e>>18)+qn(128|e>>12&63)+qn(128|e>>6&63)+qn(128|63&e)}function Hu(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function Qu(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(EI,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function ko(e){return e<=31||e>126}function RI(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return ko(e)}}function tl(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return ko(e)}}function kI(e){return tl(e)||e===39}function Ju(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return tl(e)}}function ps(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 Ju(e)}}function fh(e){switch(e){case 33:case 39:case 40:case 41:case 126:return!0;default:return(function(n){switch(n){case 36:case 37:case 38:case 43:case 44:return!0;default:return ps(n)}})(e)}}function Ih(e,t){return Sh(e=e||0,t)}function Un(e,t,n=!1){let r=0;for(;r<e.length;r++){let a=e.charCodeAt(r);if(a>=128||n&&a===32||t(a))break}if(r===e.length)return e;let i=e.slice(0,r);for(;r<e.length;r++){let a=e.charCodeAt(r),o=a;if(a>=55296&&a<=56319&&r+1<e.length){let s=e.charCodeAt(r+1);s>=56320&&s<=57343&&(o=(a-55296<<10)+s-56320+65536,r++)}i+=Sh(o,t,n)}return i}function nl(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([Qu(i.slice(0,a),!0),Qu(i.slice(a+1),!0)])}if(n=r+1,r===e.length)break}return t}function Zu(e){let t="";for(let n=0;n<e.length;n++){let r=Un(e[n][0],fh,!0),i=Un(e[n][1],fh,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var jI=[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],TI=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],NI=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],DI=[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 FI(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[MI,qI,UI,gh]=[[[],"0,6,7,8,m,w,10,1b,1d,1f,72,73,7k,8k,dt,2rk","AAAAAAAAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAA/AAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAADAAABwfwAAAAAAAMADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhAAAAQAAAAAAAAQCAAABAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgACAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAP///////////////wAAAAAAAAAAAAAAAAAAAAA="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAEF9+P/+BwAAAMAA//8AAPz/////BlADAAAAAJwAAPz///8AAADA//H/5+X8AAAAAAAAAAAA/P///wcAAAAAAAAAAAAAPv0vAD0BAABA/gAA/5/5/f8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8g+N8B+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAYAAAAAAAAAAAAAD/////CwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANgAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/HgwAAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAP3////+BwAAAMDu//////////////8vAADAAJwAAP3///8AAADg////////AAAAAAAAAAAA/P///wcAAAAAAAAAAAAA////Ab0H//9H/gAA/9////8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL/G//8T+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAfgAAAAAAAAAAAAD+////DwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANwAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/Hg4AAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"0,3,4,5,6,7,8,9,a,b,c,d,e,f,g,j,n,o,p,q,r,s,t,w,18,19,1c,4m,4o,4p,4q,4r,6z,72,73,75,76,77,7e,7h,7i,7j,7k,7l,7m,7n,7o,7p,7q,7r,7s,7t,7u,7v,7w,7x,7y,7z,8k,9t,a2,a3,a7,cc,cv,cx,cy,d6,dc,dd,de,dg,dh,di,dk,dl,2rk,2rl","AAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAD//////////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD4AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/v////+/tgAAAAAAAAAAAP8XAAAAAAD4//8AAAEAAAAAAAAAAAAAAMCfnz0AAACAAgAAAP///wcAAAAAAAAAAAAAwP8BAAAAAAAA+A8gAADA++8+AAAAAAAOAAAAAAAAgP8AAAAAAPz///v///8HAAAAAAAAFP4h/gAMAAAAAgAAAAAAABAeIAAADAAAQAYAAAAAAAAQhjkCAAAAIwAGAAAAAAAAEL4hAAAMAAD8AgAAAAAAAJAeIGAADAAAAAQAAAAAAAAAASAAAAAAAAARAAAAAAAA0ME9YAAMAAAAAgAAAAAAAJBAMAAADAAAAAMAAAAAAAAYHiAAAAwAAAACAAAAAAAAAAAEXAAAAAAAAAAAAAAA8geAfwAAAAAAAAAAAAAAAPIfAH8AAAAAAAAAAAADAACgAgAAAAAAAP5/3+D//v///x9AAAAAAAAAAAAAAAAA4P1mAAAAwwEAHgBkIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAAAAMAAAADAAAAAwAAAAAAAAAsD9A/g8gAAAAAAC4AAAAAAAAAAAAAAAAAABgAAAAAAIAAAAAAAAAAAAAAAAAAIcBBA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAJAAAAAAAAQH/lH/ifAAAAAAAA//////8//w8AAA8AAAAAANAXBAAAAAD4DwADAAAAPDsAAAAAAABAowMAAAAAAADwzwAAAAAAAAAAAAAAAAAAAAAAAAD3//0hEAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////wDIAAAAfAAAAAAAAB/8AAAAAAAAAAAAAAAA/////wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAwAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAA/////wAAAAAAPAAAAAAAAAAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAID3PwAAAMAAAAAAAAAAAAAAAwBECAAAYBAAAAAAAAAAAAAAAAAAAAAAAAAwAAAA//8DgAAAAADAPwAAgP8DAAAAAAAHAAAAAADIMwAAAAAgAAAAAAAAAAB+ZgAIEAAAAAAAEAAAAAAAAJ3BAgAAAAAwQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICEAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8AAP//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAMAHAAAAAAAAAAAAAAAAAAAAAG7wAAAAAACHAAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAPAAAAAAAAAAAD4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAAAAAAAAA/AAAAAAAAAAAwP8BAAAAAAA8AAAAAAAAAAAAAAAAAAAAAgAAAAAAAP9/AAAAAAAZgAMAAAAAAHgGBAAAAAAAAAAHAAAAgO8fAAAAAAAAAAgAAwAAAAAAwH8AngAAAAAAAAAAAAAAgNNAAgAAAAAAAAAAAAAAAAAAAAAAAID4BwAAAwAAAAAAABgBAAAAwB8fAAAAAAAAAAD4AUAFAAYAAAAAAAAAAAAA/1wAAEAAAAAAAAAAAAAA+IUNAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8sAEAADAAAAAAAAAAAAAA+KcBAAAAAAAAAAAAAAAAKL8AAAAAAAAAAAAAAACgvA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgP8GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFgIAAAAAAAAAAAAAAAAAAAAAADwDAEAAAD+BwAAAAD4eYAAfg4AAAAAAPx/AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf78AAAAAAAAAAAAA/P///G0AAAAAAAAAAAAAAAAAAAB+tL8AAAAAAAAAAACjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAAwAAAAAAwAcFAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//4H/PwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMD/4wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHwAAAAAAAAB/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAgAcAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGAPAAAAAAAAAAAAAAD//////z///38AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAD+P/nDwAAADwAAAAAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////9/+P//////HyAAEAAA+P7/AAAAAAAAAAAAAH////nbBwAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASMAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAADwDwAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAA////////////////AAAAAAAAAAAAAAAAAAAAAP///////////////////////////////////////wAA"]].map(function([t,n,r]){return[t,n.split(",").map(i=>parseInt(i,36)),Uint8Array.from(atob(r),i=>i.charCodeAt(0))]});function BI(e,t){return t===931||t===1010||t===120531||t===120589||t===120647||t===120705||t===120763?"\u03C3":t>=5112&&t<=5117?String.fromCodePoint(t-8):t>=43888&&t<=43967?String.fromCodePoint(t-38864):t>=93856&&t<=93880?String.fromCodePoint(t+27):t===837||t===890||t>=8064&&t<=8111||t>=8114&&t<=8188?e.normalize("NFD").replace(/\u0345/g,"\u03B9").normalize("NFC").toLowerCase():""}function vh(e,t){for(let n=0;n<e.length;n+=2)if(t>=e[n]&&t<=e[n+1])return!0;return!1}function Eo(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 VI(e){let t=Array.from(e,n=>n.codePointAt(0));for(let n=0;n<t.length;n++){let r=t[n];if(r!==8204&&r!==8205||n>0&&vh(DI,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&Eo(gh,t[i]);)i--;let a=n+1;for(;a<t.length&&Eo(gh,t[a]);)a++;if(!(i>=0&&a<t.length&&Eo(qI,t[i])&&Eo(UI,t[a])))return!1}return!0}var LI=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,zI=/\p{Script=Latin}/u;function $I(e){return!LI.test(e)||!zI.test(e)}var lr=36,us=1,Wu=26,GI=38,KI=700,HI=72,QI=128,JI=2147483647;function hh(e){return String.fromCharCode(e+22+75*+(e<26))}function ZI(e,t,n){let r=0;for(e=n?Math.floor(e/KI):e>>1,e+=Math.floor(e/t);e>(lr-us)*Wu>>1;r+=lr)e=Math.floor(e/(lr-us));return Math.floor(r+(lr-us+1)*e/(e+GI))}function WI(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=QI,o=0,s=HI;for(;r<t.length;){let c=JI;for(let u=0;u<t.length;u++){let l=t[u];l>=a&&l<c&&(c=l)}o+=(c-a)*(r+1),a=c;for(let u=0;u<t.length;u++){let l=t[u];if(l<a&&o++,l===a){let m=o;for(let f=lr;;f+=lr){let g=f<=s?us:f>=s+Wu?Wu:f-s;if(m<g)break;n+=hh(g+(m-g)%(lr-g)),m=Math.floor((m-g)/(lr-g))}n+=hh(m),s=ZI(o,r+1,r===i),o=0,r++}}o++,a++}return n}function zu(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=Hu(e.charCodeAt(r));if(i>=t||i<0)return-1;n=n*t+i}return n}function yh(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function wh(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function Oh(e){return e.length===2&&wh(e.codePointAt(0),e.codePointAt(1))}function Ah(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function mt(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function Ph(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function Yu(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=Hu(c[s]))>=0;)l=(l<<4)+u,s++,m++;if(c[s]===46){if(m===0||o>6)return null;s-=m;let f=0;for(;c[s]!==void 0;){let g=0;if(f>0)if(c[s]===46&&f<4)s++;else return null;if(c[s]==null||c[s]<48||c[s]>57)return null;for(;c[s]>=48&&c[s]<=57;){if(g=10*g+Hu(c[s]),g>255)return null;s++}i[o]=256*i[o]+g,f++,f%2==0&&o++}if(f!==4)return null;break}else if(c[s]===58){if(c[++s]===void 0)return null}else if(c[s]!==void 0)return null;i[o]=l,o++}if(a!==null){let u=o-a;for(o=7;o!==0&&u>0;){let l=i[a+u-1];i[a+u-1]=i[o],i[o]=l,o--,u--}}else if(a===null&&o!==8)return null;return i})(e.substring(1,e.length-1)):null;if(t)return(function(r){return Ah(r)?null:Un(r,ko)})(e);{let n=(function(i){let a=!1,o=!1;for(let c=0;c<i.length;c++){let u=i.charCodeAt(c);if(u<=32||u===37||u===127)return null;if(u>=128){a=!0;break}u>=65&&u<=90&&(o=!0)}if(!a)return i!==""?o?i.toLowerCase():i:null;if((function(u){for(let l of u){let m=l.codePointAt(0);if(/[\p{Cn}\p{Co}\p{Cs}\p{Noncharacter_Code_Point}]/u.test(l)&&!vh(jI,m)||Eo(MI,m))return!0}return!1})(i))return null;let s=(i=(function(u){let l="";for(let m of u){let f=m.codePointAt(0);if(f!==8204&&f!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(m))continue;let g=BI(m,f);if(g){l+=g;continue}let d=TI.indexOf(f);l+=d<0?m:NI[d]}return l})(i).normalize("NFKC").replace(/[\u3002\uff0e\uff61]/g,".").toLowerCase()).split(".");for(let c=0;c<s.length;c++){let u=s[c];if(u==="")continue;let l=/[^\0-\x7f]/.test(u);if(FI(u)||l&&(/^\p{Mark}/u.test(u)||!VI(u)||!$I(u)||u.startsWith("xn--")))return null;l&&(s[c]=`xn--${WI(u)}`)}return(i=s.join("."))!==""?i:null})(e.indexOf("%")===-1?e:Qu(e));return n===null||Ah(n)?null:(function(i){let a=i.length,o=i.lastIndexOf(".",a-2)+1;if(i.charCodeAt(a-1)===46&&a--,a<=o)return!1;if(zu(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=zu(a[u]);if(l<0||l>255)return null;s+=l*(1<<8*(3-u))}let c=zu(a[o-1]);return c<0||c>=256**(5-o)?null:(s+=c,s)})(n):n}}function Xu(e){return typeof e=="number"?(function(n){let i="";return i+=`${(n>>>24&255).toString(10)}.`,i+=`${(n>>>16&255).toString(10)}.`,i+=`${(n>>>8&255).toString(10)}.`,i+=(n&255).toString(10),i})(e):Array.isArray(e)?`[${(function(n){let r=(function(s){let c=-1,u=-1,l=1,m=0;for(let f=0;f<s.length;++f)s[f]!==0?(m>l&&(c=u,l=m),u=-1,m=0):(u===-1&&(u=f),++m);return m>l?u:c})(n),i="",a=!1;for(let o=0;o<=7;++o)if(!(a&&n[o]===0)){if(a&&(a=!1),r===o){i+=o===0?"::":":",a=!0;continue}i+=n[o].toString(16),o!==7&&(i+=":")}return i})(e)}]`:e}function Ch(e){e.path.length>0&&(e.path.length!==1||e.scheme!=="file"||!(function(n){return/^[A-Za-z]:$/u.test(n)})(e.path[0]))&&e.path.pop()}function _h(e){return e.username!==""||e.password!==""}function $u(e){return e.host===null||e.host===""||e.scheme==="file"}var E=0,U="",Oe="",Ve=null,B,ls=!1,ds=!1,Gr=!1,ft;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),E=0,U=e,Oe="",Ve=n||null,B=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},ls=!1,ds=!1,Gr=!1,ft=r||0;let i=YI;switch(r){case 3:case 4:i=ms;break;case 5:i=il;break;case 6:i=Kr;break;case 7:i=dr;break;case 8:i=Bn}return i(G(e,E))!==1?B:null}function ee(e,t){return E+=E===e?jn(t):1,E<=U.length}function G(e,t){return t<e.length?e.codePointAt(t):void 0}function jn(e){return e!=null&&e>65535?2:1}function Eh(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var YI=e=>{let t=E;if(e!=null&&(e>=65&&e<=90||e>=97&&e<=122)){let n=E+1;for(e=U.charCodeAt(n);e===43||e===45||e===46||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57;)n++,e=U.charCodeAt(n);return Oe=U.slice(E,n).toLowerCase(),E=n,XI(n<U.length?e:void 0)}else return ft?1:(--E,ee(t,e)?Rh(G(U,E)):0)},XI=e=>{let t=E;if(e===58){if(ft){if(mt(B.scheme)!==mt(Oe))return 0;if((_h(B)||B.port!==null)&&Oe==="file")return 0;if(B.scheme==="file"&&B.host==="")return 0}return B.scheme=Oe,ft?(B.port===Ph(B.scheme)&&(B.port=null),0):(Oe="",B.scheme==="file"?ee(t,e)?ol(G(U,E)):0:mt(B.scheme)&&Ve!==null&&Ve.scheme===B.scheme?ee(t,e)?ev(G(U,E)):0:mt(B.scheme)?ee(t,e)?nv(G(U,E)):0:G(U,E+1)===47?(E++,ee(t,e)?tv(G(U,E)):0):(B.path=[""],B.opaquePath=!0,ee(t,e)?jh(G(U,E)):0))}else return ft?1:(Oe="",E=-1,ee(t,e)?Rh(G(U,E)):0)},Rh=e=>{let t=E;return Ve===null||Ve.opaquePath&&e!==35?1:Ve.opaquePath&&e===35?(B.scheme=Ve.scheme,B.path=Ve.path.slice(),B.opaquePath=Ve.opaquePath,B.query=Ve.query,B.fragment="",ee(t,e)?Bn(G(U,E)):0):Ve.scheme==="file"?(E--,ee(t,e)?ol(G(U,E)):0):(E--,ee(t,e)?rl(G(U,E)):0)},ev=e=>{let t=E;return e===47&&G(U,E+1)===47?(++E,ee(t,e)?gs(G(U,E)):0):(E--,ee(t,e)?rl(G(U,E)):0)},tv=e=>{let t=E;return e===47?ee(t,e)?Ti(G(U,E)):0:(E--,ee(t,e)?Tn(G(U,E)):0)},rl=e=>{let t=E;return B.scheme=Ve.scheme,e===47||mt(B.scheme)&&e===92?ee(t,e)?bh(G(U,E)):0:(B.username=Ve.username,B.password=Ve.password,B.host=Ve.host,B.port=Ve.port,B.path=Ve.path.slice(),B.query=Ve.query,e===63?(B.query="",ee(t,e)?dr(G(U,E)):0):e===35?(B.fragment="",ee(t,e)?Bn(G(U,E)):0):e!=null?(B.query=null,B.path.pop(),E--,ee(t,e)?Tn(G(U,E)):0):ee(t,e)?rl(G(U,E)):0)},bh=e=>{let t=E;return mt(B.scheme)&&(e===47||e===92)?ee(t,e)?gs(G(U,E)):0:e===47?ee(t,e)?Ti(G(U,E)):0:(B.username=Ve.username,B.password=Ve.password,B.host=Ve.host,B.port=Ve.port,E--,ee(t,e)?Tn(G(U,E)):0)},nv=e=>{let t=E;return e===47&&G(U,E+1)===47?E++:E--,ee(t,e)?gs(G(U,E)):0},gs=e=>{let t=E;return e!==47&&e!==92?(E--,ee(t,e)?Ti(G(U,E)):0):ee(t,e)?gs(G(U,E)):0},Ti=e=>{let t=E;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!mt(B.scheme))){let n=E+jn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===64||r===35||r===47||r===63||r===92&&mt(B.scheme))break;n+=jn(r)}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?Ti(G(U,E)):0}if(e===64){ls&&(Oe=`%40${Oe}`),ls=!0;for(let n=0;n<Oe.length;n++){let r=Oe.codePointAt(n);if(r===58&&!ds){ds=!0;continue}let i=Ih(r,ps);ds?B.password+=i:B.username+=i,r!=null&&r>65535&&n++}return Oe="",ee(t,e)?Ti(G(U,E)):0}else return e==null||e===35||e===47||e===63||e===92&&mt(B.scheme)?ls&&Oe===""?1:(E-=Oe.length+1,Oe="",ee(t,e)?ms(G(U,E)):0):(Oe+=Eh(e),ee(t,e)?Ti(G(U,E)):0)},ms=e=>{let t=E;if(ft&&B.scheme==="file")return E--,ee(t,e)?al(G(U,E)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!mt(B.scheme))){let n=E+jn(e);for(e===91?Gr=!0:e===93&&(Gr=!1);n<U.length;){let r=G(U,n);if(r==null||!Gr&&r===58||r===35||r===47||r===63||r===92&&mt(B.scheme))break;r===91?Gr=!0:r===93&&(Gr=!1),n+=jn(r)}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?ms(G(U,E)):0}else if(e===58&&!Gr){if(Oe===""||ft===4)return 1;let n=Yu(Oe,!mt(B.scheme));return n===null?1:(B.host=Xu(n),Oe="",ee(t,e)?il(G(U,E)):0)}else if(e==null||e===35||e===47||e===63||e===92&&mt(B.scheme)){if(E--,mt(B.scheme)&&Oe==="")return 1;if(ft&&Oe===""&&(_h(B)||B.port!==null))return 1;let n=Yu(Oe,!mt(B.scheme));return n===null?1:(B.host=Xu(n),Oe="",ft?0:ee(t,e)?Kr(G(U,E)):0)}else return Oe+=Eh(e),ee(t,e)?ms(G(U,E)):0},il=e=>{let t=E;if(e!=null&&e>=48&&e<=57){let n=E+1;for(;n<U.length;){let r=U.charCodeAt(n);if(r<48||r>57)break;n++}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?il(G(U,E)):0}else if(ft||e==null||e===35||e===47||e===63||e===92&&mt(B.scheme)){if(Oe!==""){let n=parseInt(Oe,10);if(n>65535)return 1;if(B.port=n===Ph(B.scheme)?null:n,Oe="",ft)return 0}return ft?1:(E--,ee(t,e)?Kr(G(U,E)):0)}else return 1};function kh(e,t){let n=e.length-t;if(n<2)return!1;if(wh(G(e,t),G(e,t+1))){if(n===2)return!0;{let r=G(e,t+2);return r===47||r===92||r===63||r===35}}else return!1}var ol=e=>{let t=E;return B.scheme="file",B.host="",e===47||e===92?ee(t,e)?rv(G(U,E)):0:Ve?.scheme==="file"?(B.host=Ve.host,B.path=Ve.path.slice(),B.opaquePath=Ve.opaquePath,B.query=Ve.query,e===63?(B.query="",ee(t,e)?dr(G(U,E)):0):e===35?(B.fragment="",ee(t,e)?Bn(G(U,E)):0):e!=null?(B.query=null,kh(U,E)?B.path=[]:Ch(B),E--,ee(t,e)?Tn(G(U,E)):0):ee(t,e)?ol(G(U,E)):0):(E--,ee(t,e)?Tn(G(U,E)):0)},rv=e=>{let t=E;return e===47||e===92?ee(t,e)?al(G(U,E)):0:(Ve!==null&&Ve.scheme==="file"&&(!kh(U,E)&&(function(r){if(r.length===2){let i=r.codePointAt(0),a=r.codePointAt(1);return(i>=65&&i<=90||i>=97&&i<=122)&&a===58}else return!1})(Ve.path[0])&&B.path.push(Ve.path[0]),B.host=Ve.host),E--,ee(t,e)?Tn(G(U,E)):0)},al=e=>{let t=E;if(e!=null&&e!==47&&e!==92&&e!==63&&e!==35){let n=E+jn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===47||r===92||r===63||r===35)break;n+=jn(r)}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?al(G(U,E)):0}else if(e==null||e===47||e===92||e===63||e===35){if(E--,!ft&&Oh(Oe))return ee(t,e)?Tn(G(U,E)):0;if(Oe==="")return B.host="",ft?0:ee(t,e)?Kr(G(U,E)):0;{let n=Yu(Oe,!mt(B.scheme));return n===null?1:(n==="localhost"&&(n=""),B.host=Xu(n),Oe="",ft?0:ee(t,e)?Kr(G(U,E)):0)}}return 1},Kr=e=>{let t=E;return mt(B.scheme)?(e!==92&&e!==47&&E--,ee(t,e)?Tn(G(U,E)):0):!ft&&e===63?(B.query="",ee(t,e)?dr(G(U,E)):0):!ft&&e===35?(B.fragment="",ee(t,e)?Bn(G(U,E)):0):e!=null?(e!==47&&E--,ee(t,e)?Tn(G(U,E)):0):(ft&&B.host===null&&B.path.push(""),ee(t,e)?Kr(G(U,E)):0)},Tn=e=>{let t=E;if(e!=null&&e!==47&&(!mt(B.scheme)||e!==92)&&(ft||e!==63&&e!==35)){let n=E+jn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===47||mt(B.scheme)&&r===92||!ft&&(r===63||r===35))break;n+=jn(r)}Oe+=Un(U.slice(E,n),Ju),E=n,e=G(U,n)}if(e==null||e===47||mt(B.scheme)&&e===92||!ft&&(e===63||e===35)){let n=mt(B.scheme)&&e===92;return(function(i){switch(i){case"..":case"%2e.":case"%2E.":case".%2e":case".%2E":case"%2e%2e":case"%2E%2e":case"%2e%2E":case"%2E%2E":return!0;default:return!1}})(Oe)?(Ch(B),e!==47&&!n&&B.path.push("")):yh(Oe)&&e!==47&&!n?B.path.push(""):yh(Oe)||(B.scheme==="file"&&B.path.length===0&&Oh(Oe)&&(Oe=`${Oe[0]}:`),B.path.push(Oe)),Oe="",e===63?(B.query="",ee(t,e)?dr(G(U,E)):0):e===35?(B.fragment="",ee(t,e)?Bn(G(U,E)):0):ee(t,e)?Tn(G(U,E)):0}else return Oe+=Ih(e,Ju),ee(t,e)?Tn(G(U,E)):0},jh=e=>{let t=E;if(e===63)return B.query="",ee(t,e)?dr(G(U,E)):0;if(e===35)return B.fragment="",ee(t,e)?Bn(G(U,E)):0;if(e!=null){let n=E+jn(e);for(;n<U.length;){let i=G(U,n);if(i===63||i===35)break;n+=jn(i)}let r=U.slice(E,n);if(n<U.length&&r.charCodeAt(r.length-1)===32?B.path[0]+=Un(r.slice(0,-1),ko)+"%20":B.path[0]+=Un(r,ko),E=n,(e=G(U,n))===63)return B.query="",ee(t,e)?dr(G(U,E)):0;if(e===35)return B.fragment="",ee(t,e)?Bn(G(U,E)):0}return ee(t,e)?jh(G(U,E)):0},dr=e=>{let t=E,n=E;if(e!=null){if(ft)n=U.length;else{let i=U.indexOf("#",E);n=i===-1?U.length:i}let r=mt(B.scheme)?kI:tl;B.query+=Un(U.slice(E,n),r)}return E=n,G(U,n)===35&&!ft?(B.fragment="",ee(t,e)?Bn(G(U,E)):0):ee(t,e)?dr(G(U,E)):0},Bn=e=>{let t=E;return e!=null&&(B.fragment+=Un(U.slice(E),RI),E=U.length),ee(t,e)?Bn(G(U,E)):0};function el(e){if(e.opaquePath)return e.path[0];{let t="";for(let n of e.path)t+=`/${n}`;return t}}function Th(e){switch(e.scheme){case"blob":{let t=mn(el(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":Th(t)}case"ftp":case"http":case"https":case"ws":case"wss":return(function(n){let r=`${n.scheme}://`;return r+=n.host,n.port!==null&&(r+=`:${n.port}`),r})(e);default:return"null"}}var Ke=Symbol("URLImpl"),bn=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[Ke]={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+=el(n),n.query!==null&&(r+=`?${n.query}`),n.fragment!==null&&(r+=`#${n.fragment}`),r})(this[Ke].url)}set href(t){let n=mn(t=He(t),null,null,0);if(n==null)throw new TypeError(`Invalid URL: ${t}`);this[Ke].url=n,this[Ke].query&&Gu(this[Ke].query,n.query)}get origin(){return Th(this[Ke].url)}get protocol(){return`${this[Ke].url.scheme}:`}set protocol(t){mn(`${t=He(t)}:`,this[Ke].url,null,2)}get username(){return this[Ke].url.username}set username(t){t=He(t),$u(this[Ke].url)||(function(r,i){r.username=Un(i,ps)})(this[Ke].url,t)}get password(){return this[Ke].url.password}set password(t){t=He(t),$u(this[Ke].url)||(function(r,i){r.password=Un(i,ps)})(this[Ke].url,t)}get host(){let{url:t}=this[Ke];return t.host==null?"":t.port==null?t.host:`${t.host}:${t.port}`}set host(t){t=He(t),this[Ke].url.opaquePath||mn(t,this[Ke].url,null,3)}get hostname(){let{url:t}=this[Ke];return t.host!=null?t.host:""}set hostname(t){t=He(t),this[Ke].url.opaquePath||mn(t,this[Ke].url,null,4)}get port(){let{url:t}=this[Ke];return t.port!=null?`${t.port}`:""}set port(t){t=He(t);let{url:n}=this[Ke];$u(n)||(t?mn(t,n,null,5):n.port=null)}get pathname(){return el(this[Ke].url)}set pathname(t){t=He(t);let{url:n}=this[Ke];n.opaquePath||(n.path=[],mn(t,n,null,6))}get search(){let{url:t}=this[Ke];return t.query?`?${t.query}`:""}set search(t){t=He(t);let{url:n,query:r}=this[Ke];if(!t)n.query=null,r&&Gu(r,null);else{let i=t[0]==="?"?t.substring(1):t;n.query="",mn(i,n,null,7),r&&Gu(r,n.query)}}get searchParams(){let t=this[Ke],n=t.query;return n==null&&(n=t.query=(function(i,a){let o=new fs;return o[at].url=i,o[at].serialized=a==null,a&&(o[at].list=nl(a)),o})(this,t.url.query)),n}get hash(){let{url:t}=this[Ke];return t.fragment?`#${t.fragment}`:""}set hash(t){t=He(t);let{url:n}=this[Ke];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(bn.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var at=Symbol("URLSearchParamsImpl"),iv=Symbol.dispose||Symbol.for("dispose");function Gu(e,t){t?e[at].list=nl(t):e[at].list.length=0,e[at].serialized=t==null}function cs(e){if(e.url){let t=Zu(e.list);(function(r,i){r[Ke].url.query=i})(e.url,t||null),e.serialized=!0}}var ov=typeof Iterator<"u"?Iterator:Object,Ro=class extends ov{constructor(t,n){super(),this[at]={ptr:t,map:n,index:0}}next(){let t=this[at];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}[iv](){}},fs=class{constructor(t){let n=this[at]={list:[],url:null,serialized:!0},r;if(Array.isArray(t))for(let i=0;i<t.length;i++)n.list.push(ph(t[i]));else if((r=xh(t))!=null){let i;for(;!(i=Ku(r.next())).done;)n.list.push(ph(i.value))}else if((typeof t=="object"||typeof t=="function")&&t!=null){let i=Object.keys(t);for(let a=0;a<i.length;a++){let o=i[a],s=_I(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=nl(i)}}get size(){return this[at].list.length}append(t,n){t=He(t),n=He(n),this[at].list.push([t,n]);let r=this[at];r.url&&r.serialized?(function(a,o){let s=a[Ke].url;s.query=s.query?`${s.query}&${o}`:o})(r.url,Zu([[t,n]])):cs(r)}delete(t,n){t=He(t),n=n!=null?He(n):void 0;let{list:r}=this[at],i=0;for(;i<r.length;)r[i][0]===t&&(n==null||r[i][1]===n)?r.splice(i,1):i++;cs(this[at])}get(t){t=He(t);let{list:n}=this[at];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[at];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[at];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[at],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&&cs(this[at])}sort(){this[at].list.sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0),cs(this[at])}forEach(t,n){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:r}=this[at];for(let i=0;i<r.length;i++)t.call(n,r[i][1],r[i][0],this)}entries(){return new Ro(this[at],t=>t)}keys(){return new Ro(this[at],t=>t[0])}values(){return new Ro(this[at],t=>t[1])}toString(){return Zu(this[at].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(fs.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var pr="https://api.longplayai.com";function Nh(e){let t,n=()=>typeof t=="string"?t:t?.accessToken,r=0,i,a=new Map,o=()=>{for(let m of[...a.keys()])try{m()}catch{}};function s(m){let f=++r;i=void 0,t=void 0;for(let g of[...a.values()])try{g?.()}catch{}f===r&&(t=m,o())}let c=()=>s();function u(m,f=!1){let g=Zn.safeParse(m);if(!g.success||f&&Date.parse(g.data.expiresAt)<=Date.now()||Date.parse(g.data.refreshExpiresAt)<=Date.now()||Date.parse(g.data.refreshExpiresAt)<Date.parse(g.data.expiresAt))throw new b("INVALID_RESPONSE","Invalid customer session credentials");return g.data}async function l(){if(i)return i;let m=typeof t=="object"?t:void 0,f=r;if(!m||Date.parse(m.refreshExpiresAt)<=Date.now())throw m&&c(),new b("UNAUTHENTICATED","Customer authentication is required",401);let g=(async()=>{try{let d=await e(m.refreshToken);if(f!==r)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");let h=u(d,!0);if(h.customerId!==m.customerId||h.sessionId!==m.sessionId)throw new b("SCOPE_MISMATCH","Refresh changed the customer session");return t=h,{...h}}catch(d){throw f!==r?new b("IDENTITY_CHANGED","Customer identity changed during refresh"):(d instanceof b&&d.status===401&&c(),d)}})();i=g;try{return await g}finally{i===g&&(i=void 0)}}return{identify(m){let f=typeof m=="string"?m:u(m),g=typeof f=="string"?f:f.accessToken;if(!g.trim()||/\s/.test(g)||g.length>4096)throw new b("INVALID_TOKEN","A server-issued token is required");s(f)},reset:c,subscribeIdentity(m,f){return a.set(m,f),()=>{a.delete(m)}},access(){let m=typeof t=="object"?t:void 0;if(m&&Date.parse(m.expiresAt)<=Date.now()+3e4){let g=r;return l().then(()=>{let d=n();if(g!==r||!d)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");return d})}let f=n();if(!f)throw new b("NOT_IDENTIFIED","Identify a customer session before making a request");return f},peek:n,snapshot:()=>typeof t=="object"?{...t}:void 0,refresh:l}}var Dh=Symbol("IndianaNoContent");function mr(e,t,n=bn){let r=e.configuration?.scope,i=e.scope??(r&&{projectId:r.projectId,environment:r.environment}),a=i?Te.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??pr);if(o.username||o.password||o.search||o.hash)throw new b("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(o.protocol!=="https:"&&!(o.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(o.hostname)))throw new b("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let s=e.fetch??globalThis.fetch.bind(globalThis),c=e.timeoutMs??1e4;if(!Number.isFinite(c)||c<1||c>12e4)throw new b("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let u=!1,l=0,m=null,f=new Set,g=e.session??Nh(async A=>{let x=await y("customer-sessions/refresh",{},"POST",{},A);if(!x||typeof x!="object")throw new b("INVALID_RESPONSE","Invalid refresh response");let{requestId:v,scope:P,...j}=x;return j});function d(){l+=1,m=null;for(let A of f)A.abort();f.clear()}let h=g.subscribeIdentity(d);function R(){u||g.reset()}async function y(A,x={},v="POST",P={},j){let _=P.installationDetach===!0;if(_&&(A!=="push/installations/detach"||v!=="POST"))throw new b("INVALID_REQUEST","Installation authority only detaches this installation");if(!j&&!_)throw new b("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let X=l,le=new AbortController;_||f.add(le);let he=()=>!_&&X!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new b("TIMEOUT","Longplay request timed out"),Re,Se=new Promise((je,et)=>{Re=()=>et(he()),le.signal.addEventListener("abort",Re,{once:!0})}),gt=setTimeout(()=>le.abort(),P.timeoutMs??c),Qe=async()=>{let je=await s(`${o.href.replace(/\/$/,"")}/api/v1/${A}`,{method:v,headers:{...P.headers,"Content-Type":"application/json",..._?{}:{Authorization:`Bearer ${j}`},[Es]:Rs.current,[_l]:dh.version,...a?{"X-Indiana-Project":a.projectId,"X-Indiana-Environment":a.environment}:{}},body:v==="POST"?JSON.stringify(x):void 0,signal:le.signal,credentials:"omit",cache:"no-store",redirect:"error",...P.keepalive?{keepalive:!0}:{}});if(le.signal.aborted)throw he();let et;try{et=je.status===204?Dh:await je.json()}catch{throw le.signal.aborted?he():new b(je.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",je.status,je.headers.get("X-Request-Id")??void 0)}if(le.signal.aborted)throw he();if(!_&&X!==l)throw new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!je.ok){let dt=_s.safeParse(et),Jt=dt.success&&(!zn.safeParse(dt.data.error.code).success||Pl(dt.data.error.code,je.status)),yr=Jt?dt.data.error.code:"HTTP_ERROR",Ar=qo(yr,je.status,{retryAfter:je.headers.get("Retry-After"),recovery:Jt?dt.data.error.recovery:void 0,reason:Jt?dt.data.error.reason:void 0});throw new b(yr,Jt?dt.data.error.message:"Longplay request failed",je.status,je.headers.get("X-Request-Id")??(dt.success?dt.data.requestId:void 0),{...Ar,...dt.success&&dt.data.error.retryable===!1?{retryable:!1}:{},...Ar.retryAfterSeconds===void 0&&dt.success&&dt.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:dt.data.error.retryAfterSeconds}:{}})}if(je.headers.get(Es)!==Rs.current)throw new b("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&et!==Dh){let dt=et&&typeof et=="object"&&"scope"in et?et:et&&typeof et=="object"&&"configuration"in et?et.configuration:null;if(!dt||typeof dt!="object"||!("scope"in dt))throw new b("INVALID_RESPONSE","Response is missing its App/environment scope");let Jt=Te.safeParse(dt.scope);if(!Jt.success||Jt.data.projectId!==a.projectId||Jt.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let Qr=je.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 et};try{return await Promise.race([Qe(),Se])}catch(je){throw!_&&X!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):je instanceof b?je:new b(le.signal.aborted?"TIMEOUT":"NETWORK_ERROR",le.signal.aborted?"Longplay request timed out":"Unable to read the Longplay response")}finally{clearTimeout(gt),le.signal.removeEventListener("abort",Re),f.delete(le)}}return{session:g,requestWithCredential(A,x,v,P={}){return u?Promise.reject(new b("CLOSED","SDK client was destroyed")):y(A,x,"POST",P,v)},subjectKey:()=>m,identify(A){if(u)throw new b("CLOSED","SDK client was destroyed");if(a&&typeof A=="object"&&"scope"in A){let x=Te.safeParse(A.scope);if(!x.success||x.data.projectId!==a.projectId||x.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Customer session belongs to another App/environment")}g.identify(A)},reset:R,dispose(){u||(u=!0,h(),d())},request(A,x={},v="POST",P={}){if(u)return Promise.reject(new b("CLOSED","SDK client was destroyed"));if(P.installationDetach)return y(A,x,v,P);let j=l;try{let _=g.access(),X=le=>{if(j!==l)throw new b("IDENTITY_CHANGED","Customer identity changed before dispatch");return y(A,x,v,P,le)};return typeof _=="string"?X(_):_.then(X)}catch(_){return Promise.reject(_)}}}}function Fh(e,t,n={}){let r=!1;function i(){if(r)throw new b("CLOSED","SDK client was destroyed")}let a=new Set,o=c=>{for(let u of a)try{u(c)}catch{}},s=e.session.subscribeIdentity(()=>{o(!!e.session.peek()),n.afterChange?.()},()=>{t()});return{assertActive:i,isIdentified:()=>!r&&!!e.session.peek(),methods:{subscribeIdentity(c){return i(),a.add(c),()=>{a.delete(c)}},identify(c){i();let u=typeof c=="string"?c:c.accessToken;if(!kt.test(u))throw new b("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(u),e.identify(c)},reset(){if(!r)try{n.beforeReset?.()}finally{e.reset()}},destroy(){if(!r){r=!0,s(),a.clear();try{n.beforeDestroy?.(),t()}finally{e.dispose()}}}}}}function Le(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new b("INVALID_REQUEST","Customer requests use the verified session identity")}var av={...O.readHoldings,request:O.readHoldings.request.omit({customerId:!0})};function Mh(e){return{async checkEntitlement(t){Le(t);let n=O.checkEntitlement;return ge(e,n,t)},async readHoldings(t={}){return ge(e,av,t)}}}function qh(e){return{async readLedger(t){let n=O.readLedger;return ge(e,n,{query:t})},async readCreditStatement(t){Le(t);let n=O.readCreditStatement;return ge(e,n,t)},async quoteBalance(t){Le(t);let n=O.quoteBalance;return ge(e,n,{command:t})}}}function Uh(e){return{async setupPayment(t){Le(t);let n=O.setupPayment;return ge(e,n,t)},async readPaymentSetup(t){Le(t);let n=O.readPaymentSetup;return ge(e,n,t)},async readBillingInvoice(t){Le(t);let n=O.readBillingInvoice;return ge(e,n,t)},async readBillingControls(t={}){Le(t);let n=O.readBillingControls;return ge(e,n,t)},async prepareBillingAuthorization(t){Le(t);let n=O.prepareBillingAuthorization;return ge(e,n,t)},async confirmBillingAuthorization(t){Le(t);let n=O.confirmBillingAuthorization;return ge(e,n,t)},async setBillingCoupons(t){Le(t);let n=O.setBillingCoupons;return ge(e,n,t,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(t){Le(t);let n=O.revokeBillingAuthorization;return ge(e,n,t)},async listBillingInvoices(t={after:null,limit:25}){Le(t);let n=O.listBillingInvoices;return ge(e,n,t)},async confirmBillingAdjustment(t){Le(t);let n=O.confirmBillingAdjustment;return ge(e,n,t)}}}function Bh(e){return{async previewUpdate(t){Le(t);let n=O.previewUpdate;return ge(e,n,t)},async update(t){Le(t);let n=O.update;return ge(e,n,t)},async readSubscriptionUpdate(t){Le(t);let n=O.readSubscriptionUpdate;return ge(e,n,t)},async restoreNativePurchase(t){Le(t);let n=O.restoreNativePurchase;return ge(e,n,t)},async previewAttach(t){Le(t);let n=O.previewAttach;return ge(e,n,t)},async attach(t){Le(t);let n=O.attach;return ge(e,n,t)},async readSubscriptionOperation(t){Le(t);let n=O.readSubscriptionOperation;return ge(e,n,t)}}}function Vh(e){return{async redeemReward(t){return Le(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 Le(t),(await ge(e,O.claimRewardProduct,t,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(t){return Le(t),(await ge(e,O.createReferralCode,{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(t,n=crypto.randomUUID()){let r=await ge(e,O.redeemCoupon,{code:t,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(t,n=crypto.randomUUID()){let r=await ge(e,O.grantOffer,{couponId:t,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await ge(e,O.listOffers,{},{response:"Invalid offers response"})).offers}}}function Lh(e){return{...Mh(e),...qh(e),...Uh(e),...Bh(e),...Vh(e)}}function zh(e){return{async resolveContent(t){Le(t);let n=O.resolveContent;return ge(e,n,t)},async resolvePaywall(t){Le(t);let n=O.resolvePaywall;return ge(e,n,t)},async resolveOffering(t){Le(t);let n=O.resolveOffering;return ge(e,n,t)}}}var sl=e=>new TextEncoder().encode(JSON.stringify(e)).length,$h=16384;function Gh(e,t){let n=0,r,i=d=>{r={config:structuredClone(d),until:Date.now()+3e4}},a=[],o=null,s;function c(){if(!t())throw new b("NOT_IDENTIFIED","Call identify before using Features or events")}function u(){s||!a.length||(s=setTimeout(()=>{s=void 0,m().catch(()=>{}).finally(u)},5e3),typeof s=="object"&&"unref"in s&&s.unref())}function l(d,h={},R={}){if(c(),r&&Date.now()<r.until&&!Xm(r.config,d))return;g();let y=O.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:d,properties:h,...R}]}).events[0];if(sl({events:[y]})>$h)throw new b("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new b("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(y)),u()}async function m(d=!1){if(c(),o)return o;let h=n,R=(async()=>{let y={inserted:0,duplicates:0,rejected:0,skipped:0},A=a.length;for(;A&&h===n;){let x=[],v=sl({events:[]});for(let _ of a.slice(0,Math.min(A,100))){let X=sl(_)+(x.length?1:0);if(x.length&&v+X>$h)break;x.push(_),v+=X}let P=O.trackEvents,j=await ge(e,P,{events:x},void 0,{keepalive:d});if(h!==n)throw new b("IDENTITY_CHANGED","Event identity changed during delivery");if(j.inserted+j.duplicates+j.rejected+j.skipped!==x.length)throw new b("INVALID_RESPONSE","Incomplete event acknowledgement");i(j.analyticsConfig),a.splice(0,x.length),A-=x.length,y.inserted+=j.inserted,y.duplicates+=j.duplicates,y.rejected+=j.rejected,y.skipped+=j.skipped}return y})();o=R;try{return await R}finally{o===R&&(o=null)}}let f;function g(){if(f||typeof document>"u")return;let d=()=>{document.visibilityState==="hidden"&&t()&&a.length&&m(!0).catch(()=>{})};document.addEventListener("visibilitychange",d),f=()=>document.removeEventListener("visibilitychange",d)}return{rememberConfiguration:i,track:l,flush:m,reset(){n++,r=void 0,clearTimeout(s),s=void 0,a=[],o=null},detachVisibility(){f?.(),f=void 0}}}function cl(e){let t=null,n=null,r=0,i=0,a=new Set,o=null,s=null,c=new Set,u=()=>{for(let y of c)try{y()}catch{}},l={attributes:vt.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(y,A)=>{!a.has(y)&&(!t||!("analyticsConfig"in t)||t.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(y,structuredClone(A),structuredClone(l.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(y,A)=>(!t||!("analyticsConfig"in t)||t.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(y),structuredClone(A),structuredClone(l.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?y=>e.saveStickyBucketAssignmentDoc(structuredClone(y)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},m=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function f(y,A=new Set){return a.has(y)?!o||!o.features[y]||["unknownFeature","cyclicPrerequisite"].includes(o.features[y].source):A.has(y)?!1:(A.add(y),(t?.features[y]?.rules??[]).some(x=>[...x.parentConditions??[],...(x.tracks??[]).flatMap(v=>v.experiment.parentConditions??[])].some(v=>f(v.id,A))))}let g=y=>{if(e.assertUsable?.(t?.generation),!t)throw new Error("Initialize the Feature client before evaluation");if(t.expiresAt&&Date.parse(t.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return o?.expiresAt&&Date.parse(o.expiresAt)<=Date.now()&&(o=null,l.features=t.features),a.has(y)?!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now()?m():structuredClone(o.features[y]??m()):e.evaluateRemote&&(l.attributes?.merchandise||l.attributes?.merchandiseId)&&!o||f(y)?m():structuredClone(Gn(y,l))};async function d(){if(!t||!a.size&&!l.attributes?.merchandise&&!l.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(a.size)throw new Error("Remote Feature evaluation requires a server loader");return}let y=i;if(s?.revision===y)return s.loading;let A=r,x=t,v=[...a],P=(async()=>{let j=qa.parse(await e.evaluateRemote({attributes:structuredClone(l.attributes),features:v}));if(!(A!==r||y!==i||x!==t)){if(e.assertUsable?.(x.generation),j.generation!==x.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(v.some(_=>!Object.hasOwn(j.features,_))||Object.keys(j.features).some(_=>!a.has(_)))throw new Error("Invalid remote Feature results");if(l.attributes?.merchandise||l.attributes?.merchandiseId){if(!j.merchandiseContext)throw new Error("Server did not resolve merchandise context");l.attributes=vt.parse({...l.attributes,...j.merchandiseContext})}o=structuredClone(j),l.features={...x.features,...Object.fromEntries(Object.entries(o.features).map(([_,X])=>[_,{defaultValue:X.value}]))},u()}})();s={revision:y,loading:P};try{await P}finally{s?.loading===P&&(s=null)}}function h(){d().catch(y=>{try{e.onError?.(y)}catch{}})}async function R(){if(n)return n;let y=r,A=(async()=>{let x=await e.load(),v="remoteFeatures"in x?fo.parse(x):null,P=v??hn.parse(x);if(P.scope.projectId!==e.scope.projectId||P.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(y!==r)throw new Error("Feature client was reset");if(e.assertUsable&&t?.generation===P.generation){let{evaluatedAt:_,expiresAt:X,...le}=t,{evaluatedAt:he,expiresAt:Re,...Se}=P;if(Ot(le)!==Ot(Se))throw new Error("Immutable Feature generation changed content");return t.evaluatedAt=P.evaluatedAt,t.expiresAt=P.expiresAt,u(),(!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())&&h(),structuredClone(t)}let j=new Set(v?.remoteFeatures??[]);if([...j].some(_=>Object.hasOwn(P.features,_)))throw new Error("Remote Feature definitions must not be delivered locally");return t&&"analyticsConfig"in t&&"analyticsConfig"in P&&!t.analyticsConfig.experimentViewsEnabled&&v?.analyticsConfig.experimentViewsEnabled&&l.trackedExperiments?.clear(),t=structuredClone(P),a=j,o=null,s=null,i++,l.features=t.features,l.savedGroups=ii(t.savedGroups),l.trackedFeatureUsage={},u(),h(),structuredClone(t)})();n=A;try{return await A}finally{n===A&&(n=null)}}return{init:R,refresh:R,refreshRemote:d,get generation(){return t?.generation??null},get expiresAt(){return t?.expiresAt??null},subscribe(y){return c.add(y),()=>{c.delete(y)}},setAttributes(y){let A=vt.parse(y);(l.attributes?.merchandise||l.attributes?.merchandiseId||y.merchandise||y.merchandiseId)&&l.trackedExperiments?.clear(),l.attributes=A,i++,o=null,s=null,l.features=t?.features??{},l.trackedFeatureUsage={},u(),h()},evalFeature:g,isOn(y){return g(y).on},isOff(y){return g(y).off},getFeatureValue(y,A){let x=g(y).value;return structuredClone(x===null?A:x)},reset(){r++,i++,n=null,s=null,t=null,o=null,a.clear(),l.features={},l.savedGroups={},l.stickyBucketAssignmentDocs={},l.attributes={},l.trackedFeatureUsage={},l.trackedExperiments?.clear(),u()}}}function Kh(e){let t=e.merchandise;if(typeof e.merchandiseId=="string")return{internalId:e.merchandiseId};if(!(!t||typeof t!="object"||Array.isArray(t))){if(typeof t.internalId=="string")return{internalId:t.internalId};if(typeof t.externalId=="string")return{id:t.externalId};if(typeof t.id=="string")return{id:t.id}}}function sv(e){let t=Kh(e),{merchandiseId:n,merchandise:r,...i}=e;return{...i,...t?{merchandise:t}:{}}}function Hh(e,t,n,r,i){if(i&&r&&(i.scope.projectId!==r.projectId||i.scope.environment!==r.environment))throw new b("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,o=new Set;function s(){if(!t())throw new b("NOT_IDENTIFIED","Call identify before using Features or events")}async function c(u={}){i||s();let l=a,m=!1,f=async()=>{if(m||l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let he=O.getFeatures,Re=i?{scope:{projectId:i.scope.projectId,environment:i.scope.environment},payload:await i.features()}:await ge(e,he,{});if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");if(r&&(Re.scope.projectId!==r.projectId||Re.scope.environment!==r.environment))throw new b("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(Re.payload.analyticsConfig),Re},g=await f(),d=!0,h,R=he=>{try{u.onError?.(he)}catch{}},y=(he,Re,Se)=>{try{let gt=Kh(Se);n.track(he,Re,gt?{merchandise:gt}:{})}catch(gt){R(gt)}},A=cl({assertUsable:i?.assertFeatures,scope:g.scope,attributes:u.attributes,onError:u.onError,load:async()=>d?(d=!1,g.payload):(await f()).payload,evaluateRemote:async he=>{if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let Re=O.evaluateFeatures,Se=await ge(e,Re,{...he,attributes:sv(he.attributes)});if(Se.scope.projectId!==g.scope.projectId||Se.scope.environment!==g.scope.environment)throw new b("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:Se.generation,evaluatedAt:Se.evaluatedAt,expiresAt:Se.expiresAt,features:Se.features,...Se.merchandiseContext?{merchandiseContext:Se.merchandiseContext}:{}}},onExperimentViewed:(he,Re,Se)=>y("Experiment Viewed",{experimentId:he.key,variationId:Re.key},Se),onFeatureUsage:(he,Re,Se)=>y("Feature Evaluated",{feature:he,value:Re.value,source:Re.source,ruleId:Re.ruleId,...Re.experimentResult?{variationId:Re.experimentResult.key}:{}},Se)}),x=A.refresh;function v(){clearTimeout(h),!i&&(m||l!==a||!A.expiresAt||(h=setTimeout(()=>{P().catch(R)},Math.min(2147483647,Math.max(1e3,Date.parse(A.expiresAt)-Date.now()))),typeof h=="object"&&"unref"in h&&h.unref()))}async function P(){try{return await x()}finally{v()}}let j=()=>{m||P().catch(R)},_=A.subscribe(v),X=i?.subscribe(()=>{!m&&i.fresh&&P().catch(R)});function le(){m||(m=!0,clearTimeout(h),typeof window<"u"&&window.removeEventListener("focus",j),_(),X?.(),A.reset(),o.delete(le))}o.add(le);try{await A.init(),(u.attributes?.merchandise||u.attributes?.merchandiseId)&&await A.refreshRemote()}catch(he){throw le(),he}return v(),!i&&typeof window<"u"&&window.addEventListener("focus",j),Object.assign(A,{refresh:P,destroy:le})}return{features:c,reset(u){a++,u();for(let l of o)l()}}}import{z as cv}from"zod";function Qh(e,t){let n="source"in t?{funnelId:t.source.id,funnelVersionId:t.source.versionId}:"versionId"in t?{funnelId:t.funnelId,funnelVersionId:t.versionId}:t,r=cv.object({funnelId:is.shape.id,funnelVersionId:is.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new b("INVALID_REQUEST","A valid Funnel source is required");let i=Object.freeze(r.data);function a(o){if("customerId"in o)throw new b("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in o&&o.funnelId!==void 0&&o.funnelId!==i.funnelId||"funnelVersionId"in o&&o.funnelVersionId!==void 0&&o.funnelVersionId!==i.funnelVersionId)throw new b("SCOPE_MISMATCH","The original Funnel source cannot change");return{...o,...i}}return{async claimCoupon(o,s=crypto.randomUUID()){let c=O.grantOffer,u=await ge(e,c,a({couponId:o,requestId:s}));return{offer:u.offer,reason:u.reason}},async resolveOffering(o){let s=O.resolveOffering;return ge(e,s,a(o))},async resolvePaywall(o){let s=O.resolvePaywall;return ge(e,s,a(o))},async previewAttach(o){let s=O.previewAttach;return ge(e,s,a(o))}}}function Jh(e){let t=mr(e),n=t.request,r;try{r=ch(e.push,t,e.scope??e.configuration?.scope)}catch(s){throw t.dispose(),s}let i=Fh(t,()=>{o.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=Gh(n,i.isIdentified),o=Hh(n,i.isIdentified,a,e.scope,e.configuration);return{session:t.session,...lh(n,r),...Lh(n),...zh(n),forFunnel(s){return i.assertActive(),Qh(n,s)},async features(s={}){return i.assertActive(),o.features(s)},track(s,c,u={}){return a.track(s,c,u)},flush(){return a.flush()},...i.methods}}function Ni(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,a)=>Ni(i,t[a]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let n=Object.entries(e),r=Object.entries(t);return n.length===r.length&&n.every(([i,a])=>Object.hasOwn(t,i)&&Ni(a,Reflect.get(t,i)))}function hs(e,t){let n=Gg.safeParse(t);if(!n.success)throw new b("INVALID_RESPONSE","Funnel response contract changed");let r=n.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new b("SCOPE_MISMATCH","Funnel scope changed");return r}var Di=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function ys(e){let t=kt.test(e.apiKey);if(typeof window<"u"&&!t)throw new b("SERVER_ONLY","Funnel starts are issued by your backend");if(!t&&!Di.test(e.apiKey))throw new b("INVALID_TOKEN","A customer credential or server API key is required");return{async start(n){let r=wt.safeParse({...n,operation:"start"});if(!r.success||r.data.operation!=="start"||(t?r.data.customer!==void 0:r.data.customer===void 0))throw new b("INVALID_REQUEST","Invalid current Funnel start");let i=r.data,a=mr({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||a.identify(e.apiKey);let o=hs(e,await a.request("funnels",i));if(!o.runToken)throw new b("INVALID_RESPONSE","Funnel start credentials are missing");if(o.run.source.id!==i.funnelId||o.run.locale!==(i.locale??"en")||!Ni(o.run.parameters,i.parameters??{})||(i.customer?!o.customerId||i.customer.type==="id"&&o.customerId!==i.customer.value:o.customerId!==void 0))throw new b("INVALID_RESPONSE","Funnel start contract changed");return{...o,runToken:o.runToken}}finally{a.dispose()}}}}async function ul(e,t,n){if(Number(e.headers.get("content-length"))>t)throw e.body?.cancel().catch(()=>{}),n.error("limit");let r=e.body?.getReader();if(!r)throw n.error("missing");let i=[],a=0,o=!1,s=()=>{},c=new Promise((m,f)=>{s=()=>f(n.signal?.reason),n.signal?.addEventListener("abort",s,{once:!0}),n.signal?.aborted&&s()});try{for(;;){let m=await Promise.race([r.read(),c]);if(m.done){o=!0;break}if(a+=m.value.length,a>t)throw n.error("limit");i.push(m.value)}}finally{n.signal?.removeEventListener("abort",s),o||r.cancel().catch(()=>{}),r.releaseLock()}n.signal?.throwIfAborted();let u=new Uint8Array(a),l=0;for(let m of i)u.set(m,l),l+=m.length;return u}async function Zh(e,t,n){return new TextDecoder("utf-8",{fatal:!0}).decode(await ul(e,t,n))}function As(e,t){let n=typeof e=="string"?new TextEncoder().encode(e):e;return n.byteLength===t.byteLength&&xu(n)===t.sha256}async function bs(e,t){let n=Br.parse(t),{artifact:r,environmentId:i}=n.content,a=new bn(e.baseUrl??pr).origin,o=new bn(r.url,a);if(o.origin!==a||o.username||o.password||o.search||o.hash||o.pathname!==`/api/v1/configuration/${i}/artifacts/${r.sha256}`)throw new b("INVALID_RESPONSE","Public Paywall locator is not trusted");let s=new AbortController,c,u=new Promise((m,f)=>{c=setTimeout(()=>{let g=new b("TIMEOUT","Public Paywall read timed out");s.abort(g),f(g)},nn.initializationMs)}),l=(async()=>{let m=await(e.fetch??globalThis.fetch)(o,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:s.signal});if(s.signal.aborted&&(m.body?.cancel().catch(()=>{}),s.signal.throwIfAborted()),!m.ok||!m.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(m.headers.get("content-length"))>r.byteLength)throw m.body?.cancel().catch(()=>{}),new b("INVALID_RESPONSE","Public Paywall is unavailable");let f=await ul(m,r.byteLength,{signal:s.signal,error:g=>new b("INVALID_RESPONSE",g==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!As(f,r))throw new b("INVALID_RESPONSE","Public Paywall digest or size changed");return Jf(n,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(f)))})();try{return await Promise.race([l,u])}finally{clearTimeout(c)}}var Wh=(e,t)=>new b(e,t);async function ll(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=uv(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 uv(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=qu({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:hn.parse(o)}),c=lv(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 lv(e,t,n){return sh(e,t,n,Wh)}import{z as fn}from"zod";var Yh=wt.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new b("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),Xh=fn.strictObject({schemaVersion:fn.literal(1),scope:Te,runId:fn.uuid(),funnelId:fn.uuid(),versionId:fn.uuid(),processBindingIds:fn.record(fn.uuid(),fn.uuid().nullable()).optional(),command:Yh.optional(),closeCommand:Yh.refine(e=>e.operation==="close").optional(),purchase:fn.strictObject({receiptId:fn.uuid(),operationId:fn.uuid(),generation:fn.number().int().nonnegative()}).optional(),closed:fn.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),Xt=()=>new b("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),xs=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function ey(e){let t=0,n=null,r=u=>JSON.stringify([u.scope,u.runId,u.funnelId,u.versionId]),i=Promise.resolve();async function a(){let u=await e.read();if(!Number.isSafeInteger(u.revision)||u.revision<0)throw new b("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:u.revision,entry:u.entry===null?null:Xh.parse(u.entry)}}function o(u){let l=i.then(u);return i=l.catch(()=>{}),l}async function s(u){for(let l=0;l<4;l++){let m=await a();if(m.entry&&n!==null&&r(m.entry)!==n)throw Xt();let f=u(m.entry,m.revision);if(xs(m.entry,f)){t=m.revision;return}let g=await e.write(m.revision,f);if(g!==null){if(!Number.isSafeInteger(g)||g<=m.revision)throw Xt();t=g;return}}throw Xt()}function c(u,l){if(!u||!l)return u;if(u.processBindingIds&&Object.hasOwn(u.processBindingIds,l)){let m={...u.processBindingIds};delete m[l],u={...u,processBindingIds:m}}return u.command?.requestId===l?u.closeCommand?{...u,command:u.closeCommand,closeCommand:void 0}:u.purchase?{...u,command:void 0}:null:u.closeCommand?.requestId===l?{...u,closeCommand:void 0}:u}return{bind(u){let l=JSON.stringify([u.scope,u.runId,u.funnelId,u.versionId]);if(n!==null&&n!==l)throw Xt();n=l},async load(){let u=await a();return t=u.revision,n=u.entry?r(u.entry):null,u.entry},retain(u){let l=Xh.parse(u),m=l.command;return!m||n!==null&&r(l)!==n?Promise.reject(Xt()):(n??(n=r(l)),o(()=>s((f,g)=>{if(f&&!xs(r(f),r(l)))throw Xt();if(f&&l.processBindingIds){for(let[d,h]of Object.entries(l.processBindingIds))if(f.processBindingIds&&Object.hasOwn(f.processBindingIds,d)&&f.processBindingIds[d]!==h)throw Xt();f={...f,processBindingIds:{...f.processBindingIds,...l.processBindingIds}}}if(!f){if(g!==t&&m.operation!=="close")throw Xt();return l}if(!f.command)return{...f,command:m,...m.operation==="close"?{closed:!0}:{}};if(m.operation==="close"&&f.command.operation!=="close"){if(f.command.requestId===m.requestId||f.closeCommand&&!xs(f.closeCommand,m))throw Xt();return{...f,closeCommand:m,closed:!0}}if(!xs(f.command,m))throw Xt();return f})))},observePurchase(u,l,m,f){return o(()=>s((g,d)=>{if(!g&&d!==t||g&&r(g)!==r({...u,schemaVersion:1}))throw Xt();if(g?.purchase&&g.purchase.generation>l.generation)return c(g,f);if(g?.purchase&&g.purchase.generation===l.generation&&g.purchase.operationId!==l.operationId)throw Xt();return m?!g?.purchase||g.purchase.operationId!==l.operationId?c(g,f):c(g.command?{...g,purchase:void 0}:null,f):c({schemaVersion:1,...u,...g,purchase:l},f)}))},settle(u){return o(()=>s(l=>c(l,u)))}}}function ty(e){let t,n,r=()=>new b("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,n=e.locks??globalThis.navigator?.locks,!t||!n||!globalThis.crypto?.subtle)throw r();let s=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??pr).href,e.runToken])),c=new Uint8Array(await crypto.subtle.digest("SHA-256",s));return"indiana.funnel.commands.v1."+Array.from(c,u=>u.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function a(s){try{let c=await i;return await n.request(c,{mode:"exclusive"},()=>s(c))}catch(c){throw c instanceof b?c:r()}}function o(s){let c=t.getItem(s);if(c===null)return{revision:0,entry:null};if(c.length>1048576)throw r();let u=JSON.parse(c);if(!u||typeof u!="object"||!("revision"in u)||!("entry"in u)||!Number.isSafeInteger(u.revision)||Number(u.revision)<0)throw r();return{revision:Number(u.revision),entry:u.entry}}return{read:()=>a(o),write:(s,c)=>a(u=>{if(o(u).revision!==s)return null;if(!Number.isSafeInteger(s+1))throw r();return t.setItem(u,JSON.stringify({revision:s+1,entry:c})),s+1})}}function ny(e,t){let n=t&&{...t},r=null,i=0,a=new AbortController;function o(){i++,a.abort(new b("IDENTITY_CHANGED","Run identity changed")),a=new AbortController}let s=!1,c,u=0,l=new Set;return{get scope(){return n},bindScope(m){if(n&&(n.projectId!==m.projectId||n.environment!==m.environment))throw new b("SCOPE_MISMATCH","Run scope changed");n??(n={...m})},get view(){return r},get generation(){return i},get signal(){return a.signal},get disposed(){return s},get customerToken(){return c},get readSequence(){return u},nextRead(){return++u},assertCurrent(m,f="Run identity changed during the request"){if(m!==i||s)throw new b("IDENTITY_CHANGED",f)},assertRun(m){if(r&&(m.id!==r.id||m.source.type!==r.source.type||m.source.id!==r.source.id||m.source.versionId!==r.source.versionId||m.locale!==r.locale||!Ni(m.parameters,r.parameters)))throw new b("INVALID_RESPONSE","Run version changed");if(e&&m.source.id!==e)throw new b("INVALID_RESPONSE","Run belongs to another Funnel")},publish(m,f,g,d,h){if(!(m.operation==="review"&&r&&r!==g&&f.run.revision<=r.revision)&&!(r&&f.run.revision===r.revision&&d!==void 0&&d<u)&&(m.operation==="review"&&!f.run.stopped&&["running","waiting"].includes(f.run.status)&&r&&f.run.nodeId===r.nodeId&&f.run.visit===r.visit&&f.run.revision===r.revision&&(f.run.screen=r.screen,(r.paywall?.quote?.operationId===f.review?.activeOperationId||!r.paywall?.quote&&f.review?.activeOperationId===null)&&(f.run.paywall=r.paywall)),!(r?.paywall&&f.run.paywall&&r.paywall.receiptId===f.run.paywall.receiptId&&(f.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||f.run.revision>=r.revision)r=f.run;else if(!h)return;if(r)for(let R of l)try{R(structuredClone(r))}catch{}}},identify(m){if(s)throw new b("IDENTITY_CHANGED","Controller was reset");if(!kt.test(m))throw new b("INVALID_TOKEN","Customer credential required");o(),c=m},subscribe(m){return l.add(m),()=>l.delete(m)},reset(){s||(s=!0,o(),c=void 0,r=null,l.clear())}}}function fr(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)||e.recovery==="recover_operation";function ry({journal:e,state:t,call:n,processIdentity:r}){let i=null,a=null,o=!1,s={command:null,close:null},c=new Set,u,l=null,m=e?e.load().then(y=>{if(t.disposed)throw new b("IDENTITY_CHANGED","Controller was reset during command restoration");if(l=y,!y)return;if(r){if([y.command,y.closeCommand].some(x=>x&&!Object.hasOwn(y.processBindingIds??{},x.requestId)))throw new b("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(y.processBindingIds??{})}if(t.scope&&(y.scope.projectId!==t.scope.projectId||y.scope.environment!==t.scope.environment))throw new b("SCOPE_MISMATCH","Pending command belongs to another scope");if(u=y.purchase,o=y.closed===!0,!y.command)return;let A=y.command;i=A.operation==="close"?null:A,a=A.operation==="close"?A:y.closeCommand?.operation==="close"?y.closeCommand:null,a&&(o=!0);for(let x of[i,a])x&&c.add(x.requestId)}):Promise.resolve();m.catch(()=>{});async function f(y){e&&await m;let A=t.generation;if(e){if(!t.view||!t.scope)throw new b("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:fr(y),...r?{processBindingIds:{[y.requestId]:r.binding(y.requestId)}}:{}})}if(A!==t.generation||i!==y&&a!==y)throw new b("IDENTITY_CHANGED","Run changed before command dispatch");let x=c.has(y.requestId);c.add(y.requestId);try{return await n(y)}catch(v){throw A===t.generation&&(i===y||a===y)&&!x&&!dv(v)&&(e&&await e.settle(y.requestId),A===t.generation&&R(y)),v}}function g(y){let A=wt.parse(y);if(A.operation==="start"||A.operation==="get"||A.operation==="review")throw new b("INVALID_REQUEST","Mutation required");if(o&&A.operation!=="close"){if(i?.requestId===A.requestId)return h(A.requestId);throw new b("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(A.operation==="close"){if(i?.requestId===A.requestId)throw new b("INVALID_REQUEST","Close requires its own request identity");if(o=!0,a&&JSON.stringify(fr(a))!==JSON.stringify(fr(A)))throw new b("COMMAND_PENDING","Retry the original Close");return a??(a=A),s.close?s.close:d(a,"close")}if(i){if(JSON.stringify(fr(i))!==JSON.stringify(fr(A)))throw new b("COMMAND_PENDING","Retry the original command before sending another");if(s.command)return s.command}else i=A;return d(i,"command")}function d(y,A){let x=f(y);s[A]=x;let v=()=>{s[A]===x&&(s[A]=null)};return x.then(v,v),x}function h(y){return n({operation:"get",settlementRequestId:y})}function R(y){return!y||i!==y&&a!==y?!1:(i===y&&(i=null),a===y&&(a=null),c.delete(y.requestId),!i&&!a&&(l=null),!0)}return{ready:m,get pending(){return i},get closing(){return a},get closeRequested(){return o},get inFlight(){return s.command},get closeFlight(){return s.close},get purchase(){return u},assertBinding(y){if(l&&(y.run.id!==l.runId||y.run.source.id!==l.funnelId||y.run.source.versionId!==l.versionId))throw new b("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(y,A,x,v){let P=y.operation==="get"?y.settlementRequestId:"requestId"in y&&y.operation!=="start"?y.requestId:void 0,j=P&&A.settlement?.state==="settled"&&A.run.pendingRequest?.requestId!==P&&(y.operation==="get"||!o||y.operation==="close"||!["running","waiting"].includes(A.run.status))?P:void 0,_=i?.requestId===j?i:a?.requestId===j?a:void 0;e?.bind({scope:A.scope,runId:A.run.id,funnelId:A.run.source.id,versionId:A.run.source.versionId});let X=A.run.paywall,le=X??A.purchase,he=le?.operation,Re=A.settlement&&(!X||X.purchaseRequestId===A.settlement.requestId)&&(!u||u.operationId===A.settlement.operationId)?A.settlement:void 0,Se=he?.operationId??le?.quote?.operationId??Re?.operationId,gt=le?.receiptId??Re?.receiptId,Qe=X?.selectionGeneration??u?.generation??0;if(e&&Se&>&&y.operation!=="review"&&(!t.view||A.run.revision>=t.view.revision)&&(v===void 0||v>=t.readSequence)&&(!u||Qe>=u.generation)){let je={receiptId:gt,operationId:Se,generation:Qe},et=he?.status==="complete"||le?.canReselect===!0;await e.observePurchase({scope:A.scope,runId:A.run.id,funnelId:A.run.source.id,versionId:A.run.source.versionId},je,et,j),t.assertCurrent(x),(!u||je.generation>=u.generation)&&(v===void 0||v>=t.readSequence)&&(et?u?.operationId===je.operationId&&(u=void 0):u=je)}else e&&j&&await e.settle(j);return t.assertCurrent(x),j?R(_):!1},stop(){o=!0},submit:g,settle:h,reset(){o=!0,i=null,a=null,u=void 0,l=null,s.close=null,c.clear(),s.command=null}}}function gr(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new b("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!Di.test(e.serverKey)))throw new b("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new b("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let t=mr({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),n=ny(e.funnelId,e.scope??e.configuration?.scope),r=e.session?.subscribeIdentity(u),i=null,a=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?ty(e):void 0),o=a&&ey(a),s=ry({journal:o,state:n,call:l,processIdentity:e.process});async function c(A){if(e.process)return e.process.request(A);let x=n.generation;n.assertCurrent(x);let v=performance.now()+(e.timeoutMs??35e3),P=n.customerToken??("customerToken"in A?A.customerToken:void 0);if(e.session){let X=n.signal,le,he=()=>{},Re=new Promise((Se,gt)=>{he=()=>gt(X.reason),X.addEventListener("abort",he,{once:!0}),le=setTimeout(()=>gt(new b("TIMEOUT","Longplay request timed out")),Math.max(1,v-performance.now()))});try{P=await Promise.race([Promise.resolve().then(()=>(n.assertCurrent(x),e.session.access())),Re])}finally{clearTimeout(le),X.removeEventListener("abort",he)}}n.assertCurrent(x);let j={...A,...P?{customerToken:P}:{}},_=A.operation==="page_experiments"?Po.parse(j):wt.parse(j);return t.requestWithCredential("funnels",_,e.runToken,{headers:e.serverKey&&!P?{[Kg]:e.serverKey}:void 0,timeoutMs:Math.max(1,v-performance.now())})}function u(){r?.(),n.reset(),s.reset(),i=null,t.dispose()}async function l(A,x){let v=n.generation,P=()=>n.assertCurrent(v);o&&await s.ready,P();let j=n.view,_=hs(e,await c(A));if(A.operation==="review"&&!_.review)throw new b("INVALID_RESPONSE","Historical projection is missing");if(P(),_.runToken&&_.runToken!==e.runToken)throw new b("INVALID_RESPONSE","Run credential changed");let X=A.operation==="get"?A.settlementRequestId:"requestId"in A&&A.operation!=="start"?A.requestId:void 0;if(X&&_.settlement?.requestId!==X)throw new b("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");s.assertBinding(_),n.assertRun(_.run),n.bindScope(_.scope);let le=await s.observe(A,_,v,x);return!_.run.stopped&&["running","waiting"].includes(_.run.status)&&A.operation==="get"&&A.settlementRequestId||(P(),["running","waiting"].includes(_.run.status)||s.stop(),n.publish(A,_,j,x,le)),_}let m=s.submit,f=null,g=new WeakMap;function d(A){let x=g.get(A);if(x)return x;let v=R(A);return g.set(A,v),v}let h=!1;async function R(A){let x=await A;if(x.run.instruction?.type!=="evaluate_segment")return x;if(f)return f;h=!0;let v=n.generation,P=(async()=>{for(let j=0;j<32&&x.run.instruction?.type==="evaluate_segment";j++){if(s.pending||s.closeRequested)return x;let _=x.run;if(x.run.instruction?.type==="evaluate_segment"){let{advance:le}=await ll(e.configuration,_,{predict:!1});if(v!==n.generation)throw new b("IDENTITY_CHANGED","Run identity changed during segment calculation");if(s.pending||s.closeRequested)return x;if(n.view&&(n.view.revision!==_.revision||n.view.visit!==_.visit||n.view.nodeId!==_.nodeId))return l({operation:"get"});let he=!0;ll(e.configuration,_).then(({prediction:Re})=>{he&&v===n.generation&&!s.closeRequested&&n.view?.id===_.id&&!n.view.stopped&&n.view.nodeId===_.nodeId&&n.view.visit===_.visit&&n.view.revision===_.revision&&(i=Re)}).catch(()=>{});try{x=await m({operation:"commit_segment",requestId:$g(_.id,_.visit,`segment:${_.revision}`),nodeId:_.nodeId,visit:_.visit,revision:_.revision,...le})}finally{he=!1,i=null}}}return x})();f=P;try{return await P}finally{f===P&&(f=null)}}let y={get configuration(){return h?e.configuration:void 0},get configurationReady(){return!0},get view(){return n.view?structuredClone(n.view):null},get pendingCommand(){let A=s.closing??s.pending;return A?structuredClone(fr(A)):null},get pendingCommands(){return[s.pending,s.closing].filter(A=>A!==null).map(A=>structuredClone(fr(A)))},get pendingPurchase(){return s.purchase?structuredClone(s.purchase):null},get hasDurableJournal(){return o!==void 0},get prediction(){let A=n.view;return i&&A&&!A.stopped&&["running","waiting"].includes(A.status)&&A.id===i.runId&&A.nodeId===i.from.nodeId&&A.visit===i.from.visit&&A.revision===i.from.revision&&!s.closeRequested?structuredClone(i):null},settle:s.settle,get webViewUrl(){return"bundled"},resolvePaywall(A){return bs(e,A)},async pageExperiments(A,x=[]){let v=n.generation;n.assertCurrent(v);let P=n.view?.id;if(!P)throw new b("INVALID_REQUEST","Read the Run before its page experiments");let j=Zg.parse(await c(Po.parse({operation:"page_experiments",release:A,usedReceiptIds:x})));if(n.assertCurrent(v),j.runId!==P||j.scope.projectId!==n.scope?.projectId||j.scope.environment!==n.scope?.environment)throw new b("SCOPE_MISMATCH","Page experiment Run changed");return j},review(A){return l({operation:"review",...A?{receiptId:A}:{}},n.nextRead())},async get(A,x){o&&await s.ready,x??(x=s.purchase&&{receiptId:s.purchase.receiptId,operationId:s.purchase.operationId});let v=n.nextRead();return d(l({operation:"get",...A?{data:A}:{},...x?{purchase:x}:{}},v))},resume(A=n.view?.pendingRequest?.requestId){return A?s.closeRequested?y.settle(A):s.pending?.requestId===A?d(m(s.pending)):d(m({operation:"resume",requestId:A})):Promise.reject(new b("INVALID_REQUEST","No interrupted command is available"))},submit(A){return d(m(A))},retry(){return s.closeFlight?s.closeFlight:s.closing?m(s.closing):s.closeRequested&&s.pending?y.settle(s.pending.requestId):s.inFlight?d(s.inFlight):s.pending?d(m(s.pending)):Promise.reject(new b("INVALID_REQUEST","No command is pending"))},identify(A){n.identify(A),i=null,t.reset()},subscribe:n.subscribe,reset:u};return y}function iy(e){if(!kt.test(e.customerToken))throw new b("INVALID_TOKEN","A customer credential is required");if(!e.scope)throw new b("INVALID_REQUEST","An explicit App and environment scope is required");let t=ys({...e,scope:e.scope,apiKey:e.customerToken});return{async start(n){let r=await t.start(n),i=gr({...e,runToken:r.runToken});i.identify(e.customerToken);let a=r.run.instruction?.type==="evaluate_segment"?await i.get():r;return{...r,...a,controller:i}}}}function oy(e,t){let n=r=>"document"in r?r.offering.id:r.content.offeringVersionId;return e.id===t.id&&n(e)===n(t)&&e.content?.artifact.sha256===t.content?.artifact.sha256}function ay(e,t,n){if(e.operationId!==t.operationId||t.currency!==void 0&&e.currency!==t.currency)throw new b("INVALID_RESPONSE",n)}function sy(e,t,n){let r=Object.fromEntries((e.lines[0]?.prepaid??[]).map(i=>[i.internal_feature_id,i.quantity]));if(t.featureQuantities&&(Object.keys(r).length!==Object.keys(t.featureQuantities).length||Object.entries(t.featureQuantities).some(([i,a])=>r[i]!==a)))throw new b("INVALID_RESPONSE","The purchase quote changed its selected quantities");if(e.lines.length!==1||e.lines[0].productVersionId!==t.productVersionId||t.currency!==void 0&&e.currency!==t.currency||t.provider!==void 0&&e.provider!==t.provider&&!(t.provider==="stripe"&&e.provider==="merchant"&&e.execution?.provider==="merchant"))throw new b("INVALID_RESPONSE",n)}function cy(e,t,n=!1){return!e||e.operationId!==t?.operationId?t:e.status==="complete"&&t.status!=="complete"||e.status!=="pending"&&(t.status==="pending"||n&&t.status!=="complete")?e:t}function uy(e){let{quote:t,operation:n,requestId:r}=e,a={type:"recover",operationId:n?.operationId??t?.operationId??null,requestId:r};if(e.destroyed||e.pending)return a;if(!n)return t?{type:"cancel",operationId:t.operationId}:a;let o=n.merchantExecution;if(o?.type==="purchase"){if(["succeeded","not_required"].includes(o.paymentStatus))return!["applied","not_applicable"].includes(o.fulfillmentStatus)||n.problem?.phase==="fulfillment"||o.problem?.phase==="fulfillment"?{type:"fulfillment",operationId:n.operationId}:{type:o.recordingStatus==="accepted"&&n.status==="complete"?"complete":"recording",operationId:n.operationId};if(n.status==="pending"&&n.checkoutUrl&&o.checkoutUrl===n.checkoutUrl&&o.checkoutExpiresAt&&Date.parse(o.checkoutExpiresAt)>Date.now()&&["not_started","pending"].includes(o.paymentStatus))return{type:"checkout",operationId:n.operationId,checkoutUrl:n.checkoutUrl}}let s=[n.problem,o?.problem],c=s.every(u=>!u||u.phase==="execution"&&u.reason!=="RESULT_UNKNOWN");return!s.some(Boolean)&&n.status==="complete"&&n.executor!=="merchant"?{type:"complete",operationId:n.operationId}:c&&e.canReselect!==!1&&["cancelled","failed"].includes(n.status)&&!n.checkoutUrl&&!n.execution&&!n.nativePurchase&&(n.executor!=="merchant"?!n.confirmedAt&&(n.status==="cancelled"||!n.quoteFinalized):!o&&!n.quoteFinalized||o?.type==="purchase"&&["failed","expired"].includes(o.paymentStatus)&&o.fulfillmentStatus==="not_applicable"&&o.recordingStatus==="accepted")?{type:"native",operationId:n.operationId}:n.status==="pending"&&c&&!n.quoteFinalized&&!o&&!n.checkoutUrl&&!n.execution&&!n.nativePurchase?{type:"cancel",operationId:n.operationId}:a}async function ly(e,t){if(!kt.test(t.customerToken))throw new b("INVALID_TOKEN","A verified Customer credential is required");if(e.session&&e.session.peek()!==t.customerToken)throw new b("SCOPE_MISMATCH","Paywall credential does not match the shared session");let n=O.resolvePaywall.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale,...t.requirement?{requirement:t.requirement}:{}}),r=mr(e);e.session||r.identify(t.customerToken);let i=null,a=!1,o=null,s=null,c=null,u=null,l=null,m=null,f=null,g=0;function d(){if(a)throw new b("IDENTITY_CHANGED","Paywall is closed")}async function h(){d();let x=O.resolvePaywall,v=await ge(r.request,x,{...n,selector:i?{type:"version",versionId:i.id}:n.selector}),P=await bs(e,v.paywall);if(d(),t.paywallVersionId?P.id!==t.paywallVersionId:P.paywallId!==t.paywallId)throw new b("INVALID_RESPONSE","The requested Paywall changed");if(i&&(!oy(P,i)||P.paywallId!==i.paywallId))throw new b("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return i=P,structuredClone(i)}async function R(x){if(d(),u&&x!=="read")throw new b("COMMAND_PENDING","Wait for the original quote");if(!o)throw new b("INVALID_REQUEST","A quoted purchase is required");let v=o;if(x!=="read"){if(f){if(m===x)return f;throw new b("COMMAND_PENDING","Wait for the original purchase command")}if(m&&m!==x)throw new b("COMMAND_PENDING","Read the original purchase before changing an uncertain command");m=x,g++}let P=m,j=g,_=x==="read"&&f===null,X=x==="read"?O.readSubscriptionOperation:O.attach,le=(async()=>{let he=await ge(r.request,X,{operationId:v.operationId,...x==="read"?{}:{intent:x}});return ay(he.operation,{operationId:v.operationId,currency:n.commerce.currency},"The purchase operation changed"),d(),o?.operationId!==v.operationId?structuredClone(he.operation):(s=cy(s,he.operation),(x!=="read"||_&&f===null)&&g===j&&m===P&&(m=null),structuredClone(s))})();if(x!=="read"){f=le;let he=()=>{f===le&&(f=null)};le.then(he,he)}return le}let y={get view(){return i?structuredClone(i):null},get quote(){return o?structuredClone(o):null},get operation(){return s?structuredClone(s):null},get webViewUrl(){return"bundled"},get recovery(){return uy({quote:o,operation:s,requestId:l,pending:u!==null||m!==null,destroyed:a})},get pendingCancellation(){return!a&&m==="cancel"},refresh:h,async preview(x){if(d(),!i)throw new b("INVALID_REQUEST","Load the Paywall first");let v=i.document.buttons[x.actionId];if(v?.type!=="checkout")throw new b("INVALID_REQUEST","Choose an authored purchase action");let P=Zm(v.product,x.selection,i.capabilities);if(!P)throw new b("PRODUCT_UNAVAILABLE","Choose an available Product");let j=Bf(i.document.screen,P,x.selection,i.capabilities),_=O.previewAttach.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,requestId:x.requestId,plans:[{productVersionId:P,...Object.keys(j).length?{featureQuantities:j}:{}}],provider:n.commerce.provider,currency:n.commerce.currency,...x.offerId?{offerId:x.offerId}:{},...x.nativeOffer?{nativeOffer:x.nativeOffer}:{}}),X=JSON.stringify(_);if(c&&c!==X&&(u||m||!s||s.status==="pending"))throw new b("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(c===X){if(u)return u;if(o)return structuredClone(o)}c!==X&&(o=null,s=null),c=X,l=_.requestId;let le=(async()=>{let he=O.previewAttach,Re=await ge(r.request,he,_);return d(),sy(Re.quote,{productVersionId:P,featureQuantities:j,currency:n.commerce.currency,provider:n.commerce.provider},"The purchase quote changed its selected Product or presentment"),o=Re.quote,s=null,structuredClone(o)})();u=le;try{return await le}finally{u===le&&(u=null)}},confirm:()=>R("confirm"),cancel:()=>R("cancel"),read:()=>R("read"),destroy(){a||(a=!0,A?.(),r.dispose(),i=null,o=null,s=null,c=null,l=null)}},A=e.session?.subscribeIdentity(y.destroy);try{return await h(),y}catch(x){throw y.destroy(),x}}function dy(e,t){let n,r=0,i=-1,a,o=!1,s=()=>{if(o)throw new b("CLOSED","Native host was destroyed");if(!e.nativeModule)throw new b("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return e.nativeModule},c=()=>new b("IDENTITY_CHANGED","Customer identity changed during the native operation"),u=t.subscribeIdentity(()=>{r++,i=-1;let g=r;n&&e.nativeModule&&n.then(d=>e.nativeModule.reset(d,g)).catch(()=>{})}),l=e.nativeEvents?.(g=>{!n||!e.nativeModule||typeof g?.requestId!="string"||(async()=>{let d=await n;if(g.instanceId!==d)return;if(g.kind==="credential"){let y=r,A=null;try{if(!o&&g.revision===y){let x=await t.access();!o&&r===y&&(A=x)}}finally{await e.nativeModule.provideCredential(d,g.requestId,A)}return}let h=!1,R=r;try{if(o||g.revision!==R||!e.onNativeAction)throw c();await e.onNativeAction(g.action),h=!o&&r===R}finally{await e.nativeModule.acknowledge(d,g.requestId,h)}})().catch(()=>{})});async function m(g,d={}){let h=s();if(t.snapshot()&&!e.nativeEvents)throw new b("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let R=r,y=await t.access();if(o||r!==R)throw c();if(!n){let v=h.create(JSON.stringify({baseUrl:e.baseUrl??"https://api.longplayai.com",scope:e.scope,timeout:(e.timeoutMs??15e3)/1e3,credentialEvents:!!e.nativeEvents}));n=v,v.catch(()=>{n===v&&(n=void 0)})}let A=await n;if(o||r!==R)throw c();if(i!==R){if(!a||a.epoch!==R){let P=(async()=>{if(await h.identify(A,JSON.stringify({revision:R,credentials:y})),o||r!==R)throw await h.reset(A,R),c();i=R})();a={epoch:R,task:P}}let v=a;try{await v.task}finally{a===v&&(a=void 0)}}let x=await h.invoke(A,g,JSON.stringify(d));if(o||r!==R)throw c();try{return JSON.parse(x)}catch{throw new b("INVALID_RESPONSE","Native host returned invalid JSON")}}async function f(g,d){let h=await m(g,d);if(!h||typeof h!="object"||Array.isArray(h)||h.status!=="complete"&&h.status!=="dismissed")throw new b("INVALID_RESPONSE","Native presentation returned an invalid result");return h}return{showFunnel(g){return f("showFunnel",{runToken:g})},showPaywall(g){return f("showPaywall",g)},showContent(g){return f("showContent",g)},purchaseSubscription(g,d){return m("purchaseSubscription",{operationId:g,accepted:d})},switchSubscription(g,d){return m("switchSubscription",{operationId:g,accepted:d})},restorePurchases(){return m("restorePurchases")},manageSubscriptions(g){return m("manageSubscriptions",g?{productId:g}:{})},async dismiss(){r++,i=-1,n&&await s().reset(await n,r)},async destroy(){o||(o=!0,r++,u(),l?.(),n&&e.nativeModule&&await e.nativeModule.destroy(await n))}}}var pv=O.trackUsage.request.shape.command,mv=O.trackUsage.response;function fv(e){let t=Te.parse(e.scope),n=Jh({...e,scope:t}),r={...e,scope:t,session:n.session},i=dy(e,n.session),a=0,o=!1;n.subscribeIdentity(()=>{a++});let s=()=>{if(o)throw new b("CLOSED","SDK client was destroyed");let c=n.session.peek();if(!c)throw new b("UNAUTHENTICATED","Identify the Customer first");return c};return{...n,native:i,async destroy(){o||(o=!0,a++,n.destroy(),await i.destroy())},funnel(){return iy({...r,customerToken:s()})},resumeFunnel(c){return s(),gr({...r,runToken:c})},paywall(c){return ly(r,{...c,customerToken:s()})},async trackUsage(c){if(s(),!e.usageReporter)throw new b("INVALID_REQUEST","Configure your authenticated backend usageReporter");let u=pv.parse(c),l=a,m;try{m=await e.usageReporter(u)}catch(g){throw l!==a?new b("IDENTITY_CHANGED","Customer identity changed during usage reporting"):g}if(l!==a)throw new b("IDENTITY_CHANGED","Customer identity changed during usage reporting");let f=mv.parse(m);if(f.scope.projectId!==t.projectId||f.scope.environment!==t.environment)throw new b("INVALID_RESPONSE","Usage response scope differs");return f}}}import{z as Av}from"zod";import{z as jo}from"zod";var gv=jo.record(jo.string().regex(/^[a-f0-9]{64}$/),jo.strictObject({at:jo.number(),text:jo.string()})),Hr=2*1048576,hv=100;function yv(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function py(e,t){let n=t===void 0?yv():t,r=new Map,i=0,a=!1,o=!1,s,c;async function u(m){if(!n)return null;let f;try{let g=await Promise.race([Promise.resolve().then(()=>n.getItem(m)),new Promise(d=>{f=setTimeout(()=>d(null),hv)})]);return typeof g=="string"&&g.length<=Hr&&new TextEncoder().encode(g).byteLength<=Hr?g:null}catch{return null}finally{clearTimeout(f)}}function l(){if(c)return c;let m=(async()=>{try{let f=await u(`${e}:artifacts`);if(f)return gv.parse(JSON.parse(f))}catch{}return{}})();return c=m,m.finally(()=>{c===m&&(c=void 0)}),m}return{async readManifest(){return u(e)},writeManifest(m){!n||m.length>Hr||new TextEncoder().encode(m).byteLength>Hr||(s=m,!o&&(o=!0,Promise.resolve().then(async()=>{try{for(;s!==void 0;){let f=s;try{await n.setItem(e,f)}catch{}s===f&&(s=void 0)}}finally{o=!1}})))},async readArtifact(m){let f=(await l())[m],g=Date.now();return f&&g>=f.at&&g-f.at<=nn.retentionMs?f.text:void 0},writeArtifact(m,f){if(!n||f.length>Hr)return;let g=r.get(m);if(g?.text===f||!g&&r.size>=128)return;let d=new TextEncoder().encode(f).byteLength;i-(g?.byteLength??0)+d>Hr||(r.set(m,{text:f,byteLength:d}),i+=d-(g?.byteLength??0),!a&&(a=!0,Promise.resolve().then(async()=>{try{for(;r.size;){let h=new Map(r);try{let R={...await l()},y=Date.now();for(let[P,j]of h)R[P]={at:y,text:j.text};let A={},x=2,v=0;for(let[P,j]of Object.entries(R).sort(([,_],[,X])=>X.at-_.at)){if(j.at>y||y-j.at>nn.retentionMs)continue;let _=new TextEncoder().encode(JSON.stringify({[P]:j})).byteLength;x+_>Hr||v>=128||(A[P]=j,x+=_,v++)}await n.setItem(`${e}:artifacts`,JSON.stringify(A))}catch{}finally{for(let[R,y]of h)r.get(R)===y&&(r.delete(R),i-=y.byteLength)}}}finally{a=!1}})))}}}var Pe=(e,t)=>new b(e,t),hr=()=>performance.now(),my=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function bv(e){let t=yu.parse(e.scope),n=new bn(e.origin??pr);if(n.username||n.password||n.search||n.hash||n.pathname!=="/"||n.protocol!=="https:"&&!(n.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(n.hostname)))throw Pe("INVALID_URL","Configuration requires a trusted HTTPS origin");let r=new Set([n.origin,...(e.assetOrigins??[]).map(Y=>{let J=new bn(Y);if(J.protocol!=="https:"||J.username||J.password||J.search||J.hash||J.pathname!=="/")throw Pe("INVALID_URL","Invalid configuration asset origin");return J.origin})]),i=e.fetch??globalThis.fetch.bind(globalThis),a=`/api/v1/configuration/${t.environmentId}`,o=`indiana:configuration:1:${n.origin}:${Ot(t)}`,s=py(o,e.storage),c,u=0,l=0,m=!1,f=!1,g=0,d=0,h,R,y,A,x=0,v=new Set,P=new Set,j=new Map,_=new Map,X=0,le=!1;function he(){for(let Y of v)try{Y()}catch{}}function Re(Y){try{e.onError?.(Y)}catch{}}let Se=()=>!f&&!m&&!!c&&hr()<u&&Date.now()<l;function gt(){if(!Se())throw Pe("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Qe(Y,J,de){if(!j.has(Y)){for(;j.size&&(j.size>=128||X+de>nn.maxCacheBytes);){let pe=j.entries().next().value;X-=pe[1].byteLength,j.delete(pe[0])}j.set(Y,{text:J,byteLength:de}),X+=de}}function je(Y,J,de){return Zh(Y,J,{signal:de,error:pe=>Pe("INVALID_RESPONSE",pe==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function et(Y){let J=new bn(Y,n);if(!r.has(J.origin)||J.username||J.password||J.hash||J.search)throw Pe("INVALID_URL","Configuration artifact origin is not trusted");return J.href}async function To(Y,J,de=!1){let pe=await i(et(Y),{method:"GET",credentials:"omit",redirect:"error",cache:de?"default":"no-cache",signal:J,headers:{}});if(pe.status===429){let Ye=pe.headers.get("retry-after")??"";x=/^\d+$/.test(Ye)?Number(Ye)*1e3:Math.max(0,Date.parse(Ye)-Date.now())||15e3}if(!pe.ok&&pe.status!==304)throw Pe(`CONFIGURATION_HTTP_${pe.status}`,"Configuration synchronization failed");return pe}function Qr(Y,J,de){let pe=Date.parse(Y.headers.get("x-indiana-config-validated-at")??""),Ye=Date.parse(Y.headers.get("x-indiana-config-valid-until")??""),rt=Date.parse(Y.headers.get("date")??""),ze=Y.headers.get("age"),rn=ze!==null&&/^\d+(\.\d+)?$/.test(ze)?Number(ze)*1e3:NaN;if(![pe,Ye,rt,rn].every(Number.isFinite)||Ye<=pe||Ye-pe>nn.maxControlAgeMs||pe>rt+1e3)throw Pe("INVALID_RESPONSE","Configuration freshness evidence is invalid");let qt=Math.min(Ye-pe,de.maxControlAgeSeconds*1e3,nn.maxControlAgeMs)-Math.max(rn,rt-pe,0)-(hr()-J);if(qt<=0)throw Pe("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return hr()+qt}function dt(){if(clearTimeout(y),clearTimeout(A),f||!v.size)return;Se()&&(A=setTimeout(()=>{Se()?dt():he()},Math.max(1,u-hr())),my(A));let Y=d?Math.min(15e3,1e3*2**Math.min(d-1,4)):Math.min(15e3,(c?.policy.refreshIntervalSeconds??15)*1e3);y=setTimeout(()=>{Jt().catch(Re)},Math.max(x,Y*(.8+Math.random()*.2))),my(y)}async function Jt(){if(f)throw Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(h)return h;let Y=g,J=new AbortController;R=J;let de=(async()=>{if(!le){le=!0;try{let Do=await s.readManifest();if(Do&&!c){let Ln=bu.parse(JSON.parse(Do));Ot(Ln.scope)===Ot(t)&&(c=Ln)}}catch{}}J.signal.throwIfAborted();let ze=c,rn=hr(),Lt=await To(a,J.signal);Lt.status===304&&(!ze||!Lt.headers.has("x-indiana-config-validated-at")||!Lt.headers.has("x-indiana-config-valid-until")||!Lt.headers.has("age"))&&(Lt=await To(a,J.signal));let qt=Lt.status===304?ze:bu.parse(JSON.parse(await je(Lt,nn.maxManifestBytes,J.signal))),{generation:Jr,...Zr}=qt,Vn=Lt.headers.get("etag");if(Ot(qt.scope)!==Ot(t)||Gf(Zr)!==Jr||Vn!==`"${Jr}"`&&Vn!==`W/"${Jr}"`)throw Pe("INVALID_RESPONSE","Configuration scope or content identity changed");if(ze&&(qt.revision<ze.revision||qt.revision===ze.revision&&qt.generation!==ze.generation))throw Pe("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[Do,Ln]of Object.entries(ze?.funnels??{})){let xr=qt.funnels[Do];if(xr&&(xr.controlRevision<Ln.controlRevision||xr.evaluationRevision<Ln.evaluationRevision||xr.controlRevision===Ln.controlRevision&&xr.state!==Ln.state||xr.evaluationRevision===Ln.evaluationRevision&&xr.evaluationMode!==Ln.evaluationMode))throw Pe("INVALID_RESPONSE","Funnel control revision changed identity")}let br=Qr(Lt,rn,qt.policy);if(J.signal.throwIfAborted(),Y!==g)throw Pe("CONFIGURATION_DISPOSED","Configuration scope changed");return c=qt,u=br,l=Date.now()+Math.max(0,br-hr()),m=!1,d=0,x=0,s.writeManifest(Ot(qt)),he(),structuredClone(qt)})(),pe=setTimeout(()=>J.abort(Pe("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),nn.initializationMs),Ye=new Promise((ze,rn)=>J.signal.addEventListener("abort",()=>rn(J.signal.reason),{once:!0})),rt=Promise.race([de,Ye]).catch(ze=>{throw d++,(ze instanceof Av.ZodError||ze instanceof SyntaxError||ze instanceof b&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(ze.code))&&(u=0,m=!0,he()),ze}).finally(()=>{clearTimeout(pe),h===rt&&(h=void 0),dt()});return h=rt,rt}async function yr(Y){let J=Y.sha256,de=Zr=>As(Zr,Y);et(Y.url);let pe=j.get(J);if(pe){if(pe.byteLength!==Y.byteLength)throw Pe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return j.delete(J),j.set(J,pe),pe.text}let Ye=_.get(J);if(Ye){if(Ye.byteLength!==Y.byteLength)throw Pe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return Ye.promise}let rt=new AbortController;P.add(rt);let ze=g,rn=(async()=>{try{let br=await s.readArtifact(J);if(br&&de(br)){if(rt.signal.throwIfAborted(),f||ze!==g)throw Pe("CONFIGURATION_DISPOSED","Configuration scope changed");return Qe(J,br,Y.byteLength),br}}catch{}rt.signal.throwIfAborted();let Zr=await To(Y.url,rt.signal,!0),Vn=await je(Zr,Y.byteLength,rt.signal);if(!de(Vn))throw Pe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(f||ze!==g)throw Pe("CONFIGURATION_DISPOSED","Configuration scope changed");return Qe(J,Vn,Y.byteLength),s.writeArtifact(J,Vn),Vn})(),Lt=setTimeout(()=>rt.abort(Pe("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),nn.initializationMs),qt=new Promise((Zr,Vn)=>rt.signal.addEventListener("abort",()=>Vn(rt.signal.reason),{once:!0})),Jr=Promise.race([rn,qt]).finally(()=>{clearTimeout(Lt),P.delete(rt),_.delete(J)});return _.set(J,{promise:Jr,byteLength:Y.byteLength}),Jr}async function Ar(){return Se()||await Jt(),gt(),c}async function Fi(Y){let J,de=new Promise((pe,Ye)=>{J=setTimeout(()=>Ye(Pe("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),nn.initializationMs)});try{return await Promise.race([Y(),de])}finally{clearTimeout(J)}}function Mi(Y,J){if(gt(),c?.generation!==Y.generation)throw Pe("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(J&&c.funnels[J]?.state!=="active")throw Pe("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function pl(Y){let J=Y.gb.features;if(!J)throw Pe("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let de=Y.artifacts[J];if(de.formatVersion!==1)throw Pe("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let pe=zc.parse(JSON.parse(await yr(de)));if(Ot(pe.scope)!==Ot({projectId:t.projectId,environment:t.environment})||pe.generation!==de.generation||pe.remoteFeatures.some(Ye=>Object.hasOwn(pe.features,Ye)))throw Pe("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return Mi(Y),{...pe,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,u-hr())).toISOString()}}async function ml(Y,J){let de=await Ar(),pe=de.funnels[Y];J&&(!pe||pe.evaluationMode==="local"&&!pe.versions[J])&&(h&&await h,de=await Jt()),Mi(de,Y);let Ye=de.funnels[Y];if(Ye.evaluationMode!=="local")throw Pe("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let rt=J??Ye.currentVersionId,ze=Ye.versions[rt];if(!ze)throw Pe("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(de.artifacts[ze.artifact].formatVersion!==3)throw Pe("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[rn,Lt]=await Promise.all([yr(de.artifacts[ze.artifact]).then(qt=>Hf(JSON.parse(qt))),Ye.evaluationMode==="local"?pl(de):void 0]);if(Lt&&Ot(Kf(rn,Lt))!==Ot(ze.dependencies))throw Pe("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return Mi(de,Y),{document:rn,growth:Lt,versionId:rt,control:structuredClone(Ye),manifest:structuredClone(de)}}async function fl(Y,J){try{return await ml(Y,J)}catch(de){if(!(de instanceof b)||!(de.code==="CONFIGURATION_CHANGED"||de.code==="CONFIGURATION_HTTP_404"&&Se()))throw de;let pe=c?.generation;if(h&&await h,await Jt(),de.code!=="CONFIGURATION_CHANGED"&&c?.generation===pe)throw de;return ml(Y,J)}}function Ss(){m=!0,he(),Jt().catch(Re)}let No=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Ss()};function fy(Y){if(f)throw Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return v.add(Y),v.size===1&&(typeof window<"u"&&(window.addEventListener("online",Ss),window.addEventListener("focus",No),document.addEventListener("visibilitychange",No)),dt()),()=>{v.delete(Y),v.size||(clearTimeout(y),clearTimeout(A),gl())}}function gl(){typeof window<"u"&&(window.removeEventListener("online",Ss),window.removeEventListener("focus",No),document.removeEventListener("visibilitychange",No))}return{scope:Object.freeze({...t}),refresh:Jt,subscribe:fy,assertFresh:gt,assertFeatures(Y){gt();let J=c.gb.features;if(!J)throw Pe("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(Y!==void 0&&c.artifacts[J].generation!==Y)throw Pe("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return Se()},get snapshot(){return c?structuredClone(c):null},get remainingMs(){return Se()?Math.max(0,u-hr()):0},async features(){return Fi(async()=>pl(await Ar()))},pageExperiments:()=>Fi(async()=>{let Y=await Ar(),J=Y.gb.pageExperiments;if(!J)throw Pe("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let de=Y.artifacts[J];if(de.formatVersion!==1)throw Pe("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let pe=ih.parse(JSON.parse(await yr(de)));if(pe.environmentId!==t.environmentId||pe.generation!==de.generation)throw Pe("INVALID_RESPONSE","Page experiment scope or generation changed");return Mi(Y),pe}),funnel:(Y,J)=>Fi(()=>fl(Y,J)),paywall:(Y,J)=>Fi(async()=>{let de=await Ar(),pe=de.paywalls?.[Y];if(!pe||!J&&pe.state!=="published")throw Pe("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let Ye=J??pe.currentVersionId,rt=pe.versions[Ye],ze=rt&&de.artifacts[rt.artifact];if(!ze||ze.kind!=="paywall"||ze.formatVersion!==1)throw Pe("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let rn=rs.parse(JSON.parse(await yr(ze)));return Mi(de),{document:rn,versionId:Ye,version:rt.version,control:structuredClone(pe),manifest:structuredClone(de)}}),async localFunnel(Y,J){let de=await Fi(()=>fl(Y,J));if(!de.growth)throw Pe("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:pe,remoteFeatures:Ye,...rt}=de.growth;return nh({scope:{projectId:t.projectId,environment:t.environment},funnelId:Y,versionId:de.versionId,evaluationMode:"local",evaluationRevision:de.control.evaluationRevision,document:de.document,payload:rt})},assertFunnel(Y,J,de){gt();let pe=c.funnels[Y];if(!pe||pe.state!=="active")throw Pe("FUNNEL_STOPPED","Funnel is paused or unavailable");if(pe.evaluationMode!=="local")throw Pe("EVALUATION_MODE","This Funnel now executes at Longplay");if(J!==void 0&&pe.controlRevision!==J)throw Pe("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(de!==void 0&&!pe.versions[de])throw Pe("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!f){f=!0,g++,u=0,R?.abort(Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(y),clearTimeout(A),gl(),he(),v.clear();for(let Y of P)Y.abort(Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));j.clear(),X=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&&Ot(n)!==Ot(e.scope))throw new b("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await t.funnel(e.funnelId)).control.evaluationMode!=="local")throw new b("EVALUATION_MODE","This Funnel uses Remote evaluation");let i=Di.test(e.credential);if(i?!e.customerId:e.customerId!==void 0)throw new b("INVALID_REQUEST","Only Server-Key starts name their Customer");let a=ys({...e,scope:n,apiKey:e.credential}),o=s=>{let c=gr({...e,scope:n,runToken:s,...i?{serverKey:e.credential}:{}});return i||c.identify(e.credential),c};return{async start(s){let c=await a.start({...s,funnelId:e.funnelId,...i?{customer:{type:"id",value:e.customerId}}:{}}),u=o(c.runToken),l=await u.get();return{...c,...l,controller:u}},async restore(s){let c=o(s),u=await c.get();if(u.run.source.id!==e.funnelId)throw c.reset(),new b("SCOPE_MISMATCH","Run belongs to another Funnel");return{...u,runToken:s,controller:c}}}}function dl(e,...t){try{Promise.resolve(e?.(...t)).catch(()=>{})}catch{}}function Sv(e){if(!e.scope)throw new b("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(e.session!==void 0)throw new b("INVALID_CONFIGURATION","The merchant process adapter owns the session");let t=null,n,r=0,i=new Set,a=new Map,o=new Map;async function s(f){let g,d=new Promise((h,R)=>{g=setTimeout(()=>R(new b("TIMEOUT","Process bridge request timed out")),e.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(f),d])}finally{clearTimeout(g)}}function c(f){throw f instanceof b&&(f.status===401||f.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear()),f}function u(f,g){if(g!==r)throw new b("IDENTITY_CHANGED","Process was detached during a request");let d=Mu.parse(f);if(d.scope.projectId!==e.scope.projectId||d.scope.environment!==e.scope.environment)throw new b("SCOPE_MISMATCH","Process response belongs to another App/environment");if(t&&(t.run.id!==d.run.id||t.run.source.versionId!==d.run.source.versionId||t.run.source.id!==d.run.source.id||t.run.runExpiresAt!==d.run.runExpiresAt||t.run.identity.startedAs!==d.run.identity.startedAs||t.run.identity.participantId!==d.run.identity.participantId||t.run.identity.binding&&d.run.identity.binding&&t.run.identity.binding.id!==d.run.identity.binding.id))throw new b("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!t||d.run.revision>=t.run.revision){if(t?.run.identity.binding&&!d.run.identity.binding)throw new b("INVALID_RESPONSE","The process lost its Customer binding");t=d;for(let j of i)dl(j,d.run);d.run.instruction?.type==="authentication_required"&&dl(e.onAuthenticationRequired,d.run)}d.settlement?.accepted!==void 0&&o.set(d.settlement.requestId,d.settlement.accepted);let{identity:h,instruction:R,...y}=d.run,{contract:A,settlement:x,...v}=d,P=x&&(({accepted:j,..._})=>_)(x);return{...v,run:{...y,authenticated:h.binding!==null,instruction:R?.type==="authentication_required"?null:R},...P?{settlement:P}:{}}}let l=f=>(a.has(f)||a.set(f,t?.run.identity.binding?.id??null),a.get(f));async function m(f){let g=r,d=t?.run.identity.binding?.id??null,h=y=>{if(d!==(t?.run.identity.binding?.id??null))throw y;return c(y)};if(f.operation==="page_experiments"){if(!e.adapter.pageExperiments)throw new b("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return s(()=>e.adapter.pageExperiments(f.release,f.usedReceiptIds)).catch(h)}let R;if(f.operation==="get"){let{operation:y,customerToken:A,...x}=f;R=await s(()=>e.adapter.get({...x,...x.settlementRequestId?{settlementBindingId:l(x.settlementRequestId)}:{}})).catch(h)}else if(f.operation==="review")R=await s(()=>e.adapter.review(f.receiptId)).catch(h);else{if(f.operation==="start")throw new b("INVALID_REQUEST","Use process.open for entry");{let{customerToken:y,...A}=f;R=await s(()=>e.adapter.command(A,l(A.requestId))).catch(h)}}return u(R,g)}return{get view(){return t?.run??null},get controller(){return n},async open(f){let g=r,d=await s(()=>e.adapter.open(f)).catch(c);if(u(d,g),!n){n=gr({...e,runToken:d.runToken,process:{request:m,binding:l,restore(y){for(let[A,x]of Object.entries(y))a.set(A,x)}}});let h=n,R=h.submit;h.submit=async y=>{try{return await R(y)}catch(A){if(!(A instanceof b)||A.reason!=="IDENTITY_CONTEXT_CHANGED"||y.operation!=="submit"||y.input.type!=="screen"||a.get(y.requestId)!==null)throw A;await h.settle?.(y.requestId),await h.get();let x=h.view;if(o.get(y.requestId)!==!1||!x||x.id!==t?.run.id||x.nodeId!==y.nodeId||x.visit!==y.visit||!t?.run.identity.binding)throw A;return R({...y,requestId:crypto.randomUUID(),revision:x.revision})}}}await n.get();for(let h of n.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(t?.run.identity.binding?.id??null)&&await n.settle?.(h.requestId);return{run:t.run,controller:n}},async syncIdentity(){let f=r;u(await s(()=>e.adapter.syncIdentity()).catch(c),f),await n?.get();for(let g of n?.pendingCommands??[])a.has(g.requestId)&&a.get(g.requestId)!==(t?.run.identity.binding?.id??null)&&await n?.settle?.(g.requestId);return t.run},async detach(){r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear(),await s(()=>e.adapter.detach())},forProcess(f){if(!t?.run.identity.binding)throw new b("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:t.run.id,bindingId:t.run.identity.binding.id,receiptId:f}},subscribe(f){return i.add(f),()=>{i.delete(f)}},destroy(){r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear(),i.clear()}}}export{b as LongplayError,bv as createConfigurationSync,cl as createFeatureClient,Sv as createFunnelProcess,xv as createLocalFunnelClient,fv as createLongplayReactNative};
|