@tinkerlandai/longplay-react-native 0.10.11 → 0.10.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs 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 Se=N.z.json().superRefine((e,t)=>{let n=0;function r(i,a){if(++n>1e4||a>20){t.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof i=="string"&&(i.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(i))&&t.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(i))i.forEach(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))(o.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(o)||["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved JSON property"}),r(s,a+1)}r(e,0),new TextEncoder().encode(JSON.stringify(e)).byteLength>65536&&t.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),Ot=N.z.record(N.z.string().min(1).max(128),Se).superRefine((e,t)=>{(!Se.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"})}),Iy=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"]),Jt=Ot.superRefine((e,t)=>{function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,a]of Object.entries(r)){if(i==="$savedGroup"&&!N.z.strictObject({id:N.z.uuid(),attributeKey:N.z.string().min(1).max(128).optional()}).safeParse(a).success&&t.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!i.startsWith("$")&&i.split(".").some(o=>["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved attribute path"}),i.startsWith("$")&&!Iy.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)}),vy=N.z.discriminatedUnion("type",[N.z.strictObject({type:N.z.literal("condition"),condition:Jt}),N.z.strictObject({type:N.z.literal("list"),attributeKey:N.z.string().min(1).max(128),values:N.z.array(N.z.union([N.z.string(),N.z.number().finite()])).max(1e5)})]).refine(e=>e.type!=="list"||new TextEncoder().encode(JSON.stringify(e.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function Un(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 wy=N.z.record(N.z.uuid(),vy).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"&&Un(o.condition).forEach(i),n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),Xs=N.z.tuple([N.z.number().min(0).max(1),N.z.number().min(0).max(1)]).refine(([e,t])=>e<=t),Cd=N.z.strictObject({attribute:N.z.string().optional(),seed:N.z.string().min(1),hashVersion:N.z.literal(2),ranges:N.z.array(Xs).min(1).max(100)}),Oy=N.z.strictObject({id:N.z.string().min(1).max(128),condition:Jt,gate:N.z.boolean().optional()}),Ys={id:N.z.string().max(128).optional(),condition:Jt.optional(),parentConditions:N.z.array(Oy).max(50).optional(),filters:N.z.array(Cd).max(20).optional()},Py=N.z.union([N.z.strictObject({...Ys}),N.z.strictObject({...Ys,force:Se,coverage:N.z.number().min(0).max(1).optional(),range:Xs.optional(),seed:N.z.string().min(1).optional(),hashAttribute:N.z.string().optional(),hashVersion:N.z.literal(2).optional()}),N.z.strictObject({...Ys,type:N.z.literal("experiment-ref"),experimentId:N.z.uuid(),values:N.z.record(N.z.string().min(1),Se),meta:N.z.record(N.z.string().min(1),N.z.strictObject({passthrough:N.z.boolean()})).optional()})]),Cy=N.z.strictObject({defaultValue:Se,rules:N.z.array(Py).max(100)}),Cw=N.z.record(N.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Cy).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)}),_y=N.z.strictObject({name:N.z.string().max(80),reason:N.z.string().max(500),dateStarted:N.z.iso.datetime({offset:!0}),dateEnded:N.z.iso.datetime({offset:!0}).nullable(),coverage:N.z.number().min(0).max(1),variationWeights:N.z.array(N.z.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:Jt,savedGroups:N.z.array(N.z.strictObject({match:N.z.enum(["any","all","none"]),ids:N.z.array(N.z.uuid()).min(1)})).max(50),namespace:N.z.strictObject({id:N.z.uuid(),ranges:N.z.array(Xs).min(1)}).nullable(),seed:N.z.string().min(1).max(128)}),Ey=N.z.strictObject({key:N.z.string().min(1).max(128),name:N.z.string().min(1).max(80),hypothesis:N.z.string().max(2e3),status:N.z.enum(["draft","running","stopped"]),hashAttribute:N.z.string().min(1).max(128),fallbackAttribute:N.z.string().max(128).nullable(),hashVersion:N.z.literal(2),disableStickyBucketing:N.z.boolean(),bucketVersion:N.z.number().int().min(0).max(1e3),minBucketVersion:N.z.number().int().min(0).max(1e3),variations:N.z.array(N.z.strictObject({id:N.z.string().min(1),key:N.z.string().min(1),name:N.z.string().max(80),description:N.z.string().max(500)})).min(2).max(20),phases:N.z.array(_y).min(1).max(100),releasedVariationId:N.z.string().nullable(),excludeFromPayload:N.z.boolean(),statusSchedule:N.z.strictObject({startAt:N.z.iso.datetime({offset:!0}).nullable(),stopAt:N.z.iso.datetime({offset:!0}).nullable(),stopAfter:N.z.strictObject({value:N.z.number().int().positive().max(36500),unit:N.z.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((e,t)=>{(e.minBucketVersion>e.bucketVersion||e.statusSchedule?.stopAt&&e.statusSchedule?.stopAfter||e.phases.some((n,r)=>{if(r===0)return!1;let i=e.phases[r-1];return!i?.dateEnded||Date.parse(n.dateStarted)<Date.parse(i.dateStarted)||Date.parse(i.dateEnded)>Date.parse(n.dateStarted)})||new Set(e.variations.map(n=>n.key)).size!==e.variations.length||new Set(e.variations.map(n=>n.id)).size!==e.variations.length||e.releasedVariationId!==null&&!e.variations.some(n=>n.id===e.releasedVariationId)||e.statusSchedule?.startAt&&e.statusSchedule?.stopAt&&Date.parse(e.statusSchedule.startAt)>=Date.parse(e.statusSchedule.stopAt)||e.phases.some(n=>n.dateEnded&&Date.parse(n.dateStarted)>=Date.parse(n.dateEnded)||n.namespace?.ranges.some(([r,i],a,o)=>r>=i||o.some(([s,c],u)=>u!==a&&r<c&&s<i)))||e.phases.some(n=>n.variationWeights.length!==e.variations.length))&&t.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});var Ry=Ey.safeExtend({filters:N.z.array(Cd).optional()}),ky=N.z.strictObject({experiments:N.z.record(N.z.uuid(),Ry),savedGroups:wy}),Vi=N.z.strictObject({attributeName:N.z.string(),attributeValue:N.z.string(),assignments:N.z.record(N.z.string(),N.z.string())}),_w=N.z.strictObject({snapshot:ky,attributes:Ot,results:Ot,stickyBucketAssignmentDocs:N.z.record(N.z.string(),Vi)}),Ew=N.z.strictObject({variantKey:N.z.string().nullable(),bucketVersion:N.z.number().int().min(0),source:N.z.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:N.z.number().min(0).max(1).optional(),stickyBucketUsed:N.z.boolean().optional(),hashUsed:N.z.boolean().optional()});function Yn(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 jy=_t.z.enum(["active","inactive"]),Ty=_t.z.preprocess((e,t)=>{let n=0;function r(i,a){if(!(++n>1e4||a>20)){if(Array.isArray(i))i.forEach(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))["__proto__","constructor","prototype"].includes(o)&&t.addIssue({code:"custom",message:"Reserved merchandise attribute"}),r(s,a+1)}}return r(e,0),e},Ot),Ny=_t.z.strictObject({id:_t.z.string().trim().min(1).max(255),name:_t.z.string().trim().min(1).max(255),status:jy,metadata:Ty}),Nw=Ny.extend({internal_id:_t.z.uuid(),project_id:_t.z.uuid(),environment_id:_t.z.uuid(),created_at:_t.z.iso.datetime({offset:!0}),updated_at:_t.z.iso.datetime({offset:!0})}),Ed=_t.z.union([_t.z.strictObject({id:_t.z.string().trim().min(1).max(255)}),_t.z.strictObject({internalId:_t.z.uuid()})]),Dw=_t.z.enum(["customer","merchandise","context"]),Fw=_t.z.enum(["system","stored","request"]),Mw=_t.z.enum(["customer","merchandise","mixed"]),_d=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function ec(e,t={},n=new Set){if(Yn(e).some(_d))return!0;for(let r of Un(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&_d(i.attributeKey)||i?.type==="condition"&&ec(i.condition,t,n))return!0}return!1}var Rd=require("zod"),Dy=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,xn=Rd.z.string().max(16).regex(Dy,"\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 zw=Y.z.enum(["draft","active","paused","archived"]),Xn=Y.z.discriminatedUnion("type",[Y.z.object({type:Y.z.literal("percent"),percentOff:Y.z.number().min(1).max(100).multipleOf(.01)}).strict(),Y.z.object({type:Y.z.literal("amount"),amountOffCents:Y.z.number().int().min(1).max(1e8),currency:be}).strict()]),on=Y.z.discriminatedUnion("type",[Y.z.object({type:Y.z.literal("once")}).strict(),Y.z.object({type:Y.z.literal("repeating"),months:Y.z.number().int().min(1).max(36)}).strict(),Y.z.object({type:Y.z.literal("forever")}).strict()]),kd=[Y.z.object({type:Y.z.literal("all")}).strict(),Y.z.object({type:Y.z.literal("plans"),planIds:Y.z.array(Y.z.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],Fy=Y.z.discriminatedUnion("type",[...kd,Y.z.strictObject({type:Y.z.literal("merchandise"),scope:Y.z.discriminatedUnion("type",[Y.z.strictObject({type:Y.z.literal("all")}),Y.z.strictObject({type:Y.z.literal("selected"),merchandiseIds:Y.z.array(Y.z.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),Y.z.strictObject({type:Y.z.literal("condition"),condition:Jt})])})]),tc=Y.z.discriminatedUnion("type",[...kd,Y.z.strictObject({type:Y.z.literal("merchandise"),scope:Y.z.strictObject({type:Y.z.enum(["all","selected","condition"])})})]),My=Y.z.strictObject({firstPurchaseOnly:Y.z.boolean(),condition:Jt}),$w=Y.z.object({name:Y.z.string().trim().min(1).max(80),description:Y.z.string().max(500),discount:Xn,duration:on,appliesTo:Fy,eligibility:My,selfClaimEnabled:Y.z.boolean().default(!1),startsAt:Y.z.iso.datetime().nullable(),endsAt:Y.z.iso.datetime().nullable(),totalLimit:Y.z.number().int().min(1).max(1e6).nullable(),perCustomerLimit:Y.z.number().int().min(1).max(10),grantWindowHours:Y.z.number().int().min(1).max(2160)}).strict().refine(e=>!e.startsAt||!e.endsAt||Date.parse(e.endsAt)>Date.parse(e.startsAt),{message:"\u7ED3\u675F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u5F00\u59CB\u65F6\u95F4",path:["endsAt"]}).refine(e=>!ec(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"]}),Gw=Y.z.object({code:Y.z.string().trim().transform(e=>e.toUpperCase()).pipe(Y.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/,"\u4F18\u60E0\u7801\u53EA\u80FD\u7528 3\u201332 \u4F4D\u5B57\u6BCD\u3001\u6570\u5B57\u3001- \u548C _\uFF0C\u4EE5\u5B57\u6BCD\u6216\u6570\u5B57\u5F00\u5934")),maxRedemptions:Y.z.number().int().min(1).max(1e6).nullable(),expiresAt:Y.z.iso.datetime().nullable(),firstPurchaseOnly:Y.z.boolean(),minimumAmountCents:Y.z.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:be.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var Li=Y.z.object({id:Y.z.uuid(),couponId:Y.z.uuid(),status:Y.z.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:Y.z.iso.datetime(),expiresAt:Y.z.iso.datetime(),coupon:Y.z.object({name:Y.z.string(),discount:Xn,duration:on,appliesTo:tc}).strict()}).strict(),jd=Y.z.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var Md=x.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),nc=x.z.string().regex(/^(0|[1-9]\d{0,14})$/),ri=x.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),qy=x.z.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),Ui=qy,zn=Ae.refine(e=>/[1-9]/.test(e)),zt=x.z.iso.datetime({offset:!0}),aa=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"))},By=x.z.array(x.z.object({upTo:zn.nullable(),unitAmountMinor:Md,flatAmountMinor:x.z.number().int().min(0).max(1e8).optional()}).strict()).min(1).max(12).refine(e=>{try{return e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let r=e[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&aa(t.upTo)>aa(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),Vy=x.z.discriminatedUnion("kind",[x.z.object({kind:x.z.literal("flat"),units:zn,unitAmountMinor:Md}).strict(),x.z.object({kind:x.z.enum(["graduated","volume"]),units:zn,tiers:By}).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"),Ly=x.z.strictObject({interval:x.z.enum(["month","year"]),count:x.z.number().int().min(1).max(12),anchor:x.z.enum(["membership","calendar"])}),zi=x.z.object({currency:be,pricing:Vy,billingCycle:Ly.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var Td={requestId:x.z.uuid(),productVersionId:x.z.uuid(),internal_feature_id:x.z.uuid(),currency:be},qd=x.z.strictObject({interval:x.z.enum(["hour","day","week","month"]),intervalCount:x.z.number().int().min(1).max(12),limit:x.z.number().int().min(1).max(1e6)}),Bd=x.z.discriminatedUnion("kind",[x.z.object({...Td,kind:x.z.literal("auto_topup"),threshold:Ho,quantity:zn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:qd.optional()}).strict(),x.z.object({...Td,kind:x.z.literal("postpaid"),maxAmountMinorPerPeriod:Ui,maxOutstandingMinor:Ui}).strict()]),Nd={productVersionId:x.z.uuid(),internal_feature_id:x.z.uuid(),currency:be},Vd=x.z.discriminatedUnion("kind",[x.z.object({...Nd,kind:x.z.literal("auto_topup"),threshold:Ho,quantity:zn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:qd.optional(),purchaseAmountMinor:Ui,purchaseUnits:zn}).strict(),x.z.object({...Nd,kind:x.z.literal("postpaid"),maxAmountMinorPerPeriod:Ui,maxOutstandingMinor:Ui,cashPrice:zi}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),sa=x.z.object({id:x.z.uuid(),terms:Vd,status:x.z.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"),Ld=x.z.object({authorizationId:x.z.uuid(),terms:Vd,setupUrl:x.z.url().nullable()}).strict(),Ud=x.z.object({authorizationId:x.z.uuid(),accepted:x.z.literal(!0)}).strict(),zd=x.z.object({authorizationId:x.z.uuid(),requestId:x.z.uuid()}).strict(),$d=x.z.object({internal_feature_id:x.z.uuid(),entityId:x.z.uuid().nullable(),interval:x.z.enum(["day","week","month","year"]),anchor:x.z.enum(["billing_cycle","utc"]).optional(),basis:x.z.enum(["usage","credits"]),filter:wt.optional(),limit:Ae.nullable(),thresholds:x.z.array(x.z.number().positive().max(1)).max(8),includedThresholds:x.z.array(x.z.number().positive().max(1)).max(8).optional(),absoluteThresholds:x.z.array(zn).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&&aa(t)>aa(i)}),"Notification thresholds must increase"),Uy=$d.safeExtend({requestId:x.z.uuid()}),Dd={control:x.z.literal("overage"),requestId:x.z.uuid(),internal_feature_id:x.z.uuid(),entityId:x.z.uuid().nullable()},zy=x.z.discriminatedUnion("action",[x.z.strictObject({...Dd,action:x.z.literal("set"),allowed:x.z.boolean().nullable(),overageLimit:Ae.nullable(),skipOverageBilling:x.z.boolean()}),x.z.strictObject({...Dd,action:x.z.literal("remove")})]),Gd=x.z.union([Uy,zy]),$y=x.z.strictObject({internal_feature_id:x.z.uuid(),entityId:x.z.uuid().nullable(),allowed:x.z.boolean().nullable(),overageLimit:Ae.nullable(),skipOverageBilling:x.z.boolean(),interval:x.z.enum(["day","week","month","year"]),startsAt:zt,endsAt:zt,used:x.z.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:x.z.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:x.z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),Gy=x.z.object({internal_feature_id:x.z.uuid(),entityId:x.z.uuid().nullable(),interval:x.z.enum(["day","week","month","year"]),anchor:x.z.enum(["billing_cycle","utc"]).optional(),basis:x.z.enum(["usage","credits"]),filter:wt.optional(),startsAt:zt,endsAt:zt,used:Qt,reserved:Qt,limit:Ae.nullable(),thresholds:x.z.array(x.z.number().positive().max(1)).max(8),notifiedThresholds:x.z.array(x.z.number().positive().max(1)).max(1024),includedThresholds:x.z.array(x.z.number().positive().max(1)).max(8).optional(),includedAllowance:x.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:x.z.array(x.z.number().positive().max(1)).max(1024).optional(),absoluteThresholds:x.z.array(zn).max(8).optional(),notifiedAbsoluteThresholds:x.z.array(zn).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||Ae.safeParse(e.used).success&&Ae.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),Ky=x.z.object({authorizationId:x.z.uuid(),status:x.z.enum(["idle","pending","blocked"]),taskId:x.z.uuid().nullable(),invoiceId:x.z.uuid().nullable(),hostedInvoiceUrl:x.z.url().nullable(),purchaseCount:x.z.number().int().nonnegative(),purchaseWindowEndsAt:zt.nullable(),attemptCount:x.z.number().int().nonnegative(),failedAttemptCount:x.z.number().int().nonnegative(),suspendedAt:zt.nullable(),nextAttemptAt:zt.nullable(),failureReason:x.z.string().min(1).max(240).nullable()}).strict(),Kd=x.z.object({internal_feature_id:x.z.uuid().optional(),entityId:x.z.uuid().optional()}).strict(),rc=x.z.object({authorizations:x.z.array(sa).max(100),limits:x.z.array($d).max(100),overages:x.z.array($y).max(100).optional(),windows:x.z.array(Gy).max(200),autoTopups:x.z.array(Ky).max(100),limited:x.z.boolean()}).strict(),Hy=x.z.object({id:x.z.uuid(),internal_feature_id:x.z.uuid(),productVersionId:x.z.uuid(),authorizationId:x.z.uuid(),entityId:x.z.uuid().nullable(),units:Ae,amountMinor:ri,cashPrice:zi}).strict(),$i=x.z.object({id:x.z.uuid(),sourceKind:x.z.enum(["product","usage","manual"]),providerInvoiceId:x.z.string().min(1).max(240).nullable(),status:x.z.enum(["accruing","open","pending","paid","failed","void"]),currency:be,startsAt:zt.nullable(),endsAt:zt.nullable(),amountMinor:x.z.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:x.z.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:nc,paidAmountMinor:nc,refundedAmountMinor:nc,createdAt:zt,hostedInvoiceUrl:x.z.url().nullable(),adjustment:x.z.object({originalInvoiceId:x.z.uuid(),amountMinor:x.z.string().regex(/^-?(0|[1-9]\d{0,8})$/).refine(e=>e!=="-0"&&/^-?(0|[1-9]\d{0,8})$/.test(e)&&BigInt(e)>=-200000000n&&BigInt(e)<=200000000n,"Invoice adjustment exceeds the bounded minor amount"),acceptedAt:zt.nullable(),reason:x.z.string().min(1).max(500).optional()}).strict().nullable(),lines:x.z.array(Hy).max(100),linesLimited:x.z.boolean()}).strict(),Hd=x.z.object({invoiceId:x.z.uuid(),accepted:x.z.literal(!0)}).strict(),Qd=x.z.strictObject({requestId:x.z.uuid(),originalInvoiceId:x.z.uuid(),amountMinor:x.z.string().regex(/^[1-9]\d{0,8}$/).refine(e=>/^[1-9]\d{0,8}$/.test(e)&&BigInt(e)<=200000000n,"Supplemental amount exceeds the bounded minor amount"),reason:x.z.string().trim().min(1).max(500)}),Jd=x.z.object({after:x.z.uuid().nullable(),limit:x.z.number().int().min(1).max(100)}).strict(),Zd=x.z.object({rows:x.z.array($i).max(100),nextCursor:x.z.uuid().nullable()}).strict(),Fd=x.z.strictObject({id:x.z.string(),coupon:x.z.string(),start:x.z.number().nonnegative(),end:x.z.number().nullable()}),Qy=x.z.strictObject({subscriptionId:x.z.string(),customerId:x.z.string(),accountId:x.z.string(),sourceItems:x.z.array(x.z.strictObject({id:x.z.string(),price_id:x.z.string(),quantity:x.z.number().int(),discounts:x.z.array(Fd).optional()})).max(100),items:x.z.array(x.z.strictObject({id:x.z.string(),price:x.z.string(),quantity:x.z.number().int(),discounts:x.z.array(x.z.strictObject({coupon:x.z.string().optional(),terms:x.z.strictObject({id:x.z.string(),name:x.z.string().optional(),percent_off:x.z.number().optional(),amount_off:x.z.number().optional(),currency:x.z.string().optional(),duration:x.z.enum(["once","forever","repeating"]),duration_in_months:x.z.number().optional()}).optional(),discount:x.z.string().optional(),receipt:Fd.optional()})).max(20)})).max(100)}),Wd=x.z.strictObject({membershipId:x.z.uuid(),requestId:x.z.uuid(),grantIds:x.z.array(x.z.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),Yd=x.z.strictObject({membershipId:x.z.uuid(),operationId:x.z.uuid(),status:x.z.enum(["pending","effective"]),execution:Qy.nullable(),grants:x.z.array(x.z.strictObject({id:x.z.uuid(),couponId:x.z.uuid(),name:x.z.string(),discount:Xn,duration:on,startedAt:zt.nullable()})).max(20)});var ii=require("zod");var Xd=ii.z.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),ep=ii.z.number().int().min(1).max(1e3),ca=ii.z.object({cap:Ae.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:ii.z.number().positive().max(1e4).nullable(),cycles:ii.z.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");var $n=require("zod");var tp=$n.z.strictObject({itemKey:$n.z.string().regex(/^paid:feature:[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),internal_feature_id:$n.z.uuid(),includedAmount:$n.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:$n.z.number().int().min(0).max(1e4),terms:Jo,pricing:Mi.optional(),unitAmountMinor:$n.z.number().int().min(0).max(1e8),productId:$n.z.string().min(1).max(255).nullable(),priceId:$n.z.string().min(1).max(255).nullable()}).superRefine((e,t)=>{(e.quantity<e.terms.minimumQuantity||e.quantity>e.terms.maximumQuantity||e.productId===null!=(e.priceId===null)||e.quantity>0&&(e.pricing||e.unitAmountMinor>0)&&e.priceId===null)&&t.addIssue({code:"custom",message:"Purchased quantities need their published bounds and immutable price binding"});try{Kl(e.includedAmount,e.terms.units,e.quantity),Qo({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{t.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});var X=require("zod");var _r=Ae.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Gi=X.z.string().min(1).max(120),ua=X.z.enum(["cap","overflow"]),an=(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"))},Ki=e=>{try{return e()}catch{return!1}},Hi=X.z.discriminatedUnion("operation",[X.z.object({operation:X.z.literal("quote"),overageBehavior:ua.optional(),internal_feature_id:X.z.uuid(),entityId:X.z.uuid().optional(),quantity:_r,properties:wt}).strict(),X.z.object({operation:X.z.literal("consume"),overageBehavior:ua.optional(),occurredAt:X.z.iso.datetime({offset:!0}).optional(),internal_feature_id:X.z.uuid(),entityId:X.z.uuid().optional(),quantity:Ae,properties:wt,idempotencyKey:Gi}).strict(),X.z.object({operation:X.z.literal("reserve"),occurredAt:X.z.iso.datetime({offset:!0}).optional(),internal_feature_id:X.z.uuid(),entityId:X.z.uuid().optional(),quantity:_r,properties:wt,idempotencyKey:Gi,expiresInSeconds:X.z.number().int().min(1).max(86400)}).strict(),X.z.object({operation:X.z.literal("confirm"),operationId:X.z.uuid(),quantity:_r,properties:wt.optional(),idempotencyKey:Gi}).strict(),X.z.object({operation:X.z.literal("refund"),operationId:X.z.uuid(),quantity:_r,idempotencyKey:Gi}).strict(),X.z.object({operation:X.z.literal("release"),operationId:X.z.uuid(),idempotencyKey:Gi}).strict()]),ic=X.z.object({internal_credit_feature_id:X.z.uuid().nullable(),internal_metered_feature_id:X.z.uuid(),dimension:X.z.string().min(1).max(64),counterKey:X.z.string().min(1).max(240),cycleStart:X.z.iso.datetime({offset:!0}),unitCost:Ae,units:_r,amount:Qt,tier:X.z.number().int().min(1).max(12).nullable()}).strict(),Er=X.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function np(e,t){let n=e.reduce((r,i)=>r+an(i.units,12),0n)-an(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var rp=X.z.discriminatedUnion("funding",[X.z.strictObject({funding:X.z.literal("balance"),sourceId:X.z.uuid(),rolloverId:X.z.uuid().nullable(),units:Er.refine(e=>/[1-9]/.test(e)),amount:Qt}),X.z.strictObject({funding:X.z.literal("unbilled"),units:Er.refine(e=>/[1-9]/.test(e))}),X.z.object({funding:X.z.literal("prepaid"),sourceId:X.z.uuid(),units:_r,amount:Qt,pricing:X.z.array(ic).min(1).max(12)}).strict().refine(e=>Ki(()=>e.pricing.reduce((t,n)=>t+an(n.units,6),0n)===an(e.units,6)&&e.pricing.reduce((t,n)=>t+an(n.amount,12),0n)===an(e.amount,12)&&e.pricing.every(t=>an(t.unitCost,6)*an(t.units,6)===an(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),X.z.object({funding:X.z.literal("postpaid"),invoiceLineId:X.z.uuid().nullable(),units:_r,authorizationId:X.z.uuid()}).strict()]),la=X.z.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),ip=X.z.object({allowed:X.z.boolean(),internal_feature_id:X.z.uuid(),quantity:Ae,requestedQuantity:Ae.optional(),overageBehavior:ua.optional(),reason:la.nullable(),allocations:X.z.array(rp).max(500)}).strict().refine(e=>Ki(()=>e.allowed?e.reason===null&&np(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>Ki(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&an(e.requestedQuantity,6)>=an(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Qi=X.z.object({id:X.z.uuid(),internal_feature_id:X.z.uuid(),kind:X.z.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:X.z.uuid().nullable(),quantity:Ae,requestedQuantity:Ae.optional(),overageBehavior:ua.optional(),accepted:X.z.boolean(),reason:X.z.enum([...la.options,"expired"]).nullable(),createdAt:X.z.iso.datetime({offset:!0}),reservationStatus:X.z.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:X.z.iso.datetime({offset:!0}).nullable(),allocations:X.z.array(rp).max(500)}).strict().refine(e=>Ki(()=>e.accepted?e.reason===null&&np(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>Ki(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&an(e.requestedQuantity,6)>=an(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");var ke=require("zod");var Rr=ke.z.iso.datetime({offset:!0}),op=Ae.refine(e=>/[1-9]/.test(e)),ap=ke.z.strictObject({interval:Xd.exclude(["lifetime"]),count:ep}),Jy=ke.z.strictObject({action:ke.z.literal("create"),requestId:ke.z.uuid(),internal_feature_id:ke.z.uuid(),entityId:ke.z.uuid().nullable(),amount:op.nullable(),expiresAt:Rr.nullable(),reset:ap.nullable(),rollover:ca.nullable(),nextResetAt:Rr.nullable()}).refine(e=>e.amount!==null||e.reset===null&&e.rollover===null,"Unlimited grants cannot reset or roll over").refine(e=>!e.rollover||e.reset!==null,"Rollover requires a recurring grant").refine(e=>e.nextResetAt===null||e.reset!==null&&(e.expiresAt===null||Date.parse(e.nextResetAt)<Date.parse(e.expiresAt)),"The first reset needs a reset interval and must precede expiry"),sp=ke.z.discriminatedUnion("action",[Jy,ke.z.strictObject({action:ke.z.literal("update"),requestId:ke.z.uuid(),grantId:ke.z.uuid(),revision:ke.z.number().int().nonnegative(),amount:op.nullable(),expiresAt:Rr.nullable(),rollover:ca.nullable(),nextResetAt:Rr.nullable()}),ke.z.strictObject({action:ke.z.enum(["add","subtract","set_remaining"]),requestId:ke.z.uuid(),grantId:ke.z.uuid(),revision:ke.z.number().int().nonnegative(),amount:Ae}),ke.z.strictObject({action:ke.z.literal("revoke"),requestId:ke.z.uuid(),grantId:ke.z.uuid(),revision:ke.z.number().int().nonnegative()})]),oc=ke.z.strictObject({id:ke.z.uuid(),internal_feature_id:ke.z.uuid(),entityId:ke.z.uuid().nullable(),amount:Ae.nullable(),reset:ap.nullable(),rollover:ca.nullable(),nextResetAt:Rr.nullable(),startsAt:Rr,expiresAt:Rr.nullable(),revision:ke.z.number().int().nonnegative(),revoked:ke.z.boolean(),available:Qt,held:Qt,spent:Qt}),cp=ke.z.strictObject({customerId:ke.z.uuid(),after:ke.z.uuid().nullable(),limit:ke.z.number().int().min(1).max(100)}),up=ke.z.strictObject({rows:ke.z.array(oc).max(100),nextCursor:ke.z.uuid().nullable()});var ne=require("zod");var En=ne.z.iso.datetime({offset:!0}),lp=ne.z.strictObject({invoiceId:ne.z.uuid(),after:ne.z.string().min(1).max(180).nullable(),limit:ne.z.number().int().min(1).max(100)}),Zy=ne.z.strictObject({kind:ne.z.literal("product"),key:ne.z.string(),productVersionId:ne.z.uuid(),productName:ne.z.string(),itemKey:ne.z.string(),entityId:ne.z.uuid().nullable(),quantity:ne.z.number().positive(),subtotalMinor:ne.z.string().regex(/^-?\d+$/),discountMinor:ne.z.string().regex(/^\d+$/),taxMinor:ne.z.string().regex(/^-?\d+$/).nullable(),totalMinor:ne.z.string().regex(/^-?\d+$/),startsAt:En.nullable(),endsAt:En.nullable(),providerLineId:ne.z.string().nullable(),providerItemId:ne.z.string()}),dp=ne.z.strictObject({invoice:$i,items:ne.z.array(ne.z.discriminatedUnion("kind",[Zy,ne.z.strictObject({kind:ne.z.literal("invoice_credit"),key:ne.z.string(),internal_feature_id:ne.z.uuid(),internal_credit_feature_id:ne.z.uuid(),name:ne.z.string(),units:Ae,reserved:Ae,amountMinor:ri,grossAmountMinor:ri,creditsAppliedMinor:ri,properties:wt,cashPrice:zi,providerItemId:ne.z.string().nullable(),creditProviderItemId:ne.z.string().nullable()}),ne.z.strictObject({kind:ne.z.literal("usage"),key:ne.z.string(),internal_feature_id:ne.z.uuid(),name:ne.z.string(),units:Ae,reserved:Ae,amountMinor:ri,cashPrice:zi})])).max(100),nextCursor:ne.z.string().min(1).max(180).nullable()}),Wy=ne.z.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),ac=ne.z.strictObject({from:En,to:En,entityId:ne.z.uuid().optional(),snapshotAt:En.nullable(),after:ne.z.strictObject({at:En,id:ne.z.uuid(),position:ne.z.number().int().nonnegative()}).nullable(),limit:ne.z.number().int().min(1).max(100)}).refine(e=>Date.parse(e.from)<Date.parse(e.to)&&Date.parse(e.to)-Date.parse(e.from)<=366*864e5,"Statement range must be positive and at most 366 days").refine(e=>e.after===null||e.snapshotAt!==null,"A cursor requires the original snapshot time"),pp=ne.z.strictObject({customerId:ne.z.uuid(),entityId:ne.z.uuid().nullable(),from:En,to:En,snapshotAt:En,totals:ne.z.array(ne.z.strictObject({internal_credit_feature_id:ne.z.uuid(),name:ne.z.string(),consumed:Qt,refunded:Qt,net:Wy})).max(1e3),rows:ne.z.array(ne.z.strictObject({operationId:ne.z.uuid(),position:ne.z.number().int().nonnegative(),kind:ne.z.enum(["consume","confirm","refund"]),originalId:ne.z.uuid().nullable(),occurredAt:En,internal_feature_id:ne.z.uuid(),entitlementName:ne.z.string(),sourceId:ne.z.uuid(),internal_credit_feature_id:ne.z.uuid(),creditName:ne.z.string(),units:Er,amount:Qt,pricing:ne.z.array(ic).max(12),properties:wt})).max(100),nextCursor:ac.shape.after});var D=require("zod");var mn=require("zod");var Yy=mn.z.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),Xy=mn.z.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),da=mn.z.strictObject({internal_feature_id:mn.z.uuid(),entityId:mn.z.uuid().nullable()}),mp=da.extend({quantity:Ae,expectedRevision:mn.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:mn.z.string().min(1).max(120),properties:wt.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),Ji=da.extend({operationId:mn.z.uuid().nullable(),usage:Ae,capacity:Yy.nullable(),remaining:Xy.nullable(),withinLimit:mn.z.boolean(),revision:mn.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:mn.z.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let n=r=>{let i=r.startsWith("-"),[a,o=""]=(i?r.slice(1):r).split(".");if(a===void 0||a==="")throw new Error("Invalid decimal value");return(i?-1n:1n)*(BigInt(a)*10n**12n+BigInt(o.padEnd(12,"0")))};(e.capacity===null!=(e.remaining===null)||(e.capacity===null?!e.withinLimit:e.remaining===null||n(e.remaining)!==n(e.capacity)-n(e.usage)||e.withinLimit!==n(e.remaining)>=0n)||e.revision===0!=(e.operationId===null)||e.operationId===null!=(e.updatedAt===null))&&t.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var $t=D.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),Sn=D.z.iso.datetime({offset:!0}),eb=D.z.enum(["access","metered","credit"]),Zi={internal_feature_id:D.z.uuid(),key:wr,name:D.z.string().min(1).max(120),kind:eb},fp=D.z.object({customerId:D.z.uuid(),snapshotAt:Sn,memberships:D.z.array(D.z.object({id:D.z.uuid(),productId:D.z.string().min(1).max(255),productVersionId:D.z.uuid(),billingProductVersionId:D.z.uuid(),version:D.z.number().int().positive(),key:D.z.string().min(1).max(64),name:D.z.string().min(1).max(120),groupId:D.z.string().max(255).nullable(),membershipType:D.z.enum(["main","addon"]),status:D.z.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:D.z.boolean(),accessEnabled:D.z.boolean(),renewalChange:D.z.object({productVersionId:D.z.uuid(),name:D.z.string().min(1).max(120),version:D.z.number().int().positive(),effectiveAt:Sn,benefitsAppliedAt:Sn.nullable(),timing:D.z.enum(["immediate","renewal"]),changeKind:D.z.enum(["plan","seats","quantity"]),feature:D.z.strictObject({internal_feature_id:D.z.uuid(),name:D.z.string().min(1).max(80),fromQuantity:D.z.number().int().min(0).max(1e4),toQuantity:D.z.number().int().min(0).max(1e4)}).optional(),seat:D.z.object({key:D.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:D.z.number().int().min(0).max(1e4),toQuantity:D.z.number().int().min(0).max(1e4)}).strict().nullable(),status:D.z.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(e=>e.changeKind==="seats"==(e.seat!==null)&&e.changeKind==="quantity"==(e.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:D.z.object({phase:D.z.enum(["paid","trial"]),startsAt:Sn,endsAt:Sn.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:D.z.boolean(),balances:D.z.array(D.z.object({...Zi,usageType:D.z.enum(["consumable","non_consumable"]).nullable(),accessible:D.z.boolean(),unlimited:D.z.boolean(),available:$t,held:$t,debt:$t,nextExpiresAt:Sn.nullable(),usage:Ji.nullable()}).strict().refine(e=>e.kind==="metered"==(e.usageType!==null)&&(e.accessible||e.available==="0"&&e.held==="0")&&(e.usageType==="non_consumable"?e.usage!==null&&e.usage.internal_feature_id===e.internal_feature_id&&e.unlimited===(e.usage.capacity===null)&&e.available===(e.usage.remaining===null||e.usage.remaining.startsWith("-")?"0":e.usage.remaining)&&e.held==="0"&&e.debt==="0":e.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:D.z.boolean()}).strict(),gp=D.z.enum(["source","usage","transaction","invoice","debt","settlement"]),pa=D.z.object({at:Sn,id:D.z.uuid(),type:gp}).strict(),hp=D.z.object({type:gp.nullable(),resourceKey:wr.optional(),kind:D.z.enum(["purchase","refund"]).optional(),topup:D.z.boolean().optional(),from:D.z.iso.date().nullable(),to:D.z.iso.date().nullable(),after:pa.nullable(),limit:D.z.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),oi={id:D.z.uuid(),occurredAt:Sn},tb=D.z.discriminatedUnion("type",[D.z.strictObject({...oi,type:D.z.literal("invoice"),status:D.z.string().min(1).max(80),paid:$t,refunded:$t,currency:be,externalId:D.z.string().nullable()}),D.z.object({...oi,...Zi,type:D.z.literal("source"),reason:D.z.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:$t,unlimited:D.z.boolean(),status:D.z.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:Sn,expiresAt:Sn.nullable(),orderId:D.z.uuid().nullable(),parentSourceId:D.z.uuid().nullable()}).strict(),D.z.object({...oi,type:D.z.literal("usage"),internal_feature_id:D.z.uuid(),name:D.z.string().min(1).max(120),kind:D.z.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:D.z.uuid().nullable(),quantity:Ae,accepted:D.z.boolean(),reason:D.z.enum([...la.options,"expired"]).nullable(),properties:wt,reservationStatus:D.z.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:Sn.nullable(),charges:D.z.array(D.z.discriminatedUnion("funding",[D.z.strictObject({funding:D.z.literal("balance"),sourceId:D.z.uuid(),rolloverId:D.z.uuid().nullable(),units:Er,amount:$t}),D.z.strictObject({funding:D.z.literal("unbilled"),units:Er}),D.z.object({...Zi,funding:D.z.literal("prepaid"),amount:$t}).strict(),D.z.object({funding:D.z.literal("postpaid"),invoiceId:D.z.uuid(),invoiceLineId:D.z.uuid(),authorizationId:D.z.uuid(),units:Ae,currency:be}).strict()])).max(500)}).strict().refine(e=>(e.kind==="set_usage"||e.kind==="consume"&&e.quantity==="0"?e.accepted&&e.reason===null&&e.charges.length===0&&e.reservationStatus===null:e.accepted?e.reason===null&&e.charges.length>0:e.reason!==null&&e.charges.length===0)&&e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),D.z.object({...oi,type:D.z.literal("transaction"),purpose:D.z.enum(["product","invoice"]),productVersionId:D.z.uuid().nullable(),productName:D.z.string().min(1).max(120).nullable(),productVersion:D.z.number().int().positive().nullable(),invoiceId:D.z.uuid().nullable(),orderId:D.z.uuid(),originalId:D.z.uuid().nullable(),kind:D.z.enum(["purchase","refund"]),amountMinor:D.z.number().int().nonnegative().max(2e8).nullable(),currency:be.nullable()}).strict().refine(e=>e.currency===null==(e.amountMinor===null)&&(e.purpose==="product"?e.productVersionId!==null&&e.productName!==null&&e.productVersion!==null&&e.invoiceId===null:e.productVersionId===null&&e.productName===null&&e.productVersion===null&&e.invoiceId!==null)&&e.kind==="refund"==(e.originalId!==null)&&(e.kind!=="refund"||e.amountMinor===null||e.amountMinor>0),"Payment fact provenance is incomplete"),D.z.object({...oi,...Zi,type:D.z.literal("debt"),sourceId:D.z.uuid(),transactionId:D.z.uuid(),amount:$t}).strict(),D.z.object({...oi,...Zi,type:D.z.literal("settlement"),sourceId:D.z.uuid(),debtId:D.z.uuid(),kind:D.z.enum(["payment","usage_refund","payment_return"]),amount:$t}).strict()]),Ap=D.z.object({customerId:D.z.uuid(),rows:D.z.array(tb).max(50),nextCursor:pa.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");var pe=require("zod"),bp=pe.z.object({customerId:pe.z.uuid()}).strict(),xp=pe.z.discriminatedUnion("action",[pe.z.object({customerId:pe.z.uuid(),requestId:pe.z.uuid(),action:pe.z.literal("assign"),poolId:pe.z.uuid(),memberCustomerId:pe.z.uuid()}).strict(),pe.z.strictObject({customerId:pe.z.uuid(),requestId:pe.z.uuid(),action:pe.z.literal("assign_entity"),poolId:pe.z.uuid(),entityId:pe.z.uuid()}),pe.z.object({customerId:pe.z.uuid(),requestId:pe.z.uuid(),action:pe.z.literal("release"),poolId:pe.z.uuid(),slotId:pe.z.uuid()}).strict()]),Wi=pe.z.number().int().nonnegative(),sc=pe.z.iso.datetime({offset:!0}),cc=pe.z.strictObject({internalId:pe.z.uuid(),id:pe.z.string(),name:pe.z.string().nullable(),version:pe.z.number().int().positive()}),yp=pe.z.enum(["active","past_due"]),uc=pe.z.strictObject({customerId:pe.z.uuid(),licenses:pe.z.array(pe.z.strictObject({id:pe.z.uuid(),linkId:pe.z.uuid(),parent:pe.z.strictObject({customerProductId:pe.z.uuid(),status:yp,product:cc}),product:cc,planLicense:pe.z.strictObject({id:pe.z.uuid(),prepaidOnly:pe.z.boolean(),isCustom:pe.z.boolean()}).nullable(),granted:Wi,included:Wi,paidQuantity:Wi,usage:Wi,remaining:Wi,createdAt:sc}).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:pe.z.array(pe.z.strictObject({id:pe.z.uuid(),linkId:pe.z.uuid(),status:yp,product:cc,entity:pe.z.strictObject({internalId:pe.z.uuid(),id:pe.z.string().nullable(),name:pe.z.string().nullable()}).nullable(),beneficiary:pe.z.strictObject({internalId:pe.z.uuid(),id:pe.z.string().nullable(),name:pe.z.string().nullable()}).nullable(),startedAt:sc.nullable(),endedAt:sc.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:pe.z.boolean()});var ue=require("zod"),Yi=ue.z.enum(["email","sms","voice","push"]),xO=ue.z.enum(["resend","twilio","fcm","apns"]);var SO=ue.z.string().regex(/^\+[1-9]\d{1,14}$/),nb=ue.z.enum(["email_recipient","sms_segment","voice_second","push_device"]);var rb=ue.z.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),ib=ue.z.strictObject({subject:rb,html:ue.z.string().min(1).max(131072).optional(),text:ue.z.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),ob=ue.z.strictObject({body:ue.z.string().min(1).max(1600).refine(e=>e.trim().length>0)}),ab=ue.z.strictObject({text:ue.z.string().trim().min(1).max(4e3),language:ue.z.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:ue.z.number().int().min(1).max(900)}),sb=ue.z.record(ue.z.string().min(1).max(64),ue.z.string().max(256)).refine(e=>Object.keys(e).length<=20&&Object.keys(e).every(t=>!/^(?:indiana_|google\.|gcm\.)/i.test(t)&&t!=="aps"),"Push data contains reserved fields or too many entries"),cb=ue.z.strictObject({title:ue.z.string().trim().min(1).max(200),body:ue.z.string().trim().min(1).max(2e3),url:ue.z.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:sb.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),Sp=ue.z.discriminatedUnion("channel",[ue.z.strictObject({channel:ue.z.literal("email"),content:ib}),ue.z.strictObject({channel:ue.z.literal("sms"),content:ob}),ue.z.strictObject({channel:ue.z.literal("voice"),content:ab}),ue.z.strictObject({channel:ue.z.literal("push"),content:cb})]),Ip=ue.z.strictObject({requestId:ue.z.uuid(),customerId:ue.z.uuid(),connectionId:ue.z.uuid().optional(),message:Sp,expiresAt:ue.z.iso.datetime({offset:!0})}),ub=ue.z.array(ue.z.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),lb=ue.z.discriminatedUnion("kind",[ue.z.strictObject({kind:ue.z.literal("all")}),ue.z.strictObject({kind:ue.z.literal("customers"),customerIds:ub})]),IO=ue.z.strictObject({name:ue.z.string().trim().min(1).max(120),connectionId:ue.z.uuid().optional(),message:Sp,audience:lb,frequencyLimit:ue.z.number().int().min(1).max(100)}),vp=ue.z.strictObject({requestId:ue.z.uuid(),channel:Yi,state:ue.z.enum(["allowed","denied"]),expectedRevision:ue.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),wp=ue.z.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Op=ue.z.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),vO=ue.z.strictObject({meter:nb,estimatedUnits:ue.z.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:ue.z.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});var ve=require("zod");var te=require("zod");var kr=require("zod");var Xi=kr.z.strictObject({internalFeatureId:kr.z.uuid(),name:kr.z.string().min(1).max(120),includedAmount:kr.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:kr.z.enum(["hour","day","week","month","year","lifetime"]),resetCount:kr.z.number().int().min(1).max(100),terms:Jo});var it=require("zod");var _p=require("zod");var jr=require("zod"),Pp=jr.z.enum(["stripe","apple","google","merchant"]),Cp=jr.z.enum(["membership","credit_pack","lifetime"]),CO=jr.z.enum(["active","grace","suspended","inactive","revoked"]),_O=jr.z.strictObject({currency:jr.z.string().regex(/^[A-Z]{3}$/),micros:jr.z.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var ai=_p.z.object({provider:Pp,currency:be}).strict();var er=it.z.strictObject({internal_feature_id:it.z.uuid(),quantity:Ae.refine(e=>/[1-9]/.test(e)),properties:wt,entityId:it.z.uuid().optional()}),Ep=it.z.strictObject({requirement:er,commerce:ai.optional(),paywallId:it.z.uuid().optional()}),db=it.z.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),lc=it.z.strictObject({productId:it.z.string().min(1),productVersionId:it.z.string().min(1),name:it.z.string().min(1).max(120),action:it.z.enum(["purchase","upgrade","addon","topup"]),membershipId:it.z.string().min(1).nullable(),currency:be,amountMinor:it.z.string().regex(/^(0|[1-9]\d{0,8})$/),interval:it.z.enum(["free","week","month","year","one_time"]),intervalCount:it.z.number().int().min(1).max(156)}),Tr=it.z.strictObject({internal_feature_id:it.z.string().min(1),name:it.z.string().min(1).max(120),kind:it.z.enum(["access","metered","credit"]),quantity:Ae,allowed:it.z.boolean(),reason:db.nullable(),preview:it.z.strictObject({scenario:it.z.enum(["feature_flag","usage_limit"]),candidates:it.z.array(lc).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"})}),FO=it.z.strictObject({paywallId:it.z.uuid(),requirement:er});var fa=te.z.object({plan:te.z.string().min(1).max(200).optional(),coupon:te.z.uuid().optional(),promotionCode:te.z.uuid().optional(),picker:te.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),ma=te.z.object({text:te.z.string().optional(),label:te.z.string().optional(),alt:te.z.string().optional(),html:te.z.string().max(32768).optional(),price:te.z.object({current:te.z.string(),original:te.z.string().nullable(),period:te.z.string()}).optional(),code:te.z.string().optional(),countdownAt:te.z.iso.datetime().optional(),planId:te.z.string().min(1).max(200).optional(),planVersionId:te.z.string().min(1).max(200).optional(),currency:be.optional(),couponId:te.z.uuid().optional(),offerId:te.z.uuid().optional(),unavailable:te.z.boolean().optional(),unavailableReason:te.z.string().optional(),missing:te.z.array(te.z.string()).optional()}).strict(),si=te.z.object({paywall:Tr.optional(),nodes:te.z.record(te.z.string(),te.z.object({base:ma,picker:te.z.string().optional(),byPlan:te.z.record(te.z.string(),ma).optional()}).strict()),plans:te.z.record(te.z.string(),te.z.object({id:te.z.string().min(1).max(200),versionId:te.z.string().min(1).max(200),available:te.z.boolean(),name:te.z.string(),price:te.z.string(),period:te.z.string(),currency:be.optional(),amountMinor:te.z.number().int().nonnegative().optional(),interval:te.z.enum(["free","week","month","year","one_time"]).optional(),intervalCount:te.z.number().int().positive().optional(),prepaid:te.z.array(Xi).max(100).optional()}).strict()),pickers:te.z.record(te.z.string(),te.z.object({options:te.z.array(te.z.string().min(1).max(200)).max(20),selected:te.z.string().min(1).max(200).nullable()}).strict()),quantities:te.z.record(te.z.string(),te.z.strictObject({minimum:te.z.number().int().nonnegative(),maximum:te.z.number().int().nonnegative(),step:te.z.number().int().positive(),value:te.z.number().int().nonnegative(),label:te.z.string(),available:te.z.boolean()})).optional(),diagnostics:te.z.array(te.z.object({nodeId:te.z.string(),message:te.z.string()}).strict())}).strict();function Rp(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}var S=require("zod");function pb(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function kp(e){let t={};function n(r){var i;if(pb(r)){let a=t[i=r.interaction.pickerId]??(t[i]={ids:[],defaultId:null});for(let s of r.children){let c=s.type==="stack"?s.bind?.plan:void 0;c&&!a.ids.includes(c)&&a.ids.push(c)}let o=r.children[r.interaction.defaultIndex];!a.defaultId&&o?.type==="stack"&&(a.defaultId=o.bind?.plan??null)}r.type==="stack"&&r.children.forEach(n)}return e.pages.forEach(r=>n(r.root)),t}var Rn=require("zod"),jp=Rn.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ga=Rn.z.strictObject({tiers:Rn.z.array(Rn.z.strictObject({id:jp,name:Rn.z.string().trim().min(1).max(80)})).min(1).max(8),assignments:Rn.z.array(Rn.z.strictObject({productVersionId:Rn.z.string().min(1).max(200),tierId:jp,period:Rn.z.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let n=e.tiers.map(r=>r.id);(new Set(n).size!==n.length||new Set(e.assignments.map(r=>r.productVersionId)).size!==e.assignments.length||new Set(e.assignments.map(r=>`${r.tierId}:${r.period}`)).size!==e.assignments.length||e.assignments.some(r=>!n.includes(r.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function ha(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}var se=require("zod");var mb=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],Tp=se.z.enum(mb),Np=se.z.object({source:Tp,layout:se.z.enum(["full","compact"]),resourceKey:wr.optional(),pageSize:se.z.number().int().min(1).max(50),showSources:se.z.boolean(),allowPurchase:se.z.boolean(),outputs:se.z.object({billing_adjustment:se.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:se.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:se.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:se.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:se.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:se.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((e,t)=>{(e.outputs?.billing_authorization||e.outputs?.billing_adjustment)&&e.source!=="billing_controls"&&t.addIssue({code:"custom",message:"Payment authorization routes belong to the billing controls component."}),e.resourceKey&&!["credit_balance","credit_transactions"].includes(e.source)&&t.addIssue({code:"custom",message:"\u8FD9\u4E2A\u6570\u636E\u6E90\u4E0D\u80FD\u7ED1\u5B9A\u79EF\u5206\u8D44\u6E90\u3002"}),e.showSources&&e.source!=="credit_balance"&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u4F59\u989D\u53EF\u4EE5\u5C55\u5F00\u6765\u6E90\u3002"}),e.allowPurchase&&!["credit_packs","customer_plans","membership"].includes(e.source)&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u5305\u3001\u5957\u9910\u4E0E\u4F1A\u5458\u7EC4\u4EF6\u53EF\u4EE5\u542F\u7528\u4EA4\u6613\u3002"})}),Et=se.z.string().max(2e3),Dp=se.z.object({id:se.z.string().max(100),label:Et,detail:se.z.array(Et).max(12),value:Et.optional(),status:Et.optional(),facts:se.z.array(se.z.object({label:Et,value:Et}).strict()).max(1e3),purchaseId:se.z.uuid().optional(),invoiceUrl:se.z.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:se.z.array(se.z.strictObject({action:se.z.literal("invoice_open"),label:Et})).max(1).optional(),membershipActions:se.z.array(se.z.object({value:se.z.string().max(100),label:Et}).strict()).max(3).optional()}).strict(),fb=se.z.object({key:wr,name:Et,spendable:Et,reserved:Et,available:Et,expiry:Et.nullable(),sources:se.z.array(Dp).max(50),sourceCount:se.z.number().int().nonnegative(),sourcePage:se.z.number().int().positive(),hasNextSources:se.z.boolean(),hasPreviousSources:se.z.boolean()}).strict(),gb=se.z.object({source:Tp,status:se.z.enum(["idle","loading","ready","error"]),stale:se.z.boolean(),preview:se.z.boolean(),errorCode:se.z.string().max(80).optional(),errorMessage:Et.optional(),resources:se.z.array(fb).max(500),rows:se.z.array(Dp).max(50),hasNext:se.z.boolean(),hasPrevious:se.z.boolean(),page:se.z.number().int().positive(),filter:se.z.string().max(40),updatedAt:se.z.iso.datetime().optional(),buyingId:se.z.uuid().optional(),membershipBusy:se.z.boolean().optional(),billingBusy:se.z.boolean().optional(),membershipReview:se.z.object({title:Et,note:Et,facts:se.z.array(se.z.object({label:Et,value:Et}).strict()).max(100)}).strict().optional(),membershipResult:Et.optional()}).strict(),Fp=se.z.object({nodes:se.z.record(se.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),gb)}).strict(),GO=se.z.object({nodeId:se.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:se.z.enum(["refresh","next","previous","filter","buy_pack","billing_portal","billing_authorization","billing_adjustment","invoice_open","membership_preview","membership_confirm","membership_dismiss","sources_next","sources_previous"]),value:se.z.string().max(100).optional()}).strict();var Ab=4,vn={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},to=S.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Me=S.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),yb=S.z.enum(["none","xs","sm","md","lg","xl"]),bb=S.z.enum(["none","sm","md","lg","full"]),dc=S.z.string().regex(/^#[0-9a-fA-F]{6}$/),Bp=S.z.string().max(2048).refine(e=>{try{let t=new URL(e);return t.protocol==="https:"&&t.hostname.length>0}catch{return!1}},"\u53EA\u652F\u6301 https \u94FE\u63A5"),pc=S.z.union([Bp,S.z.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),S.z.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),S.z.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Mp=S.z.object({primary:dc,background:dc,text:dc,radius:bb,font:S.z.enum(["system","serif","rounded","mono"])}).strict(),no=S.z.union([S.z.enum(["primary","text","muted","background","surface"]),S.z.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),De=(e,t)=>S.z.number().int().min(e).max(t),qp=S.z.union([S.z.enum(["fit","fill"]),De(1,1200)]),xb=S.z.object({top:De(0,200),right:De(0,200),bottom:De(0,200),left:De(0,200)}).strict(),Sb=S.z.object({top:De(-100,200),right:De(-100,200),bottom:De(-100,200),left:De(-100,200)}).strict(),Vp=S.z.object({x:De(0,100),y:De(0,100)}).strict(),Ib=S.z.discriminatedUnion("type",[S.z.object({type:S.z.literal("color"),color:no}).strict(),S.z.object({type:S.z.literal("linear"),angle:De(0,360),stops:S.z.array(S.z.object({color:no,at:De(0,100)}).strict()).min(2).max(4)}).strict(),S.z.object({type:S.z.literal("image"),src:pc,fit:S.z.enum(["cover","contain"]),position:Vp.optional()}).strict()]),vb=S.z.discriminatedUnion("type",[S.z.object({type:S.z.literal("rect"),radius:S.z.union([De(0,200),S.z.object({topLeft:De(0,200),topRight:De(0,200),bottomRight:De(0,200),bottomLeft:De(0,200)}).strict()])}).strict(),S.z.object({type:S.z.literal("pill")}).strict()]),wb=S.z.object({width:De(0,12),color:no,style:S.z.enum(["solid","dashed"])}).strict(),Ob=S.z.object({x:De(-40,40),y:De(-40,40),blur:De(0,80),spread:De(-20,40),color:no}).strict(),Pb=S.z.object({font:S.z.enum(["system","serif","rounded","mono"]),size:De(8,96),weight:S.z.number().int().min(100).max(900).multipleOf(100),lineHeight:S.z.number().min(.8).max(3),letterSpacing:S.z.number().min(-5).max(20),color:no,align:S.z.enum(["start","center","end"]),italic:S.z.boolean(),decoration:S.z.enum(["none","underline","line-through"]),transform:S.z.enum(["none","uppercase"])}).strict().partial(),Nr=S.z.object({width:qp,height:qp,padding:xb,margin:Sb,gap:De(0,120),grow:S.z.union([S.z.boolean(),S.z.number().min(0).max(12)]),background:Ib,opacity:S.z.number().min(0).max(1),clipContent:S.z.boolean(),shape:vb,border:wb,shadow:Ob,text:Pb}).strict().partial(),Yt={id:to,name:S.z.string().trim().min(1).max(60).optional(),hidden:S.z.boolean().optional(),style:Nr.optional(),fallback:Me.optional()},Cb=S.z.object({...Yt,type:S.z.literal("text"),productField:S.z.enum(["name","price","trial","period"]).optional(),feature:S.z.object({id:S.z.uuid(),field:S.z.enum(["name","allowance"])}).strict().optional(),text:Me,variant:S.z.enum(["title","heading","body","caption"])}).strict(),_b=S.z.object({...Yt,type:S.z.literal("image"),src:pc,localizedSrc:S.z.record(xn,pc).optional(),alt:Me,aspect:S.z.enum(["auto","1:1","4:3","16:9","3:1"]),fit:S.z.enum(["cover","contain"]),position:Vp.optional()}).strict(),Eb=S.z.object({...Yt,type:S.z.literal("button"),label:Me,variant:S.z.enum(["primary","secondary","link"]),action:Me,purpose:S.z.enum(["purchase","navigation","close"]).optional(),bind:fa.optional()}).strict(),Rb=S.z.object({...Yt,type:S.z.literal("divider")}).strict(),kb=S.z.object({...Yt,type:S.z.literal("customer_data"),title:Me,data:Np}).strict(),jb=S.z.object({...Yt,type:S.z.literal("spacer"),size:yb}).strict(),Tb=S.z.object({...Yt,type:S.z.literal("custom_html"),html:S.z.record(xn,S.z.string().max(vn.customHtml)),css:S.z.string().max(vn.customCss)}).strict(),Nb=S.z.object({...Yt,type:S.z.literal("price"),fallback:Me,parts:S.z.object({current:Nr.optional(),original:Nr.optional(),period:Nr.optional()}).strict().optional()}).strict(),Db=S.z.object({...Yt,type:S.z.literal("coupon_code"),label:Me,fallback:Me}).strict(),Fb=S.z.object({...Yt,type:S.z.literal("countdown"),source:S.z.enum(["offer.ends_at","offer.expires_at","fixed"]),at:S.z.iso.datetime().optional(),granularity:S.z.enum(["day","hour","minute","second"]),expired:Me,fallback:Me}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),Mb=S.z.object({...Yt,type:S.z.literal("plan_picker"),label:Me,fallback:Me,planIds:S.z.array(S.z.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:S.z.string().min(1).max(200).optional(),grouping:ga.safeExtend({monthLabel:Me,yearLabel:Me,unavailableLabel:Me}).optional(),states:S.z.object({selected:Nr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!ha(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),qb=S.z.object({...Yt,type:S.z.literal("quantity_picker"),bind:fa.optional(),label:Me,fallback:Me,internalFeatureId:S.z.uuid(),minimumQuantity:De(0,1e4),maximumQuantity:De(0,1e4),defaultQuantity:De(0,1e4),step:De(1,1e4)}).strict().refine(e=>e.minimumQuantity<=e.defaultQuantity&&e.defaultQuantity<=e.maximumQuantity&&(e.defaultQuantity-e.minimumQuantity)%e.step===0,"Quantity controls require a Product binding and valid bounds"),Bb=S.z.discriminatedUnion("type",[S.z.object({type:S.z.literal("input"),label:Me,keyboard:S.z.enum(["text","email","tel","url"]),maxLength:De(1,500)}).strict(),S.z.object({type:S.z.literal("multiselect"),label:Me,min:De(0,50),max:De(1,50)}).strict(),S.z.object({type:S.z.literal("select"),label:Me,defaultIndex:De(0,49),purpose:S.z.enum(["option","product","tier"]).optional(),pickerId:to.optional(),selectedStyle:Nr.optional()}).strict(),S.z.object({type:S.z.literal("tabs"),label:Me,defaultIndex:De(0,49),purpose:S.z.literal("tier").optional()}).strict(),S.z.object({type:S.z.literal("toggle"),label:Me,defaultEnabled:S.z.boolean()}).strict(),S.z.object({type:S.z.literal("carousel"),label:Me}).strict()]),In={...Yt,type:S.z.literal("stack"),direction:S.z.enum(["vertical","horizontal","overlay"]),align:S.z.enum(["start","center","end","stretch"]),justify:S.z.enum(["start","center","end","between"]),productSlot:S.z.object({index:De(0,19),period:S.z.enum(["month","year"]).optional(),requireBinding:S.z.boolean().optional()}).strict().optional(),interaction:Bb.optional(),states:S.z.object({selected:Nr.optional()}).strict().optional(),purpose:S.z.literal("benefits").optional(),purchaseAction:Me.optional(),buttonVariant:S.z.enum(["primary","secondary","link"]).optional(),bind:fa.optional()},Lp=S.z.lazy(()=>S.z.object({...Yt,type:In.type,direction:In.direction,align:In.align,justify:In.justify,children:S.z.array(Vb).max(vn.children),productSlot:In.productSlot,interaction:In.interaction,states:In.states,purpose:In.purpose,purchaseAction:In.purchaseAction,buttonVariant:In.buttonVariant,bind:In.bind}).strict()),Vb=S.z.lazy(()=>S.z.union([Lp,Cb,_b,Eb,Rb,jb,Tb,Nb,Db,Fb,Mb,qb,kb])),Lb=S.z.union([S.z.string().max(500),S.z.number().finite(),S.z.boolean(),S.z.null()]),eo={id:Me,event:Me,properties:S.z.record(Me,Lb).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},Ub=S.z.discriminatedUnion("type",[S.z.object({...eo,type:S.z.literal("navigate"),close:S.z.literal(!1),pageId:to}).strict(),S.z.object({...eo,type:S.z.literal("event"),close:S.z.boolean()}).strict(),S.z.object({...eo,type:S.z.literal("close"),close:S.z.literal(!0)}).strict(),S.z.object({...eo,type:S.z.literal("open_url"),close:S.z.boolean(),url:Bp}).strict(),S.z.object({...eo,type:S.z.literal("claim_offer"),close:S.z.boolean(),couponId:S.z.uuid()}).strict()]),zb=S.z.object({defaultLocale:xn,locales:S.z.record(xn,S.z.record(Me,S.z.string().max(vn.stringLength)))}).strict(),$b=S.z.enum(["popup","paywall","onboarding","page","banner"]);var Gb=S.z.discriminatedUnion("type",[S.z.object({type:S.z.literal("modal"),size:S.z.enum(["sm","md","lg"])}).strict(),S.z.object({type:S.z.literal("sheet"),size:S.z.enum(["sm","md","lg"])}).strict(),S.z.object({type:S.z.literal("fullscreen")}).strict(),S.z.object({type:S.z.literal("inline")}).strict()]);var Kb=S.z.object({kind:S.z.literal("screen"),schemaVersion:S.z.literal(Ab),name:S.z.string().trim().min(1).max(80),surface:$b,initialPageId:to.optional(),presentation:Gb,theme:Mp,pages:S.z.array(S.z.object({id:to,name:S.z.string().trim().min(1).max(60),root:Lp,theme:Mp.optional(),editorPosition:S.z.object({x:S.z.number().finite().min(-1e5).max(1e5),y:S.z.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(vn.pages),strings:zb,actions:S.z.array(Ub).max(vn.actions)}).strict();function Gt(e,t){for(let n of e.pages)Gn(n.root,t)}var sn=Kb.superRefine((e,t)=>{let n=vn;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(f=>f.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>vn.locales&&r(`\u6700\u591A ${vn.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,f)=>{if(c++,f>vn.depth&&(u=!0),s.has(l.id)&&r(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${l.id}`),s.add(l.id),l.type==="button"&&!a.has(l.action)&&r(`\u6309\u94AE ${l.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${l.action}`),l.type==="custom_html")for(let m of Object.keys(l.html))i.includes(m)||r(`\u81EA\u5B9A\u4E49 HTML ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${m}`);if(l.type==="image")for(let m of Object.keys(l.localizedSrc??{}))i.includes(m)||r(`\u56FE\u7247 ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${m}`)}),c>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),u&&r(`\u5C42\u7EA7\u6700\u591A ${vn.depth} \u5C42`)});function Gn(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)Gn(i,t,n+1,e)}function Aa(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 Hb(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=ro(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 tr(e){let t=Aa(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=>!Hb(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 Qb(e,t){let n=null;return Gn(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function ro(e,t){for(let n of e.pages){let r=Qb(n.root,t);if(r)return r}return null}var Nt=require("zod"),yt=Nt.z.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/).refine(e=>e.split(".").every(t=>t.length>0&&!["__proto__","constructor","prototype"].includes(t)),"Reserved or empty variable path"),mc=Nt.z.strictObject({type:Nt.z.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:Nt.z.boolean(),enum:Nt.z.array(Nt.z.string().max(255)).min(1).max(100).optional()}),ci=mc.extend({type:Nt.z.enum([...mc.shape.type.options,"array"]),items:mc.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"})}),ui=ci.safeExtend({source:Nt.z.discriminatedUnion("type",[Nt.z.strictObject({type:Nt.z.literal("input")}),Nt.z.strictObject({type:Nt.z.literal("node")}),Nt.z.strictObject({type:Nt.z.enum(["parameter","attribute"]),key:yt})])}),eP=Nt.z.record(yt,ui),fc=Nt.z.record(yt,yt).refine(e=>Object.keys(e).length<=20);function fn(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=>fn(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&&Nt.z.uuid().safeParse(t.id).success:e.type==="json"||(e.type==="strings"?Array.isArray(t)&&t.every(n=>typeof n=="string"):typeof t===e.type):!1}function gc(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&&gc(e.items,t.items)}function ya(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(!fn(i,u))throw new Error(`Invalid variable value: ${r}`);n[r]=u}}return n}function li(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 Up(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"||!fn(e[i],a))throw new Error(`Invalid node variable write: ${i}`);if(r.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}var nr=require("zod");var wn=nr.z.string().min(1).max(255).regex(/^[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+){0,9}$/).refine(e=>e.split(".").every(t=>!["__proto__","constructor","prototype"].includes(t)),"Reserved value path"),kn=nr.z.discriminatedUnion("source",[nr.z.strictObject({source:nr.z.literal("literal"),value:Se}),nr.z.strictObject({source:nr.z.literal("variable"),key:nr.z.string().min(1).max(255),path:wn.optional()})]);function zp(e,t){if(!t)return e;for(let n of wn.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 hc(e,t){if(e.source==="literal")return structuredClone(e.value);let n=ya(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(Se.parse(zp(n[e.key],e.path)))}function Ac(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&&!wn.safeParse(r).success?null:{key:n,path:r}}function yc(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(Rp))]}function ba(e){return yc(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function cn(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(/^-/,""),f=l.replace(".","").length,m=(l.includes(".")?l.indexOf("."):f)+Number(u),h=m<=0?2-m+f:m>=f?m:f+1;n+=h+(c.startsWith("-")?1:0)-s.length}}return n}var rr=ve.z.enum(["page","popup","banner"]),Jb=3e5,$p=ve.z.strictObject({type:ve.z.enum(["string","number","boolean","strings","json"]),nullable:ve.z.boolean()}),Zb=ve.z.strictObject({inputs:ve.z.record(Me,$p.extend({required:ve.z.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:ve.z.record(Me,$p).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),Wb=ve.z.strictObject({kind:rr,schemaVersion:ve.z.literal(1),name:ve.z.string().trim().min(1).max(80),screen:sn,contract:Zb}),xa=Wb.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"]),cn(e)>Jb&&n("Content document exceeds its byte budget",[])});function Yb(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 Xb=xa.superRefine((e,t)=>{for(let n of ba(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&&!Yb(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}tr(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),Gp=ve.z.strictObject({id:ve.z.uuid(),kind:rr,projectId:ve.z.uuid(),environmentId:ve.z.uuid(),name:ve.z.string(),revision:ve.z.number().int().nonnegative(),status:ve.z.enum(["draft","published","archived"]),publishedVersionId:ve.z.uuid().nullable(),createdAt:ve.z.iso.datetime({offset:!0}),updatedAt:ve.z.iso.datetime({offset:!0})}),fP=Gp.extend({draft:xa}),gP=ve.z.strictObject({rows:ve.z.array(Gp).max(200),nextCursor:ve.z.uuid().nullable()}),bc=ve.z.strictObject({id:ve.z.uuid(),kind:rr,resourceId:ve.z.uuid(),projectId:ve.z.uuid(),environmentId:ve.z.uuid(),version:ve.z.number().int().positive(),sourceRevision:ve.z.number().int().nonnegative(),document:Xb,createdAt:ve.z.iso.datetime({offset:!0})}),hP=bc.omit({document:!0}),AP=ve.z.discriminatedUnion("action",[ve.z.strictObject({action:ve.z.literal("create"),kind:rr,id:ve.z.uuid(),document:xa}),ve.z.strictObject({action:ve.z.literal("save"),kind:rr,id:ve.z.uuid(),revision:ve.z.number().int().nonnegative(),document:xa}),ve.z.strictObject({action:ve.z.enum(["publish","archive"]),kind:rr,id:ve.z.uuid(),revision:ve.z.number().int().nonnegative()})]).superRefine((e,t)=>{"document"in e&&e.document.kind!==e.kind&&t.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});var xc=require("zod"),di={funnelId:xc.z.uuid().optional(),funnelVersionId:xc.z.uuid().optional()};var io=require("zod"),Sa=io.z.strictObject({runId:io.z.uuid(),bindingId:io.z.uuid(),receiptId:io.z.uuid()});var nt=require("zod");var qe=require("zod");var We=require("zod"),SP=We.z.discriminatedUnion("action",[We.z.strictObject({action:We.z.literal("create"),couponId:We.z.uuid(),productBindingId:We.z.uuid(),storeOfferId:We.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:We.z.enum(["introductory","promotional"])}),We.z.strictObject({action:We.z.literal("set_enabled"),id:We.z.uuid(),revision:We.z.number().int().nonnegative(),enabled:We.z.boolean()})]),IP=We.z.array(We.z.strictObject({id:We.z.uuid(),couponId:We.z.uuid(),productBindingId:We.z.uuid(),storeOfferId:We.z.string().min(1).max(255).nullable(),storeOfferType:We.z.enum(["introductory","promotional"]),enabled:We.z.boolean(),revision:We.z.number().int().nonnegative()})).max(500),pi=We.z.strictObject({offerKind:We.z.enum(["none","introductory","promotional"]),offerId:We.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:We.z.number().int().min(0).max(1e8),trialDays:We.z.number().int().min(1).max(730).nullable()}).superRefine((e,t)=>{(e.offerKind==="none"&&(e.offerId!==null||e.discountMinor!==0||e.trialDays!==null)||e.trialDays!==null&&e.discountMinor!==0)&&t.addIssue({code:"custom",message:"Select one store purchase option with its exact terms"})}),vP=We.z.record(We.z.uuid(),pi).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var Sc=qe.z.object({type:qe.z.literal("native_purchase"),receiptId:qe.z.uuid(),orderId:qe.z.uuid(),productVersionId:qe.z.uuid(),provider:qe.z.enum(["apple","google"]),productId:qe.z.string().min(1).max(255),productKind:Cp,replacement:qe.z.strictObject({sourceOrderId:qe.z.uuid(),sourceProductId:qe.z.string().min(1).max(255),policy:qe.z.enum(["apple_store","google_full_price"]),sourceAccountTokens:qe.z.array(qe.z.uuid()).max(50)}).nullable(),appAccountToken:qe.z.uuid().optional(),obfuscatedAccountId:qe.z.string().min(1).max(64).optional(),obfuscatedProfileId:qe.z.uuid().optional(),basePlanId:qe.z.string().min(1).max(255).optional(),offerId:qe.z.string().min(1).max(255).optional(),offerKind:qe.z.enum(["none","introductory","promotional"]),currency:be,catalogAmountMinor:qe.z.number().int().nonnegative().max(1e8),discountMinor:qe.z.number().int().nonnegative().max(1e8),trialDays:qe.z.number().int().min(1).max(730).nullable(),seatBundle:qe.z.array(qe.z.strictObject({key:qe.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:qe.z.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:qe.z.strictObject({offerId:qe.z.string().min(1).max(255),keyId:qe.z.string().min(1).max(255),nonce:qe.z.uuid(),signature:qe.z.string().min(1).max(1024),timestamp:qe.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,t)=>{let n=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(n?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!n&&e.productKind==="membership"&&e.basePlanId===void 0||e.discountMinor>e.catalogAmountMinor||new Set(e.seatBundle.map(i=>i.key)).size!==e.seatBundle.length||e.trialDays!==null&&(e.discountMinor!==0||e.offerKind==="none")||e.offerKind==="none"&&e.discountMinor!==0||(n?!e.appAccountToken||e.obfuscatedAccountId!==void 0||e.obfuscatedProfileId!==void 0||e.basePlanId!==void 0||e.offerKind==="promotional"!=(e.applePromotionalOffer!==null)||e.offerKind==="promotional"!=(e.offerId!==void 0)||e.applePromotionalOffer!==null&&e.applePromotionalOffer.offerId!==e.offerId:e.appAccountToken!==void 0||!e.obfuscatedAccountId||!e.obfuscatedProfileId||e.applePromotionalOffer!==null||e.offerKind==="none"!=(e.offerId===void 0)))&&t.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});var p=require("zod");var Ce=require("zod/v4"),Kp=require("zod/v4"),ex=Kp.z.registry(),{BillingInterval:Hp}=(()=>{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:tx}=(e=>({DisplaySchema:e.object({primary_text:e.string().meta({description:"Main display text (e.g. '$10' or '100 messages')."}),secondary_text:e.string().optional().meta({description:"Secondary display text (e.g. 'per month' or 'then $0.5 per 100')."})})}))(Ce.z),{withSpecDefault:nx}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(ex),{COMMON:Qp}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:rx}={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)}))(Qp),{hasNoDuplicateCurrencies:Jp}={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:Zp}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:ox}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(Ce.z),{Infinite:ax}={Infinite:"inf"},{TierBehavior:sx}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:Wp}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:cx}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:ux}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:lx}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:dx}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(Ce.z),{ApiCreditTierSchema:Yp}=(e=>({ApiCreditTierSchema:e.object({to:e.union([e.number().positive(),e.enum(["inf"])]).meta({description:"Inclusive upper usage boundary for this graduated tier. The final tier must be 'inf'."}),credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group within this tier."})})}))(Ce.z),{VIOLATION_MESSAGES:px}={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:Xp}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(Ce.z),{ModelMarkupsSchema:mx}=((e,t)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),t.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(Ce.z,Xp),{InvoiceUsageEntrySchema:fx}=(e=>({InvoiceUsageEntrySchema:e.object({feature_id:e.string().meta({description:"The metered feature whose units are being converted."}),quantity:e.number().nonnegative().meta({description:"Billable units of the metered feature. Converted to the credit-system feature through its rate card."}),properties:e.record(e.string(),e.unknown()).optional().meta({description:"Event properties used to pick the rate card dimension and multipliers."})}).strict()}))(Ce.z),{AttachDiscountSchema:em}=(e=>({AttachDiscountSchema:e.object({reward_id:e.string().optional().meta({description:"The ID of the reward to apply as a discount."}),promotion_code:e.string().optional().meta({description:"The promotion code to apply as a discount."})}).refine(n=>n.reward_id||n.promotion_code,{message:"Either reward_id or promotion_code must be provided."}).meta({title:"AttachDiscount",description:"A discount to apply. Can be either a reward ID or a promotion code."})}))(Ce.z),{CustomLineItemSchema:gx}=(e=>({CustomLineItemSchema:e.object({amount:e.number().meta({description:"Amount in dollars for this line item (e.g. 10.50). Can be negative for credits."}),description:e.string().meta({description:"Description for the line item."})})}))(Ce.z),{UnixMsTimestampSchema:hx}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(Ce.z),{CreateInvoicePreviewLineSchema:Ax}=(e=>({CreateInvoicePreviewLineSchema:e.object({plan_id:e.string().nullable(),feature_id:e.string().nullable(),description:e.string(),amount:e.number(),amount_after_discounts:e.number(),quantity:e.number().nullable(),prorated:e.boolean(),period_start:e.number().nullable(),period_end:e.number().nullable()})}))(Ce.z),{ReissueInvoiceParamsSchema:tm}=(e=>({ReissueInvoiceParamsSchema:e.object({invoice_id:e.string().meta({description:"The Autumn invoice ID to void and replace.",example:"inv_2b3c4d5e6f7g8h"}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer and memo are applied to the replacement invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the replacement invoice. Defaults to the original invoice's due date; required when that date has already passed."}),update_customer_email:e.email().optional().meta({description:"Updates the customer's billing email before the replacement is issued, so Stripe sends the new invoice to this address."})})}))(Ce.z),{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."})}))(Ce.z),{InvoiceTemplateSchema:yx}=(e=>({InvoiceTemplateSchema:e.object({id:e.string().meta({description:"Unique identifier for the invoice template."}),name:e.string().meta({description:"User-defined name to distinguish this template when sending an invoice."}),footer:e.string().optional().meta({description:"Footer text rendered on the invoice, typically bank details so customers can pay directly."}),memo:e.string().optional().meta({description:"Memo shown near the top of the invoice (Stripe invoice description), e.g. a contact line for payment questions."}),net_terms_days:e.number().int().positive().optional().meta({description:"Default number of days the customer has to pay before the invoice is due. Overridable when sending."}),created_at:e.number().optional().meta({description:"Timestamp (ms) when the template was created."})})}))(Ce.z),{BasePriceSchema:bx}=((e,t,n)=>({BasePriceSchema:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),interval:e.enum(t).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),display:n.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(Ce.z,Hp,tx),{CURRENCY_CODES:xx}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(Qp,rx,ix),{ApiPriceProcessorsSchema:nm}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(Ce.z,ox),{AllocatedBillingFieldSchema:Sx}=((e,t)=>({AllocatedBillingFieldSchema:e.enum(t).optional().meta({internal:!0,description:"How an allocated usage_based price bills mid-cycle quantity changes. 'arrear' (default) bills at period end. 'prorated_legacy' is only returned for prices still on the legacy immediate-proration behavior; omit it to migrate the price to 'arrear'."})}))(Ce.z,cx),{CreditDimensionNameSchema:Ix}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(Ce.z,ux,lx),{ApiCreditMatchSchema:rm}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(dx),{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}}))(px),{ApiCreditMultiplierSchema:wx}=((e,t)=>({ApiCreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional().meta({description:"Multiplies the matched rate. All matching multipliers stack."}),add:e.number().optional().meta({description:"Added to the rate after every factor is applied, in credits per billing-unit group."})}).strict().refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(Ce.z,rm),{ProviderMarkupsSchema:Ox}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(Ce.z,Xp),{InvoiceFeatureQuantitySchema:im}=((e,t,n)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(t).meta({description:"Which of the feature's prices to use: 'prepaid' or 'usage_based'."}),quantity:e.number().nonnegative().optional().meta({description:"Billable feature units in total, exclusive of any included usage. Not per seat or per entity. For a credit-system feature this is the number of credits."}),usage:e.array(n).optional().meta({description:"For credit-system features: billable units of the source features, converted through the credit rate card. Mutually exclusive with quantity."}),prorate:e.boolean().optional().meta({description:"Whether to prorate this line against period_start / period_end. Defaults to true for prepaid and false for usage-based."})}).strict().refine(i=>i.quantity!==void 0!=(i.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(Ce.z,Wp,fx),{CreateInvoicePreviewSchema:Ic}=((e,t)=>({CreateInvoicePreviewSchema:e.object({currency:e.string(),lines:e.array(t),subtotal:e.number(),discount_total:e.number(),tax:e.object({total:e.number(),amount_inclusive:e.number(),amount_exclusive:e.number(),status:e.enum(["complete","incomplete"])}).nullable(),total:e.number(),due_date:e.number().nullable()})}))(Ce.z,Ax),{SUPPORTED_SET:Px}=(e=>({SUPPORTED_SET:new Set(e)}))(xx),{ApiCreditDimensionBaseSchema:Cx}=((e,t)=>({ApiCreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(Ce.z,rm),{refineGraduatedTiers:om}=(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:_x}=((e,t,n)=>({ApiFeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional().meta({description:"Default percentage markup for customers on this plan. Use -100 to make usage free."}),provider_markups:t.meta({description:"Per-provider markup percentages for customers on this plan."}),model_markups:n.meta({description:"Per-model markup overrides for customers on this plan."})})}))(Ce.z,Ox,mx),{isValidCurrencyCode:Ex}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(Px),{ApiCreditDimensionSchema:Rx}=((e,t,n,r)=>({ApiCreditDimensionSchema:e.union([t.extend({tier_behavior:e.literal("graduated"),tiers:e.array(n).min(1)}).strict().superRefine(r),t.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(Ce.z,Cx,Yp,om),{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')."})}))(Ce.z,Ex),{AdditionalCurrencyTierSchema:kx}=((e,t)=>({AdditionalCurrencyTierSchema:e.object({currency:t,amount:e.number().optional().meta({description:"Per-unit amount for this tier in this currency."}),flat_amount:e.number().optional().meta({description:"Flat amount for this tier in this currency, if the tier uses one."})}).refine(r=>r.amount!==void 0||r.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(Ce.z,am),{ApiCreditSchemaItemBaseSchema:sm}=((e,t,n,r)=>({ApiCreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string().nonempty().meta({description:"ID of the metered feature that draws from this credit system."}),billing_units:e.number().positive().optional().meta({description:"Number of metered-feature units priced together. Defaults to one when omitted."}),dimensions:e.record(t,n).optional().meta({description:"Named rates chosen by event properties. The most specific match sets the rate; with no match the item's own rate applies."}),multipliers:e.record(t,r).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(Ce.z,Ix,Rx,wx),{ApiFlatCreditSchemaItemSchema:jx}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(sm,Ce.z),{AdditionalCurrencyPriceSchema:Tx}=((e,t)=>({AdditionalCurrencyPriceSchema:e.object({currency:t,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(Ce.z,am),{AdditionalCurrencyTierArraySchema:Nx}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(Ce.z,kx,Jp,Zp),{ApiGraduatedCreditSchemaItemSchema:Dx}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(sm,Ce.z,Yp,om),{AdditionalCurrencyPriceArraySchema:cm}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(Ce.z,Tx,Jp,Zp),{ApiUsageTierWithCurrenciesSchema:Fx}=((e,t,n)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:n.optional().meta({description:"Per-currency amounts for this tier. Tier boundaries ('to') are shared across all currencies."})}).refine(i=>i.amount!==void 0||i.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(i=>({...i,amount:i.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:n.optional()}))}))(Ce.z,ax,Nx),{ApiCreditSchemaItemSchema:Mx}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(Ce.z,Dx,jx),{BasePriceParamsSchema:qx}=((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."})}))(bx,nx,Ce.z,cm),{PlanItemPriceParamsSchema:Bx}=((e,t,n,r,i,a,o)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(c=>c??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:t.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(i).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(a).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:o,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(Ce.z,cm,Fx,sx,Hp,Wp,Sx),{ApiFeatureOverrideSchema:Vx}=((e,t,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(t).optional().meta({description:"For credit system features: replaces the feature's credit_schema entirely for customers on this plan."}),markups:n.optional().meta({description:"For AI credit system features: replaces the feature's markup chain entirely for customers on this plan. An unset level means no markup at that level rather than inheriting the feature's."})})}))(Ce.z,Mx,_x),{InvoiceBasePriceParamsSchema:um}=((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()}))(qx,nm),{InvoiceItemPriceParamsSchema:Lx}=((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()}))(Bx,nm),{InvoiceLicenseQuantitySchema:Ux}=((e,t,n)=>({InvoiceLicenseQuantitySchema:e.object({license_plan_id:e.string().meta({description:"The license plan linked to the parent plan."}),quantity:e.number().int().nonnegative().meta({description:"Billable seats, exclusive of any included seats."}),customize:e.object({price:t.nullable().optional()}).strict().optional().meta({description:"Override the license's per-seat price on this invoice."}),feature_quantities:e.array(n).optional().meta({description:"Feature charges priced through the license plan."}),prorate:e.boolean().optional().meta({description:"Whether to prorate seat charges against period_start / period_end. Defaults to true."})}).strict()}))(Ce.z,um,im),{InvoiceCustomizeItemSchema:zx}=((e,t,n)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:t.optional().meta({description:"Pricing to use for this feature on this invoice."}),feature_override:n.pick({credit_schema:!0}).strict().optional().meta({description:"For credit-system features: a credit rate card to use when converting `usage` on this invoice."})}).strict()}))(Ce.z,Lx,Vx),{InvoiceCustomizeSchema:$x}=((e,t,n)=>({InvoiceCustomizeSchema:e.object({price:t.nullable().optional().meta({description:"Override the plan's base price for this invoice. Pass null or an amount of 0 to omit the base price line."}),items:e.array(n).optional().meta({description:"Override feature pricing for this invoice. Only pricing fields are accepted; grants, resets and rollovers are not part of an invoice."})}).strict().meta({title:"InvoiceCustomize",description:"Pricing overrides applied to this invoice only. The catalog and the customer's plan are not changed."})}))(Ce.z,um,zx),{InvoicePlanParamsSchema:Gx}=((e,t,n,r,i)=>({InvoicePlanParamsSchema:e.object({plan_id:e.string().meta({description:"The catalog plan (or variant) whose pricing to use."}),version:e.number().optional().meta({description:"Plan version. Defaults to the active version."}),customize:t.optional(),feature_quantities:e.array(n).optional(),license_quantities:e.array(r).optional(),discounts:e.array(i).optional().meta({description:"Discounts applied only to this plan's lines."}),prorate:e.boolean().optional().meta({description:"Whether to prorate the base price against period_start / period_end. Defaults to true."})}).strict()}))(Ce.z,$x,im,Ux,em),{CreateInvoiceParamsSchema:mi}=((e,t,n,r,i)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(t).optional(),custom_line_items:e.array(n).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(r).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:i.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start \u2192 period_end against one price interval starting at period_start."}),period_end:i.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(o=>o.period_start===void 0==(o.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(o=>o.period_start===void 0||o.period_end===void 0||o.period_end>o.period_start,{message:"period_end must be after period_start."})}))(Ce.z,Gx,gx,em,hx);var pm=p.z.strictObject({requestId:p.z.uuid(),predecessorOperationId:p.z.uuid().optional(),invoiceMode:Dr.optional(),entityId:p.z.uuid().optional(),billingSubscriptionId:p.z.uuid().optional(),newBillingSubscription:p.z.literal(!0).optional(),offerId:p.z.uuid().optional(),nativeOffer:pi.optional(),plans:p.z.array(p.z.strictObject({productVersionId:p.z.uuid(),seatQuantities:p.z.record(zo,p.z.number().int().min(0).max(1e4)).optional(),featureQuantities:p.z.record(p.z.uuid(),p.z.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100,"At most 100 feature quantities").optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Plan versions must be unique"),provider:p.z.enum(["stripe","apple","google","merchant"]),currency:be}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||["apple","google"].includes(e.provider)&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||["stripe","merchant"].includes(e.provider)&&!e.billingSubscriptionId,"A new billing subscription has no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),Mr=p.z.strictObject({operationId:p.z.uuid()}),Dt=p.z.number().int().min(0).max(1e8),Kx=p.z.strictObject({lineId:p.z.uuid(),productVersionId:p.z.uuid(),productName:p.z.string().min(1).max(80),interval:p.z.enum(["free","week","month","year","one_time"]),intervalCount:p.z.number().int().min(1).max(156).optional(),baseAmountMinor:Dt,seats:p.z.array(p.z.strictObject({key:zo,quantity:p.z.number().int().min(0).max(1e4),includedQuantity:p.z.number().int().min(0).max(1e4),maximumQuantity:p.z.number().int().min(0).max(1e4),unitAmountMinor:Dt})).max(20),prepaid:p.z.array(tp).max(100).optional(),catalogAmountMinor:Dt,trial:p.z.strictObject({days:p.z.number().int().min(1).max(730),cardRequired:p.z.boolean()}).nullable()}).refine(e=>new Set(e.seats.map(t=>t.key)).size===e.seats.length&&e.seats.every(t=>t.quantity>=t.includedQuantity&&t.quantity<=t.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((t,n)=>t+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((t,n)=>t+Qo({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"),mm=p.z.string().regex(/^[A-Za-z0-9_-]{1,200}$/),Hx=p.z.strictObject({id:mm,name:p.z.string().min(1).max(40),percent_off:p.z.number().gt(0).max(100).optional(),amount_off:p.z.number().int().positive().optional(),currency:p.z.string().regex(/^[a-z]{3}$/).optional(),duration:p.z.enum(["once","repeating","forever"]),duration_in_months:p.z.number().int().min(1).max(36).optional()}).refine(e=>e.percent_off===void 0!=(e.amount_off===void 0)&&e.amount_off===void 0==(e.currency===void 0)&&e.duration==="repeating"==(e.duration_in_months!==void 0),"A Stripe coupon has one percentage or amount and months only when repeating"),Qx=p.z.strictObject({subscriptionId:p.z.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:p.z.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:p.z.array(p.z.strictObject({id:p.z.string(),price_id:p.z.string(),quantity:p.z.number().int().nonnegative(),discounts:p.z.array(p.z.strictObject({id:p.z.string(),coupon:p.z.string(),start:p.z.number(),end:p.z.number().nullable()})).optional()})).min(1).max(100),prorationDate:p.z.number().int().nonnegative(),amountMinor:p.z.number().int().positive(),periodStartMs:p.z.number(),periodEndMs:p.z.number()}),fm=p.z.strictObject({invoiceMode:Dr.optional(),append:Qx.optional(),provider:p.z.literal("stripe"),executor:p.z.enum(["indiana","merchant"]),accountId:p.z.string().regex(/^acct_[A-Za-z0-9]+$/),mode:p.z.enum(["payment","subscription"]),lineItems:p.z.array(p.z.strictObject({price:p.z.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:p.z.number().int().min(1).max(1e4),priceId:p.z.uuid(),productName:p.z.string().min(1).max(80),amountMinor:p.z.number().int().min(0).max(1e8),currency:p.z.string().regex(/^[a-z]{3}$/),interval:p.z.enum(["week","month","year","one_off"]),intervalCount:p.z.number().int().min(1).max(52),slot:p.z.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:p.z.strictObject({mode:p.z.enum(["graduated","volume"]),tiers:p.z.array(p.z.strictObject({upTo:p.z.number().int().min(1).max(1e6).nullable(),unitAmountMinor:p.z.number().int().min(0).max(1e8),flatAmountMinor:p.z.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:p.z.array(p.z.strictObject({coupon:mm,terms:Hx})).max(1),trialPeriodDays:p.z.number().int().min(1).max(730).nullable(),metadata:p.z.strictObject({grooveCheckoutId:p.z.uuid(),grooveCustomerId:p.z.uuid()}),expiresAt:p.z.iso.datetime({offset:!0})}),fi=p.z.strictObject({operationId:p.z.uuid(),entityId:p.z.uuid().nullable(),billingSubscriptionId:p.z.uuid().nullable(),discount:p.z.strictObject({offerId:p.z.uuid(),couponId:p.z.uuid(),discount:Xn,duration:on,amountMinor:Dt,allocations:p.z.array(p.z.strictObject({productVersionId:p.z.uuid(),amountMinor:Dt})).min(1).max(20),expiresAt:p.z.iso.datetime({offset:!0})}).nullable(),charge:p.z.strictObject({effectiveAt:p.z.iso.datetime({offset:!0}),periodEndsAt:p.z.iso.datetime({offset:!0}),debitMinor:Dt,discountMinor:Dt,taxMinor:Dt,totalMinor:Dt}).nullable(),expiresAt:p.z.iso.datetime({offset:!0}),provider:p.z.enum(["stripe","apple","google","merchant"]),nativeOffer:pi.optional(),currency:be,lines:p.z.array(Kx).min(1).max(20),catalogAmountMinor:Dt,automaticTax:p.z.boolean(),execution:p.z.union([fm,qo]).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"),gi=p.z.strictObject({operationId:p.z.uuid(),orderId:p.z.uuid(),append:p.z.boolean().optional(),invoiceMode:p.z.boolean().optional(),status:p.z.enum(["pending","complete","cancelled","failed"]),executor:p.z.enum(["indiana","merchant"]),checkoutUrl:p.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:p.z.union([fm,qo]).nullable(),currency:be,catalogAmountMinor:Dt,taxMinor:Dt,totalMinor:p.z.number().int().min(0).max(2e8).nullable(),quoteFinalized:p.z.boolean(),nativePurchase:Sc.nullable(),confirmedAt:p.z.iso.datetime({offset:!0}).nullable().optional(),quote:fi.optional(),merchantExecution:Ir.nullable().optional(),problem:Di.nullable().optional(),authority:Uo.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"),va=p.z.strictObject({enabled:p.z.literal(!0),featureIds:p.z.array(p.z.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),gm=p.z.strictObject({requestId:p.z.uuid(),invoiceMode:Dr.optional(),membershipId:p.z.uuid(),carryOverBalances:va.optional(),carryOverUsages:va.optional(),membershipIds:p.z.array(p.z.uuid()).min(1).max(20).optional(),prorationBehavior:p.z.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:p.z.enum(["immediate","renewal","store"]),change:p.z.discriminatedUnion("type",[p.z.strictObject({type:p.z.literal("plan"),productVersionId:p.z.uuid()}),p.z.strictObject({type:p.z.literal("seats"),licenseKey:zo,quantity:p.z.number().int().min(0).max(1e4)}),p.z.strictObject({type:p.z.literal("quantity"),internal_feature_id:p.z.uuid(),quantity:p.z.number().int().min(0).max(1e4)}),p.z.strictObject({type:p.z.literal("cancel")}),p.z.strictObject({type:p.z.literal("uncancel")}),p.z.strictObject({type:p.z.literal("billing_cycle"),billingCycleAnchor:p.z.union([p.z.literal("now"),p.z.number().int().positive().max(0xe677d21fdbff)])})])}).refine(e=>e.timing!=="store"||e.change.type==="plan","Store timing applies to a native plan replacement").refine(e=>e.change.type!=="billing_cycle"||e.timing===(e.change.billingCycleAnchor==="now"?"immediate":"renewal"),"Use immediate for now and renewal for a future millisecond anchor").refine(e=>!e.membershipIds||["cancel","uncancel"].includes(e.change.type)&&e.membershipIds.includes(e.membershipId)&&new Set(e.membershipIds).size===e.membershipIds.length,"Grouped actions require unique cancel/uncancel targets including the primary membership").refine(e=>!e.carryOverBalances&&!e.carryOverUsages||e.change.type==="plan"&&e.timing==="immediate","Carry applies only to immediate upgrades").refine(e=>!e.prorationBehavior||e.change.type==="quantity","prorationBehavior applies to prepaid quantity changes"),Ia=p.z.string().regex(/^price_[A-Za-z0-9]+$/),lm=p.z.strictObject({grooveUpdateId:p.z.uuid(),grooveCustomerId:p.z.uuid()}),dm=p.z.strictObject({price:Ia.nullable(),priceId:p.z.uuid().optional(),quantity:p.z.number().int().min(0).max(1e4)}),hm=p.z.strictObject({provider:p.z.literal("stripe"),invoiceMode:Dr.optional(),executor:p.z.enum(["indiana","merchant"]),accountId:p.z.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:p.z.string().regex(/^sub_[A-Za-z0-9]+$/),action:p.z.enum(["update","cancel","schedule","release"]),update:p.z.strictObject({items:p.z.array(dm).max(20),remove:p.z.array(Ia).max(20),restoreItems:p.z.array(p.z.strictObject({price:Ia,quantity:p.z.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:p.z.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:p.z.number().int().positive().optional(),paymentBehavior:p.z.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:p.z.boolean().optional(),clearCancelAt:p.z.literal(!0).optional(),billingCycleAnchorNow:p.z.literal(!0).optional(),metadata:lm}).nullable(),cancel:p.z.strictObject({prorate:p.z.literal(!1),invoiceNow:p.z.literal(!1)}).nullable(),schedule:p.z.strictObject({currentItems:p.z.array(p.z.strictObject({price:Ia,quantity:p.z.number().int().min(0).max(1e4)})).max(20),nextItems:p.z.array(dm).min(1).max(20),switchAt:p.z.number().int().positive(),interval:p.z.enum(["week","month","year"]),intervalCount:p.z.number().int().min(1).max(52),resetBillingCycleAnchor:p.z.literal(!0).optional(),metadata:lm}).nullable(),release:p.z.strictObject({schedule:p.z.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:p.z.iso.datetime({offset:!0})}).refine(e=>["update","cancel","schedule","release"].every(t=>e[t]!==null==(e.action===t))&&(e.executor==="indiana"||[...e.update?.items??[],...e.schedule?.nextItems??[]].every(t=>t.price!==null)),"Stripe update execution carries exactly its action, with bound Prices for the merchant"),wa=p.z.strictObject({carryOverBalances:va.optional(),carryOverUsages:va.optional(),operationId:p.z.uuid(),membershipId:p.z.uuid(),productVersionId:p.z.uuid(),timing:p.z.enum(["immediate","renewal"]),effectiveAt:p.z.iso.datetime({offset:!0}),expiresAt:p.z.iso.datetime({offset:!0}),currency:be,creditMinor:Dt,debitMinor:Dt,discountMinor:Dt,taxMinor:Dt,totalMinor:Dt,retainedProductVersionIds:p.z.array(p.z.uuid()).max(19),execution:p.z.union([hm,Bo])}),Jx=p.z.strictObject({operationId:p.z.uuid(),invoiceMode:p.z.boolean().optional(),membershipId:p.z.uuid(),productVersionId:p.z.uuid(),status:p.z.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:p.z.enum(["immediate","renewal"]),effectiveAt:p.z.iso.datetime({offset:!0}),checkoutUrl:p.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:p.z.enum(["indiana","merchant"]),execution:p.z.union([hm,Bo]).nullable(),confirmedAt:p.z.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Ir.nullable().optional(),problem:Di.nullable().optional(),quote:wa.optional(),authority:Uo.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),Zx=p.z.strictObject({operationId:p.z.uuid(),membershipId:p.z.uuid(),productVersionId:p.z.uuid(),timing:p.z.literal("store"),effectiveAt:p.z.null(),expiresAt:p.z.iso.datetime({offset:!0}),currency:be,creditMinor:p.z.null(),debitMinor:p.z.null(),discountMinor:p.z.null(),taxMinor:p.z.null(),totalMinor:p.z.null(),retainedProductVersionIds:p.z.array(p.z.uuid()).max(19),store:p.z.strictObject({provider:p.z.enum(["apple","google"]),productId:p.z.string().min(1).max(255),catalogAmountMinor:Dt,policy:p.z.enum(["apple_store","google_full_price"])})}),Wx=p.z.strictObject({operationId:p.z.uuid(),membershipId:p.z.uuid(),productVersionId:p.z.uuid(),status:p.z.enum(["prepared","pending","effective","cancelled","failed"]),timing:p.z.literal("store"),effectiveAt:p.z.iso.datetime({offset:!0}).nullable(),checkoutUrl:p.z.null(),nativePurchase:Sc.nullable()}),Am=p.z.union([wa,Zx]),vc=p.z.union([Jx,Wx]),oo=p.z.number().int().positive().max(2e8),Fr=p.z.number().int().min(0).max(2e8),ym=p.z.strictObject({requestId:p.z.uuid(),invoiceId:p.z.uuid(),mode:p.z.enum(["full","partial"]),amountMinor:oo.optional(),entitlementAction:p.z.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),bm=p.z.strictObject({provider:p.z.literal("stripe"),executor:p.z.enum(["indiana","merchant"]),accountId:p.z.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:p.z.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:oo,currency:p.z.string().regex(/^[a-z]{3}$/),metadata:p.z.strictObject({indianaRefundId:p.z.uuid()}),idempotencyKey:p.z.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:p.z.array(p.z.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),wc=p.z.strictObject({operationId:p.z.uuid(),invoiceId:p.z.uuid(),providerInvoiceId:p.z.string().min(1).max(200),currency:be,paidMinor:Fr,refundedMinor:Fr,pendingMinor:Fr,amountMinor:oo,mode:p.z.enum(["full","partial"]),entitlementAction:p.z.enum(["retain","revoke"]),revokes:p.z.strictObject({customerProductIds:p.z.array(p.z.uuid()).max(100),subscriptionIds:p.z.array(p.z.string().min(1).max(200)).max(20)}),execution:p.z.union([bm,Vo]),expiresAt:p.z.iso.datetime({offset:!0})}).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&(e.execution.provider==="merchant"?e.execution.merchantInvoiceId===e.providerInvoiceId&&e.execution.operationId===e.operationId&&e.execution.currency===e.currency:e.execution.invoice===e.providerInvoiceId&&e.execution.metadata.indianaRefundId===e.operationId&&e.execution.currency===e.currency.toLowerCase())&&(e.entitlementAction==="revoke"||e.revokes.customerProductIds.length===0&&e.revokes.subscriptionIds.length===0),"Refund quote must stay within the refundable amount and match its execution"),Oa=p.z.strictObject({operationId:p.z.uuid(),invoiceId:p.z.uuid(),providerInvoiceId:p.z.string().min(1).max(200),status:p.z.enum(["quoted","pending","succeeded","failed","expired"]),executor:p.z.enum(["indiana","merchant"]),currency:be,amountMinor:oo,mode:p.z.enum(["full","partial"]),entitlementAction:p.z.enum(["retain","revoke"]),refundId:p.z.string().min(1).max(200).nullable(),quote:wc.optional(),execution:p.z.union([bm,Vo]).nullable(),confirmedAt:p.z.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Ir.nullable().optional(),problem:Di.nullable().optional(),authority:Uo.optional(),failureReason:p.z.string().min(1).max(200).nullable(),createdAt:p.z.iso.datetime({offset:!0}),completedAt:p.z.iso.datetime({offset:!0}).nullable()}).refine(e=>(e.execution===null||e.executor==="merchant"&&e.status==="quoted")&&(e.status!=="succeeded"||e.refundId!==null),"Only quoted record-only refunds carry instructions; a succeeded refund names its Stripe refund"),BP=p.z.strictObject({invoiceId:p.z.uuid(),currency:be,paidMinor:Fr,refundedMinor:Fr,pendingMinor:Fr,refundableMinor:Fr,executor:p.z.enum(["indiana","merchant"]).nullable(),canRefund:p.z.boolean(),operations:p.z.array(Oa).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),VP=p.z.strictObject({requestId:p.z.uuid(),mode:p.z.enum(["full","partial"]),amountMinor:oo.optional(),entitlementAction:p.z.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount");var xm=nt.z.strictObject({requestId:nt.z.uuid(),targets:nt.z.array(nt.z.strictObject({membershipId:nt.z.uuid(),action:nt.z.enum(["cancel","uncancel"]),timing:nt.z.enum(["immediate","renewal"])}).refine(e=>e.action!=="uncancel"||e.timing==="immediate","Restoration is immediate")).min(1).max(100)}).refine(e=>new Set(e.targets.map(t=>t.membershipId)).size===e.targets.length,"Duplicate batch target"),Pa=nt.z.strictObject({batchId:nt.z.uuid()}),Yx=nt.z.strictObject({operationId:nt.z.uuid(),membershipIds:nt.z.array(nt.z.uuid()).min(1).max(20),provider:nt.z.enum(["stripe","apple","google"]),action:nt.z.enum(["cancel","uncancel"]),timing:nt.z.enum(["immediate","renewal"]),status:nt.z.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:wa.nullable(),managementUrl:nt.z.url().nullable(),failureCode:nt.z.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),ao=nt.z.strictObject({batchId:nt.z.uuid(),ready:nt.z.boolean(),status:nt.z.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:nt.z.iso.datetime({offset:!0}),acceptedAt:nt.z.iso.datetime({offset:!0}).nullable(),groups:nt.z.array(Yx).min(1).max(100)});var Re=require("zod"),Xx=Re.z.string().trim().min(1).max(240),Oc={requestId:Re.z.uuid(),reason:Xx},Ca=Re.z.discriminatedUnion("action",[Re.z.strictObject({...Oc,action:Re.z.literal("start"),productVersionId:Re.z.uuid(),entityId:Re.z.uuid().optional(),days:Re.z.number().int().min(1).max(730).optional()}),Re.z.strictObject({...Oc,action:Re.z.literal("extend"),membershipId:Re.z.uuid(),days:Re.z.number().int().min(1).max(730)}),Re.z.strictObject({...Oc,action:Re.z.literal("end"),membershipId:Re.z.uuid()})]),Sm=Re.z.strictObject({operationId:Re.z.uuid()}),Im=Re.z.iso.datetime({offset:!0}),eS=Re.z.strictObject({provider:Re.z.literal("stripe"),executor:Re.z.enum(["indiana","merchant"]),accountId:Re.z.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:Re.z.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:Re.z.union([Re.z.literal("now"),Im]),prorationBehavior:Re.z.literal("none")}),Pc=Re.z.strictObject({operationId:Re.z.uuid(),action:Re.z.enum(["start","extend","end"]),status:Re.z.enum(["pending","effective"]),managedBy:Re.z.enum(["indiana","stripe"]),membershipIds:Re.z.array(Re.z.uuid()).min(1).max(20),endsAt:Im.nullable(),execution:eS.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"),$P=Re.z.strictObject({groupId:Re.z.uuid(),productVersionId:Re.z.uuid(),enabled:Re.z.boolean()});var He=require("zod");var vm=He.z.strictObject({requestId:He.z.uuid(),currency:be,makeDefault:He.z.boolean()}),wm=He.z.strictObject({setupId:He.z.uuid()}),tS=He.z.strictObject({provider:He.z.literal("stripe"),executor:He.z.literal("merchant"),accountId:He.z.string().regex(/^acct_[A-Za-z0-9]+$/),mode:He.z.literal("setup"),currency:He.z.string().regex(/^[a-z]{3}$/),customer:He.z.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:He.z.uuid(),metadata:He.z.strictObject({grooveProjectId:He.z.uuid(),grooveEnvironmentId:He.z.uuid(),grooveCustomerId:He.z.uuid(),groovePaymentSetupId:He.z.uuid()}),setDefaultPaymentMethod:He.z.boolean(),expiresAt:He.z.iso.datetime({offset:!0})}),Cc=He.z.strictObject({id:He.z.uuid(),provider:He.z.literal("stripe"),status:He.z.enum(["prepared","complete","expired"]),currency:be,makeDefault:He.z.boolean(),url:He.z.url().nullable(),createdAt:He.z.iso.datetime({offset:!0}),expiresAt:He.z.iso.datetime({offset:!0}),completedAt:He.z.iso.datetime({offset:!0}).nullable(),execution:tS.nullable()});var Rt=require("zod"),Om=Rt.z.union([Rt.z.string(),Rt.z.number(),Rt.z.boolean(),Rt.z.null()]),Pm=Rt.z.strictObject({customerId:Rt.z.uuid()}),Cm=Rt.z.strictObject({customerId:Rt.z.uuid(),provider:Rt.z.literal("stripe"),checkedAt:Rt.z.iso.datetime({offset:!0}),status:Rt.z.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Rt.z.number().int().nonnegative(),differences:Rt.z.array(Rt.z.strictObject({subscriptionId:Rt.z.string().startsWith("sub_"),itemId:Rt.z.string().nullable(),field:Rt.z.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Om,actual:Om})).max(1e4)});var Ie=require("zod");var _a=Ie.z.iso.datetime({offset:!0}),Ea=Ie.z.strictObject({createdAt:_a,id:Ie.z.uuid()}),Ra=Ie.z.strictObject({customerId:Ie.z.uuid().optional(),entityId:Ie.z.uuid().optional(),productId:Ie.z.string().min(1).max(256).optional(),provider:Ie.z.enum(["stripe","apple","google","merchant","free"]).optional(),status:Ie.z.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:Ea.optional(),limit:Ie.z.number().int().min(1).max(100).optional()}),_c={id:Ie.z.uuid(),customerId:Ie.z.uuid(),entityId:Ie.z.uuid().nullable(),productId:Ie.z.string().min(1).max(256),productVersionId:Ie.z.uuid(),name:Ie.z.string().min(1).max(120),provider:Ie.z.enum(["stripe","apple","google","merchant","free"]),createdAt:_a},nS=Ie.z.strictObject({..._c,status:Ie.z.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:Ie.z.boolean(),billingSubscriptionId:Ie.z.uuid().nullable()}),rS=Ie.z.strictObject({..._c,status:Ie.z.enum(["active","ended","refunded"]),orderId:Ie.z.uuid().nullable(),transactionId:Ie.z.uuid().nullable(),currency:be.nullable(),amountMinor:Ie.z.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),iS=Ie.z.strictObject({..._c,status:Ie.z.enum(["blocked","resolved"]),conflict:Ie.z.strictObject({detectedAt:_a,blockingMembershipIds:Ie.z.array(Ie.z.uuid()).min(1).max(100),transactionId:Ie.z.uuid()}),resolvedAt:_a.nullable()}),_m=Ra.extend({status:Ie.z.enum(["blocked","resolved"]).optional()}),Em=Ie.z.strictObject({customerId:Ie.z.uuid(),orderId:Ie.z.uuid()}),Rm=Ie.z.strictObject({orderId:Ie.z.uuid(),status:Ie.z.enum(["blocked","resolved"])}),km=Ie.z.strictObject({items:Ie.z.array(nS).max(100),nextCursor:Ea.nullable()}),jm=Ie.z.strictObject({items:Ie.z.array(rS).max(100),nextCursor:Ea.nullable()}),Tm=Ie.z.strictObject({items:Ie.z.array(iS).max(100),nextCursor:Ea.nullable()});var Xe=require("zod");var Nm=Xe.z.union([Xe.z.strictObject({intent:Xe.z.literal("read"),requestId:Xe.z.uuid(),purchaseIntentId:Xe.z.uuid()}),Xe.z.strictObject({requestId:Xe.z.uuid(),provider:Xe.z.literal("apple"),purchaseIntentId:Xe.z.uuid(),productId:Xe.z.string().min(1).max(255).optional(),signedTransaction:Xe.z.string().min(1).max(131072)}),Xe.z.strictObject({requestId:Xe.z.uuid(),provider:Xe.z.literal("google"),purchaseIntentId:Xe.z.uuid(),productId:Xe.z.string().min(1).max(255).optional(),purchaseToken:Xe.z.string().min(1).max(16384)})]),Dm=Xe.z.strictObject({requestId:Xe.z.uuid(),orderId:Xe.z.uuid(),purchaseIntentId:Xe.z.uuid(),status:Xe.z.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:be,refunded:Xe.z.boolean(),completion:Xe.z.strictObject({transactionIds:Xe.z.array(Xe.z.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:Xe.z.boolean()}).nullable()});var L=require("zod"),Rc=L.z.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),oS=L.z.record(L.z.string(),L.z.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),aS=3,so=20,sS=aS*so,Ec=L.z.strictObject({type:L.z.literal("product"),productId:Rc}),Fm={type:L.z.literal("group"),key:L.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:L.z.string().trim().min(1).max(80)},cS=L.z.discriminatedUnion("type",[Ec,L.z.strictObject({...Fm,items:L.z.array(Ec).max(so)})]),uS=L.z.discriminatedUnion("type",[Ec,L.z.strictObject({...Fm,items:L.z.array(cS).max(so)})]),lS=L.z.array(uS).max(so).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>so||i>sS)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function kc(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:kc(t))}var hi=L.z.strictObject({lookupKey:L.z.string().trim().min(1).max(200),displayName:L.z.string().trim().min(1).max(1500),items:lS,metadata:oS}),dS=L.z.strictObject({product:L.z.record(L.z.string(),L.z.json()),prices:L.z.array(L.z.record(L.z.string(),L.z.json())),entitlements:L.z.array(L.z.record(L.z.string(),L.z.json())),freeTrials:L.z.array(L.z.record(L.z.string(),L.z.json())),licenses:L.z.array(L.z.record(L.z.string(),L.z.json()))}),Mm=hi.extend({id:L.z.uuid(),projectId:L.z.uuid(),environmentId:L.z.uuid(),state:L.z.enum(["active","archived"]),isCurrent:L.z.boolean(),revision:L.z.number().int().nonnegative(),publishedVersionId:L.z.uuid().nullable(),createdAt:L.z.iso.datetime({offset:!0})}).superRefine((e,t)=>{e.isCurrent&&(e.state!=="active"||!e.publishedVersionId)&&t.addIssue({code:"custom",message:"Current Offering must be active and published"})}),qm=L.z.strictObject({id:L.z.uuid(),offeringId:L.z.uuid(),projectId:L.z.uuid(),environmentId:L.z.uuid(),version:L.z.number().int().positive(),document:hi,productEvidence:L.z.record(Rc,dS),createdAt:L.z.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=kc(e.document);(!n.length||fS(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"})}),pS=L.z.strictObject({rows:L.z.array(Mm).max(200),versions:L.z.array(qm).max(500)}),XP=L.z.discriminatedUnion("action",[L.z.strictObject({action:L.z.literal("create"),document:hi}),L.z.strictObject({action:L.z.literal("save"),id:L.z.uuid(),revision:L.z.number().int().nonnegative(),document:hi}),L.z.strictObject({action:L.z.enum(["publish","set_current","archive","restore"]),id:L.z.uuid(),revision:L.z.number().int().nonnegative()})]),eC=L.z.strictObject({record:Mm,version:qm.nullable()}),Bm=L.z.discriminatedUnion("type",[L.z.strictObject({type:L.z.literal("current")}),L.z.strictObject({type:L.z.literal("id"),id:L.z.uuid()}),L.z.strictObject({type:L.z.literal("lookup_key"),lookupKey:L.z.string().min(1).max(200)}),L.z.strictObject({type:L.z.literal("version"),versionId:L.z.uuid()})]),mS=L.z.strictObject({internalId:Rc,id:L.z.string(),name:L.z.string().nullable(),version:L.z.number().int().positive(),archived:L.z.boolean()}),tC=pS.extend({products:L.z.array(mS).max(500),pagination:L.z.strictObject({rows:L.z.string().nullable(),versions:L.z.string().nullable(),products:L.z.string().nullable()}).optional()});function fS(e){let t=[];kc(e).length||t.push("Select at least one Product before publishing");function n(r){for(let i of r)i.type==="group"&&(i.items.length||t.push("Every published group requires a Product"),n(i.items))}return n(e.items),t}var co=require("zod");var Vm=co.z.strictObject({id:co.z.uuid(),offeringId:co.z.uuid(),version:co.z.number().int().positive(),document:hi});var xt=require("zod");var fe=require("zod");var qr=require("zod");var ka=qr.z.strictObject({items:qr.z.array(qr.z.strictObject({productVersionId:qr.z.string().min(1).max(200),label:qr.z.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:qr.z.string().min(1).max(200).nullable(),grouping:ga.optional()});function Lm(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 bt=require("zod"),gS=bt.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ja=bt.z.discriminatedUnion("type",[bt.z.object({type:bt.z.literal("fixed"),productVersionId:bt.z.string().min(1).max(200)}).strict(),bt.z.object({type:bt.z.literal("picker"),pickerId:gS,allowedProductVersionIds:bt.z.array(bt.z.string().min(1).max(200)).min(1).max(20)}).strict().refine(e=>new Set(e.allowedProductVersionIds).size===e.allowedProductVersionIds.length,"Product choices must be unique")]),Kn=bt.z.discriminatedUnion("type",[bt.z.object({type:bt.z.literal("modal"),size:bt.z.enum(["sm","md","lg"])}).strict(),bt.z.object({type:bt.z.literal("sheet"),size:bt.z.enum(["sm","md","lg"])}).strict(),bt.z.object({type:bt.z.literal("fullscreen")}).strict(),bt.z.object({type:bt.z.literal("inline")}).strict()]);var jc=fe.z.discriminatedUnion("type",[fe.z.strictObject({type:fe.z.literal("event"),event:fe.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),fe.z.strictObject({type:fe.z.literal("open_url"),url:fe.z.url().refine(e=>new URL(e).protocol==="https:")})]),hS=sn,AS=fe.z.discriminatedUnion("type",[fe.z.object({type:fe.z.literal("checkout"),product:ja}).strict(),fe.z.object({type:fe.z.literal("close")}).strict(),fe.z.object({type:fe.z.literal("action"),action:jc}).strict()]),Ai=fe.z.object({schemaVersion:fe.z.literal(3),kind:fe.z.literal("paywall"),name:fe.z.string().trim().min(1).max(80),presentation:Kn,requirement:er.optional(),products:ka,offeringVersionId:fe.z.uuid().nullable(),offeringId:fe.z.uuid(),screen:hS,buttons:fe.z.record(fe.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),AS)}).strict(),fC=Ai.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 bS(e))t.addIssue({code:"custom",message:r});for(let r of yS(e))t.addIssue({code:"custom",message:r});tr(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 yS(e){let t=e.products.items.map(a=>a.productVersionId),n=kp(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&&(!ha(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 bS(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),Gn(s.root,c=>{let u=c.type==="button"?c.action:c.type==="stack"?c.purchaseAction:void 0;if(u){let l=e.screen.actions.find(m=>m.id===u);l?.type==="navigate"&&r.get(s.id).push(l.pageId);let f=e.buttons[u];s.id!==n.id&&f&&f.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 Um=fe.z.object({id:fe.z.uuid(),projectId:fe.z.uuid(),environmentId:fe.z.uuid(),revision:fe.z.number().int().nonnegative(),state:fe.z.enum(["active","archived"]),publishedVersionId:fe.z.uuid().nullable(),updatedAt:fe.z.iso.datetime({offset:!0}),draft:Ai}).strict(),gC=fe.z.object({rows:fe.z.array(Um).max(200),nextCursor:fe.z.uuid().nullable()}).strict(),hC=Um.omit({draft:!0}).extend({name:fe.z.string(),productCount:fe.z.number().int().nonnegative()}).strict(),AC=fe.z.discriminatedUnion("action",[fe.z.object({action:fe.z.literal("save"),id:fe.z.uuid().nullable(),revision:fe.z.number().int().nonnegative(),document:Ai}).strict(),fe.z.object({action:fe.z.enum(["publish","archive"]),id:fe.z.uuid(),revision:fe.z.number().int().nonnegative()}).strict()]),yC=fe.z.object({paywalls:fe.z.array(fe.z.object({id:fe.z.uuid(),paywallId:fe.z.uuid(),version:fe.z.number().int().positive(),name:fe.z.string().min(1).max(80),presentation:Kn,buttons:Ai.shape.buttons}).strict()).max(500),limited:fe.z.boolean()}).strict();var _e=require("zod");var qt=require("zod");var yi=qt.z.string().regex(/^[a-f0-9]{64}$/),xS=ma.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),zm=qt.z.strictObject({couponDigests:qt.z.record(qt.z.uuid(),yi),variables:qt.z.record(xn,qt.z.record(qt.z.uuid(),qt.z.partialRecord(qt.z.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),qt.z.string()))),locales:qt.z.record(xn,si.extend({nodes:qt.z.record(qt.z.string(),qt.z.strictObject({base:xS})),plans:qt.z.object({}).strict(),pickers:qt.z.object({}).strict()}).omit({paywall:!0}))});var Be=require("zod");var uo=require("zod"),Tc=uo.z.strictObject({eventsEnabled:uo.z.boolean(),experimentViewsEnabled:uo.z.boolean(),featureUsageEnabled:uo.z.boolean()}),vC=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function $m(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}var $=require("zod");var Nc=$.z.tuple([$.z.number().min(0).max(1),$.z.number().min(0).max(1)]).refine(([e,t])=>e<=t),SS=$.z.strictObject({attribute:$.z.string().optional(),seed:$.z.string(),hashVersion:$.z.literal(2),ranges:$.z.array(Nc).max(100)}),IS=$.z.strictObject({id:$.z.string().min(1).max(255),condition:Jt,gate:$.z.boolean().optional()}),vS=$.z.strictObject({key:$.z.string().optional(),name:$.z.string().optional(),passthrough:$.z.boolean().optional()}),Gm={condition:Jt.optional(),parentConditions:$.z.array(IS).max(100).optional(),weights:$.z.array($.z.number().min(0).max(1)).max(20).optional(),coverage:$.z.number().min(0).max(1).optional(),hashAttribute:$.z.string().optional(),fallbackAttribute:$.z.string().optional(),hashVersion:$.z.literal(2).optional(),disableStickyBucketing:$.z.boolean().optional(),bucketVersion:$.z.number().int().nonnegative().optional(),minBucketVersion:$.z.number().int().nonnegative().optional(),filters:$.z.array(SS).max(100).optional(),ranges:$.z.array(Nc).max(20).optional(),meta:$.z.array(vS).max(20).optional(),seed:$.z.string().optional(),name:$.z.string().optional(),phase:$.z.string().optional()},bi=$.z.strictObject({...Gm,key:$.z.string().min(1).max(255),variations:$.z.tuple([Se,Se]).rest(Se).refine(e=>e.length<=20),urlPatterns:$.z.array($.z.strictObject({include:$.z.boolean(),type:$.z.enum(["regex","simple"]),pattern:$.z.string()})).max(100).optional(),force:$.z.number().int().nonnegative().optional(),active:$.z.boolean().optional(),persistQueryString:$.z.boolean().optional()}),Dc=$.z.strictObject({value:Se,variationId:$.z.number().int(),key:$.z.string(),name:$.z.string().optional(),bucket:$.z.number().optional(),passthrough:$.z.boolean().optional(),inExperiment:$.z.boolean(),hashUsed:$.z.boolean().optional(),hashAttribute:$.z.string(),hashValue:$.z.string(),featureId:$.z.string().nullable(),stickyBucketUsed:$.z.boolean().optional()}),wS=$.z.strictObject({...Gm,id:$.z.string().max(255).optional(),force:Se.optional(),variations:$.z.array(Se).min(2).max(20).optional(),key:$.z.string().optional(),range:Nc.optional(),tracks:$.z.array($.z.strictObject({experiment:bi,result:Dc})).max(100).optional()}),OS=$.z.strictObject({defaultValue:Se.optional(),rules:$.z.array(wS).max(500).optional()}),lo=$.z.record($.z.string(),$.z.union([$.z.strictObject({type:$.z.literal("hashed"),attributeKey:$.z.string(),values:$.z.array($.z.string().regex(/^[a-f0-9]{64}$/))}),$.z.strictObject({type:$.z.literal("list"),attributeKey:$.z.string(),values:$.z.array($.z.union([$.z.string(),$.z.number()]))}),$.z.strictObject({type:$.z.literal("condition"),condition:Jt})])),gn=$.z.strictObject({scope:Ne,generation:$.z.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:$.z.iso.datetime({offset:!0}),expiresAt:$.z.iso.datetime({offset:!0}).nullable(),features:$.z.record($.z.string(),OS),savedGroups:lo,experiments:$.z.record($.z.uuid(),bi)});var po=gn.extend({analyticsConfig:Tc,remoteFeatures:Be.z.array(Be.z.string().min(1).max(255)).max(500)}),Fc=po.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"})}),Km=Be.z.strictObject({attributes:Ot,features:Be.z.array(Be.z.string().min(1).max(255)).max(500).optional(),customerId:Be.z.uuid().optional()}),PS=Be.z.strictObject({value:Se,source:Be.z.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:Be.z.boolean(),off:Be.z.boolean(),ruleId:Be.z.string(),experimentResult:Dc.optional()}),Ta=Be.z.strictObject({generation:gn.shape.generation,evaluatedAt:gn.shape.evaluatedAt,expiresAt:gn.shape.expiresAt,features:Be.z.record(Be.z.string(),PS),merchandiseContext:Be.z.strictObject({merchandiseId:Be.z.uuid(),merchandise:Ot}).optional()}),Hm=Be.z.strictObject({customerId:Be.z.uuid().optional(),events:Be.z.array(Be.z.strictObject({eventUuid:Be.z.uuid(),timestamp:Be.z.iso.datetime({offset:!0}),name:Be.z.string().min(1).max(255),merchandise:Ed.optional(),properties:Be.z.record(Be.z.string(),Se).default({}),deviceId:Be.z.string().min(1).max(255).optional(),sessionId:Be.z.string().min(1).max(255).optional()})).min(1).max(100)}),Qm=Be.z.strictObject({inserted:Be.z.number().int().nonnegative(),duplicates:Be.z.number().int().nonnegative(),rejected:Be.z.number().int().nonnegative(),skipped:Be.z.number().int().nonnegative(),analyticsConfig:Tc});var U=require("zod");var Jm=require("zod"),Zm=Jm.z.enum(["funnel-run/1","funnel-process/1"]),Wm="funnel-process/1";function Mc(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(Aa(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 Ym(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>Ym(t)??[])}}function CS(e){let t=e.pages.map(i=>{let a=Ym(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(Aa({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 Xm(e,t=[]){let n=sn.parse(structuredClone(CS(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=Mc(n,t);if(i.length)throw new Error(i.join("; "));return n}var H=require("zod");var M=require("zod");var ut=require("zod"),Na=ut.z.strictObject({schemaVersion:ut.z.literal(1),renderKey:ut.z.string().min(1).max(256),routeTemplate:ut.z.string().startsWith("/").max(2048),selectors:ut.z.array(ut.z.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:ut.z.array(ut.z.number().int().min(0)).min(1),absent:ut.z.array(ut.z.number().int().min(0))}).superRefine((e,t)=>{let n=[...e.present,...e.absent];(new Set(e.selectors).size!==e.selectors.length||new Set(n).size!==n.length||n.length!==e.selectors.length||n.some(r=>r>=e.selectors.length))&&t.addIssue({code:"custom",message:"Incomplete or ambiguous render signature"})}),ef=ut.z.strictObject({renderKey:ut.z.string().min(1).max(256),routeKey:ut.z.string().min(1).max(256),stateKey:ut.z.string().min(1).max(256),documentKey:ut.z.string().min(1).max(256),documentHash:ut.z.string().regex(/^[a-f0-9]{64}$/),compositionKey:ut.z.string().min(1).max(256),entryMode:ut.z.enum(["hard","soft"]),match:ut.z.strictObject({present:ut.z.array(ut.z.number().int().min(0)),absent:ut.z.array(ut.z.number().int().min(0))})});var ir=require("zod"),_S=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],qc="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",ES=ir.z.string().regex(new RegExp(`^${qc}/${qc}/${qc}/manifest\\.json$`)),tf=ir.z.strictObject({kind:ir.z.literal("gcs-resumable"),url:ir.z.url(),bucket:ir.z.enum(_S),objectKey:ES,byteLength:ir.z.number().int().positive(),expiresAt:ir.z.iso.datetime()}).superRefine((e,t)=>{let n=new URL(e.url),r=n.searchParams,i=["uploadType","upload_id","name","upload_protocol","ifGenerationMatch"];(n.origin!=="https://storage.googleapis.com"||n.username||n.password||n.hash||n.pathname!==`/upload/storage/v1/b/${e.bucket}/o`||[...r.keys()].some(a=>!i.includes(a)||r.getAll(a).length!==1)||r.get("uploadType")!=="resumable"||!/^[A-Za-z0-9_-]{1,4096}$/.test(r.get("upload_id")??"")||r.has("name")&&r.get("name")!==`app-manifests/${e.objectKey}`||r.has("upload_protocol")&&r.get("upload_protocol")!=="resumable"||r.has("ifGenerationMatch")&&r.get("ifGenerationMatch")!=="0")&&t.addIssue({code:"custom",message:"Invalid IAM upload capability"})});var ht=M.z.string().min(1).max(256),un=M.z.string().regex(/^[a-f0-9]{64}$/),Da=M.z.strictObject({versionId:M.z.uuid(),manifestDigest:un,sourceGraphDigest:un,pageKey:ht,stateKey:ht,documentKey:ht,documentHash:un,elementKey:ht.optional(),nodeId:ht.optional(),contentHash:un.optional(),renderKey:ht.optional()}),nf=M.z.strictObject({pageKey:ht,documentKey:ht,expectedDocumentHash:un,renderKey:ht.optional(),nodeId:ht,elementKey:ht,expectedContentHash:un,property:M.z.enum(["text","fontSize","color"]),value:M.z.union([M.z.string().max(4e3),M.z.number().finite()])}),rf=M.z.strictObject({versionId:M.z.uuid(),manifestDigest:un,sourceGraphDigest:un,pageKey:ht,stateKey:ht,documentKey:ht,documentHash:un,renderKey:ht.optional(),patches:M.z.array(nf.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),RS=/^[a-z][a-z0-9-]{0,39}$/,mo=M.z.string().regex(RS),Vc=M.z.enum(["web","ios","android"]),VC=M.z.discriminatedUnion("action",[M.z.strictObject({action:M.z.literal("register"),requestId:M.z.uuid(),client:mo,platform:Vc,label:M.z.string().trim().min(1).max(100),sha256:un,bytes:M.z.number().int().min(1),transferBytes:M.z.number().int().min(1)}),M.z.strictObject({action:M.z.literal("complete"),versionId:M.z.uuid()}),M.z.strictObject({action:M.z.literal("current"),versionId:M.z.uuid(),expectedCurrent:M.z.uuid().nullable()}),M.z.strictObject({action:M.z.literal("delivery"),enabled:M.z.boolean()}),M.z.strictObject({action:M.z.literal("changes"),versionId:M.z.uuid(),experimentId:M.z.uuid(),variationId:ht,changesetId:M.z.uuid().nullable(),expectedRevision:un.nullable(),editorUrl:M.z.string().url().max(2048),patches:M.z.array(nf).max(200)})]),Lc=M.z.strictObject({id:M.z.uuid(),projectId:M.z.uuid(),environmentId:M.z.uuid(),clientKey:mo,platform:Vc,label:M.z.string(),sha256:un,bytes:M.z.number().int().positive(),objectKey:M.z.string(),state:M.z.enum(["uploading","ready","rejected"]),isCurrent:M.z.boolean(),revision:M.z.number().int().nonnegative(),createdAt:M.z.string(),expiresAt:M.z.string(),readyAt:M.z.string().nullable(),summary:M.z.record(M.z.string(),M.z.json()),routeTree:M.z.json().nullable(),validation:M.z.record(M.z.string(),M.z.json())}),kS=M.z.strictObject({key:mo,platform:Vc,currentId:M.z.uuid().nullable()}),LC=M.z.strictObject({rows:M.z.array(Lc).max(100),nextCursor:M.z.uuid().nullable(),clients:M.z.array(kS).max(20)}),Bc=M.z.strictObject({storedBytes:M.z.number().int().nonnegative(),reservedBytes:M.z.number().int().nonnegative(),chargedBytes:M.z.number().int().nonnegative(),versions:M.z.number().int().nonnegative(),objects:M.z.number().int().nonnegative(),orphanObjects:M.z.number().int().nonnegative(),missingReadyObjects:M.z.number().int().nonnegative(),unknownObjectSizes:M.z.number().int().nonnegative(),byteLimit:M.z.number().int().positive(),versionLimit:M.z.number().int().positive(),remainingBytes:M.z.number().int().nonnegative()}),UC=M.z.strictObject({asOf:M.z.iso.datetime({offset:!0}),reclamation:M.z.literal("manual-review-required"),buckets:M.z.strictObject({source:Bc,runtime:Bc,previews:Bc})}),zC=M.z.strictObject({version:Lc,actorId:M.z.uuid(),claims:M.z.record(M.z.string(),M.z.json())}),$C=M.z.strictObject({version:Lc,upload:tf.nullable()}),GC=M.z.object({format:M.z.literal("indiana-route-state-index"),schemaVersion:M.z.literal(3),routes:M.z.array(M.z.object({routeKey:ht,path:M.z.string(),documentKey:ht,documentHash:un,initialStateKey:ht,initialRenderKey:ht})),renders:M.z.array(ef)}).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"})}),KC=M.z.strictObject({rows:M.z.array(M.z.object({id:M.z.uuid(),name:M.z.string(),status:M.z.string(),variations:M.z.array(M.z.object({id:ht,key:ht,name:M.z.string().optional()}).loose())}).loose()),limited:M.z.boolean()}),HC=M.z.strictObject({enabled:M.z.boolean(),allowedOrigins:M.z.array(M.z.string())});var Br=require("zod");var of=Br.z.strictObject({id:Br.z.uuid(),name:Br.z.string().trim().min(1).max(80),client:mo,source:Da,event:Br.z.enum(["screen_enter","button_click"]),cooldownSeconds:Br.z.number().int().min(0).max(2592e3),behavior:Br.z.literal("observe")}).superRefine((e,t)=>{e.event==="button_click"&&(!e.source.nodeId||!e.source.elementKey)&&t.addIssue({code:"custom",path:["source"],message:"Choose a uniquely bound button"})});var Le=require("zod");var Uc=Se,jS=["parameters","answers","results","variables"];function zc(e){return jS.some(t=>e===t||e.startsWith(t+"."))}function $c(e){let t={};for(let[r,i]of Object.entries(ya(e.declarations,e))){let a=r.split(".");if(a.some(c=>["__proto__","constructor","prototype"].includes(c)))throw new Error("Reserved result path");let o=t;for(let c of a.slice(0,-1)){Object.hasOwn(o,c)||(o[c]={});let u=o[c];if(!u||typeof u!="object"||Array.isArray(u))throw new Error("Ambiguous result path");o=u}let s=a.at(-1);if(s===void 0)throw new Error("Empty result path");o[s]=i}return{...Object.fromEntries(Object.entries(e.attributes).filter(([r])=>!zc(r))),variables:t}}var dt=require("zod");var Fa=dt.z.discriminatedUnion("kind",[dt.z.object({kind:dt.z.literal("ledger"),cursor:pa}).strict(),dt.z.object({kind:dt.z.literal("billing"),cursor:dt.z.uuid()}).strict()]),TS=dt.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),or=dt.z.record(dt.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),dt.z.union([dt.z.string().max(500),dt.z.boolean(),dt.z.array(dt.z.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),NS=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function Gc(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>Gc(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||NS.test(n)||Gc(r,t+1)))}var DS=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,ar=dt.z.record(TS,Se).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!Gc(e)&&!DS.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var af=dt.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ma=dt.z.array(dt.z.object({variable:af,componentId:af,required:dt.z.boolean()}).strict()).max(40).refine(e=>new Set(e.map(t=>t.variable)).size===e.length&&new Set(e.map(t=>t.componentId)).size===e.length,"Input bindings must be unique"),r_=dt.z.object({bindings:Ma,answers:or,values:dt.z.record(dt.z.string(),Se).optional()}).strict();var sf=require("zod"),qa=sf.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var Kc=Le.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),cf=Le.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),uf=ar.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),Hc=Le.z.record(Kc,Le.z.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),FS=kn,lf=Le.z.strictObject({type:Le.z.literal("external_task"),endpointId:Le.z.uuid(),taskKey:Kc,inputs:Le.z.record(Kc,FS).refine(e=>Object.keys(e).length<=20),outputs:Hc}),df=Le.z.strictObject({maxAttempts:Le.z.number().int().min(1).max(5),retryDelaySeconds:Le.z.number().int().min(1).max(30),backoff:Le.z.enum(["fixed","exponential"]),requestTimeoutSeconds:Le.z.number().int().min(1).max(10),timeoutSeconds:Le.z.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var d_=Le.z.strictObject({outcome:Le.z.enum(["success","failure"]),data:uf});var p_=Le.z.discriminatedUnion("operation",[Le.z.strictObject({operation:Le.z.literal("signal"),runId:Le.z.uuid(),nodeId:cf,eventName:qa,eventId:Le.z.uuid(),data:uf}),Le.z.strictObject({operation:Le.z.literal("read_results"),runId:Le.z.uuid()})]),m_=Le.z.strictObject({scope:Ne,runId:Le.z.uuid(),eventId:Le.z.uuid(),accepted:Le.z.boolean()}),MS=Le.z.record(cf,Uc),f_=Le.z.strictObject({scope:Ne,runId:Le.z.uuid(),results:MS});var On={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},pf="00000000-0000-0000-0000-000000000000";var Q=require("zod");var Qe=require("zod");var b_=Qe.z.enum(["local","remote"]),Qc=Qe.z.strictObject({port:Qe.z.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:Se.optional(),sticky:Qe.z.array(Qe.z.strictObject({expected:Vi.nullable(),next:Vi})).max(100),exposures:Qe.z.array(Se).max(100),features:Qe.z.array(Se).max(100)}),mf=Qe.z.strictObject({type:Qe.z.literal("evaluate"),receiptId:Qe.z.uuid(),environmentId:Qe.z.uuid(),policyRevision:Qe.z.number().int().nonnegative(),attributes:Ot,sticky:Qe.z.record(Qe.z.string(),Vi)}),ff=mf.extend({runId:Qe.z.uuid(),versionId:Qe.z.uuid(),nodeId:Qe.z.string().min(1).max(64),visit:Qe.z.number().int().nonnegative(),revision:Qe.z.number().int().nonnegative()}),Jc=mf.omit({type:!0,receiptId:!0}).extend({type:Qe.z.literal("evaluate_segment")}),gf=Qe.z.strictObject({nodeId:Qe.z.string().min(1).max(64),result:Qc}),hf=Jc.extend({runId:Qe.z.uuid(),versionId:Qe.z.uuid(),nodeId:Qe.z.string().min(1).max(64),visit:Qe.z.number().int().nonnegative(),revision:Qe.z.number().int().nonnegative(),parameters:ar,answers:or,variables:Qe.z.record(Qe.z.string(),Se)});var ce=require("zod");var Zc=ce.z.array(ce.z.string().trim().min(1).max(40).refine(e=>!e.includes(","),"\u6807\u7B7E\u4E0D\u80FD\u5305\u542B\u9017\u53F7")).max(20).refine(e=>new Set(e).size===e.length,"\u6807\u7B7E\u4E0D\u80FD\u91CD\u590D"),Ba=ce.z.intersection(Ot,ce.z.looseObject({tags:Zc.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),Va=ce.z.string().trim().max(80),La=ce.z.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),Ua=ce.z.union([ce.z.email().max(254),ce.z.literal("")]),za=ce.z.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),Af=ce.z.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),yf=ce.z.object({externalUserId:Af.optional(),name:Va.default(""),email:Ua.default(""),phone:La.optional(),attributes:Ba.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),Vr=ce.z.discriminatedUnion("type",[ce.z.strictObject({type:ce.z.literal("id"),value:ce.z.uuid()}),ce.z.strictObject({type:ce.z.literal("externalUserId"),value:Af})]),xi=ce.z.strictObject({name:Va.optional(),email:Ua.optional(),phone:La.optional(),attributes:Ba.optional(),fingerprint:za.optional()}),$a=e=>!e.customerData||e.customer?.type==="externalUserId",Ga="customerData requires an externalUserId customer",Si=ce.z.object({id:ce.z.uuid(),externalUserId:ce.z.string().min(1).max(255).nullable(),name:Va,email:Ua,phone:La.optional(),attributes:Ba,createdAt:ce.z.iso.datetime()}).strict(),bf=ce.z.object({customer:Si,changed:ce.z.boolean(),replayed:ce.z.boolean()}).strict(),qS=ce.z.discriminatedUnion("type",[ce.z.object({type:ce.z.literal("id"),value:ce.z.uuid()}).strict(),ce.z.object({type:ce.z.literal("externalUserId"),value:ce.z.string().trim().min(1).max(255)}).strict()]),BS=ce.z.object({name:Va.optional(),email:Ua.optional(),phone:La.optional(),attributes:Ba.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:ce.z.array(ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:ce.z.strictObject({add:Zc,remove:Zc}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),Wc=ce.z.object({lookup:qS}).strict(),xf=Wc.extend({requestId:ce.z.uuid(),patch:BS}).strict(),Sf=ce.z.object({search:ce.z.string().trim().max(200).default(""),tag:ce.z.string().trim().max(40).default(""),planId:ce.z.string().max(200).default(""),versionId:ce.z.string().max(200).default(""),holdingStatus:ce.z.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:ce.z.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:ce.z.union([ce.z.iso.datetime(),ce.z.literal("")]).default(""),createdUntil:ce.z.union([ce.z.iso.datetime(),ce.z.literal("")]).default(""),offset:ce.z.coerce.number().int().min(0).max(1e5).default(0),limit:ce.z.coerce.number().int().min(1).max(100).default(50)}).strict(),If=ce.z.object({customers:Si.array(),hasMore:ce.z.boolean(),total:ce.z.number().int().nonnegative().nullable(),evaluatedAt:ce.z.iso.datetime()}).strict();var fo=Q.z.discriminatedUnion("type",[Q.z.strictObject({type:Q.z.literal("literal"),value:Se}),Q.z.strictObject({type:Q.z.literal("variable"),key:yt,path:wn.optional()}),Q.z.strictObject({type:Q.z.literal("feature"),featureKey:Q.z.string().min(1).max(128)})]),VS=Q.z.strictObject({requestId:Q.z.uuid(),decisionId:Q.z.uuid(),customerId:Q.z.uuid(),externalUserId:Q.z.string().min(1).max(255).nullable(),versionId:Q.z.uuid(),receiptId:Q.z.uuid(),value:Se}),LS={funnelId:Q.z.uuid(),requestId:Q.z.uuid(),customer:Vr,customerData:xi.optional(),attributes:Ot.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},E_=Q.z.discriminatedUnion("operation",[Q.z.strictObject({operation:Q.z.literal("decide"),...LS}).refine($a,Ga),Q.z.strictObject({operation:Q.z.literal("read_decision"),decisionId:Q.z.uuid()}),Q.z.strictObject({operation:Q.z.literal("evaluate_decision"),decisionId:Q.z.uuid(),requestId:Q.z.uuid(),nodeId:Q.z.string().min(1).max(64),visit:Q.z.number().int().nonnegative(),revision:Q.z.number().int().nonnegative(),receiptId:Q.z.uuid(),policyRevision:Q.z.number().int().nonnegative(),generation:Q.z.string().min(1).max(256),result:Qc}),Q.z.strictObject({operation:Q.z.literal("feature_config"),funnelId:Q.z.uuid()}),Q.z.strictObject({operation:Q.z.literal("commit_decision_segment"),decisionId:Q.z.uuid(),requestId:Q.z.uuid(),nodeId:Q.z.string().min(1).max(64),visit:Q.z.number().int().nonnegative(),revision:Q.z.number().int().nonnegative(),policyRevision:Q.z.number().int().nonnegative(),generation:Q.z.string().min(1).max(256),steps:Q.z.array(gf).max(32),boundary:Q.z.strictObject({nodeId:Q.z.string().min(1).max(64),visit:Q.z.number().int().nonnegative()}).optional()}),Q.z.strictObject({operation:Q.z.literal("segment_configuration"),funnelId:Q.z.uuid(),versionId:Q.z.uuid()}),Q.z.strictObject({operation:Q.z.literal("configuration"),funnelId:Q.z.uuid(),versionId:Q.z.uuid().optional()}),Q.z.strictObject({operation:Q.z.literal("local_configuration"),funnelId:Q.z.uuid()}),Q.z.strictObject({operation:Q.z.literal("report_used"),decisionId:Q.z.uuid(),eventId:Q.z.uuid(),occurredAt:Q.z.iso.datetime({offset:!0}),reference:Q.z.string().min(1).max(128).optional()})]),R_=Q.z.strictObject({scope:Ne,decisionId:Q.z.uuid(),requestId:Q.z.uuid(),status:Q.z.enum(["pending","completed","failed"]),decision:VS.nullable(),evaluation:Q.z.discriminatedUnion("type",[ff,hf]).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"),k_=Q.z.strictObject({scope:Ne,decisionId:Q.z.uuid(),eventId:Q.z.uuid(),source:Q.z.literal("caller_reported")});var kt=require("zod");var vf=kt.z.strictObject({type:kt.z.literal("bundle"),paywall:kn.optional(),offering:kn.optional(),coupons:kn,data:kn}),US=e=>kt.z.strictObject({type:kt.z.literal(e),id:kt.z.uuid()}),F_=kt.z.strictObject({type:kt.z.literal("bundle"),paywallVersionId:kt.z.uuid().optional(),offeringVersionId:kt.z.uuid().optional(),couponIds:kt.z.array(kt.z.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:Se});var M_=kt.z.strictObject({type:kt.z.literal("bundle"),offering:US("offering_version").nullable(),paywall:kt.z.strictObject({versionId:kt.z.uuid(),paywallId:kt.z.uuid(),offeringVersionId:kt.z.uuid()}).nullable(),coupons:kt.z.array(Li).max(20),data:Se});var hn=require("zod");var ln=require("zod");var wf=ln.z.union([ln.z.string(),ln.z.number().finite(),ln.z.boolean(),ln.z.null()]),zS=ln.z.union([wf,ln.z.array(wf).min(1).max(20)]),$S=ln.z.record(wn,zS).refine(e=>Object.keys(e).length<=10),Of=ln.z.strictObject({path:wn,type:ln.z.enum(["string","number","boolean","strings"]),nullable:ln.z.boolean().optional(),aggregation:ln.z.enum(["count","exists"]).optional(),where:$S.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 GS=["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"],Pf=hn.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),KS=kn,Cf=hn.z.discriminatedUnion("type",[lf,hn.z.strictObject({type:hn.z.literal("claim_offer"),coupon:kn}),hn.z.strictObject({type:hn.z.literal("event"),event:Pf}),hn.z.strictObject({type:hn.z.literal("api"),operation:hn.z.enum(GS),inputs:hn.z.record(wn,KS).refine(e=>Object.keys(e).length<=40),outputs:hn.z.record(Pf,Of).refine(e=>Object.keys(e).length<=20)})]);var ct=qa,HS=H.z.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),dn={id:ct,name:H.z.string().trim().min(1).max(80),position:H.z.strictObject({x:H.z.number().finite(),y:H.z.number().finite()}).optional()},QS={success:ct,cancel:ct,unavailable:ct,failure:ct},Yc=H.z.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),Xc=H.z.enum(["same_window","new_window"]),JS=H.z.discriminatedUnion("type",[H.z.strictObject({...dn,type:H.z.literal("entry"),next:ct,triggers:H.z.array(of).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),H.z.strictObject({...dn,type:H.z.literal("screen"),screenId:ct,presentation:Kn,outputs:H.z.record(ct,ct),offering:H.z.discriminatedUnion("source",[H.z.strictObject({source:H.z.literal("variable"),key:yt}),H.z.strictObject({source:H.z.literal("fixed"),versionId:H.z.uuid()})]).optional()}),H.z.strictObject({...dn,type:H.z.literal("offering"),configuration:H.z.discriminatedUnion("source",[H.z.strictObject({source:H.z.literal("fixed"),versionId:H.z.uuid()}),H.z.strictObject({source:H.z.literal("feature"),featureKey:H.z.string().min(1).max(128)})]),writes:H.z.strictObject({value:yt}),next:ct}),H.z.strictObject({...dn,type:H.z.literal("coupon"),couponId:H.z.uuid(),writes:H.z.strictObject({value:yt}),next:ct}),H.z.strictObject({...dn,type:H.z.literal("coupons"),couponIds:H.z.array(H.z.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:H.z.strictObject({value:yt}),next:ct}),H.z.strictObject({...dn,type:H.z.literal("output"),value:H.z.discriminatedUnion("type",[...fo.options,vf,H.z.strictObject({type:H.z.literal("selection"),screenId:ct,offeringKey:yt})])}),H.z.strictObject({...dn,type:H.z.literal("condition"),cases:H.z.array(H.z.strictObject({condition:Jt,target:ct})).min(1).max(50),default:ct}),H.z.strictObject({...dn,type:H.z.literal("feature"),featureKey:H.z.string().min(1).max(128),writes:H.z.strictObject({value:yt}),next:ct}),H.z.strictObject({...dn,type:H.z.literal("split"),experimentId:H.z.uuid(),applyPageExperiment:H.z.literal(!0).optional(),routes:H.z.record(HS,ct).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:ct}),H.z.strictObject({...dn,type:H.z.literal("action"),...QS,execution:df,action:Cf,writes:fc.optional()}),H.z.strictObject({...dn,type:H.z.literal("external_page"),appManifest:Da.optional(),url:Yc,openIn:Xc,opened:ct,failed:ct}),H.z.strictObject({...dn,type:H.z.literal("end"),outcome:H.z.enum(["completed","closed","ineligible","failed"]),output:fo.optional()}),H.z.strictObject({...dn,type:H.z.literal("wait"),writes:fc.optional(),wait:H.z.discriminatedUnion("type",[H.z.strictObject({type:H.z.literal("duration"),delaySeconds:H.z.number().int().min(1).max(2592e3),elapsed:ct}),H.z.strictObject({type:H.z.literal("event"),eventName:ct,outputs:Hc,timeoutSeconds:H.z.number().int().min(1).max(2592e3),received:ct,timeout:ct})])})]),eu=H.z.strictObject({version:H.z.literal(5),entry:ct,nodes:H.z.array(JS).min(1).max(On.flowNodes)}),tu=eu.superRefine((e,t)=>{ZS(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function Ka(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 ZS(e,t){let n=[],r=new Map(e.nodes.map(l=>[l.id,l])),i=(l,f,m)=>{n.push(l),t?.({message:l,reason:f,path:m?["nodes",e.nodes.indexOf(m)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(l=>l.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(l=>l.type==="screen").length>On.pages||e.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>On.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let l of e.nodes){for(let f of Ka(l))f===e.entry&&i("An entry cannot be a transition target","entryTarget",l),r.has(f)||i(`Missing target ${f}`,"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 f of Ka(r.get(l)))u(f);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 nu={maxTransitions:1e4,runTimeoutSeconds:2592e3};function _f(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 Yn(c.condition))u.startsWith("variables.")&&a(u.slice(10),!0)}if(e.type==="screen"&&e.offering?.source==="variable"&&a(e.offering.key),e.type==="action"&&(e.action.type==="api"||e.action.type==="external_task"))for(let s of Object.values(e.action.inputs))s.source==="variable"&&a(s.key);e.type==="action"&&e.action.type==="claim_offer"&&e.action.coupon.source==="variable"&&a(e.action.coupon.key);let o=e.type==="output"?e.value:e.type==="end"?e.output:null;if(o?.type==="variable"&&a(o.key),o?.type==="bundle")for(let s of[o.paywall,o.offering,o.coupons,o.data])s?.source==="variable"&&a(s.key);return o?.type==="selection"&&a(o.offeringKey),[...i]}var q=require("zod");var Ii=q.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Ha=e=>q.z.record(q.z.string(),Se).refine(t=>cn(t)<=e,"Funnel evidence exceeds its byte budget"),l1=q.z.enum(["local_segment","evaluation","presentation","timer","event","operation"]),iu=q.z.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),ou=q.z.discriminatedUnion("type",[q.z.strictObject({type:q.z.literal("flag"),key:q.z.string().min(1).max(128)}),q.z.strictObject({type:q.z.literal("experiment"),id:q.z.uuid()}),q.z.strictObject({type:q.z.literal("saved_group"),id:q.z.uuid()}),q.z.strictObject({type:q.z.literal("config"),key:q.z.string().min(1).max(128)}),q.z.strictObject({type:q.z.literal("constant"),key:q.z.string().min(1).max(128)}),q.z.strictObject({type:q.z.literal("paywall_version"),id:q.z.uuid()}),q.z.strictObject({type:q.z.literal("offering_version"),id:q.z.uuid()}),q.z.strictObject({type:q.z.literal("reward"),id:q.z.uuid()})]),go=q.z.strictObject({schemaVersion:q.z.literal(1),kind:iu,selector:ou.nullable(),context:Ha(131072),contract:q.z.strictObject({version:q.z.number().int().positive(),evaluator:q.z.string().min(1).max(128),policyRevision:q.z.number().int().nonnegative()})}).refine(e=>cn(e)<=131072,"Node input exceeds its byte budget"),Ef=q.z.strictObject({schemaVersion:q.z.literal(1),kind:iu,outcome:q.z.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:Ha(131072),route:q.z.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:Ha(131072)}).refine(e=>cn(e)<=131072,"Node result exceeds its byte budget"),d1=q.z.strictObject({schemaVersion:q.z.literal(1),operations:q.z.record(Ii,q.z.strictObject({attempts:q.z.number().int().nonnegative(),maxAttempts:q.z.number().int().min(1).max(5),deadlineAt:q.z.iso.datetime({offset:!0}),retryAt:q.z.iso.datetime({offset:!0}).nullable(),error:q.z.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:q.z.strictObject({type:Ii,id:q.z.uuid()}).nullable()}))}).refine(e=>cn(e)<=65536,"Execution state exceeds its byte budget"),Lr={receiptId:q.z.uuid()},ru=q.z.iso.datetime({offset:!0}),p1=q.z.discriminatedUnion("type",[q.z.strictObject({type:q.z.literal("node_entered"),details:q.z.strictObject({kind:iu})}),q.z.strictObject({type:q.z.literal("presentation_shown"),details:q.z.strictObject({...Lr,source:q.z.literal("client"),occurredAt:ru.optional()})}),q.z.strictObject({type:q.z.literal("decision_accepted"),details:q.z.strictObject(Lr)}),q.z.strictObject({type:q.z.literal("signal_received"),details:q.z.strictObject({signalId:q.z.uuid(),nodeId:Ii,eventName:Ii,data:Ha(8192),source:q.z.literal("server"),occurredAt:ru})}),q.z.strictObject({type:q.z.literal("signal_consumed"),details:q.z.strictObject({...Lr,signalId:q.z.uuid()})}),q.z.strictObject({type:q.z.literal("wait_elapsed"),details:q.z.strictObject(Lr)}),q.z.strictObject({type:q.z.literal("wait_timeout"),details:q.z.strictObject(Lr)}),q.z.strictObject({type:q.z.literal("operation_completed"),details:q.z.strictObject({...Lr,operation:Ii,reference:q.z.strictObject({type:Ii,id:q.z.uuid()}).nullable()})}),q.z.strictObject({type:q.z.literal("execution_recovered"),details:q.z.strictObject({generation:q.z.number().int().positive(),reason:q.z.enum(["interrupted","expired_lease","delivery_failed"])})}),q.z.strictObject({type:q.z.literal("execution_failed"),details:q.z.strictObject({generation:q.z.number().int().positive(),code:q.z.string().regex(/^[a-z_]{1,64}$/)})}),q.z.strictObject({type:q.z.literal("run_completed"),details:q.z.strictObject({outcome:q.z.enum(["completed","ineligible","failed"])})}),q.z.strictObject({type:q.z.literal("run_closed"),details:q.z.strictObject({source:q.z.enum(["client","server","expiry"])})}),q.z.strictObject({type:q.z.literal("treatment_used"),details:q.z.strictObject({...Lr,source:q.z.enum(["client","server"]),occurredAt:ru,reference:q.z.string().min(1).max(128).optional()})})]);var An=U.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),WS=U.z.discriminatedUnion("type",[U.z.strictObject({id:An,type:U.z.literal("owned"),publicData:zm.optional(),document:sn.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")}),U.z.strictObject({id:An,type:U.z.literal("paywall"),paywallVersionId:U.z.uuid()})]),au={executionContract:Zm.optional(),kind:U.z.literal("funnel"),schemaVersion:U.z.literal(4),screens:U.z.array(WS).max(On.pages),references:U.z.record(An,ou).refine(e=>Object.keys(e).length<=500),inputs:U.z.array(U.z.strictObject({variable:An,screenId:An,componentId:An,required:U.z.boolean()})).max(On.questions),variables:U.z.record(yt,ui).refine(e=>Object.keys(e).length<=On.logicNodes),outputSchema:ci,execution:U.z.strictObject({runTimeoutSeconds:U.z.number().int().min(1).max(nu.runTimeoutSeconds),maxTransitions:U.z.number().int().min(1).max(nu.maxTransitions)})},k1=U.z.strictObject({...au,graph:eu});function YS(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 Ja(e){return Array.isArray(e)?e.some(Ja):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===pf:Ja(n))}function XS(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=Xm(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&&!ro(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}),YS(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"&&Ja(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&Ja(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function Rf(e,t){for(let{message:n,reason:r,path:i}of XS(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function kf(e,t){let n=(h,d,A=[])=>t.addIssue({code:"custom",message:h,path:A,params:{reason:d}}),r=Object.values(e.references),i=new Map(e.screens.map(h=>[h.id,h])),a=(h,d)=>r.some(A=>A.type===h&&("id"in A?A.id:A.key)===d);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let o=e.graph.nodes.filter(h=>h.type==="screen");(o.length!==i.size||o.some(h=>!i.has(h.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(h=>c.some(d=>h!==d&&d.startsWith(h+".")))&&n("Variable paths must not overlap","variable");function u(h,d){Object.hasOwn(e.variables,h)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(d)]);let A=s.get(h)??new Set;A.add(d.id),s.set(h,A)}for(let[h,d]of e.graph.nodes.entries()){let A=["graph","nodes",h],k=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;k&&!a("flag",k)&&n("Flag selectors require an explicit GB resource reference","feature",A);let g=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):[],y="writes"in d?d.writes??{}:{};(g.length!==Object.keys(y).length||g.some(w=>!Object.hasOwn(y,w))||new Set(Object.values(y)).size!==Object.values(y).length)&&n("Node writes must map every named output exactly once","variable",A);for(let[w,C]of Object.entries(y)){u(C,d);let j=e.variables[C],E=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[w]:d.type==="wait"&&d.wait.type==="event"?d.wait.outputs[w]:void 0;(j?.source.type!=="node"||E&&j.type!==E)&&n("Node writer source or output type does not match declaration","variable",A)}if(d.type==="coupons"){let w=e.variables[d.writes.value];(w?.type!=="array"||w.items?.type!=="reward"||w.items.nullable||w.nullable)&&n("Coupons output requires a non-null Reward array","variable",A);for(let C of d.couponIds)a("reward",C)||n("Coupons require Reward references","coupon",A)}if(d.type==="split"&&!a("experiment",d.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",A),d.type==="coupon"&&!a("reward",d.couponId)&&n("Coupon selectors require a Reward reference","coupon",A),d.type==="action"&&d.action.type==="claim_offer"&&d.action.coupon.source==="literal"){let w=d.action.coupon.value;(!w||typeof w!="object"||Array.isArray(w)||w.type!=="reward"||typeof w.id!="string"||Object.keys(w).length!==2||!a("reward",w.id))&&n("Coupon claims require a Reward reference","coupon",A)}if(d.type==="offering"&&d.configuration.source==="fixed"&&!a("offering_version",d.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",A),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",A),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",A),d.type==="screen"){let w=i.get(d.screenId);if(d.offering?.source==="fixed"&&!a("offering_version",d.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",A),w?.type==="paywall"&&d.offering&&n("Paywall owns its fixed Offering Version","offering",A),w?.type==="paywall"&&!a("paywall_version",w.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",A),w?.type==="owned"){let C=w.document.pages[0];if(!C){n("Owned screen requires a page","screen",A);continue}tr(w.document).some(E=>!E.complete)&&n("Owned screens require complete local content","translations",A);let j=new Set(w.document.actions.map(E=>E.id));(j.size!==Object.keys(d.outputs).length||Object.keys(d.outputs).some(E=>!j.has(E)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",A),Gn(C.root,E=>{!d.offering&&(E.type==="plan_picker"||(E.type==="stack"||E.type==="button")&&E.bind?.plan||E.type==="customer_data"&&["customer_plans","credit_packs"].includes(E.data.source))&&n("Product presentation requires an Offering Version","offering",A),E.type==="customer_data"&&Object.values(E.data.outputs??{}).some(ae=>ae!==void 0&&!j.has(ae))&&n("Customer components require declared screen outcomes","componentOutput",A)})}}d.type==="end"&&["completed","ineligible"].includes(d.outcome)&&!d.output&&n("Completed and ineligible ends require a declared output","output",A),d.type==="end"&&d.output?.type==="literal"&&!fn(e.outputSchema,d.output.value)&&n("Terminal output does not match outputSchema","output",A),d.type==="output"&&d.value.type==="literal"&&!fn(e.outputSchema,d.value.value)&&n("Terminal output does not match outputSchema","output",A);let I=d.type==="output"?d.value:d.type==="end"?d.output:void 0;if(I?.type==="variable"&&!I.path){let w=e.variables[I.key];w&&!gc(w,e.outputSchema)&&n("Variable output does not match outputSchema","output",A)}if(d.type==="screen"){let w=i.get(d.screenId);if(w?.type==="owned")for(let C of yc(w.document))(/^(input|params)\./.test(C)||C.startsWith("variables.")&&!Ac(C.slice(10),c))&&n("Screen values must reference registered variables","variable",A)}if(d.type==="condition")for(let w of d.cases){for(let C of Un(w.condition))a("saved_group",C)||n("Conditions require explicit Saved Group references","savedGroup",A);for(let C of Yn(w.condition))C.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",A)}if(d.type==="output"&&d.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",A);for(let[w,C]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let j=d.value[w];if(j)if(j.source==="literal"){let E=w==="coupons"?j.value:[j.value];(!Array.isArray(E)||E.length>20||E.some(ae=>!fn({type:C,nullable:!1},ae)||!a(C,ae.id))||w==="coupons"&&new Set(E.map(ae=>ae.id)).size!==E.length)&&n("Bundle requires distinct scoped resource references",w==="coupons"?"coupon":w==="paywall"?"paywall":"offering",[...A,"value",w])}else{let E=e.variables[j.key];(j.path||!E||E.nullable||(w==="coupons"?E.type!=="array"||E.items?.type!=="reward"||E.items.nullable:E.type!==C))&&n("Bundle binding type does not match its slot","output",A)}}}}for(let[h,d]of e.graph.nodes.entries()){let A=d.type==="screen"?i.get(d.screenId):void 0,k=[..._f(d,c),...A?.type==="owned"?ba(A.document).map(g=>Ac(g,c)?.key??g):[]];for(let g of new Set(k)){let C=function(j){if(j===d.id)return!0;if(w.has(j))return!1;w.add(j);let E=e.graph.nodes.find(xe=>xe.id===j);return E?(I.has(j)?E.type==="action"?[E.cancel,E.unavailable,E.failure]:E.type==="wait"&&E.wait.type==="event"?[E.wait.timeout]:[]:Ka(E)).some(C):!1};var m=C;if(!Object.hasOwn(e.variables,g)){n("Consumed variable is undeclared","variable",["graph","nodes",h]);continue}let y=e.variables[g];if(d.type==="screen"&&y.source.type==="input"&&e.inputs.some(j=>j.screenId===d.screenId&&j.variable===g)||y.source.type==="parameter"||y.source.type==="attribute")continue;let I=y.source.type==="input"?new Set(e.inputs.filter(j=>j.variable===g&&j.required).flatMap(j=>o.filter(E=>E.screenId===j.screenId).map(E=>E.id))):s.get(g)??new Set,w=new Set;(!I.size||C(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",h])}}(new Set(e.inputs.map(h=>h.variable)).size!==e.inputs.length||new Set(e.inputs.map(h=>`${h.screenId}:${h.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[h,d]of e.inputs.entries()){e.variables[d.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",h]);let A=i.get(d.screenId),k=A?.type==="owned"?ro(A.document,d.componentId):null;if((k?.type!=="stack"||!k.interaction||!["input","toggle","select","multiselect","tabs"].includes(k.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",h]),k?.type==="stack"&&k.interaction){let g=k.interaction.type==="toggle"?"boolean":k.interaction.type==="multiselect"?"strings":"string";e.variables[d.variable]?.type!==g&&n("Input variable type does not match component","inputBinding",["inputs",h]);let y=e.variables[d.variable]?.enum;y&&!k.children.filter(I=>!I.hidden).every(I=>y.includes(I.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",h])}}for(let[h,d]of Object.entries(e.variables))d.enum&&d.type!=="string"&&n("Only string variables support enum","variable",["variables",h]),d.source.type==="input"&&!e.inputs.some(A=>A.variable===h)&&n("Input variable requires a component binding","inputBinding",["variables",h]);let l=0,f=0;for(let h of e.screens)if(h.type==="owned"){for(let d of h.document.pages)Gn(d.root,()=>{l++});f+=h.document.actions.length}(l>On.components||f>On.actions||cn(e)>On.documentBytes)&&n("Funnel document exceeds its budget","budget")}var e0=U.z.strictObject({...au,graph:tu}).superRefine(kf),vi=U.z.strictObject({...au,graph:tu,displayName:U.z.string().trim().min(1).max(80)}).superRefine(kf),j1=vi.superRefine(Rf),T1=e0.superRefine(Rf),Qa=U.z.string().regex(jt),ho={requestId:U.z.uuid(),nodeId:An,visit:U.z.number().int().nonnegative(),revision:U.z.number().int().nonnegative(),customerToken:Qa.optional()},t0=U.z.discriminatedUnion("type",[U.z.strictObject({type:U.z.literal("screen"),output:An,answers:or,selection:U.z.record(An,U.z.union([U.z.string().max(200),U.z.boolean(),U.z.number().int().min(0).max(1e4)])).optional()}),U.z.strictObject({type:U.z.literal("paywall_quote"),featureQuantities:U.z.record(U.z.uuid(),U.z.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100).optional(),actionId:An,productVersionId:U.z.uuid(),offerId:U.z.uuid().optional(),nativeOffer:pi.optional(),predecessor:U.z.strictObject({operationId:U.z.uuid().nullable(),generation:U.z.number().int().positive()}).optional()}),U.z.strictObject({type:U.z.literal("paywall_confirm"),operationId:U.z.uuid()}),U.z.strictObject({type:U.z.literal("paywall_cancel"),operationId:U.z.uuid()}),U.z.strictObject({type:U.z.literal("client_action"),receiptId:U.z.uuid(),outcome:U.z.enum(["success","cancel","failure","opened","failed"])})]),n0=U.z.object({nodeId:An,visit:U.z.number().int().nonnegative(),revision:U.z.number().int().nonnegative(),components:U.z.record(An,U.z.object({resourceKey:U.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:U.z.number().int().min(1).max(1e5),after:Fa.nullable(),filter:U.z.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),Pt=U.z.discriminatedUnion("operation",[U.z.strictObject({operation:U.z.literal("start"),funnelId:U.z.uuid(),requestId:U.z.uuid(),customer:Vr.optional(),customerData:xi.optional(),locale:U.z.string().min(1).max(35),parameters:ar}).refine($a,Ga),U.z.strictObject({operation:U.z.literal("get"),settlementRequestId:U.z.uuid().optional(),data:n0.optional(),purchase:U.z.strictObject({receiptId:U.z.uuid(),operationId:U.z.uuid()}).optional(),customerToken:Qa.optional()}),U.z.strictObject({operation:U.z.literal("resume"),requestId:U.z.uuid(),customerToken:Qa.optional()}),U.z.strictObject({operation:U.z.literal("submit"),...ho,input:t0}),U.z.strictObject({operation:U.z.literal("back"),...ho}),U.z.strictObject({operation:U.z.literal("shown"),...ho}),U.z.strictObject({operation:U.z.literal("close"),...ho}),U.z.strictObject({operation:U.z.literal("commit_segment"),...ho,policyRevision:U.z.number().int().nonnegative(),generation:U.z.string().min(1).max(256)}),U.z.strictObject({operation:U.z.literal("review"),receiptId:U.z.uuid().optional(),customerToken:Qa.optional()})]);function Za(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 A of Un(d))l(A)}function l(d){if(i.has(d)||!Object.hasOwn(t.savedGroups,d))return;let A=t.savedGroups[d];A&&(i.add(d),c.set(d,A),a.push(()=>{!Array.isArray(A)&&A.type==="condition"&&u(A.condition)}))}function f(d){for(let A of["hashAttribute","fallbackAttribute"])if(d[A]!==void 0&&zc(d[A]))throw new Error(`Funnel GB ${A} uses a reserved flow namespace`);u(d.condition);for(let A of d.parentConditions??[])m(A.id),u(A.condition)}function m(d,A=!1){let k=Object.hasOwn(t.features,d)?t.features[d]:void 0;if(!k){if(A)throw new Error("Required GB Feature is unavailable");return}n.has(d)||(n.add(d),o.set(d,k),a.push(()=>{for(let g of k.rules??[]){f(g);for(let y of g.tracks??[])f(y.experiment)}}))}function h(d){let A=Object.hasOwn(t.experiments,d)?t.experiments[d]:void 0;if(!A)throw new Error("Required GB Experiment is unavailable");r.has(d)||(r.add(d),s.set(d,A),a.push(()=>f(A)))}for(let d of e.graph.nodes){d.type==="feature"&&m(d.featureKey,!0),d.type==="split"&&h(d.experimentId),d.type==="condition"&&d.cases.forEach(k=>u(k.condition)),d.type==="offering"&&d.configuration.source==="feature"&&m(d.configuration.featureKey,!0);let A=d.type==="output"?d.value:d.type==="end"?d.output:null;A?.type==="feature"&&m(A.featureKey,!0)}for(let d of a)d();return{...t,features:Object.fromEntries(o),experiments:Object.fromEntries(s),savedGroups:Object.fromEntries(c)}}var ie=require("zod");function jf(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 Tf(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}var wi=require("zod");var Nf=wi.z.object({defaultLocale:xn,locales:wi.z.record(xn,wi.z.object({name:wi.z.string().max(80),description:wi.z.string().max(500)}).strict())}).strict().superRefine((e,t)=>{let n=Object.keys(e.locales);(!n.length||n.length>20||!e.locales[e.defaultLocale])&&t.addIssue({code:"custom",message:"Invalid content languages"}),new TextEncoder().encode(JSON.stringify(e)).length>5e4&&t.addIssue({code:"custom",message:"Content exceeds 50 KB"})});var r0=["customer_data","coupon_code"],i0=ie.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),Df=ie.z.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),Wa=(e,t)=>new Set(e.map(t)).size===e.length,o0=ie.z.strictObject({currency:be,amountMinor:ie.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),a0=ie.z.strictObject({featureId:ie.z.uuid(),name:ie.z.string().trim().min(1).max(120),allowance:ie.z.string().max(40).nullable(),access:ie.z.boolean()}),s0=ie.z.strictObject({stripe:ie.z.strictObject({prices:ie.z.array(o0).min(1).max(50)}).optional(),apple:ie.z.strictObject({productIds:ie.z.array(i0).min(1).max(10)}).optional(),google:ie.z.strictObject({products:ie.z.array(ie.z.strictObject({productId:Df,basePlanId:Df.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!Wa(e.stripe.prices,n=>n.currency)||e.apple&&!Wa(e.apple.productIds,n=>n)||e.google&&!Wa(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),c0=ie.z.strictObject({name:ie.z.string().trim().min(1).max(80),interval:ie.z.enum(["free","week","month","year","one_time"]),intervalCount:ie.z.number().int().min(1).max(100),trial:ie.z.strictObject({days:ie.z.number().int().min(1).max(730),cardRequired:ie.z.boolean()}).nullable(),benefits:ie.z.array(a0).max(50).refine(e=>Wa(e,t=>t.featureId),"Duplicate benefit"),channels:s0,prepaid:ie.z.array(Xi).max(100).optional()}),u0=ie.z.strictObject({digest:yi,content:ie.z.strictObject({discount:Xn,duration:on,appliesTo:tc,displayCopy:Nf.nullable(),firstPurchaseOnly:ie.z.boolean(),qualificationRequired:ie.z.boolean(),startsAt:ie.z.iso.datetime().nullable(),endsAt:ie.z.iso.datetime().nullable(),grantWindowHours:ie.z.number().int().positive(),perCustomerLimit:ie.z.number().int().positive()})}),l0=ie.z.discriminatedUnion("type",[ie.z.strictObject({type:ie.z.literal("checkout"),product:ja}),ie.z.strictObject({type:ie.z.literal("close")}),ie.z.strictObject({type:ie.z.literal("action"),action:jc})]),Ya=ie.z.strictObject({kind:ie.z.literal("paywall"),formatVersion:ie.z.literal(1),name:ie.z.string().trim().min(1).max(80),offeringVersionId:ie.z.uuid(),presentation:Kn,screen:sn,products:ka,catalog:ie.z.record(ie.z.uuid(),c0),buttons:ie.z.record(Me,l0),coupons:ie.z.record(ie.z.uuid(),u0)}).superRefine((e,t)=>{let n=A=>t.addIssue({code:"custom",message:A}),{screen:r}=e;jf(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),Mc(r,r0).forEach(n),tr(r).some(A=>!A.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,o=new Set;Gt(r,A=>{let k="bind"in A?A.bind:void 0;k?.promotionCode&&n("Promotion codes must not be published"),k?.plan&&i.add(k.plan),k?.coupon&&a.add(k.coupon),A.type==="plan_picker"&&(A.planIds?.forEach(g=>i.add(g)),A.defaultPlan&&i.add(A.defaultPlan)),A.type==="text"&&A.feature&&o.add(A.feature.id)});let s=e.products.items.map(A=>A.productVersionId),c=Object.keys(e.catalog);(s.length!==c.length||s.some(A=>!Object.hasOwn(e.catalog,A)))&&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 A of i)u.has(A)||n("Screen references a Product that is not displayed");for(let A of Object.values(e.catalog))!A.channels.stripe&&!A.channels.apple&&!A.channels.google&&n("A displayed Product needs at least one sales channel");let l=new Set(Object.values(e.catalog).flatMap(A=>A.benefits.map(k=>k.featureId)));for(let A of o)l.has(A)||n("Feature text must read a displayed benefit");let f=r.actions.filter(A=>A.type!=="navigate");r.actions.some(A=>A.type!=="event"&&A.type!=="navigate")&&n("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==f.length||f.some(A=>!Object.hasOwn(e.buttons,A.id)))&&n("Buttons must match the screen's actions");let h=!1;for(let A of Object.values(e.buttons)){if(A.type!=="checkout")continue;h=!0,(A.product.type==="fixed"?[A.product.productVersionId]:A.product.allowedProductVersionIds).some(g=>!u.has(g))&&n("Checkout may only sell displayed Products")}h||n("A Paywall needs a checkout button");let d=Object.keys(e.coupons);(d.length!==a.size||d.some(A=>!a.has(A)))&&n("Coupons must be exactly the bound Coupons")}),Ff=ie.z.strictObject({state:ie.z.enum(["published","archived"]),controlRevision:ie.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:ie.z.uuid(),versions:ie.z.record(ie.z.uuid(),ie.z.strictObject({version:ie.z.number().int().positive(),artifact:ie.z.string().min(1),sourceDigest:ie.z.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var Xt={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},su=_e.z.string().regex(/^[a-f0-9]{64}$/),cu=_e.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),lu=Ne.extend({environmentId:_e.z.uuid()}),Mf=_e.z.strictObject({features:_e.z.array(_e.z.string()).max(500),experiments:_e.z.record(_e.z.uuid(),_e.z.array(_e.z.string()).max(20)),savedGroups:_e.z.array(_e.z.string()).max(1e3)}),du=_e.z.strictObject({kind:_e.z.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:_e.z.number().int().positive(),url:_e.z.string().min(1).max(2048),sha256:su,byteLength:_e.z.number().int().positive().max(Xt.maxArtifactBytes),generation:su.optional()}),d0=_e.z.strictObject({state:_e.z.enum(["active","paused","archived"]),controlRevision:cu,evaluationMode:_e.z.enum(["local","remote"]),evaluationRevision:cu,currentVersionId:_e.z.uuid(),versions:_e.z.record(_e.z.uuid(),_e.z.strictObject({artifact:_e.z.string(),dependencies:Mf,definitionDigest:yi.optional(),couponDigests:_e.z.record(_e.z.uuid(),yi).optional()}))}),pu=_e.z.strictObject({kind:_e.z.literal("sdk_configuration"),schemaVersion:_e.z.literal(1),scope:lu,revision:cu,generation:su,policy:_e.z.strictObject({refreshIntervalSeconds:_e.z.number().positive().max(15),maxControlAgeSeconds:_e.z.number().positive().max(60)}),gb:_e.z.strictObject({features:_e.z.string().nullable(),pageExperiments:_e.z.string().nullable()}),artifacts:_e.z.record(_e.z.string(),du),funnels:_e.z.record(_e.z.uuid(),d0),paywalls:_e.z.record(_e.z.uuid(),Ff).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 Ct(e){if(Array.isArray(e))return`[${e.map(Ct).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)}:${Ct(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function mu(e){return ei(ti(typeof e=="string"?new TextEncoder().encode(e):e))}function qf(e){return mu(Ct(e))}var uu=class extends Error{constructor(n,r){super(n);Fe(this,"dependency",r)}};function Bf(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,f)=>e.graph.nodes.find(m=>l==="experiment"?m.type==="split"&&m.experimentId===f:l==="feature"&&n(m)===f)?.name,i=(l,f,m=r(f.type,f.resource))=>new uu(l,{...f,...m?{step:m}:{}});for(let l of Object.values(e.references)){let f=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(f)throw i("Funnel dependency is absent from GB public delivery",{reason:"unavailable",...f})}let a=Za(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),o=new Set(t.remoteFeatures);for(let l of e.graph.nodes){let f=n(l);if(!f)continue;let m=a.features[f],h=l.type==="feature"?e.variables[l.writes.value]:e.outputSchema,d={type:"feature",resource:f};if(!m||!h)throw i("Required public Feature declaration is unavailable",{reason:"unavailable",...d},l.name);if([m.defaultValue,...(m.rules??[]).flatMap(k=>[...Object.hasOwn(k,"force")?[k.force]:[],...k.variations??[],...(k.tracks??[]).flatMap(g=>g.experiment.variations)])].some(k=>k===void 0||!fn(h,k)))throw i("GB Feature values violate the Funnel type contract",{reason:"value_type",...d},l.name)}let s=new Set,c=(l,f)=>{for(let m of Un(l)){if(s.has(m))continue;let h=t.savedGroups[m];if(!h)throw i("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:m},f);s.add(m),!Array.isArray(h)&&h.type==="condition"&&c(h.condition,f)}},u=(l,f)=>{if(o.has(l)||!t.features[l])throw i("Local Funnel requires public Local prerequisites",{reason:"unavailable",type:"feature",resource:l},f)};for(let l of e.graph.nodes)if(l.type==="condition")for(let f of l.cases)c(f.condition,l.name);for(let[l,f]of Object.entries(a.features)){let m=r("feature",l);for(let h of f.rules??[]){c(h.condition,m);for(let d of[...h.parentConditions??[],...(h.tracks??[]).flatMap(A=>A.experiment.parentConditions??[])])u(d.id,m),c(d.condition,m);for(let d of h.tracks??[])c(d.experiment.condition,m)}}for(let[l,f]of Object.entries(a.experiments)){let m=r("experiment",l);c(f.condition,m);for(let h of f.parentConditions??[])u(h.id,m),c(h.condition,m)}for(let l of e.graph.nodes)if(l.type==="split"){let f=a.experiments[l.experimentId],m={type:"experiment",resource:l.experimentId};if(!f)throw i("Local Funnel requires a public Experiment",{reason:"unavailable",...m},l.name);for(let h of f.variations)if(typeof h!="string"||!Object.hasOwn(l.routes,h))throw i("Experiment variation has no declared Funnel route",{reason:"variation_route",...m},l.name)}return Mf.parse({features:Object.keys(a.features).sort(),experiments:Object.fromEntries(Object.entries(a.experiments).map(([l,f])=>[l,f.variations.map(String)])),savedGroups:[...s].sort()})}function Vf(e){return vi.parse(e)}var Lf=xt.z.strictObject({processContext:Sa.optional(),...di,selector:xt.z.discriminatedUnion("type",[xt.z.strictObject({type:xt.z.literal("paywall"),paywallId:xt.z.uuid()}),xt.z.strictObject({type:xt.z.literal("version"),versionId:xt.z.uuid()})]),customerId:xt.z.uuid().optional(),commerce:ai,locale:xt.z.string().min(1).max(35),requirement:er.optional()}),Ao=xt.z.strictObject({id:xt.z.uuid(),paywallId:xt.z.uuid(),version:xt.z.number().int().positive(),document:Ai.omit({requirement:!0,offeringId:!0}),offering:xt.z.strictObject({id:xt.z.uuid()}),content:xt.z.strictObject({environmentId:xt.z.uuid(),offeringVersionId:xt.z.uuid(),artifact:du.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:si,check:Tr.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"})}),Ur=xt.z.strictObject(Ao.shape).omit({document:!0,offering:!0}).extend({content:Ao.shape.content.unwrap()});function Uf(e,t){let n=Ya.parse(t);if(n.offeringVersionId!==e.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");let r=structuredClone(e.capabilities);for(let[i,a]of Object.entries(n.catalog)){let o=r.plans[i],s=a.channels.stripe?.prices.find(c=>c.currency===o?.currency);o&&s&&Object.assign(o,{amountMinor:s.amountMinor,interval:a.interval,intervalCount:a.intervalCount,...a.prepaid?.length?{prepaid:a.prepaid}:{}})}return Ao.parse({...e,capabilities:r,document:{schemaVersion:3,kind:n.kind,name:n.name,presentation:n.presentation,products:n.products,offeringVersionId:n.offeringVersionId,screen:n.screen,buttons:n.buttons},offering:{id:n.offeringVersionId}})}var Bt=require("zod");var zf={requestId:Bt.z.uuid(),sourceId:Bt.z.uuid(),expectedAvailable:$t},$f=Bt.z.discriminatedUnion("action",[Bt.z.strictObject({...zf,action:Bt.z.enum(["add","subtract","set_remaining"]),amount:Ae}),Bt.z.strictObject({...zf,action:Bt.z.literal("edit"),granted:Ae,expiresAt:Bt.z.iso.datetime({offset:!0}).nullable(),nextResetAt:Bt.z.iso.datetime({offset:!0}).nullable(),expectedRevision:Bt.z.number().int().nonnegative()})]),fu=Bt.z.strictObject({sourceId:Bt.z.uuid(),available:$t,held:$t,spent:$t,adjustmentGrantId:Bt.z.uuid().nullable()}),Gf=fu.extend({granted:$t,expiresAt:Bt.z.iso.datetime({offset:!0}).nullable(),nextResetAt:Bt.z.iso.datetime({offset:!0}).nullable(),revision:Bt.z.number().int().nonnegative()});var en=require("zod"),Kf=en.z.discriminatedUnion("action",[en.z.object({action:en.z.literal("upsert"),externalId:en.z.string().min(1).max(128),name:en.z.string().trim().min(1).max(80)}).strict(),en.z.object({action:en.z.literal("archive"),entityId:en.z.uuid()}).strict()]),Hf=en.z.object({id:en.z.uuid(),externalId:en.z.string().min(1).max(128),name:en.z.string().min(1).max(80),archived:en.z.boolean()}).strict();var Ft=require("zod");var sr=require("zod"),Jf=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],Qf=sr.z.string().regex(/.+\/.+/),gu=sr.z.number().min(-100),zr=sr.z.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),p0=sr.z.strictObject({input:zr,output:zr,cache_read:zr.optional(),cache_write:zr.optional(),reasoning:zr.optional(),input_audio:zr.optional(),output_audio:zr.optional()}),hu=(e,t)=>sr.z.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),OE=sr.z.strictObject({defaultMarkup:gu,providerMarkups:hu(sr.z.string().min(1),gu),modelMarkups:hu(Qf,gu),customModels:hu(Qf,p0.partial())});var he=require("zod"),$r=he.z.iso.datetime({offset:!0}),cr=he.z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),m0=he.z.discriminatedUnion("kind",[he.z.object({kind:he.z.literal("absolute"),from:$r,to:$r}).strict(),he.z.object({kind:he.z.literal("last_days"),days:he.z.union([he.z.literal(1),he.z.literal(7),he.z.literal(30),he.z.literal(90)])}).strict(),he.z.object({kind:he.z.literal("billing_cycles"),membershipId:he.z.uuid(),count:he.z.number().int().min(1).max(12),includeCurrent:he.z.boolean()}).strict()]),Zf=he.z.string().max(100).refine(e=>{if(e!=="UTC"&&!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+\-]+)+$/.test(e))return!1;try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Use an IANA timezone"),f0=he.z.object({key:he.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:he.z.array(he.z.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),Gr=he.z.object({range:m0,timezone:Zf,filterBy:he.z.array(f0).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:he.z.enum(["hour","day","week","month"]),internal_feature_id:he.z.uuid().nullable(),entityId:he.z.uuid().nullable(),topN:he.z.number().int().min(1).max(50).nullable(),groupBy:he.z.union([he.z.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),he.z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:he.z.object({bucket:$r,group:he.z.string().max(240),isOther:he.z.boolean(),internal_feature_id:he.z.uuid(),resourceId:he.z.uuid()}).strict().nullable(),limit:he.z.number().int().min(1).max(100)}).strict().superRefine((e,t)=>{if(e.range.kind!=="absolute"){e.interval==="hour"&&e.range.kind==="last_days"&&e.range.days>31&&t.addIssue({code:"custom",message:"Hourly reports are bounded to 31 days"});return}let n=Date.parse(e.range.to)-Date.parse(e.range.from);(n<=0||n>366*864e5||e.interval==="hour"&&n>31*864e5)&&t.addIssue({code:"custom",message:"Reporting range must be positive and bounded (31 days hourly, 366 days otherwise)"})}),Wf=he.z.object({from:$r,to:$r,interval:he.z.enum(["hour","day","week","month"]),timezone:Zf,rows:he.z.array(he.z.object({bucket:$r,group:he.z.string().max(240),isOther:he.z.boolean(),internal_feature_id:he.z.uuid(),resourceId:he.z.uuid(),consumedUnits:cr,refundedUnits:cr,reservedUnits:cr,charged:cr,refunded:cr,reserved:cr,netUnits:cr,netCharged:cr}).strict()).max(100),nextCursor:he.z.object({bucket:$r,group:he.z.string().max(240),isOther:he.z.boolean(),internal_feature_id:he.z.uuid(),resourceId:he.z.uuid()}).strict().nullable()}).strict();var Oi=Ft.z.string().regex(/^(0|[1-9]\d{0,29})$/),Yf=Ft.z.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),Au=Ft.z.strictObject({bucket:Ft.z.iso.datetime({offset:!0}),group:Ft.z.string().max(240),isOther:Ft.z.boolean(),internal_feature_id:Ft.z.uuid()}),Xf=Ft.z.strictObject({...Gr.shape,groupBy:Ft.z.union([Ft.z.enum(["customer","entity","entitlement"]),Ft.z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Au.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})}),eg=Ft.z.strictObject({from:Ft.z.iso.datetime({offset:!0}),to:Ft.z.iso.datetime({offset:!0}),interval:Gr.shape.interval,timezone:Gr.shape.timezone,rows:Ft.z.array(Ft.z.strictObject({...Au.shape,eventCount:Oi,units:Yf,tokenEventCount:Oi,tokens:Ft.z.strictObject(Object.fromEntries(Jf.map(e=>[e,Oi]))),totalTokens:Oi,providerCostEventCount:Oi,providerCostUsd:Yf,invalidTelemetryEventCount:Oi})).max(100),nextCursor:Au.nullable()});var pt=require("zod");var tg=pt.z.object({requestId:pt.z.uuid(),items:pt.z.array(pt.z.object({customerId:pt.z.uuid(),command:Hi.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"),ng=pt.z.object({batchId:pt.z.uuid(),after:pt.z.number().int().min(-1).max(999),limit:pt.z.number().int().min(1).max(100)}).strict(),rg=pt.z.object({batchId:pt.z.uuid(),status:pt.z.enum(["queued","complete"]),total:pt.z.number().int().min(1).max(1e3),processed:pt.z.number().int().min(0).max(1e3),items:pt.z.array(pt.z.object({position:pt.z.number().int().min(0).max(999),customerId:pt.z.uuid(),idempotencyKey:pt.z.string().min(1).max(120),status:pt.z.enum(["queued","accepted","rejected","failed"]),receipt:Qi.nullable(),errorCode:pt.z.enum(["invalid_request","forbidden","conflict","internal_error"]).nullable()}).strict().refine(e=>e.status==="queued"?e.receipt===null&&e.errorCode===null:e.status==="failed"?e.receipt===null&&e.errorCode!==null:e.receipt!==null&&e.errorCode===null&&e.receipt.accepted===(e.status==="accepted"))).max(100),nextAfter:pt.z.number().int().min(0).max(999).nullable()}).strict();var R=require("zod");var g0=R.z.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),ig=R.z.enum(["draft","active","paused","archived"]),og=R.z.string().min(1).max(256),ag=R.z.array(og).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),h0=R.z.strictObject({duration:R.z.enum(["day","week","month","year"]),length:R.z.number().int().min(1).max(3660)}),A0=R.z.strictObject({internal_feature_id:R.z.uuid(),allowance:R.z.number().nonnegative().max(1e15).nullable(),expiry:h0.nullable()}),y0=R.z.discriminatedUnion("type",[R.z.strictObject({type:R.z.literal("feature_grant"),grants:R.z.array(A0).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),R.z.strictObject({type:R.z.literal("free_product"),productId:og,duration:on}),R.z.strictObject({type:R.z.literal("invoice_credits"),amount:R.z.number().positive().max(1e8),duration:on,rollover:R.z.boolean(),productIds:ag})]),b0=R.z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),sg=R.z.object({key:b0,name:R.z.string().trim().min(1).max(80),configuration:y0}).strict(),cg=R.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),yu=R.z.object({code:cg,maxUses:R.z.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:R.z.boolean()}).strict(),ug=R.z.object({key:R.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:R.z.string().trim().min(1).max(80),rewardId:R.z.uuid(),redeemOn:R.z.enum(["customer_creation","checkout"]),receivedBy:R.z.enum(["referrer","all"]),maxRedemptions:R.z.number().int().min(1).max(1e6).nullable(),productIds:ag,excludeTrial:R.z.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),lg={id:R.z.uuid(),projectId:R.z.uuid(),environmentId:R.z.uuid(),revision:R.z.number().int().nonnegative(),status:ig,createdAt:R.z.iso.datetime({offset:!0}),updatedAt:R.z.iso.datetime({offset:!0})},x0=sg.extend(lg).strict(),S0=ug.safeExtend(lg).strict(),DE=R.z.strictObject({id:R.z.uuid(),key:R.z.string(),name:R.z.string(),type:g0,status:ig}),FE=R.z.discriminatedUnion("action",[R.z.object({action:R.z.literal("save"),id:R.z.uuid().nullable(),revision:R.z.number().int().nonnegative(),input:sg}).strict(),R.z.object({action:R.z.enum(["activate","pause","resume","archive","delete"]),id:R.z.uuid(),revision:R.z.number().int().nonnegative()}).strict()]),ME=R.z.discriminatedUnion("action",[R.z.object({action:R.z.literal("save"),id:R.z.uuid().nullable(),revision:R.z.number().int().nonnegative(),input:ug}).strict(),R.z.object({action:R.z.enum(["activate","pause","resume","archive","delete"]),id:R.z.uuid(),revision:R.z.number().int().nonnegative()}).strict()]),dg=R.z.object({id:R.z.uuid(),rewardId:R.z.uuid(),programId:R.z.uuid().nullable(),customerId:R.z.uuid(),referrerId:R.z.uuid().nullable(),status:R.z.enum(["pending","applied","unavailable"]),result:R.z.record(R.z.string(),R.z.unknown()).nullable(),createdAt:R.z.iso.datetime({offset:!0})}).strict(),pg=R.z.object({code:cg,requestId:R.z.uuid()}).strict(),mg=R.z.strictObject({redemptionId:R.z.uuid(),currency:be,requestId:R.z.uuid(),accepted:R.z.literal(!0)}),I0=R.z.strictObject({type:R.z.literal("checkout"),orderId:R.z.uuid(),productVersionId:R.z.uuid(),currency:be,duration:on,renewalAmountMinor:R.z.number().int().positive().max(1e8),status:R.z.enum(["created","pending","trialing","paid","cancelled","failed"]),url:R.z.url().nullable()}),fg=R.z.discriminatedUnion("type",[I0,R.z.strictObject({type:R.z.literal("subscription"),operationId:R.z.uuid(),membershipId:R.z.uuid(),productVersionId:R.z.uuid(),currency:be,duration:on,renewalAmountMinor:R.z.number().int().positive().max(1e8),status:R.z.enum(["pending","running","applied","failed"])})]),gg=R.z.object({programId:R.z.uuid(),requestId:R.z.uuid()}).strict(),hg=R.z.object({id:R.z.uuid(),programId:R.z.uuid(),code:yu.shape.code,createdAt:R.z.iso.datetime({offset:!0})}).strict(),qE=R.z.object({rows:R.z.array(x0).max(100),nextCursor:R.z.uuid().nullable()}).strict(),BE=R.z.object({rows:R.z.array(S0).max(100),nextCursor:R.z.uuid().nullable()}).strict(),v0=yu.extend({id:R.z.uuid(),redemptions:R.z.number().int().nonnegative()}).strict(),w0=R.z.strictObject({id:R.z.uuid(),programId:R.z.uuid().nullable(),customerId:R.z.uuid().nullable(),referrerId:R.z.uuid().nullable(),code:R.z.string().nullable(),status:R.z.enum(["pending","triggered","applied"]),createdAt:R.z.iso.datetime({offset:!0})}),VE=R.z.object({codes:R.z.array(v0).max(100),redemptions:R.z.array(w0).max(100),customers:R.z.record(R.z.uuid(),R.z.string()),codesCursor:R.z.uuid().nullable(),redemptionsCursor:R.z.uuid().nullable()}).strict(),LE=R.z.discriminatedUnion("action",[R.z.object({action:R.z.literal("create"),rewardId:R.z.uuid(),revision:R.z.number().int().nonnegative(),input:yu}).strict(),R.z.object({action:R.z.literal("remove"),rewardId:R.z.uuid(),revision:R.z.number().int().nonnegative(),codeId:R.z.uuid()}).strict()]);var v=require("zod");var J=require("zod"),jn={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},yo=e=>new Set(e).size===e.length,bu=J.z.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),O0=J.z.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),bo=J.z.string().min(1).max(200).regex(/^[a-zA-Z0-9_./-]+$/).refine(e=>!e.includes("..")&&!e.endsWith(".")&&!e.split("/").some(t=>!t||t.startsWith(".")||t.endsWith(".lock"))),P0=J.z.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),Ag=J.z.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var yg=J.z.strictObject({id:J.z.uuid(),repo:O0,platform:J.z.enum(["github","gitlab","bitbucket"]),branches:J.z.array(bo).min(1).max(4).refine(yo),workflow:J.z.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:J.z.array(J.z.uuid()).min(1).max(4).refine(yo),include:J.z.array(Ag).min(1).max(16),exclude:J.z.array(Ag).max(16),methods:J.z.array(J.z.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(yo),maxAgeHours:J.z.number().int().min(1).max(720)}),bg=yg.extend({revision:J.z.number().int().positive()}),zE=J.z.strictObject({repository:yg,expectedRevision:J.z.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),xg=J.z.strictObject({repositoryId:J.z.uuid(),branch:bo}),C0=J.z.array(bu).max(jn.keys).refine(yo),Sg=J.z.strictObject({repository:bg.omit({keyIds:!0}),branch:bo,keys:C0,keySetHash:J.z.string().regex(/^[a-f0-9]{64}$/)}),_0=J.z.strictObject({filePath:P0,startingLineNumber:J.z.number().int().min(1).max(1e7)}),xu=J.z.strictObject({protocol:J.z.literal(1),repositoryId:J.z.uuid(),branch:bo,workflow:J.z.string().max(200),configurationRevision:J.z.number().int().positive(),keySetHash:J.z.string().regex(/^[a-f0-9]{64}$/),commit:J.z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:J.z.uuid(),runNumber:J.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:J.z.number().int().min(1).max(1e4),scannerVersion:J.z.literal("1"),scannedAt:J.z.iso.datetime({offset:!0}),coverage:J.z.strictObject({complete:J.z.literal(!0),files:J.z.number().int().min(0).max(jn.files),sourceBytes:J.z.number().int().min(0).max(jn.sourceBytes),unresolvedCalls:J.z.number().int().min(0).max(1e6),unsupportedFiles:J.z.number().int().min(0).max(jn.files)}),features:J.z.array(J.z.strictObject({key:bu,refs:J.z.array(_0).max(jn.referencesPerKey)})).max(jn.keys)}).superRefine((e,t)=>{yo(e.features.map(n=>n.key))||t.addIssue({code:"custom",path:["features"],message:"Duplicate feature"}),e.features.reduce((n,r)=>n+r.refs.length,0)>jn.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),Su=J.z.strictObject({scanId:J.z.uuid(),commit:J.z.string(),receivedAt:J.z.string(),references:J.z.number().int().nonnegative(),removedReferences:J.z.number().int().nonnegative()}),E0=Su.extend({repositoryId:J.z.uuid(),branch:bo,workflow:J.z.string(),digest:J.z.string(),configurationRevision:J.z.number().int().positive(),runNumber:J.z.number().int().positive(),runAttempt:J.z.number().int().positive(),scannedAt:J.z.string(),keySetHash:J.z.string(),coverage:xu.shape.coverage}),R0=J.z.strictObject({repositories:J.z.array(bg).max(jn.repositories),scans:J.z.array(E0).max(jn.repositories*jn.branches)}),k0=J.z.strictObject({key:bu,references:J.z.number().int().nonnegative(),coveredTargets:J.z.number().int().nonnegative(),expiredTargets:J.z.number().int().nonnegative(),uncertainTargets:J.z.number().int().nonnegative()}),$E=J.z.strictObject({available:J.z.boolean().default(!0),settings:R0,expectedTargets:J.z.number().int().min(0).max(80),features:J.z.array(k0).max(2001),truncated:J.z.boolean()});var St=require("zod");var j0=St.z.enum(["checkout.session.completed","checkout.session.expired","checkout.session.async_payment_succeeded","checkout.session.async_payment_failed","customer.subscription.created","customer.subscription.updated","customer.subscription.deleted","customer.subscription.paused","customer.subscription.resumed","invoice.created","invoice.paid","customer.discount.created","customer.discount.updated","refund.created","refund.updated","refund.failed","charge.refunded"]),T0=St.z.strictObject({provider:St.z.literal("stripe"),accountId:St.z.string().regex(/^acct_[A-Za-z0-9]+$/),eventId:St.z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),type:j0,occurredAt:St.z.number().int().positive().max(Number.MAX_SAFE_INTEGER),data:St.z.record(St.z.string(),St.z.unknown()).and(St.z.object({id:St.z.string().min(1).max(255),object:St.z.enum(["checkout.session","subscription","invoice","discount","refund","charge"]),livemode:St.z.boolean()}))}),Ig=St.z.union([T0,Pl]),vg=St.z.strictObject({id:St.z.uuid(),eventId:St.z.string().min(1).max(200),source:St.z.literal("merchant"),providerVerified:St.z.literal(!1),outcome:St.z.string().min(1).max(100)});var Vt=require("zod"),Og={customerId:Vt.z.uuid(),eventId:Vt.z.string().trim().min(1).max(200),grantId:Vt.z.uuid(),occurredAt:Vt.z.iso.datetime({offset:!0})},Pg=Vt.z.strictObject({...Og,productVersionId:Vt.z.uuid(),subscriptionId:Vt.z.string().trim().min(1).max(255)}),Cg=Vt.z.strictObject({...Og,merchandiseId:Vt.z.uuid()}),_g=Vt.z.union([Pg,Cg]),wg={id:Vt.z.uuid(),couponId:Vt.z.uuid(),status:Vt.z.literal("redeemed"),source:Vt.z.literal("merchant"),recordedAt:Vt.z.iso.datetime({offset:!0})},Eg=Vt.z.union([Pg.extend(wg),Cg.extend(wg)]);var re=require("zod");var Rg=tm,N0=Rg.extend({invoice_id:Rg.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),Iu=re.z.strictObject({name:re.z.string().trim().min(1).max(255),memo:re.z.string().max(1e4).nullable().optional(),footer:re.z.string().max(1e4).nullable().optional(),net_terms_days:re.z.number().int().positive().nullable().optional()}),D0=Iu.extend({id:re.z.string().min(1).max(255),created_at:re.z.number().nullable()}),kg=re.z.strictObject({items:re.z.array(D0).max(50),nextCursor:re.z.uuid().nullable()}),ZE=re.z.discriminatedUnion("action",[re.z.strictObject({action:re.z.literal("create"),requestId:re.z.uuid(),values:Iu}),re.z.strictObject({action:re.z.literal("update"),id:re.z.string().min(1).max(255),values:Iu}),re.z.strictObject({action:re.z.literal("delete"),id:re.z.string().min(1).max(255)})]),jg=re.z.discriminatedUnion("action",[re.z.strictObject({action:re.z.literal("create"),requestId:re.z.uuid(),params:mi}),re.z.strictObject({action:re.z.enum(["finalize","send","pay","void"]),requestId:re.z.uuid(),invoiceId:re.z.uuid()}),re.z.strictObject({action:re.z.literal("reissue"),requestId:re.z.uuid(),invoiceId:re.z.uuid(),params:N0})]),vu=re.z.strictObject({id:re.z.uuid(),customerId:re.z.uuid(),providerInvoiceId:re.z.string().nullable(),status:re.z.enum(["draft","open","paid","void","uncollectible"]),currency:re.z.string(),totalMinor:re.z.string().regex(/^-?\d+$/),paidMinor:re.z.string().regex(/^\d+$/),refundedMinor:re.z.string().regex(/^\d+$/),hostedInvoiceUrl:re.z.url().nullable(),createdAt:re.z.number(),collectionMethod:re.z.enum(["send_invoice","charge_automatically"]).nullable()}),Tg=vu.extend({lines:re.z.array(re.z.strictObject({id:re.z.uuid(),description:re.z.string(),amountMinor:re.z.string().regex(/^-?\d+$/),netAmountMinor:re.z.string().regex(/^-?\d+$/),quantity:re.z.number().nullable(),periodStart:re.z.number().nullable(),periodEnd:re.z.number().nullable()})).max(1e3)}),Pi=re.z.strictObject({taskId:re.z.uuid(),status:re.z.enum(["ready","running","done","dead"]),invoice:vu.nullable(),errorCode:re.z.string().nullable()}),Ng=re.z.strictObject({items:re.z.array(vu).max(50),nextCursor:re.z.uuid().nullable(),operations:re.z.array(Pi).max(50),operationsLimited:re.z.boolean()});var F0=v.z.enum(["customers:read","customers:write","entitlements:read","content:read","sessions:create","funnels:run","offers:resolve","offers:grant","billing:read","billing:write","credits:read","credits:consume","credits:manage","features:read","events:write","messaging:write","code-references:read","code-references:write","app-manifests:write"]),Dg={scope:Ne,permissions:v.z.array(F0),expiresAt:v.z.iso.datetime().nullable()},LR=v.z.discriminatedUnion("kind",[v.z.object({...Dg,kind:v.z.literal("server"),keyId:v.z.string().min(1)}),v.z.object({...Dg,kind:v.z.literal("customer"),customerId:v.z.string().min(1),identityKind:v.z.enum(["identified","guest"]),expiresAt:v.z.iso.datetime()})]),z=v.z.object({requestId:v.z.uuid(),scope:Ne}).strict(),M0=yf.safeExtend({fingerprint:za.optional()}).strict(),q0=z.extend({customer:Si,created:v.z.boolean()});function Fg(){return z.extend({offer:Li.nullable(),reason:jd.nullable()})}var O={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:Ip,response:z.extend({message:v.z.object({messageId:v.z.uuid(),channel:Yi,acceptedAt:v.z.iso.datetime({offset:!0}),status:v.z.enum(["accepted","sending","completed","canceled"]),replayed:v.z.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:v.z.strictObject({messageId:v.z.uuid()}),response:z.extend({message:v.z.object({id:v.z.uuid(),channel:Yi,status:v.z.enum(["accepted","sending","completed","canceled"]),deliveries:v.z.array(v.z.object({id:v.z.uuid(),status:wp,attempts:v.z.number().int().nonnegative(),receipts:v.z.array(v.z.object({kind:Op,occurredAt:v.z.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:ul,response:z.extend({installation:Sr})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:ll,response:z.extend({installation:Sr})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:Do,response:z.extend({installation:Sr})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:v.z.strictObject({channel:Yi}),response:z.extend({preference:Ss})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:vp,response:z.extend({preference:Ss})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:v.z.strictObject({cursor:v.z.uuid().optional()}),response:z.extend({templates:kg})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),params:mi}),response:z.extend({preview:Ic})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),requestId:v.z.uuid(),params:mi}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:z.extend({operation:Pi})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),command:jg}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:z.extend({operation:Pi})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),taskId:v.z.uuid()}),response:z.extend({operation:Pi})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),cursor:v.z.uuid().optional()}),response:z.extend({invoices:Ng})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),invoiceId:v.z.uuid()}),response:z.extend({invoice:Tg})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:xg,response:z.extend({config:Sg})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:xu,response:z.extend({receipt:Su})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:v.z.strictObject({}),response:z.extend({payload:po})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:Km,response:z.merge(Ta)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:Hm,response:z.merge(Qm)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),sourceId:v.z.uuid()}),response:z.extend({balance:Gf})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),command:$f}),response:z.extend({balance:fu})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:v.z.strictObject({internal_feature_id:v.z.uuid(),customerId:v.z.uuid().optional(),entityId:v.z.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:z.extend({internal_feature_id:v.z.uuid(),config:Fs,model_markups:Ko})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),query:da}),response:z.extend({usage:Ji})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),command:mp}),response:z.extend({usage:Ji})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),command:sp}),response:z.extend({grant:oc})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:cp,response:z.extend({grants:up})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:v.z.union(Nm.options.map(e=>e.extend({customerId:v.z.uuid().optional(),customerToken:v.z.string().regex(jt).optional()}))),response:z.extend({operation:Dm})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:vm.extend({customerId:v.z.uuid().optional()}),response:z.extend({setup:Cc})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:wm.extend({customerId:v.z.uuid().optional()}),response:z.extend({setup:Cc})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:xm.safeExtend({customerId:v.z.uuid()}),response:z.extend({batch:ao})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:Pa.extend({customerId:v.z.uuid()}),response:z.extend({batch:ao})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:Pa.extend({customerId:v.z.uuid()}),response:z.extend({batch:ao})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:Pa.extend({customerId:v.z.uuid()}),response:z.extend({batch:ao})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:v.z.discriminatedUnion("action",[Ca.options[0].extend({customerId:v.z.uuid()}),Ca.options[1].extend({customerId:v.z.uuid()}),Ca.options[2].extend({customerId:v.z.uuid()})]),response:z.extend({trial:Pc})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Sm.extend({customerId:v.z.uuid()}),response:z.extend({trial:Pc})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:Ra,response:z.extend({subscriptions:km})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:Ra,response:z.extend({purchases:jm})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:_m,response:z.extend({conflicts:Tm})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:Em,response:z.extend({resolution:Rm})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:Pm,response:z.extend({verification:Cm})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:pm.safeExtend({...di,customerId:v.z.uuid().optional()}),response:z.extend({quote:fi})},recordBillingEvent:{method:"POST",path:"billing/events/record",permission:"billing:write",audience:"server",request:Ig,response:z.extend({record:vg})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Mr.extend({customerId:v.z.uuid().optional(),intent:v.z.enum(["confirm","cancel"]).optional()}),response:z.extend({operation:gi})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Mr.extend({customerId:v.z.uuid().optional()}),response:z.extend({operation:gi})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:gm.safeExtend({customerId:v.z.uuid().optional()}),response:z.extend({quote:Am})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Mr.extend({customerId:v.z.uuid().optional(),intent:v.z.enum(["confirm","cancel"]).optional()}),response:z.extend({operation:vc})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Mr.extend({customerId:v.z.uuid().optional()}),response:z.extend({operation:vc})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:ym.safeExtend({customerId:v.z.uuid()}),response:z.extend({quote:wc})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Mr.extend({customerId:v.z.uuid()}),response:z.extend({operation:Oa})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Mr.extend({customerId:v.z.uuid()}),response:z.extend({operation:Oa})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:Kd,response:z.extend({controls:rc})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:Bd,response:z.extend({prepared:Ld})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:Ud,response:z.extend({authorization:sa})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Wd,response:z.extend({coupons:Yd})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:zd,response:z.extend({authorization:sa})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:Jd,response:z.extend({invoices:Zd})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:Qd.extend({customerId:v.z.uuid()}),response:z.extend({operation:Pi})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:Hd,response:z.extend({invoice:$i})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:v.z.object({customerId:v.z.uuid(),command:Gd}).strict(),response:z.extend({controls:rc})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:v.z.object({customerId:v.z.uuid(),command:Kf}).strict(),response:z.extend({entity:Hf})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:v.z.strictObject({customerId:v.z.uuid().nullable(),query:Xf}),response:z.extend({analytics:eg})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:v.z.object({customerId:v.z.uuid().nullable(),query:Gr}).strict(),response:z.extend({analytics:Wf})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:tg,response:z.extend({batchId:v.z.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:ng,response:z.extend({batch:rg})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:Ep.extend({customerId:v.z.string().min(1).optional()}),response:z.extend({check:Tr})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:v.z.strictObject({kind:rr,selector:v.z.discriminatedUnion("type",[v.z.strictObject({type:v.z.literal("resource"),id:v.z.uuid()}),v.z.strictObject({type:v.z.literal("version"),id:v.z.uuid()})]),customerId:v.z.string().min(1).optional()}),response:z.extend({content:bc})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Lf,response:z.extend({paywall:Ur})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:v.z.strictObject({processContext:Sa.optional(),...di,selector:Bm,customerId:v.z.string().min(1).optional(),commerce:ai,requirement:er.optional()}),response:z.extend({offering:Vm,candidates:v.z.array(lc).max(20),availability:v.z.array(v.z.strictObject({productVersionId:v.z.uuid(),available:v.z.boolean(),reason:v.z.enum(["platform_binding_missing","commercial_runtime_pending","commerce_not_configured","currency_mismatch","product_unavailable","already_attached","attach_in_progress","already_scheduled","subscription_change_required","purchase_conflict"]).nullable()})).max(20),check:Tr.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:v.z.object({customerId:v.z.uuid().optional(),entityId:v.z.uuid().optional()}).strict(),response:z.extend({holdings:fp})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:v.z.object({customerId:v.z.uuid().optional(),query:hp}).strict(),response:z.extend({ledger:Ap})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:lp.extend({customerId:v.z.uuid().optional()}),response:z.extend({detail:dp})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:ac.safeExtend({customerId:v.z.uuid().optional()}),response:z.extend({statement:pp})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:v.z.object({customerId:v.z.uuid().optional(),command:Hi.options[0]}).strict(),response:z.extend({quote:ip})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),command:v.z.union([v.z.strictObject({eventName:v.z.string().min(1),quantity:Ae.optional(),properties:wt.optional(),entityId:v.z.uuid().optional(),idempotencyKey:v.z.string().min(1).max(120)}),v.z.strictObject({internal_feature_id:v.z.uuid(),quantity:Ae.optional(),properties:wt.optional(),entityId:v.z.uuid().optional(),idempotencyKey:v.z.string().min(1).max(120)})])}),response:z.extend({receipts:v.z.array(Qi).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:v.z.object({customerId:v.z.uuid(),command:Hi.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:z.extend({receipt:Qi})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:pg,response:z.extend({redemption:dg})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:gg,response:z.extend({referralCode:hg})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:mg,response:z.extend({checkout:fg})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:bp,response:z.extend({seats:uc})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:xp,response:z.extend({seats:uc})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:M0,response:q0},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Wc,response:z.extend({customer:Si})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:Sf,response:z.extend(If.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:xf,response:z.extend(bf.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:v.z.object({customerId:v.z.uuid()}).strict(),response:z.extend(Qn.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:v.z.strictObject({}),response:z.extend(Qn.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),sessionId:v.z.uuid().optional()}),response:z.extend({revoked:v.z.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:v.z.strictObject({guestToken:v.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:za.optional()}),response:z.extend({customerId:v.z.uuid(),guestToken:v.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:v.z.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:v.z.strictObject({guestToken:v.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:z.extend(Qn.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:v.z.strictObject({guestToken:v.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:v.z.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:v.z.uuid()}),response:z.extend({customer:Si,switched:v.z.boolean(),replayed:v.z.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:v.z.strictObject({code:v.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:v.z.uuid()}),response:Fg()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:v.z.object({}).strict(),response:z.extend({offers:v.z.array(Li)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:v.z.object({customerId:v.z.string().min(1).max(255).optional(),couponId:v.z.uuid(),...di,requestId:v.z.uuid(),couponContentDigest:v.z.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:Fg()},recordCouponRedemption:{method:"POST",path:"offers/redemptions",permission:"billing:write",audience:"server",request:_g,response:z.extend({receipt:Eg})}},UR={recordBillingEvent:O.recordBillingEvent,sendMessage:O.sendMessage,readMessage:O.readMessage,bindPushInstallation:O.bindPushInstallation,readPushInstallation:O.readPushInstallation,updatePushAddress:O.updatePushAddress,readMessagingPreference:O.readMessagingPreference,setMessagingPreference:O.setMessagingPreference,listInvoiceTemplates:O.listInvoiceTemplates,previewInvoice:O.previewInvoice,createInvoice:O.createInvoice,manageInvoice:O.manageInvoice,readInvoiceOperation:O.readInvoiceOperation,listInvoices:O.listInvoices,getInvoice:O.getInvoice,getCodeReferenceConfig:O.getCodeReferenceConfig,submitCodeReferences:O.submitCodeReferences,getFeatures:O.getFeatures,evaluateFeatures:O.evaluateFeatures,trackEvents:O.trackEvents,setupPayment:O.setupPayment,readPaymentSetup:O.readPaymentSetup,previewSubscriptionBatch:O.previewSubscriptionBatch,confirmSubscriptionBatch:O.confirmSubscriptionBatch,readSubscriptionBatch:O.readSubscriptionBatch,abandonSubscriptionBatch:O.abandonSubscriptionBatch,manageSubscriptionTrial:O.manageSubscriptionTrial,readSubscriptionTrial:O.readSubscriptionTrial,listSubscriptions:O.listSubscriptions,listPurchases:O.listPurchases,listSubscriptionConflicts:O.listSubscriptionConflicts,retrySubscriptionConflict:O.retrySubscriptionConflict,readAiPricing:O.readAiPricing,readUsage:O.readUsage,setUsage:O.setUsage,previewRefund:O.previewRefund,refund:O.refund,readRefund:O.readRefund,previewUpdate:O.previewUpdate,update:O.update,readSubscriptionUpdate:O.readSubscriptionUpdate,restoreNativePurchase:O.restoreNativePurchase,verifySubscriptions:O.verifySubscriptions,previewAttach:O.previewAttach,attach:O.attach,readSubscriptionOperation:O.readSubscriptionOperation,manageBalanceGrant:O.manageBalanceGrant,readBalanceSource:O.readBalanceSource,adjustBalance:O.adjustBalance,listBalanceGrants:O.listBalanceGrants,readBillingControls:O.readBillingControls,prepareBillingAuthorization:O.prepareBillingAuthorization,confirmBillingAuthorization:O.confirmBillingAuthorization,setBillingCoupons:O.setBillingCoupons,revokeBillingAuthorization:O.revokeBillingAuthorization,listBillingInvoices:O.listBillingInvoices,confirmBillingAdjustment:O.confirmBillingAdjustment,prepareBillingAdjustment:O.prepareBillingAdjustment,manageBillingLimits:O.manageBillingLimits,createCustomer:O.createCustomer,getCustomer:O.getCustomer,listCustomers:O.listCustomers,updateCustomer:O.updateCustomer,createSession:O.createSession,refreshSession:O.refreshSession,revokeSessions:O.revokeSessions,createGuestCustomer:O.createGuestCustomer,resumeGuestSession:O.resumeGuestSession,claimGuestCustomer:O.claimGuestCustomer,checkEntitlement:O.checkEntitlement,resolveOffering:O.resolveOffering,resolveContent:O.resolveContent,resolvePaywall:O.resolvePaywall,readHoldings:O.readHoldings,readLedger:O.readLedger,readBillingInvoice:O.readBillingInvoice,readCreditStatement:O.readCreditStatement,quoteBalance:O.quoteBalance,trackUsage:O.trackUsage,mutateBalance:O.mutateBalance,manageUsageEntity:O.manageUsageEntity,readUsageAnalytics:O.readUsageAnalytics,readCreditAnalytics:O.readCreditAnalytics,submitUsageBatch:O.submitUsageBatch,readUsageBatch:O.readUsageBatch,listOffers:O.listOffers,grantOffer:O.grantOffer,recordCouponRedemption:O.recordCouponRedemption,redeemCoupon:O.redeemCoupon,redeemReward:O.redeemReward,createReferralCode:O.createReferralCode,claimRewardProduct:O.claimRewardProduct,readSeats:O.readSeats,manageSeat:O.manageSeat};var Xa=require("zod");var xo=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function wu(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=>Wt(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 xo("Required GB Feature is unavailable");i=Ln(e.featureKey,t),o=i.value,Object.assign(r,li(e,{value:o})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new xo("Required GB Experiment is unavailable");if(a=oa(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 xo("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:Ln(e.configuration.featureKey,t).value;o={type:"offering_version",id:Xa.z.uuid().parse(u)},Object.assign(r,li(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,li(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 Mg(e,t,n){Xa.z.uuid().parse(e),Xa.z.number().int().nonnegative().parse(t);let r=ei(ti(new TextEncoder().encode(JSON.stringify([e,t,n])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}var K=require("zod");var ur=K.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),B0=K.z.enum(["running","waiting","completed","closed","ineligible","failed"]),Ou=K.z.discriminatedUnion("type",[Jc,K.z.strictObject({type:K.z.literal("wait"),receiptId:K.z.uuid(),kind:K.z.enum(["timer","event","operation"]),deadline:K.z.iso.datetime({offset:!0}).nullable(),eventName:ur.optional()}),K.z.strictObject({type:K.z.literal("open_url"),receiptId:K.z.uuid(),url:Yc,openIn:Xc}),K.z.strictObject({type:K.z.literal("event"),receiptId:K.z.uuid(),event:ur})]),es=K.z.strictObject({type:K.z.literal("funnel"),id:K.z.uuid(),versionId:K.z.uuid()}),V0={id:ur,presentation:Kn,outputs:K.z.array(ur).max(250),inputs:Ma,values:K.z.record(K.z.string(),Se).optional(),offeringKey:yt.optional(),capabilities:si,customerData:Fp,dataCursors:K.z.record(ur,Fa.nullable())},L0=K.z.strictObject({...V0,content:K.z.strictObject({type:K.z.literal("document"),document:sn})}),So=K.z.strictObject({id:K.z.uuid(),source:es,revision:K.z.number().int().nonnegative(),visit:K.z.number().int().nonnegative(),nodeId:ur,nodeType:K.z.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:B0,stopped:K.z.boolean(),canBack:K.z.boolean(),authenticated:K.z.boolean(),locale:K.z.string().min(1).max(35),answers:or,parameters:ar,variables:K.z.record(K.z.string(),Se),output:Se.nullable(),screen:L0.nullable(),paywall:K.z.strictObject({receiptId:K.z.uuid(),resolution:K.z.union([Ao,Ur]),quote:fi.nullable(),operation:gi.nullable(),purchaseRequestId:K.z.uuid().nullable(),selectionGeneration:K.z.number().int().nonnegative().optional(),canReselect:K.z.boolean().optional()}).nullable(),instruction:Ou.nullable(),pendingRequest:K.z.strictObject({requestId:K.z.uuid(),authenticationRequired:K.z.boolean()}).nullable(),runExpiresAt:K.z.iso.datetime({offset:!0}),credentialExpiresAt:K.z.iso.datetime({offset:!0}).nullable()}),ts=K.z.strictObject({scope:Ne,run:So,settlement:K.z.strictObject({requestId:K.z.uuid(),state:K.z.enum(["pending","unknown","settled"]),operationId:K.z.uuid().nullable(),receiptId:K.z.uuid().nullable().optional()}).optional(),purchase:K.z.strictObject({receiptId:K.z.uuid(),quote:fi.nullable(),operation:gi.nullable(),canReselect:K.z.boolean().optional()}).optional(),review:K.z.strictObject({activeOperationId:K.z.uuid().nullable(),pages:K.z.array(K.z.strictObject({receiptId:K.z.uuid(),nodeId:ur,visit:K.z.number().int().nonnegative()})).max(100),page:K.z.strictObject({receiptId:K.z.uuid(),nodeId:ur,visit:K.z.number().int().nonnegative(),document:sn,answers:or,inputs:Ma,values:K.z.record(K.z.string(),Se).optional()}).nullable(),coupons:K.z.array(K.z.strictObject({grantId:K.z.uuid(),status:K.z.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:K.z.string().nullable()})).max(100),purchases:K.z.array(K.z.strictObject({receiptId:K.z.uuid(),operationId:K.z.uuid(),status:K.z.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:K.z.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:K.z.uuid().optional()}),qg=ts.extend({run:So.extend({paywall:So.shape.paywall.unwrap().extend({resolution:Ur}).nullable()})});var Bg="X-Indiana-Server-Key";var oe=require("zod");var ge=require("zod");var It=require("zod");var U0=It.z.strictObject({selector:It.z.string().min(1).max(2048),action:It.z.enum(["set","append","remove"]),attribute:It.z.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:It.z.string().max(5e4).optional(),parentSelector:It.z.string().max(2048).optional(),insertBeforeSelector:It.z.string().max(2048).optional()}),z0=It.z.strictObject({variation:It.z.string().min(1).max(128),description:It.z.string().max(2e3).default(""),css:It.z.string().max(1e5).default(""),js:It.z.string().max(1e5).default(""),domMutations:It.z.array(U0).max(200).default([]),iam:rf.optional(),renderGuard:Na.optional()}),Pu=z0.omit({variation:!0,description:!0,iam:!0}),$0=bi.omit({variations:!0,active:!0}).extend({changeId:It.z.string().regex(/^[a-f0-9]{64}$/),variations:It.z.tuple([Pu,Pu]).rest(Pu).refine(e=>e.length<=20)}),Vg=It.z.strictObject({trackExposures:It.z.boolean(),environmentId:It.z.uuid(),generation:It.z.string().regex(/^[a-f0-9]{64}$/),experiments:It.z.array($0).max(100),savedGroups:lo});var Io=ge.z.string().regex(/^[a-f0-9]{64}$/),yk=ge.z.strictObject({iam:Io,executionContracts:ge.z.union([ge.z.tuple([ge.z.literal("funnel-run/1")]),ge.z.tuple([ge.z.literal("funnel-process/1")])]).default(["funnel-run/1"])}),G0=ge.z.strictObject({release:Io,render:Na,button:ge.z.strictObject({selector:ge.z.string().min(1).max(512),elementKey:ge.z.string().min(1).max(256),tag:ge.z.enum(["button","a","input"])}).nullable()}),bk=ge.z.strictObject({scope:Ne.extend({environmentId:ge.z.uuid()}),release:Io,validatedAt:ge.z.iso.datetime({offset:!0}),validUntil:ge.z.iso.datetime({offset:!0}),entries:ge.z.array(ge.z.strictObject({id:ge.z.uuid(),funnelId:ge.z.uuid(),versionId:ge.z.uuid(),event:ge.z.enum(["screen_enter","button_click"]),target:G0})).max(4e3)}),Lg=ge.z.strictObject({operation:ge.z.literal("entry_start"),funnelId:ge.z.uuid(),versionId:ge.z.uuid(),entryId:ge.z.uuid(),release:Io,requestId:ge.z.uuid(),locale:ge.z.string().min(1).max(35).default("en")}),Ug=ge.z.strictObject({scope:Ne,suppressed:ge.z.literal(!0),reason:ge.z.enum(["frequency","in_progress"]),retryAt:ge.z.iso.datetime({offset:!0}).nullable()}),xk=ge.z.strictObject({experimentId:ge.z.uuid(),splitNodeId:ge.z.string().min(1).max(128)}),K0=ge.z.strictObject({experimentId:ge.z.uuid(),experimentKey:ge.z.string().min(1).max(128),variationKey:ge.z.string().min(1).max(128),inExperiment:ge.z.boolean(),generation:ge.z.string().min(1).max(256)}),vo=ge.z.strictObject({operation:ge.z.literal("page_experiments"),release:Io,usedReceiptIds:ge.z.array(ge.z.uuid()).max(20).default([]),customerToken:ge.z.string().regex(jt).optional()}),zg=ge.z.strictObject({scope:Ne,runId:ge.z.uuid(),assignments:ge.z.array(K0.extend({receiptId:ge.z.uuid()})).max(100),payload:Vg});var Pn=oe.z.literal(Wm),H0=oe.z.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),Cu=oe.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),$g=oe.z.discriminatedUnion("type",[oe.z.strictObject({type:oe.z.literal("guest"),guestToken:Cu}),oe.z.strictObject({type:oe.z.literal("customer"),customer:Vr,customerData:xi.optional()})]),_u=oe.z.strictObject({id:oe.z.uuid(),runId:oe.z.uuid(),customerId:oe.z.uuid(),requestId:oe.z.uuid(),acceptedAt:oe.z.iso.datetime({offset:!0})}),Q0=oe.z.strictObject({participantId:oe.z.uuid(),startedAs:oe.z.enum(["guest","identified"]),binding:_u.omit({runId:!0,requestId:!0}).nullable()}),J0=oe.z.union([Ou,oe.z.strictObject({type:oe.z.literal("authentication_required"),reason:oe.z.enum(["customer_required","customer_experiment_required"]),nodeId:oe.z.string().min(1).max(64),visit:oe.z.number().int().nonnegative()})]),Z0=So.omit({authenticated:!0}).extend({identity:Q0,instruction:J0.nullable()}),W0=oe.z.discriminatedUnion("operation",[Pt.options[2].omit({customerToken:!0}),Pt.options[3].omit({customerToken:!0}),Pt.options[4].omit({customerToken:!0}),Pt.options[5].omit({customerToken:!0}),Pt.options[6].omit({customerToken:!0}),Pt.options[7].omit({customerToken:!0})]),ns={contract:Pn,customerToken:oe.z.string().regex(jt)},Gg={contract:Pn,requestId:oe.z.uuid(),runToken:H0,externalUserId:Vr.options[1].shape.value},Kg=oe.z.discriminatedUnion("operation",[oe.z.strictObject({contract:Pn,operation:oe.z.literal("describe")}),oe.z.strictObject({contract:Pn,operation:oe.z.literal("start"),source:$g,funnelId:Pt.options[0].shape.funnelId,requestId:oe.z.uuid(),locale:Pt.options[0].shape.locale,parameters:Pt.options[0].shape.parameters}),Lg.omit({operation:!0}).extend({contract:Pn,operation:oe.z.literal("entry_start"),source:$g}),oe.z.strictObject({...Gg,operation:oe.z.literal("bind_customer"),guestToken:Cu,claimRequestId:oe.z.uuid(),expectedBindingId:oe.z.null()}),oe.z.strictObject({...Gg,operation:oe.z.literal("binding_status"),guestToken:Cu.optional()}),Pt.options[1].omit({operation:!0,customerToken:!0}).extend({...ns,operation:oe.z.literal("get"),settlementBindingId:oe.z.uuid().nullable().optional()}),Pt.options[8].omit({operation:!0,customerToken:!0}).extend({...ns,operation:oe.z.literal("review")}),vo.omit({customerToken:!0}).extend(ns),oe.z.strictObject({...ns,operation:oe.z.literal("command"),identity:oe.z.strictObject({bindingId:oe.z.uuid().nullable()}),command:W0})]),Eu=ts.omit({run:!0}).extend({contract:Pn,run:Z0,settlement:ts.shape.settlement.unwrap().extend({accepted:oe.z.boolean().nullable().optional()}).optional()}),Ek=Ug.extend({contract:Pn}),Rk=oe.z.discriminatedUnion("operation",[Kg.options[1].omit({contract:!0,source:!0,requestId:!0}),Kg.options[2].omit({contract:!0,source:!0,requestId:!0})]),kk=Eu.extend({binding:_u,outcome:oe.z.enum(["bound","already_bound"]),replayed:oe.z.boolean()}),jk=oe.z.discriminatedUnion("state",[oe.z.strictObject({contract:Pn,scope:Ne,state:oe.z.literal("not_accepted")}),oe.z.strictObject({contract:Pn,scope:Ne,state:oe.z.literal("conflict")}),oe.z.strictObject({contract:Pn,scope:Ne,state:oe.z.literal("bound"),binding:_u})]),Tk=oe.z.strictObject({contract:Pn,scope:Ne,keyId:oe.z.uuid(),operations:oe.z.array(oe.z.string()).max(20)});var je=require("zod");var Ci=je.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Qg=je.z.strictObject({entry:Ci,nodes:je.z.array(je.z.strictObject({id:Ci,type:je.z.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:je.z.record(je.z.string(),Ci),writes:je.z.record(yt,yt),resources:je.z.strictObject({screenId:Ci.optional(),paywallVersionId:je.z.uuid().optional(),couponId:je.z.uuid().optional(),couponIds:je.z.array(je.z.uuid()).max(20).optional(),experimentId:je.z.uuid().optional(),featureKey:je.z.string().optional(),offeringVersionId:je.z.uuid().optional()})})).min(1).max(500)}),Hg={scope:Ne,funnelId:je.z.uuid(),versionId:je.z.uuid(),evaluationRevision:je.z.number().int().nonnegative(),expiresAt:je.z.iso.datetime({offset:!0}).nullable(),topology:Qg},rs=je.z.discriminatedUnion("evaluationMode",[je.z.strictObject({...Hg,evaluationMode:je.z.literal("local"),growth:gn,conditions:je.z.record(Ci,je.z.array(je.z.strictObject({condition:Jt,port:je.z.string()})))}),je.z.strictObject({...Hg,evaluationMode:je.z.literal("remote")})]),Y0=rs.options[0].extend({evaluation:je.z.strictObject({maxTransitions:je.z.number().int().min(1).max(1e4),variables:je.z.record(yt,ui),outputSchema:ci,terminals:je.z.record(Ci,je.z.strictObject({outcome:je.z.enum(["completed","closed","ineligible","failed"]),output:fo.nullable()}))})});function X0(e){return Qg.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=je.z.uuid().parse(t.action.coupon.value.id));break;case"external_page":n.opened=t.opened,n.failed=t.failed;break;case"wait":t.wait.type==="duration"?n.elapsed=t.wait.elapsed:(n.received=t.wait.received,n.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let i=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return i?.type==="feature"&&(r.featureKey=i.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:n,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function Ru(e){let t=vi.parse(e.document),n=e.evaluationMode==="local"?gn.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:X0(t)};return rs.parse(e.evaluationMode==="remote"?r:{...r,growth:Za(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 Jg(e){let t=Ru(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=vi.parse(e.document);return Y0.parse({...t,evaluation:{maxTransitions:n.execution.maxTransitions,variables:n.variables,outputSchema:n.outputSchema,terminals:Object.fromEntries(n.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}var et=require("zod");var Zg=et.z.string().regex(/^[a-f0-9]{64}$/),eI=bi.omit({variations:!0,active:!0}).extend({changeId:Zg,variations:et.z.array(et.z.strictObject({urlRedirect:et.z.string().max(2048)})).min(2).max(20)}),Wg=et.z.strictObject({environmentId:et.z.uuid(),trackExposures:et.z.boolean(),generation:Zg,experiments:et.z.array(eI).max(100),savedGroups:lo}),tI=et.z.strictObject({eventUuid:et.z.uuid(),timestamp:et.z.iso.datetime({offset:!0}).optional(),deviceId:et.z.string().min(1).max(128),sessionId:et.z.string().min(1).max(128).optional(),url:et.z.url().max(2048),pageTitle:et.z.string().max(512).optional(),experimentKey:et.z.string().min(1).max(255),variationKey:et.z.string().min(1).max(64)}),$k=et.z.strictObject({events:et.z.array(tI).min(1).max(20)}),Gk=et.z.strictObject({inserted:et.z.number().int().nonnegative(),duplicates:et.z.number().int().nonnegative(),skipped:et.z.number().int().nonnegative(),rejected:et.z.array(et.z.strictObject({index:et.z.number().int().nonnegative(),reason:et.z.string()}))});var ot=require("zod");var ju=32,nI=522240;function Tu(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 rI=ot.z.strictObject({nodeId:ot.z.string().min(1).max(64),visit:ot.z.number().int().nonnegative(),revision:ot.z.number().int().nonnegative()}),ku=ot.z.record(ot.z.string(),Se),iI=ot.z.strictObject({id:ot.z.uuid(),nodeId:ot.z.string().min(1).max(64),visit:ot.z.number().int().nonnegative(),input:ot.z.strictObject({schemaVersion:go.shape.schemaVersion,kind:go.shape.kind,selector:go.shape.selector,contract:go.shape.contract}),context:ku,removed:ot.z.array(ot.z.string()).max(100),attributes:ku,removedAttributes:ot.z.array(ot.z.string()).max(100),result:Ef,offeringVersionId:ot.z.uuid().nullable(),events:ot.z.strictObject({entered:ot.z.string().regex(/^[1-9][0-9]{0,18}$/),decision:ot.z.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),Zk=ot.z.strictObject({schemaVersion:ot.z.literal(1),mode:ot.z.enum(["local","remote"]),versionId:ot.z.uuid(),generation:ot.z.number().int().positive(),base:rI,context:ku,steps:ot.z.array(iI).min(1).max(ju)}).refine(e=>cn(e)<=nI,"Segment exceeds its byte budget");var oI=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function wo(e){return Array.isArray(e)?e.some(wo):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&wo(n):!oI.test(t))}function Yg(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=>wo(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"||wo(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"||wo(s.condition)||s.parentConditions?.length)?"customer_experiment_required":null}var Nu=class extends Error{constructor(n,r){super(r);Fe(this,"code",n);this.name="FunnelLocalCalculationError"}},Xg=(e,t)=>new Nu(e,t),aI=e=>({experiments:e.experiments,features:e.features});function sI(e,t=Xg){let n=new Map(e.topology.nodes.map(o=>[o.id,o])),r=ni(e.growth.savedGroups),i=aI(e.growth);function a(o,s){if(!Object.hasOwn(e.growth.features,o))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Ln(o,s).value}return{nodes:n,savedGroups:r,features:i.features,feature:a,evaluate(o,s){let c=n.get(o);if(!c)throw t("NOT_FOUND","Funnel node is unavailable");let u,l;if(c.type==="condition"){let m=e.conditions[c.id];if(!m)throw t("INVALID_RESPONSE","Local condition rules are unavailable");u=wu({id:c.id,name:c.id,type:"condition",cases:m.map(h=>({condition:h.condition,target:c.outputs[h.port]})),default:c.outputs.default},s,i.experiments).port}else if(c.type==="feature"){if(!c.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");l=a(c.resources.featureKey,s),u="next"}else if(c.type==="split"){if(!(c.resources.experimentId?e.growth.experiments[c.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let h=wu({id:c.id,name:c.id,type:"split",experimentId:c.resources.experimentId,routes:c.outputs,notParticipating:c.outputs.notParticipating},s,i.experiments);l=h.value,u=h.port}else if(["offering","end","output"].includes(c.type)&&c.resources.featureKey)l=a(c.resources.featureKey,s),u=c.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let f=c.outputs[u]??(u==="value"?c.id:void 0);if(!f)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:o,port:u,target:f,...l===void 0?{}:{value:l}}}}}function cI(e,t){let n=rs.parse(e);if(n.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=n.expiresAt?Date.parse(n.expiresAt):null,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let a=sI(n,t);return(o,s)=>(i(),uI(a,o,s))}function uI(e,t,n){let r=Ot.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 lI(e,t,n){let r=[],i=[],a=[],o=e(t,{...n.attributes?{attributes:n.attributes}:{},stickyBucketAssignmentDocs:n.sticky,saveStickyBucketAssignmentDoc(s){let c=r.findIndex(f=>f.next.attributeName===s.attributeName&&f.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(Se.parse({key:s.key,variationId:c.variationId,keyUsed:c.key,hashAttribute:c.hashAttribute,hashValue:c.hashValue}))},onFeatureUsage(s,c){a.push(Se.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 eh(e,t,n,r=Xg){let i=n,a=new Map(t.graph.nodes.map(k=>[k.id,k])),o=structuredClone(n.variables),s=structuredClone(i.sticky),c=[],u=n.nodeId,l=n.visit,f=!1,m,h=k=>Yg(t,k,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),d=k=>(m??(m=cI(e,r)),lI(m,k,{attributes:$c({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:o,savedGroups:{}}),sticky:s}));for(let k=0;k<ju;k++){let g=a.get(u);if(!g||!Tu(g)||h(g))break;if(l>=t.execution.maxTransitions&&(l>t.execution.maxTransitions||g.type!=="end"&&g.type!=="output")){if(!c.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let y,I;if(["condition","feature","split"].includes(g.type)||g.type==="offering"&&g.configuration.source==="feature")y=d(g.id),g.type==="offering"&&(y.value={type:"offering_version",id:String(y.value)}),g.type==="condition"?I=y.port==="default"?g.default:g.cases[Number(y.port.slice(5))]?.target:g.type==="split"?I=y.port==="notParticipating"?g.notParticipating:g.routes[y.port]:(g.type==="feature"||g.type==="offering")&&(I=g.next);else if(y={port:"next",sticky:[],exposures:[],features:[]},(g.type==="entry"||g.type==="coupon"||g.type==="coupons")&&(I=g.next),g.type==="offering"&&g.configuration.source==="fixed"&&(y.value={type:"offering_version",id:g.configuration.versionId},I=g.next),g.type==="end"||g.type==="output"){let C=g.type==="end"?g.output:g.value;if(y=C?.type==="feature"?d(g.id):{...y,port:"value",value:C?.type==="literal"?C.value:C?.type==="variable"?hc({source:"variable",key:C.key,...C.path?{path:C.path}:{}},{declarations:t.variables,answers:n.answers,results:o,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},C&&(y.value===void 0||!fn(t.outputSchema,y.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let w=[...c,{nodeId:u,result:y}];if(cn({steps:w})>6e4){if(!c.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(c.push({nodeId:u,result:y}),g.type==="feature"||g.type==="offering"||g.type==="coupon"||g.type==="coupons"){let C=g.type==="coupons"?g.couponIds.map(E=>({type:"reward",id:E})):g.type==="coupon"?{type:"reward",id:g.couponId}:y.value;if(C===void 0)throw r("INVALID_RESPONSE","Node output is missing");let j=li(g,{value:C});Up(t.variables,g,j),Object.assign(o,j)}for(let C of y.sticky)s[`${C.next.attributeName}||${C.next.attributeValue}`]=structuredClone(C.next);if(g.type==="end"||g.type==="output"){f=!0;break}if(!I)throw r("INVALID_RESPONSE","Local pure exit is unavailable");u=I,l++}let A=a.get(u);return{steps:c,...!f&&A&&(!Tu(A)||h(A))?{boundary:{nodeId:u,visit:l}}:{}}}var b=class extends Error{constructor(n,r,i,a,o){super(r);Fe(this,"code",n);Fe(this,"status",i);Fe(this,"requestId",a);Fe(this,"commandRequestId");Fe(this,"retryable");Fe(this,"recovery");Fe(this,"retryAfterSeconds");Fe(this,"reason");this.name="IndianaError",this.reason=o?.reason;let s=Fo(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 Oo=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new b("INVALID_STATE","Installation sequence exhausted");return e+1},dI=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 Tn(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 th(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=I=>{if(I!==i)throw new b("IDENTITY_CHANGED","Identity changed during Push operation")};async function f(I){let w=u();if(!w.sha256&&!globalThis.crypto?.subtle)throw new b("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let C=w.sha256?await w.sha256(Uint8Array.from(I,j=>j.charCodeAt(0))):await dI(I);if(!/^[a-f0-9]{64}$/.test(C))throw new b("INVALID_STATE","Push credential digest is invalid");return C}function m(I){let w=Sr.parse(I);if(w.installationId.toLowerCase()!==u().installationId.toLowerCase())throw new b("INVALID_RESPONSE","Push response belongs to another installation");return w}async function h(I,w){let C=u(),j={installationId:C.installationId,publicKey:C.publicKey,issuedAt:new Date().toISOString(),...w},E=await C.sign(fl(I,C.scope,j));return{...j,signature:E}}let d=(I,w,C)=>t.requestWithCredential?t.requestWithCredential(I,w,C):t.request(I,w);async function A(){let I=u(),w=i,C=r?await(t.session?.access()??r):null,j=Tn(I,ye=>ye),E;if(j.detachSeq!==null){let ye=j.detachSeq,gt=dl.parse(await h("detach",{sequence:ye,platform:I.platform}));try{let Je=await t.request("push/installations/detach",{...I.scope,...gt},"POST",{installationDetach:!0});if(!Je||typeof Je!="object"||!("installation"in Je))throw new b("INVALID_RESPONSE","Push detach acknowledgement is invalid");let Te=m(Je.installation);if(Te.bound||Te.identitySeq!==ye)throw new b("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(Je){if(Je instanceof b&&Je.status===404)E=Je;else if(!(Je instanceof b)||Je.status!==412)throw Je}E||Tn(I,Je=>({...Je,detachSeq:Je.detachSeq===ye?null:Je.detachSeq}))}if(l(w),!C){if(E)throw E;return null}let ae=O.bindPushInstallation,xe=ae.request.parse(await h("bind",{sequence:o,platform:I.platform,credentialDigest:await f(C)}));l(w);let Pe=ae.response.parse(await d(ae.path,xe,C));l(w);let Ee=m(Pe.installation);if(!Ee.bound||Ee.identitySeq!==o)throw new b("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return E&&j.detachSeq!==null&&o>j.detachSeq&&Tn(I,ye=>({...ye,detachSeq:ye.detachSeq===j.detachSeq?null:ye.detachSeq})),Ee}async function k(){u();let I=i,w=r?await(t.session?.access()??r):null;if(!w)throw new b("NOT_IDENTIFIED","Identify before reading this installation");let C=O.readPushInstallation,j=C.request.parse(await h("read",{credentialDigest:await f(w)}));l(I);let E=C.response.parse(await d(C.path,j,w));return l(I),m(E.installation)}function g(I=A){let w=s.catch(()=>{}).then(I);return s=w,w.catch(C=>{try{e?.onError?.(C instanceof Error?C:new Error("Push synchronization failed"))}catch{}}),w}async function y(I,w,C){let j=u(),E=w.identity,ae=w.observation,xe=r?await(t.session?.access()??r):null;if(l(E),ae!==a)throw new b("INVALID_STATE","Push observation changed during recovery");if(!xe)throw new b("NOT_IDENTIFIED","Identify before recovering a Push address");if(!I.connectionId||!I.kind||!I.token||!["granted","provisional"].includes(I.permission))throw new b("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await g(async()=>{if(l(E),await A(),l(E),ae!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let Pe=Tn(j,Te=>C?Te:{...Te,addressSeq:Oo(Te.addressSeq)}),ye=await h(C?"recovery_confirm":"recovery_request",{...I,sequence:Pe.addressSeq,credentialDigest:await f(xe),...C?{challenge:C}:{}}),gt=C?ml.parse(ye):pl.parse(ye);if(l(E),ae!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let Je=await d(`push/installations/recovery/${C?"confirm":"request"}`,gt,xe);if(l(E),ae!==a||Tn(j,Te=>Te).addressSeq!==Pe.addressSeq)throw new b("INVALID_STATE","Push observation changed during recovery");if(C){let Te=O.updatePushAddress.response.parse(Je),tt=m(Te.installation);if(!tt.bound||tt.identitySeq!==o||tt.addressSeq!==Pe.addressSeq||tt.connectionId!==I.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 xs.parse(Je.recovery)})}return{recoveryObserver(){u();let I={identity:i,observation:++a};return{async request(w){return xs.parse(await y(w,I))},async confirm(w,C){return Sr.parse(await y(C,I,w))}}},identify(I){if(!e)return;o=Tn(e,C=>({...C,identitySeq:Oo(C.identitySeq)})).identitySeq,r=I,i++,a++},reset(){if(e)try{Tn(e,I=>{let w=Oo(I.identitySeq);return{...I,identitySeq:w,detachSeq:w}})}finally{r=null,i++,a++}},start(){e&&!c&&g()},destroy(){c=!0,r=null,i++,a++},async sync(){return await g()},read:k,async recover(){let I=u(),w=i,C=o;return a++,await g(async()=>{l(w);let j=await k();return l(w),o=Tn(I,ae=>{if(ae.identitySeq!==C)throw new b("IDENTITY_CHANGED","A newer installation intent exists");return{...ae,identitySeq:Oo(Math.max(ae.identitySeq,j.identitySeq)),addressSeq:Math.max(ae.addressSeq,j.addressSeq)}}).identitySeq,await A()})},tokenObserver(){u();let I=++a,w=i;return async C=>{if(I!==a||w!==i)return null;let j=u(),E=r?await(t.session?.access()??r):null;if(!E)throw new b("NOT_IDENTIFIED","Identify before registering a Push token");if(await g(),l(w),I!==a)return null;let ae=Tn(j,ye=>({...ye,addressSeq:Oo(ye.addressSeq)})),xe=O.updatePushAddress,Pe=xe.request.parse(await h("address",{...C,sequence:ae.addressSeq,credentialDigest:await f(E)}));if(l(w),I!==a)return null;let Ee=await d(xe.path,Pe,E);return l(w),I!==a||Tn(j,ye=>ye).addressSeq!==ae.addressSeq?null:m(xe.response.parse(Ee).installation)}}}}var rh=require("zod");function nh(e,t,n,r){try{return e.parse(t)}catch(i){throw r&&i instanceof rh.ZodError?new b(n,r):i}}async function me(e,t,n,r={},i){let a=typeof r=="function"?{}:r,o=nh(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):nh(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 ih(e,t){let n={async preference(r){let i=O.readMessagingPreference;return(await me(e,i,{channel:r})).preference},async setPreference(r){let i=O.setMessagingPreference;return(await me(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 oh={name:"@tinkerlandai/longplay-sdk",version:"0.10.11",description:"Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};function Ke(e){return typeof e=="string"?e:String(e)}var mI=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function fI(e){return e.replace(mI,"$1\uFFFD")}function qu(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 fh(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 ah(e){let t;if(Array.isArray(e)){let n=e.map(Ke);if(n.length===2)return n}else if((t=fh(e))!=null){let n=qu(t.next()),r=qu(t.next());if(!n.done&&!r.done)return[Ke(n.value),Ke(r.value)]}throw new TypeError("Each query pair must be an iterable [name, value] tuple")}var sh="0123456789ABCDEF",gI=/(?:%[0-9A-Fa-f]{2})+/g;function Nn(e){return`%${sh[e>>4&15]}${sh[15&e]}`}function gh(e,t,n=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?n&&e===32?"+":t(e)?Nn(e):String.fromCharCode(e):e<=2047?Nn(192|e>>6)+Nn(128|63&e):e<=65535?Nn(224|e>>12)+Nn(128|e>>6&63)+Nn(128|63&e):Nn(240|e>>18)+Nn(128|e>>12&63)+Nn(128|e>>6&63)+Nn(128|63&e)}function Bu(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function Vu(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(gI,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function _o(e){return e<=31||e>126}function hI(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return _o(e)}}function Hu(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return _o(e)}}function AI(e){return Hu(e)||e===39}function Lu(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return Hu(e)}}function cs(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 Lu(e)}}function ch(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 cs(n)}})(e)}}function hh(e,t){return gh(e=e||0,t)}function Dn(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+=gh(o,t,n)}return i}function Qu(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([Vu(i.slice(0,a),!0),Vu(i.slice(a+1),!0)])}if(n=r+1,r===e.length)break}return t}function Uu(e){let t="";for(let n=0;n<e.length;n++){let r=Dn(e[n][0],ch,!0),i=Dn(e[n][1],ch,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var yI=[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],bI=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],xI=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],SI=[2381,2381,2509,2509,2637,2637,2765,2765,2893,2893,3021,3021,3149,3149,3277,3277,3387,3388,3405,3405,3530,3530,3642,3642,3770,3770,3972,3972,4153,4154,5908,5909,5940,5940,6098,6098,6752,6752,6980,6980,7082,7083,7154,7155,11647,11647,43014,43014,43052,43052,43204,43204,43347,43347,43456,43456,43766,43766,44013,44013,68159,68159,69702,69702,69744,69744,69759,69759,69817,69817,69939,69940,70080,70080,70197,70197,70378,70378,70477,70477,70606,70608,70722,70722,70850,70850,71103,71103,71231,71231,71350,71350,71467,71467,71737,71737,71997,71998,72160,72160,72244,72244,72263,72263,72345,72345,72767,72767,73028,73029,73111,73111,73537,73538,90415,90415];function II(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[vI,wI,OI,uh]=[[[],"0,6,7,8,m,w,10,1b,1d,1f,72,73,7k,8k,dt,2rk","AAAAAAAAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAA/AAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAADAAABwfwAAAAAAAMADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhAAAAQAAAAAAAAQCAAABAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgACAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAP///////////////wAAAAAAAAAAAAAAAAAAAAA="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAEF9+P/+BwAAAMAA//8AAPz/////BlADAAAAAJwAAPz///8AAADA//H/5+X8AAAAAAAAAAAA/P///wcAAAAAAAAAAAAAPv0vAD0BAABA/gAA/5/5/f8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8g+N8B+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAYAAAAAAAAAAAAAD/////CwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANgAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/HgwAAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAP3////+BwAAAMDu//////////////8vAADAAJwAAP3///8AAADg////////AAAAAAAAAAAA/P///wcAAAAAAAAAAAAA////Ab0H//9H/gAA/9////8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL/G//8T+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAfgAAAAAAAAAAAAD+////DwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANwAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/Hg4AAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"0,3,4,5,6,7,8,9,a,b,c,d,e,f,g,j,n,o,p,q,r,s,t,w,18,19,1c,4m,4o,4p,4q,4r,6z,72,73,75,76,77,7e,7h,7i,7j,7k,7l,7m,7n,7o,7p,7q,7r,7s,7t,7u,7v,7w,7x,7y,7z,8k,9t,a2,a3,a7,cc,cv,cx,cy,d6,dc,dd,de,dg,dh,di,dk,dl,2rk,2rl","AAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAD//////////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD4AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/v////+/tgAAAAAAAAAAAP8XAAAAAAD4//8AAAEAAAAAAAAAAAAAAMCfnz0AAACAAgAAAP///wcAAAAAAAAAAAAAwP8BAAAAAAAA+A8gAADA++8+AAAAAAAOAAAAAAAAgP8AAAAAAPz///v///8HAAAAAAAAFP4h/gAMAAAAAgAAAAAAABAeIAAADAAAQAYAAAAAAAAQhjkCAAAAIwAGAAAAAAAAEL4hAAAMAAD8AgAAAAAAAJAeIGAADAAAAAQAAAAAAAAAASAAAAAAAAARAAAAAAAA0ME9YAAMAAAAAgAAAAAAAJBAMAAADAAAAAMAAAAAAAAYHiAAAAwAAAACAAAAAAAAAAAEXAAAAAAAAAAAAAAA8geAfwAAAAAAAAAAAAAAAPIfAH8AAAAAAAAAAAADAACgAgAAAAAAAP5/3+D//v///x9AAAAAAAAAAAAAAAAA4P1mAAAAwwEAHgBkIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAAAAMAAAADAAAAAwAAAAAAAAAsD9A/g8gAAAAAAC4AAAAAAAAAAAAAAAAAABgAAAAAAIAAAAAAAAAAAAAAAAAAIcBBA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAJAAAAAAAAQH/lH/ifAAAAAAAA//////8//w8AAA8AAAAAANAXBAAAAAD4DwADAAAAPDsAAAAAAABAowMAAAAAAADwzwAAAAAAAAAAAAAAAAAAAAAAAAD3//0hEAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////wDIAAAAfAAAAAAAAB/8AAAAAAAAAAAAAAAA/////wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAwAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAA/////wAAAAAAPAAAAAAAAAAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAID3PwAAAMAAAAAAAAAAAAAAAwBECAAAYBAAAAAAAAAAAAAAAAAAAAAAAAAwAAAA//8DgAAAAADAPwAAgP8DAAAAAAAHAAAAAADIMwAAAAAgAAAAAAAAAAB+ZgAIEAAAAAAAEAAAAAAAAJ3BAgAAAAAwQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICEAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8AAP//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAMAHAAAAAAAAAAAAAAAAAAAAAG7wAAAAAACHAAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAPAAAAAAAAAAAD4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAAAAAAAAA/AAAAAAAAAAAwP8BAAAAAAA8AAAAAAAAAAAAAAAAAAAAAgAAAAAAAP9/AAAAAAAZgAMAAAAAAHgGBAAAAAAAAAAHAAAAgO8fAAAAAAAAAAgAAwAAAAAAwH8AngAAAAAAAAAAAAAAgNNAAgAAAAAAAAAAAAAAAAAAAAAAAID4BwAAAwAAAAAAABgBAAAAwB8fAAAAAAAAAAD4AUAFAAYAAAAAAAAAAAAA/1wAAEAAAAAAAAAAAAAA+IUNAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8sAEAADAAAAAAAAAAAAAA+KcBAAAAAAAAAAAAAAAAKL8AAAAAAAAAAAAAAACgvA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgP8GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFgIAAAAAAAAAAAAAAAAAAAAAADwDAEAAAD+BwAAAAD4eYAAfg4AAAAAAPx/AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf78AAAAAAAAAAAAA/P///G0AAAAAAAAAAAAAAAAAAAB+tL8AAAAAAAAAAACjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAAwAAAAAAwAcFAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//4H/PwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMD/4wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHwAAAAAAAAB/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAgAcAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGAPAAAAAAAAAAAAAAD//////z///38AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAD+P/nDwAAADwAAAAAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////9/+P//////HyAAEAAA+P7/AAAAAAAAAAAAAH////nbBwAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASMAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAADwDwAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAA////////////////AAAAAAAAAAAAAAAAAAAAAP///////////////////////////////////////wAA"]].map(function([t,n,r]){return[t,n.split(",").map(i=>parseInt(i,36)),Uint8Array.from(atob(r),i=>i.charCodeAt(0))]});function PI(e,t){return t===931||t===1010||t===120531||t===120589||t===120647||t===120705||t===120763?"\u03C3":t>=5112&&t<=5117?String.fromCodePoint(t-8):t>=43888&&t<=43967?String.fromCodePoint(t-38864):t>=93856&&t<=93880?String.fromCodePoint(t+27):t===837||t===890||t>=8064&&t<=8111||t>=8114&&t<=8188?e.normalize("NFD").replace(/\u0345/g,"\u03B9").normalize("NFC").toLowerCase():""}function Ah(e,t){for(let n=0;n<e.length;n+=2)if(t>=e[n]&&t<=e[n+1])return!0;return!1}function Po(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 CI(e){let t=Array.from(e,n=>n.codePointAt(0));for(let n=0;n<t.length;n++){let r=t[n];if(r!==8204&&r!==8205||n>0&&Ah(SI,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&Po(uh,t[i]);)i--;let a=n+1;for(;a<t.length&&Po(uh,t[a]);)a++;if(!(i>=0&&a<t.length&&Po(wI,t[i])&&Po(OI,t[a])))return!1}return!0}var _I=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,EI=/\p{Script=Latin}/u;function RI(e){return!_I.test(e)||!EI.test(e)}var lr=36,os=1,zu=26,kI=38,jI=700,TI=72,NI=128,DI=2147483647;function lh(e){return String.fromCharCode(e+22+75*+(e<26))}function FI(e,t,n){let r=0;for(e=n?Math.floor(e/jI):e>>1,e+=Math.floor(e/t);e>(lr-os)*zu>>1;r+=lr)e=Math.floor(e/(lr-os));return Math.floor(r+(lr-os+1)*e/(e+kI))}function MI(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=NI,o=0,s=TI;for(;r<t.length;){let c=DI;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 f=o;for(let m=lr;;m+=lr){let h=m<=s?os:m>=s+zu?zu:m-s;if(f<h)break;n+=lh(h+(f-h)%(lr-h)),f=Math.floor((f-h)/(lr-h))}n+=lh(f),s=FI(o,r+1,r===i),o=0,r++}}o++,a++}return n}function Du(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=Bu(e.charCodeAt(r));if(i>=t||i<0)return-1;n=n*t+i}return n}function dh(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function yh(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function bh(e){return e.length===2&&yh(e.codePointAt(0),e.codePointAt(1))}function ph(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function mt(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function xh(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function $u(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,f=0;for(;f<4&&(u=Bu(c[s]))>=0;)l=(l<<4)+u,s++,f++;if(c[s]===46){if(f===0||o>6)return null;s-=f;let m=0;for(;c[s]!==void 0;){let h=0;if(m>0)if(c[s]===46&&m<4)s++;else return null;if(c[s]==null||c[s]<48||c[s]>57)return null;for(;c[s]>=48&&c[s]<=57;){if(h=10*h+Bu(c[s]),h>255)return null;s++}i[o]=256*i[o]+h,m++,m%2==0&&o++}if(m!==4)return null;break}else if(c[s]===58){if(c[++s]===void 0)return null}else if(c[s]!==void 0)return null;i[o]=l,o++}if(a!==null){let u=o-a;for(o=7;o!==0&&u>0;){let l=i[a+u-1];i[a+u-1]=i[o],i[o]=l,o--,u--}}else if(a===null&&o!==8)return null;return i})(e.substring(1,e.length-1)):null;if(t)return(function(r){return ph(r)?null:Dn(r,_o)})(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 f=l.codePointAt(0);if(/[\p{Cn}\p{Co}\p{Cs}\p{Noncharacter_Code_Point}]/u.test(l)&&!Ah(yI,f)||Po(vI,f))return!0}return!1})(i))return null;let s=(i=(function(u){let l="";for(let f of u){let m=f.codePointAt(0);if(m!==8204&&m!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(f))continue;let h=PI(f,m);if(h){l+=h;continue}let d=bI.indexOf(m);l+=d<0?f:xI[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(II(u)||l&&(/^\p{Mark}/u.test(u)||!CI(u)||!RI(u)||u.startsWith("xn--")))return null;l&&(s[c]=`xn--${MI(u)}`)}return(i=s.join("."))!==""?i:null})(e.indexOf("%")===-1?e:Vu(e));return n===null||ph(n)?null:(function(i){let a=i.length,o=i.lastIndexOf(".",a-2)+1;if(i.charCodeAt(a-1)===46&&a--,a<=o)return!1;if(Du(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=Du(a[u]);if(l<0||l>255)return null;s+=l*(1<<8*(3-u))}let c=Du(a[o-1]);return c<0||c>=256**(5-o)?null:(s+=c,s)})(n):n}}function Gu(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,f=0;for(let m=0;m<s.length;++m)s[m]!==0?(f>l&&(c=u,l=f),u=-1,f=0):(u===-1&&(u=m),++f);return f>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 Sh(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 Ih(e){return e.username!==""||e.password!==""}function Fu(e){return e.host===null||e.host===""||e.scheme==="file"}var _=0,B="",we="",Ue=null,V,as=!1,ss=!1,Kr=!1,ft;function pn(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),_=0,B=e,we="",Ue=n||null,V=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},as=!1,ss=!1,Kr=!1,ft=r||0;let i=qI;switch(r){case 3:case 4:i=us;break;case 5:i=Zu;break;case 6:i=Hr;break;case 7:i=dr;break;case 8:i=Fn}return i(G(e,_))!==1?V:null}function ee(e,t){return _+=_===e?Cn(t):1,_<=B.length}function G(e,t){return t<e.length?e.codePointAt(t):void 0}function Cn(e){return e!=null&&e>65535?2:1}function vh(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var qI=e=>{let t=_;if(e!=null&&(e>=65&&e<=90||e>=97&&e<=122)){let n=_+1;for(e=B.charCodeAt(n);e===43||e===45||e===46||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57;)n++,e=B.charCodeAt(n);return we=B.slice(_,n).toLowerCase(),_=n,BI(n<B.length?e:void 0)}else return ft?1:(--_,ee(t,e)?wh(G(B,_)):0)},BI=e=>{let t=_;if(e===58){if(ft){if(mt(V.scheme)!==mt(we))return 0;if((Ih(V)||V.port!==null)&&we==="file")return 0;if(V.scheme==="file"&&V.host==="")return 0}return V.scheme=we,ft?(V.port===xh(V.scheme)&&(V.port=null),0):(we="",V.scheme==="file"?ee(t,e)?Wu(G(B,_)):0:mt(V.scheme)&&Ue!==null&&Ue.scheme===V.scheme?ee(t,e)?VI(G(B,_)):0:mt(V.scheme)?ee(t,e)?UI(G(B,_)):0:G(B,_+1)===47?(_++,ee(t,e)?LI(G(B,_)):0):(V.path=[""],V.opaquePath=!0,ee(t,e)?Ph(G(B,_)):0))}else return ft?1:(we="",_=-1,ee(t,e)?wh(G(B,_)):0)},wh=e=>{let t=_;return Ue===null||Ue.opaquePath&&e!==35?1:Ue.opaquePath&&e===35?(V.scheme=Ue.scheme,V.path=Ue.path.slice(),V.opaquePath=Ue.opaquePath,V.query=Ue.query,V.fragment="",ee(t,e)?Fn(G(B,_)):0):Ue.scheme==="file"?(_--,ee(t,e)?Wu(G(B,_)):0):(_--,ee(t,e)?Ju(G(B,_)):0)},VI=e=>{let t=_;return e===47&&G(B,_+1)===47?(++_,ee(t,e)?ds(G(B,_)):0):(_--,ee(t,e)?Ju(G(B,_)):0)},LI=e=>{let t=_;return e===47?ee(t,e)?_i(G(B,_)):0:(_--,ee(t,e)?_n(G(B,_)):0)},Ju=e=>{let t=_;return V.scheme=Ue.scheme,e===47||mt(V.scheme)&&e===92?ee(t,e)?mh(G(B,_)):0:(V.username=Ue.username,V.password=Ue.password,V.host=Ue.host,V.port=Ue.port,V.path=Ue.path.slice(),V.query=Ue.query,e===63?(V.query="",ee(t,e)?dr(G(B,_)):0):e===35?(V.fragment="",ee(t,e)?Fn(G(B,_)):0):e!=null?(V.query=null,V.path.pop(),_--,ee(t,e)?_n(G(B,_)):0):ee(t,e)?Ju(G(B,_)):0)},mh=e=>{let t=_;return mt(V.scheme)&&(e===47||e===92)?ee(t,e)?ds(G(B,_)):0:e===47?ee(t,e)?_i(G(B,_)):0:(V.username=Ue.username,V.password=Ue.password,V.host=Ue.host,V.port=Ue.port,_--,ee(t,e)?_n(G(B,_)):0)},UI=e=>{let t=_;return e===47&&G(B,_+1)===47?_++:_--,ee(t,e)?ds(G(B,_)):0},ds=e=>{let t=_;return e!==47&&e!==92?(_--,ee(t,e)?_i(G(B,_)):0):ee(t,e)?ds(G(B,_)):0},_i=e=>{let t=_;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!mt(V.scheme))){let n=_+Cn(e);for(;n<B.length;){let r=G(B,n);if(r==null||r===64||r===35||r===47||r===63||r===92&&mt(V.scheme))break;n+=Cn(r)}return we+=B.slice(_,n),_=n-1,ee(t,e)?_i(G(B,_)):0}if(e===64){as&&(we=`%40${we}`),as=!0;for(let n=0;n<we.length;n++){let r=we.codePointAt(n);if(r===58&&!ss){ss=!0;continue}let i=hh(r,cs);ss?V.password+=i:V.username+=i,r!=null&&r>65535&&n++}return we="",ee(t,e)?_i(G(B,_)):0}else return e==null||e===35||e===47||e===63||e===92&&mt(V.scheme)?as&&we===""?1:(_-=we.length+1,we="",ee(t,e)?us(G(B,_)):0):(we+=vh(e),ee(t,e)?_i(G(B,_)):0)},us=e=>{let t=_;if(ft&&V.scheme==="file")return _--,ee(t,e)?Yu(G(B,_)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!mt(V.scheme))){let n=_+Cn(e);for(e===91?Kr=!0:e===93&&(Kr=!1);n<B.length;){let r=G(B,n);if(r==null||!Kr&&r===58||r===35||r===47||r===63||r===92&&mt(V.scheme))break;r===91?Kr=!0:r===93&&(Kr=!1),n+=Cn(r)}return we+=B.slice(_,n),_=n-1,ee(t,e)?us(G(B,_)):0}else if(e===58&&!Kr){if(we===""||ft===4)return 1;let n=$u(we,!mt(V.scheme));return n===null?1:(V.host=Gu(n),we="",ee(t,e)?Zu(G(B,_)):0)}else if(e==null||e===35||e===47||e===63||e===92&&mt(V.scheme)){if(_--,mt(V.scheme)&&we==="")return 1;if(ft&&we===""&&(Ih(V)||V.port!==null))return 1;let n=$u(we,!mt(V.scheme));return n===null?1:(V.host=Gu(n),we="",ft?0:ee(t,e)?Hr(G(B,_)):0)}else return we+=vh(e),ee(t,e)?us(G(B,_)):0},Zu=e=>{let t=_;if(e!=null&&e>=48&&e<=57){let n=_+1;for(;n<B.length;){let r=B.charCodeAt(n);if(r<48||r>57)break;n++}return we+=B.slice(_,n),_=n-1,ee(t,e)?Zu(G(B,_)):0}else if(ft||e==null||e===35||e===47||e===63||e===92&&mt(V.scheme)){if(we!==""){let n=parseInt(we,10);if(n>65535)return 1;if(V.port=n===xh(V.scheme)?null:n,we="",ft)return 0}return ft?1:(_--,ee(t,e)?Hr(G(B,_)):0)}else return 1};function Oh(e,t){let n=e.length-t;if(n<2)return!1;if(yh(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 Wu=e=>{let t=_;return V.scheme="file",V.host="",e===47||e===92?ee(t,e)?zI(G(B,_)):0:Ue?.scheme==="file"?(V.host=Ue.host,V.path=Ue.path.slice(),V.opaquePath=Ue.opaquePath,V.query=Ue.query,e===63?(V.query="",ee(t,e)?dr(G(B,_)):0):e===35?(V.fragment="",ee(t,e)?Fn(G(B,_)):0):e!=null?(V.query=null,Oh(B,_)?V.path=[]:Sh(V),_--,ee(t,e)?_n(G(B,_)):0):ee(t,e)?Wu(G(B,_)):0):(_--,ee(t,e)?_n(G(B,_)):0)},zI=e=>{let t=_;return e===47||e===92?ee(t,e)?Yu(G(B,_)):0:(Ue!==null&&Ue.scheme==="file"&&(!Oh(B,_)&&(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})(Ue.path[0])&&V.path.push(Ue.path[0]),V.host=Ue.host),_--,ee(t,e)?_n(G(B,_)):0)},Yu=e=>{let t=_;if(e!=null&&e!==47&&e!==92&&e!==63&&e!==35){let n=_+Cn(e);for(;n<B.length;){let r=G(B,n);if(r==null||r===47||r===92||r===63||r===35)break;n+=Cn(r)}return we+=B.slice(_,n),_=n-1,ee(t,e)?Yu(G(B,_)):0}else if(e==null||e===47||e===92||e===63||e===35){if(_--,!ft&&bh(we))return ee(t,e)?_n(G(B,_)):0;if(we==="")return V.host="",ft?0:ee(t,e)?Hr(G(B,_)):0;{let n=$u(we,!mt(V.scheme));return n===null?1:(n==="localhost"&&(n=""),V.host=Gu(n),we="",ft?0:ee(t,e)?Hr(G(B,_)):0)}}return 1},Hr=e=>{let t=_;return mt(V.scheme)?(e!==92&&e!==47&&_--,ee(t,e)?_n(G(B,_)):0):!ft&&e===63?(V.query="",ee(t,e)?dr(G(B,_)):0):!ft&&e===35?(V.fragment="",ee(t,e)?Fn(G(B,_)):0):e!=null?(e!==47&&_--,ee(t,e)?_n(G(B,_)):0):(ft&&V.host===null&&V.path.push(""),ee(t,e)?Hr(G(B,_)):0)},_n=e=>{let t=_;if(e!=null&&e!==47&&(!mt(V.scheme)||e!==92)&&(ft||e!==63&&e!==35)){let n=_+Cn(e);for(;n<B.length;){let r=G(B,n);if(r==null||r===47||mt(V.scheme)&&r===92||!ft&&(r===63||r===35))break;n+=Cn(r)}we+=Dn(B.slice(_,n),Lu),_=n,e=G(B,n)}if(e==null||e===47||mt(V.scheme)&&e===92||!ft&&(e===63||e===35)){let n=mt(V.scheme)&&e===92;return(function(i){switch(i){case"..":case"%2e.":case"%2E.":case".%2e":case".%2E":case"%2e%2e":case"%2E%2e":case"%2e%2E":case"%2E%2E":return!0;default:return!1}})(we)?(Sh(V),e!==47&&!n&&V.path.push("")):dh(we)&&e!==47&&!n?V.path.push(""):dh(we)||(V.scheme==="file"&&V.path.length===0&&bh(we)&&(we=`${we[0]}:`),V.path.push(we)),we="",e===63?(V.query="",ee(t,e)?dr(G(B,_)):0):e===35?(V.fragment="",ee(t,e)?Fn(G(B,_)):0):ee(t,e)?_n(G(B,_)):0}else return we+=hh(e,Lu),ee(t,e)?_n(G(B,_)):0},Ph=e=>{let t=_;if(e===63)return V.query="",ee(t,e)?dr(G(B,_)):0;if(e===35)return V.fragment="",ee(t,e)?Fn(G(B,_)):0;if(e!=null){let n=_+Cn(e);for(;n<B.length;){let i=G(B,n);if(i===63||i===35)break;n+=Cn(i)}let r=B.slice(_,n);if(n<B.length&&r.charCodeAt(r.length-1)===32?V.path[0]+=Dn(r.slice(0,-1),_o)+"%20":V.path[0]+=Dn(r,_o),_=n,(e=G(B,n))===63)return V.query="",ee(t,e)?dr(G(B,_)):0;if(e===35)return V.fragment="",ee(t,e)?Fn(G(B,_)):0}return ee(t,e)?Ph(G(B,_)):0},dr=e=>{let t=_,n=_;if(e!=null){if(ft)n=B.length;else{let i=B.indexOf("#",_);n=i===-1?B.length:i}let r=mt(V.scheme)?AI:Hu;V.query+=Dn(B.slice(_,n),r)}return _=n,G(B,n)===35&&!ft?(V.fragment="",ee(t,e)?Fn(G(B,_)):0):ee(t,e)?dr(G(B,_)):0},Fn=e=>{let t=_;return e!=null&&(V.fragment+=Dn(B.slice(_),hI),_=B.length),ee(t,e)?Fn(G(B,_)):0};function Ku(e){if(e.opaquePath)return e.path[0];{let t="";for(let n of e.path)t+=`/${n}`;return t}}function Ch(e){switch(e.scheme){case"blob":{let t=pn(Ku(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":Ch(t)}case"ftp":case"http":case"https":case"ws":case"wss":return(function(n){let r=`${n.scheme}://`;return r+=n.host,n.port!==null&&(r+=`:${n.port}`),r})(e);default:return"null"}}var Ge=Symbol("URLImpl"),yn=class e{constructor(t,n){if(t===void 0&&n===void 0)throw new TypeError('The "url" argument must be specified.');t=Ke(t),n!=null&&(n=Ke(n));let r=null;if(n!=null&&(r=pn(n,null,null,0),r==null))throw new TypeError(`Invalid base URL: ${n}`);let i=pn(t,null,r,0);if(i==null)throw new TypeError(`Invalid URL: ${t}`);this[Ge]={url:i,query:null}}static createObjectURL(t){throw new TypeError("URL.createObjetURL is unsupported")}static revokeObjectURL(t){}static parse(t,n){t=Ke(t),n!==void 0&&(n=Ke(n));try{return new e(t,n)}catch{return null}}static canParse(t,n){t=Ke(t),n!==void 0&&(n=Ke(n));let r=null;return n!=null&&(r=pn(n,null,null,0),r==null)?!1:pn(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+=Ku(n),n.query!==null&&(r+=`?${n.query}`),n.fragment!==null&&(r+=`#${n.fragment}`),r})(this[Ge].url)}set href(t){let n=pn(t=Ke(t),null,null,0);if(n==null)throw new TypeError(`Invalid URL: ${t}`);this[Ge].url=n,this[Ge].query&&Mu(this[Ge].query,n.query)}get origin(){return Ch(this[Ge].url)}get protocol(){return`${this[Ge].url.scheme}:`}set protocol(t){pn(`${t=Ke(t)}:`,this[Ge].url,null,2)}get username(){return this[Ge].url.username}set username(t){t=Ke(t),Fu(this[Ge].url)||(function(r,i){r.username=Dn(i,cs)})(this[Ge].url,t)}get password(){return this[Ge].url.password}set password(t){t=Ke(t),Fu(this[Ge].url)||(function(r,i){r.password=Dn(i,cs)})(this[Ge].url,t)}get host(){let{url:t}=this[Ge];return t.host==null?"":t.port==null?t.host:`${t.host}:${t.port}`}set host(t){t=Ke(t),this[Ge].url.opaquePath||pn(t,this[Ge].url,null,3)}get hostname(){let{url:t}=this[Ge];return t.host!=null?t.host:""}set hostname(t){t=Ke(t),this[Ge].url.opaquePath||pn(t,this[Ge].url,null,4)}get port(){let{url:t}=this[Ge];return t.port!=null?`${t.port}`:""}set port(t){t=Ke(t);let{url:n}=this[Ge];Fu(n)||(t?pn(t,n,null,5):n.port=null)}get pathname(){return Ku(this[Ge].url)}set pathname(t){t=Ke(t);let{url:n}=this[Ge];n.opaquePath||(n.path=[],pn(t,n,null,6))}get search(){let{url:t}=this[Ge];return t.query?`?${t.query}`:""}set search(t){t=Ke(t);let{url:n,query:r}=this[Ge];if(!t)n.query=null,r&&Mu(r,null);else{let i=t[0]==="?"?t.substring(1):t;n.query="",pn(i,n,null,7),r&&Mu(r,n.query)}}get searchParams(){let t=this[Ge],n=t.query;return n==null&&(n=t.query=(function(i,a){let o=new ls;return o[at].url=i,o[at].serialized=a==null,a&&(o[at].list=Qu(a)),o})(this,t.url.query)),n}get hash(){let{url:t}=this[Ge];return t.fragment?`#${t.fragment}`:""}set hash(t){t=Ke(t);let{url:n}=this[Ge];if(!t)n.fragment=null;else{let r=t[0]==="#"?t.substring(1):t;n.fragment="",pn(r,n,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(yn.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var at=Symbol("URLSearchParamsImpl"),$I=Symbol.dispose||Symbol.for("dispose");function Mu(e,t){t?e[at].list=Qu(t):e[at].list.length=0,e[at].serialized=t==null}function is(e){if(e.url){let t=Uu(e.list);(function(r,i){r[Ge].url.query=i})(e.url,t||null),e.serialized=!0}}var GI=typeof Iterator<"u"?Iterator:Object,Co=class extends GI{constructor(t,n){super(),this[at]={ptr:t,map:n,index:0}}next(){let t=this[at];return t.index<t.ptr.list.length?{value:t.map(t.ptr.list[t.index++]),done:!1}:{value:void 0,done:!0}}[Symbol.iterator](){return this}[$I](){}},ls=class{constructor(t){let n=this[at]={list:[],url:null,serialized:!0},r;if(Array.isArray(t))for(let i=0;i<t.length;i++)n.list.push(ah(t[i]));else if((r=fh(t))!=null){let i;for(;!(i=qu(r.next())).done;)n.list.push(ah(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=fI(o),c=Ke(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=Ke(t);i=i[0]==="?"?i.substring(1):i,n.list=Qu(i)}}get size(){return this[at].list.length}append(t,n){t=Ke(t),n=Ke(n),this[at].list.push([t,n]);let r=this[at];r.url&&r.serialized?(function(a,o){let s=a[Ge].url;s.query=s.query?`${s.query}&${o}`:o})(r.url,Uu([[t,n]])):is(r)}delete(t,n){t=Ke(t),n=n!=null?Ke(n):void 0;let{list:r}=this[at],i=0;for(;i<r.length;)r[i][0]===t&&(n==null||r[i][1]===n)?r.splice(i,1):i++;is(this[at])}get(t){t=Ke(t);let{list:n}=this[at];for(let r=0;r<n.length;r++)if(n[r][0]===t)return n[r][1];return null}getAll(t){t=Ke(t);let n=[],{list:r}=this[at];for(let i=0;i<r.length;i++)r[i][0]===t&&n.push(r[i][1]);return n}has(t,n){t=Ke(t),n=n!=null?Ke(n):void 0;let{list:r}=this[at];for(let i=0;i<r.length;i++)if(r[i][0]===t&&(n==null||r[i][1]===n))return!0;return!1}set(t,n){t=Ke(t),n=Ke(n);let{list:r}=this[at],i=!1,a=!1,o=0;for(;o<r.length;)r[o][0]===t?i?(r.splice(o,1),a=!0):(i=!0,r[o][1]!==n&&(r[o][1]=n,a=!0),o++):o++;i||(r.push([t,n]),a=!0),a&&is(this[at])}sort(){this[at].list.sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0),is(this[at])}forEach(t,n){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:r}=this[at];for(let i=0;i<r.length;i++)t.call(n,r[i][1],r[i][0],this)}entries(){return new Co(this[at],t=>t)}keys(){return new Co(this[at],t=>t[0])}values(){return new Co(this[at],t=>t[1])}toString(){return Uu(this[at].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(ls.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var pr="https://api.longplayai.com";function _h(e){let t,n=()=>typeof t=="string"?t:t?.accessToken,r=0,i,a=new Map,o=()=>{for(let f of[...a.keys()])try{f()}catch{}};function s(f){let m=++r;i=void 0,t=void 0;for(let h of[...a.values()])try{h?.()}catch{}m===r&&(t=f,o())}let c=()=>s();function u(f,m=!1){let h=Qn.safeParse(f);if(!h.success||m&&Date.parse(h.data.expiresAt)<=Date.now()||Date.parse(h.data.refreshExpiresAt)<=Date.now()||Date.parse(h.data.refreshExpiresAt)<Date.parse(h.data.expiresAt))throw new b("INVALID_RESPONSE","Invalid customer session credentials");return h.data}async function l(){if(i)return i;let f=typeof t=="object"?t:void 0,m=r;if(!f||Date.parse(f.refreshExpiresAt)<=Date.now())throw f&&c(),new b("UNAUTHENTICATED","Customer authentication is required",401);let h=(async()=>{try{let d=await e(f.refreshToken);if(m!==r)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");let A=u(d,!0);if(A.customerId!==f.customerId||A.sessionId!==f.sessionId)throw new b("SCOPE_MISMATCH","Refresh changed the customer session");return t=A,{...A}}catch(d){throw m!==r?new b("IDENTITY_CHANGED","Customer identity changed during refresh"):(d instanceof b&&d.status===401&&c(),d)}})();i=h;try{return await h}finally{i===h&&(i=void 0)}}return{identify(f){let m=typeof f=="string"?f:u(f),h=typeof m=="string"?m:m.accessToken;if(!h.trim()||/\s/.test(h)||h.length>4096)throw new b("INVALID_TOKEN","A server-issued token is required");s(m)},reset:c,subscribeIdentity(f,m){return a.set(f,m),()=>{a.delete(f)}},access(){let f=typeof t=="object"?t:void 0;if(f&&Date.parse(f.expiresAt)<=Date.now()+3e4){let h=r;return l().then(()=>{let d=n();if(h!==r||!d)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");return d})}let m=n();if(!m)throw new b("NOT_IDENTIFIED","Identify a customer session before making a request");return m},peek:n,snapshot:()=>typeof t=="object"?{...t}:void 0,refresh:l}}var Eh=Symbol("IndianaNoContent");function mr(e,t,n=yn){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??pr);if(o.username||o.password||o.search||o.hash)throw new b("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(o.protocol!=="https:"&&!(o.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(o.hostname)))throw new b("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let s=e.fetch??globalThis.fetch.bind(globalThis),c=e.timeoutMs??1e4;if(!Number.isFinite(c)||c<1||c>12e4)throw new b("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let u=!1,l=0,f=null,m=new Set,h=e.session??_h(async y=>{let I=await g("customer-sessions/refresh",{},"POST",{},y);if(!I||typeof I!="object")throw new b("INVALID_RESPONSE","Invalid refresh response");let{requestId:w,scope:C,...j}=I;return j});function d(){l+=1,f=null;for(let y of m)y.abort();m.clear()}let A=h.subscribeIdentity(d);function k(){u||h.reset()}async function g(y,I={},w="POST",C={},j){let E=C.installationDetach===!0;if(E&&(y!=="push/installations/detach"||w!=="POST"))throw new b("INVALID_REQUEST","Installation authority only detaches this installation");if(!j&&!E)throw new b("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let ae=l,xe=new AbortController;E||m.add(xe);let Pe=()=>!E&&ae!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new b("TIMEOUT","Longplay request timed out"),Ee,ye=new Promise((Te,tt)=>{Ee=()=>tt(Pe()),xe.signal.addEventListener("abort",Ee,{once:!0})}),gt=setTimeout(()=>xe.abort(),C.timeoutMs??c),Je=async()=>{let Te=await s(`${o.href.replace(/\/$/,"")}/api/v1/${y}`,{method:w,headers:{...C.headers,"Content-Type":"application/json",...E?{}:{Authorization:`Bearer ${j}`},[Os]:Ps.current,[bl]:oh.version,...a?{"X-Indiana-Project":a.projectId,"X-Indiana-Environment":a.environment}:{}},body:w==="POST"?JSON.stringify(I):void 0,signal:xe.signal,credentials:"omit",cache:"no-store",redirect:"error",...C.keepalive?{keepalive:!0}:{}});if(xe.signal.aborted)throw Pe();let tt;try{tt=Te.status===204?Eh:await Te.json()}catch{throw xe.signal.aborted?Pe():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(xe.signal.aborted)throw Pe();if(!E&&ae!==l)throw new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!Te.ok){let lt=ws.safeParse(tt),Kt=lt.success&&(!Bn.safeParse(lt.data.error.code).success||Al(lt.data.error.code,Te.status)),Ar=Kt?lt.data.error.code:"HTTP_ERROR",yr=Fo(Ar,Te.status,{retryAfter:Te.headers.get("Retry-After"),recovery:Kt?lt.data.error.recovery:void 0,reason:Kt?lt.data.error.reason:void 0});throw new b(Ar,Kt?lt.data.error.message:"Longplay request failed",Te.status,Te.headers.get("X-Request-Id")??(lt.success?lt.data.requestId:void 0),{...yr,...lt.success&&lt.data.error.retryable===!1?{retryable:!1}:{},...yr.retryAfterSeconds===void 0&&lt.success&&lt.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:lt.data.error.retryAfterSeconds}:{}})}if(Te.headers.get(Os)!==Ps.current)throw new b("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&tt!==Eh){let lt=tt&&typeof tt=="object"&&"scope"in tt?tt:tt&&typeof tt=="object"&&"configuration"in tt?tt.configuration:null;if(!lt||typeof lt!="object"||!("scope"in lt))throw new b("INVALID_RESPONSE","Response is missing its App/environment scope");let Kt=Ne.safeParse(lt.scope);if(!Kt.success||Kt.data.projectId!==a.projectId||Kt.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");f!==Jr&&(f=Jr,t?.(f))}return tt};try{return await Promise.race([Je(),ye])}catch(Te){throw!E&&ae!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):Te instanceof b?Te:new b(xe.signal.aborted?"TIMEOUT":"NETWORK_ERROR",xe.signal.aborted?"Longplay request timed out":"Unable to read the Longplay response")}finally{clearTimeout(gt),xe.signal.removeEventListener("abort",Ee),m.delete(xe)}}return{session:h,requestWithCredential(y,I,w,C={}){return u?Promise.reject(new b("CLOSED","SDK client was destroyed")):g(y,I,"POST",C,w)},subjectKey:()=>f,identify(y){if(u)throw new b("CLOSED","SDK client was destroyed");if(a&&typeof y=="object"&&"scope"in y){let I=Ne.safeParse(y.scope);if(!I.success||I.data.projectId!==a.projectId||I.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Customer session belongs to another App/environment")}h.identify(y)},reset:k,dispose(){u||(u=!0,A(),d())},request(y,I={},w="POST",C={}){if(u)return Promise.reject(new b("CLOSED","SDK client was destroyed"));if(C.installationDetach)return g(y,I,w,C);let j=l;try{let E=h.access(),ae=xe=>{if(j!==l)throw new b("IDENTITY_CHANGED","Customer identity changed before dispatch");return g(y,I,w,C,xe)};return typeof E=="string"?ae(E):E.then(ae)}catch(E){return Promise.reject(E)}}}}function Rh(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(!jt.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 KI={...O.readHoldings,request:O.readHoldings.request.omit({customerId:!0})};function kh(e){return{async checkEntitlement(t){ze(t);let n=O.checkEntitlement;return me(e,n,t)},async readHoldings(t={}){return me(e,KI,t)}}}function jh(e){return{async readLedger(t){let n=O.readLedger;return me(e,n,{query:t})},async readCreditStatement(t){ze(t);let n=O.readCreditStatement;return me(e,n,t)},async quoteBalance(t){ze(t);let n=O.quoteBalance;return me(e,n,{command:t})}}}function Th(e){return{async setupPayment(t){ze(t);let n=O.setupPayment;return me(e,n,t)},async readPaymentSetup(t){ze(t);let n=O.readPaymentSetup;return me(e,n,t)},async readBillingInvoice(t){ze(t);let n=O.readBillingInvoice;return me(e,n,t)},async readBillingControls(t={}){ze(t);let n=O.readBillingControls;return me(e,n,t)},async prepareBillingAuthorization(t){ze(t);let n=O.prepareBillingAuthorization;return me(e,n,t)},async confirmBillingAuthorization(t){ze(t);let n=O.confirmBillingAuthorization;return me(e,n,t)},async setBillingCoupons(t){ze(t);let n=O.setBillingCoupons;return me(e,n,t,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(t){ze(t);let n=O.revokeBillingAuthorization;return me(e,n,t)},async listBillingInvoices(t={after:null,limit:25}){ze(t);let n=O.listBillingInvoices;return me(e,n,t)},async confirmBillingAdjustment(t){ze(t);let n=O.confirmBillingAdjustment;return me(e,n,t)}}}function Nh(e){return{async previewUpdate(t){ze(t);let n=O.previewUpdate;return me(e,n,t)},async update(t){ze(t);let n=O.update;return me(e,n,t)},async readSubscriptionUpdate(t){ze(t);let n=O.readSubscriptionUpdate;return me(e,n,t)},async restoreNativePurchase(t){ze(t);let n=O.restoreNativePurchase;return me(e,n,t)},async previewAttach(t){ze(t);let n=O.previewAttach;return me(e,n,t)},async attach(t){ze(t);let n=O.attach;return me(e,n,t)},async readSubscriptionOperation(t){ze(t);let n=O.readSubscriptionOperation;return me(e,n,t)}}}function Dh(e){return{async redeemReward(t){return ze(t),(await me(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 me(e,O.claimRewardProduct,t,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(t){return ze(t),(await me(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 me(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 me(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 me(e,O.listOffers,{},{response:"Invalid offers response"})).offers}}}function Fh(e){return{...kh(e),...jh(e),...Th(e),...Nh(e),...Dh(e)}}function Mh(e){return{async resolveContent(t){ze(t);let n=O.resolveContent;return me(e,n,t)},async resolvePaywall(t){ze(t);let n=O.resolvePaywall;return me(e,n,t)},async resolveOffering(t){ze(t);let n=O.resolveOffering;return me(e,n,t)}}}var Xu=e=>new TextEncoder().encode(JSON.stringify(e)).length,qh=16384;function Bh(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,f().catch(()=>{}).finally(u)},5e3),typeof s=="object"&&"unref"in s&&s.unref())}function l(d,A={},k={}){if(c(),r&&Date.now()<r.until&&!$m(r.config,d))return;h();let g=O.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:d,properties:A,...k}]}).events[0];if(Xu({events:[g]})>qh)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(g)),u()}async function f(d=!1){if(c(),o)return o;let A=n,k=(async()=>{let g={inserted:0,duplicates:0,rejected:0,skipped:0},y=a.length;for(;y&&A===n;){let I=[],w=Xu({events:[]});for(let E of a.slice(0,Math.min(y,100))){let ae=Xu(E)+(I.length?1:0);if(I.length&&w+ae>qh)break;I.push(E),w+=ae}let C=O.trackEvents,j=await me(e,C,{events:I},void 0,{keepalive:d});if(A!==n)throw new b("IDENTITY_CHANGED","Event identity changed during delivery");if(j.inserted+j.duplicates+j.rejected+j.skipped!==I.length)throw new b("INVALID_RESPONSE","Incomplete event acknowledgement");i(j.analyticsConfig),a.splice(0,I.length),y-=I.length,g.inserted+=j.inserted,g.duplicates+=j.duplicates,g.rejected+=j.rejected,g.skipped+=j.skipped}return g})();o=k;try{return await k}finally{o===k&&(o=null)}}let m;function h(){if(m||typeof document>"u")return;let d=()=>{document.visibilityState==="hidden"&&t()&&a.length&&f(!0).catch(()=>{})};document.addEventListener("visibilitychange",d),m=()=>document.removeEventListener("visibilitychange",d)}return{rememberConfiguration:i,track:l,flush:f,reset(){n++,r=void 0,clearTimeout(s),s=void 0,a=[],o=null},detachVisibility(){m?.(),m=void 0}}}function ps(e){let t=null,n=null,r=0,i=0,a=new Set,o=null,s=null,c=new Set,u=()=>{for(let g of c)try{g()}catch{}},l={attributes:Ot.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(g,y)=>{!a.has(g)&&(!t||!("analyticsConfig"in t)||t.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(g,structuredClone(y),structuredClone(l.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(g,y)=>(!t||!("analyticsConfig"in t)||t.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(g),structuredClone(y),structuredClone(l.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?g=>e.saveStickyBucketAssignmentDoc(structuredClone(g)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},f=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function m(g,y=new Set){return a.has(g)?!o||!o.features[g]||["unknownFeature","cyclicPrerequisite"].includes(o.features[g].source):y.has(g)?!1:(y.add(g),(t?.features[g]?.rules??[]).some(I=>[...I.parentConditions??[],...(I.tracks??[]).flatMap(w=>w.experiment.parentConditions??[])].some(w=>m(w.id,y))))}let h=g=>{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(g)?!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now()?f():structuredClone(o.features[g]??f()):e.evaluateRemote&&(l.attributes?.merchandise||l.attributes?.merchandiseId)&&!o||m(g)?f():structuredClone(Ln(g,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 g=i;if(s?.revision===g)return s.loading;let y=r,I=t,w=[...a],C=(async()=>{let j=Ta.parse(await e.evaluateRemote({attributes:structuredClone(l.attributes),features:w}));if(!(y!==r||g!==i||I!==t)){if(e.assertUsable?.(I.generation),j.generation!==I.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(w.some(E=>!Object.hasOwn(j.features,E))||Object.keys(j.features).some(E=>!a.has(E)))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=Ot.parse({...l.attributes,...j.merchandiseContext})}o=structuredClone(j),l.features={...I.features,...Object.fromEntries(Object.entries(o.features).map(([E,ae])=>[E,{defaultValue:ae.value}]))},u()}})();s={revision:g,loading:C};try{await C}finally{s?.loading===C&&(s=null)}}function A(){d().catch(g=>{try{e.onError?.(g)}catch{}})}async function k(){if(n)return n;let g=r,y=(async()=>{let I=await e.load(),w="remoteFeatures"in I?po.parse(I):null,C=w??gn.parse(I);if(C.scope.projectId!==e.scope.projectId||C.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(g!==r)throw new Error("Feature client was reset");if(e.assertUsable&&t?.generation===C.generation){let{evaluatedAt:E,expiresAt:ae,...xe}=t,{evaluatedAt:Pe,expiresAt:Ee,...ye}=C;if(Ct(xe)!==Ct(ye))throw new Error("Immutable Feature generation changed content");return t.evaluatedAt=C.evaluatedAt,t.expiresAt=C.expiresAt,u(),(!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())&&A(),structuredClone(t)}let j=new Set(w?.remoteFeatures??[]);if([...j].some(E=>Object.hasOwn(C.features,E)))throw new Error("Remote Feature definitions must not be delivered locally");return t&&"analyticsConfig"in t&&"analyticsConfig"in C&&!t.analyticsConfig.experimentViewsEnabled&&w?.analyticsConfig.experimentViewsEnabled&&l.trackedExperiments?.clear(),t=structuredClone(C),a=j,o=null,s=null,i++,l.features=t.features,l.savedGroups=ni(t.savedGroups),l.trackedFeatureUsage={},u(),A(),structuredClone(t)})();n=y;try{return await y}finally{n===y&&(n=null)}}return{init:k,refresh:k,refreshRemote:d,get generation(){return t?.generation??null},get expiresAt(){return t?.expiresAt??null},subscribe(g){return c.add(g),()=>{c.delete(g)}},setAttributes(g){let y=Ot.parse(g);(l.attributes?.merchandise||l.attributes?.merchandiseId||g.merchandise||g.merchandiseId)&&l.trackedExperiments?.clear(),l.attributes=y,i++,o=null,s=null,l.features=t?.features??{},l.trackedFeatureUsage={},u(),A()},evalFeature:h,isOn(g){return h(g).on},isOff(g){return h(g).off},getFeatureValue(g,y){let I=h(g).value;return structuredClone(I===null?y:I)},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 Vh(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 HI(e){let t=Vh(e),{merchandiseId:n,merchandise:r,...i}=e;return{...i,...t?{merchandise:t}:{}}}function Lh(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,f=!1,m=async()=>{if(f||l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let Pe=O.getFeatures,Ee=i?{scope:{projectId:i.scope.projectId,environment:i.scope.environment},payload:await i.features()}:await me(e,Pe,{});if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");if(r&&(Ee.scope.projectId!==r.projectId||Ee.scope.environment!==r.environment))throw new b("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(Ee.payload.analyticsConfig),Ee},h=await m(),d=!0,A,k=Pe=>{try{u.onError?.(Pe)}catch{}},g=(Pe,Ee,ye)=>{try{let gt=Vh(ye);n.track(Pe,Ee,gt?{merchandise:gt}:{})}catch(gt){k(gt)}},y=ps({assertUsable:i?.assertFeatures,scope:h.scope,attributes:u.attributes,onError:u.onError,load:async()=>d?(d=!1,h.payload):(await m()).payload,evaluateRemote:async Pe=>{if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let Ee=O.evaluateFeatures,ye=await me(e,Ee,{...Pe,attributes:HI(Pe.attributes)});if(ye.scope.projectId!==h.scope.projectId||ye.scope.environment!==h.scope.environment)throw new b("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:ye.generation,evaluatedAt:ye.evaluatedAt,expiresAt:ye.expiresAt,features:ye.features,...ye.merchandiseContext?{merchandiseContext:ye.merchandiseContext}:{}}},onExperimentViewed:(Pe,Ee,ye)=>g("Experiment Viewed",{experimentId:Pe.key,variationId:Ee.key},ye),onFeatureUsage:(Pe,Ee,ye)=>g("Feature Evaluated",{feature:Pe,value:Ee.value,source:Ee.source,ruleId:Ee.ruleId,...Ee.experimentResult?{variationId:Ee.experimentResult.key}:{}},ye)}),I=y.refresh;function w(){clearTimeout(A),!i&&(f||l!==a||!y.expiresAt||(A=setTimeout(()=>{C().catch(k)},Math.min(2147483647,Math.max(1e3,Date.parse(y.expiresAt)-Date.now()))),typeof A=="object"&&"unref"in A&&A.unref()))}async function C(){try{return await I()}finally{w()}}let j=()=>{f||C().catch(k)},E=y.subscribe(w),ae=i?.subscribe(()=>{!f&&i.fresh&&C().catch(k)});function xe(){f||(f=!0,clearTimeout(A),typeof window<"u"&&window.removeEventListener("focus",j),E(),ae?.(),y.reset(),o.delete(xe))}o.add(xe);try{await y.init(),(u.attributes?.merchandise||u.attributes?.merchandiseId)&&await y.refreshRemote()}catch(Pe){throw xe(),Pe}return w(),!i&&typeof window<"u"&&window.addEventListener("focus",j),Object.assign(y,{refresh:C,destroy:xe})}return{features:c,reset(u){a++,u();for(let l of o)l()}}}var Uh=require("zod");function zh(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=Uh.z.object({funnelId:es.shape.id,funnelVersionId:es.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 me(e,c,a({couponId:o,requestId:s}));return{offer:u.offer,reason:u.reason}},async resolveOffering(o){let s=O.resolveOffering;return me(e,s,a(o))},async resolvePaywall(o){let s=O.resolvePaywall;return me(e,s,a(o))},async previewAttach(o){let s=O.previewAttach;return me(e,s,a(o))}}}function $h(e){let t=mr(e),n=t.request,r;try{r=th(e.push,t,e.scope??e.configuration?.scope)}catch(s){throw t.dispose(),s}let i=Rh(t,()=>{o.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=Bh(n,i.isIdentified),o=Lh(n,i.isIdentified,a,e.scope,e.configuration);return{session:t.session,...ih(n,r),...Fh(n),...Mh(n),forFunnel(s){return i.assertActive(),zh(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 Ei(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,a)=>Ei(i,t[a]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let n=Object.entries(e),r=Object.entries(t);return n.length===r.length&&n.every(([i,a])=>Object.hasOwn(t,i)&&Ei(a,Reflect.get(t,i)))}function ms(e,t){let n=qg.safeParse(t);if(!n.success)throw new b("INVALID_RESPONSE","Funnel response contract changed");let r=n.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new b("SCOPE_MISMATCH","Funnel scope changed");return r}var Ri=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function fs(e){let t=jt.test(e.apiKey);if(typeof window<"u"&&!t)throw new b("SERVER_ONLY","Funnel starts are issued by your backend");if(!t&&!Ri.test(e.apiKey))throw new b("INVALID_TOKEN","A customer credential or server API key is required");return{async start(n){let r=Pt.safeParse({...n,operation:"start"});if(!r.success||r.data.operation!=="start"||(t?r.data.customer!==void 0:r.data.customer===void 0))throw new b("INVALID_REQUEST","Invalid current Funnel start");let i=r.data,a=mr({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||a.identify(e.apiKey);let o=ms(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")||!Ei(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 el(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((f,m)=>{s=()=>m(n.signal?.reason),n.signal?.addEventListener("abort",s,{once:!0}),n.signal?.aborted&&s()});try{for(;;){let f=await Promise.race([r.read(),c]);if(f.done){o=!0;break}if(a+=f.value.length,a>t)throw n.error("limit");i.push(f.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 f of i)u.set(f,l),l+=f.length;return u}async function Gh(e,t,n){return new TextDecoder("utf-8",{fatal:!0}).decode(await el(e,t,n))}function gs(e,t){let n=typeof e=="string"?new TextEncoder().encode(e):e;return n.byteLength===t.byteLength&&mu(n)===t.sha256}async function hs(e,t){let n=Ur.parse(t),{artifact:r,environmentId:i}=n.content,a=new yn(e.baseUrl??pr).origin,o=new yn(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((f,m)=>{c=setTimeout(()=>{let h=new b("TIMEOUT","Public Paywall read timed out");s.abort(h),m(h)},Xt.initializationMs)}),l=(async()=>{let f=await(e.fetch??globalThis.fetch)(o,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:s.signal});if(s.signal.aborted&&(f.body?.cancel().catch(()=>{}),s.signal.throwIfAborted()),!f.ok||!f.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(f.headers.get("content-length"))>r.byteLength)throw f.body?.cancel().catch(()=>{}),new b("INVALID_RESPONSE","Public Paywall is unavailable");let m=await el(f,r.byteLength,{signal:s.signal,error:h=>new b("INVALID_RESPONSE",h==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!gs(m,r))throw new b("INVALID_RESPONSE","Public Paywall digest or size changed");return Uf(n,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(m)))})();try{return await Promise.race([l,u])}finally{clearTimeout(c)}}var Kh=(e,t)=>new b(e,t);async function tl(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=QI(e,t,o)}catch{i=null}return a??(a=e.snapshot?.generation??(await e.refresh()).generation),{advance:{policyRevision:r.policyRevision,generation:a},prediction:i}}function QI(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=Ru({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:gn.parse(o)}),c=JI(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 JI(e,t,n){return eh(e,t,n,Kh)}var tn=require("zod");var Hh=Pt.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}),Qh=tn.z.strictObject({schemaVersion:tn.z.literal(1),scope:Ne,runId:tn.z.uuid(),funnelId:tn.z.uuid(),versionId:tn.z.uuid(),processBindingIds:tn.z.record(tn.z.uuid(),tn.z.uuid().nullable()).optional(),command:Hh.optional(),closeCommand:Hh.refine(e=>e.operation==="close").optional(),purchase:tn.z.strictObject({receiptId:tn.z.uuid(),operationId:tn.z.uuid(),generation:tn.z.number().int().nonnegative()}).optional(),closed:tn.z.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),Zt=()=>new b("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),As=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Jh(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:Qh.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 f=await a();if(f.entry&&n!==null&&r(f.entry)!==n)throw Zt();let m=u(f.entry,f.revision);if(As(f.entry,m)){t=f.revision;return}let h=await e.write(f.revision,m);if(h!==null){if(!Number.isSafeInteger(h)||h<=f.revision)throw Zt();t=h;return}}throw Zt()}function c(u,l){if(!u||!l)return u;if(u.processBindingIds&&Object.hasOwn(u.processBindingIds,l)){let f={...u.processBindingIds};delete f[l],u={...u,processBindingIds:f}}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 Zt();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=Qh.parse(u),f=l.command;return!f||n!==null&&r(l)!==n?Promise.reject(Zt()):(n??(n=r(l)),o(()=>s((m,h)=>{if(m&&!As(r(m),r(l)))throw Zt();if(m&&l.processBindingIds){for(let[d,A]of Object.entries(l.processBindingIds))if(m.processBindingIds&&Object.hasOwn(m.processBindingIds,d)&&m.processBindingIds[d]!==A)throw Zt();m={...m,processBindingIds:{...m.processBindingIds,...l.processBindingIds}}}if(!m){if(h!==t&&f.operation!=="close")throw Zt();return l}if(!m.command)return{...m,command:f,...f.operation==="close"?{closed:!0}:{}};if(f.operation==="close"&&m.command.operation!=="close"){if(m.command.requestId===f.requestId||m.closeCommand&&!As(m.closeCommand,f))throw Zt();return{...m,closeCommand:f,closed:!0}}if(!As(m.command,f))throw Zt();return m})))},observePurchase(u,l,f,m){return o(()=>s((h,d)=>{if(!h&&d!==t||h&&r(h)!==r({...u,schemaVersion:1}))throw Zt();if(h?.purchase&&h.purchase.generation>l.generation)return c(h,m);if(h?.purchase&&h.purchase.generation===l.generation&&h.purchase.operationId!==l.operationId)throw Zt();return f?!h?.purchase||h.purchase.operationId!==l.operationId?c(h,m):c(h.command?{...h,purchase:void 0}:null,m):c({schemaVersion:1,...u,...h,purchase:l},m)}))},settle(u){return o(()=>s(l=>c(l,u)))}}}function Zh(e){let t,n,r=()=>new b("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,n=e.locks??globalThis.navigator?.locks,!t||!n||!globalThis.crypto?.subtle)throw r();let s=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??pr).href,e.runToken])),c=new Uint8Array(await crypto.subtle.digest("SHA-256",s));return"indiana.funnel.commands.v1."+Array.from(c,u=>u.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function a(s){try{let c=await i;return await n.request(c,{mode:"exclusive"},()=>s(c))}catch(c){throw c instanceof b?c:r()}}function o(s){let c=t.getItem(s);if(c===null)return{revision:0,entry:null};if(c.length>1048576)throw r();let u=JSON.parse(c);if(!u||typeof u!="object"||!("revision"in u)||!("entry"in u)||!Number.isSafeInteger(u.revision)||Number(u.revision)<0)throw r();return{revision:Number(u.revision),entry:u.entry}}return{read:()=>a(o),write:(s,c)=>a(u=>{if(o(u).revision!==s)return null;if(!Number.isSafeInteger(s+1))throw r();return t.setItem(u,JSON.stringify({revision:s+1,entry:c})),s+1})}}function Wh(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(f){if(n&&(n.projectId!==f.projectId||n.environment!==f.environment))throw new b("SCOPE_MISMATCH","Run scope changed");n??(n={...f})},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(f,m="Run identity changed during the request"){if(f!==i||s)throw new b("IDENTITY_CHANGED",m)},assertRun(f){if(r&&(f.id!==r.id||f.source.type!==r.source.type||f.source.id!==r.source.id||f.source.versionId!==r.source.versionId||f.locale!==r.locale||!Ei(f.parameters,r.parameters)))throw new b("INVALID_RESPONSE","Run version changed");if(e&&f.source.id!==e)throw new b("INVALID_RESPONSE","Run belongs to another Funnel")},publish(f,m,h,d,A){if(!(f.operation==="review"&&r&&r!==h&&m.run.revision<=r.revision)&&!(r&&m.run.revision===r.revision&&d!==void 0&&d<u)&&(f.operation==="review"&&!m.run.stopped&&["running","waiting"].includes(m.run.status)&&r&&m.run.nodeId===r.nodeId&&m.run.visit===r.visit&&m.run.revision===r.revision&&(m.run.screen=r.screen,(r.paywall?.quote?.operationId===m.review?.activeOperationId||!r.paywall?.quote&&m.review?.activeOperationId===null)&&(m.run.paywall=r.paywall)),!(r?.paywall&&m.run.paywall&&r.paywall.receiptId===m.run.paywall.receiptId&&(m.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||m.run.revision>=r.revision)r=m.run;else if(!A)return;if(r)for(let k of l)try{k(structuredClone(r))}catch{}}},identify(f){if(s)throw new b("IDENTITY_CHANGED","Controller was reset");if(!jt.test(f))throw new b("INVALID_TOKEN","Customer credential required");o(),c=f},subscribe(f){return l.add(f),()=>l.delete(f)},reset(){s||(s=!0,o(),c=void 0,r=null,l.clear())}}}function fr(e){let{customerToken:t,...n}=e;return n}var ZI=e=>!(e instanceof b)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function Yh({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,f=e?e.load().then(g=>{if(t.disposed)throw new b("IDENTITY_CHANGED","Controller was reset during command restoration");if(l=g,!g)return;if(r){if([g.command,g.closeCommand].some(I=>I&&!Object.hasOwn(g.processBindingIds??{},I.requestId)))throw new b("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(g.processBindingIds??{})}if(t.scope&&(g.scope.projectId!==t.scope.projectId||g.scope.environment!==t.scope.environment))throw new b("SCOPE_MISMATCH","Pending command belongs to another scope");if(u=g.purchase,o=g.closed===!0,!g.command)return;let y=g.command;i=y.operation==="close"?null:y,a=y.operation==="close"?y:g.closeCommand?.operation==="close"?g.closeCommand:null,a&&(o=!0);for(let I of[i,a])I&&c.add(I.requestId)}):Promise.resolve();f.catch(()=>{});async function m(g){e&&await f;let y=t.generation;if(e){if(!t.view||!t.scope)throw new b("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:fr(g),...r?{processBindingIds:{[g.requestId]:r.binding(g.requestId)}}:{}})}if(y!==t.generation||i!==g&&a!==g)throw new b("IDENTITY_CHANGED","Run changed before command dispatch");let I=c.has(g.requestId);c.add(g.requestId);try{return await n(g)}catch(w){throw y===t.generation&&(i===g||a===g)&&!I&&!ZI(w)&&(e&&await e.settle(g.requestId),y===t.generation&&k(g)),w}}function h(g){let y=Pt.parse(g);if(y.operation==="start"||y.operation==="get"||y.operation==="review")throw new b("INVALID_REQUEST","Mutation required");if(o&&y.operation!=="close"){if(i?.requestId===y.requestId)return A(y.requestId);throw new b("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(y.operation==="close"){if(i?.requestId===y.requestId)throw new b("INVALID_REQUEST","Close requires its own request identity");if(o=!0,a&&JSON.stringify(fr(a))!==JSON.stringify(fr(y)))throw new b("COMMAND_PENDING","Retry the original Close");return a??(a=y),s.close?s.close:d(a,"close")}if(i){if(JSON.stringify(fr(i))!==JSON.stringify(fr(y)))throw new b("COMMAND_PENDING","Retry the original command before sending another");if(s.command)return s.command}else i=y;return d(i,"command")}function d(g,y){let I=m(g);s[y]=I;let w=()=>{s[y]===I&&(s[y]=null)};return I.then(w,w),I}function A(g){return n({operation:"get",settlementRequestId:g})}function k(g){return!g||i!==g&&a!==g?!1:(i===g&&(i=null),a===g&&(a=null),c.delete(g.requestId),!i&&!a&&(l=null),!0)}return{ready:f,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(g){if(l&&(g.run.id!==l.runId||g.run.source.id!==l.funnelId||g.run.source.versionId!==l.versionId))throw new b("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(g,y,I,w){let C=g.operation==="get"?g.settlementRequestId:"requestId"in g&&g.operation!=="start"?g.requestId:void 0,j=C&&y.settlement?.state==="settled"&&y.run.pendingRequest?.requestId!==C&&(g.operation==="get"||!o||g.operation==="close"||!["running","waiting"].includes(y.run.status))?C:void 0,E=i?.requestId===j?i:a?.requestId===j?a:void 0;e?.bind({scope:y.scope,runId:y.run.id,funnelId:y.run.source.id,versionId:y.run.source.versionId});let ae=y.run.paywall,xe=ae??y.purchase,Pe=xe?.operation,Ee=y.settlement&&(!ae||ae.purchaseRequestId===y.settlement.requestId)&&(!u||u.operationId===y.settlement.operationId)?y.settlement:void 0,ye=Pe?.operationId??xe?.quote?.operationId??Ee?.operationId,gt=xe?.receiptId??Ee?.receiptId,Je=ae?.selectionGeneration??u?.generation??0;if(e&&ye&&gt&&g.operation!=="review"&&(!t.view||y.run.revision>=t.view.revision)&&(w===void 0||w>=t.readSequence)&&(!u||Je>=u.generation)){let Te={receiptId:gt,operationId:ye,generation:Je},tt=Pe?.status==="complete"||xe?.canReselect===!0;await e.observePurchase({scope:y.scope,runId:y.run.id,funnelId:y.run.source.id,versionId:y.run.source.versionId},Te,tt,j),t.assertCurrent(I),(!u||Te.generation>=u.generation)&&(w===void 0||w>=t.readSequence)&&(tt?u?.operationId===Te.operationId&&(u=void 0):u=Te)}else e&&j&&await e.settle(j);return t.assertCurrent(I),j?k(E):!1},stop(){o=!0},submit:h,settle:A,reset(){o=!0,i=null,a=null,u=void 0,l=null,s.close=null,c.clear(),s.command=null}}}function gr(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new b("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!Ri.test(e.serverKey)))throw new b("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new b("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let t=mr({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),n=Wh(e.funnelId,e.scope??e.configuration?.scope),r=e.session?.subscribeIdentity(u),i=null,a=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?Zh(e):void 0),o=a&&Jh(a),s=Yh({journal:o,state:n,call:l,processIdentity:e.process});async function c(y){if(e.process)return e.process.request(y);let I=n.generation;n.assertCurrent(I);let w=performance.now()+(e.timeoutMs??35e3),C=n.customerToken??("customerToken"in y?y.customerToken:void 0);if(e.session){let ae=n.signal,xe,Pe=()=>{},Ee=new Promise((ye,gt)=>{Pe=()=>gt(ae.reason),ae.addEventListener("abort",Pe,{once:!0}),xe=setTimeout(()=>gt(new b("TIMEOUT","Longplay request timed out")),Math.max(1,w-performance.now()))});try{C=await Promise.race([Promise.resolve().then(()=>(n.assertCurrent(I),e.session.access())),Ee])}finally{clearTimeout(xe),ae.removeEventListener("abort",Pe)}}n.assertCurrent(I);let j={...y,...C?{customerToken:C}:{}},E=y.operation==="page_experiments"?vo.parse(j):Pt.parse(j);return t.requestWithCredential("funnels",E,e.runToken,{headers:e.serverKey&&!C?{[Bg]:e.serverKey}:void 0,timeoutMs:Math.max(1,w-performance.now())})}function u(){r?.(),n.reset(),s.reset(),i=null,t.dispose()}async function l(y,I){let w=n.generation,C=()=>n.assertCurrent(w);o&&await s.ready,C();let j=n.view,E=ms(e,await c(y));if(y.operation==="review"&&!E.review)throw new b("INVALID_RESPONSE","Historical projection is missing");if(C(),E.runToken&&E.runToken!==e.runToken)throw new b("INVALID_RESPONSE","Run credential changed");let ae=y.operation==="get"?y.settlementRequestId:"requestId"in y&&y.operation!=="start"?y.requestId:void 0;if(ae&&E.settlement?.requestId!==ae)throw new b("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");s.assertBinding(E),n.assertRun(E.run),n.bindScope(E.scope);let xe=await s.observe(y,E,w,I);return!E.run.stopped&&["running","waiting"].includes(E.run.status)&&y.operation==="get"&&y.settlementRequestId||(C(),["running","waiting"].includes(E.run.status)||s.stop(),n.publish(y,E,j,I,xe)),E}let f=s.submit,m=null,h=new WeakMap;function d(y){let I=h.get(y);if(I)return I;let w=k(y);return h.set(y,w),w}let A=!1;async function k(y){let I=await y;if(I.run.instruction?.type!=="evaluate_segment")return I;if(m)return m;A=!0;let w=n.generation,C=(async()=>{for(let j=0;j<32&&I.run.instruction?.type==="evaluate_segment";j++){if(s.pending||s.closeRequested)return I;let E=I.run;if(I.run.instruction?.type==="evaluate_segment"){let{advance:xe}=await tl(e.configuration,E,{predict:!1});if(w!==n.generation)throw new b("IDENTITY_CHANGED","Run identity changed during segment calculation");if(s.pending||s.closeRequested)return I;if(n.view&&(n.view.revision!==E.revision||n.view.visit!==E.visit||n.view.nodeId!==E.nodeId))return l({operation:"get"});let Pe=!0;tl(e.configuration,E).then(({prediction:Ee})=>{Pe&&w===n.generation&&!s.closeRequested&&n.view?.id===E.id&&!n.view.stopped&&n.view.nodeId===E.nodeId&&n.view.visit===E.visit&&n.view.revision===E.revision&&(i=Ee)}).catch(()=>{});try{I=await f({operation:"commit_segment",requestId:Mg(E.id,E.visit,`segment:${E.revision}`),nodeId:E.nodeId,visit:E.visit,revision:E.revision,...xe})}finally{Pe=!1,i=null}}}return I})();m=C;try{return await C}finally{m===C&&(m=null)}}let g={get configuration(){return A?e.configuration:void 0},get configurationReady(){return!0},get view(){return n.view?structuredClone(n.view):null},get pendingCommand(){let y=s.closing??s.pending;return y?structuredClone(fr(y)):null},get pendingCommands(){return[s.pending,s.closing].filter(y=>y!==null).map(y=>structuredClone(fr(y)))},get pendingPurchase(){return s.purchase?structuredClone(s.purchase):null},get prediction(){let y=n.view;return i&&y&&!y.stopped&&["running","waiting"].includes(y.status)&&y.id===i.runId&&y.nodeId===i.from.nodeId&&y.visit===i.from.visit&&y.revision===i.from.revision&&!s.closeRequested?structuredClone(i):null},settle:s.settle,get webViewUrl(){return"bundled"},resolvePaywall(y){return hs(e,y)},async pageExperiments(y,I=[]){let w=n.generation;n.assertCurrent(w);let C=n.view?.id;if(!C)throw new b("INVALID_REQUEST","Read the Run before its page experiments");let j=zg.parse(await c(vo.parse({operation:"page_experiments",release:y,usedReceiptIds:I})));if(n.assertCurrent(w),j.runId!==C||j.scope.projectId!==n.scope?.projectId||j.scope.environment!==n.scope?.environment)throw new b("SCOPE_MISMATCH","Page experiment Run changed");return j},review(y){return l({operation:"review",...y?{receiptId:y}:{}},n.nextRead())},async get(y,I){o&&await s.ready,I??(I=s.purchase&&{receiptId:s.purchase.receiptId,operationId:s.purchase.operationId});let w=n.nextRead();return d(l({operation:"get",...y?{data:y}:{},...I?{purchase:I}:{}},w))},resume(y=n.view?.pendingRequest?.requestId){return y?s.closeRequested?g.settle(y):s.pending?.requestId===y?d(f(s.pending)):d(f({operation:"resume",requestId:y})):Promise.reject(new b("INVALID_REQUEST","No interrupted command is available"))},submit(y){return d(f(y))},retry(){return s.closeFlight?s.closeFlight:s.closing?f(s.closing):s.closeRequested&&s.pending?g.settle(s.pending.requestId):s.inFlight?d(s.inFlight):s.pending?d(f(s.pending)):Promise.reject(new b("INVALID_REQUEST","No command is pending"))},identify(y){n.identify(y),i=null,t.reset()},subscribe:n.subscribe,reset:u};return g}function Xh(e){if(!jt.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=fs({...e,scope:e.scope,apiKey:e.customerToken});return{async start(n){let r=await t.start(n),i=gr({...e,runToken:r.runToken});i.identify(e.customerToken);let a=r.run.instruction?.type==="evaluate_segment"?await i.get():r;return{...r,...a,controller:i}}}}function eA(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 tA(e,t,n){if(e.operationId!==t.operationId||t.currency!==void 0&&e.currency!==t.currency)throw new b("INVALID_RESPONSE",n)}function nA(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 rA(e,t,n=!1){return!e||e.operationId!==t?.operationId?t:e.status==="complete"&&t.status!=="complete"||e.status!=="pending"&&(t.status==="pending"||n&&t.status!=="complete")?e:t}async function iA(e,t){if(!jt.test(t.customerToken))throw new b("INVALID_TOKEN","A verified Customer credential is required");if(e.session&&e.session.peek()!==t.customerToken)throw new b("SCOPE_MISMATCH","Paywall credential does not match the shared session");let n=O.resolvePaywall.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale,...t.requirement?{requirement:t.requirement}:{}}),r=mr(e);e.session||r.identify(t.customerToken);let i=null,a=!1,o=null,s=null,c=null,u=null;function l(){if(a)throw new b("IDENTITY_CHANGED","Paywall is closed")}async function f(){l();let A=O.resolvePaywall,k=await me(r.request,A,{...n,selector:i?{type:"version",versionId:i.id}:n.selector}),g=await hs(e,k.paywall);if(l(),t.paywallVersionId?g.id!==t.paywallVersionId:g.paywallId!==t.paywallId)throw new b("INVALID_RESPONSE","The requested Paywall changed");if(i&&(!eA(g,i)||g.paywallId!==i.paywallId))throw new b("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return i=g,structuredClone(i)}async function m(A){if(l(),u&&A!=="read")throw new b("COMMAND_PENDING","Wait for the original quote");if(!o)throw new b("INVALID_REQUEST","A quoted purchase is required");let k=o,g=A==="read"?O.readSubscriptionOperation:O.attach,y=await me(r.request,g,{operationId:k.operationId,...A==="read"?{}:{intent:A}});return tA(y.operation,{operationId:k.operationId,currency:n.commerce.currency},"The purchase operation changed"),l(),o?.operationId!==k.operationId?structuredClone(y.operation):(s=rA(s,y.operation),structuredClone(s))}let h={get view(){return i?structuredClone(i):null},get quote(){return o?structuredClone(o):null},get operation(){return s?structuredClone(s):null},get webViewUrl(){return"bundled"},refresh:f,async preview(A){if(l(),!i)throw new b("INVALID_REQUEST","Load the Paywall first");let k=i.document.buttons[A.actionId];if(k?.type!=="checkout")throw new b("INVALID_REQUEST","Choose an authored purchase action");let g=Lm(k.product,A.selection,i.capabilities);if(!g)throw new b("PRODUCT_UNAVAILABLE","Choose an available Product");let y=Tf(i.document.screen,g,A.selection,i.capabilities),I=O.previewAttach.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,requestId:A.requestId,plans:[{productVersionId:g,...Object.keys(y).length?{featureQuantities:y}:{}}],provider:n.commerce.provider,currency:n.commerce.currency,...A.offerId?{offerId:A.offerId}:{},...A.nativeOffer?{nativeOffer:A.nativeOffer}:{}}),w=JSON.stringify(I);if(c&&c!==w&&(u||!s||s.status==="pending"))throw new b("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(c===w){if(u)return u;if(o)return structuredClone(o)}c!==w&&(o=null,s=null),c=w;let C=(async()=>{let j=O.previewAttach,E=await me(r.request,j,I);return l(),nA(E.quote,{productVersionId:g,featureQuantities:y,currency:n.commerce.currency,provider:n.commerce.provider},"The purchase quote changed its selected Product or presentment"),o=E.quote,s=null,structuredClone(o)})();u=C;try{return await C}finally{u===C&&(u=null)}},confirm:()=>m("confirm"),cancel:()=>m("cancel"),read:()=>m("read"),destroy(){a||(a=!0,d?.(),r.dispose(),i=null,o=null,s=null,c=null)}},d=e.session?.subscribeIdentity(h.destroy);try{return await f(),h}catch(A){throw h.destroy(),A}}function oA(e,t){let n,r=0,i=-1,a,o=!1,s=()=>{if(o)throw new b("CLOSED","Native host was destroyed");if(!e.nativeModule)throw new b("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return e.nativeModule},c=()=>new b("IDENTITY_CHANGED","Customer identity changed during the native operation"),u=t.subscribeIdentity(()=>{r++,i=-1;let h=r;n&&e.nativeModule&&n.then(d=>e.nativeModule.reset(d,h)).catch(()=>{})}),l=e.nativeEvents?.(h=>{!n||!e.nativeModule||typeof h?.requestId!="string"||(async()=>{let d=await n;if(h.instanceId!==d)return;if(h.kind==="credential"){let g=r,y=null;try{if(!o&&h.revision===g){let I=await t.access();!o&&r===g&&(y=I)}}finally{await e.nativeModule.provideCredential(d,h.requestId,y)}return}let A=!1,k=r;try{if(o||h.revision!==k||!e.onNativeAction)throw c();await e.onNativeAction(h.action),A=!o&&r===k}finally{await e.nativeModule.acknowledge(d,h.requestId,A)}})().catch(()=>{})});async function f(h,d={}){let A=s();if(t.snapshot()&&!e.nativeEvents)throw new b("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let k=r,g=await t.access();if(o||r!==k)throw c();if(!n){let w=A.create(JSON.stringify({baseUrl:e.baseUrl??"https://api.longplayai.com",scope:e.scope,timeout:(e.timeoutMs??15e3)/1e3,credentialEvents:!!e.nativeEvents}));n=w,w.catch(()=>{n===w&&(n=void 0)})}let y=await n;if(o||r!==k)throw c();if(i!==k){if(!a||a.epoch!==k){let C=(async()=>{if(await A.identify(y,JSON.stringify({revision:k,credentials:g})),o||r!==k)throw await A.reset(y,k),c();i=k})();a={epoch:k,task:C}}let w=a;try{await w.task}finally{a===w&&(a=void 0)}}let I=await A.invoke(y,h,JSON.stringify(d));if(o||r!==k)throw c();try{return JSON.parse(I)}catch{throw new b("INVALID_RESPONSE","Native host returned invalid JSON")}}async function m(h,d){let A=await f(h,d);if(!A||typeof A!="object"||Array.isArray(A)||A.status!=="complete"&&A.status!=="dismissed")throw new b("INVALID_RESPONSE","Native presentation returned an invalid result");return A}return{showFunnel(h){return m("showFunnel",{runToken:h})},showPaywall(h){return m("showPaywall",h)},showContent(h){return m("showContent",h)},purchaseSubscription(h,d){return f("purchaseSubscription",{operationId:h,accepted:d})},switchSubscription(h,d){return f("switchSubscription",{operationId:h,accepted:d})},restorePurchases(){return f("restorePurchases")},manageSubscriptions(h){return f("manageSubscriptions",h?{productId:h}:{})},async dismiss(){r++,i=-1,n&&await s().reset(await n,r)},async destroy(){o||(o=!0,r++,u(),l?.(),n&&e.nativeModule&&await e.nativeModule.destroy(await n))}}}var WI=O.trackUsage.request.shape.command,YI=O.trackUsage.response;function aA(e){let t=Ne.parse(e.scope),n=$h({...e,scope:t}),r={...e,scope:t,session:n.session},i=oA(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 Xh({...r,customerToken:s()})},resumeFunnel(c){return s(),gr({...r,runToken:c})},paywall(c){return iA(r,{...c,customerToken:s()})},async trackUsage(c){if(s(),!e.usageReporter)throw new b("INVALID_REQUEST","Configure your authenticated backend usageReporter");let u=WI.parse(c),l=a,f;try{f=await e.usageReporter(u)}catch(h){throw l!==a?new b("IDENTITY_CHANGED","Customer identity changed during usage reporting"):h}if(l!==a)throw new b("IDENTITY_CHANGED","Customer identity changed during usage reporting");let m=YI.parse(f);if(m.scope.projectId!==t.projectId||m.scope.environment!==t.environment)throw new b("INVALID_RESPONSE","Usage response scope differs");return m}}}var uA=require("zod");var ki=require("zod");var XI=ki.z.record(ki.z.string().regex(/^[a-f0-9]{64}$/),ki.z.strictObject({at:ki.z.number(),text:ki.z.string()})),Qr=2*1048576,ev=100;function tv(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function sA(e,t){let n=t===void 0?tv():t,r=new Map,i=0,a=!1,o=!1,s,c;async function u(f){if(!n)return null;let m;try{let h=await Promise.race([Promise.resolve().then(()=>n.getItem(f)),new Promise(d=>{m=setTimeout(()=>d(null),ev)})]);return typeof h=="string"&&h.length<=Qr&&new TextEncoder().encode(h).byteLength<=Qr?h:null}catch{return null}finally{clearTimeout(m)}}function l(){if(c)return c;let f=(async()=>{try{let m=await u(`${e}:artifacts`);if(m)return XI.parse(JSON.parse(m))}catch{}return{}})();return c=f,f.finally(()=>{c===f&&(c=void 0)}),f}return{async readManifest(){return u(e)},writeManifest(f){!n||f.length>Qr||new TextEncoder().encode(f).byteLength>Qr||(s=f,!o&&(o=!0,Promise.resolve().then(async()=>{try{for(;s!==void 0;){let m=s;try{await n.setItem(e,m)}catch{}s===m&&(s=void 0)}}finally{o=!1}})))},async readArtifact(f){let m=(await l())[f],h=Date.now();return m&&h>=m.at&&h-m.at<=Xt.retentionMs?m.text:void 0},writeArtifact(f,m){if(!n||m.length>Qr)return;let h=r.get(f);if(h?.text===m||!h&&r.size>=128)return;let d=new TextEncoder().encode(m).byteLength;i-(h?.byteLength??0)+d>Qr||(r.set(f,{text:m,byteLength:d}),i+=d-(h?.byteLength??0),!a&&(a=!0,Promise.resolve().then(async()=>{try{for(;r.size;){let A=new Map(r);try{let k={...await l()},g=Date.now();for(let[C,j]of A)k[C]={at:g,text:j.text};let y={},I=2,w=0;for(let[C,j]of Object.entries(k).sort(([,E],[,ae])=>ae.at-E.at)){if(j.at>g||g-j.at>Xt.retentionMs)continue;let E=new TextEncoder().encode(JSON.stringify({[C]:j})).byteLength;I+E>Qr||w>=128||(y[C]=j,I+=E,w++)}await n.setItem(`${e}:artifacts`,JSON.stringify(y))}catch{}finally{for(let[k,g]of A)r.get(k)===g&&(r.delete(k),i-=g.byteLength)}}}finally{a=!1}})))}}}var Oe=(e,t)=>new b(e,t),hr=()=>performance.now(),cA=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function lA(e){let t=lu.parse(e.scope),n=new yn(e.origin??pr);if(n.username||n.password||n.search||n.hash||n.pathname!=="/"||n.protocol!=="https:"&&!(n.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(n.hostname)))throw Oe("INVALID_URL","Configuration requires a trusted HTTPS origin");let r=new Set([n.origin,...(e.assetOrigins??[]).map(W=>{let Z=new yn(W);if(Z.protocol!=="https:"||Z.username||Z.password||Z.search||Z.hash||Z.pathname!=="/")throw Oe("INVALID_URL","Invalid configuration asset origin");return Z.origin})]),i=e.fetch??globalThis.fetch.bind(globalThis),a=`/api/v1/configuration/${t.environmentId}`,o=`indiana:configuration:1:${n.origin}:${Ct(t)}`,s=sA(o,e.storage),c,u=0,l=0,f=!1,m=!1,h=0,d=0,A,k,g,y,I=0,w=new Set,C=new Set,j=new Map,E=new Map,ae=0,xe=!1;function Pe(){for(let W of w)try{W()}catch{}}function Ee(W){try{e.onError?.(W)}catch{}}let ye=()=>!m&&!f&&!!c&&hr()<u&&Date.now()<l;function gt(){if(!ye())throw Oe("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Je(W,Z,le){if(!j.has(W)){for(;j.size&&(j.size>=128||ae+le>Xt.maxCacheBytes);){let de=j.entries().next().value;ae-=de[1].byteLength,j.delete(de[0])}j.set(W,{text:Z,byteLength:le}),ae+=le}}function Te(W,Z,le){return Gh(W,Z,{signal:le,error:de=>Oe("INVALID_RESPONSE",de==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function tt(W){let Z=new yn(W,n);if(!r.has(Z.origin)||Z.username||Z.password||Z.hash||Z.search)throw Oe("INVALID_URL","Configuration artifact origin is not trusted");return Z.href}async function Eo(W,Z,le=!1){let de=await i(tt(W),{method:"GET",credentials:"omit",redirect:"error",cache:le?"default":"no-cache",signal:Z,headers:{}});if(de.status===429){let Ye=de.headers.get("retry-after")??"";I=/^\d+$/.test(Ye)?Number(Ye)*1e3:Math.max(0,Date.parse(Ye)-Date.now())||15e3}if(!de.ok&&de.status!==304)throw Oe(`CONFIGURATION_HTTP_${de.status}`,"Configuration synchronization failed");return de}function Jr(W,Z,le){let de=Date.parse(W.headers.get("x-indiana-config-validated-at")??""),Ye=Date.parse(W.headers.get("x-indiana-config-valid-until")??""),rt=Date.parse(W.headers.get("date")??""),$e=W.headers.get("age"),nn=$e!==null&&/^\d+(\.\d+)?$/.test($e)?Number($e)*1e3:NaN;if(![de,Ye,rt,nn].every(Number.isFinite)||Ye<=de||Ye-de>Xt.maxControlAgeMs||de>rt+1e3)throw Oe("INVALID_RESPONSE","Configuration freshness evidence is invalid");let Mt=Math.min(Ye-de,le.maxControlAgeSeconds*1e3,Xt.maxControlAgeMs)-Math.max(nn,rt-de,0)-(hr()-Z);if(Mt<=0)throw Oe("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return hr()+Mt}function lt(){if(clearTimeout(g),clearTimeout(y),m||!w.size)return;ye()&&(y=setTimeout(()=>{ye()?lt():Pe()},Math.max(1,u-hr())),cA(y));let W=d?Math.min(15e3,1e3*2**Math.min(d-1,4)):Math.min(15e3,(c?.policy.refreshIntervalSeconds??15)*1e3);g=setTimeout(()=>{Kt().catch(Ee)},Math.max(I,W*(.8+Math.random()*.2))),cA(g)}async function Kt(){if(m)throw Oe("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(A)return A;let W=h,Z=new AbortController;k=Z;let le=(async()=>{if(!xe){xe=!0;try{let ko=await s.readManifest();if(ko&&!c){let qn=pu.parse(JSON.parse(ko));Ct(qn.scope)===Ct(t)&&(c=qn)}}catch{}}Z.signal.throwIfAborted();let $e=c,nn=hr(),Lt=await Eo(a,Z.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 Eo(a,Z.signal));let Mt=Lt.status===304?$e:pu.parse(JSON.parse(await Te(Lt,Xt.maxManifestBytes,Z.signal))),{generation:Zr,...Wr}=Mt,Mn=Lt.headers.get("etag");if(Ct(Mt.scope)!==Ct(t)||qf(Wr)!==Zr||Mn!==`"${Zr}"`&&Mn!==`W/"${Zr}"`)throw Oe("INVALID_RESPONSE","Configuration scope or content identity changed");if($e&&(Mt.revision<$e.revision||Mt.revision===$e.revision&&Mt.generation!==$e.generation))throw Oe("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[ko,qn]of Object.entries($e?.funnels??{})){let xr=Mt.funnels[ko];if(xr&&(xr.controlRevision<qn.controlRevision||xr.evaluationRevision<qn.evaluationRevision||xr.controlRevision===qn.controlRevision&&xr.state!==qn.state||xr.evaluationRevision===qn.evaluationRevision&&xr.evaluationMode!==qn.evaluationMode))throw Oe("INVALID_RESPONSE","Funnel control revision changed identity")}let br=Jr(Lt,nn,Mt.policy);if(Z.signal.throwIfAborted(),W!==h)throw Oe("CONFIGURATION_DISPOSED","Configuration scope changed");return c=Mt,u=br,l=Date.now()+Math.max(0,br-hr()),f=!1,d=0,I=0,s.writeManifest(Ct(Mt)),Pe(),structuredClone(Mt)})(),de=setTimeout(()=>Z.abort(Oe("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Xt.initializationMs),Ye=new Promise(($e,nn)=>Z.signal.addEventListener("abort",()=>nn(Z.signal.reason),{once:!0})),rt=Promise.race([le,Ye]).catch($e=>{throw d++,($e instanceof uA.z.ZodError||$e instanceof SyntaxError||$e instanceof b&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes($e.code))&&(u=0,f=!0,Pe()),$e}).finally(()=>{clearTimeout(de),A===rt&&(A=void 0),lt()});return A=rt,rt}async function Ar(W){let Z=W.sha256,le=Wr=>gs(Wr,W);tt(W.url);let de=j.get(Z);if(de){if(de.byteLength!==W.byteLength)throw Oe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return j.delete(Z),j.set(Z,de),de.text}let Ye=E.get(Z);if(Ye){if(Ye.byteLength!==W.byteLength)throw Oe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return Ye.promise}let rt=new AbortController;C.add(rt);let $e=h,nn=(async()=>{try{let br=await s.readArtifact(Z);if(br&&le(br)){if(rt.signal.throwIfAborted(),m||$e!==h)throw Oe("CONFIGURATION_DISPOSED","Configuration scope changed");return Je(Z,br,W.byteLength),br}}catch{}rt.signal.throwIfAborted();let Wr=await Eo(W.url,rt.signal,!0),Mn=await Te(Wr,W.byteLength,rt.signal);if(!le(Mn))throw Oe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(m||$e!==h)throw Oe("CONFIGURATION_DISPOSED","Configuration scope changed");return Je(Z,Mn,W.byteLength),s.writeArtifact(Z,Mn),Mn})(),Lt=setTimeout(()=>rt.abort(Oe("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),Xt.initializationMs),Mt=new Promise((Wr,Mn)=>rt.signal.addEventListener("abort",()=>Mn(rt.signal.reason),{once:!0})),Zr=Promise.race([nn,Mt]).finally(()=>{clearTimeout(Lt),C.delete(rt),E.delete(Z)});return E.set(Z,{promise:Zr,byteLength:W.byteLength}),Zr}async function yr(){return ye()||await Kt(),gt(),c}async function ji(W){let Z,le=new Promise((de,Ye)=>{Z=setTimeout(()=>Ye(Oe("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Xt.initializationMs)});try{return await Promise.race([W(),le])}finally{clearTimeout(Z)}}function Ti(W,Z){if(gt(),c?.generation!==W.generation)throw Oe("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(Z&&c.funnels[Z]?.state!=="active")throw Oe("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function rl(W){let Z=W.gb.features;if(!Z)throw Oe("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let le=W.artifacts[Z];if(le.formatVersion!==1)throw Oe("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let de=Fc.parse(JSON.parse(await Ar(le)));if(Ct(de.scope)!==Ct({projectId:t.projectId,environment:t.environment})||de.generation!==le.generation||de.remoteFeatures.some(Ye=>Object.hasOwn(de.features,Ye)))throw Oe("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return Ti(W),{...de,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,u-hr())).toISOString()}}async function il(W,Z){let le=await yr(),de=le.funnels[W];Z&&(!de||de.evaluationMode==="local"&&!de.versions[Z])&&(A&&await A,le=await Kt()),Ti(le,W);let Ye=le.funnels[W];if(Ye.evaluationMode!=="local")throw Oe("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let rt=Z??Ye.currentVersionId,$e=Ye.versions[rt];if(!$e)throw Oe("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(le.artifacts[$e.artifact].formatVersion!==3)throw Oe("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[nn,Lt]=await Promise.all([Ar(le.artifacts[$e.artifact]).then(Mt=>Vf(JSON.parse(Mt))),Ye.evaluationMode==="local"?rl(le):void 0]);if(Lt&&Ct(Bf(nn,Lt))!==Ct($e.dependencies))throw Oe("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return Ti(le,W),{document:nn,growth:Lt,versionId:rt,control:structuredClone(Ye),manifest:structuredClone(le)}}async function ol(W,Z){try{return await il(W,Z)}catch(le){if(!(le instanceof b)||!(le.code==="CONFIGURATION_CHANGED"||le.code==="CONFIGURATION_HTTP_404"&&ye()))throw le;let de=c?.generation;if(A&&await A,await Kt(),le.code!=="CONFIGURATION_CHANGED"&&c?.generation===de)throw le;return il(W,Z)}}function ys(){f=!0,Pe(),Kt().catch(Ee)}let Ro=()=>{(typeof document>"u"||document.visibilityState==="visible")&&ys()};function mA(W){if(m)throw Oe("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return w.add(W),w.size===1&&(typeof window<"u"&&(window.addEventListener("online",ys),window.addEventListener("focus",Ro),document.addEventListener("visibilitychange",Ro)),lt()),()=>{w.delete(W),w.size||(clearTimeout(g),clearTimeout(y),al())}}function al(){typeof window<"u"&&(window.removeEventListener("online",ys),window.removeEventListener("focus",Ro),document.removeEventListener("visibilitychange",Ro))}return{scope:Object.freeze({...t}),refresh:Kt,subscribe:mA,assertFresh:gt,assertFeatures(W){gt();let Z=c.gb.features;if(!Z)throw Oe("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(W!==void 0&&c.artifacts[Z].generation!==W)throw Oe("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return ye()},get snapshot(){return c?structuredClone(c):null},get remainingMs(){return ye()?Math.max(0,u-hr()):0},async features(){return ji(async()=>rl(await yr()))},pageExperiments:()=>ji(async()=>{let W=await yr(),Z=W.gb.pageExperiments;if(!Z)throw Oe("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let le=W.artifacts[Z];if(le.formatVersion!==1)throw Oe("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let de=Wg.parse(JSON.parse(await Ar(le)));if(de.environmentId!==t.environmentId||de.generation!==le.generation)throw Oe("INVALID_RESPONSE","Page experiment scope or generation changed");return Ti(W),de}),funnel:(W,Z)=>ji(()=>ol(W,Z)),paywall:(W,Z)=>ji(async()=>{let le=await yr(),de=le.paywalls?.[W];if(!de||!Z&&de.state!=="published")throw Oe("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let Ye=Z??de.currentVersionId,rt=de.versions[Ye],$e=rt&&le.artifacts[rt.artifact];if(!$e||$e.kind!=="paywall"||$e.formatVersion!==1)throw Oe("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let nn=Ya.parse(JSON.parse(await Ar($e)));return Ti(le),{document:nn,versionId:Ye,version:rt.version,control:structuredClone(de),manifest:structuredClone(le)}}),async localFunnel(W,Z){let le=await ji(()=>ol(W,Z));if(!le.growth)throw Oe("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:de,remoteFeatures:Ye,...rt}=le.growth;return Jg({scope:{projectId:t.projectId,environment:t.environment},funnelId:W,versionId:le.versionId,evaluationMode:"local",evaluationRevision:le.control.evaluationRevision,document:le.document,payload:rt})},assertFunnel(W,Z,le){gt();let de=c.funnels[W];if(!de||de.state!=="active")throw Oe("FUNNEL_STOPPED","Funnel is paused or unavailable");if(de.evaluationMode!=="local")throw Oe("EVALUATION_MODE","This Funnel now executes at Longplay");if(Z!==void 0&&de.controlRevision!==Z)throw Oe("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(le!==void 0&&!de.versions[le])throw Oe("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!m){m=!0,h++,u=0,k?.abort(Oe("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(g),clearTimeout(y),al(),Pe(),w.clear();for(let W of C)W.abort(Oe("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));j.clear(),ae=0}}}}async function dA(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&&Ct(n)!==Ct(e.scope))throw new b("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await t.funnel(e.funnelId)).control.evaluationMode!=="local")throw new b("EVALUATION_MODE","This Funnel uses Remote evaluation");let i=Ri.test(e.credential);if(i?!e.customerId:e.customerId!==void 0)throw new b("INVALID_REQUEST","Only Server-Key starts name their Customer");let a=fs({...e,scope:n,apiKey:e.credential}),o=s=>{let c=gr({...e,scope:n,runToken:s,...i?{serverKey:e.credential}:{}});return i||c.identify(e.credential),c};return{async start(s){let c=await a.start({...s,funnelId:e.funnelId,...i?{customer:{type:"id",value:e.customerId}}:{}}),u=o(c.runToken),l=await u.get();return{...c,...l,controller:u}},async restore(s){let c=o(s),u=await c.get();if(u.run.source.id!==e.funnelId)throw c.reset(),new b("SCOPE_MISMATCH","Run belongs to another Funnel");return{...u,runToken:s,controller:c}}}}function nl(e,...t){try{Promise.resolve(e?.(...t)).catch(()=>{})}catch{}}function pA(e){if(!e.scope)throw new b("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(e.session!==void 0)throw new b("INVALID_CONFIGURATION","The merchant process adapter owns the session");let t=null,n,r=0,i=new Set,a=new Map,o=new Map;async function s(m){let h,d=new Promise((A,k)=>{h=setTimeout(()=>k(new b("TIMEOUT","Process bridge request timed out")),e.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(m),d])}finally{clearTimeout(h)}}function c(m){throw m instanceof b&&(m.status===401||m.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear()),m}function u(m,h){if(h!==r)throw new b("IDENTITY_CHANGED","Process was detached during a request");let d=Eu.parse(m);if(d.scope.projectId!==e.scope.projectId||d.scope.environment!==e.scope.environment)throw new b("SCOPE_MISMATCH","Process response belongs to another App/environment");if(t&&(t.run.id!==d.run.id||t.run.source.versionId!==d.run.source.versionId||t.run.source.id!==d.run.source.id||t.run.runExpiresAt!==d.run.runExpiresAt||t.run.identity.startedAs!==d.run.identity.startedAs||t.run.identity.participantId!==d.run.identity.participantId||t.run.identity.binding&&d.run.identity.binding&&t.run.identity.binding.id!==d.run.identity.binding.id))throw new b("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!t||d.run.revision>=t.run.revision){if(t?.run.identity.binding&&!d.run.identity.binding)throw new b("INVALID_RESPONSE","The process lost its Customer binding");t=d;for(let j of i)nl(j,d.run);d.run.instruction?.type==="authentication_required"&&nl(e.onAuthenticationRequired,d.run)}d.settlement?.accepted!==void 0&&o.set(d.settlement.requestId,d.settlement.accepted);let{identity:A,instruction:k,...g}=d.run,{contract:y,settlement:I,...w}=d,C=I&&(({accepted:j,...E})=>E)(I);return{...w,run:{...g,authenticated:A.binding!==null,instruction:k?.type==="authentication_required"?null:k},...C?{settlement:C}:{}}}let l=m=>(a.has(m)||a.set(m,t?.run.identity.binding?.id??null),a.get(m));async function f(m){let h=r,d=t?.run.identity.binding?.id??null,A=g=>{if(d!==(t?.run.identity.binding?.id??null))throw g;return c(g)};if(m.operation==="page_experiments"){if(!e.adapter.pageExperiments)throw new b("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return s(()=>e.adapter.pageExperiments(m.release,m.usedReceiptIds)).catch(A)}let k;if(m.operation==="get"){let{operation:g,customerToken:y,...I}=m;k=await s(()=>e.adapter.get({...I,...I.settlementRequestId?{settlementBindingId:l(I.settlementRequestId)}:{}})).catch(A)}else if(m.operation==="review")k=await s(()=>e.adapter.review(m.receiptId)).catch(A);else{if(m.operation==="start")throw new b("INVALID_REQUEST","Use process.open for entry");{let{customerToken:g,...y}=m;k=await s(()=>e.adapter.command(y,l(y.requestId))).catch(A)}}return u(k,h)}return{get view(){return t?.run??null},get controller(){return n},async open(m){let h=r,d=await s(()=>e.adapter.open(m)).catch(c);if(u(d,h),!n){n=gr({...e,runToken:d.runToken,process:{request:f,binding:l,restore(g){for(let[y,I]of Object.entries(g))a.set(y,I)}}});let A=n,k=A.submit;A.submit=async g=>{try{return await k(g)}catch(y){if(!(y instanceof b)||y.reason!=="IDENTITY_CONTEXT_CHANGED"||g.operation!=="submit"||g.input.type!=="screen"||a.get(g.requestId)!==null)throw y;await A.settle?.(g.requestId),await A.get();let I=A.view;if(o.get(g.requestId)!==!1||!I||I.id!==t?.run.id||I.nodeId!==g.nodeId||I.visit!==g.visit||!t?.run.identity.binding)throw y;return k({...g,requestId:crypto.randomUUID(),revision:I.revision})}}}await n.get();for(let A of n.pendingCommands??[])a.has(A.requestId)&&a.get(A.requestId)!==(t?.run.identity.binding?.id??null)&&await n.settle?.(A.requestId);return{run:t.run,controller:n}},async syncIdentity(){let m=r;u(await s(()=>e.adapter.syncIdentity()).catch(c),m),await n?.get();for(let h of n?.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(t?.run.identity.binding?.id??null)&&await n?.settle?.(h.requestId);return t.run},async detach(){r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear(),await s(()=>e.adapter.detach())},forProcess(m){if(!t?.run.identity.binding)throw new b("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:t.run.id,bindingId:t.run.identity.binding.id,receiptId:m}},subscribe(m){return i.add(m),()=>{i.delete(m)}},destroy(){r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear(),i.clear()}}}
17
+ */var Se=N.z.json().superRefine((e,t)=>{let n=0;function r(i,a){if(++n>1e4||a>20){t.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof i=="string"&&(i.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(i))&&t.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(i))i.forEach(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))(o.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(o)||["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved JSON property"}),r(s,a+1)}r(e,0),new TextEncoder().encode(JSON.stringify(e)).byteLength>65536&&t.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),Ot=N.z.record(N.z.string().min(1).max(128),Se).superRefine((e,t)=>{(!Se.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"})}),Iy=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"]),Jt=Ot.superRefine((e,t)=>{function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,a]of Object.entries(r)){if(i==="$savedGroup"&&!N.z.strictObject({id:N.z.uuid(),attributeKey:N.z.string().min(1).max(128).optional()}).safeParse(a).success&&t.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!i.startsWith("$")&&i.split(".").some(o=>["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved attribute path"}),i.startsWith("$")&&!Iy.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)}),vy=N.z.discriminatedUnion("type",[N.z.strictObject({type:N.z.literal("condition"),condition:Jt}),N.z.strictObject({type:N.z.literal("list"),attributeKey:N.z.string().min(1).max(128),values:N.z.array(N.z.union([N.z.string(),N.z.number().finite()])).max(1e5)})]).refine(e=>e.type!=="list"||new TextEncoder().encode(JSON.stringify(e.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function Un(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 wy=N.z.record(N.z.uuid(),vy).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"&&Un(o.condition).forEach(i),n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),Xs=N.z.tuple([N.z.number().min(0).max(1),N.z.number().min(0).max(1)]).refine(([e,t])=>e<=t),Cd=N.z.strictObject({attribute:N.z.string().optional(),seed:N.z.string().min(1),hashVersion:N.z.literal(2),ranges:N.z.array(Xs).min(1).max(100)}),Oy=N.z.strictObject({id:N.z.string().min(1).max(128),condition:Jt,gate:N.z.boolean().optional()}),Ys={id:N.z.string().max(128).optional(),condition:Jt.optional(),parentConditions:N.z.array(Oy).max(50).optional(),filters:N.z.array(Cd).max(20).optional()},Py=N.z.union([N.z.strictObject({...Ys}),N.z.strictObject({...Ys,force:Se,coverage:N.z.number().min(0).max(1).optional(),range:Xs.optional(),seed:N.z.string().min(1).optional(),hashAttribute:N.z.string().optional(),hashVersion:N.z.literal(2).optional()}),N.z.strictObject({...Ys,type:N.z.literal("experiment-ref"),experimentId:N.z.uuid(),values:N.z.record(N.z.string().min(1),Se),meta:N.z.record(N.z.string().min(1),N.z.strictObject({passthrough:N.z.boolean()})).optional()})]),Cy=N.z.strictObject({defaultValue:Se,rules:N.z.array(Py).max(100)}),Cw=N.z.record(N.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Cy).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)}),_y=N.z.strictObject({name:N.z.string().max(80),reason:N.z.string().max(500),dateStarted:N.z.iso.datetime({offset:!0}),dateEnded:N.z.iso.datetime({offset:!0}).nullable(),coverage:N.z.number().min(0).max(1),variationWeights:N.z.array(N.z.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:Jt,savedGroups:N.z.array(N.z.strictObject({match:N.z.enum(["any","all","none"]),ids:N.z.array(N.z.uuid()).min(1)})).max(50),namespace:N.z.strictObject({id:N.z.uuid(),ranges:N.z.array(Xs).min(1)}).nullable(),seed:N.z.string().min(1).max(128)}),Ey=N.z.strictObject({key:N.z.string().min(1).max(128),name:N.z.string().min(1).max(80),hypothesis:N.z.string().max(2e3),status:N.z.enum(["draft","running","stopped"]),hashAttribute:N.z.string().min(1).max(128),fallbackAttribute:N.z.string().max(128).nullable(),hashVersion:N.z.literal(2),disableStickyBucketing:N.z.boolean(),bucketVersion:N.z.number().int().min(0).max(1e3),minBucketVersion:N.z.number().int().min(0).max(1e3),variations:N.z.array(N.z.strictObject({id:N.z.string().min(1),key:N.z.string().min(1),name:N.z.string().max(80),description:N.z.string().max(500)})).min(2).max(20),phases:N.z.array(_y).min(1).max(100),releasedVariationId:N.z.string().nullable(),excludeFromPayload:N.z.boolean(),statusSchedule:N.z.strictObject({startAt:N.z.iso.datetime({offset:!0}).nullable(),stopAt:N.z.iso.datetime({offset:!0}).nullable(),stopAfter:N.z.strictObject({value:N.z.number().int().positive().max(36500),unit:N.z.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((e,t)=>{(e.minBucketVersion>e.bucketVersion||e.statusSchedule?.stopAt&&e.statusSchedule?.stopAfter||e.phases.some((n,r)=>{if(r===0)return!1;let i=e.phases[r-1];return!i?.dateEnded||Date.parse(n.dateStarted)<Date.parse(i.dateStarted)||Date.parse(i.dateEnded)>Date.parse(n.dateStarted)})||new Set(e.variations.map(n=>n.key)).size!==e.variations.length||new Set(e.variations.map(n=>n.id)).size!==e.variations.length||e.releasedVariationId!==null&&!e.variations.some(n=>n.id===e.releasedVariationId)||e.statusSchedule?.startAt&&e.statusSchedule?.stopAt&&Date.parse(e.statusSchedule.startAt)>=Date.parse(e.statusSchedule.stopAt)||e.phases.some(n=>n.dateEnded&&Date.parse(n.dateStarted)>=Date.parse(n.dateEnded)||n.namespace?.ranges.some(([r,i],a,o)=>r>=i||o.some(([s,c],u)=>u!==a&&r<c&&s<i)))||e.phases.some(n=>n.variationWeights.length!==e.variations.length))&&t.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});var Ry=Ey.safeExtend({filters:N.z.array(Cd).optional()}),ky=N.z.strictObject({experiments:N.z.record(N.z.uuid(),Ry),savedGroups:wy}),Vi=N.z.strictObject({attributeName:N.z.string(),attributeValue:N.z.string(),assignments:N.z.record(N.z.string(),N.z.string())}),_w=N.z.strictObject({snapshot:ky,attributes:Ot,results:Ot,stickyBucketAssignmentDocs:N.z.record(N.z.string(),Vi)}),Ew=N.z.strictObject({variantKey:N.z.string().nullable(),bucketVersion:N.z.number().int().min(0),source:N.z.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:N.z.number().min(0).max(1).optional(),stickyBucketUsed:N.z.boolean().optional(),hashUsed:N.z.boolean().optional()});function Yn(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 jy=_t.z.enum(["active","inactive"]),Ty=_t.z.preprocess((e,t)=>{let n=0;function r(i,a){if(!(++n>1e4||a>20)){if(Array.isArray(i))i.forEach(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))["__proto__","constructor","prototype"].includes(o)&&t.addIssue({code:"custom",message:"Reserved merchandise attribute"}),r(s,a+1)}}return r(e,0),e},Ot),Ny=_t.z.strictObject({id:_t.z.string().trim().min(1).max(255),name:_t.z.string().trim().min(1).max(255),status:jy,metadata:Ty}),Nw=Ny.extend({internal_id:_t.z.uuid(),project_id:_t.z.uuid(),environment_id:_t.z.uuid(),created_at:_t.z.iso.datetime({offset:!0}),updated_at:_t.z.iso.datetime({offset:!0})}),Ed=_t.z.union([_t.z.strictObject({id:_t.z.string().trim().min(1).max(255)}),_t.z.strictObject({internalId:_t.z.uuid()})]),Dw=_t.z.enum(["customer","merchandise","context"]),Fw=_t.z.enum(["system","stored","request"]),Mw=_t.z.enum(["customer","merchandise","mixed"]),_d=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function ec(e,t={},n=new Set){if(Yn(e).some(_d))return!0;for(let r of Un(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&_d(i.attributeKey)||i?.type==="condition"&&ec(i.condition,t,n))return!0}return!1}var Rd=require("zod"),Dy=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,xn=Rd.z.string().max(16).regex(Dy,"\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 zw=Y.z.enum(["draft","active","paused","archived"]),Xn=Y.z.discriminatedUnion("type",[Y.z.object({type:Y.z.literal("percent"),percentOff:Y.z.number().min(1).max(100).multipleOf(.01)}).strict(),Y.z.object({type:Y.z.literal("amount"),amountOffCents:Y.z.number().int().min(1).max(1e8),currency:be}).strict()]),on=Y.z.discriminatedUnion("type",[Y.z.object({type:Y.z.literal("once")}).strict(),Y.z.object({type:Y.z.literal("repeating"),months:Y.z.number().int().min(1).max(36)}).strict(),Y.z.object({type:Y.z.literal("forever")}).strict()]),kd=[Y.z.object({type:Y.z.literal("all")}).strict(),Y.z.object({type:Y.z.literal("plans"),planIds:Y.z.array(Y.z.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],Fy=Y.z.discriminatedUnion("type",[...kd,Y.z.strictObject({type:Y.z.literal("merchandise"),scope:Y.z.discriminatedUnion("type",[Y.z.strictObject({type:Y.z.literal("all")}),Y.z.strictObject({type:Y.z.literal("selected"),merchandiseIds:Y.z.array(Y.z.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),Y.z.strictObject({type:Y.z.literal("condition"),condition:Jt})])})]),tc=Y.z.discriminatedUnion("type",[...kd,Y.z.strictObject({type:Y.z.literal("merchandise"),scope:Y.z.strictObject({type:Y.z.enum(["all","selected","condition"])})})]),My=Y.z.strictObject({firstPurchaseOnly:Y.z.boolean(),condition:Jt}),$w=Y.z.object({name:Y.z.string().trim().min(1).max(80),description:Y.z.string().max(500),discount:Xn,duration:on,appliesTo:Fy,eligibility:My,selfClaimEnabled:Y.z.boolean().default(!1),startsAt:Y.z.iso.datetime().nullable(),endsAt:Y.z.iso.datetime().nullable(),totalLimit:Y.z.number().int().min(1).max(1e6).nullable(),perCustomerLimit:Y.z.number().int().min(1).max(10),grantWindowHours:Y.z.number().int().min(1).max(2160)}).strict().refine(e=>!e.startsAt||!e.endsAt||Date.parse(e.endsAt)>Date.parse(e.startsAt),{message:"\u7ED3\u675F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u5F00\u59CB\u65F6\u95F4",path:["endsAt"]}).refine(e=>!ec(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"]}),Gw=Y.z.object({code:Y.z.string().trim().transform(e=>e.toUpperCase()).pipe(Y.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/,"\u4F18\u60E0\u7801\u53EA\u80FD\u7528 3\u201332 \u4F4D\u5B57\u6BCD\u3001\u6570\u5B57\u3001- \u548C _\uFF0C\u4EE5\u5B57\u6BCD\u6216\u6570\u5B57\u5F00\u5934")),maxRedemptions:Y.z.number().int().min(1).max(1e6).nullable(),expiresAt:Y.z.iso.datetime().nullable(),firstPurchaseOnly:Y.z.boolean(),minimumAmountCents:Y.z.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:be.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var Li=Y.z.object({id:Y.z.uuid(),couponId:Y.z.uuid(),status:Y.z.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:Y.z.iso.datetime(),expiresAt:Y.z.iso.datetime(),coupon:Y.z.object({name:Y.z.string(),discount:Xn,duration:on,appliesTo:tc}).strict()}).strict(),jd=Y.z.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var Md=x.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),nc=x.z.string().regex(/^(0|[1-9]\d{0,14})$/),ri=x.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),qy=x.z.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),Ui=qy,zn=Ae.refine(e=>/[1-9]/.test(e)),zt=x.z.iso.datetime({offset:!0}),aa=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"))},By=x.z.array(x.z.object({upTo:zn.nullable(),unitAmountMinor:Md,flatAmountMinor:x.z.number().int().min(0).max(1e8).optional()}).strict()).min(1).max(12).refine(e=>{try{return e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let r=e[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&aa(t.upTo)>aa(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),Vy=x.z.discriminatedUnion("kind",[x.z.object({kind:x.z.literal("flat"),units:zn,unitAmountMinor:Md}).strict(),x.z.object({kind:x.z.enum(["graduated","volume"]),units:zn,tiers:By}).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"),Ly=x.z.strictObject({interval:x.z.enum(["month","year"]),count:x.z.number().int().min(1).max(12),anchor:x.z.enum(["membership","calendar"])}),zi=x.z.object({currency:be,pricing:Vy,billingCycle:Ly.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var Td={requestId:x.z.uuid(),productVersionId:x.z.uuid(),internal_feature_id:x.z.uuid(),currency:be},qd=x.z.strictObject({interval:x.z.enum(["hour","day","week","month"]),intervalCount:x.z.number().int().min(1).max(12),limit:x.z.number().int().min(1).max(1e6)}),Bd=x.z.discriminatedUnion("kind",[x.z.object({...Td,kind:x.z.literal("auto_topup"),threshold:Ho,quantity:zn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:qd.optional()}).strict(),x.z.object({...Td,kind:x.z.literal("postpaid"),maxAmountMinorPerPeriod:Ui,maxOutstandingMinor:Ui}).strict()]),Nd={productVersionId:x.z.uuid(),internal_feature_id:x.z.uuid(),currency:be},Vd=x.z.discriminatedUnion("kind",[x.z.object({...Nd,kind:x.z.literal("auto_topup"),threshold:Ho,quantity:zn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:qd.optional(),purchaseAmountMinor:Ui,purchaseUnits:zn}).strict(),x.z.object({...Nd,kind:x.z.literal("postpaid"),maxAmountMinorPerPeriod:Ui,maxOutstandingMinor:Ui,cashPrice:zi}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),sa=x.z.object({id:x.z.uuid(),terms:Vd,status:x.z.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"),Ld=x.z.object({authorizationId:x.z.uuid(),terms:Vd,setupUrl:x.z.url().nullable()}).strict(),Ud=x.z.object({authorizationId:x.z.uuid(),accepted:x.z.literal(!0)}).strict(),zd=x.z.object({authorizationId:x.z.uuid(),requestId:x.z.uuid()}).strict(),$d=x.z.object({internal_feature_id:x.z.uuid(),entityId:x.z.uuid().nullable(),interval:x.z.enum(["day","week","month","year"]),anchor:x.z.enum(["billing_cycle","utc"]).optional(),basis:x.z.enum(["usage","credits"]),filter:wt.optional(),limit:Ae.nullable(),thresholds:x.z.array(x.z.number().positive().max(1)).max(8),includedThresholds:x.z.array(x.z.number().positive().max(1)).max(8).optional(),absoluteThresholds:x.z.array(zn).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&&aa(t)>aa(i)}),"Notification thresholds must increase"),Uy=$d.safeExtend({requestId:x.z.uuid()}),Dd={control:x.z.literal("overage"),requestId:x.z.uuid(),internal_feature_id:x.z.uuid(),entityId:x.z.uuid().nullable()},zy=x.z.discriminatedUnion("action",[x.z.strictObject({...Dd,action:x.z.literal("set"),allowed:x.z.boolean().nullable(),overageLimit:Ae.nullable(),skipOverageBilling:x.z.boolean()}),x.z.strictObject({...Dd,action:x.z.literal("remove")})]),Gd=x.z.union([Uy,zy]),$y=x.z.strictObject({internal_feature_id:x.z.uuid(),entityId:x.z.uuid().nullable(),allowed:x.z.boolean().nullable(),overageLimit:Ae.nullable(),skipOverageBilling:x.z.boolean(),interval:x.z.enum(["day","week","month","year"]),startsAt:zt,endsAt:zt,used:x.z.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:x.z.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:x.z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),Gy=x.z.object({internal_feature_id:x.z.uuid(),entityId:x.z.uuid().nullable(),interval:x.z.enum(["day","week","month","year"]),anchor:x.z.enum(["billing_cycle","utc"]).optional(),basis:x.z.enum(["usage","credits"]),filter:wt.optional(),startsAt:zt,endsAt:zt,used:Qt,reserved:Qt,limit:Ae.nullable(),thresholds:x.z.array(x.z.number().positive().max(1)).max(8),notifiedThresholds:x.z.array(x.z.number().positive().max(1)).max(1024),includedThresholds:x.z.array(x.z.number().positive().max(1)).max(8).optional(),includedAllowance:x.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:x.z.array(x.z.number().positive().max(1)).max(1024).optional(),absoluteThresholds:x.z.array(zn).max(8).optional(),notifiedAbsoluteThresholds:x.z.array(zn).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||Ae.safeParse(e.used).success&&Ae.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),Ky=x.z.object({authorizationId:x.z.uuid(),status:x.z.enum(["idle","pending","blocked"]),taskId:x.z.uuid().nullable(),invoiceId:x.z.uuid().nullable(),hostedInvoiceUrl:x.z.url().nullable(),purchaseCount:x.z.number().int().nonnegative(),purchaseWindowEndsAt:zt.nullable(),attemptCount:x.z.number().int().nonnegative(),failedAttemptCount:x.z.number().int().nonnegative(),suspendedAt:zt.nullable(),nextAttemptAt:zt.nullable(),failureReason:x.z.string().min(1).max(240).nullable()}).strict(),Kd=x.z.object({internal_feature_id:x.z.uuid().optional(),entityId:x.z.uuid().optional()}).strict(),rc=x.z.object({authorizations:x.z.array(sa).max(100),limits:x.z.array($d).max(100),overages:x.z.array($y).max(100).optional(),windows:x.z.array(Gy).max(200),autoTopups:x.z.array(Ky).max(100),limited:x.z.boolean()}).strict(),Hy=x.z.object({id:x.z.uuid(),internal_feature_id:x.z.uuid(),productVersionId:x.z.uuid(),authorizationId:x.z.uuid(),entityId:x.z.uuid().nullable(),units:Ae,amountMinor:ri,cashPrice:zi}).strict(),$i=x.z.object({id:x.z.uuid(),sourceKind:x.z.enum(["product","usage","manual"]),providerInvoiceId:x.z.string().min(1).max(240).nullable(),status:x.z.enum(["accruing","open","pending","paid","failed","void"]),currency:be,startsAt:zt.nullable(),endsAt:zt.nullable(),amountMinor:x.z.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:x.z.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:nc,paidAmountMinor:nc,refundedAmountMinor:nc,createdAt:zt,hostedInvoiceUrl:x.z.url().nullable(),adjustment:x.z.object({originalInvoiceId:x.z.uuid(),amountMinor:x.z.string().regex(/^-?(0|[1-9]\d{0,8})$/).refine(e=>e!=="-0"&&/^-?(0|[1-9]\d{0,8})$/.test(e)&&BigInt(e)>=-200000000n&&BigInt(e)<=200000000n,"Invoice adjustment exceeds the bounded minor amount"),acceptedAt:zt.nullable(),reason:x.z.string().min(1).max(500).optional()}).strict().nullable(),lines:x.z.array(Hy).max(100),linesLimited:x.z.boolean()}).strict(),Hd=x.z.object({invoiceId:x.z.uuid(),accepted:x.z.literal(!0)}).strict(),Qd=x.z.strictObject({requestId:x.z.uuid(),originalInvoiceId:x.z.uuid(),amountMinor:x.z.string().regex(/^[1-9]\d{0,8}$/).refine(e=>/^[1-9]\d{0,8}$/.test(e)&&BigInt(e)<=200000000n,"Supplemental amount exceeds the bounded minor amount"),reason:x.z.string().trim().min(1).max(500)}),Jd=x.z.object({after:x.z.uuid().nullable(),limit:x.z.number().int().min(1).max(100)}).strict(),Zd=x.z.object({rows:x.z.array($i).max(100),nextCursor:x.z.uuid().nullable()}).strict(),Fd=x.z.strictObject({id:x.z.string(),coupon:x.z.string(),start:x.z.number().nonnegative(),end:x.z.number().nullable()}),Qy=x.z.strictObject({subscriptionId:x.z.string(),customerId:x.z.string(),accountId:x.z.string(),sourceItems:x.z.array(x.z.strictObject({id:x.z.string(),price_id:x.z.string(),quantity:x.z.number().int(),discounts:x.z.array(Fd).optional()})).max(100),items:x.z.array(x.z.strictObject({id:x.z.string(),price:x.z.string(),quantity:x.z.number().int(),discounts:x.z.array(x.z.strictObject({coupon:x.z.string().optional(),terms:x.z.strictObject({id:x.z.string(),name:x.z.string().optional(),percent_off:x.z.number().optional(),amount_off:x.z.number().optional(),currency:x.z.string().optional(),duration:x.z.enum(["once","forever","repeating"]),duration_in_months:x.z.number().optional()}).optional(),discount:x.z.string().optional(),receipt:Fd.optional()})).max(20)})).max(100)}),Wd=x.z.strictObject({membershipId:x.z.uuid(),requestId:x.z.uuid(),grantIds:x.z.array(x.z.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),Yd=x.z.strictObject({membershipId:x.z.uuid(),operationId:x.z.uuid(),status:x.z.enum(["pending","effective"]),execution:Qy.nullable(),grants:x.z.array(x.z.strictObject({id:x.z.uuid(),couponId:x.z.uuid(),name:x.z.string(),discount:Xn,duration:on,startedAt:zt.nullable()})).max(20)});var ii=require("zod");var Xd=ii.z.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),ep=ii.z.number().int().min(1).max(1e3),ca=ii.z.object({cap:Ae.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:ii.z.number().positive().max(1e4).nullable(),cycles:ii.z.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");var $n=require("zod");var tp=$n.z.strictObject({itemKey:$n.z.string().regex(/^paid:feature:[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),internal_feature_id:$n.z.uuid(),includedAmount:$n.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:$n.z.number().int().min(0).max(1e4),terms:Jo,pricing:Mi.optional(),unitAmountMinor:$n.z.number().int().min(0).max(1e8),productId:$n.z.string().min(1).max(255).nullable(),priceId:$n.z.string().min(1).max(255).nullable()}).superRefine((e,t)=>{(e.quantity<e.terms.minimumQuantity||e.quantity>e.terms.maximumQuantity||e.productId===null!=(e.priceId===null)||e.quantity>0&&(e.pricing||e.unitAmountMinor>0)&&e.priceId===null)&&t.addIssue({code:"custom",message:"Purchased quantities need their published bounds and immutable price binding"});try{Kl(e.includedAmount,e.terms.units,e.quantity),Qo({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{t.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});var X=require("zod");var _r=Ae.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Gi=X.z.string().min(1).max(120),ua=X.z.enum(["cap","overflow"]),an=(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"))},Ki=e=>{try{return e()}catch{return!1}},Hi=X.z.discriminatedUnion("operation",[X.z.object({operation:X.z.literal("quote"),overageBehavior:ua.optional(),internal_feature_id:X.z.uuid(),entityId:X.z.uuid().optional(),quantity:_r,properties:wt}).strict(),X.z.object({operation:X.z.literal("consume"),overageBehavior:ua.optional(),occurredAt:X.z.iso.datetime({offset:!0}).optional(),internal_feature_id:X.z.uuid(),entityId:X.z.uuid().optional(),quantity:Ae,properties:wt,idempotencyKey:Gi}).strict(),X.z.object({operation:X.z.literal("reserve"),occurredAt:X.z.iso.datetime({offset:!0}).optional(),internal_feature_id:X.z.uuid(),entityId:X.z.uuid().optional(),quantity:_r,properties:wt,idempotencyKey:Gi,expiresInSeconds:X.z.number().int().min(1).max(86400)}).strict(),X.z.object({operation:X.z.literal("confirm"),operationId:X.z.uuid(),quantity:_r,properties:wt.optional(),idempotencyKey:Gi}).strict(),X.z.object({operation:X.z.literal("refund"),operationId:X.z.uuid(),quantity:_r,idempotencyKey:Gi}).strict(),X.z.object({operation:X.z.literal("release"),operationId:X.z.uuid(),idempotencyKey:Gi}).strict()]),ic=X.z.object({internal_credit_feature_id:X.z.uuid().nullable(),internal_metered_feature_id:X.z.uuid(),dimension:X.z.string().min(1).max(64),counterKey:X.z.string().min(1).max(240),cycleStart:X.z.iso.datetime({offset:!0}),unitCost:Ae,units:_r,amount:Qt,tier:X.z.number().int().min(1).max(12).nullable()}).strict(),Er=X.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function np(e,t){let n=e.reduce((r,i)=>r+an(i.units,12),0n)-an(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var rp=X.z.discriminatedUnion("funding",[X.z.strictObject({funding:X.z.literal("balance"),sourceId:X.z.uuid(),rolloverId:X.z.uuid().nullable(),units:Er.refine(e=>/[1-9]/.test(e)),amount:Qt}),X.z.strictObject({funding:X.z.literal("unbilled"),units:Er.refine(e=>/[1-9]/.test(e))}),X.z.object({funding:X.z.literal("prepaid"),sourceId:X.z.uuid(),units:_r,amount:Qt,pricing:X.z.array(ic).min(1).max(12)}).strict().refine(e=>Ki(()=>e.pricing.reduce((t,n)=>t+an(n.units,6),0n)===an(e.units,6)&&e.pricing.reduce((t,n)=>t+an(n.amount,12),0n)===an(e.amount,12)&&e.pricing.every(t=>an(t.unitCost,6)*an(t.units,6)===an(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),X.z.object({funding:X.z.literal("postpaid"),invoiceLineId:X.z.uuid().nullable(),units:_r,authorizationId:X.z.uuid()}).strict()]),la=X.z.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),ip=X.z.object({allowed:X.z.boolean(),internal_feature_id:X.z.uuid(),quantity:Ae,requestedQuantity:Ae.optional(),overageBehavior:ua.optional(),reason:la.nullable(),allocations:X.z.array(rp).max(500)}).strict().refine(e=>Ki(()=>e.allowed?e.reason===null&&np(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>Ki(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&an(e.requestedQuantity,6)>=an(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Qi=X.z.object({id:X.z.uuid(),internal_feature_id:X.z.uuid(),kind:X.z.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:X.z.uuid().nullable(),quantity:Ae,requestedQuantity:Ae.optional(),overageBehavior:ua.optional(),accepted:X.z.boolean(),reason:X.z.enum([...la.options,"expired"]).nullable(),createdAt:X.z.iso.datetime({offset:!0}),reservationStatus:X.z.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:X.z.iso.datetime({offset:!0}).nullable(),allocations:X.z.array(rp).max(500)}).strict().refine(e=>Ki(()=>e.accepted?e.reason===null&&np(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>Ki(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&an(e.requestedQuantity,6)>=an(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");var ke=require("zod");var Rr=ke.z.iso.datetime({offset:!0}),op=Ae.refine(e=>/[1-9]/.test(e)),ap=ke.z.strictObject({interval:Xd.exclude(["lifetime"]),count:ep}),Jy=ke.z.strictObject({action:ke.z.literal("create"),requestId:ke.z.uuid(),internal_feature_id:ke.z.uuid(),entityId:ke.z.uuid().nullable(),amount:op.nullable(),expiresAt:Rr.nullable(),reset:ap.nullable(),rollover:ca.nullable(),nextResetAt:Rr.nullable()}).refine(e=>e.amount!==null||e.reset===null&&e.rollover===null,"Unlimited grants cannot reset or roll over").refine(e=>!e.rollover||e.reset!==null,"Rollover requires a recurring grant").refine(e=>e.nextResetAt===null||e.reset!==null&&(e.expiresAt===null||Date.parse(e.nextResetAt)<Date.parse(e.expiresAt)),"The first reset needs a reset interval and must precede expiry"),sp=ke.z.discriminatedUnion("action",[Jy,ke.z.strictObject({action:ke.z.literal("update"),requestId:ke.z.uuid(),grantId:ke.z.uuid(),revision:ke.z.number().int().nonnegative(),amount:op.nullable(),expiresAt:Rr.nullable(),rollover:ca.nullable(),nextResetAt:Rr.nullable()}),ke.z.strictObject({action:ke.z.enum(["add","subtract","set_remaining"]),requestId:ke.z.uuid(),grantId:ke.z.uuid(),revision:ke.z.number().int().nonnegative(),amount:Ae}),ke.z.strictObject({action:ke.z.literal("revoke"),requestId:ke.z.uuid(),grantId:ke.z.uuid(),revision:ke.z.number().int().nonnegative()})]),oc=ke.z.strictObject({id:ke.z.uuid(),internal_feature_id:ke.z.uuid(),entityId:ke.z.uuid().nullable(),amount:Ae.nullable(),reset:ap.nullable(),rollover:ca.nullable(),nextResetAt:Rr.nullable(),startsAt:Rr,expiresAt:Rr.nullable(),revision:ke.z.number().int().nonnegative(),revoked:ke.z.boolean(),available:Qt,held:Qt,spent:Qt}),cp=ke.z.strictObject({customerId:ke.z.uuid(),after:ke.z.uuid().nullable(),limit:ke.z.number().int().min(1).max(100)}),up=ke.z.strictObject({rows:ke.z.array(oc).max(100),nextCursor:ke.z.uuid().nullable()});var ne=require("zod");var En=ne.z.iso.datetime({offset:!0}),lp=ne.z.strictObject({invoiceId:ne.z.uuid(),after:ne.z.string().min(1).max(180).nullable(),limit:ne.z.number().int().min(1).max(100)}),Zy=ne.z.strictObject({kind:ne.z.literal("product"),key:ne.z.string(),productVersionId:ne.z.uuid(),productName:ne.z.string(),itemKey:ne.z.string(),entityId:ne.z.uuid().nullable(),quantity:ne.z.number().positive(),subtotalMinor:ne.z.string().regex(/^-?\d+$/),discountMinor:ne.z.string().regex(/^\d+$/),taxMinor:ne.z.string().regex(/^-?\d+$/).nullable(),totalMinor:ne.z.string().regex(/^-?\d+$/),startsAt:En.nullable(),endsAt:En.nullable(),providerLineId:ne.z.string().nullable(),providerItemId:ne.z.string()}),dp=ne.z.strictObject({invoice:$i,items:ne.z.array(ne.z.discriminatedUnion("kind",[Zy,ne.z.strictObject({kind:ne.z.literal("invoice_credit"),key:ne.z.string(),internal_feature_id:ne.z.uuid(),internal_credit_feature_id:ne.z.uuid(),name:ne.z.string(),units:Ae,reserved:Ae,amountMinor:ri,grossAmountMinor:ri,creditsAppliedMinor:ri,properties:wt,cashPrice:zi,providerItemId:ne.z.string().nullable(),creditProviderItemId:ne.z.string().nullable()}),ne.z.strictObject({kind:ne.z.literal("usage"),key:ne.z.string(),internal_feature_id:ne.z.uuid(),name:ne.z.string(),units:Ae,reserved:Ae,amountMinor:ri,cashPrice:zi})])).max(100),nextCursor:ne.z.string().min(1).max(180).nullable()}),Wy=ne.z.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),ac=ne.z.strictObject({from:En,to:En,entityId:ne.z.uuid().optional(),snapshotAt:En.nullable(),after:ne.z.strictObject({at:En,id:ne.z.uuid(),position:ne.z.number().int().nonnegative()}).nullable(),limit:ne.z.number().int().min(1).max(100)}).refine(e=>Date.parse(e.from)<Date.parse(e.to)&&Date.parse(e.to)-Date.parse(e.from)<=366*864e5,"Statement range must be positive and at most 366 days").refine(e=>e.after===null||e.snapshotAt!==null,"A cursor requires the original snapshot time"),pp=ne.z.strictObject({customerId:ne.z.uuid(),entityId:ne.z.uuid().nullable(),from:En,to:En,snapshotAt:En,totals:ne.z.array(ne.z.strictObject({internal_credit_feature_id:ne.z.uuid(),name:ne.z.string(),consumed:Qt,refunded:Qt,net:Wy})).max(1e3),rows:ne.z.array(ne.z.strictObject({operationId:ne.z.uuid(),position:ne.z.number().int().nonnegative(),kind:ne.z.enum(["consume","confirm","refund"]),originalId:ne.z.uuid().nullable(),occurredAt:En,internal_feature_id:ne.z.uuid(),entitlementName:ne.z.string(),sourceId:ne.z.uuid(),internal_credit_feature_id:ne.z.uuid(),creditName:ne.z.string(),units:Er,amount:Qt,pricing:ne.z.array(ic).max(12),properties:wt})).max(100),nextCursor:ac.shape.after});var D=require("zod");var mn=require("zod");var Yy=mn.z.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),Xy=mn.z.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),da=mn.z.strictObject({internal_feature_id:mn.z.uuid(),entityId:mn.z.uuid().nullable()}),mp=da.extend({quantity:Ae,expectedRevision:mn.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:mn.z.string().min(1).max(120),properties:wt.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),Ji=da.extend({operationId:mn.z.uuid().nullable(),usage:Ae,capacity:Yy.nullable(),remaining:Xy.nullable(),withinLimit:mn.z.boolean(),revision:mn.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:mn.z.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let n=r=>{let i=r.startsWith("-"),[a,o=""]=(i?r.slice(1):r).split(".");if(a===void 0||a==="")throw new Error("Invalid decimal value");return(i?-1n:1n)*(BigInt(a)*10n**12n+BigInt(o.padEnd(12,"0")))};(e.capacity===null!=(e.remaining===null)||(e.capacity===null?!e.withinLimit:e.remaining===null||n(e.remaining)!==n(e.capacity)-n(e.usage)||e.withinLimit!==n(e.remaining)>=0n)||e.revision===0!=(e.operationId===null)||e.operationId===null!=(e.updatedAt===null))&&t.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var $t=D.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),Sn=D.z.iso.datetime({offset:!0}),eb=D.z.enum(["access","metered","credit"]),Zi={internal_feature_id:D.z.uuid(),key:wr,name:D.z.string().min(1).max(120),kind:eb},fp=D.z.object({customerId:D.z.uuid(),snapshotAt:Sn,memberships:D.z.array(D.z.object({id:D.z.uuid(),productId:D.z.string().min(1).max(255),productVersionId:D.z.uuid(),billingProductVersionId:D.z.uuid(),version:D.z.number().int().positive(),key:D.z.string().min(1).max(64),name:D.z.string().min(1).max(120),groupId:D.z.string().max(255).nullable(),membershipType:D.z.enum(["main","addon"]),status:D.z.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:D.z.boolean(),accessEnabled:D.z.boolean(),renewalChange:D.z.object({productVersionId:D.z.uuid(),name:D.z.string().min(1).max(120),version:D.z.number().int().positive(),effectiveAt:Sn,benefitsAppliedAt:Sn.nullable(),timing:D.z.enum(["immediate","renewal"]),changeKind:D.z.enum(["plan","seats","quantity"]),feature:D.z.strictObject({internal_feature_id:D.z.uuid(),name:D.z.string().min(1).max(80),fromQuantity:D.z.number().int().min(0).max(1e4),toQuantity:D.z.number().int().min(0).max(1e4)}).optional(),seat:D.z.object({key:D.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:D.z.number().int().min(0).max(1e4),toQuantity:D.z.number().int().min(0).max(1e4)}).strict().nullable(),status:D.z.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(e=>e.changeKind==="seats"==(e.seat!==null)&&e.changeKind==="quantity"==(e.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:D.z.object({phase:D.z.enum(["paid","trial"]),startsAt:Sn,endsAt:Sn.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:D.z.boolean(),balances:D.z.array(D.z.object({...Zi,usageType:D.z.enum(["consumable","non_consumable"]).nullable(),accessible:D.z.boolean(),unlimited:D.z.boolean(),available:$t,held:$t,debt:$t,nextExpiresAt:Sn.nullable(),usage:Ji.nullable()}).strict().refine(e=>e.kind==="metered"==(e.usageType!==null)&&(e.accessible||e.available==="0"&&e.held==="0")&&(e.usageType==="non_consumable"?e.usage!==null&&e.usage.internal_feature_id===e.internal_feature_id&&e.unlimited===(e.usage.capacity===null)&&e.available===(e.usage.remaining===null||e.usage.remaining.startsWith("-")?"0":e.usage.remaining)&&e.held==="0"&&e.debt==="0":e.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:D.z.boolean()}).strict(),gp=D.z.enum(["source","usage","transaction","invoice","debt","settlement"]),pa=D.z.object({at:Sn,id:D.z.uuid(),type:gp}).strict(),hp=D.z.object({type:gp.nullable(),resourceKey:wr.optional(),kind:D.z.enum(["purchase","refund"]).optional(),topup:D.z.boolean().optional(),from:D.z.iso.date().nullable(),to:D.z.iso.date().nullable(),after:pa.nullable(),limit:D.z.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),oi={id:D.z.uuid(),occurredAt:Sn},tb=D.z.discriminatedUnion("type",[D.z.strictObject({...oi,type:D.z.literal("invoice"),status:D.z.string().min(1).max(80),paid:$t,refunded:$t,currency:be,externalId:D.z.string().nullable()}),D.z.object({...oi,...Zi,type:D.z.literal("source"),reason:D.z.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:$t,unlimited:D.z.boolean(),status:D.z.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:Sn,expiresAt:Sn.nullable(),orderId:D.z.uuid().nullable(),parentSourceId:D.z.uuid().nullable()}).strict(),D.z.object({...oi,type:D.z.literal("usage"),internal_feature_id:D.z.uuid(),name:D.z.string().min(1).max(120),kind:D.z.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:D.z.uuid().nullable(),quantity:Ae,accepted:D.z.boolean(),reason:D.z.enum([...la.options,"expired"]).nullable(),properties:wt,reservationStatus:D.z.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:Sn.nullable(),charges:D.z.array(D.z.discriminatedUnion("funding",[D.z.strictObject({funding:D.z.literal("balance"),sourceId:D.z.uuid(),rolloverId:D.z.uuid().nullable(),units:Er,amount:$t}),D.z.strictObject({funding:D.z.literal("unbilled"),units:Er}),D.z.object({...Zi,funding:D.z.literal("prepaid"),amount:$t}).strict(),D.z.object({funding:D.z.literal("postpaid"),invoiceId:D.z.uuid(),invoiceLineId:D.z.uuid(),authorizationId:D.z.uuid(),units:Ae,currency:be}).strict()])).max(500)}).strict().refine(e=>(e.kind==="set_usage"||e.kind==="consume"&&e.quantity==="0"?e.accepted&&e.reason===null&&e.charges.length===0&&e.reservationStatus===null:e.accepted?e.reason===null&&e.charges.length>0:e.reason!==null&&e.charges.length===0)&&e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),D.z.object({...oi,type:D.z.literal("transaction"),purpose:D.z.enum(["product","invoice"]),productVersionId:D.z.uuid().nullable(),productName:D.z.string().min(1).max(120).nullable(),productVersion:D.z.number().int().positive().nullable(),invoiceId:D.z.uuid().nullable(),orderId:D.z.uuid(),originalId:D.z.uuid().nullable(),kind:D.z.enum(["purchase","refund"]),amountMinor:D.z.number().int().nonnegative().max(2e8).nullable(),currency:be.nullable()}).strict().refine(e=>e.currency===null==(e.amountMinor===null)&&(e.purpose==="product"?e.productVersionId!==null&&e.productName!==null&&e.productVersion!==null&&e.invoiceId===null:e.productVersionId===null&&e.productName===null&&e.productVersion===null&&e.invoiceId!==null)&&e.kind==="refund"==(e.originalId!==null)&&(e.kind!=="refund"||e.amountMinor===null||e.amountMinor>0),"Payment fact provenance is incomplete"),D.z.object({...oi,...Zi,type:D.z.literal("debt"),sourceId:D.z.uuid(),transactionId:D.z.uuid(),amount:$t}).strict(),D.z.object({...oi,...Zi,type:D.z.literal("settlement"),sourceId:D.z.uuid(),debtId:D.z.uuid(),kind:D.z.enum(["payment","usage_refund","payment_return"]),amount:$t}).strict()]),Ap=D.z.object({customerId:D.z.uuid(),rows:D.z.array(tb).max(50),nextCursor:pa.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");var pe=require("zod"),bp=pe.z.object({customerId:pe.z.uuid()}).strict(),xp=pe.z.discriminatedUnion("action",[pe.z.object({customerId:pe.z.uuid(),requestId:pe.z.uuid(),action:pe.z.literal("assign"),poolId:pe.z.uuid(),memberCustomerId:pe.z.uuid()}).strict(),pe.z.strictObject({customerId:pe.z.uuid(),requestId:pe.z.uuid(),action:pe.z.literal("assign_entity"),poolId:pe.z.uuid(),entityId:pe.z.uuid()}),pe.z.object({customerId:pe.z.uuid(),requestId:pe.z.uuid(),action:pe.z.literal("release"),poolId:pe.z.uuid(),slotId:pe.z.uuid()}).strict()]),Wi=pe.z.number().int().nonnegative(),sc=pe.z.iso.datetime({offset:!0}),cc=pe.z.strictObject({internalId:pe.z.uuid(),id:pe.z.string(),name:pe.z.string().nullable(),version:pe.z.number().int().positive()}),yp=pe.z.enum(["active","past_due"]),uc=pe.z.strictObject({customerId:pe.z.uuid(),licenses:pe.z.array(pe.z.strictObject({id:pe.z.uuid(),linkId:pe.z.uuid(),parent:pe.z.strictObject({customerProductId:pe.z.uuid(),status:yp,product:cc}),product:cc,planLicense:pe.z.strictObject({id:pe.z.uuid(),prepaidOnly:pe.z.boolean(),isCustom:pe.z.boolean()}).nullable(),granted:Wi,included:Wi,paidQuantity:Wi,usage:Wi,remaining:Wi,createdAt:sc}).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:pe.z.array(pe.z.strictObject({id:pe.z.uuid(),linkId:pe.z.uuid(),status:yp,product:cc,entity:pe.z.strictObject({internalId:pe.z.uuid(),id:pe.z.string().nullable(),name:pe.z.string().nullable()}).nullable(),beneficiary:pe.z.strictObject({internalId:pe.z.uuid(),id:pe.z.string().nullable(),name:pe.z.string().nullable()}).nullable(),startedAt:sc.nullable(),endedAt:sc.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:pe.z.boolean()});var ue=require("zod"),Yi=ue.z.enum(["email","sms","voice","push"]),xO=ue.z.enum(["resend","twilio","fcm","apns"]);var SO=ue.z.string().regex(/^\+[1-9]\d{1,14}$/),nb=ue.z.enum(["email_recipient","sms_segment","voice_second","push_device"]);var rb=ue.z.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),ib=ue.z.strictObject({subject:rb,html:ue.z.string().min(1).max(131072).optional(),text:ue.z.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),ob=ue.z.strictObject({body:ue.z.string().min(1).max(1600).refine(e=>e.trim().length>0)}),ab=ue.z.strictObject({text:ue.z.string().trim().min(1).max(4e3),language:ue.z.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:ue.z.number().int().min(1).max(900)}),sb=ue.z.record(ue.z.string().min(1).max(64),ue.z.string().max(256)).refine(e=>Object.keys(e).length<=20&&Object.keys(e).every(t=>!/^(?:indiana_|google\.|gcm\.)/i.test(t)&&t!=="aps"),"Push data contains reserved fields or too many entries"),cb=ue.z.strictObject({title:ue.z.string().trim().min(1).max(200),body:ue.z.string().trim().min(1).max(2e3),url:ue.z.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:sb.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),Sp=ue.z.discriminatedUnion("channel",[ue.z.strictObject({channel:ue.z.literal("email"),content:ib}),ue.z.strictObject({channel:ue.z.literal("sms"),content:ob}),ue.z.strictObject({channel:ue.z.literal("voice"),content:ab}),ue.z.strictObject({channel:ue.z.literal("push"),content:cb})]),Ip=ue.z.strictObject({requestId:ue.z.uuid(),customerId:ue.z.uuid(),connectionId:ue.z.uuid().optional(),message:Sp,expiresAt:ue.z.iso.datetime({offset:!0})}),ub=ue.z.array(ue.z.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),lb=ue.z.discriminatedUnion("kind",[ue.z.strictObject({kind:ue.z.literal("all")}),ue.z.strictObject({kind:ue.z.literal("customers"),customerIds:ub})]),IO=ue.z.strictObject({name:ue.z.string().trim().min(1).max(120),connectionId:ue.z.uuid().optional(),message:Sp,audience:lb,frequencyLimit:ue.z.number().int().min(1).max(100)}),vp=ue.z.strictObject({requestId:ue.z.uuid(),channel:Yi,state:ue.z.enum(["allowed","denied"]),expectedRevision:ue.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),wp=ue.z.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Op=ue.z.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),vO=ue.z.strictObject({meter:nb,estimatedUnits:ue.z.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:ue.z.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});var ve=require("zod");var te=require("zod");var kr=require("zod");var Xi=kr.z.strictObject({internalFeatureId:kr.z.uuid(),name:kr.z.string().min(1).max(120),includedAmount:kr.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:kr.z.enum(["hour","day","week","month","year","lifetime"]),resetCount:kr.z.number().int().min(1).max(100),terms:Jo});var it=require("zod");var _p=require("zod");var jr=require("zod"),Pp=jr.z.enum(["stripe","apple","google","merchant"]),Cp=jr.z.enum(["membership","credit_pack","lifetime"]),CO=jr.z.enum(["active","grace","suspended","inactive","revoked"]),_O=jr.z.strictObject({currency:jr.z.string().regex(/^[A-Z]{3}$/),micros:jr.z.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var ai=_p.z.object({provider:Pp,currency:be}).strict();var er=it.z.strictObject({internal_feature_id:it.z.uuid(),quantity:Ae.refine(e=>/[1-9]/.test(e)),properties:wt,entityId:it.z.uuid().optional()}),Ep=it.z.strictObject({requirement:er,commerce:ai.optional(),paywallId:it.z.uuid().optional()}),db=it.z.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),lc=it.z.strictObject({productId:it.z.string().min(1),productVersionId:it.z.string().min(1),name:it.z.string().min(1).max(120),action:it.z.enum(["purchase","upgrade","addon","topup"]),membershipId:it.z.string().min(1).nullable(),currency:be,amountMinor:it.z.string().regex(/^(0|[1-9]\d{0,8})$/),interval:it.z.enum(["free","week","month","year","one_time"]),intervalCount:it.z.number().int().min(1).max(156)}),Tr=it.z.strictObject({internal_feature_id:it.z.string().min(1),name:it.z.string().min(1).max(120),kind:it.z.enum(["access","metered","credit"]),quantity:Ae,allowed:it.z.boolean(),reason:db.nullable(),preview:it.z.strictObject({scenario:it.z.enum(["feature_flag","usage_limit"]),candidates:it.z.array(lc).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"})}),FO=it.z.strictObject({paywallId:it.z.uuid(),requirement:er});var fa=te.z.object({plan:te.z.string().min(1).max(200).optional(),coupon:te.z.uuid().optional(),promotionCode:te.z.uuid().optional(),picker:te.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),ma=te.z.object({text:te.z.string().optional(),label:te.z.string().optional(),alt:te.z.string().optional(),html:te.z.string().max(32768).optional(),price:te.z.object({current:te.z.string(),original:te.z.string().nullable(),period:te.z.string()}).optional(),code:te.z.string().optional(),countdownAt:te.z.iso.datetime().optional(),planId:te.z.string().min(1).max(200).optional(),planVersionId:te.z.string().min(1).max(200).optional(),currency:be.optional(),couponId:te.z.uuid().optional(),offerId:te.z.uuid().optional(),unavailable:te.z.boolean().optional(),unavailableReason:te.z.string().optional(),missing:te.z.array(te.z.string()).optional()}).strict(),si=te.z.object({paywall:Tr.optional(),nodes:te.z.record(te.z.string(),te.z.object({base:ma,picker:te.z.string().optional(),byPlan:te.z.record(te.z.string(),ma).optional()}).strict()),plans:te.z.record(te.z.string(),te.z.object({id:te.z.string().min(1).max(200),versionId:te.z.string().min(1).max(200),available:te.z.boolean(),name:te.z.string(),price:te.z.string(),period:te.z.string(),currency:be.optional(),amountMinor:te.z.number().int().nonnegative().optional(),interval:te.z.enum(["free","week","month","year","one_time"]).optional(),intervalCount:te.z.number().int().positive().optional(),prepaid:te.z.array(Xi).max(100).optional()}).strict()),pickers:te.z.record(te.z.string(),te.z.object({options:te.z.array(te.z.string().min(1).max(200)).max(20),selected:te.z.string().min(1).max(200).nullable()}).strict()),quantities:te.z.record(te.z.string(),te.z.strictObject({minimum:te.z.number().int().nonnegative(),maximum:te.z.number().int().nonnegative(),step:te.z.number().int().positive(),value:te.z.number().int().nonnegative(),label:te.z.string(),available:te.z.boolean()})).optional(),diagnostics:te.z.array(te.z.object({nodeId:te.z.string(),message:te.z.string()}).strict())}).strict();function Rp(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}var S=require("zod");function pb(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function kp(e){let t={};function n(r){var i;if(pb(r)){let a=t[i=r.interaction.pickerId]??(t[i]={ids:[],defaultId:null});for(let s of r.children){let c=s.type==="stack"?s.bind?.plan:void 0;c&&!a.ids.includes(c)&&a.ids.push(c)}let o=r.children[r.interaction.defaultIndex];!a.defaultId&&o?.type==="stack"&&(a.defaultId=o.bind?.plan??null)}r.type==="stack"&&r.children.forEach(n)}return e.pages.forEach(r=>n(r.root)),t}var Rn=require("zod"),jp=Rn.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ga=Rn.z.strictObject({tiers:Rn.z.array(Rn.z.strictObject({id:jp,name:Rn.z.string().trim().min(1).max(80)})).min(1).max(8),assignments:Rn.z.array(Rn.z.strictObject({productVersionId:Rn.z.string().min(1).max(200),tierId:jp,period:Rn.z.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let n=e.tiers.map(r=>r.id);(new Set(n).size!==n.length||new Set(e.assignments.map(r=>r.productVersionId)).size!==e.assignments.length||new Set(e.assignments.map(r=>`${r.tierId}:${r.period}`)).size!==e.assignments.length||e.assignments.some(r=>!n.includes(r.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function ha(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}var se=require("zod");var mb=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],Tp=se.z.enum(mb),Np=se.z.object({source:Tp,layout:se.z.enum(["full","compact"]),resourceKey:wr.optional(),pageSize:se.z.number().int().min(1).max(50),showSources:se.z.boolean(),allowPurchase:se.z.boolean(),outputs:se.z.object({billing_adjustment:se.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:se.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:se.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:se.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:se.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:se.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((e,t)=>{(e.outputs?.billing_authorization||e.outputs?.billing_adjustment)&&e.source!=="billing_controls"&&t.addIssue({code:"custom",message:"Payment authorization routes belong to the billing controls component."}),e.resourceKey&&!["credit_balance","credit_transactions"].includes(e.source)&&t.addIssue({code:"custom",message:"\u8FD9\u4E2A\u6570\u636E\u6E90\u4E0D\u80FD\u7ED1\u5B9A\u79EF\u5206\u8D44\u6E90\u3002"}),e.showSources&&e.source!=="credit_balance"&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u4F59\u989D\u53EF\u4EE5\u5C55\u5F00\u6765\u6E90\u3002"}),e.allowPurchase&&!["credit_packs","customer_plans","membership"].includes(e.source)&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u5305\u3001\u5957\u9910\u4E0E\u4F1A\u5458\u7EC4\u4EF6\u53EF\u4EE5\u542F\u7528\u4EA4\u6613\u3002"})}),Et=se.z.string().max(2e3),Dp=se.z.object({id:se.z.string().max(100),label:Et,detail:se.z.array(Et).max(12),value:Et.optional(),status:Et.optional(),facts:se.z.array(se.z.object({label:Et,value:Et}).strict()).max(1e3),purchaseId:se.z.uuid().optional(),invoiceUrl:se.z.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:se.z.array(se.z.strictObject({action:se.z.literal("invoice_open"),label:Et})).max(1).optional(),membershipActions:se.z.array(se.z.object({value:se.z.string().max(100),label:Et}).strict()).max(3).optional()}).strict(),fb=se.z.object({key:wr,name:Et,spendable:Et,reserved:Et,available:Et,expiry:Et.nullable(),sources:se.z.array(Dp).max(50),sourceCount:se.z.number().int().nonnegative(),sourcePage:se.z.number().int().positive(),hasNextSources:se.z.boolean(),hasPreviousSources:se.z.boolean()}).strict(),gb=se.z.object({source:Tp,status:se.z.enum(["idle","loading","ready","error"]),stale:se.z.boolean(),preview:se.z.boolean(),errorCode:se.z.string().max(80).optional(),errorMessage:Et.optional(),resources:se.z.array(fb).max(500),rows:se.z.array(Dp).max(50),hasNext:se.z.boolean(),hasPrevious:se.z.boolean(),page:se.z.number().int().positive(),filter:se.z.string().max(40),updatedAt:se.z.iso.datetime().optional(),buyingId:se.z.uuid().optional(),membershipBusy:se.z.boolean().optional(),billingBusy:se.z.boolean().optional(),membershipReview:se.z.object({title:Et,note:Et,facts:se.z.array(se.z.object({label:Et,value:Et}).strict()).max(100)}).strict().optional(),membershipResult:Et.optional()}).strict(),Fp=se.z.object({nodes:se.z.record(se.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),gb)}).strict(),GO=se.z.object({nodeId:se.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:se.z.enum(["refresh","next","previous","filter","buy_pack","billing_portal","billing_authorization","billing_adjustment","invoice_open","membership_preview","membership_confirm","membership_dismiss","sources_next","sources_previous"]),value:se.z.string().max(100).optional()}).strict();var Ab=4,vn={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},to=S.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Me=S.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),yb=S.z.enum(["none","xs","sm","md","lg","xl"]),bb=S.z.enum(["none","sm","md","lg","full"]),dc=S.z.string().regex(/^#[0-9a-fA-F]{6}$/),Bp=S.z.string().max(2048).refine(e=>{try{let t=new URL(e);return t.protocol==="https:"&&t.hostname.length>0}catch{return!1}},"\u53EA\u652F\u6301 https \u94FE\u63A5"),pc=S.z.union([Bp,S.z.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),S.z.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),S.z.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Mp=S.z.object({primary:dc,background:dc,text:dc,radius:bb,font:S.z.enum(["system","serif","rounded","mono"])}).strict(),no=S.z.union([S.z.enum(["primary","text","muted","background","surface"]),S.z.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),De=(e,t)=>S.z.number().int().min(e).max(t),qp=S.z.union([S.z.enum(["fit","fill"]),De(1,1200)]),xb=S.z.object({top:De(0,200),right:De(0,200),bottom:De(0,200),left:De(0,200)}).strict(),Sb=S.z.object({top:De(-100,200),right:De(-100,200),bottom:De(-100,200),left:De(-100,200)}).strict(),Vp=S.z.object({x:De(0,100),y:De(0,100)}).strict(),Ib=S.z.discriminatedUnion("type",[S.z.object({type:S.z.literal("color"),color:no}).strict(),S.z.object({type:S.z.literal("linear"),angle:De(0,360),stops:S.z.array(S.z.object({color:no,at:De(0,100)}).strict()).min(2).max(4)}).strict(),S.z.object({type:S.z.literal("image"),src:pc,fit:S.z.enum(["cover","contain"]),position:Vp.optional()}).strict()]),vb=S.z.discriminatedUnion("type",[S.z.object({type:S.z.literal("rect"),radius:S.z.union([De(0,200),S.z.object({topLeft:De(0,200),topRight:De(0,200),bottomRight:De(0,200),bottomLeft:De(0,200)}).strict()])}).strict(),S.z.object({type:S.z.literal("pill")}).strict()]),wb=S.z.object({width:De(0,12),color:no,style:S.z.enum(["solid","dashed"])}).strict(),Ob=S.z.object({x:De(-40,40),y:De(-40,40),blur:De(0,80),spread:De(-20,40),color:no}).strict(),Pb=S.z.object({font:S.z.enum(["system","serif","rounded","mono"]),size:De(8,96),weight:S.z.number().int().min(100).max(900).multipleOf(100),lineHeight:S.z.number().min(.8).max(3),letterSpacing:S.z.number().min(-5).max(20),color:no,align:S.z.enum(["start","center","end"]),italic:S.z.boolean(),decoration:S.z.enum(["none","underline","line-through"]),transform:S.z.enum(["none","uppercase"])}).strict().partial(),Nr=S.z.object({width:qp,height:qp,padding:xb,margin:Sb,gap:De(0,120),grow:S.z.union([S.z.boolean(),S.z.number().min(0).max(12)]),background:Ib,opacity:S.z.number().min(0).max(1),clipContent:S.z.boolean(),shape:vb,border:wb,shadow:Ob,text:Pb}).strict().partial(),Yt={id:to,name:S.z.string().trim().min(1).max(60).optional(),hidden:S.z.boolean().optional(),style:Nr.optional(),fallback:Me.optional()},Cb=S.z.object({...Yt,type:S.z.literal("text"),productField:S.z.enum(["name","price","trial","period"]).optional(),feature:S.z.object({id:S.z.uuid(),field:S.z.enum(["name","allowance"])}).strict().optional(),text:Me,variant:S.z.enum(["title","heading","body","caption"])}).strict(),_b=S.z.object({...Yt,type:S.z.literal("image"),src:pc,localizedSrc:S.z.record(xn,pc).optional(),alt:Me,aspect:S.z.enum(["auto","1:1","4:3","16:9","3:1"]),fit:S.z.enum(["cover","contain"]),position:Vp.optional()}).strict(),Eb=S.z.object({...Yt,type:S.z.literal("button"),label:Me,variant:S.z.enum(["primary","secondary","link"]),action:Me,purpose:S.z.enum(["purchase","navigation","close"]).optional(),bind:fa.optional()}).strict(),Rb=S.z.object({...Yt,type:S.z.literal("divider")}).strict(),kb=S.z.object({...Yt,type:S.z.literal("customer_data"),title:Me,data:Np}).strict(),jb=S.z.object({...Yt,type:S.z.literal("spacer"),size:yb}).strict(),Tb=S.z.object({...Yt,type:S.z.literal("custom_html"),html:S.z.record(xn,S.z.string().max(vn.customHtml)),css:S.z.string().max(vn.customCss)}).strict(),Nb=S.z.object({...Yt,type:S.z.literal("price"),fallback:Me,parts:S.z.object({current:Nr.optional(),original:Nr.optional(),period:Nr.optional()}).strict().optional()}).strict(),Db=S.z.object({...Yt,type:S.z.literal("coupon_code"),label:Me,fallback:Me}).strict(),Fb=S.z.object({...Yt,type:S.z.literal("countdown"),source:S.z.enum(["offer.ends_at","offer.expires_at","fixed"]),at:S.z.iso.datetime().optional(),granularity:S.z.enum(["day","hour","minute","second"]),expired:Me,fallback:Me}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),Mb=S.z.object({...Yt,type:S.z.literal("plan_picker"),label:Me,fallback:Me,planIds:S.z.array(S.z.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:S.z.string().min(1).max(200).optional(),grouping:ga.safeExtend({monthLabel:Me,yearLabel:Me,unavailableLabel:Me}).optional(),states:S.z.object({selected:Nr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!ha(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),qb=S.z.object({...Yt,type:S.z.literal("quantity_picker"),bind:fa.optional(),label:Me,fallback:Me,internalFeatureId:S.z.uuid(),minimumQuantity:De(0,1e4),maximumQuantity:De(0,1e4),defaultQuantity:De(0,1e4),step:De(1,1e4)}).strict().refine(e=>e.minimumQuantity<=e.defaultQuantity&&e.defaultQuantity<=e.maximumQuantity&&(e.defaultQuantity-e.minimumQuantity)%e.step===0,"Quantity controls require a Product binding and valid bounds"),Bb=S.z.discriminatedUnion("type",[S.z.object({type:S.z.literal("input"),label:Me,keyboard:S.z.enum(["text","email","tel","url"]),maxLength:De(1,500)}).strict(),S.z.object({type:S.z.literal("multiselect"),label:Me,min:De(0,50),max:De(1,50)}).strict(),S.z.object({type:S.z.literal("select"),label:Me,defaultIndex:De(0,49),purpose:S.z.enum(["option","product","tier"]).optional(),pickerId:to.optional(),selectedStyle:Nr.optional()}).strict(),S.z.object({type:S.z.literal("tabs"),label:Me,defaultIndex:De(0,49),purpose:S.z.literal("tier").optional()}).strict(),S.z.object({type:S.z.literal("toggle"),label:Me,defaultEnabled:S.z.boolean()}).strict(),S.z.object({type:S.z.literal("carousel"),label:Me}).strict()]),In={...Yt,type:S.z.literal("stack"),direction:S.z.enum(["vertical","horizontal","overlay"]),align:S.z.enum(["start","center","end","stretch"]),justify:S.z.enum(["start","center","end","between"]),productSlot:S.z.object({index:De(0,19),period:S.z.enum(["month","year"]).optional(),requireBinding:S.z.boolean().optional()}).strict().optional(),interaction:Bb.optional(),states:S.z.object({selected:Nr.optional()}).strict().optional(),purpose:S.z.literal("benefits").optional(),purchaseAction:Me.optional(),buttonVariant:S.z.enum(["primary","secondary","link"]).optional(),bind:fa.optional()},Lp=S.z.lazy(()=>S.z.object({...Yt,type:In.type,direction:In.direction,align:In.align,justify:In.justify,children:S.z.array(Vb).max(vn.children),productSlot:In.productSlot,interaction:In.interaction,states:In.states,purpose:In.purpose,purchaseAction:In.purchaseAction,buttonVariant:In.buttonVariant,bind:In.bind}).strict()),Vb=S.z.lazy(()=>S.z.union([Lp,Cb,_b,Eb,Rb,jb,Tb,Nb,Db,Fb,Mb,qb,kb])),Lb=S.z.union([S.z.string().max(500),S.z.number().finite(),S.z.boolean(),S.z.null()]),eo={id:Me,event:Me,properties:S.z.record(Me,Lb).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},Ub=S.z.discriminatedUnion("type",[S.z.object({...eo,type:S.z.literal("navigate"),close:S.z.literal(!1),pageId:to}).strict(),S.z.object({...eo,type:S.z.literal("event"),close:S.z.boolean()}).strict(),S.z.object({...eo,type:S.z.literal("close"),close:S.z.literal(!0)}).strict(),S.z.object({...eo,type:S.z.literal("open_url"),close:S.z.boolean(),url:Bp}).strict(),S.z.object({...eo,type:S.z.literal("claim_offer"),close:S.z.boolean(),couponId:S.z.uuid()}).strict()]),zb=S.z.object({defaultLocale:xn,locales:S.z.record(xn,S.z.record(Me,S.z.string().max(vn.stringLength)))}).strict(),$b=S.z.enum(["popup","paywall","onboarding","page","banner"]);var Gb=S.z.discriminatedUnion("type",[S.z.object({type:S.z.literal("modal"),size:S.z.enum(["sm","md","lg"])}).strict(),S.z.object({type:S.z.literal("sheet"),size:S.z.enum(["sm","md","lg"])}).strict(),S.z.object({type:S.z.literal("fullscreen")}).strict(),S.z.object({type:S.z.literal("inline")}).strict()]);var Kb=S.z.object({kind:S.z.literal("screen"),schemaVersion:S.z.literal(Ab),name:S.z.string().trim().min(1).max(80),surface:$b,initialPageId:to.optional(),presentation:Gb,theme:Mp,pages:S.z.array(S.z.object({id:to,name:S.z.string().trim().min(1).max(60),root:Lp,theme:Mp.optional(),editorPosition:S.z.object({x:S.z.number().finite().min(-1e5).max(1e5),y:S.z.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(vn.pages),strings:zb,actions:S.z.array(Ub).max(vn.actions)}).strict();function Gt(e,t){for(let n of e.pages)Gn(n.root,t)}var sn=Kb.superRefine((e,t)=>{let n=vn;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(f=>f.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>vn.locales&&r(`\u6700\u591A ${vn.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,f)=>{if(c++,f>vn.depth&&(u=!0),s.has(l.id)&&r(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${l.id}`),s.add(l.id),l.type==="button"&&!a.has(l.action)&&r(`\u6309\u94AE ${l.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${l.action}`),l.type==="custom_html")for(let m of Object.keys(l.html))i.includes(m)||r(`\u81EA\u5B9A\u4E49 HTML ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${m}`);if(l.type==="image")for(let m of Object.keys(l.localizedSrc??{}))i.includes(m)||r(`\u56FE\u7247 ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${m}`)}),c>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),u&&r(`\u5C42\u7EA7\u6700\u591A ${vn.depth} \u5C42`)});function Gn(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)Gn(i,t,n+1,e)}function Aa(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 Hb(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=ro(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 tr(e){let t=Aa(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=>!Hb(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 Qb(e,t){let n=null;return Gn(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function ro(e,t){for(let n of e.pages){let r=Qb(n.root,t);if(r)return r}return null}var Nt=require("zod"),yt=Nt.z.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/).refine(e=>e.split(".").every(t=>t.length>0&&!["__proto__","constructor","prototype"].includes(t)),"Reserved or empty variable path"),mc=Nt.z.strictObject({type:Nt.z.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:Nt.z.boolean(),enum:Nt.z.array(Nt.z.string().max(255)).min(1).max(100).optional()}),ci=mc.extend({type:Nt.z.enum([...mc.shape.type.options,"array"]),items:mc.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"})}),ui=ci.safeExtend({source:Nt.z.discriminatedUnion("type",[Nt.z.strictObject({type:Nt.z.literal("input")}),Nt.z.strictObject({type:Nt.z.literal("node")}),Nt.z.strictObject({type:Nt.z.enum(["parameter","attribute"]),key:yt})])}),eP=Nt.z.record(yt,ui),fc=Nt.z.record(yt,yt).refine(e=>Object.keys(e).length<=20);function fn(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=>fn(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&&Nt.z.uuid().safeParse(t.id).success:e.type==="json"||(e.type==="strings"?Array.isArray(t)&&t.every(n=>typeof n=="string"):typeof t===e.type):!1}function gc(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&&gc(e.items,t.items)}function ya(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(!fn(i,u))throw new Error(`Invalid variable value: ${r}`);n[r]=u}}return n}function li(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 Up(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"||!fn(e[i],a))throw new Error(`Invalid node variable write: ${i}`);if(r.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}var nr=require("zod");var wn=nr.z.string().min(1).max(255).regex(/^[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+){0,9}$/).refine(e=>e.split(".").every(t=>!["__proto__","constructor","prototype"].includes(t)),"Reserved value path"),kn=nr.z.discriminatedUnion("source",[nr.z.strictObject({source:nr.z.literal("literal"),value:Se}),nr.z.strictObject({source:nr.z.literal("variable"),key:nr.z.string().min(1).max(255),path:wn.optional()})]);function zp(e,t){if(!t)return e;for(let n of wn.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 hc(e,t){if(e.source==="literal")return structuredClone(e.value);let n=ya(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(Se.parse(zp(n[e.key],e.path)))}function Ac(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&&!wn.safeParse(r).success?null:{key:n,path:r}}function yc(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(Rp))]}function ba(e){return yc(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function cn(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(/^-/,""),f=l.replace(".","").length,m=(l.includes(".")?l.indexOf("."):f)+Number(u),h=m<=0?2-m+f:m>=f?m:f+1;n+=h+(c.startsWith("-")?1:0)-s.length}}return n}var rr=ve.z.enum(["page","popup","banner"]),Jb=3e5,$p=ve.z.strictObject({type:ve.z.enum(["string","number","boolean","strings","json"]),nullable:ve.z.boolean()}),Zb=ve.z.strictObject({inputs:ve.z.record(Me,$p.extend({required:ve.z.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:ve.z.record(Me,$p).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),Wb=ve.z.strictObject({kind:rr,schemaVersion:ve.z.literal(1),name:ve.z.string().trim().min(1).max(80),screen:sn,contract:Zb}),xa=Wb.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"]),cn(e)>Jb&&n("Content document exceeds its byte budget",[])});function Yb(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 Xb=xa.superRefine((e,t)=>{for(let n of ba(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&&!Yb(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}tr(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),Gp=ve.z.strictObject({id:ve.z.uuid(),kind:rr,projectId:ve.z.uuid(),environmentId:ve.z.uuid(),name:ve.z.string(),revision:ve.z.number().int().nonnegative(),status:ve.z.enum(["draft","published","archived"]),publishedVersionId:ve.z.uuid().nullable(),createdAt:ve.z.iso.datetime({offset:!0}),updatedAt:ve.z.iso.datetime({offset:!0})}),fP=Gp.extend({draft:xa}),gP=ve.z.strictObject({rows:ve.z.array(Gp).max(200),nextCursor:ve.z.uuid().nullable()}),bc=ve.z.strictObject({id:ve.z.uuid(),kind:rr,resourceId:ve.z.uuid(),projectId:ve.z.uuid(),environmentId:ve.z.uuid(),version:ve.z.number().int().positive(),sourceRevision:ve.z.number().int().nonnegative(),document:Xb,createdAt:ve.z.iso.datetime({offset:!0})}),hP=bc.omit({document:!0}),AP=ve.z.discriminatedUnion("action",[ve.z.strictObject({action:ve.z.literal("create"),kind:rr,id:ve.z.uuid(),document:xa}),ve.z.strictObject({action:ve.z.literal("save"),kind:rr,id:ve.z.uuid(),revision:ve.z.number().int().nonnegative(),document:xa}),ve.z.strictObject({action:ve.z.enum(["publish","archive"]),kind:rr,id:ve.z.uuid(),revision:ve.z.number().int().nonnegative()})]).superRefine((e,t)=>{"document"in e&&e.document.kind!==e.kind&&t.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});var xc=require("zod"),di={funnelId:xc.z.uuid().optional(),funnelVersionId:xc.z.uuid().optional()};var io=require("zod"),Sa=io.z.strictObject({runId:io.z.uuid(),bindingId:io.z.uuid(),receiptId:io.z.uuid()});var nt=require("zod");var qe=require("zod");var We=require("zod"),SP=We.z.discriminatedUnion("action",[We.z.strictObject({action:We.z.literal("create"),couponId:We.z.uuid(),productBindingId:We.z.uuid(),storeOfferId:We.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:We.z.enum(["introductory","promotional"])}),We.z.strictObject({action:We.z.literal("set_enabled"),id:We.z.uuid(),revision:We.z.number().int().nonnegative(),enabled:We.z.boolean()})]),IP=We.z.array(We.z.strictObject({id:We.z.uuid(),couponId:We.z.uuid(),productBindingId:We.z.uuid(),storeOfferId:We.z.string().min(1).max(255).nullable(),storeOfferType:We.z.enum(["introductory","promotional"]),enabled:We.z.boolean(),revision:We.z.number().int().nonnegative()})).max(500),pi=We.z.strictObject({offerKind:We.z.enum(["none","introductory","promotional"]),offerId:We.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:We.z.number().int().min(0).max(1e8),trialDays:We.z.number().int().min(1).max(730).nullable()}).superRefine((e,t)=>{(e.offerKind==="none"&&(e.offerId!==null||e.discountMinor!==0||e.trialDays!==null)||e.trialDays!==null&&e.discountMinor!==0)&&t.addIssue({code:"custom",message:"Select one store purchase option with its exact terms"})}),vP=We.z.record(We.z.uuid(),pi).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var Sc=qe.z.object({type:qe.z.literal("native_purchase"),receiptId:qe.z.uuid(),orderId:qe.z.uuid(),productVersionId:qe.z.uuid(),provider:qe.z.enum(["apple","google"]),productId:qe.z.string().min(1).max(255),productKind:Cp,replacement:qe.z.strictObject({sourceOrderId:qe.z.uuid(),sourceProductId:qe.z.string().min(1).max(255),policy:qe.z.enum(["apple_store","google_full_price"]),sourceAccountTokens:qe.z.array(qe.z.uuid()).max(50)}).nullable(),appAccountToken:qe.z.uuid().optional(),obfuscatedAccountId:qe.z.string().min(1).max(64).optional(),obfuscatedProfileId:qe.z.uuid().optional(),basePlanId:qe.z.string().min(1).max(255).optional(),offerId:qe.z.string().min(1).max(255).optional(),offerKind:qe.z.enum(["none","introductory","promotional"]),currency:be,catalogAmountMinor:qe.z.number().int().nonnegative().max(1e8),discountMinor:qe.z.number().int().nonnegative().max(1e8),trialDays:qe.z.number().int().min(1).max(730).nullable(),seatBundle:qe.z.array(qe.z.strictObject({key:qe.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:qe.z.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:qe.z.strictObject({offerId:qe.z.string().min(1).max(255),keyId:qe.z.string().min(1).max(255),nonce:qe.z.uuid(),signature:qe.z.string().min(1).max(1024),timestamp:qe.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,t)=>{let n=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(n?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!n&&e.productKind==="membership"&&e.basePlanId===void 0||e.discountMinor>e.catalogAmountMinor||new Set(e.seatBundle.map(i=>i.key)).size!==e.seatBundle.length||e.trialDays!==null&&(e.discountMinor!==0||e.offerKind==="none")||e.offerKind==="none"&&e.discountMinor!==0||(n?!e.appAccountToken||e.obfuscatedAccountId!==void 0||e.obfuscatedProfileId!==void 0||e.basePlanId!==void 0||e.offerKind==="promotional"!=(e.applePromotionalOffer!==null)||e.offerKind==="promotional"!=(e.offerId!==void 0)||e.applePromotionalOffer!==null&&e.applePromotionalOffer.offerId!==e.offerId:e.appAccountToken!==void 0||!e.obfuscatedAccountId||!e.obfuscatedProfileId||e.applePromotionalOffer!==null||e.offerKind==="none"!=(e.offerId===void 0)))&&t.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});var p=require("zod");var Ce=require("zod/v4"),Kp=require("zod/v4"),ex=Kp.z.registry(),{BillingInterval:Hp}=(()=>{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:tx}=(e=>({DisplaySchema:e.object({primary_text:e.string().meta({description:"Main display text (e.g. '$10' or '100 messages')."}),secondary_text:e.string().optional().meta({description:"Secondary display text (e.g. 'per month' or 'then $0.5 per 100')."})})}))(Ce.z),{withSpecDefault:nx}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(ex),{COMMON:Qp}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:rx}={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)}))(Qp),{hasNoDuplicateCurrencies:Jp}={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:Zp}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:ox}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(Ce.z),{Infinite:ax}={Infinite:"inf"},{TierBehavior:sx}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:Wp}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:cx}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:ux}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:lx}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:dx}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(Ce.z),{ApiCreditTierSchema:Yp}=(e=>({ApiCreditTierSchema:e.object({to:e.union([e.number().positive(),e.enum(["inf"])]).meta({description:"Inclusive upper usage boundary for this graduated tier. The final tier must be 'inf'."}),credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group within this tier."})})}))(Ce.z),{VIOLATION_MESSAGES:px}={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:Xp}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(Ce.z),{ModelMarkupsSchema:mx}=((e,t)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),t.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(Ce.z,Xp),{InvoiceUsageEntrySchema:fx}=(e=>({InvoiceUsageEntrySchema:e.object({feature_id:e.string().meta({description:"The metered feature whose units are being converted."}),quantity:e.number().nonnegative().meta({description:"Billable units of the metered feature. Converted to the credit-system feature through its rate card."}),properties:e.record(e.string(),e.unknown()).optional().meta({description:"Event properties used to pick the rate card dimension and multipliers."})}).strict()}))(Ce.z),{AttachDiscountSchema:em}=(e=>({AttachDiscountSchema:e.object({reward_id:e.string().optional().meta({description:"The ID of the reward to apply as a discount."}),promotion_code:e.string().optional().meta({description:"The promotion code to apply as a discount."})}).refine(n=>n.reward_id||n.promotion_code,{message:"Either reward_id or promotion_code must be provided."}).meta({title:"AttachDiscount",description:"A discount to apply. Can be either a reward ID or a promotion code."})}))(Ce.z),{CustomLineItemSchema:gx}=(e=>({CustomLineItemSchema:e.object({amount:e.number().meta({description:"Amount in dollars for this line item (e.g. 10.50). Can be negative for credits."}),description:e.string().meta({description:"Description for the line item."})})}))(Ce.z),{UnixMsTimestampSchema:hx}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(Ce.z),{CreateInvoicePreviewLineSchema:Ax}=(e=>({CreateInvoicePreviewLineSchema:e.object({plan_id:e.string().nullable(),feature_id:e.string().nullable(),description:e.string(),amount:e.number(),amount_after_discounts:e.number(),quantity:e.number().nullable(),prorated:e.boolean(),period_start:e.number().nullable(),period_end:e.number().nullable()})}))(Ce.z),{ReissueInvoiceParamsSchema:tm}=(e=>({ReissueInvoiceParamsSchema:e.object({invoice_id:e.string().meta({description:"The Autumn invoice ID to void and replace.",example:"inv_2b3c4d5e6f7g8h"}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer and memo are applied to the replacement invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the replacement invoice. Defaults to the original invoice's due date; required when that date has already passed."}),update_customer_email:e.email().optional().meta({description:"Updates the customer's billing email before the replacement is issued, so Stripe sends the new invoice to this address."})})}))(Ce.z),{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."})}))(Ce.z),{InvoiceTemplateSchema:yx}=(e=>({InvoiceTemplateSchema:e.object({id:e.string().meta({description:"Unique identifier for the invoice template."}),name:e.string().meta({description:"User-defined name to distinguish this template when sending an invoice."}),footer:e.string().optional().meta({description:"Footer text rendered on the invoice, typically bank details so customers can pay directly."}),memo:e.string().optional().meta({description:"Memo shown near the top of the invoice (Stripe invoice description), e.g. a contact line for payment questions."}),net_terms_days:e.number().int().positive().optional().meta({description:"Default number of days the customer has to pay before the invoice is due. Overridable when sending."}),created_at:e.number().optional().meta({description:"Timestamp (ms) when the template was created."})})}))(Ce.z),{BasePriceSchema:bx}=((e,t,n)=>({BasePriceSchema:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),interval:e.enum(t).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),display:n.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(Ce.z,Hp,tx),{CURRENCY_CODES:xx}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(Qp,rx,ix),{ApiPriceProcessorsSchema:nm}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(Ce.z,ox),{AllocatedBillingFieldSchema:Sx}=((e,t)=>({AllocatedBillingFieldSchema:e.enum(t).optional().meta({internal:!0,description:"How an allocated usage_based price bills mid-cycle quantity changes. 'arrear' (default) bills at period end. 'prorated_legacy' is only returned for prices still on the legacy immediate-proration behavior; omit it to migrate the price to 'arrear'."})}))(Ce.z,cx),{CreditDimensionNameSchema:Ix}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(Ce.z,ux,lx),{ApiCreditMatchSchema:rm}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(dx),{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}}))(px),{ApiCreditMultiplierSchema:wx}=((e,t)=>({ApiCreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional().meta({description:"Multiplies the matched rate. All matching multipliers stack."}),add:e.number().optional().meta({description:"Added to the rate after every factor is applied, in credits per billing-unit group."})}).strict().refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(Ce.z,rm),{ProviderMarkupsSchema:Ox}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(Ce.z,Xp),{InvoiceFeatureQuantitySchema:im}=((e,t,n)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(t).meta({description:"Which of the feature's prices to use: 'prepaid' or 'usage_based'."}),quantity:e.number().nonnegative().optional().meta({description:"Billable feature units in total, exclusive of any included usage. Not per seat or per entity. For a credit-system feature this is the number of credits."}),usage:e.array(n).optional().meta({description:"For credit-system features: billable units of the source features, converted through the credit rate card. Mutually exclusive with quantity."}),prorate:e.boolean().optional().meta({description:"Whether to prorate this line against period_start / period_end. Defaults to true for prepaid and false for usage-based."})}).strict().refine(i=>i.quantity!==void 0!=(i.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(Ce.z,Wp,fx),{CreateInvoicePreviewSchema:Ic}=((e,t)=>({CreateInvoicePreviewSchema:e.object({currency:e.string(),lines:e.array(t),subtotal:e.number(),discount_total:e.number(),tax:e.object({total:e.number(),amount_inclusive:e.number(),amount_exclusive:e.number(),status:e.enum(["complete","incomplete"])}).nullable(),total:e.number(),due_date:e.number().nullable()})}))(Ce.z,Ax),{SUPPORTED_SET:Px}=(e=>({SUPPORTED_SET:new Set(e)}))(xx),{ApiCreditDimensionBaseSchema:Cx}=((e,t)=>({ApiCreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(Ce.z,rm),{refineGraduatedTiers:om}=(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:_x}=((e,t,n)=>({ApiFeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional().meta({description:"Default percentage markup for customers on this plan. Use -100 to make usage free."}),provider_markups:t.meta({description:"Per-provider markup percentages for customers on this plan."}),model_markups:n.meta({description:"Per-model markup overrides for customers on this plan."})})}))(Ce.z,Ox,mx),{isValidCurrencyCode:Ex}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(Px),{ApiCreditDimensionSchema:Rx}=((e,t,n,r)=>({ApiCreditDimensionSchema:e.union([t.extend({tier_behavior:e.literal("graduated"),tiers:e.array(n).min(1)}).strict().superRefine(r),t.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(Ce.z,Cx,Yp,om),{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')."})}))(Ce.z,Ex),{AdditionalCurrencyTierSchema:kx}=((e,t)=>({AdditionalCurrencyTierSchema:e.object({currency:t,amount:e.number().optional().meta({description:"Per-unit amount for this tier in this currency."}),flat_amount:e.number().optional().meta({description:"Flat amount for this tier in this currency, if the tier uses one."})}).refine(r=>r.amount!==void 0||r.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(Ce.z,am),{ApiCreditSchemaItemBaseSchema:sm}=((e,t,n,r)=>({ApiCreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string().nonempty().meta({description:"ID of the metered feature that draws from this credit system."}),billing_units:e.number().positive().optional().meta({description:"Number of metered-feature units priced together. Defaults to one when omitted."}),dimensions:e.record(t,n).optional().meta({description:"Named rates chosen by event properties. The most specific match sets the rate; with no match the item's own rate applies."}),multipliers:e.record(t,r).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(Ce.z,Ix,Rx,wx),{ApiFlatCreditSchemaItemSchema:jx}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(sm,Ce.z),{AdditionalCurrencyPriceSchema:Tx}=((e,t)=>({AdditionalCurrencyPriceSchema:e.object({currency:t,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(Ce.z,am),{AdditionalCurrencyTierArraySchema:Nx}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(Ce.z,kx,Jp,Zp),{ApiGraduatedCreditSchemaItemSchema:Dx}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(sm,Ce.z,Yp,om),{AdditionalCurrencyPriceArraySchema:cm}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(Ce.z,Tx,Jp,Zp),{ApiUsageTierWithCurrenciesSchema:Fx}=((e,t,n)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:n.optional().meta({description:"Per-currency amounts for this tier. Tier boundaries ('to') are shared across all currencies."})}).refine(i=>i.amount!==void 0||i.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(i=>({...i,amount:i.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:n.optional()}))}))(Ce.z,ax,Nx),{ApiCreditSchemaItemSchema:Mx}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(Ce.z,Dx,jx),{BasePriceParamsSchema:qx}=((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."})}))(bx,nx,Ce.z,cm),{PlanItemPriceParamsSchema:Bx}=((e,t,n,r,i,a,o)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(c=>c??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:t.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(i).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(a).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:o,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(Ce.z,cm,Fx,sx,Hp,Wp,Sx),{ApiFeatureOverrideSchema:Vx}=((e,t,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(t).optional().meta({description:"For credit system features: replaces the feature's credit_schema entirely for customers on this plan."}),markups:n.optional().meta({description:"For AI credit system features: replaces the feature's markup chain entirely for customers on this plan. An unset level means no markup at that level rather than inheriting the feature's."})})}))(Ce.z,Mx,_x),{InvoiceBasePriceParamsSchema:um}=((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()}))(qx,nm),{InvoiceItemPriceParamsSchema:Lx}=((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()}))(Bx,nm),{InvoiceLicenseQuantitySchema:Ux}=((e,t,n)=>({InvoiceLicenseQuantitySchema:e.object({license_plan_id:e.string().meta({description:"The license plan linked to the parent plan."}),quantity:e.number().int().nonnegative().meta({description:"Billable seats, exclusive of any included seats."}),customize:e.object({price:t.nullable().optional()}).strict().optional().meta({description:"Override the license's per-seat price on this invoice."}),feature_quantities:e.array(n).optional().meta({description:"Feature charges priced through the license plan."}),prorate:e.boolean().optional().meta({description:"Whether to prorate seat charges against period_start / period_end. Defaults to true."})}).strict()}))(Ce.z,um,im),{InvoiceCustomizeItemSchema:zx}=((e,t,n)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:t.optional().meta({description:"Pricing to use for this feature on this invoice."}),feature_override:n.pick({credit_schema:!0}).strict().optional().meta({description:"For credit-system features: a credit rate card to use when converting `usage` on this invoice."})}).strict()}))(Ce.z,Lx,Vx),{InvoiceCustomizeSchema:$x}=((e,t,n)=>({InvoiceCustomizeSchema:e.object({price:t.nullable().optional().meta({description:"Override the plan's base price for this invoice. Pass null or an amount of 0 to omit the base price line."}),items:e.array(n).optional().meta({description:"Override feature pricing for this invoice. Only pricing fields are accepted; grants, resets and rollovers are not part of an invoice."})}).strict().meta({title:"InvoiceCustomize",description:"Pricing overrides applied to this invoice only. The catalog and the customer's plan are not changed."})}))(Ce.z,um,zx),{InvoicePlanParamsSchema:Gx}=((e,t,n,r,i)=>({InvoicePlanParamsSchema:e.object({plan_id:e.string().meta({description:"The catalog plan (or variant) whose pricing to use."}),version:e.number().optional().meta({description:"Plan version. Defaults to the active version."}),customize:t.optional(),feature_quantities:e.array(n).optional(),license_quantities:e.array(r).optional(),discounts:e.array(i).optional().meta({description:"Discounts applied only to this plan's lines."}),prorate:e.boolean().optional().meta({description:"Whether to prorate the base price against period_start / period_end. Defaults to true."})}).strict()}))(Ce.z,$x,im,Ux,em),{CreateInvoiceParamsSchema:mi}=((e,t,n,r,i)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(t).optional(),custom_line_items:e.array(n).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(r).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:i.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start \u2192 period_end against one price interval starting at period_start."}),period_end:i.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(o=>o.period_start===void 0==(o.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(o=>o.period_start===void 0||o.period_end===void 0||o.period_end>o.period_start,{message:"period_end must be after period_start."})}))(Ce.z,Gx,gx,em,hx);var pm=p.z.strictObject({requestId:p.z.uuid(),predecessorOperationId:p.z.uuid().optional(),invoiceMode:Dr.optional(),entityId:p.z.uuid().optional(),billingSubscriptionId:p.z.uuid().optional(),newBillingSubscription:p.z.literal(!0).optional(),offerId:p.z.uuid().optional(),nativeOffer:pi.optional(),plans:p.z.array(p.z.strictObject({productVersionId:p.z.uuid(),seatQuantities:p.z.record(zo,p.z.number().int().min(0).max(1e4)).optional(),featureQuantities:p.z.record(p.z.uuid(),p.z.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100,"At most 100 feature quantities").optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Plan versions must be unique"),provider:p.z.enum(["stripe","apple","google","merchant"]),currency:be}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||["apple","google"].includes(e.provider)&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||["stripe","merchant"].includes(e.provider)&&!e.billingSubscriptionId,"A new billing subscription has no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),Mr=p.z.strictObject({operationId:p.z.uuid()}),Dt=p.z.number().int().min(0).max(1e8),Kx=p.z.strictObject({lineId:p.z.uuid(),productVersionId:p.z.uuid(),productName:p.z.string().min(1).max(80),interval:p.z.enum(["free","week","month","year","one_time"]),intervalCount:p.z.number().int().min(1).max(156).optional(),baseAmountMinor:Dt,seats:p.z.array(p.z.strictObject({key:zo,quantity:p.z.number().int().min(0).max(1e4),includedQuantity:p.z.number().int().min(0).max(1e4),maximumQuantity:p.z.number().int().min(0).max(1e4),unitAmountMinor:Dt})).max(20),prepaid:p.z.array(tp).max(100).optional(),catalogAmountMinor:Dt,trial:p.z.strictObject({days:p.z.number().int().min(1).max(730),cardRequired:p.z.boolean()}).nullable()}).refine(e=>new Set(e.seats.map(t=>t.key)).size===e.seats.length&&e.seats.every(t=>t.quantity>=t.includedQuantity&&t.quantity<=t.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((t,n)=>t+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((t,n)=>t+Qo({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"),mm=p.z.string().regex(/^[A-Za-z0-9_-]{1,200}$/),Hx=p.z.strictObject({id:mm,name:p.z.string().min(1).max(40),percent_off:p.z.number().gt(0).max(100).optional(),amount_off:p.z.number().int().positive().optional(),currency:p.z.string().regex(/^[a-z]{3}$/).optional(),duration:p.z.enum(["once","repeating","forever"]),duration_in_months:p.z.number().int().min(1).max(36).optional()}).refine(e=>e.percent_off===void 0!=(e.amount_off===void 0)&&e.amount_off===void 0==(e.currency===void 0)&&e.duration==="repeating"==(e.duration_in_months!==void 0),"A Stripe coupon has one percentage or amount and months only when repeating"),Qx=p.z.strictObject({subscriptionId:p.z.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:p.z.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:p.z.array(p.z.strictObject({id:p.z.string(),price_id:p.z.string(),quantity:p.z.number().int().nonnegative(),discounts:p.z.array(p.z.strictObject({id:p.z.string(),coupon:p.z.string(),start:p.z.number(),end:p.z.number().nullable()})).optional()})).min(1).max(100),prorationDate:p.z.number().int().nonnegative(),amountMinor:p.z.number().int().positive(),periodStartMs:p.z.number(),periodEndMs:p.z.number()}),fm=p.z.strictObject({invoiceMode:Dr.optional(),append:Qx.optional(),provider:p.z.literal("stripe"),executor:p.z.enum(["indiana","merchant"]),accountId:p.z.string().regex(/^acct_[A-Za-z0-9]+$/),mode:p.z.enum(["payment","subscription"]),lineItems:p.z.array(p.z.strictObject({price:p.z.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:p.z.number().int().min(1).max(1e4),priceId:p.z.uuid(),productName:p.z.string().min(1).max(80),amountMinor:p.z.number().int().min(0).max(1e8),currency:p.z.string().regex(/^[a-z]{3}$/),interval:p.z.enum(["week","month","year","one_off"]),intervalCount:p.z.number().int().min(1).max(52),slot:p.z.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:p.z.strictObject({mode:p.z.enum(["graduated","volume"]),tiers:p.z.array(p.z.strictObject({upTo:p.z.number().int().min(1).max(1e6).nullable(),unitAmountMinor:p.z.number().int().min(0).max(1e8),flatAmountMinor:p.z.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:p.z.array(p.z.strictObject({coupon:mm,terms:Hx})).max(1),trialPeriodDays:p.z.number().int().min(1).max(730).nullable(),metadata:p.z.strictObject({grooveCheckoutId:p.z.uuid(),grooveCustomerId:p.z.uuid()}),expiresAt:p.z.iso.datetime({offset:!0})}),fi=p.z.strictObject({operationId:p.z.uuid(),entityId:p.z.uuid().nullable(),billingSubscriptionId:p.z.uuid().nullable(),discount:p.z.strictObject({offerId:p.z.uuid(),couponId:p.z.uuid(),discount:Xn,duration:on,amountMinor:Dt,allocations:p.z.array(p.z.strictObject({productVersionId:p.z.uuid(),amountMinor:Dt})).min(1).max(20),expiresAt:p.z.iso.datetime({offset:!0})}).nullable(),charge:p.z.strictObject({effectiveAt:p.z.iso.datetime({offset:!0}),periodEndsAt:p.z.iso.datetime({offset:!0}),debitMinor:Dt,discountMinor:Dt,taxMinor:Dt,totalMinor:Dt}).nullable(),expiresAt:p.z.iso.datetime({offset:!0}),provider:p.z.enum(["stripe","apple","google","merchant"]),nativeOffer:pi.optional(),currency:be,lines:p.z.array(Kx).min(1).max(20),catalogAmountMinor:Dt,automaticTax:p.z.boolean(),execution:p.z.union([fm,qo]).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"),gi=p.z.strictObject({operationId:p.z.uuid(),orderId:p.z.uuid(),append:p.z.boolean().optional(),invoiceMode:p.z.boolean().optional(),status:p.z.enum(["pending","complete","cancelled","failed"]),executor:p.z.enum(["indiana","merchant"]),checkoutUrl:p.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:p.z.union([fm,qo]).nullable(),currency:be,catalogAmountMinor:Dt,taxMinor:Dt,totalMinor:p.z.number().int().min(0).max(2e8).nullable(),quoteFinalized:p.z.boolean(),nativePurchase:Sc.nullable(),confirmedAt:p.z.iso.datetime({offset:!0}).nullable().optional(),quote:fi.optional(),merchantExecution:Ir.nullable().optional(),problem:Di.nullable().optional(),authority:Uo.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"),va=p.z.strictObject({enabled:p.z.literal(!0),featureIds:p.z.array(p.z.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),gm=p.z.strictObject({requestId:p.z.uuid(),invoiceMode:Dr.optional(),membershipId:p.z.uuid(),carryOverBalances:va.optional(),carryOverUsages:va.optional(),membershipIds:p.z.array(p.z.uuid()).min(1).max(20).optional(),prorationBehavior:p.z.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:p.z.enum(["immediate","renewal","store"]),change:p.z.discriminatedUnion("type",[p.z.strictObject({type:p.z.literal("plan"),productVersionId:p.z.uuid()}),p.z.strictObject({type:p.z.literal("seats"),licenseKey:zo,quantity:p.z.number().int().min(0).max(1e4)}),p.z.strictObject({type:p.z.literal("quantity"),internal_feature_id:p.z.uuid(),quantity:p.z.number().int().min(0).max(1e4)}),p.z.strictObject({type:p.z.literal("cancel")}),p.z.strictObject({type:p.z.literal("uncancel")}),p.z.strictObject({type:p.z.literal("billing_cycle"),billingCycleAnchor:p.z.union([p.z.literal("now"),p.z.number().int().positive().max(0xe677d21fdbff)])})])}).refine(e=>e.timing!=="store"||e.change.type==="plan","Store timing applies to a native plan replacement").refine(e=>e.change.type!=="billing_cycle"||e.timing===(e.change.billingCycleAnchor==="now"?"immediate":"renewal"),"Use immediate for now and renewal for a future millisecond anchor").refine(e=>!e.membershipIds||["cancel","uncancel"].includes(e.change.type)&&e.membershipIds.includes(e.membershipId)&&new Set(e.membershipIds).size===e.membershipIds.length,"Grouped actions require unique cancel/uncancel targets including the primary membership").refine(e=>!e.carryOverBalances&&!e.carryOverUsages||e.change.type==="plan"&&e.timing==="immediate","Carry applies only to immediate upgrades").refine(e=>!e.prorationBehavior||e.change.type==="quantity","prorationBehavior applies to prepaid quantity changes"),Ia=p.z.string().regex(/^price_[A-Za-z0-9]+$/),lm=p.z.strictObject({grooveUpdateId:p.z.uuid(),grooveCustomerId:p.z.uuid()}),dm=p.z.strictObject({price:Ia.nullable(),priceId:p.z.uuid().optional(),quantity:p.z.number().int().min(0).max(1e4)}),hm=p.z.strictObject({provider:p.z.literal("stripe"),invoiceMode:Dr.optional(),executor:p.z.enum(["indiana","merchant"]),accountId:p.z.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:p.z.string().regex(/^sub_[A-Za-z0-9]+$/),action:p.z.enum(["update","cancel","schedule","release"]),update:p.z.strictObject({items:p.z.array(dm).max(20),remove:p.z.array(Ia).max(20),restoreItems:p.z.array(p.z.strictObject({price:Ia,quantity:p.z.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:p.z.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:p.z.number().int().positive().optional(),paymentBehavior:p.z.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:p.z.boolean().optional(),clearCancelAt:p.z.literal(!0).optional(),billingCycleAnchorNow:p.z.literal(!0).optional(),metadata:lm}).nullable(),cancel:p.z.strictObject({prorate:p.z.literal(!1),invoiceNow:p.z.literal(!1)}).nullable(),schedule:p.z.strictObject({currentItems:p.z.array(p.z.strictObject({price:Ia,quantity:p.z.number().int().min(0).max(1e4)})).max(20),nextItems:p.z.array(dm).min(1).max(20),switchAt:p.z.number().int().positive(),interval:p.z.enum(["week","month","year"]),intervalCount:p.z.number().int().min(1).max(52),resetBillingCycleAnchor:p.z.literal(!0).optional(),metadata:lm}).nullable(),release:p.z.strictObject({schedule:p.z.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:p.z.iso.datetime({offset:!0})}).refine(e=>["update","cancel","schedule","release"].every(t=>e[t]!==null==(e.action===t))&&(e.executor==="indiana"||[...e.update?.items??[],...e.schedule?.nextItems??[]].every(t=>t.price!==null)),"Stripe update execution carries exactly its action, with bound Prices for the merchant"),wa=p.z.strictObject({carryOverBalances:va.optional(),carryOverUsages:va.optional(),operationId:p.z.uuid(),membershipId:p.z.uuid(),productVersionId:p.z.uuid(),timing:p.z.enum(["immediate","renewal"]),effectiveAt:p.z.iso.datetime({offset:!0}),expiresAt:p.z.iso.datetime({offset:!0}),currency:be,creditMinor:Dt,debitMinor:Dt,discountMinor:Dt,taxMinor:Dt,totalMinor:Dt,retainedProductVersionIds:p.z.array(p.z.uuid()).max(19),execution:p.z.union([hm,Bo])}),Jx=p.z.strictObject({operationId:p.z.uuid(),invoiceMode:p.z.boolean().optional(),membershipId:p.z.uuid(),productVersionId:p.z.uuid(),status:p.z.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:p.z.enum(["immediate","renewal"]),effectiveAt:p.z.iso.datetime({offset:!0}),checkoutUrl:p.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:p.z.enum(["indiana","merchant"]),execution:p.z.union([hm,Bo]).nullable(),confirmedAt:p.z.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Ir.nullable().optional(),problem:Di.nullable().optional(),quote:wa.optional(),authority:Uo.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),Zx=p.z.strictObject({operationId:p.z.uuid(),membershipId:p.z.uuid(),productVersionId:p.z.uuid(),timing:p.z.literal("store"),effectiveAt:p.z.null(),expiresAt:p.z.iso.datetime({offset:!0}),currency:be,creditMinor:p.z.null(),debitMinor:p.z.null(),discountMinor:p.z.null(),taxMinor:p.z.null(),totalMinor:p.z.null(),retainedProductVersionIds:p.z.array(p.z.uuid()).max(19),store:p.z.strictObject({provider:p.z.enum(["apple","google"]),productId:p.z.string().min(1).max(255),catalogAmountMinor:Dt,policy:p.z.enum(["apple_store","google_full_price"])})}),Wx=p.z.strictObject({operationId:p.z.uuid(),membershipId:p.z.uuid(),productVersionId:p.z.uuid(),status:p.z.enum(["prepared","pending","effective","cancelled","failed"]),timing:p.z.literal("store"),effectiveAt:p.z.iso.datetime({offset:!0}).nullable(),checkoutUrl:p.z.null(),nativePurchase:Sc.nullable()}),Am=p.z.union([wa,Zx]),vc=p.z.union([Jx,Wx]),oo=p.z.number().int().positive().max(2e8),Fr=p.z.number().int().min(0).max(2e8),ym=p.z.strictObject({requestId:p.z.uuid(),invoiceId:p.z.uuid(),mode:p.z.enum(["full","partial"]),amountMinor:oo.optional(),entitlementAction:p.z.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),bm=p.z.strictObject({provider:p.z.literal("stripe"),executor:p.z.enum(["indiana","merchant"]),accountId:p.z.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:p.z.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:oo,currency:p.z.string().regex(/^[a-z]{3}$/),metadata:p.z.strictObject({indianaRefundId:p.z.uuid()}),idempotencyKey:p.z.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:p.z.array(p.z.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),wc=p.z.strictObject({operationId:p.z.uuid(),invoiceId:p.z.uuid(),providerInvoiceId:p.z.string().min(1).max(200),currency:be,paidMinor:Fr,refundedMinor:Fr,pendingMinor:Fr,amountMinor:oo,mode:p.z.enum(["full","partial"]),entitlementAction:p.z.enum(["retain","revoke"]),revokes:p.z.strictObject({customerProductIds:p.z.array(p.z.uuid()).max(100),subscriptionIds:p.z.array(p.z.string().min(1).max(200)).max(20)}),execution:p.z.union([bm,Vo]),expiresAt:p.z.iso.datetime({offset:!0})}).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&(e.execution.provider==="merchant"?e.execution.merchantInvoiceId===e.providerInvoiceId&&e.execution.operationId===e.operationId&&e.execution.currency===e.currency:e.execution.invoice===e.providerInvoiceId&&e.execution.metadata.indianaRefundId===e.operationId&&e.execution.currency===e.currency.toLowerCase())&&(e.entitlementAction==="revoke"||e.revokes.customerProductIds.length===0&&e.revokes.subscriptionIds.length===0),"Refund quote must stay within the refundable amount and match its execution"),Oa=p.z.strictObject({operationId:p.z.uuid(),invoiceId:p.z.uuid(),providerInvoiceId:p.z.string().min(1).max(200),status:p.z.enum(["quoted","pending","succeeded","failed","expired"]),executor:p.z.enum(["indiana","merchant"]),currency:be,amountMinor:oo,mode:p.z.enum(["full","partial"]),entitlementAction:p.z.enum(["retain","revoke"]),refundId:p.z.string().min(1).max(200).nullable(),quote:wc.optional(),execution:p.z.union([bm,Vo]).nullable(),confirmedAt:p.z.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Ir.nullable().optional(),problem:Di.nullable().optional(),authority:Uo.optional(),failureReason:p.z.string().min(1).max(200).nullable(),createdAt:p.z.iso.datetime({offset:!0}),completedAt:p.z.iso.datetime({offset:!0}).nullable()}).refine(e=>(e.execution===null||e.executor==="merchant"&&e.status==="quoted")&&(e.status!=="succeeded"||e.refundId!==null),"Only quoted record-only refunds carry instructions; a succeeded refund names its Stripe refund"),BP=p.z.strictObject({invoiceId:p.z.uuid(),currency:be,paidMinor:Fr,refundedMinor:Fr,pendingMinor:Fr,refundableMinor:Fr,executor:p.z.enum(["indiana","merchant"]).nullable(),canRefund:p.z.boolean(),operations:p.z.array(Oa).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),VP=p.z.strictObject({requestId:p.z.uuid(),mode:p.z.enum(["full","partial"]),amountMinor:oo.optional(),entitlementAction:p.z.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount");var xm=nt.z.strictObject({requestId:nt.z.uuid(),targets:nt.z.array(nt.z.strictObject({membershipId:nt.z.uuid(),action:nt.z.enum(["cancel","uncancel"]),timing:nt.z.enum(["immediate","renewal"])}).refine(e=>e.action!=="uncancel"||e.timing==="immediate","Restoration is immediate")).min(1).max(100)}).refine(e=>new Set(e.targets.map(t=>t.membershipId)).size===e.targets.length,"Duplicate batch target"),Pa=nt.z.strictObject({batchId:nt.z.uuid()}),Yx=nt.z.strictObject({operationId:nt.z.uuid(),membershipIds:nt.z.array(nt.z.uuid()).min(1).max(20),provider:nt.z.enum(["stripe","apple","google"]),action:nt.z.enum(["cancel","uncancel"]),timing:nt.z.enum(["immediate","renewal"]),status:nt.z.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:wa.nullable(),managementUrl:nt.z.url().nullable(),failureCode:nt.z.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),ao=nt.z.strictObject({batchId:nt.z.uuid(),ready:nt.z.boolean(),status:nt.z.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:nt.z.iso.datetime({offset:!0}),acceptedAt:nt.z.iso.datetime({offset:!0}).nullable(),groups:nt.z.array(Yx).min(1).max(100)});var Re=require("zod"),Xx=Re.z.string().trim().min(1).max(240),Oc={requestId:Re.z.uuid(),reason:Xx},Ca=Re.z.discriminatedUnion("action",[Re.z.strictObject({...Oc,action:Re.z.literal("start"),productVersionId:Re.z.uuid(),entityId:Re.z.uuid().optional(),days:Re.z.number().int().min(1).max(730).optional()}),Re.z.strictObject({...Oc,action:Re.z.literal("extend"),membershipId:Re.z.uuid(),days:Re.z.number().int().min(1).max(730)}),Re.z.strictObject({...Oc,action:Re.z.literal("end"),membershipId:Re.z.uuid()})]),Sm=Re.z.strictObject({operationId:Re.z.uuid()}),Im=Re.z.iso.datetime({offset:!0}),eS=Re.z.strictObject({provider:Re.z.literal("stripe"),executor:Re.z.enum(["indiana","merchant"]),accountId:Re.z.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:Re.z.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:Re.z.union([Re.z.literal("now"),Im]),prorationBehavior:Re.z.literal("none")}),Pc=Re.z.strictObject({operationId:Re.z.uuid(),action:Re.z.enum(["start","extend","end"]),status:Re.z.enum(["pending","effective"]),managedBy:Re.z.enum(["indiana","stripe"]),membershipIds:Re.z.array(Re.z.uuid()).min(1).max(20),endsAt:Im.nullable(),execution:eS.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"),$P=Re.z.strictObject({groupId:Re.z.uuid(),productVersionId:Re.z.uuid(),enabled:Re.z.boolean()});var He=require("zod");var vm=He.z.strictObject({requestId:He.z.uuid(),currency:be,makeDefault:He.z.boolean()}),wm=He.z.strictObject({setupId:He.z.uuid()}),tS=He.z.strictObject({provider:He.z.literal("stripe"),executor:He.z.literal("merchant"),accountId:He.z.string().regex(/^acct_[A-Za-z0-9]+$/),mode:He.z.literal("setup"),currency:He.z.string().regex(/^[a-z]{3}$/),customer:He.z.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:He.z.uuid(),metadata:He.z.strictObject({grooveProjectId:He.z.uuid(),grooveEnvironmentId:He.z.uuid(),grooveCustomerId:He.z.uuid(),groovePaymentSetupId:He.z.uuid()}),setDefaultPaymentMethod:He.z.boolean(),expiresAt:He.z.iso.datetime({offset:!0})}),Cc=He.z.strictObject({id:He.z.uuid(),provider:He.z.literal("stripe"),status:He.z.enum(["prepared","complete","expired"]),currency:be,makeDefault:He.z.boolean(),url:He.z.url().nullable(),createdAt:He.z.iso.datetime({offset:!0}),expiresAt:He.z.iso.datetime({offset:!0}),completedAt:He.z.iso.datetime({offset:!0}).nullable(),execution:tS.nullable()});var Rt=require("zod"),Om=Rt.z.union([Rt.z.string(),Rt.z.number(),Rt.z.boolean(),Rt.z.null()]),Pm=Rt.z.strictObject({customerId:Rt.z.uuid()}),Cm=Rt.z.strictObject({customerId:Rt.z.uuid(),provider:Rt.z.literal("stripe"),checkedAt:Rt.z.iso.datetime({offset:!0}),status:Rt.z.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Rt.z.number().int().nonnegative(),differences:Rt.z.array(Rt.z.strictObject({subscriptionId:Rt.z.string().startsWith("sub_"),itemId:Rt.z.string().nullable(),field:Rt.z.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Om,actual:Om})).max(1e4)});var Ie=require("zod");var _a=Ie.z.iso.datetime({offset:!0}),Ea=Ie.z.strictObject({createdAt:_a,id:Ie.z.uuid()}),Ra=Ie.z.strictObject({customerId:Ie.z.uuid().optional(),entityId:Ie.z.uuid().optional(),productId:Ie.z.string().min(1).max(256).optional(),provider:Ie.z.enum(["stripe","apple","google","merchant","free"]).optional(),status:Ie.z.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:Ea.optional(),limit:Ie.z.number().int().min(1).max(100).optional()}),_c={id:Ie.z.uuid(),customerId:Ie.z.uuid(),entityId:Ie.z.uuid().nullable(),productId:Ie.z.string().min(1).max(256),productVersionId:Ie.z.uuid(),name:Ie.z.string().min(1).max(120),provider:Ie.z.enum(["stripe","apple","google","merchant","free"]),createdAt:_a},nS=Ie.z.strictObject({..._c,status:Ie.z.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:Ie.z.boolean(),billingSubscriptionId:Ie.z.uuid().nullable()}),rS=Ie.z.strictObject({..._c,status:Ie.z.enum(["active","ended","refunded"]),orderId:Ie.z.uuid().nullable(),transactionId:Ie.z.uuid().nullable(),currency:be.nullable(),amountMinor:Ie.z.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),iS=Ie.z.strictObject({..._c,status:Ie.z.enum(["blocked","resolved"]),conflict:Ie.z.strictObject({detectedAt:_a,blockingMembershipIds:Ie.z.array(Ie.z.uuid()).min(1).max(100),transactionId:Ie.z.uuid()}),resolvedAt:_a.nullable()}),_m=Ra.extend({status:Ie.z.enum(["blocked","resolved"]).optional()}),Em=Ie.z.strictObject({customerId:Ie.z.uuid(),orderId:Ie.z.uuid()}),Rm=Ie.z.strictObject({orderId:Ie.z.uuid(),status:Ie.z.enum(["blocked","resolved"])}),km=Ie.z.strictObject({items:Ie.z.array(nS).max(100),nextCursor:Ea.nullable()}),jm=Ie.z.strictObject({items:Ie.z.array(rS).max(100),nextCursor:Ea.nullable()}),Tm=Ie.z.strictObject({items:Ie.z.array(iS).max(100),nextCursor:Ea.nullable()});var Xe=require("zod");var Nm=Xe.z.union([Xe.z.strictObject({intent:Xe.z.literal("read"),requestId:Xe.z.uuid(),purchaseIntentId:Xe.z.uuid()}),Xe.z.strictObject({requestId:Xe.z.uuid(),provider:Xe.z.literal("apple"),purchaseIntentId:Xe.z.uuid(),productId:Xe.z.string().min(1).max(255).optional(),signedTransaction:Xe.z.string().min(1).max(131072)}),Xe.z.strictObject({requestId:Xe.z.uuid(),provider:Xe.z.literal("google"),purchaseIntentId:Xe.z.uuid(),productId:Xe.z.string().min(1).max(255).optional(),purchaseToken:Xe.z.string().min(1).max(16384)})]),Dm=Xe.z.strictObject({requestId:Xe.z.uuid(),orderId:Xe.z.uuid(),purchaseIntentId:Xe.z.uuid(),status:Xe.z.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:be,refunded:Xe.z.boolean(),completion:Xe.z.strictObject({transactionIds:Xe.z.array(Xe.z.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:Xe.z.boolean()}).nullable()});var L=require("zod"),Rc=L.z.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),oS=L.z.record(L.z.string(),L.z.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),aS=3,so=20,sS=aS*so,Ec=L.z.strictObject({type:L.z.literal("product"),productId:Rc}),Fm={type:L.z.literal("group"),key:L.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:L.z.string().trim().min(1).max(80)},cS=L.z.discriminatedUnion("type",[Ec,L.z.strictObject({...Fm,items:L.z.array(Ec).max(so)})]),uS=L.z.discriminatedUnion("type",[Ec,L.z.strictObject({...Fm,items:L.z.array(cS).max(so)})]),lS=L.z.array(uS).max(so).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>so||i>sS)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function kc(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:kc(t))}var hi=L.z.strictObject({lookupKey:L.z.string().trim().min(1).max(200),displayName:L.z.string().trim().min(1).max(1500),items:lS,metadata:oS}),dS=L.z.strictObject({product:L.z.record(L.z.string(),L.z.json()),prices:L.z.array(L.z.record(L.z.string(),L.z.json())),entitlements:L.z.array(L.z.record(L.z.string(),L.z.json())),freeTrials:L.z.array(L.z.record(L.z.string(),L.z.json())),licenses:L.z.array(L.z.record(L.z.string(),L.z.json()))}),Mm=hi.extend({id:L.z.uuid(),projectId:L.z.uuid(),environmentId:L.z.uuid(),state:L.z.enum(["active","archived"]),isCurrent:L.z.boolean(),revision:L.z.number().int().nonnegative(),publishedVersionId:L.z.uuid().nullable(),createdAt:L.z.iso.datetime({offset:!0})}).superRefine((e,t)=>{e.isCurrent&&(e.state!=="active"||!e.publishedVersionId)&&t.addIssue({code:"custom",message:"Current Offering must be active and published"})}),qm=L.z.strictObject({id:L.z.uuid(),offeringId:L.z.uuid(),projectId:L.z.uuid(),environmentId:L.z.uuid(),version:L.z.number().int().positive(),document:hi,productEvidence:L.z.record(Rc,dS),createdAt:L.z.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=kc(e.document);(!n.length||fS(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"})}),pS=L.z.strictObject({rows:L.z.array(Mm).max(200),versions:L.z.array(qm).max(500)}),XP=L.z.discriminatedUnion("action",[L.z.strictObject({action:L.z.literal("create"),document:hi}),L.z.strictObject({action:L.z.literal("save"),id:L.z.uuid(),revision:L.z.number().int().nonnegative(),document:hi}),L.z.strictObject({action:L.z.enum(["publish","set_current","archive","restore"]),id:L.z.uuid(),revision:L.z.number().int().nonnegative()})]),eC=L.z.strictObject({record:Mm,version:qm.nullable()}),Bm=L.z.discriminatedUnion("type",[L.z.strictObject({type:L.z.literal("current")}),L.z.strictObject({type:L.z.literal("id"),id:L.z.uuid()}),L.z.strictObject({type:L.z.literal("lookup_key"),lookupKey:L.z.string().min(1).max(200)}),L.z.strictObject({type:L.z.literal("version"),versionId:L.z.uuid()})]),mS=L.z.strictObject({internalId:Rc,id:L.z.string(),name:L.z.string().nullable(),version:L.z.number().int().positive(),archived:L.z.boolean()}),tC=pS.extend({products:L.z.array(mS).max(500),pagination:L.z.strictObject({rows:L.z.string().nullable(),versions:L.z.string().nullable(),products:L.z.string().nullable()}).optional()});function fS(e){let t=[];kc(e).length||t.push("Select at least one Product before publishing");function n(r){for(let i of r)i.type==="group"&&(i.items.length||t.push("Every published group requires a Product"),n(i.items))}return n(e.items),t}var co=require("zod");var Vm=co.z.strictObject({id:co.z.uuid(),offeringId:co.z.uuid(),version:co.z.number().int().positive(),document:hi});var xt=require("zod");var fe=require("zod");var qr=require("zod");var ka=qr.z.strictObject({items:qr.z.array(qr.z.strictObject({productVersionId:qr.z.string().min(1).max(200),label:qr.z.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:qr.z.string().min(1).max(200).nullable(),grouping:ga.optional()});function Lm(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 bt=require("zod"),gS=bt.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ja=bt.z.discriminatedUnion("type",[bt.z.object({type:bt.z.literal("fixed"),productVersionId:bt.z.string().min(1).max(200)}).strict(),bt.z.object({type:bt.z.literal("picker"),pickerId:gS,allowedProductVersionIds:bt.z.array(bt.z.string().min(1).max(200)).min(1).max(20)}).strict().refine(e=>new Set(e.allowedProductVersionIds).size===e.allowedProductVersionIds.length,"Product choices must be unique")]),Kn=bt.z.discriminatedUnion("type",[bt.z.object({type:bt.z.literal("modal"),size:bt.z.enum(["sm","md","lg"])}).strict(),bt.z.object({type:bt.z.literal("sheet"),size:bt.z.enum(["sm","md","lg"])}).strict(),bt.z.object({type:bt.z.literal("fullscreen")}).strict(),bt.z.object({type:bt.z.literal("inline")}).strict()]);var jc=fe.z.discriminatedUnion("type",[fe.z.strictObject({type:fe.z.literal("event"),event:fe.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),fe.z.strictObject({type:fe.z.literal("open_url"),url:fe.z.url().refine(e=>new URL(e).protocol==="https:")})]),hS=sn,AS=fe.z.discriminatedUnion("type",[fe.z.object({type:fe.z.literal("checkout"),product:ja}).strict(),fe.z.object({type:fe.z.literal("close")}).strict(),fe.z.object({type:fe.z.literal("action"),action:jc}).strict()]),Ai=fe.z.object({schemaVersion:fe.z.literal(3),kind:fe.z.literal("paywall"),name:fe.z.string().trim().min(1).max(80),presentation:Kn,requirement:er.optional(),products:ka,offeringVersionId:fe.z.uuid().nullable(),offeringId:fe.z.uuid(),screen:hS,buttons:fe.z.record(fe.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),AS)}).strict(),fC=Ai.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 bS(e))t.addIssue({code:"custom",message:r});for(let r of yS(e))t.addIssue({code:"custom",message:r});tr(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 yS(e){let t=e.products.items.map(a=>a.productVersionId),n=kp(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&&(!ha(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 bS(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),Gn(s.root,c=>{let u=c.type==="button"?c.action:c.type==="stack"?c.purchaseAction:void 0;if(u){let l=e.screen.actions.find(m=>m.id===u);l?.type==="navigate"&&r.get(s.id).push(l.pageId);let f=e.buttons[u];s.id!==n.id&&f&&f.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 Um=fe.z.object({id:fe.z.uuid(),projectId:fe.z.uuid(),environmentId:fe.z.uuid(),revision:fe.z.number().int().nonnegative(),state:fe.z.enum(["active","archived"]),publishedVersionId:fe.z.uuid().nullable(),updatedAt:fe.z.iso.datetime({offset:!0}),draft:Ai}).strict(),gC=fe.z.object({rows:fe.z.array(Um).max(200),nextCursor:fe.z.uuid().nullable()}).strict(),hC=Um.omit({draft:!0}).extend({name:fe.z.string(),productCount:fe.z.number().int().nonnegative()}).strict(),AC=fe.z.discriminatedUnion("action",[fe.z.object({action:fe.z.literal("save"),id:fe.z.uuid().nullable(),revision:fe.z.number().int().nonnegative(),document:Ai}).strict(),fe.z.object({action:fe.z.enum(["publish","archive"]),id:fe.z.uuid(),revision:fe.z.number().int().nonnegative()}).strict()]),yC=fe.z.object({paywalls:fe.z.array(fe.z.object({id:fe.z.uuid(),paywallId:fe.z.uuid(),version:fe.z.number().int().positive(),name:fe.z.string().min(1).max(80),presentation:Kn,buttons:Ai.shape.buttons}).strict()).max(500),limited:fe.z.boolean()}).strict();var _e=require("zod");var qt=require("zod");var yi=qt.z.string().regex(/^[a-f0-9]{64}$/),xS=ma.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),zm=qt.z.strictObject({couponDigests:qt.z.record(qt.z.uuid(),yi),variables:qt.z.record(xn,qt.z.record(qt.z.uuid(),qt.z.partialRecord(qt.z.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),qt.z.string()))),locales:qt.z.record(xn,si.extend({nodes:qt.z.record(qt.z.string(),qt.z.strictObject({base:xS})),plans:qt.z.object({}).strict(),pickers:qt.z.object({}).strict()}).omit({paywall:!0}))});var Be=require("zod");var uo=require("zod"),Tc=uo.z.strictObject({eventsEnabled:uo.z.boolean(),experimentViewsEnabled:uo.z.boolean(),featureUsageEnabled:uo.z.boolean()}),vC=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function $m(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}var $=require("zod");var Nc=$.z.tuple([$.z.number().min(0).max(1),$.z.number().min(0).max(1)]).refine(([e,t])=>e<=t),SS=$.z.strictObject({attribute:$.z.string().optional(),seed:$.z.string(),hashVersion:$.z.literal(2),ranges:$.z.array(Nc).max(100)}),IS=$.z.strictObject({id:$.z.string().min(1).max(255),condition:Jt,gate:$.z.boolean().optional()}),vS=$.z.strictObject({key:$.z.string().optional(),name:$.z.string().optional(),passthrough:$.z.boolean().optional()}),Gm={condition:Jt.optional(),parentConditions:$.z.array(IS).max(100).optional(),weights:$.z.array($.z.number().min(0).max(1)).max(20).optional(),coverage:$.z.number().min(0).max(1).optional(),hashAttribute:$.z.string().optional(),fallbackAttribute:$.z.string().optional(),hashVersion:$.z.literal(2).optional(),disableStickyBucketing:$.z.boolean().optional(),bucketVersion:$.z.number().int().nonnegative().optional(),minBucketVersion:$.z.number().int().nonnegative().optional(),filters:$.z.array(SS).max(100).optional(),ranges:$.z.array(Nc).max(20).optional(),meta:$.z.array(vS).max(20).optional(),seed:$.z.string().optional(),name:$.z.string().optional(),phase:$.z.string().optional()},bi=$.z.strictObject({...Gm,key:$.z.string().min(1).max(255),variations:$.z.tuple([Se,Se]).rest(Se).refine(e=>e.length<=20),urlPatterns:$.z.array($.z.strictObject({include:$.z.boolean(),type:$.z.enum(["regex","simple"]),pattern:$.z.string()})).max(100).optional(),force:$.z.number().int().nonnegative().optional(),active:$.z.boolean().optional(),persistQueryString:$.z.boolean().optional()}),Dc=$.z.strictObject({value:Se,variationId:$.z.number().int(),key:$.z.string(),name:$.z.string().optional(),bucket:$.z.number().optional(),passthrough:$.z.boolean().optional(),inExperiment:$.z.boolean(),hashUsed:$.z.boolean().optional(),hashAttribute:$.z.string(),hashValue:$.z.string(),featureId:$.z.string().nullable(),stickyBucketUsed:$.z.boolean().optional()}),wS=$.z.strictObject({...Gm,id:$.z.string().max(255).optional(),force:Se.optional(),variations:$.z.array(Se).min(2).max(20).optional(),key:$.z.string().optional(),range:Nc.optional(),tracks:$.z.array($.z.strictObject({experiment:bi,result:Dc})).max(100).optional()}),OS=$.z.strictObject({defaultValue:Se.optional(),rules:$.z.array(wS).max(500).optional()}),lo=$.z.record($.z.string(),$.z.union([$.z.strictObject({type:$.z.literal("hashed"),attributeKey:$.z.string(),values:$.z.array($.z.string().regex(/^[a-f0-9]{64}$/))}),$.z.strictObject({type:$.z.literal("list"),attributeKey:$.z.string(),values:$.z.array($.z.union([$.z.string(),$.z.number()]))}),$.z.strictObject({type:$.z.literal("condition"),condition:Jt})])),gn=$.z.strictObject({scope:Ne,generation:$.z.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:$.z.iso.datetime({offset:!0}),expiresAt:$.z.iso.datetime({offset:!0}).nullable(),features:$.z.record($.z.string(),OS),savedGroups:lo,experiments:$.z.record($.z.uuid(),bi)});var po=gn.extend({analyticsConfig:Tc,remoteFeatures:Be.z.array(Be.z.string().min(1).max(255)).max(500)}),Fc=po.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"})}),Km=Be.z.strictObject({attributes:Ot,features:Be.z.array(Be.z.string().min(1).max(255)).max(500).optional(),customerId:Be.z.uuid().optional()}),PS=Be.z.strictObject({value:Se,source:Be.z.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:Be.z.boolean(),off:Be.z.boolean(),ruleId:Be.z.string(),experimentResult:Dc.optional()}),Ta=Be.z.strictObject({generation:gn.shape.generation,evaluatedAt:gn.shape.evaluatedAt,expiresAt:gn.shape.expiresAt,features:Be.z.record(Be.z.string(),PS),merchandiseContext:Be.z.strictObject({merchandiseId:Be.z.uuid(),merchandise:Ot}).optional()}),Hm=Be.z.strictObject({customerId:Be.z.uuid().optional(),events:Be.z.array(Be.z.strictObject({eventUuid:Be.z.uuid(),timestamp:Be.z.iso.datetime({offset:!0}),name:Be.z.string().min(1).max(255),merchandise:Ed.optional(),properties:Be.z.record(Be.z.string(),Se).default({}),deviceId:Be.z.string().min(1).max(255).optional(),sessionId:Be.z.string().min(1).max(255).optional()})).min(1).max(100)}),Qm=Be.z.strictObject({inserted:Be.z.number().int().nonnegative(),duplicates:Be.z.number().int().nonnegative(),rejected:Be.z.number().int().nonnegative(),skipped:Be.z.number().int().nonnegative(),analyticsConfig:Tc});var U=require("zod");var Jm=require("zod"),Zm=Jm.z.enum(["funnel-run/1","funnel-process/1"]),Wm="funnel-process/1";function Mc(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(Aa(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 Ym(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>Ym(t)??[])}}function CS(e){let t=e.pages.map(i=>{let a=Ym(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(Aa({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 Xm(e,t=[]){let n=sn.parse(structuredClone(CS(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=Mc(n,t);if(i.length)throw new Error(i.join("; "));return n}var H=require("zod");var M=require("zod");var ut=require("zod"),Na=ut.z.strictObject({schemaVersion:ut.z.literal(1),renderKey:ut.z.string().min(1).max(256),routeTemplate:ut.z.string().startsWith("/").max(2048),selectors:ut.z.array(ut.z.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:ut.z.array(ut.z.number().int().min(0)).min(1),absent:ut.z.array(ut.z.number().int().min(0))}).superRefine((e,t)=>{let n=[...e.present,...e.absent];(new Set(e.selectors).size!==e.selectors.length||new Set(n).size!==n.length||n.length!==e.selectors.length||n.some(r=>r>=e.selectors.length))&&t.addIssue({code:"custom",message:"Incomplete or ambiguous render signature"})}),ef=ut.z.strictObject({renderKey:ut.z.string().min(1).max(256),routeKey:ut.z.string().min(1).max(256),stateKey:ut.z.string().min(1).max(256),documentKey:ut.z.string().min(1).max(256),documentHash:ut.z.string().regex(/^[a-f0-9]{64}$/),compositionKey:ut.z.string().min(1).max(256),entryMode:ut.z.enum(["hard","soft"]),match:ut.z.strictObject({present:ut.z.array(ut.z.number().int().min(0)),absent:ut.z.array(ut.z.number().int().min(0))})});var ir=require("zod"),_S=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],qc="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",ES=ir.z.string().regex(new RegExp(`^${qc}/${qc}/${qc}/manifest\\.json$`)),tf=ir.z.strictObject({kind:ir.z.literal("gcs-resumable"),url:ir.z.url(),bucket:ir.z.enum(_S),objectKey:ES,byteLength:ir.z.number().int().positive(),expiresAt:ir.z.iso.datetime()}).superRefine((e,t)=>{let n=new URL(e.url),r=n.searchParams,i=["uploadType","upload_id","name","upload_protocol","ifGenerationMatch"];(n.origin!=="https://storage.googleapis.com"||n.username||n.password||n.hash||n.pathname!==`/upload/storage/v1/b/${e.bucket}/o`||[...r.keys()].some(a=>!i.includes(a)||r.getAll(a).length!==1)||r.get("uploadType")!=="resumable"||!/^[A-Za-z0-9_-]{1,4096}$/.test(r.get("upload_id")??"")||r.has("name")&&r.get("name")!==`app-manifests/${e.objectKey}`||r.has("upload_protocol")&&r.get("upload_protocol")!=="resumable"||r.has("ifGenerationMatch")&&r.get("ifGenerationMatch")!=="0")&&t.addIssue({code:"custom",message:"Invalid IAM upload capability"})});var ht=M.z.string().min(1).max(256),un=M.z.string().regex(/^[a-f0-9]{64}$/),Da=M.z.strictObject({versionId:M.z.uuid(),manifestDigest:un,sourceGraphDigest:un,pageKey:ht,stateKey:ht,documentKey:ht,documentHash:un,elementKey:ht.optional(),nodeId:ht.optional(),contentHash:un.optional(),renderKey:ht.optional()}),nf=M.z.strictObject({pageKey:ht,documentKey:ht,expectedDocumentHash:un,renderKey:ht.optional(),nodeId:ht,elementKey:ht,expectedContentHash:un,property:M.z.enum(["text","fontSize","color"]),value:M.z.union([M.z.string().max(4e3),M.z.number().finite()])}),rf=M.z.strictObject({versionId:M.z.uuid(),manifestDigest:un,sourceGraphDigest:un,pageKey:ht,stateKey:ht,documentKey:ht,documentHash:un,renderKey:ht.optional(),patches:M.z.array(nf.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),RS=/^[a-z][a-z0-9-]{0,39}$/,mo=M.z.string().regex(RS),Vc=M.z.enum(["web","ios","android"]),VC=M.z.discriminatedUnion("action",[M.z.strictObject({action:M.z.literal("register"),requestId:M.z.uuid(),client:mo,platform:Vc,label:M.z.string().trim().min(1).max(100),sha256:un,bytes:M.z.number().int().min(1),transferBytes:M.z.number().int().min(1)}),M.z.strictObject({action:M.z.literal("complete"),versionId:M.z.uuid()}),M.z.strictObject({action:M.z.literal("current"),versionId:M.z.uuid(),expectedCurrent:M.z.uuid().nullable()}),M.z.strictObject({action:M.z.literal("delivery"),enabled:M.z.boolean()}),M.z.strictObject({action:M.z.literal("changes"),versionId:M.z.uuid(),experimentId:M.z.uuid(),variationId:ht,changesetId:M.z.uuid().nullable(),expectedRevision:un.nullable(),editorUrl:M.z.string().url().max(2048),patches:M.z.array(nf).max(200)})]),Lc=M.z.strictObject({id:M.z.uuid(),projectId:M.z.uuid(),environmentId:M.z.uuid(),clientKey:mo,platform:Vc,label:M.z.string(),sha256:un,bytes:M.z.number().int().positive(),objectKey:M.z.string(),state:M.z.enum(["uploading","ready","rejected"]),isCurrent:M.z.boolean(),revision:M.z.number().int().nonnegative(),createdAt:M.z.string(),expiresAt:M.z.string(),readyAt:M.z.string().nullable(),summary:M.z.record(M.z.string(),M.z.json()),routeTree:M.z.json().nullable(),validation:M.z.record(M.z.string(),M.z.json())}),kS=M.z.strictObject({key:mo,platform:Vc,currentId:M.z.uuid().nullable()}),LC=M.z.strictObject({rows:M.z.array(Lc).max(100),nextCursor:M.z.uuid().nullable(),clients:M.z.array(kS).max(20)}),Bc=M.z.strictObject({storedBytes:M.z.number().int().nonnegative(),reservedBytes:M.z.number().int().nonnegative(),chargedBytes:M.z.number().int().nonnegative(),versions:M.z.number().int().nonnegative(),objects:M.z.number().int().nonnegative(),orphanObjects:M.z.number().int().nonnegative(),missingReadyObjects:M.z.number().int().nonnegative(),unknownObjectSizes:M.z.number().int().nonnegative(),byteLimit:M.z.number().int().positive(),versionLimit:M.z.number().int().positive(),remainingBytes:M.z.number().int().nonnegative()}),UC=M.z.strictObject({asOf:M.z.iso.datetime({offset:!0}),reclamation:M.z.literal("manual-review-required"),buckets:M.z.strictObject({source:Bc,runtime:Bc,previews:Bc})}),zC=M.z.strictObject({version:Lc,actorId:M.z.uuid(),claims:M.z.record(M.z.string(),M.z.json())}),$C=M.z.strictObject({version:Lc,upload:tf.nullable()}),GC=M.z.object({format:M.z.literal("indiana-route-state-index"),schemaVersion:M.z.literal(3),routes:M.z.array(M.z.object({routeKey:ht,path:M.z.string(),documentKey:ht,documentHash:un,initialStateKey:ht,initialRenderKey:ht})),renders:M.z.array(ef)}).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"})}),KC=M.z.strictObject({rows:M.z.array(M.z.object({id:M.z.uuid(),name:M.z.string(),status:M.z.string(),variations:M.z.array(M.z.object({id:ht,key:ht,name:M.z.string().optional()}).loose())}).loose()),limited:M.z.boolean()}),HC=M.z.strictObject({enabled:M.z.boolean(),allowedOrigins:M.z.array(M.z.string())});var Br=require("zod");var of=Br.z.strictObject({id:Br.z.uuid(),name:Br.z.string().trim().min(1).max(80),client:mo,source:Da,event:Br.z.enum(["screen_enter","button_click"]),cooldownSeconds:Br.z.number().int().min(0).max(2592e3),behavior:Br.z.literal("observe")}).superRefine((e,t)=>{e.event==="button_click"&&(!e.source.nodeId||!e.source.elementKey)&&t.addIssue({code:"custom",path:["source"],message:"Choose a uniquely bound button"})});var Le=require("zod");var Uc=Se,jS=["parameters","answers","results","variables"];function zc(e){return jS.some(t=>e===t||e.startsWith(t+"."))}function $c(e){let t={};for(let[r,i]of Object.entries(ya(e.declarations,e))){let a=r.split(".");if(a.some(c=>["__proto__","constructor","prototype"].includes(c)))throw new Error("Reserved result path");let o=t;for(let c of a.slice(0,-1)){Object.hasOwn(o,c)||(o[c]={});let u=o[c];if(!u||typeof u!="object"||Array.isArray(u))throw new Error("Ambiguous result path");o=u}let s=a.at(-1);if(s===void 0)throw new Error("Empty result path");o[s]=i}return{...Object.fromEntries(Object.entries(e.attributes).filter(([r])=>!zc(r))),variables:t}}var dt=require("zod");var Fa=dt.z.discriminatedUnion("kind",[dt.z.object({kind:dt.z.literal("ledger"),cursor:pa}).strict(),dt.z.object({kind:dt.z.literal("billing"),cursor:dt.z.uuid()}).strict()]),TS=dt.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),or=dt.z.record(dt.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),dt.z.union([dt.z.string().max(500),dt.z.boolean(),dt.z.array(dt.z.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),NS=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function Gc(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>Gc(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||NS.test(n)||Gc(r,t+1)))}var DS=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,ar=dt.z.record(TS,Se).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!Gc(e)&&!DS.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var af=dt.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ma=dt.z.array(dt.z.object({variable:af,componentId:af,required:dt.z.boolean()}).strict()).max(40).refine(e=>new Set(e.map(t=>t.variable)).size===e.length&&new Set(e.map(t=>t.componentId)).size===e.length,"Input bindings must be unique"),r_=dt.z.object({bindings:Ma,answers:or,values:dt.z.record(dt.z.string(),Se).optional()}).strict();var sf=require("zod"),qa=sf.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var Kc=Le.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),cf=Le.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),uf=ar.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),Hc=Le.z.record(Kc,Le.z.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),FS=kn,lf=Le.z.strictObject({type:Le.z.literal("external_task"),endpointId:Le.z.uuid(),taskKey:Kc,inputs:Le.z.record(Kc,FS).refine(e=>Object.keys(e).length<=20),outputs:Hc}),df=Le.z.strictObject({maxAttempts:Le.z.number().int().min(1).max(5),retryDelaySeconds:Le.z.number().int().min(1).max(30),backoff:Le.z.enum(["fixed","exponential"]),requestTimeoutSeconds:Le.z.number().int().min(1).max(10),timeoutSeconds:Le.z.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var d_=Le.z.strictObject({outcome:Le.z.enum(["success","failure"]),data:uf});var p_=Le.z.discriminatedUnion("operation",[Le.z.strictObject({operation:Le.z.literal("signal"),runId:Le.z.uuid(),nodeId:cf,eventName:qa,eventId:Le.z.uuid(),data:uf}),Le.z.strictObject({operation:Le.z.literal("read_results"),runId:Le.z.uuid()})]),m_=Le.z.strictObject({scope:Ne,runId:Le.z.uuid(),eventId:Le.z.uuid(),accepted:Le.z.boolean()}),MS=Le.z.record(cf,Uc),f_=Le.z.strictObject({scope:Ne,runId:Le.z.uuid(),results:MS});var On={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},pf="00000000-0000-0000-0000-000000000000";var Q=require("zod");var Qe=require("zod");var b_=Qe.z.enum(["local","remote"]),Qc=Qe.z.strictObject({port:Qe.z.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:Se.optional(),sticky:Qe.z.array(Qe.z.strictObject({expected:Vi.nullable(),next:Vi})).max(100),exposures:Qe.z.array(Se).max(100),features:Qe.z.array(Se).max(100)}),mf=Qe.z.strictObject({type:Qe.z.literal("evaluate"),receiptId:Qe.z.uuid(),environmentId:Qe.z.uuid(),policyRevision:Qe.z.number().int().nonnegative(),attributes:Ot,sticky:Qe.z.record(Qe.z.string(),Vi)}),ff=mf.extend({runId:Qe.z.uuid(),versionId:Qe.z.uuid(),nodeId:Qe.z.string().min(1).max(64),visit:Qe.z.number().int().nonnegative(),revision:Qe.z.number().int().nonnegative()}),Jc=mf.omit({type:!0,receiptId:!0}).extend({type:Qe.z.literal("evaluate_segment")}),gf=Qe.z.strictObject({nodeId:Qe.z.string().min(1).max(64),result:Qc}),hf=Jc.extend({runId:Qe.z.uuid(),versionId:Qe.z.uuid(),nodeId:Qe.z.string().min(1).max(64),visit:Qe.z.number().int().nonnegative(),revision:Qe.z.number().int().nonnegative(),parameters:ar,answers:or,variables:Qe.z.record(Qe.z.string(),Se)});var ce=require("zod");var Zc=ce.z.array(ce.z.string().trim().min(1).max(40).refine(e=>!e.includes(","),"\u6807\u7B7E\u4E0D\u80FD\u5305\u542B\u9017\u53F7")).max(20).refine(e=>new Set(e).size===e.length,"\u6807\u7B7E\u4E0D\u80FD\u91CD\u590D"),Ba=ce.z.intersection(Ot,ce.z.looseObject({tags:Zc.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),Va=ce.z.string().trim().max(80),La=ce.z.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),Ua=ce.z.union([ce.z.email().max(254),ce.z.literal("")]),za=ce.z.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),Af=ce.z.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),yf=ce.z.object({externalUserId:Af.optional(),name:Va.default(""),email:Ua.default(""),phone:La.optional(),attributes:Ba.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),Vr=ce.z.discriminatedUnion("type",[ce.z.strictObject({type:ce.z.literal("id"),value:ce.z.uuid()}),ce.z.strictObject({type:ce.z.literal("externalUserId"),value:Af})]),xi=ce.z.strictObject({name:Va.optional(),email:Ua.optional(),phone:La.optional(),attributes:Ba.optional(),fingerprint:za.optional()}),$a=e=>!e.customerData||e.customer?.type==="externalUserId",Ga="customerData requires an externalUserId customer",Si=ce.z.object({id:ce.z.uuid(),externalUserId:ce.z.string().min(1).max(255).nullable(),name:Va,email:Ua,phone:La.optional(),attributes:Ba,createdAt:ce.z.iso.datetime()}).strict(),bf=ce.z.object({customer:Si,changed:ce.z.boolean(),replayed:ce.z.boolean()}).strict(),qS=ce.z.discriminatedUnion("type",[ce.z.object({type:ce.z.literal("id"),value:ce.z.uuid()}).strict(),ce.z.object({type:ce.z.literal("externalUserId"),value:ce.z.string().trim().min(1).max(255)}).strict()]),BS=ce.z.object({name:Va.optional(),email:Ua.optional(),phone:La.optional(),attributes:Ba.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:ce.z.array(ce.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:ce.z.strictObject({add:Zc,remove:Zc}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),Wc=ce.z.object({lookup:qS}).strict(),xf=Wc.extend({requestId:ce.z.uuid(),patch:BS}).strict(),Sf=ce.z.object({search:ce.z.string().trim().max(200).default(""),tag:ce.z.string().trim().max(40).default(""),planId:ce.z.string().max(200).default(""),versionId:ce.z.string().max(200).default(""),holdingStatus:ce.z.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:ce.z.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:ce.z.union([ce.z.iso.datetime(),ce.z.literal("")]).default(""),createdUntil:ce.z.union([ce.z.iso.datetime(),ce.z.literal("")]).default(""),offset:ce.z.coerce.number().int().min(0).max(1e5).default(0),limit:ce.z.coerce.number().int().min(1).max(100).default(50)}).strict(),If=ce.z.object({customers:Si.array(),hasMore:ce.z.boolean(),total:ce.z.number().int().nonnegative().nullable(),evaluatedAt:ce.z.iso.datetime()}).strict();var fo=Q.z.discriminatedUnion("type",[Q.z.strictObject({type:Q.z.literal("literal"),value:Se}),Q.z.strictObject({type:Q.z.literal("variable"),key:yt,path:wn.optional()}),Q.z.strictObject({type:Q.z.literal("feature"),featureKey:Q.z.string().min(1).max(128)})]),VS=Q.z.strictObject({requestId:Q.z.uuid(),decisionId:Q.z.uuid(),customerId:Q.z.uuid(),externalUserId:Q.z.string().min(1).max(255).nullable(),versionId:Q.z.uuid(),receiptId:Q.z.uuid(),value:Se}),LS={funnelId:Q.z.uuid(),requestId:Q.z.uuid(),customer:Vr,customerData:xi.optional(),attributes:Ot.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},E_=Q.z.discriminatedUnion("operation",[Q.z.strictObject({operation:Q.z.literal("decide"),...LS}).refine($a,Ga),Q.z.strictObject({operation:Q.z.literal("read_decision"),decisionId:Q.z.uuid()}),Q.z.strictObject({operation:Q.z.literal("evaluate_decision"),decisionId:Q.z.uuid(),requestId:Q.z.uuid(),nodeId:Q.z.string().min(1).max(64),visit:Q.z.number().int().nonnegative(),revision:Q.z.number().int().nonnegative(),receiptId:Q.z.uuid(),policyRevision:Q.z.number().int().nonnegative(),generation:Q.z.string().min(1).max(256),result:Qc}),Q.z.strictObject({operation:Q.z.literal("feature_config"),funnelId:Q.z.uuid()}),Q.z.strictObject({operation:Q.z.literal("commit_decision_segment"),decisionId:Q.z.uuid(),requestId:Q.z.uuid(),nodeId:Q.z.string().min(1).max(64),visit:Q.z.number().int().nonnegative(),revision:Q.z.number().int().nonnegative(),policyRevision:Q.z.number().int().nonnegative(),generation:Q.z.string().min(1).max(256),steps:Q.z.array(gf).max(32),boundary:Q.z.strictObject({nodeId:Q.z.string().min(1).max(64),visit:Q.z.number().int().nonnegative()}).optional()}),Q.z.strictObject({operation:Q.z.literal("segment_configuration"),funnelId:Q.z.uuid(),versionId:Q.z.uuid()}),Q.z.strictObject({operation:Q.z.literal("configuration"),funnelId:Q.z.uuid(),versionId:Q.z.uuid().optional()}),Q.z.strictObject({operation:Q.z.literal("local_configuration"),funnelId:Q.z.uuid()}),Q.z.strictObject({operation:Q.z.literal("report_used"),decisionId:Q.z.uuid(),eventId:Q.z.uuid(),occurredAt:Q.z.iso.datetime({offset:!0}),reference:Q.z.string().min(1).max(128).optional()})]),R_=Q.z.strictObject({scope:Ne,decisionId:Q.z.uuid(),requestId:Q.z.uuid(),status:Q.z.enum(["pending","completed","failed"]),decision:VS.nullable(),evaluation:Q.z.discriminatedUnion("type",[ff,hf]).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"),k_=Q.z.strictObject({scope:Ne,decisionId:Q.z.uuid(),eventId:Q.z.uuid(),source:Q.z.literal("caller_reported")});var kt=require("zod");var vf=kt.z.strictObject({type:kt.z.literal("bundle"),paywall:kn.optional(),offering:kn.optional(),coupons:kn,data:kn}),US=e=>kt.z.strictObject({type:kt.z.literal(e),id:kt.z.uuid()}),F_=kt.z.strictObject({type:kt.z.literal("bundle"),paywallVersionId:kt.z.uuid().optional(),offeringVersionId:kt.z.uuid().optional(),couponIds:kt.z.array(kt.z.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:Se});var M_=kt.z.strictObject({type:kt.z.literal("bundle"),offering:US("offering_version").nullable(),paywall:kt.z.strictObject({versionId:kt.z.uuid(),paywallId:kt.z.uuid(),offeringVersionId:kt.z.uuid()}).nullable(),coupons:kt.z.array(Li).max(20),data:Se});var hn=require("zod");var ln=require("zod");var wf=ln.z.union([ln.z.string(),ln.z.number().finite(),ln.z.boolean(),ln.z.null()]),zS=ln.z.union([wf,ln.z.array(wf).min(1).max(20)]),$S=ln.z.record(wn,zS).refine(e=>Object.keys(e).length<=10),Of=ln.z.strictObject({path:wn,type:ln.z.enum(["string","number","boolean","strings"]),nullable:ln.z.boolean().optional(),aggregation:ln.z.enum(["count","exists"]).optional(),where:$S.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 GS=["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"],Pf=hn.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),KS=kn,Cf=hn.z.discriminatedUnion("type",[lf,hn.z.strictObject({type:hn.z.literal("claim_offer"),coupon:kn}),hn.z.strictObject({type:hn.z.literal("event"),event:Pf}),hn.z.strictObject({type:hn.z.literal("api"),operation:hn.z.enum(GS),inputs:hn.z.record(wn,KS).refine(e=>Object.keys(e).length<=40),outputs:hn.z.record(Pf,Of).refine(e=>Object.keys(e).length<=20)})]);var ct=qa,HS=H.z.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),dn={id:ct,name:H.z.string().trim().min(1).max(80),position:H.z.strictObject({x:H.z.number().finite(),y:H.z.number().finite()}).optional()},QS={success:ct,cancel:ct,unavailable:ct,failure:ct},Yc=H.z.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),Xc=H.z.enum(["same_window","new_window"]),JS=H.z.discriminatedUnion("type",[H.z.strictObject({...dn,type:H.z.literal("entry"),next:ct,triggers:H.z.array(of).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),H.z.strictObject({...dn,type:H.z.literal("screen"),screenId:ct,presentation:Kn,outputs:H.z.record(ct,ct),offering:H.z.discriminatedUnion("source",[H.z.strictObject({source:H.z.literal("variable"),key:yt}),H.z.strictObject({source:H.z.literal("fixed"),versionId:H.z.uuid()})]).optional()}),H.z.strictObject({...dn,type:H.z.literal("offering"),configuration:H.z.discriminatedUnion("source",[H.z.strictObject({source:H.z.literal("fixed"),versionId:H.z.uuid()}),H.z.strictObject({source:H.z.literal("feature"),featureKey:H.z.string().min(1).max(128)})]),writes:H.z.strictObject({value:yt}),next:ct}),H.z.strictObject({...dn,type:H.z.literal("coupon"),couponId:H.z.uuid(),writes:H.z.strictObject({value:yt}),next:ct}),H.z.strictObject({...dn,type:H.z.literal("coupons"),couponIds:H.z.array(H.z.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:H.z.strictObject({value:yt}),next:ct}),H.z.strictObject({...dn,type:H.z.literal("output"),value:H.z.discriminatedUnion("type",[...fo.options,vf,H.z.strictObject({type:H.z.literal("selection"),screenId:ct,offeringKey:yt})])}),H.z.strictObject({...dn,type:H.z.literal("condition"),cases:H.z.array(H.z.strictObject({condition:Jt,target:ct})).min(1).max(50),default:ct}),H.z.strictObject({...dn,type:H.z.literal("feature"),featureKey:H.z.string().min(1).max(128),writes:H.z.strictObject({value:yt}),next:ct}),H.z.strictObject({...dn,type:H.z.literal("split"),experimentId:H.z.uuid(),applyPageExperiment:H.z.literal(!0).optional(),routes:H.z.record(HS,ct).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:ct}),H.z.strictObject({...dn,type:H.z.literal("action"),...QS,execution:df,action:Cf,writes:fc.optional()}),H.z.strictObject({...dn,type:H.z.literal("external_page"),appManifest:Da.optional(),url:Yc,openIn:Xc,opened:ct,failed:ct}),H.z.strictObject({...dn,type:H.z.literal("end"),outcome:H.z.enum(["completed","closed","ineligible","failed"]),output:fo.optional()}),H.z.strictObject({...dn,type:H.z.literal("wait"),writes:fc.optional(),wait:H.z.discriminatedUnion("type",[H.z.strictObject({type:H.z.literal("duration"),delaySeconds:H.z.number().int().min(1).max(2592e3),elapsed:ct}),H.z.strictObject({type:H.z.literal("event"),eventName:ct,outputs:Hc,timeoutSeconds:H.z.number().int().min(1).max(2592e3),received:ct,timeout:ct})])})]),eu=H.z.strictObject({version:H.z.literal(5),entry:ct,nodes:H.z.array(JS).min(1).max(On.flowNodes)}),tu=eu.superRefine((e,t)=>{ZS(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function Ka(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 ZS(e,t){let n=[],r=new Map(e.nodes.map(l=>[l.id,l])),i=(l,f,m)=>{n.push(l),t?.({message:l,reason:f,path:m?["nodes",e.nodes.indexOf(m)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(l=>l.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(l=>l.type==="screen").length>On.pages||e.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>On.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let l of e.nodes){for(let f of Ka(l))f===e.entry&&i("An entry cannot be a transition target","entryTarget",l),r.has(f)||i(`Missing target ${f}`,"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 f of Ka(r.get(l)))u(f);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 nu={maxTransitions:1e4,runTimeoutSeconds:2592e3};function _f(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 Yn(c.condition))u.startsWith("variables.")&&a(u.slice(10),!0)}if(e.type==="screen"&&e.offering?.source==="variable"&&a(e.offering.key),e.type==="action"&&(e.action.type==="api"||e.action.type==="external_task"))for(let s of Object.values(e.action.inputs))s.source==="variable"&&a(s.key);e.type==="action"&&e.action.type==="claim_offer"&&e.action.coupon.source==="variable"&&a(e.action.coupon.key);let o=e.type==="output"?e.value:e.type==="end"?e.output:null;if(o?.type==="variable"&&a(o.key),o?.type==="bundle")for(let s of[o.paywall,o.offering,o.coupons,o.data])s?.source==="variable"&&a(s.key);return o?.type==="selection"&&a(o.offeringKey),[...i]}var q=require("zod");var Ii=q.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Ha=e=>q.z.record(q.z.string(),Se).refine(t=>cn(t)<=e,"Funnel evidence exceeds its byte budget"),l1=q.z.enum(["local_segment","evaluation","presentation","timer","event","operation"]),iu=q.z.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),ou=q.z.discriminatedUnion("type",[q.z.strictObject({type:q.z.literal("flag"),key:q.z.string().min(1).max(128)}),q.z.strictObject({type:q.z.literal("experiment"),id:q.z.uuid()}),q.z.strictObject({type:q.z.literal("saved_group"),id:q.z.uuid()}),q.z.strictObject({type:q.z.literal("config"),key:q.z.string().min(1).max(128)}),q.z.strictObject({type:q.z.literal("constant"),key:q.z.string().min(1).max(128)}),q.z.strictObject({type:q.z.literal("paywall_version"),id:q.z.uuid()}),q.z.strictObject({type:q.z.literal("offering_version"),id:q.z.uuid()}),q.z.strictObject({type:q.z.literal("reward"),id:q.z.uuid()})]),go=q.z.strictObject({schemaVersion:q.z.literal(1),kind:iu,selector:ou.nullable(),context:Ha(131072),contract:q.z.strictObject({version:q.z.number().int().positive(),evaluator:q.z.string().min(1).max(128),policyRevision:q.z.number().int().nonnegative()})}).refine(e=>cn(e)<=131072,"Node input exceeds its byte budget"),Ef=q.z.strictObject({schemaVersion:q.z.literal(1),kind:iu,outcome:q.z.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:Ha(131072),route:q.z.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:Ha(131072)}).refine(e=>cn(e)<=131072,"Node result exceeds its byte budget"),d1=q.z.strictObject({schemaVersion:q.z.literal(1),operations:q.z.record(Ii,q.z.strictObject({attempts:q.z.number().int().nonnegative(),maxAttempts:q.z.number().int().min(1).max(5),deadlineAt:q.z.iso.datetime({offset:!0}),retryAt:q.z.iso.datetime({offset:!0}).nullable(),error:q.z.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:q.z.strictObject({type:Ii,id:q.z.uuid()}).nullable()}))}).refine(e=>cn(e)<=65536,"Execution state exceeds its byte budget"),Lr={receiptId:q.z.uuid()},ru=q.z.iso.datetime({offset:!0}),p1=q.z.discriminatedUnion("type",[q.z.strictObject({type:q.z.literal("node_entered"),details:q.z.strictObject({kind:iu})}),q.z.strictObject({type:q.z.literal("presentation_shown"),details:q.z.strictObject({...Lr,source:q.z.literal("client"),occurredAt:ru.optional()})}),q.z.strictObject({type:q.z.literal("decision_accepted"),details:q.z.strictObject(Lr)}),q.z.strictObject({type:q.z.literal("signal_received"),details:q.z.strictObject({signalId:q.z.uuid(),nodeId:Ii,eventName:Ii,data:Ha(8192),source:q.z.literal("server"),occurredAt:ru})}),q.z.strictObject({type:q.z.literal("signal_consumed"),details:q.z.strictObject({...Lr,signalId:q.z.uuid()})}),q.z.strictObject({type:q.z.literal("wait_elapsed"),details:q.z.strictObject(Lr)}),q.z.strictObject({type:q.z.literal("wait_timeout"),details:q.z.strictObject(Lr)}),q.z.strictObject({type:q.z.literal("operation_completed"),details:q.z.strictObject({...Lr,operation:Ii,reference:q.z.strictObject({type:Ii,id:q.z.uuid()}).nullable()})}),q.z.strictObject({type:q.z.literal("execution_recovered"),details:q.z.strictObject({generation:q.z.number().int().positive(),reason:q.z.enum(["interrupted","expired_lease","delivery_failed"])})}),q.z.strictObject({type:q.z.literal("execution_failed"),details:q.z.strictObject({generation:q.z.number().int().positive(),code:q.z.string().regex(/^[a-z_]{1,64}$/)})}),q.z.strictObject({type:q.z.literal("run_completed"),details:q.z.strictObject({outcome:q.z.enum(["completed","ineligible","failed"])})}),q.z.strictObject({type:q.z.literal("run_closed"),details:q.z.strictObject({source:q.z.enum(["client","server","expiry"])})}),q.z.strictObject({type:q.z.literal("treatment_used"),details:q.z.strictObject({...Lr,source:q.z.enum(["client","server"]),occurredAt:ru,reference:q.z.string().min(1).max(128).optional()})})]);var An=U.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),WS=U.z.discriminatedUnion("type",[U.z.strictObject({id:An,type:U.z.literal("owned"),publicData:zm.optional(),document:sn.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")}),U.z.strictObject({id:An,type:U.z.literal("paywall"),paywallVersionId:U.z.uuid()})]),au={executionContract:Zm.optional(),kind:U.z.literal("funnel"),schemaVersion:U.z.literal(4),screens:U.z.array(WS).max(On.pages),references:U.z.record(An,ou).refine(e=>Object.keys(e).length<=500),inputs:U.z.array(U.z.strictObject({variable:An,screenId:An,componentId:An,required:U.z.boolean()})).max(On.questions),variables:U.z.record(yt,ui).refine(e=>Object.keys(e).length<=On.logicNodes),outputSchema:ci,execution:U.z.strictObject({runTimeoutSeconds:U.z.number().int().min(1).max(nu.runTimeoutSeconds),maxTransitions:U.z.number().int().min(1).max(nu.maxTransitions)})},k1=U.z.strictObject({...au,graph:eu});function YS(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 Ja(e){return Array.isArray(e)?e.some(Ja):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===pf:Ja(n))}function XS(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=Xm(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&&!ro(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}),YS(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"&&Ja(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&Ja(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function Rf(e,t){for(let{message:n,reason:r,path:i}of XS(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function kf(e,t){let n=(h,d,A=[])=>t.addIssue({code:"custom",message:h,path:A,params:{reason:d}}),r=Object.values(e.references),i=new Map(e.screens.map(h=>[h.id,h])),a=(h,d)=>r.some(A=>A.type===h&&("id"in A?A.id:A.key)===d);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let o=e.graph.nodes.filter(h=>h.type==="screen");(o.length!==i.size||o.some(h=>!i.has(h.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(h=>c.some(d=>h!==d&&d.startsWith(h+".")))&&n("Variable paths must not overlap","variable");function u(h,d){Object.hasOwn(e.variables,h)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(d)]);let A=s.get(h)??new Set;A.add(d.id),s.set(h,A)}for(let[h,d]of e.graph.nodes.entries()){let A=["graph","nodes",h],k=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;k&&!a("flag",k)&&n("Flag selectors require an explicit GB resource reference","feature",A);let g=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):[],y="writes"in d?d.writes??{}:{};(g.length!==Object.keys(y).length||g.some(w=>!Object.hasOwn(y,w))||new Set(Object.values(y)).size!==Object.values(y).length)&&n("Node writes must map every named output exactly once","variable",A);for(let[w,C]of Object.entries(y)){u(C,d);let j=e.variables[C],E=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[w]:d.type==="wait"&&d.wait.type==="event"?d.wait.outputs[w]:void 0;(j?.source.type!=="node"||E&&j.type!==E)&&n("Node writer source or output type does not match declaration","variable",A)}if(d.type==="coupons"){let w=e.variables[d.writes.value];(w?.type!=="array"||w.items?.type!=="reward"||w.items.nullable||w.nullable)&&n("Coupons output requires a non-null Reward array","variable",A);for(let C of d.couponIds)a("reward",C)||n("Coupons require Reward references","coupon",A)}if(d.type==="split"&&!a("experiment",d.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",A),d.type==="coupon"&&!a("reward",d.couponId)&&n("Coupon selectors require a Reward reference","coupon",A),d.type==="action"&&d.action.type==="claim_offer"&&d.action.coupon.source==="literal"){let w=d.action.coupon.value;(!w||typeof w!="object"||Array.isArray(w)||w.type!=="reward"||typeof w.id!="string"||Object.keys(w).length!==2||!a("reward",w.id))&&n("Coupon claims require a Reward reference","coupon",A)}if(d.type==="offering"&&d.configuration.source==="fixed"&&!a("offering_version",d.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",A),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",A),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",A),d.type==="screen"){let w=i.get(d.screenId);if(d.offering?.source==="fixed"&&!a("offering_version",d.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",A),w?.type==="paywall"&&d.offering&&n("Paywall owns its fixed Offering Version","offering",A),w?.type==="paywall"&&!a("paywall_version",w.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",A),w?.type==="owned"){let C=w.document.pages[0];if(!C){n("Owned screen requires a page","screen",A);continue}tr(w.document).some(E=>!E.complete)&&n("Owned screens require complete local content","translations",A);let j=new Set(w.document.actions.map(E=>E.id));(j.size!==Object.keys(d.outputs).length||Object.keys(d.outputs).some(E=>!j.has(E)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",A),Gn(C.root,E=>{!d.offering&&(E.type==="plan_picker"||(E.type==="stack"||E.type==="button")&&E.bind?.plan||E.type==="customer_data"&&["customer_plans","credit_packs"].includes(E.data.source))&&n("Product presentation requires an Offering Version","offering",A),E.type==="customer_data"&&Object.values(E.data.outputs??{}).some(ae=>ae!==void 0&&!j.has(ae))&&n("Customer components require declared screen outcomes","componentOutput",A)})}}d.type==="end"&&["completed","ineligible"].includes(d.outcome)&&!d.output&&n("Completed and ineligible ends require a declared output","output",A),d.type==="end"&&d.output?.type==="literal"&&!fn(e.outputSchema,d.output.value)&&n("Terminal output does not match outputSchema","output",A),d.type==="output"&&d.value.type==="literal"&&!fn(e.outputSchema,d.value.value)&&n("Terminal output does not match outputSchema","output",A);let I=d.type==="output"?d.value:d.type==="end"?d.output:void 0;if(I?.type==="variable"&&!I.path){let w=e.variables[I.key];w&&!gc(w,e.outputSchema)&&n("Variable output does not match outputSchema","output",A)}if(d.type==="screen"){let w=i.get(d.screenId);if(w?.type==="owned")for(let C of yc(w.document))(/^(input|params)\./.test(C)||C.startsWith("variables.")&&!Ac(C.slice(10),c))&&n("Screen values must reference registered variables","variable",A)}if(d.type==="condition")for(let w of d.cases){for(let C of Un(w.condition))a("saved_group",C)||n("Conditions require explicit Saved Group references","savedGroup",A);for(let C of Yn(w.condition))C.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",A)}if(d.type==="output"&&d.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",A);for(let[w,C]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let j=d.value[w];if(j)if(j.source==="literal"){let E=w==="coupons"?j.value:[j.value];(!Array.isArray(E)||E.length>20||E.some(ae=>!fn({type:C,nullable:!1},ae)||!a(C,ae.id))||w==="coupons"&&new Set(E.map(ae=>ae.id)).size!==E.length)&&n("Bundle requires distinct scoped resource references",w==="coupons"?"coupon":w==="paywall"?"paywall":"offering",[...A,"value",w])}else{let E=e.variables[j.key];(j.path||!E||E.nullable||(w==="coupons"?E.type!=="array"||E.items?.type!=="reward"||E.items.nullable:E.type!==C))&&n("Bundle binding type does not match its slot","output",A)}}}}for(let[h,d]of e.graph.nodes.entries()){let A=d.type==="screen"?i.get(d.screenId):void 0,k=[..._f(d,c),...A?.type==="owned"?ba(A.document).map(g=>Ac(g,c)?.key??g):[]];for(let g of new Set(k)){let C=function(j){if(j===d.id)return!0;if(w.has(j))return!1;w.add(j);let E=e.graph.nodes.find(xe=>xe.id===j);return E?(I.has(j)?E.type==="action"?[E.cancel,E.unavailable,E.failure]:E.type==="wait"&&E.wait.type==="event"?[E.wait.timeout]:[]:Ka(E)).some(C):!1};var m=C;if(!Object.hasOwn(e.variables,g)){n("Consumed variable is undeclared","variable",["graph","nodes",h]);continue}let y=e.variables[g];if(d.type==="screen"&&y.source.type==="input"&&e.inputs.some(j=>j.screenId===d.screenId&&j.variable===g)||y.source.type==="parameter"||y.source.type==="attribute")continue;let I=y.source.type==="input"?new Set(e.inputs.filter(j=>j.variable===g&&j.required).flatMap(j=>o.filter(E=>E.screenId===j.screenId).map(E=>E.id))):s.get(g)??new Set,w=new Set;(!I.size||C(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",h])}}(new Set(e.inputs.map(h=>h.variable)).size!==e.inputs.length||new Set(e.inputs.map(h=>`${h.screenId}:${h.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[h,d]of e.inputs.entries()){e.variables[d.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",h]);let A=i.get(d.screenId),k=A?.type==="owned"?ro(A.document,d.componentId):null;if((k?.type!=="stack"||!k.interaction||!["input","toggle","select","multiselect","tabs"].includes(k.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",h]),k?.type==="stack"&&k.interaction){let g=k.interaction.type==="toggle"?"boolean":k.interaction.type==="multiselect"?"strings":"string";e.variables[d.variable]?.type!==g&&n("Input variable type does not match component","inputBinding",["inputs",h]);let y=e.variables[d.variable]?.enum;y&&!k.children.filter(I=>!I.hidden).every(I=>y.includes(I.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",h])}}for(let[h,d]of Object.entries(e.variables))d.enum&&d.type!=="string"&&n("Only string variables support enum","variable",["variables",h]),d.source.type==="input"&&!e.inputs.some(A=>A.variable===h)&&n("Input variable requires a component binding","inputBinding",["variables",h]);let l=0,f=0;for(let h of e.screens)if(h.type==="owned"){for(let d of h.document.pages)Gn(d.root,()=>{l++});f+=h.document.actions.length}(l>On.components||f>On.actions||cn(e)>On.documentBytes)&&n("Funnel document exceeds its budget","budget")}var e0=U.z.strictObject({...au,graph:tu}).superRefine(kf),vi=U.z.strictObject({...au,graph:tu,displayName:U.z.string().trim().min(1).max(80)}).superRefine(kf),j1=vi.superRefine(Rf),T1=e0.superRefine(Rf),Qa=U.z.string().regex(jt),ho={requestId:U.z.uuid(),nodeId:An,visit:U.z.number().int().nonnegative(),revision:U.z.number().int().nonnegative(),customerToken:Qa.optional()},t0=U.z.discriminatedUnion("type",[U.z.strictObject({type:U.z.literal("screen"),output:An,answers:or,selection:U.z.record(An,U.z.union([U.z.string().max(200),U.z.boolean(),U.z.number().int().min(0).max(1e4)])).optional()}),U.z.strictObject({type:U.z.literal("paywall_quote"),featureQuantities:U.z.record(U.z.uuid(),U.z.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100).optional(),actionId:An,productVersionId:U.z.uuid(),offerId:U.z.uuid().optional(),nativeOffer:pi.optional(),predecessor:U.z.strictObject({operationId:U.z.uuid().nullable(),generation:U.z.number().int().positive()}).optional()}),U.z.strictObject({type:U.z.literal("paywall_confirm"),operationId:U.z.uuid()}),U.z.strictObject({type:U.z.literal("paywall_cancel"),operationId:U.z.uuid()}),U.z.strictObject({type:U.z.literal("client_action"),receiptId:U.z.uuid(),outcome:U.z.enum(["success","cancel","failure","opened","failed"])})]),n0=U.z.object({nodeId:An,visit:U.z.number().int().nonnegative(),revision:U.z.number().int().nonnegative(),components:U.z.record(An,U.z.object({resourceKey:U.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:U.z.number().int().min(1).max(1e5),after:Fa.nullable(),filter:U.z.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),Pt=U.z.discriminatedUnion("operation",[U.z.strictObject({operation:U.z.literal("start"),funnelId:U.z.uuid(),requestId:U.z.uuid(),customer:Vr.optional(),customerData:xi.optional(),locale:U.z.string().min(1).max(35),parameters:ar}).refine($a,Ga),U.z.strictObject({operation:U.z.literal("get"),settlementRequestId:U.z.uuid().optional(),data:n0.optional(),purchase:U.z.strictObject({receiptId:U.z.uuid(),operationId:U.z.uuid()}).optional(),customerToken:Qa.optional()}),U.z.strictObject({operation:U.z.literal("resume"),requestId:U.z.uuid(),customerToken:Qa.optional()}),U.z.strictObject({operation:U.z.literal("submit"),...ho,input:t0}),U.z.strictObject({operation:U.z.literal("back"),...ho}),U.z.strictObject({operation:U.z.literal("shown"),...ho}),U.z.strictObject({operation:U.z.literal("close"),...ho}),U.z.strictObject({operation:U.z.literal("commit_segment"),...ho,policyRevision:U.z.number().int().nonnegative(),generation:U.z.string().min(1).max(256)}),U.z.strictObject({operation:U.z.literal("review"),receiptId:U.z.uuid().optional(),customerToken:Qa.optional()})]);function Za(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 A of Un(d))l(A)}function l(d){if(i.has(d)||!Object.hasOwn(t.savedGroups,d))return;let A=t.savedGroups[d];A&&(i.add(d),c.set(d,A),a.push(()=>{!Array.isArray(A)&&A.type==="condition"&&u(A.condition)}))}function f(d){for(let A of["hashAttribute","fallbackAttribute"])if(d[A]!==void 0&&zc(d[A]))throw new Error(`Funnel GB ${A} uses a reserved flow namespace`);u(d.condition);for(let A of d.parentConditions??[])m(A.id),u(A.condition)}function m(d,A=!1){let k=Object.hasOwn(t.features,d)?t.features[d]:void 0;if(!k){if(A)throw new Error("Required GB Feature is unavailable");return}n.has(d)||(n.add(d),o.set(d,k),a.push(()=>{for(let g of k.rules??[]){f(g);for(let y of g.tracks??[])f(y.experiment)}}))}function h(d){let A=Object.hasOwn(t.experiments,d)?t.experiments[d]:void 0;if(!A)throw new Error("Required GB Experiment is unavailable");r.has(d)||(r.add(d),s.set(d,A),a.push(()=>f(A)))}for(let d of e.graph.nodes){d.type==="feature"&&m(d.featureKey,!0),d.type==="split"&&h(d.experimentId),d.type==="condition"&&d.cases.forEach(k=>u(k.condition)),d.type==="offering"&&d.configuration.source==="feature"&&m(d.configuration.featureKey,!0);let A=d.type==="output"?d.value:d.type==="end"?d.output:null;A?.type==="feature"&&m(A.featureKey,!0)}for(let d of a)d();return{...t,features:Object.fromEntries(o),experiments:Object.fromEntries(s),savedGroups:Object.fromEntries(c)}}var ie=require("zod");function jf(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 Tf(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}var wi=require("zod");var Nf=wi.z.object({defaultLocale:xn,locales:wi.z.record(xn,wi.z.object({name:wi.z.string().max(80),description:wi.z.string().max(500)}).strict())}).strict().superRefine((e,t)=>{let n=Object.keys(e.locales);(!n.length||n.length>20||!e.locales[e.defaultLocale])&&t.addIssue({code:"custom",message:"Invalid content languages"}),new TextEncoder().encode(JSON.stringify(e)).length>5e4&&t.addIssue({code:"custom",message:"Content exceeds 50 KB"})});var r0=["customer_data","coupon_code"],Df=ie.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),i0=ie.z.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),Wa=(e,t)=>new Set(e.map(t)).size===e.length,o0=ie.z.strictObject({currency:be,amountMinor:ie.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),a0=ie.z.strictObject({featureId:ie.z.uuid(),name:ie.z.string().trim().min(1).max(120),allowance:ie.z.string().max(40).nullable(),access:ie.z.boolean()}),s0=ie.z.strictObject({stripe:ie.z.strictObject({prices:ie.z.array(o0).min(1).max(50)}).optional(),apple:ie.z.strictObject({productIds:ie.z.array(Df).min(1).max(10)}).optional(),google:ie.z.strictObject({products:ie.z.array(ie.z.strictObject({productId:Df,basePlanId:i0.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!Wa(e.stripe.prices,n=>n.currency)||e.apple&&!Wa(e.apple.productIds,n=>n)||e.google&&!Wa(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),c0=ie.z.strictObject({name:ie.z.string().trim().min(1).max(80),interval:ie.z.enum(["free","week","month","year","one_time"]),intervalCount:ie.z.number().int().min(1).max(100),trial:ie.z.strictObject({days:ie.z.number().int().min(1).max(730),cardRequired:ie.z.boolean()}).nullable(),benefits:ie.z.array(a0).max(50).refine(e=>Wa(e,t=>t.featureId),"Duplicate benefit"),channels:s0,prepaid:ie.z.array(Xi).max(100).optional()}),u0=ie.z.strictObject({digest:yi,content:ie.z.strictObject({discount:Xn,duration:on,appliesTo:tc,displayCopy:Nf.nullable(),firstPurchaseOnly:ie.z.boolean(),qualificationRequired:ie.z.boolean(),startsAt:ie.z.iso.datetime().nullable(),endsAt:ie.z.iso.datetime().nullable(),grantWindowHours:ie.z.number().int().positive(),perCustomerLimit:ie.z.number().int().positive()})}),l0=ie.z.discriminatedUnion("type",[ie.z.strictObject({type:ie.z.literal("checkout"),product:ja}),ie.z.strictObject({type:ie.z.literal("close")}),ie.z.strictObject({type:ie.z.literal("action"),action:jc})]),Ya=ie.z.strictObject({kind:ie.z.literal("paywall"),formatVersion:ie.z.literal(1),name:ie.z.string().trim().min(1).max(80),offeringVersionId:ie.z.uuid(),presentation:Kn,screen:sn,products:ka,catalog:ie.z.record(ie.z.uuid(),c0),buttons:ie.z.record(Me,l0),coupons:ie.z.record(ie.z.uuid(),u0)}).superRefine((e,t)=>{let n=A=>t.addIssue({code:"custom",message:A}),{screen:r}=e;jf(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),Mc(r,r0).forEach(n),tr(r).some(A=>!A.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,o=new Set;Gt(r,A=>{let k="bind"in A?A.bind:void 0;k?.promotionCode&&n("Promotion codes must not be published"),k?.plan&&i.add(k.plan),k?.coupon&&a.add(k.coupon),A.type==="plan_picker"&&(A.planIds?.forEach(g=>i.add(g)),A.defaultPlan&&i.add(A.defaultPlan)),A.type==="text"&&A.feature&&o.add(A.feature.id)});let s=e.products.items.map(A=>A.productVersionId),c=Object.keys(e.catalog);(s.length!==c.length||s.some(A=>!Object.hasOwn(e.catalog,A)))&&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 A of i)u.has(A)||n("Screen references a Product that is not displayed");for(let A of Object.values(e.catalog))!A.channels.stripe&&!A.channels.apple&&!A.channels.google&&n("A displayed Product needs at least one sales channel");let l=new Set(Object.values(e.catalog).flatMap(A=>A.benefits.map(k=>k.featureId)));for(let A of o)l.has(A)||n("Feature text must read a displayed benefit");let f=r.actions.filter(A=>A.type!=="navigate");r.actions.some(A=>A.type!=="event"&&A.type!=="navigate")&&n("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==f.length||f.some(A=>!Object.hasOwn(e.buttons,A.id)))&&n("Buttons must match the screen's actions");let h=!1;for(let A of Object.values(e.buttons)){if(A.type!=="checkout")continue;h=!0,(A.product.type==="fixed"?[A.product.productVersionId]:A.product.allowedProductVersionIds).some(g=>!u.has(g))&&n("Checkout may only sell displayed Products")}h||n("A Paywall needs a checkout button");let d=Object.keys(e.coupons);(d.length!==a.size||d.some(A=>!a.has(A)))&&n("Coupons must be exactly the bound Coupons")}),Ff=ie.z.strictObject({state:ie.z.enum(["published","archived"]),controlRevision:ie.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:ie.z.uuid(),versions:ie.z.record(ie.z.uuid(),ie.z.strictObject({version:ie.z.number().int().positive(),artifact:ie.z.string().min(1),sourceDigest:ie.z.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var Xt={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},su=_e.z.string().regex(/^[a-f0-9]{64}$/),cu=_e.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),lu=Ne.extend({environmentId:_e.z.uuid()}),Mf=_e.z.strictObject({features:_e.z.array(_e.z.string()).max(500),experiments:_e.z.record(_e.z.uuid(),_e.z.array(_e.z.string()).max(20)),savedGroups:_e.z.array(_e.z.string()).max(1e3)}),du=_e.z.strictObject({kind:_e.z.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:_e.z.number().int().positive(),url:_e.z.string().min(1).max(2048),sha256:su,byteLength:_e.z.number().int().positive().max(Xt.maxArtifactBytes),generation:su.optional()}),d0=_e.z.strictObject({state:_e.z.enum(["active","paused","archived"]),controlRevision:cu,evaluationMode:_e.z.enum(["local","remote"]),evaluationRevision:cu,currentVersionId:_e.z.uuid(),versions:_e.z.record(_e.z.uuid(),_e.z.strictObject({artifact:_e.z.string(),dependencies:Mf,definitionDigest:yi.optional(),couponDigests:_e.z.record(_e.z.uuid(),yi).optional()}))}),pu=_e.z.strictObject({kind:_e.z.literal("sdk_configuration"),schemaVersion:_e.z.literal(1),scope:lu,revision:cu,generation:su,policy:_e.z.strictObject({refreshIntervalSeconds:_e.z.number().positive().max(15),maxControlAgeSeconds:_e.z.number().positive().max(60)}),gb:_e.z.strictObject({features:_e.z.string().nullable(),pageExperiments:_e.z.string().nullable()}),artifacts:_e.z.record(_e.z.string(),du),funnels:_e.z.record(_e.z.uuid(),d0),paywalls:_e.z.record(_e.z.uuid(),Ff).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 Ct(e){if(Array.isArray(e))return`[${e.map(Ct).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)}:${Ct(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function mu(e){return ei(ti(typeof e=="string"?new TextEncoder().encode(e):e))}function qf(e){return mu(Ct(e))}var uu=class extends Error{constructor(n,r){super(n);Fe(this,"dependency",r)}};function Bf(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,f)=>e.graph.nodes.find(m=>l==="experiment"?m.type==="split"&&m.experimentId===f:l==="feature"&&n(m)===f)?.name,i=(l,f,m=r(f.type,f.resource))=>new uu(l,{...f,...m?{step:m}:{}});for(let l of Object.values(e.references)){let f=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(f)throw i("Funnel dependency is absent from GB public delivery",{reason:"unavailable",...f})}let a=Za(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),o=new Set(t.remoteFeatures);for(let l of e.graph.nodes){let f=n(l);if(!f)continue;let m=a.features[f],h=l.type==="feature"?e.variables[l.writes.value]:e.outputSchema,d={type:"feature",resource:f};if(!m||!h)throw i("Required public Feature declaration is unavailable",{reason:"unavailable",...d},l.name);if([m.defaultValue,...(m.rules??[]).flatMap(k=>[...Object.hasOwn(k,"force")?[k.force]:[],...k.variations??[],...(k.tracks??[]).flatMap(g=>g.experiment.variations)])].some(k=>k===void 0||!fn(h,k)))throw i("GB Feature values violate the Funnel type contract",{reason:"value_type",...d},l.name)}let s=new Set,c=(l,f)=>{for(let m of Un(l)){if(s.has(m))continue;let h=t.savedGroups[m];if(!h)throw i("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:m},f);s.add(m),!Array.isArray(h)&&h.type==="condition"&&c(h.condition,f)}},u=(l,f)=>{if(o.has(l)||!t.features[l])throw i("Local Funnel requires public Local prerequisites",{reason:"unavailable",type:"feature",resource:l},f)};for(let l of e.graph.nodes)if(l.type==="condition")for(let f of l.cases)c(f.condition,l.name);for(let[l,f]of Object.entries(a.features)){let m=r("feature",l);for(let h of f.rules??[]){c(h.condition,m);for(let d of[...h.parentConditions??[],...(h.tracks??[]).flatMap(A=>A.experiment.parentConditions??[])])u(d.id,m),c(d.condition,m);for(let d of h.tracks??[])c(d.experiment.condition,m)}}for(let[l,f]of Object.entries(a.experiments)){let m=r("experiment",l);c(f.condition,m);for(let h of f.parentConditions??[])u(h.id,m),c(h.condition,m)}for(let l of e.graph.nodes)if(l.type==="split"){let f=a.experiments[l.experimentId],m={type:"experiment",resource:l.experimentId};if(!f)throw i("Local Funnel requires a public Experiment",{reason:"unavailable",...m},l.name);for(let h of f.variations)if(typeof h!="string"||!Object.hasOwn(l.routes,h))throw i("Experiment variation has no declared Funnel route",{reason:"variation_route",...m},l.name)}return Mf.parse({features:Object.keys(a.features).sort(),experiments:Object.fromEntries(Object.entries(a.experiments).map(([l,f])=>[l,f.variations.map(String)])),savedGroups:[...s].sort()})}function Vf(e){return vi.parse(e)}var Lf=xt.z.strictObject({processContext:Sa.optional(),...di,selector:xt.z.discriminatedUnion("type",[xt.z.strictObject({type:xt.z.literal("paywall"),paywallId:xt.z.uuid()}),xt.z.strictObject({type:xt.z.literal("version"),versionId:xt.z.uuid()})]),customerId:xt.z.uuid().optional(),commerce:ai,locale:xt.z.string().min(1).max(35),requirement:er.optional()}),Ao=xt.z.strictObject({id:xt.z.uuid(),paywallId:xt.z.uuid(),version:xt.z.number().int().positive(),document:Ai.omit({requirement:!0,offeringId:!0}),offering:xt.z.strictObject({id:xt.z.uuid()}),content:xt.z.strictObject({environmentId:xt.z.uuid(),offeringVersionId:xt.z.uuid(),artifact:du.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:si,check:Tr.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"})}),Ur=xt.z.strictObject(Ao.shape).omit({document:!0,offering:!0}).extend({content:Ao.shape.content.unwrap()});function Uf(e,t){let n=Ya.parse(t);if(n.offeringVersionId!==e.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");let r=structuredClone(e.capabilities);for(let[i,a]of Object.entries(n.catalog)){let o=r.plans[i],s=a.channels.stripe?.prices.find(c=>c.currency===o?.currency);o&&s&&Object.assign(o,{amountMinor:s.amountMinor,interval:a.interval,intervalCount:a.intervalCount,...a.prepaid?.length?{prepaid:a.prepaid}:{}})}return Ao.parse({...e,capabilities:r,document:{schemaVersion:3,kind:n.kind,name:n.name,presentation:n.presentation,products:n.products,offeringVersionId:n.offeringVersionId,screen:n.screen,buttons:n.buttons},offering:{id:n.offeringVersionId}})}var Bt=require("zod");var zf={requestId:Bt.z.uuid(),sourceId:Bt.z.uuid(),expectedAvailable:$t},$f=Bt.z.discriminatedUnion("action",[Bt.z.strictObject({...zf,action:Bt.z.enum(["add","subtract","set_remaining"]),amount:Ae}),Bt.z.strictObject({...zf,action:Bt.z.literal("edit"),granted:Ae,expiresAt:Bt.z.iso.datetime({offset:!0}).nullable(),nextResetAt:Bt.z.iso.datetime({offset:!0}).nullable(),expectedRevision:Bt.z.number().int().nonnegative()})]),fu=Bt.z.strictObject({sourceId:Bt.z.uuid(),available:$t,held:$t,spent:$t,adjustmentGrantId:Bt.z.uuid().nullable()}),Gf=fu.extend({granted:$t,expiresAt:Bt.z.iso.datetime({offset:!0}).nullable(),nextResetAt:Bt.z.iso.datetime({offset:!0}).nullable(),revision:Bt.z.number().int().nonnegative()});var en=require("zod"),Kf=en.z.discriminatedUnion("action",[en.z.object({action:en.z.literal("upsert"),externalId:en.z.string().min(1).max(128),name:en.z.string().trim().min(1).max(80)}).strict(),en.z.object({action:en.z.literal("archive"),entityId:en.z.uuid()}).strict()]),Hf=en.z.object({id:en.z.uuid(),externalId:en.z.string().min(1).max(128),name:en.z.string().min(1).max(80),archived:en.z.boolean()}).strict();var Ft=require("zod");var sr=require("zod"),Jf=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],Qf=sr.z.string().regex(/.+\/.+/),gu=sr.z.number().min(-100),zr=sr.z.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),p0=sr.z.strictObject({input:zr,output:zr,cache_read:zr.optional(),cache_write:zr.optional(),reasoning:zr.optional(),input_audio:zr.optional(),output_audio:zr.optional()}),hu=(e,t)=>sr.z.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),OE=sr.z.strictObject({defaultMarkup:gu,providerMarkups:hu(sr.z.string().min(1),gu),modelMarkups:hu(Qf,gu),customModels:hu(Qf,p0.partial())});var he=require("zod"),$r=he.z.iso.datetime({offset:!0}),cr=he.z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),m0=he.z.discriminatedUnion("kind",[he.z.object({kind:he.z.literal("absolute"),from:$r,to:$r}).strict(),he.z.object({kind:he.z.literal("last_days"),days:he.z.union([he.z.literal(1),he.z.literal(7),he.z.literal(30),he.z.literal(90)])}).strict(),he.z.object({kind:he.z.literal("billing_cycles"),membershipId:he.z.uuid(),count:he.z.number().int().min(1).max(12),includeCurrent:he.z.boolean()}).strict()]),Zf=he.z.string().max(100).refine(e=>{if(e!=="UTC"&&!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+\-]+)+$/.test(e))return!1;try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Use an IANA timezone"),f0=he.z.object({key:he.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:he.z.array(he.z.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),Gr=he.z.object({range:m0,timezone:Zf,filterBy:he.z.array(f0).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:he.z.enum(["hour","day","week","month"]),internal_feature_id:he.z.uuid().nullable(),entityId:he.z.uuid().nullable(),topN:he.z.number().int().min(1).max(50).nullable(),groupBy:he.z.union([he.z.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),he.z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:he.z.object({bucket:$r,group:he.z.string().max(240),isOther:he.z.boolean(),internal_feature_id:he.z.uuid(),resourceId:he.z.uuid()}).strict().nullable(),limit:he.z.number().int().min(1).max(100)}).strict().superRefine((e,t)=>{if(e.range.kind!=="absolute"){e.interval==="hour"&&e.range.kind==="last_days"&&e.range.days>31&&t.addIssue({code:"custom",message:"Hourly reports are bounded to 31 days"});return}let n=Date.parse(e.range.to)-Date.parse(e.range.from);(n<=0||n>366*864e5||e.interval==="hour"&&n>31*864e5)&&t.addIssue({code:"custom",message:"Reporting range must be positive and bounded (31 days hourly, 366 days otherwise)"})}),Wf=he.z.object({from:$r,to:$r,interval:he.z.enum(["hour","day","week","month"]),timezone:Zf,rows:he.z.array(he.z.object({bucket:$r,group:he.z.string().max(240),isOther:he.z.boolean(),internal_feature_id:he.z.uuid(),resourceId:he.z.uuid(),consumedUnits:cr,refundedUnits:cr,reservedUnits:cr,charged:cr,refunded:cr,reserved:cr,netUnits:cr,netCharged:cr}).strict()).max(100),nextCursor:he.z.object({bucket:$r,group:he.z.string().max(240),isOther:he.z.boolean(),internal_feature_id:he.z.uuid(),resourceId:he.z.uuid()}).strict().nullable()}).strict();var Oi=Ft.z.string().regex(/^(0|[1-9]\d{0,29})$/),Yf=Ft.z.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),Au=Ft.z.strictObject({bucket:Ft.z.iso.datetime({offset:!0}),group:Ft.z.string().max(240),isOther:Ft.z.boolean(),internal_feature_id:Ft.z.uuid()}),Xf=Ft.z.strictObject({...Gr.shape,groupBy:Ft.z.union([Ft.z.enum(["customer","entity","entitlement"]),Ft.z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Au.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})}),eg=Ft.z.strictObject({from:Ft.z.iso.datetime({offset:!0}),to:Ft.z.iso.datetime({offset:!0}),interval:Gr.shape.interval,timezone:Gr.shape.timezone,rows:Ft.z.array(Ft.z.strictObject({...Au.shape,eventCount:Oi,units:Yf,tokenEventCount:Oi,tokens:Ft.z.strictObject(Object.fromEntries(Jf.map(e=>[e,Oi]))),totalTokens:Oi,providerCostEventCount:Oi,providerCostUsd:Yf,invalidTelemetryEventCount:Oi})).max(100),nextCursor:Au.nullable()});var pt=require("zod");var tg=pt.z.object({requestId:pt.z.uuid(),items:pt.z.array(pt.z.object({customerId:pt.z.uuid(),command:Hi.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"),ng=pt.z.object({batchId:pt.z.uuid(),after:pt.z.number().int().min(-1).max(999),limit:pt.z.number().int().min(1).max(100)}).strict(),rg=pt.z.object({batchId:pt.z.uuid(),status:pt.z.enum(["queued","complete"]),total:pt.z.number().int().min(1).max(1e3),processed:pt.z.number().int().min(0).max(1e3),items:pt.z.array(pt.z.object({position:pt.z.number().int().min(0).max(999),customerId:pt.z.uuid(),idempotencyKey:pt.z.string().min(1).max(120),status:pt.z.enum(["queued","accepted","rejected","failed"]),receipt:Qi.nullable(),errorCode:pt.z.enum(["invalid_request","forbidden","conflict","internal_error"]).nullable()}).strict().refine(e=>e.status==="queued"?e.receipt===null&&e.errorCode===null:e.status==="failed"?e.receipt===null&&e.errorCode!==null:e.receipt!==null&&e.errorCode===null&&e.receipt.accepted===(e.status==="accepted"))).max(100),nextAfter:pt.z.number().int().min(0).max(999).nullable()}).strict();var R=require("zod");var g0=R.z.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),ig=R.z.enum(["draft","active","paused","archived"]),og=R.z.string().min(1).max(256),ag=R.z.array(og).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),h0=R.z.strictObject({duration:R.z.enum(["day","week","month","year"]),length:R.z.number().int().min(1).max(3660)}),A0=R.z.strictObject({internal_feature_id:R.z.uuid(),allowance:R.z.number().nonnegative().max(1e15).nullable(),expiry:h0.nullable()}),y0=R.z.discriminatedUnion("type",[R.z.strictObject({type:R.z.literal("feature_grant"),grants:R.z.array(A0).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),R.z.strictObject({type:R.z.literal("free_product"),productId:og,duration:on}),R.z.strictObject({type:R.z.literal("invoice_credits"),amount:R.z.number().positive().max(1e8),duration:on,rollover:R.z.boolean(),productIds:ag})]),b0=R.z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),sg=R.z.object({key:b0,name:R.z.string().trim().min(1).max(80),configuration:y0}).strict(),cg=R.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),yu=R.z.object({code:cg,maxUses:R.z.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:R.z.boolean()}).strict(),ug=R.z.object({key:R.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:R.z.string().trim().min(1).max(80),rewardId:R.z.uuid(),redeemOn:R.z.enum(["customer_creation","checkout"]),receivedBy:R.z.enum(["referrer","all"]),maxRedemptions:R.z.number().int().min(1).max(1e6).nullable(),productIds:ag,excludeTrial:R.z.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),lg={id:R.z.uuid(),projectId:R.z.uuid(),environmentId:R.z.uuid(),revision:R.z.number().int().nonnegative(),status:ig,createdAt:R.z.iso.datetime({offset:!0}),updatedAt:R.z.iso.datetime({offset:!0})},x0=sg.extend(lg).strict(),S0=ug.safeExtend(lg).strict(),DE=R.z.strictObject({id:R.z.uuid(),key:R.z.string(),name:R.z.string(),type:g0,status:ig}),FE=R.z.discriminatedUnion("action",[R.z.object({action:R.z.literal("save"),id:R.z.uuid().nullable(),revision:R.z.number().int().nonnegative(),input:sg}).strict(),R.z.object({action:R.z.enum(["activate","pause","resume","archive","delete"]),id:R.z.uuid(),revision:R.z.number().int().nonnegative()}).strict()]),ME=R.z.discriminatedUnion("action",[R.z.object({action:R.z.literal("save"),id:R.z.uuid().nullable(),revision:R.z.number().int().nonnegative(),input:ug}).strict(),R.z.object({action:R.z.enum(["activate","pause","resume","archive","delete"]),id:R.z.uuid(),revision:R.z.number().int().nonnegative()}).strict()]),dg=R.z.object({id:R.z.uuid(),rewardId:R.z.uuid(),programId:R.z.uuid().nullable(),customerId:R.z.uuid(),referrerId:R.z.uuid().nullable(),status:R.z.enum(["pending","applied","unavailable"]),result:R.z.record(R.z.string(),R.z.unknown()).nullable(),createdAt:R.z.iso.datetime({offset:!0})}).strict(),pg=R.z.object({code:cg,requestId:R.z.uuid()}).strict(),mg=R.z.strictObject({redemptionId:R.z.uuid(),currency:be,requestId:R.z.uuid(),accepted:R.z.literal(!0)}),I0=R.z.strictObject({type:R.z.literal("checkout"),orderId:R.z.uuid(),productVersionId:R.z.uuid(),currency:be,duration:on,renewalAmountMinor:R.z.number().int().positive().max(1e8),status:R.z.enum(["created","pending","trialing","paid","cancelled","failed"]),url:R.z.url().nullable()}),fg=R.z.discriminatedUnion("type",[I0,R.z.strictObject({type:R.z.literal("subscription"),operationId:R.z.uuid(),membershipId:R.z.uuid(),productVersionId:R.z.uuid(),currency:be,duration:on,renewalAmountMinor:R.z.number().int().positive().max(1e8),status:R.z.enum(["pending","running","applied","failed"])})]),gg=R.z.object({programId:R.z.uuid(),requestId:R.z.uuid()}).strict(),hg=R.z.object({id:R.z.uuid(),programId:R.z.uuid(),code:yu.shape.code,createdAt:R.z.iso.datetime({offset:!0})}).strict(),qE=R.z.object({rows:R.z.array(x0).max(100),nextCursor:R.z.uuid().nullable()}).strict(),BE=R.z.object({rows:R.z.array(S0).max(100),nextCursor:R.z.uuid().nullable()}).strict(),v0=yu.extend({id:R.z.uuid(),redemptions:R.z.number().int().nonnegative()}).strict(),w0=R.z.strictObject({id:R.z.uuid(),programId:R.z.uuid().nullable(),customerId:R.z.uuid().nullable(),referrerId:R.z.uuid().nullable(),code:R.z.string().nullable(),status:R.z.enum(["pending","triggered","applied"]),createdAt:R.z.iso.datetime({offset:!0})}),VE=R.z.object({codes:R.z.array(v0).max(100),redemptions:R.z.array(w0).max(100),customers:R.z.record(R.z.uuid(),R.z.string()),codesCursor:R.z.uuid().nullable(),redemptionsCursor:R.z.uuid().nullable()}).strict(),LE=R.z.discriminatedUnion("action",[R.z.object({action:R.z.literal("create"),rewardId:R.z.uuid(),revision:R.z.number().int().nonnegative(),input:yu}).strict(),R.z.object({action:R.z.literal("remove"),rewardId:R.z.uuid(),revision:R.z.number().int().nonnegative(),codeId:R.z.uuid()}).strict()]);var v=require("zod");var J=require("zod"),jn={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},yo=e=>new Set(e).size===e.length,bu=J.z.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),O0=J.z.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),bo=J.z.string().min(1).max(200).regex(/^[a-zA-Z0-9_./-]+$/).refine(e=>!e.includes("..")&&!e.endsWith(".")&&!e.split("/").some(t=>!t||t.startsWith(".")||t.endsWith(".lock"))),P0=J.z.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),Ag=J.z.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var yg=J.z.strictObject({id:J.z.uuid(),repo:O0,platform:J.z.enum(["github","gitlab","bitbucket"]),branches:J.z.array(bo).min(1).max(4).refine(yo),workflow:J.z.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:J.z.array(J.z.uuid()).min(1).max(4).refine(yo),include:J.z.array(Ag).min(1).max(16),exclude:J.z.array(Ag).max(16),methods:J.z.array(J.z.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(yo),maxAgeHours:J.z.number().int().min(1).max(720)}),bg=yg.extend({revision:J.z.number().int().positive()}),zE=J.z.strictObject({repository:yg,expectedRevision:J.z.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),xg=J.z.strictObject({repositoryId:J.z.uuid(),branch:bo}),C0=J.z.array(bu).max(jn.keys).refine(yo),Sg=J.z.strictObject({repository:bg.omit({keyIds:!0}),branch:bo,keys:C0,keySetHash:J.z.string().regex(/^[a-f0-9]{64}$/)}),_0=J.z.strictObject({filePath:P0,startingLineNumber:J.z.number().int().min(1).max(1e7)}),xu=J.z.strictObject({protocol:J.z.literal(1),repositoryId:J.z.uuid(),branch:bo,workflow:J.z.string().max(200),configurationRevision:J.z.number().int().positive(),keySetHash:J.z.string().regex(/^[a-f0-9]{64}$/),commit:J.z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:J.z.uuid(),runNumber:J.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:J.z.number().int().min(1).max(1e4),scannerVersion:J.z.literal("1"),scannedAt:J.z.iso.datetime({offset:!0}),coverage:J.z.strictObject({complete:J.z.literal(!0),files:J.z.number().int().min(0).max(jn.files),sourceBytes:J.z.number().int().min(0).max(jn.sourceBytes),unresolvedCalls:J.z.number().int().min(0).max(1e6),unsupportedFiles:J.z.number().int().min(0).max(jn.files)}),features:J.z.array(J.z.strictObject({key:bu,refs:J.z.array(_0).max(jn.referencesPerKey)})).max(jn.keys)}).superRefine((e,t)=>{yo(e.features.map(n=>n.key))||t.addIssue({code:"custom",path:["features"],message:"Duplicate feature"}),e.features.reduce((n,r)=>n+r.refs.length,0)>jn.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),Su=J.z.strictObject({scanId:J.z.uuid(),commit:J.z.string(),receivedAt:J.z.string(),references:J.z.number().int().nonnegative(),removedReferences:J.z.number().int().nonnegative()}),E0=Su.extend({repositoryId:J.z.uuid(),branch:bo,workflow:J.z.string(),digest:J.z.string(),configurationRevision:J.z.number().int().positive(),runNumber:J.z.number().int().positive(),runAttempt:J.z.number().int().positive(),scannedAt:J.z.string(),keySetHash:J.z.string(),coverage:xu.shape.coverage}),R0=J.z.strictObject({repositories:J.z.array(bg).max(jn.repositories),scans:J.z.array(E0).max(jn.repositories*jn.branches)}),k0=J.z.strictObject({key:bu,references:J.z.number().int().nonnegative(),coveredTargets:J.z.number().int().nonnegative(),expiredTargets:J.z.number().int().nonnegative(),uncertainTargets:J.z.number().int().nonnegative()}),$E=J.z.strictObject({available:J.z.boolean().default(!0),settings:R0,expectedTargets:J.z.number().int().min(0).max(80),features:J.z.array(k0).max(2001),truncated:J.z.boolean()});var St=require("zod");var j0=St.z.enum(["checkout.session.completed","checkout.session.expired","checkout.session.async_payment_succeeded","checkout.session.async_payment_failed","customer.subscription.created","customer.subscription.updated","customer.subscription.deleted","customer.subscription.paused","customer.subscription.resumed","invoice.created","invoice.paid","customer.discount.created","customer.discount.updated","refund.created","refund.updated","refund.failed","charge.refunded"]),T0=St.z.strictObject({provider:St.z.literal("stripe"),accountId:St.z.string().regex(/^acct_[A-Za-z0-9]+$/),eventId:St.z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),type:j0,occurredAt:St.z.number().int().positive().max(Number.MAX_SAFE_INTEGER),data:St.z.record(St.z.string(),St.z.unknown()).and(St.z.object({id:St.z.string().min(1).max(255),object:St.z.enum(["checkout.session","subscription","invoice","discount","refund","charge"]),livemode:St.z.boolean()}))}),Ig=St.z.union([T0,Pl]),vg=St.z.strictObject({id:St.z.uuid(),eventId:St.z.string().min(1).max(200),source:St.z.literal("merchant"),providerVerified:St.z.literal(!1),outcome:St.z.string().min(1).max(100)});var Vt=require("zod"),Og={customerId:Vt.z.uuid(),eventId:Vt.z.string().trim().min(1).max(200),grantId:Vt.z.uuid(),occurredAt:Vt.z.iso.datetime({offset:!0})},Pg=Vt.z.strictObject({...Og,productVersionId:Vt.z.uuid(),subscriptionId:Vt.z.string().trim().min(1).max(255)}),Cg=Vt.z.strictObject({...Og,merchandiseId:Vt.z.uuid()}),_g=Vt.z.union([Pg,Cg]),wg={id:Vt.z.uuid(),couponId:Vt.z.uuid(),status:Vt.z.literal("redeemed"),source:Vt.z.literal("merchant"),recordedAt:Vt.z.iso.datetime({offset:!0})},Eg=Vt.z.union([Pg.extend(wg),Cg.extend(wg)]);var re=require("zod");var Rg=tm,N0=Rg.extend({invoice_id:Rg.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),Iu=re.z.strictObject({name:re.z.string().trim().min(1).max(255),memo:re.z.string().max(1e4).nullable().optional(),footer:re.z.string().max(1e4).nullable().optional(),net_terms_days:re.z.number().int().positive().nullable().optional()}),D0=Iu.extend({id:re.z.string().min(1).max(255),created_at:re.z.number().nullable()}),kg=re.z.strictObject({items:re.z.array(D0).max(50),nextCursor:re.z.uuid().nullable()}),ZE=re.z.discriminatedUnion("action",[re.z.strictObject({action:re.z.literal("create"),requestId:re.z.uuid(),values:Iu}),re.z.strictObject({action:re.z.literal("update"),id:re.z.string().min(1).max(255),values:Iu}),re.z.strictObject({action:re.z.literal("delete"),id:re.z.string().min(1).max(255)})]),jg=re.z.discriminatedUnion("action",[re.z.strictObject({action:re.z.literal("create"),requestId:re.z.uuid(),params:mi}),re.z.strictObject({action:re.z.enum(["finalize","send","pay","void"]),requestId:re.z.uuid(),invoiceId:re.z.uuid()}),re.z.strictObject({action:re.z.literal("reissue"),requestId:re.z.uuid(),invoiceId:re.z.uuid(),params:N0})]),vu=re.z.strictObject({id:re.z.uuid(),customerId:re.z.uuid(),providerInvoiceId:re.z.string().nullable(),status:re.z.enum(["draft","open","paid","void","uncollectible"]),currency:re.z.string(),totalMinor:re.z.string().regex(/^-?\d+$/),paidMinor:re.z.string().regex(/^\d+$/),refundedMinor:re.z.string().regex(/^\d+$/),hostedInvoiceUrl:re.z.url().nullable(),createdAt:re.z.number(),collectionMethod:re.z.enum(["send_invoice","charge_automatically"]).nullable()}),Tg=vu.extend({lines:re.z.array(re.z.strictObject({id:re.z.uuid(),description:re.z.string(),amountMinor:re.z.string().regex(/^-?\d+$/),netAmountMinor:re.z.string().regex(/^-?\d+$/),quantity:re.z.number().nullable(),periodStart:re.z.number().nullable(),periodEnd:re.z.number().nullable()})).max(1e3)}),Pi=re.z.strictObject({taskId:re.z.uuid(),status:re.z.enum(["ready","running","done","dead"]),invoice:vu.nullable(),errorCode:re.z.string().nullable()}),Ng=re.z.strictObject({items:re.z.array(vu).max(50),nextCursor:re.z.uuid().nullable(),operations:re.z.array(Pi).max(50),operationsLimited:re.z.boolean()});var F0=v.z.enum(["customers:read","customers:write","entitlements:read","content:read","sessions:create","funnels:run","offers:resolve","offers:grant","billing:read","billing:write","credits:read","credits:consume","credits:manage","features:read","events:write","messaging:write","code-references:read","code-references:write","app-manifests:write"]),Dg={scope:Ne,permissions:v.z.array(F0),expiresAt:v.z.iso.datetime().nullable()},LR=v.z.discriminatedUnion("kind",[v.z.object({...Dg,kind:v.z.literal("server"),keyId:v.z.string().min(1)}),v.z.object({...Dg,kind:v.z.literal("customer"),customerId:v.z.string().min(1),identityKind:v.z.enum(["identified","guest"]),expiresAt:v.z.iso.datetime()})]),z=v.z.object({requestId:v.z.uuid(),scope:Ne}).strict(),M0=yf.safeExtend({fingerprint:za.optional()}).strict(),q0=z.extend({customer:Si,created:v.z.boolean()});function Fg(){return z.extend({offer:Li.nullable(),reason:jd.nullable()})}var O={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:Ip,response:z.extend({message:v.z.object({messageId:v.z.uuid(),channel:Yi,acceptedAt:v.z.iso.datetime({offset:!0}),status:v.z.enum(["accepted","sending","completed","canceled"]),replayed:v.z.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:v.z.strictObject({messageId:v.z.uuid()}),response:z.extend({message:v.z.object({id:v.z.uuid(),channel:Yi,status:v.z.enum(["accepted","sending","completed","canceled"]),deliveries:v.z.array(v.z.object({id:v.z.uuid(),status:wp,attempts:v.z.number().int().nonnegative(),receipts:v.z.array(v.z.object({kind:Op,occurredAt:v.z.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:ul,response:z.extend({installation:Sr})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:ll,response:z.extend({installation:Sr})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:Do,response:z.extend({installation:Sr})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:v.z.strictObject({channel:Yi}),response:z.extend({preference:Ss})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:vp,response:z.extend({preference:Ss})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:v.z.strictObject({cursor:v.z.uuid().optional()}),response:z.extend({templates:kg})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),params:mi}),response:z.extend({preview:Ic})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),requestId:v.z.uuid(),params:mi}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:z.extend({operation:Pi})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),command:jg}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:z.extend({operation:Pi})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),taskId:v.z.uuid()}),response:z.extend({operation:Pi})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),cursor:v.z.uuid().optional()}),response:z.extend({invoices:Ng})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),invoiceId:v.z.uuid()}),response:z.extend({invoice:Tg})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:xg,response:z.extend({config:Sg})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:xu,response:z.extend({receipt:Su})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:v.z.strictObject({}),response:z.extend({payload:po})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:Km,response:z.merge(Ta)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:Hm,response:z.merge(Qm)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),sourceId:v.z.uuid()}),response:z.extend({balance:Gf})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),command:$f}),response:z.extend({balance:fu})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:v.z.strictObject({internal_feature_id:v.z.uuid(),customerId:v.z.uuid().optional(),entityId:v.z.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:z.extend({internal_feature_id:v.z.uuid(),config:Fs,model_markups:Ko})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),query:da}),response:z.extend({usage:Ji})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),command:mp}),response:z.extend({usage:Ji})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),command:sp}),response:z.extend({grant:oc})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:cp,response:z.extend({grants:up})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:v.z.union(Nm.options.map(e=>e.extend({customerId:v.z.uuid().optional(),customerToken:v.z.string().regex(jt).optional()}))),response:z.extend({operation:Dm})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:vm.extend({customerId:v.z.uuid().optional()}),response:z.extend({setup:Cc})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:wm.extend({customerId:v.z.uuid().optional()}),response:z.extend({setup:Cc})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:xm.safeExtend({customerId:v.z.uuid()}),response:z.extend({batch:ao})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:Pa.extend({customerId:v.z.uuid()}),response:z.extend({batch:ao})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:Pa.extend({customerId:v.z.uuid()}),response:z.extend({batch:ao})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:Pa.extend({customerId:v.z.uuid()}),response:z.extend({batch:ao})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:v.z.discriminatedUnion("action",[Ca.options[0].extend({customerId:v.z.uuid()}),Ca.options[1].extend({customerId:v.z.uuid()}),Ca.options[2].extend({customerId:v.z.uuid()})]),response:z.extend({trial:Pc})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Sm.extend({customerId:v.z.uuid()}),response:z.extend({trial:Pc})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:Ra,response:z.extend({subscriptions:km})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:Ra,response:z.extend({purchases:jm})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:_m,response:z.extend({conflicts:Tm})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:Em,response:z.extend({resolution:Rm})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:Pm,response:z.extend({verification:Cm})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:pm.safeExtend({...di,customerId:v.z.uuid().optional()}),response:z.extend({quote:fi})},recordBillingEvent:{method:"POST",path:"billing/events/record",permission:"billing:write",audience:"server",request:Ig,response:z.extend({record:vg})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Mr.extend({customerId:v.z.uuid().optional(),intent:v.z.enum(["confirm","cancel"]).optional()}),response:z.extend({operation:gi})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Mr.extend({customerId:v.z.uuid().optional()}),response:z.extend({operation:gi})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:gm.safeExtend({customerId:v.z.uuid().optional()}),response:z.extend({quote:Am})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Mr.extend({customerId:v.z.uuid().optional(),intent:v.z.enum(["confirm","cancel"]).optional()}),response:z.extend({operation:vc})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Mr.extend({customerId:v.z.uuid().optional()}),response:z.extend({operation:vc})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:ym.safeExtend({customerId:v.z.uuid()}),response:z.extend({quote:wc})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Mr.extend({customerId:v.z.uuid()}),response:z.extend({operation:Oa})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Mr.extend({customerId:v.z.uuid()}),response:z.extend({operation:Oa})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:Kd,response:z.extend({controls:rc})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:Bd,response:z.extend({prepared:Ld})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:Ud,response:z.extend({authorization:sa})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Wd,response:z.extend({coupons:Yd})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:zd,response:z.extend({authorization:sa})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:Jd,response:z.extend({invoices:Zd})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:Qd.extend({customerId:v.z.uuid()}),response:z.extend({operation:Pi})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:Hd,response:z.extend({invoice:$i})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:v.z.object({customerId:v.z.uuid(),command:Gd}).strict(),response:z.extend({controls:rc})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:v.z.object({customerId:v.z.uuid(),command:Kf}).strict(),response:z.extend({entity:Hf})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:v.z.strictObject({customerId:v.z.uuid().nullable(),query:Xf}),response:z.extend({analytics:eg})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:v.z.object({customerId:v.z.uuid().nullable(),query:Gr}).strict(),response:z.extend({analytics:Wf})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:tg,response:z.extend({batchId:v.z.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:ng,response:z.extend({batch:rg})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:Ep.extend({customerId:v.z.string().min(1).optional()}),response:z.extend({check:Tr})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:v.z.strictObject({kind:rr,selector:v.z.discriminatedUnion("type",[v.z.strictObject({type:v.z.literal("resource"),id:v.z.uuid()}),v.z.strictObject({type:v.z.literal("version"),id:v.z.uuid()})]),customerId:v.z.string().min(1).optional()}),response:z.extend({content:bc})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Lf,response:z.extend({paywall:Ur})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:v.z.strictObject({processContext:Sa.optional(),...di,selector:Bm,customerId:v.z.string().min(1).optional(),commerce:ai,requirement:er.optional()}),response:z.extend({offering:Vm,candidates:v.z.array(lc).max(20),availability:v.z.array(v.z.strictObject({productVersionId:v.z.uuid(),available:v.z.boolean(),reason:v.z.enum(["platform_binding_missing","commercial_runtime_pending","commerce_not_configured","currency_mismatch","product_unavailable","already_attached","attach_in_progress","already_scheduled","subscription_change_required","purchase_conflict"]).nullable()})).max(20),check:Tr.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:v.z.object({customerId:v.z.uuid().optional(),entityId:v.z.uuid().optional()}).strict(),response:z.extend({holdings:fp})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:v.z.object({customerId:v.z.uuid().optional(),query:hp}).strict(),response:z.extend({ledger:Ap})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:lp.extend({customerId:v.z.uuid().optional()}),response:z.extend({detail:dp})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:ac.safeExtend({customerId:v.z.uuid().optional()}),response:z.extend({statement:pp})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:v.z.object({customerId:v.z.uuid().optional(),command:Hi.options[0]}).strict(),response:z.extend({quote:ip})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),command:v.z.union([v.z.strictObject({eventName:v.z.string().min(1),quantity:Ae.optional(),properties:wt.optional(),entityId:v.z.uuid().optional(),idempotencyKey:v.z.string().min(1).max(120)}),v.z.strictObject({internal_feature_id:v.z.uuid(),quantity:Ae.optional(),properties:wt.optional(),entityId:v.z.uuid().optional(),idempotencyKey:v.z.string().min(1).max(120)})])}),response:z.extend({receipts:v.z.array(Qi).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:v.z.object({customerId:v.z.uuid(),command:Hi.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:z.extend({receipt:Qi})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:pg,response:z.extend({redemption:dg})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:gg,response:z.extend({referralCode:hg})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:mg,response:z.extend({checkout:fg})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:bp,response:z.extend({seats:uc})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:xp,response:z.extend({seats:uc})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:M0,response:q0},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Wc,response:z.extend({customer:Si})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:Sf,response:z.extend(If.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:xf,response:z.extend(bf.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:v.z.object({customerId:v.z.uuid()}).strict(),response:z.extend(Qn.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:v.z.strictObject({}),response:z.extend(Qn.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:v.z.strictObject({customerId:v.z.uuid(),sessionId:v.z.uuid().optional()}),response:z.extend({revoked:v.z.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:v.z.strictObject({guestToken:v.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:za.optional()}),response:z.extend({customerId:v.z.uuid(),guestToken:v.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:v.z.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:v.z.strictObject({guestToken:v.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:z.extend(Qn.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:v.z.strictObject({guestToken:v.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:v.z.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:v.z.uuid()}),response:z.extend({customer:Si,switched:v.z.boolean(),replayed:v.z.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:v.z.strictObject({code:v.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:v.z.uuid()}),response:Fg()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:v.z.object({}).strict(),response:z.extend({offers:v.z.array(Li)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:v.z.object({customerId:v.z.string().min(1).max(255).optional(),couponId:v.z.uuid(),...di,requestId:v.z.uuid(),couponContentDigest:v.z.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:Fg()},recordCouponRedemption:{method:"POST",path:"offers/redemptions",permission:"billing:write",audience:"server",request:_g,response:z.extend({receipt:Eg})}},UR={recordBillingEvent:O.recordBillingEvent,sendMessage:O.sendMessage,readMessage:O.readMessage,bindPushInstallation:O.bindPushInstallation,readPushInstallation:O.readPushInstallation,updatePushAddress:O.updatePushAddress,readMessagingPreference:O.readMessagingPreference,setMessagingPreference:O.setMessagingPreference,listInvoiceTemplates:O.listInvoiceTemplates,previewInvoice:O.previewInvoice,createInvoice:O.createInvoice,manageInvoice:O.manageInvoice,readInvoiceOperation:O.readInvoiceOperation,listInvoices:O.listInvoices,getInvoice:O.getInvoice,getCodeReferenceConfig:O.getCodeReferenceConfig,submitCodeReferences:O.submitCodeReferences,getFeatures:O.getFeatures,evaluateFeatures:O.evaluateFeatures,trackEvents:O.trackEvents,setupPayment:O.setupPayment,readPaymentSetup:O.readPaymentSetup,previewSubscriptionBatch:O.previewSubscriptionBatch,confirmSubscriptionBatch:O.confirmSubscriptionBatch,readSubscriptionBatch:O.readSubscriptionBatch,abandonSubscriptionBatch:O.abandonSubscriptionBatch,manageSubscriptionTrial:O.manageSubscriptionTrial,readSubscriptionTrial:O.readSubscriptionTrial,listSubscriptions:O.listSubscriptions,listPurchases:O.listPurchases,listSubscriptionConflicts:O.listSubscriptionConflicts,retrySubscriptionConflict:O.retrySubscriptionConflict,readAiPricing:O.readAiPricing,readUsage:O.readUsage,setUsage:O.setUsage,previewRefund:O.previewRefund,refund:O.refund,readRefund:O.readRefund,previewUpdate:O.previewUpdate,update:O.update,readSubscriptionUpdate:O.readSubscriptionUpdate,restoreNativePurchase:O.restoreNativePurchase,verifySubscriptions:O.verifySubscriptions,previewAttach:O.previewAttach,attach:O.attach,readSubscriptionOperation:O.readSubscriptionOperation,manageBalanceGrant:O.manageBalanceGrant,readBalanceSource:O.readBalanceSource,adjustBalance:O.adjustBalance,listBalanceGrants:O.listBalanceGrants,readBillingControls:O.readBillingControls,prepareBillingAuthorization:O.prepareBillingAuthorization,confirmBillingAuthorization:O.confirmBillingAuthorization,setBillingCoupons:O.setBillingCoupons,revokeBillingAuthorization:O.revokeBillingAuthorization,listBillingInvoices:O.listBillingInvoices,confirmBillingAdjustment:O.confirmBillingAdjustment,prepareBillingAdjustment:O.prepareBillingAdjustment,manageBillingLimits:O.manageBillingLimits,createCustomer:O.createCustomer,getCustomer:O.getCustomer,listCustomers:O.listCustomers,updateCustomer:O.updateCustomer,createSession:O.createSession,refreshSession:O.refreshSession,revokeSessions:O.revokeSessions,createGuestCustomer:O.createGuestCustomer,resumeGuestSession:O.resumeGuestSession,claimGuestCustomer:O.claimGuestCustomer,checkEntitlement:O.checkEntitlement,resolveOffering:O.resolveOffering,resolveContent:O.resolveContent,resolvePaywall:O.resolvePaywall,readHoldings:O.readHoldings,readLedger:O.readLedger,readBillingInvoice:O.readBillingInvoice,readCreditStatement:O.readCreditStatement,quoteBalance:O.quoteBalance,trackUsage:O.trackUsage,mutateBalance:O.mutateBalance,manageUsageEntity:O.manageUsageEntity,readUsageAnalytics:O.readUsageAnalytics,readCreditAnalytics:O.readCreditAnalytics,submitUsageBatch:O.submitUsageBatch,readUsageBatch:O.readUsageBatch,listOffers:O.listOffers,grantOffer:O.grantOffer,recordCouponRedemption:O.recordCouponRedemption,redeemCoupon:O.redeemCoupon,redeemReward:O.redeemReward,createReferralCode:O.createReferralCode,claimRewardProduct:O.claimRewardProduct,readSeats:O.readSeats,manageSeat:O.manageSeat};var Xa=require("zod");var xo=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function wu(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=>Wt(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 xo("Required GB Feature is unavailable");i=Ln(e.featureKey,t),o=i.value,Object.assign(r,li(e,{value:o})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new xo("Required GB Experiment is unavailable");if(a=oa(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 xo("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:Ln(e.configuration.featureKey,t).value;o={type:"offering_version",id:Xa.z.uuid().parse(u)},Object.assign(r,li(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,li(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 Mg(e,t,n){Xa.z.uuid().parse(e),Xa.z.number().int().nonnegative().parse(t);let r=ei(ti(new TextEncoder().encode(JSON.stringify([e,t,n])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}var K=require("zod");var ur=K.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),B0=K.z.enum(["running","waiting","completed","closed","ineligible","failed"]),Ou=K.z.discriminatedUnion("type",[Jc,K.z.strictObject({type:K.z.literal("wait"),receiptId:K.z.uuid(),kind:K.z.enum(["timer","event","operation"]),deadline:K.z.iso.datetime({offset:!0}).nullable(),eventName:ur.optional()}),K.z.strictObject({type:K.z.literal("open_url"),receiptId:K.z.uuid(),url:Yc,openIn:Xc}),K.z.strictObject({type:K.z.literal("event"),receiptId:K.z.uuid(),event:ur})]),es=K.z.strictObject({type:K.z.literal("funnel"),id:K.z.uuid(),versionId:K.z.uuid()}),V0={id:ur,presentation:Kn,outputs:K.z.array(ur).max(250),inputs:Ma,values:K.z.record(K.z.string(),Se).optional(),offeringKey:yt.optional(),capabilities:si,customerData:Fp,dataCursors:K.z.record(ur,Fa.nullable())},L0=K.z.strictObject({...V0,content:K.z.strictObject({type:K.z.literal("document"),document:sn})}),So=K.z.strictObject({id:K.z.uuid(),source:es,revision:K.z.number().int().nonnegative(),visit:K.z.number().int().nonnegative(),nodeId:ur,nodeType:K.z.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:B0,stopped:K.z.boolean(),canBack:K.z.boolean(),authenticated:K.z.boolean(),locale:K.z.string().min(1).max(35),answers:or,parameters:ar,variables:K.z.record(K.z.string(),Se),output:Se.nullable(),screen:L0.nullable(),paywall:K.z.strictObject({receiptId:K.z.uuid(),resolution:K.z.union([Ao,Ur]),quote:fi.nullable(),operation:gi.nullable(),purchaseRequestId:K.z.uuid().nullable(),selectionGeneration:K.z.number().int().nonnegative().optional(),canReselect:K.z.boolean().optional()}).nullable(),instruction:Ou.nullable(),pendingRequest:K.z.strictObject({requestId:K.z.uuid(),authenticationRequired:K.z.boolean()}).nullable(),runExpiresAt:K.z.iso.datetime({offset:!0}),credentialExpiresAt:K.z.iso.datetime({offset:!0}).nullable()}),ts=K.z.strictObject({scope:Ne,run:So,settlement:K.z.strictObject({requestId:K.z.uuid(),state:K.z.enum(["pending","unknown","settled"]),operationId:K.z.uuid().nullable(),receiptId:K.z.uuid().nullable().optional()}).optional(),purchase:K.z.strictObject({receiptId:K.z.uuid(),quote:fi.nullable(),operation:gi.nullable(),canReselect:K.z.boolean().optional()}).optional(),review:K.z.strictObject({activeOperationId:K.z.uuid().nullable(),pages:K.z.array(K.z.strictObject({receiptId:K.z.uuid(),nodeId:ur,visit:K.z.number().int().nonnegative()})).max(100),page:K.z.strictObject({receiptId:K.z.uuid(),nodeId:ur,visit:K.z.number().int().nonnegative(),document:sn,answers:or,inputs:Ma,values:K.z.record(K.z.string(),Se).optional()}).nullable(),coupons:K.z.array(K.z.strictObject({grantId:K.z.uuid(),status:K.z.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:K.z.string().nullable()})).max(100),purchases:K.z.array(K.z.strictObject({receiptId:K.z.uuid(),operationId:K.z.uuid(),status:K.z.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:K.z.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:K.z.uuid().optional()}),qg=ts.extend({run:So.extend({paywall:So.shape.paywall.unwrap().extend({resolution:Ur}).nullable()})});var Bg="X-Indiana-Server-Key";var oe=require("zod");var ge=require("zod");var It=require("zod");var U0=It.z.strictObject({selector:It.z.string().min(1).max(2048),action:It.z.enum(["set","append","remove"]),attribute:It.z.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:It.z.string().max(5e4).optional(),parentSelector:It.z.string().max(2048).optional(),insertBeforeSelector:It.z.string().max(2048).optional()}),z0=It.z.strictObject({variation:It.z.string().min(1).max(128),description:It.z.string().max(2e3).default(""),css:It.z.string().max(1e5).default(""),js:It.z.string().max(1e5).default(""),domMutations:It.z.array(U0).max(200).default([]),iam:rf.optional(),renderGuard:Na.optional()}),Pu=z0.omit({variation:!0,description:!0,iam:!0}),$0=bi.omit({variations:!0,active:!0}).extend({changeId:It.z.string().regex(/^[a-f0-9]{64}$/),variations:It.z.tuple([Pu,Pu]).rest(Pu).refine(e=>e.length<=20)}),Vg=It.z.strictObject({trackExposures:It.z.boolean(),environmentId:It.z.uuid(),generation:It.z.string().regex(/^[a-f0-9]{64}$/),experiments:It.z.array($0).max(100),savedGroups:lo});var Io=ge.z.string().regex(/^[a-f0-9]{64}$/),yk=ge.z.strictObject({iam:Io,executionContracts:ge.z.union([ge.z.tuple([ge.z.literal("funnel-run/1")]),ge.z.tuple([ge.z.literal("funnel-process/1")])]).default(["funnel-run/1"])}),G0=ge.z.strictObject({release:Io,render:Na,button:ge.z.strictObject({selector:ge.z.string().min(1).max(512),elementKey:ge.z.string().min(1).max(256),tag:ge.z.enum(["button","a","input"])}).nullable()}),bk=ge.z.strictObject({scope:Ne.extend({environmentId:ge.z.uuid()}),release:Io,validatedAt:ge.z.iso.datetime({offset:!0}),validUntil:ge.z.iso.datetime({offset:!0}),entries:ge.z.array(ge.z.strictObject({id:ge.z.uuid(),funnelId:ge.z.uuid(),versionId:ge.z.uuid(),event:ge.z.enum(["screen_enter","button_click"]),target:G0})).max(4e3)}),Lg=ge.z.strictObject({operation:ge.z.literal("entry_start"),funnelId:ge.z.uuid(),versionId:ge.z.uuid(),entryId:ge.z.uuid(),release:Io,requestId:ge.z.uuid(),locale:ge.z.string().min(1).max(35).default("en")}),Ug=ge.z.strictObject({scope:Ne,suppressed:ge.z.literal(!0),reason:ge.z.enum(["frequency","in_progress"]),retryAt:ge.z.iso.datetime({offset:!0}).nullable()}),xk=ge.z.strictObject({experimentId:ge.z.uuid(),splitNodeId:ge.z.string().min(1).max(128)}),K0=ge.z.strictObject({experimentId:ge.z.uuid(),experimentKey:ge.z.string().min(1).max(128),variationKey:ge.z.string().min(1).max(128),inExperiment:ge.z.boolean(),generation:ge.z.string().min(1).max(256)}),vo=ge.z.strictObject({operation:ge.z.literal("page_experiments"),release:Io,usedReceiptIds:ge.z.array(ge.z.uuid()).max(20).default([]),customerToken:ge.z.string().regex(jt).optional()}),zg=ge.z.strictObject({scope:Ne,runId:ge.z.uuid(),assignments:ge.z.array(K0.extend({receiptId:ge.z.uuid()})).max(100),payload:Vg});var Pn=oe.z.literal(Wm),H0=oe.z.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),Cu=oe.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),$g=oe.z.discriminatedUnion("type",[oe.z.strictObject({type:oe.z.literal("guest"),guestToken:Cu}),oe.z.strictObject({type:oe.z.literal("customer"),customer:Vr,customerData:xi.optional()})]),_u=oe.z.strictObject({id:oe.z.uuid(),runId:oe.z.uuid(),customerId:oe.z.uuid(),requestId:oe.z.uuid(),acceptedAt:oe.z.iso.datetime({offset:!0})}),Q0=oe.z.strictObject({participantId:oe.z.uuid(),startedAs:oe.z.enum(["guest","identified"]),binding:_u.omit({runId:!0,requestId:!0}).nullable()}),J0=oe.z.union([Ou,oe.z.strictObject({type:oe.z.literal("authentication_required"),reason:oe.z.enum(["customer_required","customer_experiment_required"]),nodeId:oe.z.string().min(1).max(64),visit:oe.z.number().int().nonnegative()})]),Z0=So.omit({authenticated:!0}).extend({identity:Q0,instruction:J0.nullable()}),W0=oe.z.discriminatedUnion("operation",[Pt.options[2].omit({customerToken:!0}),Pt.options[3].omit({customerToken:!0}),Pt.options[4].omit({customerToken:!0}),Pt.options[5].omit({customerToken:!0}),Pt.options[6].omit({customerToken:!0}),Pt.options[7].omit({customerToken:!0})]),ns={contract:Pn,customerToken:oe.z.string().regex(jt)},Gg={contract:Pn,requestId:oe.z.uuid(),runToken:H0,externalUserId:Vr.options[1].shape.value},Kg=oe.z.discriminatedUnion("operation",[oe.z.strictObject({contract:Pn,operation:oe.z.literal("describe")}),oe.z.strictObject({contract:Pn,operation:oe.z.literal("start"),source:$g,funnelId:Pt.options[0].shape.funnelId,requestId:oe.z.uuid(),locale:Pt.options[0].shape.locale,parameters:Pt.options[0].shape.parameters}),Lg.omit({operation:!0}).extend({contract:Pn,operation:oe.z.literal("entry_start"),source:$g}),oe.z.strictObject({...Gg,operation:oe.z.literal("bind_customer"),guestToken:Cu,claimRequestId:oe.z.uuid(),expectedBindingId:oe.z.null()}),oe.z.strictObject({...Gg,operation:oe.z.literal("binding_status"),guestToken:Cu.optional()}),Pt.options[1].omit({operation:!0,customerToken:!0}).extend({...ns,operation:oe.z.literal("get"),settlementBindingId:oe.z.uuid().nullable().optional()}),Pt.options[8].omit({operation:!0,customerToken:!0}).extend({...ns,operation:oe.z.literal("review")}),vo.omit({customerToken:!0}).extend(ns),oe.z.strictObject({...ns,operation:oe.z.literal("command"),identity:oe.z.strictObject({bindingId:oe.z.uuid().nullable()}),command:W0})]),Eu=ts.omit({run:!0}).extend({contract:Pn,run:Z0,settlement:ts.shape.settlement.unwrap().extend({accepted:oe.z.boolean().nullable().optional()}).optional()}),Ek=Ug.extend({contract:Pn}),Rk=oe.z.discriminatedUnion("operation",[Kg.options[1].omit({contract:!0,source:!0,requestId:!0}),Kg.options[2].omit({contract:!0,source:!0,requestId:!0})]),kk=Eu.extend({binding:_u,outcome:oe.z.enum(["bound","already_bound"]),replayed:oe.z.boolean()}),jk=oe.z.discriminatedUnion("state",[oe.z.strictObject({contract:Pn,scope:Ne,state:oe.z.literal("not_accepted")}),oe.z.strictObject({contract:Pn,scope:Ne,state:oe.z.literal("conflict")}),oe.z.strictObject({contract:Pn,scope:Ne,state:oe.z.literal("bound"),binding:_u})]),Tk=oe.z.strictObject({contract:Pn,scope:Ne,keyId:oe.z.uuid(),operations:oe.z.array(oe.z.string()).max(20)});var je=require("zod");var Ci=je.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Qg=je.z.strictObject({entry:Ci,nodes:je.z.array(je.z.strictObject({id:Ci,type:je.z.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:je.z.record(je.z.string(),Ci),writes:je.z.record(yt,yt),resources:je.z.strictObject({screenId:Ci.optional(),paywallVersionId:je.z.uuid().optional(),couponId:je.z.uuid().optional(),couponIds:je.z.array(je.z.uuid()).max(20).optional(),experimentId:je.z.uuid().optional(),featureKey:je.z.string().optional(),offeringVersionId:je.z.uuid().optional()})})).min(1).max(500)}),Hg={scope:Ne,funnelId:je.z.uuid(),versionId:je.z.uuid(),evaluationRevision:je.z.number().int().nonnegative(),expiresAt:je.z.iso.datetime({offset:!0}).nullable(),topology:Qg},rs=je.z.discriminatedUnion("evaluationMode",[je.z.strictObject({...Hg,evaluationMode:je.z.literal("local"),growth:gn,conditions:je.z.record(Ci,je.z.array(je.z.strictObject({condition:Jt,port:je.z.string()})))}),je.z.strictObject({...Hg,evaluationMode:je.z.literal("remote")})]),Y0=rs.options[0].extend({evaluation:je.z.strictObject({maxTransitions:je.z.number().int().min(1).max(1e4),variables:je.z.record(yt,ui),outputSchema:ci,terminals:je.z.record(Ci,je.z.strictObject({outcome:je.z.enum(["completed","closed","ineligible","failed"]),output:fo.nullable()}))})});function X0(e){return Qg.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=je.z.uuid().parse(t.action.coupon.value.id));break;case"external_page":n.opened=t.opened,n.failed=t.failed;break;case"wait":t.wait.type==="duration"?n.elapsed=t.wait.elapsed:(n.received=t.wait.received,n.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let i=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return i?.type==="feature"&&(r.featureKey=i.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:n,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function Ru(e){let t=vi.parse(e.document),n=e.evaluationMode==="local"?gn.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:X0(t)};return rs.parse(e.evaluationMode==="remote"?r:{...r,growth:Za(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 Jg(e){let t=Ru(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=vi.parse(e.document);return Y0.parse({...t,evaluation:{maxTransitions:n.execution.maxTransitions,variables:n.variables,outputSchema:n.outputSchema,terminals:Object.fromEntries(n.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}var et=require("zod");var Zg=et.z.string().regex(/^[a-f0-9]{64}$/),eI=bi.omit({variations:!0,active:!0}).extend({changeId:Zg,variations:et.z.array(et.z.strictObject({urlRedirect:et.z.string().max(2048)})).min(2).max(20)}),Wg=et.z.strictObject({environmentId:et.z.uuid(),trackExposures:et.z.boolean(),generation:Zg,experiments:et.z.array(eI).max(100),savedGroups:lo}),tI=et.z.strictObject({eventUuid:et.z.uuid(),timestamp:et.z.iso.datetime({offset:!0}).optional(),deviceId:et.z.string().min(1).max(128),sessionId:et.z.string().min(1).max(128).optional(),url:et.z.url().max(2048),pageTitle:et.z.string().max(512).optional(),experimentKey:et.z.string().min(1).max(255),variationKey:et.z.string().min(1).max(64)}),$k=et.z.strictObject({events:et.z.array(tI).min(1).max(20)}),Gk=et.z.strictObject({inserted:et.z.number().int().nonnegative(),duplicates:et.z.number().int().nonnegative(),skipped:et.z.number().int().nonnegative(),rejected:et.z.array(et.z.strictObject({index:et.z.number().int().nonnegative(),reason:et.z.string()}))});var ot=require("zod");var ju=32,nI=522240;function Tu(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 rI=ot.z.strictObject({nodeId:ot.z.string().min(1).max(64),visit:ot.z.number().int().nonnegative(),revision:ot.z.number().int().nonnegative()}),ku=ot.z.record(ot.z.string(),Se),iI=ot.z.strictObject({id:ot.z.uuid(),nodeId:ot.z.string().min(1).max(64),visit:ot.z.number().int().nonnegative(),input:ot.z.strictObject({schemaVersion:go.shape.schemaVersion,kind:go.shape.kind,selector:go.shape.selector,contract:go.shape.contract}),context:ku,removed:ot.z.array(ot.z.string()).max(100),attributes:ku,removedAttributes:ot.z.array(ot.z.string()).max(100),result:Ef,offeringVersionId:ot.z.uuid().nullable(),events:ot.z.strictObject({entered:ot.z.string().regex(/^[1-9][0-9]{0,18}$/),decision:ot.z.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),Zk=ot.z.strictObject({schemaVersion:ot.z.literal(1),mode:ot.z.enum(["local","remote"]),versionId:ot.z.uuid(),generation:ot.z.number().int().positive(),base:rI,context:ku,steps:ot.z.array(iI).min(1).max(ju)}).refine(e=>cn(e)<=nI,"Segment exceeds its byte budget");var oI=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function wo(e){return Array.isArray(e)?e.some(wo):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&wo(n):!oI.test(t))}function Yg(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=>wo(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"||wo(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"||wo(s.condition)||s.parentConditions?.length)?"customer_experiment_required":null}var Nu=class extends Error{constructor(n,r){super(r);Fe(this,"code",n);this.name="FunnelLocalCalculationError"}},Xg=(e,t)=>new Nu(e,t),aI=e=>({experiments:e.experiments,features:e.features});function sI(e,t=Xg){let n=new Map(e.topology.nodes.map(o=>[o.id,o])),r=ni(e.growth.savedGroups),i=aI(e.growth);function a(o,s){if(!Object.hasOwn(e.growth.features,o))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Ln(o,s).value}return{nodes:n,savedGroups:r,features:i.features,feature:a,evaluate(o,s){let c=n.get(o);if(!c)throw t("NOT_FOUND","Funnel node is unavailable");let u,l;if(c.type==="condition"){let m=e.conditions[c.id];if(!m)throw t("INVALID_RESPONSE","Local condition rules are unavailable");u=wu({id:c.id,name:c.id,type:"condition",cases:m.map(h=>({condition:h.condition,target:c.outputs[h.port]})),default:c.outputs.default},s,i.experiments).port}else if(c.type==="feature"){if(!c.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");l=a(c.resources.featureKey,s),u="next"}else if(c.type==="split"){if(!(c.resources.experimentId?e.growth.experiments[c.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let h=wu({id:c.id,name:c.id,type:"split",experimentId:c.resources.experimentId,routes:c.outputs,notParticipating:c.outputs.notParticipating},s,i.experiments);l=h.value,u=h.port}else if(["offering","end","output"].includes(c.type)&&c.resources.featureKey)l=a(c.resources.featureKey,s),u=c.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let f=c.outputs[u]??(u==="value"?c.id:void 0);if(!f)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:o,port:u,target:f,...l===void 0?{}:{value:l}}}}}function cI(e,t){let n=rs.parse(e);if(n.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=n.expiresAt?Date.parse(n.expiresAt):null,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let a=sI(n,t);return(o,s)=>(i(),uI(a,o,s))}function uI(e,t,n){let r=Ot.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 lI(e,t,n){let r=[],i=[],a=[],o=e(t,{...n.attributes?{attributes:n.attributes}:{},stickyBucketAssignmentDocs:n.sticky,saveStickyBucketAssignmentDoc(s){let c=r.findIndex(f=>f.next.attributeName===s.attributeName&&f.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(Se.parse({key:s.key,variationId:c.variationId,keyUsed:c.key,hashAttribute:c.hashAttribute,hashValue:c.hashValue}))},onFeatureUsage(s,c){a.push(Se.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 eh(e,t,n,r=Xg){let i=n,a=new Map(t.graph.nodes.map(k=>[k.id,k])),o=structuredClone(n.variables),s=structuredClone(i.sticky),c=[],u=n.nodeId,l=n.visit,f=!1,m,h=k=>Yg(t,k,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),d=k=>(m??(m=cI(e,r)),lI(m,k,{attributes:$c({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:o,savedGroups:{}}),sticky:s}));for(let k=0;k<ju;k++){let g=a.get(u);if(!g||!Tu(g)||h(g))break;if(l>=t.execution.maxTransitions&&(l>t.execution.maxTransitions||g.type!=="end"&&g.type!=="output")){if(!c.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let y,I;if(["condition","feature","split"].includes(g.type)||g.type==="offering"&&g.configuration.source==="feature")y=d(g.id),g.type==="offering"&&(y.value={type:"offering_version",id:String(y.value)}),g.type==="condition"?I=y.port==="default"?g.default:g.cases[Number(y.port.slice(5))]?.target:g.type==="split"?I=y.port==="notParticipating"?g.notParticipating:g.routes[y.port]:(g.type==="feature"||g.type==="offering")&&(I=g.next);else if(y={port:"next",sticky:[],exposures:[],features:[]},(g.type==="entry"||g.type==="coupon"||g.type==="coupons")&&(I=g.next),g.type==="offering"&&g.configuration.source==="fixed"&&(y.value={type:"offering_version",id:g.configuration.versionId},I=g.next),g.type==="end"||g.type==="output"){let C=g.type==="end"?g.output:g.value;if(y=C?.type==="feature"?d(g.id):{...y,port:"value",value:C?.type==="literal"?C.value:C?.type==="variable"?hc({source:"variable",key:C.key,...C.path?{path:C.path}:{}},{declarations:t.variables,answers:n.answers,results:o,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},C&&(y.value===void 0||!fn(t.outputSchema,y.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let w=[...c,{nodeId:u,result:y}];if(cn({steps:w})>6e4){if(!c.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(c.push({nodeId:u,result:y}),g.type==="feature"||g.type==="offering"||g.type==="coupon"||g.type==="coupons"){let C=g.type==="coupons"?g.couponIds.map(E=>({type:"reward",id:E})):g.type==="coupon"?{type:"reward",id:g.couponId}:y.value;if(C===void 0)throw r("INVALID_RESPONSE","Node output is missing");let j=li(g,{value:C});Up(t.variables,g,j),Object.assign(o,j)}for(let C of y.sticky)s[`${C.next.attributeName}||${C.next.attributeValue}`]=structuredClone(C.next);if(g.type==="end"||g.type==="output"){f=!0;break}if(!I)throw r("INVALID_RESPONSE","Local pure exit is unavailable");u=I,l++}let A=a.get(u);return{steps:c,...!f&&A&&(!Tu(A)||h(A))?{boundary:{nodeId:u,visit:l}}:{}}}var b=class extends Error{constructor(n,r,i,a,o){super(r);Fe(this,"code",n);Fe(this,"status",i);Fe(this,"requestId",a);Fe(this,"commandRequestId");Fe(this,"retryable");Fe(this,"recovery");Fe(this,"retryAfterSeconds");Fe(this,"reason");this.name="IndianaError",this.reason=o?.reason;let s=Fo(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 Oo=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new b("INVALID_STATE","Installation sequence exhausted");return e+1},dI=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 Tn(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 th(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=I=>{if(I!==i)throw new b("IDENTITY_CHANGED","Identity changed during Push operation")};async function f(I){let w=u();if(!w.sha256&&!globalThis.crypto?.subtle)throw new b("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let C=w.sha256?await w.sha256(Uint8Array.from(I,j=>j.charCodeAt(0))):await dI(I);if(!/^[a-f0-9]{64}$/.test(C))throw new b("INVALID_STATE","Push credential digest is invalid");return C}function m(I){let w=Sr.parse(I);if(w.installationId.toLowerCase()!==u().installationId.toLowerCase())throw new b("INVALID_RESPONSE","Push response belongs to another installation");return w}async function h(I,w){let C=u(),j={installationId:C.installationId,publicKey:C.publicKey,issuedAt:new Date().toISOString(),...w},E=await C.sign(fl(I,C.scope,j));return{...j,signature:E}}let d=(I,w,C)=>t.requestWithCredential?t.requestWithCredential(I,w,C):t.request(I,w);async function A(){let I=u(),w=i,C=r?await(t.session?.access()??r):null,j=Tn(I,ye=>ye),E;if(j.detachSeq!==null){let ye=j.detachSeq,gt=dl.parse(await h("detach",{sequence:ye,platform:I.platform}));try{let Je=await t.request("push/installations/detach",{...I.scope,...gt},"POST",{installationDetach:!0});if(!Je||typeof Je!="object"||!("installation"in Je))throw new b("INVALID_RESPONSE","Push detach acknowledgement is invalid");let Te=m(Je.installation);if(Te.bound||Te.identitySeq!==ye)throw new b("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(Je){if(Je instanceof b&&Je.status===404)E=Je;else if(!(Je instanceof b)||Je.status!==412)throw Je}E||Tn(I,Je=>({...Je,detachSeq:Je.detachSeq===ye?null:Je.detachSeq}))}if(l(w),!C){if(E)throw E;return null}let ae=O.bindPushInstallation,xe=ae.request.parse(await h("bind",{sequence:o,platform:I.platform,credentialDigest:await f(C)}));l(w);let Pe=ae.response.parse(await d(ae.path,xe,C));l(w);let Ee=m(Pe.installation);if(!Ee.bound||Ee.identitySeq!==o)throw new b("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return E&&j.detachSeq!==null&&o>j.detachSeq&&Tn(I,ye=>({...ye,detachSeq:ye.detachSeq===j.detachSeq?null:ye.detachSeq})),Ee}async function k(){u();let I=i,w=r?await(t.session?.access()??r):null;if(!w)throw new b("NOT_IDENTIFIED","Identify before reading this installation");let C=O.readPushInstallation,j=C.request.parse(await h("read",{credentialDigest:await f(w)}));l(I);let E=C.response.parse(await d(C.path,j,w));return l(I),m(E.installation)}function g(I=A){let w=s.catch(()=>{}).then(I);return s=w,w.catch(C=>{try{e?.onError?.(C instanceof Error?C:new Error("Push synchronization failed"))}catch{}}),w}async function y(I,w,C){let j=u(),E=w.identity,ae=w.observation,xe=r?await(t.session?.access()??r):null;if(l(E),ae!==a)throw new b("INVALID_STATE","Push observation changed during recovery");if(!xe)throw new b("NOT_IDENTIFIED","Identify before recovering a Push address");if(!I.connectionId||!I.kind||!I.token||!["granted","provisional"].includes(I.permission))throw new b("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await g(async()=>{if(l(E),await A(),l(E),ae!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let Pe=Tn(j,Te=>C?Te:{...Te,addressSeq:Oo(Te.addressSeq)}),ye=await h(C?"recovery_confirm":"recovery_request",{...I,sequence:Pe.addressSeq,credentialDigest:await f(xe),...C?{challenge:C}:{}}),gt=C?ml.parse(ye):pl.parse(ye);if(l(E),ae!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let Je=await d(`push/installations/recovery/${C?"confirm":"request"}`,gt,xe);if(l(E),ae!==a||Tn(j,Te=>Te).addressSeq!==Pe.addressSeq)throw new b("INVALID_STATE","Push observation changed during recovery");if(C){let Te=O.updatePushAddress.response.parse(Je),tt=m(Te.installation);if(!tt.bound||tt.identitySeq!==o||tt.addressSeq!==Pe.addressSeq||tt.connectionId!==I.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 xs.parse(Je.recovery)})}return{recoveryObserver(){u();let I={identity:i,observation:++a};return{async request(w){return xs.parse(await y(w,I))},async confirm(w,C){return Sr.parse(await y(C,I,w))}}},identify(I){if(!e)return;o=Tn(e,C=>({...C,identitySeq:Oo(C.identitySeq)})).identitySeq,r=I,i++,a++},reset(){if(e)try{Tn(e,I=>{let w=Oo(I.identitySeq);return{...I,identitySeq:w,detachSeq:w}})}finally{r=null,i++,a++}},start(){e&&!c&&g()},destroy(){c=!0,r=null,i++,a++},async sync(){return await g()},read:k,async recover(){let I=u(),w=i,C=o;return a++,await g(async()=>{l(w);let j=await k();return l(w),o=Tn(I,ae=>{if(ae.identitySeq!==C)throw new b("IDENTITY_CHANGED","A newer installation intent exists");return{...ae,identitySeq:Oo(Math.max(ae.identitySeq,j.identitySeq)),addressSeq:Math.max(ae.addressSeq,j.addressSeq)}}).identitySeq,await A()})},tokenObserver(){u();let I=++a,w=i;return async C=>{if(I!==a||w!==i)return null;let j=u(),E=r?await(t.session?.access()??r):null;if(!E)throw new b("NOT_IDENTIFIED","Identify before registering a Push token");if(await g(),l(w),I!==a)return null;let ae=Tn(j,ye=>({...ye,addressSeq:Oo(ye.addressSeq)})),xe=O.updatePushAddress,Pe=xe.request.parse(await h("address",{...C,sequence:ae.addressSeq,credentialDigest:await f(E)}));if(l(w),I!==a)return null;let Ee=await d(xe.path,Pe,E);return l(w),I!==a||Tn(j,ye=>ye).addressSeq!==ae.addressSeq?null:m(xe.response.parse(Ee).installation)}}}}var rh=require("zod");function nh(e,t,n,r){try{return e.parse(t)}catch(i){throw r&&i instanceof rh.ZodError?new b(n,r):i}}async function me(e,t,n,r={},i){let a=typeof r=="function"?{}:r,o=nh(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):nh(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 ih(e,t){let n={async preference(r){let i=O.readMessagingPreference;return(await me(e,i,{channel:r})).preference},async setPreference(r){let i=O.setMessagingPreference;return(await me(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 oh={name:"@tinkerlandai/longplay-sdk",version:"0.10.13",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 Ke(e){return typeof e=="string"?e:String(e)}var mI=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function fI(e){return e.replace(mI,"$1\uFFFD")}function qu(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 fh(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 ah(e){let t;if(Array.isArray(e)){let n=e.map(Ke);if(n.length===2)return n}else if((t=fh(e))!=null){let n=qu(t.next()),r=qu(t.next());if(!n.done&&!r.done)return[Ke(n.value),Ke(r.value)]}throw new TypeError("Each query pair must be an iterable [name, value] tuple")}var sh="0123456789ABCDEF",gI=/(?:%[0-9A-Fa-f]{2})+/g;function Nn(e){return`%${sh[e>>4&15]}${sh[15&e]}`}function gh(e,t,n=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?n&&e===32?"+":t(e)?Nn(e):String.fromCharCode(e):e<=2047?Nn(192|e>>6)+Nn(128|63&e):e<=65535?Nn(224|e>>12)+Nn(128|e>>6&63)+Nn(128|63&e):Nn(240|e>>18)+Nn(128|e>>12&63)+Nn(128|e>>6&63)+Nn(128|63&e)}function Bu(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function Vu(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(gI,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function _o(e){return e<=31||e>126}function hI(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return _o(e)}}function Hu(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return _o(e)}}function AI(e){return Hu(e)||e===39}function Lu(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return Hu(e)}}function cs(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 Lu(e)}}function ch(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 cs(n)}})(e)}}function hh(e,t){return gh(e=e||0,t)}function Dn(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+=gh(o,t,n)}return i}function Qu(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([Vu(i.slice(0,a),!0),Vu(i.slice(a+1),!0)])}if(n=r+1,r===e.length)break}return t}function Uu(e){let t="";for(let n=0;n<e.length;n++){let r=Dn(e[n][0],ch,!0),i=Dn(e[n][1],ch,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var yI=[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],bI=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],xI=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],SI=[2381,2381,2509,2509,2637,2637,2765,2765,2893,2893,3021,3021,3149,3149,3277,3277,3387,3388,3405,3405,3530,3530,3642,3642,3770,3770,3972,3972,4153,4154,5908,5909,5940,5940,6098,6098,6752,6752,6980,6980,7082,7083,7154,7155,11647,11647,43014,43014,43052,43052,43204,43204,43347,43347,43456,43456,43766,43766,44013,44013,68159,68159,69702,69702,69744,69744,69759,69759,69817,69817,69939,69940,70080,70080,70197,70197,70378,70378,70477,70477,70606,70608,70722,70722,70850,70850,71103,71103,71231,71231,71350,71350,71467,71467,71737,71737,71997,71998,72160,72160,72244,72244,72263,72263,72345,72345,72767,72767,73028,73029,73111,73111,73537,73538,90415,90415];function II(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[vI,wI,OI,uh]=[[[],"0,6,7,8,m,w,10,1b,1d,1f,72,73,7k,8k,dt,2rk","AAAAAAAAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAA/AAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAADAAABwfwAAAAAAAMADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhAAAAQAAAAAAAAQCAAABAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgACAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAP///////////////wAAAAAAAAAAAAAAAAAAAAA="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAEF9+P/+BwAAAMAA//8AAPz/////BlADAAAAAJwAAPz///8AAADA//H/5+X8AAAAAAAAAAAA/P///wcAAAAAAAAAAAAAPv0vAD0BAABA/gAA/5/5/f8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8g+N8B+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAYAAAAAAAAAAAAAD/////CwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANgAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/HgwAAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAP3////+BwAAAMDu//////////////8vAADAAJwAAP3///8AAADg////////AAAAAAAAAAAA/P///wcAAAAAAAAAAAAA////Ab0H//9H/gAA/9////8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL/G//8T+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAfgAAAAAAAAAAAAD+////DwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANwAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/Hg4AAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"0,3,4,5,6,7,8,9,a,b,c,d,e,f,g,j,n,o,p,q,r,s,t,w,18,19,1c,4m,4o,4p,4q,4r,6z,72,73,75,76,77,7e,7h,7i,7j,7k,7l,7m,7n,7o,7p,7q,7r,7s,7t,7u,7v,7w,7x,7y,7z,8k,9t,a2,a3,a7,cc,cv,cx,cy,d6,dc,dd,de,dg,dh,di,dk,dl,2rk,2rl","AAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAD//////////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD4AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/v////+/tgAAAAAAAAAAAP8XAAAAAAD4//8AAAEAAAAAAAAAAAAAAMCfnz0AAACAAgAAAP///wcAAAAAAAAAAAAAwP8BAAAAAAAA+A8gAADA++8+AAAAAAAOAAAAAAAAgP8AAAAAAPz///v///8HAAAAAAAAFP4h/gAMAAAAAgAAAAAAABAeIAAADAAAQAYAAAAAAAAQhjkCAAAAIwAGAAAAAAAAEL4hAAAMAAD8AgAAAAAAAJAeIGAADAAAAAQAAAAAAAAAASAAAAAAAAARAAAAAAAA0ME9YAAMAAAAAgAAAAAAAJBAMAAADAAAAAMAAAAAAAAYHiAAAAwAAAACAAAAAAAAAAAEXAAAAAAAAAAAAAAA8geAfwAAAAAAAAAAAAAAAPIfAH8AAAAAAAAAAAADAACgAgAAAAAAAP5/3+D//v///x9AAAAAAAAAAAAAAAAA4P1mAAAAwwEAHgBkIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAAAAMAAAADAAAAAwAAAAAAAAAsD9A/g8gAAAAAAC4AAAAAAAAAAAAAAAAAABgAAAAAAIAAAAAAAAAAAAAAAAAAIcBBA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAJAAAAAAAAQH/lH/ifAAAAAAAA//////8//w8AAA8AAAAAANAXBAAAAAD4DwADAAAAPDsAAAAAAABAowMAAAAAAADwzwAAAAAAAAAAAAAAAAAAAAAAAAD3//0hEAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////wDIAAAAfAAAAAAAAB/8AAAAAAAAAAAAAAAA/////wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAwAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAA/////wAAAAAAPAAAAAAAAAAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAID3PwAAAMAAAAAAAAAAAAAAAwBECAAAYBAAAAAAAAAAAAAAAAAAAAAAAAAwAAAA//8DgAAAAADAPwAAgP8DAAAAAAAHAAAAAADIMwAAAAAgAAAAAAAAAAB+ZgAIEAAAAAAAEAAAAAAAAJ3BAgAAAAAwQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICEAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8AAP//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAMAHAAAAAAAAAAAAAAAAAAAAAG7wAAAAAACHAAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAPAAAAAAAAAAAD4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAAAAAAAAA/AAAAAAAAAAAwP8BAAAAAAA8AAAAAAAAAAAAAAAAAAAAAgAAAAAAAP9/AAAAAAAZgAMAAAAAAHgGBAAAAAAAAAAHAAAAgO8fAAAAAAAAAAgAAwAAAAAAwH8AngAAAAAAAAAAAAAAgNNAAgAAAAAAAAAAAAAAAAAAAAAAAID4BwAAAwAAAAAAABgBAAAAwB8fAAAAAAAAAAD4AUAFAAYAAAAAAAAAAAAA/1wAAEAAAAAAAAAAAAAA+IUNAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8sAEAADAAAAAAAAAAAAAA+KcBAAAAAAAAAAAAAAAAKL8AAAAAAAAAAAAAAACgvA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgP8GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFgIAAAAAAAAAAAAAAAAAAAAAADwDAEAAAD+BwAAAAD4eYAAfg4AAAAAAPx/AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf78AAAAAAAAAAAAA/P///G0AAAAAAAAAAAAAAAAAAAB+tL8AAAAAAAAAAACjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAAwAAAAAAwAcFAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//4H/PwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMD/4wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHwAAAAAAAAB/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAgAcAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGAPAAAAAAAAAAAAAAD//////z///38AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAD+P/nDwAAADwAAAAAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////9/+P//////HyAAEAAA+P7/AAAAAAAAAAAAAH////nbBwAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASMAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAADwDwAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAA////////////////AAAAAAAAAAAAAAAAAAAAAP///////////////////////////////////////wAA"]].map(function([t,n,r]){return[t,n.split(",").map(i=>parseInt(i,36)),Uint8Array.from(atob(r),i=>i.charCodeAt(0))]});function PI(e,t){return t===931||t===1010||t===120531||t===120589||t===120647||t===120705||t===120763?"\u03C3":t>=5112&&t<=5117?String.fromCodePoint(t-8):t>=43888&&t<=43967?String.fromCodePoint(t-38864):t>=93856&&t<=93880?String.fromCodePoint(t+27):t===837||t===890||t>=8064&&t<=8111||t>=8114&&t<=8188?e.normalize("NFD").replace(/\u0345/g,"\u03B9").normalize("NFC").toLowerCase():""}function Ah(e,t){for(let n=0;n<e.length;n+=2)if(t>=e[n]&&t<=e[n+1])return!0;return!1}function Po(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 CI(e){let t=Array.from(e,n=>n.codePointAt(0));for(let n=0;n<t.length;n++){let r=t[n];if(r!==8204&&r!==8205||n>0&&Ah(SI,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&Po(uh,t[i]);)i--;let a=n+1;for(;a<t.length&&Po(uh,t[a]);)a++;if(!(i>=0&&a<t.length&&Po(wI,t[i])&&Po(OI,t[a])))return!1}return!0}var _I=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,EI=/\p{Script=Latin}/u;function RI(e){return!_I.test(e)||!EI.test(e)}var lr=36,os=1,zu=26,kI=38,jI=700,TI=72,NI=128,DI=2147483647;function lh(e){return String.fromCharCode(e+22+75*+(e<26))}function FI(e,t,n){let r=0;for(e=n?Math.floor(e/jI):e>>1,e+=Math.floor(e/t);e>(lr-os)*zu>>1;r+=lr)e=Math.floor(e/(lr-os));return Math.floor(r+(lr-os+1)*e/(e+kI))}function MI(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=NI,o=0,s=TI;for(;r<t.length;){let c=DI;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 f=o;for(let m=lr;;m+=lr){let h=m<=s?os:m>=s+zu?zu:m-s;if(f<h)break;n+=lh(h+(f-h)%(lr-h)),f=Math.floor((f-h)/(lr-h))}n+=lh(f),s=FI(o,r+1,r===i),o=0,r++}}o++,a++}return n}function Du(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=Bu(e.charCodeAt(r));if(i>=t||i<0)return-1;n=n*t+i}return n}function dh(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function yh(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function bh(e){return e.length===2&&yh(e.codePointAt(0),e.codePointAt(1))}function ph(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function mt(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function xh(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function $u(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,f=0;for(;f<4&&(u=Bu(c[s]))>=0;)l=(l<<4)+u,s++,f++;if(c[s]===46){if(f===0||o>6)return null;s-=f;let m=0;for(;c[s]!==void 0;){let h=0;if(m>0)if(c[s]===46&&m<4)s++;else return null;if(c[s]==null||c[s]<48||c[s]>57)return null;for(;c[s]>=48&&c[s]<=57;){if(h=10*h+Bu(c[s]),h>255)return null;s++}i[o]=256*i[o]+h,m++,m%2==0&&o++}if(m!==4)return null;break}else if(c[s]===58){if(c[++s]===void 0)return null}else if(c[s]!==void 0)return null;i[o]=l,o++}if(a!==null){let u=o-a;for(o=7;o!==0&&u>0;){let l=i[a+u-1];i[a+u-1]=i[o],i[o]=l,o--,u--}}else if(a===null&&o!==8)return null;return i})(e.substring(1,e.length-1)):null;if(t)return(function(r){return ph(r)?null:Dn(r,_o)})(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 f=l.codePointAt(0);if(/[\p{Cn}\p{Co}\p{Cs}\p{Noncharacter_Code_Point}]/u.test(l)&&!Ah(yI,f)||Po(vI,f))return!0}return!1})(i))return null;let s=(i=(function(u){let l="";for(let f of u){let m=f.codePointAt(0);if(m!==8204&&m!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(f))continue;let h=PI(f,m);if(h){l+=h;continue}let d=bI.indexOf(m);l+=d<0?f:xI[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(II(u)||l&&(/^\p{Mark}/u.test(u)||!CI(u)||!RI(u)||u.startsWith("xn--")))return null;l&&(s[c]=`xn--${MI(u)}`)}return(i=s.join("."))!==""?i:null})(e.indexOf("%")===-1?e:Vu(e));return n===null||ph(n)?null:(function(i){let a=i.length,o=i.lastIndexOf(".",a-2)+1;if(i.charCodeAt(a-1)===46&&a--,a<=o)return!1;if(Du(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=Du(a[u]);if(l<0||l>255)return null;s+=l*(1<<8*(3-u))}let c=Du(a[o-1]);return c<0||c>=256**(5-o)?null:(s+=c,s)})(n):n}}function Gu(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,f=0;for(let m=0;m<s.length;++m)s[m]!==0?(f>l&&(c=u,l=f),u=-1,f=0):(u===-1&&(u=m),++f);return f>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 Sh(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 Ih(e){return e.username!==""||e.password!==""}function Fu(e){return e.host===null||e.host===""||e.scheme==="file"}var _=0,B="",we="",Ue=null,V,as=!1,ss=!1,Kr=!1,ft;function pn(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),_=0,B=e,we="",Ue=n||null,V=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},as=!1,ss=!1,Kr=!1,ft=r||0;let i=qI;switch(r){case 3:case 4:i=us;break;case 5:i=Zu;break;case 6:i=Hr;break;case 7:i=dr;break;case 8:i=Fn}return i(G(e,_))!==1?V:null}function ee(e,t){return _+=_===e?Cn(t):1,_<=B.length}function G(e,t){return t<e.length?e.codePointAt(t):void 0}function Cn(e){return e!=null&&e>65535?2:1}function vh(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var qI=e=>{let t=_;if(e!=null&&(e>=65&&e<=90||e>=97&&e<=122)){let n=_+1;for(e=B.charCodeAt(n);e===43||e===45||e===46||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57;)n++,e=B.charCodeAt(n);return we=B.slice(_,n).toLowerCase(),_=n,BI(n<B.length?e:void 0)}else return ft?1:(--_,ee(t,e)?wh(G(B,_)):0)},BI=e=>{let t=_;if(e===58){if(ft){if(mt(V.scheme)!==mt(we))return 0;if((Ih(V)||V.port!==null)&&we==="file")return 0;if(V.scheme==="file"&&V.host==="")return 0}return V.scheme=we,ft?(V.port===xh(V.scheme)&&(V.port=null),0):(we="",V.scheme==="file"?ee(t,e)?Wu(G(B,_)):0:mt(V.scheme)&&Ue!==null&&Ue.scheme===V.scheme?ee(t,e)?VI(G(B,_)):0:mt(V.scheme)?ee(t,e)?UI(G(B,_)):0:G(B,_+1)===47?(_++,ee(t,e)?LI(G(B,_)):0):(V.path=[""],V.opaquePath=!0,ee(t,e)?Ph(G(B,_)):0))}else return ft?1:(we="",_=-1,ee(t,e)?wh(G(B,_)):0)},wh=e=>{let t=_;return Ue===null||Ue.opaquePath&&e!==35?1:Ue.opaquePath&&e===35?(V.scheme=Ue.scheme,V.path=Ue.path.slice(),V.opaquePath=Ue.opaquePath,V.query=Ue.query,V.fragment="",ee(t,e)?Fn(G(B,_)):0):Ue.scheme==="file"?(_--,ee(t,e)?Wu(G(B,_)):0):(_--,ee(t,e)?Ju(G(B,_)):0)},VI=e=>{let t=_;return e===47&&G(B,_+1)===47?(++_,ee(t,e)?ds(G(B,_)):0):(_--,ee(t,e)?Ju(G(B,_)):0)},LI=e=>{let t=_;return e===47?ee(t,e)?_i(G(B,_)):0:(_--,ee(t,e)?_n(G(B,_)):0)},Ju=e=>{let t=_;return V.scheme=Ue.scheme,e===47||mt(V.scheme)&&e===92?ee(t,e)?mh(G(B,_)):0:(V.username=Ue.username,V.password=Ue.password,V.host=Ue.host,V.port=Ue.port,V.path=Ue.path.slice(),V.query=Ue.query,e===63?(V.query="",ee(t,e)?dr(G(B,_)):0):e===35?(V.fragment="",ee(t,e)?Fn(G(B,_)):0):e!=null?(V.query=null,V.path.pop(),_--,ee(t,e)?_n(G(B,_)):0):ee(t,e)?Ju(G(B,_)):0)},mh=e=>{let t=_;return mt(V.scheme)&&(e===47||e===92)?ee(t,e)?ds(G(B,_)):0:e===47?ee(t,e)?_i(G(B,_)):0:(V.username=Ue.username,V.password=Ue.password,V.host=Ue.host,V.port=Ue.port,_--,ee(t,e)?_n(G(B,_)):0)},UI=e=>{let t=_;return e===47&&G(B,_+1)===47?_++:_--,ee(t,e)?ds(G(B,_)):0},ds=e=>{let t=_;return e!==47&&e!==92?(_--,ee(t,e)?_i(G(B,_)):0):ee(t,e)?ds(G(B,_)):0},_i=e=>{let t=_;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!mt(V.scheme))){let n=_+Cn(e);for(;n<B.length;){let r=G(B,n);if(r==null||r===64||r===35||r===47||r===63||r===92&&mt(V.scheme))break;n+=Cn(r)}return we+=B.slice(_,n),_=n-1,ee(t,e)?_i(G(B,_)):0}if(e===64){as&&(we=`%40${we}`),as=!0;for(let n=0;n<we.length;n++){let r=we.codePointAt(n);if(r===58&&!ss){ss=!0;continue}let i=hh(r,cs);ss?V.password+=i:V.username+=i,r!=null&&r>65535&&n++}return we="",ee(t,e)?_i(G(B,_)):0}else return e==null||e===35||e===47||e===63||e===92&&mt(V.scheme)?as&&we===""?1:(_-=we.length+1,we="",ee(t,e)?us(G(B,_)):0):(we+=vh(e),ee(t,e)?_i(G(B,_)):0)},us=e=>{let t=_;if(ft&&V.scheme==="file")return _--,ee(t,e)?Yu(G(B,_)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!mt(V.scheme))){let n=_+Cn(e);for(e===91?Kr=!0:e===93&&(Kr=!1);n<B.length;){let r=G(B,n);if(r==null||!Kr&&r===58||r===35||r===47||r===63||r===92&&mt(V.scheme))break;r===91?Kr=!0:r===93&&(Kr=!1),n+=Cn(r)}return we+=B.slice(_,n),_=n-1,ee(t,e)?us(G(B,_)):0}else if(e===58&&!Kr){if(we===""||ft===4)return 1;let n=$u(we,!mt(V.scheme));return n===null?1:(V.host=Gu(n),we="",ee(t,e)?Zu(G(B,_)):0)}else if(e==null||e===35||e===47||e===63||e===92&&mt(V.scheme)){if(_--,mt(V.scheme)&&we==="")return 1;if(ft&&we===""&&(Ih(V)||V.port!==null))return 1;let n=$u(we,!mt(V.scheme));return n===null?1:(V.host=Gu(n),we="",ft?0:ee(t,e)?Hr(G(B,_)):0)}else return we+=vh(e),ee(t,e)?us(G(B,_)):0},Zu=e=>{let t=_;if(e!=null&&e>=48&&e<=57){let n=_+1;for(;n<B.length;){let r=B.charCodeAt(n);if(r<48||r>57)break;n++}return we+=B.slice(_,n),_=n-1,ee(t,e)?Zu(G(B,_)):0}else if(ft||e==null||e===35||e===47||e===63||e===92&&mt(V.scheme)){if(we!==""){let n=parseInt(we,10);if(n>65535)return 1;if(V.port=n===xh(V.scheme)?null:n,we="",ft)return 0}return ft?1:(_--,ee(t,e)?Hr(G(B,_)):0)}else return 1};function Oh(e,t){let n=e.length-t;if(n<2)return!1;if(yh(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 Wu=e=>{let t=_;return V.scheme="file",V.host="",e===47||e===92?ee(t,e)?zI(G(B,_)):0:Ue?.scheme==="file"?(V.host=Ue.host,V.path=Ue.path.slice(),V.opaquePath=Ue.opaquePath,V.query=Ue.query,e===63?(V.query="",ee(t,e)?dr(G(B,_)):0):e===35?(V.fragment="",ee(t,e)?Fn(G(B,_)):0):e!=null?(V.query=null,Oh(B,_)?V.path=[]:Sh(V),_--,ee(t,e)?_n(G(B,_)):0):ee(t,e)?Wu(G(B,_)):0):(_--,ee(t,e)?_n(G(B,_)):0)},zI=e=>{let t=_;return e===47||e===92?ee(t,e)?Yu(G(B,_)):0:(Ue!==null&&Ue.scheme==="file"&&(!Oh(B,_)&&(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})(Ue.path[0])&&V.path.push(Ue.path[0]),V.host=Ue.host),_--,ee(t,e)?_n(G(B,_)):0)},Yu=e=>{let t=_;if(e!=null&&e!==47&&e!==92&&e!==63&&e!==35){let n=_+Cn(e);for(;n<B.length;){let r=G(B,n);if(r==null||r===47||r===92||r===63||r===35)break;n+=Cn(r)}return we+=B.slice(_,n),_=n-1,ee(t,e)?Yu(G(B,_)):0}else if(e==null||e===47||e===92||e===63||e===35){if(_--,!ft&&bh(we))return ee(t,e)?_n(G(B,_)):0;if(we==="")return V.host="",ft?0:ee(t,e)?Hr(G(B,_)):0;{let n=$u(we,!mt(V.scheme));return n===null?1:(n==="localhost"&&(n=""),V.host=Gu(n),we="",ft?0:ee(t,e)?Hr(G(B,_)):0)}}return 1},Hr=e=>{let t=_;return mt(V.scheme)?(e!==92&&e!==47&&_--,ee(t,e)?_n(G(B,_)):0):!ft&&e===63?(V.query="",ee(t,e)?dr(G(B,_)):0):!ft&&e===35?(V.fragment="",ee(t,e)?Fn(G(B,_)):0):e!=null?(e!==47&&_--,ee(t,e)?_n(G(B,_)):0):(ft&&V.host===null&&V.path.push(""),ee(t,e)?Hr(G(B,_)):0)},_n=e=>{let t=_;if(e!=null&&e!==47&&(!mt(V.scheme)||e!==92)&&(ft||e!==63&&e!==35)){let n=_+Cn(e);for(;n<B.length;){let r=G(B,n);if(r==null||r===47||mt(V.scheme)&&r===92||!ft&&(r===63||r===35))break;n+=Cn(r)}we+=Dn(B.slice(_,n),Lu),_=n,e=G(B,n)}if(e==null||e===47||mt(V.scheme)&&e===92||!ft&&(e===63||e===35)){let n=mt(V.scheme)&&e===92;return(function(i){switch(i){case"..":case"%2e.":case"%2E.":case".%2e":case".%2E":case"%2e%2e":case"%2E%2e":case"%2e%2E":case"%2E%2E":return!0;default:return!1}})(we)?(Sh(V),e!==47&&!n&&V.path.push("")):dh(we)&&e!==47&&!n?V.path.push(""):dh(we)||(V.scheme==="file"&&V.path.length===0&&bh(we)&&(we=`${we[0]}:`),V.path.push(we)),we="",e===63?(V.query="",ee(t,e)?dr(G(B,_)):0):e===35?(V.fragment="",ee(t,e)?Fn(G(B,_)):0):ee(t,e)?_n(G(B,_)):0}else return we+=hh(e,Lu),ee(t,e)?_n(G(B,_)):0},Ph=e=>{let t=_;if(e===63)return V.query="",ee(t,e)?dr(G(B,_)):0;if(e===35)return V.fragment="",ee(t,e)?Fn(G(B,_)):0;if(e!=null){let n=_+Cn(e);for(;n<B.length;){let i=G(B,n);if(i===63||i===35)break;n+=Cn(i)}let r=B.slice(_,n);if(n<B.length&&r.charCodeAt(r.length-1)===32?V.path[0]+=Dn(r.slice(0,-1),_o)+"%20":V.path[0]+=Dn(r,_o),_=n,(e=G(B,n))===63)return V.query="",ee(t,e)?dr(G(B,_)):0;if(e===35)return V.fragment="",ee(t,e)?Fn(G(B,_)):0}return ee(t,e)?Ph(G(B,_)):0},dr=e=>{let t=_,n=_;if(e!=null){if(ft)n=B.length;else{let i=B.indexOf("#",_);n=i===-1?B.length:i}let r=mt(V.scheme)?AI:Hu;V.query+=Dn(B.slice(_,n),r)}return _=n,G(B,n)===35&&!ft?(V.fragment="",ee(t,e)?Fn(G(B,_)):0):ee(t,e)?dr(G(B,_)):0},Fn=e=>{let t=_;return e!=null&&(V.fragment+=Dn(B.slice(_),hI),_=B.length),ee(t,e)?Fn(G(B,_)):0};function Ku(e){if(e.opaquePath)return e.path[0];{let t="";for(let n of e.path)t+=`/${n}`;return t}}function Ch(e){switch(e.scheme){case"blob":{let t=pn(Ku(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":Ch(t)}case"ftp":case"http":case"https":case"ws":case"wss":return(function(n){let r=`${n.scheme}://`;return r+=n.host,n.port!==null&&(r+=`:${n.port}`),r})(e);default:return"null"}}var Ge=Symbol("URLImpl"),yn=class e{constructor(t,n){if(t===void 0&&n===void 0)throw new TypeError('The "url" argument must be specified.');t=Ke(t),n!=null&&(n=Ke(n));let r=null;if(n!=null&&(r=pn(n,null,null,0),r==null))throw new TypeError(`Invalid base URL: ${n}`);let i=pn(t,null,r,0);if(i==null)throw new TypeError(`Invalid URL: ${t}`);this[Ge]={url:i,query:null}}static createObjectURL(t){throw new TypeError("URL.createObjetURL is unsupported")}static revokeObjectURL(t){}static parse(t,n){t=Ke(t),n!==void 0&&(n=Ke(n));try{return new e(t,n)}catch{return null}}static canParse(t,n){t=Ke(t),n!==void 0&&(n=Ke(n));let r=null;return n!=null&&(r=pn(n,null,null,0),r==null)?!1:pn(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+=Ku(n),n.query!==null&&(r+=`?${n.query}`),n.fragment!==null&&(r+=`#${n.fragment}`),r})(this[Ge].url)}set href(t){let n=pn(t=Ke(t),null,null,0);if(n==null)throw new TypeError(`Invalid URL: ${t}`);this[Ge].url=n,this[Ge].query&&Mu(this[Ge].query,n.query)}get origin(){return Ch(this[Ge].url)}get protocol(){return`${this[Ge].url.scheme}:`}set protocol(t){pn(`${t=Ke(t)}:`,this[Ge].url,null,2)}get username(){return this[Ge].url.username}set username(t){t=Ke(t),Fu(this[Ge].url)||(function(r,i){r.username=Dn(i,cs)})(this[Ge].url,t)}get password(){return this[Ge].url.password}set password(t){t=Ke(t),Fu(this[Ge].url)||(function(r,i){r.password=Dn(i,cs)})(this[Ge].url,t)}get host(){let{url:t}=this[Ge];return t.host==null?"":t.port==null?t.host:`${t.host}:${t.port}`}set host(t){t=Ke(t),this[Ge].url.opaquePath||pn(t,this[Ge].url,null,3)}get hostname(){let{url:t}=this[Ge];return t.host!=null?t.host:""}set hostname(t){t=Ke(t),this[Ge].url.opaquePath||pn(t,this[Ge].url,null,4)}get port(){let{url:t}=this[Ge];return t.port!=null?`${t.port}`:""}set port(t){t=Ke(t);let{url:n}=this[Ge];Fu(n)||(t?pn(t,n,null,5):n.port=null)}get pathname(){return Ku(this[Ge].url)}set pathname(t){t=Ke(t);let{url:n}=this[Ge];n.opaquePath||(n.path=[],pn(t,n,null,6))}get search(){let{url:t}=this[Ge];return t.query?`?${t.query}`:""}set search(t){t=Ke(t);let{url:n,query:r}=this[Ge];if(!t)n.query=null,r&&Mu(r,null);else{let i=t[0]==="?"?t.substring(1):t;n.query="",pn(i,n,null,7),r&&Mu(r,n.query)}}get searchParams(){let t=this[Ge],n=t.query;return n==null&&(n=t.query=(function(i,a){let o=new ls;return o[at].url=i,o[at].serialized=a==null,a&&(o[at].list=Qu(a)),o})(this,t.url.query)),n}get hash(){let{url:t}=this[Ge];return t.fragment?`#${t.fragment}`:""}set hash(t){t=Ke(t);let{url:n}=this[Ge];if(!t)n.fragment=null;else{let r=t[0]==="#"?t.substring(1):t;n.fragment="",pn(r,n,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(yn.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var at=Symbol("URLSearchParamsImpl"),$I=Symbol.dispose||Symbol.for("dispose");function Mu(e,t){t?e[at].list=Qu(t):e[at].list.length=0,e[at].serialized=t==null}function is(e){if(e.url){let t=Uu(e.list);(function(r,i){r[Ge].url.query=i})(e.url,t||null),e.serialized=!0}}var GI=typeof Iterator<"u"?Iterator:Object,Co=class extends GI{constructor(t,n){super(),this[at]={ptr:t,map:n,index:0}}next(){let t=this[at];return t.index<t.ptr.list.length?{value:t.map(t.ptr.list[t.index++]),done:!1}:{value:void 0,done:!0}}[Symbol.iterator](){return this}[$I](){}},ls=class{constructor(t){let n=this[at]={list:[],url:null,serialized:!0},r;if(Array.isArray(t))for(let i=0;i<t.length;i++)n.list.push(ah(t[i]));else if((r=fh(t))!=null){let i;for(;!(i=qu(r.next())).done;)n.list.push(ah(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=fI(o),c=Ke(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=Ke(t);i=i[0]==="?"?i.substring(1):i,n.list=Qu(i)}}get size(){return this[at].list.length}append(t,n){t=Ke(t),n=Ke(n),this[at].list.push([t,n]);let r=this[at];r.url&&r.serialized?(function(a,o){let s=a[Ge].url;s.query=s.query?`${s.query}&${o}`:o})(r.url,Uu([[t,n]])):is(r)}delete(t,n){t=Ke(t),n=n!=null?Ke(n):void 0;let{list:r}=this[at],i=0;for(;i<r.length;)r[i][0]===t&&(n==null||r[i][1]===n)?r.splice(i,1):i++;is(this[at])}get(t){t=Ke(t);let{list:n}=this[at];for(let r=0;r<n.length;r++)if(n[r][0]===t)return n[r][1];return null}getAll(t){t=Ke(t);let n=[],{list:r}=this[at];for(let i=0;i<r.length;i++)r[i][0]===t&&n.push(r[i][1]);return n}has(t,n){t=Ke(t),n=n!=null?Ke(n):void 0;let{list:r}=this[at];for(let i=0;i<r.length;i++)if(r[i][0]===t&&(n==null||r[i][1]===n))return!0;return!1}set(t,n){t=Ke(t),n=Ke(n);let{list:r}=this[at],i=!1,a=!1,o=0;for(;o<r.length;)r[o][0]===t?i?(r.splice(o,1),a=!0):(i=!0,r[o][1]!==n&&(r[o][1]=n,a=!0),o++):o++;i||(r.push([t,n]),a=!0),a&&is(this[at])}sort(){this[at].list.sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0),is(this[at])}forEach(t,n){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:r}=this[at];for(let i=0;i<r.length;i++)t.call(n,r[i][1],r[i][0],this)}entries(){return new Co(this[at],t=>t)}keys(){return new Co(this[at],t=>t[0])}values(){return new Co(this[at],t=>t[1])}toString(){return Uu(this[at].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(ls.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var pr="https://api.longplayai.com";function _h(e){let t,n=()=>typeof t=="string"?t:t?.accessToken,r=0,i,a=new Map,o=()=>{for(let f of[...a.keys()])try{f()}catch{}};function s(f){let m=++r;i=void 0,t=void 0;for(let h of[...a.values()])try{h?.()}catch{}m===r&&(t=f,o())}let c=()=>s();function u(f,m=!1){let h=Qn.safeParse(f);if(!h.success||m&&Date.parse(h.data.expiresAt)<=Date.now()||Date.parse(h.data.refreshExpiresAt)<=Date.now()||Date.parse(h.data.refreshExpiresAt)<Date.parse(h.data.expiresAt))throw new b("INVALID_RESPONSE","Invalid customer session credentials");return h.data}async function l(){if(i)return i;let f=typeof t=="object"?t:void 0,m=r;if(!f||Date.parse(f.refreshExpiresAt)<=Date.now())throw f&&c(),new b("UNAUTHENTICATED","Customer authentication is required",401);let h=(async()=>{try{let d=await e(f.refreshToken);if(m!==r)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");let A=u(d,!0);if(A.customerId!==f.customerId||A.sessionId!==f.sessionId)throw new b("SCOPE_MISMATCH","Refresh changed the customer session");return t=A,{...A}}catch(d){throw m!==r?new b("IDENTITY_CHANGED","Customer identity changed during refresh"):(d instanceof b&&d.status===401&&c(),d)}})();i=h;try{return await h}finally{i===h&&(i=void 0)}}return{identify(f){let m=typeof f=="string"?f:u(f),h=typeof m=="string"?m:m.accessToken;if(!h.trim()||/\s/.test(h)||h.length>4096)throw new b("INVALID_TOKEN","A server-issued token is required");s(m)},reset:c,subscribeIdentity(f,m){return a.set(f,m),()=>{a.delete(f)}},access(){let f=typeof t=="object"?t:void 0;if(f&&Date.parse(f.expiresAt)<=Date.now()+3e4){let h=r;return l().then(()=>{let d=n();if(h!==r||!d)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");return d})}let m=n();if(!m)throw new b("NOT_IDENTIFIED","Identify a customer session before making a request");return m},peek:n,snapshot:()=>typeof t=="object"?{...t}:void 0,refresh:l}}var Eh=Symbol("IndianaNoContent");function mr(e,t,n=yn){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??pr);if(o.username||o.password||o.search||o.hash)throw new b("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(o.protocol!=="https:"&&!(o.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(o.hostname)))throw new b("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let s=e.fetch??globalThis.fetch.bind(globalThis),c=e.timeoutMs??1e4;if(!Number.isFinite(c)||c<1||c>12e4)throw new b("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let u=!1,l=0,f=null,m=new Set,h=e.session??_h(async y=>{let I=await g("customer-sessions/refresh",{},"POST",{},y);if(!I||typeof I!="object")throw new b("INVALID_RESPONSE","Invalid refresh response");let{requestId:w,scope:C,...j}=I;return j});function d(){l+=1,f=null;for(let y of m)y.abort();m.clear()}let A=h.subscribeIdentity(d);function k(){u||h.reset()}async function g(y,I={},w="POST",C={},j){let E=C.installationDetach===!0;if(E&&(y!=="push/installations/detach"||w!=="POST"))throw new b("INVALID_REQUEST","Installation authority only detaches this installation");if(!j&&!E)throw new b("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let ae=l,xe=new AbortController;E||m.add(xe);let Pe=()=>!E&&ae!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new b("TIMEOUT","Longplay request timed out"),Ee,ye=new Promise((Te,tt)=>{Ee=()=>tt(Pe()),xe.signal.addEventListener("abort",Ee,{once:!0})}),gt=setTimeout(()=>xe.abort(),C.timeoutMs??c),Je=async()=>{let Te=await s(`${o.href.replace(/\/$/,"")}/api/v1/${y}`,{method:w,headers:{...C.headers,"Content-Type":"application/json",...E?{}:{Authorization:`Bearer ${j}`},[Os]:Ps.current,[bl]:oh.version,...a?{"X-Indiana-Project":a.projectId,"X-Indiana-Environment":a.environment}:{}},body:w==="POST"?JSON.stringify(I):void 0,signal:xe.signal,credentials:"omit",cache:"no-store",redirect:"error",...C.keepalive?{keepalive:!0}:{}});if(xe.signal.aborted)throw Pe();let tt;try{tt=Te.status===204?Eh:await Te.json()}catch{throw xe.signal.aborted?Pe():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(xe.signal.aborted)throw Pe();if(!E&&ae!==l)throw new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!Te.ok){let lt=ws.safeParse(tt),Kt=lt.success&&(!Bn.safeParse(lt.data.error.code).success||Al(lt.data.error.code,Te.status)),Ar=Kt?lt.data.error.code:"HTTP_ERROR",yr=Fo(Ar,Te.status,{retryAfter:Te.headers.get("Retry-After"),recovery:Kt?lt.data.error.recovery:void 0,reason:Kt?lt.data.error.reason:void 0});throw new b(Ar,Kt?lt.data.error.message:"Longplay request failed",Te.status,Te.headers.get("X-Request-Id")??(lt.success?lt.data.requestId:void 0),{...yr,...lt.success&&lt.data.error.retryable===!1?{retryable:!1}:{},...yr.retryAfterSeconds===void 0&&lt.success&&lt.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:lt.data.error.retryAfterSeconds}:{}})}if(Te.headers.get(Os)!==Ps.current)throw new b("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&tt!==Eh){let lt=tt&&typeof tt=="object"&&"scope"in tt?tt:tt&&typeof tt=="object"&&"configuration"in tt?tt.configuration:null;if(!lt||typeof lt!="object"||!("scope"in lt))throw new b("INVALID_RESPONSE","Response is missing its App/environment scope");let Kt=Ne.safeParse(lt.scope);if(!Kt.success||Kt.data.projectId!==a.projectId||Kt.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");f!==Jr&&(f=Jr,t?.(f))}return tt};try{return await Promise.race([Je(),ye])}catch(Te){throw!E&&ae!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):Te instanceof b?Te:new b(xe.signal.aborted?"TIMEOUT":"NETWORK_ERROR",xe.signal.aborted?"Longplay request timed out":"Unable to read the Longplay response")}finally{clearTimeout(gt),xe.signal.removeEventListener("abort",Ee),m.delete(xe)}}return{session:h,requestWithCredential(y,I,w,C={}){return u?Promise.reject(new b("CLOSED","SDK client was destroyed")):g(y,I,"POST",C,w)},subjectKey:()=>f,identify(y){if(u)throw new b("CLOSED","SDK client was destroyed");if(a&&typeof y=="object"&&"scope"in y){let I=Ne.safeParse(y.scope);if(!I.success||I.data.projectId!==a.projectId||I.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Customer session belongs to another App/environment")}h.identify(y)},reset:k,dispose(){u||(u=!0,A(),d())},request(y,I={},w="POST",C={}){if(u)return Promise.reject(new b("CLOSED","SDK client was destroyed"));if(C.installationDetach)return g(y,I,w,C);let j=l;try{let E=h.access(),ae=xe=>{if(j!==l)throw new b("IDENTITY_CHANGED","Customer identity changed before dispatch");return g(y,I,w,C,xe)};return typeof E=="string"?ae(E):E.then(ae)}catch(E){return Promise.reject(E)}}}}function Rh(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(!jt.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 KI={...O.readHoldings,request:O.readHoldings.request.omit({customerId:!0})};function kh(e){return{async checkEntitlement(t){ze(t);let n=O.checkEntitlement;return me(e,n,t)},async readHoldings(t={}){return me(e,KI,t)}}}function jh(e){return{async readLedger(t){let n=O.readLedger;return me(e,n,{query:t})},async readCreditStatement(t){ze(t);let n=O.readCreditStatement;return me(e,n,t)},async quoteBalance(t){ze(t);let n=O.quoteBalance;return me(e,n,{command:t})}}}function Th(e){return{async setupPayment(t){ze(t);let n=O.setupPayment;return me(e,n,t)},async readPaymentSetup(t){ze(t);let n=O.readPaymentSetup;return me(e,n,t)},async readBillingInvoice(t){ze(t);let n=O.readBillingInvoice;return me(e,n,t)},async readBillingControls(t={}){ze(t);let n=O.readBillingControls;return me(e,n,t)},async prepareBillingAuthorization(t){ze(t);let n=O.prepareBillingAuthorization;return me(e,n,t)},async confirmBillingAuthorization(t){ze(t);let n=O.confirmBillingAuthorization;return me(e,n,t)},async setBillingCoupons(t){ze(t);let n=O.setBillingCoupons;return me(e,n,t,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(t){ze(t);let n=O.revokeBillingAuthorization;return me(e,n,t)},async listBillingInvoices(t={after:null,limit:25}){ze(t);let n=O.listBillingInvoices;return me(e,n,t)},async confirmBillingAdjustment(t){ze(t);let n=O.confirmBillingAdjustment;return me(e,n,t)}}}function Nh(e){return{async previewUpdate(t){ze(t);let n=O.previewUpdate;return me(e,n,t)},async update(t){ze(t);let n=O.update;return me(e,n,t)},async readSubscriptionUpdate(t){ze(t);let n=O.readSubscriptionUpdate;return me(e,n,t)},async restoreNativePurchase(t){ze(t);let n=O.restoreNativePurchase;return me(e,n,t)},async previewAttach(t){ze(t);let n=O.previewAttach;return me(e,n,t)},async attach(t){ze(t);let n=O.attach;return me(e,n,t)},async readSubscriptionOperation(t){ze(t);let n=O.readSubscriptionOperation;return me(e,n,t)}}}function Dh(e){return{async redeemReward(t){return ze(t),(await me(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 me(e,O.claimRewardProduct,t,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(t){return ze(t),(await me(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 me(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 me(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 me(e,O.listOffers,{},{response:"Invalid offers response"})).offers}}}function Fh(e){return{...kh(e),...jh(e),...Th(e),...Nh(e),...Dh(e)}}function Mh(e){return{async resolveContent(t){ze(t);let n=O.resolveContent;return me(e,n,t)},async resolvePaywall(t){ze(t);let n=O.resolvePaywall;return me(e,n,t)},async resolveOffering(t){ze(t);let n=O.resolveOffering;return me(e,n,t)}}}var Xu=e=>new TextEncoder().encode(JSON.stringify(e)).length,qh=16384;function Bh(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,f().catch(()=>{}).finally(u)},5e3),typeof s=="object"&&"unref"in s&&s.unref())}function l(d,A={},k={}){if(c(),r&&Date.now()<r.until&&!$m(r.config,d))return;h();let g=O.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:d,properties:A,...k}]}).events[0];if(Xu({events:[g]})>qh)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(g)),u()}async function f(d=!1){if(c(),o)return o;let A=n,k=(async()=>{let g={inserted:0,duplicates:0,rejected:0,skipped:0},y=a.length;for(;y&&A===n;){let I=[],w=Xu({events:[]});for(let E of a.slice(0,Math.min(y,100))){let ae=Xu(E)+(I.length?1:0);if(I.length&&w+ae>qh)break;I.push(E),w+=ae}let C=O.trackEvents,j=await me(e,C,{events:I},void 0,{keepalive:d});if(A!==n)throw new b("IDENTITY_CHANGED","Event identity changed during delivery");if(j.inserted+j.duplicates+j.rejected+j.skipped!==I.length)throw new b("INVALID_RESPONSE","Incomplete event acknowledgement");i(j.analyticsConfig),a.splice(0,I.length),y-=I.length,g.inserted+=j.inserted,g.duplicates+=j.duplicates,g.rejected+=j.rejected,g.skipped+=j.skipped}return g})();o=k;try{return await k}finally{o===k&&(o=null)}}let m;function h(){if(m||typeof document>"u")return;let d=()=>{document.visibilityState==="hidden"&&t()&&a.length&&f(!0).catch(()=>{})};document.addEventListener("visibilitychange",d),m=()=>document.removeEventListener("visibilitychange",d)}return{rememberConfiguration:i,track:l,flush:f,reset(){n++,r=void 0,clearTimeout(s),s=void 0,a=[],o=null},detachVisibility(){m?.(),m=void 0}}}function ps(e){let t=null,n=null,r=0,i=0,a=new Set,o=null,s=null,c=new Set,u=()=>{for(let g of c)try{g()}catch{}},l={attributes:Ot.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(g,y)=>{!a.has(g)&&(!t||!("analyticsConfig"in t)||t.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(g,structuredClone(y),structuredClone(l.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(g,y)=>(!t||!("analyticsConfig"in t)||t.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(g),structuredClone(y),structuredClone(l.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?g=>e.saveStickyBucketAssignmentDoc(structuredClone(g)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},f=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function m(g,y=new Set){return a.has(g)?!o||!o.features[g]||["unknownFeature","cyclicPrerequisite"].includes(o.features[g].source):y.has(g)?!1:(y.add(g),(t?.features[g]?.rules??[]).some(I=>[...I.parentConditions??[],...(I.tracks??[]).flatMap(w=>w.experiment.parentConditions??[])].some(w=>m(w.id,y))))}let h=g=>{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(g)?!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now()?f():structuredClone(o.features[g]??f()):e.evaluateRemote&&(l.attributes?.merchandise||l.attributes?.merchandiseId)&&!o||m(g)?f():structuredClone(Ln(g,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 g=i;if(s?.revision===g)return s.loading;let y=r,I=t,w=[...a],C=(async()=>{let j=Ta.parse(await e.evaluateRemote({attributes:structuredClone(l.attributes),features:w}));if(!(y!==r||g!==i||I!==t)){if(e.assertUsable?.(I.generation),j.generation!==I.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(w.some(E=>!Object.hasOwn(j.features,E))||Object.keys(j.features).some(E=>!a.has(E)))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=Ot.parse({...l.attributes,...j.merchandiseContext})}o=structuredClone(j),l.features={...I.features,...Object.fromEntries(Object.entries(o.features).map(([E,ae])=>[E,{defaultValue:ae.value}]))},u()}})();s={revision:g,loading:C};try{await C}finally{s?.loading===C&&(s=null)}}function A(){d().catch(g=>{try{e.onError?.(g)}catch{}})}async function k(){if(n)return n;let g=r,y=(async()=>{let I=await e.load(),w="remoteFeatures"in I?po.parse(I):null,C=w??gn.parse(I);if(C.scope.projectId!==e.scope.projectId||C.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(g!==r)throw new Error("Feature client was reset");if(e.assertUsable&&t?.generation===C.generation){let{evaluatedAt:E,expiresAt:ae,...xe}=t,{evaluatedAt:Pe,expiresAt:Ee,...ye}=C;if(Ct(xe)!==Ct(ye))throw new Error("Immutable Feature generation changed content");return t.evaluatedAt=C.evaluatedAt,t.expiresAt=C.expiresAt,u(),(!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())&&A(),structuredClone(t)}let j=new Set(w?.remoteFeatures??[]);if([...j].some(E=>Object.hasOwn(C.features,E)))throw new Error("Remote Feature definitions must not be delivered locally");return t&&"analyticsConfig"in t&&"analyticsConfig"in C&&!t.analyticsConfig.experimentViewsEnabled&&w?.analyticsConfig.experimentViewsEnabled&&l.trackedExperiments?.clear(),t=structuredClone(C),a=j,o=null,s=null,i++,l.features=t.features,l.savedGroups=ni(t.savedGroups),l.trackedFeatureUsage={},u(),A(),structuredClone(t)})();n=y;try{return await y}finally{n===y&&(n=null)}}return{init:k,refresh:k,refreshRemote:d,get generation(){return t?.generation??null},get expiresAt(){return t?.expiresAt??null},subscribe(g){return c.add(g),()=>{c.delete(g)}},setAttributes(g){let y=Ot.parse(g);(l.attributes?.merchandise||l.attributes?.merchandiseId||g.merchandise||g.merchandiseId)&&l.trackedExperiments?.clear(),l.attributes=y,i++,o=null,s=null,l.features=t?.features??{},l.trackedFeatureUsage={},u(),A()},evalFeature:h,isOn(g){return h(g).on},isOff(g){return h(g).off},getFeatureValue(g,y){let I=h(g).value;return structuredClone(I===null?y:I)},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 Vh(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 HI(e){let t=Vh(e),{merchandiseId:n,merchandise:r,...i}=e;return{...i,...t?{merchandise:t}:{}}}function Lh(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,f=!1,m=async()=>{if(f||l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let Pe=O.getFeatures,Ee=i?{scope:{projectId:i.scope.projectId,environment:i.scope.environment},payload:await i.features()}:await me(e,Pe,{});if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");if(r&&(Ee.scope.projectId!==r.projectId||Ee.scope.environment!==r.environment))throw new b("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(Ee.payload.analyticsConfig),Ee},h=await m(),d=!0,A,k=Pe=>{try{u.onError?.(Pe)}catch{}},g=(Pe,Ee,ye)=>{try{let gt=Vh(ye);n.track(Pe,Ee,gt?{merchandise:gt}:{})}catch(gt){k(gt)}},y=ps({assertUsable:i?.assertFeatures,scope:h.scope,attributes:u.attributes,onError:u.onError,load:async()=>d?(d=!1,h.payload):(await m()).payload,evaluateRemote:async Pe=>{if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let Ee=O.evaluateFeatures,ye=await me(e,Ee,{...Pe,attributes:HI(Pe.attributes)});if(ye.scope.projectId!==h.scope.projectId||ye.scope.environment!==h.scope.environment)throw new b("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:ye.generation,evaluatedAt:ye.evaluatedAt,expiresAt:ye.expiresAt,features:ye.features,...ye.merchandiseContext?{merchandiseContext:ye.merchandiseContext}:{}}},onExperimentViewed:(Pe,Ee,ye)=>g("Experiment Viewed",{experimentId:Pe.key,variationId:Ee.key},ye),onFeatureUsage:(Pe,Ee,ye)=>g("Feature Evaluated",{feature:Pe,value:Ee.value,source:Ee.source,ruleId:Ee.ruleId,...Ee.experimentResult?{variationId:Ee.experimentResult.key}:{}},ye)}),I=y.refresh;function w(){clearTimeout(A),!i&&(f||l!==a||!y.expiresAt||(A=setTimeout(()=>{C().catch(k)},Math.min(2147483647,Math.max(1e3,Date.parse(y.expiresAt)-Date.now()))),typeof A=="object"&&"unref"in A&&A.unref()))}async function C(){try{return await I()}finally{w()}}let j=()=>{f||C().catch(k)},E=y.subscribe(w),ae=i?.subscribe(()=>{!f&&i.fresh&&C().catch(k)});function xe(){f||(f=!0,clearTimeout(A),typeof window<"u"&&window.removeEventListener("focus",j),E(),ae?.(),y.reset(),o.delete(xe))}o.add(xe);try{await y.init(),(u.attributes?.merchandise||u.attributes?.merchandiseId)&&await y.refreshRemote()}catch(Pe){throw xe(),Pe}return w(),!i&&typeof window<"u"&&window.addEventListener("focus",j),Object.assign(y,{refresh:C,destroy:xe})}return{features:c,reset(u){a++,u();for(let l of o)l()}}}var Uh=require("zod");function zh(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=Uh.z.object({funnelId:es.shape.id,funnelVersionId:es.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 me(e,c,a({couponId:o,requestId:s}));return{offer:u.offer,reason:u.reason}},async resolveOffering(o){let s=O.resolveOffering;return me(e,s,a(o))},async resolvePaywall(o){let s=O.resolvePaywall;return me(e,s,a(o))},async previewAttach(o){let s=O.previewAttach;return me(e,s,a(o))}}}function $h(e){let t=mr(e),n=t.request,r;try{r=th(e.push,t,e.scope??e.configuration?.scope)}catch(s){throw t.dispose(),s}let i=Rh(t,()=>{o.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=Bh(n,i.isIdentified),o=Lh(n,i.isIdentified,a,e.scope,e.configuration);return{session:t.session,...ih(n,r),...Fh(n),...Mh(n),forFunnel(s){return i.assertActive(),zh(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 Ei(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,a)=>Ei(i,t[a]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let n=Object.entries(e),r=Object.entries(t);return n.length===r.length&&n.every(([i,a])=>Object.hasOwn(t,i)&&Ei(a,Reflect.get(t,i)))}function ms(e,t){let n=qg.safeParse(t);if(!n.success)throw new b("INVALID_RESPONSE","Funnel response contract changed");let r=n.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new b("SCOPE_MISMATCH","Funnel scope changed");return r}var Ri=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function fs(e){let t=jt.test(e.apiKey);if(typeof window<"u"&&!t)throw new b("SERVER_ONLY","Funnel starts are issued by your backend");if(!t&&!Ri.test(e.apiKey))throw new b("INVALID_TOKEN","A customer credential or server API key is required");return{async start(n){let r=Pt.safeParse({...n,operation:"start"});if(!r.success||r.data.operation!=="start"||(t?r.data.customer!==void 0:r.data.customer===void 0))throw new b("INVALID_REQUEST","Invalid current Funnel start");let i=r.data,a=mr({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||a.identify(e.apiKey);let o=ms(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")||!Ei(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 el(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((f,m)=>{s=()=>m(n.signal?.reason),n.signal?.addEventListener("abort",s,{once:!0}),n.signal?.aborted&&s()});try{for(;;){let f=await Promise.race([r.read(),c]);if(f.done){o=!0;break}if(a+=f.value.length,a>t)throw n.error("limit");i.push(f.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 f of i)u.set(f,l),l+=f.length;return u}async function Gh(e,t,n){return new TextDecoder("utf-8",{fatal:!0}).decode(await el(e,t,n))}function gs(e,t){let n=typeof e=="string"?new TextEncoder().encode(e):e;return n.byteLength===t.byteLength&&mu(n)===t.sha256}async function hs(e,t){let n=Ur.parse(t),{artifact:r,environmentId:i}=n.content,a=new yn(e.baseUrl??pr).origin,o=new yn(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((f,m)=>{c=setTimeout(()=>{let h=new b("TIMEOUT","Public Paywall read timed out");s.abort(h),m(h)},Xt.initializationMs)}),l=(async()=>{let f=await(e.fetch??globalThis.fetch)(o,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:s.signal});if(s.signal.aborted&&(f.body?.cancel().catch(()=>{}),s.signal.throwIfAborted()),!f.ok||!f.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(f.headers.get("content-length"))>r.byteLength)throw f.body?.cancel().catch(()=>{}),new b("INVALID_RESPONSE","Public Paywall is unavailable");let m=await el(f,r.byteLength,{signal:s.signal,error:h=>new b("INVALID_RESPONSE",h==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!gs(m,r))throw new b("INVALID_RESPONSE","Public Paywall digest or size changed");return Uf(n,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(m)))})();try{return await Promise.race([l,u])}finally{clearTimeout(c)}}var Kh=(e,t)=>new b(e,t);async function tl(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=QI(e,t,o)}catch{i=null}return a??(a=e.snapshot?.generation??(await e.refresh()).generation),{advance:{policyRevision:r.policyRevision,generation:a},prediction:i}}function QI(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=Ru({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:gn.parse(o)}),c=JI(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 JI(e,t,n){return eh(e,t,n,Kh)}var tn=require("zod");var Hh=Pt.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}),Qh=tn.z.strictObject({schemaVersion:tn.z.literal(1),scope:Ne,runId:tn.z.uuid(),funnelId:tn.z.uuid(),versionId:tn.z.uuid(),processBindingIds:tn.z.record(tn.z.uuid(),tn.z.uuid().nullable()).optional(),command:Hh.optional(),closeCommand:Hh.refine(e=>e.operation==="close").optional(),purchase:tn.z.strictObject({receiptId:tn.z.uuid(),operationId:tn.z.uuid(),generation:tn.z.number().int().nonnegative()}).optional(),closed:tn.z.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),Zt=()=>new b("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),As=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Jh(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:Qh.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 f=await a();if(f.entry&&n!==null&&r(f.entry)!==n)throw Zt();let m=u(f.entry,f.revision);if(As(f.entry,m)){t=f.revision;return}let h=await e.write(f.revision,m);if(h!==null){if(!Number.isSafeInteger(h)||h<=f.revision)throw Zt();t=h;return}}throw Zt()}function c(u,l){if(!u||!l)return u;if(u.processBindingIds&&Object.hasOwn(u.processBindingIds,l)){let f={...u.processBindingIds};delete f[l],u={...u,processBindingIds:f}}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 Zt();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=Qh.parse(u),f=l.command;return!f||n!==null&&r(l)!==n?Promise.reject(Zt()):(n??(n=r(l)),o(()=>s((m,h)=>{if(m&&!As(r(m),r(l)))throw Zt();if(m&&l.processBindingIds){for(let[d,A]of Object.entries(l.processBindingIds))if(m.processBindingIds&&Object.hasOwn(m.processBindingIds,d)&&m.processBindingIds[d]!==A)throw Zt();m={...m,processBindingIds:{...m.processBindingIds,...l.processBindingIds}}}if(!m){if(h!==t&&f.operation!=="close")throw Zt();return l}if(!m.command)return{...m,command:f,...f.operation==="close"?{closed:!0}:{}};if(f.operation==="close"&&m.command.operation!=="close"){if(m.command.requestId===f.requestId||m.closeCommand&&!As(m.closeCommand,f))throw Zt();return{...m,closeCommand:f,closed:!0}}if(!As(m.command,f))throw Zt();return m})))},observePurchase(u,l,f,m){return o(()=>s((h,d)=>{if(!h&&d!==t||h&&r(h)!==r({...u,schemaVersion:1}))throw Zt();if(h?.purchase&&h.purchase.generation>l.generation)return c(h,m);if(h?.purchase&&h.purchase.generation===l.generation&&h.purchase.operationId!==l.operationId)throw Zt();return f?!h?.purchase||h.purchase.operationId!==l.operationId?c(h,m):c(h.command?{...h,purchase:void 0}:null,m):c({schemaVersion:1,...u,...h,purchase:l},m)}))},settle(u){return o(()=>s(l=>c(l,u)))}}}function Zh(e){let t,n,r=()=>new b("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,n=e.locks??globalThis.navigator?.locks,!t||!n||!globalThis.crypto?.subtle)throw r();let s=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??pr).href,e.runToken])),c=new Uint8Array(await crypto.subtle.digest("SHA-256",s));return"indiana.funnel.commands.v1."+Array.from(c,u=>u.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function a(s){try{let c=await i;return await n.request(c,{mode:"exclusive"},()=>s(c))}catch(c){throw c instanceof b?c:r()}}function o(s){let c=t.getItem(s);if(c===null)return{revision:0,entry:null};if(c.length>1048576)throw r();let u=JSON.parse(c);if(!u||typeof u!="object"||!("revision"in u)||!("entry"in u)||!Number.isSafeInteger(u.revision)||Number(u.revision)<0)throw r();return{revision:Number(u.revision),entry:u.entry}}return{read:()=>a(o),write:(s,c)=>a(u=>{if(o(u).revision!==s)return null;if(!Number.isSafeInteger(s+1))throw r();return t.setItem(u,JSON.stringify({revision:s+1,entry:c})),s+1})}}function Wh(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(f){if(n&&(n.projectId!==f.projectId||n.environment!==f.environment))throw new b("SCOPE_MISMATCH","Run scope changed");n??(n={...f})},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(f,m="Run identity changed during the request"){if(f!==i||s)throw new b("IDENTITY_CHANGED",m)},assertRun(f){if(r&&(f.id!==r.id||f.source.type!==r.source.type||f.source.id!==r.source.id||f.source.versionId!==r.source.versionId||f.locale!==r.locale||!Ei(f.parameters,r.parameters)))throw new b("INVALID_RESPONSE","Run version changed");if(e&&f.source.id!==e)throw new b("INVALID_RESPONSE","Run belongs to another Funnel")},publish(f,m,h,d,A){if(!(f.operation==="review"&&r&&r!==h&&m.run.revision<=r.revision)&&!(r&&m.run.revision===r.revision&&d!==void 0&&d<u)&&(f.operation==="review"&&!m.run.stopped&&["running","waiting"].includes(m.run.status)&&r&&m.run.nodeId===r.nodeId&&m.run.visit===r.visit&&m.run.revision===r.revision&&(m.run.screen=r.screen,(r.paywall?.quote?.operationId===m.review?.activeOperationId||!r.paywall?.quote&&m.review?.activeOperationId===null)&&(m.run.paywall=r.paywall)),!(r?.paywall&&m.run.paywall&&r.paywall.receiptId===m.run.paywall.receiptId&&(m.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||m.run.revision>=r.revision)r=m.run;else if(!A)return;if(r)for(let k of l)try{k(structuredClone(r))}catch{}}},identify(f){if(s)throw new b("IDENTITY_CHANGED","Controller was reset");if(!jt.test(f))throw new b("INVALID_TOKEN","Customer credential required");o(),c=f},subscribe(f){return l.add(f),()=>l.delete(f)},reset(){s||(s=!0,o(),c=void 0,r=null,l.clear())}}}function fr(e){let{customerToken:t,...n}=e;return n}var ZI=e=>!(e instanceof b)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function Yh({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,f=e?e.load().then(g=>{if(t.disposed)throw new b("IDENTITY_CHANGED","Controller was reset during command restoration");if(l=g,!g)return;if(r){if([g.command,g.closeCommand].some(I=>I&&!Object.hasOwn(g.processBindingIds??{},I.requestId)))throw new b("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(g.processBindingIds??{})}if(t.scope&&(g.scope.projectId!==t.scope.projectId||g.scope.environment!==t.scope.environment))throw new b("SCOPE_MISMATCH","Pending command belongs to another scope");if(u=g.purchase,o=g.closed===!0,!g.command)return;let y=g.command;i=y.operation==="close"?null:y,a=y.operation==="close"?y:g.closeCommand?.operation==="close"?g.closeCommand:null,a&&(o=!0);for(let I of[i,a])I&&c.add(I.requestId)}):Promise.resolve();f.catch(()=>{});async function m(g){e&&await f;let y=t.generation;if(e){if(!t.view||!t.scope)throw new b("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:fr(g),...r?{processBindingIds:{[g.requestId]:r.binding(g.requestId)}}:{}})}if(y!==t.generation||i!==g&&a!==g)throw new b("IDENTITY_CHANGED","Run changed before command dispatch");let I=c.has(g.requestId);c.add(g.requestId);try{return await n(g)}catch(w){throw y===t.generation&&(i===g||a===g)&&!I&&!ZI(w)&&(e&&await e.settle(g.requestId),y===t.generation&&k(g)),w}}function h(g){let y=Pt.parse(g);if(y.operation==="start"||y.operation==="get"||y.operation==="review")throw new b("INVALID_REQUEST","Mutation required");if(o&&y.operation!=="close"){if(i?.requestId===y.requestId)return A(y.requestId);throw new b("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(y.operation==="close"){if(i?.requestId===y.requestId)throw new b("INVALID_REQUEST","Close requires its own request identity");if(o=!0,a&&JSON.stringify(fr(a))!==JSON.stringify(fr(y)))throw new b("COMMAND_PENDING","Retry the original Close");return a??(a=y),s.close?s.close:d(a,"close")}if(i){if(JSON.stringify(fr(i))!==JSON.stringify(fr(y)))throw new b("COMMAND_PENDING","Retry the original command before sending another");if(s.command)return s.command}else i=y;return d(i,"command")}function d(g,y){let I=m(g);s[y]=I;let w=()=>{s[y]===I&&(s[y]=null)};return I.then(w,w),I}function A(g){return n({operation:"get",settlementRequestId:g})}function k(g){return!g||i!==g&&a!==g?!1:(i===g&&(i=null),a===g&&(a=null),c.delete(g.requestId),!i&&!a&&(l=null),!0)}return{ready:f,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(g){if(l&&(g.run.id!==l.runId||g.run.source.id!==l.funnelId||g.run.source.versionId!==l.versionId))throw new b("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(g,y,I,w){let C=g.operation==="get"?g.settlementRequestId:"requestId"in g&&g.operation!=="start"?g.requestId:void 0,j=C&&y.settlement?.state==="settled"&&y.run.pendingRequest?.requestId!==C&&(g.operation==="get"||!o||g.operation==="close"||!["running","waiting"].includes(y.run.status))?C:void 0,E=i?.requestId===j?i:a?.requestId===j?a:void 0;e?.bind({scope:y.scope,runId:y.run.id,funnelId:y.run.source.id,versionId:y.run.source.versionId});let ae=y.run.paywall,xe=ae??y.purchase,Pe=xe?.operation,Ee=y.settlement&&(!ae||ae.purchaseRequestId===y.settlement.requestId)&&(!u||u.operationId===y.settlement.operationId)?y.settlement:void 0,ye=Pe?.operationId??xe?.quote?.operationId??Ee?.operationId,gt=xe?.receiptId??Ee?.receiptId,Je=ae?.selectionGeneration??u?.generation??0;if(e&&ye&&gt&&g.operation!=="review"&&(!t.view||y.run.revision>=t.view.revision)&&(w===void 0||w>=t.readSequence)&&(!u||Je>=u.generation)){let Te={receiptId:gt,operationId:ye,generation:Je},tt=Pe?.status==="complete"||xe?.canReselect===!0;await e.observePurchase({scope:y.scope,runId:y.run.id,funnelId:y.run.source.id,versionId:y.run.source.versionId},Te,tt,j),t.assertCurrent(I),(!u||Te.generation>=u.generation)&&(w===void 0||w>=t.readSequence)&&(tt?u?.operationId===Te.operationId&&(u=void 0):u=Te)}else e&&j&&await e.settle(j);return t.assertCurrent(I),j?k(E):!1},stop(){o=!0},submit:h,settle:A,reset(){o=!0,i=null,a=null,u=void 0,l=null,s.close=null,c.clear(),s.command=null}}}function gr(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new b("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!Ri.test(e.serverKey)))throw new b("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new b("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let t=mr({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),n=Wh(e.funnelId,e.scope??e.configuration?.scope),r=e.session?.subscribeIdentity(u),i=null,a=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?Zh(e):void 0),o=a&&Jh(a),s=Yh({journal:o,state:n,call:l,processIdentity:e.process});async function c(y){if(e.process)return e.process.request(y);let I=n.generation;n.assertCurrent(I);let w=performance.now()+(e.timeoutMs??35e3),C=n.customerToken??("customerToken"in y?y.customerToken:void 0);if(e.session){let ae=n.signal,xe,Pe=()=>{},Ee=new Promise((ye,gt)=>{Pe=()=>gt(ae.reason),ae.addEventListener("abort",Pe,{once:!0}),xe=setTimeout(()=>gt(new b("TIMEOUT","Longplay request timed out")),Math.max(1,w-performance.now()))});try{C=await Promise.race([Promise.resolve().then(()=>(n.assertCurrent(I),e.session.access())),Ee])}finally{clearTimeout(xe),ae.removeEventListener("abort",Pe)}}n.assertCurrent(I);let j={...y,...C?{customerToken:C}:{}},E=y.operation==="page_experiments"?vo.parse(j):Pt.parse(j);return t.requestWithCredential("funnels",E,e.runToken,{headers:e.serverKey&&!C?{[Bg]:e.serverKey}:void 0,timeoutMs:Math.max(1,w-performance.now())})}function u(){r?.(),n.reset(),s.reset(),i=null,t.dispose()}async function l(y,I){let w=n.generation,C=()=>n.assertCurrent(w);o&&await s.ready,C();let j=n.view,E=ms(e,await c(y));if(y.operation==="review"&&!E.review)throw new b("INVALID_RESPONSE","Historical projection is missing");if(C(),E.runToken&&E.runToken!==e.runToken)throw new b("INVALID_RESPONSE","Run credential changed");let ae=y.operation==="get"?y.settlementRequestId:"requestId"in y&&y.operation!=="start"?y.requestId:void 0;if(ae&&E.settlement?.requestId!==ae)throw new b("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");s.assertBinding(E),n.assertRun(E.run),n.bindScope(E.scope);let xe=await s.observe(y,E,w,I);return!E.run.stopped&&["running","waiting"].includes(E.run.status)&&y.operation==="get"&&y.settlementRequestId||(C(),["running","waiting"].includes(E.run.status)||s.stop(),n.publish(y,E,j,I,xe)),E}let f=s.submit,m=null,h=new WeakMap;function d(y){let I=h.get(y);if(I)return I;let w=k(y);return h.set(y,w),w}let A=!1;async function k(y){let I=await y;if(I.run.instruction?.type!=="evaluate_segment")return I;if(m)return m;A=!0;let w=n.generation,C=(async()=>{for(let j=0;j<32&&I.run.instruction?.type==="evaluate_segment";j++){if(s.pending||s.closeRequested)return I;let E=I.run;if(I.run.instruction?.type==="evaluate_segment"){let{advance:xe}=await tl(e.configuration,E,{predict:!1});if(w!==n.generation)throw new b("IDENTITY_CHANGED","Run identity changed during segment calculation");if(s.pending||s.closeRequested)return I;if(n.view&&(n.view.revision!==E.revision||n.view.visit!==E.visit||n.view.nodeId!==E.nodeId))return l({operation:"get"});let Pe=!0;tl(e.configuration,E).then(({prediction:Ee})=>{Pe&&w===n.generation&&!s.closeRequested&&n.view?.id===E.id&&!n.view.stopped&&n.view.nodeId===E.nodeId&&n.view.visit===E.visit&&n.view.revision===E.revision&&(i=Ee)}).catch(()=>{});try{I=await f({operation:"commit_segment",requestId:Mg(E.id,E.visit,`segment:${E.revision}`),nodeId:E.nodeId,visit:E.visit,revision:E.revision,...xe})}finally{Pe=!1,i=null}}}return I})();m=C;try{return await C}finally{m===C&&(m=null)}}let g={get configuration(){return A?e.configuration:void 0},get configurationReady(){return!0},get view(){return n.view?structuredClone(n.view):null},get pendingCommand(){let y=s.closing??s.pending;return y?structuredClone(fr(y)):null},get pendingCommands(){return[s.pending,s.closing].filter(y=>y!==null).map(y=>structuredClone(fr(y)))},get pendingPurchase(){return s.purchase?structuredClone(s.purchase):null},get prediction(){let y=n.view;return i&&y&&!y.stopped&&["running","waiting"].includes(y.status)&&y.id===i.runId&&y.nodeId===i.from.nodeId&&y.visit===i.from.visit&&y.revision===i.from.revision&&!s.closeRequested?structuredClone(i):null},settle:s.settle,get webViewUrl(){return"bundled"},resolvePaywall(y){return hs(e,y)},async pageExperiments(y,I=[]){let w=n.generation;n.assertCurrent(w);let C=n.view?.id;if(!C)throw new b("INVALID_REQUEST","Read the Run before its page experiments");let j=zg.parse(await c(vo.parse({operation:"page_experiments",release:y,usedReceiptIds:I})));if(n.assertCurrent(w),j.runId!==C||j.scope.projectId!==n.scope?.projectId||j.scope.environment!==n.scope?.environment)throw new b("SCOPE_MISMATCH","Page experiment Run changed");return j},review(y){return l({operation:"review",...y?{receiptId:y}:{}},n.nextRead())},async get(y,I){o&&await s.ready,I??(I=s.purchase&&{receiptId:s.purchase.receiptId,operationId:s.purchase.operationId});let w=n.nextRead();return d(l({operation:"get",...y?{data:y}:{},...I?{purchase:I}:{}},w))},resume(y=n.view?.pendingRequest?.requestId){return y?s.closeRequested?g.settle(y):s.pending?.requestId===y?d(f(s.pending)):d(f({operation:"resume",requestId:y})):Promise.reject(new b("INVALID_REQUEST","No interrupted command is available"))},submit(y){return d(f(y))},retry(){return s.closeFlight?s.closeFlight:s.closing?f(s.closing):s.closeRequested&&s.pending?g.settle(s.pending.requestId):s.inFlight?d(s.inFlight):s.pending?d(f(s.pending)):Promise.reject(new b("INVALID_REQUEST","No command is pending"))},identify(y){n.identify(y),i=null,t.reset()},subscribe:n.subscribe,reset:u};return g}function Xh(e){if(!jt.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=fs({...e,scope:e.scope,apiKey:e.customerToken});return{async start(n){let r=await t.start(n),i=gr({...e,runToken:r.runToken});i.identify(e.customerToken);let a=r.run.instruction?.type==="evaluate_segment"?await i.get():r;return{...r,...a,controller:i}}}}function eA(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 tA(e,t,n){if(e.operationId!==t.operationId||t.currency!==void 0&&e.currency!==t.currency)throw new b("INVALID_RESPONSE",n)}function nA(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 rA(e,t,n=!1){return!e||e.operationId!==t?.operationId?t:e.status==="complete"&&t.status!=="complete"||e.status!=="pending"&&(t.status==="pending"||n&&t.status!=="complete")?e:t}async function iA(e,t){if(!jt.test(t.customerToken))throw new b("INVALID_TOKEN","A verified Customer credential is required");if(e.session&&e.session.peek()!==t.customerToken)throw new b("SCOPE_MISMATCH","Paywall credential does not match the shared session");let n=O.resolvePaywall.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale,...t.requirement?{requirement:t.requirement}:{}}),r=mr(e);e.session||r.identify(t.customerToken);let i=null,a=!1,o=null,s=null,c=null,u=null;function l(){if(a)throw new b("IDENTITY_CHANGED","Paywall is closed")}async function f(){l();let A=O.resolvePaywall,k=await me(r.request,A,{...n,selector:i?{type:"version",versionId:i.id}:n.selector}),g=await hs(e,k.paywall);if(l(),t.paywallVersionId?g.id!==t.paywallVersionId:g.paywallId!==t.paywallId)throw new b("INVALID_RESPONSE","The requested Paywall changed");if(i&&(!eA(g,i)||g.paywallId!==i.paywallId))throw new b("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return i=g,structuredClone(i)}async function m(A){if(l(),u&&A!=="read")throw new b("COMMAND_PENDING","Wait for the original quote");if(!o)throw new b("INVALID_REQUEST","A quoted purchase is required");let k=o,g=A==="read"?O.readSubscriptionOperation:O.attach,y=await me(r.request,g,{operationId:k.operationId,...A==="read"?{}:{intent:A}});return tA(y.operation,{operationId:k.operationId,currency:n.commerce.currency},"The purchase operation changed"),l(),o?.operationId!==k.operationId?structuredClone(y.operation):(s=rA(s,y.operation),structuredClone(s))}let h={get view(){return i?structuredClone(i):null},get quote(){return o?structuredClone(o):null},get operation(){return s?structuredClone(s):null},get webViewUrl(){return"bundled"},refresh:f,async preview(A){if(l(),!i)throw new b("INVALID_REQUEST","Load the Paywall first");let k=i.document.buttons[A.actionId];if(k?.type!=="checkout")throw new b("INVALID_REQUEST","Choose an authored purchase action");let g=Lm(k.product,A.selection,i.capabilities);if(!g)throw new b("PRODUCT_UNAVAILABLE","Choose an available Product");let y=Tf(i.document.screen,g,A.selection,i.capabilities),I=O.previewAttach.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,requestId:A.requestId,plans:[{productVersionId:g,...Object.keys(y).length?{featureQuantities:y}:{}}],provider:n.commerce.provider,currency:n.commerce.currency,...A.offerId?{offerId:A.offerId}:{},...A.nativeOffer?{nativeOffer:A.nativeOffer}:{}}),w=JSON.stringify(I);if(c&&c!==w&&(u||!s||s.status==="pending"))throw new b("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(c===w){if(u)return u;if(o)return structuredClone(o)}c!==w&&(o=null,s=null),c=w;let C=(async()=>{let j=O.previewAttach,E=await me(r.request,j,I);return l(),nA(E.quote,{productVersionId:g,featureQuantities:y,currency:n.commerce.currency,provider:n.commerce.provider},"The purchase quote changed its selected Product or presentment"),o=E.quote,s=null,structuredClone(o)})();u=C;try{return await C}finally{u===C&&(u=null)}},confirm:()=>m("confirm"),cancel:()=>m("cancel"),read:()=>m("read"),destroy(){a||(a=!0,d?.(),r.dispose(),i=null,o=null,s=null,c=null)}},d=e.session?.subscribeIdentity(h.destroy);try{return await f(),h}catch(A){throw h.destroy(),A}}function oA(e,t){let n,r=0,i=-1,a,o=!1,s=()=>{if(o)throw new b("CLOSED","Native host was destroyed");if(!e.nativeModule)throw new b("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return e.nativeModule},c=()=>new b("IDENTITY_CHANGED","Customer identity changed during the native operation"),u=t.subscribeIdentity(()=>{r++,i=-1;let h=r;n&&e.nativeModule&&n.then(d=>e.nativeModule.reset(d,h)).catch(()=>{})}),l=e.nativeEvents?.(h=>{!n||!e.nativeModule||typeof h?.requestId!="string"||(async()=>{let d=await n;if(h.instanceId!==d)return;if(h.kind==="credential"){let g=r,y=null;try{if(!o&&h.revision===g){let I=await t.access();!o&&r===g&&(y=I)}}finally{await e.nativeModule.provideCredential(d,h.requestId,y)}return}let A=!1,k=r;try{if(o||h.revision!==k||!e.onNativeAction)throw c();await e.onNativeAction(h.action),A=!o&&r===k}finally{await e.nativeModule.acknowledge(d,h.requestId,A)}})().catch(()=>{})});async function f(h,d={}){let A=s();if(t.snapshot()&&!e.nativeEvents)throw new b("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let k=r,g=await t.access();if(o||r!==k)throw c();if(!n){let w=A.create(JSON.stringify({baseUrl:e.baseUrl??"https://api.longplayai.com",scope:e.scope,timeout:(e.timeoutMs??15e3)/1e3,credentialEvents:!!e.nativeEvents}));n=w,w.catch(()=>{n===w&&(n=void 0)})}let y=await n;if(o||r!==k)throw c();if(i!==k){if(!a||a.epoch!==k){let C=(async()=>{if(await A.identify(y,JSON.stringify({revision:k,credentials:g})),o||r!==k)throw await A.reset(y,k),c();i=k})();a={epoch:k,task:C}}let w=a;try{await w.task}finally{a===w&&(a=void 0)}}let I=await A.invoke(y,h,JSON.stringify(d));if(o||r!==k)throw c();try{return JSON.parse(I)}catch{throw new b("INVALID_RESPONSE","Native host returned invalid JSON")}}async function m(h,d){let A=await f(h,d);if(!A||typeof A!="object"||Array.isArray(A)||A.status!=="complete"&&A.status!=="dismissed")throw new b("INVALID_RESPONSE","Native presentation returned an invalid result");return A}return{showFunnel(h){return m("showFunnel",{runToken:h})},showPaywall(h){return m("showPaywall",h)},showContent(h){return m("showContent",h)},purchaseSubscription(h,d){return f("purchaseSubscription",{operationId:h,accepted:d})},switchSubscription(h,d){return f("switchSubscription",{operationId:h,accepted:d})},restorePurchases(){return f("restorePurchases")},manageSubscriptions(h){return f("manageSubscriptions",h?{productId:h}:{})},async dismiss(){r++,i=-1,n&&await s().reset(await n,r)},async destroy(){o||(o=!0,r++,u(),l?.(),n&&e.nativeModule&&await e.nativeModule.destroy(await n))}}}var WI=O.trackUsage.request.shape.command,YI=O.trackUsage.response;function aA(e){let t=Ne.parse(e.scope),n=$h({...e,scope:t}),r={...e,scope:t,session:n.session},i=oA(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 Xh({...r,customerToken:s()})},resumeFunnel(c){return s(),gr({...r,runToken:c})},paywall(c){return iA(r,{...c,customerToken:s()})},async trackUsage(c){if(s(),!e.usageReporter)throw new b("INVALID_REQUEST","Configure your authenticated backend usageReporter");let u=WI.parse(c),l=a,f;try{f=await e.usageReporter(u)}catch(h){throw l!==a?new b("IDENTITY_CHANGED","Customer identity changed during usage reporting"):h}if(l!==a)throw new b("IDENTITY_CHANGED","Customer identity changed during usage reporting");let m=YI.parse(f);if(m.scope.projectId!==t.projectId||m.scope.environment!==t.environment)throw new b("INVALID_RESPONSE","Usage response scope differs");return m}}}var uA=require("zod");var ki=require("zod");var XI=ki.z.record(ki.z.string().regex(/^[a-f0-9]{64}$/),ki.z.strictObject({at:ki.z.number(),text:ki.z.string()})),Qr=2*1048576,ev=100;function tv(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function sA(e,t){let n=t===void 0?tv():t,r=new Map,i=0,a=!1,o=!1,s,c;async function u(f){if(!n)return null;let m;try{let h=await Promise.race([Promise.resolve().then(()=>n.getItem(f)),new Promise(d=>{m=setTimeout(()=>d(null),ev)})]);return typeof h=="string"&&h.length<=Qr&&new TextEncoder().encode(h).byteLength<=Qr?h:null}catch{return null}finally{clearTimeout(m)}}function l(){if(c)return c;let f=(async()=>{try{let m=await u(`${e}:artifacts`);if(m)return XI.parse(JSON.parse(m))}catch{}return{}})();return c=f,f.finally(()=>{c===f&&(c=void 0)}),f}return{async readManifest(){return u(e)},writeManifest(f){!n||f.length>Qr||new TextEncoder().encode(f).byteLength>Qr||(s=f,!o&&(o=!0,Promise.resolve().then(async()=>{try{for(;s!==void 0;){let m=s;try{await n.setItem(e,m)}catch{}s===m&&(s=void 0)}}finally{o=!1}})))},async readArtifact(f){let m=(await l())[f],h=Date.now();return m&&h>=m.at&&h-m.at<=Xt.retentionMs?m.text:void 0},writeArtifact(f,m){if(!n||m.length>Qr)return;let h=r.get(f);if(h?.text===m||!h&&r.size>=128)return;let d=new TextEncoder().encode(m).byteLength;i-(h?.byteLength??0)+d>Qr||(r.set(f,{text:m,byteLength:d}),i+=d-(h?.byteLength??0),!a&&(a=!0,Promise.resolve().then(async()=>{try{for(;r.size;){let A=new Map(r);try{let k={...await l()},g=Date.now();for(let[C,j]of A)k[C]={at:g,text:j.text};let y={},I=2,w=0;for(let[C,j]of Object.entries(k).sort(([,E],[,ae])=>ae.at-E.at)){if(j.at>g||g-j.at>Xt.retentionMs)continue;let E=new TextEncoder().encode(JSON.stringify({[C]:j})).byteLength;I+E>Qr||w>=128||(y[C]=j,I+=E,w++)}await n.setItem(`${e}:artifacts`,JSON.stringify(y))}catch{}finally{for(let[k,g]of A)r.get(k)===g&&(r.delete(k),i-=g.byteLength)}}}finally{a=!1}})))}}}var Oe=(e,t)=>new b(e,t),hr=()=>performance.now(),cA=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function lA(e){let t=lu.parse(e.scope),n=new yn(e.origin??pr);if(n.username||n.password||n.search||n.hash||n.pathname!=="/"||n.protocol!=="https:"&&!(n.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(n.hostname)))throw Oe("INVALID_URL","Configuration requires a trusted HTTPS origin");let r=new Set([n.origin,...(e.assetOrigins??[]).map(W=>{let Z=new yn(W);if(Z.protocol!=="https:"||Z.username||Z.password||Z.search||Z.hash||Z.pathname!=="/")throw Oe("INVALID_URL","Invalid configuration asset origin");return Z.origin})]),i=e.fetch??globalThis.fetch.bind(globalThis),a=`/api/v1/configuration/${t.environmentId}`,o=`indiana:configuration:1:${n.origin}:${Ct(t)}`,s=sA(o,e.storage),c,u=0,l=0,f=!1,m=!1,h=0,d=0,A,k,g,y,I=0,w=new Set,C=new Set,j=new Map,E=new Map,ae=0,xe=!1;function Pe(){for(let W of w)try{W()}catch{}}function Ee(W){try{e.onError?.(W)}catch{}}let ye=()=>!m&&!f&&!!c&&hr()<u&&Date.now()<l;function gt(){if(!ye())throw Oe("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Je(W,Z,le){if(!j.has(W)){for(;j.size&&(j.size>=128||ae+le>Xt.maxCacheBytes);){let de=j.entries().next().value;ae-=de[1].byteLength,j.delete(de[0])}j.set(W,{text:Z,byteLength:le}),ae+=le}}function Te(W,Z,le){return Gh(W,Z,{signal:le,error:de=>Oe("INVALID_RESPONSE",de==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function tt(W){let Z=new yn(W,n);if(!r.has(Z.origin)||Z.username||Z.password||Z.hash||Z.search)throw Oe("INVALID_URL","Configuration artifact origin is not trusted");return Z.href}async function Eo(W,Z,le=!1){let de=await i(tt(W),{method:"GET",credentials:"omit",redirect:"error",cache:le?"default":"no-cache",signal:Z,headers:{}});if(de.status===429){let Ye=de.headers.get("retry-after")??"";I=/^\d+$/.test(Ye)?Number(Ye)*1e3:Math.max(0,Date.parse(Ye)-Date.now())||15e3}if(!de.ok&&de.status!==304)throw Oe(`CONFIGURATION_HTTP_${de.status}`,"Configuration synchronization failed");return de}function Jr(W,Z,le){let de=Date.parse(W.headers.get("x-indiana-config-validated-at")??""),Ye=Date.parse(W.headers.get("x-indiana-config-valid-until")??""),rt=Date.parse(W.headers.get("date")??""),$e=W.headers.get("age"),nn=$e!==null&&/^\d+(\.\d+)?$/.test($e)?Number($e)*1e3:NaN;if(![de,Ye,rt,nn].every(Number.isFinite)||Ye<=de||Ye-de>Xt.maxControlAgeMs||de>rt+1e3)throw Oe("INVALID_RESPONSE","Configuration freshness evidence is invalid");let Mt=Math.min(Ye-de,le.maxControlAgeSeconds*1e3,Xt.maxControlAgeMs)-Math.max(nn,rt-de,0)-(hr()-Z);if(Mt<=0)throw Oe("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return hr()+Mt}function lt(){if(clearTimeout(g),clearTimeout(y),m||!w.size)return;ye()&&(y=setTimeout(()=>{ye()?lt():Pe()},Math.max(1,u-hr())),cA(y));let W=d?Math.min(15e3,1e3*2**Math.min(d-1,4)):Math.min(15e3,(c?.policy.refreshIntervalSeconds??15)*1e3);g=setTimeout(()=>{Kt().catch(Ee)},Math.max(I,W*(.8+Math.random()*.2))),cA(g)}async function Kt(){if(m)throw Oe("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(A)return A;let W=h,Z=new AbortController;k=Z;let le=(async()=>{if(!xe){xe=!0;try{let ko=await s.readManifest();if(ko&&!c){let qn=pu.parse(JSON.parse(ko));Ct(qn.scope)===Ct(t)&&(c=qn)}}catch{}}Z.signal.throwIfAborted();let $e=c,nn=hr(),Lt=await Eo(a,Z.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 Eo(a,Z.signal));let Mt=Lt.status===304?$e:pu.parse(JSON.parse(await Te(Lt,Xt.maxManifestBytes,Z.signal))),{generation:Zr,...Wr}=Mt,Mn=Lt.headers.get("etag");if(Ct(Mt.scope)!==Ct(t)||qf(Wr)!==Zr||Mn!==`"${Zr}"`&&Mn!==`W/"${Zr}"`)throw Oe("INVALID_RESPONSE","Configuration scope or content identity changed");if($e&&(Mt.revision<$e.revision||Mt.revision===$e.revision&&Mt.generation!==$e.generation))throw Oe("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[ko,qn]of Object.entries($e?.funnels??{})){let xr=Mt.funnels[ko];if(xr&&(xr.controlRevision<qn.controlRevision||xr.evaluationRevision<qn.evaluationRevision||xr.controlRevision===qn.controlRevision&&xr.state!==qn.state||xr.evaluationRevision===qn.evaluationRevision&&xr.evaluationMode!==qn.evaluationMode))throw Oe("INVALID_RESPONSE","Funnel control revision changed identity")}let br=Jr(Lt,nn,Mt.policy);if(Z.signal.throwIfAborted(),W!==h)throw Oe("CONFIGURATION_DISPOSED","Configuration scope changed");return c=Mt,u=br,l=Date.now()+Math.max(0,br-hr()),f=!1,d=0,I=0,s.writeManifest(Ct(Mt)),Pe(),structuredClone(Mt)})(),de=setTimeout(()=>Z.abort(Oe("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Xt.initializationMs),Ye=new Promise(($e,nn)=>Z.signal.addEventListener("abort",()=>nn(Z.signal.reason),{once:!0})),rt=Promise.race([le,Ye]).catch($e=>{throw d++,($e instanceof uA.z.ZodError||$e instanceof SyntaxError||$e instanceof b&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes($e.code))&&(u=0,f=!0,Pe()),$e}).finally(()=>{clearTimeout(de),A===rt&&(A=void 0),lt()});return A=rt,rt}async function Ar(W){let Z=W.sha256,le=Wr=>gs(Wr,W);tt(W.url);let de=j.get(Z);if(de){if(de.byteLength!==W.byteLength)throw Oe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return j.delete(Z),j.set(Z,de),de.text}let Ye=E.get(Z);if(Ye){if(Ye.byteLength!==W.byteLength)throw Oe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return Ye.promise}let rt=new AbortController;C.add(rt);let $e=h,nn=(async()=>{try{let br=await s.readArtifact(Z);if(br&&le(br)){if(rt.signal.throwIfAborted(),m||$e!==h)throw Oe("CONFIGURATION_DISPOSED","Configuration scope changed");return Je(Z,br,W.byteLength),br}}catch{}rt.signal.throwIfAborted();let Wr=await Eo(W.url,rt.signal,!0),Mn=await Te(Wr,W.byteLength,rt.signal);if(!le(Mn))throw Oe("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(m||$e!==h)throw Oe("CONFIGURATION_DISPOSED","Configuration scope changed");return Je(Z,Mn,W.byteLength),s.writeArtifact(Z,Mn),Mn})(),Lt=setTimeout(()=>rt.abort(Oe("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),Xt.initializationMs),Mt=new Promise((Wr,Mn)=>rt.signal.addEventListener("abort",()=>Mn(rt.signal.reason),{once:!0})),Zr=Promise.race([nn,Mt]).finally(()=>{clearTimeout(Lt),C.delete(rt),E.delete(Z)});return E.set(Z,{promise:Zr,byteLength:W.byteLength}),Zr}async function yr(){return ye()||await Kt(),gt(),c}async function ji(W){let Z,le=new Promise((de,Ye)=>{Z=setTimeout(()=>Ye(Oe("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Xt.initializationMs)});try{return await Promise.race([W(),le])}finally{clearTimeout(Z)}}function Ti(W,Z){if(gt(),c?.generation!==W.generation)throw Oe("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(Z&&c.funnels[Z]?.state!=="active")throw Oe("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function rl(W){let Z=W.gb.features;if(!Z)throw Oe("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let le=W.artifacts[Z];if(le.formatVersion!==1)throw Oe("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let de=Fc.parse(JSON.parse(await Ar(le)));if(Ct(de.scope)!==Ct({projectId:t.projectId,environment:t.environment})||de.generation!==le.generation||de.remoteFeatures.some(Ye=>Object.hasOwn(de.features,Ye)))throw Oe("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return Ti(W),{...de,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,u-hr())).toISOString()}}async function il(W,Z){let le=await yr(),de=le.funnels[W];Z&&(!de||de.evaluationMode==="local"&&!de.versions[Z])&&(A&&await A,le=await Kt()),Ti(le,W);let Ye=le.funnels[W];if(Ye.evaluationMode!=="local")throw Oe("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let rt=Z??Ye.currentVersionId,$e=Ye.versions[rt];if(!$e)throw Oe("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(le.artifacts[$e.artifact].formatVersion!==3)throw Oe("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[nn,Lt]=await Promise.all([Ar(le.artifacts[$e.artifact]).then(Mt=>Vf(JSON.parse(Mt))),Ye.evaluationMode==="local"?rl(le):void 0]);if(Lt&&Ct(Bf(nn,Lt))!==Ct($e.dependencies))throw Oe("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return Ti(le,W),{document:nn,growth:Lt,versionId:rt,control:structuredClone(Ye),manifest:structuredClone(le)}}async function ol(W,Z){try{return await il(W,Z)}catch(le){if(!(le instanceof b)||!(le.code==="CONFIGURATION_CHANGED"||le.code==="CONFIGURATION_HTTP_404"&&ye()))throw le;let de=c?.generation;if(A&&await A,await Kt(),le.code!=="CONFIGURATION_CHANGED"&&c?.generation===de)throw le;return il(W,Z)}}function ys(){f=!0,Pe(),Kt().catch(Ee)}let Ro=()=>{(typeof document>"u"||document.visibilityState==="visible")&&ys()};function mA(W){if(m)throw Oe("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return w.add(W),w.size===1&&(typeof window<"u"&&(window.addEventListener("online",ys),window.addEventListener("focus",Ro),document.addEventListener("visibilitychange",Ro)),lt()),()=>{w.delete(W),w.size||(clearTimeout(g),clearTimeout(y),al())}}function al(){typeof window<"u"&&(window.removeEventListener("online",ys),window.removeEventListener("focus",Ro),document.removeEventListener("visibilitychange",Ro))}return{scope:Object.freeze({...t}),refresh:Kt,subscribe:mA,assertFresh:gt,assertFeatures(W){gt();let Z=c.gb.features;if(!Z)throw Oe("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(W!==void 0&&c.artifacts[Z].generation!==W)throw Oe("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return ye()},get snapshot(){return c?structuredClone(c):null},get remainingMs(){return ye()?Math.max(0,u-hr()):0},async features(){return ji(async()=>rl(await yr()))},pageExperiments:()=>ji(async()=>{let W=await yr(),Z=W.gb.pageExperiments;if(!Z)throw Oe("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let le=W.artifacts[Z];if(le.formatVersion!==1)throw Oe("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let de=Wg.parse(JSON.parse(await Ar(le)));if(de.environmentId!==t.environmentId||de.generation!==le.generation)throw Oe("INVALID_RESPONSE","Page experiment scope or generation changed");return Ti(W),de}),funnel:(W,Z)=>ji(()=>ol(W,Z)),paywall:(W,Z)=>ji(async()=>{let le=await yr(),de=le.paywalls?.[W];if(!de||!Z&&de.state!=="published")throw Oe("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let Ye=Z??de.currentVersionId,rt=de.versions[Ye],$e=rt&&le.artifacts[rt.artifact];if(!$e||$e.kind!=="paywall"||$e.formatVersion!==1)throw Oe("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let nn=Ya.parse(JSON.parse(await Ar($e)));return Ti(le),{document:nn,versionId:Ye,version:rt.version,control:structuredClone(de),manifest:structuredClone(le)}}),async localFunnel(W,Z){let le=await ji(()=>ol(W,Z));if(!le.growth)throw Oe("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:de,remoteFeatures:Ye,...rt}=le.growth;return Jg({scope:{projectId:t.projectId,environment:t.environment},funnelId:W,versionId:le.versionId,evaluationMode:"local",evaluationRevision:le.control.evaluationRevision,document:le.document,payload:rt})},assertFunnel(W,Z,le){gt();let de=c.funnels[W];if(!de||de.state!=="active")throw Oe("FUNNEL_STOPPED","Funnel is paused or unavailable");if(de.evaluationMode!=="local")throw Oe("EVALUATION_MODE","This Funnel now executes at Longplay");if(Z!==void 0&&de.controlRevision!==Z)throw Oe("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(le!==void 0&&!de.versions[le])throw Oe("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!m){m=!0,h++,u=0,k?.abort(Oe("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(g),clearTimeout(y),al(),Pe(),w.clear();for(let W of C)W.abort(Oe("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));j.clear(),ae=0}}}}async function dA(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&&Ct(n)!==Ct(e.scope))throw new b("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await t.funnel(e.funnelId)).control.evaluationMode!=="local")throw new b("EVALUATION_MODE","This Funnel uses Remote evaluation");let i=Ri.test(e.credential);if(i?!e.customerId:e.customerId!==void 0)throw new b("INVALID_REQUEST","Only Server-Key starts name their Customer");let a=fs({...e,scope:n,apiKey:e.credential}),o=s=>{let c=gr({...e,scope:n,runToken:s,...i?{serverKey:e.credential}:{}});return i||c.identify(e.credential),c};return{async start(s){let c=await a.start({...s,funnelId:e.funnelId,...i?{customer:{type:"id",value:e.customerId}}:{}}),u=o(c.runToken),l=await u.get();return{...c,...l,controller:u}},async restore(s){let c=o(s),u=await c.get();if(u.run.source.id!==e.funnelId)throw c.reset(),new b("SCOPE_MISMATCH","Run belongs to another Funnel");return{...u,runToken:s,controller:c}}}}function nl(e,...t){try{Promise.resolve(e?.(...t)).catch(()=>{})}catch{}}function pA(e){if(!e.scope)throw new b("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(e.session!==void 0)throw new b("INVALID_CONFIGURATION","The merchant process adapter owns the session");let t=null,n,r=0,i=new Set,a=new Map,o=new Map;async function s(m){let h,d=new Promise((A,k)=>{h=setTimeout(()=>k(new b("TIMEOUT","Process bridge request timed out")),e.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(m),d])}finally{clearTimeout(h)}}function c(m){throw m instanceof b&&(m.status===401||m.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear()),m}function u(m,h){if(h!==r)throw new b("IDENTITY_CHANGED","Process was detached during a request");let d=Eu.parse(m);if(d.scope.projectId!==e.scope.projectId||d.scope.environment!==e.scope.environment)throw new b("SCOPE_MISMATCH","Process response belongs to another App/environment");if(t&&(t.run.id!==d.run.id||t.run.source.versionId!==d.run.source.versionId||t.run.source.id!==d.run.source.id||t.run.runExpiresAt!==d.run.runExpiresAt||t.run.identity.startedAs!==d.run.identity.startedAs||t.run.identity.participantId!==d.run.identity.participantId||t.run.identity.binding&&d.run.identity.binding&&t.run.identity.binding.id!==d.run.identity.binding.id))throw new b("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!t||d.run.revision>=t.run.revision){if(t?.run.identity.binding&&!d.run.identity.binding)throw new b("INVALID_RESPONSE","The process lost its Customer binding");t=d;for(let j of i)nl(j,d.run);d.run.instruction?.type==="authentication_required"&&nl(e.onAuthenticationRequired,d.run)}d.settlement?.accepted!==void 0&&o.set(d.settlement.requestId,d.settlement.accepted);let{identity:A,instruction:k,...g}=d.run,{contract:y,settlement:I,...w}=d,C=I&&(({accepted:j,...E})=>E)(I);return{...w,run:{...g,authenticated:A.binding!==null,instruction:k?.type==="authentication_required"?null:k},...C?{settlement:C}:{}}}let l=m=>(a.has(m)||a.set(m,t?.run.identity.binding?.id??null),a.get(m));async function f(m){let h=r,d=t?.run.identity.binding?.id??null,A=g=>{if(d!==(t?.run.identity.binding?.id??null))throw g;return c(g)};if(m.operation==="page_experiments"){if(!e.adapter.pageExperiments)throw new b("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return s(()=>e.adapter.pageExperiments(m.release,m.usedReceiptIds)).catch(A)}let k;if(m.operation==="get"){let{operation:g,customerToken:y,...I}=m;k=await s(()=>e.adapter.get({...I,...I.settlementRequestId?{settlementBindingId:l(I.settlementRequestId)}:{}})).catch(A)}else if(m.operation==="review")k=await s(()=>e.adapter.review(m.receiptId)).catch(A);else{if(m.operation==="start")throw new b("INVALID_REQUEST","Use process.open for entry");{let{customerToken:g,...y}=m;k=await s(()=>e.adapter.command(y,l(y.requestId))).catch(A)}}return u(k,h)}return{get view(){return t?.run??null},get controller(){return n},async open(m){let h=r,d=await s(()=>e.adapter.open(m)).catch(c);if(u(d,h),!n){n=gr({...e,runToken:d.runToken,process:{request:f,binding:l,restore(g){for(let[y,I]of Object.entries(g))a.set(y,I)}}});let A=n,k=A.submit;A.submit=async g=>{try{return await k(g)}catch(y){if(!(y instanceof b)||y.reason!=="IDENTITY_CONTEXT_CHANGED"||g.operation!=="submit"||g.input.type!=="screen"||a.get(g.requestId)!==null)throw y;await A.settle?.(g.requestId),await A.get();let I=A.view;if(o.get(g.requestId)!==!1||!I||I.id!==t?.run.id||I.nodeId!==g.nodeId||I.visit!==g.visit||!t?.run.identity.binding)throw y;return k({...g,requestId:crypto.randomUUID(),revision:I.revision})}}}await n.get();for(let A of n.pendingCommands??[])a.has(A.requestId)&&a.get(A.requestId)!==(t?.run.identity.binding?.id??null)&&await n.settle?.(A.requestId);return{run:t.run,controller:n}},async syncIdentity(){let m=r;u(await s(()=>e.adapter.syncIdentity()).catch(c),m),await n?.get();for(let h of n?.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(t?.run.identity.binding?.id??null)&&await n?.settle?.(h.requestId);return t.run},async detach(){r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear(),await s(()=>e.adapter.detach())},forProcess(m){if(!t?.run.identity.binding)throw new b("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:t.run.id,bindingId:t.run.identity.binding.id,receiptId:m}},subscribe(m){return i.add(m),()=>{i.delete(m)}},destroy(){r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear(),i.clear()}}}