@tinkerlandai/longplay-react-native 0.10.18-rc.1 → 0.10.18

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"})}),wt=N.record(N.string().min(1).max(128),ve).superRefine((e,t)=>{(!ve.safeParse(e).success||Object.keys(e).length>128||new TextEncoder().encode(JSON.stringify(e)).byteLength>65536||["__proto__","constructor","prototype"].some(n=>Object.hasOwn(e,n)))&&t.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),OA=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),Yt=wt.superRefine((e,t)=>{function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,a]of Object.entries(r)){if(i==="$savedGroup"&&!N.strictObject({id:N.uuid(),attributeKey:N.string().min(1).max(128).optional()}).safeParse(a).success&&t.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!i.startsWith("$")&&i.split(".").some(o=>["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved attribute path"}),i.startsWith("$")&&!OA.has(i)&&t.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${i}`}),["$regex","$regexi"].includes(i)&&typeof a=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(a)||[...a.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(o=>Number(o[1])>255||Number(o[2]||0)>255)||i==="$regexi"&&/[^\x00-\x7f]/.test(a.replace(/\\u([0-9a-f]{4})/gi,(o,s)=>String.fromCharCode(Number.parseInt(s,16)))))&&t.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(a)}catch{t.addIssue({code:"custom",message:"Invalid regular expression"})}}n(a)}}typeof e.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(e.source)&&("operator"in e||"predicates"in e||"groupId"in e)&&t.addIssue({code:"custom",message:"Obsolete condition protocol"}),n(e)}),PA=N.discriminatedUnion("type",[N.strictObject({type:N.literal("condition"),condition:Yt}),N.strictObject({type:N.literal("list"),attributeKey:N.string().min(1).max(128),values:N.array(N.union([N.string(),N.number().finite()])).max(1e5)})]).refine(e=>e.type!=="list"||new TextEncoder().encode(JSON.stringify(e.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function Hn(e){let t=new Set;function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,a]of Object.entries(r))i==="$savedGroup"&&a&&typeof a=="object"&&!Array.isArray(a)&&typeof a.id=="string"?t.add(a.id):["$inGroup","$notInGroup"].includes(i)&&typeof a=="string"?t.add(a):["$eq","$ne","$in","$nin","$ini","$nini"].includes(i)||n(a)}return n(e),[...t]}var CA=N.record(N.uuid(),PA).superRefine((e,t)=>{let n=new Set,r=new Set;function i(a){if(n.has(a)){t.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(r.has(a))return;let o=e[a];if(!o){t.addIssue({code:"custom",message:"Missing saved group dependency"});return}n.add(a),o.type==="condition"&&Hn(o.condition).forEach(i),n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),oc=N.tuple([N.number().min(0).max(1),N.number().min(0).max(1)]).refine(([e,t])=>e<=t),qd=N.strictObject({attribute:N.string().optional(),seed:N.string().min(1),hashVersion:N.literal(2),ranges:N.array(oc).min(1).max(100)}),_A=N.strictObject({id:N.string().min(1).max(128),condition:Yt,gate:N.boolean().optional()}),ic={id:N.string().max(128).optional(),condition:Yt.optional(),parentConditions:N.array(_A).max(50).optional(),filters:N.array(qd).max(20).optional()},EA=N.union([N.strictObject({...ic}),N.strictObject({...ic,force:ve,coverage:N.number().min(0).max(1).optional(),range:oc.optional(),seed:N.string().min(1).optional(),hashAttribute:N.string().optional(),hashVersion:N.literal(2).optional()}),N.strictObject({...ic,type:N.literal("experiment-ref"),experimentId:N.uuid(),values:N.record(N.string().min(1),ve),meta:N.record(N.string().min(1),N.strictObject({passthrough:N.boolean()})).optional()})]),RA=N.strictObject({defaultValue:ve,rules:N.array(EA).max(100)}),bO=N.record(N.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),RA).superRefine((e,t)=>{Object.keys(e).length>100&&t.addIssue({code:"custom",message:"Too many Features"});let n=new Set,r=new Set;function i(a){if(n.has(a)){t.addIssue({code:"custom",message:`Cyclic Feature dependency: ${a}`});return}if(r.has(a))return;let o=e[a];if(!o){t.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${a}`});return}n.add(a);for(let s of o.rules)for(let c of s.parentConditions??[])i(c.id);n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),kA=N.strictObject({name:N.string().max(80),reason:N.string().max(500),dateStarted:N.iso.datetime({offset:!0}),dateEnded:N.iso.datetime({offset:!0}).nullable(),coverage:N.number().min(0).max(1),variationWeights:N.array(N.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:Yt,savedGroups:N.array(N.strictObject({match:N.enum(["any","all","none"]),ids:N.array(N.uuid()).min(1)})).max(50),namespace:N.strictObject({id:N.uuid(),ranges:N.array(oc).min(1)}).nullable(),seed:N.string().min(1).max(128)}),jA=N.strictObject({key:N.string().min(1).max(128),name:N.string().min(1).max(80),hypothesis:N.string().max(2e3),status:N.enum(["draft","running","stopped"]),hashAttribute:N.string().min(1).max(128),fallbackAttribute:N.string().max(128).nullable(),hashVersion:N.literal(2),disableStickyBucketing:N.boolean(),bucketVersion:N.number().int().min(0).max(1e3),minBucketVersion:N.number().int().min(0).max(1e3),variations:N.array(N.strictObject({id:N.string().min(1),key:N.string().min(1),name:N.string().max(80),description:N.string().max(500)})).min(2).max(20),phases:N.array(kA).min(1).max(100),releasedVariationId:N.string().nullable(),excludeFromPayload:N.boolean(),statusSchedule:N.strictObject({startAt:N.iso.datetime({offset:!0}).nullable(),stopAt:N.iso.datetime({offset:!0}).nullable(),stopAfter:N.strictObject({value:N.number().int().positive().max(36500),unit:N.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((e,t)=>{(e.minBucketVersion>e.bucketVersion||e.statusSchedule?.stopAt&&e.statusSchedule?.stopAfter||e.phases.some((n,r)=>{if(r===0)return!1;let i=e.phases[r-1];return!i?.dateEnded||Date.parse(n.dateStarted)<Date.parse(i.dateStarted)||Date.parse(i.dateEnded)>Date.parse(n.dateStarted)})||new Set(e.variations.map(n=>n.key)).size!==e.variations.length||new Set(e.variations.map(n=>n.id)).size!==e.variations.length||e.releasedVariationId!==null&&!e.variations.some(n=>n.id===e.releasedVariationId)||e.statusSchedule?.startAt&&e.statusSchedule?.stopAt&&Date.parse(e.statusSchedule.startAt)>=Date.parse(e.statusSchedule.stopAt)||e.phases.some(n=>n.dateEnded&&Date.parse(n.dateStarted)>=Date.parse(n.dateEnded)||n.namespace?.ranges.some(([r,i],a,o)=>r>=i||o.some(([s,c],u)=>u!==a&&r<c&&s<i)))||e.phases.some(n=>n.variationWeights.length!==e.variations.length))&&t.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});var TA=jA.safeExtend({filters:N.array(qd).optional()}),NA=N.strictObject({experiments:N.record(N.uuid(),TA),savedGroups:CA}),$i=N.strictObject({attributeName:N.string(),attributeValue:N.string(),assignments:N.record(N.string(),N.string())}),xO=N.strictObject({snapshot:NA,attributes:wt,results:wt,stickyBucketAssignmentDocs:N.record(N.string(),$i)}),SO=N.strictObject({variantKey:N.string().nullable(),bucketVersion:N.number().int().min(0),source:N.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:N.number().min(0).max(1).optional(),stickyBucketUsed:N.boolean().optional(),hashUsed:N.boolean().optional()});function tr(e){let t=new Set,n=a=>a!==null&&typeof a=="object"&&!Array.isArray(a);function r(a,o){if(n(a))for(let[s,c]of Object.entries(a))s==="$elemMatch"?i(c,o):s==="$not"?r(c,o):s==="$all"&&Array.isArray(c)&&c.forEach(u=>r(u,o))}function i(a,o=""){if(n(a)){for(let[s,c]of Object.entries(a))if(["$and","$or","$nor"].includes(s)&&Array.isArray(c))c.forEach(u=>i(u,o));else if(s==="$not")i(c,o);else if(s==="$savedGroup"&&n(c))typeof c.attributeKey=="string"&&t.add(c.attributeKey);else if(!s.startsWith("$")){let u=o?`${o}.${s}`:s;t.add(u),r(c,u)}}}return i(e),[...t]}var DA=Tt.enum(["active","inactive"]),FA=Tt.preprocess((e,t)=>{let n=0;function r(i,a){if(!(++n>1e4||a>20)){if(Array.isArray(i))i.forEach(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))["__proto__","constructor","prototype"].includes(o)&&t.addIssue({code:"custom",message:"Reserved merchandise attribute"}),r(s,a+1)}}return r(e,0),e},wt),MA=Tt.strictObject({id:Tt.string().trim().min(1).max(255),name:Tt.string().trim().min(1).max(255),status:DA,metadata:FA}),CO=MA.extend({internal_id:Tt.uuid(),project_id:Tt.uuid(),environment_id:Tt.uuid(),created_at:Tt.iso.datetime({offset:!0}),updated_at:Tt.iso.datetime({offset:!0})}),Bd=Tt.union([Tt.strictObject({id:Tt.string().trim().min(1).max(255)}),Tt.strictObject({internalId:Tt.uuid()})]),_O=Tt.enum(["customer","merchandise","context"]),EO=Tt.enum(["system","stored","request"]),RO=Tt.enum(["customer","merchandise","mixed"]),Ud=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function ac(e,t={},n=new Set){if(tr(e).some(Ud))return!0;for(let r of Hn(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&Ud(i.attributeKey)||i?.type==="condition"&&ac(i.condition,t,n))return!0}return!1}import{z as qA}from"zod";var UA=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,In=qA.string().max(16).regex(UA,"\u8BED\u8A00\u4EE3\u7801\u683C\u5F0F\u4E0D\u6B63\u786E\uFF0C\u4F8B\u5982 zh-CN\u3001en").refine(e=>{try{return Intl.getCanonicalLocales(e)[0]===e}catch{return!1}},"\u6301\u4E45\u5316\u8BED\u8A00\u4EE3\u7801\u5FC5\u987B\u4F7F\u7528\u89C4\u8303\u5199\u6CD5");var qO=te.enum(["draft","active","paused","archived"]),nr=te.discriminatedUnion("type",[te.object({type:te.literal("percent"),percentOff:te.number().min(1).max(100).multipleOf(.01)}).strict(),te.object({type:te.literal("amount"),amountOffCents:te.number().int().min(1).max(1e8),currency:Ie}).strict()]),sn=te.discriminatedUnion("type",[te.object({type:te.literal("once")}).strict(),te.object({type:te.literal("repeating"),months:te.number().int().min(1).max(36)}).strict(),te.object({type:te.literal("forever")}).strict()]),Vd=[te.object({type:te.literal("all")}).strict(),te.object({type:te.literal("plans"),planIds:te.array(te.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],BA=te.discriminatedUnion("type",[...Vd,te.strictObject({type:te.literal("merchandise"),scope:te.discriminatedUnion("type",[te.strictObject({type:te.literal("all")}),te.strictObject({type:te.literal("selected"),merchandiseIds:te.array(te.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),te.strictObject({type:te.literal("condition"),condition:Yt})])})]),sc=te.discriminatedUnion("type",[...Vd,te.strictObject({type:te.literal("merchandise"),scope:te.strictObject({type:te.enum(["all","selected","condition"])})})]),VA=te.strictObject({firstPurchaseOnly:te.boolean(),condition:Yt}),UO=te.object({name:te.string().trim().min(1).max(80),description:te.string().max(500),discount:nr,duration:sn,appliesTo:BA,eligibility:VA,selfClaimEnabled:te.boolean().default(!1),startsAt:te.iso.datetime().nullable(),endsAt:te.iso.datetime().nullable(),totalLimit:te.number().int().min(1).max(1e6).nullable(),perCustomerLimit:te.number().int().min(1).max(10),grantWindowHours:te.number().int().min(1).max(2160)}).strict().refine(e=>!e.startsAt||!e.endsAt||Date.parse(e.endsAt)>Date.parse(e.startsAt),{message:"\u7ED3\u675F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u5F00\u59CB\u65F6\u95F4",path:["endsAt"]}).refine(e=>!ac(e.eligibility.condition),{message:"Customer eligibility cannot read merchandise; use merchandise applicability",path:["eligibility","condition"]}).refine(e=>e.appliesTo.type!=="merchandise"||e.duration.type==="once",{message:"Merchandise Coupons apply to one purchase",path:["duration"]}).refine(e=>e.appliesTo.type!=="merchandise"||!e.eligibility.firstPurchaseOnly,{message:"Merchant purchase eligibility requires trusted targeting attributes",path:["eligibility","firstPurchaseOnly"]}),BO=te.object({code:te.string().trim().transform(e=>e.toUpperCase()).pipe(te.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/,"\u4F18\u60E0\u7801\u53EA\u80FD\u7528 3\u201332 \u4F4D\u5B57\u6BCD\u3001\u6570\u5B57\u3001- \u548C _\uFF0C\u4EE5\u5B57\u6BCD\u6216\u6570\u5B57\u5F00\u5934")),maxRedemptions:te.number().int().min(1).max(1e6).nullable(),expiresAt:te.iso.datetime().nullable(),firstPurchaseOnly:te.boolean(),minimumAmountCents:te.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:Ie.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var Gi=te.object({id:te.uuid(),couponId:te.uuid(),status:te.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:te.iso.datetime(),expiresAt:te.iso.datetime(),coupon:te.object({name:te.string(),discount:nr,duration:sn,appliesTo:sc}).strict()}).strict(),Ld=te.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var Hd=S.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),cc=S.string().regex(/^(0|[1-9]\d{0,14})$/),oi=S.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),LA=S.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),Ki=LA,Qn=xe.refine(e=>/[1-9]/.test(e)),zt=S.iso.datetime({offset:!0}),ua=e=>{let[t,n=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");return BigInt(t)*1000000n+BigInt(n.padEnd(6,"0"))},zA=S.array(S.object({upTo:Qn.nullable(),unitAmountMinor:Hd,flatAmountMinor:S.number().int().min(0).max(1e8).optional()}).strict()).min(1).max(12).refine(e=>{try{return e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let r=e[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&ua(t.upTo)>ua(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),$A=S.discriminatedUnion("kind",[S.object({kind:S.literal("flat"),units:Qn,unitAmountMinor:Hd}).strict(),S.object({kind:S.enum(["graduated","volume"]),units:Qn,tiers:zA}).strict()]).refine(e=>e.kind==="flat"||!e.tiers.some(t=>(t.flatAmountMinor??0)>0)||e.kind==="volume"&&e.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers"),GA=S.strictObject({interval:S.enum(["month","year"]),count:S.number().int().min(1).max(12),anchor:S.enum(["membership","calendar"])}),Hi=S.object({currency:Ie,pricing:$A,billingCycle:GA.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var zd={requestId:S.uuid(),productVersionId:S.uuid(),internal_feature_id:S.uuid(),currency:Ie},Qd=S.strictObject({interval:S.enum(["hour","day","week","month"]),intervalCount:S.number().int().min(1).max(12),limit:S.number().int().min(1).max(1e6)}),Jd=S.discriminatedUnion("kind",[S.object({...zd,kind:S.literal("auto_topup"),threshold:Zo,quantity:Qn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Qd.optional()}).strict(),S.object({...zd,kind:S.literal("postpaid"),maxAmountMinorPerPeriod:Ki,maxOutstandingMinor:Ki}).strict()]),$d={productVersionId:S.uuid(),internal_feature_id:S.uuid(),currency:Ie},Zd=S.discriminatedUnion("kind",[S.object({...$d,kind:S.literal("auto_topup"),threshold:Zo,quantity:Qn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Qd.optional(),purchaseAmountMinor:Ki,purchaseUnits:Qn}).strict(),S.object({...$d,kind:S.literal("postpaid"),maxAmountMinorPerPeriod:Ki,maxOutstandingMinor:Ki,cashPrice:Hi}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),la=S.object({id:S.uuid(),terms:Zd,status:S.enum(["prepared","active","revoked","blocked"]),createdAt:zt,acceptedAt:zt.nullable(),effectiveAt:zt.nullable(),revokedAt:zt.nullable()}).strict().refine(e=>(e.status==="prepared"?e.acceptedAt===null:!0)&&(e.status==="active"?e.acceptedAt!==null&&e.effectiveAt!==null:!0)&&(e.status==="revoked"?e.revokedAt!==null:e.revokedAt===null),"Authorization consent and revocation must be explicit"),Wd=S.object({authorizationId:S.uuid(),terms:Zd,setupUrl:S.url().nullable()}).strict(),Yd=S.object({authorizationId:S.uuid(),accepted:S.literal(!0)}).strict(),Xd=S.object({authorizationId:S.uuid(),requestId:S.uuid()}).strict(),ep=S.object({internal_feature_id:S.uuid(),entityId:S.uuid().nullable(),interval:S.enum(["day","week","month","year"]),anchor:S.enum(["billing_cycle","utc"]).optional(),basis:S.enum(["usage","credits"]),filter:vt.optional(),limit:xe.nullable(),thresholds:S.array(S.number().positive().max(1)).max(8),includedThresholds:S.array(S.number().positive().max(1)).max(8).optional(),absoluteThresholds:S.array(Qn).max(8).optional()}).strict().refine(e=>e.thresholds.every((t,n)=>{let r=e.thresholds[n-1];return n===0||r!==void 0&&t>r})&&(e.includedThresholds??[]).every((t,n,r)=>{let i=r[n-1];return n===0||i!==void 0&&t>i})&&(e.absoluteThresholds??[]).every((t,n,r)=>{let i=r[n-1];return n===0||i!==void 0&&ua(t)>ua(i)}),"Notification thresholds must increase"),KA=ep.safeExtend({requestId:S.uuid()}),Gd={control:S.literal("overage"),requestId:S.uuid(),internal_feature_id:S.uuid(),entityId:S.uuid().nullable()},HA=S.discriminatedUnion("action",[S.strictObject({...Gd,action:S.literal("set"),allowed:S.boolean().nullable(),overageLimit:xe.nullable(),skipOverageBilling:S.boolean()}),S.strictObject({...Gd,action:S.literal("remove")})]),tp=S.union([KA,HA]),QA=S.strictObject({internal_feature_id:S.uuid(),entityId:S.uuid().nullable(),allowed:S.boolean().nullable(),overageLimit:xe.nullable(),skipOverageBilling:S.boolean(),interval:S.enum(["day","week","month","year"]),startsAt:zt,endsAt:zt,used:S.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:S.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:S.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),JA=S.object({internal_feature_id:S.uuid(),entityId:S.uuid().nullable(),interval:S.enum(["day","week","month","year"]),anchor:S.enum(["billing_cycle","utc"]).optional(),basis:S.enum(["usage","credits"]),filter:vt.optional(),startsAt:zt,endsAt:zt,used:Wt,reserved:Wt,limit:xe.nullable(),thresholds:S.array(S.number().positive().max(1)).max(8),notifiedThresholds:S.array(S.number().positive().max(1)).max(1024),includedThresholds:S.array(S.number().positive().max(1)).max(8).optional(),includedAllowance:S.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:S.array(S.number().positive().max(1)).max(1024).optional(),absoluteThresholds:S.array(Qn).max(8).optional(),notifiedAbsoluteThresholds:S.array(Qn).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||xe.safeParse(e.used).success&&xe.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),ZA=S.object({authorizationId:S.uuid(),status:S.enum(["idle","pending","blocked"]),taskId:S.uuid().nullable(),invoiceId:S.uuid().nullable(),hostedInvoiceUrl:S.url().nullable(),purchaseCount:S.number().int().nonnegative(),purchaseWindowEndsAt:zt.nullable(),attemptCount:S.number().int().nonnegative(),failedAttemptCount:S.number().int().nonnegative(),suspendedAt:zt.nullable(),nextAttemptAt:zt.nullable(),failureReason:S.string().min(1).max(240).nullable()}).strict(),np=S.object({internal_feature_id:S.uuid().optional(),entityId:S.uuid().optional()}).strict(),uc=S.object({authorizations:S.array(la).max(100),limits:S.array(ep).max(100),overages:S.array(QA).max(100).optional(),windows:S.array(JA).max(200),autoTopups:S.array(ZA).max(100),limited:S.boolean()}).strict(),WA=S.object({id:S.uuid(),internal_feature_id:S.uuid(),productVersionId:S.uuid(),authorizationId:S.uuid(),entityId:S.uuid().nullable(),units:xe,amountMinor:oi,cashPrice:Hi}).strict(),Qi=S.object({id:S.uuid(),sourceKind:S.enum(["product","usage","manual"]),providerInvoiceId:S.string().min(1).max(240).nullable(),status:S.enum(["accruing","open","pending","paid","failed","void"]),currency:Ie,startsAt:zt.nullable(),endsAt:zt.nullable(),amountMinor:S.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:S.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:cc,paidAmountMinor:cc,refundedAmountMinor:cc,createdAt:zt,hostedInvoiceUrl:S.url().nullable(),adjustment:S.object({originalInvoiceId:S.uuid(),amountMinor:S.string().regex(/^-?(0|[1-9]\d{0,8})$/).refine(e=>e!=="-0"&&/^-?(0|[1-9]\d{0,8})$/.test(e)&&BigInt(e)>=-200000000n&&BigInt(e)<=200000000n,"Invoice adjustment exceeds the bounded minor amount"),acceptedAt:zt.nullable(),reason:S.string().min(1).max(500).optional()}).strict().nullable(),lines:S.array(WA).max(100),linesLimited:S.boolean()}).strict(),rp=S.object({invoiceId:S.uuid(),accepted:S.literal(!0)}).strict(),ip=S.strictObject({requestId:S.uuid(),originalInvoiceId:S.uuid(),amountMinor:S.string().regex(/^[1-9]\d{0,8}$/).refine(e=>/^[1-9]\d{0,8}$/.test(e)&&BigInt(e)<=200000000n,"Supplemental amount exceeds the bounded minor amount"),reason:S.string().trim().min(1).max(500)}),op=S.object({after:S.uuid().nullable(),limit:S.number().int().min(1).max(100)}).strict(),ap=S.object({rows:S.array(Qi).max(100),nextCursor:S.uuid().nullable()}).strict(),Kd=S.strictObject({id:S.string(),coupon:S.string(),start:S.number().nonnegative(),end:S.number().nullable()}),YA=S.strictObject({subscriptionId:S.string(),customerId:S.string(),accountId:S.string(),sourceItems:S.array(S.strictObject({id:S.string(),price_id:S.string(),quantity:S.number().int(),discounts:S.array(Kd).optional()})).max(100),items:S.array(S.strictObject({id:S.string(),price:S.string(),quantity:S.number().int(),discounts:S.array(S.strictObject({coupon:S.string().optional(),terms:S.strictObject({id:S.string(),name:S.string().optional(),percent_off:S.number().optional(),amount_off:S.number().optional(),currency:S.string().optional(),duration:S.enum(["once","forever","repeating"]),duration_in_months:S.number().optional()}).optional(),discount:S.string().optional(),receipt:Kd.optional()})).max(20)})).max(100)}),sp=S.strictObject({membershipId:S.uuid(),requestId:S.uuid(),grantIds:S.array(S.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),cp=S.strictObject({membershipId:S.uuid(),operationId:S.uuid(),status:S.enum(["pending","effective"]),execution:YA.nullable(),grants:S.array(S.strictObject({id:S.uuid(),couponId:S.uuid(),name:S.string(),discount:nr,duration:sn,startedAt:zt.nullable()})).max(20)});import{z as Ji}from"zod";var up=Ji.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),lp=Ji.number().int().min(1).max(1e3),da=Ji.object({cap:xe.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:Ji.number().positive().max(1e4).nullable(),cycles:Ji.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");import{z as rr}from"zod";var dp=rr.strictObject({itemKey:rr.string().regex(/^paid:feature:[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),internal_feature_id:rr.uuid(),includedAmount:rr.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:rr.number().int().min(0).max(1e4),terms:Yo,pricing:Vi.optional(),unitAmountMinor:rr.number().int().min(0).max(1e8),productId:rr.string().min(1).max(255).nullable(),priceId:rr.string().min(1).max(255).nullable()}).superRefine((e,t)=>{(e.quantity<e.terms.minimumQuantity||e.quantity>e.terms.maximumQuantity||e.productId===null!=(e.priceId===null)||e.quantity>0&&(e.pricing||e.unitAmountMinor>0)&&e.priceId===null)&&t.addIssue({code:"custom",message:"Purchased quantities need their published bounds and immutable price binding"});try{rd(e.includedAmount,e.terms.units,e.quantity),Wo({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{t.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});import{z as ne}from"zod";var Cr=xe.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Zi=ne.string().min(1).max(120),pa=ne.enum(["cap","overflow"]),cn=(e,t)=>{let[n,r=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");return BigInt(n)*10n**BigInt(t)+BigInt(r.padEnd(t,"0"))},Wi=e=>{try{return e()}catch{return!1}},Yi=ne.discriminatedUnion("operation",[ne.object({operation:ne.literal("quote"),overageBehavior:pa.optional(),internal_feature_id:ne.uuid(),entityId:ne.uuid().optional(),quantity:Cr,properties:vt}).strict(),ne.object({operation:ne.literal("consume"),overageBehavior:pa.optional(),occurredAt:ne.iso.datetime({offset:!0}).optional(),internal_feature_id:ne.uuid(),entityId:ne.uuid().optional(),quantity:xe,properties:vt,idempotencyKey:Zi}).strict(),ne.object({operation:ne.literal("reserve"),occurredAt:ne.iso.datetime({offset:!0}).optional(),internal_feature_id:ne.uuid(),entityId:ne.uuid().optional(),quantity:Cr,properties:vt,idempotencyKey:Zi,expiresInSeconds:ne.number().int().min(1).max(86400)}).strict(),ne.object({operation:ne.literal("confirm"),operationId:ne.uuid(),quantity:Cr,properties:vt.optional(),idempotencyKey:Zi}).strict(),ne.object({operation:ne.literal("refund"),operationId:ne.uuid(),quantity:Cr,idempotencyKey:Zi}).strict(),ne.object({operation:ne.literal("release"),operationId:ne.uuid(),idempotencyKey:Zi}).strict()]),lc=ne.object({internal_credit_feature_id:ne.uuid().nullable(),internal_metered_feature_id:ne.uuid(),dimension:ne.string().min(1).max(64),counterKey:ne.string().min(1).max(240),cycleStart:ne.iso.datetime({offset:!0}),unitCost:xe,units:Cr,amount:Wt,tier:ne.number().int().min(1).max(12).nullable()}).strict(),_r=ne.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function pp(e,t){let n=e.reduce((r,i)=>r+cn(i.units,12),0n)-cn(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var mp=ne.discriminatedUnion("funding",[ne.strictObject({funding:ne.literal("balance"),sourceId:ne.uuid(),rolloverId:ne.uuid().nullable(),units:_r.refine(e=>/[1-9]/.test(e)),amount:Wt}),ne.strictObject({funding:ne.literal("unbilled"),units:_r.refine(e=>/[1-9]/.test(e))}),ne.object({funding:ne.literal("prepaid"),sourceId:ne.uuid(),units:Cr,amount:Wt,pricing:ne.array(lc).min(1).max(12)}).strict().refine(e=>Wi(()=>e.pricing.reduce((t,n)=>t+cn(n.units,6),0n)===cn(e.units,6)&&e.pricing.reduce((t,n)=>t+cn(n.amount,12),0n)===cn(e.amount,12)&&e.pricing.every(t=>cn(t.unitCost,6)*cn(t.units,6)===cn(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),ne.object({funding:ne.literal("postpaid"),invoiceLineId:ne.uuid().nullable(),units:Cr,authorizationId:ne.uuid()}).strict()]),ma=ne.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),fp=ne.object({allowed:ne.boolean(),internal_feature_id:ne.uuid(),quantity:xe,requestedQuantity:xe.optional(),overageBehavior:pa.optional(),reason:ma.nullable(),allocations:ne.array(mp).max(500)}).strict().refine(e=>Wi(()=>e.allowed?e.reason===null&&pp(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>Wi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&cn(e.requestedQuantity,6)>=cn(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Xi=ne.object({id:ne.uuid(),internal_feature_id:ne.uuid(),kind:ne.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:ne.uuid().nullable(),quantity:xe,requestedQuantity:xe.optional(),overageBehavior:pa.optional(),accepted:ne.boolean(),reason:ne.enum([...ma.options,"expired"]).nullable(),createdAt:ne.iso.datetime({offset:!0}),reservationStatus:ne.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:ne.iso.datetime({offset:!0}).nullable(),allocations:ne.array(mp).max(500)}).strict().refine(e=>Wi(()=>e.accepted?e.reason===null&&pp(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>Wi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&cn(e.requestedQuantity,6)>=cn(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");import{z as De}from"zod";var Er=De.iso.datetime({offset:!0}),gp=xe.refine(e=>/[1-9]/.test(e)),hp=De.strictObject({interval:up.exclude(["lifetime"]),count:lp}),XA=De.strictObject({action:De.literal("create"),requestId:De.uuid(),internal_feature_id:De.uuid(),entityId:De.uuid().nullable(),amount:gp.nullable(),expiresAt:Er.nullable(),reset:hp.nullable(),rollover:da.nullable(),nextResetAt:Er.nullable()}).refine(e=>e.amount!==null||e.reset===null&&e.rollover===null,"Unlimited grants cannot reset or roll over").refine(e=>!e.rollover||e.reset!==null,"Rollover requires a recurring grant").refine(e=>e.nextResetAt===null||e.reset!==null&&(e.expiresAt===null||Date.parse(e.nextResetAt)<Date.parse(e.expiresAt)),"The first reset needs a reset interval and must precede expiry"),yp=De.discriminatedUnion("action",[XA,De.strictObject({action:De.literal("update"),requestId:De.uuid(),grantId:De.uuid(),revision:De.number().int().nonnegative(),amount:gp.nullable(),expiresAt:Er.nullable(),rollover:da.nullable(),nextResetAt:Er.nullable()}),De.strictObject({action:De.enum(["add","subtract","set_remaining"]),requestId:De.uuid(),grantId:De.uuid(),revision:De.number().int().nonnegative(),amount:xe}),De.strictObject({action:De.literal("revoke"),requestId:De.uuid(),grantId:De.uuid(),revision:De.number().int().nonnegative()})]),dc=De.strictObject({id:De.uuid(),internal_feature_id:De.uuid(),entityId:De.uuid().nullable(),amount:xe.nullable(),reset:hp.nullable(),rollover:da.nullable(),nextResetAt:Er.nullable(),startsAt:Er,expiresAt:Er.nullable(),revision:De.number().int().nonnegative(),revoked:De.boolean(),available:Wt,held:Wt,spent:Wt}),Ap=De.strictObject({customerId:De.uuid(),after:De.uuid().nullable(),limit:De.number().int().min(1).max(100)}),bp=De.strictObject({rows:De.array(dc).max(100),nextCursor:De.uuid().nullable()});import{z as ie}from"zod";var Dn=ie.iso.datetime({offset:!0}),xp=ie.strictObject({invoiceId:ie.uuid(),after:ie.string().min(1).max(180).nullable(),limit:ie.number().int().min(1).max(100)}),eb=ie.strictObject({kind:ie.literal("product"),key:ie.string(),productVersionId:ie.uuid(),productName:ie.string(),itemKey:ie.string(),entityId:ie.uuid().nullable(),quantity:ie.number().positive(),subtotalMinor:ie.string().regex(/^-?\d+$/),discountMinor:ie.string().regex(/^\d+$/),taxMinor:ie.string().regex(/^-?\d+$/).nullable(),totalMinor:ie.string().regex(/^-?\d+$/),startsAt:Dn.nullable(),endsAt:Dn.nullable(),providerLineId:ie.string().nullable(),providerItemId:ie.string()}),Sp=ie.strictObject({invoice:Qi,items:ie.array(ie.discriminatedUnion("kind",[eb,ie.strictObject({kind:ie.literal("invoice_credit"),key:ie.string(),internal_feature_id:ie.uuid(),internal_credit_feature_id:ie.uuid(),name:ie.string(),units:xe,reserved:xe,amountMinor:oi,grossAmountMinor:oi,creditsAppliedMinor:oi,properties:vt,cashPrice:Hi,providerItemId:ie.string().nullable(),creditProviderItemId:ie.string().nullable()}),ie.strictObject({kind:ie.literal("usage"),key:ie.string(),internal_feature_id:ie.uuid(),name:ie.string(),units:xe,reserved:xe,amountMinor:oi,cashPrice:Hi})])).max(100),nextCursor:ie.string().min(1).max(180).nullable()}),tb=ie.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),pc=ie.strictObject({from:Dn,to:Dn,entityId:ie.uuid().optional(),snapshotAt:Dn.nullable(),after:ie.strictObject({at:Dn,id:ie.uuid(),position:ie.number().int().nonnegative()}).nullable(),limit:ie.number().int().min(1).max(100)}).refine(e=>Date.parse(e.from)<Date.parse(e.to)&&Date.parse(e.to)-Date.parse(e.from)<=366*864e5,"Statement range must be positive and at most 366 days").refine(e=>e.after===null||e.snapshotAt!==null,"A cursor requires the original snapshot time"),Ip=ie.strictObject({customerId:ie.uuid(),entityId:ie.uuid().nullable(),from:Dn,to:Dn,snapshotAt:Dn,totals:ie.array(ie.strictObject({internal_credit_feature_id:ie.uuid(),name:ie.string(),consumed:Wt,refunded:Wt,net:tb})).max(1e3),rows:ie.array(ie.strictObject({operationId:ie.uuid(),position:ie.number().int().nonnegative(),kind:ie.enum(["consume","confirm","refund"]),originalId:ie.uuid().nullable(),occurredAt:Dn,internal_feature_id:ie.uuid(),entitlementName:ie.string(),sourceId:ie.uuid(),internal_credit_feature_id:ie.uuid(),creditName:ie.string(),units:_r,amount:Wt,pricing:ie.array(lc).max(12),properties:vt})).max(100),nextCursor:pc.shape.after});import{z as D}from"zod";import{z as vn}from"zod";var nb=vn.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),rb=vn.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),fa=vn.strictObject({internal_feature_id:vn.uuid(),entityId:vn.uuid().nullable()}),vp=fa.extend({quantity:xe,expectedRevision:vn.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:vn.string().min(1).max(120),properties:vt.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),eo=fa.extend({operationId:vn.uuid().nullable(),usage:xe,capacity:nb.nullable(),remaining:rb.nullable(),withinLimit:vn.boolean(),revision:vn.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:vn.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let n=r=>{let i=r.startsWith("-"),[a,o=""]=(i?r.slice(1):r).split(".");if(a===void 0||a==="")throw new Error("Invalid decimal value");return(i?-1n:1n)*(BigInt(a)*10n**12n+BigInt(o.padEnd(12,"0")))};(e.capacity===null!=(e.remaining===null)||(e.capacity===null?!e.withinLimit:e.remaining===null||n(e.remaining)!==n(e.capacity)-n(e.usage)||e.withinLimit!==n(e.remaining)>=0n)||e.revision===0!=(e.operationId===null)||e.operationId===null!=(e.updatedAt===null))&&t.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var $t=D.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),wn=D.iso.datetime({offset:!0}),ib=D.enum(["access","metered","credit"]),to={internal_feature_id:D.uuid(),key:Or,name:D.string().min(1).max(120),kind:ib},wp=D.object({customerId:D.uuid(),snapshotAt:wn,memberships:D.array(D.object({id:D.uuid(),productId:D.string().min(1).max(255),productVersionId:D.uuid(),billingProductVersionId:D.uuid(),version:D.number().int().positive(),key:D.string().min(1).max(64),name:D.string().min(1).max(120),groupId:D.string().max(255).nullable(),membershipType:D.enum(["main","addon"]),status:D.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:D.boolean(),accessEnabled:D.boolean(),renewalChange:D.object({productVersionId:D.uuid(),name:D.string().min(1).max(120),version:D.number().int().positive(),effectiveAt:wn,benefitsAppliedAt:wn.nullable(),timing:D.enum(["immediate","renewal"]),changeKind:D.enum(["plan","seats","quantity"]),feature:D.strictObject({internal_feature_id:D.uuid(),name:D.string().min(1).max(80),fromQuantity:D.number().int().min(0).max(1e4),toQuantity:D.number().int().min(0).max(1e4)}).optional(),seat:D.object({key:D.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:D.number().int().min(0).max(1e4),toQuantity:D.number().int().min(0).max(1e4)}).strict().nullable(),status:D.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(e=>e.changeKind==="seats"==(e.seat!==null)&&e.changeKind==="quantity"==(e.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:D.object({phase:D.enum(["paid","trial"]),startsAt:wn,endsAt:wn.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:D.boolean(),balances:D.array(D.object({...to,usageType:D.enum(["consumable","non_consumable"]).nullable(),accessible:D.boolean(),unlimited:D.boolean(),available:$t,held:$t,debt:$t,nextExpiresAt:wn.nullable(),usage:eo.nullable()}).strict().refine(e=>e.kind==="metered"==(e.usageType!==null)&&(e.accessible||e.available==="0"&&e.held==="0")&&(e.usageType==="non_consumable"?e.usage!==null&&e.usage.internal_feature_id===e.internal_feature_id&&e.unlimited===(e.usage.capacity===null)&&e.available===(e.usage.remaining===null||e.usage.remaining.startsWith("-")?"0":e.usage.remaining)&&e.held==="0"&&e.debt==="0":e.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:D.boolean()}).strict(),Op=D.enum(["source","usage","transaction","invoice","debt","settlement"]),ga=D.object({at:wn,id:D.uuid(),type:Op}).strict(),Pp=D.object({type:Op.nullable(),resourceKey:Or.optional(),kind:D.enum(["purchase","refund"]).optional(),topup:D.boolean().optional(),from:D.iso.date().nullable(),to:D.iso.date().nullable(),after:ga.nullable(),limit:D.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),ai={id:D.uuid(),occurredAt:wn},ob=D.discriminatedUnion("type",[D.strictObject({...ai,type:D.literal("invoice"),status:D.string().min(1).max(80),paid:$t,refunded:$t,currency:Ie,externalId:D.string().nullable()}),D.object({...ai,...to,type:D.literal("source"),reason:D.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:$t,unlimited:D.boolean(),status:D.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:wn,expiresAt:wn.nullable(),orderId:D.uuid().nullable(),parentSourceId:D.uuid().nullable()}).strict(),D.object({...ai,type:D.literal("usage"),internal_feature_id:D.uuid(),name:D.string().min(1).max(120),kind:D.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:D.uuid().nullable(),quantity:xe,accepted:D.boolean(),reason:D.enum([...ma.options,"expired"]).nullable(),properties:vt,reservationStatus:D.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:wn.nullable(),charges:D.array(D.discriminatedUnion("funding",[D.strictObject({funding:D.literal("balance"),sourceId:D.uuid(),rolloverId:D.uuid().nullable(),units:_r,amount:$t}),D.strictObject({funding:D.literal("unbilled"),units:_r}),D.object({...to,funding:D.literal("prepaid"),amount:$t}).strict(),D.object({funding:D.literal("postpaid"),invoiceId:D.uuid(),invoiceLineId:D.uuid(),authorizationId:D.uuid(),units:xe,currency:Ie}).strict()])).max(500)}).strict().refine(e=>(e.kind==="set_usage"||e.kind==="consume"&&e.quantity==="0"?e.accepted&&e.reason===null&&e.charges.length===0&&e.reservationStatus===null:e.accepted?e.reason===null&&e.charges.length>0:e.reason!==null&&e.charges.length===0)&&e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),D.object({...ai,type:D.literal("transaction"),purpose:D.enum(["product","invoice"]),productVersionId:D.uuid().nullable(),productName:D.string().min(1).max(120).nullable(),productVersion:D.number().int().positive().nullable(),invoiceId:D.uuid().nullable(),orderId:D.uuid(),originalId:D.uuid().nullable(),kind:D.enum(["purchase","refund"]),amountMinor:D.number().int().nonnegative().max(2e8).nullable(),currency:Ie.nullable()}).strict().refine(e=>e.currency===null==(e.amountMinor===null)&&(e.purpose==="product"?e.productVersionId!==null&&e.productName!==null&&e.productVersion!==null&&e.invoiceId===null:e.productVersionId===null&&e.productName===null&&e.productVersion===null&&e.invoiceId!==null)&&e.kind==="refund"==(e.originalId!==null)&&(e.kind!=="refund"||e.amountMinor===null||e.amountMinor>0),"Payment fact provenance is incomplete"),D.object({...ai,...to,type:D.literal("debt"),sourceId:D.uuid(),transactionId:D.uuid(),amount:$t}).strict(),D.object({...ai,...to,type:D.literal("settlement"),sourceId:D.uuid(),debtId:D.uuid(),kind:D.enum(["payment","usage_refund","payment_return"]),amount:$t}).strict()]),Cp=D.object({customerId:D.uuid(),rows:D.array(ob).max(50),nextCursor:ga.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");import{z as fe}from"zod";var Ep=fe.object({customerId:fe.uuid()}).strict(),Rp=fe.discriminatedUnion("action",[fe.object({customerId:fe.uuid(),requestId:fe.uuid(),action:fe.literal("assign"),poolId:fe.uuid(),memberCustomerId:fe.uuid()}).strict(),fe.strictObject({customerId:fe.uuid(),requestId:fe.uuid(),action:fe.literal("assign_entity"),poolId:fe.uuid(),entityId:fe.uuid()}),fe.object({customerId:fe.uuid(),requestId:fe.uuid(),action:fe.literal("release"),poolId:fe.uuid(),slotId:fe.uuid()}).strict()]),no=fe.number().int().nonnegative(),mc=fe.iso.datetime({offset:!0}),fc=fe.strictObject({internalId:fe.uuid(),id:fe.string(),name:fe.string().nullable(),version:fe.number().int().positive()}),_p=fe.enum(["active","past_due"]),gc=fe.strictObject({customerId:fe.uuid(),licenses:fe.array(fe.strictObject({id:fe.uuid(),linkId:fe.uuid(),parent:fe.strictObject({customerProductId:fe.uuid(),status:_p,product:fc}),product:fc,planLicense:fe.strictObject({id:fe.uuid(),prepaidOnly:fe.boolean(),isCustom:fe.boolean()}).nullable(),granted:no,included:no,paidQuantity:no,usage:no,remaining:no,createdAt:mc}).refine(e=>e.granted===e.included+e.paidQuantity&&e.granted===e.usage+e.remaining,"Granted seats are included plus paid, and usage plus remaining")).max(2e3),assignments:fe.array(fe.strictObject({id:fe.uuid(),linkId:fe.uuid(),status:_p,product:fc,entity:fe.strictObject({internalId:fe.uuid(),id:fe.string().nullable(),name:fe.string().nullable()}).nullable(),beneficiary:fe.strictObject({internalId:fe.uuid(),id:fe.string().nullable(),name:fe.string().nullable()}).nullable(),startedAt:mc.nullable(),endedAt:mc.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:fe.boolean()});import{z as me}from"zod";var ro=me.enum(["email","sms","voice","push"]),OP=me.enum(["resend","twilio","fcm","apns"]);var PP=me.string().regex(/^\+[1-9]\d{1,14}$/),ab=me.enum(["email_recipient","sms_segment","voice_second","push_device"]);var sb=me.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),cb=me.strictObject({subject:sb,html:me.string().min(1).max(131072).optional(),text:me.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),ub=me.strictObject({body:me.string().min(1).max(1600).refine(e=>e.trim().length>0)}),lb=me.strictObject({text:me.string().trim().min(1).max(4e3),language:me.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:me.number().int().min(1).max(900)}),db=me.record(me.string().min(1).max(64),me.string().max(256)).refine(e=>Object.keys(e).length<=20&&Object.keys(e).every(t=>!/^(?:indiana_|google\.|gcm\.)/i.test(t)&&t!=="aps"),"Push data contains reserved fields or too many entries"),pb=me.strictObject({title:me.string().trim().min(1).max(200),body:me.string().trim().min(1).max(2e3),url:me.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:db.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),kp=me.discriminatedUnion("channel",[me.strictObject({channel:me.literal("email"),content:cb}),me.strictObject({channel:me.literal("sms"),content:ub}),me.strictObject({channel:me.literal("voice"),content:lb}),me.strictObject({channel:me.literal("push"),content:pb})]),jp=me.strictObject({requestId:me.uuid(),customerId:me.uuid(),connectionId:me.uuid().optional(),message:kp,expiresAt:me.iso.datetime({offset:!0})}),mb=me.array(me.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),fb=me.discriminatedUnion("kind",[me.strictObject({kind:me.literal("all")}),me.strictObject({kind:me.literal("customers"),customerIds:mb})]),CP=me.strictObject({name:me.string().trim().min(1).max(120),connectionId:me.uuid().optional(),message:kp,audience:fb,frequencyLimit:me.number().int().min(1).max(100)}),Tp=me.strictObject({requestId:me.uuid(),channel:ro,state:me.enum(["allowed","denied"]),expectedRevision:me.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),Np=me.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Dp=me.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),_P=me.strictObject({meter:ab,estimatedUnits:me.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:me.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});import{z as Ce}from"zod";import{z as re}from"zod";import{z as si}from"zod";var io=si.strictObject({internalFeatureId:si.uuid(),name:si.string().min(1).max(120),includedAmount:si.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:si.enum(["hour","day","week","month","year","lifetime"]),resetCount:si.number().int().min(1).max(100),terms:Yo});import{z as ct}from"zod";import{z as gb}from"zod";import{z as ci}from"zod";var Fp=ci.enum(["stripe","apple","google","merchant"]),Mp=ci.enum(["membership","credit_pack","lifetime"]),NP=ci.enum(["active","grace","suspended","inactive","revoked"]),DP=ci.strictObject({currency:ci.string().regex(/^[A-Z]{3}$/),micros:ci.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var ui=gb.object({provider:Fp,currency:Ie}).strict();var ir=ct.strictObject({internal_feature_id:ct.uuid(),quantity:xe.refine(e=>/[1-9]/.test(e)),properties:vt,entityId:ct.uuid().optional()}),qp=ct.strictObject({requirement:ir,commerce:ui.optional(),paywallId:ct.uuid().optional()}),hb=ct.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),hc=ct.strictObject({productId:ct.string().min(1),productVersionId:ct.string().min(1),name:ct.string().min(1).max(120),action:ct.enum(["purchase","upgrade","addon","topup"]),membershipId:ct.string().min(1).nullable(),currency:Ie,amountMinor:ct.string().regex(/^(0|[1-9]\d{0,8})$/),interval:ct.enum(["free","week","month","year","one_time"]),intervalCount:ct.number().int().min(1).max(156)}),Rr=ct.strictObject({internal_feature_id:ct.string().min(1),name:ct.string().min(1).max(120),kind:ct.enum(["access","metered","credit"]),quantity:xe,allowed:ct.boolean(),reason:hb.nullable(),preview:ct.strictObject({scenario:ct.enum(["feature_flag","usage_limit"]),candidates:ct.array(hc).max(20)}).nullable()}).superRefine((e,t)=>{(e.allowed!==(e.reason===null)||e.allowed&&e.preview!==null||new Set(e.preview?.candidates.map(n=>n.productVersionId)).size!==(e.preview?.candidates.length??0)||e.preview?.candidates.some(n=>n.action==="upgrade"!=(n.membershipId!==null)))&&t.addIssue({code:"custom",message:"Invalid access recommendation"})}),GP=ct.strictObject({paywallId:ct.uuid(),requirement:ir});var ya=re.object({plan:re.string().min(1).max(200).optional(),coupon:re.uuid().optional(),promotionCode:re.uuid().optional(),picker:re.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),ha=re.object({text:re.string().optional(),label:re.string().optional(),alt:re.string().optional(),html:re.string().max(32768).optional(),price:re.object({current:re.string(),original:re.string().nullable(),period:re.string()}).optional(),code:re.string().optional(),countdownAt:re.iso.datetime().optional(),planId:re.string().min(1).max(200).optional(),planVersionId:re.string().min(1).max(200).optional(),currency:Ie.optional(),couponId:re.uuid().optional(),offerId:re.uuid().optional(),unavailable:re.boolean().optional(),unavailableReason:re.string().optional(),missing:re.array(re.string()).optional()}).strict(),li=re.object({paywall:Rr.optional(),nodes:re.record(re.string(),re.object({base:ha,picker:re.string().optional(),byPlan:re.record(re.string(),ha).optional()}).strict()),plans:re.record(re.string(),re.object({id:re.string().min(1).max(200),versionId:re.string().min(1).max(200),available:re.boolean(),name:re.string(),price:re.string(),period:re.string(),currency:Ie.optional(),amountMinor:re.number().int().nonnegative().optional(),interval:re.enum(["free","week","month","year","one_time"]).optional(),intervalCount:re.number().int().positive().optional(),prepaid:re.array(io).max(100).optional()}).strict()),pickers:re.record(re.string(),re.object({options:re.array(re.string().min(1).max(200)).max(20),selected:re.string().min(1).max(200).nullable()}).strict()),quantities:re.record(re.string(),re.strictObject({minimum:re.number().int().nonnegative(),maximum:re.number().int().nonnegative(),step:re.number().int().positive(),value:re.number().int().nonnegative(),label:re.string(),available:re.boolean()})).optional(),diagnostics:re.array(re.object({nodeId:re.string(),message:re.string()}).strict())}).strict();function Up(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}import{z as I}from"zod";function yb(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function Bp(e){let t={};function n(r){var i;if(yb(r)){let a=t[i=r.interaction.pickerId]??(t[i]={ids:[],defaultId:null});for(let s of r.children){let c=s.type==="stack"?s.bind?.plan:void 0;c&&!a.ids.includes(c)&&a.ids.push(c)}let o=r.children[r.interaction.defaultIndex];!a.defaultId&&o?.type==="stack"&&(a.defaultId=o.bind?.plan??null)}r.type==="stack"&&r.children.forEach(n)}return e.pages.forEach(r=>n(r.root)),t}import{z as Jn}from"zod";var Vp=Jn.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Aa=Jn.strictObject({tiers:Jn.array(Jn.strictObject({id:Vp,name:Jn.string().trim().min(1).max(80)})).min(1).max(8),assignments:Jn.array(Jn.strictObject({productVersionId:Jn.string().min(1).max(200),tierId:Vp,period:Jn.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let n=e.tiers.map(r=>r.id);(new Set(n).size!==n.length||new Set(e.assignments.map(r=>r.productVersionId)).size!==e.assignments.length||new Set(e.assignments.map(r=>`${r.tierId}:${r.period}`)).size!==e.assignments.length||e.assignments.some(r=>!n.includes(r.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function ba(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}import{z as ce}from"zod";var Ab=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],Lp=ce.enum(Ab),zp=ce.object({source:Lp,layout:ce.enum(["full","compact"]),resourceKey:Or.optional(),pageSize:ce.number().int().min(1).max(50),showSources:ce.boolean(),allowPurchase:ce.boolean(),outputs:ce.object({billing_adjustment:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((e,t)=>{(e.outputs?.billing_authorization||e.outputs?.billing_adjustment)&&e.source!=="billing_controls"&&t.addIssue({code:"custom",message:"Payment authorization routes belong to the billing controls component."}),e.resourceKey&&!["credit_balance","credit_transactions"].includes(e.source)&&t.addIssue({code:"custom",message:"\u8FD9\u4E2A\u6570\u636E\u6E90\u4E0D\u80FD\u7ED1\u5B9A\u79EF\u5206\u8D44\u6E90\u3002"}),e.showSources&&e.source!=="credit_balance"&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u4F59\u989D\u53EF\u4EE5\u5C55\u5F00\u6765\u6E90\u3002"}),e.allowPurchase&&!["credit_packs","customer_plans","membership"].includes(e.source)&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u5305\u3001\u5957\u9910\u4E0E\u4F1A\u5458\u7EC4\u4EF6\u53EF\u4EE5\u542F\u7528\u4EA4\u6613\u3002"})}),Rt=ce.string().max(2e3),$p=ce.object({id:ce.string().max(100),label:Rt,detail:ce.array(Rt).max(12),value:Rt.optional(),status:Rt.optional(),facts:ce.array(ce.object({label:Rt,value:Rt}).strict()).max(1e3),purchaseId:ce.uuid().optional(),invoiceUrl:ce.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:ce.array(ce.strictObject({action:ce.literal("invoice_open"),label:Rt})).max(1).optional(),membershipActions:ce.array(ce.object({value:ce.string().max(100),label:Rt}).strict()).max(3).optional()}).strict(),bb=ce.object({key:Or,name:Rt,spendable:Rt,reserved:Rt,available:Rt,expiry:Rt.nullable(),sources:ce.array($p).max(50),sourceCount:ce.number().int().nonnegative(),sourcePage:ce.number().int().positive(),hasNextSources:ce.boolean(),hasPreviousSources:ce.boolean()}).strict(),xb=ce.object({source:Lp,status:ce.enum(["idle","loading","ready","error"]),stale:ce.boolean(),preview:ce.boolean(),errorCode:ce.string().max(80).optional(),errorMessage:Rt.optional(),resources:ce.array(bb).max(500),rows:ce.array($p).max(50),hasNext:ce.boolean(),hasPrevious:ce.boolean(),page:ce.number().int().positive(),filter:ce.string().max(40),updatedAt:ce.iso.datetime().optional(),buyingId:ce.uuid().optional(),membershipBusy:ce.boolean().optional(),billingBusy:ce.boolean().optional(),membershipReview:ce.object({title:Rt,note:Rt,facts:ce.array(ce.object({label:Rt,value:Rt}).strict()).max(100)}).strict().optional(),membershipResult:Rt.optional()}).strict(),Gp=ce.object({nodes:ce.record(ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),xb)}).strict(),rC=ce.object({nodeId:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:ce.enum(["refresh","next","previous","filter","buy_pack","billing_portal","billing_authorization","billing_adjustment","invoice_open","membership_preview","membership_confirm","membership_dismiss","sources_next","sources_previous"]),value:ce.string().max(100).optional()}).strict();import{z as K}from"zod";var St={state:32,enumValues:64,derived:96,bindings:256,controls:64,timers:4,effects:8,depth:12,expressionNodes:2e3},Hp=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]),Nt=K.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/).refine(e=>!Hp.has(e),"Reserved UI identifier"),yc=K.union([K.string().max(2e3),K.number().finite(),K.boolean(),K.null()]),Sb=K.discriminatedUnion("type",[K.strictObject({type:K.literal("enum"),values:K.array(yc).min(1).max(St.enumValues),default:yc}),K.strictObject({type:K.literal("number"),min:K.number().finite(),max:K.number().finite(),step:K.number().finite().positive(),default:K.number().finite()}),K.strictObject({type:K.literal("text"),maxLength:K.number().int().min(0).max(2e3),default:K.string().max(2e3).nullable()}),K.strictObject({type:K.literal("boolean"),default:K.boolean()})]);function bc(e,t){if(e.type==="enum")return e.values.some(r=>r===t);if(e.type==="boolean")return typeof t=="boolean";if(e.type==="text")return t===null||typeof t=="string"&&t.length<=e.maxLength;if(typeof t!="number"||!Number.isFinite(t)||t<e.min||t>e.max)return!1;let n=(t-e.min)/e.step;return Number.isFinite(n)&&Math.abs(n-Math.round(n))<=Math.min(1e-7,Math.max(1,Math.abs(n))*Number.EPSILON*8)}var Ib=Sb.superRefine((e,t)=>{e.type==="enum"&&new Set(e.values).size!==e.values.length&&t.addIssue({code:"custom",path:["values"],message:"UI enum values must be unique"}),e.type==="number"&&e.min>e.max&&t.addIssue({code:"custom",path:["max"],message:"UI number range is reversed"}),bc(e,e.default)||t.addIssue({code:"custom",path:["default"],message:"UI default must match its state definition"})}),vb=["add","sub","mul","div","min","max","round","floor","eq","ne","gt","gte","lt","lte","and","or","not","if","concat","number","parse_number","money","lookup","now","duration"];function wb(e,t){return e==="now"?t===0:e==="concat"?!0:e==="lookup"?t>=4&&t%2===0:e==="if"?t===3:["sub","div","eq","ne","gt","gte","lt","lte"].includes(e)?t===2:["round","floor","not","number","parse_number","money","duration"].includes(e)?t===1:t>=1}var jr=K.lazy(()=>K.union([yc,K.strictObject({ref:Nt}),K.strictObject({op:K.enum(vb),args:K.array(jr).max(St.expressionNodes)}).superRefine((e,t)=>{wb(e.op,e.args.length)||t.addIssue({code:"custom",path:["args"],message:"Invalid UI expression arity"})})]));function On(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function kr(e,t,n){if(!e||typeof e!="object")return!0;if(!On(e))return t.addIssue({code:"custom",path:n,message:"UI objects must be plain data"}),!1;for(let r of Object.keys(e)){if(Hp.has(r))return t.addIssue({code:"custom",path:[...n,r],message:"Reserved UI object key"}),!1;let i=Object.getOwnPropertyDescriptor(e,r);if(i&&!Object.hasOwn(i,"value"))return t.addIssue({code:"custom",path:[...n,r],message:"UI objects cannot contain accessors"}),!1}return!0}function di(e,t,n,r){let i=[{value:e,depth:1,path:n}];for(;i.length;){let a=i.pop();if(++r.nodes>St.expressionNodes||a.depth>St.depth){t.addIssue({code:"custom",path:a.path,message:"UI expression budget exceeded"});return}if(!kr(a.value,t,a.path))return;if(On(a.value)&&Array.isArray(a.value.args)){if(a.value.args.length>St.expressionNodes){t.addIssue({code:"custom",path:[...a.path,"args"],message:"UI expression budget exceeded"});return}for(let o=a.value.args.length-1;o>=0;o--)i.push({value:a.value.args[o],depth:a.depth+1,path:[...a.path,"args",o]})}}}var aC=K.unknown().superRefine((e,t)=>{di(e,t,[],{nodes:0})}).pipe(jr),Ac=K.record(Nt,jr).refine(e=>Object.keys(e).length>0&&Object.keys(e).length<=St.state,"UI assignments need 1\u201332 state keys"),Ob=K.strictObject({target:Nt,property:K.enum(["text","visible","disabled","checked","value","class","aria-label","aria-selected","aria-checked","aria-valuetext","tabindex"]),expression:jr,className:Nt.optional()}).superRefine((e,t)=>{e.property==="class"!=(e.className!==void 0)&&t.addIssue({code:"custom",path:["className"],message:"Only class bindings require a safe className"})}),Pb=K.discriminatedUnion("type",[K.strictObject({type:K.literal("scroll_latch"),target:Nt,state:Nt}),K.strictObject({type:K.literal("input"),target:Nt,state:Nt,set:Ac.optional()}),K.strictObject({type:K.literal("action"),target:Nt,set:Ac}),K.strictObject({type:K.literal("carousel"),target:Nt,state:Nt,initialIndex:K.number().int().nonnegative().optional(),maxWidth:K.number().int().min(1).max(1e4).optional(),previousTarget:Nt.optional(),nextTarget:Nt.optional(),inactiveTargets:K.array(Nt).max(20).optional(),inactiveMaxWidth:K.number().int().min(1).max(1e4).optional()})]),Cb=K.strictObject({afterMs:K.number().int().min(0).max(6e4),set:Ac}),_b=K.strictObject({type:K.literal("mosaic_waves"),target:Nt,color:K.string().regex(/^#[0-9a-fA-F]{6}$/),hotColor:K.string().regex(/^#[0-9a-fA-F]{6}$/),enabled:jr.optional(),speed:K.number().min(0).max(4).optional(),pitch:K.number().min(.05).max(4).optional(),fill:K.number().min(.05).max(1).optional(),feather:K.number().min(0).max(1).optional(),warp:K.number().min(0).max(4).optional(),warpScale:K.number().min(0).max(32).optional(),detailScale:K.number().min(0).max(32).optional(),waveScale:K.number().min(0).max(32).optional(),falloff:K.number().min(.1).max(32).optional(),brightness:K.number().min(0).max(32).optional(),ambient:K.number().min(0).max(1).optional(),gamma:K.number().min(.05).max(8).optional(),vignette:K.number().min(0).max(1).optional(),opacity:K.number().min(0).max(1).optional()}),Eb=K.strictObject({type:K.literal("number_counter"),target:Nt,value:jr,prefix:K.string().max(20).optional(),format:K.enum(["number","short"]).optional()}),Rb=K.strictObject({state:K.record(Nt,Ib).refine(e=>Object.keys(e).length<=St.state,"Too many UI state keys").optional(),derived:K.record(Nt,jr).refine(e=>Object.keys(e).length<=St.derived,"Too many UI derived keys").optional(),bindings:K.array(Ob).max(St.bindings).optional(),controls:K.array(Pb).max(St.controls).optional(),timers:K.array(Cb).max(St.timers).optional(),effects:K.array(K.discriminatedUnion("type",[_b,Eb])).max(St.effects).optional(),clock:K.boolean().optional()});function kb(e,t){if(!kr(e,t,[])||!On(e))return;for(let[r,i]of[["state",St.state],["derived",St.derived]]){let a=e[r];if(!kr(a,t,[r]))return;if(On(a)&&Object.keys(a).length>i){t.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}}for(let[r,i]of[["bindings",St.bindings],["controls",St.controls],["timers",St.timers],["effects",St.effects]])if(Array.isArray(e[r])&&e[r].length>i){t.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}if(Array.isArray(e.effects)){for(let[r,i]of e.effects.entries())if(!kr(i,t,["effects",r]))return}if(On(e.state))for(let[r,i]of Object.entries(e.state)){if(!kr(i,t,["state",r]))return;if(On(i)&&Array.isArray(i.values)&&i.values.length>St.enumValues){t.addIssue({code:"custom",path:["state",r,"values"],message:"Too many UI enum values"});return}}let n={nodes:0};if(On(e.derived))for(let[r,i]of Object.entries(e.derived))di(i,t,["derived",r],n);for(let r of["bindings","controls","timers"]){let i=e[r];if(Array.isArray(i)){for(let[a,o]of i.entries())if(!(!kr(o,t,[r,a])||!On(o))){if(r==="bindings")di(o.expression,t,[r,a,"expression"],n);else if(kr(o.set,t,[r,a,"set"])&&On(o.set)){if(Object.keys(o.set).length>St.state){t.addIssue({code:"custom",path:[r,a,"set"],message:"Too many UI assignments"});return}for(let[s,c]of Object.entries(o.set))di(c,t,[r,a,"set",s],n)}if(n.nodes>St.expressionNodes)return}}}if(Array.isArray(e.effects))for(let[r,i]of e.effects.entries())On(i)&&i.type==="number_counter"?di(i.value,t,["effects",r,"value"],n):On(i)&&i.enabled!==void 0&&di(i.enabled,t,["effects",r,"enabled"],n)}function Kp(e){let t=[],n=[e];for(;n.length;){let r=n.pop();!r||typeof r!="object"||("ref"in r?t.push(r.ref):n.push(...r.args))}return t}var Qp=K.unknown().superRefine(kb).pipe(Rb).superRefine((e,t)=>{let n=e.state??{},r=e.derived??{},i=new Set([...Object.keys(n),...Object.keys(r)]),a=(g,d)=>{for(let h of Kp(g))i.has(h)||t.addIssue({code:"custom",path:d,message:`Unknown UI reference: ${h}`})};for(let[g,d]of Object.entries(e.derived??{}))Object.hasOwn(n,g)&&t.addIssue({code:"custom",path:["derived",g],message:"UI state and derived identifiers must be distinct"}),a(d,["derived",g]);let o=new Set,s=new Set,c=g=>{if(o.has(g))return!1;if(s.has(g))return!0;o.add(g);for(let d of Kp(r[g]))if(Object.hasOwn(r,d)&&!c(d))return!1;return o.delete(g),s.add(g),!0};for(let g of Object.keys(r))if(!c(g)){t.addIssue({code:"custom",path:["derived",g],message:"Cyclic UI derived references"});break}for(let[g,d]of(e.bindings??[]).entries())a(d.expression,["bindings",g,"expression"]);let u=new Set;for(let[g,d]of(e.effects??[]).entries())u.has(d.target)&&t.addIssue({code:"custom",path:["effects",g,"target"],message:"Effect targets must be unique"}),u.add(d.target),d.type==="number_counter"?(a(d.value,["effects",g,"value"]),typeof d.value=="number"&&Math.abs(d.value)>1e12&&t.addIssue({code:"custom",path:["effects",g,"value"],message:"Counter values must be within the display bound"})):d.enabled!==void 0&&a(d.enabled,["effects",g,"enabled"]);let l=(g,d)=>{for(let[h,R]of Object.entries(g))Object.hasOwn(n,h)||t.addIssue({code:"custom",path:[...d,h],message:"UI assignments can only update declared state"}),a(R,[...d,h])},m=new Set,f=new Set;for(let[g,d]of(e.controls??[]).entries()){if(d.type==="carousel"&&d.inactiveMaxWidth!==void 0&&d.inactiveTargets===void 0&&t.addIssue({code:"custom",path:["controls",g,"inactiveMaxWidth"],message:"Inactive width requires inactive article targets"}),d.type==="carousel")for(let h of d.inactiveTargets??[])(h===d.target||f.has(h))&&t.addIssue({code:"custom",path:["controls",g,"inactiveTargets"],message:"Inactive article targets must have one carousel owner"}),f.add(h);if(d.type==="carousel")for(let h of["previousTarget","nextTarget"]){let R=d[h];R!==void 0&&((R===d.target||m.has(R)||(e.controls??[]).some(y=>y.target===R))&&t.addIssue({code:"custom",path:["controls",g,h],message:"Carousel navigation needs a distinct, exclusive button target"}),m.add(R))}if(d.type!=="action"){let h=Object.hasOwn(n,d.state)?n[d.state]:void 0;(!h||d.type==="input"&&h.type==="enum"&&h.values.some(R=>typeof R!="string"))&&t.addIssue({code:"custom",path:["controls",g,"state"],message:"Control needs a supported declared UI state"}),d.type==="carousel"&&(h?.type!=="number"||!Number.isInteger(h.min)||h.min<0||!Number.isInteger(h.max)||h.step!==1||d.initialIndex!==void 0&&!bc(h,d.initialIndex))&&t.addIssue({code:"custom",path:["controls",g],message:"Carousel needs bounded nonnegative integer index state"}),d.type==="scroll_latch"&&h?.type!=="boolean"&&t.addIssue({code:"custom",path:["controls",g,"state"],message:"Scroll latches require boolean UI state"})}(d.type==="input"||d.type==="action")&&d.set&&l(d.set,["controls",g,"set"])}for(let[g,d]of(e.timers??[]).entries())l(d.set,["timers",g,"set"])});import{z as ot}from"zod";var jb=ot.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),xa=ot.discriminatedUnion("type",[ot.object({type:ot.literal("fixed"),productVersionId:ot.string().min(1).max(200)}).strict(),ot.object({type:ot.literal("picker"),pickerId:jb,allowedProductVersionIds:ot.array(ot.string().min(1).max(200)).min(1).max(20)}).strict().refine(e=>new Set(e.allowedProductVersionIds).size===e.allowedProductVersionIds.length,"Product choices must be unique")]),Tb=ot.strictObject({min:ot.number().finite().min(1).max(1800),max:ot.number().finite().min(1).max(1800),viewport:ot.number().finite().min(1).max(100)}).refine(e=>e.min<=e.max,"Desktop width range is reversed"),Jp={desktopWidth:Tb.optional(),mobile:ot.enum(["sheet","fullscreen"]).optional(),backdrop:ot.enum(["none","scrim","dim","strong-dim","blur"]).optional()},Pn=ot.discriminatedUnion("type",[ot.strictObject({type:ot.literal("modal"),size:ot.enum(["sm","md","lg"]),...Jp}),ot.strictObject({type:ot.literal("sheet"),size:ot.enum(["sm","md","lg"]),...Jp}),ot.strictObject({type:ot.literal("fullscreen")}),ot.strictObject({type:ot.literal("inline")})]);var Db=4,_n={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:32768,documentBytes:2e5},ao=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ue=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Fb=I.enum(["none","xs","sm","md","lg","xl"]),Mb=I.enum(["none","sm","md","lg","full"]),xc=I.string().regex(/^#[0-9a-fA-F]{6}$/),Ic=I.string().max(2048).refine(e=>{try{let t=new URL(e);return t.protocol==="https:"&&t.hostname.length>0}catch{return!1}},"\u53EA\u652F\u6301 https \u94FE\u63A5"),Sc=I.union([Ic,I.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),I.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),I.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Zp=I.object({primary:xc,background:xc,text:xc,radius:Mb,font:I.enum(["system","serif","rounded","mono"]),fontAssets:I.object({family:I.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/),faces:I.array(I.object({url:Ic,weight:I.number().int().min(100).max(900).multipleOf(100),family:I.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/).optional()}).strict()).min(1).max(4)}).strict().optional()}).strict(),so=I.union([I.enum(["primary","text","muted","background","surface"]),I.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),Me=(e,t)=>I.number().int().min(e).max(t),Wp=I.union([I.enum(["fit","fill"]),Me(1,1200)]),qb=I.object({top:Me(0,200),right:Me(0,200),bottom:Me(0,200),left:Me(0,200)}).strict(),Ub=I.object({top:Me(-100,200),right:Me(-100,200),bottom:Me(-100,200),left:Me(-100,200)}).strict(),Yp=I.object({x:Me(0,100),y:Me(0,100)}).strict(),Bb=I.discriminatedUnion("type",[I.object({type:I.literal("color"),color:so}).strict(),I.object({type:I.literal("linear"),angle:Me(0,360),stops:I.array(I.object({color:so,at:Me(0,100)}).strict()).min(2).max(4)}).strict(),I.object({type:I.literal("image"),src:Sc,fit:I.enum(["cover","contain"]),position:Yp.optional()}).strict()]),Vb=I.discriminatedUnion("type",[I.object({type:I.literal("rect"),radius:I.union([Me(0,200),I.object({topLeft:Me(0,200),topRight:Me(0,200),bottomRight:Me(0,200),bottomLeft:Me(0,200)}).strict()])}).strict(),I.object({type:I.literal("pill")}).strict()]),Lb=I.object({width:Me(0,12),color:so,style:I.enum(["solid","dashed"])}).strict(),zb=I.object({x:Me(-40,40),y:Me(-40,40),blur:Me(0,80),spread:Me(-20,40),color:so}).strict(),$b=I.object({font:I.enum(["system","serif","rounded","mono"]),size:Me(8,96),weight:I.number().int().min(100).max(900).multipleOf(100),lineHeight:I.number().min(.8).max(3),letterSpacing:I.number().min(-5).max(20),color:so,align:I.enum(["start","center","end"]),italic:I.boolean(),decoration:I.enum(["none","underline","line-through"]),transform:I.enum(["none","uppercase"])}).strict().partial(),Tr=I.object({width:Wp,height:Wp,padding:qb,margin:Ub,gap:Me(0,120),grow:I.union([I.boolean(),I.number().min(0).max(12)]),background:Bb,opacity:I.number().min(0).max(1),clipContent:I.boolean(),shape:Vb,border:Lb,shadow:zb,text:$b}).strict().partial(),tn={id:ao,name:I.string().trim().min(1).max(60).optional(),hidden:I.boolean().optional(),style:Tr.optional(),fallback:Ue.optional()},Gb=I.object({...tn,type:I.literal("text"),productField:I.enum(["name","price","trial","period"]).optional(),feature:I.object({id:I.uuid(),field:I.enum(["name","allowance"])}).strict().optional(),text:Ue,variant:I.enum(["title","heading","body","caption"])}).strict(),Kb=I.object({...tn,type:I.literal("image"),src:Sc,localizedSrc:I.record(In,Sc).optional(),alt:Ue,aspect:I.enum(["auto","1:1","4:3","16:9","3:1"]),fit:I.enum(["cover","contain"]),position:Yp.optional()}).strict(),Hb=I.object({...tn,type:I.literal("button"),label:Ue,variant:I.enum(["primary","secondary","link"]),action:Ue,purpose:I.enum(["purchase","navigation","close"]).optional(),bind:ya.optional()}).strict(),Qb=I.object({...tn,type:I.literal("divider")}).strict(),Jb=I.object({...tn,type:I.literal("customer_data"),title:Ue,data:zp}).strict(),Zb=I.object({...tn,type:I.literal("spacer"),size:Fb}).strict(),Wb=I.object({...tn,type:I.literal("custom_html"),html:I.record(In,I.string().max(_n.customHtml)),css:I.string().max(_n.customCss),ui:Qp.optional()}).strict(),Yb=I.object({...tn,type:I.literal("price"),fallback:Ue,parts:I.object({current:Tr.optional(),original:Tr.optional(),period:Tr.optional()}).strict().optional()}).strict(),Xb=I.object({...tn,type:I.literal("coupon_code"),label:Ue,fallback:Ue}).strict(),ex=I.object({...tn,type:I.literal("countdown"),source:I.enum(["offer.ends_at","offer.expires_at","fixed"]),at:I.iso.datetime().optional(),granularity:I.enum(["day","hour","minute","second"]),expired:Ue,fallback:Ue}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),tx=I.object({...tn,type:I.literal("plan_picker"),label:Ue,fallback:Ue,planIds:I.array(I.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:I.string().min(1).max(200).optional(),grouping:Aa.safeExtend({monthLabel:Ue,yearLabel:Ue,unavailableLabel:Ue}).optional(),states:I.object({selected:Tr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!ba(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),nx=I.object({...tn,type:I.literal("quantity_picker"),bind:ya.optional(),label:Ue,fallback:Ue,internalFeatureId:I.uuid(),minimumQuantity:Me(0,1e4),maximumQuantity:Me(0,1e4),defaultQuantity:Me(0,1e4),step:Me(1,1e4)}).strict().refine(e=>e.minimumQuantity<=e.defaultQuantity&&e.defaultQuantity<=e.maximumQuantity&&(e.defaultQuantity-e.minimumQuantity)%e.step===0,"Quantity controls require a Product binding and valid bounds"),rx=I.discriminatedUnion("type",[I.object({type:I.literal("input"),label:Ue,keyboard:I.enum(["text","email","tel","url"]),maxLength:Me(1,500)}).strict(),I.object({type:I.literal("multiselect"),label:Ue,min:Me(0,50),max:Me(1,50)}).strict(),I.object({type:I.literal("select"),label:Ue,defaultIndex:Me(0,49),purpose:I.enum(["option","product","tier"]).optional(),pickerId:ao.optional(),selectedStyle:Tr.optional()}).strict(),I.object({type:I.literal("tabs"),label:Ue,defaultIndex:Me(0,49),purpose:I.literal("tier").optional()}).strict(),I.object({type:I.literal("toggle"),label:Ue,defaultEnabled:I.boolean()}).strict(),I.object({type:I.literal("carousel"),label:Ue}).strict()]),Cn={...tn,type:I.literal("stack"),direction:I.enum(["vertical","horizontal","overlay"]),align:I.enum(["start","center","end","stretch"]),justify:I.enum(["start","center","end","between"]),productSlot:I.object({index:Me(0,19),period:I.enum(["month","year"]).optional(),requireBinding:I.boolean().optional()}).strict().optional(),interaction:rx.optional(),states:I.object({selected:Tr.optional()}).strict().optional(),purpose:I.literal("benefits").optional(),purchaseAction:Ue.optional(),buttonVariant:I.enum(["primary","secondary","link"]).optional(),bind:ya.optional()},Xp=I.lazy(()=>I.object({...tn,type:Cn.type,direction:Cn.direction,align:Cn.align,justify:Cn.justify,children:I.array(ix).max(_n.children),productSlot:Cn.productSlot,interaction:Cn.interaction,states:Cn.states,purpose:Cn.purpose,purchaseAction:Cn.purchaseAction,buttonVariant:Cn.buttonVariant,bind:Cn.bind}).strict()),ix=I.lazy(()=>I.union([Xp,Gb,Kb,Hb,Qb,Zb,Wb,Yb,Xb,ex,tx,nx,Jb])),ox=I.union([I.string().max(500),I.number().finite(),I.boolean(),I.null()]),oo={id:Ue,event:Ue,properties:I.record(Ue,ox).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},ax=I.discriminatedUnion("type",[I.object({...oo,type:I.literal("navigate"),close:I.literal(!1),pageId:ao}).strict(),I.object({...oo,type:I.literal("event"),close:I.boolean()}).strict(),I.object({...oo,type:I.literal("close"),close:I.literal(!0)}).strict(),I.object({...oo,type:I.literal("open_url"),close:I.boolean(),url:Ic}).strict(),I.object({...oo,type:I.literal("claim_offer"),close:I.boolean(),couponId:I.uuid()}).strict()]),sx=I.object({defaultLocale:In,locales:I.record(In,I.record(Ue,I.string().max(_n.stringLength)))}).strict(),cx=I.enum(["popup","paywall","onboarding","page","banner"]);var ux=I.object({kind:I.literal("screen"),schemaVersion:I.literal(Db),name:I.string().trim().min(1).max(80),surface:cx,initialPageId:ao.optional(),presentation:Pn,theme:Zp,pages:I.array(I.object({id:ao,name:I.string().trim().min(1).max(60),root:Xp,theme:Zp.optional(),editorPosition:I.object({x:I.number().finite().min(-1e5).max(1e5),y:I.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(_n.pages),strings:sx,actions:I.array(ax).max(_n.actions)}).strict();function Gt(e,t){for(let n of e.pages)Zn(n.root,t)}var un=ux.superRefine((e,t)=>{let n=_n;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(l=>l.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let l of e.actions)l.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(m=>m.id===l.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>n.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${n.pages} \u4E2A`}),e.actions.length>n.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${n.actions} \u4E2A`});let r=l=>t.addIssue({code:"custom",message:l}),i=Object.keys(e.strings.locales);i.includes(e.strings.defaultLocale)||r("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),i.length>_n.locales&&r(`\u6700\u591A ${_n.locales} \u79CD\u8BED\u8A00`);let a=new Set;for(let l of e.actions)a.has(l.id)&&r(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${l.id}`),a.add(l.id);let o=new Set;for(let l of e.pages)["next","back"].includes(l.id)&&r(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${l.id}`),o.has(l.id)&&r(`\u9875\u9762 id \u91CD\u590D\uFF1A${l.id}`),o.add(l.id);let s=new Set,c=0,u=!1;Gt(e,(l,m)=>{if(c++,m>_n.depth&&(u=!0),s.has(l.id)&&r(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${l.id}`),s.add(l.id),l.type==="button"&&!a.has(l.action)&&r(`\u6309\u94AE ${l.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${l.action}`),l.type==="custom_html")for(let f of Object.keys(l.html))i.includes(f)||r(`\u81EA\u5B9A\u4E49 HTML ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${f}`);if(l.type==="image")for(let f of Object.keys(l.localizedSrc??{}))i.includes(f)||r(`\u56FE\u7247 ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${f}`)}),c>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),u&&r(`\u5C42\u7EA7\u6700\u591A ${_n.depth} \u5C42`)});function Zn(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)Zn(i,t,n+1,e)}function Sa(e){let t=[],n=new Set;return Gt(e,r=>{let i=(a,o,s)=>{n.has(a)||(n.add(a),t.push({key:a,nodeId:r.id,nodeType:r.type,field:o,required:s}))};r.type==="stack"&&r.interaction&&i(r.interaction.label,"label",!0),r.fallback&&i(r.fallback,"text",!0),r.type==="text"&&i(r.text,"text",!0),r.type==="customer_data"&&i(r.title,"title",!0),(r.type==="plan_picker"||r.type==="quantity_picker"||r.type==="coupon_code")&&i(r.label,"label",!0),r.type==="plan_picker"&&r.grouping&&(i(r.grouping.monthLabel,"label",!0),i(r.grouping.yearLabel,"label",!0),i(r.grouping.unavailableLabel,"text",!0)),r.type==="countdown"&&i(r.expired,"text",!0),r.type==="button"&&i(r.label,"label",!0),r.type==="image"&&(i(`image:${r.id}`,"src",!1),i(r.alt,"alt",!1)),r.type==="custom_html"&&i(`html:${r.id}`,"html",!0)}),t}function lx(e,t,n){if(t.field==="html"){let r;return Gt(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=co(e,t.nodeId);return r?.type==="image"?r.localizedSrc?.[n]??(n===e.strings.defaultLocale?r.src:void 0):void 0}return e.strings.locales[n]?.[t.key]}function or(e){let t=Sa(e).filter(r=>r.required);return Object.keys(e.strings.locales).sort((r,i)=>r===e.strings.defaultLocale?-1:i===e.strings.defaultLocale?1:0).map(r=>{let i=t.filter(a=>!lx(e,a,r)?.trim()).map(a=>a.key);return{locale:r,total:t.length,filled:t.length-i.length,missing:i,complete:i.length===0}})}function dx(e,t){let n=null;return Zn(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function co(e,t){for(let n of e.pages){let r=dx(n.root,t);if(r)return r}return null}import{z as Bt}from"zod";var It=Bt.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/).refine(e=>e.split(".").every(t=>t.length>0&&!["__proto__","constructor","prototype"].includes(t)),"Reserved or empty variable path"),vc=Bt.strictObject({type:Bt.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:Bt.boolean(),enum:Bt.array(Bt.string().max(255)).min(1).max(100).optional()}),pi=vc.extend({type:Bt.enum([...vc.shape.type.options,"array"]),items:vc.optional()}).superRefine((e,t)=>{(e.type==="array"!=!!e.items||e.enum&&e.type!=="string"||e.items?.enum&&e.items.type!=="string")&&t.addIssue({code:"custom",message:"Array requires items; only strings support enum"})}),mi=pi.safeExtend({source:Bt.discriminatedUnion("type",[Bt.strictObject({type:Bt.literal("input")}),Bt.strictObject({type:Bt.literal("node")}),Bt.strictObject({type:Bt.enum(["parameter","attribute"]),key:It})])}),SC=Bt.record(It,mi),wc=Bt.record(It,It).refine(e=>Object.keys(e).length<=20);function hn(e,t){return e?t===null?e.nullable:e.enum&&(typeof t!="string"||!e.enum.includes(t))?!1:e.type==="array"?Array.isArray(t)&&t.length<=100&&!!e.items&&t.every(n=>hn(e.items,n)):["offering_version","reward","paywall_version"].includes(e.type)?typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===2&&t.type===e.type&&Bt.uuid().safeParse(t.id).success:e.type==="json"||(e.type==="strings"?Array.isArray(t)&&t.every(n=>typeof n=="string"):typeof t===e.type):!1}function Oc(e,t){return e.nullable&&!t.nullable?!1:t.type==="json"?!0:e.type!==t.type||t.enum&&(!e.enum||e.enum.some(n=>!t.enum.includes(n)))?!1:e.type!=="array"||!!e.items&&!!t.items&&Oc(e.items,t.items)}function Ia(e,t){let n={};for(let[r,i]of Object.entries(e)){let a=i.source,o=a.type==="input"?t.answers:a.type==="node"?t.results??{}:a.type==="parameter"?t.parameters:t.attributes,s=a.type==="parameter"||a.type==="attribute"?a.key:r,c=Object.hasOwn(o,s),u=o[s];if(a.type==="attribute"&&s.includes(".")&&(!c||s.startsWith("merchandise."))){u=o,c=!0;for(let l of s.split(".")){if(!u||typeof u!="object"||!Object.hasOwn(u,l)||Array.isArray(u)&&(!/^(0|[1-9]\d*)$/.test(l)||Number(l)>=u.length)){c=!1;break}u=u[l]}}if(!(!c||u===void 0)){if(!hn(i,u))throw new Error(`Invalid variable value: ${r}`);n[r]=u}}return n}function fi(e,t){let n={};for(let[r,i]of Object.entries(e.writes??{})){if(!Object.hasOwn(t,r))throw new Error(`Node output is missing: ${r}`);if(Object.hasOwn(n,i))throw new Error("Node outputs cannot overwrite one another");n[i]=t[r]}return n}function em(e,t,n){let r=new Set(Object.values(t.writes??{}));for(let[i,a]of Object.entries(n))if(!r.has(i)||e[i]?.source.type!=="node"||!hn(e[i],a))throw new Error(`Invalid node variable write: ${i}`);if(r.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}import{z as Nr}from"zod";var En=Nr.string().min(1).max(255).regex(/^[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+){0,9}$/).refine(e=>e.split(".").every(t=>!["__proto__","constructor","prototype"].includes(t)),"Reserved value path"),Fn=Nr.discriminatedUnion("source",[Nr.strictObject({source:Nr.literal("literal"),value:ve}),Nr.strictObject({source:Nr.literal("variable"),key:Nr.string().min(1).max(255),path:En.optional()})]);function tm(e,t){if(!t)return e;for(let n of En.parse(t).split(".")){if(Array.isArray(e)){if(!/^(0|[1-9]\d*)$/.test(n)||Number(n)>=e.length)return;e=e[Number(n)];continue}if(e===null||typeof e!="object"||!Object.hasOwn(e,n))return;e=Reflect.get(e,n)}return e}function Pc(e,t){if(e.source==="literal")return structuredClone(e.value);let n=Ia(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(ve.parse(tm(n[e.key],e.path)))}function Cc(e,t){let n=[...t].sort((i,a)=>a.length-i.length).find(i=>e===i||e.startsWith(i+"."));if(!n)return null;let r=e===n?void 0:e.slice(n.length+1);return r&&!En.safeParse(r).success?null:{key:n,path:r}}function _c(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Gt(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(Up))]}function va(e){return _c(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function ln(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("A JSON value is required");let n=new TextEncoder().encode(t).length,r=!1;for(let i=0;i<t.length;i++){let a=t.charAt(i);if(r)a==="\\"?i++:a==='"'&&(r=!1);else if(a==='"')r=!0;else if(a===":"||a===",")n++;else if(a==="-"||a>="0"&&a<="9"){let o=i;for(;i+1<t.length&&/[0-9.eE+-]/.test(t.charAt(i+1));)i++;let s=t.slice(o,i+1);if(!/[eE]/.test(s))continue;let[c="",u]=s.split(/[eE]/),l=c.replace(/^-/,""),m=l.replace(".","").length,f=(l.includes(".")?l.indexOf("."):m)+Number(u),g=f<=0?2-f+m:f>=m?f:m+1;n+=g+(c.startsWith("-")?1:0)-s.length}}return n}var ar=Ce.enum(["page","popup","banner"]),px=3e5,nm=Ce.strictObject({type:Ce.enum(["string","number","boolean","strings","json"]),nullable:Ce.boolean()}),mx=Ce.strictObject({inputs:Ce.record(Ue,nm.extend({required:Ce.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:Ce.record(Ue,nm).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),fx=Ce.strictObject({kind:ar,schemaVersion:Ce.literal(1),name:Ce.string().trim().min(1).max(80),screen:un,contract:mx}),wa=fx.superRefine((e,t)=>{let n=(i,a)=>t.addIssue({code:"custom",message:i,path:a});e.screen.surface!==e.kind&&n("Content surface must match its domain",["screen","surface"]),e.screen.name!==e.name&&n("Content has one editable name",["screen","name"]),e.kind==="banner"&&e.screen.presentation.type!=="inline"&&n("Banner requires an inline container",["screen","presentation"]),e.kind!=="banner"&&e.screen.presentation.type==="inline"&&n("Inline presentation belongs to Banner",["screen","presentation"]),e.screen.actions.some(i=>i.type!=="event"&&i.type!=="navigate")&&n("Content actions must emit host intents or navigate locally",["screen","actions"]);let r=new Set(e.screen.actions.filter(i=>i.type==="event").map(i=>i.id));(Object.keys(e.contract.outputs).some(i=>!r.has(i))||[...r].some(i=>!Object.hasOwn(e.contract.outputs,i)))&&n("Every event needs exactly one output declaration",["contract","outputs"]),ln(e)>px&&n("Content document exceeds its byte budget",[])});function gx(e,t){if(e===null)return t.nullable;switch(t.type){case"json":return!0;case"string":return typeof e=="string";case"number":return typeof e=="number"&&Number.isFinite(e);case"boolean":return typeof e=="boolean";case"strings":return Array.isArray(e)&&e.every(n=>typeof n=="string")}}var hx=wa.superRefine((e,t)=>{for(let n of va(e.screen))Object.keys(e.contract.inputs).some(r=>n===r||n.startsWith(r+"."))||t.addIssue({code:"custom",path:["contract","inputs"],message:"Declare every reusable input read"});for(let n of e.screen.actions){if(n.type!=="event")continue;let r=e.contract.outputs[n.id],i=Object.hasOwn(n.properties,"value")?n.properties.value:n.properties;r&&!gx(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}or(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),rm=Ce.strictObject({id:Ce.uuid(),kind:ar,projectId:Ce.uuid(),environmentId:Ce.uuid(),name:Ce.string(),revision:Ce.number().int().nonnegative(),status:Ce.enum(["draft","published","archived"]),publishedVersionId:Ce.uuid().nullable(),createdAt:Ce.iso.datetime({offset:!0}),updatedAt:Ce.iso.datetime({offset:!0})}),MC=rm.extend({draft:wa}),qC=Ce.strictObject({rows:Ce.array(rm).max(200),nextCursor:Ce.uuid().nullable()}),Ec=Ce.strictObject({id:Ce.uuid(),kind:ar,resourceId:Ce.uuid(),projectId:Ce.uuid(),environmentId:Ce.uuid(),version:Ce.number().int().positive(),sourceRevision:Ce.number().int().nonnegative(),document:hx,createdAt:Ce.iso.datetime({offset:!0})}),UC=Ec.omit({document:!0}),BC=Ce.discriminatedUnion("action",[Ce.strictObject({action:Ce.literal("create"),kind:ar,id:Ce.uuid(),document:wa}),Ce.strictObject({action:Ce.literal("save"),kind:ar,id:Ce.uuid(),revision:Ce.number().int().nonnegative(),document:wa}),Ce.strictObject({action:Ce.enum(["publish","archive"]),kind:ar,id:Ce.uuid(),revision:Ce.number().int().nonnegative()})]).superRefine((e,t)=>{"document"in e&&e.document.kind!==e.kind&&t.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});import{z as im}from"zod";var gi={funnelId:im.uuid().optional(),funnelVersionId:im.uuid().optional()};import{z as Oa}from"zod";var Pa=Oa.strictObject({runId:Oa.uuid(),bindingId:Oa.uuid(),receiptId:Oa.uuid()});import{z as at}from"zod";import{z as Be}from"zod";import{z as et}from"zod";var HC=et.discriminatedUnion("action",[et.strictObject({action:et.literal("create"),couponId:et.uuid(),productBindingId:et.uuid(),storeOfferId:et.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:et.enum(["introductory","promotional"])}),et.strictObject({action:et.literal("set_enabled"),id:et.uuid(),revision:et.number().int().nonnegative(),enabled:et.boolean()})]),QC=et.array(et.strictObject({id:et.uuid(),couponId:et.uuid(),productBindingId:et.uuid(),storeOfferId:et.string().min(1).max(255).nullable(),storeOfferType:et.enum(["introductory","promotional"]),enabled:et.boolean(),revision:et.number().int().nonnegative()})).max(500),hi=et.strictObject({offerKind:et.enum(["none","introductory","promotional"]),offerId:et.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:et.number().int().min(0).max(1e8),trialDays:et.number().int().min(1).max(730).nullable()}).superRefine((e,t)=>{(e.offerKind==="none"&&(e.offerId!==null||e.discountMinor!==0||e.trialDays!==null)||e.trialDays!==null&&e.discountMinor!==0)&&t.addIssue({code:"custom",message:"Select one store purchase option with its exact terms"})}),JC=et.record(et.uuid(),hi).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var Rc=Be.object({type:Be.literal("native_purchase"),receiptId:Be.uuid(),orderId:Be.uuid(),productVersionId:Be.uuid(),provider:Be.enum(["apple","google"]),productId:Be.string().min(1).max(255),productKind:Mp,replacement:Be.strictObject({sourceOrderId:Be.uuid(),sourceProductId:Be.string().min(1).max(255),policy:Be.enum(["apple_store","google_full_price"]),sourceAccountTokens:Be.array(Be.uuid()).max(50)}).nullable(),appAccountToken:Be.uuid().optional(),obfuscatedAccountId:Be.string().min(1).max(64).optional(),obfuscatedProfileId:Be.uuid().optional(),basePlanId:Be.string().min(1).max(255).optional(),offerId:Be.string().min(1).max(255).optional(),offerKind:Be.enum(["none","introductory","promotional"]),currency:Ie,catalogAmountMinor:Be.number().int().nonnegative().max(1e8),discountMinor:Be.number().int().nonnegative().max(1e8),trialDays:Be.number().int().min(1).max(730).nullable(),seatBundle:Be.array(Be.strictObject({key:Be.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:Be.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:Be.strictObject({offerId:Be.string().min(1).max(255),keyId:Be.string().min(1).max(255),nonce:Be.uuid(),signature:Be.string().min(1).max(1024),timestamp:Be.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,t)=>{let n=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(n?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!n&&e.productKind==="membership"&&e.basePlanId===void 0||e.discountMinor>e.catalogAmountMinor||new Set(e.seatBundle.map(i=>i.key)).size!==e.seatBundle.length||e.trialDays!==null&&(e.discountMinor!==0||e.offerKind==="none")||e.offerKind==="none"&&e.discountMinor!==0||(n?!e.appAccountToken||e.obfuscatedAccountId!==void 0||e.obfuscatedProfileId!==void 0||e.basePlanId!==void 0||e.offerKind==="promotional"!=(e.applePromotionalOffer!==null)||e.offerKind==="promotional"!=(e.offerId!==void 0)||e.applePromotionalOffer!==null&&e.applePromotionalOffer.offerId!==e.offerId:e.appAccountToken!==void 0||!e.obfuscatedAccountId||!e.obfuscatedProfileId||e.applePromotionalOffer!==null||e.offerKind==="none"!=(e.offerId===void 0)))&&t.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});import{z as p}from"zod";import{z as _e}from"zod/v4";import{z as yx}from"zod/v4";var Ax=yx.registry(),{BillingInterval:om}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{BillingInterval:e}})(),{DisplaySchema:bx}=(e=>({DisplaySchema:e.object({primary_text:e.string().meta({description:"Main display text (e.g. '$10' or '100 messages')."}),secondary_text:e.string().optional().meta({description:"Secondary display text (e.g. 'per month' or 'then $0.5 per 100')."})})}))(_e),{withSpecDefault:xx}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(Ax),{COMMON:am}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:Sx}={STRIPE_PRESENTMENT_CURRENCIES:["usd","aed","afn","all","amd","ang","aoa","ars","aud","awg","azn","bam","bbd","bdt","bif","bmd","bnd","bob","brl","bsd","bwp","byn","bzd","cad","cdf","chf","clp","cny","cop","crc","cve","czk","djf","dkk","dop","dzd","egp","etb","eur","fjd","fkp","gbp","gel","gip","gmd","gnf","gtq","gyd","hkd","hnl","htg","huf","idr","ils","inr","isk","jmd","jpy","kes","kgs","khr","kmf","krw","kyd","kzt","lak","lbp","lkr","lrd","lsl","mad","mdl","mga","mkd","mmk","mnt","mop","mur","mvr","mwk","mxn","myr","mzn","nad","ngn","nio","nok","npr","nzd","pab","pen","pgk","php","pkr","pln","pyg","qar","ron","rsd","rub","rwf","sar","sbd","scr","sek","sgd","shp","sle","sos","srd","std","szl","thb","tjs","top","try","ttd","twd","tzs","uah","ugx","uyu","uzs","vnd","vuv","wst","xaf","xcd","xcg","xof","xpf","yer","zar","zmw"]},{COMMON_SET:Ix}=(e=>({COMMON_SET:new Set(e)}))(am),{hasNoDuplicateCurrencies:sm}={hasNoDuplicateCurrencies:t=>{let n=new Set;for(let{currency:r}of t){let i=r.toLowerCase();if(n.has(i))return!1;n.add(i)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:cm}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:vx}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(_e),{Infinite:wx}={Infinite:"inf"},{TierBehavior:Ox}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:um}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Px}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:Cx}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:_x}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Ex}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(_e),{ApiCreditTierSchema:lm}=(e=>({ApiCreditTierSchema:e.object({to:e.union([e.number().positive(),e.enum(["inf"])]).meta({description:"Inclusive upper usage boundary for this graduated tier. The final tier must be 'inf'."}),credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group within this tier."})})}))(_e),{VIOLATION_MESSAGES:Rx}={VIOLATION_MESSAGES:{non_final_infinity:"Only the final tier may use an 'inf' boundary.",not_increasing:"Tier boundaries must be strictly increasing.",final_not_infinity:"The final tier must use an 'inf' boundary."}},{MarkupEntrySchema:dm}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(_e),{ModelMarkupsSchema:kx}=((e,t)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),t.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(_e,dm),{InvoiceUsageEntrySchema:jx}=(e=>({InvoiceUsageEntrySchema:e.object({feature_id:e.string().meta({description:"The metered feature whose units are being converted."}),quantity:e.number().nonnegative().meta({description:"Billable units of the metered feature. Converted to the credit-system feature through its rate card."}),properties:e.record(e.string(),e.unknown()).optional().meta({description:"Event properties used to pick the rate card dimension and multipliers."})}).strict()}))(_e),{AttachDiscountSchema:pm}=(e=>({AttachDiscountSchema:e.object({reward_id:e.string().optional().meta({description:"The ID of the reward to apply as a discount."}),promotion_code:e.string().optional().meta({description:"The promotion code to apply as a discount."})}).refine(n=>n.reward_id||n.promotion_code,{message:"Either reward_id or promotion_code must be provided."}).meta({title:"AttachDiscount",description:"A discount to apply. Can be either a reward ID or a promotion code."})}))(_e),{CustomLineItemSchema:Tx}=(e=>({CustomLineItemSchema:e.object({amount:e.number().meta({description:"Amount in dollars for this line item (e.g. 10.50). Can be negative for credits."}),description:e.string().meta({description:"Description for the line item."})})}))(_e),{UnixMsTimestampSchema:Nx}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(_e),{CreateInvoicePreviewLineSchema:Dx}=(e=>({CreateInvoicePreviewLineSchema:e.object({plan_id:e.string().nullable(),feature_id:e.string().nullable(),description:e.string(),amount:e.number(),amount_after_discounts:e.number(),quantity:e.number().nullable(),prorated:e.boolean(),period_start:e.number().nullable(),period_end:e.number().nullable()})}))(_e),{ReissueInvoiceParamsSchema:mm}=(e=>({ReissueInvoiceParamsSchema:e.object({invoice_id:e.string().meta({description:"The Autumn invoice ID to void and replace.",example:"inv_2b3c4d5e6f7g8h"}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer and memo are applied to the replacement invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the replacement invoice. Defaults to the original invoice's due date; required when that date has already passed."}),update_customer_email:e.email().optional().meta({description:"Updates the customer's billing email before the replacement is issued, so Stripe sends the new invoice to this address."})})}))(_e),{InvoiceModeParamsSchema:Dr}=(e=>({InvoiceModeParamsSchema:e.object({enabled:e.boolean().meta({description:"When true, creates an invoice and sends it to the customer instead of charging their card immediately. Uses Stripe's send_invoice collection method."}),enable_plan_immediately:e.boolean().default(!1).meta({description:"If true, enables the plan immediately even though the invoice is not paid yet."}),finalize:e.boolean().default(!0).meta({description:"If true, finalizes the invoice so it can be sent to the customer. If false, keeps it as a draft for manual review."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer (e.g. bank details) is applied to the invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the invoice before it is due (Stripe days_until_due)."})}).meta({title:"InvoiceMode",description:"Invoice mode configuration. Creates an invoice instead of charging the card immediately."})}))(_e),{InvoiceTemplateSchema:Fx}=(e=>({InvoiceTemplateSchema:e.object({id:e.string().meta({description:"Unique identifier for the invoice template."}),name:e.string().meta({description:"User-defined name to distinguish this template when sending an invoice."}),footer:e.string().optional().meta({description:"Footer text rendered on the invoice, typically bank details so customers can pay directly."}),memo:e.string().optional().meta({description:"Memo shown near the top of the invoice (Stripe invoice description), e.g. a contact line for payment questions."}),net_terms_days:e.number().int().positive().optional().meta({description:"Default number of days the customer has to pay before the invoice is due. Overridable when sending."}),created_at:e.number().optional().meta({description:"Timestamp (ms) when the template was created."})})}))(_e),{BasePriceSchema:Mx}=((e,t,n)=>({BasePriceSchema:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),interval:e.enum(t).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),display:n.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(_e,om,bx),{CURRENCY_CODES:qx}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(am,Sx,Ix),{ApiPriceProcessorsSchema:fm}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(_e,vx),{AllocatedBillingFieldSchema:Ux}=((e,t)=>({AllocatedBillingFieldSchema:e.enum(t).optional().meta({internal:!0,description:"How an allocated usage_based price bills mid-cycle quantity changes. 'arrear' (default) bills at period end. 'prorated_legacy' is only returned for prices still on the legacy immediate-proration behavior; omit it to migrate the price to 'arrear'."})}))(_e,Px),{CreditDimensionNameSchema:Bx}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(_e,Cx,_x),{ApiCreditMatchSchema:gm}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Ex),{findCreditTierViolations:Vx}=(e=>({findCreditTierViolations:n=>{let r=[],i=(o,s)=>r.push({index:o,reason:s,message:e[s]}),a=0;for(let[o,s]of n.entries()){let c=o===n.length-1;if(s==="inf"){c||i(o,"non_final_infinity");continue}(!Number.isFinite(s)||s<=a)&&i(o,"not_increasing"),a=s,c&&i(o,"final_not_infinity")}return r}}))(Rx),{ApiCreditMultiplierSchema:Lx}=((e,t)=>({ApiCreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional().meta({description:"Multiplies the matched rate. All matching multipliers stack."}),add:e.number().optional().meta({description:"Added to the rate after every factor is applied, in credits per billing-unit group."})}).strict().refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(_e,gm),{ProviderMarkupsSchema:zx}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(_e,dm),{InvoiceFeatureQuantitySchema:hm}=((e,t,n)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(t).meta({description:"Which of the feature's prices to use: 'prepaid' or 'usage_based'."}),quantity:e.number().nonnegative().optional().meta({description:"Billable feature units in total, exclusive of any included usage. Not per seat or per entity. For a credit-system feature this is the number of credits."}),usage:e.array(n).optional().meta({description:"For credit-system features: billable units of the source features, converted through the credit rate card. Mutually exclusive with quantity."}),prorate:e.boolean().optional().meta({description:"Whether to prorate this line against period_start / period_end. Defaults to true for prepaid and false for usage-based."})}).strict().refine(i=>i.quantity!==void 0!=(i.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(_e,um,jx),{CreateInvoicePreviewSchema:kc}=((e,t)=>({CreateInvoicePreviewSchema:e.object({currency:e.string(),lines:e.array(t),subtotal:e.number(),discount_total:e.number(),tax:e.object({total:e.number(),amount_inclusive:e.number(),amount_exclusive:e.number(),status:e.enum(["complete","incomplete"])}).nullable(),total:e.number(),due_date:e.number().nullable()})}))(_e,Dx),{SUPPORTED_SET:$x}=(e=>({SUPPORTED_SET:new Set(e)}))(qx),{ApiCreditDimensionBaseSchema:Gx}=((e,t)=>({ApiCreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(_e,gm),{refineGraduatedTiers:ym}=(e=>({refineGraduatedTiers:(n,r)=>{let i=e(n.tiers.map(a=>a.to));for(let{index:a,message:o}of i)r.addIssue({code:"custom",message:o,path:["tiers",a,"to"]})}}))(Vx),{ApiFeatureMarkupsOverrideSchema:Kx}=((e,t,n)=>({ApiFeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional().meta({description:"Default percentage markup for customers on this plan. Use -100 to make usage free."}),provider_markups:t.meta({description:"Per-provider markup percentages for customers on this plan."}),model_markups:n.meta({description:"Per-model markup overrides for customers on this plan."})})}))(_e,zx,kx),{isValidCurrencyCode:Hx}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))($x),{ApiCreditDimensionSchema:Qx}=((e,t,n,r)=>({ApiCreditDimensionSchema:e.union([t.extend({tier_behavior:e.literal("graduated"),tiers:e.array(n).min(1)}).strict().superRefine(r),t.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(_e,Gx,lm,ym),{CurrencyCodeSchema:Am}=((e,t)=>({CurrencyCodeSchema:e.string().refine(t,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(_e,Hx),{AdditionalCurrencyTierSchema:Jx}=((e,t)=>({AdditionalCurrencyTierSchema:e.object({currency:t,amount:e.number().optional().meta({description:"Per-unit amount for this tier in this currency."}),flat_amount:e.number().optional().meta({description:"Flat amount for this tier in this currency, if the tier uses one."})}).refine(r=>r.amount!==void 0||r.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(_e,Am),{ApiCreditSchemaItemBaseSchema:bm}=((e,t,n,r)=>({ApiCreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string().nonempty().meta({description:"ID of the metered feature that draws from this credit system."}),billing_units:e.number().positive().optional().meta({description:"Number of metered-feature units priced together. Defaults to one when omitted."}),dimensions:e.record(t,n).optional().meta({description:"Named rates chosen by event properties. The most specific match sets the rate; with no match the item's own rate applies."}),multipliers:e.record(t,r).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(_e,Bx,Qx,Lx),{ApiFlatCreditSchemaItemSchema:Zx}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(bm,_e),{AdditionalCurrencyPriceSchema:Wx}=((e,t)=>({AdditionalCurrencyPriceSchema:e.object({currency:t,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(_e,Am),{AdditionalCurrencyTierArraySchema:Yx}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(_e,Jx,sm,cm),{ApiGraduatedCreditSchemaItemSchema:Xx}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(bm,_e,lm,ym),{AdditionalCurrencyPriceArraySchema:xm}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(_e,Wx,sm,cm),{ApiUsageTierWithCurrenciesSchema:eS}=((e,t,n)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:n.optional().meta({description:"Per-currency amounts for this tier. Tier boundaries ('to') are shared across all currencies."})}).refine(i=>i.amount!==void 0||i.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(i=>({...i,amount:i.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:n.optional()}))}))(_e,wx,Yx),{ApiCreditSchemaItemSchema:tS}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(_e,Xx,Zx),{BasePriceParamsSchema:nS}=((e,t,n,r)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:t({schema:n.number().optional(),defaultValue:1,description:"Number of intervals per billing cycle. Defaults to 1."}),additional_currencies:r.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),base_currency:n.string().optional().meta({internal:!0}),entitlement_id:n.string().optional().meta({internal:!0}),price_id:n.string().optional().meta({internal:!0}),stripe_price_id:n.string().optional().meta({description:"Stripe price id this base price is billed under. Set by sync flows to capture the actual Stripe price when it differs from the catalog default.",internal:!0})}).meta({title:"BasePrice",description:"Base price configuration for a plan."})}))(Mx,xx,_e,xm),{PlanItemPriceParamsSchema:rS}=((e,t,n,r,i,a,o)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(c=>c??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:t.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(i).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(a).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:o,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(_e,xm,eS,Ox,om,um,Ux),{ApiFeatureOverrideSchema:iS}=((e,t,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(t).optional().meta({description:"For credit system features: replaces the feature's credit_schema entirely for customers on this plan."}),markups:n.optional().meta({description:"For AI credit system features: replaces the feature's markup chain entirely for customers on this plan. An unset level means no markup at that level rather than inheriting the feature's."})})}))(_e,tS,Kx),{InvoiceBasePriceParamsSchema:Sm}=((e,t)=>({InvoiceBasePriceParamsSchema:e.pick({amount:!0,interval:!0,interval_count:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(nS,fm),{InvoiceItemPriceParamsSchema:oS}=((e,t)=>({InvoiceItemPriceParamsSchema:e.pick({amount:!0,tiers:!0,tier_behavior:!0,interval:!0,interval_count:!0,billing_units:!0,billing_method:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(rS,fm),{InvoiceLicenseQuantitySchema:aS}=((e,t,n)=>({InvoiceLicenseQuantitySchema:e.object({license_plan_id:e.string().meta({description:"The license plan linked to the parent plan."}),quantity:e.number().int().nonnegative().meta({description:"Billable seats, exclusive of any included seats."}),customize:e.object({price:t.nullable().optional()}).strict().optional().meta({description:"Override the license's per-seat price on this invoice."}),feature_quantities:e.array(n).optional().meta({description:"Feature charges priced through the license plan."}),prorate:e.boolean().optional().meta({description:"Whether to prorate seat charges against period_start / period_end. Defaults to true."})}).strict()}))(_e,Sm,hm),{InvoiceCustomizeItemSchema:sS}=((e,t,n)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:t.optional().meta({description:"Pricing to use for this feature on this invoice."}),feature_override:n.pick({credit_schema:!0}).strict().optional().meta({description:"For credit-system features: a credit rate card to use when converting `usage` on this invoice."})}).strict()}))(_e,oS,iS),{InvoiceCustomizeSchema:cS}=((e,t,n)=>({InvoiceCustomizeSchema:e.object({price:t.nullable().optional().meta({description:"Override the plan's base price for this invoice. Pass null or an amount of 0 to omit the base price line."}),items:e.array(n).optional().meta({description:"Override feature pricing for this invoice. Only pricing fields are accepted; grants, resets and rollovers are not part of an invoice."})}).strict().meta({title:"InvoiceCustomize",description:"Pricing overrides applied to this invoice only. The catalog and the customer's plan are not changed."})}))(_e,Sm,sS),{InvoicePlanParamsSchema:uS}=((e,t,n,r,i)=>({InvoicePlanParamsSchema:e.object({plan_id:e.string().meta({description:"The catalog plan (or variant) whose pricing to use."}),version:e.number().optional().meta({description:"Plan version. Defaults to the active version."}),customize:t.optional(),feature_quantities:e.array(n).optional(),license_quantities:e.array(r).optional(),discounts:e.array(i).optional().meta({description:"Discounts applied only to this plan's lines."}),prorate:e.boolean().optional().meta({description:"Whether to prorate the base price against period_start / period_end. Defaults to true."})}).strict()}))(_e,cS,hm,aS,pm),{CreateInvoiceParamsSchema:yi}=((e,t,n,r,i)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(t).optional(),custom_line_items:e.array(n).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(r).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:i.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start \u2192 period_end against one price interval starting at period_start."}),period_end:i.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(o=>o.period_start===void 0==(o.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(o=>o.period_start===void 0||o.period_end===void 0||o.period_end>o.period_start,{message:"period_end must be after period_start."})}))(_e,uS,Tx,pm,Nx);var wm=p.strictObject({requestId:p.uuid(),predecessorOperationId:p.uuid().optional(),invoiceMode:Dr.optional(),entityId:p.uuid().optional(),billingSubscriptionId:p.uuid().optional(),newBillingSubscription:p.literal(!0).optional(),offerId:p.uuid().optional(),nativeOffer:hi.optional(),plans:p.array(p.strictObject({productVersionId:p.uuid(),seatQuantities:p.record(Ko,p.number().int().min(0).max(1e4)).optional(),featureQuantities:p.record(p.uuid(),p.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100,"At most 100 feature quantities").optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Plan versions must be unique"),provider:p.enum(["stripe","apple","google","merchant"]),currency:Ie}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||["apple","google"].includes(e.provider)&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||["stripe","merchant"].includes(e.provider)&&!e.billingSubscriptionId,"A new billing subscription has no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),Mr=p.strictObject({operationId:p.uuid()}),Dt=p.number().int().min(0).max(1e8),lS=p.strictObject({lineId:p.uuid(),productVersionId:p.uuid(),productName:p.string().min(1).max(80),interval:p.enum(["free","week","month","year","one_time"]),intervalCount:p.number().int().min(1).max(156).optional(),baseAmountMinor:Dt,seats:p.array(p.strictObject({key:Ko,quantity:p.number().int().min(0).max(1e4),includedQuantity:p.number().int().min(0).max(1e4),maximumQuantity:p.number().int().min(0).max(1e4),unitAmountMinor:Dt})).max(20),prepaid:p.array(dp).max(100).optional(),catalogAmountMinor:Dt,trial:p.strictObject({days:p.number().int().min(1).max(730),cardRequired:p.boolean()}).nullable()}).refine(e=>new Set(e.seats.map(t=>t.key)).size===e.seats.length&&e.seats.every(t=>t.quantity>=t.includedQuantity&&t.quantity<=t.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((t,n)=>t+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((t,n)=>t+Wo({quantity:n.quantity,unitAmountMinor:n.unitAmountMinor,...n.pricing===void 0?{}:{pricing:n.pricing}}),0)===e.catalogAmountMinor,"Quote must retain its published base price and component quantities"),Om=p.string().regex(/^[A-Za-z0-9_-]{1,200}$/),dS=p.strictObject({id:Om,name:p.string().min(1).max(40),percent_off:p.number().gt(0).max(100).optional(),amount_off:p.number().int().positive().optional(),currency:p.string().regex(/^[a-z]{3}$/).optional(),duration:p.enum(["once","repeating","forever"]),duration_in_months:p.number().int().min(1).max(36).optional()}).refine(e=>e.percent_off===void 0!=(e.amount_off===void 0)&&e.amount_off===void 0==(e.currency===void 0)&&e.duration==="repeating"==(e.duration_in_months!==void 0),"A Stripe coupon has one percentage or amount and months only when repeating"),pS=p.strictObject({subscriptionId:p.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:p.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:p.array(p.strictObject({id:p.string(),price_id:p.string(),quantity:p.number().int().nonnegative(),discounts:p.array(p.strictObject({id:p.string(),coupon:p.string(),start:p.number(),end:p.number().nullable()})).optional()})).min(1).max(100),prorationDate:p.number().int().nonnegative(),amountMinor:p.number().int().positive(),periodStartMs:p.number(),periodEndMs:p.number()}),Pm=p.strictObject({invoiceMode:Dr.optional(),append:pS.optional(),provider:p.literal("stripe"),executor:p.enum(["indiana","merchant"]),accountId:p.string().regex(/^acct_[A-Za-z0-9]+$/),mode:p.enum(["payment","subscription"]),lineItems:p.array(p.strictObject({price:p.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:p.number().int().min(1).max(1e4),priceId:p.uuid(),productName:p.string().min(1).max(80),amountMinor:p.number().int().min(0).max(1e8),currency:p.string().regex(/^[a-z]{3}$/),interval:p.enum(["week","month","year","one_off"]),intervalCount:p.number().int().min(1).max(52),slot:p.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:p.strictObject({mode:p.enum(["graduated","volume"]),tiers:p.array(p.strictObject({upTo:p.number().int().min(1).max(1e6).nullable(),unitAmountMinor:p.number().int().min(0).max(1e8),flatAmountMinor:p.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:p.array(p.strictObject({coupon:Om,terms:dS})).max(1),trialPeriodDays:p.number().int().min(1).max(730).nullable(),metadata:p.strictObject({grooveCheckoutId:p.uuid(),grooveCustomerId:p.uuid()}),expiresAt:p.iso.datetime({offset:!0})}),Ai=p.strictObject({operationId:p.uuid(),entityId:p.uuid().nullable(),billingSubscriptionId:p.uuid().nullable(),discount:p.strictObject({offerId:p.uuid(),couponId:p.uuid(),discount:nr,duration:sn,amountMinor:Dt,allocations:p.array(p.strictObject({productVersionId:p.uuid(),amountMinor:Dt})).min(1).max(20),expiresAt:p.iso.datetime({offset:!0})}).nullable(),charge:p.strictObject({effectiveAt:p.iso.datetime({offset:!0}),periodEndsAt:p.iso.datetime({offset:!0}),debitMinor:Dt,discountMinor:Dt,taxMinor:Dt,totalMinor:Dt}).nullable(),expiresAt:p.iso.datetime({offset:!0}),provider:p.enum(["stripe","apple","google","merchant"]),nativeOffer:hi.optional(),currency:Ie,lines:p.array(lS).min(1).max(20),catalogAmountMinor:Dt,automaticTax:p.boolean(),execution:p.union([Pm,Vo]).nullable()}).refine(e=>e.provider==="merchant"?e.execution?.provider==="merchant"&&e.execution.operationId===e.operationId&&e.execution.catalogAmountMinor===e.catalogAmountMinor&&e.execution.currency===e.currency&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&e.execution.discount?.grantId===e.discount?.offerId:e.provider==="stripe"?e.execution?.provider!=="merchant"&&(e.lines[0]?.trial?.cardRequired===!1&&!e.execution?.invoiceMode?.enabled?e.execution===null&&e.discount===null:e.execution!==null&&e.execution.metadata.grooveCheckoutId===e.operationId&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.mode===(e.lines.some(t=>!["one_time","free"].includes(t.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(t=>t.price!==null))&&e.execution.discounts.every(t=>t.coupon===t.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(t=>e.discount!==null&&(t.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&t.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${t.terms.amount_off}`&&t.terms.amount_off===e.discount.discount.amountOffCents&&t.terms.currency?.toUpperCase()===e.currency&&t.terms.duration==="once"))):e.execution===null,"Stripe execution must carry the quote identity, expiry, mode, trial and held coupon").refine(e=>(!e.discount||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.discount.duration.type==="once")&&e.discount.amountMinor<=e.catalogAmountMinor&&e.discount.allocations.length===e.lines.length&&e.discount.allocations.every((t,n)=>{let r=e.lines[n];return r!==void 0&&t.productVersionId===r.productVersionId&&t.amountMinor<=r.catalogAmountMinor})&&e.discount.allocations.reduce((t,n)=>t+n.amountMinor,0)===e.discount.amountMinor)&&(["stripe","merchant"].includes(e.provider)?e.nativeOffer===void 0:e.nativeOffer!==void 0&&e.lines.length===1&&e.nativeOffer.discountMinor<=e.catalogAmountMinor&&e.nativeOffer.trialDays===(e.lines[0]?.trial?.days??null)&&(!e.discount||e.nativeOffer.discountMinor===e.discount.amountMinor))&&(!e.charge||e.billingSubscriptionId!==null&&e.charge.totalMinor===e.charge.debitMinor-e.charge.discountMinor+e.charge.taxMinor&&e.charge.discountMinor<=e.charge.debitMinor&&Date.parse(e.charge.periodEndsAt)>Date.parse(e.charge.effectiveAt))&&new Set(e.lines.map(t=>t.lineId)).size===e.lines.length&&e.lines.reduce((t,n)=>t+n.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),bi=p.strictObject({operationId:p.uuid(),orderId:p.uuid(),append:p.boolean().optional(),invoiceMode:p.boolean().optional(),status:p.enum(["pending","complete","cancelled","failed"]),executor:p.enum(["indiana","merchant"]),checkoutUrl:p.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:p.union([Pm,Vo]).nullable(),currency:Ie,catalogAmountMinor:Dt,taxMinor:Dt,totalMinor:p.number().int().min(0).max(2e8).nullable(),quoteFinalized:p.boolean(),nativePurchase:Rc.nullable(),confirmedAt:p.iso.datetime({offset:!0}).nullable().optional(),quote:Ai.optional(),merchantExecution:vr.nullable().optional(),problem:Ui.nullable().optional(),authority:Go.optional()}).refine(e=>(e.checkoutUrl===null||e.executor==="indiana"||e.merchantExecution?.type==="purchase")&&(e.execution===null||e.executor==="merchant"),"Only Indiana-executed purchases carry a Checkout URL and only record-only purchases carry execution instructions"),_a=p.strictObject({enabled:p.literal(!0),featureIds:p.array(p.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),Cm=p.strictObject({requestId:p.uuid(),invoiceMode:Dr.optional(),membershipId:p.uuid(),carryOverBalances:_a.optional(),carryOverUsages:_a.optional(),membershipIds:p.array(p.uuid()).min(1).max(20).optional(),prorationBehavior:p.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:p.enum(["immediate","renewal","store"]),change:p.discriminatedUnion("type",[p.strictObject({type:p.literal("plan"),productVersionId:p.uuid()}),p.strictObject({type:p.literal("seats"),licenseKey:Ko,quantity:p.number().int().min(0).max(1e4)}),p.strictObject({type:p.literal("quantity"),internal_feature_id:p.uuid(),quantity:p.number().int().min(0).max(1e4)}),p.strictObject({type:p.literal("cancel")}),p.strictObject({type:p.literal("uncancel")}),p.strictObject({type:p.literal("billing_cycle"),billingCycleAnchor:p.union([p.literal("now"),p.number().int().positive().max(0xe677d21fdbff)])})])}).refine(e=>e.timing!=="store"||e.change.type==="plan","Store timing applies to a native plan replacement").refine(e=>e.change.type!=="billing_cycle"||e.timing===(e.change.billingCycleAnchor==="now"?"immediate":"renewal"),"Use immediate for now and renewal for a future millisecond anchor").refine(e=>!e.membershipIds||["cancel","uncancel"].includes(e.change.type)&&e.membershipIds.includes(e.membershipId)&&new Set(e.membershipIds).size===e.membershipIds.length,"Grouped actions require unique cancel/uncancel targets including the primary membership").refine(e=>!e.carryOverBalances&&!e.carryOverUsages||e.change.type==="plan"&&e.timing==="immediate","Carry applies only to immediate upgrades").refine(e=>!e.prorationBehavior||e.change.type==="quantity","prorationBehavior applies to prepaid quantity changes"),Ca=p.string().regex(/^price_[A-Za-z0-9]+$/),Im=p.strictObject({grooveUpdateId:p.uuid(),grooveCustomerId:p.uuid()}),vm=p.strictObject({price:Ca.nullable(),priceId:p.uuid().optional(),quantity:p.number().int().min(0).max(1e4)}),_m=p.strictObject({provider:p.literal("stripe"),invoiceMode:Dr.optional(),executor:p.enum(["indiana","merchant"]),accountId:p.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:p.string().regex(/^sub_[A-Za-z0-9]+$/),action:p.enum(["update","cancel","schedule","release"]),update:p.strictObject({items:p.array(vm).max(20),remove:p.array(Ca).max(20),restoreItems:p.array(p.strictObject({price:Ca,quantity:p.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:p.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:p.number().int().positive().optional(),paymentBehavior:p.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:p.boolean().optional(),clearCancelAt:p.literal(!0).optional(),billingCycleAnchorNow:p.literal(!0).optional(),metadata:Im}).nullable(),cancel:p.strictObject({prorate:p.literal(!1),invoiceNow:p.literal(!1)}).nullable(),schedule:p.strictObject({currentItems:p.array(p.strictObject({price:Ca,quantity:p.number().int().min(0).max(1e4)})).max(20),nextItems:p.array(vm).min(1).max(20),switchAt:p.number().int().positive(),interval:p.enum(["week","month","year"]),intervalCount:p.number().int().min(1).max(52),resetBillingCycleAnchor:p.literal(!0).optional(),metadata:Im}).nullable(),release:p.strictObject({schedule:p.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:p.iso.datetime({offset:!0})}).refine(e=>["update","cancel","schedule","release"].every(t=>e[t]!==null==(e.action===t))&&(e.executor==="indiana"||[...e.update?.items??[],...e.schedule?.nextItems??[]].every(t=>t.price!==null)),"Stripe update execution carries exactly its action, with bound Prices for the merchant"),Ea=p.strictObject({carryOverBalances:_a.optional(),carryOverUsages:_a.optional(),operationId:p.uuid(),membershipId:p.uuid(),productVersionId:p.uuid(),timing:p.enum(["immediate","renewal"]),effectiveAt:p.iso.datetime({offset:!0}),expiresAt:p.iso.datetime({offset:!0}),currency:Ie,creditMinor:Dt,debitMinor:Dt,discountMinor:Dt,taxMinor:Dt,totalMinor:Dt,retainedProductVersionIds:p.array(p.uuid()).max(19),execution:p.union([_m,Lo])}),mS=p.strictObject({operationId:p.uuid(),invoiceMode:p.boolean().optional(),membershipId:p.uuid(),productVersionId:p.uuid(),status:p.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:p.enum(["immediate","renewal"]),effectiveAt:p.iso.datetime({offset:!0}),checkoutUrl:p.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:p.enum(["indiana","merchant"]),execution:p.union([_m,Lo]).nullable(),confirmedAt:p.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:vr.nullable().optional(),problem:Ui.nullable().optional(),quote:Ea.optional(),authority:Go.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),fS=p.strictObject({operationId:p.uuid(),membershipId:p.uuid(),productVersionId:p.uuid(),timing:p.literal("store"),effectiveAt:p.null(),expiresAt:p.iso.datetime({offset:!0}),currency:Ie,creditMinor:p.null(),debitMinor:p.null(),discountMinor:p.null(),taxMinor:p.null(),totalMinor:p.null(),retainedProductVersionIds:p.array(p.uuid()).max(19),store:p.strictObject({provider:p.enum(["apple","google"]),productId:p.string().min(1).max(255),catalogAmountMinor:Dt,policy:p.enum(["apple_store","google_full_price"])})}),gS=p.strictObject({operationId:p.uuid(),membershipId:p.uuid(),productVersionId:p.uuid(),status:p.enum(["prepared","pending","effective","cancelled","failed"]),timing:p.literal("store"),effectiveAt:p.iso.datetime({offset:!0}).nullable(),checkoutUrl:p.null(),nativePurchase:Rc.nullable()}),Em=p.union([Ea,fS]),jc=p.union([mS,gS]),uo=p.number().int().positive().max(2e8),Fr=p.number().int().min(0).max(2e8),Rm=p.strictObject({requestId:p.uuid(),invoiceId:p.uuid(),mode:p.enum(["full","partial"]),amountMinor:uo.optional(),entitlementAction:p.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),km=p.strictObject({provider:p.literal("stripe"),executor:p.enum(["indiana","merchant"]),accountId:p.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:p.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:uo,currency:p.string().regex(/^[a-z]{3}$/),metadata:p.strictObject({indianaRefundId:p.uuid()}),idempotencyKey:p.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:p.array(p.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),Tc=p.strictObject({operationId:p.uuid(),invoiceId:p.uuid(),providerInvoiceId:p.string().min(1).max(200),currency:Ie,paidMinor:Fr,refundedMinor:Fr,pendingMinor:Fr,amountMinor:uo,mode:p.enum(["full","partial"]),entitlementAction:p.enum(["retain","revoke"]),revokes:p.strictObject({customerProductIds:p.array(p.uuid()).max(100),subscriptionIds:p.array(p.string().min(1).max(200)).max(20)}),execution:p.union([km,zo]),expiresAt:p.iso.datetime({offset:!0})}).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&(e.execution.provider==="merchant"?e.execution.merchantInvoiceId===e.providerInvoiceId&&e.execution.operationId===e.operationId&&e.execution.currency===e.currency:e.execution.invoice===e.providerInvoiceId&&e.execution.metadata.indianaRefundId===e.operationId&&e.execution.currency===e.currency.toLowerCase())&&(e.entitlementAction==="revoke"||e.revokes.customerProductIds.length===0&&e.revokes.subscriptionIds.length===0),"Refund quote must stay within the refundable amount and match its execution"),Ra=p.strictObject({operationId:p.uuid(),invoiceId:p.uuid(),providerInvoiceId:p.string().min(1).max(200),status:p.enum(["quoted","pending","succeeded","failed","expired"]),executor:p.enum(["indiana","merchant"]),currency:Ie,amountMinor:uo,mode:p.enum(["full","partial"]),entitlementAction:p.enum(["retain","revoke"]),refundId:p.string().min(1).max(200).nullable(),quote:Tc.optional(),execution:p.union([km,zo]).nullable(),confirmedAt:p.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:vr.nullable().optional(),problem:Ui.nullable().optional(),authority:Go.optional(),failureReason:p.string().min(1).max(200).nullable(),createdAt:p.iso.datetime({offset:!0}),completedAt:p.iso.datetime({offset:!0}).nullable()}).refine(e=>(e.execution===null||e.executor==="merchant"&&e.status==="quoted")&&(e.status!=="succeeded"||e.refundId!==null),"Only quoted record-only refunds carry instructions; a succeeded refund names its Stripe refund"),g_=p.strictObject({invoiceId:p.uuid(),currency:Ie,paidMinor:Fr,refundedMinor:Fr,pendingMinor:Fr,refundableMinor:Fr,executor:p.enum(["indiana","merchant"]).nullable(),canRefund:p.boolean(),operations:p.array(Ra).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),h_=p.strictObject({requestId:p.uuid(),mode:p.enum(["full","partial"]),amountMinor:uo.optional(),entitlementAction:p.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount");var jm=at.strictObject({requestId:at.uuid(),targets:at.array(at.strictObject({membershipId:at.uuid(),action:at.enum(["cancel","uncancel"]),timing:at.enum(["immediate","renewal"])}).refine(e=>e.action!=="uncancel"||e.timing==="immediate","Restoration is immediate")).min(1).max(100)}).refine(e=>new Set(e.targets.map(t=>t.membershipId)).size===e.targets.length,"Duplicate batch target"),ka=at.strictObject({batchId:at.uuid()}),hS=at.strictObject({operationId:at.uuid(),membershipIds:at.array(at.uuid()).min(1).max(20),provider:at.enum(["stripe","apple","google"]),action:at.enum(["cancel","uncancel"]),timing:at.enum(["immediate","renewal"]),status:at.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:Ea.nullable(),managementUrl:at.url().nullable(),failureCode:at.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),lo=at.strictObject({batchId:at.uuid(),ready:at.boolean(),status:at.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:at.iso.datetime({offset:!0}),acceptedAt:at.iso.datetime({offset:!0}).nullable(),groups:at.array(hS).min(1).max(100)});import{z as je}from"zod";var yS=je.string().trim().min(1).max(240),Nc={requestId:je.uuid(),reason:yS},ja=je.discriminatedUnion("action",[je.strictObject({...Nc,action:je.literal("start"),productVersionId:je.uuid(),entityId:je.uuid().optional(),days:je.number().int().min(1).max(730).optional()}),je.strictObject({...Nc,action:je.literal("extend"),membershipId:je.uuid(),days:je.number().int().min(1).max(730)}),je.strictObject({...Nc,action:je.literal("end"),membershipId:je.uuid()})]),Tm=je.strictObject({operationId:je.uuid()}),Nm=je.iso.datetime({offset:!0}),AS=je.strictObject({provider:je.literal("stripe"),executor:je.enum(["indiana","merchant"]),accountId:je.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:je.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:je.union([je.literal("now"),Nm]),prorationBehavior:je.literal("none")}),Dc=je.strictObject({operationId:je.uuid(),action:je.enum(["start","extend","end"]),status:je.enum(["pending","effective"]),managedBy:je.enum(["indiana","stripe"]),membershipIds:je.array(je.uuid()).min(1).max(20),endsAt:Nm.nullable(),execution:AS.nullable()}).refine(e=>e.execution!==null==(e.managedBy==="stripe"&&e.status==="pending")&&e.action==="end"==(e.endsAt===null)&&(e.action!=="start"||e.managedBy==="indiana")&&(e.execution===null||e.execution.trialEnd==="now"==(e.action==="end")),"Only a pending Stripe trial change carries execution instructions"),I_=je.strictObject({groupId:je.uuid(),productVersionId:je.uuid(),enabled:je.boolean()});import{z as We}from"zod";var Dm=We.strictObject({requestId:We.uuid(),currency:Ie,makeDefault:We.boolean()}),Fm=We.strictObject({setupId:We.uuid()}),bS=We.strictObject({provider:We.literal("stripe"),executor:We.literal("merchant"),accountId:We.string().regex(/^acct_[A-Za-z0-9]+$/),mode:We.literal("setup"),currency:We.string().regex(/^[a-z]{3}$/),customer:We.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:We.uuid(),metadata:We.strictObject({grooveProjectId:We.uuid(),grooveEnvironmentId:We.uuid(),grooveCustomerId:We.uuid(),groovePaymentSetupId:We.uuid()}),setDefaultPaymentMethod:We.boolean(),expiresAt:We.iso.datetime({offset:!0})}),Fc=We.strictObject({id:We.uuid(),provider:We.literal("stripe"),status:We.enum(["prepared","complete","expired"]),currency:Ie,makeDefault:We.boolean(),url:We.url().nullable(),createdAt:We.iso.datetime({offset:!0}),expiresAt:We.iso.datetime({offset:!0}),completedAt:We.iso.datetime({offset:!0}).nullable(),execution:bS.nullable()});import{z as Ft}from"zod";var Mm=Ft.union([Ft.string(),Ft.number(),Ft.boolean(),Ft.null()]),qm=Ft.strictObject({customerId:Ft.uuid()}),Um=Ft.strictObject({customerId:Ft.uuid(),provider:Ft.literal("stripe"),checkedAt:Ft.iso.datetime({offset:!0}),status:Ft.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Ft.number().int().nonnegative(),differences:Ft.array(Ft.strictObject({subscriptionId:Ft.string().startsWith("sub_"),itemId:Ft.string().nullable(),field:Ft.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Mm,actual:Mm})).max(1e4)});import{z as we}from"zod";var Ta=we.iso.datetime({offset:!0}),Na=we.strictObject({createdAt:Ta,id:we.uuid()}),Da=we.strictObject({customerId:we.uuid().optional(),entityId:we.uuid().optional(),productId:we.string().min(1).max(256).optional(),provider:we.enum(["stripe","apple","google","merchant","free"]).optional(),status:we.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:Na.optional(),limit:we.number().int().min(1).max(100).optional()}),Mc={id:we.uuid(),customerId:we.uuid(),entityId:we.uuid().nullable(),productId:we.string().min(1).max(256),productVersionId:we.uuid(),name:we.string().min(1).max(120),provider:we.enum(["stripe","apple","google","merchant","free"]),createdAt:Ta},xS=we.strictObject({...Mc,status:we.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:we.boolean(),billingSubscriptionId:we.uuid().nullable()}),SS=we.strictObject({...Mc,status:we.enum(["active","ended","refunded"]),orderId:we.uuid().nullable(),transactionId:we.uuid().nullable(),currency:Ie.nullable(),amountMinor:we.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),IS=we.strictObject({...Mc,status:we.enum(["blocked","resolved"]),conflict:we.strictObject({detectedAt:Ta,blockingMembershipIds:we.array(we.uuid()).min(1).max(100),transactionId:we.uuid()}),resolvedAt:Ta.nullable()}),Bm=Da.extend({status:we.enum(["blocked","resolved"]).optional()}),Vm=we.strictObject({customerId:we.uuid(),orderId:we.uuid()}),Lm=we.strictObject({orderId:we.uuid(),status:we.enum(["blocked","resolved"])}),zm=we.strictObject({items:we.array(xS).max(100),nextCursor:Na.nullable()}),$m=we.strictObject({items:we.array(SS).max(100),nextCursor:Na.nullable()}),Gm=we.strictObject({items:we.array(IS).max(100),nextCursor:Na.nullable()});import{z as nt}from"zod";var Km=nt.union([nt.strictObject({intent:nt.literal("read"),requestId:nt.uuid(),purchaseIntentId:nt.uuid()}),nt.strictObject({requestId:nt.uuid(),provider:nt.literal("apple"),purchaseIntentId:nt.uuid(),productId:nt.string().min(1).max(255).optional(),signedTransaction:nt.string().min(1).max(131072)}),nt.strictObject({requestId:nt.uuid(),provider:nt.literal("google"),purchaseIntentId:nt.uuid(),productId:nt.string().min(1).max(255).optional(),purchaseToken:nt.string().min(1).max(16384)})]),Hm=nt.strictObject({requestId:nt.uuid(),orderId:nt.uuid(),purchaseIntentId:nt.uuid(),status:nt.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:Ie,refunded:nt.boolean(),completion:nt.strictObject({transactionIds:nt.array(nt.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:nt.boolean()}).nullable()});import{z as V}from"zod";var Uc=V.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),vS=V.record(V.string(),V.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),wS=3,po=20,OS=wS*po,qc=V.strictObject({type:V.literal("product"),productId:Uc}),Qm={type:V.literal("group"),key:V.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:V.string().trim().min(1).max(80)},PS=V.discriminatedUnion("type",[qc,V.strictObject({...Qm,items:V.array(qc).max(po)})]),CS=V.discriminatedUnion("type",[qc,V.strictObject({...Qm,items:V.array(PS).max(po)})]),_S=V.array(CS).max(po).superRefine((e,t)=>{let n=new Set,r=new Set,i=0;function a(o){for(let s of o){i++;let c=s.type==="product"?n:r,u=s.type==="product"?s.productId:s.key;c.has(u)&&t.addIssue({code:"custom",message:s.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),c.add(u),s.type==="group"&&a(s.items)}}a(e),(n.size>po||i>OS)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function Bc(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:Bc(t))}var xi=V.strictObject({lookupKey:V.string().trim().min(1).max(200),displayName:V.string().trim().min(1).max(1500),items:_S,metadata:vS}),ES=V.strictObject({product:V.record(V.string(),V.json()),prices:V.array(V.record(V.string(),V.json())),entitlements:V.array(V.record(V.string(),V.json())),freeTrials:V.array(V.record(V.string(),V.json())),licenses:V.array(V.record(V.string(),V.json()))}),Jm=xi.extend({id:V.uuid(),projectId:V.uuid(),environmentId:V.uuid(),state:V.enum(["active","archived"]),isCurrent:V.boolean(),revision:V.number().int().nonnegative(),publishedVersionId:V.uuid().nullable(),createdAt:V.iso.datetime({offset:!0})}).superRefine((e,t)=>{e.isCurrent&&(e.state!=="active"||!e.publishedVersionId)&&t.addIssue({code:"custom",message:"Current Offering must be active and published"})}),Zm=V.strictObject({id:V.uuid(),offeringId:V.uuid(),projectId:V.uuid(),environmentId:V.uuid(),version:V.number().int().positive(),document:xi,productEvidence:V.record(Uc,ES),createdAt:V.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=Bc(e.document);(!n.length||jS(e.document).length>0||Object.keys(e.productEvidence).length!==n.length||n.some(r=>!Object.hasOwn(e.productEvidence,r)))&&t.addIssue({code:"custom",message:"Published Offering requires evidence for every Product"})}),RS=V.strictObject({rows:V.array(Jm).max(200),versions:V.array(Zm).max(500)}),F_=V.discriminatedUnion("action",[V.strictObject({action:V.literal("create"),document:xi}),V.strictObject({action:V.literal("save"),id:V.uuid(),revision:V.number().int().nonnegative(),document:xi}),V.strictObject({action:V.enum(["publish","set_current","archive","restore"]),id:V.uuid(),revision:V.number().int().nonnegative()})]),M_=V.strictObject({record:Jm,version:Zm.nullable()}),Wm=V.discriminatedUnion("type",[V.strictObject({type:V.literal("current")}),V.strictObject({type:V.literal("id"),id:V.uuid()}),V.strictObject({type:V.literal("lookup_key"),lookupKey:V.string().min(1).max(200)}),V.strictObject({type:V.literal("version"),versionId:V.uuid()})]),kS=V.strictObject({internalId:Uc,id:V.string(),name:V.string().nullable(),version:V.number().int().positive(),archived:V.boolean()}),q_=RS.extend({products:V.array(kS).max(500),pagination:V.strictObject({rows:V.string().nullable(),versions:V.string().nullable(),products:V.string().nullable()}).optional()});function jS(e){let t=[];Bc(e).length||t.push("Select at least one Product before publishing");function n(r){for(let i of r)i.type==="group"&&(i.items.length||t.push("Every published group requires a Product"),n(i.items))}return n(e.items),t}import{z as Fa}from"zod";var Ym=Fa.strictObject({id:Fa.uuid(),offeringId:Fa.uuid(),version:Fa.number().int().positive(),document:xi});import{z as Ct}from"zod";import{z as ye}from"zod";import{z as Si}from"zod";var Ma=Si.strictObject({items:Si.array(Si.strictObject({productVersionId:Si.string().min(1).max(200),label:Si.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:Si.string().min(1).max(200).nullable(),grouping:Aa.optional()});function Xm(e,t,n){let r=e.type==="fixed"?e.productVersionId:t[e.pickerId];return typeof r!="string"||!Object.values(n.plans).some(i=>i.versionId===r&&i.available)||e.type==="picker"&&(!e.allowedProductVersionIds.includes(r)||!n.pickers[e.pickerId]?.options.includes(r))?null:r}var Vc=ye.discriminatedUnion("type",[ye.strictObject({type:ye.literal("event"),event:ye.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),ye.strictObject({type:ye.literal("open_url"),url:ye.url().refine(e=>new URL(e).protocol==="https:")})]),TS=un,NS=ye.discriminatedUnion("type",[ye.object({type:ye.literal("checkout"),product:xa}).strict(),ye.object({type:ye.literal("close")}).strict(),ye.object({type:ye.literal("action"),action:Vc}).strict()]),Ii=ye.object({schemaVersion:ye.literal(3),kind:ye.literal("paywall"),name:ye.string().trim().min(1).max(80),presentation:Pn,requirement:ir.optional(),products:Ma,offeringVersionId:ye.uuid().nullable(),offeringId:ye.uuid(),screen:TS,buttons:ye.record(ye.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),NS)}).strict(),X_=Ii.superRefine((e,t)=>{(e.screen.surface!=="paywall"||e.screen.actions.some(r=>!["event","navigate"].includes(r.type)||r.close))&&t.addIssue({code:"custom",message:"Paywall screen is incomplete"});for(let r of FS(e))t.addIssue({code:"custom",message:r});for(let r of DS(e))t.addIssue({code:"custom",message:r});or(e.screen).some(r=>!r.complete)&&t.addIssue({code:"custom",message:"Paywall needs complete local content"}),(Object.keys(e.buttons).length!==e.screen.actions.filter(r=>r.type!=="navigate").length||e.screen.actions.some(r=>r.type!=="navigate"&&!Object.hasOwn(e.buttons,r.id)))&&t.addIssue({code:"custom",message:"Paywall buttons require matching node policies"}),Object.values(e.buttons).some(r=>r.type==="checkout")||t.addIssue({code:"custom",message:"A paywall requires a purchase or membership change button"})});function DS(e){let t=e.products.items.map(a=>a.productVersionId),n=Bp(e.screen),r=new Set,i=[];(!t.length||!e.products.defaultProductVersionId||!t.includes(e.products.defaultProductVersionId))&&i.push("products"),e.offeringVersionId||i.push("offering"),e.products.grouping&&(!ba(e.products.grouping,t)||e.products.grouping.tiers.some(a=>!e.products.grouping.assignments.some(o=>o.tierId===a.id)))&&i.push("grouping");for(let a of Object.values(e.buttons))if(a.type==="checkout"){let o=a.product;if(o.type==="fixed")r.add(o.productVersionId);else{o.allowedProductVersionIds.forEach(u=>r.add(u));let s=!1,c=n[o.pickerId];c&&(s=!0,(o.allowedProductVersionIds.some(u=>!c.ids.includes(u))||c.ids.some(u=>!o.allowedProductVersionIds.includes(u)))&&i.push("picker")),Gt(e.screen,u=>{if(u.id!==o.pickerId||u.type!=="plan_picker")return;s=!0,(JSON.stringify(u.planIds)!==JSON.stringify(t)||JSON.stringify(o.allowedProductVersionIds)!==JSON.stringify(t)||u.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let l=u.grouping?{tiers:u.grouping.tiers,assignments:u.grouping.assignments}:void 0;JSON.stringify(l)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),s||i.push("picker")}}return(!r.size||[...r].some(a=>!t.includes(a)))&&i.push("purchase"),Gt(e.screen,a=>{a.type==="stack"&&a.productSlot&&!a.bind?.plan&&i.push(`productBinding:${a.id}`),(a.type==="stack"||a.type==="button")&&a.bind?.plan&&!t.includes(a.bind.plan)&&i.push("binding"),a.type==="plan_picker"&&(!a.planIds?.length||a.planIds.some(o=>!t.includes(o)))&&i.push("binding")}),[...new Set(i)]}function FS(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),Zn(s.root,c=>{let u=c.type==="button"?c.action:c.type==="stack"?c.purchaseAction:void 0;if(u){let l=e.screen.actions.find(f=>f.id===u);l?.type==="navigate"&&r.get(s.id).push(l.pageId);let m=e.buttons[u];s.id!==n.id&&m&&m.type!=="close"&&t.push(`purchaseScreen:${c.id}`)}s.id!==n.id&&(c.type==="plan_picker"||c.type==="stack"&&c.productSlot)&&t.push(`packageScreen:${c.id}`)});let i=new Set;function a(s){if(!i.has(s)){i.add(s);for(let c of r.get(s)??[])a(c)}}let o=e.screen.initialPageId??e.screen.pages[0]?.id;o?a(o):t.push("initialPage");for(let s of e.screen.pages)i.has(s.id)||t.push(`unreachableScreen:${s.id}`);return[...new Set(t)]}var ef=ye.object({id:ye.uuid(),projectId:ye.uuid(),environmentId:ye.uuid(),revision:ye.number().int().nonnegative(),state:ye.enum(["active","archived"]),publishedVersionId:ye.uuid().nullable(),updatedAt:ye.iso.datetime({offset:!0}),draft:Ii}).strict(),e1=ye.object({rows:ye.array(ef).max(200),nextCursor:ye.uuid().nullable()}).strict(),t1=ef.omit({draft:!0}).extend({name:ye.string(),productCount:ye.number().int().nonnegative()}).strict(),n1=ye.discriminatedUnion("action",[ye.object({action:ye.literal("save"),id:ye.uuid().nullable(),revision:ye.number().int().nonnegative(),document:Ii}).strict(),ye.object({action:ye.enum(["publish","archive"]),id:ye.uuid(),revision:ye.number().int().nonnegative()}).strict()]),r1=ye.object({paywalls:ye.array(ye.object({id:ye.uuid(),paywallId:ye.uuid(),version:ye.number().int().positive(),name:ye.string().min(1).max(80),presentation:Pn,buttons:Ii.shape.buttons}).strict()).max(500),limited:ye.boolean()}).strict();import{z as Re}from"zod";import{z as Kt}from"zod";var vi=Kt.string().regex(/^[a-f0-9]{64}$/),MS=ha.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),tf=Kt.strictObject({couponDigests:Kt.record(Kt.uuid(),vi),variables:Kt.record(In,Kt.record(Kt.uuid(),Kt.partialRecord(Kt.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),Kt.string()))),locales:Kt.record(In,li.extend({nodes:Kt.record(Kt.string(),Kt.strictObject({base:MS})),plans:Kt.object({}).strict(),pickers:Kt.object({}).strict()}).omit({paywall:!0}))});import{z as Ve}from"zod";import{z as qa}from"zod";var Lc=qa.strictObject({eventsEnabled:qa.boolean(),experimentViewsEnabled:qa.boolean(),featureUsageEnabled:qa.boolean()}),l1=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function nf(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}import{z as $}from"zod";var zc=$.tuple([$.number().min(0).max(1),$.number().min(0).max(1)]).refine(([e,t])=>e<=t),qS=$.strictObject({attribute:$.string().optional(),seed:$.string(),hashVersion:$.literal(2),ranges:$.array(zc).max(100)}),US=$.strictObject({id:$.string().min(1).max(255),condition:Yt,gate:$.boolean().optional()}),BS=$.strictObject({key:$.string().optional(),name:$.string().optional(),passthrough:$.boolean().optional()}),rf={condition:Yt.optional(),parentConditions:$.array(US).max(100).optional(),weights:$.array($.number().min(0).max(1)).max(20).optional(),coverage:$.number().min(0).max(1).optional(),hashAttribute:$.string().optional(),fallbackAttribute:$.string().optional(),hashVersion:$.literal(2).optional(),disableStickyBucketing:$.boolean().optional(),bucketVersion:$.number().int().nonnegative().optional(),minBucketVersion:$.number().int().nonnegative().optional(),filters:$.array(qS).max(100).optional(),ranges:$.array(zc).max(20).optional(),meta:$.array(BS).max(20).optional(),seed:$.string().optional(),name:$.string().optional(),phase:$.string().optional()},wi=$.strictObject({...rf,key:$.string().min(1).max(255),variations:$.tuple([ve,ve]).rest(ve).refine(e=>e.length<=20),urlPatterns:$.array($.strictObject({include:$.boolean(),type:$.enum(["regex","simple"]),pattern:$.string()})).max(100).optional(),force:$.number().int().nonnegative().optional(),active:$.boolean().optional(),persistQueryString:$.boolean().optional()}),$c=$.strictObject({value:ve,variationId:$.number().int(),key:$.string(),name:$.string().optional(),bucket:$.number().optional(),passthrough:$.boolean().optional(),inExperiment:$.boolean(),hashUsed:$.boolean().optional(),hashAttribute:$.string(),hashValue:$.string(),featureId:$.string().nullable(),stickyBucketUsed:$.boolean().optional()}),VS=$.strictObject({...rf,id:$.string().max(255).optional(),force:ve.optional(),variations:$.array(ve).min(2).max(20).optional(),key:$.string().optional(),range:zc.optional(),tracks:$.array($.strictObject({experiment:wi,result:$c})).max(100).optional()}),LS=$.strictObject({defaultValue:ve.optional(),rules:$.array(VS).max(500).optional()}),mo=$.record($.string(),$.union([$.strictObject({type:$.literal("hashed"),attributeKey:$.string(),values:$.array($.string().regex(/^[a-f0-9]{64}$/))}),$.strictObject({type:$.literal("list"),attributeKey:$.string(),values:$.array($.union([$.string(),$.number()]))}),$.strictObject({type:$.literal("condition"),condition:Yt})])),yn=$.strictObject({scope:Ne,generation:$.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:$.iso.datetime({offset:!0}),expiresAt:$.iso.datetime({offset:!0}).nullable(),features:$.record($.string(),LS),savedGroups:mo,experiments:$.record($.uuid(),wi)});var fo=yn.extend({analyticsConfig:Lc,remoteFeatures:Ve.array(Ve.string().min(1).max(255)).max(500)}),Gc=fo.omit({evaluatedAt:!0,expiresAt:!0}).superRefine((e,t)=>{for(let n of e.remoteFeatures)Object.hasOwn(e.features,n)&&t.addIssue({code:"custom",path:["features",n],message:"Remote Feature definitions cannot be public"});for(let[n,r]of Object.entries(e.savedGroups))r.type==="list"&&t.addIssue({code:"custom",path:["savedGroups",n],message:"Raw Saved Group lists cannot be public"})}),of=Ve.strictObject({attributes:wt,features:Ve.array(Ve.string().min(1).max(255)).max(500).optional(),customerId:Ve.uuid().optional()}),zS=Ve.strictObject({value:ve,source:Ve.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:Ve.boolean(),off:Ve.boolean(),ruleId:Ve.string(),experimentResult:$c.optional()}),Ua=Ve.strictObject({generation:yn.shape.generation,evaluatedAt:yn.shape.evaluatedAt,expiresAt:yn.shape.expiresAt,features:Ve.record(Ve.string(),zS),merchandiseContext:Ve.strictObject({merchandiseId:Ve.uuid(),merchandise:wt}).optional()}),af=Ve.strictObject({customerId:Ve.uuid().optional(),events:Ve.array(Ve.strictObject({eventUuid:Ve.uuid(),timestamp:Ve.iso.datetime({offset:!0}),name:Ve.string().min(1).max(255),merchandise:Bd.optional(),properties:Ve.record(Ve.string(),ve).default({}),deviceId:Ve.string().min(1).max(255).optional(),sessionId:Ve.string().min(1).max(255).optional()})).min(1).max(100)}),sf=Ve.strictObject({inserted:Ve.number().int().nonnegative(),duplicates:Ve.number().int().nonnegative(),rejected:Ve.number().int().nonnegative(),skipped:Ve.number().int().nonnegative(),analyticsConfig:Lc});import{z as L}from"zod";import{z as $S}from"zod";var cf=$S.enum(["funnel-run/1","funnel-process/1"]),uf="funnel-process/1";function Kc(e,t=[]){let n=[];Gt(e,i=>{i.hidden&&n.push("Hidden components must not be delivered"),t.includes(i.type)&&n.push(`Node type ${i.type} cannot be delivered`)});let r=new Set(Sa(e).map(i=>i.key));for(let[i,a]of Object.entries(e.strings.locales))for(let o of Object.keys(a))r.has(o)||n.push(`Unused string ${o} must not be delivered (${i})`);return n}function lf(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>lf(t)??[])}}function GS(e){let t=e.pages.map(i=>{let a=lf(i.root);return a?.type==="stack"?{...i,root:a}:{...i,root:{type:"stack",id:i.root.id,...i.root.name===void 0?{}:{name:i.root.name},direction:"vertical",align:"stretch",justify:"start",children:[]}}}),n=new Set(Sa({pages:t}).map(i=>i.key)),r=Object.fromEntries(Object.entries(e.strings.locales).map(([i,a])=>[i,Object.fromEntries(Object.entries(a).filter(([o])=>n.has(o)))]));return{...e,pages:t,strings:{...e.strings,locales:r}}}function df(e,t=[]){let n=un.parse(structuredClone(GS(e))),r=a=>a.type!=="stack"||a.interaction!==void 0||a.children.some(r);for(let a of n.pages)if(!r(a.root))throw new Error(`Page ${a.id} has no visible content`);let i=Kc(n,t);if(i.length)throw new Error(i.join("; "));return n}import{z as Q}from"zod";import{z as M}from"zod";import{z as mt}from"zod";var Ba=mt.strictObject({schemaVersion:mt.literal(1),renderKey:mt.string().min(1).max(256),routeTemplate:mt.string().startsWith("/").max(2048),selectors:mt.array(mt.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:mt.array(mt.number().int().min(0)).min(1),absent:mt.array(mt.number().int().min(0))}).superRefine((e,t)=>{let n=[...e.present,...e.absent];(new Set(e.selectors).size!==e.selectors.length||new Set(n).size!==n.length||n.length!==e.selectors.length||n.some(r=>r>=e.selectors.length))&&t.addIssue({code:"custom",message:"Incomplete or ambiguous render signature"})}),pf=mt.strictObject({renderKey:mt.string().min(1).max(256),routeKey:mt.string().min(1).max(256),stateKey:mt.string().min(1).max(256),documentKey:mt.string().min(1).max(256),documentHash:mt.string().regex(/^[a-f0-9]{64}$/),compositionKey:mt.string().min(1).max(256),entryMode:mt.enum(["hard","soft"]),match:mt.strictObject({present:mt.array(mt.number().int().min(0)),absent:mt.array(mt.number().int().min(0))})});import{z as qr}from"zod";var KS=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],Hc="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",HS=qr.string().regex(new RegExp(`^${Hc}/${Hc}/${Hc}/manifest\\.json$`)),mf=qr.strictObject({kind:qr.literal("gcs-resumable"),url:qr.url(),bucket:qr.enum(KS),objectKey:HS,byteLength:qr.number().int().positive(),expiresAt:qr.iso.datetime()}).superRefine((e,t)=>{let n=new URL(e.url),r=n.searchParams,i=["uploadType","upload_id","name","upload_protocol","ifGenerationMatch"];(n.origin!=="https://storage.googleapis.com"||n.username||n.password||n.hash||n.pathname!==`/upload/storage/v1/b/${e.bucket}/o`||[...r.keys()].some(a=>!i.includes(a)||r.getAll(a).length!==1)||r.get("uploadType")!=="resumable"||!/^[A-Za-z0-9_-]{1,4096}$/.test(r.get("upload_id")??"")||r.has("name")&&r.get("name")!==`app-manifests/${e.objectKey}`||r.has("upload_protocol")&&r.get("upload_protocol")!=="resumable"||r.has("ifGenerationMatch")&&r.get("ifGenerationMatch")!=="0")&&t.addIssue({code:"custom",message:"Invalid IAM upload capability"})});var yt=M.string().min(1).max(256),dn=M.string().regex(/^[a-f0-9]{64}$/),Va=M.strictObject({versionId:M.uuid(),manifestDigest:dn,sourceGraphDigest:dn,pageKey:yt,stateKey:yt,documentKey:yt,documentHash:dn,elementKey:yt.optional(),nodeId:yt.optional(),contentHash:dn.optional(),renderKey:yt.optional()}),ff=M.strictObject({pageKey:yt,documentKey:yt,expectedDocumentHash:dn,renderKey:yt.optional(),nodeId:yt,elementKey:yt,expectedContentHash:dn,property:M.enum(["text","fontSize","color"]),value:M.union([M.string().max(4e3),M.number().finite()])}),gf=M.strictObject({versionId:M.uuid(),manifestDigest:dn,sourceGraphDigest:dn,pageKey:yt,stateKey:yt,documentKey:yt,documentHash:dn,renderKey:yt.optional(),patches:M.array(ff.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),QS=/^[a-z][a-z0-9-]{0,39}$/,go=M.string().regex(QS),Jc=M.enum(["web","ios","android"]),T1=M.discriminatedUnion("action",[M.strictObject({action:M.literal("register"),requestId:M.uuid(),client:go,platform:Jc,label:M.string().trim().min(1).max(100),sha256:dn,bytes:M.number().int().min(1),transferBytes:M.number().int().min(1)}),M.strictObject({action:M.literal("complete"),versionId:M.uuid()}),M.strictObject({action:M.literal("current"),versionId:M.uuid(),expectedCurrent:M.uuid().nullable()}),M.strictObject({action:M.literal("delivery"),enabled:M.boolean()}),M.strictObject({action:M.literal("changes"),versionId:M.uuid(),experimentId:M.uuid(),variationId:yt,changesetId:M.uuid().nullable(),expectedRevision:dn.nullable(),editorUrl:M.string().url().max(2048),patches:M.array(ff).max(200)})]),Zc=M.strictObject({id:M.uuid(),projectId:M.uuid(),environmentId:M.uuid(),clientKey:go,platform:Jc,label:M.string(),sha256:dn,bytes:M.number().int().positive(),objectKey:M.string(),state:M.enum(["uploading","ready","rejected"]),isCurrent:M.boolean(),revision:M.number().int().nonnegative(),createdAt:M.string(),expiresAt:M.string(),readyAt:M.string().nullable(),summary:M.record(M.string(),M.json()),routeTree:M.json().nullable(),validation:M.record(M.string(),M.json())}),JS=M.strictObject({key:go,platform:Jc,currentId:M.uuid().nullable()}),N1=M.strictObject({rows:M.array(Zc).max(100),nextCursor:M.uuid().nullable(),clients:M.array(JS).max(20)}),Qc=M.strictObject({storedBytes:M.number().int().nonnegative(),reservedBytes:M.number().int().nonnegative(),chargedBytes:M.number().int().nonnegative(),versions:M.number().int().nonnegative(),objects:M.number().int().nonnegative(),orphanObjects:M.number().int().nonnegative(),missingReadyObjects:M.number().int().nonnegative(),unknownObjectSizes:M.number().int().nonnegative(),byteLimit:M.number().int().positive(),versionLimit:M.number().int().positive(),remainingBytes:M.number().int().nonnegative()}),D1=M.strictObject({asOf:M.iso.datetime({offset:!0}),reclamation:M.literal("manual-review-required"),buckets:M.strictObject({source:Qc,runtime:Qc,previews:Qc})}),F1=M.strictObject({version:Zc,actorId:M.uuid(),claims:M.record(M.string(),M.json())}),M1=M.strictObject({version:Zc,upload:mf.nullable()}),q1=M.object({format:M.literal("indiana-route-state-index"),schemaVersion:M.literal(3),routes:M.array(M.object({routeKey:yt,path:M.string(),documentKey:yt,documentHash:dn,initialStateKey:yt,initialRenderKey:yt})),renders:M.array(pf)}).loose().superRefine((e,t)=>{(!e.renders||e.routes.some(n=>!e.renders?.some(r=>r.renderKey===n.initialRenderKey&&r.routeKey===n.routeKey&&r.documentKey===n.documentKey&&r.stateKey===n.initialStateKey&&r.documentHash===n.documentHash&&r.entryMode==="hard")))&&t.addIssue({code:"custom",message:"Incomplete render catalog"})}),U1=M.strictObject({rows:M.array(M.object({id:M.uuid(),name:M.string(),status:M.string(),variations:M.array(M.object({id:yt,key:yt,name:M.string().optional()}).loose())}).loose()),limited:M.boolean()}),B1=M.strictObject({enabled:M.boolean(),allowedOrigins:M.array(M.string())});import{z as Oi}from"zod";var hf=Oi.strictObject({id:Oi.uuid(),name:Oi.string().trim().min(1).max(80),client:go,source:Va,event:Oi.enum(["screen_enter","button_click"]),cooldownSeconds:Oi.number().int().min(0).max(2592e3),behavior:Oi.literal("observe")}).superRefine((e,t)=>{e.event==="button_click"&&(!e.source.nodeId||!e.source.elementKey)&&t.addIssue({code:"custom",path:["source"],message:"Choose a uniquely bound button"})});import{z as Ke}from"zod";var Wc=ve,ZS=["parameters","answers","results","variables"];function Yc(e){return ZS.some(t=>e===t||e.startsWith(t+"."))}function Xc(e){let t={};for(let[r,i]of Object.entries(Ia(e.declarations,e))){let a=r.split(".");if(a.some(c=>["__proto__","constructor","prototype"].includes(c)))throw new Error("Reserved result path");let o=t;for(let c of a.slice(0,-1)){Object.hasOwn(o,c)||(o[c]={});let u=o[c];if(!u||typeof u!="object"||Array.isArray(u))throw new Error("Ambiguous result path");o=u}let s=a.at(-1);if(s===void 0)throw new Error("Empty result path");o[s]=i}return{...Object.fromEntries(Object.entries(e.attributes).filter(([r])=>!Yc(r))),variables:t}}import{z as At}from"zod";var La=At.discriminatedUnion("kind",[At.object({kind:At.literal("ledger"),cursor:ga}).strict(),At.object({kind:At.literal("billing"),cursor:At.uuid()}).strict()]),WS=At.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),sr=At.record(At.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),At.union([At.string().max(500),At.boolean(),At.array(At.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),YS=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function eu(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>eu(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||YS.test(n)||eu(r,t+1)))}var XS=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,cr=At.record(WS,ve).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!eu(e)&&!XS.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var yf=At.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),za=At.array(At.object({variable:yf,componentId:yf,required:At.boolean()}).strict()).max(40).refine(e=>new Set(e.map(t=>t.variable)).size===e.length&&new Set(e.map(t=>t.componentId)).size===e.length,"Input bindings must be unique"),Y1=At.object({bindings:za,answers:sr,values:At.record(At.string(),ve).optional()}).strict();import{z as e0}from"zod";var $a=e0.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var tu=Ke.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Af=Ke.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),bf=cr.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),nu=Ke.record(tu,Ke.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),t0=Fn,xf=Ke.strictObject({type:Ke.literal("external_task"),endpointId:Ke.uuid(),taskKey:tu,inputs:Ke.record(tu,t0).refine(e=>Object.keys(e).length<=20),outputs:nu}),Sf=Ke.strictObject({maxAttempts:Ke.number().int().min(1).max(5),retryDelaySeconds:Ke.number().int().min(1).max(30),backoff:Ke.enum(["fixed","exponential"]),requestTimeoutSeconds:Ke.number().int().min(1).max(10),timeoutSeconds:Ke.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var cE=Ke.strictObject({outcome:Ke.enum(["success","failure"]),data:bf});var uE=Ke.discriminatedUnion("operation",[Ke.strictObject({operation:Ke.literal("signal"),runId:Ke.uuid(),nodeId:Af,eventName:$a,eventId:Ke.uuid(),data:bf}),Ke.strictObject({operation:Ke.literal("read_results"),runId:Ke.uuid()})]),lE=Ke.strictObject({scope:Ne,runId:Ke.uuid(),eventId:Ke.uuid(),accepted:Ke.boolean()}),n0=Ke.record(Af,Wc),dE=Ke.strictObject({scope:Ne,runId:Ke.uuid(),results:n0});var Rn={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},If="00000000-0000-0000-0000-000000000000";import{z as Z}from"zod";import{z as Ye}from"zod";var yE=Ye.enum(["local","remote"]),ru=Ye.strictObject({port:Ye.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:ve.optional(),sticky:Ye.array(Ye.strictObject({expected:$i.nullable(),next:$i})).max(100),exposures:Ye.array(ve).max(100),features:Ye.array(ve).max(100)}),vf=Ye.strictObject({type:Ye.literal("evaluate"),receiptId:Ye.uuid(),environmentId:Ye.uuid(),policyRevision:Ye.number().int().nonnegative(),attributes:wt,sticky:Ye.record(Ye.string(),$i)}),wf=vf.extend({runId:Ye.uuid(),versionId:Ye.uuid(),nodeId:Ye.string().min(1).max(64),visit:Ye.number().int().nonnegative(),revision:Ye.number().int().nonnegative()}),iu=vf.omit({type:!0,receiptId:!0}).extend({type:Ye.literal("evaluate_segment")}),Of=Ye.strictObject({nodeId:Ye.string().min(1).max(64),result:ru}),Pf=iu.extend({runId:Ye.uuid(),versionId:Ye.uuid(),nodeId:Ye.string().min(1).max(64),visit:Ye.number().int().nonnegative(),revision:Ye.number().int().nonnegative(),parameters:cr,answers:sr,variables:Ye.record(Ye.string(),ve)});import{z as ue}from"zod";var ou=ue.array(ue.string().trim().min(1).max(40).refine(e=>!e.includes(","),"\u6807\u7B7E\u4E0D\u80FD\u5305\u542B\u9017\u53F7")).max(20).refine(e=>new Set(e).size===e.length,"\u6807\u7B7E\u4E0D\u80FD\u91CD\u590D"),Ga=ue.intersection(wt,ue.looseObject({tags:ou.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),Ka=ue.string().trim().max(80),Ha=ue.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),Qa=ue.union([ue.email().max(254),ue.literal("")]),Ja=ue.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),Cf=ue.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),_f=ue.object({externalUserId:Cf.optional(),name:Ka.default(""),email:Qa.default(""),phone:Ha.optional(),attributes:Ga.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),Ur=ue.discriminatedUnion("type",[ue.strictObject({type:ue.literal("id"),value:ue.uuid()}),ue.strictObject({type:ue.literal("externalUserId"),value:Cf})]),Pi=ue.strictObject({name:Ka.optional(),email:Qa.optional(),phone:Ha.optional(),attributes:Ga.optional(),fingerprint:Ja.optional()}),Za=e=>!e.customerData||e.customer?.type==="externalUserId",Wa="customerData requires an externalUserId customer",Ci=ue.object({id:ue.uuid(),externalUserId:ue.string().min(1).max(255).nullable(),name:Ka,email:Qa,phone:Ha.optional(),attributes:Ga,createdAt:ue.iso.datetime()}).strict(),Ef=ue.object({customer:Ci,changed:ue.boolean(),replayed:ue.boolean()}).strict(),r0=ue.discriminatedUnion("type",[ue.object({type:ue.literal("id"),value:ue.uuid()}).strict(),ue.object({type:ue.literal("externalUserId"),value:ue.string().trim().min(1).max(255)}).strict()]),i0=ue.object({name:Ka.optional(),email:Qa.optional(),phone:Ha.optional(),attributes:Ga.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:ue.array(ue.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:ue.strictObject({add:ou,remove:ou}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),au=ue.object({lookup:r0}).strict(),Rf=au.extend({requestId:ue.uuid(),patch:i0}).strict(),kf=ue.object({search:ue.string().trim().max(200).default(""),tag:ue.string().trim().max(40).default(""),planId:ue.string().max(200).default(""),versionId:ue.string().max(200).default(""),holdingStatus:ue.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:ue.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:ue.union([ue.iso.datetime(),ue.literal("")]).default(""),createdUntil:ue.union([ue.iso.datetime(),ue.literal("")]).default(""),offset:ue.coerce.number().int().min(0).max(1e5).default(0),limit:ue.coerce.number().int().min(1).max(100).default(50)}).strict(),jf=ue.object({customers:Ci.array(),hasMore:ue.boolean(),total:ue.number().int().nonnegative().nullable(),evaluatedAt:ue.iso.datetime()}).strict();var ho=Z.discriminatedUnion("type",[Z.strictObject({type:Z.literal("literal"),value:ve}),Z.strictObject({type:Z.literal("variable"),key:It,path:En.optional()}),Z.strictObject({type:Z.literal("feature"),featureKey:Z.string().min(1).max(128)})]),o0=Z.strictObject({requestId:Z.uuid(),decisionId:Z.uuid(),customerId:Z.uuid(),externalUserId:Z.string().min(1).max(255).nullable(),versionId:Z.uuid(),receiptId:Z.uuid(),value:ve}),a0={funnelId:Z.uuid(),requestId:Z.uuid(),customer:Ur,customerData:Pi.optional(),attributes:wt.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},EE=Z.discriminatedUnion("operation",[Z.strictObject({operation:Z.literal("decide"),...a0}).refine(Za,Wa),Z.strictObject({operation:Z.literal("read_decision"),decisionId:Z.uuid()}),Z.strictObject({operation:Z.literal("evaluate_decision"),decisionId:Z.uuid(),requestId:Z.uuid(),nodeId:Z.string().min(1).max(64),visit:Z.number().int().nonnegative(),revision:Z.number().int().nonnegative(),receiptId:Z.uuid(),policyRevision:Z.number().int().nonnegative(),generation:Z.string().min(1).max(256),result:ru}),Z.strictObject({operation:Z.literal("feature_config"),funnelId:Z.uuid()}),Z.strictObject({operation:Z.literal("commit_decision_segment"),decisionId:Z.uuid(),requestId:Z.uuid(),nodeId:Z.string().min(1).max(64),visit:Z.number().int().nonnegative(),revision:Z.number().int().nonnegative(),policyRevision:Z.number().int().nonnegative(),generation:Z.string().min(1).max(256),steps:Z.array(Of).max(32),boundary:Z.strictObject({nodeId:Z.string().min(1).max(64),visit:Z.number().int().nonnegative()}).optional()}),Z.strictObject({operation:Z.literal("segment_configuration"),funnelId:Z.uuid(),versionId:Z.uuid()}),Z.strictObject({operation:Z.literal("configuration"),funnelId:Z.uuid(),versionId:Z.uuid().optional()}),Z.strictObject({operation:Z.literal("local_configuration"),funnelId:Z.uuid()}),Z.strictObject({operation:Z.literal("report_used"),decisionId:Z.uuid(),eventId:Z.uuid(),occurredAt:Z.iso.datetime({offset:!0}),reference:Z.string().min(1).max(128).optional()})]),RE=Z.strictObject({scope:Ne,decisionId:Z.uuid(),requestId:Z.uuid(),status:Z.enum(["pending","completed","failed"]),decision:o0.nullable(),evaluation:Z.discriminatedUnion("type",[wf,Pf]).optional()}).refine(e=>e.status==="completed"==(e.decision!==null)&&(!e.decision||e.decision.decisionId===e.decisionId&&e.decision.requestId===e.requestId),"Completed decisions carry their committed result"),kE=Z.strictObject({scope:Ne,decisionId:Z.uuid(),eventId:Z.uuid(),source:Z.literal("caller_reported")});import{z as Mt}from"zod";var Tf=Mt.strictObject({type:Mt.literal("bundle"),paywall:Fn.optional(),offering:Fn.optional(),coupons:Fn,data:Fn}),s0=e=>Mt.strictObject({type:Mt.literal(e),id:Mt.uuid()}),ME=Mt.strictObject({type:Mt.literal("bundle"),paywallVersionId:Mt.uuid().optional(),offeringVersionId:Mt.uuid().optional(),couponIds:Mt.array(Mt.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:ve});var qE=Mt.strictObject({type:Mt.literal("bundle"),offering:s0("offering_version").nullable(),paywall:Mt.strictObject({versionId:Mt.uuid(),paywallId:Mt.uuid(),offeringVersionId:Mt.uuid()}).nullable(),coupons:Mt.array(Gi).max(20),data:ve});import{z as kn}from"zod";import{z as An}from"zod";var Nf=An.union([An.string(),An.number().finite(),An.boolean(),An.null()]),c0=An.union([Nf,An.array(Nf).min(1).max(20)]),u0=An.record(En,c0).refine(e=>Object.keys(e).length<=10),Df=An.strictObject({path:En,type:An.enum(["string","number","boolean","strings"]),nullable:An.boolean().optional(),aggregation:An.enum(["count","exists"]).optional(),where:u0.optional()}).superRefine((e,t)=>{(e.aggregation==="count"&&e.type!=="number"||e.aggregation==="exists"&&e.type!=="boolean"||!e.aggregation&&e.where)&&t.addIssue({code:"custom",message:"Collection summaries require their matching type"})});var l0=["sendMessage","checkEntitlement","resolveOffering","readHoldings","readLedger","readBillingInvoice","readCreditStatement","previewAttach","attach","readSubscriptionOperation","previewUpdate","update","readSubscriptionUpdate","setupPayment","readPaymentSetup","verifySubscriptions","previewRefund","refund","readRefund","restoreNativePurchase","readBillingControls","prepareBillingAuthorization","confirmBillingAuthorization","setBillingCoupons","revokeBillingAuthorization","listBillingInvoices","confirmBillingAdjustment","manageBillingLimits","readSeats","manageSeat","quoteBalance","mutateBalance","trackUsage","readUsage","setUsage","adjustBalance","readBalanceSource","manageBalanceGrant","listBalanceGrants","manageUsageEntity","readUsageAnalytics","readCreditAnalytics","submitUsageBatch","readUsageBatch","redeemCoupon","listOffers","grantOffer","redeemReward","createReferralCode","claimRewardProduct"],Ff=kn.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),d0=Fn,Mf=kn.discriminatedUnion("type",[xf,kn.strictObject({type:kn.literal("claim_offer"),coupon:Fn}),kn.strictObject({type:kn.literal("event"),event:Ff}),kn.strictObject({type:kn.literal("api"),operation:kn.enum(l0),inputs:kn.record(En,d0).refine(e=>Object.keys(e).length<=40),outputs:kn.record(Ff,Df).refine(e=>Object.keys(e).length<=20)})]);var ut=$a,p0=Q.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),pn={id:ut,name:Q.string().trim().min(1).max(80),position:Q.strictObject({x:Q.number().finite(),y:Q.number().finite()}).optional()},m0={success:ut,cancel:ut,unavailable:ut,failure:ut},su=Q.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),cu=Q.enum(["same_window","new_window"]),f0=Q.discriminatedUnion("type",[Q.strictObject({...pn,type:Q.literal("entry"),next:ut,triggers:Q.array(hf).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),Q.strictObject({...pn,type:Q.literal("screen"),screenId:ut,presentation:Pn,outputs:Q.record(ut,ut),offering:Q.discriminatedUnion("source",[Q.strictObject({source:Q.literal("variable"),key:It}),Q.strictObject({source:Q.literal("fixed"),versionId:Q.uuid()})]).optional()}),Q.strictObject({...pn,type:Q.literal("offering"),configuration:Q.discriminatedUnion("source",[Q.strictObject({source:Q.literal("fixed"),versionId:Q.uuid()}),Q.strictObject({source:Q.literal("feature"),featureKey:Q.string().min(1).max(128)})]),writes:Q.strictObject({value:It}),next:ut}),Q.strictObject({...pn,type:Q.literal("coupon"),couponId:Q.uuid(),writes:Q.strictObject({value:It}),next:ut}),Q.strictObject({...pn,type:Q.literal("coupons"),couponIds:Q.array(Q.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:Q.strictObject({value:It}),next:ut}),Q.strictObject({...pn,type:Q.literal("output"),value:Q.discriminatedUnion("type",[...ho.options,Tf,Q.strictObject({type:Q.literal("selection"),screenId:ut,offeringKey:It})])}),Q.strictObject({...pn,type:Q.literal("condition"),cases:Q.array(Q.strictObject({condition:Yt,target:ut})).min(1).max(50),default:ut}),Q.strictObject({...pn,type:Q.literal("feature"),featureKey:Q.string().min(1).max(128),writes:Q.strictObject({value:It}),next:ut}),Q.strictObject({...pn,type:Q.literal("split"),experimentId:Q.uuid(),applyPageExperiment:Q.literal(!0).optional(),routes:Q.record(p0,ut).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:ut}),Q.strictObject({...pn,type:Q.literal("action"),...m0,execution:Sf,action:Mf,writes:wc.optional()}),Q.strictObject({...pn,type:Q.literal("external_page"),appManifest:Va.optional(),url:su,openIn:cu,opened:ut,failed:ut}),Q.strictObject({...pn,type:Q.literal("end"),outcome:Q.enum(["completed","closed","ineligible","failed"]),output:ho.optional()}),Q.strictObject({...pn,type:Q.literal("wait"),writes:wc.optional(),wait:Q.discriminatedUnion("type",[Q.strictObject({type:Q.literal("duration"),delaySeconds:Q.number().int().min(1).max(2592e3),elapsed:ut}),Q.strictObject({type:Q.literal("event"),eventName:ut,outputs:nu,timeoutSeconds:Q.number().int().min(1).max(2592e3),received:ut,timeout:ut})])})]),uu=Q.strictObject({version:Q.literal(5),entry:ut,nodes:Q.array(f0).min(1).max(Rn.flowNodes)}),lu=uu.superRefine((e,t)=>{g0(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function Ya(e){switch(e.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":return[e.next];case"screen":return Object.values(e.outputs);case"condition":return[...e.cases.map(t=>t.target),e.default];case"split":return[...Object.values(e.routes),e.notParticipating];case"action":return[e.success,e.cancel,e.unavailable,e.failure];case"external_page":return[e.opened,e.failed];case"end":case"output":return[];case"wait":return e.wait.type==="duration"?[e.wait.elapsed]:[e.wait.received,e.wait.timeout]}}function g0(e,t){let n=[],r=new Map(e.nodes.map(l=>[l.id,l])),i=(l,m,f)=>{n.push(l),t?.({message:l,reason:m,path:f?["nodes",e.nodes.indexOf(f)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(l=>l.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(l=>l.type==="screen").length>Rn.pages||e.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>Rn.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let l of e.nodes){for(let m of Ya(l))m===e.entry&&i("An entry cannot be a transition target","entryTarget",l),r.has(m)||i(`Missing target ${m}`,"missingTarget",l);l.type==="screen"&&(a.has(l.screenId)&&i("Every screen has exactly one node owner","screenOwner",l),a.add(l.screenId))}let o=new Set,s=new Set,c=new Set;function u(l){if(o.has(l)){i("Flow edges must not form a cycle","cycle",r.get(l));return}if(!(s.has(l)||!r.has(l))){o.add(l),c.add(l);for(let m of Ya(r.get(l)))u(m);o.delete(l),s.add(l)}}u(e.entry);for(let l of e.nodes)c.has(l.id)||i("Every node must be reachable from Entry","unreachable",l);return[...new Set(n)]}var du={maxTransitions:1e4,runTimeoutSeconds:2592e3};function qf(e,t,n){let r=[...t].sort((s,c)=>c.length-s.length),i=new Set,a=(s,c=!1)=>{let u=r.find(l=>s===l||c&&s.startsWith(l+"."));i.add(u??s)};if(e.type==="condition"){let s=n?.startsWith("case_")?Number(n.slice(5)):e.cases.length-1;for(let c of e.cases.slice(0,s+1))for(let u of tr(c.condition))u.startsWith("variables.")&&a(u.slice(10),!0)}if(e.type==="screen"&&e.offering?.source==="variable"&&a(e.offering.key),e.type==="action"&&(e.action.type==="api"||e.action.type==="external_task"))for(let s of Object.values(e.action.inputs))s.source==="variable"&&a(s.key);e.type==="action"&&e.action.type==="claim_offer"&&e.action.coupon.source==="variable"&&a(e.action.coupon.key);let o=e.type==="output"?e.value:e.type==="end"?e.output:null;if(o?.type==="variable"&&a(o.key),o?.type==="bundle")for(let s of[o.paywall,o.offering,o.coupons,o.data])s?.source==="variable"&&a(s.key);return o?.type==="selection"&&a(o.offeringKey),[...i]}import{z as q}from"zod";var _i=q.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Xa=e=>q.record(q.string(),ve).refine(t=>ln(t)<=e,"Funnel evidence exceeds its byte budget"),gR=q.enum(["local_segment","evaluation","presentation","timer","event","operation"]),mu=q.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),fu=q.discriminatedUnion("type",[q.strictObject({type:q.literal("flag"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("experiment"),id:q.uuid()}),q.strictObject({type:q.literal("saved_group"),id:q.uuid()}),q.strictObject({type:q.literal("config"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("constant"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("paywall_version"),id:q.uuid()}),q.strictObject({type:q.literal("offering_version"),id:q.uuid()}),q.strictObject({type:q.literal("reward"),id:q.uuid()})]),yo=q.strictObject({schemaVersion:q.literal(1),kind:mu,selector:fu.nullable(),context:Xa(131072),contract:q.strictObject({version:q.number().int().positive(),evaluator:q.string().min(1).max(128),policyRevision:q.number().int().nonnegative()})}).refine(e=>ln(e)<=131072,"Node input exceeds its byte budget"),Uf=q.strictObject({schemaVersion:q.literal(1),kind:mu,outcome:q.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:Xa(131072),route:q.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:Xa(131072)}).refine(e=>ln(e)<=131072,"Node result exceeds its byte budget"),hR=q.strictObject({schemaVersion:q.literal(1),operations:q.record(_i,q.strictObject({attempts:q.number().int().nonnegative(),maxAttempts:q.number().int().min(1).max(5),deadlineAt:q.iso.datetime({offset:!0}),retryAt:q.iso.datetime({offset:!0}).nullable(),error:q.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:q.strictObject({type:_i,id:q.uuid()}).nullable()}))}).refine(e=>ln(e)<=65536,"Execution state exceeds its byte budget"),Br={receiptId:q.uuid()},pu=q.iso.datetime({offset:!0}),yR=q.discriminatedUnion("type",[q.strictObject({type:q.literal("node_entered"),details:q.strictObject({kind:mu})}),q.strictObject({type:q.literal("presentation_shown"),details:q.strictObject({...Br,source:q.literal("client"),occurredAt:pu.optional()})}),q.strictObject({type:q.literal("decision_accepted"),details:q.strictObject(Br)}),q.strictObject({type:q.literal("signal_received"),details:q.strictObject({signalId:q.uuid(),nodeId:_i,eventName:_i,data:Xa(8192),source:q.literal("server"),occurredAt:pu})}),q.strictObject({type:q.literal("signal_consumed"),details:q.strictObject({...Br,signalId:q.uuid()})}),q.strictObject({type:q.literal("wait_elapsed"),details:q.strictObject(Br)}),q.strictObject({type:q.literal("wait_timeout"),details:q.strictObject(Br)}),q.strictObject({type:q.literal("operation_completed"),details:q.strictObject({...Br,operation:_i,reference:q.strictObject({type:_i,id:q.uuid()}).nullable()})}),q.strictObject({type:q.literal("execution_recovered"),details:q.strictObject({generation:q.number().int().positive(),reason:q.enum(["interrupted","expired_lease","delivery_failed"])})}),q.strictObject({type:q.literal("execution_failed"),details:q.strictObject({generation:q.number().int().positive(),code:q.string().regex(/^[a-z_]{1,64}$/)})}),q.strictObject({type:q.literal("run_completed"),details:q.strictObject({outcome:q.enum(["completed","ineligible","failed"])})}),q.strictObject({type:q.literal("run_closed"),details:q.strictObject({source:q.enum(["client","server","expiry"])})}),q.strictObject({type:q.literal("treatment_used"),details:q.strictObject({...Br,source:q.enum(["client","server"]),occurredAt:pu,reference:q.string().min(1).max(128).optional()})})]);var bn=L.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),h0=L.discriminatedUnion("type",[L.strictObject({id:bn,type:L.literal("owned"),publicData:tf.optional(),document:un.refine(e=>["page","popup","onboarding"].includes(e.surface)&&e.pages.length===1&&e.actions.every(t=>t.type==="event"&&!t.close),"A Funnel owns one Page or Popup per screen and emits outputs; Paywall owns its purchase policies")}),L.strictObject({id:bn,type:L.literal("paywall"),paywallVersionId:L.uuid()})]),gu={executionContract:cf.optional(),kind:L.literal("funnel"),schemaVersion:L.literal(4),screens:L.array(h0).max(Rn.pages),references:L.record(bn,fu).refine(e=>Object.keys(e).length<=500),inputs:L.array(L.strictObject({variable:bn,screenId:bn,componentId:bn,required:L.boolean()})).max(Rn.questions),variables:L.record(It,mi).refine(e=>Object.keys(e).length<=Rn.logicNodes),outputSchema:pi,execution:L.strictObject({runTimeoutSeconds:L.number().int().min(1).max(du.runTimeoutSeconds),maxTransitions:L.number().int().min(1).max(du.maxTransitions)})},MR=L.strictObject({...gu,graph:uu});function y0(e,t){let n=!1,r=(i,a)=>{let o=i.type==="stack"||i.type==="button"?i.bind?.coupon??a:a;i.type==="text"&&Object.values(e.strings.locales).some(s=>s[i.text]?.includes("{{offer."))&&!(o&&t(o))&&(n=!0),i.type==="stack"&&i.children.forEach(s=>r(s,o))};for(let i of e.pages)r(i.root);return n}function ts(e){return Array.isArray(e)?e.some(ts):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===If:ts(n))}function A0(e){let t=[],n=new Set(Object.values(e.references).flatMap(r=>r.type==="reward"?[r.id]:[]));for(let[r,i]of e.screens.entries()){if(i.type!=="owned")continue;let a;try{a=df(i.document)}catch(o){t.push({message:o instanceof Error?o.message:"Screen cannot be delivered",reason:"screen",path:["screens",r,"document"]});continue}for(let[o,s]of e.inputs.entries())s.screenId===i.id&&!co(a,s.componentId)&&t.push({message:`Local Funnel input ${s.variable} targets hidden component ${s.componentId} on screen ${s.screenId}`,reason:"inputBinding",path:["inputs",o]})}for(let[r,i]of e.graph.nodes.entries()){let a=["graph","nodes",r],o=i.type==="screen"?e.screens.find(s=>s.id===i.screenId):void 0;o?.type==="owned"&&(o.document.actions.some(s=>typeof s.properties.templateKey=="string"&&s.properties.templateKey.startsWith("popup-coupon-"))&&t.push({message:"Funnel screens claim Coupons through a Claim Coupon step",reason:"coupon",path:a}),y0(o.document,s=>n.has(s))&&t.push({message:"Offer copy shows the Coupon of a Claim Coupon step",reason:"coupon",path:a})),(i.type==="output"&&i.value.type==="literal"&&ts(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&ts(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function Bf(e,t){for(let{message:n,reason:r,path:i}of A0(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function Vf(e,t){let n=(g,d,h=[])=>t.addIssue({code:"custom",message:g,path:h,params:{reason:d}}),r=Object.values(e.references),i=new Map(e.screens.map(g=>[g.id,g])),a=(g,d)=>r.some(h=>h.type===g&&("id"in h?h.id:h.key)===d);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let o=e.graph.nodes.filter(g=>g.type==="screen");(o.length!==i.size||o.some(g=>!i.has(g.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(g=>c.some(d=>g!==d&&d.startsWith(g+".")))&&n("Variable paths must not overlap","variable");function u(g,d){Object.hasOwn(e.variables,g)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(d)]);let h=s.get(g)??new Set;h.add(d.id),s.set(g,h)}for(let[g,d]of e.graph.nodes.entries()){let h=["graph","nodes",g],R=d.type==="feature"?d.featureKey:d.type==="offering"&&d.configuration.source==="feature"?d.configuration.featureKey:d.type==="output"&&d.value.type==="feature"?d.value.featureKey:d.type==="end"&&d.output?.type==="feature"?d.output.featureKey:null;R&&!a("flag",R)&&n("Flag selectors require an explicit GB resource reference","feature",h);let y=d.type==="feature"||d.type==="offering"||d.type==="coupon"||d.type==="coupons"||d.type==="action"&&d.action.type==="api"?["value"]:d.type==="action"&&d.action.type==="external_task"?Object.keys(d.action.outputs):d.type==="wait"&&d.wait.type==="event"?Object.keys(d.wait.outputs):[],A="writes"in d?d.writes??{}:{};(y.length!==Object.keys(A).length||y.some(v=>!Object.hasOwn(A,v))||new Set(Object.values(A)).size!==Object.values(A).length)&&n("Node writes must map every named output exactly once","variable",h);for(let[v,P]of Object.entries(A)){u(P,d);let j=e.variables[P],_=d.type==="offering"?"offering_version":d.type==="coupon"?"reward":d.type==="action"&&d.action.type==="api"?"json":d.type==="action"&&d.action.type==="external_task"?d.action.outputs[v]:d.type==="wait"&&d.wait.type==="event"?d.wait.outputs[v]:void 0;(j?.source.type!=="node"||_&&j.type!==_)&&n("Node writer source or output type does not match declaration","variable",h)}if(d.type==="coupons"){let v=e.variables[d.writes.value];(v?.type!=="array"||v.items?.type!=="reward"||v.items.nullable||v.nullable)&&n("Coupons output requires a non-null Reward array","variable",h);for(let P of d.couponIds)a("reward",P)||n("Coupons require Reward references","coupon",h)}if(d.type==="split"&&!a("experiment",d.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",h),d.type==="coupon"&&!a("reward",d.couponId)&&n("Coupon selectors require a Reward reference","coupon",h),d.type==="action"&&d.action.type==="claim_offer"&&d.action.coupon.source==="literal"){let v=d.action.coupon.value;(!v||typeof v!="object"||Array.isArray(v)||v.type!=="reward"||typeof v.id!="string"||Object.keys(v).length!==2||!a("reward",v.id))&&n("Coupon claims require a Reward reference","coupon",h)}if(d.type==="offering"&&d.configuration.source==="fixed"&&!a("offering_version",d.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",h),d.type==="screen"&&d.offering?.source==="variable"&&e.variables[d.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",h),d.type==="action"&&d.action.type==="claim_offer"&&d.action.coupon.source==="variable"&&(e.variables[d.action.coupon.key]?.type!=="reward"||d.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",h),d.type==="screen"){let v=i.get(d.screenId);if(d.offering?.source==="fixed"&&!a("offering_version",d.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",h),v?.type==="paywall"&&d.offering&&n("Paywall owns its fixed Offering Version","offering",h),v?.type==="paywall"&&!a("paywall_version",v.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",h),v?.type==="owned"){let P=v.document.pages[0];if(!P){n("Owned screen requires a page","screen",h);continue}or(v.document).some(_=>!_.complete)&&n("Owned screens require complete local content","translations",h);let j=new Set(v.document.actions.map(_=>_.id));(j.size!==Object.keys(d.outputs).length||Object.keys(d.outputs).some(_=>!j.has(_)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",h),Zn(P.root,_=>{!d.offering&&(_.type==="plan_picker"||(_.type==="stack"||_.type==="button")&&_.bind?.plan||_.type==="customer_data"&&["customer_plans","credit_packs"].includes(_.data.source))&&n("Product presentation requires an Offering Version","offering",h),_.type==="customer_data"&&Object.values(_.data.outputs??{}).some(X=>X!==void 0&&!j.has(X))&&n("Customer components require declared screen outcomes","componentOutput",h)})}}d.type==="end"&&["completed","ineligible"].includes(d.outcome)&&!d.output&&n("Completed and ineligible ends require a declared output","output",h),d.type==="end"&&d.output?.type==="literal"&&!hn(e.outputSchema,d.output.value)&&n("Terminal output does not match outputSchema","output",h),d.type==="output"&&d.value.type==="literal"&&!hn(e.outputSchema,d.value.value)&&n("Terminal output does not match outputSchema","output",h);let x=d.type==="output"?d.value:d.type==="end"?d.output:void 0;if(x?.type==="variable"&&!x.path){let v=e.variables[x.key];v&&!Oc(v,e.outputSchema)&&n("Variable output does not match outputSchema","output",h)}if(d.type==="screen"){let v=i.get(d.screenId);if(v?.type==="owned")for(let P of _c(v.document))(/^(input|params)\./.test(P)||P.startsWith("variables.")&&!Cc(P.slice(10),c))&&n("Screen values must reference registered variables","variable",h)}if(d.type==="condition")for(let v of d.cases){for(let P of Hn(v.condition))a("saved_group",P)||n("Conditions require explicit Saved Group references","savedGroup",h);for(let P of tr(v.condition))P.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",h)}if(d.type==="output"&&d.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",h);for(let[v,P]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let j=d.value[v];if(j)if(j.source==="literal"){let _=v==="coupons"?j.value:[j.value];(!Array.isArray(_)||_.length>20||_.some(X=>!hn({type:P,nullable:!1},X)||!a(P,X.id))||v==="coupons"&&new Set(_.map(X=>X.id)).size!==_.length)&&n("Bundle requires distinct scoped resource references",v==="coupons"?"coupon":v==="paywall"?"paywall":"offering",[...h,"value",v])}else{let _=e.variables[j.key];(j.path||!_||_.nullable||(v==="coupons"?_.type!=="array"||_.items?.type!=="reward"||_.items.nullable:_.type!==P))&&n("Bundle binding type does not match its slot","output",h)}}}}for(let[g,d]of e.graph.nodes.entries()){let h=d.type==="screen"?i.get(d.screenId):void 0,R=[...qf(d,c),...h?.type==="owned"?va(h.document).map(y=>Cc(y,c)?.key??y):[]];for(let y of new Set(R)){let P=function(j){if(j===d.id)return!0;if(v.has(j))return!1;v.add(j);let _=e.graph.nodes.find(le=>le.id===j);return _?(x.has(j)?_.type==="action"?[_.cancel,_.unavailable,_.failure]:_.type==="wait"&&_.wait.type==="event"?[_.wait.timeout]:[]:Ya(_)).some(P):!1};var f=P;if(!Object.hasOwn(e.variables,y)){n("Consumed variable is undeclared","variable",["graph","nodes",g]);continue}let A=e.variables[y];if(d.type==="screen"&&A.source.type==="input"&&e.inputs.some(j=>j.screenId===d.screenId&&j.variable===y)||A.source.type==="parameter"||A.source.type==="attribute")continue;let x=A.source.type==="input"?new Set(e.inputs.filter(j=>j.variable===y&&j.required).flatMap(j=>o.filter(_=>_.screenId===j.screenId).map(_=>_.id))):s.get(y)??new Set,v=new Set;(!x.size||P(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",g])}}(new Set(e.inputs.map(g=>g.variable)).size!==e.inputs.length||new Set(e.inputs.map(g=>`${g.screenId}:${g.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[g,d]of e.inputs.entries()){e.variables[d.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",g]);let h=i.get(d.screenId),R=h?.type==="owned"?co(h.document,d.componentId):null;if((R?.type!=="stack"||!R.interaction||!["input","toggle","select","multiselect","tabs"].includes(R.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",g]),R?.type==="stack"&&R.interaction){let y=R.interaction.type==="toggle"?"boolean":R.interaction.type==="multiselect"?"strings":"string";e.variables[d.variable]?.type!==y&&n("Input variable type does not match component","inputBinding",["inputs",g]);let A=e.variables[d.variable]?.enum;A&&!R.children.filter(x=>!x.hidden).every(x=>A.includes(x.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",g])}}for(let[g,d]of Object.entries(e.variables))d.enum&&d.type!=="string"&&n("Only string variables support enum","variable",["variables",g]),d.source.type==="input"&&!e.inputs.some(h=>h.variable===g)&&n("Input variable requires a component binding","inputBinding",["variables",g]);let l=0,m=0;for(let g of e.screens)if(g.type==="owned"){for(let d of g.document.pages)Zn(d.root,()=>{l++});m+=g.document.actions.length}(l>Rn.components||m>Rn.actions||ln(e)>Rn.documentBytes)&&n("Funnel document exceeds its budget","budget")}var b0=L.strictObject({...gu,graph:lu}).superRefine(Vf),Ei=L.strictObject({...gu,graph:lu,displayName:L.string().trim().min(1).max(80)}).superRefine(Vf),qR=Ei.superRefine(Bf),UR=b0.superRefine(Bf),es=L.string().regex(kt),Ao={requestId:L.uuid(),nodeId:bn,visit:L.number().int().nonnegative(),revision:L.number().int().nonnegative(),customerToken:es.optional()},x0=L.discriminatedUnion("type",[L.strictObject({type:L.literal("screen"),output:bn,answers:sr,selection:L.record(bn,L.union([L.string().max(200),L.boolean(),L.number().int().min(0).max(1e4)])).optional()}),L.strictObject({type:L.literal("paywall_quote"),featureQuantities:L.record(L.uuid(),L.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100).optional(),actionId:bn,productVersionId:L.uuid(),offerId:L.uuid().optional(),nativeOffer:hi.optional(),predecessor:L.strictObject({operationId:L.uuid().nullable(),generation:L.number().int().positive()}).optional()}),L.strictObject({type:L.literal("paywall_confirm"),operationId:L.uuid()}),L.strictObject({type:L.literal("paywall_cancel"),operationId:L.uuid()}),L.strictObject({type:L.literal("client_action"),receiptId:L.uuid(),outcome:L.enum(["success","cancel","failure","opened","failed"])})]),S0=L.object({nodeId:bn,visit:L.number().int().nonnegative(),revision:L.number().int().nonnegative(),components:L.record(bn,L.object({resourceKey:L.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:L.number().int().min(1).max(1e5),after:La.nullable(),filter:L.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),Ot=L.discriminatedUnion("operation",[L.strictObject({operation:L.literal("start"),funnelId:L.uuid(),requestId:L.uuid(),customer:Ur.optional(),customerData:Pi.optional(),locale:L.string().min(1).max(35),parameters:cr}).refine(Za,Wa),L.strictObject({operation:L.literal("get"),settlementRequestId:L.uuid().optional(),data:S0.optional(),purchase:L.strictObject({receiptId:L.uuid(),operationId:L.uuid()}).optional(),customerToken:es.optional()}),L.strictObject({operation:L.literal("resume"),requestId:L.uuid(),customerToken:es.optional()}),L.strictObject({operation:L.literal("submit"),...Ao,input:x0}),L.strictObject({operation:L.literal("back"),...Ao}),L.strictObject({operation:L.literal("shown"),...Ao}),L.strictObject({operation:L.literal("close"),...Ao}),L.strictObject({operation:L.literal("commit_segment"),...Ao,policyRevision:L.number().int().nonnegative(),generation:L.string().min(1).max(256)}),L.strictObject({operation:L.literal("review"),receiptId:L.uuid().optional(),customerToken:es.optional()})]);function ns(e,t){let n=new Set,r=new Set,i=new Set,a=[],o=new Map,s=new Map,c=new Map;function u(d){for(let h of Hn(d))l(h)}function l(d){if(i.has(d)||!Object.hasOwn(t.savedGroups,d))return;let h=t.savedGroups[d];h&&(i.add(d),c.set(d,h),a.push(()=>{!Array.isArray(h)&&h.type==="condition"&&u(h.condition)}))}function m(d){for(let h of["hashAttribute","fallbackAttribute"])if(d[h]!==void 0&&Yc(d[h]))throw new Error(`Funnel GB ${h} uses a reserved flow namespace`);u(d.condition);for(let h of d.parentConditions??[])f(h.id),u(h.condition)}function f(d,h=!1){let R=Object.hasOwn(t.features,d)?t.features[d]:void 0;if(!R){if(h)throw new Error("Required GB Feature is unavailable");return}n.has(d)||(n.add(d),o.set(d,R),a.push(()=>{for(let y of R.rules??[]){m(y);for(let A of y.tracks??[])m(A.experiment)}}))}function g(d){let h=Object.hasOwn(t.experiments,d)?t.experiments[d]:void 0;if(!h)throw new Error("Required GB Experiment is unavailable");r.has(d)||(r.add(d),s.set(d,h),a.push(()=>m(h)))}for(let d of e.graph.nodes){d.type==="feature"&&f(d.featureKey,!0),d.type==="split"&&g(d.experimentId),d.type==="condition"&&d.cases.forEach(R=>u(R.condition)),d.type==="offering"&&d.configuration.source==="feature"&&f(d.configuration.featureKey,!0);let h=d.type==="output"?d.value:d.type==="end"?d.output:null;h?.type==="feature"&&f(h.featureKey,!0)}for(let d of a)d();return{...t,features:Object.fromEntries(o),experiments:Object.fromEntries(s),savedGroups:Object.fromEntries(c)}}import{z as ae}from"zod";function Lf(e,t){let n=[],r={};Gt(e,i=>{if(i.hidden)return!1;if(i.type!=="quantity_picker")return;let a=i.bind?.plan?[i.bind.plan]:[];i.bind?.picker&&Gt(e,o=>{if(o.type==="plan_picker"&&o.id===i.bind?.picker&&a.push(...o.planIds??[]),o.type==="stack"&&o.interaction?.type==="select"&&o.interaction.pickerId===i.bind?.picker)for(let s of o.children)s.type==="stack"&&s.bind?.plan&&a.push(s.bind.plan)}),a.length||n.push(`Quantity control ${i.id} needs a Product binding`);for(let o of new Set(a)){let s=t[o]?.prepaid?.find(u=>u.internalFeatureId===i.internalFeatureId)?.terms,c=r[o]??(r[o]=new Set);(!s||c.has(i.internalFeatureId)||i.minimumQuantity<s.minimumQuantity||i.maximumQuantity>s.maximumQuantity)&&n.push(`Quantity control ${i.id} must match its Product's prepaid Feature and bounds`),c.add(i.internalFeatureId)}});for(let[i,a]of Object.entries(t))for(let o of a.prepaid??[])r[i]?.has(o.internalFeatureId)||n.push(`Product ${i} needs a quantity control for ${o.internalFeatureId}`);return n}function zf(e,t,n,r){let i=r.plans[t];if(!i?.available)throw new Error("Selected Product is unavailable");let a={};if(Gt(e,o=>{if(o.hidden)return!1;if(o.type!=="quantity_picker"||o.hidden||(o.bind?.plan??(o.bind?.picker?n[o.bind.picker]:void 0))!==t)return;let c=i.prepaid?.find(l=>l.internalFeatureId===o.internalFeatureId)?.terms,u=n[o.id];if(!c||typeof u!="number"||!Number.isSafeInteger(u)||u<Math.max(c.minimumQuantity,o.minimumQuantity)||u>Math.min(c.maximumQuantity,o.maximumQuantity)||(u-o.minimumQuantity)%o.step!==0||a[o.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");a[o.internalFeatureId]=u}),(i.prepaid??[]).some(o=>a[o.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return a}import{z as bo}from"zod";var $f=bo.object({defaultLocale:In,locales:bo.record(In,bo.object({name:bo.string().max(80),description:bo.string().max(500)}).strict())}).strict().superRefine((e,t)=>{let n=Object.keys(e.locales);(!n.length||n.length>20||!e.locales[e.defaultLocale])&&t.addIssue({code:"custom",message:"Invalid content languages"}),new TextEncoder().encode(JSON.stringify(e)).length>5e4&&t.addIssue({code:"custom",message:"Content exceeds 50 KB"})});var I0=["customer_data","coupon_code"],Gf=ae.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),v0=ae.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),rs=(e,t)=>new Set(e.map(t)).size===e.length,w0=ae.strictObject({currency:Ie,amountMinor:ae.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),O0=ae.strictObject({featureId:ae.uuid(),name:ae.string().trim().min(1).max(120),allowance:ae.string().max(40).nullable(),access:ae.boolean()}),P0=ae.strictObject({stripe:ae.strictObject({prices:ae.array(w0).min(1).max(50)}).optional(),apple:ae.strictObject({productIds:ae.array(Gf).min(1).max(10)}).optional(),google:ae.strictObject({products:ae.array(ae.strictObject({productId:Gf,basePlanId:v0.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!rs(e.stripe.prices,n=>n.currency)||e.apple&&!rs(e.apple.productIds,n=>n)||e.google&&!rs(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),C0=ae.strictObject({name:ae.string().trim().min(1).max(80),interval:ae.enum(["free","week","month","year","one_time"]),intervalCount:ae.number().int().min(1).max(100),trial:ae.strictObject({days:ae.number().int().min(1).max(730),cardRequired:ae.boolean()}).nullable(),benefits:ae.array(O0).max(50).refine(e=>rs(e,t=>t.featureId),"Duplicate benefit"),channels:P0,prepaid:ae.array(io).max(100).optional()}),_0=ae.strictObject({digest:vi,content:ae.strictObject({discount:nr,duration:sn,appliesTo:sc,displayCopy:$f.nullable(),firstPurchaseOnly:ae.boolean(),qualificationRequired:ae.boolean(),startsAt:ae.iso.datetime().nullable(),endsAt:ae.iso.datetime().nullable(),grantWindowHours:ae.number().int().positive(),perCustomerLimit:ae.number().int().positive()})}),E0=ae.discriminatedUnion("type",[ae.strictObject({type:ae.literal("checkout"),product:xa}),ae.strictObject({type:ae.literal("close")}),ae.strictObject({type:ae.literal("action"),action:Vc})]),is=ae.strictObject({kind:ae.literal("paywall"),formatVersion:ae.literal(1),name:ae.string().trim().min(1).max(80),offeringVersionId:ae.uuid(),presentation:Pn,screen:un,products:Ma,catalog:ae.record(ae.uuid(),C0),buttons:ae.record(Ue,E0),coupons:ae.record(ae.uuid(),_0)}).superRefine((e,t)=>{let n=h=>t.addIssue({code:"custom",message:h}),{screen:r}=e;Lf(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),Kc(r,I0).forEach(n),or(r).some(h=>!h.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,o=new Set;Gt(r,h=>{let R="bind"in h?h.bind:void 0;R?.promotionCode&&n("Promotion codes must not be published"),R?.plan&&i.add(R.plan),R?.coupon&&a.add(R.coupon),h.type==="plan_picker"&&(h.planIds?.forEach(y=>i.add(y)),h.defaultPlan&&i.add(h.defaultPlan)),h.type==="text"&&h.feature&&o.add(h.feature.id)});let s=e.products.items.map(h=>h.productVersionId),c=Object.keys(e.catalog);(s.length!==c.length||s.some(h=>!Object.hasOwn(e.catalog,h)))&&n("Catalog must contain exactly the displayed Products");let u=new Set(s);e.products.defaultProductVersionId!==null&&!u.has(e.products.defaultProductVersionId)&&n("Default Product must be displayed");for(let h of i)u.has(h)||n("Screen references a Product that is not displayed");for(let h of Object.values(e.catalog))!h.channels.stripe&&!h.channels.apple&&!h.channels.google&&n("A displayed Product needs at least one sales channel");let l=new Set(Object.values(e.catalog).flatMap(h=>h.benefits.map(R=>R.featureId)));for(let h of o)l.has(h)||n("Feature text must read a displayed benefit");let m=r.actions.filter(h=>h.type!=="navigate");r.actions.some(h=>h.type!=="event"&&h.type!=="navigate")&&n("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==m.length||m.some(h=>!Object.hasOwn(e.buttons,h.id)))&&n("Buttons must match the screen's actions");let g=!1;for(let h of Object.values(e.buttons)){if(h.type!=="checkout")continue;g=!0,(h.product.type==="fixed"?[h.product.productVersionId]:h.product.allowedProductVersionIds).some(y=>!u.has(y))&&n("Checkout may only sell displayed Products")}g||n("A Paywall needs a checkout button");let d=Object.keys(e.coupons);(d.length!==a.size||d.some(h=>!a.has(h)))&&n("Coupons must be exactly the bound Coupons")}),Kf=ae.strictObject({state:ae.enum(["published","archived"]),controlRevision:ae.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:ae.uuid(),versions:ae.record(ae.uuid(),ae.strictObject({version:ae.number().int().positive(),artifact:ae.string().min(1),sourceDigest:ae.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var nn={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},hu=Re.string().regex(/^[a-f0-9]{64}$/),yu=Re.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),bu=Ne.extend({environmentId:Re.uuid()}),Hf=Re.strictObject({features:Re.array(Re.string()).max(500),experiments:Re.record(Re.uuid(),Re.array(Re.string()).max(20)),savedGroups:Re.array(Re.string()).max(1e3)}),xu=Re.strictObject({kind:Re.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:Re.number().int().positive(),url:Re.string().min(1).max(2048),sha256:hu,byteLength:Re.number().int().positive().max(nn.maxArtifactBytes),generation:hu.optional()}),R0=Re.strictObject({state:Re.enum(["active","paused","archived"]),controlRevision:yu,evaluationMode:Re.enum(["local","remote"]),evaluationRevision:yu,currentVersionId:Re.uuid(),versions:Re.record(Re.uuid(),Re.strictObject({artifact:Re.string(),dependencies:Hf,definitionDigest:vi.optional(),couponDigests:Re.record(Re.uuid(),vi).optional()}))}),Su=Re.strictObject({kind:Re.literal("sdk_configuration"),schemaVersion:Re.literal(1),scope:bu,revision:yu,generation:hu,policy:Re.strictObject({refreshIntervalSeconds:Re.number().positive().max(15),maxControlAgeSeconds:Re.number().positive().max(60)}),gb:Re.strictObject({features:Re.string().nullable(),pageExperiments:Re.string().nullable()}),artifacts:Re.record(Re.string(),xu),funnels:Re.record(Re.uuid(),R0),paywalls:Re.record(Re.uuid(),Kf).optional()}).superRefine((e,t)=>{let n=(r,i)=>{r!==null&&e.artifacts[r]?.kind!==i&&t.addIssue({code:"custom",message:"Missing or wrong-kind configuration artifact"})};n(e.gb.features,"gb_features"),n(e.gb.pageExperiments,"gb_page_experiments");for(let r of Object.values(e.paywalls??{}))for(let i of Object.values(r.versions))n(i.artifact,"paywall");for(let r of Object.values(e.funnels)){r.evaluationMode==="remote"&&Object.keys(r.versions).length&&t.addIssue({code:"custom",message:"Remote Funnel graphs cannot be public"}),r.evaluationMode==="local"&&!r.versions[r.currentVersionId]&&t.addIssue({code:"custom",message:"Current Funnel Version is not retained"});for(let i of Object.values(r.versions))n(i.artifact,"funnel")}});function Pt(e){if(Array.isArray(e))return`[${e.map(Pt).join(",")}]`;if(e!==null&&typeof e=="object")return`{${Object.entries(e).sort(([n],[r])=>n<r?-1:n>r?1:0).map(([n,r])=>`${JSON.stringify(n)}:${Pt(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function Iu(e){return ni(ri(typeof e=="string"?new TextEncoder().encode(e):e))}function Qf(e){return Iu(Pt(e))}var Au=class extends Error{constructor(n,r){super(n);qe(this,"dependency",r)}};function Jf(e,t){let n=l=>l.type==="feature"?l.featureKey:l.type==="end"&&l.output?.type==="feature"?l.output.featureKey:l.type==="output"&&l.value.type==="feature"?l.value.featureKey:void 0,r=(l,m)=>e.graph.nodes.find(f=>l==="experiment"?f.type==="split"&&f.experimentId===m:l==="feature"&&n(f)===m)?.name,i=(l,m,f=r(m.type,m.resource))=>new Au(l,{...m,...f?{step:f}:{}});for(let l of Object.values(e.references)){let m=l.type==="flag"?!Object.hasOwn(t.features,l.key)||t.remoteFeatures.includes(l.key)?{type:"feature",resource:l.key}:null:l.type==="experiment"?Object.hasOwn(t.experiments,l.id)?null:{type:"experiment",resource:l.id}:l.type==="saved_group"&&!Object.hasOwn(t.savedGroups,l.id)?{type:"saved_group",resource:l.id}:null;if(m)throw i("Funnel dependency is absent from GB public delivery",{reason:"unavailable",...m})}let a=ns(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),o=new Set(t.remoteFeatures);for(let l of e.graph.nodes){let m=n(l);if(!m)continue;let f=a.features[m],g=l.type==="feature"?e.variables[l.writes.value]:e.outputSchema,d={type:"feature",resource:m};if(!f||!g)throw i("Required public Feature declaration is unavailable",{reason:"unavailable",...d},l.name);if([f.defaultValue,...(f.rules??[]).flatMap(R=>[...Object.hasOwn(R,"force")?[R.force]:[],...R.variations??[],...(R.tracks??[]).flatMap(y=>y.experiment.variations)])].some(R=>R===void 0||!hn(g,R)))throw i("GB Feature values violate the Funnel type contract",{reason:"value_type",...d},l.name)}let s=new Set,c=(l,m)=>{for(let f of Hn(l)){if(s.has(f))continue;let g=t.savedGroups[f];if(!g)throw i("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:f},m);s.add(f),!Array.isArray(g)&&g.type==="condition"&&c(g.condition,m)}},u=(l,m)=>{if(o.has(l)||!t.features[l])throw i("Local Funnel requires public Local prerequisites",{reason:"unavailable",type:"feature",resource:l},m)};for(let l of e.graph.nodes)if(l.type==="condition")for(let m of l.cases)c(m.condition,l.name);for(let[l,m]of Object.entries(a.features)){let f=r("feature",l);for(let g of m.rules??[]){c(g.condition,f);for(let d of[...g.parentConditions??[],...(g.tracks??[]).flatMap(h=>h.experiment.parentConditions??[])])u(d.id,f),c(d.condition,f);for(let d of g.tracks??[])c(d.experiment.condition,f)}}for(let[l,m]of Object.entries(a.experiments)){let f=r("experiment",l);c(m.condition,f);for(let g of m.parentConditions??[])u(g.id,f),c(g.condition,f)}for(let l of e.graph.nodes)if(l.type==="split"){let m=a.experiments[l.experimentId],f={type:"experiment",resource:l.experimentId};if(!m)throw i("Local Funnel requires a public Experiment",{reason:"unavailable",...f},l.name);for(let g of m.variations)if(typeof g!="string"||!Object.hasOwn(l.routes,g))throw i("Experiment variation has no declared Funnel route",{reason:"variation_route",...f},l.name)}return Hf.parse({features:Object.keys(a.features).sort(),experiments:Object.fromEntries(Object.entries(a.experiments).map(([l,m])=>[l,m.variations.map(String)])),savedGroups:[...s].sort()})}function Zf(e){return Ei.parse(e)}var Wf=Ct.strictObject({processContext:Pa.optional(),...gi,selector:Ct.discriminatedUnion("type",[Ct.strictObject({type:Ct.literal("paywall"),paywallId:Ct.uuid()}),Ct.strictObject({type:Ct.literal("version"),versionId:Ct.uuid()})]),customerId:Ct.uuid().optional(),commerce:ui,locale:Ct.string().min(1).max(35),requirement:ir.optional()}),xo=Ct.strictObject({id:Ct.uuid(),paywallId:Ct.uuid(),version:Ct.number().int().positive(),document:Ii.omit({requirement:!0,offeringId:!0}),offering:Ct.strictObject({id:Ct.uuid()}),content:Ct.strictObject({environmentId:Ct.uuid(),offeringVersionId:Ct.uuid(),artifact:xu.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:li,check:Rr.nullable()}).superRefine((e,t)=>{let n=new Set(e.document.products.items.map(r=>r.productVersionId));(e.document.offeringVersionId!==e.offering.id||Object.values(e.capabilities.plans).some(r=>!n.has(r.versionId)))&&t.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})}),Vr=Ct.strictObject(xo.shape).omit({document:!0,offering:!0}).extend({content:xo.shape.content.unwrap()});function Yf(e,t){let n=is.parse(t);if(n.offeringVersionId!==e.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");let r=structuredClone(e.capabilities);for(let[i,a]of Object.entries(n.catalog)){let o=r.plans[i],s=a.channels.stripe?.prices.find(c=>c.currency===o?.currency);o&&s&&Object.assign(o,{amountMinor:s.amountMinor,interval:a.interval,intervalCount:a.intervalCount,...a.prepaid?.length?{prepaid:a.prepaid}:{}})}return xo.parse({...e,capabilities:r,document:{schemaVersion:3,kind:n.kind,name:n.name,presentation:n.presentation,products:n.products,offeringVersionId:n.offeringVersionId,screen:n.screen,buttons:n.buttons},offering:{id:n.offeringVersionId}})}import{z as Ht}from"zod";var Xf={requestId:Ht.uuid(),sourceId:Ht.uuid(),expectedAvailable:$t},eg=Ht.discriminatedUnion("action",[Ht.strictObject({...Xf,action:Ht.enum(["add","subtract","set_remaining"]),amount:xe}),Ht.strictObject({...Xf,action:Ht.literal("edit"),granted:xe,expiresAt:Ht.iso.datetime({offset:!0}).nullable(),nextResetAt:Ht.iso.datetime({offset:!0}).nullable(),expectedRevision:Ht.number().int().nonnegative()})]),vu=Ht.strictObject({sourceId:Ht.uuid(),available:$t,held:$t,spent:$t,adjustmentGrantId:Ht.uuid().nullable()}),tg=vu.extend({granted:$t,expiresAt:Ht.iso.datetime({offset:!0}).nullable(),nextResetAt:Ht.iso.datetime({offset:!0}).nullable(),revision:Ht.number().int().nonnegative()});import{z as mn}from"zod";var ng=mn.discriminatedUnion("action",[mn.object({action:mn.literal("upsert"),externalId:mn.string().min(1).max(128),name:mn.string().trim().min(1).max(80)}).strict(),mn.object({action:mn.literal("archive"),entityId:mn.uuid()}).strict()]),rg=mn.object({id:mn.uuid(),externalId:mn.string().min(1).max(128),name:mn.string().min(1).max(80),archived:mn.boolean()}).strict();import{z as Vt}from"zod";import{z as zr}from"zod";var og=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],ig=zr.string().regex(/.+\/.+/),wu=zr.number().min(-100),Lr=zr.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),k0=zr.strictObject({input:Lr,output:Lr,cache_read:Lr.optional(),cache_write:Lr.optional(),reasoning:Lr.optional(),input_audio:Lr.optional(),output_audio:Lr.optional()}),Ou=(e,t)=>zr.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),qk=zr.strictObject({defaultMarkup:wu,providerMarkups:Ou(zr.string().min(1),wu),modelMarkups:Ou(ig,wu),customModels:Ou(ig,k0.partial())});import{z as be}from"zod";var $r=be.iso.datetime({offset:!0}),ur=be.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),j0=be.discriminatedUnion("kind",[be.object({kind:be.literal("absolute"),from:$r,to:$r}).strict(),be.object({kind:be.literal("last_days"),days:be.union([be.literal(1),be.literal(7),be.literal(30),be.literal(90)])}).strict(),be.object({kind:be.literal("billing_cycles"),membershipId:be.uuid(),count:be.number().int().min(1).max(12),includeCurrent:be.boolean()}).strict()]),ag=be.string().max(100).refine(e=>{if(e!=="UTC"&&!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+\-]+)+$/.test(e))return!1;try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Use an IANA timezone"),T0=be.object({key:be.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:be.array(be.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),Gr=be.object({range:j0,timezone:ag,filterBy:be.array(T0).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:be.enum(["hour","day","week","month"]),internal_feature_id:be.uuid().nullable(),entityId:be.uuid().nullable(),topN:be.number().int().min(1).max(50).nullable(),groupBy:be.union([be.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),be.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:be.object({bucket:$r,group:be.string().max(240),isOther:be.boolean(),internal_feature_id:be.uuid(),resourceId:be.uuid()}).strict().nullable(),limit:be.number().int().min(1).max(100)}).strict().superRefine((e,t)=>{if(e.range.kind!=="absolute"){e.interval==="hour"&&e.range.kind==="last_days"&&e.range.days>31&&t.addIssue({code:"custom",message:"Hourly reports are bounded to 31 days"});return}let n=Date.parse(e.range.to)-Date.parse(e.range.from);(n<=0||n>366*864e5||e.interval==="hour"&&n>31*864e5)&&t.addIssue({code:"custom",message:"Reporting range must be positive and bounded (31 days hourly, 366 days otherwise)"})}),sg=be.object({from:$r,to:$r,interval:be.enum(["hour","day","week","month"]),timezone:ag,rows:be.array(be.object({bucket:$r,group:be.string().max(240),isOther:be.boolean(),internal_feature_id:be.uuid(),resourceId:be.uuid(),consumedUnits:ur,refundedUnits:ur,reservedUnits:ur,charged:ur,refunded:ur,reserved:ur,netUnits:ur,netCharged:ur}).strict()).max(100),nextCursor:be.object({bucket:$r,group:be.string().max(240),isOther:be.boolean(),internal_feature_id:be.uuid(),resourceId:be.uuid()}).strict().nullable()}).strict();var Ri=Vt.string().regex(/^(0|[1-9]\d{0,29})$/),cg=Vt.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),Pu=Vt.strictObject({bucket:Vt.iso.datetime({offset:!0}),group:Vt.string().max(240),isOther:Vt.boolean(),internal_feature_id:Vt.uuid()}),ug=Vt.strictObject({...Gr.shape,groupBy:Vt.union([Vt.enum(["customer","entity","entitlement"]),Vt.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Pu.nullable()}).superRefine((e,t)=>{let n=Gr.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),lg=Vt.strictObject({from:Vt.iso.datetime({offset:!0}),to:Vt.iso.datetime({offset:!0}),interval:Gr.shape.interval,timezone:Gr.shape.timezone,rows:Vt.array(Vt.strictObject({...Pu.shape,eventCount:Ri,units:cg,tokenEventCount:Ri,tokens:Vt.strictObject(Object.fromEntries(og.map(e=>[e,Ri]))),totalTokens:Ri,providerCostEventCount:Ri,providerCostUsd:cg,invalidTelemetryEventCount:Ri})).max(100),nextCursor:Pu.nullable()});import{z as bt}from"zod";var dg=bt.object({requestId:bt.uuid(),items:bt.array(bt.object({customerId:bt.uuid(),command:Yi.options[1]}).strict()).min(1).max(1e3)}).strict().refine(e=>new Set(e.items.map(t=>t.customerId+":"+t.command.idempotencyKey)).size===e.items.length,"Each logical event must appear once in a batch"),pg=bt.object({batchId:bt.uuid(),after:bt.number().int().min(-1).max(999),limit:bt.number().int().min(1).max(100)}).strict(),mg=bt.object({batchId:bt.uuid(),status:bt.enum(["queued","complete"]),total:bt.number().int().min(1).max(1e3),processed:bt.number().int().min(0).max(1e3),items:bt.array(bt.object({position:bt.number().int().min(0).max(999),customerId:bt.uuid(),idempotencyKey:bt.string().min(1).max(120),status:bt.enum(["queued","accepted","rejected","failed"]),receipt:Xi.nullable(),errorCode:bt.enum(["invalid_request","forbidden","conflict","internal_error"]).nullable()}).strict().refine(e=>e.status==="queued"?e.receipt===null&&e.errorCode===null:e.status==="failed"?e.receipt===null&&e.errorCode!==null:e.receipt!==null&&e.errorCode===null&&e.receipt.accepted===(e.status==="accepted"))).max(100),nextAfter:bt.number().int().min(0).max(999).nullable()}).strict();import{z as k}from"zod";var N0=k.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),fg=k.enum(["draft","active","paused","archived"]),gg=k.string().min(1).max(256),hg=k.array(gg).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),D0=k.strictObject({duration:k.enum(["day","week","month","year"]),length:k.number().int().min(1).max(3660)}),F0=k.strictObject({internal_feature_id:k.uuid(),allowance:k.number().nonnegative().max(1e15).nullable(),expiry:D0.nullable()}),M0=k.discriminatedUnion("type",[k.strictObject({type:k.literal("feature_grant"),grants:k.array(F0).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),k.strictObject({type:k.literal("free_product"),productId:gg,duration:sn}),k.strictObject({type:k.literal("invoice_credits"),amount:k.number().positive().max(1e8),duration:sn,rollover:k.boolean(),productIds:hg})]),q0=k.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),yg=k.object({key:q0,name:k.string().trim().min(1).max(80),configuration:M0}).strict(),Ag=k.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),Cu=k.object({code:Ag,maxUses:k.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:k.boolean()}).strict(),bg=k.object({key:k.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:k.string().trim().min(1).max(80),rewardId:k.uuid(),redeemOn:k.enum(["customer_creation","checkout"]),receivedBy:k.enum(["referrer","all"]),maxRedemptions:k.number().int().min(1).max(1e6).nullable(),productIds:hg,excludeTrial:k.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),xg={id:k.uuid(),projectId:k.uuid(),environmentId:k.uuid(),revision:k.number().int().nonnegative(),status:fg,createdAt:k.iso.datetime({offset:!0}),updatedAt:k.iso.datetime({offset:!0})},U0=yg.extend(xg).strict(),B0=bg.safeExtend(xg).strict(),Yk=k.strictObject({id:k.uuid(),key:k.string(),name:k.string(),type:N0,status:fg}),Xk=k.discriminatedUnion("action",[k.object({action:k.literal("save"),id:k.uuid().nullable(),revision:k.number().int().nonnegative(),input:yg}).strict(),k.object({action:k.enum(["activate","pause","resume","archive","delete"]),id:k.uuid(),revision:k.number().int().nonnegative()}).strict()]),ej=k.discriminatedUnion("action",[k.object({action:k.literal("save"),id:k.uuid().nullable(),revision:k.number().int().nonnegative(),input:bg}).strict(),k.object({action:k.enum(["activate","pause","resume","archive","delete"]),id:k.uuid(),revision:k.number().int().nonnegative()}).strict()]),Sg=k.object({id:k.uuid(),rewardId:k.uuid(),programId:k.uuid().nullable(),customerId:k.uuid(),referrerId:k.uuid().nullable(),status:k.enum(["pending","applied","unavailable"]),result:k.record(k.string(),k.unknown()).nullable(),createdAt:k.iso.datetime({offset:!0})}).strict(),Ig=k.object({code:Ag,requestId:k.uuid()}).strict(),vg=k.strictObject({redemptionId:k.uuid(),currency:Ie,requestId:k.uuid(),accepted:k.literal(!0)}),V0=k.strictObject({type:k.literal("checkout"),orderId:k.uuid(),productVersionId:k.uuid(),currency:Ie,duration:sn,renewalAmountMinor:k.number().int().positive().max(1e8),status:k.enum(["created","pending","trialing","paid","cancelled","failed"]),url:k.url().nullable()}),wg=k.discriminatedUnion("type",[V0,k.strictObject({type:k.literal("subscription"),operationId:k.uuid(),membershipId:k.uuid(),productVersionId:k.uuid(),currency:Ie,duration:sn,renewalAmountMinor:k.number().int().positive().max(1e8),status:k.enum(["pending","running","applied","failed"])})]),Og=k.object({programId:k.uuid(),requestId:k.uuid()}).strict(),Pg=k.object({id:k.uuid(),programId:k.uuid(),code:Cu.shape.code,createdAt:k.iso.datetime({offset:!0})}).strict(),tj=k.object({rows:k.array(U0).max(100),nextCursor:k.uuid().nullable()}).strict(),nj=k.object({rows:k.array(B0).max(100),nextCursor:k.uuid().nullable()}).strict(),L0=Cu.extend({id:k.uuid(),redemptions:k.number().int().nonnegative()}).strict(),z0=k.strictObject({id:k.uuid(),programId:k.uuid().nullable(),customerId:k.uuid().nullable(),referrerId:k.uuid().nullable(),code:k.string().nullable(),status:k.enum(["pending","triggered","applied"]),createdAt:k.iso.datetime({offset:!0})}),rj=k.object({codes:k.array(L0).max(100),redemptions:k.array(z0).max(100),customers:k.record(k.uuid(),k.string()),codesCursor:k.uuid().nullable(),redemptionsCursor:k.uuid().nullable()}).strict(),ij=k.discriminatedUnion("action",[k.object({action:k.literal("create"),rewardId:k.uuid(),revision:k.number().int().nonnegative(),input:Cu}).strict(),k.object({action:k.literal("remove"),rewardId:k.uuid(),revision:k.number().int().nonnegative(),codeId:k.uuid()}).strict()]);import{z as w}from"zod";import{z as W}from"zod";var Mn={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},So=e=>new Set(e).size===e.length,_u=W.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),$0=W.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),Io=W.string().min(1).max(200).regex(/^[a-zA-Z0-9_./-]+$/).refine(e=>!e.includes("..")&&!e.endsWith(".")&&!e.split("/").some(t=>!t||t.startsWith(".")||t.endsWith(".lock"))),G0=W.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),Cg=W.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var _g=W.strictObject({id:W.uuid(),repo:$0,platform:W.enum(["github","gitlab","bitbucket"]),branches:W.array(Io).min(1).max(4).refine(So),workflow:W.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:W.array(W.uuid()).min(1).max(4).refine(So),include:W.array(Cg).min(1).max(16),exclude:W.array(Cg).max(16),methods:W.array(W.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(So),maxAgeHours:W.number().int().min(1).max(720)}),Eg=_g.extend({revision:W.number().int().positive()}),sj=W.strictObject({repository:_g,expectedRevision:W.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),Rg=W.strictObject({repositoryId:W.uuid(),branch:Io}),K0=W.array(_u).max(Mn.keys).refine(So),kg=W.strictObject({repository:Eg.omit({keyIds:!0}),branch:Io,keys:K0,keySetHash:W.string().regex(/^[a-f0-9]{64}$/)}),H0=W.strictObject({filePath:G0,startingLineNumber:W.number().int().min(1).max(1e7)}),Eu=W.strictObject({protocol:W.literal(1),repositoryId:W.uuid(),branch:Io,workflow:W.string().max(200),configurationRevision:W.number().int().positive(),keySetHash:W.string().regex(/^[a-f0-9]{64}$/),commit:W.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:W.uuid(),runNumber:W.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:W.number().int().min(1).max(1e4),scannerVersion:W.literal("1"),scannedAt:W.iso.datetime({offset:!0}),coverage:W.strictObject({complete:W.literal(!0),files:W.number().int().min(0).max(Mn.files),sourceBytes:W.number().int().min(0).max(Mn.sourceBytes),unresolvedCalls:W.number().int().min(0).max(1e6),unsupportedFiles:W.number().int().min(0).max(Mn.files)}),features:W.array(W.strictObject({key:_u,refs:W.array(H0).max(Mn.referencesPerKey)})).max(Mn.keys)}).superRefine((e,t)=>{So(e.features.map(n=>n.key))||t.addIssue({code:"custom",path:["features"],message:"Duplicate feature"}),e.features.reduce((n,r)=>n+r.refs.length,0)>Mn.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),Ru=W.strictObject({scanId:W.uuid(),commit:W.string(),receivedAt:W.string(),references:W.number().int().nonnegative(),removedReferences:W.number().int().nonnegative()}),Q0=Ru.extend({repositoryId:W.uuid(),branch:Io,workflow:W.string(),digest:W.string(),configurationRevision:W.number().int().positive(),runNumber:W.number().int().positive(),runAttempt:W.number().int().positive(),scannedAt:W.string(),keySetHash:W.string(),coverage:Eu.shape.coverage}),J0=W.strictObject({repositories:W.array(Eg).max(Mn.repositories),scans:W.array(Q0).max(Mn.repositories*Mn.branches)}),Z0=W.strictObject({key:_u,references:W.number().int().nonnegative(),coveredTargets:W.number().int().nonnegative(),expiredTargets:W.number().int().nonnegative(),uncertainTargets:W.number().int().nonnegative()}),cj=W.strictObject({available:W.boolean().default(!0),settings:J0,expectedTargets:W.number().int().min(0).max(80),features:W.array(Z0).max(2001),truncated:W.boolean()});import{z as Ee}from"zod";var rn=Ee.string().min(1).max(200),os=Ee.iso.datetime({offset:!0}),vo=Ee.number().int().min(1).max(Number.MAX_SAFE_INTEGER),ku=Ee.number().int().min(0).max(1e12),Ng=Ee.number().int().min(1).max(1e12),jg={...Zt,type:Ee.literal("coupon.redeemed"),grantId:Ee.uuid()},Tg={...Zt,type:Ee.literal("usage.observed"),merchantTransactionId:rn,resource:rn,unit:rn,quantity:Ng},W0=Ee.strictObject({...Zt,type:Ee.literal("fulfillment.updated"),operationId:Ee.uuid(),merchantFulfillmentId:rn,status:Ee.enum(["pending","applied","failed"])}),Y0=Ee.strictObject({...Zt,type:Ee.literal("benefit.claimed"),merchantBenefitId:rn,resource:rn,unit:rn,quantity:Ng,expiresAt:os.nullable(),revision:vo}),X0=Ee.strictObject({...Zt,type:Ee.literal("benefit.closed"),merchantBenefitId:rn,status:Ee.enum(["failed","expired","canceled"]),revision:vo}),eI=Ee.strictObject({...Zt,type:Ee.literal("benefit.updated"),merchantBenefitId:rn,status:Ee.enum(["active","expired","revoked"]),remainingQuantity:ku.nullable(),expiresAt:os.nullable(),revision:vo}),tI=Ee.strictObject({...Zt,type:Ee.literal("authorization.updated"),merchantAuthorizationId:rn,kind:Ee.literal("auto_topup"),status:Ee.enum(["pending","effective","revoked","failed"]),termsReference:rn.nullable(),revision:vo}),nI=Ee.strictObject({...Zt,type:Ee.literal("balance.observed"),resource:rn,unit:rn,availableQuantity:ku,reservedQuantity:ku,periodStartsAt:os.nullable(),periodEndsAt:os.nullable(),revision:vo}),Dg=Ee.union([Ee.discriminatedUnion("type",[...Ml,W0,Y0,X0,eI,tI,nI]),Ee.strictObject({...jg,productVersionId:Ee.uuid(),subscriptionId:Ee.string().trim().min(1).max(255)}),Ee.strictObject({...jg,merchandiseId:Ee.uuid()}),Ee.strictObject({...Tg,operation:Ee.literal("consume")}),Ee.strictObject({...Tg,operation:Ee.literal("reverse"),reversalOf:rn})]),Fg=Ee.strictObject({id:Ee.uuid(),eventId:Ee.string().min(1).max(200),source:Ee.literal("merchant"),providerVerified:Ee.literal(!1),outcome:Ee.string().min(1).max(100)});import{z as oe}from"zod";var Mg=mm,rI=Mg.extend({invoice_id:Mg.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),ju=oe.strictObject({name:oe.string().trim().min(1).max(255),memo:oe.string().max(1e4).nullable().optional(),footer:oe.string().max(1e4).nullable().optional(),net_terms_days:oe.number().int().positive().nullable().optional()}),iI=ju.extend({id:oe.string().min(1).max(255),created_at:oe.number().nullable()}),qg=oe.strictObject({items:oe.array(iI).max(50),nextCursor:oe.uuid().nullable()}),gj=oe.discriminatedUnion("action",[oe.strictObject({action:oe.literal("create"),requestId:oe.uuid(),values:ju}),oe.strictObject({action:oe.literal("update"),id:oe.string().min(1).max(255),values:ju}),oe.strictObject({action:oe.literal("delete"),id:oe.string().min(1).max(255)})]),Ug=oe.discriminatedUnion("action",[oe.strictObject({action:oe.literal("create"),requestId:oe.uuid(),params:yi}),oe.strictObject({action:oe.enum(["finalize","send","pay","void"]),requestId:oe.uuid(),invoiceId:oe.uuid()}),oe.strictObject({action:oe.literal("reissue"),requestId:oe.uuid(),invoiceId:oe.uuid(),params:rI})]),Tu=oe.strictObject({id:oe.uuid(),customerId:oe.uuid(),providerInvoiceId:oe.string().nullable(),status:oe.enum(["draft","open","paid","void","uncollectible"]),currency:oe.string(),totalMinor:oe.string().regex(/^-?\d+$/),paidMinor:oe.string().regex(/^\d+$/),refundedMinor:oe.string().regex(/^\d+$/),hostedInvoiceUrl:oe.url().nullable(),createdAt:oe.number(),collectionMethod:oe.enum(["send_invoice","charge_automatically"]).nullable()}),Bg=Tu.extend({lines:oe.array(oe.strictObject({id:oe.uuid(),description:oe.string(),amountMinor:oe.string().regex(/^-?\d+$/),netAmountMinor:oe.string().regex(/^-?\d+$/),quantity:oe.number().nullable(),periodStart:oe.number().nullable(),periodEnd:oe.number().nullable()})).max(1e3)}),ki=oe.strictObject({taskId:oe.uuid(),status:oe.enum(["ready","running","done","dead"]),invoice:Tu.nullable(),errorCode:oe.string().nullable()}),Vg=oe.strictObject({items:oe.array(Tu).max(50),nextCursor:oe.uuid().nullable(),operations:oe.array(ki).max(50),operationsLimited:oe.boolean()});var oI=w.enum(["customers:read","customers:write","entitlements:read","content:read","sessions:create","funnels:run","offers:resolve","offers:grant","billing:read","billing:write","credits:read","credits:consume","credits:manage","features:read","events:write","messaging:write","code-references:read","code-references:write","app-manifests:write"]),Lg={scope:Ne,permissions:w.array(oI),expiresAt:w.iso.datetime().nullable()},aT=w.discriminatedUnion("kind",[w.object({...Lg,kind:w.literal("server"),keyId:w.string().min(1)}),w.object({...Lg,kind:w.literal("customer"),customerId:w.string().min(1),identityKind:w.enum(["identified","guest"]),expiresAt:w.iso.datetime()})]),z=w.object({requestId:w.uuid(),scope:Ne}).strict(),aI=_f.safeExtend({fingerprint:Ja.optional()}).strict(),sI=z.extend({customer:Ci,created:w.boolean()});function zg(){return z.extend({offer:Gi.nullable(),reason:Ld.nullable()})}var O={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:jp,response:z.extend({message:w.object({messageId:w.uuid(),channel:ro,acceptedAt:w.iso.datetime({offset:!0}),status:w.enum(["accepted","sending","completed","canceled"]),replayed:w.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:w.strictObject({messageId:w.uuid()}),response:z.extend({message:w.object({id:w.uuid(),channel:ro,status:w.enum(["accepted","sending","completed","canceled"]),deliveries:w.array(w.object({id:w.uuid(),status:Np,attempts:w.number().int().nonnegative(),receipts:w.array(w.object({kind:Dp,occurredAt:w.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:Sl,response:z.extend({installation:Ir})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:Il,response:z.extend({installation:Ir})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:qo,response:z.extend({installation:Ir})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:w.strictObject({channel:ro}),response:z.extend({preference:Cs})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:Tp,response:z.extend({preference:Cs})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:w.strictObject({cursor:w.uuid().optional()}),response:z.extend({templates:qg})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:w.strictObject({customerId:w.uuid(),params:yi}),response:z.extend({preview:kc})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:w.strictObject({customerId:w.uuid(),requestId:w.uuid(),params:yi}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:z.extend({operation:ki})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:w.strictObject({customerId:w.uuid(),command:Ug}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:z.extend({operation:ki})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:w.strictObject({customerId:w.uuid(),taskId:w.uuid()}),response:z.extend({operation:ki})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:w.strictObject({customerId:w.uuid(),cursor:w.uuid().optional()}),response:z.extend({invoices:Vg})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:w.strictObject({customerId:w.uuid(),invoiceId:w.uuid()}),response:z.extend({invoice:Bg})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:Rg,response:z.extend({config:kg})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:Eu,response:z.extend({receipt:Ru})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:w.strictObject({}),response:z.extend({payload:fo})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:of,response:z.merge(Ua)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:af,response:z.merge(sf)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:w.strictObject({customerId:w.uuid(),sourceId:w.uuid()}),response:z.extend({balance:tg})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:w.strictObject({customerId:w.uuid(),command:eg}),response:z.extend({balance:vu})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:w.strictObject({internal_feature_id:w.uuid(),customerId:w.uuid().optional(),entityId:w.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:z.extend({internal_feature_id:w.uuid(),config:Ls,model_markups:Jo})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:w.strictObject({customerId:w.uuid(),query:fa}),response:z.extend({usage:eo})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:w.strictObject({customerId:w.uuid(),command:vp}),response:z.extend({usage:eo})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:w.strictObject({customerId:w.uuid(),command:yp}),response:z.extend({grant:dc})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:Ap,response:z.extend({grants:bp})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:w.union(Km.options.map(e=>e.extend({customerId:w.uuid().optional(),customerToken:w.string().regex(kt).optional()}))),response:z.extend({operation:Hm})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:Dm.extend({customerId:w.uuid().optional()}),response:z.extend({setup:Fc})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Fm.extend({customerId:w.uuid().optional()}),response:z.extend({setup:Fc})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:jm.safeExtend({customerId:w.uuid()}),response:z.extend({batch:lo})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:ka.extend({customerId:w.uuid()}),response:z.extend({batch:lo})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:ka.extend({customerId:w.uuid()}),response:z.extend({batch:lo})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:ka.extend({customerId:w.uuid()}),response:z.extend({batch:lo})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:w.discriminatedUnion("action",[ja.options[0].extend({customerId:w.uuid()}),ja.options[1].extend({customerId:w.uuid()}),ja.options[2].extend({customerId:w.uuid()})]),response:z.extend({trial:Dc})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Tm.extend({customerId:w.uuid()}),response:z.extend({trial:Dc})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:Da,response:z.extend({subscriptions:zm})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:Da,response:z.extend({purchases:$m})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:Bm,response:z.extend({conflicts:Gm})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:Vm,response:z.extend({resolution:Lm})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:qm,response:z.extend({verification:Um})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:wm.safeExtend({...gi,customerId:w.uuid().optional()}),response:z.extend({quote:Ai})},recordMerchantEvent:{method:"POST",path:"merchant/events/record",permission:"billing:write",audience:"server",request:Dg,response:z.extend({record:Fg})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Mr.extend({customerId:w.uuid().optional(),intent:w.enum(["confirm","cancel"]).optional()}),response:z.extend({operation:bi})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Mr.extend({customerId:w.uuid().optional()}),response:z.extend({operation:bi})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:Cm.safeExtend({customerId:w.uuid().optional()}),response:z.extend({quote:Em})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Mr.extend({customerId:w.uuid().optional(),intent:w.enum(["confirm","cancel"]).optional()}),response:z.extend({operation:jc})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Mr.extend({customerId:w.uuid().optional()}),response:z.extend({operation:jc})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:Rm.safeExtend({customerId:w.uuid()}),response:z.extend({quote:Tc})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Mr.extend({customerId:w.uuid()}),response:z.extend({operation:Ra})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Mr.extend({customerId:w.uuid()}),response:z.extend({operation:Ra})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:np,response:z.extend({controls:uc})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:Jd,response:z.extend({prepared:Wd})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:Yd,response:z.extend({authorization:la})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:sp,response:z.extend({coupons:cp})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Xd,response:z.extend({authorization:la})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:op,response:z.extend({invoices:ap})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:ip.extend({customerId:w.uuid()}),response:z.extend({operation:ki})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:rp,response:z.extend({invoice:Qi})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:w.object({customerId:w.uuid(),command:tp}).strict(),response:z.extend({controls:uc})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:w.object({customerId:w.uuid(),command:ng}).strict(),response:z.extend({entity:rg})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:w.strictObject({customerId:w.uuid().nullable(),query:ug}),response:z.extend({analytics:lg})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:w.object({customerId:w.uuid().nullable(),query:Gr}).strict(),response:z.extend({analytics:sg})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:dg,response:z.extend({batchId:w.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:pg,response:z.extend({batch:mg})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:qp.extend({customerId:w.string().min(1).optional()}),response:z.extend({check:Rr})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:w.strictObject({kind:ar,selector:w.discriminatedUnion("type",[w.strictObject({type:w.literal("resource"),id:w.uuid()}),w.strictObject({type:w.literal("version"),id:w.uuid()})]),customerId:w.string().min(1).optional()}),response:z.extend({content:Ec})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Wf,response:z.extend({paywall:Vr})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:w.strictObject({processContext:Pa.optional(),...gi,selector:Wm,customerId:w.string().min(1).optional(),commerce:ui,requirement:ir.optional()}),response:z.extend({offering:Ym,candidates:w.array(hc).max(20),availability:w.array(w.strictObject({productVersionId:w.uuid(),available:w.boolean(),reason:w.enum(["platform_binding_missing","commercial_runtime_pending","commerce_not_configured","currency_mismatch","product_unavailable","already_attached","attach_in_progress","already_scheduled","subscription_change_required","purchase_conflict"]).nullable()})).max(20),check:Rr.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:w.object({customerId:w.uuid().optional(),entityId:w.uuid().optional()}).strict(),response:z.extend({holdings:wp})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:w.object({customerId:w.uuid().optional(),query:Pp}).strict(),response:z.extend({ledger:Cp})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:xp.extend({customerId:w.uuid().optional()}),response:z.extend({detail:Sp})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:pc.safeExtend({customerId:w.uuid().optional()}),response:z.extend({statement:Ip})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:w.object({customerId:w.uuid().optional(),command:Yi.options[0]}).strict(),response:z.extend({quote:fp})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:w.strictObject({customerId:w.uuid(),command:w.union([w.strictObject({eventName:w.string().min(1),quantity:xe.optional(),properties:vt.optional(),entityId:w.uuid().optional(),idempotencyKey:w.string().min(1).max(120)}),w.strictObject({internal_feature_id:w.uuid(),quantity:xe.optional(),properties:vt.optional(),entityId:w.uuid().optional(),idempotencyKey:w.string().min(1).max(120)})])}),response:z.extend({receipts:w.array(Xi).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:w.object({customerId:w.uuid(),command:Yi.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:z.extend({receipt:Xi})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:Ig,response:z.extend({redemption:Sg})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:Og,response:z.extend({referralCode:Pg})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:vg,response:z.extend({checkout:wg})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:Ep,response:z.extend({seats:gc})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Rp,response:z.extend({seats:gc})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:aI,response:sI},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:au,response:z.extend({customer:Ci})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:kf,response:z.extend(jf.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:Rf,response:z.extend(Ef.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:w.object({customerId:w.uuid()}).strict(),response:z.extend(Wn.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:w.strictObject({}),response:z.extend(Wn.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:w.strictObject({customerId:w.uuid(),sessionId:w.uuid().optional()}),response:z.extend({revoked:w.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:w.strictObject({guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:Ja.optional()}),response:z.extend({customerId:w.uuid(),guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:w.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:w.strictObject({guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:z.extend(Wn.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:w.strictObject({guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:w.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:w.uuid()}),response:z.extend({customer:Ci,switched:w.boolean(),replayed:w.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:w.strictObject({code:w.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:w.uuid()}),response:zg()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:w.object({}).strict(),response:z.extend({offers:w.array(Gi)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:w.object({customerId:w.string().min(1).max(255).optional(),couponId:w.uuid(),...gi,requestId:w.uuid(),couponContentDigest:w.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:zg()}},sT={recordMerchantEvent:O.recordMerchantEvent,sendMessage:O.sendMessage,readMessage:O.readMessage,bindPushInstallation:O.bindPushInstallation,readPushInstallation:O.readPushInstallation,updatePushAddress:O.updatePushAddress,readMessagingPreference:O.readMessagingPreference,setMessagingPreference:O.setMessagingPreference,listInvoiceTemplates:O.listInvoiceTemplates,previewInvoice:O.previewInvoice,createInvoice:O.createInvoice,manageInvoice:O.manageInvoice,readInvoiceOperation:O.readInvoiceOperation,listInvoices:O.listInvoices,getInvoice:O.getInvoice,getCodeReferenceConfig:O.getCodeReferenceConfig,submitCodeReferences:O.submitCodeReferences,getFeatures:O.getFeatures,evaluateFeatures:O.evaluateFeatures,trackEvents:O.trackEvents,setupPayment:O.setupPayment,readPaymentSetup:O.readPaymentSetup,previewSubscriptionBatch:O.previewSubscriptionBatch,confirmSubscriptionBatch:O.confirmSubscriptionBatch,readSubscriptionBatch:O.readSubscriptionBatch,abandonSubscriptionBatch:O.abandonSubscriptionBatch,manageSubscriptionTrial:O.manageSubscriptionTrial,readSubscriptionTrial:O.readSubscriptionTrial,listSubscriptions:O.listSubscriptions,listPurchases:O.listPurchases,listSubscriptionConflicts:O.listSubscriptionConflicts,retrySubscriptionConflict:O.retrySubscriptionConflict,readAiPricing:O.readAiPricing,readUsage:O.readUsage,setUsage:O.setUsage,previewRefund:O.previewRefund,refund:O.refund,readRefund:O.readRefund,previewUpdate:O.previewUpdate,update:O.update,readSubscriptionUpdate:O.readSubscriptionUpdate,restoreNativePurchase:O.restoreNativePurchase,verifySubscriptions:O.verifySubscriptions,previewAttach:O.previewAttach,attach:O.attach,readSubscriptionOperation:O.readSubscriptionOperation,manageBalanceGrant:O.manageBalanceGrant,readBalanceSource:O.readBalanceSource,adjustBalance:O.adjustBalance,listBalanceGrants:O.listBalanceGrants,readBillingControls:O.readBillingControls,prepareBillingAuthorization:O.prepareBillingAuthorization,confirmBillingAuthorization:O.confirmBillingAuthorization,setBillingCoupons:O.setBillingCoupons,revokeBillingAuthorization:O.revokeBillingAuthorization,listBillingInvoices:O.listBillingInvoices,confirmBillingAdjustment:O.confirmBillingAdjustment,prepareBillingAdjustment:O.prepareBillingAdjustment,manageBillingLimits:O.manageBillingLimits,createCustomer:O.createCustomer,getCustomer:O.getCustomer,listCustomers:O.listCustomers,updateCustomer:O.updateCustomer,createSession:O.createSession,refreshSession:O.refreshSession,revokeSessions:O.revokeSessions,createGuestCustomer:O.createGuestCustomer,resumeGuestSession:O.resumeGuestSession,claimGuestCustomer:O.claimGuestCustomer,checkEntitlement:O.checkEntitlement,resolveOffering:O.resolveOffering,resolveContent:O.resolveContent,resolvePaywall:O.resolvePaywall,readHoldings:O.readHoldings,readLedger:O.readLedger,readBillingInvoice:O.readBillingInvoice,readCreditStatement:O.readCreditStatement,quoteBalance:O.quoteBalance,trackUsage:O.trackUsage,mutateBalance:O.mutateBalance,manageUsageEntity:O.manageUsageEntity,readUsageAnalytics:O.readUsageAnalytics,readCreditAnalytics:O.readCreditAnalytics,submitUsageBatch:O.submitUsageBatch,readUsageBatch:O.readUsageBatch,listOffers:O.listOffers,grantOffer:O.grantOffer,redeemCoupon:O.redeemCoupon,redeemReward:O.redeemReward,createReferralCode:O.createReferralCode,claimRewardProduct:O.claimRewardProduct,readSeats:O.readSeats,manageSeat:O.manageSeat};import{z as Nu}from"zod";var wo=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function Du(e,t,n){let r={},i,a,o,s="next",c;switch(e.type){case"entry":c=e.next;break;case"condition":{let u=e.cases.findIndex(l=>en(t.attributes??{},l.condition,t.savedGroups??{}));s=u<0?"default":`case:${u}`,c=u<0?e.default:e.cases[u].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new wo("Required GB Feature is unavailable");i=Kn(e.featureKey,t),o=i.value,Object.assign(r,fi(e,{value:o})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new wo("Required GB Experiment is unavailable");if(a=ca(u,t),o=a.value,s=a.inExperiment&&!a.passthrough&&typeof o=="string"?o:"notParticipating",c=s==="notParticipating"?e.notParticipating:e.routes[s],!c)throw new wo("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:Kn(e.configuration.featureKey,t).value;o={type:"offering_version",id:Nu.uuid().parse(u)},Object.assign(r,fi(e,{value:o})),c=e.next;break}case"coupon":case"coupons":o=e.type==="coupons"?e.couponIds.map(u=>({type:"reward",id:u})):{type:"reward",id:e.couponId},Object.assign(r,fi(e,{value:o})),c=e.next;break}return{port:s,target:c,projections:r,...o===void 0?{}:{value:o},...i?{feature:i}:{},...a?{experiment:a}:{}}}function $g(e,t,n){Nu.uuid().parse(e),Nu.number().int().nonnegative().parse(t);let r=ni(ri(new TextEncoder().encode(JSON.stringify([e,t,n])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}import{z as H}from"zod";var lr=H.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),cI=H.enum(["running","waiting","completed","closed","ineligible","failed"]),Fu=H.discriminatedUnion("type",[iu,H.strictObject({type:H.literal("wait"),receiptId:H.uuid(),kind:H.enum(["timer","event","operation"]),deadline:H.iso.datetime({offset:!0}).nullable(),eventName:lr.optional()}),H.strictObject({type:H.literal("open_url"),receiptId:H.uuid(),url:su,openIn:cu}),H.strictObject({type:H.literal("event"),receiptId:H.uuid(),event:lr})]),as=H.strictObject({type:H.literal("funnel"),id:H.uuid(),versionId:H.uuid()}),uI={id:lr,presentation:Pn,outputs:H.array(lr).max(250),inputs:za,values:H.record(H.string(),ve).optional(),offeringKey:It.optional(),capabilities:li,customerData:Gp,dataCursors:H.record(lr,La.nullable())},lI=H.strictObject({...uI,content:H.strictObject({type:H.literal("document"),document:un})}),Oo=H.strictObject({id:H.uuid(),source:as,revision:H.number().int().nonnegative(),visit:H.number().int().nonnegative(),nodeId:lr,nodeType:H.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:cI,stopped:H.boolean(),canBack:H.boolean(),authenticated:H.boolean(),locale:H.string().min(1).max(35),answers:sr,parameters:cr,variables:H.record(H.string(),ve),output:ve.nullable(),screen:lI.nullable(),paywall:H.strictObject({receiptId:H.uuid(),resolution:H.union([xo,Vr]),quote:Ai.nullable(),operation:bi.nullable(),purchaseRequestId:H.uuid().nullable(),selectionGeneration:H.number().int().nonnegative().optional(),canReselect:H.boolean().optional()}).nullable(),instruction:Fu.nullable(),pendingRequest:H.strictObject({requestId:H.uuid(),authenticationRequired:H.boolean()}).nullable(),runExpiresAt:H.iso.datetime({offset:!0}),credentialExpiresAt:H.iso.datetime({offset:!0}).nullable()}),ss=H.strictObject({scope:Ne,run:Oo,settlement:H.strictObject({requestId:H.uuid(),state:H.enum(["pending","unknown","settled"]),operationId:H.uuid().nullable(),receiptId:H.uuid().nullable().optional()}).optional(),purchase:H.strictObject({receiptId:H.uuid(),quote:Ai.nullable(),operation:bi.nullable(),canReselect:H.boolean().optional()}).optional(),review:H.strictObject({activeOperationId:H.uuid().nullable(),pages:H.array(H.strictObject({receiptId:H.uuid(),nodeId:lr,visit:H.number().int().nonnegative()})).max(100),page:H.strictObject({receiptId:H.uuid(),nodeId:lr,visit:H.number().int().nonnegative(),document:un,answers:sr,inputs:za,values:H.record(H.string(),ve).optional()}).nullable(),coupons:H.array(H.strictObject({grantId:H.uuid(),status:H.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:H.string().nullable()})).max(100),purchases:H.array(H.strictObject({receiptId:H.uuid(),operationId:H.uuid(),status:H.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:H.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:H.uuid().optional()}),Gg=ss.extend({run:Oo.extend({paywall:Oo.shape.paywall.unwrap().extend({resolution:Vr}).nullable()})});var Kg="X-Indiana-Server-Key";import{z as se}from"zod";import{z as Ae}from"zod";import{z as _t}from"zod";var dI=_t.strictObject({selector:_t.string().min(1).max(2048),action:_t.enum(["set","append","remove"]),attribute:_t.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:_t.string().max(5e4).optional(),parentSelector:_t.string().max(2048).optional(),insertBeforeSelector:_t.string().max(2048).optional()}),pI=_t.strictObject({variation:_t.string().min(1).max(128),description:_t.string().max(2e3).default(""),css:_t.string().max(1e5).default(""),js:_t.string().max(1e5).default(""),domMutations:_t.array(dI).max(200).default([]),iam:gf.optional(),renderGuard:Ba.optional()}),Mu=pI.omit({variation:!0,description:!0,iam:!0}),mI=wi.omit({variations:!0,active:!0}).extend({changeId:_t.string().regex(/^[a-f0-9]{64}$/),variations:_t.tuple([Mu,Mu]).rest(Mu).refine(e=>e.length<=20)}),Hg=_t.strictObject({trackExposures:_t.boolean(),environmentId:_t.uuid(),generation:_t.string().regex(/^[a-f0-9]{64}$/),experiments:_t.array(mI).max(100),savedGroups:mo});var Po=Ae.string().regex(/^[a-f0-9]{64}$/),VT=Ae.strictObject({iam:Po,executionContracts:Ae.union([Ae.tuple([Ae.literal("funnel-run/1")]),Ae.tuple([Ae.literal("funnel-process/1")])]).default(["funnel-run/1"])}),fI=Ae.strictObject({release:Po,render:Ba,button:Ae.strictObject({selector:Ae.string().min(1).max(512),elementKey:Ae.string().min(1).max(256),tag:Ae.enum(["button","a","input"])}).nullable()}),LT=Ae.strictObject({scope:Ne.extend({environmentId:Ae.uuid()}),release:Po,validatedAt:Ae.iso.datetime({offset:!0}),validUntil:Ae.iso.datetime({offset:!0}),entries:Ae.array(Ae.strictObject({id:Ae.uuid(),funnelId:Ae.uuid(),versionId:Ae.uuid(),event:Ae.enum(["screen_enter","button_click"]),target:fI})).max(4e3)}),Qg=Ae.strictObject({operation:Ae.literal("entry_start"),funnelId:Ae.uuid(),versionId:Ae.uuid(),entryId:Ae.uuid(),release:Po,requestId:Ae.uuid(),locale:Ae.string().min(1).max(35).default("en")}),Jg=Ae.strictObject({scope:Ne,suppressed:Ae.literal(!0),reason:Ae.enum(["frequency","in_progress"]),retryAt:Ae.iso.datetime({offset:!0}).nullable()}),zT=Ae.strictObject({experimentId:Ae.uuid(),splitNodeId:Ae.string().min(1).max(128)}),gI=Ae.strictObject({experimentId:Ae.uuid(),experimentKey:Ae.string().min(1).max(128),variationKey:Ae.string().min(1).max(128),inExperiment:Ae.boolean(),generation:Ae.string().min(1).max(256)}),Co=Ae.strictObject({operation:Ae.literal("page_experiments"),release:Po,usedReceiptIds:Ae.array(Ae.uuid()).max(20).default([]),customerToken:Ae.string().regex(kt).optional()}),Zg=Ae.strictObject({scope:Ne,runId:Ae.uuid(),assignments:Ae.array(gI.extend({receiptId:Ae.uuid()})).max(100),payload:Hg});var jn=se.literal(uf),hI=se.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),qu=se.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),Wg=se.discriminatedUnion("type",[se.strictObject({type:se.literal("guest"),guestToken:qu}),se.strictObject({type:se.literal("customer"),customer:Ur,customerData:Pi.optional()})]),Uu=se.strictObject({id:se.uuid(),runId:se.uuid(),customerId:se.uuid(),requestId:se.uuid(),acceptedAt:se.iso.datetime({offset:!0})}),yI=se.strictObject({participantId:se.uuid(),startedAs:se.enum(["guest","identified"]),binding:Uu.omit({runId:!0,requestId:!0}).nullable()}),AI=se.union([Fu,se.strictObject({type:se.literal("authentication_required"),reason:se.enum(["customer_required","customer_experiment_required"]),nodeId:se.string().min(1).max(64),visit:se.number().int().nonnegative()})]),bI=Oo.omit({authenticated:!0}).extend({identity:yI,instruction:AI.nullable()}),xI=se.discriminatedUnion("operation",[Ot.options[2].omit({customerToken:!0}),Ot.options[3].omit({customerToken:!0}),Ot.options[4].omit({customerToken:!0}),Ot.options[5].omit({customerToken:!0}),Ot.options[6].omit({customerToken:!0}),Ot.options[7].omit({customerToken:!0})]),cs={contract:jn,customerToken:se.string().regex(kt)},Yg={contract:jn,requestId:se.uuid(),runToken:hI,externalUserId:Ur.options[1].shape.value},Xg=se.discriminatedUnion("operation",[se.strictObject({contract:jn,operation:se.literal("describe")}),se.strictObject({contract:jn,operation:se.literal("start"),source:Wg,funnelId:Ot.options[0].shape.funnelId,requestId:se.uuid(),locale:Ot.options[0].shape.locale,parameters:Ot.options[0].shape.parameters}),Qg.omit({operation:!0}).extend({contract:jn,operation:se.literal("entry_start"),source:Wg}),se.strictObject({...Yg,operation:se.literal("bind_customer"),guestToken:qu,claimRequestId:se.uuid(),expectedBindingId:se.null()}),se.strictObject({...Yg,operation:se.literal("binding_status"),guestToken:qu.optional()}),Ot.options[1].omit({operation:!0,customerToken:!0}).extend({...cs,operation:se.literal("get"),settlementBindingId:se.uuid().nullable().optional()}),Ot.options[8].omit({operation:!0,customerToken:!0}).extend({...cs,operation:se.literal("review")}),Co.omit({customerToken:!0}).extend(cs),se.strictObject({...cs,operation:se.literal("command"),identity:se.strictObject({bindingId:se.uuid().nullable()}),command:xI})]),Bu=ss.omit({run:!0}).extend({contract:jn,run:bI,settlement:ss.shape.settlement.unwrap().extend({accepted:se.boolean().nullable().optional()}).optional()}),XT=Jg.extend({contract:jn}),eN=se.discriminatedUnion("operation",[Xg.options[1].omit({contract:!0,source:!0,requestId:!0}),Xg.options[2].omit({contract:!0,source:!0,requestId:!0})]),tN=Bu.extend({binding:Uu,outcome:se.enum(["bound","already_bound"]),replayed:se.boolean()}),nN=se.discriminatedUnion("state",[se.strictObject({contract:jn,scope:Ne,state:se.literal("not_accepted")}),se.strictObject({contract:jn,scope:Ne,state:se.literal("conflict")}),se.strictObject({contract:jn,scope:Ne,state:se.literal("bound"),binding:Uu})]),rN=se.strictObject({contract:jn,scope:Ne,keyId:se.uuid(),operations:se.array(se.string()).max(20)});import{z as Fe}from"zod";var ji=Fe.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),th=Fe.strictObject({entry:ji,nodes:Fe.array(Fe.strictObject({id:ji,type:Fe.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:Fe.record(Fe.string(),ji),writes:Fe.record(It,It),resources:Fe.strictObject({screenId:ji.optional(),paywallVersionId:Fe.uuid().optional(),couponId:Fe.uuid().optional(),couponIds:Fe.array(Fe.uuid()).max(20).optional(),experimentId:Fe.uuid().optional(),featureKey:Fe.string().optional(),offeringVersionId:Fe.uuid().optional()})})).min(1).max(500)}),eh={scope:Ne,funnelId:Fe.uuid(),versionId:Fe.uuid(),evaluationRevision:Fe.number().int().nonnegative(),expiresAt:Fe.iso.datetime({offset:!0}).nullable(),topology:th},us=Fe.discriminatedUnion("evaluationMode",[Fe.strictObject({...eh,evaluationMode:Fe.literal("local"),growth:yn,conditions:Fe.record(ji,Fe.array(Fe.strictObject({condition:Yt,port:Fe.string()})))}),Fe.strictObject({...eh,evaluationMode:Fe.literal("remote")})]),SI=us.options[0].extend({evaluation:Fe.strictObject({maxTransitions:Fe.number().int().min(1).max(1e4),variables:Fe.record(It,mi),outputSchema:pi,terminals:Fe.record(ji,Fe.strictObject({outcome:Fe.enum(["completed","closed","ineligible","failed"]),output:ho.nullable()}))})});function II(e){return th.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let n={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":n.next=t.next;break;case"screen":Object.assign(n,t.outputs),r.screenId=t.screenId;{let a=e.screens.find(o=>o.id===t.screenId);a?.type==="paywall"&&(r.paywallVersionId=a.paywallVersionId)}break;case"condition":t.cases.forEach((a,o)=>{n[`case:${o}`]=a.target}),n.default=t.default;break;case"split":Object.assign(n,t.routes),n.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let a of["success","cancel","unavailable","failure"])n[a]=t[a];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=Fe.uuid().parse(t.action.coupon.value.id));break;case"external_page":n.opened=t.opened,n.failed=t.failed;break;case"wait":t.wait.type==="duration"?n.elapsed=t.wait.elapsed:(n.received=t.wait.received,n.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let i=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return i?.type==="feature"&&(r.featureKey=i.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:n,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function Vu(e){let t=Ei.parse(e.document),n=e.evaluationMode==="local"?yn.parse(e.payload):null;if(n&&(n.scope.projectId!==e.scope.projectId||n.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:n?.expiresAt??null,topology:II(t)};return us.parse(e.evaluationMode==="remote"?r:{...r,growth:ns(t,n),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((a,o)=>({condition:a.condition,port:`case:${o}`}))]))})}function nh(e){let t=Vu(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=Ei.parse(e.document);return SI.parse({...t,evaluation:{maxTransitions:n.execution.maxTransitions,variables:n.variables,outputSchema:n.outputSchema,terminals:Object.fromEntries(n.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}import{z as rt}from"zod";var rh=rt.string().regex(/^[a-f0-9]{64}$/),vI=wi.omit({variations:!0,active:!0}).extend({changeId:rh,variations:rt.array(rt.strictObject({urlRedirect:rt.string().max(2048)})).min(2).max(20)}),ih=rt.strictObject({environmentId:rt.uuid(),trackExposures:rt.boolean(),generation:rh,experiments:rt.array(vI).max(100),savedGroups:mo}),wI=rt.strictObject({eventUuid:rt.uuid(),timestamp:rt.iso.datetime({offset:!0}).optional(),deviceId:rt.string().min(1).max(128),sessionId:rt.string().min(1).max(128).optional(),url:rt.url().max(2048),pageTitle:rt.string().max(512).optional(),experimentKey:rt.string().min(1).max(255),variationKey:rt.string().min(1).max(64)}),hN=rt.strictObject({events:rt.array(wI).min(1).max(20)}),yN=rt.strictObject({inserted:rt.number().int().nonnegative(),duplicates:rt.number().int().nonnegative(),skipped:rt.number().int().nonnegative(),rejected:rt.array(rt.strictObject({index:rt.number().int().nonnegative(),reason:rt.string()}))});import{z as lt}from"zod";var zu=32,OI=522240;function $u(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var PI=lt.strictObject({nodeId:lt.string().min(1).max(64),visit:lt.number().int().nonnegative(),revision:lt.number().int().nonnegative()}),Lu=lt.record(lt.string(),ve),CI=lt.strictObject({id:lt.uuid(),nodeId:lt.string().min(1).max(64),visit:lt.number().int().nonnegative(),input:lt.strictObject({schemaVersion:yo.shape.schemaVersion,kind:yo.shape.kind,selector:yo.shape.selector,contract:yo.shape.contract}),context:Lu,removed:lt.array(lt.string()).max(100),attributes:Lu,removedAttributes:lt.array(lt.string()).max(100),result:Uf,offeringVersionId:lt.uuid().nullable(),events:lt.strictObject({entered:lt.string().regex(/^[1-9][0-9]{0,18}$/),decision:lt.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),vN=lt.strictObject({schemaVersion:lt.literal(1),mode:lt.enum(["local","remote"]),versionId:lt.uuid(),generation:lt.number().int().positive(),base:PI,context:Lu,steps:lt.array(CI).min(1).max(zu)}).refine(e=>ln(e)<=OI,"Segment exceeds its byte budget");var _I=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function _o(e){return Array.isArray(e)?e.some(_o):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&_o(n):!_I.test(t))}function oh(e,t,n,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(s=>s.id===t.screenId&&s.type==="paywall")))return"customer_required";let i=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(i&&["bundle","selection","offering"].includes(i.type)||t.type==="condition"&&t.cases.some(s=>_o(s.condition)))return"customer_required";let a=JSON.stringify([t,t.type==="screen"?e.screens.find(s=>s.id===t.screenId):null]);for(let[s,c]of Object.entries(e.variables))if(c.source.type==="attribute"&&c.source.key!=="funnelParticipantId"&&(a.includes(`variables.${s}`)||a.includes(JSON.stringify(s))))return"customer_required";if(t.type==="split"){let s=n.experiments?.[t.experimentId];if((s?.hashAttribute??"id")!=="funnelParticipantId"||_o(s?.condition)||s?.parentConditions?.length)return"customer_experiment_required"}let o=t.type==="feature"?t.featureKey:i?.type==="feature"?i.featureKey:void 0;return o&&n.features?.[o]?.rules?.some(s=>(s.hashAttribute??"id")!=="funnelParticipantId"||_o(s.condition)||s.parentConditions?.length)?"customer_experiment_required":null}var Gu=class extends Error{constructor(n,r){super(r);qe(this,"code",n);this.name="FunnelLocalCalculationError"}},ah=(e,t)=>new Gu(e,t),EI=e=>({experiments:e.experiments,features:e.features});function RI(e,t=ah){let n=new Map(e.topology.nodes.map(o=>[o.id,o])),r=ii(e.growth.savedGroups),i=EI(e.growth);function a(o,s){if(!Object.hasOwn(e.growth.features,o))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Kn(o,s).value}return{nodes:n,savedGroups:r,features:i.features,feature:a,evaluate(o,s){let c=n.get(o);if(!c)throw t("NOT_FOUND","Funnel node is unavailable");let u,l;if(c.type==="condition"){let f=e.conditions[c.id];if(!f)throw t("INVALID_RESPONSE","Local condition rules are unavailable");u=Du({id:c.id,name:c.id,type:"condition",cases:f.map(g=>({condition:g.condition,target:c.outputs[g.port]})),default:c.outputs.default},s,i.experiments).port}else if(c.type==="feature"){if(!c.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");l=a(c.resources.featureKey,s),u="next"}else if(c.type==="split"){if(!(c.resources.experimentId?e.growth.experiments[c.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let g=Du({id:c.id,name:c.id,type:"split",experimentId:c.resources.experimentId,routes:c.outputs,notParticipating:c.outputs.notParticipating},s,i.experiments);l=g.value,u=g.port}else if(["offering","end","output"].includes(c.type)&&c.resources.featureKey)l=a(c.resources.featureKey,s),u=c.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let m=c.outputs[u]??(u==="value"?c.id:void 0);if(!m)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:o,port:u,target:m,...l===void 0?{}:{value:l}}}}}function kI(e,t){let n=us.parse(e);if(n.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=n.expiresAt?Date.parse(n.expiresAt):null,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let a=RI(n,t);return(o,s)=>(i(),jI(a,o,s))}function jI(e,t,n){let r=wt.parse(n.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:a,onExperimentViewed:o}=n,s={attributes:r,...i?{saveStickyBucketAssignmentDoc:c=>i(structuredClone(c))}:{},...a?{onFeatureUsage:(c,u)=>a(c,structuredClone(u))}:{},...o?{onExperimentViewed:(c,u)=>o(structuredClone(c),structuredClone(u))}:{},features:e.features,savedGroups:e.savedGroups,...n.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(n.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,s)}function TI(e,t,n){let r=[],i=[],a=[],o=e(t,{...n.attributes?{attributes:n.attributes}:{},stickyBucketAssignmentDocs:n.sticky,saveStickyBucketAssignmentDoc(s){let c=r.findIndex(m=>m.next.attributeName===s.attributeName&&m.next.attributeValue===s.attributeValue),u=s.attributeName+"||"+s.attributeValue,l={expected:n.sticky[u]??null,next:s};c<0?r.push(l):r[c]=l},onExperimentViewed(s,c){c.inExperiment&&c.hashUsed&&!c.passthrough&&i.push(ve.parse({key:s.key,variationId:c.variationId,keyUsed:c.key,hashAttribute:c.hashAttribute,hashValue:c.hashValue}))},onFeatureUsage(s,c){a.push(ve.parse({feature:s,value:c.value,source:c.source,...c.ruleId?{ruleId:c.ruleId}:{}}))}});return{port:o.port,...o.value===void 0?{}:{value:o.value},sticky:r,exposures:i,features:a}}function sh(e,t,n,r=ah){let i=n,a=new Map(t.graph.nodes.map(R=>[R.id,R])),o=structuredClone(n.variables),s=structuredClone(i.sticky),c=[],u=n.nodeId,l=n.visit,m=!1,f,g=R=>oh(t,R,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),d=R=>(f??(f=kI(e,r)),TI(f,R,{attributes:Xc({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:o,savedGroups:{}}),sticky:s}));for(let R=0;R<zu;R++){let y=a.get(u);if(!y||!$u(y)||g(y))break;if(l>=t.execution.maxTransitions&&(l>t.execution.maxTransitions||y.type!=="end"&&y.type!=="output")){if(!c.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let A,x;if(["condition","feature","split"].includes(y.type)||y.type==="offering"&&y.configuration.source==="feature")A=d(y.id),y.type==="offering"&&(A.value={type:"offering_version",id:String(A.value)}),y.type==="condition"?x=A.port==="default"?y.default:y.cases[Number(A.port.slice(5))]?.target:y.type==="split"?x=A.port==="notParticipating"?y.notParticipating:y.routes[A.port]:(y.type==="feature"||y.type==="offering")&&(x=y.next);else if(A={port:"next",sticky:[],exposures:[],features:[]},(y.type==="entry"||y.type==="coupon"||y.type==="coupons")&&(x=y.next),y.type==="offering"&&y.configuration.source==="fixed"&&(A.value={type:"offering_version",id:y.configuration.versionId},x=y.next),y.type==="end"||y.type==="output"){let P=y.type==="end"?y.output:y.value;if(A=P?.type==="feature"?d(y.id):{...A,port:"value",value:P?.type==="literal"?P.value:P?.type==="variable"?Pc({source:"variable",key:P.key,...P.path?{path:P.path}:{}},{declarations:t.variables,answers:n.answers,results:o,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},P&&(A.value===void 0||!hn(t.outputSchema,A.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let v=[...c,{nodeId:u,result:A}];if(ln({steps:v})>6e4){if(!c.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(c.push({nodeId:u,result:A}),y.type==="feature"||y.type==="offering"||y.type==="coupon"||y.type==="coupons"){let P=y.type==="coupons"?y.couponIds.map(_=>({type:"reward",id:_})):y.type==="coupon"?{type:"reward",id:y.couponId}:A.value;if(P===void 0)throw r("INVALID_RESPONSE","Node output is missing");let j=fi(y,{value:P});em(t.variables,y,j),Object.assign(o,j)}for(let P of A.sticky)s[`${P.next.attributeName}||${P.next.attributeValue}`]=structuredClone(P.next);if(y.type==="end"||y.type==="output"){m=!0;break}if(!x)throw r("INVALID_RESPONSE","Local pure exit is unavailable");u=x,l++}let h=a.get(u);return{steps:c,...!m&&h&&(!$u(h)||g(h))?{boundary:{nodeId:u,visit:l}}:{}}}var b=class extends Error{constructor(n,r,i,a,o){super(r);qe(this,"code",n);qe(this,"status",i);qe(this,"requestId",a);qe(this,"commandRequestId");qe(this,"retryable");qe(this,"recovery");qe(this,"retryAfterSeconds");qe(this,"reason");this.name="IndianaError",this.reason=o?.reason;let s=Uo(n,i??0,{...o,retryAfter:o?.retryAfterSeconds===void 0?void 0:String(o.retryAfterSeconds)});this.retryable=s.retryable,this.recovery=s.recovery,this.retryAfterSeconds=s.retryAfterSeconds}};var Eo=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new b("INVALID_STATE","Installation sequence exhausted");return e+1},NI=async e=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(e,t=>t.charCodeAt(0))))].map(t=>t.toString(16).padStart(2,"0")).join("");function qn(e,t){return e.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new b("INVALID_STATE","Installation journal is invalid");return t({...n})})}function ch(e,t,n){let r=null,i=0,a=0,o=0,s=Promise.resolve(),c=!1;if(e&&(!n||Ne.parse(e.scope).projectId!==n.projectId||e.scope.environment!==n.environment))throw new b("SCOPE_MISMATCH","Push installation belongs to another scope");let u=()=>{if(c)throw new b("CLOSED","SDK client was destroyed");if(!e)throw new b("NOT_CONFIGURED","Configure this client's native Push host first");return e},l=x=>{if(x!==i)throw new b("IDENTITY_CHANGED","Identity changed during Push operation")};async function m(x){let v=u();if(!v.sha256&&!globalThis.crypto?.subtle)throw new b("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let P=v.sha256?await v.sha256(Uint8Array.from(x,j=>j.charCodeAt(0))):await NI(x);if(!/^[a-f0-9]{64}$/.test(P))throw new b("INVALID_STATE","Push credential digest is invalid");return P}function f(x){let v=Ir.parse(x);if(v.installationId.toLowerCase()!==u().installationId.toLowerCase())throw new b("INVALID_RESPONSE","Push response belongs to another installation");return v}async function g(x,v){let P=u(),j={installationId:P.installationId,publicKey:P.publicKey,issuedAt:new Date().toISOString(),...v},_=await P.sign(Pl(x,P.scope,j));return{...j,signature:_}}let d=(x,v,P)=>t.requestWithCredential?t.requestWithCredential(x,v,P):t.request(x,v);async function h(){let x=u(),v=i,P=r?await(t.session?.access()??r):null,j=qn(x,Se=>Se),_;if(j.detachSeq!==null){let Se=j.detachSeq,ht=vl.parse(await g("detach",{sequence:Se,platform:x.platform}));try{let Je=await t.request("push/installations/detach",{...x.scope,...ht},"POST",{installationDetach:!0});if(!Je||typeof Je!="object"||!("installation"in Je))throw new b("INVALID_RESPONSE","Push detach acknowledgement is invalid");let Te=f(Je.installation);if(Te.bound||Te.identitySeq!==Se)throw new b("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(Je){if(Je instanceof b&&Je.status===404)_=Je;else if(!(Je instanceof b)||Je.status!==412)throw Je}_||qn(x,Je=>({...Je,detachSeq:Je.detachSeq===Se?null:Je.detachSeq}))}if(l(v),!P){if(_)throw _;return null}let X=O.bindPushInstallation,le=X.request.parse(await g("bind",{sequence:o,platform:x.platform,credentialDigest:await m(P)}));l(v);let he=X.response.parse(await d(X.path,le,P));l(v);let ke=f(he.installation);if(!ke.bound||ke.identitySeq!==o)throw new b("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return _&&j.detachSeq!==null&&o>j.detachSeq&&qn(x,Se=>({...Se,detachSeq:Se.detachSeq===j.detachSeq?null:Se.detachSeq})),ke}async function R(){u();let x=i,v=r?await(t.session?.access()??r):null;if(!v)throw new b("NOT_IDENTIFIED","Identify before reading this installation");let P=O.readPushInstallation,j=P.request.parse(await g("read",{credentialDigest:await m(v)}));l(x);let _=P.response.parse(await d(P.path,j,v));return l(x),f(_.installation)}function y(x=h){let v=s.catch(()=>{}).then(x);return s=v,v.catch(P=>{try{e?.onError?.(P instanceof Error?P:new Error("Push synchronization failed"))}catch{}}),v}async function A(x,v,P){let j=u(),_=v.identity,X=v.observation,le=r?await(t.session?.access()??r):null;if(l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");if(!le)throw new b("NOT_IDENTIFIED","Identify before recovering a Push address");if(!x.connectionId||!x.kind||!x.token||!["granted","provisional"].includes(x.permission))throw new b("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await y(async()=>{if(l(_),await h(),l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let he=qn(j,Te=>P?Te:{...Te,addressSeq:Eo(Te.addressSeq)}),Se=await g(P?"recovery_confirm":"recovery_request",{...x,sequence:he.addressSeq,credentialDigest:await m(le),...P?{challenge:P}:{}}),ht=P?Ol.parse(Se):wl.parse(Se);if(l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let Je=await d(`push/installations/recovery/${P?"confirm":"request"}`,ht,le);if(l(_),X!==a||qn(j,Te=>Te).addressSeq!==he.addressSeq)throw new b("INVALID_STATE","Push observation changed during recovery");if(P){let Te=O.updatePushAddress.response.parse(Je),tt=f(Te.installation);if(!tt.bound||tt.identitySeq!==o||tt.addressSeq!==he.addressSeq||tt.connectionId!==x.connectionId||tt.addressStatus!=="active")throw new b("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return tt}if(!Je||typeof Je!="object"||!("recovery"in Je))throw new b("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return Ps.parse(Je.recovery)})}return{recoveryObserver(){u();let x={identity:i,observation:++a};return{async request(v){return Ps.parse(await A(v,x))},async confirm(v,P){return Ir.parse(await A(P,x,v))}}},identify(x){if(!e)return;o=qn(e,P=>({...P,identitySeq:Eo(P.identitySeq)})).identitySeq,r=x,i++,a++},reset(){if(e)try{qn(e,x=>{let v=Eo(x.identitySeq);return{...x,identitySeq:v,detachSeq:v}})}finally{r=null,i++,a++}},start(){e&&!c&&y()},destroy(){c=!0,r=null,i++,a++},async sync(){return await y()},read:R,async recover(){let x=u(),v=i,P=o;return a++,await y(async()=>{l(v);let j=await R();return l(v),o=qn(x,X=>{if(X.identitySeq!==P)throw new b("IDENTITY_CHANGED","A newer installation intent exists");return{...X,identitySeq:Eo(Math.max(X.identitySeq,j.identitySeq)),addressSeq:Math.max(X.addressSeq,j.addressSeq)}}).identitySeq,await h()})},tokenObserver(){u();let x=++a,v=i;return async P=>{if(x!==a||v!==i)return null;let j=u(),_=r?await(t.session?.access()??r):null;if(!_)throw new b("NOT_IDENTIFIED","Identify before registering a Push token");if(await y(),l(v),x!==a)return null;let X=qn(j,Se=>({...Se,addressSeq:Eo(Se.addressSeq)})),le=O.updatePushAddress,he=le.request.parse(await g("address",{...P,sequence:X.addressSeq,credentialDigest:await m(_)}));if(l(v),x!==a)return null;let ke=await d(le.path,he,_);return l(v),x!==a||qn(j,Se=>Se).addressSeq!==X.addressSeq?null:f(le.response.parse(ke).installation)}}}}import{ZodError as DI}from"zod";function uh(e,t,n,r){try{return e.parse(t)}catch(i){throw r&&i instanceof DI?new b(n,r):i}}async function ge(e,t,n,r={},i){let a=typeof r=="function"?{}:r,o=uh(t.request,n,"INVALID_REQUEST",a.request);try{let s=await e(t.path,o,t.method,i),c=typeof r=="function"?r:r.parseResponse;return c?c(t.response,s):uh(t.response,s,"INVALID_RESPONSE",a.response)}catch(s){throw s instanceof b&&o!==null&&typeof o=="object"&&"requestId"in o&&typeof o.requestId=="string"&&(s.commandRequestId??(s.commandRequestId=o.requestId)),s}}function lh(e,t){let n={async preference(r){let i=O.readMessagingPreference;return(await ge(e,i,{channel:r})).preference},async setPreference(r){let i=O.setMessagingPreference;return(await ge(e,i,r)).preference}};return{messaging:n,push:{sync:t.sync,read:t.read,recover:t.recover,tokenObserver:t.tokenObserver,recoveryObserver:t.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return n.setPreference({...r,channel:"push"})}}}}var dh={name:"@tinkerlandai/longplay-sdk",version:"0.10.18-rc.1",description:"Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit && tsc --noEmit -p tsconfig.test.json",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};function Qe(e){return typeof e=="string"?e:String(e)}var MI=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function qI(e){return e.replace(MI,"$1\uFFFD")}function Ju(e,t){if(typeof e!="object"||e==null){let n="";throw n+="The provided value is not an object",new TypeError(n)}return e}function xh(e){if(e!=null&&(typeof e=="object"||typeof e=="function")){let t=e[Symbol.iterator];if(t==null)return;if(typeof t!="function")throw new TypeError("The provided value is not iterable");let n=t.call(e);if(!n||typeof n!="object")throw new TypeError("Result of the Symbol.iterator method is not an object");return n}}function ph(e){let t;if(Array.isArray(e)){let n=e.map(Qe);if(n.length===2)return n}else if((t=xh(e))!=null){let n=Ju(t.next()),r=Ju(t.next());if(!n.done&&!r.done)return[Qe(n.value),Qe(r.value)]}throw new TypeError("Each query pair must be an iterable [name, value] tuple")}var mh="0123456789ABCDEF",UI=/(?:%[0-9A-Fa-f]{2})+/g;function Un(e){return`%${mh[e>>4&15]}${mh[15&e]}`}function Sh(e,t,n=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?n&&e===32?"+":t(e)?Un(e):String.fromCharCode(e):e<=2047?Un(192|e>>6)+Un(128|63&e):e<=65535?Un(224|e>>12)+Un(128|e>>6&63)+Un(128|63&e):Un(240|e>>18)+Un(128|e>>12&63)+Un(128|e>>6&63)+Un(128|63&e)}function Zu(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function Wu(e,t=!1){let n=0;for(;n<e.length;n++){let r=e.charCodeAt(n);if(r===37||t&&r===43)break}return n===e.length?e:(t?e.replace(/\+/g," "):e).replace(UI,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function jo(e){return e<=31||e>126}function BI(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return jo(e)}}function il(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return jo(e)}}function VI(e){return il(e)||e===39}function Yu(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return il(e)}}function fs(e){switch(e){case 47:case 58:case 59:case 61:case 64:case 91:case 92:case 93:case 124:return!0;default:return Yu(e)}}function fh(e){switch(e){case 33:case 39:case 40:case 41:case 126:return!0;default:return(function(n){switch(n){case 36:case 37:case 38:case 43:case 44:return!0;default:return fs(n)}})(e)}}function Ih(e,t){return Sh(e=e||0,t)}function Bn(e,t,n=!1){let r=0;for(;r<e.length;r++){let a=e.charCodeAt(r);if(a>=128||n&&a===32||t(a))break}if(r===e.length)return e;let i=e.slice(0,r);for(;r<e.length;r++){let a=e.charCodeAt(r),o=a;if(a>=55296&&a<=56319&&r+1<e.length){let s=e.charCodeAt(r+1);s>=56320&&s<=57343&&(o=(a-55296<<10)+s-56320+65536,r++)}i+=Sh(o,t,n)}return i}function ol(e){let t=[],n=0,r=0;for(;r<=e.length;){if(r=e.indexOf("&",n),r<0&&(r=e.length),r!==n){let i=e.slice(n,r),a=i.indexOf("=");a<0&&(a=i.length),t.push([Wu(i.slice(0,a),!0),Wu(i.slice(a+1),!0)])}if(n=r+1,r===e.length)break}return t}function Xu(e){let t="";for(let n=0;n<e.length;n++){let r=Bn(e[n][0],fh,!0),i=Bn(e[n][1],fh,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var LI=[2191,2191,3164,3164,3292,3292,6863,6877,6880,6891,8385,8385,11158,11158,42958,42959,42962,42962,42964,42964,42993,42993,64451,64466,64912,64913,64968,64974,67904,67929,69317,69319,69328,69336,69370,69371,72544,72551,73136,73179,73184,73193,93856,93880,93883,93907,94194,94198,100344,100351,101641,101662,101760,101874,118010,118012,118458,118480,118496,118512,124608,124638,124640,124661,124670,124671,128728,128728,128887,128890,129232,129240,129620,129623,129674,129674,129678,129678,129736,129736,129741,129741,129770,129770,129775,129775,130042,130042,177978,177983,183970,183981,205744,210041],zI=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],$I=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],GI=[2381,2381,2509,2509,2637,2637,2765,2765,2893,2893,3021,3021,3149,3149,3277,3277,3387,3388,3405,3405,3530,3530,3642,3642,3770,3770,3972,3972,4153,4154,5908,5909,5940,5940,6098,6098,6752,6752,6980,6980,7082,7083,7154,7155,11647,11647,43014,43014,43052,43052,43204,43204,43347,43347,43456,43456,43766,43766,44013,44013,68159,68159,69702,69702,69744,69744,69759,69759,69817,69817,69939,69940,70080,70080,70197,70197,70378,70378,70477,70477,70606,70608,70722,70722,70850,70850,71103,71103,71231,71231,71350,71350,71467,71467,71737,71737,71997,71998,72160,72160,72244,72244,72263,72263,72345,72345,72767,72767,73028,73029,73111,73111,73537,73538,90415,90415];function KI(e){for(let t=0;t<e.length;t++){let n=e.codePointAt(t);if(n>65535&&t++,n<=32||n===37||n===127||n>=55296&&n<=57343||n>=128&&n<=159||n>=64976&&n<=65007||!(65534&~n)||n===65533)return!0}return!1}var[HI,QI,JI,gh]=[[[],"0,6,7,8,m,w,10,1b,1d,1f,72,73,7k,8k,dt,2rk","AAAAAAAAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAA/AAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAADAAABwfwAAAAAAAMADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhAAAAQAAAAAAAAQCAAABAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgACAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAP///////////////wAAAAAAAAAAAAAAAAAAAAA="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAEF9+P/+BwAAAMAA//8AAPz/////BlADAAAAAJwAAPz///8AAADA//H/5+X8AAAAAAAAAAAA/P///wcAAAAAAAAAAAAAPv0vAD0BAABA/gAA/5/5/f8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8g+N8B+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAYAAAAAAAAAAAAAD/////CwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANgAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/HgwAAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAP3////+BwAAAMDu//////////////8vAADAAJwAAP3///8AAADg////////AAAAAAAAAAAA/P///wcAAAAAAAAAAAAA////Ab0H//9H/gAA/9////8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL/G//8T+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAfgAAAAAAAAAAAAD+////DwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANwAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/Hg4AAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"0,3,4,5,6,7,8,9,a,b,c,d,e,f,g,j,n,o,p,q,r,s,t,w,18,19,1c,4m,4o,4p,4q,4r,6z,72,73,75,76,77,7e,7h,7i,7j,7k,7l,7m,7n,7o,7p,7q,7r,7s,7t,7u,7v,7w,7x,7y,7z,8k,9t,a2,a3,a7,cc,cv,cx,cy,d6,dc,dd,de,dg,dh,di,dk,dl,2rk,2rl","AAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAD//////////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD4AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/v////+/tgAAAAAAAAAAAP8XAAAAAAD4//8AAAEAAAAAAAAAAAAAAMCfnz0AAACAAgAAAP///wcAAAAAAAAAAAAAwP8BAAAAAAAA+A8gAADA++8+AAAAAAAOAAAAAAAAgP8AAAAAAPz///v///8HAAAAAAAAFP4h/gAMAAAAAgAAAAAAABAeIAAADAAAQAYAAAAAAAAQhjkCAAAAIwAGAAAAAAAAEL4hAAAMAAD8AgAAAAAAAJAeIGAADAAAAAQAAAAAAAAAASAAAAAAAAARAAAAAAAA0ME9YAAMAAAAAgAAAAAAAJBAMAAADAAAAAMAAAAAAAAYHiAAAAwAAAACAAAAAAAAAAAEXAAAAAAAAAAAAAAA8geAfwAAAAAAAAAAAAAAAPIfAH8AAAAAAAAAAAADAACgAgAAAAAAAP5/3+D//v///x9AAAAAAAAAAAAAAAAA4P1mAAAAwwEAHgBkIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAAAAMAAAADAAAAAwAAAAAAAAAsD9A/g8gAAAAAAC4AAAAAAAAAAAAAAAAAABgAAAAAAIAAAAAAAAAAAAAAAAAAIcBBA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAJAAAAAAAAQH/lH/ifAAAAAAAA//////8//w8AAA8AAAAAANAXBAAAAAD4DwADAAAAPDsAAAAAAABAowMAAAAAAADwzwAAAAAAAAAAAAAAAAAAAAAAAAD3//0hEAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////wDIAAAAfAAAAAAAAB/8AAAAAAAAAAAAAAAA/////wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAwAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAA/////wAAAAAAPAAAAAAAAAAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAID3PwAAAMAAAAAAAAAAAAAAAwBECAAAYBAAAAAAAAAAAAAAAAAAAAAAAAAwAAAA//8DgAAAAADAPwAAgP8DAAAAAAAHAAAAAADIMwAAAAAgAAAAAAAAAAB+ZgAIEAAAAAAAEAAAAAAAAJ3BAgAAAAAwQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICEAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8AAP//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAMAHAAAAAAAAAAAAAAAAAAAAAG7wAAAAAACHAAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAPAAAAAAAAAAAD4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAAAAAAAAA/AAAAAAAAAAAwP8BAAAAAAA8AAAAAAAAAAAAAAAAAAAAAgAAAAAAAP9/AAAAAAAZgAMAAAAAAHgGBAAAAAAAAAAHAAAAgO8fAAAAAAAAAAgAAwAAAAAAwH8AngAAAAAAAAAAAAAAgNNAAgAAAAAAAAAAAAAAAAAAAAAAAID4BwAAAwAAAAAAABgBAAAAwB8fAAAAAAAAAAD4AUAFAAYAAAAAAAAAAAAA/1wAAEAAAAAAAAAAAAAA+IUNAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8sAEAADAAAAAAAAAAAAAA+KcBAAAAAAAAAAAAAAAAKL8AAAAAAAAAAAAAAACgvA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgP8GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFgIAAAAAAAAAAAAAAAAAAAAAADwDAEAAAD+BwAAAAD4eYAAfg4AAAAAAPx/AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf78AAAAAAAAAAAAA/P///G0AAAAAAAAAAAAAAAAAAAB+tL8AAAAAAAAAAACjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAAwAAAAAAwAcFAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//4H/PwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMD/4wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHwAAAAAAAAB/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAgAcAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGAPAAAAAAAAAAAAAAD//////z///38AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAD+P/nDwAAADwAAAAAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////9/+P//////HyAAEAAA+P7/AAAAAAAAAAAAAH////nbBwAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASMAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAADwDwAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAA////////////////AAAAAAAAAAAAAAAAAAAAAP///////////////////////////////////////wAA"]].map(function([t,n,r]){return[t,n.split(",").map(i=>parseInt(i,36)),Uint8Array.from(atob(r),i=>i.charCodeAt(0))]});function ZI(e,t){return t===931||t===1010||t===120531||t===120589||t===120647||t===120705||t===120763?"\u03C3":t>=5112&&t<=5117?String.fromCodePoint(t-8):t>=43888&&t<=43967?String.fromCodePoint(t-38864):t>=93856&&t<=93880?String.fromCodePoint(t+27):t===837||t===890||t>=8064&&t<=8111||t>=8114&&t<=8188?e.normalize("NFD").replace(/\u0345/g,"\u03B9").normalize("NFC").toLowerCase():""}function vh(e,t){for(let n=0;n<e.length;n+=2)if(t>=e[n]&&t<=e[n+1])return!0;return!1}function Ro(e,t){let[n,r,i]=e,a=t>>8;for(let c=0;c<n.length;c+=2)if(a>=n[c]&&a<=n[c+1])return!0;let o=r.indexOf(a);if(o<0)return!1;let s=255&t;return!!(i[32*o+(s>>3)]&1<<(7&s))}function WI(e){let t=Array.from(e,n=>n.codePointAt(0));for(let n=0;n<t.length;n++){let r=t[n];if(r!==8204&&r!==8205||n>0&&vh(GI,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&Ro(gh,t[i]);)i--;let a=n+1;for(;a<t.length&&Ro(gh,t[a]);)a++;if(!(i>=0&&a<t.length&&Ro(QI,t[i])&&Ro(JI,t[a])))return!1}return!0}var YI=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,XI=/\p{Script=Latin}/u;function ev(e){return!YI.test(e)||!XI.test(e)}var dr=36,ds=1,el=26,tv=38,nv=700,rv=72,iv=128,ov=2147483647;function hh(e){return String.fromCharCode(e+22+75*+(e<26))}function av(e,t,n){let r=0;for(e=n?Math.floor(e/nv):e>>1,e+=Math.floor(e/t);e>(dr-ds)*el>>1;r+=dr)e=Math.floor(e/(dr-ds));return Math.floor(r+(dr-ds+1)*e/(e+tv))}function sv(e){let t=Array.from(e,c=>c.codePointAt(0)),n="",r=0;for(let c=0;c<t.length;c++){let u=t[c];u<128&&(n+=String.fromCharCode(u),r++)}let i=r;i&&(n+="-");let a=iv,o=0,s=rv;for(;r<t.length;){let c=ov;for(let u=0;u<t.length;u++){let l=t[u];l>=a&&l<c&&(c=l)}o+=(c-a)*(r+1),a=c;for(let u=0;u<t.length;u++){let l=t[u];if(l<a&&o++,l===a){let m=o;for(let f=dr;;f+=dr){let g=f<=s?ds:f>=s+el?el:f-s;if(m<g)break;n+=hh(g+(m-g)%(dr-g)),m=Math.floor((m-g)/(dr-g))}n+=hh(m),s=av(o,r+1,r===i),o=0,r++}}o++,a++}return n}function Ku(e){let t=10;if(e.length>=2&&e[0]==="0"&&(e[1]==="x"||e[1]==="X"))e=e.slice(2),t=16;else if(e.length>=2&&e[0]==="0")e=e.slice(1),t=8;else if(e==="")return-1;let n=0;for(let r=0;r<e.length;r++){let i=Zu(e.charCodeAt(r));if(i>=t||i<0)return-1;n=n*t+i}return n}function yh(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function wh(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function Oh(e){return e.length===2&&wh(e.codePointAt(0),e.codePointAt(1))}function Ah(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function ft(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function Ph(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function tl(e,t){if(e[0]==="[")return e[e.length-1]==="]"?(function(r){let i=[0,0,0,0,0,0,0,0],a=null,o=0,s=0,c=Array.from(r,u=>u.codePointAt(0));if(c[s]===58){if(c[s+1]!==58)return null;s+=2,o++,a=o}for(;s<c.length;){if(o===8)return null;if(c[s]===58){if(a!==null)return null;s++,o++,a=o;continue}let u=0,l=0,m=0;for(;m<4&&(u=Zu(c[s]))>=0;)l=(l<<4)+u,s++,m++;if(c[s]===46){if(m===0||o>6)return null;s-=m;let f=0;for(;c[s]!==void 0;){let g=0;if(f>0)if(c[s]===46&&f<4)s++;else return null;if(c[s]==null||c[s]<48||c[s]>57)return null;for(;c[s]>=48&&c[s]<=57;){if(g=10*g+Zu(c[s]),g>255)return null;s++}i[o]=256*i[o]+g,f++,f%2==0&&o++}if(f!==4)return null;break}else if(c[s]===58){if(c[++s]===void 0)return null}else if(c[s]!==void 0)return null;i[o]=l,o++}if(a!==null){let u=o-a;for(o=7;o!==0&&u>0;){let l=i[a+u-1];i[a+u-1]=i[o],i[o]=l,o--,u--}}else if(a===null&&o!==8)return null;return i})(e.substring(1,e.length-1)):null;if(t)return(function(r){return Ah(r)?null:Bn(r,jo)})(e);{let n=(function(i){let a=!1,o=!1;for(let c=0;c<i.length;c++){let u=i.charCodeAt(c);if(u<=32||u===37||u===127)return null;if(u>=128){a=!0;break}u>=65&&u<=90&&(o=!0)}if(!a)return i!==""?o?i.toLowerCase():i:null;if((function(u){for(let l of u){let m=l.codePointAt(0);if(/[\p{Cn}\p{Co}\p{Cs}\p{Noncharacter_Code_Point}]/u.test(l)&&!vh(LI,m)||Ro(HI,m))return!0}return!1})(i))return null;let s=(i=(function(u){let l="";for(let m of u){let f=m.codePointAt(0);if(f!==8204&&f!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(m))continue;let g=ZI(m,f);if(g){l+=g;continue}let d=zI.indexOf(f);l+=d<0?m:$I[d]}return l})(i).normalize("NFKC").replace(/[\u3002\uff0e\uff61]/g,".").toLowerCase()).split(".");for(let c=0;c<s.length;c++){let u=s[c];if(u==="")continue;let l=/[^\0-\x7f]/.test(u);if(KI(u)||l&&(/^\p{Mark}/u.test(u)||!WI(u)||!ev(u)||u.startsWith("xn--")))return null;l&&(s[c]=`xn--${sv(u)}`)}return(i=s.join("."))!==""?i:null})(e.indexOf("%")===-1?e:Wu(e));return n===null||Ah(n)?null:(function(i){let a=i.length,o=i.lastIndexOf(".",a-2)+1;if(i.charCodeAt(a-1)===46&&a--,a<=o)return!1;if(Ku(i.slice(o,a))>=0)return!0;for(;o<a;o++){let s=i.charCodeAt(o);if(s<48||s>57)return!1}return!0})(n)?(function(i){let a=i.split("."),o=a.length;if(a[o-1]||o--,o>4)return null;let s=0;for(let u=0;u<o-1;u++){let l=Ku(a[u]);if(l<0||l>255)return null;s+=l*(1<<8*(3-u))}let c=Ku(a[o-1]);return c<0||c>=256**(5-o)?null:(s+=c,s)})(n):n}}function nl(e){return typeof e=="number"?(function(n){let i="";return i+=`${(n>>>24&255).toString(10)}.`,i+=`${(n>>>16&255).toString(10)}.`,i+=`${(n>>>8&255).toString(10)}.`,i+=(n&255).toString(10),i})(e):Array.isArray(e)?`[${(function(n){let r=(function(s){let c=-1,u=-1,l=1,m=0;for(let f=0;f<s.length;++f)s[f]!==0?(m>l&&(c=u,l=m),u=-1,m=0):(u===-1&&(u=f),++m);return m>l?u:c})(n),i="",a=!1;for(let o=0;o<=7;++o)if(!(a&&n[o]===0)){if(a&&(a=!1),r===o){i+=o===0?"::":":",a=!0;continue}i+=n[o].toString(16),o!==7&&(i+=":")}return i})(e)}]`:e}function Ch(e){e.path.length>0&&(e.path.length!==1||e.scheme!=="file"||!(function(n){return/^[A-Za-z]:$/u.test(n)})(e.path[0]))&&e.path.pop()}function _h(e){return e.username!==""||e.password!==""}function Hu(e){return e.host===null||e.host===""||e.scheme==="file"}var E=0,U="",Oe="",Le=null,B,ps=!1,ms=!1,Kr=!1,gt;function fn(e,t,n,r){t||(e=(function(o){let s=0,c=o.length;for(;s<c&&!(o.charCodeAt(s)>32);++s);for(;c>s&&!(o.charCodeAt(c-1)>32);--c);return o.substring(s,c)})(e)),e=(function(o){let s=0;for(;s<o.length;s++){let u=o.charCodeAt(s);if(u===9||u===10||u===13)break}if(s===o.length)return o;let c=o.slice(0,s);for(;s<o.length;s++){let u=o.charCodeAt(s);u!==9&&u!==10&&u!==13&&(c+=o[s])}return c})(e),E=0,U=e,Oe="",Le=n||null,B=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},ps=!1,ms=!1,Kr=!1,gt=r||0;let i=cv;switch(r){case 3:case 4:i=gs;break;case 5:i=sl;break;case 6:i=Hr;break;case 7:i=pr;break;case 8:i=Vn}return i(G(e,E))!==1?B:null}function ee(e,t){return E+=E===e?Tn(t):1,E<=U.length}function G(e,t){return t<e.length?e.codePointAt(t):void 0}function Tn(e){return e!=null&&e>65535?2:1}function Eh(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var cv=e=>{let t=E;if(e!=null&&(e>=65&&e<=90||e>=97&&e<=122)){let n=E+1;for(e=U.charCodeAt(n);e===43||e===45||e===46||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57;)n++,e=U.charCodeAt(n);return Oe=U.slice(E,n).toLowerCase(),E=n,uv(n<U.length?e:void 0)}else return gt?1:(--E,ee(t,e)?Rh(G(U,E)):0)},uv=e=>{let t=E;if(e===58){if(gt){if(ft(B.scheme)!==ft(Oe))return 0;if((_h(B)||B.port!==null)&&Oe==="file")return 0;if(B.scheme==="file"&&B.host==="")return 0}return B.scheme=Oe,gt?(B.port===Ph(B.scheme)&&(B.port=null),0):(Oe="",B.scheme==="file"?ee(t,e)?cl(G(U,E)):0:ft(B.scheme)&&Le!==null&&Le.scheme===B.scheme?ee(t,e)?lv(G(U,E)):0:ft(B.scheme)?ee(t,e)?pv(G(U,E)):0:G(U,E+1)===47?(E++,ee(t,e)?dv(G(U,E)):0):(B.path=[""],B.opaquePath=!0,ee(t,e)?jh(G(U,E)):0))}else return gt?1:(Oe="",E=-1,ee(t,e)?Rh(G(U,E)):0)},Rh=e=>{let t=E;return Le===null||Le.opaquePath&&e!==35?1:Le.opaquePath&&e===35?(B.scheme=Le.scheme,B.path=Le.path.slice(),B.opaquePath=Le.opaquePath,B.query=Le.query,B.fragment="",ee(t,e)?Vn(G(U,E)):0):Le.scheme==="file"?(E--,ee(t,e)?cl(G(U,E)):0):(E--,ee(t,e)?al(G(U,E)):0)},lv=e=>{let t=E;return e===47&&G(U,E+1)===47?(++E,ee(t,e)?ys(G(U,E)):0):(E--,ee(t,e)?al(G(U,E)):0)},dv=e=>{let t=E;return e===47?ee(t,e)?Ti(G(U,E)):0:(E--,ee(t,e)?Nn(G(U,E)):0)},al=e=>{let t=E;return B.scheme=Le.scheme,e===47||ft(B.scheme)&&e===92?ee(t,e)?bh(G(U,E)):0:(B.username=Le.username,B.password=Le.password,B.host=Le.host,B.port=Le.port,B.path=Le.path.slice(),B.query=Le.query,e===63?(B.query="",ee(t,e)?pr(G(U,E)):0):e===35?(B.fragment="",ee(t,e)?Vn(G(U,E)):0):e!=null?(B.query=null,B.path.pop(),E--,ee(t,e)?Nn(G(U,E)):0):ee(t,e)?al(G(U,E)):0)},bh=e=>{let t=E;return ft(B.scheme)&&(e===47||e===92)?ee(t,e)?ys(G(U,E)):0:e===47?ee(t,e)?Ti(G(U,E)):0:(B.username=Le.username,B.password=Le.password,B.host=Le.host,B.port=Le.port,E--,ee(t,e)?Nn(G(U,E)):0)},pv=e=>{let t=E;return e===47&&G(U,E+1)===47?E++:E--,ee(t,e)?ys(G(U,E)):0},ys=e=>{let t=E;return e!==47&&e!==92?(E--,ee(t,e)?Ti(G(U,E)):0):ee(t,e)?ys(G(U,E)):0},Ti=e=>{let t=E;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!ft(B.scheme))){let n=E+Tn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===64||r===35||r===47||r===63||r===92&&ft(B.scheme))break;n+=Tn(r)}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?Ti(G(U,E)):0}if(e===64){ps&&(Oe=`%40${Oe}`),ps=!0;for(let n=0;n<Oe.length;n++){let r=Oe.codePointAt(n);if(r===58&&!ms){ms=!0;continue}let i=Ih(r,fs);ms?B.password+=i:B.username+=i,r!=null&&r>65535&&n++}return Oe="",ee(t,e)?Ti(G(U,E)):0}else return e==null||e===35||e===47||e===63||e===92&&ft(B.scheme)?ps&&Oe===""?1:(E-=Oe.length+1,Oe="",ee(t,e)?gs(G(U,E)):0):(Oe+=Eh(e),ee(t,e)?Ti(G(U,E)):0)},gs=e=>{let t=E;if(gt&&B.scheme==="file")return E--,ee(t,e)?ul(G(U,E)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!ft(B.scheme))){let n=E+Tn(e);for(e===91?Kr=!0:e===93&&(Kr=!1);n<U.length;){let r=G(U,n);if(r==null||!Kr&&r===58||r===35||r===47||r===63||r===92&&ft(B.scheme))break;r===91?Kr=!0:r===93&&(Kr=!1),n+=Tn(r)}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?gs(G(U,E)):0}else if(e===58&&!Kr){if(Oe===""||gt===4)return 1;let n=tl(Oe,!ft(B.scheme));return n===null?1:(B.host=nl(n),Oe="",ee(t,e)?sl(G(U,E)):0)}else if(e==null||e===35||e===47||e===63||e===92&&ft(B.scheme)){if(E--,ft(B.scheme)&&Oe==="")return 1;if(gt&&Oe===""&&(_h(B)||B.port!==null))return 1;let n=tl(Oe,!ft(B.scheme));return n===null?1:(B.host=nl(n),Oe="",gt?0:ee(t,e)?Hr(G(U,E)):0)}else return Oe+=Eh(e),ee(t,e)?gs(G(U,E)):0},sl=e=>{let t=E;if(e!=null&&e>=48&&e<=57){let n=E+1;for(;n<U.length;){let r=U.charCodeAt(n);if(r<48||r>57)break;n++}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?sl(G(U,E)):0}else if(gt||e==null||e===35||e===47||e===63||e===92&&ft(B.scheme)){if(Oe!==""){let n=parseInt(Oe,10);if(n>65535)return 1;if(B.port=n===Ph(B.scheme)?null:n,Oe="",gt)return 0}return gt?1:(E--,ee(t,e)?Hr(G(U,E)):0)}else return 1};function kh(e,t){let n=e.length-t;if(n<2)return!1;if(wh(G(e,t),G(e,t+1))){if(n===2)return!0;{let r=G(e,t+2);return r===47||r===92||r===63||r===35}}else return!1}var cl=e=>{let t=E;return B.scheme="file",B.host="",e===47||e===92?ee(t,e)?mv(G(U,E)):0:Le?.scheme==="file"?(B.host=Le.host,B.path=Le.path.slice(),B.opaquePath=Le.opaquePath,B.query=Le.query,e===63?(B.query="",ee(t,e)?pr(G(U,E)):0):e===35?(B.fragment="",ee(t,e)?Vn(G(U,E)):0):e!=null?(B.query=null,kh(U,E)?B.path=[]:Ch(B),E--,ee(t,e)?Nn(G(U,E)):0):ee(t,e)?cl(G(U,E)):0):(E--,ee(t,e)?Nn(G(U,E)):0)},mv=e=>{let t=E;return e===47||e===92?ee(t,e)?ul(G(U,E)):0:(Le!==null&&Le.scheme==="file"&&(!kh(U,E)&&(function(r){if(r.length===2){let i=r.codePointAt(0),a=r.codePointAt(1);return(i>=65&&i<=90||i>=97&&i<=122)&&a===58}else return!1})(Le.path[0])&&B.path.push(Le.path[0]),B.host=Le.host),E--,ee(t,e)?Nn(G(U,E)):0)},ul=e=>{let t=E;if(e!=null&&e!==47&&e!==92&&e!==63&&e!==35){let n=E+Tn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===47||r===92||r===63||r===35)break;n+=Tn(r)}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?ul(G(U,E)):0}else if(e==null||e===47||e===92||e===63||e===35){if(E--,!gt&&Oh(Oe))return ee(t,e)?Nn(G(U,E)):0;if(Oe==="")return B.host="",gt?0:ee(t,e)?Hr(G(U,E)):0;{let n=tl(Oe,!ft(B.scheme));return n===null?1:(n==="localhost"&&(n=""),B.host=nl(n),Oe="",gt?0:ee(t,e)?Hr(G(U,E)):0)}}return 1},Hr=e=>{let t=E;return ft(B.scheme)?(e!==92&&e!==47&&E--,ee(t,e)?Nn(G(U,E)):0):!gt&&e===63?(B.query="",ee(t,e)?pr(G(U,E)):0):!gt&&e===35?(B.fragment="",ee(t,e)?Vn(G(U,E)):0):e!=null?(e!==47&&E--,ee(t,e)?Nn(G(U,E)):0):(gt&&B.host===null&&B.path.push(""),ee(t,e)?Hr(G(U,E)):0)},Nn=e=>{let t=E;if(e!=null&&e!==47&&(!ft(B.scheme)||e!==92)&&(gt||e!==63&&e!==35)){let n=E+Tn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===47||ft(B.scheme)&&r===92||!gt&&(r===63||r===35))break;n+=Tn(r)}Oe+=Bn(U.slice(E,n),Yu),E=n,e=G(U,n)}if(e==null||e===47||ft(B.scheme)&&e===92||!gt&&(e===63||e===35)){let n=ft(B.scheme)&&e===92;return(function(i){switch(i){case"..":case"%2e.":case"%2E.":case".%2e":case".%2E":case"%2e%2e":case"%2E%2e":case"%2e%2E":case"%2E%2E":return!0;default:return!1}})(Oe)?(Ch(B),e!==47&&!n&&B.path.push("")):yh(Oe)&&e!==47&&!n?B.path.push(""):yh(Oe)||(B.scheme==="file"&&B.path.length===0&&Oh(Oe)&&(Oe=`${Oe[0]}:`),B.path.push(Oe)),Oe="",e===63?(B.query="",ee(t,e)?pr(G(U,E)):0):e===35?(B.fragment="",ee(t,e)?Vn(G(U,E)):0):ee(t,e)?Nn(G(U,E)):0}else return Oe+=Ih(e,Yu),ee(t,e)?Nn(G(U,E)):0},jh=e=>{let t=E;if(e===63)return B.query="",ee(t,e)?pr(G(U,E)):0;if(e===35)return B.fragment="",ee(t,e)?Vn(G(U,E)):0;if(e!=null){let n=E+Tn(e);for(;n<U.length;){let i=G(U,n);if(i===63||i===35)break;n+=Tn(i)}let r=U.slice(E,n);if(n<U.length&&r.charCodeAt(r.length-1)===32?B.path[0]+=Bn(r.slice(0,-1),jo)+"%20":B.path[0]+=Bn(r,jo),E=n,(e=G(U,n))===63)return B.query="",ee(t,e)?pr(G(U,E)):0;if(e===35)return B.fragment="",ee(t,e)?Vn(G(U,E)):0}return ee(t,e)?jh(G(U,E)):0},pr=e=>{let t=E,n=E;if(e!=null){if(gt)n=U.length;else{let i=U.indexOf("#",E);n=i===-1?U.length:i}let r=ft(B.scheme)?VI:il;B.query+=Bn(U.slice(E,n),r)}return E=n,G(U,n)===35&&!gt?(B.fragment="",ee(t,e)?Vn(G(U,E)):0):ee(t,e)?pr(G(U,E)):0},Vn=e=>{let t=E;return e!=null&&(B.fragment+=Bn(U.slice(E),BI),E=U.length),ee(t,e)?Vn(G(U,E)):0};function rl(e){if(e.opaquePath)return e.path[0];{let t="";for(let n of e.path)t+=`/${n}`;return t}}function Th(e){switch(e.scheme){case"blob":{let t=fn(rl(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":Th(t)}case"ftp":case"http":case"https":case"ws":case"wss":return(function(n){let r=`${n.scheme}://`;return r+=n.host,n.port!==null&&(r+=`:${n.port}`),r})(e);default:return"null"}}var He=Symbol("URLImpl"),xn=class e{constructor(t,n){if(t===void 0&&n===void 0)throw new TypeError('The "url" argument must be specified.');t=Qe(t),n!=null&&(n=Qe(n));let r=null;if(n!=null&&(r=fn(n,null,null,0),r==null))throw new TypeError(`Invalid base URL: ${n}`);let i=fn(t,null,r,0);if(i==null)throw new TypeError(`Invalid URL: ${t}`);this[He]={url:i,query:null}}static createObjectURL(t){throw new TypeError("URL.createObjetURL is unsupported")}static revokeObjectURL(t){}static parse(t,n){t=Qe(t),n!==void 0&&(n=Qe(n));try{return new e(t,n)}catch{return null}}static canParse(t,n){t=Qe(t),n!==void 0&&(n=Qe(n));let r=null;return n!=null&&(r=fn(n,null,null,0),r==null)?!1:fn(t,null,r,0)!=null}get href(){return(function(n){let r=`${n.scheme}:`;return n.host!==null&&(r+="//",(n.username!==""||n.password!=="")&&(r+=n.username,n.password!==""&&(r+=`:${n.password}`),r+="@"),r+=n.host,n.port!==null&&(r+=`:${n.port}`)),n.host===null&&!n.opaquePath&&n.path.length>1&&n.path[0]===""&&(r+="/."),r+=rl(n),n.query!==null&&(r+=`?${n.query}`),n.fragment!==null&&(r+=`#${n.fragment}`),r})(this[He].url)}set href(t){let n=fn(t=Qe(t),null,null,0);if(n==null)throw new TypeError(`Invalid URL: ${t}`);this[He].url=n,this[He].query&&Qu(this[He].query,n.query)}get origin(){return Th(this[He].url)}get protocol(){return`${this[He].url.scheme}:`}set protocol(t){fn(`${t=Qe(t)}:`,this[He].url,null,2)}get username(){return this[He].url.username}set username(t){t=Qe(t),Hu(this[He].url)||(function(r,i){r.username=Bn(i,fs)})(this[He].url,t)}get password(){return this[He].url.password}set password(t){t=Qe(t),Hu(this[He].url)||(function(r,i){r.password=Bn(i,fs)})(this[He].url,t)}get host(){let{url:t}=this[He];return t.host==null?"":t.port==null?t.host:`${t.host}:${t.port}`}set host(t){t=Qe(t),this[He].url.opaquePath||fn(t,this[He].url,null,3)}get hostname(){let{url:t}=this[He];return t.host!=null?t.host:""}set hostname(t){t=Qe(t),this[He].url.opaquePath||fn(t,this[He].url,null,4)}get port(){let{url:t}=this[He];return t.port!=null?`${t.port}`:""}set port(t){t=Qe(t);let{url:n}=this[He];Hu(n)||(t?fn(t,n,null,5):n.port=null)}get pathname(){return rl(this[He].url)}set pathname(t){t=Qe(t);let{url:n}=this[He];n.opaquePath||(n.path=[],fn(t,n,null,6))}get search(){let{url:t}=this[He];return t.query?`?${t.query}`:""}set search(t){t=Qe(t);let{url:n,query:r}=this[He];if(!t)n.query=null,r&&Qu(r,null);else{let i=t[0]==="?"?t.substring(1):t;n.query="",fn(i,n,null,7),r&&Qu(r,n.query)}}get searchParams(){let t=this[He],n=t.query;return n==null&&(n=t.query=(function(i,a){let o=new hs;return o[st].url=i,o[st].serialized=a==null,a&&(o[st].list=ol(a)),o})(this,t.url.query)),n}get hash(){let{url:t}=this[He];return t.fragment?`#${t.fragment}`:""}set hash(t){t=Qe(t);let{url:n}=this[He];if(!t)n.fragment=null;else{let r=t[0]==="#"?t.substring(1):t;n.fragment="",fn(r,n,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(xn.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var st=Symbol("URLSearchParamsImpl"),fv=Symbol.dispose||Symbol.for("dispose");function Qu(e,t){t?e[st].list=ol(t):e[st].list.length=0,e[st].serialized=t==null}function ls(e){if(e.url){let t=Xu(e.list);(function(r,i){r[He].url.query=i})(e.url,t||null),e.serialized=!0}}var gv=typeof Iterator<"u"?Iterator:Object,ko=class extends gv{constructor(t,n){super(),this[st]={ptr:t,map:n,index:0}}next(){let t=this[st];return t.index<t.ptr.list.length?{value:t.map(t.ptr.list[t.index++]),done:!1}:{value:void 0,done:!0}}[Symbol.iterator](){return this}[fv](){}},hs=class{constructor(t){let n=this[st]={list:[],url:null,serialized:!0},r;if(Array.isArray(t))for(let i=0;i<t.length;i++)n.list.push(ph(t[i]));else if((r=xh(t))!=null){let i;for(;!(i=Ju(r.next())).done;)n.list.push(ph(i.value))}else if((typeof t=="object"||typeof t=="function")&&t!=null){let i=Object.keys(t);for(let a=0;a<i.length;a++){let o=i[a],s=qI(o),c=Qe(t[o]),u=n.list.find(l=>l[0]===s);u?u[1]=c:n.list.push([s,c])}}else if(t!==void 0){let i=Qe(t);i=i[0]==="?"?i.substring(1):i,n.list=ol(i)}}get size(){return this[st].list.length}append(t,n){t=Qe(t),n=Qe(n),this[st].list.push([t,n]);let r=this[st];r.url&&r.serialized?(function(a,o){let s=a[He].url;s.query=s.query?`${s.query}&${o}`:o})(r.url,Xu([[t,n]])):ls(r)}delete(t,n){t=Qe(t),n=n!=null?Qe(n):void 0;let{list:r}=this[st],i=0;for(;i<r.length;)r[i][0]===t&&(n==null||r[i][1]===n)?r.splice(i,1):i++;ls(this[st])}get(t){t=Qe(t);let{list:n}=this[st];for(let r=0;r<n.length;r++)if(n[r][0]===t)return n[r][1];return null}getAll(t){t=Qe(t);let n=[],{list:r}=this[st];for(let i=0;i<r.length;i++)r[i][0]===t&&n.push(r[i][1]);return n}has(t,n){t=Qe(t),n=n!=null?Qe(n):void 0;let{list:r}=this[st];for(let i=0;i<r.length;i++)if(r[i][0]===t&&(n==null||r[i][1]===n))return!0;return!1}set(t,n){t=Qe(t),n=Qe(n);let{list:r}=this[st],i=!1,a=!1,o=0;for(;o<r.length;)r[o][0]===t?i?(r.splice(o,1),a=!0):(i=!0,r[o][1]!==n&&(r[o][1]=n,a=!0),o++):o++;i||(r.push([t,n]),a=!0),a&&ls(this[st])}sort(){this[st].list.sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0),ls(this[st])}forEach(t,n){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:r}=this[st];for(let i=0;i<r.length;i++)t.call(n,r[i][1],r[i][0],this)}entries(){return new ko(this[st],t=>t)}keys(){return new ko(this[st],t=>t[0])}values(){return new ko(this[st],t=>t[1])}toString(){return Xu(this[st].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(hs.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var mr="https://api.longplayai.com";function Nh(e){let t,n=()=>typeof t=="string"?t:t?.accessToken,r=0,i,a=new Map,o=()=>{for(let m of[...a.keys()])try{m()}catch{}};function s(m){let f=++r;i=void 0,t=void 0;for(let g of[...a.values()])try{g?.()}catch{}f===r&&(t=m,o())}let c=()=>s();function u(m,f=!1){let g=Wn.safeParse(m);if(!g.success||f&&Date.parse(g.data.expiresAt)<=Date.now()||Date.parse(g.data.refreshExpiresAt)<=Date.now()||Date.parse(g.data.refreshExpiresAt)<Date.parse(g.data.expiresAt))throw new b("INVALID_RESPONSE","Invalid customer session credentials");return g.data}async function l(){if(i)return i;let m=typeof t=="object"?t:void 0,f=r;if(!m||Date.parse(m.refreshExpiresAt)<=Date.now())throw m&&c(),new b("UNAUTHENTICATED","Customer authentication is required",401);let g=(async()=>{try{let d=await e(m.refreshToken);if(f!==r)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");let h=u(d,!0);if(h.customerId!==m.customerId||h.sessionId!==m.sessionId)throw new b("SCOPE_MISMATCH","Refresh changed the customer session");return t=h,{...h}}catch(d){throw f!==r?new b("IDENTITY_CHANGED","Customer identity changed during refresh"):(d instanceof b&&d.status===401&&c(),d)}})();i=g;try{return await g}finally{i===g&&(i=void 0)}}return{identify(m){let f=typeof m=="string"?m:u(m),g=typeof f=="string"?f:f.accessToken;if(!g.trim()||/\s/.test(g)||g.length>4096)throw new b("INVALID_TOKEN","A server-issued token is required");s(f)},reset:c,subscribeIdentity(m,f){return a.set(m,f),()=>{a.delete(m)}},access(){let m=typeof t=="object"?t:void 0;if(m&&Date.parse(m.expiresAt)<=Date.now()+3e4){let g=r;return l().then(()=>{let d=n();if(g!==r||!d)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");return d})}let f=n();if(!f)throw new b("NOT_IDENTIFIED","Identify a customer session before making a request");return f},peek:n,snapshot:()=>typeof t=="object"?{...t}:void 0,refresh:l}}var Dh=Symbol("IndianaNoContent");function fr(e,t,n=xn){let r=e.configuration?.scope,i=e.scope??(r&&{projectId:r.projectId,environment:r.environment}),a=i?Ne.parse(i):void 0;if(a&&r&&(a.projectId!==r.projectId||a.environment!==r.environment))throw new b("SCOPE_MISMATCH","Configuration belongs to another App/environment");let o=new n(e.baseUrl??mr);if(o.username||o.password||o.search||o.hash)throw new b("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(o.protocol!=="https:"&&!(o.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(o.hostname)))throw new b("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let s=e.fetch??globalThis.fetch.bind(globalThis),c=e.timeoutMs??1e4;if(!Number.isFinite(c)||c<1||c>12e4)throw new b("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let u=!1,l=0,m=null,f=new Set,g=e.session??Nh(async A=>{let x=await y("customer-sessions/refresh",{},"POST",{},A);if(!x||typeof x!="object")throw new b("INVALID_RESPONSE","Invalid refresh response");let{requestId:v,scope:P,...j}=x;return j});function d(){l+=1,m=null;for(let A of f)A.abort();f.clear()}let h=g.subscribeIdentity(d);function R(){u||g.reset()}async function y(A,x={},v="POST",P={},j){let _=P.installationDetach===!0;if(_&&(A!=="push/installations/detach"||v!=="POST"))throw new b("INVALID_REQUEST","Installation authority only detaches this installation");if(!j&&!_)throw new b("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let X=l,le=new AbortController;_||f.add(le);let he=()=>!_&&X!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new b("TIMEOUT","Longplay request timed out"),ke,Se=new Promise((Te,tt)=>{ke=()=>tt(he()),le.signal.addEventListener("abort",ke,{once:!0})}),ht=setTimeout(()=>le.abort(),P.timeoutMs??c),Je=async()=>{let Te=await s(`${o.href.replace(/\/$/,"")}/api/v1/${A}`,{method:v,headers:{...P.headers,"Content-Type":"application/json",..._?{}:{Authorization:`Bearer ${j}`},[ks]:js.current,[kl]:dh.version,...a?{"X-Indiana-Project":a.projectId,"X-Indiana-Environment":a.environment}:{}},body:v==="POST"?JSON.stringify(x):void 0,signal:le.signal,credentials:"omit",cache:"no-store",redirect:"error",...P.keepalive?{keepalive:!0}:{}});if(le.signal.aborted)throw he();let tt;try{tt=Te.status===204?Dh:await Te.json()}catch{throw le.signal.aborted?he():new b(Te.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",Te.status,Te.headers.get("X-Request-Id")??void 0)}if(le.signal.aborted)throw he();if(!_&&X!==l)throw new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!Te.ok){let pt=Rs.safeParse(tt),Qt=pt.success&&(!$n.safeParse(pt.data.error.code).success||El(pt.data.error.code,Te.status)),Ar=Qt?pt.data.error.code:"HTTP_ERROR",br=Uo(Ar,Te.status,{retryAfter:Te.headers.get("Retry-After"),recovery:Qt?pt.data.error.recovery:void 0,reason:Qt?pt.data.error.reason:void 0});throw new b(Ar,Qt?pt.data.error.message:"Longplay request failed",Te.status,Te.headers.get("X-Request-Id")??(pt.success?pt.data.requestId:void 0),{...br,...pt.success&&pt.data.error.retryable===!1?{retryable:!1}:{},...br.retryAfterSeconds===void 0&&pt.success&&pt.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:pt.data.error.retryAfterSeconds}:{}})}if(Te.headers.get(ks)!==js.current)throw new b("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&tt!==Dh){let pt=tt&&typeof tt=="object"&&"scope"in tt?tt:tt&&typeof tt=="object"&&"configuration"in tt?tt.configuration:null;if(!pt||typeof pt!="object"||!("scope"in pt))throw new b("INVALID_RESPONSE","Response is missing its App/environment scope");let Qt=Ne.safeParse(pt.scope);if(!Qt.success||Qt.data.projectId!==a.projectId||Qt.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let Jr=Te.headers.get("X-Indiana-Telemetry-Subject");if(Jr){if(!/^[a-f0-9]{64}$/.test(Jr))throw new b("INVALID_RESPONSE","Invalid telemetry identity");m!==Jr&&(m=Jr,t?.(m))}return tt};try{return await Promise.race([Je(),Se])}catch(Te){throw!_&&X!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):Te instanceof b?Te:new b(le.signal.aborted?"TIMEOUT":"NETWORK_ERROR",le.signal.aborted?"Longplay request timed out":"Unable to read the Longplay response")}finally{clearTimeout(ht),le.signal.removeEventListener("abort",ke),f.delete(le)}}return{session:g,requestWithCredential(A,x,v,P={}){return u?Promise.reject(new b("CLOSED","SDK client was destroyed")):y(A,x,"POST",P,v)},subjectKey:()=>m,identify(A){if(u)throw new b("CLOSED","SDK client was destroyed");if(a&&typeof A=="object"&&"scope"in A){let x=Ne.safeParse(A.scope);if(!x.success||x.data.projectId!==a.projectId||x.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Customer session belongs to another App/environment")}g.identify(A)},reset:R,dispose(){u||(u=!0,h(),d())},request(A,x={},v="POST",P={}){if(u)return Promise.reject(new b("CLOSED","SDK client was destroyed"));if(P.installationDetach)return y(A,x,v,P);let j=l;try{let _=g.access(),X=le=>{if(j!==l)throw new b("IDENTITY_CHANGED","Customer identity changed before dispatch");return y(A,x,v,P,le)};return typeof _=="string"?X(_):_.then(X)}catch(_){return Promise.reject(_)}}}}function Fh(e,t,n={}){let r=!1;function i(){if(r)throw new b("CLOSED","SDK client was destroyed")}let a=new Set,o=c=>{for(let u of a)try{u(c)}catch{}},s=e.session.subscribeIdentity(()=>{o(!!e.session.peek()),n.afterChange?.()},()=>{t()});return{assertActive:i,isIdentified:()=>!r&&!!e.session.peek(),methods:{subscribeIdentity(c){return i(),a.add(c),()=>{a.delete(c)}},identify(c){i();let u=typeof c=="string"?c:c.accessToken;if(!kt.test(u))throw new b("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(u),e.identify(c)},reset(){if(!r)try{n.beforeReset?.()}finally{e.reset()}},destroy(){if(!r){r=!0,s(),a.clear();try{n.beforeDestroy?.(),t()}finally{e.dispose()}}}}}}function ze(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new b("INVALID_REQUEST","Customer requests use the verified session identity")}var hv={...O.readHoldings,request:O.readHoldings.request.omit({customerId:!0})};function Mh(e){return{async checkEntitlement(t){ze(t);let n=O.checkEntitlement;return ge(e,n,t)},async readHoldings(t={}){return ge(e,hv,t)}}}function qh(e){return{async readLedger(t){let n=O.readLedger;return ge(e,n,{query:t})},async readCreditStatement(t){ze(t);let n=O.readCreditStatement;return ge(e,n,t)},async quoteBalance(t){ze(t);let n=O.quoteBalance;return ge(e,n,{command:t})}}}function Uh(e){return{async setupPayment(t){ze(t);let n=O.setupPayment;return ge(e,n,t)},async readPaymentSetup(t){ze(t);let n=O.readPaymentSetup;return ge(e,n,t)},async readBillingInvoice(t){ze(t);let n=O.readBillingInvoice;return ge(e,n,t)},async readBillingControls(t={}){ze(t);let n=O.readBillingControls;return ge(e,n,t)},async prepareBillingAuthorization(t){ze(t);let n=O.prepareBillingAuthorization;return ge(e,n,t)},async confirmBillingAuthorization(t){ze(t);let n=O.confirmBillingAuthorization;return ge(e,n,t)},async setBillingCoupons(t){ze(t);let n=O.setBillingCoupons;return ge(e,n,t,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(t){ze(t);let n=O.revokeBillingAuthorization;return ge(e,n,t)},async listBillingInvoices(t={after:null,limit:25}){ze(t);let n=O.listBillingInvoices;return ge(e,n,t)},async confirmBillingAdjustment(t){ze(t);let n=O.confirmBillingAdjustment;return ge(e,n,t)}}}function Bh(e){return{async previewUpdate(t){ze(t);let n=O.previewUpdate;return ge(e,n,t)},async update(t){ze(t);let n=O.update;return ge(e,n,t)},async readSubscriptionUpdate(t){ze(t);let n=O.readSubscriptionUpdate;return ge(e,n,t)},async restoreNativePurchase(t){ze(t);let n=O.restoreNativePurchase;return ge(e,n,t)},async previewAttach(t){ze(t);let n=O.previewAttach;return ge(e,n,t)},async attach(t){ze(t);let n=O.attach;return ge(e,n,t)},async readSubscriptionOperation(t){ze(t);let n=O.readSubscriptionOperation;return ge(e,n,t)}}}function Vh(e){return{async redeemReward(t){return ze(t),(await ge(e,O.redeemReward,{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(t){return ze(t),(await ge(e,O.claimRewardProduct,t,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(t){return ze(t),(await ge(e,O.createReferralCode,{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(t,n=crypto.randomUUID()){let r=await ge(e,O.redeemCoupon,{code:t,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(t,n=crypto.randomUUID()){let r=await ge(e,O.grantOffer,{couponId:t,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await ge(e,O.listOffers,{},{response:"Invalid offers response"})).offers}}}function Lh(e){return{...Mh(e),...qh(e),...Uh(e),...Bh(e),...Vh(e)}}function zh(e){return{async resolveContent(t){ze(t);let n=O.resolveContent;return ge(e,n,t)},async resolvePaywall(t){ze(t);let n=O.resolvePaywall;return ge(e,n,t)},async resolveOffering(t){ze(t);let n=O.resolveOffering;return ge(e,n,t)}}}var ll=e=>new TextEncoder().encode(JSON.stringify(e)).length,$h=16384;function Gh(e,t){let n=0,r,i=d=>{r={config:structuredClone(d),until:Date.now()+3e4}},a=[],o=null,s;function c(){if(!t())throw new b("NOT_IDENTIFIED","Call identify before using Features or events")}function u(){s||!a.length||(s=setTimeout(()=>{s=void 0,m().catch(()=>{}).finally(u)},5e3),typeof s=="object"&&"unref"in s&&s.unref())}function l(d,h={},R={}){if(c(),r&&Date.now()<r.until&&!nf(r.config,d))return;g();let y=O.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:d,properties:h,...R}]}).events[0];if(ll({events:[y]})>$h)throw new b("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new b("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(y)),u()}async function m(d=!1){if(c(),o)return o;let h=n,R=(async()=>{let y={inserted:0,duplicates:0,rejected:0,skipped:0},A=a.length;for(;A&&h===n;){let x=[],v=ll({events:[]});for(let _ of a.slice(0,Math.min(A,100))){let X=ll(_)+(x.length?1:0);if(x.length&&v+X>$h)break;x.push(_),v+=X}let P=O.trackEvents,j=await ge(e,P,{events:x},void 0,{keepalive:d});if(h!==n)throw new b("IDENTITY_CHANGED","Event identity changed during delivery");if(j.inserted+j.duplicates+j.rejected+j.skipped!==x.length)throw new b("INVALID_RESPONSE","Incomplete event acknowledgement");i(j.analyticsConfig),a.splice(0,x.length),A-=x.length,y.inserted+=j.inserted,y.duplicates+=j.duplicates,y.rejected+=j.rejected,y.skipped+=j.skipped}return y})();o=R;try{return await R}finally{o===R&&(o=null)}}let f;function g(){if(f||typeof document>"u")return;let d=()=>{document.visibilityState==="hidden"&&t()&&a.length&&m(!0).catch(()=>{})};document.addEventListener("visibilitychange",d),f=()=>document.removeEventListener("visibilitychange",d)}return{rememberConfiguration:i,track:l,flush:m,reset(){n++,r=void 0,clearTimeout(s),s=void 0,a=[],o=null},detachVisibility(){f?.(),f=void 0}}}function dl(e){let t=null,n=null,r=0,i=0,a=new Set,o=null,s=null,c=new Set,u=()=>{for(let y of c)try{y()}catch{}},l={attributes:wt.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(y,A)=>{!a.has(y)&&(!t||!("analyticsConfig"in t)||t.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(y,structuredClone(A),structuredClone(l.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(y,A)=>(!t||!("analyticsConfig"in t)||t.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(y),structuredClone(A),structuredClone(l.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?y=>e.saveStickyBucketAssignmentDoc(structuredClone(y)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},m=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function f(y,A=new Set){return a.has(y)?!o||!o.features[y]||["unknownFeature","cyclicPrerequisite"].includes(o.features[y].source):A.has(y)?!1:(A.add(y),(t?.features[y]?.rules??[]).some(x=>[...x.parentConditions??[],...(x.tracks??[]).flatMap(v=>v.experiment.parentConditions??[])].some(v=>f(v.id,A))))}let g=y=>{if(e.assertUsable?.(t?.generation),!t)throw new Error("Initialize the Feature client before evaluation");if(t.expiresAt&&Date.parse(t.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return o?.expiresAt&&Date.parse(o.expiresAt)<=Date.now()&&(o=null,l.features=t.features),a.has(y)?!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now()?m():structuredClone(o.features[y]??m()):e.evaluateRemote&&(l.attributes?.merchandise||l.attributes?.merchandiseId)&&!o||f(y)?m():structuredClone(Kn(y,l))};async function d(){if(!t||!a.size&&!l.attributes?.merchandise&&!l.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(a.size)throw new Error("Remote Feature evaluation requires a server loader");return}let y=i;if(s?.revision===y)return s.loading;let A=r,x=t,v=[...a],P=(async()=>{let j=Ua.parse(await e.evaluateRemote({attributes:structuredClone(l.attributes),features:v}));if(!(A!==r||y!==i||x!==t)){if(e.assertUsable?.(x.generation),j.generation!==x.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(v.some(_=>!Object.hasOwn(j.features,_))||Object.keys(j.features).some(_=>!a.has(_)))throw new Error("Invalid remote Feature results");if(l.attributes?.merchandise||l.attributes?.merchandiseId){if(!j.merchandiseContext)throw new Error("Server did not resolve merchandise context");l.attributes=wt.parse({...l.attributes,...j.merchandiseContext})}o=structuredClone(j),l.features={...x.features,...Object.fromEntries(Object.entries(o.features).map(([_,X])=>[_,{defaultValue:X.value}]))},u()}})();s={revision:y,loading:P};try{await P}finally{s?.loading===P&&(s=null)}}function h(){d().catch(y=>{try{e.onError?.(y)}catch{}})}async function R(){if(n)return n;let y=r,A=(async()=>{let x=await e.load(),v="remoteFeatures"in x?fo.parse(x):null,P=v??yn.parse(x);if(P.scope.projectId!==e.scope.projectId||P.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(y!==r)throw new Error("Feature client was reset");if(e.assertUsable&&t?.generation===P.generation){let{evaluatedAt:_,expiresAt:X,...le}=t,{evaluatedAt:he,expiresAt:ke,...Se}=P;if(Pt(le)!==Pt(Se))throw new Error("Immutable Feature generation changed content");return t.evaluatedAt=P.evaluatedAt,t.expiresAt=P.expiresAt,u(),(!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())&&h(),structuredClone(t)}let j=new Set(v?.remoteFeatures??[]);if([...j].some(_=>Object.hasOwn(P.features,_)))throw new Error("Remote Feature definitions must not be delivered locally");return t&&"analyticsConfig"in t&&"analyticsConfig"in P&&!t.analyticsConfig.experimentViewsEnabled&&v?.analyticsConfig.experimentViewsEnabled&&l.trackedExperiments?.clear(),t=structuredClone(P),a=j,o=null,s=null,i++,l.features=t.features,l.savedGroups=ii(t.savedGroups),l.trackedFeatureUsage={},u(),h(),structuredClone(t)})();n=A;try{return await A}finally{n===A&&(n=null)}}return{init:R,refresh:R,refreshRemote:d,get generation(){return t?.generation??null},get expiresAt(){return t?.expiresAt??null},subscribe(y){return c.add(y),()=>{c.delete(y)}},setAttributes(y){let A=wt.parse(y);(l.attributes?.merchandise||l.attributes?.merchandiseId||y.merchandise||y.merchandiseId)&&l.trackedExperiments?.clear(),l.attributes=A,i++,o=null,s=null,l.features=t?.features??{},l.trackedFeatureUsage={},u(),h()},evalFeature:g,isOn(y){return g(y).on},isOff(y){return g(y).off},getFeatureValue(y,A){let x=g(y).value;return structuredClone(x===null?A:x)},reset(){r++,i++,n=null,s=null,t=null,o=null,a.clear(),l.features={},l.savedGroups={},l.stickyBucketAssignmentDocs={},l.attributes={},l.trackedFeatureUsage={},l.trackedExperiments?.clear(),u()}}}function Kh(e){let t=e.merchandise;if(typeof e.merchandiseId=="string")return{internalId:e.merchandiseId};if(!(!t||typeof t!="object"||Array.isArray(t))){if(typeof t.internalId=="string")return{internalId:t.internalId};if(typeof t.externalId=="string")return{id:t.externalId};if(typeof t.id=="string")return{id:t.id}}}function yv(e){let t=Kh(e),{merchandiseId:n,merchandise:r,...i}=e;return{...i,...t?{merchandise:t}:{}}}function Hh(e,t,n,r,i){if(i&&r&&(i.scope.projectId!==r.projectId||i.scope.environment!==r.environment))throw new b("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,o=new Set;function s(){if(!t())throw new b("NOT_IDENTIFIED","Call identify before using Features or events")}async function c(u={}){i||s();let l=a,m=!1,f=async()=>{if(m||l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let he=O.getFeatures,ke=i?{scope:{projectId:i.scope.projectId,environment:i.scope.environment},payload:await i.features()}:await ge(e,he,{});if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");if(r&&(ke.scope.projectId!==r.projectId||ke.scope.environment!==r.environment))throw new b("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(ke.payload.analyticsConfig),ke},g=await f(),d=!0,h,R=he=>{try{u.onError?.(he)}catch{}},y=(he,ke,Se)=>{try{let ht=Kh(Se);n.track(he,ke,ht?{merchandise:ht}:{})}catch(ht){R(ht)}},A=dl({assertUsable:i?.assertFeatures,scope:g.scope,attributes:u.attributes,onError:u.onError,load:async()=>d?(d=!1,g.payload):(await f()).payload,evaluateRemote:async he=>{if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let ke=O.evaluateFeatures,Se=await ge(e,ke,{...he,attributes:yv(he.attributes)});if(Se.scope.projectId!==g.scope.projectId||Se.scope.environment!==g.scope.environment)throw new b("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:Se.generation,evaluatedAt:Se.evaluatedAt,expiresAt:Se.expiresAt,features:Se.features,...Se.merchandiseContext?{merchandiseContext:Se.merchandiseContext}:{}}},onExperimentViewed:(he,ke,Se)=>y("Experiment Viewed",{experimentId:he.key,variationId:ke.key},Se),onFeatureUsage:(he,ke,Se)=>y("Feature Evaluated",{feature:he,value:ke.value,source:ke.source,ruleId:ke.ruleId,...ke.experimentResult?{variationId:ke.experimentResult.key}:{}},Se)}),x=A.refresh;function v(){clearTimeout(h),!i&&(m||l!==a||!A.expiresAt||(h=setTimeout(()=>{P().catch(R)},Math.min(2147483647,Math.max(1e3,Date.parse(A.expiresAt)-Date.now()))),typeof h=="object"&&"unref"in h&&h.unref()))}async function P(){try{return await x()}finally{v()}}let j=()=>{m||P().catch(R)},_=A.subscribe(v),X=i?.subscribe(()=>{!m&&i.fresh&&P().catch(R)});function le(){m||(m=!0,clearTimeout(h),typeof window<"u"&&window.removeEventListener("focus",j),_(),X?.(),A.reset(),o.delete(le))}o.add(le);try{await A.init(),(u.attributes?.merchandise||u.attributes?.merchandiseId)&&await A.refreshRemote()}catch(he){throw le(),he}return v(),!i&&typeof window<"u"&&window.addEventListener("focus",j),Object.assign(A,{refresh:P,destroy:le})}return{features:c,reset(u){a++,u();for(let l of o)l()}}}import{z as Av}from"zod";function Qh(e,t){let n="source"in t?{funnelId:t.source.id,funnelVersionId:t.source.versionId}:"versionId"in t?{funnelId:t.funnelId,funnelVersionId:t.versionId}:t,r=Av.object({funnelId:as.shape.id,funnelVersionId:as.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new b("INVALID_REQUEST","A valid Funnel source is required");let i=Object.freeze(r.data);function a(o){if("customerId"in o)throw new b("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in o&&o.funnelId!==void 0&&o.funnelId!==i.funnelId||"funnelVersionId"in o&&o.funnelVersionId!==void 0&&o.funnelVersionId!==i.funnelVersionId)throw new b("SCOPE_MISMATCH","The original Funnel source cannot change");return{...o,...i}}return{async claimCoupon(o,s=crypto.randomUUID()){let c=O.grantOffer,u=await ge(e,c,a({couponId:o,requestId:s}));return{offer:u.offer,reason:u.reason}},async resolveOffering(o){let s=O.resolveOffering;return ge(e,s,a(o))},async resolvePaywall(o){let s=O.resolvePaywall;return ge(e,s,a(o))},async previewAttach(o){let s=O.previewAttach;return ge(e,s,a(o))}}}function Jh(e){let t=fr(e),n=t.request,r;try{r=ch(e.push,t,e.scope??e.configuration?.scope)}catch(s){throw t.dispose(),s}let i=Fh(t,()=>{o.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=Gh(n,i.isIdentified),o=Hh(n,i.isIdentified,a,e.scope,e.configuration);return{session:t.session,...lh(n,r),...Lh(n),...zh(n),forFunnel(s){return i.assertActive(),Qh(n,s)},async features(s={}){return i.assertActive(),o.features(s)},track(s,c,u={}){return a.track(s,c,u)},flush(){return a.flush()},...i.methods}}function Ni(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,a)=>Ni(i,t[a]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let n=Object.entries(e),r=Object.entries(t);return n.length===r.length&&n.every(([i,a])=>Object.hasOwn(t,i)&&Ni(a,Reflect.get(t,i)))}function As(e,t){let n=Gg.safeParse(t);if(!n.success)throw new b("INVALID_RESPONSE","Funnel response contract changed");let r=n.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new b("SCOPE_MISMATCH","Funnel scope changed");return r}var Di=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function bs(e){let t=kt.test(e.apiKey);if(typeof window<"u"&&!t)throw new b("SERVER_ONLY","Funnel starts are issued by your backend");if(!t&&!Di.test(e.apiKey))throw new b("INVALID_TOKEN","A customer credential or server API key is required");return{async start(n){let r=Ot.safeParse({...n,operation:"start"});if(!r.success||r.data.operation!=="start"||(t?r.data.customer!==void 0:r.data.customer===void 0))throw new b("INVALID_REQUEST","Invalid current Funnel start");let i=r.data,a=fr({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||a.identify(e.apiKey);let o=As(e,await a.request("funnels",i));if(!o.runToken)throw new b("INVALID_RESPONSE","Funnel start credentials are missing");if(o.run.source.id!==i.funnelId||o.run.locale!==(i.locale??"en")||!Ni(o.run.parameters,i.parameters??{})||(i.customer?!o.customerId||i.customer.type==="id"&&o.customerId!==i.customer.value:o.customerId!==void 0))throw new b("INVALID_RESPONSE","Funnel start contract changed");return{...o,runToken:o.runToken}}finally{a.dispose()}}}}async function pl(e,t,n){if(Number(e.headers.get("content-length"))>t)throw e.body?.cancel().catch(()=>{}),n.error("limit");let r=e.body?.getReader();if(!r)throw n.error("missing");let i=[],a=0,o=!1,s=()=>{},c=new Promise((m,f)=>{s=()=>f(n.signal?.reason),n.signal?.addEventListener("abort",s,{once:!0}),n.signal?.aborted&&s()});try{for(;;){let m=await Promise.race([r.read(),c]);if(m.done){o=!0;break}if(a+=m.value.length,a>t)throw n.error("limit");i.push(m.value)}}finally{n.signal?.removeEventListener("abort",s),o||r.cancel().catch(()=>{}),r.releaseLock()}n.signal?.throwIfAborted();let u=new Uint8Array(a),l=0;for(let m of i)u.set(m,l),l+=m.length;return u}async function Zh(e,t,n){return new TextDecoder("utf-8",{fatal:!0}).decode(await pl(e,t,n))}function xs(e,t){let n=typeof e=="string"?new TextEncoder().encode(e):e;return n.byteLength===t.byteLength&&Iu(n)===t.sha256}async function Ss(e,t){let n=Vr.parse(t),{artifact:r,environmentId:i}=n.content,a=new xn(e.baseUrl??mr).origin,o=new xn(r.url,a);if(o.origin!==a||o.username||o.password||o.search||o.hash||o.pathname!==`/api/v1/configuration/${i}/artifacts/${r.sha256}`)throw new b("INVALID_RESPONSE","Public Paywall locator is not trusted");let s=new AbortController,c,u=new Promise((m,f)=>{c=setTimeout(()=>{let g=new b("TIMEOUT","Public Paywall read timed out");s.abort(g),f(g)},nn.initializationMs)}),l=(async()=>{let m=await(e.fetch??globalThis.fetch)(o,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:s.signal});if(s.signal.aborted&&(m.body?.cancel().catch(()=>{}),s.signal.throwIfAborted()),!m.ok||!m.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(m.headers.get("content-length"))>r.byteLength)throw m.body?.cancel().catch(()=>{}),new b("INVALID_RESPONSE","Public Paywall is unavailable");let f=await pl(m,r.byteLength,{signal:s.signal,error:g=>new b("INVALID_RESPONSE",g==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!xs(f,r))throw new b("INVALID_RESPONSE","Public Paywall digest or size changed");return Yf(n,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(f)))})();try{return await Promise.race([l,u])}finally{clearTimeout(c)}}var Wh=(e,t)=>new b(e,t);var bv=3,xv=2e3;function Sv(e){return e instanceof TypeError||e instanceof b&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Iv(e){for(let t=1;;t++)try{return await e.refresh()}catch(n){if(t===bv||!Sv(n))throw n;await new Promise(r=>setTimeout(r,t*xv))}}async function ml(e,t,{predict:n=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new b("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new b("SCOPE_MISMATCH","Evaluation environment changed");let i=null,a;if(n)try{let o=await e.funnel(t.source.id,t.source.versionId);a=o.manifest.generation,i=vv(e,t,o)}catch{i=null}return a??(a=e.snapshot?.generation??(await Iv(e)).generation),{advance:{policyRevision:r.policyRevision,generation:a},prediction:i}}function vv(e,t,n){let r=t.instruction;if(r?.type!=="evaluate_segment"||!n.growth||n.control.evaluationMode!=="local"||n.control.evaluationRevision!==r.policyRevision)return null;let{analyticsConfig:i,remoteFeatures:a,...o}=n.growth,s=Vu({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t.source.id,versionId:t.source.versionId,evaluationMode:"local",evaluationRevision:r.policyRevision,document:n.document,payload:yn.parse(o)}),c=wv(s,n.document,{...t,...r}),u=c.steps.at(-1),l=c.boundary??(u?.result.port==="value"?{nodeId:u.nodeId,visit:t.visit+c.steps.length-1}:null);return l?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:l.nodeId,visit:l.visit,terminal:!c.boundary}:null}function wv(e,t,n){return sh(e,t,n,Wh)}import{z as gn}from"zod";var Yh=Ot.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new b("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),Xh=gn.strictObject({schemaVersion:gn.literal(1),scope:Ne,runId:gn.uuid(),funnelId:gn.uuid(),versionId:gn.uuid(),processBindingIds:gn.record(gn.uuid(),gn.uuid().nullable()).optional(),command:Yh.optional(),closeCommand:Yh.refine(e=>e.operation==="close").optional(),purchase:gn.strictObject({receiptId:gn.uuid(),operationId:gn.uuid(),generation:gn.number().int().nonnegative()}).optional(),closed:gn.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),Xt=()=>new b("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Is=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function ey(e){let t=0,n=null,r=u=>JSON.stringify([u.scope,u.runId,u.funnelId,u.versionId]),i=Promise.resolve();async function a(){let u=await e.read();if(!Number.isSafeInteger(u.revision)||u.revision<0)throw new b("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:u.revision,entry:u.entry===null?null:Xh.parse(u.entry)}}function o(u){let l=i.then(u);return i=l.catch(()=>{}),l}async function s(u){for(let l=0;l<4;l++){let m=await a();if(m.entry&&n!==null&&r(m.entry)!==n)throw Xt();let f=u(m.entry,m.revision);if(Is(m.entry,f)){t=m.revision;return}let g=await e.write(m.revision,f);if(g!==null){if(!Number.isSafeInteger(g)||g<=m.revision)throw Xt();t=g;return}}throw Xt()}function c(u,l){if(!u||!l)return u;if(u.processBindingIds&&Object.hasOwn(u.processBindingIds,l)){let m={...u.processBindingIds};delete m[l],u={...u,processBindingIds:m}}return u.command?.requestId===l?u.closeCommand?{...u,command:u.closeCommand,closeCommand:void 0}:u.purchase?{...u,command:void 0}:null:u.closeCommand?.requestId===l?{...u,closeCommand:void 0}:u}return{bind(u){let l=JSON.stringify([u.scope,u.runId,u.funnelId,u.versionId]);if(n!==null&&n!==l)throw Xt();n=l},async load(){let u=await a();return t=u.revision,n=u.entry?r(u.entry):null,u.entry},retain(u){let l=Xh.parse(u),m=l.command;return!m||n!==null&&r(l)!==n?Promise.reject(Xt()):(n??(n=r(l)),o(()=>s((f,g)=>{if(f&&!Is(r(f),r(l)))throw Xt();if(f&&l.processBindingIds){for(let[d,h]of Object.entries(l.processBindingIds))if(f.processBindingIds&&Object.hasOwn(f.processBindingIds,d)&&f.processBindingIds[d]!==h)throw Xt();f={...f,processBindingIds:{...f.processBindingIds,...l.processBindingIds}}}if(!f){if(g!==t&&m.operation!=="close")throw Xt();return l}if(!f.command)return{...f,command:m,...m.operation==="close"?{closed:!0}:{}};if(m.operation==="close"&&f.command.operation!=="close"){if(f.command.requestId===m.requestId||f.closeCommand&&!Is(f.closeCommand,m))throw Xt();return{...f,closeCommand:m,closed:!0}}if(!Is(f.command,m))throw Xt();return f})))},observePurchase(u,l,m,f){return o(()=>s((g,d)=>{if(!g&&d!==t||g&&r(g)!==r({...u,schemaVersion:1}))throw Xt();if(g?.purchase&&g.purchase.generation>l.generation)return c(g,f);if(g?.purchase&&g.purchase.generation===l.generation&&g.purchase.operationId!==l.operationId)throw Xt();return m?!g?.purchase||g.purchase.operationId!==l.operationId?c(g,f):c(g.command?{...g,purchase:void 0}:null,f):c({schemaVersion:1,...u,...g,purchase:l},f)}))},settle(u){return o(()=>s(l=>c(l,u)))}}}function ty(e){let t,n,r=()=>new b("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,n=e.locks??globalThis.navigator?.locks,!t||!n||!globalThis.crypto?.subtle)throw r();let s=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??mr).href,e.runToken])),c=new Uint8Array(await crypto.subtle.digest("SHA-256",s));return"indiana.funnel.commands.v1."+Array.from(c,u=>u.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function a(s){try{let c=await i;return await n.request(c,{mode:"exclusive"},()=>s(c))}catch(c){throw c instanceof b?c:r()}}function o(s){let c=t.getItem(s);if(c===null)return{revision:0,entry:null};if(c.length>1048576)throw r();let u=JSON.parse(c);if(!u||typeof u!="object"||!("revision"in u)||!("entry"in u)||!Number.isSafeInteger(u.revision)||Number(u.revision)<0)throw r();return{revision:Number(u.revision),entry:u.entry}}return{read:()=>a(o),write:(s,c)=>a(u=>{if(o(u).revision!==s)return null;if(!Number.isSafeInteger(s+1))throw r();return t.setItem(u,JSON.stringify({revision:s+1,entry:c})),s+1})}}function ny(e,t){let n=t&&{...t},r=null,i=0,a=new AbortController;function o(){i++,a.abort(new b("IDENTITY_CHANGED","Run identity changed")),a=new AbortController}let s=!1,c,u=0,l=new Set;return{get scope(){return n},bindScope(m){if(n&&(n.projectId!==m.projectId||n.environment!==m.environment))throw new b("SCOPE_MISMATCH","Run scope changed");n??(n={...m})},get view(){return r},get generation(){return i},get signal(){return a.signal},get disposed(){return s},get customerToken(){return c},get readSequence(){return u},nextRead(){return++u},assertCurrent(m,f="Run identity changed during the request"){if(m!==i||s)throw new b("IDENTITY_CHANGED",f)},assertRun(m){if(r&&(m.id!==r.id||m.source.type!==r.source.type||m.source.id!==r.source.id||m.source.versionId!==r.source.versionId||m.locale!==r.locale||!Ni(m.parameters,r.parameters)))throw new b("INVALID_RESPONSE","Run version changed");if(e&&m.source.id!==e)throw new b("INVALID_RESPONSE","Run belongs to another Funnel")},publish(m,f,g,d,h){if(!(m.operation==="review"&&r&&r!==g&&f.run.revision<=r.revision)&&!(r&&f.run.revision===r.revision&&d!==void 0&&d<u)&&(m.operation==="review"&&!f.run.stopped&&["running","waiting"].includes(f.run.status)&&r&&f.run.nodeId===r.nodeId&&f.run.visit===r.visit&&f.run.revision===r.revision&&(f.run.screen=r.screen,(r.paywall?.quote?.operationId===f.review?.activeOperationId||!r.paywall?.quote&&f.review?.activeOperationId===null)&&(f.run.paywall=r.paywall)),!(r?.paywall&&f.run.paywall&&r.paywall.receiptId===f.run.paywall.receiptId&&(f.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||f.run.revision>=r.revision)r=f.run;else if(!h)return;if(r)for(let R of l)try{R(structuredClone(r))}catch{}}},identify(m){if(s)throw new b("IDENTITY_CHANGED","Controller was reset");if(!kt.test(m))throw new b("INVALID_TOKEN","Customer credential required");o(),c=m},subscribe(m){return l.add(m),()=>l.delete(m)},reset(){s||(s=!0,o(),c=void 0,r=null,l.clear())}}}function gr(e){let{customerToken:t,...n}=e;return n}var Ov=e=>!(e instanceof b)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function ry({journal:e,state:t,call:n,processIdentity:r}){let i=null,a=null,o=!1,s={command:null,close:null},c=new Set,u,l=null,m=e?e.load().then(y=>{if(t.disposed)throw new b("IDENTITY_CHANGED","Controller was reset during command restoration");if(l=y,!y)return;if(r){if([y.command,y.closeCommand].some(x=>x&&!Object.hasOwn(y.processBindingIds??{},x.requestId)))throw new b("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(y.processBindingIds??{})}if(t.scope&&(y.scope.projectId!==t.scope.projectId||y.scope.environment!==t.scope.environment))throw new b("SCOPE_MISMATCH","Pending command belongs to another scope");if(u=y.purchase,o=y.closed===!0,!y.command)return;let A=y.command;i=A.operation==="close"?null:A,a=A.operation==="close"?A:y.closeCommand?.operation==="close"?y.closeCommand:null,a&&(o=!0);for(let x of[i,a])x&&c.add(x.requestId)}):Promise.resolve();m.catch(()=>{});async function f(y){e&&await m;let A=t.generation;if(e){if(!t.view||!t.scope)throw new b("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:gr(y),...r?{processBindingIds:{[y.requestId]:r.binding(y.requestId)}}:{}})}if(A!==t.generation||i!==y&&a!==y)throw new b("IDENTITY_CHANGED","Run changed before command dispatch");let x=c.has(y.requestId);c.add(y.requestId);try{return await n(y)}catch(v){throw A===t.generation&&(i===y||a===y)&&!x&&!Ov(v)&&(e&&await e.settle(y.requestId),A===t.generation&&R(y)),v}}function g(y){let A=Ot.parse(y);if(A.operation==="start"||A.operation==="get"||A.operation==="review")throw new b("INVALID_REQUEST","Mutation required");if(o&&A.operation!=="close"){if(i?.requestId===A.requestId)return h(A.requestId);throw new b("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(A.operation==="close"){if(i?.requestId===A.requestId)throw new b("INVALID_REQUEST","Close requires its own request identity");if(o=!0,a&&JSON.stringify(gr(a))!==JSON.stringify(gr(A)))throw new b("COMMAND_PENDING","Retry the original Close");return a??(a=A),s.close?s.close:d(a,"close")}if(i){if(JSON.stringify(gr(i))!==JSON.stringify(gr(A)))throw new b("COMMAND_PENDING","Retry the original command before sending another");if(s.command)return s.command}else i=A;return d(i,"command")}function d(y,A){let x=f(y);s[A]=x;let v=()=>{s[A]===x&&(s[A]=null)};return x.then(v,v),x}function h(y){return n({operation:"get",settlementRequestId:y})}function R(y){return!y||i!==y&&a!==y?!1:(i===y&&(i=null),a===y&&(a=null),c.delete(y.requestId),!i&&!a&&(l=null),!0)}return{ready:m,get pending(){return i},get closing(){return a},get closeRequested(){return o},get inFlight(){return s.command},get closeFlight(){return s.close},get purchase(){return u},assertBinding(y){if(l&&(y.run.id!==l.runId||y.run.source.id!==l.funnelId||y.run.source.versionId!==l.versionId))throw new b("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(y,A,x,v){let P=y.operation==="get"?y.settlementRequestId:"requestId"in y&&y.operation!=="start"?y.requestId:void 0,j=P&&A.settlement?.state==="settled"&&A.run.pendingRequest?.requestId!==P&&(y.operation==="get"||!o||y.operation==="close"||!["running","waiting"].includes(A.run.status))?P:void 0,_=i?.requestId===j?i:a?.requestId===j?a:void 0;e?.bind({scope:A.scope,runId:A.run.id,funnelId:A.run.source.id,versionId:A.run.source.versionId});let X=A.run.paywall,le=X??A.purchase,he=le?.operation,ke=A.settlement&&(!X||X.purchaseRequestId===A.settlement.requestId)&&(!u||u.operationId===A.settlement.operationId)?A.settlement:void 0,Se=he?.operationId??le?.quote?.operationId??ke?.operationId,ht=le?.receiptId??ke?.receiptId,Je=X?.selectionGeneration??u?.generation??0;if(e&&Se&&ht&&y.operation!=="review"&&(!t.view||A.run.revision>=t.view.revision)&&(v===void 0||v>=t.readSequence)&&(!u||Je>=u.generation)){let Te={receiptId:ht,operationId:Se,generation:Je},tt=he?.status==="complete"||le?.canReselect===!0;await e.observePurchase({scope:A.scope,runId:A.run.id,funnelId:A.run.source.id,versionId:A.run.source.versionId},Te,tt,j),t.assertCurrent(x),(!u||Te.generation>=u.generation)&&(v===void 0||v>=t.readSequence)&&(tt?u?.operationId===Te.operationId&&(u=void 0):u=Te)}else e&&j&&await e.settle(j);return t.assertCurrent(x),j?R(_):!1},stop(){o=!0},submit:g,settle:h,reset(){o=!0,i=null,a=null,u=void 0,l=null,s.close=null,c.clear(),s.command=null}}}function hr(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new b("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!Di.test(e.serverKey)))throw new b("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new b("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let t=fr({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),n=ny(e.funnelId,e.scope??e.configuration?.scope),r=e.session?.subscribeIdentity(u),i=null,a=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?ty(e):void 0),o=a&&ey(a),s=ry({journal:o,state:n,call:l,processIdentity:e.process});async function c(A){if(e.process)return e.process.request(A);let x=n.generation;n.assertCurrent(x);let v=performance.now()+(e.timeoutMs??35e3),P=n.customerToken??("customerToken"in A?A.customerToken:void 0);if(e.session){let X=n.signal,le,he=()=>{},ke=new Promise((Se,ht)=>{he=()=>ht(X.reason),X.addEventListener("abort",he,{once:!0}),le=setTimeout(()=>ht(new b("TIMEOUT","Longplay request timed out")),Math.max(1,v-performance.now()))});try{P=await Promise.race([Promise.resolve().then(()=>(n.assertCurrent(x),e.session.access())),ke])}finally{clearTimeout(le),X.removeEventListener("abort",he)}}n.assertCurrent(x);let j={...A,...P?{customerToken:P}:{}},_=A.operation==="page_experiments"?Co.parse(j):Ot.parse(j);return t.requestWithCredential("funnels",_,e.runToken,{headers:e.serverKey&&!P?{[Kg]:e.serverKey}:void 0,timeoutMs:Math.max(1,v-performance.now())})}function u(){r?.(),n.reset(),s.reset(),i=null,t.dispose()}async function l(A,x){let v=n.generation,P=()=>n.assertCurrent(v);o&&await s.ready,P();let j=n.view,_=As(e,await c(A));if(A.operation==="review"&&!_.review)throw new b("INVALID_RESPONSE","Historical projection is missing");if(P(),_.runToken&&_.runToken!==e.runToken)throw new b("INVALID_RESPONSE","Run credential changed");let X=A.operation==="get"?A.settlementRequestId:"requestId"in A&&A.operation!=="start"?A.requestId:void 0;if(X&&_.settlement?.requestId!==X)throw new b("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");s.assertBinding(_),n.assertRun(_.run),n.bindScope(_.scope);let le=await s.observe(A,_,v,x);return!_.run.stopped&&["running","waiting"].includes(_.run.status)&&A.operation==="get"&&A.settlementRequestId||(P(),["running","waiting"].includes(_.run.status)||s.stop(),n.publish(A,_,j,x,le)),_}let m=s.submit,f=null,g=new WeakMap;function d(A){let x=g.get(A);if(x)return x;let v=R(A);return g.set(A,v),v}let h=!1;async function R(A){let x=await A;if(x.run.instruction?.type!=="evaluate_segment")return x;if(f)return f;h=!0;let v=n.generation,P=(async()=>{for(let j=0;j<32&&x.run.instruction?.type==="evaluate_segment";j++){if(s.pending||s.closeRequested)return x;let _=x.run;if(x.run.instruction?.type==="evaluate_segment"){let{advance:le}=await ml(e.configuration,_,{predict:!1});if(v!==n.generation)throw new b("IDENTITY_CHANGED","Run identity changed during segment calculation");if(s.pending||s.closeRequested)return x;if(n.view&&(n.view.revision!==_.revision||n.view.visit!==_.visit||n.view.nodeId!==_.nodeId))return l({operation:"get"});let he=!0;ml(e.configuration,_).then(({prediction:ke})=>{he&&v===n.generation&&!s.closeRequested&&n.view?.id===_.id&&!n.view.stopped&&n.view.nodeId===_.nodeId&&n.view.visit===_.visit&&n.view.revision===_.revision&&(i=ke)}).catch(()=>{});try{x=await m({operation:"commit_segment",requestId:$g(_.id,_.visit,`segment:${_.revision}`),nodeId:_.nodeId,visit:_.visit,revision:_.revision,...le})}finally{he=!1,i=null}}}return x})();f=P;try{return await P}finally{f===P&&(f=null)}}let y={get configuration(){return h?e.configuration:void 0},get configurationReady(){return!0},get view(){return n.view?structuredClone(n.view):null},get pendingCommand(){let A=s.closing??s.pending;return A?structuredClone(gr(A)):null},get pendingCommands(){return[s.pending,s.closing].filter(A=>A!==null).map(A=>structuredClone(gr(A)))},get pendingPurchase(){return s.purchase?structuredClone(s.purchase):null},get hasDurableJournal(){return o!==void 0},get prediction(){let A=n.view;return i&&A&&!A.stopped&&["running","waiting"].includes(A.status)&&A.id===i.runId&&A.nodeId===i.from.nodeId&&A.visit===i.from.visit&&A.revision===i.from.revision&&!s.closeRequested?structuredClone(i):null},settle:s.settle,get webViewUrl(){return"bundled"},resolvePaywall(A){return Ss(e,A)},async pageExperiments(A,x=[]){let v=n.generation;n.assertCurrent(v);let P=n.view?.id;if(!P)throw new b("INVALID_REQUEST","Read the Run before its page experiments");let j=Zg.parse(await c(Co.parse({operation:"page_experiments",release:A,usedReceiptIds:x})));if(n.assertCurrent(v),j.runId!==P||j.scope.projectId!==n.scope?.projectId||j.scope.environment!==n.scope?.environment)throw new b("SCOPE_MISMATCH","Page experiment Run changed");return j},review(A){return l({operation:"review",...A?{receiptId:A}:{}},n.nextRead())},async get(A,x){o&&await s.ready,x??(x=s.purchase&&{receiptId:s.purchase.receiptId,operationId:s.purchase.operationId});let v=n.nextRead();return d(l({operation:"get",...A?{data:A}:{},...x?{purchase:x}:{}},v))},resume(A=n.view?.pendingRequest?.requestId){return A?s.closeRequested?y.settle(A):s.pending?.requestId===A?d(m(s.pending)):d(m({operation:"resume",requestId:A})):Promise.reject(new b("INVALID_REQUEST","No interrupted command is available"))},submit(A){return d(m(A))},retry(){return s.closeFlight?s.closeFlight:s.closing?m(s.closing):s.closeRequested&&s.pending?y.settle(s.pending.requestId):s.inFlight?d(s.inFlight):s.pending?d(m(s.pending)):Promise.reject(new b("INVALID_REQUEST","No command is pending"))},identify(A){n.identify(A),i=null,t.reset()},subscribe:n.subscribe,reset:u};return y}function iy(e){if(!kt.test(e.customerToken))throw new b("INVALID_TOKEN","A customer credential is required");if(!e.scope)throw new b("INVALID_REQUEST","An explicit App and environment scope is required");let t=bs({...e,scope:e.scope,apiKey:e.customerToken});return{async start(n){let r=await t.start(n),i=hr({...e,runToken:r.runToken});i.identify(e.customerToken);let a=r.run.instruction?.type==="evaluate_segment"?await i.get():r;return{...r,...a,controller:i}}}}function oy(e,t){let n=r=>"document"in r?r.offering.id:r.content.offeringVersionId;return e.id===t.id&&n(e)===n(t)&&e.content?.artifact.sha256===t.content?.artifact.sha256}function ay(e,t,n){if(e.operationId!==t.operationId||t.currency!==void 0&&e.currency!==t.currency)throw new b("INVALID_RESPONSE",n)}function sy(e,t,n){let r=Object.fromEntries((e.lines[0]?.prepaid??[]).map(i=>[i.internal_feature_id,i.quantity]));if(t.featureQuantities&&(Object.keys(r).length!==Object.keys(t.featureQuantities).length||Object.entries(t.featureQuantities).some(([i,a])=>r[i]!==a)))throw new b("INVALID_RESPONSE","The purchase quote changed its selected quantities");if(e.lines.length!==1||e.lines[0].productVersionId!==t.productVersionId||t.currency!==void 0&&e.currency!==t.currency||t.provider!==void 0&&e.provider!==t.provider&&!(t.provider==="stripe"&&e.provider==="merchant"&&e.execution?.provider==="merchant"))throw new b("INVALID_RESPONSE",n)}function cy(e,t,n=!1){return!e||e.operationId!==t?.operationId?t:e.status==="complete"&&t.status!=="complete"||e.status!=="pending"&&(t.status==="pending"||n&&t.status!=="complete")?e:t}function uy(e){let{quote:t,operation:n,requestId:r}=e,a={type:"recover",operationId:n?.operationId??t?.operationId??null,requestId:r};if(e.destroyed||e.pending)return a;if(!n)return t?{type:"cancel",operationId:t.operationId}:a;let o=n.merchantExecution;if(o?.type==="purchase"){if(["succeeded","not_required"].includes(o.paymentStatus))return!["applied","not_applicable"].includes(o.fulfillmentStatus)||n.problem?.phase==="fulfillment"||o.problem?.phase==="fulfillment"?{type:"fulfillment",operationId:n.operationId}:{type:o.recordingStatus==="accepted"&&n.status==="complete"?"complete":"recording",operationId:n.operationId};if(n.status==="pending"&&n.checkoutUrl&&o.checkoutUrl===n.checkoutUrl&&o.checkoutExpiresAt&&Date.parse(o.checkoutExpiresAt)>Date.now()&&["not_started","pending"].includes(o.paymentStatus))return{type:"checkout",operationId:n.operationId,checkoutUrl:n.checkoutUrl}}let s=[n.problem,o?.problem],c=s.every(u=>!u||u.phase==="execution"&&u.reason!=="RESULT_UNKNOWN");return!s.some(Boolean)&&n.status==="complete"&&n.executor!=="merchant"?{type:"complete",operationId:n.operationId}:c&&e.canReselect!==!1&&["cancelled","failed"].includes(n.status)&&!n.checkoutUrl&&!n.execution&&!n.nativePurchase&&(n.executor!=="merchant"?!n.confirmedAt&&(n.status==="cancelled"||!n.quoteFinalized):!o&&!n.quoteFinalized||o?.type==="purchase"&&["failed","expired"].includes(o.paymentStatus)&&o.fulfillmentStatus==="not_applicable"&&o.recordingStatus==="accepted")?{type:"native",operationId:n.operationId}:n.status==="pending"&&c&&!n.quoteFinalized&&!o&&!n.checkoutUrl&&!n.execution&&!n.nativePurchase?{type:"cancel",operationId:n.operationId}:a}async function ly(e,t){if(!kt.test(t.customerToken))throw new b("INVALID_TOKEN","A verified Customer credential is required");if(e.session&&e.session.peek()!==t.customerToken)throw new b("SCOPE_MISMATCH","Paywall credential does not match the shared session");let n=O.resolvePaywall.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale,...t.requirement?{requirement:t.requirement}:{}}),r=fr(e);e.session||r.identify(t.customerToken);let i=null,a=!1,o=null,s=null,c=null,u=null,l=null,m=null,f=null,g=0;function d(){if(a)throw new b("IDENTITY_CHANGED","Paywall is closed")}async function h(){d();let x=O.resolvePaywall,v=await ge(r.request,x,{...n,selector:i?{type:"version",versionId:i.id}:n.selector}),P=await Ss(e,v.paywall);if(d(),t.paywallVersionId?P.id!==t.paywallVersionId:P.paywallId!==t.paywallId)throw new b("INVALID_RESPONSE","The requested Paywall changed");if(i&&(!oy(P,i)||P.paywallId!==i.paywallId))throw new b("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return i=P,structuredClone(i)}async function R(x){if(d(),u&&x!=="read")throw new b("COMMAND_PENDING","Wait for the original quote");if(!o)throw new b("INVALID_REQUEST","A quoted purchase is required");let v=o;if(x!=="read"){if(f){if(m===x)return f;throw new b("COMMAND_PENDING","Wait for the original purchase command")}if(m&&m!==x)throw new b("COMMAND_PENDING","Read the original purchase before changing an uncertain command");m=x,g++}let P=m,j=g,_=x==="read"&&f===null,X=x==="read"?O.readSubscriptionOperation:O.attach,le=(async()=>{let he=await ge(r.request,X,{operationId:v.operationId,...x==="read"?{}:{intent:x}});return ay(he.operation,{operationId:v.operationId,currency:n.commerce.currency},"The purchase operation changed"),d(),o?.operationId!==v.operationId?structuredClone(he.operation):(s=cy(s,he.operation),(x!=="read"||_&&f===null)&&g===j&&m===P&&(m=null),structuredClone(s))})();if(x!=="read"){f=le;let he=()=>{f===le&&(f=null)};le.then(he,he)}return le}let y={get view(){return i?structuredClone(i):null},get quote(){return o?structuredClone(o):null},get operation(){return s?structuredClone(s):null},get webViewUrl(){return"bundled"},get recovery(){return uy({quote:o,operation:s,requestId:l,pending:u!==null||m!==null,destroyed:a})},get pendingCancellation(){return!a&&m==="cancel"},refresh:h,async preview(x){if(d(),!i)throw new b("INVALID_REQUEST","Load the Paywall first");let v=i.document.buttons[x.actionId];if(v?.type!=="checkout")throw new b("INVALID_REQUEST","Choose an authored purchase action");let P=Xm(v.product,x.selection,i.capabilities);if(!P)throw new b("PRODUCT_UNAVAILABLE","Choose an available Product");let j=zf(i.document.screen,P,x.selection,i.capabilities),_=O.previewAttach.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,requestId:x.requestId,plans:[{productVersionId:P,...Object.keys(j).length?{featureQuantities:j}:{}}],provider:n.commerce.provider,currency:n.commerce.currency,...x.offerId?{offerId:x.offerId}:{},...x.nativeOffer?{nativeOffer:x.nativeOffer}:{}}),X=JSON.stringify(_);if(c&&c!==X&&(u||m||!s||s.status==="pending"))throw new b("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(c===X){if(u)return u;if(o)return structuredClone(o)}c!==X&&(o=null,s=null),c=X,l=_.requestId;let le=(async()=>{let he=O.previewAttach,ke=await ge(r.request,he,_);return d(),sy(ke.quote,{productVersionId:P,featureQuantities:j,currency:n.commerce.currency,provider:n.commerce.provider},"The purchase quote changed its selected Product or presentment"),o=ke.quote,s=null,structuredClone(o)})();u=le;try{return await le}finally{u===le&&(u=null)}},confirm:()=>R("confirm"),cancel:()=>R("cancel"),read:()=>R("read"),destroy(){a||(a=!0,A?.(),r.dispose(),i=null,o=null,s=null,c=null,l=null)}},A=e.session?.subscribeIdentity(y.destroy);try{return await h(),y}catch(x){throw y.destroy(),x}}function dy(e,t){let n,r=0,i=-1,a,o=!1,s=()=>{if(o)throw new b("CLOSED","Native host was destroyed");if(!e.nativeModule)throw new b("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return e.nativeModule},c=()=>new b("IDENTITY_CHANGED","Customer identity changed during the native operation"),u=t.subscribeIdentity(()=>{r++,i=-1;let g=r;n&&e.nativeModule&&n.then(d=>e.nativeModule.reset(d,g)).catch(()=>{})}),l=e.nativeEvents?.(g=>{!n||!e.nativeModule||typeof g?.requestId!="string"||(async()=>{let d=await n;if(g.instanceId!==d)return;if(g.kind==="credential"){let y=r,A=null;try{if(!o&&g.revision===y){let x=await t.access();!o&&r===y&&(A=x)}}finally{await e.nativeModule.provideCredential(d,g.requestId,A)}return}let h=!1,R=r;try{if(o||g.revision!==R||!e.onNativeAction)throw c();await e.onNativeAction(g.action),h=!o&&r===R}finally{await e.nativeModule.acknowledge(d,g.requestId,h)}})().catch(()=>{})});async function m(g,d={}){let h=s();if(t.snapshot()&&!e.nativeEvents)throw new b("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let R=r,y=await t.access();if(o||r!==R)throw c();if(!n){let v=h.create(JSON.stringify({baseUrl:e.baseUrl??"https://api.longplayai.com",scope:e.scope,timeout:(e.timeoutMs??15e3)/1e3,credentialEvents:!!e.nativeEvents}));n=v,v.catch(()=>{n===v&&(n=void 0)})}let A=await n;if(o||r!==R)throw c();if(i!==R){if(!a||a.epoch!==R){let P=(async()=>{if(await h.identify(A,JSON.stringify({revision:R,credentials:y})),o||r!==R)throw await h.reset(A,R),c();i=R})();a={epoch:R,task:P}}let v=a;try{await v.task}finally{a===v&&(a=void 0)}}let x=await h.invoke(A,g,JSON.stringify(d));if(o||r!==R)throw c();try{return JSON.parse(x)}catch{throw new b("INVALID_RESPONSE","Native host returned invalid JSON")}}async function f(g,d){let h=await m(g,d);if(!h||typeof h!="object"||Array.isArray(h)||h.status!=="complete"&&h.status!=="dismissed")throw new b("INVALID_RESPONSE","Native presentation returned an invalid result");return h}return{showFunnel(g){return f("showFunnel",{runToken:g})},showPaywall(g){return f("showPaywall",g)},showContent(g){return f("showContent",g)},purchaseSubscription(g,d){return m("purchaseSubscription",{operationId:g,accepted:d})},switchSubscription(g,d){return m("switchSubscription",{operationId:g,accepted:d})},restorePurchases(){return m("restorePurchases")},manageSubscriptions(g){return m("manageSubscriptions",g?{productId:g}:{})},async dismiss(){r++,i=-1,n&&await s().reset(await n,r)},async destroy(){o||(o=!0,r++,u(),l?.(),n&&e.nativeModule&&await e.nativeModule.destroy(await n))}}}var Pv=O.trackUsage.request.shape.command,Cv=O.trackUsage.response;function _v(e){let t=Ne.parse(e.scope),n=Jh({...e,scope:t}),r={...e,scope:t,session:n.session},i=dy(e,n.session),a=0,o=!1;n.subscribeIdentity(()=>{a++});let s=()=>{if(o)throw new b("CLOSED","SDK client was destroyed");let c=n.session.peek();if(!c)throw new b("UNAUTHENTICATED","Identify the Customer first");return c};return{...n,native:i,async destroy(){o||(o=!0,a++,n.destroy(),await i.destroy())},funnel(){return iy({...r,customerToken:s()})},resumeFunnel(c){return s(),hr({...r,runToken:c})},paywall(c){return ly(r,{...c,customerToken:s()})},async trackUsage(c){if(s(),!e.usageReporter)throw new b("INVALID_REQUEST","Configure your authenticated backend usageReporter");let u=Pv.parse(c),l=a,m;try{m=await e.usageReporter(u)}catch(g){throw l!==a?new b("IDENTITY_CHANGED","Customer identity changed during usage reporting"):g}if(l!==a)throw new b("IDENTITY_CHANGED","Customer identity changed during usage reporting");let f=Cv.parse(m);if(f.scope.projectId!==t.projectId||f.scope.environment!==t.environment)throw new b("INVALID_RESPONSE","Usage response scope differs");return f}}}import{z as jv}from"zod";import{z as To}from"zod";var Ev=To.record(To.string().regex(/^[a-f0-9]{64}$/),To.strictObject({at:To.number(),text:To.string()})),Qr=2*1048576,Rv=100;function kv(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function py(e,t){let n=t===void 0?kv():t,r=new Map,i=0,a=!1,o=!1,s,c;async function u(m){if(!n)return null;let f;try{let g=await Promise.race([Promise.resolve().then(()=>n.getItem(m)),new Promise(d=>{f=setTimeout(()=>d(null),Rv)})]);return typeof g=="string"&&g.length<=Qr&&new TextEncoder().encode(g).byteLength<=Qr?g:null}catch{return null}finally{clearTimeout(f)}}function l(){if(c)return c;let m=(async()=>{try{let f=await u(`${e}:artifacts`);if(f)return Ev.parse(JSON.parse(f))}catch{}return{}})();return c=m,m.finally(()=>{c===m&&(c=void 0)}),m}return{async readManifest(){return u(e)},writeManifest(m){!n||m.length>Qr||new TextEncoder().encode(m).byteLength>Qr||(s=m,!o&&(o=!0,Promise.resolve().then(async()=>{try{for(;s!==void 0;){let f=s;try{await n.setItem(e,f)}catch{}s===f&&(s=void 0)}}finally{o=!1}})))},async readArtifact(m){let f=(await l())[m],g=Date.now();return f&&g>=f.at&&g-f.at<=nn.retentionMs?f.text:void 0},writeArtifact(m,f){if(!n||f.length>Qr)return;let g=r.get(m);if(g?.text===f||!g&&r.size>=128)return;let d=new TextEncoder().encode(f).byteLength;i-(g?.byteLength??0)+d>Qr||(r.set(m,{text:f,byteLength:d}),i+=d-(g?.byteLength??0),!a&&(a=!0,Promise.resolve().then(async()=>{try{for(;r.size;){let h=new Map(r);try{let R={...await l()},y=Date.now();for(let[P,j]of h)R[P]={at:y,text:j.text};let A={},x=2,v=0;for(let[P,j]of Object.entries(R).sort(([,_],[,X])=>X.at-_.at)){if(j.at>y||y-j.at>nn.retentionMs)continue;let _=new TextEncoder().encode(JSON.stringify({[P]:j})).byteLength;x+_>Qr||v>=128||(A[P]=j,x+=_,v++)}await n.setItem(`${e}:artifacts`,JSON.stringify(A))}catch{}finally{for(let[R,y]of h)r.get(R)===y&&(r.delete(R),i-=y.byteLength)}}}finally{a=!1}})))}}}var Pe=(e,t)=>new b(e,t),yr=()=>performance.now(),my=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function Tv(e){let t=bu.parse(e.scope),n=new xn(e.origin??mr);if(n.username||n.password||n.search||n.hash||n.pathname!=="/"||n.protocol!=="https:"&&!(n.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(n.hostname)))throw Pe("INVALID_URL","Configuration requires a trusted HTTPS origin");let r=new Set([n.origin,...(e.assetOrigins??[]).map(Y=>{let J=new xn(Y);if(J.protocol!=="https:"||J.username||J.password||J.search||J.hash||J.pathname!=="/")throw Pe("INVALID_URL","Invalid configuration asset origin");return J.origin})]),i=e.fetch??globalThis.fetch.bind(globalThis),a=`/api/v1/configuration/${t.environmentId}`,o=`indiana:configuration:1:${n.origin}:${Pt(t)}`,s=py(o,e.storage),c,u=0,l=0,m=!1,f=!1,g=0,d=0,h,R,y,A,x=0,v=new Set,P=new Set,j=new Map,_=new Map,X=0,le=!1;function he(){for(let Y of v)try{Y()}catch{}}function ke(Y){try{e.onError?.(Y)}catch{}}let Se=()=>!f&&!m&&!!c&&yr()<u&&Date.now()<l;function ht(){if(!Se())throw Pe("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Je(Y,J,de){if(!j.has(Y)){for(;j.size&&(j.size>=128||X+de>nn.maxCacheBytes);){let pe=j.entries().next().value;X-=pe[1].byteLength,j.delete(pe[0])}j.set(Y,{text:J,byteLength:de}),X+=de}}function Te(Y,J,de){return Zh(Y,J,{signal:de,error:pe=>Pe("INVALID_RESPONSE",pe==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function tt(Y){let J=new xn(Y,n);if(!r.has(J.origin)||J.username||J.password||J.hash||J.search)throw Pe("INVALID_URL","Configuration artifact origin is not trusted");return J.href}async function No(Y,J,de=!1){let pe=await i(tt(Y),{method:"GET",credentials:"omit",redirect:"error",cache:de?"default":"no-cache",signal:J,headers:{}});if(pe.status===429){let Xe=pe.headers.get("retry-after")??"";x=/^\d+$/.test(Xe)?Number(Xe)*1e3:Math.max(0,Date.parse(Xe)-Date.now())||15e3}if(!pe.ok&&pe.status!==304)throw Pe(`CONFIGURATION_HTTP_${pe.status}`,"Configuration synchronization failed");return pe}function Jr(Y,J,de){let pe=Date.parse(Y.headers.get("x-indiana-config-validated-at")??""),Xe=Date.parse(Y.headers.get("x-indiana-config-valid-until")??""),it=Date.parse(Y.headers.get("date")??""),$e=Y.headers.get("age"),on=$e!==null&&/^\d+(\.\d+)?$/.test($e)?Number($e)*1e3:NaN;if(![pe,Xe,it,on].every(Number.isFinite)||Xe<=pe||Xe-pe>nn.maxControlAgeMs||pe>it+1e3)throw Pe("INVALID_RESPONSE","Configuration freshness evidence is invalid");let qt=Math.min(Xe-pe,de.maxControlAgeSeconds*1e3,nn.maxControlAgeMs)-Math.max(on,it-pe,0)-(yr()-J);if(qt<=0)throw Pe("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return yr()+qt}function pt(){if(clearTimeout(y),clearTimeout(A),f||!v.size)return;Se()&&(A=setTimeout(()=>{Se()?pt():he()},Math.max(1,u-yr())),my(A));let Y=d?Math.min(15e3,1e3*2**Math.min(d-1,4)):Math.min(15e3,(c?.policy.refreshIntervalSeconds??15)*1e3);y=setTimeout(()=>{Qt().catch(ke)},Math.max(x,Y*(.8+Math.random()*.2))),my(y)}async function Qt(){if(f)throw Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(h)return h;let Y=g,J=new AbortController;R=J;let de=(async()=>{if(!le){le=!0;try{let Fo=await s.readManifest();if(Fo&&!c){let zn=Su.parse(JSON.parse(Fo));Pt(zn.scope)===Pt(t)&&(c=zn)}}catch{}}J.signal.throwIfAborted();let $e=c,on=yr(),Lt=await No(a,J.signal);Lt.status===304&&(!$e||!Lt.headers.has("x-indiana-config-validated-at")||!Lt.headers.has("x-indiana-config-valid-until")||!Lt.headers.has("age"))&&(Lt=await No(a,J.signal));let qt=Lt.status===304?$e:Su.parse(JSON.parse(await Te(Lt,nn.maxManifestBytes,J.signal))),{generation:Zr,...Wr}=qt,Ln=Lt.headers.get("etag");if(Pt(qt.scope)!==Pt(t)||Qf(Wr)!==Zr||Ln!==`"${Zr}"`&&Ln!==`W/"${Zr}"`)throw Pe("INVALID_RESPONSE","Configuration scope or content identity changed");if($e&&(qt.revision<$e.revision||qt.revision===$e.revision&&qt.generation!==$e.generation))throw Pe("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[Fo,zn]of Object.entries($e?.funnels??{})){let Sr=qt.funnels[Fo];if(Sr&&(Sr.controlRevision<zn.controlRevision||Sr.evaluationRevision<zn.evaluationRevision||Sr.controlRevision===zn.controlRevision&&Sr.state!==zn.state||Sr.evaluationRevision===zn.evaluationRevision&&Sr.evaluationMode!==zn.evaluationMode))throw Pe("INVALID_RESPONSE","Funnel control revision changed identity")}let xr=Jr(Lt,on,qt.policy);if(J.signal.throwIfAborted(),Y!==g)throw Pe("CONFIGURATION_DISPOSED","Configuration scope changed");return c=qt,u=xr,l=Date.now()+Math.max(0,xr-yr()),m=!1,d=0,x=0,s.writeManifest(Pt(qt)),he(),structuredClone(qt)})(),pe=setTimeout(()=>J.abort(Pe("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),nn.initializationMs),Xe=new Promise(($e,on)=>J.signal.addEventListener("abort",()=>on(J.signal.reason),{once:!0})),it=Promise.race([de,Xe]).catch($e=>{throw d++,($e instanceof jv.ZodError||$e instanceof SyntaxError||$e instanceof b&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes($e.code))&&(u=0,m=!0,he()),$e}).finally(()=>{clearTimeout(pe),h===it&&(h=void 0),pt()});return h=it,it}async function Ar(Y){let J=Y.sha256,de=Wr=>xs(Wr,Y);tt(Y.url);let pe=j.get(J);if(pe){if(pe.byteLength!==Y.byteLength)throw Pe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return j.delete(J),j.set(J,pe),pe.text}let Xe=_.get(J);if(Xe){if(Xe.byteLength!==Y.byteLength)throw Pe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return Xe.promise}let it=new AbortController;P.add(it);let $e=g,on=(async()=>{try{let xr=await s.readArtifact(J);if(xr&&de(xr)){if(it.signal.throwIfAborted(),f||$e!==g)throw Pe("CONFIGURATION_DISPOSED","Configuration scope changed");return Je(J,xr,Y.byteLength),xr}}catch{}it.signal.throwIfAborted();let Wr=await No(Y.url,it.signal,!0),Ln=await Te(Wr,Y.byteLength,it.signal);if(!de(Ln))throw Pe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(f||$e!==g)throw Pe("CONFIGURATION_DISPOSED","Configuration scope changed");return Je(J,Ln,Y.byteLength),s.writeArtifact(J,Ln),Ln})(),Lt=setTimeout(()=>it.abort(Pe("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),nn.initializationMs),qt=new Promise((Wr,Ln)=>it.signal.addEventListener("abort",()=>Ln(it.signal.reason),{once:!0})),Zr=Promise.race([on,qt]).finally(()=>{clearTimeout(Lt),P.delete(it),_.delete(J)});return _.set(J,{promise:Zr,byteLength:Y.byteLength}),Zr}async function br(){return Se()||await Qt(),ht(),c}async function Fi(Y){let J,de=new Promise((pe,Xe)=>{J=setTimeout(()=>Xe(Pe("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),nn.initializationMs)});try{return await Promise.race([Y(),de])}finally{clearTimeout(J)}}function Mi(Y,J){if(ht(),c?.generation!==Y.generation)throw Pe("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(J&&c.funnels[J]?.state!=="active")throw Pe("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function gl(Y){let J=Y.gb.features;if(!J)throw Pe("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let de=Y.artifacts[J];if(de.formatVersion!==1)throw Pe("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let pe=Gc.parse(JSON.parse(await Ar(de)));if(Pt(pe.scope)!==Pt({projectId:t.projectId,environment:t.environment})||pe.generation!==de.generation||pe.remoteFeatures.some(Xe=>Object.hasOwn(pe.features,Xe)))throw Pe("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return Mi(Y),{...pe,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,u-yr())).toISOString()}}async function hl(Y,J){let de=await br(),pe=de.funnels[Y];J&&(!pe||pe.evaluationMode==="local"&&!pe.versions[J])&&(h&&await h,de=await Qt()),Mi(de,Y);let Xe=de.funnels[Y];if(Xe.evaluationMode!=="local")throw Pe("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let it=J??Xe.currentVersionId,$e=Xe.versions[it];if(!$e)throw Pe("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(de.artifacts[$e.artifact].formatVersion!==3)throw Pe("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[on,Lt]=await Promise.all([Ar(de.artifacts[$e.artifact]).then(qt=>Zf(JSON.parse(qt))),Xe.evaluationMode==="local"?gl(de):void 0]);if(Lt&&Pt(Jf(on,Lt))!==Pt($e.dependencies))throw Pe("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return Mi(de,Y),{document:on,growth:Lt,versionId:it,control:structuredClone(Xe),manifest:structuredClone(de)}}async function yl(Y,J){try{return await hl(Y,J)}catch(de){if(!(de instanceof b)||!(de.code==="CONFIGURATION_CHANGED"||de.code==="CONFIGURATION_HTTP_404"&&Se()))throw de;let pe=c?.generation;if(h&&await h,await Qt(),de.code!=="CONFIGURATION_CHANGED"&&c?.generation===pe)throw de;return hl(Y,J)}}function vs(){m=!0,he(),Qt().catch(ke)}let Do=()=>{(typeof document>"u"||document.visibilityState==="visible")&&vs()};function fy(Y){if(f)throw Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return v.add(Y),v.size===1&&(typeof window<"u"&&(window.addEventListener("online",vs),window.addEventListener("focus",Do),document.addEventListener("visibilitychange",Do)),pt()),()=>{v.delete(Y),v.size||(clearTimeout(y),clearTimeout(A),Al())}}function Al(){typeof window<"u"&&(window.removeEventListener("online",vs),window.removeEventListener("focus",Do),document.removeEventListener("visibilitychange",Do))}return{scope:Object.freeze({...t}),refresh:Qt,subscribe:fy,assertFresh:ht,assertFeatures(Y){ht();let J=c.gb.features;if(!J)throw Pe("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(Y!==void 0&&c.artifacts[J].generation!==Y)throw Pe("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return Se()},get snapshot(){return c?structuredClone(c):null},get remainingMs(){return Se()?Math.max(0,u-yr()):0},async features(){return Fi(async()=>gl(await br()))},pageExperiments:()=>Fi(async()=>{let Y=await br(),J=Y.gb.pageExperiments;if(!J)throw Pe("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let de=Y.artifacts[J];if(de.formatVersion!==1)throw Pe("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let pe=ih.parse(JSON.parse(await Ar(de)));if(pe.environmentId!==t.environmentId||pe.generation!==de.generation)throw Pe("INVALID_RESPONSE","Page experiment scope or generation changed");return Mi(Y),pe}),funnel:(Y,J)=>Fi(()=>yl(Y,J)),paywall:(Y,J)=>Fi(async()=>{let de=await br(),pe=de.paywalls?.[Y];if(!pe||!J&&pe.state!=="published")throw Pe("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let Xe=J??pe.currentVersionId,it=pe.versions[Xe],$e=it&&de.artifacts[it.artifact];if(!$e||$e.kind!=="paywall"||$e.formatVersion!==1)throw Pe("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let on=is.parse(JSON.parse(await Ar($e)));return Mi(de),{document:on,versionId:Xe,version:it.version,control:structuredClone(pe),manifest:structuredClone(de)}}),async localFunnel(Y,J){let de=await Fi(()=>yl(Y,J));if(!de.growth)throw Pe("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:pe,remoteFeatures:Xe,...it}=de.growth;return nh({scope:{projectId:t.projectId,environment:t.environment},funnelId:Y,versionId:de.versionId,evaluationMode:"local",evaluationRevision:de.control.evaluationRevision,document:de.document,payload:it})},assertFunnel(Y,J,de){ht();let pe=c.funnels[Y];if(!pe||pe.state!=="active")throw Pe("FUNNEL_STOPPED","Funnel is paused or unavailable");if(pe.evaluationMode!=="local")throw Pe("EVALUATION_MODE","This Funnel now executes at Longplay");if(J!==void 0&&pe.controlRevision!==J)throw Pe("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(de!==void 0&&!pe.versions[de])throw Pe("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!f){f=!0,g++,u=0,R?.abort(Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(y),clearTimeout(A),Al(),he(),v.clear();for(let Y of P)Y.abort(Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));j.clear(),X=0}}}}async function Nv(e){e={...e};let t=e.configuration;if(!t)throw new b("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let n={projectId:t.scope.projectId,environment:t.scope.environment};if(e.scope&&Pt(n)!==Pt(e.scope))throw new b("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await t.funnel(e.funnelId)).control.evaluationMode!=="local")throw new b("EVALUATION_MODE","This Funnel uses Remote evaluation");let i=Di.test(e.credential);if(i?!e.customerId:e.customerId!==void 0)throw new b("INVALID_REQUEST","Only Server-Key starts name their Customer");let a=bs({...e,scope:n,apiKey:e.credential}),o=s=>{let c=hr({...e,scope:n,runToken:s,...i?{serverKey:e.credential}:{}});return i||c.identify(e.credential),c};return{async start(s){let c=await a.start({...s,funnelId:e.funnelId,...i?{customer:{type:"id",value:e.customerId}}:{}}),u=o(c.runToken),l=await u.get();return{...c,...l,controller:u}},async restore(s){let c=o(s),u=await c.get();if(u.run.source.id!==e.funnelId)throw c.reset(),new b("SCOPE_MISMATCH","Run belongs to another Funnel");return{...u,runToken:s,controller:c}}}}function fl(e,...t){try{Promise.resolve(e?.(...t)).catch(()=>{})}catch{}}function Dv(e){if(!e.scope)throw new b("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(e.session!==void 0)throw new b("INVALID_CONFIGURATION","The merchant process adapter owns the session");let t=null,n,r=0,i=new Set,a=new Map,o=new Map;async function s(f){let g,d=new Promise((h,R)=>{g=setTimeout(()=>R(new b("TIMEOUT","Process bridge request timed out")),e.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(f),d])}finally{clearTimeout(g)}}function c(f){throw f instanceof b&&(f.status===401||f.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear()),f}function u(f,g){if(g!==r)throw new b("IDENTITY_CHANGED","Process was detached during a request");let d=Bu.parse(f);if(d.scope.projectId!==e.scope.projectId||d.scope.environment!==e.scope.environment)throw new b("SCOPE_MISMATCH","Process response belongs to another App/environment");if(t&&(t.run.id!==d.run.id||t.run.source.versionId!==d.run.source.versionId||t.run.source.id!==d.run.source.id||t.run.runExpiresAt!==d.run.runExpiresAt||t.run.identity.startedAs!==d.run.identity.startedAs||t.run.identity.participantId!==d.run.identity.participantId||t.run.identity.binding&&d.run.identity.binding&&t.run.identity.binding.id!==d.run.identity.binding.id))throw new b("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!t||d.run.revision>=t.run.revision){if(t?.run.identity.binding&&!d.run.identity.binding)throw new b("INVALID_RESPONSE","The process lost its Customer binding");t=d;for(let j of i)fl(j,d.run);d.run.instruction?.type==="authentication_required"&&fl(e.onAuthenticationRequired,d.run)}d.settlement?.accepted!==void 0&&o.set(d.settlement.requestId,d.settlement.accepted);let{identity:h,instruction:R,...y}=d.run,{contract:A,settlement:x,...v}=d,P=x&&(({accepted:j,..._})=>_)(x);return{...v,run:{...y,authenticated:h.binding!==null,instruction:R?.type==="authentication_required"?null:R},...P?{settlement:P}:{}}}let l=f=>(a.has(f)||a.set(f,t?.run.identity.binding?.id??null),a.get(f));async function m(f){let g=r,d=t?.run.identity.binding?.id??null,h=y=>{if(d!==(t?.run.identity.binding?.id??null))throw y;return c(y)};if(f.operation==="page_experiments"){if(!e.adapter.pageExperiments)throw new b("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return s(()=>e.adapter.pageExperiments(f.release,f.usedReceiptIds)).catch(h)}let R;if(f.operation==="get"){let{operation:y,customerToken:A,...x}=f;R=await s(()=>e.adapter.get({...x,...x.settlementRequestId?{settlementBindingId:l(x.settlementRequestId)}:{}})).catch(h)}else if(f.operation==="review")R=await s(()=>e.adapter.review(f.receiptId)).catch(h);else{if(f.operation==="start")throw new b("INVALID_REQUEST","Use process.open for entry");{let{customerToken:y,...A}=f;R=await s(()=>e.adapter.command(A,l(A.requestId))).catch(h)}}return u(R,g)}return{get view(){return t?.run??null},get controller(){return n},async open(f){let g=r,d=await s(()=>e.adapter.open(f)).catch(c);if(u(d,g),!n){n=hr({...e,runToken:d.runToken,process:{request:m,binding:l,restore(y){for(let[A,x]of Object.entries(y))a.set(A,x)}}});let h=n,R=h.submit;h.submit=async y=>{try{return await R(y)}catch(A){if(!(A instanceof b)||A.reason!=="IDENTITY_CONTEXT_CHANGED"||y.operation!=="submit"||y.input.type!=="screen"||a.get(y.requestId)!==null)throw A;await h.settle?.(y.requestId),await h.get();let x=h.view;if(o.get(y.requestId)!==!1||!x||x.id!==t?.run.id||x.nodeId!==y.nodeId||x.visit!==y.visit||!t?.run.identity.binding)throw A;return R({...y,requestId:crypto.randomUUID(),revision:x.revision})}}}await n.get();for(let h of n.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(t?.run.identity.binding?.id??null)&&await n.settle?.(h.requestId);return{run:t.run,controller:n}},async syncIdentity(){let f=r;u(await s(()=>e.adapter.syncIdentity()).catch(c),f),await n?.get();for(let g of n?.pendingCommands??[])a.has(g.requestId)&&a.get(g.requestId)!==(t?.run.identity.binding?.id??null)&&await n?.settle?.(g.requestId);return t.run},async detach(){r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear(),await s(()=>e.adapter.detach())},forProcess(f){if(!t?.run.identity.binding)throw new b("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:t.run.id,bindingId:t.run.identity.binding.id,receiptId:f}},subscribe(f){return i.add(f),()=>{i.delete(f)}},destroy(){r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear(),i.clear()}}}export{b as LongplayError,Tv as createConfigurationSync,dl as createFeatureClient,Dv as createFunnelProcess,Nv as createLocalFunnelClient,_v as createLongplayReactNative};
17
+ */var ve=N.json().superRefine((e,t)=>{let n=0;function r(i,a){if(++n>1e4||a>20){t.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof i=="string"&&(i.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(i))&&t.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(i))i.forEach(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))(o.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(o)||["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved JSON property"}),r(s,a+1)}r(e,0),new TextEncoder().encode(JSON.stringify(e)).byteLength>65536&&t.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),wt=N.record(N.string().min(1).max(128),ve).superRefine((e,t)=>{(!ve.safeParse(e).success||Object.keys(e).length>128||new TextEncoder().encode(JSON.stringify(e)).byteLength>65536||["__proto__","constructor","prototype"].some(n=>Object.hasOwn(e,n)))&&t.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),OA=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),Yt=wt.superRefine((e,t)=>{function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,a]of Object.entries(r)){if(i==="$savedGroup"&&!N.strictObject({id:N.uuid(),attributeKey:N.string().min(1).max(128).optional()}).safeParse(a).success&&t.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!i.startsWith("$")&&i.split(".").some(o=>["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved attribute path"}),i.startsWith("$")&&!OA.has(i)&&t.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${i}`}),["$regex","$regexi"].includes(i)&&typeof a=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(a)||[...a.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(o=>Number(o[1])>255||Number(o[2]||0)>255)||i==="$regexi"&&/[^\x00-\x7f]/.test(a.replace(/\\u([0-9a-f]{4})/gi,(o,s)=>String.fromCharCode(Number.parseInt(s,16)))))&&t.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(a)}catch{t.addIssue({code:"custom",message:"Invalid regular expression"})}}n(a)}}typeof e.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(e.source)&&("operator"in e||"predicates"in e||"groupId"in e)&&t.addIssue({code:"custom",message:"Obsolete condition protocol"}),n(e)}),PA=N.discriminatedUnion("type",[N.strictObject({type:N.literal("condition"),condition:Yt}),N.strictObject({type:N.literal("list"),attributeKey:N.string().min(1).max(128),values:N.array(N.union([N.string(),N.number().finite()])).max(1e5)})]).refine(e=>e.type!=="list"||new TextEncoder().encode(JSON.stringify(e.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function Hn(e){let t=new Set;function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,a]of Object.entries(r))i==="$savedGroup"&&a&&typeof a=="object"&&!Array.isArray(a)&&typeof a.id=="string"?t.add(a.id):["$inGroup","$notInGroup"].includes(i)&&typeof a=="string"?t.add(a):["$eq","$ne","$in","$nin","$ini","$nini"].includes(i)||n(a)}return n(e),[...t]}var CA=N.record(N.uuid(),PA).superRefine((e,t)=>{let n=new Set,r=new Set;function i(a){if(n.has(a)){t.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(r.has(a))return;let o=e[a];if(!o){t.addIssue({code:"custom",message:"Missing saved group dependency"});return}n.add(a),o.type==="condition"&&Hn(o.condition).forEach(i),n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),oc=N.tuple([N.number().min(0).max(1),N.number().min(0).max(1)]).refine(([e,t])=>e<=t),qd=N.strictObject({attribute:N.string().optional(),seed:N.string().min(1),hashVersion:N.literal(2),ranges:N.array(oc).min(1).max(100)}),_A=N.strictObject({id:N.string().min(1).max(128),condition:Yt,gate:N.boolean().optional()}),ic={id:N.string().max(128).optional(),condition:Yt.optional(),parentConditions:N.array(_A).max(50).optional(),filters:N.array(qd).max(20).optional()},EA=N.union([N.strictObject({...ic}),N.strictObject({...ic,force:ve,coverage:N.number().min(0).max(1).optional(),range:oc.optional(),seed:N.string().min(1).optional(),hashAttribute:N.string().optional(),hashVersion:N.literal(2).optional()}),N.strictObject({...ic,type:N.literal("experiment-ref"),experimentId:N.uuid(),values:N.record(N.string().min(1),ve),meta:N.record(N.string().min(1),N.strictObject({passthrough:N.boolean()})).optional()})]),RA=N.strictObject({defaultValue:ve,rules:N.array(EA).max(100)}),bO=N.record(N.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),RA).superRefine((e,t)=>{Object.keys(e).length>100&&t.addIssue({code:"custom",message:"Too many Features"});let n=new Set,r=new Set;function i(a){if(n.has(a)){t.addIssue({code:"custom",message:`Cyclic Feature dependency: ${a}`});return}if(r.has(a))return;let o=e[a];if(!o){t.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${a}`});return}n.add(a);for(let s of o.rules)for(let c of s.parentConditions??[])i(c.id);n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),kA=N.strictObject({name:N.string().max(80),reason:N.string().max(500),dateStarted:N.iso.datetime({offset:!0}),dateEnded:N.iso.datetime({offset:!0}).nullable(),coverage:N.number().min(0).max(1),variationWeights:N.array(N.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:Yt,savedGroups:N.array(N.strictObject({match:N.enum(["any","all","none"]),ids:N.array(N.uuid()).min(1)})).max(50),namespace:N.strictObject({id:N.uuid(),ranges:N.array(oc).min(1)}).nullable(),seed:N.string().min(1).max(128)}),jA=N.strictObject({key:N.string().min(1).max(128),name:N.string().min(1).max(80),hypothesis:N.string().max(2e3),status:N.enum(["draft","running","stopped"]),hashAttribute:N.string().min(1).max(128),fallbackAttribute:N.string().max(128).nullable(),hashVersion:N.literal(2),disableStickyBucketing:N.boolean(),bucketVersion:N.number().int().min(0).max(1e3),minBucketVersion:N.number().int().min(0).max(1e3),variations:N.array(N.strictObject({id:N.string().min(1),key:N.string().min(1),name:N.string().max(80),description:N.string().max(500)})).min(2).max(20),phases:N.array(kA).min(1).max(100),releasedVariationId:N.string().nullable(),excludeFromPayload:N.boolean(),statusSchedule:N.strictObject({startAt:N.iso.datetime({offset:!0}).nullable(),stopAt:N.iso.datetime({offset:!0}).nullable(),stopAfter:N.strictObject({value:N.number().int().positive().max(36500),unit:N.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((e,t)=>{(e.minBucketVersion>e.bucketVersion||e.statusSchedule?.stopAt&&e.statusSchedule?.stopAfter||e.phases.some((n,r)=>{if(r===0)return!1;let i=e.phases[r-1];return!i?.dateEnded||Date.parse(n.dateStarted)<Date.parse(i.dateStarted)||Date.parse(i.dateEnded)>Date.parse(n.dateStarted)})||new Set(e.variations.map(n=>n.key)).size!==e.variations.length||new Set(e.variations.map(n=>n.id)).size!==e.variations.length||e.releasedVariationId!==null&&!e.variations.some(n=>n.id===e.releasedVariationId)||e.statusSchedule?.startAt&&e.statusSchedule?.stopAt&&Date.parse(e.statusSchedule.startAt)>=Date.parse(e.statusSchedule.stopAt)||e.phases.some(n=>n.dateEnded&&Date.parse(n.dateStarted)>=Date.parse(n.dateEnded)||n.namespace?.ranges.some(([r,i],a,o)=>r>=i||o.some(([s,c],u)=>u!==a&&r<c&&s<i)))||e.phases.some(n=>n.variationWeights.length!==e.variations.length))&&t.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});var TA=jA.safeExtend({filters:N.array(qd).optional()}),NA=N.strictObject({experiments:N.record(N.uuid(),TA),savedGroups:CA}),$i=N.strictObject({attributeName:N.string(),attributeValue:N.string(),assignments:N.record(N.string(),N.string())}),xO=N.strictObject({snapshot:NA,attributes:wt,results:wt,stickyBucketAssignmentDocs:N.record(N.string(),$i)}),SO=N.strictObject({variantKey:N.string().nullable(),bucketVersion:N.number().int().min(0),source:N.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:N.number().min(0).max(1).optional(),stickyBucketUsed:N.boolean().optional(),hashUsed:N.boolean().optional()});function tr(e){let t=new Set,n=a=>a!==null&&typeof a=="object"&&!Array.isArray(a);function r(a,o){if(n(a))for(let[s,c]of Object.entries(a))s==="$elemMatch"?i(c,o):s==="$not"?r(c,o):s==="$all"&&Array.isArray(c)&&c.forEach(u=>r(u,o))}function i(a,o=""){if(n(a)){for(let[s,c]of Object.entries(a))if(["$and","$or","$nor"].includes(s)&&Array.isArray(c))c.forEach(u=>i(u,o));else if(s==="$not")i(c,o);else if(s==="$savedGroup"&&n(c))typeof c.attributeKey=="string"&&t.add(c.attributeKey);else if(!s.startsWith("$")){let u=o?`${o}.${s}`:s;t.add(u),r(c,u)}}}return i(e),[...t]}var DA=Tt.enum(["active","inactive"]),FA=Tt.preprocess((e,t)=>{let n=0;function r(i,a){if(!(++n>1e4||a>20)){if(Array.isArray(i))i.forEach(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))["__proto__","constructor","prototype"].includes(o)&&t.addIssue({code:"custom",message:"Reserved merchandise attribute"}),r(s,a+1)}}return r(e,0),e},wt),MA=Tt.strictObject({id:Tt.string().trim().min(1).max(255),name:Tt.string().trim().min(1).max(255),status:DA,metadata:FA}),CO=MA.extend({internal_id:Tt.uuid(),project_id:Tt.uuid(),environment_id:Tt.uuid(),created_at:Tt.iso.datetime({offset:!0}),updated_at:Tt.iso.datetime({offset:!0})}),Bd=Tt.union([Tt.strictObject({id:Tt.string().trim().min(1).max(255)}),Tt.strictObject({internalId:Tt.uuid()})]),_O=Tt.enum(["customer","merchandise","context"]),EO=Tt.enum(["system","stored","request"]),RO=Tt.enum(["customer","merchandise","mixed"]),Ud=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function ac(e,t={},n=new Set){if(tr(e).some(Ud))return!0;for(let r of Hn(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&Ud(i.attributeKey)||i?.type==="condition"&&ac(i.condition,t,n))return!0}return!1}import{z as qA}from"zod";var UA=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,In=qA.string().max(16).regex(UA,"\u8BED\u8A00\u4EE3\u7801\u683C\u5F0F\u4E0D\u6B63\u786E\uFF0C\u4F8B\u5982 zh-CN\u3001en").refine(e=>{try{return Intl.getCanonicalLocales(e)[0]===e}catch{return!1}},"\u6301\u4E45\u5316\u8BED\u8A00\u4EE3\u7801\u5FC5\u987B\u4F7F\u7528\u89C4\u8303\u5199\u6CD5");var qO=te.enum(["draft","active","paused","archived"]),nr=te.discriminatedUnion("type",[te.object({type:te.literal("percent"),percentOff:te.number().min(1).max(100).multipleOf(.01)}).strict(),te.object({type:te.literal("amount"),amountOffCents:te.number().int().min(1).max(1e8),currency:Ie}).strict()]),sn=te.discriminatedUnion("type",[te.object({type:te.literal("once")}).strict(),te.object({type:te.literal("repeating"),months:te.number().int().min(1).max(36)}).strict(),te.object({type:te.literal("forever")}).strict()]),Vd=[te.object({type:te.literal("all")}).strict(),te.object({type:te.literal("plans"),planIds:te.array(te.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],BA=te.discriminatedUnion("type",[...Vd,te.strictObject({type:te.literal("merchandise"),scope:te.discriminatedUnion("type",[te.strictObject({type:te.literal("all")}),te.strictObject({type:te.literal("selected"),merchandiseIds:te.array(te.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),te.strictObject({type:te.literal("condition"),condition:Yt})])})]),sc=te.discriminatedUnion("type",[...Vd,te.strictObject({type:te.literal("merchandise"),scope:te.strictObject({type:te.enum(["all","selected","condition"])})})]),VA=te.strictObject({firstPurchaseOnly:te.boolean(),condition:Yt}),UO=te.object({name:te.string().trim().min(1).max(80),description:te.string().max(500),discount:nr,duration:sn,appliesTo:BA,eligibility:VA,selfClaimEnabled:te.boolean().default(!1),startsAt:te.iso.datetime().nullable(),endsAt:te.iso.datetime().nullable(),totalLimit:te.number().int().min(1).max(1e6).nullable(),perCustomerLimit:te.number().int().min(1).max(10),grantWindowHours:te.number().int().min(1).max(2160)}).strict().refine(e=>!e.startsAt||!e.endsAt||Date.parse(e.endsAt)>Date.parse(e.startsAt),{message:"\u7ED3\u675F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u5F00\u59CB\u65F6\u95F4",path:["endsAt"]}).refine(e=>!ac(e.eligibility.condition),{message:"Customer eligibility cannot read merchandise; use merchandise applicability",path:["eligibility","condition"]}).refine(e=>e.appliesTo.type!=="merchandise"||e.duration.type==="once",{message:"Merchandise Coupons apply to one purchase",path:["duration"]}).refine(e=>e.appliesTo.type!=="merchandise"||!e.eligibility.firstPurchaseOnly,{message:"Merchant purchase eligibility requires trusted targeting attributes",path:["eligibility","firstPurchaseOnly"]}),BO=te.object({code:te.string().trim().transform(e=>e.toUpperCase()).pipe(te.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/,"\u4F18\u60E0\u7801\u53EA\u80FD\u7528 3\u201332 \u4F4D\u5B57\u6BCD\u3001\u6570\u5B57\u3001- \u548C _\uFF0C\u4EE5\u5B57\u6BCD\u6216\u6570\u5B57\u5F00\u5934")),maxRedemptions:te.number().int().min(1).max(1e6).nullable(),expiresAt:te.iso.datetime().nullable(),firstPurchaseOnly:te.boolean(),minimumAmountCents:te.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:Ie.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var Gi=te.object({id:te.uuid(),couponId:te.uuid(),status:te.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:te.iso.datetime(),expiresAt:te.iso.datetime(),coupon:te.object({name:te.string(),discount:nr,duration:sn,appliesTo:sc}).strict()}).strict(),Ld=te.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var Hd=S.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),cc=S.string().regex(/^(0|[1-9]\d{0,14})$/),oi=S.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),LA=S.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),Ki=LA,Qn=xe.refine(e=>/[1-9]/.test(e)),zt=S.iso.datetime({offset:!0}),ua=e=>{let[t,n=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");return BigInt(t)*1000000n+BigInt(n.padEnd(6,"0"))},zA=S.array(S.object({upTo:Qn.nullable(),unitAmountMinor:Hd,flatAmountMinor:S.number().int().min(0).max(1e8).optional()}).strict()).min(1).max(12).refine(e=>{try{return e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let r=e[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&ua(t.upTo)>ua(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),$A=S.discriminatedUnion("kind",[S.object({kind:S.literal("flat"),units:Qn,unitAmountMinor:Hd}).strict(),S.object({kind:S.enum(["graduated","volume"]),units:Qn,tiers:zA}).strict()]).refine(e=>e.kind==="flat"||!e.tiers.some(t=>(t.flatAmountMinor??0)>0)||e.kind==="volume"&&e.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers"),GA=S.strictObject({interval:S.enum(["month","year"]),count:S.number().int().min(1).max(12),anchor:S.enum(["membership","calendar"])}),Hi=S.object({currency:Ie,pricing:$A,billingCycle:GA.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var zd={requestId:S.uuid(),productVersionId:S.uuid(),internal_feature_id:S.uuid(),currency:Ie},Qd=S.strictObject({interval:S.enum(["hour","day","week","month"]),intervalCount:S.number().int().min(1).max(12),limit:S.number().int().min(1).max(1e6)}),Jd=S.discriminatedUnion("kind",[S.object({...zd,kind:S.literal("auto_topup"),threshold:Zo,quantity:Qn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Qd.optional()}).strict(),S.object({...zd,kind:S.literal("postpaid"),maxAmountMinorPerPeriod:Ki,maxOutstandingMinor:Ki}).strict()]),$d={productVersionId:S.uuid(),internal_feature_id:S.uuid(),currency:Ie},Zd=S.discriminatedUnion("kind",[S.object({...$d,kind:S.literal("auto_topup"),threshold:Zo,quantity:Qn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Qd.optional(),purchaseAmountMinor:Ki,purchaseUnits:Qn}).strict(),S.object({...$d,kind:S.literal("postpaid"),maxAmountMinorPerPeriod:Ki,maxOutstandingMinor:Ki,cashPrice:Hi}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),la=S.object({id:S.uuid(),terms:Zd,status:S.enum(["prepared","active","revoked","blocked"]),createdAt:zt,acceptedAt:zt.nullable(),effectiveAt:zt.nullable(),revokedAt:zt.nullable()}).strict().refine(e=>(e.status==="prepared"?e.acceptedAt===null:!0)&&(e.status==="active"?e.acceptedAt!==null&&e.effectiveAt!==null:!0)&&(e.status==="revoked"?e.revokedAt!==null:e.revokedAt===null),"Authorization consent and revocation must be explicit"),Wd=S.object({authorizationId:S.uuid(),terms:Zd,setupUrl:S.url().nullable()}).strict(),Yd=S.object({authorizationId:S.uuid(),accepted:S.literal(!0)}).strict(),Xd=S.object({authorizationId:S.uuid(),requestId:S.uuid()}).strict(),ep=S.object({internal_feature_id:S.uuid(),entityId:S.uuid().nullable(),interval:S.enum(["day","week","month","year"]),anchor:S.enum(["billing_cycle","utc"]).optional(),basis:S.enum(["usage","credits"]),filter:vt.optional(),limit:xe.nullable(),thresholds:S.array(S.number().positive().max(1)).max(8),includedThresholds:S.array(S.number().positive().max(1)).max(8).optional(),absoluteThresholds:S.array(Qn).max(8).optional()}).strict().refine(e=>e.thresholds.every((t,n)=>{let r=e.thresholds[n-1];return n===0||r!==void 0&&t>r})&&(e.includedThresholds??[]).every((t,n,r)=>{let i=r[n-1];return n===0||i!==void 0&&t>i})&&(e.absoluteThresholds??[]).every((t,n,r)=>{let i=r[n-1];return n===0||i!==void 0&&ua(t)>ua(i)}),"Notification thresholds must increase"),KA=ep.safeExtend({requestId:S.uuid()}),Gd={control:S.literal("overage"),requestId:S.uuid(),internal_feature_id:S.uuid(),entityId:S.uuid().nullable()},HA=S.discriminatedUnion("action",[S.strictObject({...Gd,action:S.literal("set"),allowed:S.boolean().nullable(),overageLimit:xe.nullable(),skipOverageBilling:S.boolean()}),S.strictObject({...Gd,action:S.literal("remove")})]),tp=S.union([KA,HA]),QA=S.strictObject({internal_feature_id:S.uuid(),entityId:S.uuid().nullable(),allowed:S.boolean().nullable(),overageLimit:xe.nullable(),skipOverageBilling:S.boolean(),interval:S.enum(["day","week","month","year"]),startsAt:zt,endsAt:zt,used:S.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:S.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:S.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),JA=S.object({internal_feature_id:S.uuid(),entityId:S.uuid().nullable(),interval:S.enum(["day","week","month","year"]),anchor:S.enum(["billing_cycle","utc"]).optional(),basis:S.enum(["usage","credits"]),filter:vt.optional(),startsAt:zt,endsAt:zt,used:Wt,reserved:Wt,limit:xe.nullable(),thresholds:S.array(S.number().positive().max(1)).max(8),notifiedThresholds:S.array(S.number().positive().max(1)).max(1024),includedThresholds:S.array(S.number().positive().max(1)).max(8).optional(),includedAllowance:S.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:S.array(S.number().positive().max(1)).max(1024).optional(),absoluteThresholds:S.array(Qn).max(8).optional(),notifiedAbsoluteThresholds:S.array(Qn).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||xe.safeParse(e.used).success&&xe.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),ZA=S.object({authorizationId:S.uuid(),status:S.enum(["idle","pending","blocked"]),taskId:S.uuid().nullable(),invoiceId:S.uuid().nullable(),hostedInvoiceUrl:S.url().nullable(),purchaseCount:S.number().int().nonnegative(),purchaseWindowEndsAt:zt.nullable(),attemptCount:S.number().int().nonnegative(),failedAttemptCount:S.number().int().nonnegative(),suspendedAt:zt.nullable(),nextAttemptAt:zt.nullable(),failureReason:S.string().min(1).max(240).nullable()}).strict(),np=S.object({internal_feature_id:S.uuid().optional(),entityId:S.uuid().optional()}).strict(),uc=S.object({authorizations:S.array(la).max(100),limits:S.array(ep).max(100),overages:S.array(QA).max(100).optional(),windows:S.array(JA).max(200),autoTopups:S.array(ZA).max(100),limited:S.boolean()}).strict(),WA=S.object({id:S.uuid(),internal_feature_id:S.uuid(),productVersionId:S.uuid(),authorizationId:S.uuid(),entityId:S.uuid().nullable(),units:xe,amountMinor:oi,cashPrice:Hi}).strict(),Qi=S.object({id:S.uuid(),sourceKind:S.enum(["product","usage","manual"]),providerInvoiceId:S.string().min(1).max(240).nullable(),status:S.enum(["accruing","open","pending","paid","failed","void"]),currency:Ie,startsAt:zt.nullable(),endsAt:zt.nullable(),amountMinor:S.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:S.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:cc,paidAmountMinor:cc,refundedAmountMinor:cc,createdAt:zt,hostedInvoiceUrl:S.url().nullable(),adjustment:S.object({originalInvoiceId:S.uuid(),amountMinor:S.string().regex(/^-?(0|[1-9]\d{0,8})$/).refine(e=>e!=="-0"&&/^-?(0|[1-9]\d{0,8})$/.test(e)&&BigInt(e)>=-200000000n&&BigInt(e)<=200000000n,"Invoice adjustment exceeds the bounded minor amount"),acceptedAt:zt.nullable(),reason:S.string().min(1).max(500).optional()}).strict().nullable(),lines:S.array(WA).max(100),linesLimited:S.boolean()}).strict(),rp=S.object({invoiceId:S.uuid(),accepted:S.literal(!0)}).strict(),ip=S.strictObject({requestId:S.uuid(),originalInvoiceId:S.uuid(),amountMinor:S.string().regex(/^[1-9]\d{0,8}$/).refine(e=>/^[1-9]\d{0,8}$/.test(e)&&BigInt(e)<=200000000n,"Supplemental amount exceeds the bounded minor amount"),reason:S.string().trim().min(1).max(500)}),op=S.object({after:S.uuid().nullable(),limit:S.number().int().min(1).max(100)}).strict(),ap=S.object({rows:S.array(Qi).max(100),nextCursor:S.uuid().nullable()}).strict(),Kd=S.strictObject({id:S.string(),coupon:S.string(),start:S.number().nonnegative(),end:S.number().nullable()}),YA=S.strictObject({subscriptionId:S.string(),customerId:S.string(),accountId:S.string(),sourceItems:S.array(S.strictObject({id:S.string(),price_id:S.string(),quantity:S.number().int(),discounts:S.array(Kd).optional()})).max(100),items:S.array(S.strictObject({id:S.string(),price:S.string(),quantity:S.number().int(),discounts:S.array(S.strictObject({coupon:S.string().optional(),terms:S.strictObject({id:S.string(),name:S.string().optional(),percent_off:S.number().optional(),amount_off:S.number().optional(),currency:S.string().optional(),duration:S.enum(["once","forever","repeating"]),duration_in_months:S.number().optional()}).optional(),discount:S.string().optional(),receipt:Kd.optional()})).max(20)})).max(100)}),sp=S.strictObject({membershipId:S.uuid(),requestId:S.uuid(),grantIds:S.array(S.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),cp=S.strictObject({membershipId:S.uuid(),operationId:S.uuid(),status:S.enum(["pending","effective"]),execution:YA.nullable(),grants:S.array(S.strictObject({id:S.uuid(),couponId:S.uuid(),name:S.string(),discount:nr,duration:sn,startedAt:zt.nullable()})).max(20)});import{z as Ji}from"zod";var up=Ji.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),lp=Ji.number().int().min(1).max(1e3),da=Ji.object({cap:xe.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:Ji.number().positive().max(1e4).nullable(),cycles:Ji.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");import{z as rr}from"zod";var dp=rr.strictObject({itemKey:rr.string().regex(/^paid:feature:[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),internal_feature_id:rr.uuid(),includedAmount:rr.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:rr.number().int().min(0).max(1e4),terms:Yo,pricing:Vi.optional(),unitAmountMinor:rr.number().int().min(0).max(1e8),productId:rr.string().min(1).max(255).nullable(),priceId:rr.string().min(1).max(255).nullable()}).superRefine((e,t)=>{(e.quantity<e.terms.minimumQuantity||e.quantity>e.terms.maximumQuantity||e.productId===null!=(e.priceId===null)||e.quantity>0&&(e.pricing||e.unitAmountMinor>0)&&e.priceId===null)&&t.addIssue({code:"custom",message:"Purchased quantities need their published bounds and immutable price binding"});try{rd(e.includedAmount,e.terms.units,e.quantity),Wo({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{t.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});import{z as ne}from"zod";var Cr=xe.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Zi=ne.string().min(1).max(120),pa=ne.enum(["cap","overflow"]),cn=(e,t)=>{let[n,r=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");return BigInt(n)*10n**BigInt(t)+BigInt(r.padEnd(t,"0"))},Wi=e=>{try{return e()}catch{return!1}},Yi=ne.discriminatedUnion("operation",[ne.object({operation:ne.literal("quote"),overageBehavior:pa.optional(),internal_feature_id:ne.uuid(),entityId:ne.uuid().optional(),quantity:Cr,properties:vt}).strict(),ne.object({operation:ne.literal("consume"),overageBehavior:pa.optional(),occurredAt:ne.iso.datetime({offset:!0}).optional(),internal_feature_id:ne.uuid(),entityId:ne.uuid().optional(),quantity:xe,properties:vt,idempotencyKey:Zi}).strict(),ne.object({operation:ne.literal("reserve"),occurredAt:ne.iso.datetime({offset:!0}).optional(),internal_feature_id:ne.uuid(),entityId:ne.uuid().optional(),quantity:Cr,properties:vt,idempotencyKey:Zi,expiresInSeconds:ne.number().int().min(1).max(86400)}).strict(),ne.object({operation:ne.literal("confirm"),operationId:ne.uuid(),quantity:Cr,properties:vt.optional(),idempotencyKey:Zi}).strict(),ne.object({operation:ne.literal("refund"),operationId:ne.uuid(),quantity:Cr,idempotencyKey:Zi}).strict(),ne.object({operation:ne.literal("release"),operationId:ne.uuid(),idempotencyKey:Zi}).strict()]),lc=ne.object({internal_credit_feature_id:ne.uuid().nullable(),internal_metered_feature_id:ne.uuid(),dimension:ne.string().min(1).max(64),counterKey:ne.string().min(1).max(240),cycleStart:ne.iso.datetime({offset:!0}),unitCost:xe,units:Cr,amount:Wt,tier:ne.number().int().min(1).max(12).nullable()}).strict(),_r=ne.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function pp(e,t){let n=e.reduce((r,i)=>r+cn(i.units,12),0n)-cn(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var mp=ne.discriminatedUnion("funding",[ne.strictObject({funding:ne.literal("balance"),sourceId:ne.uuid(),rolloverId:ne.uuid().nullable(),units:_r.refine(e=>/[1-9]/.test(e)),amount:Wt}),ne.strictObject({funding:ne.literal("unbilled"),units:_r.refine(e=>/[1-9]/.test(e))}),ne.object({funding:ne.literal("prepaid"),sourceId:ne.uuid(),units:Cr,amount:Wt,pricing:ne.array(lc).min(1).max(12)}).strict().refine(e=>Wi(()=>e.pricing.reduce((t,n)=>t+cn(n.units,6),0n)===cn(e.units,6)&&e.pricing.reduce((t,n)=>t+cn(n.amount,12),0n)===cn(e.amount,12)&&e.pricing.every(t=>cn(t.unitCost,6)*cn(t.units,6)===cn(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),ne.object({funding:ne.literal("postpaid"),invoiceLineId:ne.uuid().nullable(),units:Cr,authorizationId:ne.uuid()}).strict()]),ma=ne.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),fp=ne.object({allowed:ne.boolean(),internal_feature_id:ne.uuid(),quantity:xe,requestedQuantity:xe.optional(),overageBehavior:pa.optional(),reason:ma.nullable(),allocations:ne.array(mp).max(500)}).strict().refine(e=>Wi(()=>e.allowed?e.reason===null&&pp(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>Wi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&cn(e.requestedQuantity,6)>=cn(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Xi=ne.object({id:ne.uuid(),internal_feature_id:ne.uuid(),kind:ne.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:ne.uuid().nullable(),quantity:xe,requestedQuantity:xe.optional(),overageBehavior:pa.optional(),accepted:ne.boolean(),reason:ne.enum([...ma.options,"expired"]).nullable(),createdAt:ne.iso.datetime({offset:!0}),reservationStatus:ne.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:ne.iso.datetime({offset:!0}).nullable(),allocations:ne.array(mp).max(500)}).strict().refine(e=>Wi(()=>e.accepted?e.reason===null&&pp(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>Wi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&cn(e.requestedQuantity,6)>=cn(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");import{z as De}from"zod";var Er=De.iso.datetime({offset:!0}),gp=xe.refine(e=>/[1-9]/.test(e)),hp=De.strictObject({interval:up.exclude(["lifetime"]),count:lp}),XA=De.strictObject({action:De.literal("create"),requestId:De.uuid(),internal_feature_id:De.uuid(),entityId:De.uuid().nullable(),amount:gp.nullable(),expiresAt:Er.nullable(),reset:hp.nullable(),rollover:da.nullable(),nextResetAt:Er.nullable()}).refine(e=>e.amount!==null||e.reset===null&&e.rollover===null,"Unlimited grants cannot reset or roll over").refine(e=>!e.rollover||e.reset!==null,"Rollover requires a recurring grant").refine(e=>e.nextResetAt===null||e.reset!==null&&(e.expiresAt===null||Date.parse(e.nextResetAt)<Date.parse(e.expiresAt)),"The first reset needs a reset interval and must precede expiry"),yp=De.discriminatedUnion("action",[XA,De.strictObject({action:De.literal("update"),requestId:De.uuid(),grantId:De.uuid(),revision:De.number().int().nonnegative(),amount:gp.nullable(),expiresAt:Er.nullable(),rollover:da.nullable(),nextResetAt:Er.nullable()}),De.strictObject({action:De.enum(["add","subtract","set_remaining"]),requestId:De.uuid(),grantId:De.uuid(),revision:De.number().int().nonnegative(),amount:xe}),De.strictObject({action:De.literal("revoke"),requestId:De.uuid(),grantId:De.uuid(),revision:De.number().int().nonnegative()})]),dc=De.strictObject({id:De.uuid(),internal_feature_id:De.uuid(),entityId:De.uuid().nullable(),amount:xe.nullable(),reset:hp.nullable(),rollover:da.nullable(),nextResetAt:Er.nullable(),startsAt:Er,expiresAt:Er.nullable(),revision:De.number().int().nonnegative(),revoked:De.boolean(),available:Wt,held:Wt,spent:Wt}),Ap=De.strictObject({customerId:De.uuid(),after:De.uuid().nullable(),limit:De.number().int().min(1).max(100)}),bp=De.strictObject({rows:De.array(dc).max(100),nextCursor:De.uuid().nullable()});import{z as ie}from"zod";var Dn=ie.iso.datetime({offset:!0}),xp=ie.strictObject({invoiceId:ie.uuid(),after:ie.string().min(1).max(180).nullable(),limit:ie.number().int().min(1).max(100)}),eb=ie.strictObject({kind:ie.literal("product"),key:ie.string(),productVersionId:ie.uuid(),productName:ie.string(),itemKey:ie.string(),entityId:ie.uuid().nullable(),quantity:ie.number().positive(),subtotalMinor:ie.string().regex(/^-?\d+$/),discountMinor:ie.string().regex(/^\d+$/),taxMinor:ie.string().regex(/^-?\d+$/).nullable(),totalMinor:ie.string().regex(/^-?\d+$/),startsAt:Dn.nullable(),endsAt:Dn.nullable(),providerLineId:ie.string().nullable(),providerItemId:ie.string()}),Sp=ie.strictObject({invoice:Qi,items:ie.array(ie.discriminatedUnion("kind",[eb,ie.strictObject({kind:ie.literal("invoice_credit"),key:ie.string(),internal_feature_id:ie.uuid(),internal_credit_feature_id:ie.uuid(),name:ie.string(),units:xe,reserved:xe,amountMinor:oi,grossAmountMinor:oi,creditsAppliedMinor:oi,properties:vt,cashPrice:Hi,providerItemId:ie.string().nullable(),creditProviderItemId:ie.string().nullable()}),ie.strictObject({kind:ie.literal("usage"),key:ie.string(),internal_feature_id:ie.uuid(),name:ie.string(),units:xe,reserved:xe,amountMinor:oi,cashPrice:Hi})])).max(100),nextCursor:ie.string().min(1).max(180).nullable()}),tb=ie.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),pc=ie.strictObject({from:Dn,to:Dn,entityId:ie.uuid().optional(),snapshotAt:Dn.nullable(),after:ie.strictObject({at:Dn,id:ie.uuid(),position:ie.number().int().nonnegative()}).nullable(),limit:ie.number().int().min(1).max(100)}).refine(e=>Date.parse(e.from)<Date.parse(e.to)&&Date.parse(e.to)-Date.parse(e.from)<=366*864e5,"Statement range must be positive and at most 366 days").refine(e=>e.after===null||e.snapshotAt!==null,"A cursor requires the original snapshot time"),Ip=ie.strictObject({customerId:ie.uuid(),entityId:ie.uuid().nullable(),from:Dn,to:Dn,snapshotAt:Dn,totals:ie.array(ie.strictObject({internal_credit_feature_id:ie.uuid(),name:ie.string(),consumed:Wt,refunded:Wt,net:tb})).max(1e3),rows:ie.array(ie.strictObject({operationId:ie.uuid(),position:ie.number().int().nonnegative(),kind:ie.enum(["consume","confirm","refund"]),originalId:ie.uuid().nullable(),occurredAt:Dn,internal_feature_id:ie.uuid(),entitlementName:ie.string(),sourceId:ie.uuid(),internal_credit_feature_id:ie.uuid(),creditName:ie.string(),units:_r,amount:Wt,pricing:ie.array(lc).max(12),properties:vt})).max(100),nextCursor:pc.shape.after});import{z as D}from"zod";import{z as vn}from"zod";var nb=vn.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),rb=vn.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),fa=vn.strictObject({internal_feature_id:vn.uuid(),entityId:vn.uuid().nullable()}),vp=fa.extend({quantity:xe,expectedRevision:vn.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:vn.string().min(1).max(120),properties:vt.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),eo=fa.extend({operationId:vn.uuid().nullable(),usage:xe,capacity:nb.nullable(),remaining:rb.nullable(),withinLimit:vn.boolean(),revision:vn.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:vn.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let n=r=>{let i=r.startsWith("-"),[a,o=""]=(i?r.slice(1):r).split(".");if(a===void 0||a==="")throw new Error("Invalid decimal value");return(i?-1n:1n)*(BigInt(a)*10n**12n+BigInt(o.padEnd(12,"0")))};(e.capacity===null!=(e.remaining===null)||(e.capacity===null?!e.withinLimit:e.remaining===null||n(e.remaining)!==n(e.capacity)-n(e.usage)||e.withinLimit!==n(e.remaining)>=0n)||e.revision===0!=(e.operationId===null)||e.operationId===null!=(e.updatedAt===null))&&t.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var $t=D.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),wn=D.iso.datetime({offset:!0}),ib=D.enum(["access","metered","credit"]),to={internal_feature_id:D.uuid(),key:Or,name:D.string().min(1).max(120),kind:ib},wp=D.object({customerId:D.uuid(),snapshotAt:wn,memberships:D.array(D.object({id:D.uuid(),productId:D.string().min(1).max(255),productVersionId:D.uuid(),billingProductVersionId:D.uuid(),version:D.number().int().positive(),key:D.string().min(1).max(64),name:D.string().min(1).max(120),groupId:D.string().max(255).nullable(),membershipType:D.enum(["main","addon"]),status:D.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:D.boolean(),accessEnabled:D.boolean(),renewalChange:D.object({productVersionId:D.uuid(),name:D.string().min(1).max(120),version:D.number().int().positive(),effectiveAt:wn,benefitsAppliedAt:wn.nullable(),timing:D.enum(["immediate","renewal"]),changeKind:D.enum(["plan","seats","quantity"]),feature:D.strictObject({internal_feature_id:D.uuid(),name:D.string().min(1).max(80),fromQuantity:D.number().int().min(0).max(1e4),toQuantity:D.number().int().min(0).max(1e4)}).optional(),seat:D.object({key:D.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:D.number().int().min(0).max(1e4),toQuantity:D.number().int().min(0).max(1e4)}).strict().nullable(),status:D.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(e=>e.changeKind==="seats"==(e.seat!==null)&&e.changeKind==="quantity"==(e.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:D.object({phase:D.enum(["paid","trial"]),startsAt:wn,endsAt:wn.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:D.boolean(),balances:D.array(D.object({...to,usageType:D.enum(["consumable","non_consumable"]).nullable(),accessible:D.boolean(),unlimited:D.boolean(),available:$t,held:$t,debt:$t,nextExpiresAt:wn.nullable(),usage:eo.nullable()}).strict().refine(e=>e.kind==="metered"==(e.usageType!==null)&&(e.accessible||e.available==="0"&&e.held==="0")&&(e.usageType==="non_consumable"?e.usage!==null&&e.usage.internal_feature_id===e.internal_feature_id&&e.unlimited===(e.usage.capacity===null)&&e.available===(e.usage.remaining===null||e.usage.remaining.startsWith("-")?"0":e.usage.remaining)&&e.held==="0"&&e.debt==="0":e.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:D.boolean()}).strict(),Op=D.enum(["source","usage","transaction","invoice","debt","settlement"]),ga=D.object({at:wn,id:D.uuid(),type:Op}).strict(),Pp=D.object({type:Op.nullable(),resourceKey:Or.optional(),kind:D.enum(["purchase","refund"]).optional(),topup:D.boolean().optional(),from:D.iso.date().nullable(),to:D.iso.date().nullable(),after:ga.nullable(),limit:D.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),ai={id:D.uuid(),occurredAt:wn},ob=D.discriminatedUnion("type",[D.strictObject({...ai,type:D.literal("invoice"),status:D.string().min(1).max(80),paid:$t,refunded:$t,currency:Ie,externalId:D.string().nullable()}),D.object({...ai,...to,type:D.literal("source"),reason:D.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:$t,unlimited:D.boolean(),status:D.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:wn,expiresAt:wn.nullable(),orderId:D.uuid().nullable(),parentSourceId:D.uuid().nullable()}).strict(),D.object({...ai,type:D.literal("usage"),internal_feature_id:D.uuid(),name:D.string().min(1).max(120),kind:D.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:D.uuid().nullable(),quantity:xe,accepted:D.boolean(),reason:D.enum([...ma.options,"expired"]).nullable(),properties:vt,reservationStatus:D.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:wn.nullable(),charges:D.array(D.discriminatedUnion("funding",[D.strictObject({funding:D.literal("balance"),sourceId:D.uuid(),rolloverId:D.uuid().nullable(),units:_r,amount:$t}),D.strictObject({funding:D.literal("unbilled"),units:_r}),D.object({...to,funding:D.literal("prepaid"),amount:$t}).strict(),D.object({funding:D.literal("postpaid"),invoiceId:D.uuid(),invoiceLineId:D.uuid(),authorizationId:D.uuid(),units:xe,currency:Ie}).strict()])).max(500)}).strict().refine(e=>(e.kind==="set_usage"||e.kind==="consume"&&e.quantity==="0"?e.accepted&&e.reason===null&&e.charges.length===0&&e.reservationStatus===null:e.accepted?e.reason===null&&e.charges.length>0:e.reason!==null&&e.charges.length===0)&&e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),D.object({...ai,type:D.literal("transaction"),purpose:D.enum(["product","invoice"]),productVersionId:D.uuid().nullable(),productName:D.string().min(1).max(120).nullable(),productVersion:D.number().int().positive().nullable(),invoiceId:D.uuid().nullable(),orderId:D.uuid(),originalId:D.uuid().nullable(),kind:D.enum(["purchase","refund"]),amountMinor:D.number().int().nonnegative().max(2e8).nullable(),currency:Ie.nullable()}).strict().refine(e=>e.currency===null==(e.amountMinor===null)&&(e.purpose==="product"?e.productVersionId!==null&&e.productName!==null&&e.productVersion!==null&&e.invoiceId===null:e.productVersionId===null&&e.productName===null&&e.productVersion===null&&e.invoiceId!==null)&&e.kind==="refund"==(e.originalId!==null)&&(e.kind!=="refund"||e.amountMinor===null||e.amountMinor>0),"Payment fact provenance is incomplete"),D.object({...ai,...to,type:D.literal("debt"),sourceId:D.uuid(),transactionId:D.uuid(),amount:$t}).strict(),D.object({...ai,...to,type:D.literal("settlement"),sourceId:D.uuid(),debtId:D.uuid(),kind:D.enum(["payment","usage_refund","payment_return"]),amount:$t}).strict()]),Cp=D.object({customerId:D.uuid(),rows:D.array(ob).max(50),nextCursor:ga.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");import{z as fe}from"zod";var Ep=fe.object({customerId:fe.uuid()}).strict(),Rp=fe.discriminatedUnion("action",[fe.object({customerId:fe.uuid(),requestId:fe.uuid(),action:fe.literal("assign"),poolId:fe.uuid(),memberCustomerId:fe.uuid()}).strict(),fe.strictObject({customerId:fe.uuid(),requestId:fe.uuid(),action:fe.literal("assign_entity"),poolId:fe.uuid(),entityId:fe.uuid()}),fe.object({customerId:fe.uuid(),requestId:fe.uuid(),action:fe.literal("release"),poolId:fe.uuid(),slotId:fe.uuid()}).strict()]),no=fe.number().int().nonnegative(),mc=fe.iso.datetime({offset:!0}),fc=fe.strictObject({internalId:fe.uuid(),id:fe.string(),name:fe.string().nullable(),version:fe.number().int().positive()}),_p=fe.enum(["active","past_due"]),gc=fe.strictObject({customerId:fe.uuid(),licenses:fe.array(fe.strictObject({id:fe.uuid(),linkId:fe.uuid(),parent:fe.strictObject({customerProductId:fe.uuid(),status:_p,product:fc}),product:fc,planLicense:fe.strictObject({id:fe.uuid(),prepaidOnly:fe.boolean(),isCustom:fe.boolean()}).nullable(),granted:no,included:no,paidQuantity:no,usage:no,remaining:no,createdAt:mc}).refine(e=>e.granted===e.included+e.paidQuantity&&e.granted===e.usage+e.remaining,"Granted seats are included plus paid, and usage plus remaining")).max(2e3),assignments:fe.array(fe.strictObject({id:fe.uuid(),linkId:fe.uuid(),status:_p,product:fc,entity:fe.strictObject({internalId:fe.uuid(),id:fe.string().nullable(),name:fe.string().nullable()}).nullable(),beneficiary:fe.strictObject({internalId:fe.uuid(),id:fe.string().nullable(),name:fe.string().nullable()}).nullable(),startedAt:mc.nullable(),endedAt:mc.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:fe.boolean()});import{z as me}from"zod";var ro=me.enum(["email","sms","voice","push"]),OP=me.enum(["resend","twilio","fcm","apns"]);var PP=me.string().regex(/^\+[1-9]\d{1,14}$/),ab=me.enum(["email_recipient","sms_segment","voice_second","push_device"]);var sb=me.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),cb=me.strictObject({subject:sb,html:me.string().min(1).max(131072).optional(),text:me.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),ub=me.strictObject({body:me.string().min(1).max(1600).refine(e=>e.trim().length>0)}),lb=me.strictObject({text:me.string().trim().min(1).max(4e3),language:me.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:me.number().int().min(1).max(900)}),db=me.record(me.string().min(1).max(64),me.string().max(256)).refine(e=>Object.keys(e).length<=20&&Object.keys(e).every(t=>!/^(?:indiana_|google\.|gcm\.)/i.test(t)&&t!=="aps"),"Push data contains reserved fields or too many entries"),pb=me.strictObject({title:me.string().trim().min(1).max(200),body:me.string().trim().min(1).max(2e3),url:me.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:db.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),kp=me.discriminatedUnion("channel",[me.strictObject({channel:me.literal("email"),content:cb}),me.strictObject({channel:me.literal("sms"),content:ub}),me.strictObject({channel:me.literal("voice"),content:lb}),me.strictObject({channel:me.literal("push"),content:pb})]),jp=me.strictObject({requestId:me.uuid(),customerId:me.uuid(),connectionId:me.uuid().optional(),message:kp,expiresAt:me.iso.datetime({offset:!0})}),mb=me.array(me.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),fb=me.discriminatedUnion("kind",[me.strictObject({kind:me.literal("all")}),me.strictObject({kind:me.literal("customers"),customerIds:mb})]),CP=me.strictObject({name:me.string().trim().min(1).max(120),connectionId:me.uuid().optional(),message:kp,audience:fb,frequencyLimit:me.number().int().min(1).max(100)}),Tp=me.strictObject({requestId:me.uuid(),channel:ro,state:me.enum(["allowed","denied"]),expectedRevision:me.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),Np=me.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Dp=me.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),_P=me.strictObject({meter:ab,estimatedUnits:me.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:me.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});import{z as Ce}from"zod";import{z as re}from"zod";import{z as si}from"zod";var io=si.strictObject({internalFeatureId:si.uuid(),name:si.string().min(1).max(120),includedAmount:si.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:si.enum(["hour","day","week","month","year","lifetime"]),resetCount:si.number().int().min(1).max(100),terms:Yo});import{z as ct}from"zod";import{z as gb}from"zod";import{z as ci}from"zod";var Fp=ci.enum(["stripe","apple","google","merchant"]),Mp=ci.enum(["membership","credit_pack","lifetime"]),NP=ci.enum(["active","grace","suspended","inactive","revoked"]),DP=ci.strictObject({currency:ci.string().regex(/^[A-Z]{3}$/),micros:ci.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var ui=gb.object({provider:Fp,currency:Ie}).strict();var ir=ct.strictObject({internal_feature_id:ct.uuid(),quantity:xe.refine(e=>/[1-9]/.test(e)),properties:vt,entityId:ct.uuid().optional()}),qp=ct.strictObject({requirement:ir,commerce:ui.optional(),paywallId:ct.uuid().optional()}),hb=ct.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),hc=ct.strictObject({productId:ct.string().min(1),productVersionId:ct.string().min(1),name:ct.string().min(1).max(120),action:ct.enum(["purchase","upgrade","addon","topup"]),membershipId:ct.string().min(1).nullable(),currency:Ie,amountMinor:ct.string().regex(/^(0|[1-9]\d{0,8})$/),interval:ct.enum(["free","week","month","year","one_time"]),intervalCount:ct.number().int().min(1).max(156)}),Rr=ct.strictObject({internal_feature_id:ct.string().min(1),name:ct.string().min(1).max(120),kind:ct.enum(["access","metered","credit"]),quantity:xe,allowed:ct.boolean(),reason:hb.nullable(),preview:ct.strictObject({scenario:ct.enum(["feature_flag","usage_limit"]),candidates:ct.array(hc).max(20)}).nullable()}).superRefine((e,t)=>{(e.allowed!==(e.reason===null)||e.allowed&&e.preview!==null||new Set(e.preview?.candidates.map(n=>n.productVersionId)).size!==(e.preview?.candidates.length??0)||e.preview?.candidates.some(n=>n.action==="upgrade"!=(n.membershipId!==null)))&&t.addIssue({code:"custom",message:"Invalid access recommendation"})}),GP=ct.strictObject({paywallId:ct.uuid(),requirement:ir});var ya=re.object({plan:re.string().min(1).max(200).optional(),coupon:re.uuid().optional(),promotionCode:re.uuid().optional(),picker:re.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),ha=re.object({text:re.string().optional(),label:re.string().optional(),alt:re.string().optional(),html:re.string().max(32768).optional(),price:re.object({current:re.string(),original:re.string().nullable(),period:re.string()}).optional(),code:re.string().optional(),countdownAt:re.iso.datetime().optional(),planId:re.string().min(1).max(200).optional(),planVersionId:re.string().min(1).max(200).optional(),currency:Ie.optional(),couponId:re.uuid().optional(),offerId:re.uuid().optional(),unavailable:re.boolean().optional(),unavailableReason:re.string().optional(),missing:re.array(re.string()).optional()}).strict(),li=re.object({paywall:Rr.optional(),nodes:re.record(re.string(),re.object({base:ha,picker:re.string().optional(),byPlan:re.record(re.string(),ha).optional()}).strict()),plans:re.record(re.string(),re.object({id:re.string().min(1).max(200),versionId:re.string().min(1).max(200),available:re.boolean(),name:re.string(),price:re.string(),period:re.string(),currency:Ie.optional(),amountMinor:re.number().int().nonnegative().optional(),interval:re.enum(["free","week","month","year","one_time"]).optional(),intervalCount:re.number().int().positive().optional(),prepaid:re.array(io).max(100).optional()}).strict()),pickers:re.record(re.string(),re.object({options:re.array(re.string().min(1).max(200)).max(20),selected:re.string().min(1).max(200).nullable()}).strict()),quantities:re.record(re.string(),re.strictObject({minimum:re.number().int().nonnegative(),maximum:re.number().int().nonnegative(),step:re.number().int().positive(),value:re.number().int().nonnegative(),label:re.string(),available:re.boolean()})).optional(),diagnostics:re.array(re.object({nodeId:re.string(),message:re.string()}).strict())}).strict();function Up(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}import{z as I}from"zod";function yb(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function Bp(e){let t={};function n(r){var i;if(yb(r)){let a=t[i=r.interaction.pickerId]??(t[i]={ids:[],defaultId:null});for(let s of r.children){let c=s.type==="stack"?s.bind?.plan:void 0;c&&!a.ids.includes(c)&&a.ids.push(c)}let o=r.children[r.interaction.defaultIndex];!a.defaultId&&o?.type==="stack"&&(a.defaultId=o.bind?.plan??null)}r.type==="stack"&&r.children.forEach(n)}return e.pages.forEach(r=>n(r.root)),t}import{z as Jn}from"zod";var Vp=Jn.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Aa=Jn.strictObject({tiers:Jn.array(Jn.strictObject({id:Vp,name:Jn.string().trim().min(1).max(80)})).min(1).max(8),assignments:Jn.array(Jn.strictObject({productVersionId:Jn.string().min(1).max(200),tierId:Vp,period:Jn.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let n=e.tiers.map(r=>r.id);(new Set(n).size!==n.length||new Set(e.assignments.map(r=>r.productVersionId)).size!==e.assignments.length||new Set(e.assignments.map(r=>`${r.tierId}:${r.period}`)).size!==e.assignments.length||e.assignments.some(r=>!n.includes(r.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function ba(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}import{z as ce}from"zod";var Ab=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],Lp=ce.enum(Ab),zp=ce.object({source:Lp,layout:ce.enum(["full","compact"]),resourceKey:Or.optional(),pageSize:ce.number().int().min(1).max(50),showSources:ce.boolean(),allowPurchase:ce.boolean(),outputs:ce.object({billing_adjustment:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((e,t)=>{(e.outputs?.billing_authorization||e.outputs?.billing_adjustment)&&e.source!=="billing_controls"&&t.addIssue({code:"custom",message:"Payment authorization routes belong to the billing controls component."}),e.resourceKey&&!["credit_balance","credit_transactions"].includes(e.source)&&t.addIssue({code:"custom",message:"\u8FD9\u4E2A\u6570\u636E\u6E90\u4E0D\u80FD\u7ED1\u5B9A\u79EF\u5206\u8D44\u6E90\u3002"}),e.showSources&&e.source!=="credit_balance"&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u4F59\u989D\u53EF\u4EE5\u5C55\u5F00\u6765\u6E90\u3002"}),e.allowPurchase&&!["credit_packs","customer_plans","membership"].includes(e.source)&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u5305\u3001\u5957\u9910\u4E0E\u4F1A\u5458\u7EC4\u4EF6\u53EF\u4EE5\u542F\u7528\u4EA4\u6613\u3002"})}),Rt=ce.string().max(2e3),$p=ce.object({id:ce.string().max(100),label:Rt,detail:ce.array(Rt).max(12),value:Rt.optional(),status:Rt.optional(),facts:ce.array(ce.object({label:Rt,value:Rt}).strict()).max(1e3),purchaseId:ce.uuid().optional(),invoiceUrl:ce.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:ce.array(ce.strictObject({action:ce.literal("invoice_open"),label:Rt})).max(1).optional(),membershipActions:ce.array(ce.object({value:ce.string().max(100),label:Rt}).strict()).max(3).optional()}).strict(),bb=ce.object({key:Or,name:Rt,spendable:Rt,reserved:Rt,available:Rt,expiry:Rt.nullable(),sources:ce.array($p).max(50),sourceCount:ce.number().int().nonnegative(),sourcePage:ce.number().int().positive(),hasNextSources:ce.boolean(),hasPreviousSources:ce.boolean()}).strict(),xb=ce.object({source:Lp,status:ce.enum(["idle","loading","ready","error"]),stale:ce.boolean(),preview:ce.boolean(),errorCode:ce.string().max(80).optional(),errorMessage:Rt.optional(),resources:ce.array(bb).max(500),rows:ce.array($p).max(50),hasNext:ce.boolean(),hasPrevious:ce.boolean(),page:ce.number().int().positive(),filter:ce.string().max(40),updatedAt:ce.iso.datetime().optional(),buyingId:ce.uuid().optional(),membershipBusy:ce.boolean().optional(),billingBusy:ce.boolean().optional(),membershipReview:ce.object({title:Rt,note:Rt,facts:ce.array(ce.object({label:Rt,value:Rt}).strict()).max(100)}).strict().optional(),membershipResult:Rt.optional()}).strict(),Gp=ce.object({nodes:ce.record(ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),xb)}).strict(),rC=ce.object({nodeId:ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:ce.enum(["refresh","next","previous","filter","buy_pack","billing_portal","billing_authorization","billing_adjustment","invoice_open","membership_preview","membership_confirm","membership_dismiss","sources_next","sources_previous"]),value:ce.string().max(100).optional()}).strict();import{z as K}from"zod";var St={state:32,enumValues:64,derived:96,bindings:256,controls:64,timers:4,effects:8,depth:12,expressionNodes:2e3},Hp=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]),Nt=K.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/).refine(e=>!Hp.has(e),"Reserved UI identifier"),yc=K.union([K.string().max(2e3),K.number().finite(),K.boolean(),K.null()]),Sb=K.discriminatedUnion("type",[K.strictObject({type:K.literal("enum"),values:K.array(yc).min(1).max(St.enumValues),default:yc}),K.strictObject({type:K.literal("number"),min:K.number().finite(),max:K.number().finite(),step:K.number().finite().positive(),default:K.number().finite()}),K.strictObject({type:K.literal("text"),maxLength:K.number().int().min(0).max(2e3),default:K.string().max(2e3).nullable()}),K.strictObject({type:K.literal("boolean"),default:K.boolean()})]);function bc(e,t){if(e.type==="enum")return e.values.some(r=>r===t);if(e.type==="boolean")return typeof t=="boolean";if(e.type==="text")return t===null||typeof t=="string"&&t.length<=e.maxLength;if(typeof t!="number"||!Number.isFinite(t)||t<e.min||t>e.max)return!1;let n=(t-e.min)/e.step;return Number.isFinite(n)&&Math.abs(n-Math.round(n))<=Math.min(1e-7,Math.max(1,Math.abs(n))*Number.EPSILON*8)}var Ib=Sb.superRefine((e,t)=>{e.type==="enum"&&new Set(e.values).size!==e.values.length&&t.addIssue({code:"custom",path:["values"],message:"UI enum values must be unique"}),e.type==="number"&&e.min>e.max&&t.addIssue({code:"custom",path:["max"],message:"UI number range is reversed"}),bc(e,e.default)||t.addIssue({code:"custom",path:["default"],message:"UI default must match its state definition"})}),vb=["add","sub","mul","div","min","max","round","floor","eq","ne","gt","gte","lt","lte","and","or","not","if","concat","number","parse_number","money","lookup","now","duration"];function wb(e,t){return e==="now"?t===0:e==="concat"?!0:e==="lookup"?t>=4&&t%2===0:e==="if"?t===3:["sub","div","eq","ne","gt","gte","lt","lte"].includes(e)?t===2:["round","floor","not","number","parse_number","money","duration"].includes(e)?t===1:t>=1}var jr=K.lazy(()=>K.union([yc,K.strictObject({ref:Nt}),K.strictObject({op:K.enum(vb),args:K.array(jr).max(St.expressionNodes)}).superRefine((e,t)=>{wb(e.op,e.args.length)||t.addIssue({code:"custom",path:["args"],message:"Invalid UI expression arity"})})]));function On(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function kr(e,t,n){if(!e||typeof e!="object")return!0;if(!On(e))return t.addIssue({code:"custom",path:n,message:"UI objects must be plain data"}),!1;for(let r of Object.keys(e)){if(Hp.has(r))return t.addIssue({code:"custom",path:[...n,r],message:"Reserved UI object key"}),!1;let i=Object.getOwnPropertyDescriptor(e,r);if(i&&!Object.hasOwn(i,"value"))return t.addIssue({code:"custom",path:[...n,r],message:"UI objects cannot contain accessors"}),!1}return!0}function di(e,t,n,r){let i=[{value:e,depth:1,path:n}];for(;i.length;){let a=i.pop();if(++r.nodes>St.expressionNodes||a.depth>St.depth){t.addIssue({code:"custom",path:a.path,message:"UI expression budget exceeded"});return}if(!kr(a.value,t,a.path))return;if(On(a.value)&&Array.isArray(a.value.args)){if(a.value.args.length>St.expressionNodes){t.addIssue({code:"custom",path:[...a.path,"args"],message:"UI expression budget exceeded"});return}for(let o=a.value.args.length-1;o>=0;o--)i.push({value:a.value.args[o],depth:a.depth+1,path:[...a.path,"args",o]})}}}var aC=K.unknown().superRefine((e,t)=>{di(e,t,[],{nodes:0})}).pipe(jr),Ac=K.record(Nt,jr).refine(e=>Object.keys(e).length>0&&Object.keys(e).length<=St.state,"UI assignments need 1\u201332 state keys"),Ob=K.strictObject({target:Nt,property:K.enum(["text","visible","disabled","checked","value","class","aria-label","aria-selected","aria-checked","aria-valuetext","tabindex"]),expression:jr,className:Nt.optional()}).superRefine((e,t)=>{e.property==="class"!=(e.className!==void 0)&&t.addIssue({code:"custom",path:["className"],message:"Only class bindings require a safe className"})}),Pb=K.discriminatedUnion("type",[K.strictObject({type:K.literal("scroll_latch"),target:Nt,state:Nt}),K.strictObject({type:K.literal("input"),target:Nt,state:Nt,set:Ac.optional()}),K.strictObject({type:K.literal("action"),target:Nt,set:Ac}),K.strictObject({type:K.literal("carousel"),target:Nt,state:Nt,initialIndex:K.number().int().nonnegative().optional(),maxWidth:K.number().int().min(1).max(1e4).optional(),previousTarget:Nt.optional(),nextTarget:Nt.optional(),inactiveTargets:K.array(Nt).max(20).optional(),inactiveMaxWidth:K.number().int().min(1).max(1e4).optional()})]),Cb=K.strictObject({afterMs:K.number().int().min(0).max(6e4),set:Ac}),_b=K.strictObject({type:K.literal("mosaic_waves"),target:Nt,color:K.string().regex(/^#[0-9a-fA-F]{6}$/),hotColor:K.string().regex(/^#[0-9a-fA-F]{6}$/),enabled:jr.optional(),speed:K.number().min(0).max(4).optional(),pitch:K.number().min(.05).max(4).optional(),fill:K.number().min(.05).max(1).optional(),feather:K.number().min(0).max(1).optional(),warp:K.number().min(0).max(4).optional(),warpScale:K.number().min(0).max(32).optional(),detailScale:K.number().min(0).max(32).optional(),waveScale:K.number().min(0).max(32).optional(),falloff:K.number().min(.1).max(32).optional(),brightness:K.number().min(0).max(32).optional(),ambient:K.number().min(0).max(1).optional(),gamma:K.number().min(.05).max(8).optional(),vignette:K.number().min(0).max(1).optional(),opacity:K.number().min(0).max(1).optional()}),Eb=K.strictObject({type:K.literal("number_counter"),target:Nt,value:jr,prefix:K.string().max(20).optional(),format:K.enum(["number","short"]).optional()}),Rb=K.strictObject({state:K.record(Nt,Ib).refine(e=>Object.keys(e).length<=St.state,"Too many UI state keys").optional(),derived:K.record(Nt,jr).refine(e=>Object.keys(e).length<=St.derived,"Too many UI derived keys").optional(),bindings:K.array(Ob).max(St.bindings).optional(),controls:K.array(Pb).max(St.controls).optional(),timers:K.array(Cb).max(St.timers).optional(),effects:K.array(K.discriminatedUnion("type",[_b,Eb])).max(St.effects).optional(),clock:K.boolean().optional()});function kb(e,t){if(!kr(e,t,[])||!On(e))return;for(let[r,i]of[["state",St.state],["derived",St.derived]]){let a=e[r];if(!kr(a,t,[r]))return;if(On(a)&&Object.keys(a).length>i){t.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}}for(let[r,i]of[["bindings",St.bindings],["controls",St.controls],["timers",St.timers],["effects",St.effects]])if(Array.isArray(e[r])&&e[r].length>i){t.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}if(Array.isArray(e.effects)){for(let[r,i]of e.effects.entries())if(!kr(i,t,["effects",r]))return}if(On(e.state))for(let[r,i]of Object.entries(e.state)){if(!kr(i,t,["state",r]))return;if(On(i)&&Array.isArray(i.values)&&i.values.length>St.enumValues){t.addIssue({code:"custom",path:["state",r,"values"],message:"Too many UI enum values"});return}}let n={nodes:0};if(On(e.derived))for(let[r,i]of Object.entries(e.derived))di(i,t,["derived",r],n);for(let r of["bindings","controls","timers"]){let i=e[r];if(Array.isArray(i)){for(let[a,o]of i.entries())if(!(!kr(o,t,[r,a])||!On(o))){if(r==="bindings")di(o.expression,t,[r,a,"expression"],n);else if(kr(o.set,t,[r,a,"set"])&&On(o.set)){if(Object.keys(o.set).length>St.state){t.addIssue({code:"custom",path:[r,a,"set"],message:"Too many UI assignments"});return}for(let[s,c]of Object.entries(o.set))di(c,t,[r,a,"set",s],n)}if(n.nodes>St.expressionNodes)return}}}if(Array.isArray(e.effects))for(let[r,i]of e.effects.entries())On(i)&&i.type==="number_counter"?di(i.value,t,["effects",r,"value"],n):On(i)&&i.enabled!==void 0&&di(i.enabled,t,["effects",r,"enabled"],n)}function Kp(e){let t=[],n=[e];for(;n.length;){let r=n.pop();!r||typeof r!="object"||("ref"in r?t.push(r.ref):n.push(...r.args))}return t}var Qp=K.unknown().superRefine(kb).pipe(Rb).superRefine((e,t)=>{let n=e.state??{},r=e.derived??{},i=new Set([...Object.keys(n),...Object.keys(r)]),a=(g,d)=>{for(let h of Kp(g))i.has(h)||t.addIssue({code:"custom",path:d,message:`Unknown UI reference: ${h}`})};for(let[g,d]of Object.entries(e.derived??{}))Object.hasOwn(n,g)&&t.addIssue({code:"custom",path:["derived",g],message:"UI state and derived identifiers must be distinct"}),a(d,["derived",g]);let o=new Set,s=new Set,c=g=>{if(o.has(g))return!1;if(s.has(g))return!0;o.add(g);for(let d of Kp(r[g]))if(Object.hasOwn(r,d)&&!c(d))return!1;return o.delete(g),s.add(g),!0};for(let g of Object.keys(r))if(!c(g)){t.addIssue({code:"custom",path:["derived",g],message:"Cyclic UI derived references"});break}for(let[g,d]of(e.bindings??[]).entries())a(d.expression,["bindings",g,"expression"]);let u=new Set;for(let[g,d]of(e.effects??[]).entries())u.has(d.target)&&t.addIssue({code:"custom",path:["effects",g,"target"],message:"Effect targets must be unique"}),u.add(d.target),d.type==="number_counter"?(a(d.value,["effects",g,"value"]),typeof d.value=="number"&&Math.abs(d.value)>1e12&&t.addIssue({code:"custom",path:["effects",g,"value"],message:"Counter values must be within the display bound"})):d.enabled!==void 0&&a(d.enabled,["effects",g,"enabled"]);let l=(g,d)=>{for(let[h,R]of Object.entries(g))Object.hasOwn(n,h)||t.addIssue({code:"custom",path:[...d,h],message:"UI assignments can only update declared state"}),a(R,[...d,h])},m=new Set,f=new Set;for(let[g,d]of(e.controls??[]).entries()){if(d.type==="carousel"&&d.inactiveMaxWidth!==void 0&&d.inactiveTargets===void 0&&t.addIssue({code:"custom",path:["controls",g,"inactiveMaxWidth"],message:"Inactive width requires inactive article targets"}),d.type==="carousel")for(let h of d.inactiveTargets??[])(h===d.target||f.has(h))&&t.addIssue({code:"custom",path:["controls",g,"inactiveTargets"],message:"Inactive article targets must have one carousel owner"}),f.add(h);if(d.type==="carousel")for(let h of["previousTarget","nextTarget"]){let R=d[h];R!==void 0&&((R===d.target||m.has(R)||(e.controls??[]).some(y=>y.target===R))&&t.addIssue({code:"custom",path:["controls",g,h],message:"Carousel navigation needs a distinct, exclusive button target"}),m.add(R))}if(d.type!=="action"){let h=Object.hasOwn(n,d.state)?n[d.state]:void 0;(!h||d.type==="input"&&h.type==="enum"&&h.values.some(R=>typeof R!="string"))&&t.addIssue({code:"custom",path:["controls",g,"state"],message:"Control needs a supported declared UI state"}),d.type==="carousel"&&(h?.type!=="number"||!Number.isInteger(h.min)||h.min<0||!Number.isInteger(h.max)||h.step!==1||d.initialIndex!==void 0&&!bc(h,d.initialIndex))&&t.addIssue({code:"custom",path:["controls",g],message:"Carousel needs bounded nonnegative integer index state"}),d.type==="scroll_latch"&&h?.type!=="boolean"&&t.addIssue({code:"custom",path:["controls",g,"state"],message:"Scroll latches require boolean UI state"})}(d.type==="input"||d.type==="action")&&d.set&&l(d.set,["controls",g,"set"])}for(let[g,d]of(e.timers??[]).entries())l(d.set,["timers",g,"set"])});import{z as ot}from"zod";var jb=ot.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),xa=ot.discriminatedUnion("type",[ot.object({type:ot.literal("fixed"),productVersionId:ot.string().min(1).max(200)}).strict(),ot.object({type:ot.literal("picker"),pickerId:jb,allowedProductVersionIds:ot.array(ot.string().min(1).max(200)).min(1).max(20)}).strict().refine(e=>new Set(e.allowedProductVersionIds).size===e.allowedProductVersionIds.length,"Product choices must be unique")]),Tb=ot.strictObject({min:ot.number().finite().min(1).max(1800),max:ot.number().finite().min(1).max(1800),viewport:ot.number().finite().min(1).max(100)}).refine(e=>e.min<=e.max,"Desktop width range is reversed"),Jp={desktopWidth:Tb.optional(),mobile:ot.enum(["sheet","fullscreen"]).optional(),backdrop:ot.enum(["none","scrim","dim","strong-dim","blur"]).optional()},Pn=ot.discriminatedUnion("type",[ot.strictObject({type:ot.literal("modal"),size:ot.enum(["sm","md","lg"]),...Jp}),ot.strictObject({type:ot.literal("sheet"),size:ot.enum(["sm","md","lg"]),...Jp}),ot.strictObject({type:ot.literal("fullscreen")}),ot.strictObject({type:ot.literal("inline")})]);var Db=4,_n={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:32768,documentBytes:2e5},ao=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ue=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Fb=I.enum(["none","xs","sm","md","lg","xl"]),Mb=I.enum(["none","sm","md","lg","full"]),xc=I.string().regex(/^#[0-9a-fA-F]{6}$/),Ic=I.string().max(2048).refine(e=>{try{let t=new URL(e);return t.protocol==="https:"&&t.hostname.length>0}catch{return!1}},"\u53EA\u652F\u6301 https \u94FE\u63A5"),Sc=I.union([Ic,I.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),I.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),I.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Zp=I.object({primary:xc,background:xc,text:xc,radius:Mb,font:I.enum(["system","serif","rounded","mono"]),fontAssets:I.object({family:I.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/),faces:I.array(I.object({url:Ic,weight:I.number().int().min(100).max(900).multipleOf(100),family:I.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/).optional()}).strict()).min(1).max(4)}).strict().optional()}).strict(),so=I.union([I.enum(["primary","text","muted","background","surface"]),I.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),Me=(e,t)=>I.number().int().min(e).max(t),Wp=I.union([I.enum(["fit","fill"]),Me(1,1200)]),qb=I.object({top:Me(0,200),right:Me(0,200),bottom:Me(0,200),left:Me(0,200)}).strict(),Ub=I.object({top:Me(-100,200),right:Me(-100,200),bottom:Me(-100,200),left:Me(-100,200)}).strict(),Yp=I.object({x:Me(0,100),y:Me(0,100)}).strict(),Bb=I.discriminatedUnion("type",[I.object({type:I.literal("color"),color:so}).strict(),I.object({type:I.literal("linear"),angle:Me(0,360),stops:I.array(I.object({color:so,at:Me(0,100)}).strict()).min(2).max(4)}).strict(),I.object({type:I.literal("image"),src:Sc,fit:I.enum(["cover","contain"]),position:Yp.optional()}).strict()]),Vb=I.discriminatedUnion("type",[I.object({type:I.literal("rect"),radius:I.union([Me(0,200),I.object({topLeft:Me(0,200),topRight:Me(0,200),bottomRight:Me(0,200),bottomLeft:Me(0,200)}).strict()])}).strict(),I.object({type:I.literal("pill")}).strict()]),Lb=I.object({width:Me(0,12),color:so,style:I.enum(["solid","dashed"])}).strict(),zb=I.object({x:Me(-40,40),y:Me(-40,40),blur:Me(0,80),spread:Me(-20,40),color:so}).strict(),$b=I.object({font:I.enum(["system","serif","rounded","mono"]),size:Me(8,96),weight:I.number().int().min(100).max(900).multipleOf(100),lineHeight:I.number().min(.8).max(3),letterSpacing:I.number().min(-5).max(20),color:so,align:I.enum(["start","center","end"]),italic:I.boolean(),decoration:I.enum(["none","underline","line-through"]),transform:I.enum(["none","uppercase"])}).strict().partial(),Tr=I.object({width:Wp,height:Wp,padding:qb,margin:Ub,gap:Me(0,120),grow:I.union([I.boolean(),I.number().min(0).max(12)]),background:Bb,opacity:I.number().min(0).max(1),clipContent:I.boolean(),shape:Vb,border:Lb,shadow:zb,text:$b}).strict().partial(),tn={id:ao,name:I.string().trim().min(1).max(60).optional(),hidden:I.boolean().optional(),style:Tr.optional(),fallback:Ue.optional()},Gb=I.object({...tn,type:I.literal("text"),productField:I.enum(["name","price","trial","period"]).optional(),feature:I.object({id:I.uuid(),field:I.enum(["name","allowance"])}).strict().optional(),text:Ue,variant:I.enum(["title","heading","body","caption"])}).strict(),Kb=I.object({...tn,type:I.literal("image"),src:Sc,localizedSrc:I.record(In,Sc).optional(),alt:Ue,aspect:I.enum(["auto","1:1","4:3","16:9","3:1"]),fit:I.enum(["cover","contain"]),position:Yp.optional()}).strict(),Hb=I.object({...tn,type:I.literal("button"),label:Ue,variant:I.enum(["primary","secondary","link"]),action:Ue,purpose:I.enum(["purchase","navigation","close"]).optional(),bind:ya.optional()}).strict(),Qb=I.object({...tn,type:I.literal("divider")}).strict(),Jb=I.object({...tn,type:I.literal("customer_data"),title:Ue,data:zp}).strict(),Zb=I.object({...tn,type:I.literal("spacer"),size:Fb}).strict(),Wb=I.object({...tn,type:I.literal("custom_html"),html:I.record(In,I.string().max(_n.customHtml)),css:I.string().max(_n.customCss),ui:Qp.optional()}).strict(),Yb=I.object({...tn,type:I.literal("price"),fallback:Ue,parts:I.object({current:Tr.optional(),original:Tr.optional(),period:Tr.optional()}).strict().optional()}).strict(),Xb=I.object({...tn,type:I.literal("coupon_code"),label:Ue,fallback:Ue}).strict(),ex=I.object({...tn,type:I.literal("countdown"),source:I.enum(["offer.ends_at","offer.expires_at","fixed"]),at:I.iso.datetime().optional(),granularity:I.enum(["day","hour","minute","second"]),expired:Ue,fallback:Ue}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),tx=I.object({...tn,type:I.literal("plan_picker"),label:Ue,fallback:Ue,planIds:I.array(I.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:I.string().min(1).max(200).optional(),grouping:Aa.safeExtend({monthLabel:Ue,yearLabel:Ue,unavailableLabel:Ue}).optional(),states:I.object({selected:Tr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!ba(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),nx=I.object({...tn,type:I.literal("quantity_picker"),bind:ya.optional(),label:Ue,fallback:Ue,internalFeatureId:I.uuid(),minimumQuantity:Me(0,1e4),maximumQuantity:Me(0,1e4),defaultQuantity:Me(0,1e4),step:Me(1,1e4)}).strict().refine(e=>e.minimumQuantity<=e.defaultQuantity&&e.defaultQuantity<=e.maximumQuantity&&(e.defaultQuantity-e.minimumQuantity)%e.step===0,"Quantity controls require a Product binding and valid bounds"),rx=I.discriminatedUnion("type",[I.object({type:I.literal("input"),label:Ue,keyboard:I.enum(["text","email","tel","url"]),maxLength:Me(1,500)}).strict(),I.object({type:I.literal("multiselect"),label:Ue,min:Me(0,50),max:Me(1,50)}).strict(),I.object({type:I.literal("select"),label:Ue,defaultIndex:Me(0,49),purpose:I.enum(["option","product","tier"]).optional(),pickerId:ao.optional(),selectedStyle:Tr.optional()}).strict(),I.object({type:I.literal("tabs"),label:Ue,defaultIndex:Me(0,49),purpose:I.literal("tier").optional()}).strict(),I.object({type:I.literal("toggle"),label:Ue,defaultEnabled:I.boolean()}).strict(),I.object({type:I.literal("carousel"),label:Ue}).strict()]),Cn={...tn,type:I.literal("stack"),direction:I.enum(["vertical","horizontal","overlay"]),align:I.enum(["start","center","end","stretch"]),justify:I.enum(["start","center","end","between"]),productSlot:I.object({index:Me(0,19),period:I.enum(["month","year"]).optional(),requireBinding:I.boolean().optional()}).strict().optional(),interaction:rx.optional(),states:I.object({selected:Tr.optional()}).strict().optional(),purpose:I.literal("benefits").optional(),purchaseAction:Ue.optional(),buttonVariant:I.enum(["primary","secondary","link"]).optional(),bind:ya.optional()},Xp=I.lazy(()=>I.object({...tn,type:Cn.type,direction:Cn.direction,align:Cn.align,justify:Cn.justify,children:I.array(ix).max(_n.children),productSlot:Cn.productSlot,interaction:Cn.interaction,states:Cn.states,purpose:Cn.purpose,purchaseAction:Cn.purchaseAction,buttonVariant:Cn.buttonVariant,bind:Cn.bind}).strict()),ix=I.lazy(()=>I.union([Xp,Gb,Kb,Hb,Qb,Zb,Wb,Yb,Xb,ex,tx,nx,Jb])),ox=I.union([I.string().max(500),I.number().finite(),I.boolean(),I.null()]),oo={id:Ue,event:Ue,properties:I.record(Ue,ox).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},ax=I.discriminatedUnion("type",[I.object({...oo,type:I.literal("navigate"),close:I.literal(!1),pageId:ao}).strict(),I.object({...oo,type:I.literal("event"),close:I.boolean()}).strict(),I.object({...oo,type:I.literal("close"),close:I.literal(!0)}).strict(),I.object({...oo,type:I.literal("open_url"),close:I.boolean(),url:Ic}).strict(),I.object({...oo,type:I.literal("claim_offer"),close:I.boolean(),couponId:I.uuid()}).strict()]),sx=I.object({defaultLocale:In,locales:I.record(In,I.record(Ue,I.string().max(_n.stringLength)))}).strict(),cx=I.enum(["popup","paywall","onboarding","page","banner"]);var ux=I.object({kind:I.literal("screen"),schemaVersion:I.literal(Db),name:I.string().trim().min(1).max(80),surface:cx,initialPageId:ao.optional(),presentation:Pn,theme:Zp,pages:I.array(I.object({id:ao,name:I.string().trim().min(1).max(60),root:Xp,theme:Zp.optional(),editorPosition:I.object({x:I.number().finite().min(-1e5).max(1e5),y:I.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(_n.pages),strings:sx,actions:I.array(ax).max(_n.actions)}).strict();function Gt(e,t){for(let n of e.pages)Zn(n.root,t)}var un=ux.superRefine((e,t)=>{let n=_n;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(l=>l.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let l of e.actions)l.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(m=>m.id===l.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>n.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${n.pages} \u4E2A`}),e.actions.length>n.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${n.actions} \u4E2A`});let r=l=>t.addIssue({code:"custom",message:l}),i=Object.keys(e.strings.locales);i.includes(e.strings.defaultLocale)||r("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),i.length>_n.locales&&r(`\u6700\u591A ${_n.locales} \u79CD\u8BED\u8A00`);let a=new Set;for(let l of e.actions)a.has(l.id)&&r(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${l.id}`),a.add(l.id);let o=new Set;for(let l of e.pages)["next","back"].includes(l.id)&&r(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${l.id}`),o.has(l.id)&&r(`\u9875\u9762 id \u91CD\u590D\uFF1A${l.id}`),o.add(l.id);let s=new Set,c=0,u=!1;Gt(e,(l,m)=>{if(c++,m>_n.depth&&(u=!0),s.has(l.id)&&r(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${l.id}`),s.add(l.id),l.type==="button"&&!a.has(l.action)&&r(`\u6309\u94AE ${l.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${l.action}`),l.type==="custom_html")for(let f of Object.keys(l.html))i.includes(f)||r(`\u81EA\u5B9A\u4E49 HTML ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${f}`);if(l.type==="image")for(let f of Object.keys(l.localizedSrc??{}))i.includes(f)||r(`\u56FE\u7247 ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${f}`)}),c>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),u&&r(`\u5C42\u7EA7\u6700\u591A ${_n.depth} \u5C42`)});function Zn(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)Zn(i,t,n+1,e)}function Sa(e){let t=[],n=new Set;return Gt(e,r=>{let i=(a,o,s)=>{n.has(a)||(n.add(a),t.push({key:a,nodeId:r.id,nodeType:r.type,field:o,required:s}))};r.type==="stack"&&r.interaction&&i(r.interaction.label,"label",!0),r.fallback&&i(r.fallback,"text",!0),r.type==="text"&&i(r.text,"text",!0),r.type==="customer_data"&&i(r.title,"title",!0),(r.type==="plan_picker"||r.type==="quantity_picker"||r.type==="coupon_code")&&i(r.label,"label",!0),r.type==="plan_picker"&&r.grouping&&(i(r.grouping.monthLabel,"label",!0),i(r.grouping.yearLabel,"label",!0),i(r.grouping.unavailableLabel,"text",!0)),r.type==="countdown"&&i(r.expired,"text",!0),r.type==="button"&&i(r.label,"label",!0),r.type==="image"&&(i(`image:${r.id}`,"src",!1),i(r.alt,"alt",!1)),r.type==="custom_html"&&i(`html:${r.id}`,"html",!0)}),t}function lx(e,t,n){if(t.field==="html"){let r;return Gt(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=co(e,t.nodeId);return r?.type==="image"?r.localizedSrc?.[n]??(n===e.strings.defaultLocale?r.src:void 0):void 0}return e.strings.locales[n]?.[t.key]}function or(e){let t=Sa(e).filter(r=>r.required);return Object.keys(e.strings.locales).sort((r,i)=>r===e.strings.defaultLocale?-1:i===e.strings.defaultLocale?1:0).map(r=>{let i=t.filter(a=>!lx(e,a,r)?.trim()).map(a=>a.key);return{locale:r,total:t.length,filled:t.length-i.length,missing:i,complete:i.length===0}})}function dx(e,t){let n=null;return Zn(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function co(e,t){for(let n of e.pages){let r=dx(n.root,t);if(r)return r}return null}import{z as Bt}from"zod";var It=Bt.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/).refine(e=>e.split(".").every(t=>t.length>0&&!["__proto__","constructor","prototype"].includes(t)),"Reserved or empty variable path"),vc=Bt.strictObject({type:Bt.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:Bt.boolean(),enum:Bt.array(Bt.string().max(255)).min(1).max(100).optional()}),pi=vc.extend({type:Bt.enum([...vc.shape.type.options,"array"]),items:vc.optional()}).superRefine((e,t)=>{(e.type==="array"!=!!e.items||e.enum&&e.type!=="string"||e.items?.enum&&e.items.type!=="string")&&t.addIssue({code:"custom",message:"Array requires items; only strings support enum"})}),mi=pi.safeExtend({source:Bt.discriminatedUnion("type",[Bt.strictObject({type:Bt.literal("input")}),Bt.strictObject({type:Bt.literal("node")}),Bt.strictObject({type:Bt.enum(["parameter","attribute"]),key:It})])}),SC=Bt.record(It,mi),wc=Bt.record(It,It).refine(e=>Object.keys(e).length<=20);function hn(e,t){return e?t===null?e.nullable:e.enum&&(typeof t!="string"||!e.enum.includes(t))?!1:e.type==="array"?Array.isArray(t)&&t.length<=100&&!!e.items&&t.every(n=>hn(e.items,n)):["offering_version","reward","paywall_version"].includes(e.type)?typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===2&&t.type===e.type&&Bt.uuid().safeParse(t.id).success:e.type==="json"||(e.type==="strings"?Array.isArray(t)&&t.every(n=>typeof n=="string"):typeof t===e.type):!1}function Oc(e,t){return e.nullable&&!t.nullable?!1:t.type==="json"?!0:e.type!==t.type||t.enum&&(!e.enum||e.enum.some(n=>!t.enum.includes(n)))?!1:e.type!=="array"||!!e.items&&!!t.items&&Oc(e.items,t.items)}function Ia(e,t){let n={};for(let[r,i]of Object.entries(e)){let a=i.source,o=a.type==="input"?t.answers:a.type==="node"?t.results??{}:a.type==="parameter"?t.parameters:t.attributes,s=a.type==="parameter"||a.type==="attribute"?a.key:r,c=Object.hasOwn(o,s),u=o[s];if(a.type==="attribute"&&s.includes(".")&&(!c||s.startsWith("merchandise."))){u=o,c=!0;for(let l of s.split(".")){if(!u||typeof u!="object"||!Object.hasOwn(u,l)||Array.isArray(u)&&(!/^(0|[1-9]\d*)$/.test(l)||Number(l)>=u.length)){c=!1;break}u=u[l]}}if(!(!c||u===void 0)){if(!hn(i,u))throw new Error(`Invalid variable value: ${r}`);n[r]=u}}return n}function fi(e,t){let n={};for(let[r,i]of Object.entries(e.writes??{})){if(!Object.hasOwn(t,r))throw new Error(`Node output is missing: ${r}`);if(Object.hasOwn(n,i))throw new Error("Node outputs cannot overwrite one another");n[i]=t[r]}return n}function em(e,t,n){let r=new Set(Object.values(t.writes??{}));for(let[i,a]of Object.entries(n))if(!r.has(i)||e[i]?.source.type!=="node"||!hn(e[i],a))throw new Error(`Invalid node variable write: ${i}`);if(r.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}import{z as Nr}from"zod";var En=Nr.string().min(1).max(255).regex(/^[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+){0,9}$/).refine(e=>e.split(".").every(t=>!["__proto__","constructor","prototype"].includes(t)),"Reserved value path"),Fn=Nr.discriminatedUnion("source",[Nr.strictObject({source:Nr.literal("literal"),value:ve}),Nr.strictObject({source:Nr.literal("variable"),key:Nr.string().min(1).max(255),path:En.optional()})]);function tm(e,t){if(!t)return e;for(let n of En.parse(t).split(".")){if(Array.isArray(e)){if(!/^(0|[1-9]\d*)$/.test(n)||Number(n)>=e.length)return;e=e[Number(n)];continue}if(e===null||typeof e!="object"||!Object.hasOwn(e,n))return;e=Reflect.get(e,n)}return e}function Pc(e,t){if(e.source==="literal")return structuredClone(e.value);let n=Ia(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(ve.parse(tm(n[e.key],e.path)))}function Cc(e,t){let n=[...t].sort((i,a)=>a.length-i.length).find(i=>e===i||e.startsWith(i+"."));if(!n)return null;let r=e===n?void 0:e.slice(n.length+1);return r&&!En.safeParse(r).success?null:{key:n,path:r}}function _c(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Gt(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(Up))]}function va(e){return _c(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function ln(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("A JSON value is required");let n=new TextEncoder().encode(t).length,r=!1;for(let i=0;i<t.length;i++){let a=t.charAt(i);if(r)a==="\\"?i++:a==='"'&&(r=!1);else if(a==='"')r=!0;else if(a===":"||a===",")n++;else if(a==="-"||a>="0"&&a<="9"){let o=i;for(;i+1<t.length&&/[0-9.eE+-]/.test(t.charAt(i+1));)i++;let s=t.slice(o,i+1);if(!/[eE]/.test(s))continue;let[c="",u]=s.split(/[eE]/),l=c.replace(/^-/,""),m=l.replace(".","").length,f=(l.includes(".")?l.indexOf("."):m)+Number(u),g=f<=0?2-f+m:f>=m?f:m+1;n+=g+(c.startsWith("-")?1:0)-s.length}}return n}var ar=Ce.enum(["page","popup","banner"]),px=3e5,nm=Ce.strictObject({type:Ce.enum(["string","number","boolean","strings","json"]),nullable:Ce.boolean()}),mx=Ce.strictObject({inputs:Ce.record(Ue,nm.extend({required:Ce.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:Ce.record(Ue,nm).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),fx=Ce.strictObject({kind:ar,schemaVersion:Ce.literal(1),name:Ce.string().trim().min(1).max(80),screen:un,contract:mx}),wa=fx.superRefine((e,t)=>{let n=(i,a)=>t.addIssue({code:"custom",message:i,path:a});e.screen.surface!==e.kind&&n("Content surface must match its domain",["screen","surface"]),e.screen.name!==e.name&&n("Content has one editable name",["screen","name"]),e.kind==="banner"&&e.screen.presentation.type!=="inline"&&n("Banner requires an inline container",["screen","presentation"]),e.kind!=="banner"&&e.screen.presentation.type==="inline"&&n("Inline presentation belongs to Banner",["screen","presentation"]),e.screen.actions.some(i=>i.type!=="event"&&i.type!=="navigate")&&n("Content actions must emit host intents or navigate locally",["screen","actions"]);let r=new Set(e.screen.actions.filter(i=>i.type==="event").map(i=>i.id));(Object.keys(e.contract.outputs).some(i=>!r.has(i))||[...r].some(i=>!Object.hasOwn(e.contract.outputs,i)))&&n("Every event needs exactly one output declaration",["contract","outputs"]),ln(e)>px&&n("Content document exceeds its byte budget",[])});function gx(e,t){if(e===null)return t.nullable;switch(t.type){case"json":return!0;case"string":return typeof e=="string";case"number":return typeof e=="number"&&Number.isFinite(e);case"boolean":return typeof e=="boolean";case"strings":return Array.isArray(e)&&e.every(n=>typeof n=="string")}}var hx=wa.superRefine((e,t)=>{for(let n of va(e.screen))Object.keys(e.contract.inputs).some(r=>n===r||n.startsWith(r+"."))||t.addIssue({code:"custom",path:["contract","inputs"],message:"Declare every reusable input read"});for(let n of e.screen.actions){if(n.type!=="event")continue;let r=e.contract.outputs[n.id],i=Object.hasOwn(n.properties,"value")?n.properties.value:n.properties;r&&!gx(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}or(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),rm=Ce.strictObject({id:Ce.uuid(),kind:ar,projectId:Ce.uuid(),environmentId:Ce.uuid(),name:Ce.string(),revision:Ce.number().int().nonnegative(),status:Ce.enum(["draft","published","archived"]),publishedVersionId:Ce.uuid().nullable(),createdAt:Ce.iso.datetime({offset:!0}),updatedAt:Ce.iso.datetime({offset:!0})}),MC=rm.extend({draft:wa}),qC=Ce.strictObject({rows:Ce.array(rm).max(200),nextCursor:Ce.uuid().nullable()}),Ec=Ce.strictObject({id:Ce.uuid(),kind:ar,resourceId:Ce.uuid(),projectId:Ce.uuid(),environmentId:Ce.uuid(),version:Ce.number().int().positive(),sourceRevision:Ce.number().int().nonnegative(),document:hx,createdAt:Ce.iso.datetime({offset:!0})}),UC=Ec.omit({document:!0}),BC=Ce.discriminatedUnion("action",[Ce.strictObject({action:Ce.literal("create"),kind:ar,id:Ce.uuid(),document:wa}),Ce.strictObject({action:Ce.literal("save"),kind:ar,id:Ce.uuid(),revision:Ce.number().int().nonnegative(),document:wa}),Ce.strictObject({action:Ce.enum(["publish","archive"]),kind:ar,id:Ce.uuid(),revision:Ce.number().int().nonnegative()})]).superRefine((e,t)=>{"document"in e&&e.document.kind!==e.kind&&t.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});import{z as im}from"zod";var gi={funnelId:im.uuid().optional(),funnelVersionId:im.uuid().optional()};import{z as Oa}from"zod";var Pa=Oa.strictObject({runId:Oa.uuid(),bindingId:Oa.uuid(),receiptId:Oa.uuid()});import{z as at}from"zod";import{z as Be}from"zod";import{z as et}from"zod";var HC=et.discriminatedUnion("action",[et.strictObject({action:et.literal("create"),couponId:et.uuid(),productBindingId:et.uuid(),storeOfferId:et.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:et.enum(["introductory","promotional"])}),et.strictObject({action:et.literal("set_enabled"),id:et.uuid(),revision:et.number().int().nonnegative(),enabled:et.boolean()})]),QC=et.array(et.strictObject({id:et.uuid(),couponId:et.uuid(),productBindingId:et.uuid(),storeOfferId:et.string().min(1).max(255).nullable(),storeOfferType:et.enum(["introductory","promotional"]),enabled:et.boolean(),revision:et.number().int().nonnegative()})).max(500),hi=et.strictObject({offerKind:et.enum(["none","introductory","promotional"]),offerId:et.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:et.number().int().min(0).max(1e8),trialDays:et.number().int().min(1).max(730).nullable()}).superRefine((e,t)=>{(e.offerKind==="none"&&(e.offerId!==null||e.discountMinor!==0||e.trialDays!==null)||e.trialDays!==null&&e.discountMinor!==0)&&t.addIssue({code:"custom",message:"Select one store purchase option with its exact terms"})}),JC=et.record(et.uuid(),hi).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var Rc=Be.object({type:Be.literal("native_purchase"),receiptId:Be.uuid(),orderId:Be.uuid(),productVersionId:Be.uuid(),provider:Be.enum(["apple","google"]),productId:Be.string().min(1).max(255),productKind:Mp,replacement:Be.strictObject({sourceOrderId:Be.uuid(),sourceProductId:Be.string().min(1).max(255),policy:Be.enum(["apple_store","google_full_price"]),sourceAccountTokens:Be.array(Be.uuid()).max(50)}).nullable(),appAccountToken:Be.uuid().optional(),obfuscatedAccountId:Be.string().min(1).max(64).optional(),obfuscatedProfileId:Be.uuid().optional(),basePlanId:Be.string().min(1).max(255).optional(),offerId:Be.string().min(1).max(255).optional(),offerKind:Be.enum(["none","introductory","promotional"]),currency:Ie,catalogAmountMinor:Be.number().int().nonnegative().max(1e8),discountMinor:Be.number().int().nonnegative().max(1e8),trialDays:Be.number().int().min(1).max(730).nullable(),seatBundle:Be.array(Be.strictObject({key:Be.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:Be.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:Be.strictObject({offerId:Be.string().min(1).max(255),keyId:Be.string().min(1).max(255),nonce:Be.uuid(),signature:Be.string().min(1).max(1024),timestamp:Be.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,t)=>{let n=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(n?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!n&&e.productKind==="membership"&&e.basePlanId===void 0||e.discountMinor>e.catalogAmountMinor||new Set(e.seatBundle.map(i=>i.key)).size!==e.seatBundle.length||e.trialDays!==null&&(e.discountMinor!==0||e.offerKind==="none")||e.offerKind==="none"&&e.discountMinor!==0||(n?!e.appAccountToken||e.obfuscatedAccountId!==void 0||e.obfuscatedProfileId!==void 0||e.basePlanId!==void 0||e.offerKind==="promotional"!=(e.applePromotionalOffer!==null)||e.offerKind==="promotional"!=(e.offerId!==void 0)||e.applePromotionalOffer!==null&&e.applePromotionalOffer.offerId!==e.offerId:e.appAccountToken!==void 0||!e.obfuscatedAccountId||!e.obfuscatedProfileId||e.applePromotionalOffer!==null||e.offerKind==="none"!=(e.offerId===void 0)))&&t.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});import{z as p}from"zod";import{z as _e}from"zod/v4";import{z as yx}from"zod/v4";var Ax=yx.registry(),{BillingInterval:om}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{BillingInterval:e}})(),{DisplaySchema:bx}=(e=>({DisplaySchema:e.object({primary_text:e.string().meta({description:"Main display text (e.g. '$10' or '100 messages')."}),secondary_text:e.string().optional().meta({description:"Secondary display text (e.g. 'per month' or 'then $0.5 per 100')."})})}))(_e),{withSpecDefault:xx}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(Ax),{COMMON:am}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:Sx}={STRIPE_PRESENTMENT_CURRENCIES:["usd","aed","afn","all","amd","ang","aoa","ars","aud","awg","azn","bam","bbd","bdt","bif","bmd","bnd","bob","brl","bsd","bwp","byn","bzd","cad","cdf","chf","clp","cny","cop","crc","cve","czk","djf","dkk","dop","dzd","egp","etb","eur","fjd","fkp","gbp","gel","gip","gmd","gnf","gtq","gyd","hkd","hnl","htg","huf","idr","ils","inr","isk","jmd","jpy","kes","kgs","khr","kmf","krw","kyd","kzt","lak","lbp","lkr","lrd","lsl","mad","mdl","mga","mkd","mmk","mnt","mop","mur","mvr","mwk","mxn","myr","mzn","nad","ngn","nio","nok","npr","nzd","pab","pen","pgk","php","pkr","pln","pyg","qar","ron","rsd","rub","rwf","sar","sbd","scr","sek","sgd","shp","sle","sos","srd","std","szl","thb","tjs","top","try","ttd","twd","tzs","uah","ugx","uyu","uzs","vnd","vuv","wst","xaf","xcd","xcg","xof","xpf","yer","zar","zmw"]},{COMMON_SET:Ix}=(e=>({COMMON_SET:new Set(e)}))(am),{hasNoDuplicateCurrencies:sm}={hasNoDuplicateCurrencies:t=>{let n=new Set;for(let{currency:r}of t){let i=r.toLowerCase();if(n.has(i))return!1;n.add(i)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:cm}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:vx}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(_e),{Infinite:wx}={Infinite:"inf"},{TierBehavior:Ox}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:um}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Px}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:Cx}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:_x}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Ex}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(_e),{ApiCreditTierSchema:lm}=(e=>({ApiCreditTierSchema:e.object({to:e.union([e.number().positive(),e.enum(["inf"])]).meta({description:"Inclusive upper usage boundary for this graduated tier. The final tier must be 'inf'."}),credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group within this tier."})})}))(_e),{VIOLATION_MESSAGES:Rx}={VIOLATION_MESSAGES:{non_final_infinity:"Only the final tier may use an 'inf' boundary.",not_increasing:"Tier boundaries must be strictly increasing.",final_not_infinity:"The final tier must use an 'inf' boundary."}},{MarkupEntrySchema:dm}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(_e),{ModelMarkupsSchema:kx}=((e,t)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),t.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(_e,dm),{InvoiceUsageEntrySchema:jx}=(e=>({InvoiceUsageEntrySchema:e.object({feature_id:e.string().meta({description:"The metered feature whose units are being converted."}),quantity:e.number().nonnegative().meta({description:"Billable units of the metered feature. Converted to the credit-system feature through its rate card."}),properties:e.record(e.string(),e.unknown()).optional().meta({description:"Event properties used to pick the rate card dimension and multipliers."})}).strict()}))(_e),{AttachDiscountSchema:pm}=(e=>({AttachDiscountSchema:e.object({reward_id:e.string().optional().meta({description:"The ID of the reward to apply as a discount."}),promotion_code:e.string().optional().meta({description:"The promotion code to apply as a discount."})}).refine(n=>n.reward_id||n.promotion_code,{message:"Either reward_id or promotion_code must be provided."}).meta({title:"AttachDiscount",description:"A discount to apply. Can be either a reward ID or a promotion code."})}))(_e),{CustomLineItemSchema:Tx}=(e=>({CustomLineItemSchema:e.object({amount:e.number().meta({description:"Amount in dollars for this line item (e.g. 10.50). Can be negative for credits."}),description:e.string().meta({description:"Description for the line item."})})}))(_e),{UnixMsTimestampSchema:Nx}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(_e),{CreateInvoicePreviewLineSchema:Dx}=(e=>({CreateInvoicePreviewLineSchema:e.object({plan_id:e.string().nullable(),feature_id:e.string().nullable(),description:e.string(),amount:e.number(),amount_after_discounts:e.number(),quantity:e.number().nullable(),prorated:e.boolean(),period_start:e.number().nullable(),period_end:e.number().nullable()})}))(_e),{ReissueInvoiceParamsSchema:mm}=(e=>({ReissueInvoiceParamsSchema:e.object({invoice_id:e.string().meta({description:"The Autumn invoice ID to void and replace.",example:"inv_2b3c4d5e6f7g8h"}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer and memo are applied to the replacement invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the replacement invoice. Defaults to the original invoice's due date; required when that date has already passed."}),update_customer_email:e.email().optional().meta({description:"Updates the customer's billing email before the replacement is issued, so Stripe sends the new invoice to this address."})})}))(_e),{InvoiceModeParamsSchema:Dr}=(e=>({InvoiceModeParamsSchema:e.object({enabled:e.boolean().meta({description:"When true, creates an invoice and sends it to the customer instead of charging their card immediately. Uses Stripe's send_invoice collection method."}),enable_plan_immediately:e.boolean().default(!1).meta({description:"If true, enables the plan immediately even though the invoice is not paid yet."}),finalize:e.boolean().default(!0).meta({description:"If true, finalizes the invoice so it can be sent to the customer. If false, keeps it as a draft for manual review."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer (e.g. bank details) is applied to the invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the invoice before it is due (Stripe days_until_due)."})}).meta({title:"InvoiceMode",description:"Invoice mode configuration. Creates an invoice instead of charging the card immediately."})}))(_e),{InvoiceTemplateSchema:Fx}=(e=>({InvoiceTemplateSchema:e.object({id:e.string().meta({description:"Unique identifier for the invoice template."}),name:e.string().meta({description:"User-defined name to distinguish this template when sending an invoice."}),footer:e.string().optional().meta({description:"Footer text rendered on the invoice, typically bank details so customers can pay directly."}),memo:e.string().optional().meta({description:"Memo shown near the top of the invoice (Stripe invoice description), e.g. a contact line for payment questions."}),net_terms_days:e.number().int().positive().optional().meta({description:"Default number of days the customer has to pay before the invoice is due. Overridable when sending."}),created_at:e.number().optional().meta({description:"Timestamp (ms) when the template was created."})})}))(_e),{BasePriceSchema:Mx}=((e,t,n)=>({BasePriceSchema:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),interval:e.enum(t).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),display:n.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(_e,om,bx),{CURRENCY_CODES:qx}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(am,Sx,Ix),{ApiPriceProcessorsSchema:fm}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(_e,vx),{AllocatedBillingFieldSchema:Ux}=((e,t)=>({AllocatedBillingFieldSchema:e.enum(t).optional().meta({internal:!0,description:"How an allocated usage_based price bills mid-cycle quantity changes. 'arrear' (default) bills at period end. 'prorated_legacy' is only returned for prices still on the legacy immediate-proration behavior; omit it to migrate the price to 'arrear'."})}))(_e,Px),{CreditDimensionNameSchema:Bx}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(_e,Cx,_x),{ApiCreditMatchSchema:gm}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Ex),{findCreditTierViolations:Vx}=(e=>({findCreditTierViolations:n=>{let r=[],i=(o,s)=>r.push({index:o,reason:s,message:e[s]}),a=0;for(let[o,s]of n.entries()){let c=o===n.length-1;if(s==="inf"){c||i(o,"non_final_infinity");continue}(!Number.isFinite(s)||s<=a)&&i(o,"not_increasing"),a=s,c&&i(o,"final_not_infinity")}return r}}))(Rx),{ApiCreditMultiplierSchema:Lx}=((e,t)=>({ApiCreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional().meta({description:"Multiplies the matched rate. All matching multipliers stack."}),add:e.number().optional().meta({description:"Added to the rate after every factor is applied, in credits per billing-unit group."})}).strict().refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(_e,gm),{ProviderMarkupsSchema:zx}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(_e,dm),{InvoiceFeatureQuantitySchema:hm}=((e,t,n)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(t).meta({description:"Which of the feature's prices to use: 'prepaid' or 'usage_based'."}),quantity:e.number().nonnegative().optional().meta({description:"Billable feature units in total, exclusive of any included usage. Not per seat or per entity. For a credit-system feature this is the number of credits."}),usage:e.array(n).optional().meta({description:"For credit-system features: billable units of the source features, converted through the credit rate card. Mutually exclusive with quantity."}),prorate:e.boolean().optional().meta({description:"Whether to prorate this line against period_start / period_end. Defaults to true for prepaid and false for usage-based."})}).strict().refine(i=>i.quantity!==void 0!=(i.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(_e,um,jx),{CreateInvoicePreviewSchema:kc}=((e,t)=>({CreateInvoicePreviewSchema:e.object({currency:e.string(),lines:e.array(t),subtotal:e.number(),discount_total:e.number(),tax:e.object({total:e.number(),amount_inclusive:e.number(),amount_exclusive:e.number(),status:e.enum(["complete","incomplete"])}).nullable(),total:e.number(),due_date:e.number().nullable()})}))(_e,Dx),{SUPPORTED_SET:$x}=(e=>({SUPPORTED_SET:new Set(e)}))(qx),{ApiCreditDimensionBaseSchema:Gx}=((e,t)=>({ApiCreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(_e,gm),{refineGraduatedTiers:ym}=(e=>({refineGraduatedTiers:(n,r)=>{let i=e(n.tiers.map(a=>a.to));for(let{index:a,message:o}of i)r.addIssue({code:"custom",message:o,path:["tiers",a,"to"]})}}))(Vx),{ApiFeatureMarkupsOverrideSchema:Kx}=((e,t,n)=>({ApiFeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional().meta({description:"Default percentage markup for customers on this plan. Use -100 to make usage free."}),provider_markups:t.meta({description:"Per-provider markup percentages for customers on this plan."}),model_markups:n.meta({description:"Per-model markup overrides for customers on this plan."})})}))(_e,zx,kx),{isValidCurrencyCode:Hx}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))($x),{ApiCreditDimensionSchema:Qx}=((e,t,n,r)=>({ApiCreditDimensionSchema:e.union([t.extend({tier_behavior:e.literal("graduated"),tiers:e.array(n).min(1)}).strict().superRefine(r),t.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(_e,Gx,lm,ym),{CurrencyCodeSchema:Am}=((e,t)=>({CurrencyCodeSchema:e.string().refine(t,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(_e,Hx),{AdditionalCurrencyTierSchema:Jx}=((e,t)=>({AdditionalCurrencyTierSchema:e.object({currency:t,amount:e.number().optional().meta({description:"Per-unit amount for this tier in this currency."}),flat_amount:e.number().optional().meta({description:"Flat amount for this tier in this currency, if the tier uses one."})}).refine(r=>r.amount!==void 0||r.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(_e,Am),{ApiCreditSchemaItemBaseSchema:bm}=((e,t,n,r)=>({ApiCreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string().nonempty().meta({description:"ID of the metered feature that draws from this credit system."}),billing_units:e.number().positive().optional().meta({description:"Number of metered-feature units priced together. Defaults to one when omitted."}),dimensions:e.record(t,n).optional().meta({description:"Named rates chosen by event properties. The most specific match sets the rate; with no match the item's own rate applies."}),multipliers:e.record(t,r).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(_e,Bx,Qx,Lx),{ApiFlatCreditSchemaItemSchema:Zx}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(bm,_e),{AdditionalCurrencyPriceSchema:Wx}=((e,t)=>({AdditionalCurrencyPriceSchema:e.object({currency:t,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(_e,Am),{AdditionalCurrencyTierArraySchema:Yx}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(_e,Jx,sm,cm),{ApiGraduatedCreditSchemaItemSchema:Xx}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(bm,_e,lm,ym),{AdditionalCurrencyPriceArraySchema:xm}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(_e,Wx,sm,cm),{ApiUsageTierWithCurrenciesSchema:eS}=((e,t,n)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:n.optional().meta({description:"Per-currency amounts for this tier. Tier boundaries ('to') are shared across all currencies."})}).refine(i=>i.amount!==void 0||i.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(i=>({...i,amount:i.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:n.optional()}))}))(_e,wx,Yx),{ApiCreditSchemaItemSchema:tS}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(_e,Xx,Zx),{BasePriceParamsSchema:nS}=((e,t,n,r)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:t({schema:n.number().optional(),defaultValue:1,description:"Number of intervals per billing cycle. Defaults to 1."}),additional_currencies:r.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),base_currency:n.string().optional().meta({internal:!0}),entitlement_id:n.string().optional().meta({internal:!0}),price_id:n.string().optional().meta({internal:!0}),stripe_price_id:n.string().optional().meta({description:"Stripe price id this base price is billed under. Set by sync flows to capture the actual Stripe price when it differs from the catalog default.",internal:!0})}).meta({title:"BasePrice",description:"Base price configuration for a plan."})}))(Mx,xx,_e,xm),{PlanItemPriceParamsSchema:rS}=((e,t,n,r,i,a,o)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(c=>c??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:t.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(i).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(a).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:o,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(_e,xm,eS,Ox,om,um,Ux),{ApiFeatureOverrideSchema:iS}=((e,t,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(t).optional().meta({description:"For credit system features: replaces the feature's credit_schema entirely for customers on this plan."}),markups:n.optional().meta({description:"For AI credit system features: replaces the feature's markup chain entirely for customers on this plan. An unset level means no markup at that level rather than inheriting the feature's."})})}))(_e,tS,Kx),{InvoiceBasePriceParamsSchema:Sm}=((e,t)=>({InvoiceBasePriceParamsSchema:e.pick({amount:!0,interval:!0,interval_count:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(nS,fm),{InvoiceItemPriceParamsSchema:oS}=((e,t)=>({InvoiceItemPriceParamsSchema:e.pick({amount:!0,tiers:!0,tier_behavior:!0,interval:!0,interval_count:!0,billing_units:!0,billing_method:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(rS,fm),{InvoiceLicenseQuantitySchema:aS}=((e,t,n)=>({InvoiceLicenseQuantitySchema:e.object({license_plan_id:e.string().meta({description:"The license plan linked to the parent plan."}),quantity:e.number().int().nonnegative().meta({description:"Billable seats, exclusive of any included seats."}),customize:e.object({price:t.nullable().optional()}).strict().optional().meta({description:"Override the license's per-seat price on this invoice."}),feature_quantities:e.array(n).optional().meta({description:"Feature charges priced through the license plan."}),prorate:e.boolean().optional().meta({description:"Whether to prorate seat charges against period_start / period_end. Defaults to true."})}).strict()}))(_e,Sm,hm),{InvoiceCustomizeItemSchema:sS}=((e,t,n)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:t.optional().meta({description:"Pricing to use for this feature on this invoice."}),feature_override:n.pick({credit_schema:!0}).strict().optional().meta({description:"For credit-system features: a credit rate card to use when converting `usage` on this invoice."})}).strict()}))(_e,oS,iS),{InvoiceCustomizeSchema:cS}=((e,t,n)=>({InvoiceCustomizeSchema:e.object({price:t.nullable().optional().meta({description:"Override the plan's base price for this invoice. Pass null or an amount of 0 to omit the base price line."}),items:e.array(n).optional().meta({description:"Override feature pricing for this invoice. Only pricing fields are accepted; grants, resets and rollovers are not part of an invoice."})}).strict().meta({title:"InvoiceCustomize",description:"Pricing overrides applied to this invoice only. The catalog and the customer's plan are not changed."})}))(_e,Sm,sS),{InvoicePlanParamsSchema:uS}=((e,t,n,r,i)=>({InvoicePlanParamsSchema:e.object({plan_id:e.string().meta({description:"The catalog plan (or variant) whose pricing to use."}),version:e.number().optional().meta({description:"Plan version. Defaults to the active version."}),customize:t.optional(),feature_quantities:e.array(n).optional(),license_quantities:e.array(r).optional(),discounts:e.array(i).optional().meta({description:"Discounts applied only to this plan's lines."}),prorate:e.boolean().optional().meta({description:"Whether to prorate the base price against period_start / period_end. Defaults to true."})}).strict()}))(_e,cS,hm,aS,pm),{CreateInvoiceParamsSchema:yi}=((e,t,n,r,i)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(t).optional(),custom_line_items:e.array(n).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(r).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:i.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start \u2192 period_end against one price interval starting at period_start."}),period_end:i.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(o=>o.period_start===void 0==(o.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(o=>o.period_start===void 0||o.period_end===void 0||o.period_end>o.period_start,{message:"period_end must be after period_start."})}))(_e,uS,Tx,pm,Nx);var wm=p.strictObject({requestId:p.uuid(),predecessorOperationId:p.uuid().optional(),invoiceMode:Dr.optional(),entityId:p.uuid().optional(),billingSubscriptionId:p.uuid().optional(),newBillingSubscription:p.literal(!0).optional(),offerId:p.uuid().optional(),nativeOffer:hi.optional(),plans:p.array(p.strictObject({productVersionId:p.uuid(),seatQuantities:p.record(Ko,p.number().int().min(0).max(1e4)).optional(),featureQuantities:p.record(p.uuid(),p.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100,"At most 100 feature quantities").optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Plan versions must be unique"),provider:p.enum(["stripe","apple","google","merchant"]),currency:Ie}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||["apple","google"].includes(e.provider)&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||["stripe","merchant"].includes(e.provider)&&!e.billingSubscriptionId,"A new billing subscription has no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),Mr=p.strictObject({operationId:p.uuid()}),Dt=p.number().int().min(0).max(1e8),lS=p.strictObject({lineId:p.uuid(),productVersionId:p.uuid(),productName:p.string().min(1).max(80),interval:p.enum(["free","week","month","year","one_time"]),intervalCount:p.number().int().min(1).max(156).optional(),baseAmountMinor:Dt,seats:p.array(p.strictObject({key:Ko,quantity:p.number().int().min(0).max(1e4),includedQuantity:p.number().int().min(0).max(1e4),maximumQuantity:p.number().int().min(0).max(1e4),unitAmountMinor:Dt})).max(20),prepaid:p.array(dp).max(100).optional(),catalogAmountMinor:Dt,trial:p.strictObject({days:p.number().int().min(1).max(730),cardRequired:p.boolean()}).nullable()}).refine(e=>new Set(e.seats.map(t=>t.key)).size===e.seats.length&&e.seats.every(t=>t.quantity>=t.includedQuantity&&t.quantity<=t.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((t,n)=>t+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((t,n)=>t+Wo({quantity:n.quantity,unitAmountMinor:n.unitAmountMinor,...n.pricing===void 0?{}:{pricing:n.pricing}}),0)===e.catalogAmountMinor,"Quote must retain its published base price and component quantities"),Om=p.string().regex(/^[A-Za-z0-9_-]{1,200}$/),dS=p.strictObject({id:Om,name:p.string().min(1).max(40),percent_off:p.number().gt(0).max(100).optional(),amount_off:p.number().int().positive().optional(),currency:p.string().regex(/^[a-z]{3}$/).optional(),duration:p.enum(["once","repeating","forever"]),duration_in_months:p.number().int().min(1).max(36).optional()}).refine(e=>e.percent_off===void 0!=(e.amount_off===void 0)&&e.amount_off===void 0==(e.currency===void 0)&&e.duration==="repeating"==(e.duration_in_months!==void 0),"A Stripe coupon has one percentage or amount and months only when repeating"),pS=p.strictObject({subscriptionId:p.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:p.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:p.array(p.strictObject({id:p.string(),price_id:p.string(),quantity:p.number().int().nonnegative(),discounts:p.array(p.strictObject({id:p.string(),coupon:p.string(),start:p.number(),end:p.number().nullable()})).optional()})).min(1).max(100),prorationDate:p.number().int().nonnegative(),amountMinor:p.number().int().positive(),periodStartMs:p.number(),periodEndMs:p.number()}),Pm=p.strictObject({invoiceMode:Dr.optional(),append:pS.optional(),provider:p.literal("stripe"),executor:p.enum(["indiana","merchant"]),accountId:p.string().regex(/^acct_[A-Za-z0-9]+$/),mode:p.enum(["payment","subscription"]),lineItems:p.array(p.strictObject({price:p.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:p.number().int().min(1).max(1e4),priceId:p.uuid(),productName:p.string().min(1).max(80),amountMinor:p.number().int().min(0).max(1e8),currency:p.string().regex(/^[a-z]{3}$/),interval:p.enum(["week","month","year","one_off"]),intervalCount:p.number().int().min(1).max(52),slot:p.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:p.strictObject({mode:p.enum(["graduated","volume"]),tiers:p.array(p.strictObject({upTo:p.number().int().min(1).max(1e6).nullable(),unitAmountMinor:p.number().int().min(0).max(1e8),flatAmountMinor:p.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:p.array(p.strictObject({coupon:Om,terms:dS})).max(1),trialPeriodDays:p.number().int().min(1).max(730).nullable(),metadata:p.strictObject({grooveCheckoutId:p.uuid(),grooveCustomerId:p.uuid()}),expiresAt:p.iso.datetime({offset:!0})}),Ai=p.strictObject({operationId:p.uuid(),entityId:p.uuid().nullable(),billingSubscriptionId:p.uuid().nullable(),discount:p.strictObject({offerId:p.uuid(),couponId:p.uuid(),discount:nr,duration:sn,amountMinor:Dt,allocations:p.array(p.strictObject({productVersionId:p.uuid(),amountMinor:Dt})).min(1).max(20),expiresAt:p.iso.datetime({offset:!0})}).nullable(),charge:p.strictObject({effectiveAt:p.iso.datetime({offset:!0}),periodEndsAt:p.iso.datetime({offset:!0}),debitMinor:Dt,discountMinor:Dt,taxMinor:Dt,totalMinor:Dt}).nullable(),expiresAt:p.iso.datetime({offset:!0}),provider:p.enum(["stripe","apple","google","merchant"]),nativeOffer:hi.optional(),currency:Ie,lines:p.array(lS).min(1).max(20),catalogAmountMinor:Dt,automaticTax:p.boolean(),execution:p.union([Pm,Vo]).nullable()}).refine(e=>e.provider==="merchant"?e.execution?.provider==="merchant"&&e.execution.operationId===e.operationId&&e.execution.catalogAmountMinor===e.catalogAmountMinor&&e.execution.currency===e.currency&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&e.execution.discount?.grantId===e.discount?.offerId:e.provider==="stripe"?e.execution?.provider!=="merchant"&&(e.lines[0]?.trial?.cardRequired===!1&&!e.execution?.invoiceMode?.enabled?e.execution===null&&e.discount===null:e.execution!==null&&e.execution.metadata.grooveCheckoutId===e.operationId&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.mode===(e.lines.some(t=>!["one_time","free"].includes(t.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(t=>t.price!==null))&&e.execution.discounts.every(t=>t.coupon===t.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(t=>e.discount!==null&&(t.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&t.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${t.terms.amount_off}`&&t.terms.amount_off===e.discount.discount.amountOffCents&&t.terms.currency?.toUpperCase()===e.currency&&t.terms.duration==="once"))):e.execution===null,"Stripe execution must carry the quote identity, expiry, mode, trial and held coupon").refine(e=>(!e.discount||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.discount.duration.type==="once")&&e.discount.amountMinor<=e.catalogAmountMinor&&e.discount.allocations.length===e.lines.length&&e.discount.allocations.every((t,n)=>{let r=e.lines[n];return r!==void 0&&t.productVersionId===r.productVersionId&&t.amountMinor<=r.catalogAmountMinor})&&e.discount.allocations.reduce((t,n)=>t+n.amountMinor,0)===e.discount.amountMinor)&&(["stripe","merchant"].includes(e.provider)?e.nativeOffer===void 0:e.nativeOffer!==void 0&&e.lines.length===1&&e.nativeOffer.discountMinor<=e.catalogAmountMinor&&e.nativeOffer.trialDays===(e.lines[0]?.trial?.days??null)&&(!e.discount||e.nativeOffer.discountMinor===e.discount.amountMinor))&&(!e.charge||e.billingSubscriptionId!==null&&e.charge.totalMinor===e.charge.debitMinor-e.charge.discountMinor+e.charge.taxMinor&&e.charge.discountMinor<=e.charge.debitMinor&&Date.parse(e.charge.periodEndsAt)>Date.parse(e.charge.effectiveAt))&&new Set(e.lines.map(t=>t.lineId)).size===e.lines.length&&e.lines.reduce((t,n)=>t+n.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),bi=p.strictObject({operationId:p.uuid(),orderId:p.uuid(),append:p.boolean().optional(),invoiceMode:p.boolean().optional(),status:p.enum(["pending","complete","cancelled","failed"]),executor:p.enum(["indiana","merchant"]),checkoutUrl:p.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:p.union([Pm,Vo]).nullable(),currency:Ie,catalogAmountMinor:Dt,taxMinor:Dt,totalMinor:p.number().int().min(0).max(2e8).nullable(),quoteFinalized:p.boolean(),nativePurchase:Rc.nullable(),confirmedAt:p.iso.datetime({offset:!0}).nullable().optional(),quote:Ai.optional(),merchantExecution:vr.nullable().optional(),problem:Ui.nullable().optional(),authority:Go.optional()}).refine(e=>(e.checkoutUrl===null||e.executor==="indiana"||e.merchantExecution?.type==="purchase")&&(e.execution===null||e.executor==="merchant"),"Only Indiana-executed purchases carry a Checkout URL and only record-only purchases carry execution instructions"),_a=p.strictObject({enabled:p.literal(!0),featureIds:p.array(p.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),Cm=p.strictObject({requestId:p.uuid(),invoiceMode:Dr.optional(),membershipId:p.uuid(),carryOverBalances:_a.optional(),carryOverUsages:_a.optional(),membershipIds:p.array(p.uuid()).min(1).max(20).optional(),prorationBehavior:p.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:p.enum(["immediate","renewal","store"]),change:p.discriminatedUnion("type",[p.strictObject({type:p.literal("plan"),productVersionId:p.uuid()}),p.strictObject({type:p.literal("seats"),licenseKey:Ko,quantity:p.number().int().min(0).max(1e4)}),p.strictObject({type:p.literal("quantity"),internal_feature_id:p.uuid(),quantity:p.number().int().min(0).max(1e4)}),p.strictObject({type:p.literal("cancel")}),p.strictObject({type:p.literal("uncancel")}),p.strictObject({type:p.literal("billing_cycle"),billingCycleAnchor:p.union([p.literal("now"),p.number().int().positive().max(0xe677d21fdbff)])})])}).refine(e=>e.timing!=="store"||e.change.type==="plan","Store timing applies to a native plan replacement").refine(e=>e.change.type!=="billing_cycle"||e.timing===(e.change.billingCycleAnchor==="now"?"immediate":"renewal"),"Use immediate for now and renewal for a future millisecond anchor").refine(e=>!e.membershipIds||["cancel","uncancel"].includes(e.change.type)&&e.membershipIds.includes(e.membershipId)&&new Set(e.membershipIds).size===e.membershipIds.length,"Grouped actions require unique cancel/uncancel targets including the primary membership").refine(e=>!e.carryOverBalances&&!e.carryOverUsages||e.change.type==="plan"&&e.timing==="immediate","Carry applies only to immediate upgrades").refine(e=>!e.prorationBehavior||e.change.type==="quantity","prorationBehavior applies to prepaid quantity changes"),Ca=p.string().regex(/^price_[A-Za-z0-9]+$/),Im=p.strictObject({grooveUpdateId:p.uuid(),grooveCustomerId:p.uuid()}),vm=p.strictObject({price:Ca.nullable(),priceId:p.uuid().optional(),quantity:p.number().int().min(0).max(1e4)}),_m=p.strictObject({provider:p.literal("stripe"),invoiceMode:Dr.optional(),executor:p.enum(["indiana","merchant"]),accountId:p.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:p.string().regex(/^sub_[A-Za-z0-9]+$/),action:p.enum(["update","cancel","schedule","release"]),update:p.strictObject({items:p.array(vm).max(20),remove:p.array(Ca).max(20),restoreItems:p.array(p.strictObject({price:Ca,quantity:p.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:p.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:p.number().int().positive().optional(),paymentBehavior:p.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:p.boolean().optional(),clearCancelAt:p.literal(!0).optional(),billingCycleAnchorNow:p.literal(!0).optional(),metadata:Im}).nullable(),cancel:p.strictObject({prorate:p.literal(!1),invoiceNow:p.literal(!1)}).nullable(),schedule:p.strictObject({currentItems:p.array(p.strictObject({price:Ca,quantity:p.number().int().min(0).max(1e4)})).max(20),nextItems:p.array(vm).min(1).max(20),switchAt:p.number().int().positive(),interval:p.enum(["week","month","year"]),intervalCount:p.number().int().min(1).max(52),resetBillingCycleAnchor:p.literal(!0).optional(),metadata:Im}).nullable(),release:p.strictObject({schedule:p.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:p.iso.datetime({offset:!0})}).refine(e=>["update","cancel","schedule","release"].every(t=>e[t]!==null==(e.action===t))&&(e.executor==="indiana"||[...e.update?.items??[],...e.schedule?.nextItems??[]].every(t=>t.price!==null)),"Stripe update execution carries exactly its action, with bound Prices for the merchant"),Ea=p.strictObject({carryOverBalances:_a.optional(),carryOverUsages:_a.optional(),operationId:p.uuid(),membershipId:p.uuid(),productVersionId:p.uuid(),timing:p.enum(["immediate","renewal"]),effectiveAt:p.iso.datetime({offset:!0}),expiresAt:p.iso.datetime({offset:!0}),currency:Ie,creditMinor:Dt,debitMinor:Dt,discountMinor:Dt,taxMinor:Dt,totalMinor:Dt,retainedProductVersionIds:p.array(p.uuid()).max(19),execution:p.union([_m,Lo])}),mS=p.strictObject({operationId:p.uuid(),invoiceMode:p.boolean().optional(),membershipId:p.uuid(),productVersionId:p.uuid(),status:p.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:p.enum(["immediate","renewal"]),effectiveAt:p.iso.datetime({offset:!0}),checkoutUrl:p.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:p.enum(["indiana","merchant"]),execution:p.union([_m,Lo]).nullable(),confirmedAt:p.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:vr.nullable().optional(),problem:Ui.nullable().optional(),quote:Ea.optional(),authority:Go.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),fS=p.strictObject({operationId:p.uuid(),membershipId:p.uuid(),productVersionId:p.uuid(),timing:p.literal("store"),effectiveAt:p.null(),expiresAt:p.iso.datetime({offset:!0}),currency:Ie,creditMinor:p.null(),debitMinor:p.null(),discountMinor:p.null(),taxMinor:p.null(),totalMinor:p.null(),retainedProductVersionIds:p.array(p.uuid()).max(19),store:p.strictObject({provider:p.enum(["apple","google"]),productId:p.string().min(1).max(255),catalogAmountMinor:Dt,policy:p.enum(["apple_store","google_full_price"])})}),gS=p.strictObject({operationId:p.uuid(),membershipId:p.uuid(),productVersionId:p.uuid(),status:p.enum(["prepared","pending","effective","cancelled","failed"]),timing:p.literal("store"),effectiveAt:p.iso.datetime({offset:!0}).nullable(),checkoutUrl:p.null(),nativePurchase:Rc.nullable()}),Em=p.union([Ea,fS]),jc=p.union([mS,gS]),uo=p.number().int().positive().max(2e8),Fr=p.number().int().min(0).max(2e8),Rm=p.strictObject({requestId:p.uuid(),invoiceId:p.uuid(),mode:p.enum(["full","partial"]),amountMinor:uo.optional(),entitlementAction:p.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),km=p.strictObject({provider:p.literal("stripe"),executor:p.enum(["indiana","merchant"]),accountId:p.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:p.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:uo,currency:p.string().regex(/^[a-z]{3}$/),metadata:p.strictObject({indianaRefundId:p.uuid()}),idempotencyKey:p.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:p.array(p.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),Tc=p.strictObject({operationId:p.uuid(),invoiceId:p.uuid(),providerInvoiceId:p.string().min(1).max(200),currency:Ie,paidMinor:Fr,refundedMinor:Fr,pendingMinor:Fr,amountMinor:uo,mode:p.enum(["full","partial"]),entitlementAction:p.enum(["retain","revoke"]),revokes:p.strictObject({customerProductIds:p.array(p.uuid()).max(100),subscriptionIds:p.array(p.string().min(1).max(200)).max(20)}),execution:p.union([km,zo]),expiresAt:p.iso.datetime({offset:!0})}).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&(e.execution.provider==="merchant"?e.execution.merchantInvoiceId===e.providerInvoiceId&&e.execution.operationId===e.operationId&&e.execution.currency===e.currency:e.execution.invoice===e.providerInvoiceId&&e.execution.metadata.indianaRefundId===e.operationId&&e.execution.currency===e.currency.toLowerCase())&&(e.entitlementAction==="revoke"||e.revokes.customerProductIds.length===0&&e.revokes.subscriptionIds.length===0),"Refund quote must stay within the refundable amount and match its execution"),Ra=p.strictObject({operationId:p.uuid(),invoiceId:p.uuid(),providerInvoiceId:p.string().min(1).max(200),status:p.enum(["quoted","pending","succeeded","failed","expired"]),executor:p.enum(["indiana","merchant"]),currency:Ie,amountMinor:uo,mode:p.enum(["full","partial"]),entitlementAction:p.enum(["retain","revoke"]),refundId:p.string().min(1).max(200).nullable(),quote:Tc.optional(),execution:p.union([km,zo]).nullable(),confirmedAt:p.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:vr.nullable().optional(),problem:Ui.nullable().optional(),authority:Go.optional(),failureReason:p.string().min(1).max(200).nullable(),createdAt:p.iso.datetime({offset:!0}),completedAt:p.iso.datetime({offset:!0}).nullable()}).refine(e=>(e.execution===null||e.executor==="merchant"&&e.status==="quoted")&&(e.status!=="succeeded"||e.refundId!==null),"Only quoted record-only refunds carry instructions; a succeeded refund names its Stripe refund"),g_=p.strictObject({invoiceId:p.uuid(),currency:Ie,paidMinor:Fr,refundedMinor:Fr,pendingMinor:Fr,refundableMinor:Fr,executor:p.enum(["indiana","merchant"]).nullable(),canRefund:p.boolean(),operations:p.array(Ra).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),h_=p.strictObject({requestId:p.uuid(),mode:p.enum(["full","partial"]),amountMinor:uo.optional(),entitlementAction:p.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount");var jm=at.strictObject({requestId:at.uuid(),targets:at.array(at.strictObject({membershipId:at.uuid(),action:at.enum(["cancel","uncancel"]),timing:at.enum(["immediate","renewal"])}).refine(e=>e.action!=="uncancel"||e.timing==="immediate","Restoration is immediate")).min(1).max(100)}).refine(e=>new Set(e.targets.map(t=>t.membershipId)).size===e.targets.length,"Duplicate batch target"),ka=at.strictObject({batchId:at.uuid()}),hS=at.strictObject({operationId:at.uuid(),membershipIds:at.array(at.uuid()).min(1).max(20),provider:at.enum(["stripe","apple","google"]),action:at.enum(["cancel","uncancel"]),timing:at.enum(["immediate","renewal"]),status:at.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:Ea.nullable(),managementUrl:at.url().nullable(),failureCode:at.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),lo=at.strictObject({batchId:at.uuid(),ready:at.boolean(),status:at.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:at.iso.datetime({offset:!0}),acceptedAt:at.iso.datetime({offset:!0}).nullable(),groups:at.array(hS).min(1).max(100)});import{z as je}from"zod";var yS=je.string().trim().min(1).max(240),Nc={requestId:je.uuid(),reason:yS},ja=je.discriminatedUnion("action",[je.strictObject({...Nc,action:je.literal("start"),productVersionId:je.uuid(),entityId:je.uuid().optional(),days:je.number().int().min(1).max(730).optional()}),je.strictObject({...Nc,action:je.literal("extend"),membershipId:je.uuid(),days:je.number().int().min(1).max(730)}),je.strictObject({...Nc,action:je.literal("end"),membershipId:je.uuid()})]),Tm=je.strictObject({operationId:je.uuid()}),Nm=je.iso.datetime({offset:!0}),AS=je.strictObject({provider:je.literal("stripe"),executor:je.enum(["indiana","merchant"]),accountId:je.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:je.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:je.union([je.literal("now"),Nm]),prorationBehavior:je.literal("none")}),Dc=je.strictObject({operationId:je.uuid(),action:je.enum(["start","extend","end"]),status:je.enum(["pending","effective"]),managedBy:je.enum(["indiana","stripe"]),membershipIds:je.array(je.uuid()).min(1).max(20),endsAt:Nm.nullable(),execution:AS.nullable()}).refine(e=>e.execution!==null==(e.managedBy==="stripe"&&e.status==="pending")&&e.action==="end"==(e.endsAt===null)&&(e.action!=="start"||e.managedBy==="indiana")&&(e.execution===null||e.execution.trialEnd==="now"==(e.action==="end")),"Only a pending Stripe trial change carries execution instructions"),I_=je.strictObject({groupId:je.uuid(),productVersionId:je.uuid(),enabled:je.boolean()});import{z as We}from"zod";var Dm=We.strictObject({requestId:We.uuid(),currency:Ie,makeDefault:We.boolean()}),Fm=We.strictObject({setupId:We.uuid()}),bS=We.strictObject({provider:We.literal("stripe"),executor:We.literal("merchant"),accountId:We.string().regex(/^acct_[A-Za-z0-9]+$/),mode:We.literal("setup"),currency:We.string().regex(/^[a-z]{3}$/),customer:We.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:We.uuid(),metadata:We.strictObject({grooveProjectId:We.uuid(),grooveEnvironmentId:We.uuid(),grooveCustomerId:We.uuid(),groovePaymentSetupId:We.uuid()}),setDefaultPaymentMethod:We.boolean(),expiresAt:We.iso.datetime({offset:!0})}),Fc=We.strictObject({id:We.uuid(),provider:We.literal("stripe"),status:We.enum(["prepared","complete","expired"]),currency:Ie,makeDefault:We.boolean(),url:We.url().nullable(),createdAt:We.iso.datetime({offset:!0}),expiresAt:We.iso.datetime({offset:!0}),completedAt:We.iso.datetime({offset:!0}).nullable(),execution:bS.nullable()});import{z as Ft}from"zod";var Mm=Ft.union([Ft.string(),Ft.number(),Ft.boolean(),Ft.null()]),qm=Ft.strictObject({customerId:Ft.uuid()}),Um=Ft.strictObject({customerId:Ft.uuid(),provider:Ft.literal("stripe"),checkedAt:Ft.iso.datetime({offset:!0}),status:Ft.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Ft.number().int().nonnegative(),differences:Ft.array(Ft.strictObject({subscriptionId:Ft.string().startsWith("sub_"),itemId:Ft.string().nullable(),field:Ft.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Mm,actual:Mm})).max(1e4)});import{z as we}from"zod";var Ta=we.iso.datetime({offset:!0}),Na=we.strictObject({createdAt:Ta,id:we.uuid()}),Da=we.strictObject({customerId:we.uuid().optional(),entityId:we.uuid().optional(),productId:we.string().min(1).max(256).optional(),provider:we.enum(["stripe","apple","google","merchant","free"]).optional(),status:we.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:Na.optional(),limit:we.number().int().min(1).max(100).optional()}),Mc={id:we.uuid(),customerId:we.uuid(),entityId:we.uuid().nullable(),productId:we.string().min(1).max(256),productVersionId:we.uuid(),name:we.string().min(1).max(120),provider:we.enum(["stripe","apple","google","merchant","free"]),createdAt:Ta},xS=we.strictObject({...Mc,status:we.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:we.boolean(),billingSubscriptionId:we.uuid().nullable()}),SS=we.strictObject({...Mc,status:we.enum(["active","ended","refunded"]),orderId:we.uuid().nullable(),transactionId:we.uuid().nullable(),currency:Ie.nullable(),amountMinor:we.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),IS=we.strictObject({...Mc,status:we.enum(["blocked","resolved"]),conflict:we.strictObject({detectedAt:Ta,blockingMembershipIds:we.array(we.uuid()).min(1).max(100),transactionId:we.uuid()}),resolvedAt:Ta.nullable()}),Bm=Da.extend({status:we.enum(["blocked","resolved"]).optional()}),Vm=we.strictObject({customerId:we.uuid(),orderId:we.uuid()}),Lm=we.strictObject({orderId:we.uuid(),status:we.enum(["blocked","resolved"])}),zm=we.strictObject({items:we.array(xS).max(100),nextCursor:Na.nullable()}),$m=we.strictObject({items:we.array(SS).max(100),nextCursor:Na.nullable()}),Gm=we.strictObject({items:we.array(IS).max(100),nextCursor:Na.nullable()});import{z as nt}from"zod";var Km=nt.union([nt.strictObject({intent:nt.literal("read"),requestId:nt.uuid(),purchaseIntentId:nt.uuid()}),nt.strictObject({requestId:nt.uuid(),provider:nt.literal("apple"),purchaseIntentId:nt.uuid(),productId:nt.string().min(1).max(255).optional(),signedTransaction:nt.string().min(1).max(131072)}),nt.strictObject({requestId:nt.uuid(),provider:nt.literal("google"),purchaseIntentId:nt.uuid(),productId:nt.string().min(1).max(255).optional(),purchaseToken:nt.string().min(1).max(16384)})]),Hm=nt.strictObject({requestId:nt.uuid(),orderId:nt.uuid(),purchaseIntentId:nt.uuid(),status:nt.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:Ie,refunded:nt.boolean(),completion:nt.strictObject({transactionIds:nt.array(nt.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:nt.boolean()}).nullable()});import{z as V}from"zod";var Uc=V.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),vS=V.record(V.string(),V.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),wS=3,po=20,OS=wS*po,qc=V.strictObject({type:V.literal("product"),productId:Uc}),Qm={type:V.literal("group"),key:V.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:V.string().trim().min(1).max(80)},PS=V.discriminatedUnion("type",[qc,V.strictObject({...Qm,items:V.array(qc).max(po)})]),CS=V.discriminatedUnion("type",[qc,V.strictObject({...Qm,items:V.array(PS).max(po)})]),_S=V.array(CS).max(po).superRefine((e,t)=>{let n=new Set,r=new Set,i=0;function a(o){for(let s of o){i++;let c=s.type==="product"?n:r,u=s.type==="product"?s.productId:s.key;c.has(u)&&t.addIssue({code:"custom",message:s.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),c.add(u),s.type==="group"&&a(s.items)}}a(e),(n.size>po||i>OS)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function Bc(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:Bc(t))}var xi=V.strictObject({lookupKey:V.string().trim().min(1).max(200),displayName:V.string().trim().min(1).max(1500),items:_S,metadata:vS}),ES=V.strictObject({product:V.record(V.string(),V.json()),prices:V.array(V.record(V.string(),V.json())),entitlements:V.array(V.record(V.string(),V.json())),freeTrials:V.array(V.record(V.string(),V.json())),licenses:V.array(V.record(V.string(),V.json()))}),Jm=xi.extend({id:V.uuid(),projectId:V.uuid(),environmentId:V.uuid(),state:V.enum(["active","archived"]),isCurrent:V.boolean(),revision:V.number().int().nonnegative(),publishedVersionId:V.uuid().nullable(),createdAt:V.iso.datetime({offset:!0})}).superRefine((e,t)=>{e.isCurrent&&(e.state!=="active"||!e.publishedVersionId)&&t.addIssue({code:"custom",message:"Current Offering must be active and published"})}),Zm=V.strictObject({id:V.uuid(),offeringId:V.uuid(),projectId:V.uuid(),environmentId:V.uuid(),version:V.number().int().positive(),document:xi,productEvidence:V.record(Uc,ES),createdAt:V.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=Bc(e.document);(!n.length||jS(e.document).length>0||Object.keys(e.productEvidence).length!==n.length||n.some(r=>!Object.hasOwn(e.productEvidence,r)))&&t.addIssue({code:"custom",message:"Published Offering requires evidence for every Product"})}),RS=V.strictObject({rows:V.array(Jm).max(200),versions:V.array(Zm).max(500)}),F_=V.discriminatedUnion("action",[V.strictObject({action:V.literal("create"),document:xi}),V.strictObject({action:V.literal("save"),id:V.uuid(),revision:V.number().int().nonnegative(),document:xi}),V.strictObject({action:V.enum(["publish","set_current","archive","restore"]),id:V.uuid(),revision:V.number().int().nonnegative()})]),M_=V.strictObject({record:Jm,version:Zm.nullable()}),Wm=V.discriminatedUnion("type",[V.strictObject({type:V.literal("current")}),V.strictObject({type:V.literal("id"),id:V.uuid()}),V.strictObject({type:V.literal("lookup_key"),lookupKey:V.string().min(1).max(200)}),V.strictObject({type:V.literal("version"),versionId:V.uuid()})]),kS=V.strictObject({internalId:Uc,id:V.string(),name:V.string().nullable(),version:V.number().int().positive(),archived:V.boolean()}),q_=RS.extend({products:V.array(kS).max(500),pagination:V.strictObject({rows:V.string().nullable(),versions:V.string().nullable(),products:V.string().nullable()}).optional()});function jS(e){let t=[];Bc(e).length||t.push("Select at least one Product before publishing");function n(r){for(let i of r)i.type==="group"&&(i.items.length||t.push("Every published group requires a Product"),n(i.items))}return n(e.items),t}import{z as Fa}from"zod";var Ym=Fa.strictObject({id:Fa.uuid(),offeringId:Fa.uuid(),version:Fa.number().int().positive(),document:xi});import{z as Ct}from"zod";import{z as ye}from"zod";import{z as Si}from"zod";var Ma=Si.strictObject({items:Si.array(Si.strictObject({productVersionId:Si.string().min(1).max(200),label:Si.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:Si.string().min(1).max(200).nullable(),grouping:Aa.optional()});function Xm(e,t,n){let r=e.type==="fixed"?e.productVersionId:t[e.pickerId];return typeof r!="string"||!Object.values(n.plans).some(i=>i.versionId===r&&i.available)||e.type==="picker"&&(!e.allowedProductVersionIds.includes(r)||!n.pickers[e.pickerId]?.options.includes(r))?null:r}var Vc=ye.discriminatedUnion("type",[ye.strictObject({type:ye.literal("event"),event:ye.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),ye.strictObject({type:ye.literal("open_url"),url:ye.url().refine(e=>new URL(e).protocol==="https:")})]),TS=un,NS=ye.discriminatedUnion("type",[ye.object({type:ye.literal("checkout"),product:xa}).strict(),ye.object({type:ye.literal("close")}).strict(),ye.object({type:ye.literal("action"),action:Vc}).strict()]),Ii=ye.object({schemaVersion:ye.literal(3),kind:ye.literal("paywall"),name:ye.string().trim().min(1).max(80),presentation:Pn,requirement:ir.optional(),products:Ma,offeringVersionId:ye.uuid().nullable(),offeringId:ye.uuid(),screen:TS,buttons:ye.record(ye.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),NS)}).strict(),X_=Ii.superRefine((e,t)=>{(e.screen.surface!=="paywall"||e.screen.actions.some(r=>!["event","navigate"].includes(r.type)||r.close))&&t.addIssue({code:"custom",message:"Paywall screen is incomplete"});for(let r of FS(e))t.addIssue({code:"custom",message:r});for(let r of DS(e))t.addIssue({code:"custom",message:r});or(e.screen).some(r=>!r.complete)&&t.addIssue({code:"custom",message:"Paywall needs complete local content"}),(Object.keys(e.buttons).length!==e.screen.actions.filter(r=>r.type!=="navigate").length||e.screen.actions.some(r=>r.type!=="navigate"&&!Object.hasOwn(e.buttons,r.id)))&&t.addIssue({code:"custom",message:"Paywall buttons require matching node policies"}),Object.values(e.buttons).some(r=>r.type==="checkout")||t.addIssue({code:"custom",message:"A paywall requires a purchase or membership change button"})});function DS(e){let t=e.products.items.map(a=>a.productVersionId),n=Bp(e.screen),r=new Set,i=[];(!t.length||!e.products.defaultProductVersionId||!t.includes(e.products.defaultProductVersionId))&&i.push("products"),e.offeringVersionId||i.push("offering"),e.products.grouping&&(!ba(e.products.grouping,t)||e.products.grouping.tiers.some(a=>!e.products.grouping.assignments.some(o=>o.tierId===a.id)))&&i.push("grouping");for(let a of Object.values(e.buttons))if(a.type==="checkout"){let o=a.product;if(o.type==="fixed")r.add(o.productVersionId);else{o.allowedProductVersionIds.forEach(u=>r.add(u));let s=!1,c=n[o.pickerId];c&&(s=!0,(o.allowedProductVersionIds.some(u=>!c.ids.includes(u))||c.ids.some(u=>!o.allowedProductVersionIds.includes(u)))&&i.push("picker")),Gt(e.screen,u=>{if(u.id!==o.pickerId||u.type!=="plan_picker")return;s=!0,(JSON.stringify(u.planIds)!==JSON.stringify(t)||JSON.stringify(o.allowedProductVersionIds)!==JSON.stringify(t)||u.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let l=u.grouping?{tiers:u.grouping.tiers,assignments:u.grouping.assignments}:void 0;JSON.stringify(l)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),s||i.push("picker")}}return(!r.size||[...r].some(a=>!t.includes(a)))&&i.push("purchase"),Gt(e.screen,a=>{a.type==="stack"&&a.productSlot&&!a.bind?.plan&&i.push(`productBinding:${a.id}`),(a.type==="stack"||a.type==="button")&&a.bind?.plan&&!t.includes(a.bind.plan)&&i.push("binding"),a.type==="plan_picker"&&(!a.planIds?.length||a.planIds.some(o=>!t.includes(o)))&&i.push("binding")}),[...new Set(i)]}function FS(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),Zn(s.root,c=>{let u=c.type==="button"?c.action:c.type==="stack"?c.purchaseAction:void 0;if(u){let l=e.screen.actions.find(f=>f.id===u);l?.type==="navigate"&&r.get(s.id).push(l.pageId);let m=e.buttons[u];s.id!==n.id&&m&&m.type!=="close"&&t.push(`purchaseScreen:${c.id}`)}s.id!==n.id&&(c.type==="plan_picker"||c.type==="stack"&&c.productSlot)&&t.push(`packageScreen:${c.id}`)});let i=new Set;function a(s){if(!i.has(s)){i.add(s);for(let c of r.get(s)??[])a(c)}}let o=e.screen.initialPageId??e.screen.pages[0]?.id;o?a(o):t.push("initialPage");for(let s of e.screen.pages)i.has(s.id)||t.push(`unreachableScreen:${s.id}`);return[...new Set(t)]}var ef=ye.object({id:ye.uuid(),projectId:ye.uuid(),environmentId:ye.uuid(),revision:ye.number().int().nonnegative(),state:ye.enum(["active","archived"]),publishedVersionId:ye.uuid().nullable(),updatedAt:ye.iso.datetime({offset:!0}),draft:Ii}).strict(),e1=ye.object({rows:ye.array(ef).max(200),nextCursor:ye.uuid().nullable()}).strict(),t1=ef.omit({draft:!0}).extend({name:ye.string(),productCount:ye.number().int().nonnegative()}).strict(),n1=ye.discriminatedUnion("action",[ye.object({action:ye.literal("save"),id:ye.uuid().nullable(),revision:ye.number().int().nonnegative(),document:Ii}).strict(),ye.object({action:ye.enum(["publish","archive"]),id:ye.uuid(),revision:ye.number().int().nonnegative()}).strict()]),r1=ye.object({paywalls:ye.array(ye.object({id:ye.uuid(),paywallId:ye.uuid(),version:ye.number().int().positive(),name:ye.string().min(1).max(80),presentation:Pn,buttons:Ii.shape.buttons}).strict()).max(500),limited:ye.boolean()}).strict();import{z as Re}from"zod";import{z as Kt}from"zod";var vi=Kt.string().regex(/^[a-f0-9]{64}$/),MS=ha.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),tf=Kt.strictObject({couponDigests:Kt.record(Kt.uuid(),vi),variables:Kt.record(In,Kt.record(Kt.uuid(),Kt.partialRecord(Kt.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),Kt.string()))),locales:Kt.record(In,li.extend({nodes:Kt.record(Kt.string(),Kt.strictObject({base:MS})),plans:Kt.object({}).strict(),pickers:Kt.object({}).strict()}).omit({paywall:!0}))});import{z as Ve}from"zod";import{z as qa}from"zod";var Lc=qa.strictObject({eventsEnabled:qa.boolean(),experimentViewsEnabled:qa.boolean(),featureUsageEnabled:qa.boolean()}),l1=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function nf(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}import{z as $}from"zod";var zc=$.tuple([$.number().min(0).max(1),$.number().min(0).max(1)]).refine(([e,t])=>e<=t),qS=$.strictObject({attribute:$.string().optional(),seed:$.string(),hashVersion:$.literal(2),ranges:$.array(zc).max(100)}),US=$.strictObject({id:$.string().min(1).max(255),condition:Yt,gate:$.boolean().optional()}),BS=$.strictObject({key:$.string().optional(),name:$.string().optional(),passthrough:$.boolean().optional()}),rf={condition:Yt.optional(),parentConditions:$.array(US).max(100).optional(),weights:$.array($.number().min(0).max(1)).max(20).optional(),coverage:$.number().min(0).max(1).optional(),hashAttribute:$.string().optional(),fallbackAttribute:$.string().optional(),hashVersion:$.literal(2).optional(),disableStickyBucketing:$.boolean().optional(),bucketVersion:$.number().int().nonnegative().optional(),minBucketVersion:$.number().int().nonnegative().optional(),filters:$.array(qS).max(100).optional(),ranges:$.array(zc).max(20).optional(),meta:$.array(BS).max(20).optional(),seed:$.string().optional(),name:$.string().optional(),phase:$.string().optional()},wi=$.strictObject({...rf,key:$.string().min(1).max(255),variations:$.tuple([ve,ve]).rest(ve).refine(e=>e.length<=20),urlPatterns:$.array($.strictObject({include:$.boolean(),type:$.enum(["regex","simple"]),pattern:$.string()})).max(100).optional(),force:$.number().int().nonnegative().optional(),active:$.boolean().optional(),persistQueryString:$.boolean().optional()}),$c=$.strictObject({value:ve,variationId:$.number().int(),key:$.string(),name:$.string().optional(),bucket:$.number().optional(),passthrough:$.boolean().optional(),inExperiment:$.boolean(),hashUsed:$.boolean().optional(),hashAttribute:$.string(),hashValue:$.string(),featureId:$.string().nullable(),stickyBucketUsed:$.boolean().optional()}),VS=$.strictObject({...rf,id:$.string().max(255).optional(),force:ve.optional(),variations:$.array(ve).min(2).max(20).optional(),key:$.string().optional(),range:zc.optional(),tracks:$.array($.strictObject({experiment:wi,result:$c})).max(100).optional()}),LS=$.strictObject({defaultValue:ve.optional(),rules:$.array(VS).max(500).optional()}),mo=$.record($.string(),$.union([$.strictObject({type:$.literal("hashed"),attributeKey:$.string(),values:$.array($.string().regex(/^[a-f0-9]{64}$/))}),$.strictObject({type:$.literal("list"),attributeKey:$.string(),values:$.array($.union([$.string(),$.number()]))}),$.strictObject({type:$.literal("condition"),condition:Yt})])),yn=$.strictObject({scope:Ne,generation:$.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:$.iso.datetime({offset:!0}),expiresAt:$.iso.datetime({offset:!0}).nullable(),features:$.record($.string(),LS),savedGroups:mo,experiments:$.record($.uuid(),wi)});var fo=yn.extend({analyticsConfig:Lc,remoteFeatures:Ve.array(Ve.string().min(1).max(255)).max(500)}),Gc=fo.omit({evaluatedAt:!0,expiresAt:!0}).superRefine((e,t)=>{for(let n of e.remoteFeatures)Object.hasOwn(e.features,n)&&t.addIssue({code:"custom",path:["features",n],message:"Remote Feature definitions cannot be public"});for(let[n,r]of Object.entries(e.savedGroups))r.type==="list"&&t.addIssue({code:"custom",path:["savedGroups",n],message:"Raw Saved Group lists cannot be public"})}),of=Ve.strictObject({attributes:wt,features:Ve.array(Ve.string().min(1).max(255)).max(500).optional(),customerId:Ve.uuid().optional()}),zS=Ve.strictObject({value:ve,source:Ve.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:Ve.boolean(),off:Ve.boolean(),ruleId:Ve.string(),experimentResult:$c.optional()}),Ua=Ve.strictObject({generation:yn.shape.generation,evaluatedAt:yn.shape.evaluatedAt,expiresAt:yn.shape.expiresAt,features:Ve.record(Ve.string(),zS),merchandiseContext:Ve.strictObject({merchandiseId:Ve.uuid(),merchandise:wt}).optional()}),af=Ve.strictObject({customerId:Ve.uuid().optional(),events:Ve.array(Ve.strictObject({eventUuid:Ve.uuid(),timestamp:Ve.iso.datetime({offset:!0}),name:Ve.string().min(1).max(255),merchandise:Bd.optional(),properties:Ve.record(Ve.string(),ve).default({}),deviceId:Ve.string().min(1).max(255).optional(),sessionId:Ve.string().min(1).max(255).optional()})).min(1).max(100)}),sf=Ve.strictObject({inserted:Ve.number().int().nonnegative(),duplicates:Ve.number().int().nonnegative(),rejected:Ve.number().int().nonnegative(),skipped:Ve.number().int().nonnegative(),analyticsConfig:Lc});import{z as L}from"zod";import{z as $S}from"zod";var cf=$S.enum(["funnel-run/1","funnel-process/1"]),uf="funnel-process/1";function Kc(e,t=[]){let n=[];Gt(e,i=>{i.hidden&&n.push("Hidden components must not be delivered"),t.includes(i.type)&&n.push(`Node type ${i.type} cannot be delivered`)});let r=new Set(Sa(e).map(i=>i.key));for(let[i,a]of Object.entries(e.strings.locales))for(let o of Object.keys(a))r.has(o)||n.push(`Unused string ${o} must not be delivered (${i})`);return n}function lf(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>lf(t)??[])}}function GS(e){let t=e.pages.map(i=>{let a=lf(i.root);return a?.type==="stack"?{...i,root:a}:{...i,root:{type:"stack",id:i.root.id,...i.root.name===void 0?{}:{name:i.root.name},direction:"vertical",align:"stretch",justify:"start",children:[]}}}),n=new Set(Sa({pages:t}).map(i=>i.key)),r=Object.fromEntries(Object.entries(e.strings.locales).map(([i,a])=>[i,Object.fromEntries(Object.entries(a).filter(([o])=>n.has(o)))]));return{...e,pages:t,strings:{...e.strings,locales:r}}}function df(e,t=[]){let n=un.parse(structuredClone(GS(e))),r=a=>a.type!=="stack"||a.interaction!==void 0||a.children.some(r);for(let a of n.pages)if(!r(a.root))throw new Error(`Page ${a.id} has no visible content`);let i=Kc(n,t);if(i.length)throw new Error(i.join("; "));return n}import{z as Q}from"zod";import{z as M}from"zod";import{z as mt}from"zod";var Ba=mt.strictObject({schemaVersion:mt.literal(1),renderKey:mt.string().min(1).max(256),routeTemplate:mt.string().startsWith("/").max(2048),selectors:mt.array(mt.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:mt.array(mt.number().int().min(0)).min(1),absent:mt.array(mt.number().int().min(0))}).superRefine((e,t)=>{let n=[...e.present,...e.absent];(new Set(e.selectors).size!==e.selectors.length||new Set(n).size!==n.length||n.length!==e.selectors.length||n.some(r=>r>=e.selectors.length))&&t.addIssue({code:"custom",message:"Incomplete or ambiguous render signature"})}),pf=mt.strictObject({renderKey:mt.string().min(1).max(256),routeKey:mt.string().min(1).max(256),stateKey:mt.string().min(1).max(256),documentKey:mt.string().min(1).max(256),documentHash:mt.string().regex(/^[a-f0-9]{64}$/),compositionKey:mt.string().min(1).max(256),entryMode:mt.enum(["hard","soft"]),match:mt.strictObject({present:mt.array(mt.number().int().min(0)),absent:mt.array(mt.number().int().min(0))})});import{z as qr}from"zod";var KS=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],Hc="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",HS=qr.string().regex(new RegExp(`^${Hc}/${Hc}/${Hc}/manifest\\.json$`)),mf=qr.strictObject({kind:qr.literal("gcs-resumable"),url:qr.url(),bucket:qr.enum(KS),objectKey:HS,byteLength:qr.number().int().positive(),expiresAt:qr.iso.datetime()}).superRefine((e,t)=>{let n=new URL(e.url),r=n.searchParams,i=["uploadType","upload_id","name","upload_protocol","ifGenerationMatch"];(n.origin!=="https://storage.googleapis.com"||n.username||n.password||n.hash||n.pathname!==`/upload/storage/v1/b/${e.bucket}/o`||[...r.keys()].some(a=>!i.includes(a)||r.getAll(a).length!==1)||r.get("uploadType")!=="resumable"||!/^[A-Za-z0-9_-]{1,4096}$/.test(r.get("upload_id")??"")||r.has("name")&&r.get("name")!==`app-manifests/${e.objectKey}`||r.has("upload_protocol")&&r.get("upload_protocol")!=="resumable"||r.has("ifGenerationMatch")&&r.get("ifGenerationMatch")!=="0")&&t.addIssue({code:"custom",message:"Invalid IAM upload capability"})});var yt=M.string().min(1).max(256),dn=M.string().regex(/^[a-f0-9]{64}$/),Va=M.strictObject({versionId:M.uuid(),manifestDigest:dn,sourceGraphDigest:dn,pageKey:yt,stateKey:yt,documentKey:yt,documentHash:dn,elementKey:yt.optional(),nodeId:yt.optional(),contentHash:dn.optional(),renderKey:yt.optional()}),ff=M.strictObject({pageKey:yt,documentKey:yt,expectedDocumentHash:dn,renderKey:yt.optional(),nodeId:yt,elementKey:yt,expectedContentHash:dn,property:M.enum(["text","fontSize","color"]),value:M.union([M.string().max(4e3),M.number().finite()])}),gf=M.strictObject({versionId:M.uuid(),manifestDigest:dn,sourceGraphDigest:dn,pageKey:yt,stateKey:yt,documentKey:yt,documentHash:dn,renderKey:yt.optional(),patches:M.array(ff.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),QS=/^[a-z][a-z0-9-]{0,39}$/,go=M.string().regex(QS),Jc=M.enum(["web","ios","android"]),T1=M.discriminatedUnion("action",[M.strictObject({action:M.literal("register"),requestId:M.uuid(),client:go,platform:Jc,label:M.string().trim().min(1).max(100),sha256:dn,bytes:M.number().int().min(1),transferBytes:M.number().int().min(1)}),M.strictObject({action:M.literal("complete"),versionId:M.uuid()}),M.strictObject({action:M.literal("current"),versionId:M.uuid(),expectedCurrent:M.uuid().nullable()}),M.strictObject({action:M.literal("delivery"),enabled:M.boolean()}),M.strictObject({action:M.literal("changes"),versionId:M.uuid(),experimentId:M.uuid(),variationId:yt,changesetId:M.uuid().nullable(),expectedRevision:dn.nullable(),editorUrl:M.string().url().max(2048),patches:M.array(ff).max(200)})]),Zc=M.strictObject({id:M.uuid(),projectId:M.uuid(),environmentId:M.uuid(),clientKey:go,platform:Jc,label:M.string(),sha256:dn,bytes:M.number().int().positive(),objectKey:M.string(),state:M.enum(["uploading","ready","rejected"]),isCurrent:M.boolean(),revision:M.number().int().nonnegative(),createdAt:M.string(),expiresAt:M.string(),readyAt:M.string().nullable(),summary:M.record(M.string(),M.json()),routeTree:M.json().nullable(),validation:M.record(M.string(),M.json())}),JS=M.strictObject({key:go,platform:Jc,currentId:M.uuid().nullable()}),N1=M.strictObject({rows:M.array(Zc).max(100),nextCursor:M.uuid().nullable(),clients:M.array(JS).max(20)}),Qc=M.strictObject({storedBytes:M.number().int().nonnegative(),reservedBytes:M.number().int().nonnegative(),chargedBytes:M.number().int().nonnegative(),versions:M.number().int().nonnegative(),objects:M.number().int().nonnegative(),orphanObjects:M.number().int().nonnegative(),missingReadyObjects:M.number().int().nonnegative(),unknownObjectSizes:M.number().int().nonnegative(),byteLimit:M.number().int().positive(),versionLimit:M.number().int().positive(),remainingBytes:M.number().int().nonnegative()}),D1=M.strictObject({asOf:M.iso.datetime({offset:!0}),reclamation:M.literal("manual-review-required"),buckets:M.strictObject({source:Qc,runtime:Qc,previews:Qc})}),F1=M.strictObject({version:Zc,actorId:M.uuid(),claims:M.record(M.string(),M.json())}),M1=M.strictObject({version:Zc,upload:mf.nullable()}),q1=M.object({format:M.literal("indiana-route-state-index"),schemaVersion:M.literal(3),routes:M.array(M.object({routeKey:yt,path:M.string(),documentKey:yt,documentHash:dn,initialStateKey:yt,initialRenderKey:yt})),renders:M.array(pf)}).loose().superRefine((e,t)=>{(!e.renders||e.routes.some(n=>!e.renders?.some(r=>r.renderKey===n.initialRenderKey&&r.routeKey===n.routeKey&&r.documentKey===n.documentKey&&r.stateKey===n.initialStateKey&&r.documentHash===n.documentHash&&r.entryMode==="hard")))&&t.addIssue({code:"custom",message:"Incomplete render catalog"})}),U1=M.strictObject({rows:M.array(M.object({id:M.uuid(),name:M.string(),status:M.string(),variations:M.array(M.object({id:yt,key:yt,name:M.string().optional()}).loose())}).loose()),limited:M.boolean()}),B1=M.strictObject({enabled:M.boolean(),allowedOrigins:M.array(M.string())});import{z as Oi}from"zod";var hf=Oi.strictObject({id:Oi.uuid(),name:Oi.string().trim().min(1).max(80),client:go,source:Va,event:Oi.enum(["screen_enter","button_click"]),cooldownSeconds:Oi.number().int().min(0).max(2592e3),behavior:Oi.literal("observe")}).superRefine((e,t)=>{e.event==="button_click"&&(!e.source.nodeId||!e.source.elementKey)&&t.addIssue({code:"custom",path:["source"],message:"Choose a uniquely bound button"})});import{z as Ke}from"zod";var Wc=ve,ZS=["parameters","answers","results","variables"];function Yc(e){return ZS.some(t=>e===t||e.startsWith(t+"."))}function Xc(e){let t={};for(let[r,i]of Object.entries(Ia(e.declarations,e))){let a=r.split(".");if(a.some(c=>["__proto__","constructor","prototype"].includes(c)))throw new Error("Reserved result path");let o=t;for(let c of a.slice(0,-1)){Object.hasOwn(o,c)||(o[c]={});let u=o[c];if(!u||typeof u!="object"||Array.isArray(u))throw new Error("Ambiguous result path");o=u}let s=a.at(-1);if(s===void 0)throw new Error("Empty result path");o[s]=i}return{...Object.fromEntries(Object.entries(e.attributes).filter(([r])=>!Yc(r))),variables:t}}import{z as At}from"zod";var La=At.discriminatedUnion("kind",[At.object({kind:At.literal("ledger"),cursor:ga}).strict(),At.object({kind:At.literal("billing"),cursor:At.uuid()}).strict()]),WS=At.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),sr=At.record(At.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),At.union([At.string().max(500),At.boolean(),At.array(At.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),YS=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function eu(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>eu(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||YS.test(n)||eu(r,t+1)))}var XS=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,cr=At.record(WS,ve).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!eu(e)&&!XS.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var yf=At.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),za=At.array(At.object({variable:yf,componentId:yf,required:At.boolean()}).strict()).max(40).refine(e=>new Set(e.map(t=>t.variable)).size===e.length&&new Set(e.map(t=>t.componentId)).size===e.length,"Input bindings must be unique"),Y1=At.object({bindings:za,answers:sr,values:At.record(At.string(),ve).optional()}).strict();import{z as e0}from"zod";var $a=e0.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var tu=Ke.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Af=Ke.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),bf=cr.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),nu=Ke.record(tu,Ke.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),t0=Fn,xf=Ke.strictObject({type:Ke.literal("external_task"),endpointId:Ke.uuid(),taskKey:tu,inputs:Ke.record(tu,t0).refine(e=>Object.keys(e).length<=20),outputs:nu}),Sf=Ke.strictObject({maxAttempts:Ke.number().int().min(1).max(5),retryDelaySeconds:Ke.number().int().min(1).max(30),backoff:Ke.enum(["fixed","exponential"]),requestTimeoutSeconds:Ke.number().int().min(1).max(10),timeoutSeconds:Ke.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var cE=Ke.strictObject({outcome:Ke.enum(["success","failure"]),data:bf});var uE=Ke.discriminatedUnion("operation",[Ke.strictObject({operation:Ke.literal("signal"),runId:Ke.uuid(),nodeId:Af,eventName:$a,eventId:Ke.uuid(),data:bf}),Ke.strictObject({operation:Ke.literal("read_results"),runId:Ke.uuid()})]),lE=Ke.strictObject({scope:Ne,runId:Ke.uuid(),eventId:Ke.uuid(),accepted:Ke.boolean()}),n0=Ke.record(Af,Wc),dE=Ke.strictObject({scope:Ne,runId:Ke.uuid(),results:n0});var Rn={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},If="00000000-0000-0000-0000-000000000000";import{z as Z}from"zod";import{z as Ye}from"zod";var yE=Ye.enum(["local","remote"]),ru=Ye.strictObject({port:Ye.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:ve.optional(),sticky:Ye.array(Ye.strictObject({expected:$i.nullable(),next:$i})).max(100),exposures:Ye.array(ve).max(100),features:Ye.array(ve).max(100)}),vf=Ye.strictObject({type:Ye.literal("evaluate"),receiptId:Ye.uuid(),environmentId:Ye.uuid(),policyRevision:Ye.number().int().nonnegative(),attributes:wt,sticky:Ye.record(Ye.string(),$i)}),wf=vf.extend({runId:Ye.uuid(),versionId:Ye.uuid(),nodeId:Ye.string().min(1).max(64),visit:Ye.number().int().nonnegative(),revision:Ye.number().int().nonnegative()}),iu=vf.omit({type:!0,receiptId:!0}).extend({type:Ye.literal("evaluate_segment")}),Of=Ye.strictObject({nodeId:Ye.string().min(1).max(64),result:ru}),Pf=iu.extend({runId:Ye.uuid(),versionId:Ye.uuid(),nodeId:Ye.string().min(1).max(64),visit:Ye.number().int().nonnegative(),revision:Ye.number().int().nonnegative(),parameters:cr,answers:sr,variables:Ye.record(Ye.string(),ve)});import{z as ue}from"zod";var ou=ue.array(ue.string().trim().min(1).max(40).refine(e=>!e.includes(","),"\u6807\u7B7E\u4E0D\u80FD\u5305\u542B\u9017\u53F7")).max(20).refine(e=>new Set(e).size===e.length,"\u6807\u7B7E\u4E0D\u80FD\u91CD\u590D"),Ga=ue.intersection(wt,ue.looseObject({tags:ou.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),Ka=ue.string().trim().max(80),Ha=ue.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),Qa=ue.union([ue.email().max(254),ue.literal("")]),Ja=ue.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),Cf=ue.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),_f=ue.object({externalUserId:Cf.optional(),name:Ka.default(""),email:Qa.default(""),phone:Ha.optional(),attributes:Ga.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),Ur=ue.discriminatedUnion("type",[ue.strictObject({type:ue.literal("id"),value:ue.uuid()}),ue.strictObject({type:ue.literal("externalUserId"),value:Cf})]),Pi=ue.strictObject({name:Ka.optional(),email:Qa.optional(),phone:Ha.optional(),attributes:Ga.optional(),fingerprint:Ja.optional()}),Za=e=>!e.customerData||e.customer?.type==="externalUserId",Wa="customerData requires an externalUserId customer",Ci=ue.object({id:ue.uuid(),externalUserId:ue.string().min(1).max(255).nullable(),name:Ka,email:Qa,phone:Ha.optional(),attributes:Ga,createdAt:ue.iso.datetime()}).strict(),Ef=ue.object({customer:Ci,changed:ue.boolean(),replayed:ue.boolean()}).strict(),r0=ue.discriminatedUnion("type",[ue.object({type:ue.literal("id"),value:ue.uuid()}).strict(),ue.object({type:ue.literal("externalUserId"),value:ue.string().trim().min(1).max(255)}).strict()]),i0=ue.object({name:Ka.optional(),email:Qa.optional(),phone:Ha.optional(),attributes:Ga.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:ue.array(ue.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:ue.strictObject({add:ou,remove:ou}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),au=ue.object({lookup:r0}).strict(),Rf=au.extend({requestId:ue.uuid(),patch:i0}).strict(),kf=ue.object({search:ue.string().trim().max(200).default(""),tag:ue.string().trim().max(40).default(""),planId:ue.string().max(200).default(""),versionId:ue.string().max(200).default(""),holdingStatus:ue.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:ue.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:ue.union([ue.iso.datetime(),ue.literal("")]).default(""),createdUntil:ue.union([ue.iso.datetime(),ue.literal("")]).default(""),offset:ue.coerce.number().int().min(0).max(1e5).default(0),limit:ue.coerce.number().int().min(1).max(100).default(50)}).strict(),jf=ue.object({customers:Ci.array(),hasMore:ue.boolean(),total:ue.number().int().nonnegative().nullable(),evaluatedAt:ue.iso.datetime()}).strict();var ho=Z.discriminatedUnion("type",[Z.strictObject({type:Z.literal("literal"),value:ve}),Z.strictObject({type:Z.literal("variable"),key:It,path:En.optional()}),Z.strictObject({type:Z.literal("feature"),featureKey:Z.string().min(1).max(128)})]),o0=Z.strictObject({requestId:Z.uuid(),decisionId:Z.uuid(),customerId:Z.uuid(),externalUserId:Z.string().min(1).max(255).nullable(),versionId:Z.uuid(),receiptId:Z.uuid(),value:ve}),a0={funnelId:Z.uuid(),requestId:Z.uuid(),customer:Ur,customerData:Pi.optional(),attributes:wt.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},EE=Z.discriminatedUnion("operation",[Z.strictObject({operation:Z.literal("decide"),...a0}).refine(Za,Wa),Z.strictObject({operation:Z.literal("read_decision"),decisionId:Z.uuid()}),Z.strictObject({operation:Z.literal("evaluate_decision"),decisionId:Z.uuid(),requestId:Z.uuid(),nodeId:Z.string().min(1).max(64),visit:Z.number().int().nonnegative(),revision:Z.number().int().nonnegative(),receiptId:Z.uuid(),policyRevision:Z.number().int().nonnegative(),generation:Z.string().min(1).max(256),result:ru}),Z.strictObject({operation:Z.literal("feature_config"),funnelId:Z.uuid()}),Z.strictObject({operation:Z.literal("commit_decision_segment"),decisionId:Z.uuid(),requestId:Z.uuid(),nodeId:Z.string().min(1).max(64),visit:Z.number().int().nonnegative(),revision:Z.number().int().nonnegative(),policyRevision:Z.number().int().nonnegative(),generation:Z.string().min(1).max(256),steps:Z.array(Of).max(32),boundary:Z.strictObject({nodeId:Z.string().min(1).max(64),visit:Z.number().int().nonnegative()}).optional()}),Z.strictObject({operation:Z.literal("segment_configuration"),funnelId:Z.uuid(),versionId:Z.uuid()}),Z.strictObject({operation:Z.literal("configuration"),funnelId:Z.uuid(),versionId:Z.uuid().optional()}),Z.strictObject({operation:Z.literal("local_configuration"),funnelId:Z.uuid()}),Z.strictObject({operation:Z.literal("report_used"),decisionId:Z.uuid(),eventId:Z.uuid(),occurredAt:Z.iso.datetime({offset:!0}),reference:Z.string().min(1).max(128).optional()})]),RE=Z.strictObject({scope:Ne,decisionId:Z.uuid(),requestId:Z.uuid(),status:Z.enum(["pending","completed","failed"]),decision:o0.nullable(),evaluation:Z.discriminatedUnion("type",[wf,Pf]).optional()}).refine(e=>e.status==="completed"==(e.decision!==null)&&(!e.decision||e.decision.decisionId===e.decisionId&&e.decision.requestId===e.requestId),"Completed decisions carry their committed result"),kE=Z.strictObject({scope:Ne,decisionId:Z.uuid(),eventId:Z.uuid(),source:Z.literal("caller_reported")});import{z as Mt}from"zod";var Tf=Mt.strictObject({type:Mt.literal("bundle"),paywall:Fn.optional(),offering:Fn.optional(),coupons:Fn,data:Fn}),s0=e=>Mt.strictObject({type:Mt.literal(e),id:Mt.uuid()}),ME=Mt.strictObject({type:Mt.literal("bundle"),paywallVersionId:Mt.uuid().optional(),offeringVersionId:Mt.uuid().optional(),couponIds:Mt.array(Mt.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:ve});var qE=Mt.strictObject({type:Mt.literal("bundle"),offering:s0("offering_version").nullable(),paywall:Mt.strictObject({versionId:Mt.uuid(),paywallId:Mt.uuid(),offeringVersionId:Mt.uuid()}).nullable(),coupons:Mt.array(Gi).max(20),data:ve});import{z as kn}from"zod";import{z as An}from"zod";var Nf=An.union([An.string(),An.number().finite(),An.boolean(),An.null()]),c0=An.union([Nf,An.array(Nf).min(1).max(20)]),u0=An.record(En,c0).refine(e=>Object.keys(e).length<=10),Df=An.strictObject({path:En,type:An.enum(["string","number","boolean","strings"]),nullable:An.boolean().optional(),aggregation:An.enum(["count","exists"]).optional(),where:u0.optional()}).superRefine((e,t)=>{(e.aggregation==="count"&&e.type!=="number"||e.aggregation==="exists"&&e.type!=="boolean"||!e.aggregation&&e.where)&&t.addIssue({code:"custom",message:"Collection summaries require their matching type"})});var l0=["sendMessage","checkEntitlement","resolveOffering","readHoldings","readLedger","readBillingInvoice","readCreditStatement","previewAttach","attach","readSubscriptionOperation","previewUpdate","update","readSubscriptionUpdate","setupPayment","readPaymentSetup","verifySubscriptions","previewRefund","refund","readRefund","restoreNativePurchase","readBillingControls","prepareBillingAuthorization","confirmBillingAuthorization","setBillingCoupons","revokeBillingAuthorization","listBillingInvoices","confirmBillingAdjustment","manageBillingLimits","readSeats","manageSeat","quoteBalance","mutateBalance","trackUsage","readUsage","setUsage","adjustBalance","readBalanceSource","manageBalanceGrant","listBalanceGrants","manageUsageEntity","readUsageAnalytics","readCreditAnalytics","submitUsageBatch","readUsageBatch","redeemCoupon","listOffers","grantOffer","redeemReward","createReferralCode","claimRewardProduct"],Ff=kn.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),d0=Fn,Mf=kn.discriminatedUnion("type",[xf,kn.strictObject({type:kn.literal("claim_offer"),coupon:Fn}),kn.strictObject({type:kn.literal("event"),event:Ff}),kn.strictObject({type:kn.literal("api"),operation:kn.enum(l0),inputs:kn.record(En,d0).refine(e=>Object.keys(e).length<=40),outputs:kn.record(Ff,Df).refine(e=>Object.keys(e).length<=20)})]);var ut=$a,p0=Q.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),pn={id:ut,name:Q.string().trim().min(1).max(80),position:Q.strictObject({x:Q.number().finite(),y:Q.number().finite()}).optional()},m0={success:ut,cancel:ut,unavailable:ut,failure:ut},su=Q.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),cu=Q.enum(["same_window","new_window"]),f0=Q.discriminatedUnion("type",[Q.strictObject({...pn,type:Q.literal("entry"),next:ut,triggers:Q.array(hf).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),Q.strictObject({...pn,type:Q.literal("screen"),screenId:ut,presentation:Pn,outputs:Q.record(ut,ut),offering:Q.discriminatedUnion("source",[Q.strictObject({source:Q.literal("variable"),key:It}),Q.strictObject({source:Q.literal("fixed"),versionId:Q.uuid()})]).optional()}),Q.strictObject({...pn,type:Q.literal("offering"),configuration:Q.discriminatedUnion("source",[Q.strictObject({source:Q.literal("fixed"),versionId:Q.uuid()}),Q.strictObject({source:Q.literal("feature"),featureKey:Q.string().min(1).max(128)})]),writes:Q.strictObject({value:It}),next:ut}),Q.strictObject({...pn,type:Q.literal("coupon"),couponId:Q.uuid(),writes:Q.strictObject({value:It}),next:ut}),Q.strictObject({...pn,type:Q.literal("coupons"),couponIds:Q.array(Q.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:Q.strictObject({value:It}),next:ut}),Q.strictObject({...pn,type:Q.literal("output"),value:Q.discriminatedUnion("type",[...ho.options,Tf,Q.strictObject({type:Q.literal("selection"),screenId:ut,offeringKey:It})])}),Q.strictObject({...pn,type:Q.literal("condition"),cases:Q.array(Q.strictObject({condition:Yt,target:ut})).min(1).max(50),default:ut}),Q.strictObject({...pn,type:Q.literal("feature"),featureKey:Q.string().min(1).max(128),writes:Q.strictObject({value:It}),next:ut}),Q.strictObject({...pn,type:Q.literal("split"),experimentId:Q.uuid(),applyPageExperiment:Q.literal(!0).optional(),routes:Q.record(p0,ut).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:ut}),Q.strictObject({...pn,type:Q.literal("action"),...m0,execution:Sf,action:Mf,writes:wc.optional()}),Q.strictObject({...pn,type:Q.literal("external_page"),appManifest:Va.optional(),url:su,openIn:cu,opened:ut,failed:ut}),Q.strictObject({...pn,type:Q.literal("end"),outcome:Q.enum(["completed","closed","ineligible","failed"]),output:ho.optional()}),Q.strictObject({...pn,type:Q.literal("wait"),writes:wc.optional(),wait:Q.discriminatedUnion("type",[Q.strictObject({type:Q.literal("duration"),delaySeconds:Q.number().int().min(1).max(2592e3),elapsed:ut}),Q.strictObject({type:Q.literal("event"),eventName:ut,outputs:nu,timeoutSeconds:Q.number().int().min(1).max(2592e3),received:ut,timeout:ut})])})]),uu=Q.strictObject({version:Q.literal(5),entry:ut,nodes:Q.array(f0).min(1).max(Rn.flowNodes)}),lu=uu.superRefine((e,t)=>{g0(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function Ya(e){switch(e.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":return[e.next];case"screen":return Object.values(e.outputs);case"condition":return[...e.cases.map(t=>t.target),e.default];case"split":return[...Object.values(e.routes),e.notParticipating];case"action":return[e.success,e.cancel,e.unavailable,e.failure];case"external_page":return[e.opened,e.failed];case"end":case"output":return[];case"wait":return e.wait.type==="duration"?[e.wait.elapsed]:[e.wait.received,e.wait.timeout]}}function g0(e,t){let n=[],r=new Map(e.nodes.map(l=>[l.id,l])),i=(l,m,f)=>{n.push(l),t?.({message:l,reason:m,path:f?["nodes",e.nodes.indexOf(f)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(l=>l.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(l=>l.type==="screen").length>Rn.pages||e.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>Rn.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let l of e.nodes){for(let m of Ya(l))m===e.entry&&i("An entry cannot be a transition target","entryTarget",l),r.has(m)||i(`Missing target ${m}`,"missingTarget",l);l.type==="screen"&&(a.has(l.screenId)&&i("Every screen has exactly one node owner","screenOwner",l),a.add(l.screenId))}let o=new Set,s=new Set,c=new Set;function u(l){if(o.has(l)){i("Flow edges must not form a cycle","cycle",r.get(l));return}if(!(s.has(l)||!r.has(l))){o.add(l),c.add(l);for(let m of Ya(r.get(l)))u(m);o.delete(l),s.add(l)}}u(e.entry);for(let l of e.nodes)c.has(l.id)||i("Every node must be reachable from Entry","unreachable",l);return[...new Set(n)]}var du={maxTransitions:1e4,runTimeoutSeconds:2592e3};function qf(e,t,n){let r=[...t].sort((s,c)=>c.length-s.length),i=new Set,a=(s,c=!1)=>{let u=r.find(l=>s===l||c&&s.startsWith(l+"."));i.add(u??s)};if(e.type==="condition"){let s=n?.startsWith("case_")?Number(n.slice(5)):e.cases.length-1;for(let c of e.cases.slice(0,s+1))for(let u of tr(c.condition))u.startsWith("variables.")&&a(u.slice(10),!0)}if(e.type==="screen"&&e.offering?.source==="variable"&&a(e.offering.key),e.type==="action"&&(e.action.type==="api"||e.action.type==="external_task"))for(let s of Object.values(e.action.inputs))s.source==="variable"&&a(s.key);e.type==="action"&&e.action.type==="claim_offer"&&e.action.coupon.source==="variable"&&a(e.action.coupon.key);let o=e.type==="output"?e.value:e.type==="end"?e.output:null;if(o?.type==="variable"&&a(o.key),o?.type==="bundle")for(let s of[o.paywall,o.offering,o.coupons,o.data])s?.source==="variable"&&a(s.key);return o?.type==="selection"&&a(o.offeringKey),[...i]}import{z as q}from"zod";var _i=q.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Xa=e=>q.record(q.string(),ve).refine(t=>ln(t)<=e,"Funnel evidence exceeds its byte budget"),gR=q.enum(["local_segment","evaluation","presentation","timer","event","operation"]),mu=q.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),fu=q.discriminatedUnion("type",[q.strictObject({type:q.literal("flag"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("experiment"),id:q.uuid()}),q.strictObject({type:q.literal("saved_group"),id:q.uuid()}),q.strictObject({type:q.literal("config"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("constant"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("paywall_version"),id:q.uuid()}),q.strictObject({type:q.literal("offering_version"),id:q.uuid()}),q.strictObject({type:q.literal("reward"),id:q.uuid()})]),yo=q.strictObject({schemaVersion:q.literal(1),kind:mu,selector:fu.nullable(),context:Xa(131072),contract:q.strictObject({version:q.number().int().positive(),evaluator:q.string().min(1).max(128),policyRevision:q.number().int().nonnegative()})}).refine(e=>ln(e)<=131072,"Node input exceeds its byte budget"),Uf=q.strictObject({schemaVersion:q.literal(1),kind:mu,outcome:q.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:Xa(131072),route:q.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:Xa(131072)}).refine(e=>ln(e)<=131072,"Node result exceeds its byte budget"),hR=q.strictObject({schemaVersion:q.literal(1),operations:q.record(_i,q.strictObject({attempts:q.number().int().nonnegative(),maxAttempts:q.number().int().min(1).max(5),deadlineAt:q.iso.datetime({offset:!0}),retryAt:q.iso.datetime({offset:!0}).nullable(),error:q.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:q.strictObject({type:_i,id:q.uuid()}).nullable()}))}).refine(e=>ln(e)<=65536,"Execution state exceeds its byte budget"),Br={receiptId:q.uuid()},pu=q.iso.datetime({offset:!0}),yR=q.discriminatedUnion("type",[q.strictObject({type:q.literal("node_entered"),details:q.strictObject({kind:mu})}),q.strictObject({type:q.literal("presentation_shown"),details:q.strictObject({...Br,source:q.literal("client"),occurredAt:pu.optional()})}),q.strictObject({type:q.literal("decision_accepted"),details:q.strictObject(Br)}),q.strictObject({type:q.literal("signal_received"),details:q.strictObject({signalId:q.uuid(),nodeId:_i,eventName:_i,data:Xa(8192),source:q.literal("server"),occurredAt:pu})}),q.strictObject({type:q.literal("signal_consumed"),details:q.strictObject({...Br,signalId:q.uuid()})}),q.strictObject({type:q.literal("wait_elapsed"),details:q.strictObject(Br)}),q.strictObject({type:q.literal("wait_timeout"),details:q.strictObject(Br)}),q.strictObject({type:q.literal("operation_completed"),details:q.strictObject({...Br,operation:_i,reference:q.strictObject({type:_i,id:q.uuid()}).nullable()})}),q.strictObject({type:q.literal("execution_recovered"),details:q.strictObject({generation:q.number().int().positive(),reason:q.enum(["interrupted","expired_lease","delivery_failed"])})}),q.strictObject({type:q.literal("execution_failed"),details:q.strictObject({generation:q.number().int().positive(),code:q.string().regex(/^[a-z_]{1,64}$/)})}),q.strictObject({type:q.literal("run_completed"),details:q.strictObject({outcome:q.enum(["completed","ineligible","failed"])})}),q.strictObject({type:q.literal("run_closed"),details:q.strictObject({source:q.enum(["client","server","expiry"])})}),q.strictObject({type:q.literal("treatment_used"),details:q.strictObject({...Br,source:q.enum(["client","server"]),occurredAt:pu,reference:q.string().min(1).max(128).optional()})})]);var bn=L.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),h0=L.discriminatedUnion("type",[L.strictObject({id:bn,type:L.literal("owned"),publicData:tf.optional(),document:un.refine(e=>["page","popup","onboarding"].includes(e.surface)&&e.pages.length===1&&e.actions.every(t=>t.type==="event"&&!t.close),"A Funnel owns one Page or Popup per screen and emits outputs; Paywall owns its purchase policies")}),L.strictObject({id:bn,type:L.literal("paywall"),paywallVersionId:L.uuid()})]),gu={executionContract:cf.optional(),kind:L.literal("funnel"),schemaVersion:L.literal(4),screens:L.array(h0).max(Rn.pages),references:L.record(bn,fu).refine(e=>Object.keys(e).length<=500),inputs:L.array(L.strictObject({variable:bn,screenId:bn,componentId:bn,required:L.boolean()})).max(Rn.questions),variables:L.record(It,mi).refine(e=>Object.keys(e).length<=Rn.logicNodes),outputSchema:pi,execution:L.strictObject({runTimeoutSeconds:L.number().int().min(1).max(du.runTimeoutSeconds),maxTransitions:L.number().int().min(1).max(du.maxTransitions)})},MR=L.strictObject({...gu,graph:uu});function y0(e,t){let n=!1,r=(i,a)=>{let o=i.type==="stack"||i.type==="button"?i.bind?.coupon??a:a;i.type==="text"&&Object.values(e.strings.locales).some(s=>s[i.text]?.includes("{{offer."))&&!(o&&t(o))&&(n=!0),i.type==="stack"&&i.children.forEach(s=>r(s,o))};for(let i of e.pages)r(i.root);return n}function ts(e){return Array.isArray(e)?e.some(ts):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===If:ts(n))}function A0(e){let t=[],n=new Set(Object.values(e.references).flatMap(r=>r.type==="reward"?[r.id]:[]));for(let[r,i]of e.screens.entries()){if(i.type!=="owned")continue;let a;try{a=df(i.document)}catch(o){t.push({message:o instanceof Error?o.message:"Screen cannot be delivered",reason:"screen",path:["screens",r,"document"]});continue}for(let[o,s]of e.inputs.entries())s.screenId===i.id&&!co(a,s.componentId)&&t.push({message:`Local Funnel input ${s.variable} targets hidden component ${s.componentId} on screen ${s.screenId}`,reason:"inputBinding",path:["inputs",o]})}for(let[r,i]of e.graph.nodes.entries()){let a=["graph","nodes",r],o=i.type==="screen"?e.screens.find(s=>s.id===i.screenId):void 0;o?.type==="owned"&&(o.document.actions.some(s=>typeof s.properties.templateKey=="string"&&s.properties.templateKey.startsWith("popup-coupon-"))&&t.push({message:"Funnel screens claim Coupons through a Claim Coupon step",reason:"coupon",path:a}),y0(o.document,s=>n.has(s))&&t.push({message:"Offer copy shows the Coupon of a Claim Coupon step",reason:"coupon",path:a})),(i.type==="output"&&i.value.type==="literal"&&ts(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&ts(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function Bf(e,t){for(let{message:n,reason:r,path:i}of A0(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function Vf(e,t){let n=(g,d,h=[])=>t.addIssue({code:"custom",message:g,path:h,params:{reason:d}}),r=Object.values(e.references),i=new Map(e.screens.map(g=>[g.id,g])),a=(g,d)=>r.some(h=>h.type===g&&("id"in h?h.id:h.key)===d);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let o=e.graph.nodes.filter(g=>g.type==="screen");(o.length!==i.size||o.some(g=>!i.has(g.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(g=>c.some(d=>g!==d&&d.startsWith(g+".")))&&n("Variable paths must not overlap","variable");function u(g,d){Object.hasOwn(e.variables,g)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(d)]);let h=s.get(g)??new Set;h.add(d.id),s.set(g,h)}for(let[g,d]of e.graph.nodes.entries()){let h=["graph","nodes",g],R=d.type==="feature"?d.featureKey:d.type==="offering"&&d.configuration.source==="feature"?d.configuration.featureKey:d.type==="output"&&d.value.type==="feature"?d.value.featureKey:d.type==="end"&&d.output?.type==="feature"?d.output.featureKey:null;R&&!a("flag",R)&&n("Flag selectors require an explicit GB resource reference","feature",h);let y=d.type==="feature"||d.type==="offering"||d.type==="coupon"||d.type==="coupons"||d.type==="action"&&d.action.type==="api"?["value"]:d.type==="action"&&d.action.type==="external_task"?Object.keys(d.action.outputs):d.type==="wait"&&d.wait.type==="event"?Object.keys(d.wait.outputs):[],A="writes"in d?d.writes??{}:{};(y.length!==Object.keys(A).length||y.some(v=>!Object.hasOwn(A,v))||new Set(Object.values(A)).size!==Object.values(A).length)&&n("Node writes must map every named output exactly once","variable",h);for(let[v,P]of Object.entries(A)){u(P,d);let j=e.variables[P],_=d.type==="offering"?"offering_version":d.type==="coupon"?"reward":d.type==="action"&&d.action.type==="api"?"json":d.type==="action"&&d.action.type==="external_task"?d.action.outputs[v]:d.type==="wait"&&d.wait.type==="event"?d.wait.outputs[v]:void 0;(j?.source.type!=="node"||_&&j.type!==_)&&n("Node writer source or output type does not match declaration","variable",h)}if(d.type==="coupons"){let v=e.variables[d.writes.value];(v?.type!=="array"||v.items?.type!=="reward"||v.items.nullable||v.nullable)&&n("Coupons output requires a non-null Reward array","variable",h);for(let P of d.couponIds)a("reward",P)||n("Coupons require Reward references","coupon",h)}if(d.type==="split"&&!a("experiment",d.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",h),d.type==="coupon"&&!a("reward",d.couponId)&&n("Coupon selectors require a Reward reference","coupon",h),d.type==="action"&&d.action.type==="claim_offer"&&d.action.coupon.source==="literal"){let v=d.action.coupon.value;(!v||typeof v!="object"||Array.isArray(v)||v.type!=="reward"||typeof v.id!="string"||Object.keys(v).length!==2||!a("reward",v.id))&&n("Coupon claims require a Reward reference","coupon",h)}if(d.type==="offering"&&d.configuration.source==="fixed"&&!a("offering_version",d.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",h),d.type==="screen"&&d.offering?.source==="variable"&&e.variables[d.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",h),d.type==="action"&&d.action.type==="claim_offer"&&d.action.coupon.source==="variable"&&(e.variables[d.action.coupon.key]?.type!=="reward"||d.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",h),d.type==="screen"){let v=i.get(d.screenId);if(d.offering?.source==="fixed"&&!a("offering_version",d.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",h),v?.type==="paywall"&&d.offering&&n("Paywall owns its fixed Offering Version","offering",h),v?.type==="paywall"&&!a("paywall_version",v.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",h),v?.type==="owned"){let P=v.document.pages[0];if(!P){n("Owned screen requires a page","screen",h);continue}or(v.document).some(_=>!_.complete)&&n("Owned screens require complete local content","translations",h);let j=new Set(v.document.actions.map(_=>_.id));(j.size!==Object.keys(d.outputs).length||Object.keys(d.outputs).some(_=>!j.has(_)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",h),Zn(P.root,_=>{!d.offering&&(_.type==="plan_picker"||(_.type==="stack"||_.type==="button")&&_.bind?.plan||_.type==="customer_data"&&["customer_plans","credit_packs"].includes(_.data.source))&&n("Product presentation requires an Offering Version","offering",h),_.type==="customer_data"&&Object.values(_.data.outputs??{}).some(X=>X!==void 0&&!j.has(X))&&n("Customer components require declared screen outcomes","componentOutput",h)})}}d.type==="end"&&["completed","ineligible"].includes(d.outcome)&&!d.output&&n("Completed and ineligible ends require a declared output","output",h),d.type==="end"&&d.output?.type==="literal"&&!hn(e.outputSchema,d.output.value)&&n("Terminal output does not match outputSchema","output",h),d.type==="output"&&d.value.type==="literal"&&!hn(e.outputSchema,d.value.value)&&n("Terminal output does not match outputSchema","output",h);let x=d.type==="output"?d.value:d.type==="end"?d.output:void 0;if(x?.type==="variable"&&!x.path){let v=e.variables[x.key];v&&!Oc(v,e.outputSchema)&&n("Variable output does not match outputSchema","output",h)}if(d.type==="screen"){let v=i.get(d.screenId);if(v?.type==="owned")for(let P of _c(v.document))(/^(input|params)\./.test(P)||P.startsWith("variables.")&&!Cc(P.slice(10),c))&&n("Screen values must reference registered variables","variable",h)}if(d.type==="condition")for(let v of d.cases){for(let P of Hn(v.condition))a("saved_group",P)||n("Conditions require explicit Saved Group references","savedGroup",h);for(let P of tr(v.condition))P.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",h)}if(d.type==="output"&&d.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",h);for(let[v,P]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let j=d.value[v];if(j)if(j.source==="literal"){let _=v==="coupons"?j.value:[j.value];(!Array.isArray(_)||_.length>20||_.some(X=>!hn({type:P,nullable:!1},X)||!a(P,X.id))||v==="coupons"&&new Set(_.map(X=>X.id)).size!==_.length)&&n("Bundle requires distinct scoped resource references",v==="coupons"?"coupon":v==="paywall"?"paywall":"offering",[...h,"value",v])}else{let _=e.variables[j.key];(j.path||!_||_.nullable||(v==="coupons"?_.type!=="array"||_.items?.type!=="reward"||_.items.nullable:_.type!==P))&&n("Bundle binding type does not match its slot","output",h)}}}}for(let[g,d]of e.graph.nodes.entries()){let h=d.type==="screen"?i.get(d.screenId):void 0,R=[...qf(d,c),...h?.type==="owned"?va(h.document).map(y=>Cc(y,c)?.key??y):[]];for(let y of new Set(R)){let P=function(j){if(j===d.id)return!0;if(v.has(j))return!1;v.add(j);let _=e.graph.nodes.find(le=>le.id===j);return _?(x.has(j)?_.type==="action"?[_.cancel,_.unavailable,_.failure]:_.type==="wait"&&_.wait.type==="event"?[_.wait.timeout]:[]:Ya(_)).some(P):!1};var f=P;if(!Object.hasOwn(e.variables,y)){n("Consumed variable is undeclared","variable",["graph","nodes",g]);continue}let A=e.variables[y];if(d.type==="screen"&&A.source.type==="input"&&e.inputs.some(j=>j.screenId===d.screenId&&j.variable===y)||A.source.type==="parameter"||A.source.type==="attribute")continue;let x=A.source.type==="input"?new Set(e.inputs.filter(j=>j.variable===y&&j.required).flatMap(j=>o.filter(_=>_.screenId===j.screenId).map(_=>_.id))):s.get(y)??new Set,v=new Set;(!x.size||P(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",g])}}(new Set(e.inputs.map(g=>g.variable)).size!==e.inputs.length||new Set(e.inputs.map(g=>`${g.screenId}:${g.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[g,d]of e.inputs.entries()){e.variables[d.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",g]);let h=i.get(d.screenId),R=h?.type==="owned"?co(h.document,d.componentId):null;if((R?.type!=="stack"||!R.interaction||!["input","toggle","select","multiselect","tabs"].includes(R.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",g]),R?.type==="stack"&&R.interaction){let y=R.interaction.type==="toggle"?"boolean":R.interaction.type==="multiselect"?"strings":"string";e.variables[d.variable]?.type!==y&&n("Input variable type does not match component","inputBinding",["inputs",g]);let A=e.variables[d.variable]?.enum;A&&!R.children.filter(x=>!x.hidden).every(x=>A.includes(x.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",g])}}for(let[g,d]of Object.entries(e.variables))d.enum&&d.type!=="string"&&n("Only string variables support enum","variable",["variables",g]),d.source.type==="input"&&!e.inputs.some(h=>h.variable===g)&&n("Input variable requires a component binding","inputBinding",["variables",g]);let l=0,m=0;for(let g of e.screens)if(g.type==="owned"){for(let d of g.document.pages)Zn(d.root,()=>{l++});m+=g.document.actions.length}(l>Rn.components||m>Rn.actions||ln(e)>Rn.documentBytes)&&n("Funnel document exceeds its budget","budget")}var b0=L.strictObject({...gu,graph:lu}).superRefine(Vf),Ei=L.strictObject({...gu,graph:lu,displayName:L.string().trim().min(1).max(80)}).superRefine(Vf),qR=Ei.superRefine(Bf),UR=b0.superRefine(Bf),es=L.string().regex(kt),Ao={requestId:L.uuid(),nodeId:bn,visit:L.number().int().nonnegative(),revision:L.number().int().nonnegative(),customerToken:es.optional()},x0=L.discriminatedUnion("type",[L.strictObject({type:L.literal("screen"),output:bn,answers:sr,selection:L.record(bn,L.union([L.string().max(200),L.boolean(),L.number().int().min(0).max(1e4)])).optional()}),L.strictObject({type:L.literal("paywall_quote"),featureQuantities:L.record(L.uuid(),L.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100).optional(),actionId:bn,productVersionId:L.uuid(),offerId:L.uuid().optional(),nativeOffer:hi.optional(),predecessor:L.strictObject({operationId:L.uuid().nullable(),generation:L.number().int().positive()}).optional()}),L.strictObject({type:L.literal("paywall_confirm"),operationId:L.uuid()}),L.strictObject({type:L.literal("paywall_cancel"),operationId:L.uuid()}),L.strictObject({type:L.literal("client_action"),receiptId:L.uuid(),outcome:L.enum(["success","cancel","failure","opened","failed"])})]),S0=L.object({nodeId:bn,visit:L.number().int().nonnegative(),revision:L.number().int().nonnegative(),components:L.record(bn,L.object({resourceKey:L.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:L.number().int().min(1).max(1e5),after:La.nullable(),filter:L.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),Ot=L.discriminatedUnion("operation",[L.strictObject({operation:L.literal("start"),funnelId:L.uuid(),requestId:L.uuid(),customer:Ur.optional(),customerData:Pi.optional(),locale:L.string().min(1).max(35),parameters:cr}).refine(Za,Wa),L.strictObject({operation:L.literal("get"),settlementRequestId:L.uuid().optional(),data:S0.optional(),purchase:L.strictObject({receiptId:L.uuid(),operationId:L.uuid()}).optional(),customerToken:es.optional()}),L.strictObject({operation:L.literal("resume"),requestId:L.uuid(),customerToken:es.optional()}),L.strictObject({operation:L.literal("submit"),...Ao,input:x0}),L.strictObject({operation:L.literal("back"),...Ao}),L.strictObject({operation:L.literal("shown"),...Ao}),L.strictObject({operation:L.literal("close"),...Ao}),L.strictObject({operation:L.literal("commit_segment"),...Ao,policyRevision:L.number().int().nonnegative(),generation:L.string().min(1).max(256)}),L.strictObject({operation:L.literal("review"),receiptId:L.uuid().optional(),customerToken:es.optional()})]);function ns(e,t){let n=new Set,r=new Set,i=new Set,a=[],o=new Map,s=new Map,c=new Map;function u(d){for(let h of Hn(d))l(h)}function l(d){if(i.has(d)||!Object.hasOwn(t.savedGroups,d))return;let h=t.savedGroups[d];h&&(i.add(d),c.set(d,h),a.push(()=>{!Array.isArray(h)&&h.type==="condition"&&u(h.condition)}))}function m(d){for(let h of["hashAttribute","fallbackAttribute"])if(d[h]!==void 0&&Yc(d[h]))throw new Error(`Funnel GB ${h} uses a reserved flow namespace`);u(d.condition);for(let h of d.parentConditions??[])f(h.id),u(h.condition)}function f(d,h=!1){let R=Object.hasOwn(t.features,d)?t.features[d]:void 0;if(!R){if(h)throw new Error("Required GB Feature is unavailable");return}n.has(d)||(n.add(d),o.set(d,R),a.push(()=>{for(let y of R.rules??[]){m(y);for(let A of y.tracks??[])m(A.experiment)}}))}function g(d){let h=Object.hasOwn(t.experiments,d)?t.experiments[d]:void 0;if(!h)throw new Error("Required GB Experiment is unavailable");r.has(d)||(r.add(d),s.set(d,h),a.push(()=>m(h)))}for(let d of e.graph.nodes){d.type==="feature"&&f(d.featureKey,!0),d.type==="split"&&g(d.experimentId),d.type==="condition"&&d.cases.forEach(R=>u(R.condition)),d.type==="offering"&&d.configuration.source==="feature"&&f(d.configuration.featureKey,!0);let h=d.type==="output"?d.value:d.type==="end"?d.output:null;h?.type==="feature"&&f(h.featureKey,!0)}for(let d of a)d();return{...t,features:Object.fromEntries(o),experiments:Object.fromEntries(s),savedGroups:Object.fromEntries(c)}}import{z as ae}from"zod";function Lf(e,t){let n=[],r={};Gt(e,i=>{if(i.hidden)return!1;if(i.type!=="quantity_picker")return;let a=i.bind?.plan?[i.bind.plan]:[];i.bind?.picker&&Gt(e,o=>{if(o.type==="plan_picker"&&o.id===i.bind?.picker&&a.push(...o.planIds??[]),o.type==="stack"&&o.interaction?.type==="select"&&o.interaction.pickerId===i.bind?.picker)for(let s of o.children)s.type==="stack"&&s.bind?.plan&&a.push(s.bind.plan)}),a.length||n.push(`Quantity control ${i.id} needs a Product binding`);for(let o of new Set(a)){let s=t[o]?.prepaid?.find(u=>u.internalFeatureId===i.internalFeatureId)?.terms,c=r[o]??(r[o]=new Set);(!s||c.has(i.internalFeatureId)||i.minimumQuantity<s.minimumQuantity||i.maximumQuantity>s.maximumQuantity)&&n.push(`Quantity control ${i.id} must match its Product's prepaid Feature and bounds`),c.add(i.internalFeatureId)}});for(let[i,a]of Object.entries(t))for(let o of a.prepaid??[])r[i]?.has(o.internalFeatureId)||n.push(`Product ${i} needs a quantity control for ${o.internalFeatureId}`);return n}function zf(e,t,n,r){let i=r.plans[t];if(!i?.available)throw new Error("Selected Product is unavailable");let a={};if(Gt(e,o=>{if(o.hidden)return!1;if(o.type!=="quantity_picker"||o.hidden||(o.bind?.plan??(o.bind?.picker?n[o.bind.picker]:void 0))!==t)return;let c=i.prepaid?.find(l=>l.internalFeatureId===o.internalFeatureId)?.terms,u=n[o.id];if(!c||typeof u!="number"||!Number.isSafeInteger(u)||u<Math.max(c.minimumQuantity,o.minimumQuantity)||u>Math.min(c.maximumQuantity,o.maximumQuantity)||(u-o.minimumQuantity)%o.step!==0||a[o.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");a[o.internalFeatureId]=u}),(i.prepaid??[]).some(o=>a[o.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return a}import{z as bo}from"zod";var $f=bo.object({defaultLocale:In,locales:bo.record(In,bo.object({name:bo.string().max(80),description:bo.string().max(500)}).strict())}).strict().superRefine((e,t)=>{let n=Object.keys(e.locales);(!n.length||n.length>20||!e.locales[e.defaultLocale])&&t.addIssue({code:"custom",message:"Invalid content languages"}),new TextEncoder().encode(JSON.stringify(e)).length>5e4&&t.addIssue({code:"custom",message:"Content exceeds 50 KB"})});var I0=["customer_data","coupon_code"],Gf=ae.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),v0=ae.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),rs=(e,t)=>new Set(e.map(t)).size===e.length,w0=ae.strictObject({currency:Ie,amountMinor:ae.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),O0=ae.strictObject({featureId:ae.uuid(),name:ae.string().trim().min(1).max(120),allowance:ae.string().max(40).nullable(),access:ae.boolean()}),P0=ae.strictObject({stripe:ae.strictObject({prices:ae.array(w0).min(1).max(50)}).optional(),apple:ae.strictObject({productIds:ae.array(Gf).min(1).max(10)}).optional(),google:ae.strictObject({products:ae.array(ae.strictObject({productId:Gf,basePlanId:v0.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!rs(e.stripe.prices,n=>n.currency)||e.apple&&!rs(e.apple.productIds,n=>n)||e.google&&!rs(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),C0=ae.strictObject({name:ae.string().trim().min(1).max(80),interval:ae.enum(["free","week","month","year","one_time"]),intervalCount:ae.number().int().min(1).max(100),trial:ae.strictObject({days:ae.number().int().min(1).max(730),cardRequired:ae.boolean()}).nullable(),benefits:ae.array(O0).max(50).refine(e=>rs(e,t=>t.featureId),"Duplicate benefit"),channels:P0,prepaid:ae.array(io).max(100).optional()}),_0=ae.strictObject({digest:vi,content:ae.strictObject({discount:nr,duration:sn,appliesTo:sc,displayCopy:$f.nullable(),firstPurchaseOnly:ae.boolean(),qualificationRequired:ae.boolean(),startsAt:ae.iso.datetime().nullable(),endsAt:ae.iso.datetime().nullable(),grantWindowHours:ae.number().int().positive(),perCustomerLimit:ae.number().int().positive()})}),E0=ae.discriminatedUnion("type",[ae.strictObject({type:ae.literal("checkout"),product:xa}),ae.strictObject({type:ae.literal("close")}),ae.strictObject({type:ae.literal("action"),action:Vc})]),is=ae.strictObject({kind:ae.literal("paywall"),formatVersion:ae.literal(1),name:ae.string().trim().min(1).max(80),offeringVersionId:ae.uuid(),presentation:Pn,screen:un,products:Ma,catalog:ae.record(ae.uuid(),C0),buttons:ae.record(Ue,E0),coupons:ae.record(ae.uuid(),_0)}).superRefine((e,t)=>{let n=h=>t.addIssue({code:"custom",message:h}),{screen:r}=e;Lf(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),Kc(r,I0).forEach(n),or(r).some(h=>!h.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,o=new Set;Gt(r,h=>{let R="bind"in h?h.bind:void 0;R?.promotionCode&&n("Promotion codes must not be published"),R?.plan&&i.add(R.plan),R?.coupon&&a.add(R.coupon),h.type==="plan_picker"&&(h.planIds?.forEach(y=>i.add(y)),h.defaultPlan&&i.add(h.defaultPlan)),h.type==="text"&&h.feature&&o.add(h.feature.id)});let s=e.products.items.map(h=>h.productVersionId),c=Object.keys(e.catalog);(s.length!==c.length||s.some(h=>!Object.hasOwn(e.catalog,h)))&&n("Catalog must contain exactly the displayed Products");let u=new Set(s);e.products.defaultProductVersionId!==null&&!u.has(e.products.defaultProductVersionId)&&n("Default Product must be displayed");for(let h of i)u.has(h)||n("Screen references a Product that is not displayed");for(let h of Object.values(e.catalog))!h.channels.stripe&&!h.channels.apple&&!h.channels.google&&n("A displayed Product needs at least one sales channel");let l=new Set(Object.values(e.catalog).flatMap(h=>h.benefits.map(R=>R.featureId)));for(let h of o)l.has(h)||n("Feature text must read a displayed benefit");let m=r.actions.filter(h=>h.type!=="navigate");r.actions.some(h=>h.type!=="event"&&h.type!=="navigate")&&n("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==m.length||m.some(h=>!Object.hasOwn(e.buttons,h.id)))&&n("Buttons must match the screen's actions");let g=!1;for(let h of Object.values(e.buttons)){if(h.type!=="checkout")continue;g=!0,(h.product.type==="fixed"?[h.product.productVersionId]:h.product.allowedProductVersionIds).some(y=>!u.has(y))&&n("Checkout may only sell displayed Products")}g||n("A Paywall needs a checkout button");let d=Object.keys(e.coupons);(d.length!==a.size||d.some(h=>!a.has(h)))&&n("Coupons must be exactly the bound Coupons")}),Kf=ae.strictObject({state:ae.enum(["published","archived"]),controlRevision:ae.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:ae.uuid(),versions:ae.record(ae.uuid(),ae.strictObject({version:ae.number().int().positive(),artifact:ae.string().min(1),sourceDigest:ae.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var nn={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},hu=Re.string().regex(/^[a-f0-9]{64}$/),yu=Re.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),bu=Ne.extend({environmentId:Re.uuid()}),Hf=Re.strictObject({features:Re.array(Re.string()).max(500),experiments:Re.record(Re.uuid(),Re.array(Re.string()).max(20)),savedGroups:Re.array(Re.string()).max(1e3)}),xu=Re.strictObject({kind:Re.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:Re.number().int().positive(),url:Re.string().min(1).max(2048),sha256:hu,byteLength:Re.number().int().positive().max(nn.maxArtifactBytes),generation:hu.optional()}),R0=Re.strictObject({state:Re.enum(["active","paused","archived"]),controlRevision:yu,evaluationMode:Re.enum(["local","remote"]),evaluationRevision:yu,currentVersionId:Re.uuid(),versions:Re.record(Re.uuid(),Re.strictObject({artifact:Re.string(),dependencies:Hf,definitionDigest:vi.optional(),couponDigests:Re.record(Re.uuid(),vi).optional()}))}),Su=Re.strictObject({kind:Re.literal("sdk_configuration"),schemaVersion:Re.literal(1),scope:bu,revision:yu,generation:hu,policy:Re.strictObject({refreshIntervalSeconds:Re.number().positive().max(15),maxControlAgeSeconds:Re.number().positive().max(60)}),gb:Re.strictObject({features:Re.string().nullable(),pageExperiments:Re.string().nullable()}),artifacts:Re.record(Re.string(),xu),funnels:Re.record(Re.uuid(),R0),paywalls:Re.record(Re.uuid(),Kf).optional()}).superRefine((e,t)=>{let n=(r,i)=>{r!==null&&e.artifacts[r]?.kind!==i&&t.addIssue({code:"custom",message:"Missing or wrong-kind configuration artifact"})};n(e.gb.features,"gb_features"),n(e.gb.pageExperiments,"gb_page_experiments");for(let r of Object.values(e.paywalls??{}))for(let i of Object.values(r.versions))n(i.artifact,"paywall");for(let r of Object.values(e.funnels)){r.evaluationMode==="remote"&&Object.keys(r.versions).length&&t.addIssue({code:"custom",message:"Remote Funnel graphs cannot be public"}),r.evaluationMode==="local"&&!r.versions[r.currentVersionId]&&t.addIssue({code:"custom",message:"Current Funnel Version is not retained"});for(let i of Object.values(r.versions))n(i.artifact,"funnel")}});function Pt(e){if(Array.isArray(e))return`[${e.map(Pt).join(",")}]`;if(e!==null&&typeof e=="object")return`{${Object.entries(e).sort(([n],[r])=>n<r?-1:n>r?1:0).map(([n,r])=>`${JSON.stringify(n)}:${Pt(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function Iu(e){return ni(ri(typeof e=="string"?new TextEncoder().encode(e):e))}function Qf(e){return Iu(Pt(e))}var Au=class extends Error{constructor(n,r){super(n);qe(this,"dependency",r)}};function Jf(e,t){let n=l=>l.type==="feature"?l.featureKey:l.type==="end"&&l.output?.type==="feature"?l.output.featureKey:l.type==="output"&&l.value.type==="feature"?l.value.featureKey:void 0,r=(l,m)=>e.graph.nodes.find(f=>l==="experiment"?f.type==="split"&&f.experimentId===m:l==="feature"&&n(f)===m)?.name,i=(l,m,f=r(m.type,m.resource))=>new Au(l,{...m,...f?{step:f}:{}});for(let l of Object.values(e.references)){let m=l.type==="flag"?!Object.hasOwn(t.features,l.key)||t.remoteFeatures.includes(l.key)?{type:"feature",resource:l.key}:null:l.type==="experiment"?Object.hasOwn(t.experiments,l.id)?null:{type:"experiment",resource:l.id}:l.type==="saved_group"&&!Object.hasOwn(t.savedGroups,l.id)?{type:"saved_group",resource:l.id}:null;if(m)throw i("Funnel dependency is absent from GB public delivery",{reason:"unavailable",...m})}let a=ns(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),o=new Set(t.remoteFeatures);for(let l of e.graph.nodes){let m=n(l);if(!m)continue;let f=a.features[m],g=l.type==="feature"?e.variables[l.writes.value]:e.outputSchema,d={type:"feature",resource:m};if(!f||!g)throw i("Required public Feature declaration is unavailable",{reason:"unavailable",...d},l.name);if([f.defaultValue,...(f.rules??[]).flatMap(R=>[...Object.hasOwn(R,"force")?[R.force]:[],...R.variations??[],...(R.tracks??[]).flatMap(y=>y.experiment.variations)])].some(R=>R===void 0||!hn(g,R)))throw i("GB Feature values violate the Funnel type contract",{reason:"value_type",...d},l.name)}let s=new Set,c=(l,m)=>{for(let f of Hn(l)){if(s.has(f))continue;let g=t.savedGroups[f];if(!g)throw i("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:f},m);s.add(f),!Array.isArray(g)&&g.type==="condition"&&c(g.condition,m)}},u=(l,m)=>{if(o.has(l)||!t.features[l])throw i("Local Funnel requires public Local prerequisites",{reason:"unavailable",type:"feature",resource:l},m)};for(let l of e.graph.nodes)if(l.type==="condition")for(let m of l.cases)c(m.condition,l.name);for(let[l,m]of Object.entries(a.features)){let f=r("feature",l);for(let g of m.rules??[]){c(g.condition,f);for(let d of[...g.parentConditions??[],...(g.tracks??[]).flatMap(h=>h.experiment.parentConditions??[])])u(d.id,f),c(d.condition,f);for(let d of g.tracks??[])c(d.experiment.condition,f)}}for(let[l,m]of Object.entries(a.experiments)){let f=r("experiment",l);c(m.condition,f);for(let g of m.parentConditions??[])u(g.id,f),c(g.condition,f)}for(let l of e.graph.nodes)if(l.type==="split"){let m=a.experiments[l.experimentId],f={type:"experiment",resource:l.experimentId};if(!m)throw i("Local Funnel requires a public Experiment",{reason:"unavailable",...f},l.name);for(let g of m.variations)if(typeof g!="string"||!Object.hasOwn(l.routes,g))throw i("Experiment variation has no declared Funnel route",{reason:"variation_route",...f},l.name)}return Hf.parse({features:Object.keys(a.features).sort(),experiments:Object.fromEntries(Object.entries(a.experiments).map(([l,m])=>[l,m.variations.map(String)])),savedGroups:[...s].sort()})}function Zf(e){return Ei.parse(e)}var Wf=Ct.strictObject({processContext:Pa.optional(),...gi,selector:Ct.discriminatedUnion("type",[Ct.strictObject({type:Ct.literal("paywall"),paywallId:Ct.uuid()}),Ct.strictObject({type:Ct.literal("version"),versionId:Ct.uuid()})]),customerId:Ct.uuid().optional(),commerce:ui,locale:Ct.string().min(1).max(35),requirement:ir.optional()}),xo=Ct.strictObject({id:Ct.uuid(),paywallId:Ct.uuid(),version:Ct.number().int().positive(),document:Ii.omit({requirement:!0,offeringId:!0}),offering:Ct.strictObject({id:Ct.uuid()}),content:Ct.strictObject({environmentId:Ct.uuid(),offeringVersionId:Ct.uuid(),artifact:xu.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:li,check:Rr.nullable()}).superRefine((e,t)=>{let n=new Set(e.document.products.items.map(r=>r.productVersionId));(e.document.offeringVersionId!==e.offering.id||Object.values(e.capabilities.plans).some(r=>!n.has(r.versionId)))&&t.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})}),Vr=Ct.strictObject(xo.shape).omit({document:!0,offering:!0}).extend({content:xo.shape.content.unwrap()});function Yf(e,t){let n=is.parse(t);if(n.offeringVersionId!==e.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");let r=structuredClone(e.capabilities);for(let[i,a]of Object.entries(n.catalog)){let o=r.plans[i],s=a.channels.stripe?.prices.find(c=>c.currency===o?.currency);o&&s&&Object.assign(o,{amountMinor:s.amountMinor,interval:a.interval,intervalCount:a.intervalCount,...a.prepaid?.length?{prepaid:a.prepaid}:{}})}return xo.parse({...e,capabilities:r,document:{schemaVersion:3,kind:n.kind,name:n.name,presentation:n.presentation,products:n.products,offeringVersionId:n.offeringVersionId,screen:n.screen,buttons:n.buttons},offering:{id:n.offeringVersionId}})}import{z as Ht}from"zod";var Xf={requestId:Ht.uuid(),sourceId:Ht.uuid(),expectedAvailable:$t},eg=Ht.discriminatedUnion("action",[Ht.strictObject({...Xf,action:Ht.enum(["add","subtract","set_remaining"]),amount:xe}),Ht.strictObject({...Xf,action:Ht.literal("edit"),granted:xe,expiresAt:Ht.iso.datetime({offset:!0}).nullable(),nextResetAt:Ht.iso.datetime({offset:!0}).nullable(),expectedRevision:Ht.number().int().nonnegative()})]),vu=Ht.strictObject({sourceId:Ht.uuid(),available:$t,held:$t,spent:$t,adjustmentGrantId:Ht.uuid().nullable()}),tg=vu.extend({granted:$t,expiresAt:Ht.iso.datetime({offset:!0}).nullable(),nextResetAt:Ht.iso.datetime({offset:!0}).nullable(),revision:Ht.number().int().nonnegative()});import{z as mn}from"zod";var ng=mn.discriminatedUnion("action",[mn.object({action:mn.literal("upsert"),externalId:mn.string().min(1).max(128),name:mn.string().trim().min(1).max(80)}).strict(),mn.object({action:mn.literal("archive"),entityId:mn.uuid()}).strict()]),rg=mn.object({id:mn.uuid(),externalId:mn.string().min(1).max(128),name:mn.string().min(1).max(80),archived:mn.boolean()}).strict();import{z as Vt}from"zod";import{z as zr}from"zod";var og=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],ig=zr.string().regex(/.+\/.+/),wu=zr.number().min(-100),Lr=zr.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),k0=zr.strictObject({input:Lr,output:Lr,cache_read:Lr.optional(),cache_write:Lr.optional(),reasoning:Lr.optional(),input_audio:Lr.optional(),output_audio:Lr.optional()}),Ou=(e,t)=>zr.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),qk=zr.strictObject({defaultMarkup:wu,providerMarkups:Ou(zr.string().min(1),wu),modelMarkups:Ou(ig,wu),customModels:Ou(ig,k0.partial())});import{z as be}from"zod";var $r=be.iso.datetime({offset:!0}),ur=be.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),j0=be.discriminatedUnion("kind",[be.object({kind:be.literal("absolute"),from:$r,to:$r}).strict(),be.object({kind:be.literal("last_days"),days:be.union([be.literal(1),be.literal(7),be.literal(30),be.literal(90)])}).strict(),be.object({kind:be.literal("billing_cycles"),membershipId:be.uuid(),count:be.number().int().min(1).max(12),includeCurrent:be.boolean()}).strict()]),ag=be.string().max(100).refine(e=>{if(e!=="UTC"&&!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+\-]+)+$/.test(e))return!1;try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Use an IANA timezone"),T0=be.object({key:be.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:be.array(be.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),Gr=be.object({range:j0,timezone:ag,filterBy:be.array(T0).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:be.enum(["hour","day","week","month"]),internal_feature_id:be.uuid().nullable(),entityId:be.uuid().nullable(),topN:be.number().int().min(1).max(50).nullable(),groupBy:be.union([be.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),be.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:be.object({bucket:$r,group:be.string().max(240),isOther:be.boolean(),internal_feature_id:be.uuid(),resourceId:be.uuid()}).strict().nullable(),limit:be.number().int().min(1).max(100)}).strict().superRefine((e,t)=>{if(e.range.kind!=="absolute"){e.interval==="hour"&&e.range.kind==="last_days"&&e.range.days>31&&t.addIssue({code:"custom",message:"Hourly reports are bounded to 31 days"});return}let n=Date.parse(e.range.to)-Date.parse(e.range.from);(n<=0||n>366*864e5||e.interval==="hour"&&n>31*864e5)&&t.addIssue({code:"custom",message:"Reporting range must be positive and bounded (31 days hourly, 366 days otherwise)"})}),sg=be.object({from:$r,to:$r,interval:be.enum(["hour","day","week","month"]),timezone:ag,rows:be.array(be.object({bucket:$r,group:be.string().max(240),isOther:be.boolean(),internal_feature_id:be.uuid(),resourceId:be.uuid(),consumedUnits:ur,refundedUnits:ur,reservedUnits:ur,charged:ur,refunded:ur,reserved:ur,netUnits:ur,netCharged:ur}).strict()).max(100),nextCursor:be.object({bucket:$r,group:be.string().max(240),isOther:be.boolean(),internal_feature_id:be.uuid(),resourceId:be.uuid()}).strict().nullable()}).strict();var Ri=Vt.string().regex(/^(0|[1-9]\d{0,29})$/),cg=Vt.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),Pu=Vt.strictObject({bucket:Vt.iso.datetime({offset:!0}),group:Vt.string().max(240),isOther:Vt.boolean(),internal_feature_id:Vt.uuid()}),ug=Vt.strictObject({...Gr.shape,groupBy:Vt.union([Vt.enum(["customer","entity","entitlement"]),Vt.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Pu.nullable()}).superRefine((e,t)=>{let n=Gr.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),lg=Vt.strictObject({from:Vt.iso.datetime({offset:!0}),to:Vt.iso.datetime({offset:!0}),interval:Gr.shape.interval,timezone:Gr.shape.timezone,rows:Vt.array(Vt.strictObject({...Pu.shape,eventCount:Ri,units:cg,tokenEventCount:Ri,tokens:Vt.strictObject(Object.fromEntries(og.map(e=>[e,Ri]))),totalTokens:Ri,providerCostEventCount:Ri,providerCostUsd:cg,invalidTelemetryEventCount:Ri})).max(100),nextCursor:Pu.nullable()});import{z as bt}from"zod";var dg=bt.object({requestId:bt.uuid(),items:bt.array(bt.object({customerId:bt.uuid(),command:Yi.options[1]}).strict()).min(1).max(1e3)}).strict().refine(e=>new Set(e.items.map(t=>t.customerId+":"+t.command.idempotencyKey)).size===e.items.length,"Each logical event must appear once in a batch"),pg=bt.object({batchId:bt.uuid(),after:bt.number().int().min(-1).max(999),limit:bt.number().int().min(1).max(100)}).strict(),mg=bt.object({batchId:bt.uuid(),status:bt.enum(["queued","complete"]),total:bt.number().int().min(1).max(1e3),processed:bt.number().int().min(0).max(1e3),items:bt.array(bt.object({position:bt.number().int().min(0).max(999),customerId:bt.uuid(),idempotencyKey:bt.string().min(1).max(120),status:bt.enum(["queued","accepted","rejected","failed"]),receipt:Xi.nullable(),errorCode:bt.enum(["invalid_request","forbidden","conflict","internal_error"]).nullable()}).strict().refine(e=>e.status==="queued"?e.receipt===null&&e.errorCode===null:e.status==="failed"?e.receipt===null&&e.errorCode!==null:e.receipt!==null&&e.errorCode===null&&e.receipt.accepted===(e.status==="accepted"))).max(100),nextAfter:bt.number().int().min(0).max(999).nullable()}).strict();import{z as k}from"zod";var N0=k.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),fg=k.enum(["draft","active","paused","archived"]),gg=k.string().min(1).max(256),hg=k.array(gg).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),D0=k.strictObject({duration:k.enum(["day","week","month","year"]),length:k.number().int().min(1).max(3660)}),F0=k.strictObject({internal_feature_id:k.uuid(),allowance:k.number().nonnegative().max(1e15).nullable(),expiry:D0.nullable()}),M0=k.discriminatedUnion("type",[k.strictObject({type:k.literal("feature_grant"),grants:k.array(F0).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),k.strictObject({type:k.literal("free_product"),productId:gg,duration:sn}),k.strictObject({type:k.literal("invoice_credits"),amount:k.number().positive().max(1e8),duration:sn,rollover:k.boolean(),productIds:hg})]),q0=k.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),yg=k.object({key:q0,name:k.string().trim().min(1).max(80),configuration:M0}).strict(),Ag=k.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),Cu=k.object({code:Ag,maxUses:k.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:k.boolean()}).strict(),bg=k.object({key:k.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:k.string().trim().min(1).max(80),rewardId:k.uuid(),redeemOn:k.enum(["customer_creation","checkout"]),receivedBy:k.enum(["referrer","all"]),maxRedemptions:k.number().int().min(1).max(1e6).nullable(),productIds:hg,excludeTrial:k.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),xg={id:k.uuid(),projectId:k.uuid(),environmentId:k.uuid(),revision:k.number().int().nonnegative(),status:fg,createdAt:k.iso.datetime({offset:!0}),updatedAt:k.iso.datetime({offset:!0})},U0=yg.extend(xg).strict(),B0=bg.safeExtend(xg).strict(),Yk=k.strictObject({id:k.uuid(),key:k.string(),name:k.string(),type:N0,status:fg}),Xk=k.discriminatedUnion("action",[k.object({action:k.literal("save"),id:k.uuid().nullable(),revision:k.number().int().nonnegative(),input:yg}).strict(),k.object({action:k.enum(["activate","pause","resume","archive","delete"]),id:k.uuid(),revision:k.number().int().nonnegative()}).strict()]),ej=k.discriminatedUnion("action",[k.object({action:k.literal("save"),id:k.uuid().nullable(),revision:k.number().int().nonnegative(),input:bg}).strict(),k.object({action:k.enum(["activate","pause","resume","archive","delete"]),id:k.uuid(),revision:k.number().int().nonnegative()}).strict()]),Sg=k.object({id:k.uuid(),rewardId:k.uuid(),programId:k.uuid().nullable(),customerId:k.uuid(),referrerId:k.uuid().nullable(),status:k.enum(["pending","applied","unavailable"]),result:k.record(k.string(),k.unknown()).nullable(),createdAt:k.iso.datetime({offset:!0})}).strict(),Ig=k.object({code:Ag,requestId:k.uuid()}).strict(),vg=k.strictObject({redemptionId:k.uuid(),currency:Ie,requestId:k.uuid(),accepted:k.literal(!0)}),V0=k.strictObject({type:k.literal("checkout"),orderId:k.uuid(),productVersionId:k.uuid(),currency:Ie,duration:sn,renewalAmountMinor:k.number().int().positive().max(1e8),status:k.enum(["created","pending","trialing","paid","cancelled","failed"]),url:k.url().nullable()}),wg=k.discriminatedUnion("type",[V0,k.strictObject({type:k.literal("subscription"),operationId:k.uuid(),membershipId:k.uuid(),productVersionId:k.uuid(),currency:Ie,duration:sn,renewalAmountMinor:k.number().int().positive().max(1e8),status:k.enum(["pending","running","applied","failed"])})]),Og=k.object({programId:k.uuid(),requestId:k.uuid()}).strict(),Pg=k.object({id:k.uuid(),programId:k.uuid(),code:Cu.shape.code,createdAt:k.iso.datetime({offset:!0})}).strict(),tj=k.object({rows:k.array(U0).max(100),nextCursor:k.uuid().nullable()}).strict(),nj=k.object({rows:k.array(B0).max(100),nextCursor:k.uuid().nullable()}).strict(),L0=Cu.extend({id:k.uuid(),redemptions:k.number().int().nonnegative()}).strict(),z0=k.strictObject({id:k.uuid(),programId:k.uuid().nullable(),customerId:k.uuid().nullable(),referrerId:k.uuid().nullable(),code:k.string().nullable(),status:k.enum(["pending","triggered","applied"]),createdAt:k.iso.datetime({offset:!0})}),rj=k.object({codes:k.array(L0).max(100),redemptions:k.array(z0).max(100),customers:k.record(k.uuid(),k.string()),codesCursor:k.uuid().nullable(),redemptionsCursor:k.uuid().nullable()}).strict(),ij=k.discriminatedUnion("action",[k.object({action:k.literal("create"),rewardId:k.uuid(),revision:k.number().int().nonnegative(),input:Cu}).strict(),k.object({action:k.literal("remove"),rewardId:k.uuid(),revision:k.number().int().nonnegative(),codeId:k.uuid()}).strict()]);import{z as w}from"zod";import{z as W}from"zod";var Mn={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},So=e=>new Set(e).size===e.length,_u=W.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),$0=W.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),Io=W.string().min(1).max(200).regex(/^[a-zA-Z0-9_./-]+$/).refine(e=>!e.includes("..")&&!e.endsWith(".")&&!e.split("/").some(t=>!t||t.startsWith(".")||t.endsWith(".lock"))),G0=W.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),Cg=W.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var _g=W.strictObject({id:W.uuid(),repo:$0,platform:W.enum(["github","gitlab","bitbucket"]),branches:W.array(Io).min(1).max(4).refine(So),workflow:W.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:W.array(W.uuid()).min(1).max(4).refine(So),include:W.array(Cg).min(1).max(16),exclude:W.array(Cg).max(16),methods:W.array(W.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(So),maxAgeHours:W.number().int().min(1).max(720)}),Eg=_g.extend({revision:W.number().int().positive()}),sj=W.strictObject({repository:_g,expectedRevision:W.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),Rg=W.strictObject({repositoryId:W.uuid(),branch:Io}),K0=W.array(_u).max(Mn.keys).refine(So),kg=W.strictObject({repository:Eg.omit({keyIds:!0}),branch:Io,keys:K0,keySetHash:W.string().regex(/^[a-f0-9]{64}$/)}),H0=W.strictObject({filePath:G0,startingLineNumber:W.number().int().min(1).max(1e7)}),Eu=W.strictObject({protocol:W.literal(1),repositoryId:W.uuid(),branch:Io,workflow:W.string().max(200),configurationRevision:W.number().int().positive(),keySetHash:W.string().regex(/^[a-f0-9]{64}$/),commit:W.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:W.uuid(),runNumber:W.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:W.number().int().min(1).max(1e4),scannerVersion:W.literal("1"),scannedAt:W.iso.datetime({offset:!0}),coverage:W.strictObject({complete:W.literal(!0),files:W.number().int().min(0).max(Mn.files),sourceBytes:W.number().int().min(0).max(Mn.sourceBytes),unresolvedCalls:W.number().int().min(0).max(1e6),unsupportedFiles:W.number().int().min(0).max(Mn.files)}),features:W.array(W.strictObject({key:_u,refs:W.array(H0).max(Mn.referencesPerKey)})).max(Mn.keys)}).superRefine((e,t)=>{So(e.features.map(n=>n.key))||t.addIssue({code:"custom",path:["features"],message:"Duplicate feature"}),e.features.reduce((n,r)=>n+r.refs.length,0)>Mn.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),Ru=W.strictObject({scanId:W.uuid(),commit:W.string(),receivedAt:W.string(),references:W.number().int().nonnegative(),removedReferences:W.number().int().nonnegative()}),Q0=Ru.extend({repositoryId:W.uuid(),branch:Io,workflow:W.string(),digest:W.string(),configurationRevision:W.number().int().positive(),runNumber:W.number().int().positive(),runAttempt:W.number().int().positive(),scannedAt:W.string(),keySetHash:W.string(),coverage:Eu.shape.coverage}),J0=W.strictObject({repositories:W.array(Eg).max(Mn.repositories),scans:W.array(Q0).max(Mn.repositories*Mn.branches)}),Z0=W.strictObject({key:_u,references:W.number().int().nonnegative(),coveredTargets:W.number().int().nonnegative(),expiredTargets:W.number().int().nonnegative(),uncertainTargets:W.number().int().nonnegative()}),cj=W.strictObject({available:W.boolean().default(!0),settings:J0,expectedTargets:W.number().int().min(0).max(80),features:W.array(Z0).max(2001),truncated:W.boolean()});import{z as Ee}from"zod";var rn=Ee.string().min(1).max(200),os=Ee.iso.datetime({offset:!0}),vo=Ee.number().int().min(1).max(Number.MAX_SAFE_INTEGER),ku=Ee.number().int().min(0).max(1e12),Ng=Ee.number().int().min(1).max(1e12),jg={...Zt,type:Ee.literal("coupon.redeemed"),grantId:Ee.uuid()},Tg={...Zt,type:Ee.literal("usage.observed"),merchantTransactionId:rn,resource:rn,unit:rn,quantity:Ng},W0=Ee.strictObject({...Zt,type:Ee.literal("fulfillment.updated"),operationId:Ee.uuid(),merchantFulfillmentId:rn,status:Ee.enum(["pending","applied","failed"])}),Y0=Ee.strictObject({...Zt,type:Ee.literal("benefit.claimed"),merchantBenefitId:rn,resource:rn,unit:rn,quantity:Ng,expiresAt:os.nullable(),revision:vo}),X0=Ee.strictObject({...Zt,type:Ee.literal("benefit.closed"),merchantBenefitId:rn,status:Ee.enum(["failed","expired","canceled"]),revision:vo}),eI=Ee.strictObject({...Zt,type:Ee.literal("benefit.updated"),merchantBenefitId:rn,status:Ee.enum(["active","expired","revoked"]),remainingQuantity:ku.nullable(),expiresAt:os.nullable(),revision:vo}),tI=Ee.strictObject({...Zt,type:Ee.literal("authorization.updated"),merchantAuthorizationId:rn,kind:Ee.literal("auto_topup"),status:Ee.enum(["pending","effective","revoked","failed"]),termsReference:rn.nullable(),revision:vo}),nI=Ee.strictObject({...Zt,type:Ee.literal("balance.observed"),resource:rn,unit:rn,availableQuantity:ku,reservedQuantity:ku,periodStartsAt:os.nullable(),periodEndsAt:os.nullable(),revision:vo}),Dg=Ee.union([Ee.discriminatedUnion("type",[...Ml,W0,Y0,X0,eI,tI,nI]),Ee.strictObject({...jg,productVersionId:Ee.uuid(),subscriptionId:Ee.string().trim().min(1).max(255)}),Ee.strictObject({...jg,merchandiseId:Ee.uuid()}),Ee.strictObject({...Tg,operation:Ee.literal("consume")}),Ee.strictObject({...Tg,operation:Ee.literal("reverse"),reversalOf:rn})]),Fg=Ee.strictObject({id:Ee.uuid(),eventId:Ee.string().min(1).max(200),source:Ee.literal("merchant"),providerVerified:Ee.literal(!1),outcome:Ee.string().min(1).max(100)});import{z as oe}from"zod";var Mg=mm,rI=Mg.extend({invoice_id:Mg.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),ju=oe.strictObject({name:oe.string().trim().min(1).max(255),memo:oe.string().max(1e4).nullable().optional(),footer:oe.string().max(1e4).nullable().optional(),net_terms_days:oe.number().int().positive().nullable().optional()}),iI=ju.extend({id:oe.string().min(1).max(255),created_at:oe.number().nullable()}),qg=oe.strictObject({items:oe.array(iI).max(50),nextCursor:oe.uuid().nullable()}),gj=oe.discriminatedUnion("action",[oe.strictObject({action:oe.literal("create"),requestId:oe.uuid(),values:ju}),oe.strictObject({action:oe.literal("update"),id:oe.string().min(1).max(255),values:ju}),oe.strictObject({action:oe.literal("delete"),id:oe.string().min(1).max(255)})]),Ug=oe.discriminatedUnion("action",[oe.strictObject({action:oe.literal("create"),requestId:oe.uuid(),params:yi}),oe.strictObject({action:oe.enum(["finalize","send","pay","void"]),requestId:oe.uuid(),invoiceId:oe.uuid()}),oe.strictObject({action:oe.literal("reissue"),requestId:oe.uuid(),invoiceId:oe.uuid(),params:rI})]),Tu=oe.strictObject({id:oe.uuid(),customerId:oe.uuid(),providerInvoiceId:oe.string().nullable(),status:oe.enum(["draft","open","paid","void","uncollectible"]),currency:oe.string(),totalMinor:oe.string().regex(/^-?\d+$/),paidMinor:oe.string().regex(/^\d+$/),refundedMinor:oe.string().regex(/^\d+$/),hostedInvoiceUrl:oe.url().nullable(),createdAt:oe.number(),collectionMethod:oe.enum(["send_invoice","charge_automatically"]).nullable()}),Bg=Tu.extend({lines:oe.array(oe.strictObject({id:oe.uuid(),description:oe.string(),amountMinor:oe.string().regex(/^-?\d+$/),netAmountMinor:oe.string().regex(/^-?\d+$/),quantity:oe.number().nullable(),periodStart:oe.number().nullable(),periodEnd:oe.number().nullable()})).max(1e3)}),ki=oe.strictObject({taskId:oe.uuid(),status:oe.enum(["ready","running","done","dead"]),invoice:Tu.nullable(),errorCode:oe.string().nullable()}),Vg=oe.strictObject({items:oe.array(Tu).max(50),nextCursor:oe.uuid().nullable(),operations:oe.array(ki).max(50),operationsLimited:oe.boolean()});var oI=w.enum(["customers:read","customers:write","entitlements:read","content:read","sessions:create","funnels:run","offers:resolve","offers:grant","billing:read","billing:write","credits:read","credits:consume","credits:manage","features:read","events:write","messaging:write","code-references:read","code-references:write","app-manifests:write"]),Lg={scope:Ne,permissions:w.array(oI),expiresAt:w.iso.datetime().nullable()},aT=w.discriminatedUnion("kind",[w.object({...Lg,kind:w.literal("server"),keyId:w.string().min(1)}),w.object({...Lg,kind:w.literal("customer"),customerId:w.string().min(1),identityKind:w.enum(["identified","guest"]),expiresAt:w.iso.datetime()})]),z=w.object({requestId:w.uuid(),scope:Ne}).strict(),aI=_f.safeExtend({fingerprint:Ja.optional()}).strict(),sI=z.extend({customer:Ci,created:w.boolean()});function zg(){return z.extend({offer:Gi.nullable(),reason:Ld.nullable()})}var O={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:jp,response:z.extend({message:w.object({messageId:w.uuid(),channel:ro,acceptedAt:w.iso.datetime({offset:!0}),status:w.enum(["accepted","sending","completed","canceled"]),replayed:w.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:w.strictObject({messageId:w.uuid()}),response:z.extend({message:w.object({id:w.uuid(),channel:ro,status:w.enum(["accepted","sending","completed","canceled"]),deliveries:w.array(w.object({id:w.uuid(),status:Np,attempts:w.number().int().nonnegative(),receipts:w.array(w.object({kind:Dp,occurredAt:w.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:Sl,response:z.extend({installation:Ir})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:Il,response:z.extend({installation:Ir})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:qo,response:z.extend({installation:Ir})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:w.strictObject({channel:ro}),response:z.extend({preference:Cs})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:Tp,response:z.extend({preference:Cs})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:w.strictObject({cursor:w.uuid().optional()}),response:z.extend({templates:qg})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:w.strictObject({customerId:w.uuid(),params:yi}),response:z.extend({preview:kc})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:w.strictObject({customerId:w.uuid(),requestId:w.uuid(),params:yi}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:z.extend({operation:ki})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:w.strictObject({customerId:w.uuid(),command:Ug}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:z.extend({operation:ki})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:w.strictObject({customerId:w.uuid(),taskId:w.uuid()}),response:z.extend({operation:ki})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:w.strictObject({customerId:w.uuid(),cursor:w.uuid().optional()}),response:z.extend({invoices:Vg})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:w.strictObject({customerId:w.uuid(),invoiceId:w.uuid()}),response:z.extend({invoice:Bg})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:Rg,response:z.extend({config:kg})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:Eu,response:z.extend({receipt:Ru})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:w.strictObject({}),response:z.extend({payload:fo})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:of,response:z.merge(Ua)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:af,response:z.merge(sf)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:w.strictObject({customerId:w.uuid(),sourceId:w.uuid()}),response:z.extend({balance:tg})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:w.strictObject({customerId:w.uuid(),command:eg}),response:z.extend({balance:vu})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:w.strictObject({internal_feature_id:w.uuid(),customerId:w.uuid().optional(),entityId:w.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:z.extend({internal_feature_id:w.uuid(),config:Ls,model_markups:Jo})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:w.strictObject({customerId:w.uuid(),query:fa}),response:z.extend({usage:eo})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:w.strictObject({customerId:w.uuid(),command:vp}),response:z.extend({usage:eo})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:w.strictObject({customerId:w.uuid(),command:yp}),response:z.extend({grant:dc})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:Ap,response:z.extend({grants:bp})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:w.union(Km.options.map(e=>e.extend({customerId:w.uuid().optional(),customerToken:w.string().regex(kt).optional()}))),response:z.extend({operation:Hm})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:Dm.extend({customerId:w.uuid().optional()}),response:z.extend({setup:Fc})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Fm.extend({customerId:w.uuid().optional()}),response:z.extend({setup:Fc})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:jm.safeExtend({customerId:w.uuid()}),response:z.extend({batch:lo})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:ka.extend({customerId:w.uuid()}),response:z.extend({batch:lo})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:ka.extend({customerId:w.uuid()}),response:z.extend({batch:lo})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:ka.extend({customerId:w.uuid()}),response:z.extend({batch:lo})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:w.discriminatedUnion("action",[ja.options[0].extend({customerId:w.uuid()}),ja.options[1].extend({customerId:w.uuid()}),ja.options[2].extend({customerId:w.uuid()})]),response:z.extend({trial:Dc})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Tm.extend({customerId:w.uuid()}),response:z.extend({trial:Dc})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:Da,response:z.extend({subscriptions:zm})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:Da,response:z.extend({purchases:$m})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:Bm,response:z.extend({conflicts:Gm})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:Vm,response:z.extend({resolution:Lm})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:qm,response:z.extend({verification:Um})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:wm.safeExtend({...gi,customerId:w.uuid().optional()}),response:z.extend({quote:Ai})},recordMerchantEvent:{method:"POST",path:"merchant/events/record",permission:"billing:write",audience:"server",request:Dg,response:z.extend({record:Fg})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Mr.extend({customerId:w.uuid().optional(),intent:w.enum(["confirm","cancel"]).optional()}),response:z.extend({operation:bi})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Mr.extend({customerId:w.uuid().optional()}),response:z.extend({operation:bi})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:Cm.safeExtend({customerId:w.uuid().optional()}),response:z.extend({quote:Em})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Mr.extend({customerId:w.uuid().optional(),intent:w.enum(["confirm","cancel"]).optional()}),response:z.extend({operation:jc})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Mr.extend({customerId:w.uuid().optional()}),response:z.extend({operation:jc})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:Rm.safeExtend({customerId:w.uuid()}),response:z.extend({quote:Tc})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Mr.extend({customerId:w.uuid()}),response:z.extend({operation:Ra})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Mr.extend({customerId:w.uuid()}),response:z.extend({operation:Ra})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:np,response:z.extend({controls:uc})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:Jd,response:z.extend({prepared:Wd})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:Yd,response:z.extend({authorization:la})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:sp,response:z.extend({coupons:cp})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Xd,response:z.extend({authorization:la})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:op,response:z.extend({invoices:ap})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:ip.extend({customerId:w.uuid()}),response:z.extend({operation:ki})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:rp,response:z.extend({invoice:Qi})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:w.object({customerId:w.uuid(),command:tp}).strict(),response:z.extend({controls:uc})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:w.object({customerId:w.uuid(),command:ng}).strict(),response:z.extend({entity:rg})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:w.strictObject({customerId:w.uuid().nullable(),query:ug}),response:z.extend({analytics:lg})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:w.object({customerId:w.uuid().nullable(),query:Gr}).strict(),response:z.extend({analytics:sg})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:dg,response:z.extend({batchId:w.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:pg,response:z.extend({batch:mg})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:qp.extend({customerId:w.string().min(1).optional()}),response:z.extend({check:Rr})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:w.strictObject({kind:ar,selector:w.discriminatedUnion("type",[w.strictObject({type:w.literal("resource"),id:w.uuid()}),w.strictObject({type:w.literal("version"),id:w.uuid()})]),customerId:w.string().min(1).optional()}),response:z.extend({content:Ec})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Wf,response:z.extend({paywall:Vr})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:w.strictObject({processContext:Pa.optional(),...gi,selector:Wm,customerId:w.string().min(1).optional(),commerce:ui,requirement:ir.optional()}),response:z.extend({offering:Ym,candidates:w.array(hc).max(20),availability:w.array(w.strictObject({productVersionId:w.uuid(),available:w.boolean(),reason:w.enum(["platform_binding_missing","commercial_runtime_pending","commerce_not_configured","currency_mismatch","product_unavailable","already_attached","attach_in_progress","already_scheduled","subscription_change_required","purchase_conflict"]).nullable()})).max(20),check:Rr.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:w.object({customerId:w.uuid().optional(),entityId:w.uuid().optional()}).strict(),response:z.extend({holdings:wp})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:w.object({customerId:w.uuid().optional(),query:Pp}).strict(),response:z.extend({ledger:Cp})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:xp.extend({customerId:w.uuid().optional()}),response:z.extend({detail:Sp})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:pc.safeExtend({customerId:w.uuid().optional()}),response:z.extend({statement:Ip})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:w.object({customerId:w.uuid().optional(),command:Yi.options[0]}).strict(),response:z.extend({quote:fp})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:w.strictObject({customerId:w.uuid(),command:w.union([w.strictObject({eventName:w.string().min(1),quantity:xe.optional(),properties:vt.optional(),entityId:w.uuid().optional(),idempotencyKey:w.string().min(1).max(120)}),w.strictObject({internal_feature_id:w.uuid(),quantity:xe.optional(),properties:vt.optional(),entityId:w.uuid().optional(),idempotencyKey:w.string().min(1).max(120)})])}),response:z.extend({receipts:w.array(Xi).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:w.object({customerId:w.uuid(),command:Yi.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:z.extend({receipt:Xi})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:Ig,response:z.extend({redemption:Sg})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:Og,response:z.extend({referralCode:Pg})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:vg,response:z.extend({checkout:wg})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:Ep,response:z.extend({seats:gc})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Rp,response:z.extend({seats:gc})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:aI,response:sI},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:au,response:z.extend({customer:Ci})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:kf,response:z.extend(jf.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:Rf,response:z.extend(Ef.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:w.object({customerId:w.uuid()}).strict(),response:z.extend(Wn.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:w.strictObject({}),response:z.extend(Wn.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:w.strictObject({customerId:w.uuid(),sessionId:w.uuid().optional()}),response:z.extend({revoked:w.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:w.strictObject({guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:Ja.optional()}),response:z.extend({customerId:w.uuid(),guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:w.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:w.strictObject({guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:z.extend(Wn.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:w.strictObject({guestToken:w.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:w.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:w.uuid()}),response:z.extend({customer:Ci,switched:w.boolean(),replayed:w.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:w.strictObject({code:w.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:w.uuid()}),response:zg()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:w.object({}).strict(),response:z.extend({offers:w.array(Gi)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:w.object({customerId:w.string().min(1).max(255).optional(),couponId:w.uuid(),...gi,requestId:w.uuid(),couponContentDigest:w.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:zg()}},sT={recordMerchantEvent:O.recordMerchantEvent,sendMessage:O.sendMessage,readMessage:O.readMessage,bindPushInstallation:O.bindPushInstallation,readPushInstallation:O.readPushInstallation,updatePushAddress:O.updatePushAddress,readMessagingPreference:O.readMessagingPreference,setMessagingPreference:O.setMessagingPreference,listInvoiceTemplates:O.listInvoiceTemplates,previewInvoice:O.previewInvoice,createInvoice:O.createInvoice,manageInvoice:O.manageInvoice,readInvoiceOperation:O.readInvoiceOperation,listInvoices:O.listInvoices,getInvoice:O.getInvoice,getCodeReferenceConfig:O.getCodeReferenceConfig,submitCodeReferences:O.submitCodeReferences,getFeatures:O.getFeatures,evaluateFeatures:O.evaluateFeatures,trackEvents:O.trackEvents,setupPayment:O.setupPayment,readPaymentSetup:O.readPaymentSetup,previewSubscriptionBatch:O.previewSubscriptionBatch,confirmSubscriptionBatch:O.confirmSubscriptionBatch,readSubscriptionBatch:O.readSubscriptionBatch,abandonSubscriptionBatch:O.abandonSubscriptionBatch,manageSubscriptionTrial:O.manageSubscriptionTrial,readSubscriptionTrial:O.readSubscriptionTrial,listSubscriptions:O.listSubscriptions,listPurchases:O.listPurchases,listSubscriptionConflicts:O.listSubscriptionConflicts,retrySubscriptionConflict:O.retrySubscriptionConflict,readAiPricing:O.readAiPricing,readUsage:O.readUsage,setUsage:O.setUsage,previewRefund:O.previewRefund,refund:O.refund,readRefund:O.readRefund,previewUpdate:O.previewUpdate,update:O.update,readSubscriptionUpdate:O.readSubscriptionUpdate,restoreNativePurchase:O.restoreNativePurchase,verifySubscriptions:O.verifySubscriptions,previewAttach:O.previewAttach,attach:O.attach,readSubscriptionOperation:O.readSubscriptionOperation,manageBalanceGrant:O.manageBalanceGrant,readBalanceSource:O.readBalanceSource,adjustBalance:O.adjustBalance,listBalanceGrants:O.listBalanceGrants,readBillingControls:O.readBillingControls,prepareBillingAuthorization:O.prepareBillingAuthorization,confirmBillingAuthorization:O.confirmBillingAuthorization,setBillingCoupons:O.setBillingCoupons,revokeBillingAuthorization:O.revokeBillingAuthorization,listBillingInvoices:O.listBillingInvoices,confirmBillingAdjustment:O.confirmBillingAdjustment,prepareBillingAdjustment:O.prepareBillingAdjustment,manageBillingLimits:O.manageBillingLimits,createCustomer:O.createCustomer,getCustomer:O.getCustomer,listCustomers:O.listCustomers,updateCustomer:O.updateCustomer,createSession:O.createSession,refreshSession:O.refreshSession,revokeSessions:O.revokeSessions,createGuestCustomer:O.createGuestCustomer,resumeGuestSession:O.resumeGuestSession,claimGuestCustomer:O.claimGuestCustomer,checkEntitlement:O.checkEntitlement,resolveOffering:O.resolveOffering,resolveContent:O.resolveContent,resolvePaywall:O.resolvePaywall,readHoldings:O.readHoldings,readLedger:O.readLedger,readBillingInvoice:O.readBillingInvoice,readCreditStatement:O.readCreditStatement,quoteBalance:O.quoteBalance,trackUsage:O.trackUsage,mutateBalance:O.mutateBalance,manageUsageEntity:O.manageUsageEntity,readUsageAnalytics:O.readUsageAnalytics,readCreditAnalytics:O.readCreditAnalytics,submitUsageBatch:O.submitUsageBatch,readUsageBatch:O.readUsageBatch,listOffers:O.listOffers,grantOffer:O.grantOffer,redeemCoupon:O.redeemCoupon,redeemReward:O.redeemReward,createReferralCode:O.createReferralCode,claimRewardProduct:O.claimRewardProduct,readSeats:O.readSeats,manageSeat:O.manageSeat};import{z as Nu}from"zod";var wo=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function Du(e,t,n){let r={},i,a,o,s="next",c;switch(e.type){case"entry":c=e.next;break;case"condition":{let u=e.cases.findIndex(l=>en(t.attributes??{},l.condition,t.savedGroups??{}));s=u<0?"default":`case:${u}`,c=u<0?e.default:e.cases[u].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new wo("Required GB Feature is unavailable");i=Kn(e.featureKey,t),o=i.value,Object.assign(r,fi(e,{value:o})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new wo("Required GB Experiment is unavailable");if(a=ca(u,t),o=a.value,s=a.inExperiment&&!a.passthrough&&typeof o=="string"?o:"notParticipating",c=s==="notParticipating"?e.notParticipating:e.routes[s],!c)throw new wo("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:Kn(e.configuration.featureKey,t).value;o={type:"offering_version",id:Nu.uuid().parse(u)},Object.assign(r,fi(e,{value:o})),c=e.next;break}case"coupon":case"coupons":o=e.type==="coupons"?e.couponIds.map(u=>({type:"reward",id:u})):{type:"reward",id:e.couponId},Object.assign(r,fi(e,{value:o})),c=e.next;break}return{port:s,target:c,projections:r,...o===void 0?{}:{value:o},...i?{feature:i}:{},...a?{experiment:a}:{}}}function $g(e,t,n){Nu.uuid().parse(e),Nu.number().int().nonnegative().parse(t);let r=ni(ri(new TextEncoder().encode(JSON.stringify([e,t,n])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}import{z as H}from"zod";var lr=H.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),cI=H.enum(["running","waiting","completed","closed","ineligible","failed"]),Fu=H.discriminatedUnion("type",[iu,H.strictObject({type:H.literal("wait"),receiptId:H.uuid(),kind:H.enum(["timer","event","operation"]),deadline:H.iso.datetime({offset:!0}).nullable(),eventName:lr.optional()}),H.strictObject({type:H.literal("open_url"),receiptId:H.uuid(),url:su,openIn:cu}),H.strictObject({type:H.literal("event"),receiptId:H.uuid(),event:lr})]),as=H.strictObject({type:H.literal("funnel"),id:H.uuid(),versionId:H.uuid()}),uI={id:lr,presentation:Pn,outputs:H.array(lr).max(250),inputs:za,values:H.record(H.string(),ve).optional(),offeringKey:It.optional(),capabilities:li,customerData:Gp,dataCursors:H.record(lr,La.nullable())},lI=H.strictObject({...uI,content:H.strictObject({type:H.literal("document"),document:un})}),Oo=H.strictObject({id:H.uuid(),source:as,revision:H.number().int().nonnegative(),visit:H.number().int().nonnegative(),nodeId:lr,nodeType:H.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:cI,stopped:H.boolean(),canBack:H.boolean(),authenticated:H.boolean(),locale:H.string().min(1).max(35),answers:sr,parameters:cr,variables:H.record(H.string(),ve),output:ve.nullable(),screen:lI.nullable(),paywall:H.strictObject({receiptId:H.uuid(),resolution:H.union([xo,Vr]),quote:Ai.nullable(),operation:bi.nullable(),purchaseRequestId:H.uuid().nullable(),selectionGeneration:H.number().int().nonnegative().optional(),canReselect:H.boolean().optional()}).nullable(),instruction:Fu.nullable(),pendingRequest:H.strictObject({requestId:H.uuid(),authenticationRequired:H.boolean()}).nullable(),runExpiresAt:H.iso.datetime({offset:!0}),credentialExpiresAt:H.iso.datetime({offset:!0}).nullable()}),ss=H.strictObject({scope:Ne,run:Oo,settlement:H.strictObject({requestId:H.uuid(),state:H.enum(["pending","unknown","settled"]),operationId:H.uuid().nullable(),receiptId:H.uuid().nullable().optional()}).optional(),purchase:H.strictObject({receiptId:H.uuid(),quote:Ai.nullable(),operation:bi.nullable(),canReselect:H.boolean().optional()}).optional(),review:H.strictObject({activeOperationId:H.uuid().nullable(),pages:H.array(H.strictObject({receiptId:H.uuid(),nodeId:lr,visit:H.number().int().nonnegative()})).max(100),page:H.strictObject({receiptId:H.uuid(),nodeId:lr,visit:H.number().int().nonnegative(),document:un,answers:sr,inputs:za,values:H.record(H.string(),ve).optional()}).nullable(),coupons:H.array(H.strictObject({grantId:H.uuid(),status:H.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:H.string().nullable()})).max(100),purchases:H.array(H.strictObject({receiptId:H.uuid(),operationId:H.uuid(),status:H.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:H.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:H.uuid().optional()}),Gg=ss.extend({run:Oo.extend({paywall:Oo.shape.paywall.unwrap().extend({resolution:Vr}).nullable()})});var Kg="X-Indiana-Server-Key";import{z as se}from"zod";import{z as Ae}from"zod";import{z as _t}from"zod";var dI=_t.strictObject({selector:_t.string().min(1).max(2048),action:_t.enum(["set","append","remove"]),attribute:_t.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:_t.string().max(5e4).optional(),parentSelector:_t.string().max(2048).optional(),insertBeforeSelector:_t.string().max(2048).optional()}),pI=_t.strictObject({variation:_t.string().min(1).max(128),description:_t.string().max(2e3).default(""),css:_t.string().max(1e5).default(""),js:_t.string().max(1e5).default(""),domMutations:_t.array(dI).max(200).default([]),iam:gf.optional(),renderGuard:Ba.optional()}),Mu=pI.omit({variation:!0,description:!0,iam:!0}),mI=wi.omit({variations:!0,active:!0}).extend({changeId:_t.string().regex(/^[a-f0-9]{64}$/),variations:_t.tuple([Mu,Mu]).rest(Mu).refine(e=>e.length<=20)}),Hg=_t.strictObject({trackExposures:_t.boolean(),environmentId:_t.uuid(),generation:_t.string().regex(/^[a-f0-9]{64}$/),experiments:_t.array(mI).max(100),savedGroups:mo});var Po=Ae.string().regex(/^[a-f0-9]{64}$/),VT=Ae.strictObject({iam:Po,executionContracts:Ae.union([Ae.tuple([Ae.literal("funnel-run/1")]),Ae.tuple([Ae.literal("funnel-process/1")])]).default(["funnel-run/1"])}),fI=Ae.strictObject({release:Po,render:Ba,button:Ae.strictObject({selector:Ae.string().min(1).max(512),elementKey:Ae.string().min(1).max(256),tag:Ae.enum(["button","a","input"])}).nullable()}),LT=Ae.strictObject({scope:Ne.extend({environmentId:Ae.uuid()}),release:Po,validatedAt:Ae.iso.datetime({offset:!0}),validUntil:Ae.iso.datetime({offset:!0}),entries:Ae.array(Ae.strictObject({id:Ae.uuid(),funnelId:Ae.uuid(),versionId:Ae.uuid(),event:Ae.enum(["screen_enter","button_click"]),target:fI})).max(4e3)}),Qg=Ae.strictObject({operation:Ae.literal("entry_start"),funnelId:Ae.uuid(),versionId:Ae.uuid(),entryId:Ae.uuid(),release:Po,requestId:Ae.uuid(),locale:Ae.string().min(1).max(35).default("en")}),Jg=Ae.strictObject({scope:Ne,suppressed:Ae.literal(!0),reason:Ae.enum(["frequency","in_progress"]),retryAt:Ae.iso.datetime({offset:!0}).nullable()}),zT=Ae.strictObject({experimentId:Ae.uuid(),splitNodeId:Ae.string().min(1).max(128)}),gI=Ae.strictObject({experimentId:Ae.uuid(),experimentKey:Ae.string().min(1).max(128),variationKey:Ae.string().min(1).max(128),inExperiment:Ae.boolean(),generation:Ae.string().min(1).max(256)}),Co=Ae.strictObject({operation:Ae.literal("page_experiments"),release:Po,usedReceiptIds:Ae.array(Ae.uuid()).max(20).default([]),customerToken:Ae.string().regex(kt).optional()}),Zg=Ae.strictObject({scope:Ne,runId:Ae.uuid(),assignments:Ae.array(gI.extend({receiptId:Ae.uuid()})).max(100),payload:Hg});var jn=se.literal(uf),hI=se.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),qu=se.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),Wg=se.discriminatedUnion("type",[se.strictObject({type:se.literal("guest"),guestToken:qu}),se.strictObject({type:se.literal("customer"),customer:Ur,customerData:Pi.optional()})]),Uu=se.strictObject({id:se.uuid(),runId:se.uuid(),customerId:se.uuid(),requestId:se.uuid(),acceptedAt:se.iso.datetime({offset:!0})}),yI=se.strictObject({participantId:se.uuid(),startedAs:se.enum(["guest","identified"]),binding:Uu.omit({runId:!0,requestId:!0}).nullable()}),AI=se.union([Fu,se.strictObject({type:se.literal("authentication_required"),reason:se.enum(["customer_required","customer_experiment_required"]),nodeId:se.string().min(1).max(64),visit:se.number().int().nonnegative()})]),bI=Oo.omit({authenticated:!0}).extend({identity:yI,instruction:AI.nullable()}),xI=se.discriminatedUnion("operation",[Ot.options[2].omit({customerToken:!0}),Ot.options[3].omit({customerToken:!0}),Ot.options[4].omit({customerToken:!0}),Ot.options[5].omit({customerToken:!0}),Ot.options[6].omit({customerToken:!0}),Ot.options[7].omit({customerToken:!0})]),cs={contract:jn,customerToken:se.string().regex(kt)},Yg={contract:jn,requestId:se.uuid(),runToken:hI,externalUserId:Ur.options[1].shape.value},Xg=se.discriminatedUnion("operation",[se.strictObject({contract:jn,operation:se.literal("describe")}),se.strictObject({contract:jn,operation:se.literal("start"),source:Wg,funnelId:Ot.options[0].shape.funnelId,requestId:se.uuid(),locale:Ot.options[0].shape.locale,parameters:Ot.options[0].shape.parameters}),Qg.omit({operation:!0}).extend({contract:jn,operation:se.literal("entry_start"),source:Wg}),se.strictObject({...Yg,operation:se.literal("bind_customer"),guestToken:qu,claimRequestId:se.uuid(),expectedBindingId:se.null()}),se.strictObject({...Yg,operation:se.literal("binding_status"),guestToken:qu.optional()}),Ot.options[1].omit({operation:!0,customerToken:!0}).extend({...cs,operation:se.literal("get"),settlementBindingId:se.uuid().nullable().optional()}),Ot.options[8].omit({operation:!0,customerToken:!0}).extend({...cs,operation:se.literal("review")}),Co.omit({customerToken:!0}).extend(cs),se.strictObject({...cs,operation:se.literal("command"),identity:se.strictObject({bindingId:se.uuid().nullable()}),command:xI})]),Bu=ss.omit({run:!0}).extend({contract:jn,run:bI,settlement:ss.shape.settlement.unwrap().extend({accepted:se.boolean().nullable().optional()}).optional()}),XT=Jg.extend({contract:jn}),eN=se.discriminatedUnion("operation",[Xg.options[1].omit({contract:!0,source:!0,requestId:!0}),Xg.options[2].omit({contract:!0,source:!0,requestId:!0})]),tN=Bu.extend({binding:Uu,outcome:se.enum(["bound","already_bound"]),replayed:se.boolean()}),nN=se.discriminatedUnion("state",[se.strictObject({contract:jn,scope:Ne,state:se.literal("not_accepted")}),se.strictObject({contract:jn,scope:Ne,state:se.literal("conflict")}),se.strictObject({contract:jn,scope:Ne,state:se.literal("bound"),binding:Uu})]),rN=se.strictObject({contract:jn,scope:Ne,keyId:se.uuid(),operations:se.array(se.string()).max(20)});import{z as Fe}from"zod";var ji=Fe.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),th=Fe.strictObject({entry:ji,nodes:Fe.array(Fe.strictObject({id:ji,type:Fe.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:Fe.record(Fe.string(),ji),writes:Fe.record(It,It),resources:Fe.strictObject({screenId:ji.optional(),paywallVersionId:Fe.uuid().optional(),couponId:Fe.uuid().optional(),couponIds:Fe.array(Fe.uuid()).max(20).optional(),experimentId:Fe.uuid().optional(),featureKey:Fe.string().optional(),offeringVersionId:Fe.uuid().optional()})})).min(1).max(500)}),eh={scope:Ne,funnelId:Fe.uuid(),versionId:Fe.uuid(),evaluationRevision:Fe.number().int().nonnegative(),expiresAt:Fe.iso.datetime({offset:!0}).nullable(),topology:th},us=Fe.discriminatedUnion("evaluationMode",[Fe.strictObject({...eh,evaluationMode:Fe.literal("local"),growth:yn,conditions:Fe.record(ji,Fe.array(Fe.strictObject({condition:Yt,port:Fe.string()})))}),Fe.strictObject({...eh,evaluationMode:Fe.literal("remote")})]),SI=us.options[0].extend({evaluation:Fe.strictObject({maxTransitions:Fe.number().int().min(1).max(1e4),variables:Fe.record(It,mi),outputSchema:pi,terminals:Fe.record(ji,Fe.strictObject({outcome:Fe.enum(["completed","closed","ineligible","failed"]),output:ho.nullable()}))})});function II(e){return th.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let n={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":n.next=t.next;break;case"screen":Object.assign(n,t.outputs),r.screenId=t.screenId;{let a=e.screens.find(o=>o.id===t.screenId);a?.type==="paywall"&&(r.paywallVersionId=a.paywallVersionId)}break;case"condition":t.cases.forEach((a,o)=>{n[`case:${o}`]=a.target}),n.default=t.default;break;case"split":Object.assign(n,t.routes),n.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let a of["success","cancel","unavailable","failure"])n[a]=t[a];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=Fe.uuid().parse(t.action.coupon.value.id));break;case"external_page":n.opened=t.opened,n.failed=t.failed;break;case"wait":t.wait.type==="duration"?n.elapsed=t.wait.elapsed:(n.received=t.wait.received,n.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let i=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return i?.type==="feature"&&(r.featureKey=i.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:n,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function Vu(e){let t=Ei.parse(e.document),n=e.evaluationMode==="local"?yn.parse(e.payload):null;if(n&&(n.scope.projectId!==e.scope.projectId||n.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:n?.expiresAt??null,topology:II(t)};return us.parse(e.evaluationMode==="remote"?r:{...r,growth:ns(t,n),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((a,o)=>({condition:a.condition,port:`case:${o}`}))]))})}function nh(e){let t=Vu(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=Ei.parse(e.document);return SI.parse({...t,evaluation:{maxTransitions:n.execution.maxTransitions,variables:n.variables,outputSchema:n.outputSchema,terminals:Object.fromEntries(n.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}import{z as rt}from"zod";var rh=rt.string().regex(/^[a-f0-9]{64}$/),vI=wi.omit({variations:!0,active:!0}).extend({changeId:rh,variations:rt.array(rt.strictObject({urlRedirect:rt.string().max(2048)})).min(2).max(20)}),ih=rt.strictObject({environmentId:rt.uuid(),trackExposures:rt.boolean(),generation:rh,experiments:rt.array(vI).max(100),savedGroups:mo}),wI=rt.strictObject({eventUuid:rt.uuid(),timestamp:rt.iso.datetime({offset:!0}).optional(),deviceId:rt.string().min(1).max(128),sessionId:rt.string().min(1).max(128).optional(),url:rt.url().max(2048),pageTitle:rt.string().max(512).optional(),experimentKey:rt.string().min(1).max(255),variationKey:rt.string().min(1).max(64)}),hN=rt.strictObject({events:rt.array(wI).min(1).max(20)}),yN=rt.strictObject({inserted:rt.number().int().nonnegative(),duplicates:rt.number().int().nonnegative(),skipped:rt.number().int().nonnegative(),rejected:rt.array(rt.strictObject({index:rt.number().int().nonnegative(),reason:rt.string()}))});import{z as lt}from"zod";var zu=32,OI=522240;function $u(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var PI=lt.strictObject({nodeId:lt.string().min(1).max(64),visit:lt.number().int().nonnegative(),revision:lt.number().int().nonnegative()}),Lu=lt.record(lt.string(),ve),CI=lt.strictObject({id:lt.uuid(),nodeId:lt.string().min(1).max(64),visit:lt.number().int().nonnegative(),input:lt.strictObject({schemaVersion:yo.shape.schemaVersion,kind:yo.shape.kind,selector:yo.shape.selector,contract:yo.shape.contract}),context:Lu,removed:lt.array(lt.string()).max(100),attributes:Lu,removedAttributes:lt.array(lt.string()).max(100),result:Uf,offeringVersionId:lt.uuid().nullable(),events:lt.strictObject({entered:lt.string().regex(/^[1-9][0-9]{0,18}$/),decision:lt.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),vN=lt.strictObject({schemaVersion:lt.literal(1),mode:lt.enum(["local","remote"]),versionId:lt.uuid(),generation:lt.number().int().positive(),base:PI,context:Lu,steps:lt.array(CI).min(1).max(zu)}).refine(e=>ln(e)<=OI,"Segment exceeds its byte budget");var _I=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function _o(e){return Array.isArray(e)?e.some(_o):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&_o(n):!_I.test(t))}function oh(e,t,n,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(s=>s.id===t.screenId&&s.type==="paywall")))return"customer_required";let i=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(i&&["bundle","selection","offering"].includes(i.type)||t.type==="condition"&&t.cases.some(s=>_o(s.condition)))return"customer_required";let a=JSON.stringify([t,t.type==="screen"?e.screens.find(s=>s.id===t.screenId):null]);for(let[s,c]of Object.entries(e.variables))if(c.source.type==="attribute"&&c.source.key!=="funnelParticipantId"&&(a.includes(`variables.${s}`)||a.includes(JSON.stringify(s))))return"customer_required";if(t.type==="split"){let s=n.experiments?.[t.experimentId];if((s?.hashAttribute??"id")!=="funnelParticipantId"||_o(s?.condition)||s?.parentConditions?.length)return"customer_experiment_required"}let o=t.type==="feature"?t.featureKey:i?.type==="feature"?i.featureKey:void 0;return o&&n.features?.[o]?.rules?.some(s=>(s.hashAttribute??"id")!=="funnelParticipantId"||_o(s.condition)||s.parentConditions?.length)?"customer_experiment_required":null}var Gu=class extends Error{constructor(n,r){super(r);qe(this,"code",n);this.name="FunnelLocalCalculationError"}},ah=(e,t)=>new Gu(e,t),EI=e=>({experiments:e.experiments,features:e.features});function RI(e,t=ah){let n=new Map(e.topology.nodes.map(o=>[o.id,o])),r=ii(e.growth.savedGroups),i=EI(e.growth);function a(o,s){if(!Object.hasOwn(e.growth.features,o))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Kn(o,s).value}return{nodes:n,savedGroups:r,features:i.features,feature:a,evaluate(o,s){let c=n.get(o);if(!c)throw t("NOT_FOUND","Funnel node is unavailable");let u,l;if(c.type==="condition"){let f=e.conditions[c.id];if(!f)throw t("INVALID_RESPONSE","Local condition rules are unavailable");u=Du({id:c.id,name:c.id,type:"condition",cases:f.map(g=>({condition:g.condition,target:c.outputs[g.port]})),default:c.outputs.default},s,i.experiments).port}else if(c.type==="feature"){if(!c.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");l=a(c.resources.featureKey,s),u="next"}else if(c.type==="split"){if(!(c.resources.experimentId?e.growth.experiments[c.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let g=Du({id:c.id,name:c.id,type:"split",experimentId:c.resources.experimentId,routes:c.outputs,notParticipating:c.outputs.notParticipating},s,i.experiments);l=g.value,u=g.port}else if(["offering","end","output"].includes(c.type)&&c.resources.featureKey)l=a(c.resources.featureKey,s),u=c.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let m=c.outputs[u]??(u==="value"?c.id:void 0);if(!m)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:o,port:u,target:m,...l===void 0?{}:{value:l}}}}}function kI(e,t){let n=us.parse(e);if(n.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=n.expiresAt?Date.parse(n.expiresAt):null,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let a=RI(n,t);return(o,s)=>(i(),jI(a,o,s))}function jI(e,t,n){let r=wt.parse(n.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:a,onExperimentViewed:o}=n,s={attributes:r,...i?{saveStickyBucketAssignmentDoc:c=>i(structuredClone(c))}:{},...a?{onFeatureUsage:(c,u)=>a(c,structuredClone(u))}:{},...o?{onExperimentViewed:(c,u)=>o(structuredClone(c),structuredClone(u))}:{},features:e.features,savedGroups:e.savedGroups,...n.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(n.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,s)}function TI(e,t,n){let r=[],i=[],a=[],o=e(t,{...n.attributes?{attributes:n.attributes}:{},stickyBucketAssignmentDocs:n.sticky,saveStickyBucketAssignmentDoc(s){let c=r.findIndex(m=>m.next.attributeName===s.attributeName&&m.next.attributeValue===s.attributeValue),u=s.attributeName+"||"+s.attributeValue,l={expected:n.sticky[u]??null,next:s};c<0?r.push(l):r[c]=l},onExperimentViewed(s,c){c.inExperiment&&c.hashUsed&&!c.passthrough&&i.push(ve.parse({key:s.key,variationId:c.variationId,keyUsed:c.key,hashAttribute:c.hashAttribute,hashValue:c.hashValue}))},onFeatureUsage(s,c){a.push(ve.parse({feature:s,value:c.value,source:c.source,...c.ruleId?{ruleId:c.ruleId}:{}}))}});return{port:o.port,...o.value===void 0?{}:{value:o.value},sticky:r,exposures:i,features:a}}function sh(e,t,n,r=ah){let i=n,a=new Map(t.graph.nodes.map(R=>[R.id,R])),o=structuredClone(n.variables),s=structuredClone(i.sticky),c=[],u=n.nodeId,l=n.visit,m=!1,f,g=R=>oh(t,R,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),d=R=>(f??(f=kI(e,r)),TI(f,R,{attributes:Xc({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:o,savedGroups:{}}),sticky:s}));for(let R=0;R<zu;R++){let y=a.get(u);if(!y||!$u(y)||g(y))break;if(l>=t.execution.maxTransitions&&(l>t.execution.maxTransitions||y.type!=="end"&&y.type!=="output")){if(!c.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let A,x;if(["condition","feature","split"].includes(y.type)||y.type==="offering"&&y.configuration.source==="feature")A=d(y.id),y.type==="offering"&&(A.value={type:"offering_version",id:String(A.value)}),y.type==="condition"?x=A.port==="default"?y.default:y.cases[Number(A.port.slice(5))]?.target:y.type==="split"?x=A.port==="notParticipating"?y.notParticipating:y.routes[A.port]:(y.type==="feature"||y.type==="offering")&&(x=y.next);else if(A={port:"next",sticky:[],exposures:[],features:[]},(y.type==="entry"||y.type==="coupon"||y.type==="coupons")&&(x=y.next),y.type==="offering"&&y.configuration.source==="fixed"&&(A.value={type:"offering_version",id:y.configuration.versionId},x=y.next),y.type==="end"||y.type==="output"){let P=y.type==="end"?y.output:y.value;if(A=P?.type==="feature"?d(y.id):{...A,port:"value",value:P?.type==="literal"?P.value:P?.type==="variable"?Pc({source:"variable",key:P.key,...P.path?{path:P.path}:{}},{declarations:t.variables,answers:n.answers,results:o,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},P&&(A.value===void 0||!hn(t.outputSchema,A.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let v=[...c,{nodeId:u,result:A}];if(ln({steps:v})>6e4){if(!c.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(c.push({nodeId:u,result:A}),y.type==="feature"||y.type==="offering"||y.type==="coupon"||y.type==="coupons"){let P=y.type==="coupons"?y.couponIds.map(_=>({type:"reward",id:_})):y.type==="coupon"?{type:"reward",id:y.couponId}:A.value;if(P===void 0)throw r("INVALID_RESPONSE","Node output is missing");let j=fi(y,{value:P});em(t.variables,y,j),Object.assign(o,j)}for(let P of A.sticky)s[`${P.next.attributeName}||${P.next.attributeValue}`]=structuredClone(P.next);if(y.type==="end"||y.type==="output"){m=!0;break}if(!x)throw r("INVALID_RESPONSE","Local pure exit is unavailable");u=x,l++}let h=a.get(u);return{steps:c,...!m&&h&&(!$u(h)||g(h))?{boundary:{nodeId:u,visit:l}}:{}}}var b=class extends Error{constructor(n,r,i,a,o){super(r);qe(this,"code",n);qe(this,"status",i);qe(this,"requestId",a);qe(this,"commandRequestId");qe(this,"retryable");qe(this,"recovery");qe(this,"retryAfterSeconds");qe(this,"reason");this.name="IndianaError",this.reason=o?.reason;let s=Uo(n,i??0,{...o,retryAfter:o?.retryAfterSeconds===void 0?void 0:String(o.retryAfterSeconds)});this.retryable=s.retryable,this.recovery=s.recovery,this.retryAfterSeconds=s.retryAfterSeconds}};var Eo=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new b("INVALID_STATE","Installation sequence exhausted");return e+1},NI=async e=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(e,t=>t.charCodeAt(0))))].map(t=>t.toString(16).padStart(2,"0")).join("");function qn(e,t){return e.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new b("INVALID_STATE","Installation journal is invalid");return t({...n})})}function ch(e,t,n){let r=null,i=0,a=0,o=0,s=Promise.resolve(),c=!1;if(e&&(!n||Ne.parse(e.scope).projectId!==n.projectId||e.scope.environment!==n.environment))throw new b("SCOPE_MISMATCH","Push installation belongs to another scope");let u=()=>{if(c)throw new b("CLOSED","SDK client was destroyed");if(!e)throw new b("NOT_CONFIGURED","Configure this client's native Push host first");return e},l=x=>{if(x!==i)throw new b("IDENTITY_CHANGED","Identity changed during Push operation")};async function m(x){let v=u();if(!v.sha256&&!globalThis.crypto?.subtle)throw new b("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let P=v.sha256?await v.sha256(Uint8Array.from(x,j=>j.charCodeAt(0))):await NI(x);if(!/^[a-f0-9]{64}$/.test(P))throw new b("INVALID_STATE","Push credential digest is invalid");return P}function f(x){let v=Ir.parse(x);if(v.installationId.toLowerCase()!==u().installationId.toLowerCase())throw new b("INVALID_RESPONSE","Push response belongs to another installation");return v}async function g(x,v){let P=u(),j={installationId:P.installationId,publicKey:P.publicKey,issuedAt:new Date().toISOString(),...v},_=await P.sign(Pl(x,P.scope,j));return{...j,signature:_}}let d=(x,v,P)=>t.requestWithCredential?t.requestWithCredential(x,v,P):t.request(x,v);async function h(){let x=u(),v=i,P=r?await(t.session?.access()??r):null,j=qn(x,Se=>Se),_;if(j.detachSeq!==null){let Se=j.detachSeq,ht=vl.parse(await g("detach",{sequence:Se,platform:x.platform}));try{let Je=await t.request("push/installations/detach",{...x.scope,...ht},"POST",{installationDetach:!0});if(!Je||typeof Je!="object"||!("installation"in Je))throw new b("INVALID_RESPONSE","Push detach acknowledgement is invalid");let Te=f(Je.installation);if(Te.bound||Te.identitySeq!==Se)throw new b("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(Je){if(Je instanceof b&&Je.status===404)_=Je;else if(!(Je instanceof b)||Je.status!==412)throw Je}_||qn(x,Je=>({...Je,detachSeq:Je.detachSeq===Se?null:Je.detachSeq}))}if(l(v),!P){if(_)throw _;return null}let X=O.bindPushInstallation,le=X.request.parse(await g("bind",{sequence:o,platform:x.platform,credentialDigest:await m(P)}));l(v);let he=X.response.parse(await d(X.path,le,P));l(v);let ke=f(he.installation);if(!ke.bound||ke.identitySeq!==o)throw new b("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return _&&j.detachSeq!==null&&o>j.detachSeq&&qn(x,Se=>({...Se,detachSeq:Se.detachSeq===j.detachSeq?null:Se.detachSeq})),ke}async function R(){u();let x=i,v=r?await(t.session?.access()??r):null;if(!v)throw new b("NOT_IDENTIFIED","Identify before reading this installation");let P=O.readPushInstallation,j=P.request.parse(await g("read",{credentialDigest:await m(v)}));l(x);let _=P.response.parse(await d(P.path,j,v));return l(x),f(_.installation)}function y(x=h){let v=s.catch(()=>{}).then(x);return s=v,v.catch(P=>{try{e?.onError?.(P instanceof Error?P:new Error("Push synchronization failed"))}catch{}}),v}async function A(x,v,P){let j=u(),_=v.identity,X=v.observation,le=r?await(t.session?.access()??r):null;if(l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");if(!le)throw new b("NOT_IDENTIFIED","Identify before recovering a Push address");if(!x.connectionId||!x.kind||!x.token||!["granted","provisional"].includes(x.permission))throw new b("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await y(async()=>{if(l(_),await h(),l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let he=qn(j,Te=>P?Te:{...Te,addressSeq:Eo(Te.addressSeq)}),Se=await g(P?"recovery_confirm":"recovery_request",{...x,sequence:he.addressSeq,credentialDigest:await m(le),...P?{challenge:P}:{}}),ht=P?Ol.parse(Se):wl.parse(Se);if(l(_),X!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let Je=await d(`push/installations/recovery/${P?"confirm":"request"}`,ht,le);if(l(_),X!==a||qn(j,Te=>Te).addressSeq!==he.addressSeq)throw new b("INVALID_STATE","Push observation changed during recovery");if(P){let Te=O.updatePushAddress.response.parse(Je),tt=f(Te.installation);if(!tt.bound||tt.identitySeq!==o||tt.addressSeq!==he.addressSeq||tt.connectionId!==x.connectionId||tt.addressStatus!=="active")throw new b("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return tt}if(!Je||typeof Je!="object"||!("recovery"in Je))throw new b("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return Ps.parse(Je.recovery)})}return{recoveryObserver(){u();let x={identity:i,observation:++a};return{async request(v){return Ps.parse(await A(v,x))},async confirm(v,P){return Ir.parse(await A(P,x,v))}}},identify(x){if(!e)return;o=qn(e,P=>({...P,identitySeq:Eo(P.identitySeq)})).identitySeq,r=x,i++,a++},reset(){if(e)try{qn(e,x=>{let v=Eo(x.identitySeq);return{...x,identitySeq:v,detachSeq:v}})}finally{r=null,i++,a++}},start(){e&&!c&&y()},destroy(){c=!0,r=null,i++,a++},async sync(){return await y()},read:R,async recover(){let x=u(),v=i,P=o;return a++,await y(async()=>{l(v);let j=await R();return l(v),o=qn(x,X=>{if(X.identitySeq!==P)throw new b("IDENTITY_CHANGED","A newer installation intent exists");return{...X,identitySeq:Eo(Math.max(X.identitySeq,j.identitySeq)),addressSeq:Math.max(X.addressSeq,j.addressSeq)}}).identitySeq,await h()})},tokenObserver(){u();let x=++a,v=i;return async P=>{if(x!==a||v!==i)return null;let j=u(),_=r?await(t.session?.access()??r):null;if(!_)throw new b("NOT_IDENTIFIED","Identify before registering a Push token");if(await y(),l(v),x!==a)return null;let X=qn(j,Se=>({...Se,addressSeq:Eo(Se.addressSeq)})),le=O.updatePushAddress,he=le.request.parse(await g("address",{...P,sequence:X.addressSeq,credentialDigest:await m(_)}));if(l(v),x!==a)return null;let ke=await d(le.path,he,_);return l(v),x!==a||qn(j,Se=>Se).addressSeq!==X.addressSeq?null:f(le.response.parse(ke).installation)}}}}import{ZodError as DI}from"zod";function uh(e,t,n,r){try{return e.parse(t)}catch(i){throw r&&i instanceof DI?new b(n,r):i}}async function ge(e,t,n,r={},i){let a=typeof r=="function"?{}:r,o=uh(t.request,n,"INVALID_REQUEST",a.request);try{let s=await e(t.path,o,t.method,i),c=typeof r=="function"?r:r.parseResponse;return c?c(t.response,s):uh(t.response,s,"INVALID_RESPONSE",a.response)}catch(s){throw s instanceof b&&o!==null&&typeof o=="object"&&"requestId"in o&&typeof o.requestId=="string"&&(s.commandRequestId??(s.commandRequestId=o.requestId)),s}}function lh(e,t){let n={async preference(r){let i=O.readMessagingPreference;return(await ge(e,i,{channel:r})).preference},async setPreference(r){let i=O.setMessagingPreference;return(await ge(e,i,r)).preference}};return{messaging:n,push:{sync:t.sync,read:t.read,recover:t.recover,tokenObserver:t.tokenObserver,recoveryObserver:t.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return n.setPreference({...r,channel:"push"})}}}}var dh={name:"@tinkerlandai/longplay-sdk",version:"0.10.18",description:"Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit && tsc --noEmit -p tsconfig.test.json",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};function Qe(e){return typeof e=="string"?e:String(e)}var MI=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function qI(e){return e.replace(MI,"$1\uFFFD")}function Ju(e,t){if(typeof e!="object"||e==null){let n="";throw n+="The provided value is not an object",new TypeError(n)}return e}function xh(e){if(e!=null&&(typeof e=="object"||typeof e=="function")){let t=e[Symbol.iterator];if(t==null)return;if(typeof t!="function")throw new TypeError("The provided value is not iterable");let n=t.call(e);if(!n||typeof n!="object")throw new TypeError("Result of the Symbol.iterator method is not an object");return n}}function ph(e){let t;if(Array.isArray(e)){let n=e.map(Qe);if(n.length===2)return n}else if((t=xh(e))!=null){let n=Ju(t.next()),r=Ju(t.next());if(!n.done&&!r.done)return[Qe(n.value),Qe(r.value)]}throw new TypeError("Each query pair must be an iterable [name, value] tuple")}var mh="0123456789ABCDEF",UI=/(?:%[0-9A-Fa-f]{2})+/g;function Un(e){return`%${mh[e>>4&15]}${mh[15&e]}`}function Sh(e,t,n=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?n&&e===32?"+":t(e)?Un(e):String.fromCharCode(e):e<=2047?Un(192|e>>6)+Un(128|63&e):e<=65535?Un(224|e>>12)+Un(128|e>>6&63)+Un(128|63&e):Un(240|e>>18)+Un(128|e>>12&63)+Un(128|e>>6&63)+Un(128|63&e)}function Zu(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function Wu(e,t=!1){let n=0;for(;n<e.length;n++){let r=e.charCodeAt(n);if(r===37||t&&r===43)break}return n===e.length?e:(t?e.replace(/\+/g," "):e).replace(UI,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function jo(e){return e<=31||e>126}function BI(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return jo(e)}}function il(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return jo(e)}}function VI(e){return il(e)||e===39}function Yu(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return il(e)}}function fs(e){switch(e){case 47:case 58:case 59:case 61:case 64:case 91:case 92:case 93:case 124:return!0;default:return Yu(e)}}function fh(e){switch(e){case 33:case 39:case 40:case 41:case 126:return!0;default:return(function(n){switch(n){case 36:case 37:case 38:case 43:case 44:return!0;default:return fs(n)}})(e)}}function Ih(e,t){return Sh(e=e||0,t)}function Bn(e,t,n=!1){let r=0;for(;r<e.length;r++){let a=e.charCodeAt(r);if(a>=128||n&&a===32||t(a))break}if(r===e.length)return e;let i=e.slice(0,r);for(;r<e.length;r++){let a=e.charCodeAt(r),o=a;if(a>=55296&&a<=56319&&r+1<e.length){let s=e.charCodeAt(r+1);s>=56320&&s<=57343&&(o=(a-55296<<10)+s-56320+65536,r++)}i+=Sh(o,t,n)}return i}function ol(e){let t=[],n=0,r=0;for(;r<=e.length;){if(r=e.indexOf("&",n),r<0&&(r=e.length),r!==n){let i=e.slice(n,r),a=i.indexOf("=");a<0&&(a=i.length),t.push([Wu(i.slice(0,a),!0),Wu(i.slice(a+1),!0)])}if(n=r+1,r===e.length)break}return t}function Xu(e){let t="";for(let n=0;n<e.length;n++){let r=Bn(e[n][0],fh,!0),i=Bn(e[n][1],fh,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var LI=[2191,2191,3164,3164,3292,3292,6863,6877,6880,6891,8385,8385,11158,11158,42958,42959,42962,42962,42964,42964,42993,42993,64451,64466,64912,64913,64968,64974,67904,67929,69317,69319,69328,69336,69370,69371,72544,72551,73136,73179,73184,73193,93856,93880,93883,93907,94194,94198,100344,100351,101641,101662,101760,101874,118010,118012,118458,118480,118496,118512,124608,124638,124640,124661,124670,124671,128728,128728,128887,128890,129232,129240,129620,129623,129674,129674,129678,129678,129736,129736,129741,129741,129770,129770,129775,129775,130042,130042,177978,177983,183970,183981,205744,210041],zI=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],$I=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],GI=[2381,2381,2509,2509,2637,2637,2765,2765,2893,2893,3021,3021,3149,3149,3277,3277,3387,3388,3405,3405,3530,3530,3642,3642,3770,3770,3972,3972,4153,4154,5908,5909,5940,5940,6098,6098,6752,6752,6980,6980,7082,7083,7154,7155,11647,11647,43014,43014,43052,43052,43204,43204,43347,43347,43456,43456,43766,43766,44013,44013,68159,68159,69702,69702,69744,69744,69759,69759,69817,69817,69939,69940,70080,70080,70197,70197,70378,70378,70477,70477,70606,70608,70722,70722,70850,70850,71103,71103,71231,71231,71350,71350,71467,71467,71737,71737,71997,71998,72160,72160,72244,72244,72263,72263,72345,72345,72767,72767,73028,73029,73111,73111,73537,73538,90415,90415];function KI(e){for(let t=0;t<e.length;t++){let n=e.codePointAt(t);if(n>65535&&t++,n<=32||n===37||n===127||n>=55296&&n<=57343||n>=128&&n<=159||n>=64976&&n<=65007||!(65534&~n)||n===65533)return!0}return!1}var[HI,QI,JI,gh]=[[[],"0,6,7,8,m,w,10,1b,1d,1f,72,73,7k,8k,dt,2rk","AAAAAAAAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAA/AAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAADAAABwfwAAAAAAAMADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhAAAAQAAAAAAAAQCAAABAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgACAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAP///////////////wAAAAAAAAAAAAAAAAAAAAA="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAEF9+P/+BwAAAMAA//8AAPz/////BlADAAAAAJwAAPz///8AAADA//H/5+X8AAAAAAAAAAAA/P///wcAAAAAAAAAAAAAPv0vAD0BAABA/gAA/5/5/f8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8g+N8B+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAYAAAAAAAAAAAAAD/////CwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANgAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/HgwAAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAP3////+BwAAAMDu//////////////8vAADAAJwAAP3///8AAADg////////AAAAAAAAAAAA/P///wcAAAAAAAAAAAAA////Ab0H//9H/gAA/9////8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL/G//8T+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAfgAAAAAAAAAAAAD+////DwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANwAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/Hg4AAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"0,3,4,5,6,7,8,9,a,b,c,d,e,f,g,j,n,o,p,q,r,s,t,w,18,19,1c,4m,4o,4p,4q,4r,6z,72,73,75,76,77,7e,7h,7i,7j,7k,7l,7m,7n,7o,7p,7q,7r,7s,7t,7u,7v,7w,7x,7y,7z,8k,9t,a2,a3,a7,cc,cv,cx,cy,d6,dc,dd,de,dg,dh,di,dk,dl,2rk,2rl","AAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAD//////////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD4AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/v////+/tgAAAAAAAAAAAP8XAAAAAAD4//8AAAEAAAAAAAAAAAAAAMCfnz0AAACAAgAAAP///wcAAAAAAAAAAAAAwP8BAAAAAAAA+A8gAADA++8+AAAAAAAOAAAAAAAAgP8AAAAAAPz///v///8HAAAAAAAAFP4h/gAMAAAAAgAAAAAAABAeIAAADAAAQAYAAAAAAAAQhjkCAAAAIwAGAAAAAAAAEL4hAAAMAAD8AgAAAAAAAJAeIGAADAAAAAQAAAAAAAAAASAAAAAAAAARAAAAAAAA0ME9YAAMAAAAAgAAAAAAAJBAMAAADAAAAAMAAAAAAAAYHiAAAAwAAAACAAAAAAAAAAAEXAAAAAAAAAAAAAAA8geAfwAAAAAAAAAAAAAAAPIfAH8AAAAAAAAAAAADAACgAgAAAAAAAP5/3+D//v///x9AAAAAAAAAAAAAAAAA4P1mAAAAwwEAHgBkIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAAAAMAAAADAAAAAwAAAAAAAAAsD9A/g8gAAAAAAC4AAAAAAAAAAAAAAAAAABgAAAAAAIAAAAAAAAAAAAAAAAAAIcBBA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAJAAAAAAAAQH/lH/ifAAAAAAAA//////8//w8AAA8AAAAAANAXBAAAAAD4DwADAAAAPDsAAAAAAABAowMAAAAAAADwzwAAAAAAAAAAAAAAAAAAAAAAAAD3//0hEAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////wDIAAAAfAAAAAAAAB/8AAAAAAAAAAAAAAAA/////wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAwAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAA/////wAAAAAAPAAAAAAAAAAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAID3PwAAAMAAAAAAAAAAAAAAAwBECAAAYBAAAAAAAAAAAAAAAAAAAAAAAAAwAAAA//8DgAAAAADAPwAAgP8DAAAAAAAHAAAAAADIMwAAAAAgAAAAAAAAAAB+ZgAIEAAAAAAAEAAAAAAAAJ3BAgAAAAAwQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICEAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8AAP//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAMAHAAAAAAAAAAAAAAAAAAAAAG7wAAAAAACHAAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAPAAAAAAAAAAAD4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAAAAAAAAA/AAAAAAAAAAAwP8BAAAAAAA8AAAAAAAAAAAAAAAAAAAAAgAAAAAAAP9/AAAAAAAZgAMAAAAAAHgGBAAAAAAAAAAHAAAAgO8fAAAAAAAAAAgAAwAAAAAAwH8AngAAAAAAAAAAAAAAgNNAAgAAAAAAAAAAAAAAAAAAAAAAAID4BwAAAwAAAAAAABgBAAAAwB8fAAAAAAAAAAD4AUAFAAYAAAAAAAAAAAAA/1wAAEAAAAAAAAAAAAAA+IUNAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8sAEAADAAAAAAAAAAAAAA+KcBAAAAAAAAAAAAAAAAKL8AAAAAAAAAAAAAAACgvA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgP8GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFgIAAAAAAAAAAAAAAAAAAAAAADwDAEAAAD+BwAAAAD4eYAAfg4AAAAAAPx/AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf78AAAAAAAAAAAAA/P///G0AAAAAAAAAAAAAAAAAAAB+tL8AAAAAAAAAAACjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAAwAAAAAAwAcFAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//4H/PwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMD/4wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHwAAAAAAAAB/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAgAcAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGAPAAAAAAAAAAAAAAD//////z///38AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAD+P/nDwAAADwAAAAAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////9/+P//////HyAAEAAA+P7/AAAAAAAAAAAAAH////nbBwAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASMAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAADwDwAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAA////////////////AAAAAAAAAAAAAAAAAAAAAP///////////////////////////////////////wAA"]].map(function([t,n,r]){return[t,n.split(",").map(i=>parseInt(i,36)),Uint8Array.from(atob(r),i=>i.charCodeAt(0))]});function ZI(e,t){return t===931||t===1010||t===120531||t===120589||t===120647||t===120705||t===120763?"\u03C3":t>=5112&&t<=5117?String.fromCodePoint(t-8):t>=43888&&t<=43967?String.fromCodePoint(t-38864):t>=93856&&t<=93880?String.fromCodePoint(t+27):t===837||t===890||t>=8064&&t<=8111||t>=8114&&t<=8188?e.normalize("NFD").replace(/\u0345/g,"\u03B9").normalize("NFC").toLowerCase():""}function vh(e,t){for(let n=0;n<e.length;n+=2)if(t>=e[n]&&t<=e[n+1])return!0;return!1}function Ro(e,t){let[n,r,i]=e,a=t>>8;for(let c=0;c<n.length;c+=2)if(a>=n[c]&&a<=n[c+1])return!0;let o=r.indexOf(a);if(o<0)return!1;let s=255&t;return!!(i[32*o+(s>>3)]&1<<(7&s))}function WI(e){let t=Array.from(e,n=>n.codePointAt(0));for(let n=0;n<t.length;n++){let r=t[n];if(r!==8204&&r!==8205||n>0&&vh(GI,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&Ro(gh,t[i]);)i--;let a=n+1;for(;a<t.length&&Ro(gh,t[a]);)a++;if(!(i>=0&&a<t.length&&Ro(QI,t[i])&&Ro(JI,t[a])))return!1}return!0}var YI=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,XI=/\p{Script=Latin}/u;function ev(e){return!YI.test(e)||!XI.test(e)}var dr=36,ds=1,el=26,tv=38,nv=700,rv=72,iv=128,ov=2147483647;function hh(e){return String.fromCharCode(e+22+75*+(e<26))}function av(e,t,n){let r=0;for(e=n?Math.floor(e/nv):e>>1,e+=Math.floor(e/t);e>(dr-ds)*el>>1;r+=dr)e=Math.floor(e/(dr-ds));return Math.floor(r+(dr-ds+1)*e/(e+tv))}function sv(e){let t=Array.from(e,c=>c.codePointAt(0)),n="",r=0;for(let c=0;c<t.length;c++){let u=t[c];u<128&&(n+=String.fromCharCode(u),r++)}let i=r;i&&(n+="-");let a=iv,o=0,s=rv;for(;r<t.length;){let c=ov;for(let u=0;u<t.length;u++){let l=t[u];l>=a&&l<c&&(c=l)}o+=(c-a)*(r+1),a=c;for(let u=0;u<t.length;u++){let l=t[u];if(l<a&&o++,l===a){let m=o;for(let f=dr;;f+=dr){let g=f<=s?ds:f>=s+el?el:f-s;if(m<g)break;n+=hh(g+(m-g)%(dr-g)),m=Math.floor((m-g)/(dr-g))}n+=hh(m),s=av(o,r+1,r===i),o=0,r++}}o++,a++}return n}function Ku(e){let t=10;if(e.length>=2&&e[0]==="0"&&(e[1]==="x"||e[1]==="X"))e=e.slice(2),t=16;else if(e.length>=2&&e[0]==="0")e=e.slice(1),t=8;else if(e==="")return-1;let n=0;for(let r=0;r<e.length;r++){let i=Zu(e.charCodeAt(r));if(i>=t||i<0)return-1;n=n*t+i}return n}function yh(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function wh(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function Oh(e){return e.length===2&&wh(e.codePointAt(0),e.codePointAt(1))}function Ah(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function ft(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function Ph(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function tl(e,t){if(e[0]==="[")return e[e.length-1]==="]"?(function(r){let i=[0,0,0,0,0,0,0,0],a=null,o=0,s=0,c=Array.from(r,u=>u.codePointAt(0));if(c[s]===58){if(c[s+1]!==58)return null;s+=2,o++,a=o}for(;s<c.length;){if(o===8)return null;if(c[s]===58){if(a!==null)return null;s++,o++,a=o;continue}let u=0,l=0,m=0;for(;m<4&&(u=Zu(c[s]))>=0;)l=(l<<4)+u,s++,m++;if(c[s]===46){if(m===0||o>6)return null;s-=m;let f=0;for(;c[s]!==void 0;){let g=0;if(f>0)if(c[s]===46&&f<4)s++;else return null;if(c[s]==null||c[s]<48||c[s]>57)return null;for(;c[s]>=48&&c[s]<=57;){if(g=10*g+Zu(c[s]),g>255)return null;s++}i[o]=256*i[o]+g,f++,f%2==0&&o++}if(f!==4)return null;break}else if(c[s]===58){if(c[++s]===void 0)return null}else if(c[s]!==void 0)return null;i[o]=l,o++}if(a!==null){let u=o-a;for(o=7;o!==0&&u>0;){let l=i[a+u-1];i[a+u-1]=i[o],i[o]=l,o--,u--}}else if(a===null&&o!==8)return null;return i})(e.substring(1,e.length-1)):null;if(t)return(function(r){return Ah(r)?null:Bn(r,jo)})(e);{let n=(function(i){let a=!1,o=!1;for(let c=0;c<i.length;c++){let u=i.charCodeAt(c);if(u<=32||u===37||u===127)return null;if(u>=128){a=!0;break}u>=65&&u<=90&&(o=!0)}if(!a)return i!==""?o?i.toLowerCase():i:null;if((function(u){for(let l of u){let m=l.codePointAt(0);if(/[\p{Cn}\p{Co}\p{Cs}\p{Noncharacter_Code_Point}]/u.test(l)&&!vh(LI,m)||Ro(HI,m))return!0}return!1})(i))return null;let s=(i=(function(u){let l="";for(let m of u){let f=m.codePointAt(0);if(f!==8204&&f!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(m))continue;let g=ZI(m,f);if(g){l+=g;continue}let d=zI.indexOf(f);l+=d<0?m:$I[d]}return l})(i).normalize("NFKC").replace(/[\u3002\uff0e\uff61]/g,".").toLowerCase()).split(".");for(let c=0;c<s.length;c++){let u=s[c];if(u==="")continue;let l=/[^\0-\x7f]/.test(u);if(KI(u)||l&&(/^\p{Mark}/u.test(u)||!WI(u)||!ev(u)||u.startsWith("xn--")))return null;l&&(s[c]=`xn--${sv(u)}`)}return(i=s.join("."))!==""?i:null})(e.indexOf("%")===-1?e:Wu(e));return n===null||Ah(n)?null:(function(i){let a=i.length,o=i.lastIndexOf(".",a-2)+1;if(i.charCodeAt(a-1)===46&&a--,a<=o)return!1;if(Ku(i.slice(o,a))>=0)return!0;for(;o<a;o++){let s=i.charCodeAt(o);if(s<48||s>57)return!1}return!0})(n)?(function(i){let a=i.split("."),o=a.length;if(a[o-1]||o--,o>4)return null;let s=0;for(let u=0;u<o-1;u++){let l=Ku(a[u]);if(l<0||l>255)return null;s+=l*(1<<8*(3-u))}let c=Ku(a[o-1]);return c<0||c>=256**(5-o)?null:(s+=c,s)})(n):n}}function nl(e){return typeof e=="number"?(function(n){let i="";return i+=`${(n>>>24&255).toString(10)}.`,i+=`${(n>>>16&255).toString(10)}.`,i+=`${(n>>>8&255).toString(10)}.`,i+=(n&255).toString(10),i})(e):Array.isArray(e)?`[${(function(n){let r=(function(s){let c=-1,u=-1,l=1,m=0;for(let f=0;f<s.length;++f)s[f]!==0?(m>l&&(c=u,l=m),u=-1,m=0):(u===-1&&(u=f),++m);return m>l?u:c})(n),i="",a=!1;for(let o=0;o<=7;++o)if(!(a&&n[o]===0)){if(a&&(a=!1),r===o){i+=o===0?"::":":",a=!0;continue}i+=n[o].toString(16),o!==7&&(i+=":")}return i})(e)}]`:e}function Ch(e){e.path.length>0&&(e.path.length!==1||e.scheme!=="file"||!(function(n){return/^[A-Za-z]:$/u.test(n)})(e.path[0]))&&e.path.pop()}function _h(e){return e.username!==""||e.password!==""}function Hu(e){return e.host===null||e.host===""||e.scheme==="file"}var E=0,U="",Oe="",Le=null,B,ps=!1,ms=!1,Kr=!1,gt;function fn(e,t,n,r){t||(e=(function(o){let s=0,c=o.length;for(;s<c&&!(o.charCodeAt(s)>32);++s);for(;c>s&&!(o.charCodeAt(c-1)>32);--c);return o.substring(s,c)})(e)),e=(function(o){let s=0;for(;s<o.length;s++){let u=o.charCodeAt(s);if(u===9||u===10||u===13)break}if(s===o.length)return o;let c=o.slice(0,s);for(;s<o.length;s++){let u=o.charCodeAt(s);u!==9&&u!==10&&u!==13&&(c+=o[s])}return c})(e),E=0,U=e,Oe="",Le=n||null,B=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},ps=!1,ms=!1,Kr=!1,gt=r||0;let i=cv;switch(r){case 3:case 4:i=gs;break;case 5:i=sl;break;case 6:i=Hr;break;case 7:i=pr;break;case 8:i=Vn}return i(G(e,E))!==1?B:null}function ee(e,t){return E+=E===e?Tn(t):1,E<=U.length}function G(e,t){return t<e.length?e.codePointAt(t):void 0}function Tn(e){return e!=null&&e>65535?2:1}function Eh(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var cv=e=>{let t=E;if(e!=null&&(e>=65&&e<=90||e>=97&&e<=122)){let n=E+1;for(e=U.charCodeAt(n);e===43||e===45||e===46||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57;)n++,e=U.charCodeAt(n);return Oe=U.slice(E,n).toLowerCase(),E=n,uv(n<U.length?e:void 0)}else return gt?1:(--E,ee(t,e)?Rh(G(U,E)):0)},uv=e=>{let t=E;if(e===58){if(gt){if(ft(B.scheme)!==ft(Oe))return 0;if((_h(B)||B.port!==null)&&Oe==="file")return 0;if(B.scheme==="file"&&B.host==="")return 0}return B.scheme=Oe,gt?(B.port===Ph(B.scheme)&&(B.port=null),0):(Oe="",B.scheme==="file"?ee(t,e)?cl(G(U,E)):0:ft(B.scheme)&&Le!==null&&Le.scheme===B.scheme?ee(t,e)?lv(G(U,E)):0:ft(B.scheme)?ee(t,e)?pv(G(U,E)):0:G(U,E+1)===47?(E++,ee(t,e)?dv(G(U,E)):0):(B.path=[""],B.opaquePath=!0,ee(t,e)?jh(G(U,E)):0))}else return gt?1:(Oe="",E=-1,ee(t,e)?Rh(G(U,E)):0)},Rh=e=>{let t=E;return Le===null||Le.opaquePath&&e!==35?1:Le.opaquePath&&e===35?(B.scheme=Le.scheme,B.path=Le.path.slice(),B.opaquePath=Le.opaquePath,B.query=Le.query,B.fragment="",ee(t,e)?Vn(G(U,E)):0):Le.scheme==="file"?(E--,ee(t,e)?cl(G(U,E)):0):(E--,ee(t,e)?al(G(U,E)):0)},lv=e=>{let t=E;return e===47&&G(U,E+1)===47?(++E,ee(t,e)?ys(G(U,E)):0):(E--,ee(t,e)?al(G(U,E)):0)},dv=e=>{let t=E;return e===47?ee(t,e)?Ti(G(U,E)):0:(E--,ee(t,e)?Nn(G(U,E)):0)},al=e=>{let t=E;return B.scheme=Le.scheme,e===47||ft(B.scheme)&&e===92?ee(t,e)?bh(G(U,E)):0:(B.username=Le.username,B.password=Le.password,B.host=Le.host,B.port=Le.port,B.path=Le.path.slice(),B.query=Le.query,e===63?(B.query="",ee(t,e)?pr(G(U,E)):0):e===35?(B.fragment="",ee(t,e)?Vn(G(U,E)):0):e!=null?(B.query=null,B.path.pop(),E--,ee(t,e)?Nn(G(U,E)):0):ee(t,e)?al(G(U,E)):0)},bh=e=>{let t=E;return ft(B.scheme)&&(e===47||e===92)?ee(t,e)?ys(G(U,E)):0:e===47?ee(t,e)?Ti(G(U,E)):0:(B.username=Le.username,B.password=Le.password,B.host=Le.host,B.port=Le.port,E--,ee(t,e)?Nn(G(U,E)):0)},pv=e=>{let t=E;return e===47&&G(U,E+1)===47?E++:E--,ee(t,e)?ys(G(U,E)):0},ys=e=>{let t=E;return e!==47&&e!==92?(E--,ee(t,e)?Ti(G(U,E)):0):ee(t,e)?ys(G(U,E)):0},Ti=e=>{let t=E;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!ft(B.scheme))){let n=E+Tn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===64||r===35||r===47||r===63||r===92&&ft(B.scheme))break;n+=Tn(r)}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?Ti(G(U,E)):0}if(e===64){ps&&(Oe=`%40${Oe}`),ps=!0;for(let n=0;n<Oe.length;n++){let r=Oe.codePointAt(n);if(r===58&&!ms){ms=!0;continue}let i=Ih(r,fs);ms?B.password+=i:B.username+=i,r!=null&&r>65535&&n++}return Oe="",ee(t,e)?Ti(G(U,E)):0}else return e==null||e===35||e===47||e===63||e===92&&ft(B.scheme)?ps&&Oe===""?1:(E-=Oe.length+1,Oe="",ee(t,e)?gs(G(U,E)):0):(Oe+=Eh(e),ee(t,e)?Ti(G(U,E)):0)},gs=e=>{let t=E;if(gt&&B.scheme==="file")return E--,ee(t,e)?ul(G(U,E)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!ft(B.scheme))){let n=E+Tn(e);for(e===91?Kr=!0:e===93&&(Kr=!1);n<U.length;){let r=G(U,n);if(r==null||!Kr&&r===58||r===35||r===47||r===63||r===92&&ft(B.scheme))break;r===91?Kr=!0:r===93&&(Kr=!1),n+=Tn(r)}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?gs(G(U,E)):0}else if(e===58&&!Kr){if(Oe===""||gt===4)return 1;let n=tl(Oe,!ft(B.scheme));return n===null?1:(B.host=nl(n),Oe="",ee(t,e)?sl(G(U,E)):0)}else if(e==null||e===35||e===47||e===63||e===92&&ft(B.scheme)){if(E--,ft(B.scheme)&&Oe==="")return 1;if(gt&&Oe===""&&(_h(B)||B.port!==null))return 1;let n=tl(Oe,!ft(B.scheme));return n===null?1:(B.host=nl(n),Oe="",gt?0:ee(t,e)?Hr(G(U,E)):0)}else return Oe+=Eh(e),ee(t,e)?gs(G(U,E)):0},sl=e=>{let t=E;if(e!=null&&e>=48&&e<=57){let n=E+1;for(;n<U.length;){let r=U.charCodeAt(n);if(r<48||r>57)break;n++}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?sl(G(U,E)):0}else if(gt||e==null||e===35||e===47||e===63||e===92&&ft(B.scheme)){if(Oe!==""){let n=parseInt(Oe,10);if(n>65535)return 1;if(B.port=n===Ph(B.scheme)?null:n,Oe="",gt)return 0}return gt?1:(E--,ee(t,e)?Hr(G(U,E)):0)}else return 1};function kh(e,t){let n=e.length-t;if(n<2)return!1;if(wh(G(e,t),G(e,t+1))){if(n===2)return!0;{let r=G(e,t+2);return r===47||r===92||r===63||r===35}}else return!1}var cl=e=>{let t=E;return B.scheme="file",B.host="",e===47||e===92?ee(t,e)?mv(G(U,E)):0:Le?.scheme==="file"?(B.host=Le.host,B.path=Le.path.slice(),B.opaquePath=Le.opaquePath,B.query=Le.query,e===63?(B.query="",ee(t,e)?pr(G(U,E)):0):e===35?(B.fragment="",ee(t,e)?Vn(G(U,E)):0):e!=null?(B.query=null,kh(U,E)?B.path=[]:Ch(B),E--,ee(t,e)?Nn(G(U,E)):0):ee(t,e)?cl(G(U,E)):0):(E--,ee(t,e)?Nn(G(U,E)):0)},mv=e=>{let t=E;return e===47||e===92?ee(t,e)?ul(G(U,E)):0:(Le!==null&&Le.scheme==="file"&&(!kh(U,E)&&(function(r){if(r.length===2){let i=r.codePointAt(0),a=r.codePointAt(1);return(i>=65&&i<=90||i>=97&&i<=122)&&a===58}else return!1})(Le.path[0])&&B.path.push(Le.path[0]),B.host=Le.host),E--,ee(t,e)?Nn(G(U,E)):0)},ul=e=>{let t=E;if(e!=null&&e!==47&&e!==92&&e!==63&&e!==35){let n=E+Tn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===47||r===92||r===63||r===35)break;n+=Tn(r)}return Oe+=U.slice(E,n),E=n-1,ee(t,e)?ul(G(U,E)):0}else if(e==null||e===47||e===92||e===63||e===35){if(E--,!gt&&Oh(Oe))return ee(t,e)?Nn(G(U,E)):0;if(Oe==="")return B.host="",gt?0:ee(t,e)?Hr(G(U,E)):0;{let n=tl(Oe,!ft(B.scheme));return n===null?1:(n==="localhost"&&(n=""),B.host=nl(n),Oe="",gt?0:ee(t,e)?Hr(G(U,E)):0)}}return 1},Hr=e=>{let t=E;return ft(B.scheme)?(e!==92&&e!==47&&E--,ee(t,e)?Nn(G(U,E)):0):!gt&&e===63?(B.query="",ee(t,e)?pr(G(U,E)):0):!gt&&e===35?(B.fragment="",ee(t,e)?Vn(G(U,E)):0):e!=null?(e!==47&&E--,ee(t,e)?Nn(G(U,E)):0):(gt&&B.host===null&&B.path.push(""),ee(t,e)?Hr(G(U,E)):0)},Nn=e=>{let t=E;if(e!=null&&e!==47&&(!ft(B.scheme)||e!==92)&&(gt||e!==63&&e!==35)){let n=E+Tn(e);for(;n<U.length;){let r=G(U,n);if(r==null||r===47||ft(B.scheme)&&r===92||!gt&&(r===63||r===35))break;n+=Tn(r)}Oe+=Bn(U.slice(E,n),Yu),E=n,e=G(U,n)}if(e==null||e===47||ft(B.scheme)&&e===92||!gt&&(e===63||e===35)){let n=ft(B.scheme)&&e===92;return(function(i){switch(i){case"..":case"%2e.":case"%2E.":case".%2e":case".%2E":case"%2e%2e":case"%2E%2e":case"%2e%2E":case"%2E%2E":return!0;default:return!1}})(Oe)?(Ch(B),e!==47&&!n&&B.path.push("")):yh(Oe)&&e!==47&&!n?B.path.push(""):yh(Oe)||(B.scheme==="file"&&B.path.length===0&&Oh(Oe)&&(Oe=`${Oe[0]}:`),B.path.push(Oe)),Oe="",e===63?(B.query="",ee(t,e)?pr(G(U,E)):0):e===35?(B.fragment="",ee(t,e)?Vn(G(U,E)):0):ee(t,e)?Nn(G(U,E)):0}else return Oe+=Ih(e,Yu),ee(t,e)?Nn(G(U,E)):0},jh=e=>{let t=E;if(e===63)return B.query="",ee(t,e)?pr(G(U,E)):0;if(e===35)return B.fragment="",ee(t,e)?Vn(G(U,E)):0;if(e!=null){let n=E+Tn(e);for(;n<U.length;){let i=G(U,n);if(i===63||i===35)break;n+=Tn(i)}let r=U.slice(E,n);if(n<U.length&&r.charCodeAt(r.length-1)===32?B.path[0]+=Bn(r.slice(0,-1),jo)+"%20":B.path[0]+=Bn(r,jo),E=n,(e=G(U,n))===63)return B.query="",ee(t,e)?pr(G(U,E)):0;if(e===35)return B.fragment="",ee(t,e)?Vn(G(U,E)):0}return ee(t,e)?jh(G(U,E)):0},pr=e=>{let t=E,n=E;if(e!=null){if(gt)n=U.length;else{let i=U.indexOf("#",E);n=i===-1?U.length:i}let r=ft(B.scheme)?VI:il;B.query+=Bn(U.slice(E,n),r)}return E=n,G(U,n)===35&&!gt?(B.fragment="",ee(t,e)?Vn(G(U,E)):0):ee(t,e)?pr(G(U,E)):0},Vn=e=>{let t=E;return e!=null&&(B.fragment+=Bn(U.slice(E),BI),E=U.length),ee(t,e)?Vn(G(U,E)):0};function rl(e){if(e.opaquePath)return e.path[0];{let t="";for(let n of e.path)t+=`/${n}`;return t}}function Th(e){switch(e.scheme){case"blob":{let t=fn(rl(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":Th(t)}case"ftp":case"http":case"https":case"ws":case"wss":return(function(n){let r=`${n.scheme}://`;return r+=n.host,n.port!==null&&(r+=`:${n.port}`),r})(e);default:return"null"}}var He=Symbol("URLImpl"),xn=class e{constructor(t,n){if(t===void 0&&n===void 0)throw new TypeError('The "url" argument must be specified.');t=Qe(t),n!=null&&(n=Qe(n));let r=null;if(n!=null&&(r=fn(n,null,null,0),r==null))throw new TypeError(`Invalid base URL: ${n}`);let i=fn(t,null,r,0);if(i==null)throw new TypeError(`Invalid URL: ${t}`);this[He]={url:i,query:null}}static createObjectURL(t){throw new TypeError("URL.createObjetURL is unsupported")}static revokeObjectURL(t){}static parse(t,n){t=Qe(t),n!==void 0&&(n=Qe(n));try{return new e(t,n)}catch{return null}}static canParse(t,n){t=Qe(t),n!==void 0&&(n=Qe(n));let r=null;return n!=null&&(r=fn(n,null,null,0),r==null)?!1:fn(t,null,r,0)!=null}get href(){return(function(n){let r=`${n.scheme}:`;return n.host!==null&&(r+="//",(n.username!==""||n.password!=="")&&(r+=n.username,n.password!==""&&(r+=`:${n.password}`),r+="@"),r+=n.host,n.port!==null&&(r+=`:${n.port}`)),n.host===null&&!n.opaquePath&&n.path.length>1&&n.path[0]===""&&(r+="/."),r+=rl(n),n.query!==null&&(r+=`?${n.query}`),n.fragment!==null&&(r+=`#${n.fragment}`),r})(this[He].url)}set href(t){let n=fn(t=Qe(t),null,null,0);if(n==null)throw new TypeError(`Invalid URL: ${t}`);this[He].url=n,this[He].query&&Qu(this[He].query,n.query)}get origin(){return Th(this[He].url)}get protocol(){return`${this[He].url.scheme}:`}set protocol(t){fn(`${t=Qe(t)}:`,this[He].url,null,2)}get username(){return this[He].url.username}set username(t){t=Qe(t),Hu(this[He].url)||(function(r,i){r.username=Bn(i,fs)})(this[He].url,t)}get password(){return this[He].url.password}set password(t){t=Qe(t),Hu(this[He].url)||(function(r,i){r.password=Bn(i,fs)})(this[He].url,t)}get host(){let{url:t}=this[He];return t.host==null?"":t.port==null?t.host:`${t.host}:${t.port}`}set host(t){t=Qe(t),this[He].url.opaquePath||fn(t,this[He].url,null,3)}get hostname(){let{url:t}=this[He];return t.host!=null?t.host:""}set hostname(t){t=Qe(t),this[He].url.opaquePath||fn(t,this[He].url,null,4)}get port(){let{url:t}=this[He];return t.port!=null?`${t.port}`:""}set port(t){t=Qe(t);let{url:n}=this[He];Hu(n)||(t?fn(t,n,null,5):n.port=null)}get pathname(){return rl(this[He].url)}set pathname(t){t=Qe(t);let{url:n}=this[He];n.opaquePath||(n.path=[],fn(t,n,null,6))}get search(){let{url:t}=this[He];return t.query?`?${t.query}`:""}set search(t){t=Qe(t);let{url:n,query:r}=this[He];if(!t)n.query=null,r&&Qu(r,null);else{let i=t[0]==="?"?t.substring(1):t;n.query="",fn(i,n,null,7),r&&Qu(r,n.query)}}get searchParams(){let t=this[He],n=t.query;return n==null&&(n=t.query=(function(i,a){let o=new hs;return o[st].url=i,o[st].serialized=a==null,a&&(o[st].list=ol(a)),o})(this,t.url.query)),n}get hash(){let{url:t}=this[He];return t.fragment?`#${t.fragment}`:""}set hash(t){t=Qe(t);let{url:n}=this[He];if(!t)n.fragment=null;else{let r=t[0]==="#"?t.substring(1):t;n.fragment="",fn(r,n,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(xn.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var st=Symbol("URLSearchParamsImpl"),fv=Symbol.dispose||Symbol.for("dispose");function Qu(e,t){t?e[st].list=ol(t):e[st].list.length=0,e[st].serialized=t==null}function ls(e){if(e.url){let t=Xu(e.list);(function(r,i){r[He].url.query=i})(e.url,t||null),e.serialized=!0}}var gv=typeof Iterator<"u"?Iterator:Object,ko=class extends gv{constructor(t,n){super(),this[st]={ptr:t,map:n,index:0}}next(){let t=this[st];return t.index<t.ptr.list.length?{value:t.map(t.ptr.list[t.index++]),done:!1}:{value:void 0,done:!0}}[Symbol.iterator](){return this}[fv](){}},hs=class{constructor(t){let n=this[st]={list:[],url:null,serialized:!0},r;if(Array.isArray(t))for(let i=0;i<t.length;i++)n.list.push(ph(t[i]));else if((r=xh(t))!=null){let i;for(;!(i=Ju(r.next())).done;)n.list.push(ph(i.value))}else if((typeof t=="object"||typeof t=="function")&&t!=null){let i=Object.keys(t);for(let a=0;a<i.length;a++){let o=i[a],s=qI(o),c=Qe(t[o]),u=n.list.find(l=>l[0]===s);u?u[1]=c:n.list.push([s,c])}}else if(t!==void 0){let i=Qe(t);i=i[0]==="?"?i.substring(1):i,n.list=ol(i)}}get size(){return this[st].list.length}append(t,n){t=Qe(t),n=Qe(n),this[st].list.push([t,n]);let r=this[st];r.url&&r.serialized?(function(a,o){let s=a[He].url;s.query=s.query?`${s.query}&${o}`:o})(r.url,Xu([[t,n]])):ls(r)}delete(t,n){t=Qe(t),n=n!=null?Qe(n):void 0;let{list:r}=this[st],i=0;for(;i<r.length;)r[i][0]===t&&(n==null||r[i][1]===n)?r.splice(i,1):i++;ls(this[st])}get(t){t=Qe(t);let{list:n}=this[st];for(let r=0;r<n.length;r++)if(n[r][0]===t)return n[r][1];return null}getAll(t){t=Qe(t);let n=[],{list:r}=this[st];for(let i=0;i<r.length;i++)r[i][0]===t&&n.push(r[i][1]);return n}has(t,n){t=Qe(t),n=n!=null?Qe(n):void 0;let{list:r}=this[st];for(let i=0;i<r.length;i++)if(r[i][0]===t&&(n==null||r[i][1]===n))return!0;return!1}set(t,n){t=Qe(t),n=Qe(n);let{list:r}=this[st],i=!1,a=!1,o=0;for(;o<r.length;)r[o][0]===t?i?(r.splice(o,1),a=!0):(i=!0,r[o][1]!==n&&(r[o][1]=n,a=!0),o++):o++;i||(r.push([t,n]),a=!0),a&&ls(this[st])}sort(){this[st].list.sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0),ls(this[st])}forEach(t,n){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:r}=this[st];for(let i=0;i<r.length;i++)t.call(n,r[i][1],r[i][0],this)}entries(){return new ko(this[st],t=>t)}keys(){return new ko(this[st],t=>t[0])}values(){return new ko(this[st],t=>t[1])}toString(){return Xu(this[st].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(hs.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var mr="https://api.longplayai.com";function Nh(e){let t,n=()=>typeof t=="string"?t:t?.accessToken,r=0,i,a=new Map,o=()=>{for(let m of[...a.keys()])try{m()}catch{}};function s(m){let f=++r;i=void 0,t=void 0;for(let g of[...a.values()])try{g?.()}catch{}f===r&&(t=m,o())}let c=()=>s();function u(m,f=!1){let g=Wn.safeParse(m);if(!g.success||f&&Date.parse(g.data.expiresAt)<=Date.now()||Date.parse(g.data.refreshExpiresAt)<=Date.now()||Date.parse(g.data.refreshExpiresAt)<Date.parse(g.data.expiresAt))throw new b("INVALID_RESPONSE","Invalid customer session credentials");return g.data}async function l(){if(i)return i;let m=typeof t=="object"?t:void 0,f=r;if(!m||Date.parse(m.refreshExpiresAt)<=Date.now())throw m&&c(),new b("UNAUTHENTICATED","Customer authentication is required",401);let g=(async()=>{try{let d=await e(m.refreshToken);if(f!==r)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");let h=u(d,!0);if(h.customerId!==m.customerId||h.sessionId!==m.sessionId)throw new b("SCOPE_MISMATCH","Refresh changed the customer session");return t=h,{...h}}catch(d){throw f!==r?new b("IDENTITY_CHANGED","Customer identity changed during refresh"):(d instanceof b&&d.status===401&&c(),d)}})();i=g;try{return await g}finally{i===g&&(i=void 0)}}return{identify(m){let f=typeof m=="string"?m:u(m),g=typeof f=="string"?f:f.accessToken;if(!g.trim()||/\s/.test(g)||g.length>4096)throw new b("INVALID_TOKEN","A server-issued token is required");s(f)},reset:c,subscribeIdentity(m,f){return a.set(m,f),()=>{a.delete(m)}},access(){let m=typeof t=="object"?t:void 0;if(m&&Date.parse(m.expiresAt)<=Date.now()+3e4){let g=r;return l().then(()=>{let d=n();if(g!==r||!d)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");return d})}let f=n();if(!f)throw new b("NOT_IDENTIFIED","Identify a customer session before making a request");return f},peek:n,snapshot:()=>typeof t=="object"?{...t}:void 0,refresh:l}}var Dh=Symbol("IndianaNoContent");function fr(e,t,n=xn){let r=e.configuration?.scope,i=e.scope??(r&&{projectId:r.projectId,environment:r.environment}),a=i?Ne.parse(i):void 0;if(a&&r&&(a.projectId!==r.projectId||a.environment!==r.environment))throw new b("SCOPE_MISMATCH","Configuration belongs to another App/environment");let o=new n(e.baseUrl??mr);if(o.username||o.password||o.search||o.hash)throw new b("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(o.protocol!=="https:"&&!(o.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(o.hostname)))throw new b("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let s=e.fetch??globalThis.fetch.bind(globalThis),c=e.timeoutMs??1e4;if(!Number.isFinite(c)||c<1||c>12e4)throw new b("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let u=!1,l=0,m=null,f=new Set,g=e.session??Nh(async A=>{let x=await y("customer-sessions/refresh",{},"POST",{},A);if(!x||typeof x!="object")throw new b("INVALID_RESPONSE","Invalid refresh response");let{requestId:v,scope:P,...j}=x;return j});function d(){l+=1,m=null;for(let A of f)A.abort();f.clear()}let h=g.subscribeIdentity(d);function R(){u||g.reset()}async function y(A,x={},v="POST",P={},j){let _=P.installationDetach===!0;if(_&&(A!=="push/installations/detach"||v!=="POST"))throw new b("INVALID_REQUEST","Installation authority only detaches this installation");if(!j&&!_)throw new b("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let X=l,le=new AbortController;_||f.add(le);let he=()=>!_&&X!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new b("TIMEOUT","Longplay request timed out"),ke,Se=new Promise((Te,tt)=>{ke=()=>tt(he()),le.signal.addEventListener("abort",ke,{once:!0})}),ht=setTimeout(()=>le.abort(),P.timeoutMs??c),Je=async()=>{let Te=await s(`${o.href.replace(/\/$/,"")}/api/v1/${A}`,{method:v,headers:{...P.headers,"Content-Type":"application/json",..._?{}:{Authorization:`Bearer ${j}`},[ks]:js.current,[kl]:dh.version,...a?{"X-Indiana-Project":a.projectId,"X-Indiana-Environment":a.environment}:{}},body:v==="POST"?JSON.stringify(x):void 0,signal:le.signal,credentials:"omit",cache:"no-store",redirect:"error",...P.keepalive?{keepalive:!0}:{}});if(le.signal.aborted)throw he();let tt;try{tt=Te.status===204?Dh:await Te.json()}catch{throw le.signal.aborted?he():new b(Te.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",Te.status,Te.headers.get("X-Request-Id")??void 0)}if(le.signal.aborted)throw he();if(!_&&X!==l)throw new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!Te.ok){let pt=Rs.safeParse(tt),Qt=pt.success&&(!$n.safeParse(pt.data.error.code).success||El(pt.data.error.code,Te.status)),Ar=Qt?pt.data.error.code:"HTTP_ERROR",br=Uo(Ar,Te.status,{retryAfter:Te.headers.get("Retry-After"),recovery:Qt?pt.data.error.recovery:void 0,reason:Qt?pt.data.error.reason:void 0});throw new b(Ar,Qt?pt.data.error.message:"Longplay request failed",Te.status,Te.headers.get("X-Request-Id")??(pt.success?pt.data.requestId:void 0),{...br,...pt.success&&pt.data.error.retryable===!1?{retryable:!1}:{},...br.retryAfterSeconds===void 0&&pt.success&&pt.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:pt.data.error.retryAfterSeconds}:{}})}if(Te.headers.get(ks)!==js.current)throw new b("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&tt!==Dh){let pt=tt&&typeof tt=="object"&&"scope"in tt?tt:tt&&typeof tt=="object"&&"configuration"in tt?tt.configuration:null;if(!pt||typeof pt!="object"||!("scope"in pt))throw new b("INVALID_RESPONSE","Response is missing its App/environment scope");let Qt=Ne.safeParse(pt.scope);if(!Qt.success||Qt.data.projectId!==a.projectId||Qt.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let Jr=Te.headers.get("X-Indiana-Telemetry-Subject");if(Jr){if(!/^[a-f0-9]{64}$/.test(Jr))throw new b("INVALID_RESPONSE","Invalid telemetry identity");m!==Jr&&(m=Jr,t?.(m))}return tt};try{return await Promise.race([Je(),Se])}catch(Te){throw!_&&X!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):Te instanceof b?Te:new b(le.signal.aborted?"TIMEOUT":"NETWORK_ERROR",le.signal.aborted?"Longplay request timed out":"Unable to read the Longplay response")}finally{clearTimeout(ht),le.signal.removeEventListener("abort",ke),f.delete(le)}}return{session:g,requestWithCredential(A,x,v,P={}){return u?Promise.reject(new b("CLOSED","SDK client was destroyed")):y(A,x,"POST",P,v)},subjectKey:()=>m,identify(A){if(u)throw new b("CLOSED","SDK client was destroyed");if(a&&typeof A=="object"&&"scope"in A){let x=Ne.safeParse(A.scope);if(!x.success||x.data.projectId!==a.projectId||x.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Customer session belongs to another App/environment")}g.identify(A)},reset:R,dispose(){u||(u=!0,h(),d())},request(A,x={},v="POST",P={}){if(u)return Promise.reject(new b("CLOSED","SDK client was destroyed"));if(P.installationDetach)return y(A,x,v,P);let j=l;try{let _=g.access(),X=le=>{if(j!==l)throw new b("IDENTITY_CHANGED","Customer identity changed before dispatch");return y(A,x,v,P,le)};return typeof _=="string"?X(_):_.then(X)}catch(_){return Promise.reject(_)}}}}function Fh(e,t,n={}){let r=!1;function i(){if(r)throw new b("CLOSED","SDK client was destroyed")}let a=new Set,o=c=>{for(let u of a)try{u(c)}catch{}},s=e.session.subscribeIdentity(()=>{o(!!e.session.peek()),n.afterChange?.()},()=>{t()});return{assertActive:i,isIdentified:()=>!r&&!!e.session.peek(),methods:{subscribeIdentity(c){return i(),a.add(c),()=>{a.delete(c)}},identify(c){i();let u=typeof c=="string"?c:c.accessToken;if(!kt.test(u))throw new b("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(u),e.identify(c)},reset(){if(!r)try{n.beforeReset?.()}finally{e.reset()}},destroy(){if(!r){r=!0,s(),a.clear();try{n.beforeDestroy?.(),t()}finally{e.dispose()}}}}}}function ze(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new b("INVALID_REQUEST","Customer requests use the verified session identity")}var hv={...O.readHoldings,request:O.readHoldings.request.omit({customerId:!0})};function Mh(e){return{async checkEntitlement(t){ze(t);let n=O.checkEntitlement;return ge(e,n,t)},async readHoldings(t={}){return ge(e,hv,t)}}}function qh(e){return{async readLedger(t){let n=O.readLedger;return ge(e,n,{query:t})},async readCreditStatement(t){ze(t);let n=O.readCreditStatement;return ge(e,n,t)},async quoteBalance(t){ze(t);let n=O.quoteBalance;return ge(e,n,{command:t})}}}function Uh(e){return{async setupPayment(t){ze(t);let n=O.setupPayment;return ge(e,n,t)},async readPaymentSetup(t){ze(t);let n=O.readPaymentSetup;return ge(e,n,t)},async readBillingInvoice(t){ze(t);let n=O.readBillingInvoice;return ge(e,n,t)},async readBillingControls(t={}){ze(t);let n=O.readBillingControls;return ge(e,n,t)},async prepareBillingAuthorization(t){ze(t);let n=O.prepareBillingAuthorization;return ge(e,n,t)},async confirmBillingAuthorization(t){ze(t);let n=O.confirmBillingAuthorization;return ge(e,n,t)},async setBillingCoupons(t){ze(t);let n=O.setBillingCoupons;return ge(e,n,t,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(t){ze(t);let n=O.revokeBillingAuthorization;return ge(e,n,t)},async listBillingInvoices(t={after:null,limit:25}){ze(t);let n=O.listBillingInvoices;return ge(e,n,t)},async confirmBillingAdjustment(t){ze(t);let n=O.confirmBillingAdjustment;return ge(e,n,t)}}}function Bh(e){return{async previewUpdate(t){ze(t);let n=O.previewUpdate;return ge(e,n,t)},async update(t){ze(t);let n=O.update;return ge(e,n,t)},async readSubscriptionUpdate(t){ze(t);let n=O.readSubscriptionUpdate;return ge(e,n,t)},async restoreNativePurchase(t){ze(t);let n=O.restoreNativePurchase;return ge(e,n,t)},async previewAttach(t){ze(t);let n=O.previewAttach;return ge(e,n,t)},async attach(t){ze(t);let n=O.attach;return ge(e,n,t)},async readSubscriptionOperation(t){ze(t);let n=O.readSubscriptionOperation;return ge(e,n,t)}}}function Vh(e){return{async redeemReward(t){return ze(t),(await ge(e,O.redeemReward,{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(t){return ze(t),(await ge(e,O.claimRewardProduct,t,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(t){return ze(t),(await ge(e,O.createReferralCode,{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(t,n=crypto.randomUUID()){let r=await ge(e,O.redeemCoupon,{code:t,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(t,n=crypto.randomUUID()){let r=await ge(e,O.grantOffer,{couponId:t,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await ge(e,O.listOffers,{},{response:"Invalid offers response"})).offers}}}function Lh(e){return{...Mh(e),...qh(e),...Uh(e),...Bh(e),...Vh(e)}}function zh(e){return{async resolveContent(t){ze(t);let n=O.resolveContent;return ge(e,n,t)},async resolvePaywall(t){ze(t);let n=O.resolvePaywall;return ge(e,n,t)},async resolveOffering(t){ze(t);let n=O.resolveOffering;return ge(e,n,t)}}}var ll=e=>new TextEncoder().encode(JSON.stringify(e)).length,$h=16384;function Gh(e,t){let n=0,r,i=d=>{r={config:structuredClone(d),until:Date.now()+3e4}},a=[],o=null,s;function c(){if(!t())throw new b("NOT_IDENTIFIED","Call identify before using Features or events")}function u(){s||!a.length||(s=setTimeout(()=>{s=void 0,m().catch(()=>{}).finally(u)},5e3),typeof s=="object"&&"unref"in s&&s.unref())}function l(d,h={},R={}){if(c(),r&&Date.now()<r.until&&!nf(r.config,d))return;g();let y=O.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:d,properties:h,...R}]}).events[0];if(ll({events:[y]})>$h)throw new b("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new b("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(y)),u()}async function m(d=!1){if(c(),o)return o;let h=n,R=(async()=>{let y={inserted:0,duplicates:0,rejected:0,skipped:0},A=a.length;for(;A&&h===n;){let x=[],v=ll({events:[]});for(let _ of a.slice(0,Math.min(A,100))){let X=ll(_)+(x.length?1:0);if(x.length&&v+X>$h)break;x.push(_),v+=X}let P=O.trackEvents,j=await ge(e,P,{events:x},void 0,{keepalive:d});if(h!==n)throw new b("IDENTITY_CHANGED","Event identity changed during delivery");if(j.inserted+j.duplicates+j.rejected+j.skipped!==x.length)throw new b("INVALID_RESPONSE","Incomplete event acknowledgement");i(j.analyticsConfig),a.splice(0,x.length),A-=x.length,y.inserted+=j.inserted,y.duplicates+=j.duplicates,y.rejected+=j.rejected,y.skipped+=j.skipped}return y})();o=R;try{return await R}finally{o===R&&(o=null)}}let f;function g(){if(f||typeof document>"u")return;let d=()=>{document.visibilityState==="hidden"&&t()&&a.length&&m(!0).catch(()=>{})};document.addEventListener("visibilitychange",d),f=()=>document.removeEventListener("visibilitychange",d)}return{rememberConfiguration:i,track:l,flush:m,reset(){n++,r=void 0,clearTimeout(s),s=void 0,a=[],o=null},detachVisibility(){f?.(),f=void 0}}}function dl(e){let t=null,n=null,r=0,i=0,a=new Set,o=null,s=null,c=new Set,u=()=>{for(let y of c)try{y()}catch{}},l={attributes:wt.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(y,A)=>{!a.has(y)&&(!t||!("analyticsConfig"in t)||t.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(y,structuredClone(A),structuredClone(l.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(y,A)=>(!t||!("analyticsConfig"in t)||t.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(y),structuredClone(A),structuredClone(l.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?y=>e.saveStickyBucketAssignmentDoc(structuredClone(y)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},m=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function f(y,A=new Set){return a.has(y)?!o||!o.features[y]||["unknownFeature","cyclicPrerequisite"].includes(o.features[y].source):A.has(y)?!1:(A.add(y),(t?.features[y]?.rules??[]).some(x=>[...x.parentConditions??[],...(x.tracks??[]).flatMap(v=>v.experiment.parentConditions??[])].some(v=>f(v.id,A))))}let g=y=>{if(e.assertUsable?.(t?.generation),!t)throw new Error("Initialize the Feature client before evaluation");if(t.expiresAt&&Date.parse(t.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return o?.expiresAt&&Date.parse(o.expiresAt)<=Date.now()&&(o=null,l.features=t.features),a.has(y)?!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now()?m():structuredClone(o.features[y]??m()):e.evaluateRemote&&(l.attributes?.merchandise||l.attributes?.merchandiseId)&&!o||f(y)?m():structuredClone(Kn(y,l))};async function d(){if(!t||!a.size&&!l.attributes?.merchandise&&!l.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(a.size)throw new Error("Remote Feature evaluation requires a server loader");return}let y=i;if(s?.revision===y)return s.loading;let A=r,x=t,v=[...a],P=(async()=>{let j=Ua.parse(await e.evaluateRemote({attributes:structuredClone(l.attributes),features:v}));if(!(A!==r||y!==i||x!==t)){if(e.assertUsable?.(x.generation),j.generation!==x.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(v.some(_=>!Object.hasOwn(j.features,_))||Object.keys(j.features).some(_=>!a.has(_)))throw new Error("Invalid remote Feature results");if(l.attributes?.merchandise||l.attributes?.merchandiseId){if(!j.merchandiseContext)throw new Error("Server did not resolve merchandise context");l.attributes=wt.parse({...l.attributes,...j.merchandiseContext})}o=structuredClone(j),l.features={...x.features,...Object.fromEntries(Object.entries(o.features).map(([_,X])=>[_,{defaultValue:X.value}]))},u()}})();s={revision:y,loading:P};try{await P}finally{s?.loading===P&&(s=null)}}function h(){d().catch(y=>{try{e.onError?.(y)}catch{}})}async function R(){if(n)return n;let y=r,A=(async()=>{let x=await e.load(),v="remoteFeatures"in x?fo.parse(x):null,P=v??yn.parse(x);if(P.scope.projectId!==e.scope.projectId||P.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(y!==r)throw new Error("Feature client was reset");if(e.assertUsable&&t?.generation===P.generation){let{evaluatedAt:_,expiresAt:X,...le}=t,{evaluatedAt:he,expiresAt:ke,...Se}=P;if(Pt(le)!==Pt(Se))throw new Error("Immutable Feature generation changed content");return t.evaluatedAt=P.evaluatedAt,t.expiresAt=P.expiresAt,u(),(!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())&&h(),structuredClone(t)}let j=new Set(v?.remoteFeatures??[]);if([...j].some(_=>Object.hasOwn(P.features,_)))throw new Error("Remote Feature definitions must not be delivered locally");return t&&"analyticsConfig"in t&&"analyticsConfig"in P&&!t.analyticsConfig.experimentViewsEnabled&&v?.analyticsConfig.experimentViewsEnabled&&l.trackedExperiments?.clear(),t=structuredClone(P),a=j,o=null,s=null,i++,l.features=t.features,l.savedGroups=ii(t.savedGroups),l.trackedFeatureUsage={},u(),h(),structuredClone(t)})();n=A;try{return await A}finally{n===A&&(n=null)}}return{init:R,refresh:R,refreshRemote:d,get generation(){return t?.generation??null},get expiresAt(){return t?.expiresAt??null},subscribe(y){return c.add(y),()=>{c.delete(y)}},setAttributes(y){let A=wt.parse(y);(l.attributes?.merchandise||l.attributes?.merchandiseId||y.merchandise||y.merchandiseId)&&l.trackedExperiments?.clear(),l.attributes=A,i++,o=null,s=null,l.features=t?.features??{},l.trackedFeatureUsage={},u(),h()},evalFeature:g,isOn(y){return g(y).on},isOff(y){return g(y).off},getFeatureValue(y,A){let x=g(y).value;return structuredClone(x===null?A:x)},reset(){r++,i++,n=null,s=null,t=null,o=null,a.clear(),l.features={},l.savedGroups={},l.stickyBucketAssignmentDocs={},l.attributes={},l.trackedFeatureUsage={},l.trackedExperiments?.clear(),u()}}}function Kh(e){let t=e.merchandise;if(typeof e.merchandiseId=="string")return{internalId:e.merchandiseId};if(!(!t||typeof t!="object"||Array.isArray(t))){if(typeof t.internalId=="string")return{internalId:t.internalId};if(typeof t.externalId=="string")return{id:t.externalId};if(typeof t.id=="string")return{id:t.id}}}function yv(e){let t=Kh(e),{merchandiseId:n,merchandise:r,...i}=e;return{...i,...t?{merchandise:t}:{}}}function Hh(e,t,n,r,i){if(i&&r&&(i.scope.projectId!==r.projectId||i.scope.environment!==r.environment))throw new b("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,o=new Set;function s(){if(!t())throw new b("NOT_IDENTIFIED","Call identify before using Features or events")}async function c(u={}){i||s();let l=a,m=!1,f=async()=>{if(m||l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let he=O.getFeatures,ke=i?{scope:{projectId:i.scope.projectId,environment:i.scope.environment},payload:await i.features()}:await ge(e,he,{});if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");if(r&&(ke.scope.projectId!==r.projectId||ke.scope.environment!==r.environment))throw new b("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(ke.payload.analyticsConfig),ke},g=await f(),d=!0,h,R=he=>{try{u.onError?.(he)}catch{}},y=(he,ke,Se)=>{try{let ht=Kh(Se);n.track(he,ke,ht?{merchandise:ht}:{})}catch(ht){R(ht)}},A=dl({assertUsable:i?.assertFeatures,scope:g.scope,attributes:u.attributes,onError:u.onError,load:async()=>d?(d=!1,g.payload):(await f()).payload,evaluateRemote:async he=>{if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let ke=O.evaluateFeatures,Se=await ge(e,ke,{...he,attributes:yv(he.attributes)});if(Se.scope.projectId!==g.scope.projectId||Se.scope.environment!==g.scope.environment)throw new b("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:Se.generation,evaluatedAt:Se.evaluatedAt,expiresAt:Se.expiresAt,features:Se.features,...Se.merchandiseContext?{merchandiseContext:Se.merchandiseContext}:{}}},onExperimentViewed:(he,ke,Se)=>y("Experiment Viewed",{experimentId:he.key,variationId:ke.key},Se),onFeatureUsage:(he,ke,Se)=>y("Feature Evaluated",{feature:he,value:ke.value,source:ke.source,ruleId:ke.ruleId,...ke.experimentResult?{variationId:ke.experimentResult.key}:{}},Se)}),x=A.refresh;function v(){clearTimeout(h),!i&&(m||l!==a||!A.expiresAt||(h=setTimeout(()=>{P().catch(R)},Math.min(2147483647,Math.max(1e3,Date.parse(A.expiresAt)-Date.now()))),typeof h=="object"&&"unref"in h&&h.unref()))}async function P(){try{return await x()}finally{v()}}let j=()=>{m||P().catch(R)},_=A.subscribe(v),X=i?.subscribe(()=>{!m&&i.fresh&&P().catch(R)});function le(){m||(m=!0,clearTimeout(h),typeof window<"u"&&window.removeEventListener("focus",j),_(),X?.(),A.reset(),o.delete(le))}o.add(le);try{await A.init(),(u.attributes?.merchandise||u.attributes?.merchandiseId)&&await A.refreshRemote()}catch(he){throw le(),he}return v(),!i&&typeof window<"u"&&window.addEventListener("focus",j),Object.assign(A,{refresh:P,destroy:le})}return{features:c,reset(u){a++,u();for(let l of o)l()}}}import{z as Av}from"zod";function Qh(e,t){let n="source"in t?{funnelId:t.source.id,funnelVersionId:t.source.versionId}:"versionId"in t?{funnelId:t.funnelId,funnelVersionId:t.versionId}:t,r=Av.object({funnelId:as.shape.id,funnelVersionId:as.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new b("INVALID_REQUEST","A valid Funnel source is required");let i=Object.freeze(r.data);function a(o){if("customerId"in o)throw new b("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in o&&o.funnelId!==void 0&&o.funnelId!==i.funnelId||"funnelVersionId"in o&&o.funnelVersionId!==void 0&&o.funnelVersionId!==i.funnelVersionId)throw new b("SCOPE_MISMATCH","The original Funnel source cannot change");return{...o,...i}}return{async claimCoupon(o,s=crypto.randomUUID()){let c=O.grantOffer,u=await ge(e,c,a({couponId:o,requestId:s}));return{offer:u.offer,reason:u.reason}},async resolveOffering(o){let s=O.resolveOffering;return ge(e,s,a(o))},async resolvePaywall(o){let s=O.resolvePaywall;return ge(e,s,a(o))},async previewAttach(o){let s=O.previewAttach;return ge(e,s,a(o))}}}function Jh(e){let t=fr(e),n=t.request,r;try{r=ch(e.push,t,e.scope??e.configuration?.scope)}catch(s){throw t.dispose(),s}let i=Fh(t,()=>{o.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=Gh(n,i.isIdentified),o=Hh(n,i.isIdentified,a,e.scope,e.configuration);return{session:t.session,...lh(n,r),...Lh(n),...zh(n),forFunnel(s){return i.assertActive(),Qh(n,s)},async features(s={}){return i.assertActive(),o.features(s)},track(s,c,u={}){return a.track(s,c,u)},flush(){return a.flush()},...i.methods}}function Ni(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,a)=>Ni(i,t[a]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let n=Object.entries(e),r=Object.entries(t);return n.length===r.length&&n.every(([i,a])=>Object.hasOwn(t,i)&&Ni(a,Reflect.get(t,i)))}function As(e,t){let n=Gg.safeParse(t);if(!n.success)throw new b("INVALID_RESPONSE","Funnel response contract changed");let r=n.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new b("SCOPE_MISMATCH","Funnel scope changed");return r}var Di=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function bs(e){let t=kt.test(e.apiKey);if(typeof window<"u"&&!t)throw new b("SERVER_ONLY","Funnel starts are issued by your backend");if(!t&&!Di.test(e.apiKey))throw new b("INVALID_TOKEN","A customer credential or server API key is required");return{async start(n){let r=Ot.safeParse({...n,operation:"start"});if(!r.success||r.data.operation!=="start"||(t?r.data.customer!==void 0:r.data.customer===void 0))throw new b("INVALID_REQUEST","Invalid current Funnel start");let i=r.data,a=fr({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||a.identify(e.apiKey);let o=As(e,await a.request("funnels",i));if(!o.runToken)throw new b("INVALID_RESPONSE","Funnel start credentials are missing");if(o.run.source.id!==i.funnelId||o.run.locale!==(i.locale??"en")||!Ni(o.run.parameters,i.parameters??{})||(i.customer?!o.customerId||i.customer.type==="id"&&o.customerId!==i.customer.value:o.customerId!==void 0))throw new b("INVALID_RESPONSE","Funnel start contract changed");return{...o,runToken:o.runToken}}finally{a.dispose()}}}}async function pl(e,t,n){if(Number(e.headers.get("content-length"))>t)throw e.body?.cancel().catch(()=>{}),n.error("limit");let r=e.body?.getReader();if(!r)throw n.error("missing");let i=[],a=0,o=!1,s=()=>{},c=new Promise((m,f)=>{s=()=>f(n.signal?.reason),n.signal?.addEventListener("abort",s,{once:!0}),n.signal?.aborted&&s()});try{for(;;){let m=await Promise.race([r.read(),c]);if(m.done){o=!0;break}if(a+=m.value.length,a>t)throw n.error("limit");i.push(m.value)}}finally{n.signal?.removeEventListener("abort",s),o||r.cancel().catch(()=>{}),r.releaseLock()}n.signal?.throwIfAborted();let u=new Uint8Array(a),l=0;for(let m of i)u.set(m,l),l+=m.length;return u}async function Zh(e,t,n){return new TextDecoder("utf-8",{fatal:!0}).decode(await pl(e,t,n))}function xs(e,t){let n=typeof e=="string"?new TextEncoder().encode(e):e;return n.byteLength===t.byteLength&&Iu(n)===t.sha256}async function Ss(e,t){let n=Vr.parse(t),{artifact:r,environmentId:i}=n.content,a=new xn(e.baseUrl??mr).origin,o=new xn(r.url,a);if(o.origin!==a||o.username||o.password||o.search||o.hash||o.pathname!==`/api/v1/configuration/${i}/artifacts/${r.sha256}`)throw new b("INVALID_RESPONSE","Public Paywall locator is not trusted");let s=new AbortController,c,u=new Promise((m,f)=>{c=setTimeout(()=>{let g=new b("TIMEOUT","Public Paywall read timed out");s.abort(g),f(g)},nn.initializationMs)}),l=(async()=>{let m=await(e.fetch??globalThis.fetch)(o,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:s.signal});if(s.signal.aborted&&(m.body?.cancel().catch(()=>{}),s.signal.throwIfAborted()),!m.ok||!m.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(m.headers.get("content-length"))>r.byteLength)throw m.body?.cancel().catch(()=>{}),new b("INVALID_RESPONSE","Public Paywall is unavailable");let f=await pl(m,r.byteLength,{signal:s.signal,error:g=>new b("INVALID_RESPONSE",g==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!xs(f,r))throw new b("INVALID_RESPONSE","Public Paywall digest or size changed");return Yf(n,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(f)))})();try{return await Promise.race([l,u])}finally{clearTimeout(c)}}var Wh=(e,t)=>new b(e,t);var bv=3,xv=2e3;function Sv(e){return e instanceof TypeError||e instanceof b&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function Iv(e){for(let t=1;;t++)try{return await e.refresh()}catch(n){if(t===bv||!Sv(n))throw n;await new Promise(r=>setTimeout(r,t*xv))}}async function ml(e,t,{predict:n=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new b("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new b("SCOPE_MISMATCH","Evaluation environment changed");let i=null,a;if(n)try{let o=await e.funnel(t.source.id,t.source.versionId);a=o.manifest.generation,i=vv(e,t,o)}catch{i=null}return a??(a=e.snapshot?.generation??(await Iv(e)).generation),{advance:{policyRevision:r.policyRevision,generation:a},prediction:i}}function vv(e,t,n){let r=t.instruction;if(r?.type!=="evaluate_segment"||!n.growth||n.control.evaluationMode!=="local"||n.control.evaluationRevision!==r.policyRevision)return null;let{analyticsConfig:i,remoteFeatures:a,...o}=n.growth,s=Vu({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t.source.id,versionId:t.source.versionId,evaluationMode:"local",evaluationRevision:r.policyRevision,document:n.document,payload:yn.parse(o)}),c=wv(s,n.document,{...t,...r}),u=c.steps.at(-1),l=c.boundary??(u?.result.port==="value"?{nodeId:u.nodeId,visit:t.visit+c.steps.length-1}:null);return l?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:l.nodeId,visit:l.visit,terminal:!c.boundary}:null}function wv(e,t,n){return sh(e,t,n,Wh)}import{z as gn}from"zod";var Yh=Ot.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new b("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),Xh=gn.strictObject({schemaVersion:gn.literal(1),scope:Ne,runId:gn.uuid(),funnelId:gn.uuid(),versionId:gn.uuid(),processBindingIds:gn.record(gn.uuid(),gn.uuid().nullable()).optional(),command:Yh.optional(),closeCommand:Yh.refine(e=>e.operation==="close").optional(),purchase:gn.strictObject({receiptId:gn.uuid(),operationId:gn.uuid(),generation:gn.number().int().nonnegative()}).optional(),closed:gn.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),Xt=()=>new b("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Is=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function ey(e){let t=0,n=null,r=u=>JSON.stringify([u.scope,u.runId,u.funnelId,u.versionId]),i=Promise.resolve();async function a(){let u=await e.read();if(!Number.isSafeInteger(u.revision)||u.revision<0)throw new b("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:u.revision,entry:u.entry===null?null:Xh.parse(u.entry)}}function o(u){let l=i.then(u);return i=l.catch(()=>{}),l}async function s(u){for(let l=0;l<4;l++){let m=await a();if(m.entry&&n!==null&&r(m.entry)!==n)throw Xt();let f=u(m.entry,m.revision);if(Is(m.entry,f)){t=m.revision;return}let g=await e.write(m.revision,f);if(g!==null){if(!Number.isSafeInteger(g)||g<=m.revision)throw Xt();t=g;return}}throw Xt()}function c(u,l){if(!u||!l)return u;if(u.processBindingIds&&Object.hasOwn(u.processBindingIds,l)){let m={...u.processBindingIds};delete m[l],u={...u,processBindingIds:m}}return u.command?.requestId===l?u.closeCommand?{...u,command:u.closeCommand,closeCommand:void 0}:u.purchase?{...u,command:void 0}:null:u.closeCommand?.requestId===l?{...u,closeCommand:void 0}:u}return{bind(u){let l=JSON.stringify([u.scope,u.runId,u.funnelId,u.versionId]);if(n!==null&&n!==l)throw Xt();n=l},async load(){let u=await a();return t=u.revision,n=u.entry?r(u.entry):null,u.entry},retain(u){let l=Xh.parse(u),m=l.command;return!m||n!==null&&r(l)!==n?Promise.reject(Xt()):(n??(n=r(l)),o(()=>s((f,g)=>{if(f&&!Is(r(f),r(l)))throw Xt();if(f&&l.processBindingIds){for(let[d,h]of Object.entries(l.processBindingIds))if(f.processBindingIds&&Object.hasOwn(f.processBindingIds,d)&&f.processBindingIds[d]!==h)throw Xt();f={...f,processBindingIds:{...f.processBindingIds,...l.processBindingIds}}}if(!f){if(g!==t&&m.operation!=="close")throw Xt();return l}if(!f.command)return{...f,command:m,...m.operation==="close"?{closed:!0}:{}};if(m.operation==="close"&&f.command.operation!=="close"){if(f.command.requestId===m.requestId||f.closeCommand&&!Is(f.closeCommand,m))throw Xt();return{...f,closeCommand:m,closed:!0}}if(!Is(f.command,m))throw Xt();return f})))},observePurchase(u,l,m,f){return o(()=>s((g,d)=>{if(!g&&d!==t||g&&r(g)!==r({...u,schemaVersion:1}))throw Xt();if(g?.purchase&&g.purchase.generation>l.generation)return c(g,f);if(g?.purchase&&g.purchase.generation===l.generation&&g.purchase.operationId!==l.operationId)throw Xt();return m?!g?.purchase||g.purchase.operationId!==l.operationId?c(g,f):c(g.command?{...g,purchase:void 0}:null,f):c({schemaVersion:1,...u,...g,purchase:l},f)}))},settle(u){return o(()=>s(l=>c(l,u)))}}}function ty(e){let t,n,r=()=>new b("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,n=e.locks??globalThis.navigator?.locks,!t||!n||!globalThis.crypto?.subtle)throw r();let s=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??mr).href,e.runToken])),c=new Uint8Array(await crypto.subtle.digest("SHA-256",s));return"indiana.funnel.commands.v1."+Array.from(c,u=>u.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function a(s){try{let c=await i;return await n.request(c,{mode:"exclusive"},()=>s(c))}catch(c){throw c instanceof b?c:r()}}function o(s){let c=t.getItem(s);if(c===null)return{revision:0,entry:null};if(c.length>1048576)throw r();let u=JSON.parse(c);if(!u||typeof u!="object"||!("revision"in u)||!("entry"in u)||!Number.isSafeInteger(u.revision)||Number(u.revision)<0)throw r();return{revision:Number(u.revision),entry:u.entry}}return{read:()=>a(o),write:(s,c)=>a(u=>{if(o(u).revision!==s)return null;if(!Number.isSafeInteger(s+1))throw r();return t.setItem(u,JSON.stringify({revision:s+1,entry:c})),s+1})}}function ny(e,t){let n=t&&{...t},r=null,i=0,a=new AbortController;function o(){i++,a.abort(new b("IDENTITY_CHANGED","Run identity changed")),a=new AbortController}let s=!1,c,u=0,l=new Set;return{get scope(){return n},bindScope(m){if(n&&(n.projectId!==m.projectId||n.environment!==m.environment))throw new b("SCOPE_MISMATCH","Run scope changed");n??(n={...m})},get view(){return r},get generation(){return i},get signal(){return a.signal},get disposed(){return s},get customerToken(){return c},get readSequence(){return u},nextRead(){return++u},assertCurrent(m,f="Run identity changed during the request"){if(m!==i||s)throw new b("IDENTITY_CHANGED",f)},assertRun(m){if(r&&(m.id!==r.id||m.source.type!==r.source.type||m.source.id!==r.source.id||m.source.versionId!==r.source.versionId||m.locale!==r.locale||!Ni(m.parameters,r.parameters)))throw new b("INVALID_RESPONSE","Run version changed");if(e&&m.source.id!==e)throw new b("INVALID_RESPONSE","Run belongs to another Funnel")},publish(m,f,g,d,h){if(!(m.operation==="review"&&r&&r!==g&&f.run.revision<=r.revision)&&!(r&&f.run.revision===r.revision&&d!==void 0&&d<u)&&(m.operation==="review"&&!f.run.stopped&&["running","waiting"].includes(f.run.status)&&r&&f.run.nodeId===r.nodeId&&f.run.visit===r.visit&&f.run.revision===r.revision&&(f.run.screen=r.screen,(r.paywall?.quote?.operationId===f.review?.activeOperationId||!r.paywall?.quote&&f.review?.activeOperationId===null)&&(f.run.paywall=r.paywall)),!(r?.paywall&&f.run.paywall&&r.paywall.receiptId===f.run.paywall.receiptId&&(f.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||f.run.revision>=r.revision)r=f.run;else if(!h)return;if(r)for(let R of l)try{R(structuredClone(r))}catch{}}},identify(m){if(s)throw new b("IDENTITY_CHANGED","Controller was reset");if(!kt.test(m))throw new b("INVALID_TOKEN","Customer credential required");o(),c=m},subscribe(m){return l.add(m),()=>l.delete(m)},reset(){s||(s=!0,o(),c=void 0,r=null,l.clear())}}}function gr(e){let{customerToken:t,...n}=e;return n}var Ov=e=>!(e instanceof b)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function ry({journal:e,state:t,call:n,processIdentity:r}){let i=null,a=null,o=!1,s={command:null,close:null},c=new Set,u,l=null,m=e?e.load().then(y=>{if(t.disposed)throw new b("IDENTITY_CHANGED","Controller was reset during command restoration");if(l=y,!y)return;if(r){if([y.command,y.closeCommand].some(x=>x&&!Object.hasOwn(y.processBindingIds??{},x.requestId)))throw new b("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(y.processBindingIds??{})}if(t.scope&&(y.scope.projectId!==t.scope.projectId||y.scope.environment!==t.scope.environment))throw new b("SCOPE_MISMATCH","Pending command belongs to another scope");if(u=y.purchase,o=y.closed===!0,!y.command)return;let A=y.command;i=A.operation==="close"?null:A,a=A.operation==="close"?A:y.closeCommand?.operation==="close"?y.closeCommand:null,a&&(o=!0);for(let x of[i,a])x&&c.add(x.requestId)}):Promise.resolve();m.catch(()=>{});async function f(y){e&&await m;let A=t.generation;if(e){if(!t.view||!t.scope)throw new b("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:gr(y),...r?{processBindingIds:{[y.requestId]:r.binding(y.requestId)}}:{}})}if(A!==t.generation||i!==y&&a!==y)throw new b("IDENTITY_CHANGED","Run changed before command dispatch");let x=c.has(y.requestId);c.add(y.requestId);try{return await n(y)}catch(v){throw A===t.generation&&(i===y||a===y)&&!x&&!Ov(v)&&(e&&await e.settle(y.requestId),A===t.generation&&R(y)),v}}function g(y){let A=Ot.parse(y);if(A.operation==="start"||A.operation==="get"||A.operation==="review")throw new b("INVALID_REQUEST","Mutation required");if(o&&A.operation!=="close"){if(i?.requestId===A.requestId)return h(A.requestId);throw new b("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(A.operation==="close"){if(i?.requestId===A.requestId)throw new b("INVALID_REQUEST","Close requires its own request identity");if(o=!0,a&&JSON.stringify(gr(a))!==JSON.stringify(gr(A)))throw new b("COMMAND_PENDING","Retry the original Close");return a??(a=A),s.close?s.close:d(a,"close")}if(i){if(JSON.stringify(gr(i))!==JSON.stringify(gr(A)))throw new b("COMMAND_PENDING","Retry the original command before sending another");if(s.command)return s.command}else i=A;return d(i,"command")}function d(y,A){let x=f(y);s[A]=x;let v=()=>{s[A]===x&&(s[A]=null)};return x.then(v,v),x}function h(y){return n({operation:"get",settlementRequestId:y})}function R(y){return!y||i!==y&&a!==y?!1:(i===y&&(i=null),a===y&&(a=null),c.delete(y.requestId),!i&&!a&&(l=null),!0)}return{ready:m,get pending(){return i},get closing(){return a},get closeRequested(){return o},get inFlight(){return s.command},get closeFlight(){return s.close},get purchase(){return u},assertBinding(y){if(l&&(y.run.id!==l.runId||y.run.source.id!==l.funnelId||y.run.source.versionId!==l.versionId))throw new b("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(y,A,x,v){let P=y.operation==="get"?y.settlementRequestId:"requestId"in y&&y.operation!=="start"?y.requestId:void 0,j=P&&A.settlement?.state==="settled"&&A.run.pendingRequest?.requestId!==P&&(y.operation==="get"||!o||y.operation==="close"||!["running","waiting"].includes(A.run.status))?P:void 0,_=i?.requestId===j?i:a?.requestId===j?a:void 0;e?.bind({scope:A.scope,runId:A.run.id,funnelId:A.run.source.id,versionId:A.run.source.versionId});let X=A.run.paywall,le=X??A.purchase,he=le?.operation,ke=A.settlement&&(!X||X.purchaseRequestId===A.settlement.requestId)&&(!u||u.operationId===A.settlement.operationId)?A.settlement:void 0,Se=he?.operationId??le?.quote?.operationId??ke?.operationId,ht=le?.receiptId??ke?.receiptId,Je=X?.selectionGeneration??u?.generation??0;if(e&&Se&&ht&&y.operation!=="review"&&(!t.view||A.run.revision>=t.view.revision)&&(v===void 0||v>=t.readSequence)&&(!u||Je>=u.generation)){let Te={receiptId:ht,operationId:Se,generation:Je},tt=he?.status==="complete"||le?.canReselect===!0;await e.observePurchase({scope:A.scope,runId:A.run.id,funnelId:A.run.source.id,versionId:A.run.source.versionId},Te,tt,j),t.assertCurrent(x),(!u||Te.generation>=u.generation)&&(v===void 0||v>=t.readSequence)&&(tt?u?.operationId===Te.operationId&&(u=void 0):u=Te)}else e&&j&&await e.settle(j);return t.assertCurrent(x),j?R(_):!1},stop(){o=!0},submit:g,settle:h,reset(){o=!0,i=null,a=null,u=void 0,l=null,s.close=null,c.clear(),s.command=null}}}function hr(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new b("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!Di.test(e.serverKey)))throw new b("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new b("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let t=fr({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),n=ny(e.funnelId,e.scope??e.configuration?.scope),r=e.session?.subscribeIdentity(u),i=null,a=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?ty(e):void 0),o=a&&ey(a),s=ry({journal:o,state:n,call:l,processIdentity:e.process});async function c(A){if(e.process)return e.process.request(A);let x=n.generation;n.assertCurrent(x);let v=performance.now()+(e.timeoutMs??35e3),P=n.customerToken??("customerToken"in A?A.customerToken:void 0);if(e.session){let X=n.signal,le,he=()=>{},ke=new Promise((Se,ht)=>{he=()=>ht(X.reason),X.addEventListener("abort",he,{once:!0}),le=setTimeout(()=>ht(new b("TIMEOUT","Longplay request timed out")),Math.max(1,v-performance.now()))});try{P=await Promise.race([Promise.resolve().then(()=>(n.assertCurrent(x),e.session.access())),ke])}finally{clearTimeout(le),X.removeEventListener("abort",he)}}n.assertCurrent(x);let j={...A,...P?{customerToken:P}:{}},_=A.operation==="page_experiments"?Co.parse(j):Ot.parse(j);return t.requestWithCredential("funnels",_,e.runToken,{headers:e.serverKey&&!P?{[Kg]:e.serverKey}:void 0,timeoutMs:Math.max(1,v-performance.now())})}function u(){r?.(),n.reset(),s.reset(),i=null,t.dispose()}async function l(A,x){let v=n.generation,P=()=>n.assertCurrent(v);o&&await s.ready,P();let j=n.view,_=As(e,await c(A));if(A.operation==="review"&&!_.review)throw new b("INVALID_RESPONSE","Historical projection is missing");if(P(),_.runToken&&_.runToken!==e.runToken)throw new b("INVALID_RESPONSE","Run credential changed");let X=A.operation==="get"?A.settlementRequestId:"requestId"in A&&A.operation!=="start"?A.requestId:void 0;if(X&&_.settlement?.requestId!==X)throw new b("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");s.assertBinding(_),n.assertRun(_.run),n.bindScope(_.scope);let le=await s.observe(A,_,v,x);return!_.run.stopped&&["running","waiting"].includes(_.run.status)&&A.operation==="get"&&A.settlementRequestId||(P(),["running","waiting"].includes(_.run.status)||s.stop(),n.publish(A,_,j,x,le)),_}let m=s.submit,f=null,g=new WeakMap;function d(A){let x=g.get(A);if(x)return x;let v=R(A);return g.set(A,v),v}let h=!1;async function R(A){let x=await A;if(x.run.instruction?.type!=="evaluate_segment")return x;if(f)return f;h=!0;let v=n.generation,P=(async()=>{for(let j=0;j<32&&x.run.instruction?.type==="evaluate_segment";j++){if(s.pending||s.closeRequested)return x;let _=x.run;if(x.run.instruction?.type==="evaluate_segment"){let{advance:le}=await ml(e.configuration,_,{predict:!1});if(v!==n.generation)throw new b("IDENTITY_CHANGED","Run identity changed during segment calculation");if(s.pending||s.closeRequested)return x;if(n.view&&(n.view.revision!==_.revision||n.view.visit!==_.visit||n.view.nodeId!==_.nodeId))return l({operation:"get"});let he=!0;ml(e.configuration,_).then(({prediction:ke})=>{he&&v===n.generation&&!s.closeRequested&&n.view?.id===_.id&&!n.view.stopped&&n.view.nodeId===_.nodeId&&n.view.visit===_.visit&&n.view.revision===_.revision&&(i=ke)}).catch(()=>{});try{x=await m({operation:"commit_segment",requestId:$g(_.id,_.visit,`segment:${_.revision}`),nodeId:_.nodeId,visit:_.visit,revision:_.revision,...le})}finally{he=!1,i=null}}}return x})();f=P;try{return await P}finally{f===P&&(f=null)}}let y={get configuration(){return h?e.configuration:void 0},get configurationReady(){return!0},get view(){return n.view?structuredClone(n.view):null},get pendingCommand(){let A=s.closing??s.pending;return A?structuredClone(gr(A)):null},get pendingCommands(){return[s.pending,s.closing].filter(A=>A!==null).map(A=>structuredClone(gr(A)))},get pendingPurchase(){return s.purchase?structuredClone(s.purchase):null},get hasDurableJournal(){return o!==void 0},get prediction(){let A=n.view;return i&&A&&!A.stopped&&["running","waiting"].includes(A.status)&&A.id===i.runId&&A.nodeId===i.from.nodeId&&A.visit===i.from.visit&&A.revision===i.from.revision&&!s.closeRequested?structuredClone(i):null},settle:s.settle,get webViewUrl(){return"bundled"},resolvePaywall(A){return Ss(e,A)},async pageExperiments(A,x=[]){let v=n.generation;n.assertCurrent(v);let P=n.view?.id;if(!P)throw new b("INVALID_REQUEST","Read the Run before its page experiments");let j=Zg.parse(await c(Co.parse({operation:"page_experiments",release:A,usedReceiptIds:x})));if(n.assertCurrent(v),j.runId!==P||j.scope.projectId!==n.scope?.projectId||j.scope.environment!==n.scope?.environment)throw new b("SCOPE_MISMATCH","Page experiment Run changed");return j},review(A){return l({operation:"review",...A?{receiptId:A}:{}},n.nextRead())},async get(A,x){o&&await s.ready,x??(x=s.purchase&&{receiptId:s.purchase.receiptId,operationId:s.purchase.operationId});let v=n.nextRead();return d(l({operation:"get",...A?{data:A}:{},...x?{purchase:x}:{}},v))},resume(A=n.view?.pendingRequest?.requestId){return A?s.closeRequested?y.settle(A):s.pending?.requestId===A?d(m(s.pending)):d(m({operation:"resume",requestId:A})):Promise.reject(new b("INVALID_REQUEST","No interrupted command is available"))},submit(A){return d(m(A))},retry(){return s.closeFlight?s.closeFlight:s.closing?m(s.closing):s.closeRequested&&s.pending?y.settle(s.pending.requestId):s.inFlight?d(s.inFlight):s.pending?d(m(s.pending)):Promise.reject(new b("INVALID_REQUEST","No command is pending"))},identify(A){n.identify(A),i=null,t.reset()},subscribe:n.subscribe,reset:u};return y}function iy(e){if(!kt.test(e.customerToken))throw new b("INVALID_TOKEN","A customer credential is required");if(!e.scope)throw new b("INVALID_REQUEST","An explicit App and environment scope is required");let t=bs({...e,scope:e.scope,apiKey:e.customerToken});return{async start(n){let r=await t.start(n),i=hr({...e,runToken:r.runToken});i.identify(e.customerToken);let a=r.run.instruction?.type==="evaluate_segment"?await i.get():r;return{...r,...a,controller:i}}}}function oy(e,t){let n=r=>"document"in r?r.offering.id:r.content.offeringVersionId;return e.id===t.id&&n(e)===n(t)&&e.content?.artifact.sha256===t.content?.artifact.sha256}function ay(e,t,n){if(e.operationId!==t.operationId||t.currency!==void 0&&e.currency!==t.currency)throw new b("INVALID_RESPONSE",n)}function sy(e,t,n){let r=Object.fromEntries((e.lines[0]?.prepaid??[]).map(i=>[i.internal_feature_id,i.quantity]));if(t.featureQuantities&&(Object.keys(r).length!==Object.keys(t.featureQuantities).length||Object.entries(t.featureQuantities).some(([i,a])=>r[i]!==a)))throw new b("INVALID_RESPONSE","The purchase quote changed its selected quantities");if(e.lines.length!==1||e.lines[0].productVersionId!==t.productVersionId||t.currency!==void 0&&e.currency!==t.currency||t.provider!==void 0&&e.provider!==t.provider&&!(t.provider==="stripe"&&e.provider==="merchant"&&e.execution?.provider==="merchant"))throw new b("INVALID_RESPONSE",n)}function cy(e,t,n=!1){return!e||e.operationId!==t?.operationId?t:e.status==="complete"&&t.status!=="complete"||e.status!=="pending"&&(t.status==="pending"||n&&t.status!=="complete")?e:t}function uy(e){let{quote:t,operation:n,requestId:r}=e,a={type:"recover",operationId:n?.operationId??t?.operationId??null,requestId:r};if(e.destroyed||e.pending)return a;if(!n)return t?{type:"cancel",operationId:t.operationId}:a;let o=n.merchantExecution;if(o?.type==="purchase"){if(["succeeded","not_required"].includes(o.paymentStatus))return!["applied","not_applicable"].includes(o.fulfillmentStatus)||n.problem?.phase==="fulfillment"||o.problem?.phase==="fulfillment"?{type:"fulfillment",operationId:n.operationId}:{type:o.recordingStatus==="accepted"&&n.status==="complete"?"complete":"recording",operationId:n.operationId};if(n.status==="pending"&&n.checkoutUrl&&o.checkoutUrl===n.checkoutUrl&&o.checkoutExpiresAt&&Date.parse(o.checkoutExpiresAt)>Date.now()&&["not_started","pending"].includes(o.paymentStatus))return{type:"checkout",operationId:n.operationId,checkoutUrl:n.checkoutUrl}}let s=[n.problem,o?.problem],c=s.every(u=>!u||u.phase==="execution"&&u.reason!=="RESULT_UNKNOWN");return!s.some(Boolean)&&n.status==="complete"&&n.executor!=="merchant"?{type:"complete",operationId:n.operationId}:c&&e.canReselect!==!1&&["cancelled","failed"].includes(n.status)&&!n.checkoutUrl&&!n.execution&&!n.nativePurchase&&(n.executor!=="merchant"?!n.confirmedAt&&(n.status==="cancelled"||!n.quoteFinalized):!o&&!n.quoteFinalized||o?.type==="purchase"&&["failed","expired"].includes(o.paymentStatus)&&o.fulfillmentStatus==="not_applicable"&&o.recordingStatus==="accepted")?{type:"native",operationId:n.operationId}:n.status==="pending"&&c&&!n.quoteFinalized&&!o&&!n.checkoutUrl&&!n.execution&&!n.nativePurchase?{type:"cancel",operationId:n.operationId}:a}async function ly(e,t){if(!kt.test(t.customerToken))throw new b("INVALID_TOKEN","A verified Customer credential is required");if(e.session&&e.session.peek()!==t.customerToken)throw new b("SCOPE_MISMATCH","Paywall credential does not match the shared session");let n=O.resolvePaywall.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale,...t.requirement?{requirement:t.requirement}:{}}),r=fr(e);e.session||r.identify(t.customerToken);let i=null,a=!1,o=null,s=null,c=null,u=null,l=null,m=null,f=null,g=0;function d(){if(a)throw new b("IDENTITY_CHANGED","Paywall is closed")}async function h(){d();let x=O.resolvePaywall,v=await ge(r.request,x,{...n,selector:i?{type:"version",versionId:i.id}:n.selector}),P=await Ss(e,v.paywall);if(d(),t.paywallVersionId?P.id!==t.paywallVersionId:P.paywallId!==t.paywallId)throw new b("INVALID_RESPONSE","The requested Paywall changed");if(i&&(!oy(P,i)||P.paywallId!==i.paywallId))throw new b("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return i=P,structuredClone(i)}async function R(x){if(d(),u&&x!=="read")throw new b("COMMAND_PENDING","Wait for the original quote");if(!o)throw new b("INVALID_REQUEST","A quoted purchase is required");let v=o;if(x!=="read"){if(f){if(m===x)return f;throw new b("COMMAND_PENDING","Wait for the original purchase command")}if(m&&m!==x)throw new b("COMMAND_PENDING","Read the original purchase before changing an uncertain command");m=x,g++}let P=m,j=g,_=x==="read"&&f===null,X=x==="read"?O.readSubscriptionOperation:O.attach,le=(async()=>{let he=await ge(r.request,X,{operationId:v.operationId,...x==="read"?{}:{intent:x}});return ay(he.operation,{operationId:v.operationId,currency:n.commerce.currency},"The purchase operation changed"),d(),o?.operationId!==v.operationId?structuredClone(he.operation):(s=cy(s,he.operation),(x!=="read"||_&&f===null)&&g===j&&m===P&&(m=null),structuredClone(s))})();if(x!=="read"){f=le;let he=()=>{f===le&&(f=null)};le.then(he,he)}return le}let y={get view(){return i?structuredClone(i):null},get quote(){return o?structuredClone(o):null},get operation(){return s?structuredClone(s):null},get webViewUrl(){return"bundled"},get recovery(){return uy({quote:o,operation:s,requestId:l,pending:u!==null||m!==null,destroyed:a})},get pendingCancellation(){return!a&&m==="cancel"},refresh:h,async preview(x){if(d(),!i)throw new b("INVALID_REQUEST","Load the Paywall first");let v=i.document.buttons[x.actionId];if(v?.type!=="checkout")throw new b("INVALID_REQUEST","Choose an authored purchase action");let P=Xm(v.product,x.selection,i.capabilities);if(!P)throw new b("PRODUCT_UNAVAILABLE","Choose an available Product");let j=zf(i.document.screen,P,x.selection,i.capabilities),_=O.previewAttach.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,requestId:x.requestId,plans:[{productVersionId:P,...Object.keys(j).length?{featureQuantities:j}:{}}],provider:n.commerce.provider,currency:n.commerce.currency,...x.offerId?{offerId:x.offerId}:{},...x.nativeOffer?{nativeOffer:x.nativeOffer}:{}}),X=JSON.stringify(_);if(c&&c!==X&&(u||m||!s||s.status==="pending"))throw new b("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(c===X){if(u)return u;if(o)return structuredClone(o)}c!==X&&(o=null,s=null),c=X,l=_.requestId;let le=(async()=>{let he=O.previewAttach,ke=await ge(r.request,he,_);return d(),sy(ke.quote,{productVersionId:P,featureQuantities:j,currency:n.commerce.currency,provider:n.commerce.provider},"The purchase quote changed its selected Product or presentment"),o=ke.quote,s=null,structuredClone(o)})();u=le;try{return await le}finally{u===le&&(u=null)}},confirm:()=>R("confirm"),cancel:()=>R("cancel"),read:()=>R("read"),destroy(){a||(a=!0,A?.(),r.dispose(),i=null,o=null,s=null,c=null,l=null)}},A=e.session?.subscribeIdentity(y.destroy);try{return await h(),y}catch(x){throw y.destroy(),x}}function dy(e,t){let n,r=0,i=-1,a,o=!1,s=()=>{if(o)throw new b("CLOSED","Native host was destroyed");if(!e.nativeModule)throw new b("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return e.nativeModule},c=()=>new b("IDENTITY_CHANGED","Customer identity changed during the native operation"),u=t.subscribeIdentity(()=>{r++,i=-1;let g=r;n&&e.nativeModule&&n.then(d=>e.nativeModule.reset(d,g)).catch(()=>{})}),l=e.nativeEvents?.(g=>{!n||!e.nativeModule||typeof g?.requestId!="string"||(async()=>{let d=await n;if(g.instanceId!==d)return;if(g.kind==="credential"){let y=r,A=null;try{if(!o&&g.revision===y){let x=await t.access();!o&&r===y&&(A=x)}}finally{await e.nativeModule.provideCredential(d,g.requestId,A)}return}let h=!1,R=r;try{if(o||g.revision!==R||!e.onNativeAction)throw c();await e.onNativeAction(g.action),h=!o&&r===R}finally{await e.nativeModule.acknowledge(d,g.requestId,h)}})().catch(()=>{})});async function m(g,d={}){let h=s();if(t.snapshot()&&!e.nativeEvents)throw new b("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let R=r,y=await t.access();if(o||r!==R)throw c();if(!n){let v=h.create(JSON.stringify({baseUrl:e.baseUrl??"https://api.longplayai.com",scope:e.scope,timeout:(e.timeoutMs??15e3)/1e3,credentialEvents:!!e.nativeEvents}));n=v,v.catch(()=>{n===v&&(n=void 0)})}let A=await n;if(o||r!==R)throw c();if(i!==R){if(!a||a.epoch!==R){let P=(async()=>{if(await h.identify(A,JSON.stringify({revision:R,credentials:y})),o||r!==R)throw await h.reset(A,R),c();i=R})();a={epoch:R,task:P}}let v=a;try{await v.task}finally{a===v&&(a=void 0)}}let x=await h.invoke(A,g,JSON.stringify(d));if(o||r!==R)throw c();try{return JSON.parse(x)}catch{throw new b("INVALID_RESPONSE","Native host returned invalid JSON")}}async function f(g,d){let h=await m(g,d);if(!h||typeof h!="object"||Array.isArray(h)||h.status!=="complete"&&h.status!=="dismissed")throw new b("INVALID_RESPONSE","Native presentation returned an invalid result");return h}return{showFunnel(g){return f("showFunnel",{runToken:g})},showPaywall(g){return f("showPaywall",g)},showContent(g){return f("showContent",g)},purchaseSubscription(g,d){return m("purchaseSubscription",{operationId:g,accepted:d})},switchSubscription(g,d){return m("switchSubscription",{operationId:g,accepted:d})},restorePurchases(){return m("restorePurchases")},manageSubscriptions(g){return m("manageSubscriptions",g?{productId:g}:{})},async dismiss(){r++,i=-1,n&&await s().reset(await n,r)},async destroy(){o||(o=!0,r++,u(),l?.(),n&&e.nativeModule&&await e.nativeModule.destroy(await n))}}}var Pv=O.trackUsage.request.shape.command,Cv=O.trackUsage.response;function _v(e){let t=Ne.parse(e.scope),n=Jh({...e,scope:t}),r={...e,scope:t,session:n.session},i=dy(e,n.session),a=0,o=!1;n.subscribeIdentity(()=>{a++});let s=()=>{if(o)throw new b("CLOSED","SDK client was destroyed");let c=n.session.peek();if(!c)throw new b("UNAUTHENTICATED","Identify the Customer first");return c};return{...n,native:i,async destroy(){o||(o=!0,a++,n.destroy(),await i.destroy())},funnel(){return iy({...r,customerToken:s()})},resumeFunnel(c){return s(),hr({...r,runToken:c})},paywall(c){return ly(r,{...c,customerToken:s()})},async trackUsage(c){if(s(),!e.usageReporter)throw new b("INVALID_REQUEST","Configure your authenticated backend usageReporter");let u=Pv.parse(c),l=a,m;try{m=await e.usageReporter(u)}catch(g){throw l!==a?new b("IDENTITY_CHANGED","Customer identity changed during usage reporting"):g}if(l!==a)throw new b("IDENTITY_CHANGED","Customer identity changed during usage reporting");let f=Cv.parse(m);if(f.scope.projectId!==t.projectId||f.scope.environment!==t.environment)throw new b("INVALID_RESPONSE","Usage response scope differs");return f}}}import{z as jv}from"zod";import{z as To}from"zod";var Ev=To.record(To.string().regex(/^[a-f0-9]{64}$/),To.strictObject({at:To.number(),text:To.string()})),Qr=2*1048576,Rv=100;function kv(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function py(e,t){let n=t===void 0?kv():t,r=new Map,i=0,a=!1,o=!1,s,c;async function u(m){if(!n)return null;let f;try{let g=await Promise.race([Promise.resolve().then(()=>n.getItem(m)),new Promise(d=>{f=setTimeout(()=>d(null),Rv)})]);return typeof g=="string"&&g.length<=Qr&&new TextEncoder().encode(g).byteLength<=Qr?g:null}catch{return null}finally{clearTimeout(f)}}function l(){if(c)return c;let m=(async()=>{try{let f=await u(`${e}:artifacts`);if(f)return Ev.parse(JSON.parse(f))}catch{}return{}})();return c=m,m.finally(()=>{c===m&&(c=void 0)}),m}return{async readManifest(){return u(e)},writeManifest(m){!n||m.length>Qr||new TextEncoder().encode(m).byteLength>Qr||(s=m,!o&&(o=!0,Promise.resolve().then(async()=>{try{for(;s!==void 0;){let f=s;try{await n.setItem(e,f)}catch{}s===f&&(s=void 0)}}finally{o=!1}})))},async readArtifact(m){let f=(await l())[m],g=Date.now();return f&&g>=f.at&&g-f.at<=nn.retentionMs?f.text:void 0},writeArtifact(m,f){if(!n||f.length>Qr)return;let g=r.get(m);if(g?.text===f||!g&&r.size>=128)return;let d=new TextEncoder().encode(f).byteLength;i-(g?.byteLength??0)+d>Qr||(r.set(m,{text:f,byteLength:d}),i+=d-(g?.byteLength??0),!a&&(a=!0,Promise.resolve().then(async()=>{try{for(;r.size;){let h=new Map(r);try{let R={...await l()},y=Date.now();for(let[P,j]of h)R[P]={at:y,text:j.text};let A={},x=2,v=0;for(let[P,j]of Object.entries(R).sort(([,_],[,X])=>X.at-_.at)){if(j.at>y||y-j.at>nn.retentionMs)continue;let _=new TextEncoder().encode(JSON.stringify({[P]:j})).byteLength;x+_>Qr||v>=128||(A[P]=j,x+=_,v++)}await n.setItem(`${e}:artifacts`,JSON.stringify(A))}catch{}finally{for(let[R,y]of h)r.get(R)===y&&(r.delete(R),i-=y.byteLength)}}}finally{a=!1}})))}}}var Pe=(e,t)=>new b(e,t),yr=()=>performance.now(),my=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function Tv(e){let t=bu.parse(e.scope),n=new xn(e.origin??mr);if(n.username||n.password||n.search||n.hash||n.pathname!=="/"||n.protocol!=="https:"&&!(n.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(n.hostname)))throw Pe("INVALID_URL","Configuration requires a trusted HTTPS origin");let r=new Set([n.origin,...(e.assetOrigins??[]).map(Y=>{let J=new xn(Y);if(J.protocol!=="https:"||J.username||J.password||J.search||J.hash||J.pathname!=="/")throw Pe("INVALID_URL","Invalid configuration asset origin");return J.origin})]),i=e.fetch??globalThis.fetch.bind(globalThis),a=`/api/v1/configuration/${t.environmentId}`,o=`indiana:configuration:1:${n.origin}:${Pt(t)}`,s=py(o,e.storage),c,u=0,l=0,m=!1,f=!1,g=0,d=0,h,R,y,A,x=0,v=new Set,P=new Set,j=new Map,_=new Map,X=0,le=!1;function he(){for(let Y of v)try{Y()}catch{}}function ke(Y){try{e.onError?.(Y)}catch{}}let Se=()=>!f&&!m&&!!c&&yr()<u&&Date.now()<l;function ht(){if(!Se())throw Pe("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Je(Y,J,de){if(!j.has(Y)){for(;j.size&&(j.size>=128||X+de>nn.maxCacheBytes);){let pe=j.entries().next().value;X-=pe[1].byteLength,j.delete(pe[0])}j.set(Y,{text:J,byteLength:de}),X+=de}}function Te(Y,J,de){return Zh(Y,J,{signal:de,error:pe=>Pe("INVALID_RESPONSE",pe==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function tt(Y){let J=new xn(Y,n);if(!r.has(J.origin)||J.username||J.password||J.hash||J.search)throw Pe("INVALID_URL","Configuration artifact origin is not trusted");return J.href}async function No(Y,J,de=!1){let pe=await i(tt(Y),{method:"GET",credentials:"omit",redirect:"error",cache:de?"default":"no-cache",signal:J,headers:{}});if(pe.status===429){let Xe=pe.headers.get("retry-after")??"";x=/^\d+$/.test(Xe)?Number(Xe)*1e3:Math.max(0,Date.parse(Xe)-Date.now())||15e3}if(!pe.ok&&pe.status!==304)throw Pe(`CONFIGURATION_HTTP_${pe.status}`,"Configuration synchronization failed");return pe}function Jr(Y,J,de){let pe=Date.parse(Y.headers.get("x-indiana-config-validated-at")??""),Xe=Date.parse(Y.headers.get("x-indiana-config-valid-until")??""),it=Date.parse(Y.headers.get("date")??""),$e=Y.headers.get("age"),on=$e!==null&&/^\d+(\.\d+)?$/.test($e)?Number($e)*1e3:NaN;if(![pe,Xe,it,on].every(Number.isFinite)||Xe<=pe||Xe-pe>nn.maxControlAgeMs||pe>it+1e3)throw Pe("INVALID_RESPONSE","Configuration freshness evidence is invalid");let qt=Math.min(Xe-pe,de.maxControlAgeSeconds*1e3,nn.maxControlAgeMs)-Math.max(on,it-pe,0)-(yr()-J);if(qt<=0)throw Pe("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return yr()+qt}function pt(){if(clearTimeout(y),clearTimeout(A),f||!v.size)return;Se()&&(A=setTimeout(()=>{Se()?pt():he()},Math.max(1,u-yr())),my(A));let Y=d?Math.min(15e3,1e3*2**Math.min(d-1,4)):Math.min(15e3,(c?.policy.refreshIntervalSeconds??15)*1e3);y=setTimeout(()=>{Qt().catch(ke)},Math.max(x,Y*(.8+Math.random()*.2))),my(y)}async function Qt(){if(f)throw Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(h)return h;let Y=g,J=new AbortController;R=J;let de=(async()=>{if(!le){le=!0;try{let Fo=await s.readManifest();if(Fo&&!c){let zn=Su.parse(JSON.parse(Fo));Pt(zn.scope)===Pt(t)&&(c=zn)}}catch{}}J.signal.throwIfAborted();let $e=c,on=yr(),Lt=await No(a,J.signal);Lt.status===304&&(!$e||!Lt.headers.has("x-indiana-config-validated-at")||!Lt.headers.has("x-indiana-config-valid-until")||!Lt.headers.has("age"))&&(Lt=await No(a,J.signal));let qt=Lt.status===304?$e:Su.parse(JSON.parse(await Te(Lt,nn.maxManifestBytes,J.signal))),{generation:Zr,...Wr}=qt,Ln=Lt.headers.get("etag");if(Pt(qt.scope)!==Pt(t)||Qf(Wr)!==Zr||Ln!==`"${Zr}"`&&Ln!==`W/"${Zr}"`)throw Pe("INVALID_RESPONSE","Configuration scope or content identity changed");if($e&&(qt.revision<$e.revision||qt.revision===$e.revision&&qt.generation!==$e.generation))throw Pe("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[Fo,zn]of Object.entries($e?.funnels??{})){let Sr=qt.funnels[Fo];if(Sr&&(Sr.controlRevision<zn.controlRevision||Sr.evaluationRevision<zn.evaluationRevision||Sr.controlRevision===zn.controlRevision&&Sr.state!==zn.state||Sr.evaluationRevision===zn.evaluationRevision&&Sr.evaluationMode!==zn.evaluationMode))throw Pe("INVALID_RESPONSE","Funnel control revision changed identity")}let xr=Jr(Lt,on,qt.policy);if(J.signal.throwIfAborted(),Y!==g)throw Pe("CONFIGURATION_DISPOSED","Configuration scope changed");return c=qt,u=xr,l=Date.now()+Math.max(0,xr-yr()),m=!1,d=0,x=0,s.writeManifest(Pt(qt)),he(),structuredClone(qt)})(),pe=setTimeout(()=>J.abort(Pe("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),nn.initializationMs),Xe=new Promise(($e,on)=>J.signal.addEventListener("abort",()=>on(J.signal.reason),{once:!0})),it=Promise.race([de,Xe]).catch($e=>{throw d++,($e instanceof jv.ZodError||$e instanceof SyntaxError||$e instanceof b&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes($e.code))&&(u=0,m=!0,he()),$e}).finally(()=>{clearTimeout(pe),h===it&&(h=void 0),pt()});return h=it,it}async function Ar(Y){let J=Y.sha256,de=Wr=>xs(Wr,Y);tt(Y.url);let pe=j.get(J);if(pe){if(pe.byteLength!==Y.byteLength)throw Pe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return j.delete(J),j.set(J,pe),pe.text}let Xe=_.get(J);if(Xe){if(Xe.byteLength!==Y.byteLength)throw Pe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return Xe.promise}let it=new AbortController;P.add(it);let $e=g,on=(async()=>{try{let xr=await s.readArtifact(J);if(xr&&de(xr)){if(it.signal.throwIfAborted(),f||$e!==g)throw Pe("CONFIGURATION_DISPOSED","Configuration scope changed");return Je(J,xr,Y.byteLength),xr}}catch{}it.signal.throwIfAborted();let Wr=await No(Y.url,it.signal,!0),Ln=await Te(Wr,Y.byteLength,it.signal);if(!de(Ln))throw Pe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(f||$e!==g)throw Pe("CONFIGURATION_DISPOSED","Configuration scope changed");return Je(J,Ln,Y.byteLength),s.writeArtifact(J,Ln),Ln})(),Lt=setTimeout(()=>it.abort(Pe("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),nn.initializationMs),qt=new Promise((Wr,Ln)=>it.signal.addEventListener("abort",()=>Ln(it.signal.reason),{once:!0})),Zr=Promise.race([on,qt]).finally(()=>{clearTimeout(Lt),P.delete(it),_.delete(J)});return _.set(J,{promise:Zr,byteLength:Y.byteLength}),Zr}async function br(){return Se()||await Qt(),ht(),c}async function Fi(Y){let J,de=new Promise((pe,Xe)=>{J=setTimeout(()=>Xe(Pe("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),nn.initializationMs)});try{return await Promise.race([Y(),de])}finally{clearTimeout(J)}}function Mi(Y,J){if(ht(),c?.generation!==Y.generation)throw Pe("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(J&&c.funnels[J]?.state!=="active")throw Pe("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function gl(Y){let J=Y.gb.features;if(!J)throw Pe("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let de=Y.artifacts[J];if(de.formatVersion!==1)throw Pe("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let pe=Gc.parse(JSON.parse(await Ar(de)));if(Pt(pe.scope)!==Pt({projectId:t.projectId,environment:t.environment})||pe.generation!==de.generation||pe.remoteFeatures.some(Xe=>Object.hasOwn(pe.features,Xe)))throw Pe("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return Mi(Y),{...pe,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,u-yr())).toISOString()}}async function hl(Y,J){let de=await br(),pe=de.funnels[Y];J&&(!pe||pe.evaluationMode==="local"&&!pe.versions[J])&&(h&&await h,de=await Qt()),Mi(de,Y);let Xe=de.funnels[Y];if(Xe.evaluationMode!=="local")throw Pe("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let it=J??Xe.currentVersionId,$e=Xe.versions[it];if(!$e)throw Pe("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(de.artifacts[$e.artifact].formatVersion!==3)throw Pe("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[on,Lt]=await Promise.all([Ar(de.artifacts[$e.artifact]).then(qt=>Zf(JSON.parse(qt))),Xe.evaluationMode==="local"?gl(de):void 0]);if(Lt&&Pt(Jf(on,Lt))!==Pt($e.dependencies))throw Pe("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return Mi(de,Y),{document:on,growth:Lt,versionId:it,control:structuredClone(Xe),manifest:structuredClone(de)}}async function yl(Y,J){try{return await hl(Y,J)}catch(de){if(!(de instanceof b)||!(de.code==="CONFIGURATION_CHANGED"||de.code==="CONFIGURATION_HTTP_404"&&Se()))throw de;let pe=c?.generation;if(h&&await h,await Qt(),de.code!=="CONFIGURATION_CHANGED"&&c?.generation===pe)throw de;return hl(Y,J)}}function vs(){m=!0,he(),Qt().catch(ke)}let Do=()=>{(typeof document>"u"||document.visibilityState==="visible")&&vs()};function fy(Y){if(f)throw Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return v.add(Y),v.size===1&&(typeof window<"u"&&(window.addEventListener("online",vs),window.addEventListener("focus",Do),document.addEventListener("visibilitychange",Do)),pt()),()=>{v.delete(Y),v.size||(clearTimeout(y),clearTimeout(A),Al())}}function Al(){typeof window<"u"&&(window.removeEventListener("online",vs),window.removeEventListener("focus",Do),document.removeEventListener("visibilitychange",Do))}return{scope:Object.freeze({...t}),refresh:Qt,subscribe:fy,assertFresh:ht,assertFeatures(Y){ht();let J=c.gb.features;if(!J)throw Pe("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(Y!==void 0&&c.artifacts[J].generation!==Y)throw Pe("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return Se()},get snapshot(){return c?structuredClone(c):null},get remainingMs(){return Se()?Math.max(0,u-yr()):0},async features(){return Fi(async()=>gl(await br()))},pageExperiments:()=>Fi(async()=>{let Y=await br(),J=Y.gb.pageExperiments;if(!J)throw Pe("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let de=Y.artifacts[J];if(de.formatVersion!==1)throw Pe("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let pe=ih.parse(JSON.parse(await Ar(de)));if(pe.environmentId!==t.environmentId||pe.generation!==de.generation)throw Pe("INVALID_RESPONSE","Page experiment scope or generation changed");return Mi(Y),pe}),funnel:(Y,J)=>Fi(()=>yl(Y,J)),paywall:(Y,J)=>Fi(async()=>{let de=await br(),pe=de.paywalls?.[Y];if(!pe||!J&&pe.state!=="published")throw Pe("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let Xe=J??pe.currentVersionId,it=pe.versions[Xe],$e=it&&de.artifacts[it.artifact];if(!$e||$e.kind!=="paywall"||$e.formatVersion!==1)throw Pe("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let on=is.parse(JSON.parse(await Ar($e)));return Mi(de),{document:on,versionId:Xe,version:it.version,control:structuredClone(pe),manifest:structuredClone(de)}}),async localFunnel(Y,J){let de=await Fi(()=>yl(Y,J));if(!de.growth)throw Pe("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:pe,remoteFeatures:Xe,...it}=de.growth;return nh({scope:{projectId:t.projectId,environment:t.environment},funnelId:Y,versionId:de.versionId,evaluationMode:"local",evaluationRevision:de.control.evaluationRevision,document:de.document,payload:it})},assertFunnel(Y,J,de){ht();let pe=c.funnels[Y];if(!pe||pe.state!=="active")throw Pe("FUNNEL_STOPPED","Funnel is paused or unavailable");if(pe.evaluationMode!=="local")throw Pe("EVALUATION_MODE","This Funnel now executes at Longplay");if(J!==void 0&&pe.controlRevision!==J)throw Pe("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(de!==void 0&&!pe.versions[de])throw Pe("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!f){f=!0,g++,u=0,R?.abort(Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(y),clearTimeout(A),Al(),he(),v.clear();for(let Y of P)Y.abort(Pe("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));j.clear(),X=0}}}}async function Nv(e){e={...e};let t=e.configuration;if(!t)throw new b("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let n={projectId:t.scope.projectId,environment:t.scope.environment};if(e.scope&&Pt(n)!==Pt(e.scope))throw new b("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await t.funnel(e.funnelId)).control.evaluationMode!=="local")throw new b("EVALUATION_MODE","This Funnel uses Remote evaluation");let i=Di.test(e.credential);if(i?!e.customerId:e.customerId!==void 0)throw new b("INVALID_REQUEST","Only Server-Key starts name their Customer");let a=bs({...e,scope:n,apiKey:e.credential}),o=s=>{let c=hr({...e,scope:n,runToken:s,...i?{serverKey:e.credential}:{}});return i||c.identify(e.credential),c};return{async start(s){let c=await a.start({...s,funnelId:e.funnelId,...i?{customer:{type:"id",value:e.customerId}}:{}}),u=o(c.runToken),l=await u.get();return{...c,...l,controller:u}},async restore(s){let c=o(s),u=await c.get();if(u.run.source.id!==e.funnelId)throw c.reset(),new b("SCOPE_MISMATCH","Run belongs to another Funnel");return{...u,runToken:s,controller:c}}}}function fl(e,...t){try{Promise.resolve(e?.(...t)).catch(()=>{})}catch{}}function Dv(e){if(!e.scope)throw new b("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(e.session!==void 0)throw new b("INVALID_CONFIGURATION","The merchant process adapter owns the session");let t=null,n,r=0,i=new Set,a=new Map,o=new Map;async function s(f){let g,d=new Promise((h,R)=>{g=setTimeout(()=>R(new b("TIMEOUT","Process bridge request timed out")),e.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(f),d])}finally{clearTimeout(g)}}function c(f){throw f instanceof b&&(f.status===401||f.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear()),f}function u(f,g){if(g!==r)throw new b("IDENTITY_CHANGED","Process was detached during a request");let d=Bu.parse(f);if(d.scope.projectId!==e.scope.projectId||d.scope.environment!==e.scope.environment)throw new b("SCOPE_MISMATCH","Process response belongs to another App/environment");if(t&&(t.run.id!==d.run.id||t.run.source.versionId!==d.run.source.versionId||t.run.source.id!==d.run.source.id||t.run.runExpiresAt!==d.run.runExpiresAt||t.run.identity.startedAs!==d.run.identity.startedAs||t.run.identity.participantId!==d.run.identity.participantId||t.run.identity.binding&&d.run.identity.binding&&t.run.identity.binding.id!==d.run.identity.binding.id))throw new b("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!t||d.run.revision>=t.run.revision){if(t?.run.identity.binding&&!d.run.identity.binding)throw new b("INVALID_RESPONSE","The process lost its Customer binding");t=d;for(let j of i)fl(j,d.run);d.run.instruction?.type==="authentication_required"&&fl(e.onAuthenticationRequired,d.run)}d.settlement?.accepted!==void 0&&o.set(d.settlement.requestId,d.settlement.accepted);let{identity:h,instruction:R,...y}=d.run,{contract:A,settlement:x,...v}=d,P=x&&(({accepted:j,..._})=>_)(x);return{...v,run:{...y,authenticated:h.binding!==null,instruction:R?.type==="authentication_required"?null:R},...P?{settlement:P}:{}}}let l=f=>(a.has(f)||a.set(f,t?.run.identity.binding?.id??null),a.get(f));async function m(f){let g=r,d=t?.run.identity.binding?.id??null,h=y=>{if(d!==(t?.run.identity.binding?.id??null))throw y;return c(y)};if(f.operation==="page_experiments"){if(!e.adapter.pageExperiments)throw new b("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return s(()=>e.adapter.pageExperiments(f.release,f.usedReceiptIds)).catch(h)}let R;if(f.operation==="get"){let{operation:y,customerToken:A,...x}=f;R=await s(()=>e.adapter.get({...x,...x.settlementRequestId?{settlementBindingId:l(x.settlementRequestId)}:{}})).catch(h)}else if(f.operation==="review")R=await s(()=>e.adapter.review(f.receiptId)).catch(h);else{if(f.operation==="start")throw new b("INVALID_REQUEST","Use process.open for entry");{let{customerToken:y,...A}=f;R=await s(()=>e.adapter.command(A,l(A.requestId))).catch(h)}}return u(R,g)}return{get view(){return t?.run??null},get controller(){return n},async open(f){let g=r,d=await s(()=>e.adapter.open(f)).catch(c);if(u(d,g),!n){n=hr({...e,runToken:d.runToken,process:{request:m,binding:l,restore(y){for(let[A,x]of Object.entries(y))a.set(A,x)}}});let h=n,R=h.submit;h.submit=async y=>{try{return await R(y)}catch(A){if(!(A instanceof b)||A.reason!=="IDENTITY_CONTEXT_CHANGED"||y.operation!=="submit"||y.input.type!=="screen"||a.get(y.requestId)!==null)throw A;await h.settle?.(y.requestId),await h.get();let x=h.view;if(o.get(y.requestId)!==!1||!x||x.id!==t?.run.id||x.nodeId!==y.nodeId||x.visit!==y.visit||!t?.run.identity.binding)throw A;return R({...y,requestId:crypto.randomUUID(),revision:x.revision})}}}await n.get();for(let h of n.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(t?.run.identity.binding?.id??null)&&await n.settle?.(h.requestId);return{run:t.run,controller:n}},async syncIdentity(){let f=r;u(await s(()=>e.adapter.syncIdentity()).catch(c),f),await n?.get();for(let g of n?.pendingCommands??[])a.has(g.requestId)&&a.get(g.requestId)!==(t?.run.identity.binding?.id??null)&&await n?.settle?.(g.requestId);return t.run},async detach(){r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear(),await s(()=>e.adapter.detach())},forProcess(f){if(!t?.run.identity.binding)throw new b("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:t.run.id,bindingId:t.run.identity.binding.id,receiptId:f}},subscribe(f){return i.add(f),()=>{i.delete(f)}},destroy(){r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear(),i.clear()}}}export{b as LongplayError,Tv as createConfigurationSync,dl as createFeatureClient,Dv as createFunnelProcess,Nv as createLocalFunnelClient,_v as createLongplayReactNative};