@tinkerlandai/indiana-sdk 0.7.0 → 0.8.0

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.
Files changed (52) hide show
  1. package/CHANGELOG.md +6 -1
  2. package/README.md +11 -10
  3. package/README.zh-CN.md +16 -11
  4. package/dist/{ai-usage-BsrSG955.d.ts → ai-usage-Bigjb8MS.d.ts} +468 -274
  5. package/dist/chunk-2A6UYUFA.js +1 -0
  6. package/dist/chunk-3BQFJANQ.js +1 -0
  7. package/dist/chunk-3ENVRJE6.js +350 -0
  8. package/dist/chunk-A3N4ZZTM.js +7 -0
  9. package/dist/chunk-AE4CUTUE.js +1 -0
  10. package/dist/chunk-CXYOZSOF.js +1 -0
  11. package/dist/{chunk-4AWSZWZD.js → chunk-G2R56FKU.js} +1 -1
  12. package/dist/{chunk-6MO6Y24B.js → chunk-OVMNCZYC.js} +1 -1
  13. package/dist/{configuration-sync-Bvd956GL.d.ts → configuration-sync-VFbY1pCN.d.ts} +34 -35
  14. package/dist/content-K2HCZVC2.js +1 -0
  15. package/dist/{customer-page-B4LkIr5q.d.ts → customer-page-BrCZxcaQ.d.ts} +279 -6
  16. package/dist/funnel-runtime-host-HNZ47TZW.js +1 -0
  17. package/dist/{funnel-runtime-start-ChVYbLzV.d.ts → funnel-runtime-start-DKcTCRrd.d.ts} +1646 -1913
  18. package/dist/index.d.ts +13975 -13679
  19. package/dist/index.js +1 -1
  20. package/dist/native-shell.js +1 -1
  21. package/dist/openrouter.d.ts +3 -2
  22. package/dist/openrouter.js +1 -1
  23. package/dist/page.d.ts +9 -9
  24. package/dist/paywall-PD62B2AY.js +1 -0
  25. package/dist/popup.d.ts +3 -271
  26. package/dist/popup.js +1 -350
  27. package/dist/react-native.d.ts +8 -8
  28. package/dist/react-native.js +1 -1
  29. package/dist/{screen-iFngkxaL.d.ts → screen-BazUOjwM.d.ts} +168 -165
  30. package/dist/server.d.ts +5 -5
  31. package/dist/server.js +1 -1
  32. package/dist/src-4MRSESVS.js +1 -0
  33. package/dist/visual.d.ts +5 -2
  34. package/dist/visual.js +2 -2
  35. package/package.json +1 -7
  36. package/dist/chunk-3SONNXFG.js +0 -1
  37. package/dist/chunk-467Z5ISI.js +0 -11
  38. package/dist/chunk-4K25DELJ.js +0 -1
  39. package/dist/chunk-HD74AAFS.js +0 -1
  40. package/dist/chunk-J4RHVU3W.js +0 -1
  41. package/dist/chunk-NOFNOHUI.js +0 -1
  42. package/dist/chunk-QO4YQLZ4.js +0 -1
  43. package/dist/chunk-U6S6AZM6.js +0 -1
  44. package/dist/chunk-WCFVNF5D.js +0 -1
  45. package/dist/client-F6UPJMHR.js +0 -1
  46. package/dist/controls-XG46TKUU.js +0 -2
  47. package/dist/funnel-runtime-host-26QI2W3S.js +0 -1
  48. package/dist/iam.d.ts +0 -131
  49. package/dist/iam.js +0 -1
  50. package/dist/paywall-WKOHBYW7.js +0 -1
  51. package/dist/src-UHLPVD6E.js +0 -1
  52. package/dist/{errors-DrdTlPwf.d.ts → errors-BpCmukJr.d.ts} +1 -1
@@ -1 +0,0 @@
1
- function r(o){try{let t=new URL(o);return t.origin===o&&!t.username&&!t.password&&(t.protocol==="https:"||t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname))}catch{return!1}}var n="X-Indiana-Capture-Version",s="3";export{r as a,n as b,s as c};
@@ -1 +0,0 @@
1
- import{a as ue}from"./chunk-RRII2DMC.js";import{z as ot}from"zod";var at=["USD","EUR","CNY","GBP","JPY","CAD","AUD","NZD","CHF","HKD","SGD","KRW","INR","BRL","MXN","TWD","THB","IDR","MYR","PHP","VND","ZAR","AED","SAR","SEK","NOK","DKK","PLN","CZK","HUF","ILS","TRY","RON"],O=ot.enum(at);function pe(e){let t=O.parse(e.toUpperCase());return["JPY","KRW","VND"].includes(t)?0:2}function Sr(e,t){let r=pe(t),i=e.trim().match(/^(\d+)(?:\.(\d+))?$/);if(!i?.[1]||(i[2]?.length??0)>r)throw new Error("Amount has invalid currency precision");let a=BigInt(i[1])*BigInt(10**r)+BigInt((i[2]??"").padEnd(r,"0")||"0");if(a>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("Amount exceeds the supported range");return Number(a)}function xr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error("Expected a nonnegative integer amount");let r=pe(t),i=String(e).padStart(r+1,"0");return r?`${i.slice(0,-r)}.${i.slice(-r)}`:i}function _r(e,t,r="en",i={}){let a=O.parse(t.toUpperCase());return new Intl.NumberFormat(r,{style:"currency",currency:a,...i}).format(e/10**pe(a))}import{z as _}from"zod";var te=_.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),E=_.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),st=_.string().regex(/^-?(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>{let t=e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e;return t==="-0"?"0":t}),me=E.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),Ie=_.string().min(1).max(64),V=_.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Ee=_.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),L=_.record(Ie,_.union([_.string().max(120),_.number().finite(),_.boolean()])).refine(e=>Object.keys(e).length<=16,"\u6700\u591A 16 \u4E2A\u8BA1\u4EF7\u5C5E\u6027").transform(e=>Object.fromEntries(Object.entries(e).map(([t,r])=>[t,String(r)]))),Ae=_.record(Ie,_.union([_.string().max(120),_.number().finite(),_.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),q=e=>{let t=e.startsWith("-");t&&(e=e.slice(1));let[r,i=""]=e.split(".");if(r===void 0||r==="")throw new Error("Invalid decimal value");let a=BigInt(r)*BigInt("1000000")+BigInt(i.padEnd(6,"0"));return t?-a:a},Ne=_.array(_.object({upTo:me.nullable(),cost:E}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,r)=>{let i=e[r-1]?.upTo;return t.upTo!==null&&(r===0||i!=null&&q(t.upTo)>q(i))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),ct=_.object({key:Ee,match:Ae,priority:_.number().int().default(0),cost:E.optional(),tiers:Ne.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),lt=_.object({key:Ee,match:Ae,factor:me.optional(),add:st.optional()}).strict().refine(e=>e.factor!==void 0||e.add!==void 0,"A multiplier needs a factor or an add").transform(e=>({...e,factor:e.factor??"1",add:e.add??"0"})),ut=_.object({units:me.default("1"),cost:E,tiers:Ne.optional(),dimensions:_.array(ct).max(12).optional(),multipliers:_.array(lt).max(4).optional()}).strict().superRefine((e,t)=>{let r=e.dimensions??[],i=e.multipliers??[];(new Set(r.map(l=>l.key)).size!==r.length||new Set(i.map(l=>l.key)).size!==i.length)&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u548C\u500D\u7387\u7684 ID \u4E0D\u80FD\u91CD\u590D"});for(let[l,d]of r.entries())for(let g of r.slice(l+1))Object.keys(d.match).length===Object.keys(g.match).length&&d.priority===g.priority&&!Object.keys(d.match).some(s=>g.match[s]!==void 0&&g.match[s]!==d.match[s])&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u53EF\u80FD\u540C\u65F6\u5339\u914D\uFF0C\u8BF7\u8C03\u6574\u4F18\u5148\u7EA7"});let a=[e.cost,...(e.tiers??[]).map(l=>l.cost),...r.flatMap(l=>[...l.cost===void 0?[]:[l.cost],...(l.tiers??[]).map(d=>d.cost)])],c=q(e.units);for(let l of a)for(let d=0;d<1<<i.length;d++){let g=i.filter((v,R)=>d&1<<R);if(g.some((v,R)=>g.slice(R+1).some(_e=>Object.keys(v.match).some(le=>_e.match[le]!==void 0&&_e.match[le]!==v.match[le]))))continue;let s=q(l),p=BigInt("1"),y=BigInt("0");for(let[v,R]of i.entries())d&1<<v&&(s*=q(R.factor??"1"),p*=BigInt("1000000"),y+=q(R.add??"0"));let h=(s+y*p)*BigInt("1000000"),w=p*c;(h<BigInt("0")||h%w!==BigInt("0")||h/w>BigInt("999999999999999999"))&&t.addIssue({code:"custom",message:"\u6BCF\u4E2A\u4E1A\u52A1\u5355\u4F4D\u7684\u6700\u7EC8\u5355\u4EF7\u5FC5\u987B\u975E\u8D1F\u3001\u5728\u8303\u56F4\u5185\u4E14\u80FD\u7CBE\u786E\u8868\u793A\u4E3A\u6700\u591A 6 \u4F4D\u5C0F\u6570"})}}),Ar=ut.safeExtend({featureKey:V});import{z as pt}from"zod";var Oe=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,M=pt.string().max(16).regex(Oe,"\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");function de(e){if(typeof e!="string")return null;try{let t=Intl.getCanonicalLocales(e.trim().replaceAll("_","-"))[0];if(!t)return null;let{language:r,script:i,region:a}=new Intl.Locale(t),c=[r,i,a].filter(Boolean).join("-");return Oe.test(c)?c:null}catch{return null}}var mt=new Set(["TW","HK","MO"]);function Re(e){let[t,r,i]=e.split("-");if(t!=="zh")return`${t}-${new Intl.Locale(e).maximize().script??""}`;let a=r?.length===4?r:void 0,c=r?.length===4?i:r;return a?`zh-${a}`:c&&mt.has(c)?"zh-Hant":"zh-Hans"}function ke(e,t,r){let i=t.map(a=>({code:M.parse(a),normalized:a}));for(let a of e){let c=de(a);if(!c)continue;let l=i.find(p=>p.normalized===c);if(l)return l.code;let d=Re(c),g=i.filter(p=>Re(p.normalized)===d),s=g.find(p=>!p.normalized.includes("-")||p.normalized===d)??g[0];if(s)return s.code}return r}var dt=[{code:"zh-CN",label:"\u7B80\u4F53\u4E2D\u6587"},{code:"zh-TW",label:"\u7E41\u9AD4\u4E2D\u6587\uFF08\u53F0\u7063\uFF09"},{code:"zh-HK",label:"\u7E41\u9AD4\u4E2D\u6587\uFF08\u9999\u6E2F\uFF09"},{code:"en",label:"English"},{code:"ja",label:"\u65E5\u672C\u8A9E"},{code:"ko",label:"\uD55C\uAD6D\uC5B4"},{code:"es",label:"Espa\xF1ol"},{code:"fr",label:"Fran\xE7ais"},{code:"de",label:"Deutsch"},{code:"pt-BR",label:"Portugu\xEAs (Brasil)"},{code:"it",label:"Italiano"},{code:"ru",label:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439"},{code:"vi",label:"Ti\u1EBFng Vi\u1EC7t"},{code:"th",label:"\u0E44\u0E17\u0E22"},{code:"id",label:"Bahasa Indonesia"},{code:"ar",label:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629"}];function Or(e){return dt.find(t=>t.code===e)?.label??e}import{z as A}from"zod";var re=A.enum(["INVALID_PROTOCOL_VERSION","UNSUPPORTED_PROTOCOL_VERSION","PROTOCOL_RETIRED","UNAUTHENTICATED","FORBIDDEN","SCOPE_MISMATCH","INVALID_REQUEST","NOT_FOUND","CONFLICT","PAYLOAD_TOO_LARGE","RATE_LIMITED","SERVICE_UNAVAILABLE","NOT_CONFIGURED","CAPABILITY_UNAVAILABLE","INTERNAL_ERROR"]),Lr=A.enum([...re.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),Tr=A.enum([...re.options,"stale_revision"]),ft=A.enum(["fix_request","authenticate","check_permissions","check_scope","resolve_conflict","reload_state","retry_same_request","configure_integration","check_availability","upgrade_sdk","recover_operation","contact_support"]),gt=A.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),Le={INVALID_PROTOCOL_VERSION:{status:400,recovery:"fix_request"},UNSUPPORTED_PROTOCOL_VERSION:{status:400,recovery:"upgrade_sdk"},PROTOCOL_RETIRED:{status:410,recovery:"upgrade_sdk"},UNAUTHENTICATED:{status:401,recovery:"authenticate"},FORBIDDEN:{status:403,recovery:"check_permissions"},SCOPE_MISMATCH:{status:403,recovery:"check_scope"},INVALID_REQUEST:{status:400,recovery:"fix_request"},NOT_FOUND:{status:404,recovery:"fix_request"},CONFLICT:{status:409,recovery:"resolve_conflict"},PAYLOAD_TOO_LARGE:{status:413,recovery:"fix_request"},RATE_LIMITED:{status:429,recovery:"retry_same_request"},SERVICE_UNAVAILABLE:{status:503,recovery:"retry_same_request"},NOT_CONFIGURED:{status:501,recovery:"configure_integration"},CAPABILITY_UNAVAILABLE:{status:501,recovery:"check_availability"},INTERNAL_ERROR:{status:500,recovery:"recover_operation"}};function jr(e){return[400,405,415,422].includes(e)?"INVALID_REQUEST":e===401?"UNAUTHENTICATED":e===403?"FORBIDDEN":e===404?"NOT_FOUND":[409,412,425].includes(e)?"CONFLICT":e===413?"PAYLOAD_TOO_LARGE":e===429?"RATE_LIMITED":e===501?"NOT_CONFIGURED":[408,502,503,504].includes(e)?"SERVICE_UNAVAILABLE":"INTERNAL_ERROR"}var Ce={TIMEOUT:"recover_operation",NETWORK_ERROR:"recover_operation",HTTP_ERROR:"recover_operation",INVALID_RESPONSE:"recover_operation",NOT_IDENTIFIED:"authenticate",INVALID_TOKEN:"authenticate",INVALID_URL:"fix_request",INVALID_TIMEOUT:"fix_request",SERVER_ONLY:"fix_request",PROTOCOL_MISMATCH:"upgrade_sdk",IDENTITY_CHANGED:"reload_state",EVENT_QUEUE_FULL:"retry_same_request",COMMAND_PENDING:"recover_operation",DECISION_PENDING:"recover_operation",DECISION_ACCEPTANCE_UNKNOWN:"recover_operation",RUN_RECONCILIATION_REQUIRED:"recover_operation",DECISION_FAILED:"contact_support",COMMAND_STORAGE_CONFLICT:"resolve_conflict",COMMAND_STORAGE_INVALID:"fix_request",CONFIGURATION_UNAVAILABLE:"check_availability",CONFIGURATION_EXPIRED:"reload_state",CONFIGURATION_CHANGED:"reload_state",CONFIGURATION_DISPOSED:"reload_state",UNSUPPORTED_SCHEMA:"upgrade_sdk",FUNNEL_STOPPED:"check_availability",PAYWALL_UNAVAILABLE:"check_availability",EVALUATION_MODE:"reload_state",SERVER_REQUIRED:"fix_request",STICKY_SAVE_FAILED:"retry_same_request",TRANSITION_LIMIT:"resolve_conflict",PRECONDITION_FAILED:"reload_state",PRODUCT_UNAVAILABLE:"fix_request",PURCHASE_HANDLER_REQUIRED:"fix_request",EVENT_HANDLER_REQUIRED:"fix_request",CLOSED:"fix_request",BRIDGE_UNAVAILABLE:"check_availability",INVALID_CONFIGURATION:"fix_request",NATIVE_OPERATION_FAILED:"contact_support",AI_PRICE_UNAVAILABLE:"fix_request",AI_USAGE_UNAVAILABLE:"recover_operation",AI_PROVIDER_ERROR:"check_availability",AI_BALANCE_REJECTED:"resolve_conflict"};function yt(e,t){if(e==="CONFLICT"&&t===425)return{retryable:!0,recovery:"retry_same_request"};if(e==="CONFLICT"&&t===412)return{retryable:!1,recovery:"reload_state"};if(e==="INVALID_SERVER_RESPONSE")return{retryable:!1,recovery:"recover_operation"};if(e==="AMBIGUOUS_AUTHENTICATION")return{retryable:!1,recovery:"fix_request"};if(Object.hasOwn(Ce,e)){let i=Ce[e];return{retryable:i==="retry_same_request",recovery:i}}let r=re.safeParse(e);return r.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:Le[r.data].recovery}:{retryable:!1,recovery:"contact_support"}}function Dr(e,t){let r=re.safeParse(e);if(r.success)return e==="CONFLICT"?[409,412,425].includes(t):e==="SERVICE_UNAVAILABLE"?[408,502,503,504].includes(t):e==="INVALID_REQUEST"?[400,405,415,422].includes(t):e==="NOT_CONFIGURED"?[501,503].includes(t):Le[r.data].status===t;let i={INVALID_SERVER_RESPONSE:[502],RESPONSE_TOO_LARGE:[502],AMBIGUOUS_AUTHENTICATION:[400],BROWSER_REQUIRED:[403],INVALID_REDIRECT_URI:[403],AUTHORIZATION_UNAVAILABLE:[400],UNREGISTERED_CLIENT:[403],MANAGEMENT_OPERATION_FAILED:[400,422,500]};return Object.hasOwn(i,e)&&(i[e]?.includes(t)??!1)}function bt(e,t=Date.now()){if(e===null)return;let r=e.trim();if(/^\d+$/.test(r)){let a=Number(r);return Number.isSafeInteger(a)?a:void 0}if(!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(r))return;let i=Date.parse(r);return Number.isFinite(i)?Math.max(0,Math.ceil((i-t)/1e3)):void 0}var Te=A.object({retryable:A.boolean(),recovery:ft,reason:gt.optional(),retryAfterSeconds:A.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),ht=A.object({requestId:A.uuid().optional(),error:A.object({code:A.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:A.string(),...Te.partial().shape})}),zr=A.object({error:ht.shape.error.extend({requestId:A.uuid().optional()})}),Pr=A.object({error:A.string(),code:A.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:A.uuid(),...Te.shape});function wr(e,t,r={}){let i=yt(e,t),a=r.reason==="RESULT_UNKNOWN"?"recover_operation":r.recovery??i.recovery,c=i.retryable&&r.retryable!==!1&&a!=="recover_operation",l=c?bt(r.retryAfter??null):void 0;return{...i,retryable:c,recovery:a,...l===void 0?{}:{retryAfterSeconds:l},...r.reason?{reason:r.reason}:{}}}import{z as u}from"zod";var $=E.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),H=u.string().min(1).max(120),ne=u.enum(["cap","overflow"]),k=(e,t)=>{let[r,i=""]=e.split(".");if(r===void 0||r==="")throw new Error("Invalid decimal value");return BigInt(r)*10n**BigInt(t)+BigInt(i.padEnd(t,"0"))},K=e=>{try{return e()}catch{return!1}},$r=u.discriminatedUnion("operation",[u.object({operation:u.literal("quote"),overageBehavior:ne.optional(),internal_feature_id:u.uuid(),entityId:u.uuid().optional(),quantity:$,properties:L}).strict(),u.object({operation:u.literal("consume"),overageBehavior:ne.optional(),occurredAt:u.iso.datetime({offset:!0}).optional(),internal_feature_id:u.uuid(),entityId:u.uuid().optional(),quantity:E,properties:L,idempotencyKey:H}).strict(),u.object({operation:u.literal("reserve"),occurredAt:u.iso.datetime({offset:!0}).optional(),internal_feature_id:u.uuid(),entityId:u.uuid().optional(),quantity:$,properties:L,idempotencyKey:H,expiresInSeconds:u.number().int().min(1).max(86400)}).strict(),u.object({operation:u.literal("confirm"),operationId:u.uuid(),quantity:$,properties:L.optional(),idempotencyKey:H}).strict(),u.object({operation:u.literal("refund"),operationId:u.uuid(),quantity:$,idempotencyKey:H}).strict(),u.object({operation:u.literal("release"),operationId:u.uuid(),idempotencyKey:H}).strict()]),St=u.object({internal_credit_feature_id:u.uuid().nullable(),internal_metered_feature_id:u.uuid(),dimension:u.string().min(1).max(64),counterKey:u.string().min(1).max(240),cycleStart:u.iso.datetime({offset:!0}),unitCost:E,units:$,amount:te,tier:u.number().int().min(1).max(12).nullable()}).strict(),Q=u.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function je(e,t){let r=e.reduce((i,a)=>i+k(a.units,12),0n)-k(t,12);return e.some(i=>i.funding==="balance")?r>=-100n&&r<=100n:r===0n}var De=u.discriminatedUnion("funding",[u.strictObject({funding:u.literal("balance"),sourceId:u.uuid(),rolloverId:u.uuid().nullable(),units:Q.refine(e=>/[1-9]/.test(e)),amount:te}),u.strictObject({funding:u.literal("unbilled"),units:Q.refine(e=>/[1-9]/.test(e))}),u.object({funding:u.literal("prepaid"),sourceId:u.uuid(),units:$,amount:te,pricing:u.array(St).min(1).max(12)}).strict().refine(e=>K(()=>e.pricing.reduce((t,r)=>t+k(r.units,6),0n)===k(e.units,6)&&e.pricing.reduce((t,r)=>t+k(r.amount,12),0n)===k(e.amount,12)&&e.pricing.every(t=>k(t.unitCost,6)*k(t.units,6)===k(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),u.object({funding:u.literal("postpaid"),invoiceLineId:u.uuid().nullable(),units:$,authorizationId:u.uuid()}).strict()]),ie=u.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),Br=u.object({allowed:u.boolean(),internal_feature_id:u.uuid(),quantity:E,requestedQuantity:E.optional(),overageBehavior:ne.optional(),reason:ie.nullable(),allocations:u.array(De).max(500)}).strict().refine(e=>K(()=>e.allowed?e.reason===null&&je(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>K(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&k(e.requestedQuantity,6)>=k(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),qr=u.object({id:u.uuid(),internal_feature_id:u.uuid(),kind:u.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:u.uuid().nullable(),quantity:E,requestedQuantity:E.optional(),overageBehavior:ne.optional(),accepted:u.boolean(),reason:u.enum([...ie.options,"expired"]).nullable(),createdAt:u.iso.datetime({offset:!0}),reservationStatus:u.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:u.iso.datetime({offset:!0}).nullable(),allocations:u.array(De).max(500)}).strict().refine(e=>K(()=>e.accepted?e.reason===null&&je(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>K(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&k(e.requestedQuantity,6)>=k(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");import{z as T}from"zod";var xt=T.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),_t=T.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),ze=T.strictObject({internal_feature_id:T.uuid(),entityId:T.uuid().nullable()}),Gr=ze.extend({quantity:E,expectedRevision:T.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:T.string().min(1).max(120),properties:L.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),Pe=ze.extend({operationId:T.uuid().nullable(),usage:E,capacity:xt.nullable(),remaining:_t.nullable(),withinLimit:T.boolean(),revision:T.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:T.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let r=i=>{let a=i.startsWith("-"),[c,l=""]=(a?i.slice(1):i).split(".");if(c===void 0||c==="")throw new Error("Invalid decimal value");return(a?-1n:1n)*(BigInt(c)*10n**12n+BigInt(l.padEnd(12,"0")))};(e.capacity===null!=(e.remaining===null)||(e.capacity===null?!e.withinLimit:e.remaining===null||r(e.remaining)!==r(e.capacity)-r(e.usage)||e.withinLimit!==r(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"})});import{z as o}from"zod";var P=o.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),j=o.iso.datetime({offset:!0}),It=o.enum(["access","metered","credit"]),W={internal_feature_id:o.uuid(),key:V,name:o.string().min(1).max(120),kind:It},Jr=o.object({customerId:o.uuid(),snapshotAt:j,memberships:o.array(o.object({id:o.uuid(),productId:o.string().min(1).max(255),productVersionId:o.uuid(),billingProductVersionId:o.uuid(),version:o.number().int().positive(),key:o.string().min(1).max(64),name:o.string().min(1).max(120),groupId:o.string().max(255).nullable(),membershipType:o.enum(["main","addon"]),status:o.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:o.boolean(),accessEnabled:o.boolean(),renewalChange:o.object({productVersionId:o.uuid(),name:o.string().min(1).max(120),version:o.number().int().positive(),effectiveAt:j,benefitsAppliedAt:j.nullable(),timing:o.enum(["immediate","renewal"]),changeKind:o.enum(["plan","seats","quantity"]),feature:o.strictObject({internal_feature_id:o.uuid(),name:o.string().min(1).max(80),fromQuantity:o.number().int().min(0).max(1e4),toQuantity:o.number().int().min(0).max(1e4)}).optional(),seat:o.object({key:o.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:o.number().int().min(0).max(1e4),toQuantity:o.number().int().min(0).max(1e4)}).strict().nullable(),status:o.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:o.object({phase:o.enum(["paid","trial"]),startsAt:j,endsAt:j.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:o.boolean(),balances:o.array(o.object({...W,usageType:o.enum(["consumable","non_consumable"]).nullable(),accessible:o.boolean(),unlimited:o.boolean(),available:P,held:P,debt:P,nextExpiresAt:j.nullable(),usage:Pe.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:o.boolean()}).strict(),we=o.enum(["source","usage","transaction","invoice","debt","settlement"]),oe=o.object({at:j,id:o.uuid(),type:we}).strict(),en=o.object({type:we.nullable(),resourceKey:V.optional(),kind:o.enum(["purchase","refund"]).optional(),topup:o.boolean().optional(),from:o.iso.date().nullable(),to:o.iso.date().nullable(),after:oe.nullable(),limit:o.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),F={id:o.uuid(),occurredAt:j},Et=o.discriminatedUnion("type",[o.strictObject({...F,type:o.literal("invoice"),status:o.string().min(1).max(80),paid:P,refunded:P,currency:O,externalId:o.string().nullable()}),o.object({...F,...W,type:o.literal("source"),reason:o.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:P,unlimited:o.boolean(),status:o.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:j,expiresAt:j.nullable(),orderId:o.uuid().nullable(),parentSourceId:o.uuid().nullable()}).strict(),o.object({...F,type:o.literal("usage"),internal_feature_id:o.uuid(),name:o.string().min(1).max(120),kind:o.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:o.uuid().nullable(),quantity:E,accepted:o.boolean(),reason:o.enum([...ie.options,"expired"]).nullable(),properties:L,reservationStatus:o.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:j.nullable(),charges:o.array(o.discriminatedUnion("funding",[o.strictObject({funding:o.literal("balance"),sourceId:o.uuid(),rolloverId:o.uuid().nullable(),units:Q,amount:P}),o.strictObject({funding:o.literal("unbilled"),units:Q}),o.object({...W,funding:o.literal("prepaid"),amount:P}).strict(),o.object({funding:o.literal("postpaid"),invoiceId:o.uuid(),invoiceLineId:o.uuid(),authorizationId:o.uuid(),units:E,currency:O}).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"),o.object({...F,type:o.literal("transaction"),purpose:o.enum(["product","invoice"]),productVersionId:o.uuid().nullable(),productName:o.string().min(1).max(120).nullable(),productVersion:o.number().int().positive().nullable(),invoiceId:o.uuid().nullable(),orderId:o.uuid(),originalId:o.uuid().nullable(),kind:o.enum(["purchase","refund"]),amountMinor:o.number().int().nonnegative().max(2e8).nullable(),currency:O.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"),o.object({...F,...W,type:o.literal("debt"),sourceId:o.uuid(),transactionId:o.uuid(),amount:P}).strict(),o.object({...F,...W,type:o.literal("settlement"),sourceId:o.uuid(),debtId:o.uuid(),kind:o.enum(["payment","usage_refund","payment_return"]),amount:P}).strict()]),tn=o.object({customerId:o.uuid(),rows:o.array(Et).max(50),nextCursor:oe.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");import{z as Z}from"zod";var ve=Z.enum(["stripe","apple","google"]),on=Z.enum(["membership","credit_pack","lifetime"]),an=Z.enum(["active","grace","suspended","inactive","revoked"]),sn=Z.strictObject({currency:Z.string().regex(/^[A-Z]{3}$/),micros:Z.string().regex(/^(0|[1-9][0-9]{0,29})$/)});import{z as At}from"zod";var Ue=At.object({provider:ve,currency:O}).strict();import{z as x}from"zod";var Ve=x.strictObject({internal_feature_id:x.uuid(),quantity:E.refine(e=>/[1-9]/.test(e)),properties:L,entityId:x.uuid().optional()}),bn=x.strictObject({requirement:Ve,commerce:Ue.optional(),paywallId:x.uuid().optional()}),Nt=x.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),Rt=x.strictObject({productId:x.string().min(1),productVersionId:x.string().min(1),name:x.string().min(1).max(120),action:x.enum(["purchase","upgrade","addon","topup"]),membershipId:x.string().min(1).nullable(),currency:O,amountMinor:x.string().regex(/^(0|[1-9]\d{0,8})$/),interval:x.enum(["free","week","month","year","one_time"]),intervalCount:x.number().int().min(1).max(156)}),$e=x.strictObject({internal_feature_id:x.string().min(1),name:x.string().min(1).max(120),kind:x.enum(["access","metered","credit"]),quantity:E,allowed:x.boolean(),reason:Nt.nullable(),preview:x.strictObject({scenario:x.enum(["feature_flag","usage_limit"]),candidates:x.array(Rt).max(20)}).nullable()}).superRefine((e,t)=>{(e.allowed!==(e.reason===null)||e.allowed&&e.preview!==null||new Set(e.preview?.candidates.map(r=>r.productVersionId)).size!==(e.preview?.candidates.length??0)||e.preview?.candidates.some(r=>r.action==="upgrade"!=(r.membershipId!==null)))&&t.addIssue({code:"custom",message:"Invalid access recommendation"})}),hn=x.strictObject({paywallId:x.uuid(),requirement:Ve});import{z as U}from"zod";var Be=U.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),qe=U.strictObject({tiers:U.array(U.strictObject({id:Be,name:U.string().trim().min(1).max(80)})).min(1).max(8),assignments:U.array(U.strictObject({productVersionId:U.string().min(1).max(200),tierId:Be,period:U.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let r=e.tiers.map(i=>i.id);(new Set(r).size!==r.length||new Set(e.assignments.map(i=>i.productVersionId)).size!==e.assignments.length||new Set(e.assignments.map(i=>`${i.tierId}:${i.period}`)).size!==e.assignments.length||e.assignments.some(i=>!r.includes(i.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function Me(e,t){return e.assignments.length===t.length&&e.assignments.every(r=>t.includes(r.productVersionId))}function Fe(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function ae(e){let t={};function r(i){if(Fe(i)){let a=t[i.interaction.pickerId]??={ids:[],defaultId:null};for(let l of i.children){let d=l.type==="stack"?l.bind?.plan:void 0;d&&!a.ids.includes(d)&&a.ids.push(d)}let c=i.children[i.interaction.defaultIndex];!a.defaultId&&c?.type==="stack"&&(a.defaultId=c.bind?.plan??null)}i.type==="stack"&&i.children.forEach(r)}return e.pages.forEach(i=>r(i.root)),t}function Ze(e,t,r){let i={};function a(g){if(g.hidden)return;if(g.type==="plan_picker"){let y=r.pickers[g.id];i[g.id]={ids:y?.options??[],defaults:y?.selected?[y.selected]:[],remembered:[]};return}if(g.type!=="stack")return;let s=g.children.filter(y=>!y.hidden),p=g.interaction;if(Fe(g)){let y=i[g.interaction.pickerId]??={ids:[],defaults:[],remembered:[]},h=r.pickers[g.interaction.pickerId]?.options??[];for(let v of s){let R=v.type==="stack"?v.bind?.plan:void 0;R&&h.includes(R)&&!y.ids.includes(R)&&y.ids.push(R),R&&v.id===t[g.id]&&y.remembered.push(R)}let w=g.children[g.interaction.defaultIndex];w?.type==="stack"&&!w.hidden&&w.bind?.plan&&y.defaults.push(w.bind.plan)}if(p?.type==="tabs"){let y=s.find(h=>h.id===t[g.id])??g.children[p.defaultIndex];y&&a(y)}else if(p?.type==="toggle"){let y=typeof t[g.id]=="boolean"?t[g.id]:p.defaultEnabled,h=g.children[y?0:1];h&&a(h)}else s.forEach(a)}let c=typeof t.__page=="string"?t.__page:e.initialPageId??e.pages[0]?.id,l=e.pages.find(g=>g.id===c);l&&a(l.root);let d={};for(let[g,s]of Object.entries(i)){let p=t[g],y=s.remembered[0]??(s.ids.includes(r.pickers[g]?.selected??"")?r.pickers[g]?.selected:s.defaults[0]);d[g]=typeof p=="string"?s.ids.includes(p)?p:"":y&&s.ids.includes(y)?y:""}for(let g of Object.keys(ae(e)))d[g]??="";return d}import{z as f}from"zod";var Ot=["plan.name","plan.price","plan.period","plan.price_per_month","trial.headline","trial.terms","offer.headline","offer.name","offer.description","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.price","offer.original_price","offer.months","offer.code","offer.ends_at","offer.expires_at","paywall.feature","paywall.message","paywall.action"],fe=f.object({plan:f.string().min(1).max(200).optional(),coupon:f.uuid().optional(),promotionCode:f.uuid().optional(),picker:f.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),Ge=f.object({text:f.string().optional(),label:f.string().optional(),alt:f.string().optional(),html:f.string().max(32768).optional(),price:f.object({current:f.string(),original:f.string().nullable(),period:f.string()}).optional(),code:f.string().optional(),countdownAt:f.iso.datetime().optional(),planId:f.string().min(1).max(200).optional(),planVersionId:f.string().min(1).max(200).optional(),currency:O.optional(),couponId:f.uuid().optional(),offerId:f.uuid().optional(),unavailable:f.boolean().optional(),unavailableReason:f.string().optional(),missing:f.array(f.string()).optional()}).strict(),Rn=f.object({paywall:$e.optional(),nodes:f.record(f.string(),f.object({base:Ge,picker:f.string().optional(),byPlan:f.record(f.string(),Ge).optional()}).strict()),plans:f.record(f.string(),f.object({id:f.string().min(1).max(200),versionId:f.string().min(1).max(200),available:f.boolean(),name:f.string(),price:f.string(),period:f.string(),currency:O.optional()}).strict()),pickers:f.record(f.string(),f.object({options:f.array(f.string().min(1).max(200)).max(20),selected:f.string().min(1).max(200).nullable()}).strict()),diagnostics:f.array(f.object({nodeId:f.string(),message:f.string()}).strict())}).strict();function se(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}function ce(e){let t=se(e).filter(i=>!Ot.includes(i)&&!/^variables\.[A-Za-z0-9_][A-Za-z0-9_.:-]*$/.test(i)),r=e.replace(/\{\{\s*[^{}]+?\s*\}\}/g,"");return(r.includes("{{")||r.includes("}}"))&&t.push("\u65E0\u6548\u53D8\u91CF\u8BED\u6CD5"),[...new Set(t)]}function On(e,t,r,i=!1){let a=se(e).filter(c=>!/^variables\.[A-Za-z0-9_][A-Za-z0-9_.:-]*$/.test(c)&&t[c]===void 0);return a.length&&!i?{value:r,missing:a}:{value:e.replace(/\{\{\s*([^{}]+?)\s*\}\}/g,(c,l)=>t[l.trim()]??c),missing:a}}function kn(e,t,r={}){let i=e?.nodes[t];if(!i)return;let a=i.picker?r[i.picker]??e?.pickers[i.picker]?.selected:void 0;return typeof a=="string"?i.byPlan?.[a]??i.base:i.base}import{z as m}from"zod";var kt=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],He=m.enum(kt),Ke=m.object({source:He,layout:m.enum(["full","compact"]),resourceKey:V.optional(),pageSize:m.number().int().min(1).max(50),showSources:m.boolean(),allowPurchase:m.boolean(),outputs:m.object({billing_adjustment:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:m.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"})}),N=m.string().max(2e3),Qe=m.object({id:m.string().max(100),label:N,detail:m.array(N).max(12),value:N.optional(),status:N.optional(),facts:m.array(m.object({label:N,value:N}).strict()).max(1e3),purchaseId:m.uuid().optional(),invoiceUrl:m.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:m.array(m.strictObject({action:m.literal("invoice_open"),label:N})).max(1).optional(),membershipActions:m.array(m.object({value:m.string().max(100),label:N}).strict()).max(3).optional()}).strict(),Ct=m.object({key:V,name:N,spendable:N,reserved:N,available:N,expiry:N.nullable(),sources:m.array(Qe).max(50),sourceCount:m.number().int().nonnegative(),sourcePage:m.number().int().positive(),hasNextSources:m.boolean(),hasPreviousSources:m.boolean()}).strict(),Lt=m.object({source:He,status:m.enum(["idle","loading","ready","error"]),stale:m.boolean(),preview:m.boolean(),errorCode:m.string().max(80).optional(),errorMessage:N.optional(),resources:m.array(Ct).max(500),rows:m.array(Qe).max(50),hasNext:m.boolean(),hasPrevious:m.boolean(),page:m.number().int().positive(),filter:m.string().max(40),updatedAt:m.iso.datetime().optional(),buyingId:m.uuid().optional(),membershipBusy:m.boolean().optional(),billingBusy:m.boolean().optional(),membershipReview:m.object({title:N,note:N,facts:m.array(m.object({label:N,value:N}).strict()).max(100)}).strict().optional(),membershipResult:N.optional()}).strict(),jn=m.object({nodes:m.record(m.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Lt)}).strict(),Dn=m.object({nodeId:m.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:m.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:m.string().max(100).optional()}).strict();function zn(e){return{source:e,status:"idle",stale:!0,preview:!1,resources:[],rows:[],hasNext:!1,hasPrevious:!1,page:1,filter:"all"}}function ge(e){let t=ce(e).map(r=>`\u672A\u77E5\u53D8\u91CF\uFF1A${r}`);for(let r=0;r<e.length;r++){if(e[r]!=="<"||!/[A-Za-z!/?{]/.test(e[r+1]??""))continue;let i=r;if(e.startsWith("<!--",r)){let a=e.indexOf("-->",r+4);r=a<0?e.length:a+2}else{let a="";for(r++;r<e.length;r++){let c=e[r];if(a)c===a&&(a="");else if(c==='"'||c==="'")a=c;else if(c===">")break}}/\{\{|\}\}/.test(e.slice(i,r+1))&&t.push("\u53D8\u91CF\u53EA\u80FD\u653E\u5728 HTML \u6587\u5B57\u4E2D\uFF0C\u4E0D\u80FD\u653E\u5165\u6807\u7B7E\u3001\u5C5E\u6027\u6216\u6CE8\u91CA")}return[...new Set(t)]}function We(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function vn(e,t,r,i=!1){let a=ge(e);if(a.length)throw new Error(a[0]);let c=[...new Set(se(e).filter(l=>!l.startsWith("variables.")&&t[l]===void 0))];return c.length&&!i?{value:We(r),missing:c}:{value:e.replace(/\{\{\s*([^{}]+?)\s*\}\}/g,(l,d)=>t[d.trim()]===void 0?l:We(t[d.trim()])),missing:c}}import{z as n}from"zod";var Tt=4,z={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},X=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),S=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),jt=n.enum(["none","xs","sm","md","lg","xl"]),Dt=n.enum(["none","sm","md","lg","full"]),ye=n.string().regex(/^#[0-9a-fA-F]{6}$/),Je=n.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"),be=n.union([Je,n.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),n.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),n.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Ye=n.object({primary:ye,background:ye,text:ye,radius:Dt,font:n.enum(["system","serif","rounded","mono"])}).strict(),J=n.union([n.enum(["primary","text","muted","background","surface"]),n.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),b=(e,t)=>n.number().int().min(e).max(t),Xe=n.union([n.enum(["fit","fill"]),b(1,1200)]),zt=n.object({top:b(0,200),right:b(0,200),bottom:b(0,200),left:b(0,200)}).strict(),Pt=n.object({top:b(-100,200),right:b(-100,200),bottom:b(-100,200),left:b(-100,200)}).strict(),et=n.object({x:b(0,100),y:b(0,100)}).strict(),wt=n.discriminatedUnion("type",[n.object({type:n.literal("color"),color:J}).strict(),n.object({type:n.literal("linear"),angle:b(0,360),stops:n.array(n.object({color:J,at:b(0,100)}).strict()).min(2).max(4)}).strict(),n.object({type:n.literal("image"),src:be,fit:n.enum(["cover","contain"]),position:et.optional()}).strict()]),vt=n.discriminatedUnion("type",[n.object({type:n.literal("rect"),radius:n.union([b(0,200),n.object({topLeft:b(0,200),topRight:b(0,200),bottomRight:b(0,200),bottomLeft:b(0,200)}).strict()])}).strict(),n.object({type:n.literal("pill")}).strict()]),Ut=n.object({width:b(0,12),color:J,style:n.enum(["solid","dashed"])}).strict(),Vt=n.object({x:b(-40,40),y:b(-40,40),blur:b(0,80),spread:b(-20,40),color:J}).strict(),$t=n.object({font:n.enum(["system","serif","rounded","mono"]),size:b(8,96),weight:n.number().int().min(100).max(900).multipleOf(100),lineHeight:n.number().min(.8).max(3),letterSpacing:n.number().min(-5).max(20),color:J,align:n.enum(["start","center","end"]),italic:n.boolean(),decoration:n.enum(["none","underline","line-through"]),transform:n.enum(["none","uppercase"])}).strict().partial(),B=n.object({width:Xe,height:Xe,padding:zt,margin:Pt,gap:b(0,120),grow:n.union([n.boolean(),n.number().min(0).max(12)]),background:wt,opacity:n.number().min(0).max(1),clipContent:n.boolean(),shape:vt,border:Ut,shadow:Vt,text:$t}).strict().partial(),C={id:X,name:n.string().trim().min(1).max(60).optional(),hidden:n.boolean().optional(),style:B.optional(),fallback:S.optional()},Bt=n.object({...C,type:n.literal("text"),productField:n.enum(["name","price","trial","period"]).optional(),feature:n.object({id:n.uuid(),field:n.enum(["name","allowance"])}).strict().optional(),text:S,variant:n.enum(["title","heading","body","caption"])}).strict(),qt=n.object({...C,type:n.literal("image"),src:be,localizedSrc:n.record(M,be).optional(),alt:S,aspect:n.enum(["auto","1:1","4:3","16:9","3:1"]),fit:n.enum(["cover","contain"]),position:et.optional()}).strict(),Mt=n.object({...C,type:n.literal("button"),label:S,variant:n.enum(["primary","secondary","link"]),action:S,purpose:n.enum(["purchase","navigation","close"]).optional(),bind:fe.optional()}).strict(),Ft=n.object({...C,type:n.literal("divider")}).strict(),Zt=n.object({...C,type:n.literal("customer_data"),title:S,data:Ke}).strict(),Gt=n.object({...C,type:n.literal("spacer"),size:jt}).strict(),Ht=n.object({...C,type:n.literal("custom_html"),html:n.record(M,n.string().max(z.customHtml)),css:n.string().max(z.customCss)}).strict(),Kt=n.object({...C,type:n.literal("price"),fallback:S,parts:n.object({current:B.optional(),original:B.optional(),period:B.optional()}).strict().optional()}).strict(),Qt=n.object({...C,type:n.literal("coupon_code"),label:S,fallback:S}).strict(),Wt=n.object({...C,type:n.literal("countdown"),source:n.enum(["offer.ends_at","offer.expires_at","fixed"]),at:n.iso.datetime().optional(),granularity:n.enum(["day","hour","minute","second"]),expired:S,fallback:S}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),Yt=n.object({...C,type:n.literal("plan_picker"),label:S,fallback:S,planIds:n.array(n.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:n.string().min(1).max(200).optional(),grouping:qe.safeExtend({monthLabel:S,yearLabel:S,unavailableLabel:S}).optional(),states:n.object({selected:B.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!Me(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),Xt=n.discriminatedUnion("type",[n.object({type:n.literal("input"),label:S,keyboard:n.enum(["text","email","tel","url"]),maxLength:b(1,500)}).strict(),n.object({type:n.literal("multiselect"),label:S,min:b(0,50),max:b(1,50)}).strict(),n.object({type:n.literal("select"),label:S,defaultIndex:b(0,49),purpose:n.enum(["option","product","tier"]).optional(),pickerId:X.optional(),selectedStyle:B.optional()}).strict(),n.object({type:n.literal("tabs"),label:S,defaultIndex:b(0,49),purpose:n.literal("tier").optional()}).strict(),n.object({type:n.literal("toggle"),label:S,defaultEnabled:n.boolean()}).strict(),n.object({type:n.literal("carousel"),label:S}).strict()]),D={...C,type:n.literal("stack"),direction:n.enum(["vertical","horizontal","overlay"]),align:n.enum(["start","center","end","stretch"]),justify:n.enum(["start","center","end","between"]),productSlot:n.object({index:b(0,19),period:n.enum(["month","year"]).optional(),requireBinding:n.boolean().optional()}).strict().optional(),interaction:Xt.optional(),states:n.object({selected:B.optional()}).strict().optional(),purpose:n.literal("benefits").optional(),purchaseAction:S.optional(),buttonVariant:n.enum(["primary","secondary","link"]).optional(),bind:fe.optional()},tt=n.lazy(()=>n.object({...C,type:D.type,direction:D.direction,align:D.align,justify:D.justify,children:n.array(Jt).max(z.children),productSlot:D.productSlot,interaction:D.interaction,states:D.states,purpose:D.purpose,purchaseAction:D.purchaseAction,buttonVariant:D.buttonVariant,bind:D.bind}).strict()),Jt=n.lazy(()=>n.union([tt,Bt,qt,Mt,Ft,Gt,Ht,Kt,Qt,Wt,Yt,Zt])),er=n.union([n.string().max(500),n.number().finite(),n.boolean(),n.null()]),Y={id:S,event:S,properties:n.record(S,er).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},tr=n.discriminatedUnion("type",[n.object({...Y,type:n.literal("navigate"),close:n.literal(!1),pageId:X}).strict(),n.object({...Y,type:n.literal("event"),close:n.boolean()}).strict(),n.object({...Y,type:n.literal("close"),close:n.literal(!0)}).strict(),n.object({...Y,type:n.literal("open_url"),close:n.boolean(),url:Je}).strict(),n.object({...Y,type:n.literal("claim_offer"),close:n.boolean(),couponId:n.uuid()}).strict()]),rr=n.object({defaultLocale:M,locales:n.record(M,n.record(S,n.string().max(z.stringLength)))}).strict(),nr=n.enum(["popup","paywall","onboarding","page"]),Gn={popup:"/workspace/popups",paywall:"/workspace/paywalls",onboarding:"/workspace/funnels",page:"/workspace/pages"},ir=n.discriminatedUnion("type",[n.object({type:n.literal("modal"),size:n.enum(["sm","md","lg"])}).strict(),n.object({type:n.literal("sheet"),size:n.enum(["sm","md","lg"])}).strict(),n.object({type:n.literal("fullscreen")}).strict()]),Hn={sm:360,md:420,lg:560},or=n.object({kind:n.literal("screen"),schemaVersion:n.literal(Tt),name:n.string().trim().min(1).max(80),surface:nr,initialPageId:X.optional(),presentation:ir,theme:Ye,pages:n.array(n.object({id:X,name:n.string().trim().min(1).max(60),root:tt,theme:Ye.optional(),editorPosition:n.object({x:n.number().finite().min(-1e5).max(1e5),y:n.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(z.pages),strings:rr,actions:n.array(tr).max(z.actions)}).strict();function G(e,t){for(let r of e.pages)ee(r.root,t)}function Kn(e,t){return{...e,pages:e.pages.map((r,i)=>i===0?{...r,root:t}:r)}}var ar=or.superRefine((e,t)=>{let r=z;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(p=>p.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let p of e.actions)p.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(y=>y.id===p.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>r.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${r.pages} \u4E2A`}),e.actions.length>r.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${r.actions} \u4E2A`});let i=p=>t.addIssue({code:"custom",message:p}),a=Object.keys(e.strings.locales);a.includes(e.strings.defaultLocale)||i("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),a.length>z.locales&&i(`\u6700\u591A ${z.locales} \u79CD\u8BED\u8A00`);let c=new Set;for(let p of e.actions)c.has(p.id)&&i(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${p.id}`),c.add(p.id);let l=new Set;for(let p of e.pages)["next","back"].includes(p.id)&&i(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${p.id}`),l.has(p.id)&&i(`\u9875\u9762 id \u91CD\u590D\uFF1A${p.id}`),l.add(p.id);let d=new Set,g=0,s=!1;G(e,(p,y)=>{if(g++,y>z.depth&&(s=!0),d.has(p.id)&&i(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${p.id}`),d.add(p.id),p.type==="button"&&!c.has(p.action)&&i(`\u6309\u94AE ${p.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${p.action}`),p.type==="custom_html")for(let h of Object.keys(p.html))a.includes(h)||i(`\u81EA\u5B9A\u4E49 HTML ${p.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${h}`);if(p.type==="image")for(let h of Object.keys(p.localizedSrc??{}))a.includes(h)||i(`\u56FE\u7247 ${p.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${h}`)}),g>r.nodes&&i(`\u7EC4\u4EF6\u6700\u591A ${r.nodes} \u4E2A`),s&&i(`\u5C42\u7EA7\u6700\u591A ${z.depth} \u5C42`)});function ee(e,t,r=1,i=null){if(t(e,r,i)!==!1&&e.type==="stack")for(let a of e.children)ee(a,t,r+1,e)}function Se(e){let t=[],r=new Set;return G(e,i=>{let a=(c,l,d)=>{r.has(c)||(r.add(c),t.push({key:c,nodeId:i.id,nodeType:i.type,field:l,required:d}))};i.type==="stack"&&i.interaction&&a(i.interaction.label,"label",!0),i.fallback&&a(i.fallback,"text",!0),i.type==="text"&&a(i.text,"text",!0),i.type==="customer_data"&&a(i.title,"title",!0),(i.type==="plan_picker"||i.type==="coupon_code")&&a(i.label,"label",!0),i.type==="plan_picker"&&i.grouping&&(a(i.grouping.monthLabel,"label",!0),a(i.grouping.yearLabel,"label",!0),a(i.grouping.unavailableLabel,"text",!0)),i.type==="countdown"&&a(i.expired,"text",!0),i.type==="button"&&a(i.label,"label",!0),i.type==="image"&&(a(`image:${i.id}`,"src",!1),a(i.alt,"alt",!1)),i.type==="custom_html"&&a(`html:${i.id}`,"html",!0)}),t}function sr(e,t,r){if(t.field==="html"){let i;return G(e,a=>{a.id===t.nodeId&&a.type==="custom_html"&&(i=a.html[r])}),i}if(t.field==="src"){let i=he(e,t.nodeId);return i?.type==="image"?i.localizedSrc?.[r]??(r===e.strings.defaultLocale?i.src:void 0):void 0}return e.strings.locales[r]?.[t.key]}function rt(e){let t=Se(e).filter(i=>i.required);return Object.keys(e.strings.locales).sort((i,a)=>i===e.strings.defaultLocale?-1:a===e.strings.defaultLocale?1:0).map(i=>{let a=t.filter(c=>!sr(e,c,i)?.trim()).map(c=>c.key);return{locale:i,total:t.length,filled:t.length-a.length,missing:a,complete:a.length===0}})}function Qn(e){return nt(e,!0)}function Wn(e){return nt(e,!1)}function nt(e,t){let r=[],i=t&&e.actions.some(s=>typeof s.properties.templateKey=="string"&&s.properties.templateKey.startsWith("popup-coupon-"));i&&(!e.actions.some(s=>s.type==="claim_offer")||e.actions.some(s=>s.type==="event"&&typeof s.properties.templateKey=="string"&&s.properties.templateKey.startsWith("popup-coupon-")))&&r.push("\u4F18\u60E0\u5F39\u7A97\u6A21\u677F\u5C1A\u672A\u7ED1\u5B9A\u771F\u5B9E\u4F18\u60E0\u5238\uFF1A\u8BF7\u5C06\u9886\u53D6\u6309\u94AE\u8BBE\u4E3A\u300C\u9886\u53D6\u4F18\u60E0\u300D\u5E76\u9009\u62E9\u751F\u6548\u4E2D\u7684\u5238");function a(s,p){let y=s.type==="stack"||s.type==="button"?s.bind?.coupon??p:p;if(i&&s.type==="text"&&Object.values(e.strings.locales).some(h=>h[s.text]?.includes("{{offer."))&&!y&&r.push("\u4F18\u60E0\u5F39\u7A97\u6A21\u677F\u5C1A\u672A\u7ED1\u5B9A\u771F\u5B9E\u4F18\u60E0\u5238\uFF1A\u52A8\u6001\u6587\u6848\u9700\u8981\u7EE7\u627F\u4F18\u60E0\u5238\u7ED1\u5B9A"),s.type==="button"){let h=e.actions.find(w=>w.id===s.action);h?.type==="claim_offer"&&y&&y!==h.couponId&&r.push(`\u9886\u53D6\u6309\u94AE ${s.id} \u4E0E\u5C55\u793A\u5185\u5BB9\u7ED1\u5B9A\u4E86\u4E0D\u540C\u7684\u4F18\u60E0\u5238`)}s.type==="stack"&&s.children.forEach(h=>a(h,y))}e.pages.forEach(s=>a(s.root));let c=[],l=ar.safeParse(e);l.success||r.push(...l.error.issues.map(s=>s.message));for(let s of Object.values(e.strings.locales))for(let p of Object.values(s))for(let y of ce(p))r.push(`\u672A\u77E5\u53D8\u91CF\uFF1A${y}`);G(e,s=>{if(s.type==="customer_data"&&Object.values(e.strings.locales).some(y=>/\{\{|\}\}/.test(y[s.title]??""))&&r.push(`\u6570\u636E\u7EC4\u4EF6 ${s.id} \u7684\u6807\u9898\u9700\u8981\u4F7F\u7528\u9759\u6001\u6587\u5B57`),(s.type==="text"?[s.text]:s.type==="button"?[s.label]:[]).some(y=>Object.values(e.strings.locales).some(h=>h[y]?.includes("{{")))&&!s.fallback&&r.push(`\u7EC4\u4EF6 ${s.id} \u4F7F\u7528\u53D8\u91CF\uFF0C\u8BF7\u586B\u5199\u5907\u7528\u6587\u6848`),s.fallback&&Object.values(e.strings.locales).some(y=>y[s.fallback]?.includes("{{"))&&r.push(`\u7EC4\u4EF6 ${s.id} \u7684\u5907\u7528\u6587\u6848\u9700\u8981\u4F7F\u7528\u9759\u6001\u6587\u5B57`),s.type==="custom_html"){for(let y of Object.values(s.html))r.push(...ge(y).map(h=>`HTML ${s.id}\uFF1A${h}`));Object.values(s.html).some(y=>y.includes("{{"))&&!s.fallback&&r.push(`HTML ${s.id} \u4F7F\u7528\u53D8\u91CF\uFF0C\u8BF7\u586B\u5199\u5907\u7528\u6587\u6848`),/\{\{/.test(s.css)&&r.push(`HTML ${s.id} \u7684 CSS \u4E0D\u652F\u6301\u53D8\u91CF`)}(s.type==="stack"||s.type==="button")&&s.bind?.picker&&he(e,s.bind.picker)?.type!=="plan_picker"&&!Object.hasOwn(ae(e),s.bind.picker)&&r.push(`\u5BB9\u5668 ${s.id} \u5F15\u7528\u7684\u5957\u9910\u9009\u62E9\u4E0D\u5B58\u5728`)});for(let s of Object.keys(ae(e)))he(e,s)||r.push(`Product selection scope ${s} must reference a UI node`);let d=rt(e);for(let s of d)s.complete||(s.locale===e.strings.defaultLocale?r.push(`\u9ED8\u8BA4\u8BED\u8A00 ${s.locale} \u8FD8\u6709 ${s.missing.length} \u5904\u5185\u5BB9\u6CA1\u586B`):r.push(`${s.locale} \u8FD8\u6709 ${s.missing.length} \u5904\u6CA1\u7FFB\u8BD1\uFF0C\u8BF7\u8865\u9F50\u6216\u5220\u9664\u8FD9\u79CD\u8BED\u8A00\u540E\u53D1\u5E03`));Se(e).length===0&&!e.pages.some(s=>cr(s.root))&&r.push("\u5F39\u7A97\u91CC\u8FD8\u6CA1\u6709\u53EF\u663E\u793A\u7684\u5185\u5BB9");let g=new Set;G(e,s=>{s.type==="button"&&g.add(s.action)});for(let s of e.actions)!g.has(s.id)&&!e.pages.some(p=>lr(p.root,s.id))&&c.push(`\u52A8\u4F5C ${s.id} \u6CA1\u6709\u88AB\u4EFB\u4F55\u6309\u94AE\u4F7F\u7528`);return{errors:r,warnings:c}}function cr(e){let t=!1;return ee(e,r=>{if(r.hidden)return!1;r.type==="image"&&(t=!0)}),t}function lr(e,t){let r=!1;return ee(e,i=>{if(i.type==="custom_html")for(let a of Object.values(i.html))a.includes(`data-grow-action="${t}"`)&&(r=!0)}),r}function ur(e){return rt(e).filter(t=>t.complete||t.locale===e.strings.defaultLocale).map(t=>t.locale)}function Yn(e,t){return ke(t,ur(e),e.strings.defaultLocale)}function Xn(e,t){let r=e.strings.locales[t]??{},i=e.strings.locales[e.strings.defaultLocale]??{},a={};for(let l of Se(e)){if(l.field==="html"||l.field==="src")continue;let d=r[l.key]?.trim()?r[l.key]:i[l.key];d!==void 0&&(a[l.key]=d)}let c=l=>{if(l.type==="stack")return{...l,children:l.children.map(c)};if(l.type==="custom_html"){let d=l.html[t]?.trim()?l.html[t]:l.html[e.strings.defaultLocale];return{...l,html:d===void 0?{}:{[t]:d}}}if(l.type==="image"){let{localizedSrc:d,...g}=l;return{...g,src:d?.[t]??d?.[e.strings.defaultLocale]??l.src}}return l};return{...e,pages:e.pages.map(l=>({...l,root:c(l.root)})),strings:{defaultLocale:t,locales:{[t]:a}}}}function pr(e,t){let r=null;return ee(e,i=>{if(r)return!1;i.id===t&&(r=i)}),r}function he(e,t){for(let r of e.pages){let i=pr(r.root,t);if(i)return i}return null}function Jn(e){let t=de(e)?.split("-")[0];return t!==void 0&&["ar","he","fa","ur"].includes(t)}function ei(e,t,r){let i={};if(!t||typeof t!="object"||Array.isArray(t))return i;let a=t;if(G(e,c=>{if(c.type==="plan_picker"){let d=a[c.id];typeof d=="string"&&(i[c.id]=r?.pickers[c.id]?.options.includes(d)?d:"");return}if(c.type!=="stack"||!c.interaction)return;let l=Object.hasOwn(a,c.id)?a[c.id]:void 0;["select","tabs"].includes(c.interaction.type)&&typeof l=="string"&&c.children.some(d=>d.id===l)&&(i[c.id]=l),c.interaction.type==="toggle"&&typeof l=="boolean"&&(i[c.id]=l)}),e.surface==="paywall"&&typeof a.__page=="string"&&e.pages.some(c=>c.id===a.__page)&&(i.__page=a.__page),r){let c={...i};for(let[l,d]of Object.entries(a))(typeof d=="string"||typeof d=="boolean")&&(c[l]=d);Object.assign(i,Ze(e,c,r))}return i}import{z as I}from"zod";var oi=I.discriminatedUnion("kind",[I.object({kind:I.literal("ledger"),cursor:oe}).strict(),I.object({kind:I.literal("billing"),cursor:I.uuid()}).strict()]),mr=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),dr=I.record(I.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),I.union([I.string().max(500),I.boolean(),I.array(I.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),fr=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function xe(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(r=>xe(r,t+1)):Object.entries(e).some(([r,i])=>["__proto__","constructor","prototype"].includes(r)||fr.test(r)||xe(i,t+1)))}var gr=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,yr=I.record(mr,ue).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!xe(e)&&!gr.test(JSON.stringify(e)),"Credentials cannot be screen parameters");function ai(e){let t=Object.create(null);for(let[r,i]of new URL(e).searchParams)I.string().max(500).parse(i),Object.hasOwn(t,r)||(t[r]=i);return yr.parse(t),t}var it=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),br=I.array(I.object({variable:it,componentId:it,required:I.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"),si=I.object({bindings:br,answers:dr,values:I.record(I.string(),ue).optional()}).strict();export{at as a,O as b,pe as c,Sr as d,xr as e,_r as f,te as g,E as h,st as i,V as j,L as k,Ne as l,ct as m,lt as n,ut as o,Ar as p,M as q,de as r,ke as s,dt as t,Or as u,re as v,Lr as w,Tr as x,ft as y,gt as z,Le as A,jr as B,Ce as C,yt as D,Dr as E,bt as F,Te as G,ht as H,zr as I,Pr as J,wr as K,ne as L,$r as M,St as N,Q as O,De as P,ie as Q,Br as R,qr as S,ze as T,Gr as U,Pe as V,P as W,Jr as X,we as Y,oe as Z,en as _,Et as $,tn as aa,ve as ba,on as ca,an as da,sn as ea,Ue as fa,Ve as ga,bn as ha,Nt as ia,Rt as ja,$e as ka,hn as la,qe as ma,Me as na,Fe as oa,ae as pa,Ze as qa,Ot as ra,fe as sa,Ge as ta,Rn as ua,se as va,ce as wa,On as xa,kn as ya,kt as za,He as Aa,Ke as Ba,Lt as Ca,jn as Da,Dn as Ea,zn as Fa,ge as Ga,We as Ha,vn as Ia,Tt as Ja,z as Ka,X as La,S as Ma,jt as Na,Dt as Oa,be as Pa,Ye as Qa,J as Ra,Xe as Sa,zt as Ta,Pt as Ua,et as Va,wt as Wa,vt as Xa,Ut as Ya,Vt as Za,$t as _a,B as $a,Bt as ab,qt as bb,Mt as cb,Ft as db,Zt as eb,Gt as fb,Ht as gb,Kt as hb,Qt as ib,Wt as jb,Yt as kb,Xt as lb,tt as mb,Jt as nb,tr as ob,rr as pb,nr as qb,Gn as rb,ir as sb,Hn as tb,G as ub,Kn as vb,ar as wb,ee as xb,Se as yb,sr as zb,rt as Ab,Qn as Bb,Wn as Cb,ur as Db,Yn as Eb,Xn as Fb,pr as Gb,he as Hb,Jn as Ib,ei as Jb,oi as Kb,dr as Lb,yr as Mb,ai as Nb,br as Ob,si as Pb};
@@ -1 +0,0 @@
1
- import{a as N,b as O,c as U}from"./chunk-4K25DELJ.js";function M(n){let c=n.document??document,r=c.defaultView;if(!r)return{destroy(){},checkpoint(e){},retry(){}};let d="indiana:iam:authoring:v2:"+new URL(n.baseUrl).origin+":"+n.environmentId;function m(e){if(e.length>12e3||!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(e))return!1;try{let t=JSON.parse(r.atob(e.split(".")[0].replaceAll("-","+").replaceAll("_","/")));return N(r.location.origin)&&typeof t=="object"&&t!==null&&"version"in t&&"environmentId"in t&&"origin"in t&&t.version===2&&t.environmentId===n.environmentId&&t.origin===r.location.origin}catch{return!1}}let u=!1,f=!1,i=0,o=!1,s="",b,h,y=0,_=!1,l,I=()=>{try{r.sessionStorage.removeItem(d)}catch{}},E=e=>{if(f!==e){f=e;try{n.onAuthoringChange?.(e)}catch{}}},v=e=>{y=e.snapshots,["authorized","idle","capturing","uploading","waiting"].includes(e.state)&&(_=!0),h?.update({...e,reloadRequired:_});try{n.onStatus?.(e)}catch{}c.dispatchEvent(new r.CustomEvent("indiana:iam:status",{detail:e}))};function g(){u||(i++,b?.abort(),l?.destroy("USER_STOPPED"),l=void 0,o=!1,I(),s="",E(!1),c.removeEventListener("indiana:iam:checkpoint",p),v({state:"stopped",reason:"USER_STOPPED",snapshots:y}))}let p=e=>{let t=e instanceof r.CustomEvent?e.detail:void 0,A=t&&typeof t=="object"&&"label"in t?t.label:void 0;if(typeof A=="string"&&/^[\p{L}\p{N} _.-]{1,64}$/u.test(A))try{l?l.checkpoint(A):s&&!o&&R(s)}catch{}};function L(){let e=new URLSearchParams(r.location.hash.slice(1)),t=e.get("indiana-capture");if(!t)return null;m(t)&&E(!0),e.delete("indiana-capture");let A=new URL(r.location.href);return A.hash=e.toString(),r.history.replaceState(r.history.state,"",A),/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(t)&&t.length<=12e3?t:null}function R(e){if(u||!m(e))return;let t=++i;b?.abort(),b=new AbortController;let A=b.signal;l?.destroy("REPLACED"),l=void 0,s=e,o=!0,E(!0),c.addEventListener("indiana:iam:checkpoint",p);try{r.sessionStorage.setItem(d,e)}catch{}(async()=>{if(n.controls!==!1&&!h?.active){let{createCaptureControls:w}=await import("./controls-XG46TKUU.js");if(u||t!==i)return;h?.destroy(),h=w({document:c,nonce:n.nonce,retry(){l?l.retry():s&&!o&&R(s)},stop:g,close(){h?.destroy(),h=void 0}})}if(h?.update({state:"connecting",snapshots:0}),!r.navigator.onLine)throw Object.assign(Error("Capture offline"),{code:"OFFLINE"});if(await n.prepare?.(),u||t!==i)return;let a=await fetch(new URL("/api/app-manifest-captures",n.baseUrl),{method:"POST",credentials:"omit",redirect:"error",cache:"no-store",headers:{Authorization:"Bearer "+e,[O]:U,"Content-Type":"application/json"},body:JSON.stringify({action:"authorize"}),signal:AbortSignal.any([A,AbortSignal.timeout(3e4)])});if(a.status!==204||a.headers.get(O)!==U)throw a.body?.cancel().catch(()=>{}),Object.assign(new Error("Capture authorization refused"),{code:a.ok?a.status===204?"CAPTURE_VERSION_MISMATCH":"SERVICE_RESPONSE_INVALID":"AUTH_OR_SERVICE_"+a.status});if(u||t!==i)return;v({state:"authorized",snapshots:0});let{startCapture:S}=await import("./client-F6UPJMHR.js");if(u||t!==i)return;let C=await S({environmentId:n.environmentId,grant:e,baseUrl:n.baseUrl,document:c,signal:A,onStatus(w){u||t!==i||(w.state==="stopped"&&(I(),s="",E(!1),c.removeEventListener("indiana:iam:checkpoint",p)),v(w))}});if(u||t!==i){C.destroy("REPLACED");return}l=C,c.addEventListener("indiana:iam:checkpoint",p)})().catch(a=>{if(!u&&t===i){let S=a instanceof Error&&["TypeError","TimeoutError"].includes(a.name)||a&&typeof a=="object"&&"code"in a&&/^(?:AUTH_OR_SERVICE_(?:408|429|5\d\d)|SERVICE_RESPONSE_INVALID|OFFLINE)$/.test(String(a.code));S||(I(),s="",E(!1),c.removeEventListener("indiana:iam:checkpoint",p));let C=a&&typeof a=="object"&&"code"in a?String(a.code):"",w={state:S?"paused":"stopped",reason:["CAPTURE_VERSION_MISMATCH","AUTH_OR_SERVICE_426"].includes(C)?"CAPTURE_UPGRADE_REQUIRED":C==="OFFLINE"?"OFFLINE":a&&typeof a=="object"&&"code"in a&&a.code==="AUTHORING_CONTROLS_BLOCKED"?"AUTHORING_CONTROLS_BLOCKED":S?"SERVICE_UNAVAILABLE":"AUTH_OR_SERVICE_UNAVAILABLE",snapshots:0};v(w)}}).finally(()=>{t===i&&(o=!1)})}let k=()=>{let e=L();e&&R(e)};r.addEventListener("hashchange",k);try{let e=L()??r.sessionStorage.getItem(d);e&&R(e)}catch{}return{destroy(){u=!0,i++,b?.abort(),l?.destroy(),h?.destroy(),h=void 0,r.removeEventListener("hashchange",k),c.removeEventListener("indiana:iam:checkpoint",p),I(),s="",E(!1)},checkpoint(e){l?l.checkpoint(e):s&&!o&&R(s)},retry(){l?l.retry():s&&!o&&R(s)}}}async function P(n,c,r){let d=new URL(n,c.baseURI),m=c.defaultView?.location.origin,u=/^\/\.well-known\/indiana\/releases\/([a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12})\.json$/.exec(d.pathname)?.[1];if(!u||d.origin!==m||d.search||d.hash||d.username||d.password)throw Error("Invalid IAM release URL");let f=AbortSignal.any([r,AbortSignal.timeout(2e3)]),i=await fetch(d,{credentials:"omit",redirect:"error",cache:"force-cache",signal:f}),o=i.headers.get("content-length");if(!i.ok||!/^application\/json(?:;|$)/i.test(i.headers.get("content-type")??"")||o!==null&&(!/^\d+$/.test(o)||Number(o)>512))throw i.body?.cancel().catch(()=>{}),Error("IAM release is unavailable");let s=i.body?.getReader();if(!s)throw Error("IAM release is unavailable");let b=[],h=0,y=()=>{},_=new Promise((p,L)=>{y=()=>L(Error("IAM release timeout")),f.addEventListener("abort",y,{once:!0}),f.aborted&&y()}),l=!1;try{for(;;){let p=await Promise.race([s.read(),_]);if(p.done){l=!0;break}if(h+=p.value.length,h>512)throw Error("IAM release budget");b.push(p.value)}}finally{f.removeEventListener("abort",y),l||s.cancel().catch(()=>{}),s.releaseLock()}let I=new Uint8Array(h),E=0;for(let p of b)I.set(p,E),E+=p.length;let v=new TextDecoder("utf-8",{fatal:!0}).decode(I),g=JSON.parse(v);if(v.trim()!==JSON.stringify(g))throw Error("Noncanonical IAM release descriptor");if(!g||typeof g!="object"||Array.isArray(g)||Object.keys(g).sort().join(",")!=="format,manifestDigest,releaseId,schemaVersion"||Reflect.get(g,"format")!=="indiana-app-manifest-release"||Reflect.get(g,"schemaVersion")!==2||Reflect.get(g,"releaseId")!==u||!/^[a-f0-9]{64}$/.test(String(Reflect.get(g,"manifestDigest"))))throw Error("Invalid IAM release descriptor");return Reflect.get(g,"manifestDigest")}var T=new WeakMap;function x(n,c=document){if(!/^[a-f0-9]{64}$/.test(n))throw new Error("Invalid IAM manifest digest");let r=T.get(c);r||(r=new Map,T.set(c,r));let d="data-indiana-release",m=c.documentElement,u=()=>new Set((m.getAttribute(d)??"").split(/\s+/).filter(Boolean)),f=r.get(n);if(!f){let o=u();f={count:0,owned:!o.has(n)},r.set(n,f),o.add(n),m.setAttribute(d,[...o].join(" "))}f.count++;let i=!1;return{attributes:{indianaAppManifestRelease:n},destroy(){if(!i&&(i=!0,f.count--,!f.count&&(r.delete(n),f.owned))){let o=u();o.delete(n),o.size?m.setAttribute(d,[...o].join(" ")):m.removeAttribute(d)}}}}async function z(n){return(await import("./client-F6UPJMHR.js")).startCapture(n)}export{M as a,P as b,x as c,z as d};
@@ -1 +0,0 @@
1
- import{a as Ie}from"./chunk-QO4YQLZ4.js";import{Ag as _e,Bg as q,Cg as Ae,Dg as Be,Eg as ze,Ek as Ze,Fg as He,Gd as Ue,Ig as $e,Kg as Ke,Pi as De,Yd as ke,Zd as qe,_i as Pe,ae as Ge,bj as Qe,ig as ie,li as fe,ll as We,mj as Ne,ml as Xe,nj as Ye,nl as en,ol as nn,tg as je,vg as H,wg as Je}from"./chunk-467Z5ISI.js";import{b as xe,h as we}from"./chunk-3SONNXFG.js";import{a as ye}from"./chunk-S5TVMQRC.js";import{a as u}from"./chunk-6MO6Y24B.js";import{b as Te}from"./chunk-RRII2DMC.js";import{h as Ve,l as Me}from"./chunk-KQCTDXVD.js";function En(e){let n=null,i=null,t=0,f=0,v=new Set,o=null,s=null,r=new Set,a=()=>{for(let h of r)try{h()}catch{}},p={attributes:Te.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(h,F)=>{!v.has(h)&&(!n||!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(h,structuredClone(F))}:void 0,onExperimentViewed:e.onExperimentViewed?(h,F)=>(!n||!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(h),structuredClone(F)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?h=>e.saveStickyBucketAssignmentDoc(structuredClone(h)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},w=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function P(h,F=new Set){return v.has(h)?!o||!o.features[h]||["unknownFeature","cyclicPrerequisite"].includes(o.features[h].source):F.has(h)?!1:(F.add(h),(n?.features[h]?.rules??[]).some(T=>[...T.parentConditions??[],...(T.tracks??[]).flatMap(_=>_.experiment.parentConditions??[])].some(_=>P(_.id,F))))}let S=h=>{if(e.assertUsable?.(n?.generation),!n)throw new Error("Initialize the Feature client before evaluation");if(n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return o?.expiresAt&&Date.parse(o.expiresAt)<=Date.now()&&(o=null,p.features=n.features),v.has(h)?!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now()?w():structuredClone(o.features[h]??w()):P(h)?w():structuredClone(Me(h,p))};async function C(){if(!n||!v.size)return;if(!e.evaluateRemote)throw new Error("Remote Feature evaluation requires a server loader");let h=f;if(s?.revision===h)return s.loading;let F=t,T=n,_=[...v],D=(async()=>{let L=Ge.parse(await e.evaluateRemote({attributes:structuredClone(p.attributes),features:_}));if(!(F!==t||h!==f||T!==n)){if(e.assertUsable?.(T.generation),L.generation!==T.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(_.some(G=>!Object.hasOwn(L.features,G))||Object.keys(L.features).some(G=>!v.has(G)))throw new Error("Invalid remote Feature results");o=structuredClone(L),p.features={...T.features,...Object.fromEntries(Object.entries(o.features).map(([G,J])=>[G,{defaultValue:J.value}]))},a()}})();s={revision:h,loading:D};try{await D}finally{s?.loading===D&&(s=null)}}function I(){C().catch(h=>{try{e.onError?.(h)}catch{}})}async function U(){if(i)return i;let h=t,F=(async()=>{let T=await e.load(),_="remoteFeatures"in T?ke.parse(T):null,D=_??we.parse(T);if(D.scope.projectId!==e.scope.projectId||D.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(h!==t)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===D.generation){let{evaluatedAt:G,expiresAt:J,...se}=n,{evaluatedAt:W,expiresAt:X,...l}=D;if(q(se)!==q(l))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=D.evaluatedAt,n.expiresAt=D.expiresAt,a(),(!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())&&I(),structuredClone(n)}let L=new Set(_?.remoteFeatures??[]);if([...L].some(G=>Object.hasOwn(D.features,G)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in D&&!n.analyticsConfig.experimentViewsEnabled&&_?.analyticsConfig.experimentViewsEnabled&&p.trackedExperiments?.clear(),n=structuredClone(D),v=L,o=null,s=null,f++,p.features=n.features,p.savedGroups=Ve(n.savedGroups),p.trackedFeatureUsage={},a(),I(),structuredClone(n)})();i=F;try{return await F}finally{i===F&&(i=null)}}return{init:U,refresh:U,refreshRemote:C,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(h){return r.add(h),()=>{r.delete(h)}},setAttributes(h){p.attributes=Te.parse(h),f++,o=null,s=null,p.features=n?.features??{},p.trackedFeatureUsage={},a(),I()},evalFeature:S,isOn(h){return S(h).on},isOff(h){return S(h).off},getFeatureValue(h,F){let T=S(h).value;return structuredClone(T===null?F:T)},reset(){t++,f++,i=null,s=null,n=null,o=null,v.clear(),p.features={},p.savedGroups={},p.stickyBucketAssignmentDocs={},p.attributes={},p.trackedFeatureUsage={},p.trackedExperiments?.clear(),a()}}}async function be(e,n){let i=$e.parse(n),{artifact:t,environmentId:f}=i.content,v=new URL(e.baseUrl??ye).origin,o=new URL(t.url,v);if(o.origin!==v||o.username||o.password||o.search||o.hash||o.pathname!==`/api/v1/configuration/${f}/artifacts/${t.sha256}`)throw new u("INVALID_RESPONSE","Public Paywall locator is not trusted");let s=new AbortController,r=setTimeout(()=>s.abort(),H.initializationMs);try{let a=await(e.fetch??globalThis.fetch)(o,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:s.signal});if(!a.ok||!a.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(a.headers.get("content-length"))>t.byteLength)throw new u("INVALID_RESPONSE","Public Paywall is unavailable");let p=a.body?.getReader();if(!p)throw new u("INVALID_RESPONSE","Public Paywall body is missing");let w=[],P=0;try{for(;;){let I=await p.read();if(I.done)break;if(P+=I.value.length,P>t.byteLength)throw new u("INVALID_RESPONSE","Public Paywall exceeds its byte limit");w.push(I.value)}}finally{await p.cancel().catch(()=>{})}let S=new Uint8Array(P),C=0;for(let I of w)S.set(I,C),C+=I.length;if(P!==t.byteLength||Ae(S)!==t.sha256)throw new u("INVALID_RESPONSE","Public Paywall digest or size changed");return Ke(i,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(S)))}finally{clearTimeout(r)}}async function Fe(e,n){let{funnelRuntimeDeliverySchema:i}=await import("./src-UHLPVD6E.js"),t=i.safeParse(n);if(!t.success)throw new u("INVALID_RESPONSE","Funnel response contract changed");let f=t.data;if(e.scope&&(f.scope.projectId!==e.scope.projectId||f.scope.environment!==e.scope.environment))throw new u("SCOPE_MISMATCH","Funnel scope changed");return f}function tn(e){let n,i,t=()=>new u("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),f=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,i=e.locks??globalThis.navigator?.locks,!n||!i||!globalThis.crypto?.subtle)throw t();let s=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??ye).href,e.runToken])),r=new Uint8Array(await crypto.subtle.digest("SHA-256",s));return"indiana.funnel.commands.v1."+Array.from(r,a=>a.toString(16).padStart(2,"0")).join("")});f.catch(()=>{});async function v(s){try{let r=await f;return await i.request(r,{mode:"exclusive"},()=>s(r))}catch(r){throw r instanceof u?r:t()}}function o(s){let r=n.getItem(s);if(r===null)return{revision:0,entry:null};if(r.length>1048576)throw t();let a=JSON.parse(r);if(!a||typeof a!="object"||!("revision"in a)||!("entry"in a)||!Number.isSafeInteger(a.revision)||Number(a.revision)<0)throw t();return{revision:Number(a.revision),entry:a.entry}}return{read:()=>v(o),write:(s,r)=>v(a=>{if(o(a).revision!==s)return null;if(!Number.isSafeInteger(s+1))throw t();return n.setItem(a,JSON.stringify({revision:s+1,entry:r})),s+1})}}function Tn(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function he(e,n){if(e===n)return!0;if(Array.isArray(e)||Array.isArray(n))return Array.isArray(e)&&Array.isArray(n)&&e.length===n.length&&e.every((f,v)=>he(f,n[v]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let i=Object.entries(e),t=Object.entries(n);return i.length===t.length&&i.every(([f,v])=>Object.hasOwn(n,f)&&he(v,Reflect.get(n,f)))}var me=(e,n)=>new u(e,n);function xn(e){return We(e,me)}function pn(e,n,i){return en(e,n,i,me)}async function rn(e,n){let i=n.instruction;if(i?.type!=="evaluate")throw new Error("Evaluation instruction required");if(!e)throw new u("CONFIGURATION_UNAVAILABLE","Local conditions require the shared public configuration manager");let t=await e.funnel(n.source.id,n.source.versionId);if(!t.growth||t.control.evaluationMode!=="local"||t.control.evaluationRevision!==i.policyRevision)throw new u("EVALUATION_MODE","Refresh the original Funnel evaluation policy");let{analyticsConfig:f,remoteFeatures:v,...o}=t.growth,s=Ne({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:i.policyRevision,document:t.document,payload:we.parse(o)});if(e.scope.environmentId!==i.environmentId)throw new u("SCOPE_MISMATCH","Evaluation environment changed");let r=pn(s,n.nodeId,i);return e.assertFunnel(n.source.id,void 0,n.source.versionId),{generation:t.manifest.generation,result:r}}async function on(e,n){let i=n.instruction;if(i?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new u("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");let t=await e.funnel(n.source.id,n.source.versionId);if(!t.growth||t.control.evaluationMode!=="local"||t.control.evaluationRevision!==i.policyRevision)throw new u("EVALUATION_MODE","Refresh the original Funnel evaluation policy");if(e.scope.environmentId!==i.environmentId)throw new u("SCOPE_MISMATCH","Evaluation environment changed");let{analyticsConfig:f,remoteFeatures:v,...o}=t.growth,s=Ne({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:i.policyRevision,document:t.document,payload:we.parse(o)}),r=gn(s,t.document,{...n,...i});return e.assertFunnel(n.source.id,void 0,n.source.versionId),{...r,generation:t.manifest.generation,policyRevision:i.policyRevision}}function gn(e,n,i){return nn(e,n,i,me)}import{z as K}from"zod";var an=ie.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 u("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),sn=K.strictObject({schemaVersion:K.literal(1),scope:xe,runId:K.uuid(),funnelId:K.uuid(),versionId:K.uuid(),command:an.optional(),closeCommand:an.refine(e=>e.operation==="close").optional(),purchase:K.strictObject({receiptId:K.uuid(),operationId:K.uuid(),generation:K.number().int().nonnegative()}).optional(),closed:K.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"),B=()=>new u("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Oe=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function un(e){let n=0,i=null,t=r=>JSON.stringify([r.scope,r.runId,r.funnelId,r.versionId]),f=Promise.resolve();async function v(){let r=await e.read();if(!Number.isSafeInteger(r.revision)||r.revision<0)throw new u("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:r.revision,entry:r.entry===null?null:sn.parse(r.entry)}}function o(r){let a=f.then(r);return f=a.catch(()=>{}),a}async function s(r){for(let a=0;a<4;a++){let p=await v();if(p.entry&&i!==null&&t(p.entry)!==i)throw B();let w=r(p.entry,p.revision);if(Oe(p.entry,w)){n=p.revision;return}let P=await e.write(p.revision,w);if(P!==null){if(!Number.isSafeInteger(P)||P<=p.revision)throw B();n=P;return}}throw B()}return{bind(r){let a=JSON.stringify([r.scope,r.runId,r.funnelId,r.versionId]);if(i!==null&&i!==a)throw B();i=a},async load(){let r=await v();return n=r.revision,i=r.entry?t(r.entry):null,r.entry},retain(r){let a=sn.parse(r),p=a.command;return!p||i!==null&&t(a)!==i?Promise.reject(B()):(i??=t(a),o(()=>s((w,P)=>{if(w&&!Oe(t(w),t(a)))throw B();if(!w){if(P!==n&&p.operation!=="close")throw B();return a}if(!w.command)return{...w,command:p,...p.operation==="close"?{closed:!0}:{}};if(p.operation==="close"&&w.command.operation!=="close"){if(w.command.requestId===p.requestId||w.closeCommand&&!Oe(w.closeCommand,p))throw B();return{...w,closeCommand:p,closed:!0}}if(!Oe(w.command,p))throw B();return w})))},observePurchase(r,a,p){return o(()=>s((w,P)=>{if(!w&&P!==n||w&&t(w)!==t({...r,schemaVersion:1}))throw B();if(w?.purchase&&w.purchase.generation>a.generation)return w;if(w?.purchase&&w.purchase.generation===a.generation&&w.purchase.operationId!==a.operationId)throw B();return p?!w?.purchase||w.purchase.operationId!==a.operationId?w:w.command?{...w,purchase:void 0}:null:{schemaVersion:1,...r,...w,purchase:a}}))},settle(r){return o(()=>s(a=>a?a.command&&"requestId"in a.command&&a.command.requestId===r?a.closeCommand?{...a,command:a.closeCommand,closeCommand:void 0}:a.purchase?{...a,command:void 0}:null:a.closeCommand&&"requestId"in a.closeCommand&&a.closeCommand.requestId===r?{...a,closeCommand:void 0}:a:null))}}}function pe(e){let{customerToken:n,...i}=e;return i}var wn=e=>!(e instanceof u)||e.status===void 0||e.status>=500||[401,425].includes(e.status);function ln(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new u("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.serverKey)))throw new u("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");let n=Ie({...e,...e.serverKey?{fetch:(l,c)=>{let O=new Headers(c?.headers),V=typeof c?.body=="string"?JSON.parse(c.body):null;return V!==null&&typeof V=="object"&&"customerToken"in V&&typeof V.customerToken=="string"&&V.customerToken.length>0||O.set(Qe,e.serverKey),(e.fetch??globalThis.fetch)(l,{...c,headers:O})}}:{},timeoutMs:e.timeoutMs??35e3});n.identify(e.runToken);let i,t=null,f=0,v=0,o=null,s=null,r=!1,a=null,p=!1,w=null,P=new Set,S=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?tn(e):void 0),C=S&&un(S),I,U=null,h=!1,F=C?C.load().then(l=>{if(h)throw new u("IDENTITY_CHANGED","Controller was reset during command restoration");if(U=l,!l)return;if(e.scope&&(l.scope.projectId!==e.scope.projectId||l.scope.environment!==e.scope.environment))throw new u("SCOPE_MISMATCH","Pending command belongs to another scope");if(I=l.purchase,r=l.closed===!0,!l.command)return;let c=ie.parse(l.command);if(c.operation==="start"||c.operation==="get"||c.operation==="review")throw new u("COMMAND_STORAGE_INVALID","Stored mutation required");o=c,l.closeCommand&&(s=l.closeCommand,r=!0),c.operation==="close"&&(r=!0),p=!0}):Promise.resolve();F.catch(()=>{});async function T(l,c,O){let V=f,z=()=>{if(V!==f||h)throw new u("IDENTITY_CHANGED","Run identity changed during the request")};C&&await F,z();let A=t,m=Pe.parse(await Fe(e,await n.request("funnels",ie.parse(l))));if(l.operation==="review"&&!m.review)throw new u("INVALID_RESPONSE","Historical projection is missing");if(z(),m.runToken&&m.runToken!==e.runToken)throw new u("INVALID_RESPONSE","Run credential changed");let ee=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(ee&&m.settlement?.requestId!==ee)throw new u("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");if(U&&(m.run.id!==U.runId||m.run.source.id!==U.funnelId||m.run.source.versionId!==U.versionId))throw new u("SCOPE_MISMATCH","Stored command belongs to another Run or Version");if(t&&(m.run.id!==t.id||m.run.source.type!==t.source.type||m.run.source.id!==t.source.id||m.run.source.versionId!==t.source.versionId||m.run.locale!==t.locale||!he(m.run.parameters,t.parameters)))throw new u("INVALID_RESPONSE","Run version changed");if(e.funnelId&&m.run.source.id!==e.funnelId)throw new u("INVALID_RESPONSE","Run belongs to another Funnel");C?.bind({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId}),S&&!e.scope&&(e.scope=m.scope);let $=m.run.paywall,Q=$??m.purchase,ue=Q?.operation,ne=m.settlement&&(!$||$.purchaseRequestId===m.settlement.requestId)&&(!I||I.operationId===m.settlement.operationId)?m.settlement:void 0,te=ue?.operationId??Q?.quote?.operationId??ne?.operationId,ve=Q?.receiptId??ne?.receiptId,Re=$?.selectionGeneration??I?.generation??0;if(C&&te&&ve&&l.operation!=="review"&&(!t||m.run.revision>=t.revision)&&(O===void 0||O>=v)&&(!I||Re>=I.generation)){let le={receiptId:ve,operationId:te,generation:Re},Ee=ue?.status==="complete"||Q?.canReselect===!0;await C.observePurchase({scope:m.scope,runId:m.run.id,funnelId:m.run.source.id,versionId:m.run.source.versionId},le,Ee),z(),Ee?I?.operationId===le.operationId&&(I=void 0):I=le}if(!m.run.stopped&&["running","waiting"].includes(m.run.status)&&l.operation==="get"&&l.settlementRequestId)return m;let re=c?.(m),ge=typeof re=="boolean"?re:re?await re:!1;if(z(),["running","waiting"].includes(m.run.status)||(r=!0),l.operation==="review"&&t&&t!==A&&m.run.revision<=t.revision||t&&m.run.revision===t.revision&&O!==void 0&&O<v||(l.operation==="review"&&!m.run.stopped&&["running","waiting"].includes(m.run.status)&&t&&m.run.nodeId===t.nodeId&&m.run.visit===t.visit&&m.run.revision===t.revision&&(m.run.screen=t.screen,(t.paywall?.quote?.operationId===m.review?.activeOperationId||!t.paywall?.quote&&m.review?.activeOperationId===null)&&(m.run.paywall=t.paywall)),t?.paywall&&m.run.paywall&&t.paywall.receiptId===m.run.paywall.receiptId&&(m.run.paywall.selectionGeneration??0)<(t.paywall.selectionGeneration??0)))return m;if(!t||m.run.revision>=t.revision)t=m.run;else if(!ge)return m;if(t)for(let le of P)try{le(structuredClone(t))}catch{}return m}async function _(l=o){if(C&&await F,!l)throw new u("INVALID_REQUEST","No command is pending");let c=l,O=f;if(C){if(!t||!e.scope)throw new u("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await C.retain({schemaVersion:1,scope:e.scope,runId:t.id,funnelId:t.source.id,versionId:t.source.versionId,command:pe(c)})}if(O!==f||o!==c&&s!==c)throw new u("IDENTITY_CHANGED","Run changed before command dispatch");let V={...c,...i?{customerToken:i}:{}},z=p;p=!0;try{return await T(V,A=>{if(!A.settlement)throw new u("INVALID_RESPONSE","Exact command settlement is missing");if(A.settlement.requestId!==c.requestId)throw new u("INVALID_RESPONSE","Command settlement identity changed");if(O===f&&(o===c||s===c)&&A.run.pendingRequest?.requestId!==c.requestId&&A.settlement.state==="settled"&&(!r||c.operation==="close"||A.settlement?.state==="settled"&&!["running","waiting"].includes(A.run.status))){let m=()=>O!==f||o!==c&&s!==c?!1:(o===c&&(o=null),s===c&&(s=null),p=o!==null,U=null,!0);return C?C.settle(c.requestId).then(m):m()}return!1})}catch(A){throw O===f&&o===c&&!z&&!wn(A)&&(C&&await C.settle(c.requestId),O===f&&o===c&&(o=null,p=!1,U=null)),A}}function D(l){let c=ie.parse(l);if(c.operation==="start"||c.operation==="get"||c.operation==="review")throw new u("INVALID_REQUEST","Mutation required");if(t?.recoveryRestricted&&c.operation!=="close"&&c.operation!=="resume"&&o?.requestId!==c.requestId)throw new u("PRECONDITION_FAILED","Original Run requires restricted recovery");if(r&&c.operation!=="close"){if(o?.requestId===c.requestId)return X.settle(c.requestId);throw new u("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(c.operation==="close"&&o?.operation!=="close"){if(r=!0,s&&JSON.stringify(pe(s))!==JSON.stringify(pe(c)))throw new u("COMMAND_PENDING","Retry the original Close");if(s??=c,a)return a;let V=_(s);return a=V,V.then(()=>{a===V&&(a=null)},()=>{a===V&&(a=null)}),V}if(o){if(JSON.stringify(pe(o))!==JSON.stringify(pe(c)))throw new u("COMMAND_PENDING","Retry the original command before sending another");if(w)return w}else o=c,p=!1;let O=_();return w=O,O.then(()=>{w===O&&(w=null)},()=>{w===O&&(w=null)}),O}let L=null,G=new WeakMap;function J(l){let c=G.get(l);if(c)return c;let O=W(l);return G.set(l,O),O}let se=!1;async function W(l){let c=await l;if(c.run.recoveryRestricted||!["evaluate","evaluate_segment"].includes(c.run.instruction?.type??""))return c;if(L)return L;se=!0;let O=f,V=(async()=>{for(let z=0;z<32&&["evaluate","evaluate_segment"].includes(c.run.instruction?.type??"");z++){if(o||r)return c;let A=c.run,m=c.run.instruction;if(m?.type==="evaluate_segment"){let $=await on(e.configuration,A);if(O!==f)throw new u("IDENTITY_CHANGED","Run identity changed during segment calculation");if(o||r)return c;if(t&&(t.revision!==A.revision||t.visit!==A.visit||t.nodeId!==A.nodeId))return T({operation:"get",...i?{customerToken:i}:{}});c=await D({operation:"commit_segment",requestId:De(A.id,A.visit,`segment:${A.revision}`),nodeId:A.nodeId,visit:A.visit,revision:A.revision,...$});continue}if(m?.type!=="evaluate")return c;let ee=await rn(e.configuration,A);if(O!==f)throw new u("IDENTITY_CHANGED","Run identity changed during evaluation");if(o||r)return c;if(t&&(t.revision!==A.revision||t.visit!==A.visit||t.nodeId!==A.nodeId))return T({operation:"get",...i?{customerToken:i}:{}});c=await D({operation:"evaluate",requestId:De(A.id,A.visit,"evaluation"),nodeId:A.nodeId,visit:A.visit,revision:A.revision,receiptId:m.receiptId,policyRevision:m.policyRevision,...ee})}return c})();L=V;try{return await V}finally{L===V&&(L=null)}}let X={get configuration(){return se?e.configuration:void 0},get configurationReady(){return!0},get view(){return t?structuredClone(t):null},get pendingCommand(){let l=s??o;return l?structuredClone(pe(l)):null},get pendingCommands(){return[o,s].filter(l=>l!==null).map(l=>structuredClone(pe(l)))},get pendingPurchase(){return I?structuredClone(I):null},async settle(l){let c=await T({operation:"get",settlementRequestId:l,...i?{customerToken:i}:{}});if(c.settlement?.requestId!==l)throw new u("INVALID_RESPONSE","Exact command settlement is missing");return c.settlement.state==="settled"&&(C&&await C.settle(l),o?.requestId===l&&(o=null,p=!1),s?.requestId===l&&(s=null)),c},get webViewUrl(){return"bundled"},resolvePaywall(l){return be(e,l)},review(l){return T({operation:"review",...l?{receiptId:l}:{},...i?{customerToken:i}:{}},void 0,++v)},async get(l,c){C&&await F,c??=I&&{receiptId:I.receiptId,operationId:I.operationId};let O=++v;return J(T({operation:"get",...l?{data:l}:{},...c?{purchase:c}:{},...i?{customerToken:i}:{}},void 0,O))},resume(l=t?.pendingRequest?.requestId){return l?r?X.settle(l):o?.requestId===l?J(D(o)):J(D({operation:"resume",requestId:l})):Promise.reject(new u("INVALID_REQUEST","No interrupted command is available"))},submit(l){return J(D(l))},retry(){return a||(s?_(s):r&&o?X.settle(o.requestId):w?J(w):o?J(D(o)):Promise.reject(new u("INVALID_REQUEST","No command is pending")))},identify(l){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(l))throw new u("INVALID_TOKEN","Customer credential required");f++,i=l,n.identify(e.runToken)},subscribe(l){return P.add(l),()=>P.delete(l)},reset(){h=!0,f++,i=void 0,t=null,o=null,s=null,a=null,p=!1,w=null,n.reset(),P.clear()}};return X}async function ut(e,n){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(n.customerToken))throw new u("INVALID_TOKEN","A verified Customer credential is required");let i=Ie(e);i.identify(n.customerToken);let t=fe.resolvePaywall.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,selector:n.paywallVersionId?{type:"version",versionId:n.paywallVersionId}:{type:"paywall",paywallId:n.paywallId},commerce:n.commerce,locale:n.locale,...n.requirement?{requirement:n.requirement}:{}}),f=null,v=!1,o=null,s=null,r=null,a=null;async function p(){if(v)throw new u("IDENTITY_CHANGED","Paywall is closed");let S=fe.resolvePaywall,C=S.response.parse(await i.request(S.path,S.request.parse({...t,selector:f?{type:"version",versionId:f.id}:t.selector}))),I={paywall:await be(e,C.paywall)};if(v)throw new u("IDENTITY_CHANGED","Paywall is closed");if(n.paywallVersionId?I.paywall.id!==n.paywallVersionId:I.paywall.paywallId!==n.paywallId)throw new u("INVALID_RESPONSE","The requested Paywall changed");if(f&&(I.paywall.id!==f.id||I.paywall.paywallId!==f.paywallId||I.paywall.offering.id!==f.offering.id||I.paywall.content?.artifact.sha256!==f.content?.artifact.sha256))throw new u("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return f=I.paywall,structuredClone(f)}async function w(S){if(!o)throw new u("INVALID_REQUEST","A quoted purchase is required");let C=S==="read"?fe.readSubscriptionOperation:fe.attach,I=C.response.parse(await i.request(C.path,C.request.parse({operationId:o.operationId,...S==="read"?{}:{intent:S}})));if(I.operation.operationId!==o.operationId||I.operation.currency!==t.commerce.currency)throw new u("INVALID_RESPONSE","The purchase operation changed");return s?.status==="complete"&&I.operation.status!=="complete"||s&&s.status!=="pending"&&I.operation.status==="pending"||(s=I.operation),structuredClone(s)}let P={get view(){return f?structuredClone(f):null},get quote(){return o?structuredClone(o):null},get operation(){return s?structuredClone(s):null},get webViewUrl(){return"bundled"},refresh:p,async preview(S){if(!f)throw new u("INVALID_REQUEST","Load the Paywall first");let C=f.document.buttons[S.actionId];if(C?.type!=="checkout")throw new u("INVALID_REQUEST","Choose an authored purchase action");let I=Ue(C.product,S.selection,f.capabilities);if(!I)throw new u("PRODUCT_UNAVAILABLE","Choose an available Product");let U=fe.previewAttach.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,requestId:S.requestId,plans:[{productVersionId:I}],provider:t.commerce.provider,currency:t.commerce.currency,...S.offerId?{offerId:S.offerId}:{},...S.nativeOffer?{nativeOffer:S.nativeOffer}:{}}),h=JSON.stringify(U);if(r&&r!==h&&(!s||s.status==="pending"))throw new u("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(r===h){if(a)return a;if(o)return structuredClone(o)}r=h;let F=(async()=>{let T=fe.previewAttach,_=T.response.parse(await i.request(T.path,U));if(_.quote.currency!==t.commerce.currency||_.quote.provider!==t.commerce.provider||_.quote.lines.length!==1||_.quote.lines[0].productVersionId!==I)throw new u("INVALID_RESPONSE","The purchase quote changed its selected Product or presentment");return o=_.quote,s=null,structuredClone(o)})();a=F;try{return await F}finally{a===F&&(a=null)}},confirm:()=>w("confirm"),cancel:()=>w("cancel"),read:()=>w("read"),destroy(){v=!0,i.reset(),f=null,o=null,s=null,r=null}};return await p(),P}import{z as vn}from"zod";import{z as Ce}from"zod";var yn=Ce.record(Ce.string().regex(/^[a-f0-9]{64}$/),Ce.strictObject({at:Ce.number(),text:Ce.string()})),cn=2*1048576,In=100;function hn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function dn(e,n){let i=n===void 0?hn():n,t=Promise.resolve();async function f(o){if(!i)return null;let s;try{return await Promise.race([Promise.resolve().then(()=>i.getItem(o)),new Promise(r=>{s=setTimeout(()=>r(null),In)})])}catch{return null}finally{clearTimeout(s)}}async function v(){try{let o=await f(`${e}:artifacts`);if(o&&o.length<=cn)return yn.parse(JSON.parse(o))}catch{}return{}}return{async readManifest(){return f(e)},writeManifest(o){Promise.resolve().then(()=>i?.setItem(e,o)).catch(()=>{})},async readArtifact(o){let s=(await v())[o];return s&&Date.now()>=s.at&&Date.now()-s.at<=H.retentionMs?s.text:void 0},writeArtifact(o,s){i&&(t=t.catch(()=>{}).then(async()=>{let r=await v(),a=Date.now();r[o]={at:a,text:s};let p={},w=2,P=0;for(let[S,C]of Object.entries(r).sort(([,I],[,U])=>U.at-I.at)){if(C.at>a||a-C.at>H.retentionMs)continue;let I=new TextEncoder().encode(JSON.stringify({[S]:C})).byteLength;w+I>cn||P>=128||(p[S]=C,w+=I,P++)}await i.setItem(`${e}:artifacts`,JSON.stringify(p))}).catch(()=>{}))}}}var E=(e,n)=>new u(e,n),ae=()=>performance.now(),fn=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function It(e){let n=Je.parse(e.scope),i=new URL(e.origin??ye);if(i.username||i.password||i.search||i.hash||i.pathname!=="/"||i.protocol!=="https:"&&!(i.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(i.hostname)))throw E("INVALID_URL","Configuration requires a trusted HTTPS origin");let t=new Set([i.origin,...(e.assetOrigins??[]).map(g=>{let d=new URL(g);if(d.protocol!=="https:"||d.username||d.password||d.search||d.hash||d.pathname!=="/")throw E("INVALID_URL","Invalid configuration asset origin");return d.origin})]),f=e.fetch??globalThis.fetch.bind(globalThis),v=`/api/v1/configuration/${n.environmentId}`,o=`indiana:configuration:1:${i.origin}:${q(n)}`,s=dn(o,e.storage),r,a=0,p=0,w=!1,P=!1,S=0,C=0,I,U,h,F,T=0,_=new Set,D=new Set,L=new Map,G=new Map,J=0,se=!1;function W(){for(let g of _)try{g()}catch{}}function X(g){try{e.onError?.(g)}catch{}}let l=()=>!P&&!w&&!!r&&ae()<a&&Date.now()<p;function c(){if(!l())throw E("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function O(g,d){let R=new TextEncoder().encode(d).byteLength;if(!L.has(g)){for(;L.size&&(L.size>=128||J+R>H.maxCacheBytes);){let y=L.entries().next().value;J-=new TextEncoder().encode(y[1]).byteLength,L.delete(y[0])}L.set(g,d),J+=R}}async function V(g,d,R){if(Number(g.headers.get("content-length"))>d)throw E("INVALID_RESPONSE","Configuration exceeds its byte limit");let y=g.body?.getReader();if(!y)throw E("INVALID_RESPONSE","Configuration body is missing");let N=[],x=0;try{for(;;){R.throwIfAborted();let M=await y.read();if(M.done)break;if(x+=M.value.length,x>d)throw E("INVALID_RESPONSE","Configuration exceeds its byte limit");N.push(M.value)}}finally{await y.cancel().catch(()=>{})}R.throwIfAborted();let b=new Uint8Array(x),k=0;for(let M of N)b.set(M,k),k+=M.length;return new TextDecoder("utf-8",{fatal:!0}).decode(b)}function z(g){let d=new URL(g,i);if(!t.has(d.origin)||d.username||d.password||d.hash||d.search)throw E("INVALID_URL","Configuration artifact origin is not trusted");return d.href}async function A(g,d,R=!1){let y=await f(z(g),{method:"GET",credentials:"omit",redirect:"error",cache:R?"default":"no-cache",signal:d,headers:{}});if(y.status===429){let N=y.headers.get("retry-after")??"";T=/^\d+$/.test(N)?Number(N)*1e3:Math.max(0,Date.parse(N)-Date.now())||15e3}if(!y.ok&&y.status!==304)throw E(`CONFIGURATION_HTTP_${y.status}`,"Configuration synchronization failed");return y}function m(g,d,R){let y=Date.parse(g.headers.get("x-indiana-config-validated-at")??""),N=Date.parse(g.headers.get("x-indiana-config-valid-until")??""),x=Date.parse(g.headers.get("date")??""),b=g.headers.get("age"),k=b!==null&&/^\d+(\.\d+)?$/.test(b)?Number(b)*1e3:NaN;if(![y,N,x,k].every(Number.isFinite)||N<=y||N-y>H.maxControlAgeMs||y>x+1e3)throw E("INVALID_RESPONSE","Configuration freshness evidence is invalid");let j=Math.min(N-y,R.maxControlAgeSeconds*1e3,H.maxControlAgeMs)-Math.max(k,x-y,0)-(ae()-d);if(j<=0)throw E("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return ae()+j}function ee(){if(clearTimeout(h),clearTimeout(F),P||!_.size)return;l()&&(F=setTimeout(()=>{l()?ee():W()},Math.max(1,a-ae())),fn(F));let g=C?Math.min(15e3,1e3*2**Math.min(C-1,4)):Math.min(15e3,(r?.policy.refreshIntervalSeconds??15)*1e3);h=setTimeout(()=>{$().catch(X)},Math.max(T,g*(.8+Math.random()*.2))),fn(h)}async function $(){if(P)throw E("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(I)return I;let g=S,d=new AbortController;U=d;let R=(async()=>{if(!se){se=!0;try{let Se=await s.readManifest();if(Se&&!r){let Z=_e.parse(JSON.parse(Se));q(Z.scope)===q(n)&&(r=Z)}}catch{}}d.signal.throwIfAborted();let b=r,k=ae(),M=await A(v,d.signal);M.status===304&&(!b||!M.headers.has("x-indiana-config-validated-at")||!M.headers.has("x-indiana-config-valid-until")||!M.headers.has("age"))&&(M=await A(v,d.signal));let j=M.status===304?b:_e.parse(JSON.parse(await V(M,H.maxManifestBytes,d.signal))),{generation:Y,...oe}=j,ce=M.headers.get("etag");if(q(j.scope)!==q(n)||Be(oe)!==Y||ce!==`"${Y}"`&&ce!==`W/"${Y}"`)throw E("INVALID_RESPONSE","Configuration scope or content identity changed");if(b&&(j.revision<b.revision||j.revision===b.revision&&j.generation!==b.generation))throw E("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[Se,Z]of Object.entries(b?.funnels??{})){let de=j.funnels[Se];if(de&&(de.controlRevision<Z.controlRevision||de.evaluationRevision<Z.evaluationRevision||de.controlRevision===Z.controlRevision&&de.state!==Z.state||de.evaluationRevision===Z.evaluationRevision&&de.evaluationMode!==Z.evaluationMode))throw E("INVALID_RESPONSE","Funnel control revision changed identity")}let Le=m(M,k,j.policy);if(d.signal.throwIfAborted(),g!==S)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return r=j,a=Le,p=Date.now()+Math.max(0,Le-ae()),w=!1,C=0,T=0,s.writeManifest(q(j)),W(),structuredClone(j)})(),y=setTimeout(()=>d.abort(E("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),H.initializationMs),N=new Promise((b,k)=>d.signal.addEventListener("abort",()=>k(d.signal.reason),{once:!0})),x=Promise.race([R,N]).catch(b=>{throw C++,(b instanceof vn.ZodError||b instanceof SyntaxError||b instanceof u&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(b.code))&&(a=0,w=!0,W()),b}).finally(()=>{clearTimeout(y),I===x&&(I=void 0),ee()});return I=x,x}async function Q(g){let d=g.sha256,R=Y=>new TextEncoder().encode(Y).byteLength===g.byteLength&&Ae(Y)===d;z(g.url);let y=L.get(d);if(y&&R(y))return L.delete(d),L.set(d,y),y;if(G.has(d))return G.get(d);let N=new AbortController;D.add(N);let x=S,b=(async()=>{try{let ce=await s.readArtifact(d);if(ce&&R(ce))return O(d,ce),ce}catch{}N.signal.throwIfAborted();let Y=await A(g.url,N.signal,!0),oe=await V(Y,g.byteLength,N.signal);if(!R(oe))throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(P||x!==S)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return O(d,oe),s.writeArtifact(d,oe),oe})(),k=setTimeout(()=>N.abort(E("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),H.initializationMs),M=new Promise((Y,oe)=>N.signal.addEventListener("abort",()=>oe(N.signal.reason),{once:!0})),j=Promise.race([b,M]).finally(()=>{clearTimeout(k),D.delete(N),G.delete(d)});return G.set(d,j),j}async function ue(){return l()||await $(),c(),r}async function ne(g){let d,R=new Promise((y,N)=>{d=setTimeout(()=>N(E("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),H.initializationMs)});try{return await Promise.race([g(),R])}finally{clearTimeout(d)}}function te(g,d){if(c(),r?.generation!==g.generation)throw E("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(d&&r.funnels[d]?.state!=="active")throw E("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function ve(g){let d=g.gb.features;if(!d)throw E("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let R=g.artifacts[d];if(R.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let y=qe.parse(JSON.parse(await Q(R)));if(q(y.scope)!==q({projectId:n.projectId,environment:n.environment})||y.generation!==R.generation||y.remoteFeatures.some(N=>Object.hasOwn(y.features,N)))throw E("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return te(g),{...y,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,a-ae())).toISOString()}}async function Re(g,d){let R=await ue();te(R,g);let y=R.funnels[g];if(y.evaluationMode!=="local")throw E("EVALUATION_MODE","This Funnel executes at Indiana; public graph loading is disabled");let N=d??y.currentVersionId,x=y.versions[N];if(!x)throw E("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(R.artifacts[x.artifact].formatVersion!==3)throw E("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[b,k]=await Promise.all([Q(R.artifacts[x.artifact]).then(M=>He(JSON.parse(M))),y.evaluationMode==="local"?ve(R):void 0]);if(k&&q(ze(b,k))!==q(x.dependencies))throw E("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return te(R,g),{document:b,growth:k,versionId:N,control:structuredClone(y),manifest:structuredClone(R)}}function re(){w=!0,W(),$().catch(X)}let ge=()=>{(typeof document>"u"||document.visibilityState==="visible")&&re()};function le(g){if(P)throw E("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return _.add(g),_.size===1&&(typeof window<"u"&&(window.addEventListener("online",re),window.addEventListener("focus",ge),document.addEventListener("visibilitychange",ge)),ee()),()=>{_.delete(g),_.size||(clearTimeout(h),clearTimeout(F),Ee())}}function Ee(){typeof window<"u"&&(window.removeEventListener("online",re),window.removeEventListener("focus",ge),document.removeEventListener("visibilitychange",ge))}return{scope:Object.freeze({...n}),refresh:$,subscribe:le,assertFresh:c,assertFeatures(g){c();let d=r.gb.features;if(!d)throw E("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(g!==void 0&&r.artifacts[d].generation!==g)throw E("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return l()},get snapshot(){return r?structuredClone(r):null},get remainingMs(){return l()?Math.max(0,a-ae()):0},async features(){return ne(async()=>ve(await ue()))},pageExperiments:()=>ne(async()=>{let g=await ue(),d=g.gb.pageExperiments;if(!d)throw E("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let R=g.artifacts[d];if(R.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let y=Ze.parse(JSON.parse(await Q(R)));if(y.environmentId!==n.environmentId||y.generation!==R.generation)throw E("INVALID_RESPONSE","Page experiment scope or generation changed");return te(g),y}),funnel:(g,d)=>ne(()=>Re(g,d)),paywall:(g,d)=>ne(async()=>{let R=await ue(),y=R.paywalls?.[g];if(!y||!d&&y.state!=="published")throw E("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let N=d??y.currentVersionId,x=y.versions[N],b=x&&R.artifacts[x.artifact];if(!b||b.kind!=="paywall"||b.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let k=je.parse(JSON.parse(await Q(b)));return te(R),{document:k,versionId:N,version:x.version,control:structuredClone(y),manifest:structuredClone(R)}}),async localFunnel(g,d){let R=await ne(()=>Re(g,d));if(!R.growth)throw E("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:y,remoteFeatures:N,...x}=R.growth;return Ye({scope:{projectId:n.projectId,environment:n.environment},funnelId:g,versionId:R.versionId,evaluationMode:"local",evaluationRevision:R.control.evaluationRevision,document:R.document,payload:x})},assertFunnel(g,d,R){c();let y=r.funnels[g];if(!y||y.state!=="active")throw E("FUNNEL_STOPPED","Funnel is paused or unavailable");if(y.evaluationMode!=="local")throw E("EVALUATION_MODE","This Funnel now executes at Indiana");if(d!==void 0&&y.controlRevision!==d)throw E("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(R!==void 0&&!y.versions[R])throw E("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!P){P=!0,S++,a=0,U?.abort(E("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(h),clearTimeout(F),Ee(),W(),_.clear();for(let g of D)g.abort(E("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));L.clear(),J=0}}}}function Et(e,n,i){return Xe(e,n,i,me)}function mn(e){let n=/^gg_ct_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey);if(typeof window<"u"&&!n)throw new u("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.apiKey))throw new u("INVALID_TOKEN","A customer credential or server API key is required");let i=Ie({...e,timeoutMs:e.timeoutMs??35e3});return i.identify(e.apiKey),{async start(t){let f=ie.safeParse({...t,operation:"start"});if(!f.success||f.data.operation!=="start"||(n?f.data.customer!==void 0:f.data.customer===void 0))throw new u("INVALID_REQUEST","Invalid current Funnel start");let v=f.data,o=Pe.safeParse(await Fe(e,await i.request("funnels",v)));if(!o.success||!o.data.runToken)throw new u("INVALID_RESPONSE","Funnel start credentials are missing");let s=o.data;if(s.run.source.id!==v.funnelId||s.run.locale!==(v.locale??"en")||!he(s.run.parameters,v.parameters??{})||(v.customer?!s.customerId||v.customer.type==="id"&&s.customerId!==v.customer.value:s.customerId!==void 0))throw new u("INVALID_RESPONSE","Funnel start contract changed");return{...s,runToken:s.runToken}}}}async function Dt(e){e={...e};let n=e.configuration;if(!n)throw new u("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let i={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&q(i)!==q(e.scope))throw new u("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnel(e.funnelId)).control.evaluationMode!=="local")throw new u("EVALUATION_MODE","This Funnel uses Remote evaluation");let f=/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(e.credential);if(f?!e.customerId:e.customerId!==void 0)throw new u("INVALID_REQUEST","Only Server-Key starts name their Customer");let v=mn({...e,scope:i,apiKey:e.credential}),o=s=>{let r=ln({...e,scope:i,runToken:s,...f?{serverKey:e.credential}:{}});return f||r.identify(e.credential),r};return{async start(s){let r=await v.start({...s,funnelId:e.funnelId,...f?{customer:{type:"id",value:e.customerId}}:{}}),a=o(r.runToken),p=await a.get();return{...r,...p,controller:a}},async restore(s){let r=o(s),a=await r.get();if(a.run.source.id!==e.funnelId)throw r.reset(),new u("SCOPE_MISMATCH","Run belongs to another Funnel");return{...a,runToken:s,controller:r}}}}export{En as a,Tn as b,he as c,Fe as d,xn as e,pn as f,gn as g,tn as h,ln as i,ut as j,It as k,Et as l,mn as m,Dt as n};
@@ -1 +0,0 @@
1
- import{kb as T,lb as C,ob as E}from"./chunk-467Z5ISI.js";import{b as I}from"./chunk-3SONNXFG.js";import{a as k}from"./chunk-S5TVMQRC.js";import{a as t}from"./chunk-6MO6Y24B.js";import{E as N,H as D,K as O,v as A}from"./chunk-HD74AAFS.js";var _={name:"@tinkerlandai/indiana-sdk",version:"0.7.0",description:"Framework-independent Indiana 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"},"./iam":{types:"./dist/iam.d.ts",import:"./dist/iam.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/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.5"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@rrweb/types":"2.1.7","@types/css-tree":"^3.2.0",ai:"7.0.136","rrweb-snapshot":"2.1.7",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}}};var F=Symbol("IndianaNoContent");function J(d,j,P=URL){let a=d.scope?I.parse(d.scope):void 0,o=new P(d.baseUrl??k);if(o.username||o.password||o.search||o.hash)throw new t("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 t("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let L=d.fetch??globalThis.fetch.bind(globalThis),p=d.timeoutMs??1e4;if(!Number.isFinite(p)||p<=0||p>12e4)throw new t("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let u=null,c=0,l=null,m=new Set;function b(){c+=1,u=null,l=null;for(let i of m)i.abort();m.clear()}async function M(i,U={},v="POST",H={}){if(!u)throw new t("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let g=c,n=new AbortController;m.add(n);let f=()=>g!==c?new t("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new t("TIMEOUT","Indiana request timed out"),y,q=new Promise((r,s)=>{y=()=>s(f()),n.signal.addEventListener("abort",y,{once:!0})}),K=setTimeout(()=>n.abort(),p),x=async()=>{let r=await L(`${o.href.replace(/\/$/,"")}/api/v1/${i}`,{method:v,headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`,[T]:E.current,[C]:_.version,...a?{"X-Indiana-Project":a.projectId,"X-Indiana-Environment":a.environment}:{}},body:v==="POST"?JSON.stringify(U):void 0,signal:n.signal,credentials:"omit",cache:"no-store",redirect:"error",...H.keepalive?{keepalive:!0}:{}});if(n.signal.aborted)throw f();let s;try{s=r.status===204?F:await r.json()}catch{throw n.signal.aborted?f():new t(r.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",r.status,r.headers.get("X-Request-Id")??void 0)}if(n.signal.aborted)throw f();if(g!==c)throw new t("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!r.ok){let e=D.safeParse(s),w=e.success&&(!A.safeParse(e.data.error.code).success||N(e.data.error.code,r.status)),S=w?e.data.error.code:"HTTP_ERROR",R=O(S,r.status,{retryAfter:r.headers.get("Retry-After"),recovery:w?e.data.error.recovery:void 0,reason:w?e.data.error.reason:void 0});throw new t(S,w?e.data.error.message:"Indiana request failed",r.status,r.headers.get("X-Request-Id")??(e.success?e.data.requestId:void 0),{...R,...e.success&&e.data.error.retryable===!1?{retryable:!1}:{},...R.retryAfterSeconds===void 0&&e.success&&e.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:e.data.error.retryAfterSeconds}:{}})}if(r.headers.get(T)!==E.current)throw new t("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&s&&typeof s=="object"&&"scope"in s){let e=I.safeParse(s.scope);if(!e.success||e.data.projectId!==a.projectId||e.data.environment!==a.environment)throw new t("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let h=r.headers.get("X-Indiana-Telemetry-Subject");if(h){if(!/^[a-f0-9]{64}$/.test(h))throw new t("INVALID_RESPONSE","Invalid telemetry identity");l!==h&&(l=h,j?.(l))}return s};try{return await Promise.race([x(),q])}catch(r){throw g!==c?new t("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):r instanceof t?r:new t(n.signal.aborted?"TIMEOUT":"NETWORK_ERROR",n.signal.aborted?"Indiana request timed out":"Unable to read the Indiana response")}finally{clearTimeout(K),n.signal.removeEventListener("abort",y),m.delete(n)}}return{subjectKey:()=>l,identify(i){if(!i.trim()||/\s/.test(i)||i.length>4096)throw new t("INVALID_TOKEN","A nonempty server-issued token is required");b(),u=i},reset:b,request:M}}export{J as a};
@@ -1 +0,0 @@
1
- import{a as z}from"./chunk-4K25DELJ.js";var W=new Set(["script","noscript","iframe","object","embed","base","link","meta","canvas","video","audio","source","track"]),M='[data-indiana-private],[data-private],input,textarea,select,[contenteditable]:not([contenteditable="false"])',R=/password|passwd|secret|token|authorization|api.?key|email|phone|ssn|card.?number/i,b=e=>e.replace(/\b([a-z][a-z0-9+.-]*:\/\/)[^\s/?#]*@/gi,"$1[redacted-credentials]@").replace(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi,"[redacted]").replace(/\b(?:sk_(?:live|test)_\w{12,}|gh[pousr]_\w{16,}|eyJ[\w-]{8,}\.[\w-]{8,}\.[\w-]+)\b/g,"[redacted]").replace(/\bBearer\s+[\w.~+/=-]{12,}/gi,"[redacted]"),y=e=>/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}|\d{7,}|[a-f0-9]{32,}/i.test(e)||b(e)!==e;function O(e,i){let r=e;for(let s=0;r&&s<=80;s++){if(r.closest(i))return!0;let n=r.getRootNode();if(!("host"in n))return!1;r=n.host}return!0}function D(e,i){return!!(O(e,[M,...i.blockedSelectors].join(","))||e.matches("input,textarea,select")&&R.test(e.getAttribute("name")||e.id))}function K(e,i,r){return!i||D(i,r)||!r.publicSelectors.some(s=>i.closest(s))?e.replace(/\S/g,"\u2022"):b(e)}function Z(e,i){let r={};for(let s of e.getAttributeNames()){let n=s.toLowerCase(),a=e.getAttribute(s);if(a!==null&&/^(?:class|id|role|type|dir|lang|hidden|open|disabled|checked|width|height|viewbox|preserveaspectratio|transform|opacity|fill-opacity|stroke-opacity|stroke-dasharray|stroke-dashoffset|stroke-miterlimit|clip-path|gradientunits|gradienttransform|spreadmethod|offset|stop-color|stop-opacity|fx|fy|fr|d|fill|fill-rule|clip-rule|stroke|stroke-width|stroke-linecap|stroke-linejoin|cx|cy|r|rx|ry|x|y|x1|x2|y1|y2|points|data-indiana-id|data-indiana-public|data-indiana-private|data-(?:state|side|align|orientation|disabled|highlighted|slot|variant|size)|aria-(?:hidden|expanded|selected|checked|disabled|modal|busy|invalid|required))$/.test(n)&&!(b(a)!==a||R.test(a)&&n==="id")){if(/(?:[a-z][a-z0-9+.-]*:\/\/|\b(?:data|blob):|url\s*\()/i.test(a)){let t=/^(?:fill|stroke|clip-path)$/.test(n)&&/^url\(\s*["']?#([\w:-]{1,160})["']?\s*\)$/i.exec(a);t&&t[1]!==void 0&&!y(t[1])&&(r[n]=a);continue}{if(n==="data-indiana-id"&&!i?.sourceAnchors.includes(a)||n==="id"&&(y(a)||!/^[\w:-]{1,160}$/.test(a)))continue;if(n==="class"){let t=a.split(/\s+/).filter(d=>d&&!y(d));t.length&&(r[n]=t.join(" "));continue}}if(n==="data-indiana-public"||n==="data-indiana-private"){r[n]="";continue}if(/^data-(?:slot|variant|size)$/.test(n)){/^[a-z][a-z0-9-]{0,63}$/.test(a)&&!y(a)&&(r[n]=a);continue}n.startsWith("data-")&&n!=="data-indiana-id"&&!/^(?:open|closed|checked|unchecked|on|off|active|inactive|top|bottom|left|right|start|center|end|horizontal|vertical|true|false|)$/.test(a)||(r[n]=a)}}return e.hasAttribute("style")&&(r.style=e.getAttribute("style")||""),e.tagName==="INPUT"&&["checkbox","radio"].includes(e.type)&&(e.checked?r.checked="":delete r.checked),e.tagName==="DIALOG"&&e.open&&(r.open=""),r}function V(e){let i=new Map,r=new Map,s=0,n=0,a=0;for(let t of e){if(i.has(t.id)||Object.keys(t.attributes).length>40)throw Error("Invalid capture tree");if(t.parentId===null){if(++s>1||t.kind!=="element"||t.tag!=="html")throw Error("Invalid capture root");i.set(t.id,0)}else{let d=i.get(t.parentId),u=r.get(t.parentId);if(d===void 0||d>=80||u?.kind!=="element")throw Error("Invalid capture depth");i.set(t.id,d+1)}if(t.shadow&&(t.parentId===null||t.tag==="html"||t.tag==="body"||t.tag==="head"))throw Error("Invalid shadow root");if(t.tag==="html"&&t.parentId!==null)throw Error("Nested document");if((t.tag==="head"||t.tag==="body")&&(r.get(t.parentId)?.tag!=="html"||(t.tag==="head"?++n:++a)>1))throw Error("Invalid document structure");if(t.kind==="element"&&(!t.tag||t.text!==null)||t.kind==="text"&&(t.tag!==null||t.text===null||Object.keys(t.attributes).length))throw Error("Invalid capture node");r.set(t.id,t)}if(s!==1||a!==1)throw Error("Missing capture root/body")}import{array as f,boolean as B,discriminatedUnion as N,enum as U,literal as l,number as c,record as j,string as p,url as $,uuid as g}from"zod";import{refine as P,strictObject as o}from"zod/mini";function Q(e,i,r){try{let s=new URL(i).origin,n=new URL(e,i);if(n.origin!==s||n.username||n.password||n.hash)return null;if(!n.search)return r.includes(n.pathname)?n.pathname:null;if(n.pathname!=="/_next/image")return null;let a=[...n.searchParams];if(a.length!==3||new Set(a.map(([x])=>x)).size!==3||a.some(([x])=>!["url","w","q"].includes(x)))return null;let t=n.searchParams.get("w"),d=n.searchParams.get("q");if(!/^[1-9]\d{0,4}$/.test(t)||Number(t)>8192||!/^[1-9]\d?$|^100$/.test(d))return null;let u=n.searchParams.get("url");if(!u.startsWith("/")||u.startsWith("//")||u.includes("\\")||/[\u0000-\u0020]/.test(u))return null;let m=new URL(u,s);return m.origin!==s||m.search||m.hash||m.pathname==="/_next/image"?null:r.includes(m.pathname)?m.pathname:null}catch{return null}}var h=p().regex(/^[a-f0-9]{64}$/),v=p().min(1).max(256),q=p().regex(/^[\p{L}\p{N} _.-]{1,64}$/u).refine(e=>b(e)===e&&!y(e),"Use a public state label");var S=Object.freeze({maxNodes:5e3,maxDepth:80,maxAttributes:40,maxText:4096,maxBytes:2097152,maxCssBytes:524288,maxStyleSheets:256,maxCssRules:5e3,sliceMs:1,maxSliceMs:8,deadlineMs:3e3,quietMs:300,minIntervalMs:1e3,maxSnapshots:10,urgentIntervalMs:250,maxBufferedSnapshots:2}),F=o({pageKey:v,path:p().startsWith("/").max(2048)}),w=p().regex(/^(?:#[A-Za-z][\w-]{0,80}|\.[A-Za-z][\w-]{0,80}|\[data-indiana-(?:public|private)\])$/),L=o({environmentId:g(),privacy:l("masked-default-v2"),sourceAnchors:f(p().min(1).max(256)).max(1e3).default([]),sourceVersionId:g(),manifestDigest:h,origin:$(),routes:f(F).min(1).max(200),publicSelectors:f(w).max(8),blockedSelectors:f(w).max(8),assetPaths:f(p().startsWith("/").max(2048)).max(128)}),re=o({policy:L.check(P(e=>e.privacy==="masked-default-v2"&&!!e.environmentId)),expiresAt:c().int().positive(),serverTime:c().int().positive(),progress:o({sequence:c().int().min(0).max(10),lastContentHash:h.nullable(),readyCount:c().int().min(0).max(10)}).check(P(e=>e.readyCount<=e.sequence))}),ae=N("ready",[o({versionId:g(),ready:l(!0),upload:l(null)}),o({versionId:g(),ready:l(!1),upload:o({mode:l("proxy")})})]),ie=o({versionId:g(),ready:l(!0)}),H=o({id:c().int().nonnegative().max(5e3),parentId:c().int().nonnegative().max(5e3).nullable(),kind:U(["element","text"]),tag:p().regex(/^[a-z][a-z0-9-]*$/).max(64).nullable(),text:p().max(4096).nullable(),attributes:j(p().max(100),p().max(4096)),shadow:B()}),J=o({nodes:f(H).min(1).max(S.maxNodes),css:p().max(S.maxCssBytes),shadowCss:f(o({hostId:c().int().nonnegative().max(5e3),css:p().max(S.maxCssBytes)})).max(128),scroll:o({x:c().finite().nonnegative().max(1e7),y:c().finite().nonnegative().max(1e7)})}),oe=o({format:l("indiana-runtime-snapshot"),schemaVersion:l(1),collector:o({name:l("indiana-bounded-dom"),version:l(2),buildSha256:h.optional()}),sourceVersionId:g(),manifestDigest:h,pageKey:v,routeTemplate:p().startsWith("/").max(2048),sequence:c().int().min(1).max(10),label:q,viewport:o({width:c().int().min(100).max(8192),height:c().int().min(100).max(8192),dpr:c().finite().min(.1).max(10)}),privacy:l("masked-default-v2"),contentHash:h,previousContentHash:h.nullable(),document:J,gaps:f(p().regex(/^[A-Z_]{1,80}$/)).max(32),metrics:o({maxSliceMs:c().finite().nonnegative(),totalWorkMs:c().finite().nonnegative(),elapsedMs:c().finite().nonnegative()})});function se(e){let{sourceVersionId:i,manifestDigest:r,pageKey:s,viewport:n,document:a,privacy:t}=e;return{sourceVersionId:i,manifestDigest:r,pageKey:s,viewport:n,document:a,privacy:t}}function E(e){if(e===null||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="string"){if(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(e))throw Error("Invalid Unicode");return JSON.stringify(e)}if(typeof e=="number"&&Number.isFinite(e))return JSON.stringify(e);if(Array.isArray(e))return"["+e.map(E).join(",")+"]";if(e&&typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype)return"{"+Object.keys(e).sort().map(i=>JSON.stringify(i)+":"+E(e[i])).join(",")+"}";throw Error("Invalid capture JSON")}function ce(e,i){let r=i.replace(/\/$/,"").split("/").filter(Boolean),s=[];for(let t of e){let d=t.path.replace(/\/$/,"").split("/").filter(Boolean),u=[],m=0,x=!0;for(let[_,k]of d.entries()){let I=/^\[\[\.\.\.[^\[\]]+\]\]$/.test(k),T=I||/^\[\.\.\.[^\[\]]+\]$/.test(k),A=/^\[[^\[\]]+\]$/.test(k);if(T){(_!==d.length-1||!I&&m===r.length)&&(x=!1),m=r.length,u.push(I?0:1);break}let C=r[m++];if(C===void 0){x=!1;break}try{!A&&decodeURIComponent(k)!==decodeURIComponent(C)&&(x=!1),decodeURIComponent(C)}catch{x=!1}u.push(A?2:3)}x&&m===r.length&&s.push({route:t,rank:u})}s.sort((t,d)=>{for(let u=0;u<Math.max(t.rank.length,d.rank.length);u++){let m=(d.rank[u]??4)-(t.rank[u]??4);if(m)return m}return 0});let[n,a]=s;if(n&&a&&JSON.stringify(n.rank)===JSON.stringify(a.rank))throw Error("Ambiguous capture route");return n?.route??null}var ue=N("action",[o({action:l("authorize")}),o({action:l("policy")}),o({action:l("register"),requestId:g(),sha256:h,bytes:c().int().min(1).max(S.maxBytes),pageKey:v,sequence:c().int().min(1).max(10),contentHash:h}),o({action:l("complete"),versionId:g()})]),le=o({action:l("capture-grant"),versionId:g(),origin:$().refine(z,"Capture requires HTTPS or loopback HTTP"),routeKeys:f(v).min(1).max(20),publicSelectors:f(w).max(8),blockedSelectors:f(w).max(8)}),pe=o({versionId:g(),sha256:h,contentHash:h});export{Q as a,W as b,b as c,y as d,O as e,D as f,K as g,Z as h,V as i,q as j,S as k,re as l,ae as m,ie as n,se as o,E as p,ce as q,pe as r};
@@ -1 +0,0 @@
1
- async function g(e,l,o,h={}){let a=h.message??"Invalid SDK JSON response",c=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||c!==null&&(!/^\d+$/.test(c)||Number(c)>l)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(a);let s=e.body.getReader(),u=[],i=0,b=!1,r=()=>{},f=new Promise((d,n)=>{r=()=>n(Error(a)),o.addEventListener("abort",r,{once:!0}),o.aborted&&r()});try{for(;;){let t=await Promise.race([s.read(),f]);if(t.done){b=!0;break}if(i+=t.value.byteLength,i>l)throw Error(a);u.push(t.value)}let d=new Uint8Array(i),n=0;for(let t of u)d.set(t,n),n+=t.length;return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(d))}finally{o.removeEventListener("abort",r),b||s.cancel().catch(()=>{}),s.releaseLock()}}export{g as a};
@@ -1 +0,0 @@
1
- import{a as Fe}from"./chunk-WCFVNF5D.js";import{a as Ue,b as ve,c as Pe,d as ce,e as Le,f as pe,g as De,h as Me,i as xe,j as he,k as S,l as ke,m as Be,n as He,o as Ve,p as Ge,q as Ye}from"./chunk-U6S6AZM6.js";import{a as Ce,b as se,c as ie}from"./chunk-4K25DELJ.js";function me(c){return c.nodeType===1&&c.hasAttribute("data-indiana-capture-controls")&&c.hasAttribute("data-indiana-private")}async function Se(c,l){let o=[];async function e(a){if(a===null||typeof a!="object"){o.push(Ge(a));return}let _=Array.isArray(a),U=_?Object.keys(a):Object.keys(a).sort();o.push(_?"[":"{");for(let y=0;y<U.length;y++)y&&o.push(","),_||o.push(JSON.stringify(U[y]),":"),await e(a[U[y]]),await l();o.push(_?"]":"}")}return await e(c),o.join("")}async function We(c,l,o){if(!Number.isSafeInteger(l)||l<0)throw new RangeError("Invalid byte limit");if(c.length>l)return null;let e=new TextEncoder,a=[],_=0;for(let f=0;f<c.length;){let r=Math.min(c.length,f+4096),T=c.charCodeAt(r-1),h=c.charCodeAt(r);r<c.length&&T>=55296&&T<=56319&&h>=56320&&h<=57343&&r--;let D=e.encode(c.slice(f,r));if(_+=D.byteLength,_>l)return null;a.push(D),f=r,await o()}let U=new Uint8Array(_),y=0;for(let f of a)U.set(f,y),y+=f.byteLength,await o();return U}import{default as qe}from"css-tree/parser";import{default as J}from"css-tree/walker";import{default as Ee}from"css-tree/generator";function we(c,l=[],o=!1,e="https://iam.invalid/",a="masked-default-v2",_=new URL(e).origin){if(a!=="masked-default-v2")throw Error("Unsupported capture privacy");if(c.length>524288||/<\/(?:style|script)/i.test(c))throw Error("CSS budget or boundary");let U=new Set,y=new Set(l),f=qe(c,{context:o?"declarationList":"stylesheet",parseCustomProperty:!0,onParseError:()=>{U.add("CSS_SYNTAX_RECOVERED")}});return J(f,function(r,T,h){if((r.type==="Rule"||r.type==="Atrule")&&r.prelude){let D=Ee(r.prelude);if(ce(D)||Pe(D)!==D)return T&&h&&h.remove(T),U.add("CSS_PRIVATE_SELECTOR_OMITTED"),J.skip}}),J(f,{visit:"Atrule",enter(r,T,h){if(["import","namespace","charset"].includes(r.name.toLowerCase()))return T&&h&&h.remove(T),U.add("CSS_EXTERNAL_RULE_OMITTED"),J.skip}}),J(f,{visit:"Declaration",enter(r,T,h){if(/^(?:content|-moz-binding|behavior)$/i.test(r.property))return T&&h&&h.remove(T),U.add("CSS_CONTENT_OMITTED"),J.skip;let D=Ee(r.value),k=!1;if(k=/(?:password|secret|token|email|phone|(?:user|customer|session|account|tenant)[_-]?id)/i.test(r.property),J(r.value,u=>{(u.type==="Identifier"&&ce(u.name)||(u.type==="String"||u.type==="Hash")&&ce(u.value)||u.type==="Dimension"&&ce(u.unit))&&(k=!0)}),/(?:[\w.%+-]+@[\w.-]+\.[a-z]{2,}|sk_(?:live|test)_\w{12,}|\bBearer\s+|eyJ[\w-]+\.[\w-]+\.)/i.test(D)||k)return T&&h&&h.remove(T),U.add("CSS_PRIVATE_VALUE_OMITTED"),J.skip}}),J(f,r=>{if(r.type==="Raw")throw Error("Unparsed CSS cannot be captured");if(r.type==="Url"){let T="";try{let h=new URL(r.value,e);h.origin===_&&!h.search&&!h.hash&&!h.username&&!h.password&&(T=h.pathname)}catch{}y.has(T)?r.value=T:(r.value="",U.add("CSS_RESOURCE_OMITTED"))}}),{css:Ee(f),gaps:[...U]}}async function Ke(c,l,o,e,a,_,U,y){let f=new Set,r=(u,v=!1)=>{if(u.length>8192)throw Error("Atomic CSS budget");let g=we(u,l.assetPaths,v,o,l.privacy,l.origin);return g.gaps.forEach(p=>a.add(p)),g.css};function T(u){let v;try{v=r(u+(u.startsWith("@keyframes ")?"{from{opacity:1}}":u.startsWith("@")?"{.iam-capture-probe{opacity:1}}":"{opacity:1}"))}catch(p){if(p instanceof Error&&p.message==="Unparsed CSS cannot be captured")return a.add("CSS_SELECTOR_UNSUPPORTED"),"";throw p}let g=v.indexOf("{");return g<0?"":v.slice(0,g+1)}async function h(u){if(u.length>512)throw Error("Atomic CSS budget");let v=0,g=!1,p=[];for(let n=0;n<u.length;n++){await _();let d=u[n],R=u.getPropertyValue(d),C=u.getPropertyPriority(d);if(v+=d.length+R.length+C.length+3,v>8192)throw Error("Atomic CSS budget");p.push({property:d,value:R,priority:C})}if(p.some(n=>n.value==="")){let n=r(u.cssText,!0);return n&&e(n),await _(),!!n}for(let{property:n,value:d,priority:R}of p){await _(),y.cssText="",y.setProperty(n,d,R);let C=r(y.cssText,!0);C&&(g&&e(";"),e(C),g=!0),await _()}return g}async function D(u,v){if(v>20)throw Error("CSS nesting budget");for(let g of u){if(await _(),++U.count>S.maxCssRules)throw Error("CSS rule budget");let p=g.constructor.name;if(p==="CSSImportRule"){let n=g;if(!n.styleSheet){a.add("CSS_EXTERNAL_RULE_OMITTED");continue}let d=n,R=[d.layerName!==null&&d.layerName!==void 0?"@layer "+d.layerName:null,d.supportsText?"@supports "+d.supportsText:null,n.media?.mediaText?"@media "+n.media.mediaText:null].filter(G=>G!==null),C=R.map(T);if(C.some(G=>!G)){a.add("CSS_GROUP_UNSUPPORTED");continue}C.forEach(e),await k(n.styleSheet,v+1),C.forEach(()=>e("}"))}else if(p==="CSSKeyframesRule"){let n=g,d=T("@keyframes "+n.name);if(!d){a.add("CSS_GROUP_UNSUPPORTED");continue}e(d);for(let R of n.cssRules){if(++U.count>S.maxCssRules)throw Error("CSS rule budget");let C=R,G=C.keyText.replace(/\s/g,"");if(!/^(?:(?:from|to|\d+(?:\.\d+)?%)(?:,|$))+$/.test(G)){a.add("CSS_GROUP_UNSUPPORTED");continue}e(G+"{"),await h(C.style),e("}"),await _()}e("}")}else{let n=g,d="cssRules"in g?n.cssRules:null,R=null;if(p==="CSSLayerBlockRule"?R="@layer "+(n.name??""):p==="CSSMediaRule"?R="@media "+n.conditionText:p==="CSSSupportsRule"?R="@supports "+n.conditionText:p==="CSSContainerRule"?R="@container "+n.conditionText:p==="CSSStartingStyleRule"?R="@starting-style":p==="CSSStyleRule"&&(R=n.selectorText??null),R!==null&&(d||p==="CSSStyleRule")){let C=T(R);if(!C){a.add("CSS_GROUP_UNSUPPORTED");continue}e(C),p==="CSSStyleRule"&&n.style&&await h(n.style)&&d?.length&&e(";"),d&&await D(d,v+1),e("}")}else if(d?.length)a.add("CSS_GROUP_UNSUPPORTED");else{let C=g.cssText;if(C.length>32768)throw Error("Atomic CSS budget");e(r(C))}}await _()}}async function k(u,v){if(u.disabled){a.add("DISABLED_STYLESHEET_OMITTED");return}if(f.has(u)){a.add("CSS_IMPORT_CYCLE");return}let g;try{g=u.cssRules}catch{a.add("CROSS_ORIGIN_STYLESHEET");return}f.add(u);let p=o;o=u.href||o;try{let n=u.media?.mediaText,d=n&&n!=="all"?T("@media "+n):"";if(n&&n!=="all"&&!d){a.add("CSS_GROUP_UNSUPPORTED");return}d&&e(d),await D(g,v),d&&e("}")}finally{o=p,f.delete(u)}}await k(c,0)}var i=class extends Error{constructor(o,e){super(o);this.code=o;this.metrics=e}code;metrics},z=()=>performance.now(),je=new URL(import.meta.url).pathname.match(/^\/web-view\/visual-sdk\/([a-f0-9]{64})\//)?.[1],nt=async c=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",c))].map(l=>l.toString(16).padStart(2,"0")).join("");async function Je(c){let{document:l,policy:o,signal:e}=c,a=l.defaultView;if(!he.safeParse(c.label).success)throw new i("PRIVATE_OR_INVALID_LABEL");if(!a||l.hidden||a.location.origin!==o.origin||!l.documentElement.getAttribute("data-indiana-release")?.split(/\s+/).includes(o.manifestDigest))throw new i("SCOPE_OR_VISIBILITY");let _=Ye(o.routes,a.location.pathname);if(!_)throw new i("ROUTE_NOT_ALLOWED");for(let P of[...o.publicSelectors,...o.blockedSelectors])l.querySelector(P);let U=a.location.href,y=z(),f=new Set,r=[],T=[],h=z(),D=0,k=0,u=0,v=0,g="dom",p=()=>{if(e.throwIfAborted(),l.hidden||c.changed()||a.location.origin!==o.origin||a.location.href!==U||!l.documentElement.getAttribute("data-indiana-release")?.split(/\s+/).includes(o.manifestDigest))throw new i("UNSTABLE");if(z()-y>S.deadlineMs)throw new i("DEADLINE")};async function n(P=!1){let M=z()-h;if(!(!P&&M<S.sliceMs)){if(D=Math.max(D,M),k+=M,M>S.maxSliceMs)throw new i("SLICE_BUDGET",{maxSliceMs:D,totalWorkMs:k,elapsedMs:z()-y,phase:g});p(),await new Promise((V,ne)=>{let X=()=>{clearTimeout(re),ne(new i("ABORTED"))},re=setTimeout(()=>{e.removeEventListener("abort",X),V()},0);e.addEventListener("abort",X,{once:!0})}),h=z(),p()}}let d=[{node:l.documentElement,parent:null,depth:0,shadow:!1}],R=[],C=new Map,G=new WeakMap,$=new Map,B=new Map,Q=[],ee=l.adoptedStyleSheets??[];if(l.styleSheets.length+ee.length>S.maxStyleSheets)throw new i("STYLESHEET_BUDGET");function Y(P,M){let V=B.get(M);if(!V?.has(P)){if(R.length>=S.maxStyleSheets)throw new i("STYLESHEET_BUDGET");V||(V=new Set,B.set(M,V)),V.add(P),R.push({sheet:P,hostId:M})}}try{for(;d.length;){await n(),p();let b=d.pop(),E=b.node;if(r.length>=S.maxNodes||b.depth>S.maxDepth)throw new i("NODE_BUDGET");if(E.nodeType!==1&&E.nodeType!==3)continue;let t=E.nodeType===1?E:null;if(me(E))continue;if(t&&(t.tagName==="STYLE"||t.tagName==="LINK")){if(pe(t,o)){f.add("PRIVATE_STYLESHEET_OMITTED");continue}let m=t.sheet;if(m){let N=t.getRootNode(),W=N instanceof a.ShadowRoot?G.get(N):null;W===void 0?f.add("STYLESHEET_SCOPE_UNKNOWN"):($.set(m,W),Y(m,W))}continue}if(t&&ve.has(t.tagName.toLowerCase())){["IFRAME","CANVAS","IMG","PICTURE","VIDEO","AUDIO","OBJECT","EMBED"].includes(t.tagName)&&f.add("NON_DOM_OR_EXTERNAL_OMITTED");continue}if(t){let m=t.getAttributeNames();if(m.length>S.maxAttributes)throw new i("ATTRIBUTE_BUDGET");let N=0;for(let W of m){let oe=t.getAttribute(W)??"";if(N+=oe.length,oe.length>S.maxText||N>8192)throw new i("ATTRIBUTE_BUDGET")}}else if((E.nodeValue?.length??0)>S.maxText)throw new i("TEXT_BUDGET");let H=t&&pe(t,o);if(H&&!["INPUT","TEXTAREA","SELECT"].includes(t.tagName)){f.add("PRIVATE_SUBTREE_OMITTED");continue}let A=t?Me(t,o):{};if(t&&["fill","stroke"].some(m=>/url\s*\(/i.test(t.getAttribute(m)??"")&&!A[m])&&f.add("SVG_RESOURCE_OMITTED"),t?.hasAttribute("data-indiana-id")&&!A["data-indiana-id"]&&f.add("UNKNOWN_ANCHOR_OMITTED"),t?.tagName==="IMG"){let m=Ue(t.getAttribute("src")||"",l.baseURI,o.assetPaths);m?A["data-indiana-asset"]=m:f.add("UNKNOWN_IMAGE_OMITTED")}if(t?.tagName==="DIALOG"&&t.open)try{A.rr_open_mode=t.matches("dialog:modal")?"modal":"non-modal"}catch{A.rr_open_mode="non-modal"}if(A.style){let m=we(A.style,o.assetPaths,!0,l.baseURI,o.privacy,o.origin);A.style=m.css,m.gaps.forEach(N=>f.add(N))}let I=r.length,F={id:I,parentId:b.parent,kind:t?"element":"text",tag:t?.tagName.toLowerCase()??null,text:t?null:De(E.nodeValue??"",E.parentElement,o),attributes:A,shadow:b.shadow};if(u+=new TextEncoder().encode(JSON.stringify(F)).length,u>S.maxBytes-S.maxCssBytes-4096)throw new i("BYTE_BUDGET");if(r.push(F),t&&Q.push({element:t,id:I}),t&&!H){if(r.length+d.length+t.childNodes.length+(t.shadowRoot?.childNodes.length??0)>S.maxNodes)throw new i("NODE_BUDGET");if(t.shadowRoot){if(C.size>=128)throw new i("SHADOW_BUDGET");c.onShadowRoot?.(t.shadowRoot),C.set(I,[]),G.set(t.shadowRoot,I);let m=t.shadowRoot.adoptedStyleSheets??[];if(m.length>S.maxStyleSheets)throw new i("STYLESHEET_BUDGET");for(let N of m)Y(N,I);for(let N=t.shadowRoot.childNodes.length-1;N>=0;N--)d.push({node:t.shadowRoot.childNodes[N],parent:I,depth:b.depth+1,shadow:!0})}for(let m=E.childNodes.length-1;m>=0;m--)d.push({node:E.childNodes[m],parent:I,depth:b.depth+1,shadow:!1})}}await n(!0),g="css";for(let b of l.styleSheets){await n();let E=b.ownerNode;if(E instanceof a.Element&&pe(E,o)){f.add("PRIVATE_STYLESHEET_OMITTED");continue}$.has(b)?Y(b,$.get(b)):E&&E.getRootNode()===l?Y(b,null):f.add("STYLESHEET_OWNER_UNKNOWN")}for(let b of ee)Y(b,null);let P={count:0},M=l.createElement("span").style;for(let{sheet:b,hostId:E}of R)p(),await Ke(b,o,l.baseURI,t=>{if(v+=new TextEncoder().encode(t).length,v>S.maxCssBytes)throw new i("CSS_BUDGET");(E===null?T:C.get(E)).push(t)},f,()=>n(),P,M);await n(!0),g="scroll",await new Promise((b,E)=>{let t=0,H,A=!1,I=N=>{A||(A=!0,a.cancelAnimationFrame(t),clearTimeout(H),clearTimeout(m),e.removeEventListener("abort",F),N?E(N):b())},F=()=>I(new i("ABORTED"));e.addEventListener("abort",F,{once:!0}),t=a.requestAnimationFrame(()=>{H=setTimeout(()=>I(),0)});let m=setTimeout(()=>I(new i("FRAME_UNAVAILABLE")),250);e.aborted&&F()}),h=z(),p();for(let{element:b,id:E}of Q){for(let[t,H]of[["scrollLeft","rr_scrollLeft"],["scrollTop","rr_scrollTop"]]){let A=b[t];if(!Number.isFinite(A)||Math.abs(A)>1e7)throw new i("SCROLL_BUDGET");A&&(r[E].attributes[H]=String(A))}if(Object.keys(r[E].attributes).length>S.maxAttributes)throw new i("ATTRIBUTE_BUDGET");await n()}await n(!0),g="hash",xe(r),await n(!0),p();let V={nodes:r,css:T.join(""),shadowCss:[...C].map(([b,E])=>({hostId:b,css:E.join("")})),scroll:{x:Math.max(0,a.scrollX),y:Math.max(0,a.scrollY)}},ne={width:Math.max(100,a.innerWidth),height:Math.max(100,a.innerHeight),dpr:a.devicePixelRatio},X={sourceVersionId:o.sourceVersionId,manifestDigest:o.manifestDigest,pageKey:_.pageKey,viewport:ne,document:V,privacy:o.privacy},re=await Se(Ve(X),n),le=new TextEncoder().encode(re);await n(!0);let ue=await nt(le);return h=z(),p(),{format:"indiana-runtime-snapshot",schemaVersion:1,collector:{name:"indiana-bounded-dom",version:2,...je?{buildSha256:je}:{}},...X,routeTemplate:_.path,sequence:c.sequence,label:c.label,contentHash:ue,previousContentHash:c.previousContentHash,gaps:[...f].slice(0,32),metrics:{maxSliceMs:D,totalWorkMs:k,elapsedMs:z()-y}}}catch(P){throw P instanceof i||e.aborted?P:new i(g==="css"?"CSS_UNSUPPORTED":"SERIALIZATION_UNSUPPORTED",{maxSliceMs:D,totalWorkMs:k,elapsedMs:z()-y,phase:g})}finally{Q.length=0,d.length=0,R.length=0}}var ze=1081344,Re=16*1024;function be(c,l,o){return Fe(c,l,o,{message:"CAPTURE_SERVICE_RESPONSE"})}async function Ut(c){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(c.environmentId))throw Error("Invalid capture environment");let l=c.document??document,o=l.defaultView;if(!o)throw Error("Capture requires a window");let e=o;if(!e.navigator.onLine)throw new i("OFFLINE");let a=c.grant,_=c.onStatus,U=c.transport,y=new URL(c.baseUrl);if(y.pathname!=="/"||y.search||y.hash||y.username||y.password||!Ce(y.origin))throw Error("Invalid capture service origin");let f=new AbortController,r=c.signal?AbortSignal.any([f.signal,c.signal]):f.signal;r.throwIfAborted();let T=y.origin+"/api/app-manifest-captures",h=async s=>{let O=AbortSignal.any([r,AbortSignal.timeout(45e3)]),L=await fetch(T,{method:"POST",credentials:"omit",redirect:"error",cache:"no-store",headers:{Authorization:"Bearer "+a,[se]:ie,"Content-Type":"application/json"},body:JSON.stringify(s),signal:O});if(!L.ok)throw L.body?.cancel().catch(()=>{}),new i("AUTH_OR_SERVICE_"+L.status);if(L.headers.get(se)!==ie)throw L.body?.cancel().catch(()=>{}),new i("CAPTURE_VERSION_MISMATCH");try{return await be(L,s.action==="policy"?ze:Re,O)}catch{throw new i("SERVICE_RESPONSE_INVALID")}},D=performance.now(),k;try{k=ke.parse(await h({action:"policy"}))}catch(s){throw s instanceof i?s:new i("SERVICE_RESPONSE_INVALID")}let{policy:u,progress:v}=k,g=Math.min(k.expiresAt-k.serverTime,9e5)-(performance.now()-D),p=Date.now()+g;if(u.environmentId!==c.environmentId)throw Error("Foreign capture environment");if(g<=0||u.origin!==e.location.origin||!Ce(u.origin))throw Error("Capture authorization expired or foreign origin");let n=0,d=v.sequence,R=v.readyCount,C=v.lastContentHash,G=-1/0,$=!0,B=!1,Q=!1,ee=!1,Y=!1,P=!1,M=!1,V=0,ne=-1/0,X=!1,re=performance.now(),le=performance.now(),ue=e.location.href,de="initial",b=!1,E=!1,t=null,H=null,A=null,I=(s,O,L)=>{try{_?.({state:s,reason:O,snapshots:R,expiresAt:p,pending:+!!t+ +!!H,...L?{metrics:L}:{}})}catch{}},F=()=>{B||M||(M=!0,Y=!0,P=!0,A?.abort(),I("paused","OFFLINE"))};e.addEventListener("offline",F);let m=(s=!1)=>{$=!0,n++,re=performance.now(),s===!0&&(b=!0)},N=new e.MutationObserver(s=>{let O=["[data-indiana-private]","[data-private]",...u.blockedSelectors].join(","),L=!1,Z=!1;for(let w of s.slice(0,16)){if(w.type==="childList"){let K=w.addedNodes.length+w.removedNodes.length;if(K>0&&K<=8&&[...w.addedNodes,...w.removedNodes].every(me))continue}let x=w.target.nodeType===1?w.target:w.target.parentElement;x&&Le(x,O)||(L=!0,(x?.tagName==="DIALOG"||["dialog","menu","listbox","tooltip"].includes(x?.getAttribute("role")??""))&&(Z=!0))}(s.length>16||L)&&m(Z)}),W=new Set,oe=s=>{W.has(s)||(N.observe(s,{childList:!0,attributes:!0,characterData:!0,subtree:!0}),W.add(s))};oe(l);let _e=s=>{let O=s.target instanceof e.Element&&s.target.closest('input:not([type="checkbox"]):not([type="radio"]):not([type="button"]):not([type="submit"]):not([type="reset"]),textarea,[contenteditable="true"],[contenteditable=""]');O&&["input","beforeinput","compositionend"].includes(s.type)&&(ne=performance.now()),O&&s.type==="compositionstart"&&(X=!0),(s.type==="compositionend"||s.type==="focusout")&&(X=!1),m(s.type==="click"||s.type==="change")},Ae=["input","beforeinput","compositionstart","compositionend","change","click","focusout","popstate","hashchange","resize","scroll","visibilitychange"],Ie=new Set(["input","beforeinput","compositionstart","compositionend","change","click","focusout","scroll","visibilitychange"]);for(let s of Ae)(Ie.has(s)?l:e).addEventListener(s,_e,{capture:!0,passive:!0});let Xe=U??(async(s,O,L,Z)=>{let w=[...new Uint8Array(await crypto.subtle.digest("SHA-256",O))].map(Te=>Te.toString(16).padStart(2,"0")).join(""),x=Be.parse(await h({action:"register",requestId:Z,sha256:w,bytes:O.byteLength,pageKey:s.pageKey,sequence:s.sequence,contentHash:s.contentHash}));if(x.ready)return;let K=new URL(T+"/"+x.versionId+"/content"),q=AbortSignal.any([L,AbortSignal.timeout(9e4)]),j=await fetch(K,{method:"PUT",body:O,headers:{Authorization:"Bearer "+a,[se]:ie,"Content-Type":"application/json"},credentials:"omit",redirect:"error",signal:q});if(!j.ok)throw j.body?.cancel().catch(()=>{}),new i("UPLOAD_"+j.status);if(j.headers.get(se)!==ie)throw j.body?.cancel().catch(()=>{}),new i("CAPTURE_VERSION_MISMATCH");if(He.parse(await be(j,Re,q)).versionId!==x.versionId)throw new i("SERVICE_RESPONSE_INVALID")}),$e=e.setInterval(()=>{Ze()},250),Qe=e.setTimeout(()=>te("EXPIRED"),Math.min(p-Date.now(),9e5));async function ae(){if(B||ee||P)return;if(H||(H=t,t=null),!H){d>=S.maxSnapshots&&!Q&&te("QUOTA");return}ee=!0;let s=H;I("uploading",void 0,s.metrics);try{if(await Xe(s.snapshot,s.bytes,r,s.requestId),B)return;R++,H=null,E=!1,I(M?"paused":"idle",M?"OFFLINE":void 0)}catch(O){if(B)return;let L=O instanceof i?O.code:"UPLOAD_FAILED";if(L==="CAPTURE_VERSION_MISMATCH"||/^(?:AUTH_OR_SERVICE|UPLOAD)_426$/.test(L)){te("CAPTURE_UPGRADE_REQUIRED");return}if(/^(?:AUTH_OR_SERVICE|UPLOAD)_(?:401|403|409)$/.test(L)){te("REVOKED_OR_CHANGED");return}P=!0,I("paused",M?"OFFLINE":L)}finally{ee=!1,!B&&!P&&ae()}}async function Ze(){if(B||Q||r.aborted)return;if(!e.navigator.onLine){F();return}if(e.location.href!==ue&&(ue=e.location.href,de="navigation",Y=!1,V=0,m(!0)),Y||P)return;let s=!1;for(let w of W)w instanceof e.ShadowRoot&&!w.host.isConnected&&(W.delete(w),s=!0);if(s){N.takeRecords().length&&m(),N.disconnect();for(let w of W)N.observe(w,{childList:!0,attributes:!0,characterData:!0,subtree:!0})}if(d>=S.maxSnapshots){ae();return}if(performance.now()-le>15e3&&(le=performance.now(),m()),!$||l.hidden||!e.navigator.onLine||performance.now()-re<S.quietMs||performance.now()-G<(b?S.urgentIntervalMs:S.minIntervalMs)||X||performance.now()-ne<1e3)return;if(t&&H){E||(E=!0,I("waiting","UPLOAD_BACKPRESSURE"));return}Q=!0;let O=n,L=de;b=!1,A=new AbortController;let Z=AbortSignal.any([r,A.signal]);I("capturing");try{let w=await Je({document:l,policy:u,sequence:d+1,label:L,previousContentHash:C,signal:Z,changed:()=>n!==O,onShadowRoot:oe});if(B)return;if(w.contentHash===C){$=n!==O,I(ee?"uploading":"idle");return}let x=performance.now(),K=0,q=0,j=x,ge=async()=>{let fe=performance.now()-x;if(fe>=S.sliceMs){if(K+=fe,q=Math.max(q,fe),fe>S.maxSliceMs)throw new i("ENCODING_BUDGET",{maxSliceMs:q,totalWorkMs:K,elapsedMs:performance.now()-j,phase:"encoding"});await new Promise(et=>setTimeout(et,0)),Z.throwIfAborted(),x=performance.now()}},Te=await Se(w,ge),ye=await We(Te,S.maxBytes,ge);if(!ye)throw new i("BYTE_BUDGET");let Ne=performance.now()-x;if(K+=Ne,q=Math.max(q,Ne),q>S.maxSliceMs)throw new i("ENCODING_BUDGET",{maxSliceMs:q,totalWorkMs:K,elapsedMs:performance.now()-j,phase:"encoding"});if(ye.length>S.maxBytes)throw new i("BYTE_BUDGET");Z.throwIfAborted(),t={snapshot:w,bytes:ye,requestId:crypto.randomUUID(),metrics:{maxSliceMs:Math.max(w.metrics.maxSliceMs,q),totalWorkMs:w.metrics.totalWorkMs+K,elapsedMs:w.metrics.elapsedMs+performance.now()-j,phase:"capture-and-encoding"}},d=w.sequence,C=w.contentHash,G=performance.now(),$=n!==O,V=0,E=!1,ae()}catch(w){if(B)return;let x=w instanceof i?w.code:"CAPTURE_FAILED";G=performance.now(),["UNSTABLE","ROUTE_NOT_ALLOWED","SCOPE_OR_VISIBILITY"].includes(x)&&++V<3?I("idle",x):(Y=!0,I("paused",M?"OFFLINE":x,w instanceof i?w.metrics:void 0))}finally{Q=!1,A=null}}function te(s="DESTROYED"){if(!B){B=!0,r.removeEventListener("abort",Oe),f.abort(),A?.abort(),N.disconnect(),W.clear(),t=null,H=null,a="",e.clearInterval($e),e.clearTimeout(Qe),e.removeEventListener("offline",F);for(let O of Ae)(Ie.has(O)?l:e).removeEventListener(O,_e,!0);I("stopped",s)}}let Oe=()=>te("ABORTED");return r.addEventListener("abort",Oe,{once:!0}),r.aborted&&te("ABORTED"),B||(e.navigator.onLine?I("idle"):F()),{checkpoint(s="checkpoint"){if(!B){if(!he.safeParse(s).success)throw Error("Invalid checkpoint label");if(de=s,!e.navigator.onLine){F();return}M=!1,Y=!1,P=!1,V=0,m(!0),ae()}},retry(){if(!B){if(!e.navigator.onLine){F();return}M=!1,Y=!1,P=!1,V=0,ae()}},destroy:te,get paused(){return Y||P},get snapshots(){return R}}}export{Ut as startCapture};
@@ -1,2 +0,0 @@
1
- var N={connecting:["\u6B63\u5728\u8FDE\u63A5\u91C7\u96C6\u670D\u52A1\u2026","Connecting to the capture service\u2026"],authorized:["\u91C7\u96C6\u6388\u6743\u5DF2\u786E\u8BA4\uFF0C\u6B63\u5728\u52A0\u8F7D\u2026","Capture authorized; loading\u2026"],idle:["\u9875\u9762\u7A33\u5B9A\u540E\u81EA\u52A8\u91C7\u96C6\uFF0C\u8F93\u5165\u6587\u672C\u4F1A\u906E\u853D\u3002","Stable page states are captured automatically. Input text is masked."],capturing:["\u6B63\u5728\u91C7\u96C6\u9875\u9762\u7ED3\u6784\u2026","Capturing page structure\u2026"],uploading:["\u6B63\u5728\u4FDD\u5B58\u8131\u654F\u5FEB\u7167\u2026","Saving a masked snapshot\u2026"],waiting:["\u4E0A\u4F20\u5904\u7406\u4E2D\uFF0C\u540E\u7EED\u53D8\u5316\u5DF2\u5408\u5E76\u7B49\u5F85\u3002","Upload in progress; later changes are coalesced."],paused:["\u91C7\u96C6\u5DF2\u6682\u505C\u3002\u68C0\u67E5\u9875\u9762\u6216\u8FDE\u63A5\u540E\uFF0C\u53EF\u624B\u52A8\u91CD\u8BD5\u3002","Capture paused. Check the page or connection, then retry."],stopped:["\u91C7\u96C6\u5DF2\u505C\u6B62\u3002","Capture stopped."]},O=["\u6B64\u9875\u9762\u4E0D\u5728\u672C\u6B21\u6388\u6743\u7684\u9875\u9762\u8303\u56F4\u5185\u3002\u6253\u5F00\u5DF2\u6388\u6743\u7684\u9875\u9762\u540E\u4F1A\u81EA\u52A8\u7EE7\u7EED\u91C7\u96C6\u3002","This page is not one of the authorized pages for this link. Open an authorized page and capture continues automatically."],R=["\u672C\u9875\u7684\u5B9E\u9A8C\u548C\u8DF3\u8F6C\u4ECD\u5904\u4E8E\u6682\u505C\u72B6\u6001\uFF0C\u5237\u65B0\u9875\u9762\u540E\u6062\u590D\u3002","Experiments and redirects stay paused on this page until you reload it."];function I(o,e){let t=o.reason??"";if(o.state==="idle"){if(t==="ROUTE_NOT_ALLOWED")return O;if(t==="UNSTABLE")return["\u9875\u9762\u4ECD\u5728\u53D8\u5316\uFF0C\u7A33\u5B9A\u540E\u4F1A\u81EA\u52A8\u91CD\u8BD5\u3002","The page is still changing; capture retries once it settles."]}if(o.state==="paused"){if(t==="ROUTE_NOT_ALLOWED")return O;if(t==="UNSTABLE")return["\u91C7\u96C6\u671F\u95F4\u9875\u9762\u6301\u7EED\u53D8\u5316\u3002\u8BF7\u7B49\u5F85\u9875\u9762\u7A33\u5B9A\u540E\u91CD\u8BD5\u3002","The page kept changing during capture. Wait for it to settle, then retry."];if(t==="OFFLINE")return["\u7F51\u7EDC\u5DF2\u65AD\u5F00\u3002\u6062\u590D\u8FDE\u63A5\u540E\uFF0C\u8BF7\u624B\u52A8\u91CD\u8BD5\u3002","You are offline. Reconnect, then retry explicitly."];if(/(?:SLICE|ENCODING|NODE|BYTE|TEXT|ATTRIBUTE|CSS|DEADLINE)/.test(t))return["\u9875\u9762\u8D85\u51FA\u91C7\u96C6\u9884\u7B97\u3002\u7F29\u5C0F\u9875\u9762\u72B6\u6001\u540E\u518D\u8BD5\u3002","This page exceeds the capture budget. Reduce the page state before retrying."];if(/(?:429|QUOTA)/.test(t))return["\u5DF2\u8FBE\u5230\u91C7\u96C6\u914D\u989D\uFF0C\u8BF7\u8FD4\u56DE\u63A7\u5236\u53F0\u67E5\u770B\u3002","Capture quota reached. Check the Console before retrying."]}if(o.state==="stopped"){if(t==="QUOTA")return[`\u91C7\u96C6\u5B8C\u6210\uFF1A\u5DF2\u4FDD\u5B58 ${e} \u4E2A\u9875\u9762\u72B6\u6001\u3002\u8BF7\u56DE\u5230\u63A7\u5236\u53F0 \u203A App \u9875\u9762\u76EE\u5F55\uFF0C\u5237\u65B0\u5DF2\u91C7\u96C6\u72B6\u6001\u3002`,`Capture complete: ${e} page states saved. Return to Console \u203A App page map and refresh captured states.`];if(t==="EXPIRED")return[`\u91C7\u96C6\u94FE\u63A5\u5DF2\u8FC7\u671F\uFF0C\u5DF2\u4FDD\u5B58 ${e} \u4E2A\u9875\u9762\u72B6\u6001\u3002\u5982\u9700\u7EE7\u7EED\u91C7\u96C6\uFF0C\u8BF7\u5728\u63A7\u5236\u53F0 \u203A App \u9875\u9762\u76EE\u5F55\u83B7\u53D6\u65B0\u94FE\u63A5\u3002`,`This capture link has expired after saving ${e} page states. To capture more, get a new link in Console \u203A App page map.`];if(/REVOKED/.test(t))return["\u91C7\u96C6\u94FE\u63A5\u5DF2\u64A4\u9500\u6216\u6743\u9650\u5DF2\u53D8\u66F4\u3002\u8BF7\u5728\u63A7\u5236\u53F0 \u203A App \u9875\u9762\u76EE\u5F55\u83B7\u53D6\u65B0\u94FE\u63A5\u3002","This capture link was revoked or its access changed. Get a new link in Console \u203A App page map."];if(t==="CAPTURE_UPGRADE_REQUIRED")return["\u91C7\u96C6\u7248\u672C\u4E0D\u5339\u914D\u3002\u8BF7\u5237\u65B0\u9875\u9762\u6216\u66F4\u65B0 SDK\uFF0C\u7136\u540E\u5728\u63A7\u5236\u53F0 \u203A App \u9875\u9762\u76EE\u5F55\u83B7\u53D6\u65B0\u94FE\u63A5\u3002","Capture versions differ. Reload the page or update the SDK, then get a new link in Console \u203A App page map."];if(t==="AUTH_OR_SERVICE_UNAVAILABLE")return["\u65E0\u6CD5\u786E\u8BA4\u91C7\u96C6\u6388\u6743\u3002\u8BF7\u5728\u63A7\u5236\u53F0 \u203A App \u9875\u9762\u76EE\u5F55\u83B7\u53D6\u65B0\u94FE\u63A5\u540E\u91CD\u8BD5\u3002","This capture link could not be authorized. Get a new link in Console \u203A App page map and try again."]}return N[o.state]??N.paused}function L(o){let e=o.document,t=/^zh\b/i.test(e.documentElement.lang),n=e.createElement("div"),T=n.attachShadow({mode:"open"}),g=e.createElement("style");n.setAttribute("data-indiana-private",""),n.setAttribute("data-indiana-capture-controls",""),n.setAttribute("aria-live","off");let S=typeof n.showPopover=="function";S&&n.setAttribute("popover","manual"),n.hidden=!0,o.nonce&&(g.nonce=o.nonce),g.textContent=":host{all:initial!important;position:fixed!important;margin:0!important;inset:auto!important;right:12px!important;bottom:12px!important;z-index:2147483647!important;display:block!important;width:340px!important;max-width:calc(100vw - 24px)!important;color:#17202d!important;font:13px/1.4 system-ui,sans-serif!important;color-scheme:light!important}:host([hidden]){display:none!important}*{box-sizing:border-box}.panel{background:white;border:1px solid #98a4b4;border-radius:2px;padding:12px;box-shadow:0 2px 10px #17202d20}.top,.actions{display:flex;align-items:center;gap:8px}.top{justify-content:space-between}strong{font-weight:600}small{font-size:12px;font-variant-numeric:tabular-nums}.message{margin:6px 0;color:#465467;overflow-wrap:anywhere;white-space:pre-line}.actions{justify-content:flex-end}button{font:inherit;min-height:40px;border:1px solid #98a4b4;border-radius:2px;padding:6px 12px;background:white;color:#17202d;cursor:pointer}button:focus-visible{outline:2px solid #155eef;outline-offset:2px}button:disabled{cursor:default;color:#5b6778;background:#f2f4f7}button.primary:enabled{background:#155eef;border-color:#155eef;color:white}@media(forced-colors:active){.panel,button{border:1px solid CanvasText}button:focus-visible{outline:2px solid Highlight}}";let u=e.createElement("section"),x=e.createElement("div"),w=e.createElement("strong"),k=e.createElement("small"),m=e.createElement("p"),y=e.createElement("div"),p=e.createElement("button"),h=e.createElement("button");if(u.className="panel",x.className="top",y.className="actions",u.setAttribute("aria-label",t?"Indiana \u9875\u9762\u91C7\u96C6":"Indiana page capture"),u.setAttribute("role","region"),w.textContent=t?"Indiana \u9875\u9762\u91C7\u96C6":"Indiana page capture",m.className="message",m.setAttribute("role","status"),p.type=h.type="button",p.className="primary",p.textContent=t?"\u91CD\u8BD5\u91C7\u96C6":"Retry capture",x.append(w,k),y.append(p,h),u.append(x,m,y),T.append(g,u),(e.body??e.documentElement).append(n),!g.sheet)throw n.remove(),Object.assign(Error("Authoring controls blocked by style policy"),{code:"AUTHORING_CONTROLS_BLOCKED"});n.hidden=!1;let r={state:"connecting",snapshots:0},l=!1,b,d;function E(a=e.activeElement){if(l||a===n||a&&n.contains(a))return;let s,i=a;for(let c=0;i&&c<80;c++,i=i.parentElement)if(i.matches('dialog[open],[role="dialog"],[role="alertdialog"],[role="menu"],[role="listbox"]')&&i.getAttribute("aria-hidden")!=="true"){s=i;break}b=s;let f=s??e.body??e.documentElement;if(n.parentElement!==f&&f.append(n),n.removeAttribute("aria-hidden"),S)try{n.showPopover()}catch{}}let A=a=>{a.target instanceof e.defaultView.Element&&E(a.target)},v=a=>{a.target===b&&E(e.body)};e.addEventListener("focusin",A,!0),e.addEventListener("close",v,!0);function C(){if(l)return;if(n.isConnected||b&&!b.isConnected&&E(),!n.isConnected){l=!0,clearInterval(d),e.removeEventListener("focusin",A,!0),e.removeEventListener("close",v,!0),o.stop();return}let a=Number.isInteger(r.snapshots)?Math.min(10,Math.max(0,r.snapshots)):0,s=r.expiresAt&&Number.isFinite(r.expiresAt)?Math.max(0,Math.ceil((r.expiresAt-Date.now())/1e3)):null,i=s===null?"":`${Math.floor(s/60)}:${String(s%60).padStart(2,"0")}`;k.textContent=t?`\u5DF2\u4FDD\u5B58 ${a}/10`+(i&&` \xB7 \u5269\u4F59 ${i}`):`${a}/10 saved`+(i&&` \xB7 ${i} left`);let f=t?0:1,c=I(r,a)[f];r.state==="stopped"&&r.reloadRequired&&(c+=`
2
- `+R[f]),m.textContent!==c&&(m.textContent=c),p.hidden=r.state==="stopped",p.disabled=r.state!=="paused"||s===0,h.textContent=r.state==="stopped"?t?"\u5173\u95ED":"Close":t?"\u505C\u6B62\u91C7\u96C6":"Stop capture"}for(let a of["click","pointerdown","pointerup","keydown","keyup"])T.addEventListener(a,s=>s.stopPropagation());return p.onclick=()=>{p.disabled||o.retry()},h.onclick=()=>{r.state==="stopped"?o.close():o.stop()},E(),C(),{update(a){l||(r=a,d&&clearInterval(d),d=void 0,r.state!=="stopped"&&r.expiresAt&&Number.isFinite(r.expiresAt)&&(d=setInterval(C,1e3)),C())},destroy(){l||(l=!0,clearInterval(d),e.removeEventListener("focusin",A,!0),e.removeEventListener("close",v,!0),n.remove())},get active(){return!l&&n.isConnected}}}export{L as createCaptureControls};
@@ -1 +0,0 @@
1
- import{a as re}from"./chunk-6X42DWOM.js";import"./chunk-QO4YQLZ4.js";import{Gd as ve,ig as me}from"./chunk-467Z5ISI.js";import"./chunk-3SONNXFG.js";import"./chunk-U6S6AZM6.js";import"./chunk-4K25DELJ.js";import"./chunk-S5TVMQRC.js";import{a}from"./chunk-6MO6Y24B.js";import{Hb as Ce}from"./chunk-HD74AAFS.js";import"./chunk-RRII2DMC.js";import"./chunk-KQCTDXVD.js";function be(P){let M=P.view;if(!M?.paywall)throw new a("INVALID_REQUEST","The current node is not a Paywall");let n=M.paywall.receiptId,te=M.nodeId,se=M.visit,I=M.paywall.resolution,Q=I,v="document"in I?I:null;function F(t){return"document"in t?t.offering.id:t.content.offeringVersionId}function ie(t){if(t.id!==I.id||F(t)!==F(I)||t.content?.artifact.sha256!==I.content?.artifact.sha256)throw new a("INVALID_RESPONSE","The pinned Paywall binding changed")}let m=M.paywall.quote,T=M.paywall.operation,J=!1,q=new AbortController,S=M.paywall.purchaseRequestId,H=0,k=M.paywall.selectionGeneration??0,R=M.paywall.canReselect===!0,C=null,D=new Map,j=new Map;function L(t){if(t.purchase&&t.purchase.receiptId!==n)throw new a("INVALID_RESPONSE","Purchase receipt changed");let r=t.run.paywall;return t.purchase??(r?.receiptId===n?r:null)}function $(){if(J)throw new a("IDENTITY_CHANGED","Paywall presentation has closed")}function X(t,r,w){if($(),r!==H||w!==void 0&&m?.operationId!==w)return!1;let y=k,s=t.run.paywall;if(s?.receiptId===n){if((s.selectionGeneration??0)<k)return!1;k=s.selectionGeneration??0,R=s.canReselect===!0,ie(s.resolution)}let l=L(t),c=k>y,_=c?l?.quote??null:l?.quote??m,N=l?.operation??(_?.operationId===m?.operationId?T:null);if(_&&N&&_.operationId!==N.operationId)throw new a("INVALID_RESPONSE","Purchase operation changed");return s?.receiptId===n&&(Q=s.resolution,v="document"in Q?Q:v?{...Q,document:v.document,offering:v.offering}:null),(c||_?.operationId!==m?.operationId)&&(H++,s?.receiptId===n&&(S=s.purchaseRequestId)),m=_,(T?.operationId!==N?.operationId||T?.status==="pending"||N?.status==="complete")&&(T=N),!0}function B(t,r,w){return new Promise((y,s)=>{let l=!1,c=()=>{clearTimeout(Z),q.signal.removeEventListener("abort",Y)},_=x=>{l||(l=!0,c(),y(x))},N=x=>{l||(l=!0,c(),s(x))},Y=()=>N(new a("IDENTITY_CHANGED","Paywall presentation has closed")),Z=setTimeout(()=>N(new a("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,w)),Math.max(0,r-Date.now()));q.signal.addEventListener("abort",Y,{once:!0}),q.signal.aborted&&Y(),t.then(_,N)})}function h(t){return new Promise(r=>{let w=()=>{clearTimeout(y),q.signal.removeEventListener("abort",w),r()},y=setTimeout(w,t);q.signal.addEventListener("abort",w,{once:!0}),q.signal.aborted&&w()})}async function U(t,r,w){$();let y=D.get(t);if(!y){let c=P.pendingCommands?.find(_=>_.requestId===t)??P.pendingCommand;if(c?.operation==="submit"&&c.requestId===t&&c.nodeId===te&&c.visit===se){r.type==="paywall_quote"&&c.input.type==="paywall_quote"&&c.input.predecessor&&!r.predecessor&&(r={...r,predecessor:c.input.predecessor});let _=me.parse(c),N=me.parse({...c,input:r});if(N.operation!=="submit"||_.operation!=="submit"||JSON.stringify(N.input)!==JSON.stringify(_.input))throw new a("CONFLICT","A restored purchase request cannot change its input");r=N.input,y=_,D.set(t,y)}}if(y){if(JSON.stringify(y.input)!==JSON.stringify(r))throw new a("CONFLICT","A purchase request cannot change its input")}else{let c=P.view;if(!c||c.nodeId!==te||c.visit!==se||c.paywall?.receiptId!==n)throw new a("PRECONDITION_FAILED","The Paywall visit has changed");y={operation:"submit",requestId:t,nodeId:te,visit:se,revision:c.revision,input:r},D.set(t,y)}let s=Date.now()+3e4,l=await B(P.submit(y),s,t);for(;l.run.pendingRequest?.requestId===t&&Date.now()<s&&!J&&(await h(Math.min(1e3,s-Date.now())),!(J||Date.now()>=s));)l=await B(P.resume(t),s,t);if(J)throw new a("IDENTITY_CHANGED","Paywall presentation has closed");if(l.run.pendingRequest?.requestId===t)throw new a("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,t);if(!X(l,w,r.type==="paywall_confirm"||r.type==="paywall_cancel"?r.operationId:void 0))throw new a("PRECONDITION_FAILED","The purchase selection has changed")}async function oe(t){if(!m)throw new a("INVALID_REQUEST","A quoted purchase is required");let r=`${t}:${m.operationId}`,w=j.get(r);if(!w){let y=t==="confirm"?"paywall_confirm":"paywall_cancel",s=P.pendingCommands?.find(l=>l.operation==="submit"&&l.input.type===y&&"operationId"in l.input&&l.input.operationId===m.operationId)??P.pendingCommand;w=s?.operation==="submit"&&s.input.type===y&&"operationId"in s.input&&s.input.operationId===m.operationId?s.requestId:crypto.randomUUID(),j.set(r,w)}if(await U(w,{type:t==="confirm"?"paywall_confirm":"paywall_cancel",operationId:m.operationId},H),!T)throw new a("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(T)}return{get view(){return structuredClone(v)},get quote(){return m?structuredClone(m):null},get operation(){return T?structuredClone(T):null},get webViewUrl(){return P.webViewUrl},get canReselect(){return R},async refresh(){$();let t=H,r=await P.get();if(X(r,t),r.run.paywall?.receiptId!==n)throw new a("PRECONDITION_FAILED","Paywall presentation has changed");if(!v){if("document"in Q||!P.resolvePaywall)throw new a("INVALID_RESPONSE","Public Paywall reader is unavailable");let w=await P.resolvePaywall(Q);$(),ie(w),v={...Q,document:w.document,offering:w.offering}}return structuredClone(v)},preview(t){if(!v)return Promise.reject(new a("PRECONDITION_FAILED","Load the Paywall presentation first"));if(S&&S!==t.requestId&&(C||!R))return Promise.reject(new a("COMMAND_PENDING","Retry the original purchase before starting another"));if(S===t.requestId&&C)return C;let r=v.document.buttons[t.actionId],w=r?.type==="checkout"?ve(r.product,t.selection,v.capabilities):null;if(!w)return Promise.reject(new a("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let y=S!==t.requestId&&k>0?{operationId:m?.operationId??null,generation:k}:void 0;if(y&&(!R||k<=0))return Promise.reject(new a("COMMAND_PENDING","Original purchase requires authoritative termination"));S!==t.requestId&&H++;let s=H;S=t.requestId;let l=(async()=>{if(await U(t.requestId,{type:"paywall_quote",actionId:t.actionId,productVersionId:w,...y?{predecessor:y}:{},...t.offerId?{offerId:t.offerId}:{},...t.nativeOffer?{nativeOffer:t.nativeOffer}:{}},s),!m)throw new a("INVALID_RESPONSE","The accepted quote is missing");return structuredClone(m)})();return C=l,l.then(()=>{C===l&&(C=null)},c=>{C===l&&(C=null),S===t.requestId&&P.pendingCommand?.requestId!==t.requestId&&c instanceof a&&c.status!==void 0&&c.status<500&&![401,425].includes(c.status)&&(S=null)}),l},confirm:()=>oe("confirm"),cancel:()=>oe("cancel"),async read(){if($(),!m)throw new a("INVALID_REQUEST","A quoted purchase is required");let t=m.operationId,r=H,w=P.pendingCommands?.find(c=>c.operation==="submit"&&(c.input.type==="paywall_confirm"||c.input.type==="paywall_cancel")&&c.input.operationId===t)??P.pendingCommand;w?.operation==="submit"&&(w.input.type==="paywall_confirm"||w.input.type==="paywall_cancel")&&w.input.operationId===t&&await P.settle?.(w.requestId);let y=await P.get(void 0,{receiptId:n,operationId:t});$();let s=L(y);if(s?.quote&&s.quote.operationId!==t||s?.operation&&s.operation.operationId!==t)throw new a("INVALID_RESPONSE","Purchase operation changed");let l=X(y,r,t)?T:s?.operation;if(!l)throw new a("INVALID_RESPONSE","The current purchase result is missing");return structuredClone(l)},destroy(){J=!0,q.abort(),D.clear(),j.clear()}}}async function Fe(P,M){let n=M,{mountScreenPreview:te}=await import("./popup.js"),{showPaywall:se}=await import("./paywall-WKOHBYW7.js"),I=P.ownerDocument,Q=I.activeElement,v=I.createElement("section"),F=I.createElement("div"),ie=I.createElement("div"),m=I.createElement("div"),T=I.createElement("button");m.hidden=!0,T.type="button";let J=I.createElement("p"),q=I.createElement("p"),S=I.createElement("button"),H=I.createElement("button"),k=I.createElement("button"),R=I.createElement("dialog");v.dataset.indianaFunnel="",v.setAttribute("aria-busy","false"),v.style.cssText="box-sizing:border-box;width:100%;min-width:0;font:14px/1.5 system-ui,sans-serif;color:#172033;background:#fff",ie.style.cssText="display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:12px 20px",J.setAttribute("role","status"),q.setAttribute("role","alert"),q.hidden=!0,S.type=H.type=k.type="button",ie.append(S,J,q,k,T,H),v.append(F,m,ie),P.append(v);let C=null,D=null,j=null,L="",$="",X="",B="",h=!1,U=0,oe=!1,t="",r=null,w=Promise.resolve(),y=null,s=null,l={},c=new Map,_=new Set,N=new Set,Y=new Set,Z=null,x={},E=!1,he,z=0,V=null,ae="",le=new Map,ye=e=>e?`${e.id}:${e.nodeId}:${e.visit}:${e.revision}:${e.paywall?.quote?.operationId??""}`:"",W=(e,i=null)=>{h||(s=i,q.textContent=e instanceof Error?e.message:"Request failed",q.hidden=!1,k.hidden=n.client.pendingCommand===null,re(n.onError,e))};function K(){let e=n.client.view;if(!e)throw new a("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision}}async function ee(e,i=!1){if(!(U&&!i||h||(E||n.client.view?.recoveryRestricted)&&!i)){U++,v.setAttribute("aria-busy","true"),q.hidden=!0,s=null;try{if(!i&&Z){let o=n.client.view;await Z;let g=n.client.view;if(!o||!g||g.id!==o.id||g.nodeId!==o.nodeId||g.visit!==o.visit||g.stopped||!["running","waiting"].includes(g.status))throw new a("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}if(h)return;let d=await e();h||await ne(n.client.view??d.run)}catch(d){W(d,n.client.pendingCommand?.requestId??null)}finally{U=Math.max(0,U-1),v.setAttribute("aria-busy",String(U>0)),h||(k.hidden=n.client.pendingCommand===null,S.disabled=U>0||!!n.client.pendingCommand||!n.client.view?.canBack)}}}function ge(e){if(E||_.has(e)||N.has(e)||h)return;N.add(e);let i=async()=>{if(E||h||L!==e){N.delete(e);return}if(U||n.client.pendingCommand){setTimeout(()=>{i()},250);return}let d=(async()=>{let g=n.client.view,p=K(),A=p.requestId,u=!1;try{await n.client.submit({operation:"shown",...p})}catch(b){if(!(b instanceof a)||b.code!=="CONFLICT"||b.status!==409||n.client.pendingCommand)throw b;await n.client.get();let f=n.client.view;if(h||E||L!==e||!f||!g||f.id!==g.id||f.source.versionId!==g.source.versionId||f.nodeId!==p.nodeId||f.visit!==p.visit||f.revision<=p.revision||f.stopped||!f.screen||!["running","waiting"].includes(f.status)||n.client.pendingCommand)throw b;let O=K();A=O.requestId,await n.client.submit({operation:"shown",...O})}for(;!h&&L===e&&n.client.pendingCommand?.requestId===A;){if(!n.client.settle)throw new a("COMMAND_PENDING","The original display acknowledgement is still pending");await n.client.settle(A),u=!0,n.client.pendingCommand?.requestId===A&&await new Promise(b=>setTimeout(b,1500))}h||L!==e||(u&&await n.client.get(),!(h||L!==e)&&_.add(e))})();Z=d;let o=()=>{Z===d&&(Z=null),N.delete(e)};d.then(o,g=>{o(),U||W(g)})};i()}function ce(){r&&clearTimeout(r),!(h||!j||!["running","waiting"].includes(j.status)&&!n.client.pendingCommand)&&(r=setTimeout(()=>{r=null,Ie().finally(ce)},j.pendingRequest||n.client.pendingCommand?1500:5e3))}async function Ie(){if(!(h||oe||U)){if(E){await ue(he);return}oe=!0;try{let e=n.client.pendingCommand;e&&n.client.settle&&await n.client.settle(e.requestId);let i=n.client.view,d=l,o=await n.client.get(i?.screen&&Object.keys(d).length?{nodeId:i.nodeId,visit:i.visit,revision:i.revision,components:d}:void 0);!h&&d===l&&await ne(n.client.view??o.run)}catch(e){W(e)}finally{oe=!1}}}async function Ee(e){let i=n.client.view,d=i?.screen,o=d?.customerData.nodes[e.nodeId];if(h||U||!i||!d||!o)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(e.action)){let O=C?.document,G=O?Ce(O,e.nodeId):null,we=G?.type==="customer_data"?G.data.outputs?.[e.action]:void 0;we&&d.outputs.includes(we)?await ee(()=>n.client.submit({operation:"submit",...K(),input:{type:"screen",output:we,answers:x,selection:e.value?{[e.nodeId]:e.value}:{}}})):await n.onCustomerDataIntent?.(e,i);return}let p=e.action.startsWith("sources_")?o.resources.find(O=>O.key===e.value):null;if(e.action.startsWith("sources_")&&!p)throw new a("INVALID_REQUEST","Choose a current resource");let A=`${i.visit}:${e.nodeId}:${p?.key??""}`,u=c.get(A)??[null],f=l[e.nodeId]??{page:1,after:null,filter:"all",...p?{resourceKey:p.key}:{}};if(e.action==="filter"){let O=e.value;if(!O||!(o.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(O))throw new a("INVALID_REQUEST","Unknown data filter");f={page:1,after:null,filter:O},u.splice(0,u.length,null)}else if(e.action==="next"||e.action==="sources_next"){let O=p?.sources.at(-1),G=p?O?{kind:"ledger",cursor:{at:O.detail[0],id:O.id,type:"source"}}:null:d.dataCursors[e.nodeId];if(!G||!p&&!o.hasNext)return;u[f.page]=G,f={...f,page:f.page+1,after:G}}else if(e.action==="previous"||e.action==="sources_previous"){if(f.page<=1)return;f={...f,page:f.page-1,after:u[f.page-2]??null}}c.set(A,u),l={...l,[e.nodeId]:f},await ee(()=>n.client.get({nodeId:i.nodeId,visit:i.visit,revision:i.revision,components:l}))}function Pe(e){let i=e.screen?.presentation;if(!i||i.type==="inline"){R.open&&R.close(),v.parentElement!==P&&P.append(v);return}v.parentElement!==R&&(R.append(v),P.append(R));let d={sm:420,md:640,lg:900};R.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in i?d[i.size]+"px":"100vw"}`,R.setAttribute("aria-label",C?.document?.name??e.screen?.content.document.name??"Funnel"),R.open||R.showModal()}async function Re(e){if(h)return;j=e,s&&n.client.pendingCommand?.requestId!==s&&(q.hidden=!0,s=null);let i=e.locale.startsWith("zh");if(T.textContent=i?"\u56DE\u770B":"History",T.hidden=!n.client.review,S.textContent=E?i?"\u8FD4\u56DE\u5F53\u524D":"Return to current":i?"\u8FD4\u56DE":"Back",H.textContent=i?"\u5173\u95ED":"Close",k.textContent=i?"\u91CD\u8BD5":"Retry",S.disabled=!E&&(U>0||!!n.client.pendingCommand||!e.canBack),k.hidden=n.client.pendingCommand===null,J.textContent=e.pendingRequest?i?"\u6B63\u5728\u5904\u7406":"Processing":e.instruction?.type==="wait"?i?"\u7B49\u5F85\u4E2D":"Waiting":"",t!==`${e.revision}:${e.visit}:${e.status}:${e.stopped}`&&(t=`${e.revision}:${e.visit}:${e.status}:${e.stopped}`,re(n.onState,structuredClone(e))),e.stopped||n.client.configurationReady===!1){E=!1,z++,V?.destroy(),V=null,m.replaceChildren(),m.hidden=!0,F.hidden=!1,C?.destroy(),C=null,D?.destroy(),D=null,F.replaceChildren(),L="",$="",B="",R.open&&R.close(),v.hidden=!0,ce();return}if(v.hidden=!1,E){ce();return}if(e.recoveryRestricted){C?.destroy(),C=null,D?.destroy(),D=null,F.replaceChildren(),L="",J.textContent=i?"\u539F\u8BB0\u5F55\u9700\u8981\u6838\u5BF9\uFF0C\u53EF\u53EA\u8BFB\u56DE\u770B":"Original records require reconciliation; read-only history is available";return}let d=e.screen||e.paywall?`${e.id}:${e.nodeId}:${e.visit}`:"";if(d!==L&&(C?.destroy(),C=null,D?.destroy(),D=null,F.replaceChildren(),L=d,$="",B="",x={...e.answers},l={},c.clear()),Pe(e),e.screen){let g=e.screen.content;C||(C=te(F,{mode:"live",rendererUrl:n.client.webViewUrl,title:g.document.name,onAction(u,b={},f={}){if(E)return;x={...x,...f};let O=Object.fromEntries((e.screen?.inputs??[]).filter(({variable:G})=>Object.hasOwn(x,G)).map(({variable:G})=>[G,x[G]]));ee(()=>n.client.submit({operation:"submit",...K(),input:{type:"screen",output:u,answers:O,selection:b}}))},onAnswers:u=>{E||(x={...x,...u})},onCustomerDataIntent:u=>{E||Ee(u).catch(W)},onEscape:()=>{E||de()},onError:u=>W(new Error(u)),onRendered:()=>ge(d)}));let p={capabilities:e.screen.capabilities,customerData:e.screen.customerData,parameters:e.parameters,serverInput:{bindings:e.screen.inputs,answers:x,values:e.screen.values}},A=JSON.stringify([g,e.locale,p.parameters,e.screen.inputs,e.screen.values]);if(A!==$)C.update(g.document,e.locale,p),$=A,X=JSON.stringify(p.capabilities),B=JSON.stringify(p.customerData);else{let u=JSON.stringify(p.capabilities);u!==X&&(C.updateCapabilities(p.capabilities),X=u),JSON.stringify(p.customerData)!==B&&(C.updateCustomerData(p.customerData),B=JSON.stringify(p.customerData))}await C.ready}else if(e.paywall&&!D){let g=await se(F,{canInteract:()=>!E&&!h&&!n.client.view?.recoveryRestricted,start:async()=>be(n.client),onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,resolveOfferId:n.resolveOfferId,onEvent:n.onEvent,onOpenUrl:p=>n.onOpenUrl?n.onOpenUrl({receiptId:e.paywall.receiptId,url:p,openIn:"same_window"}):I.defaultView?.location.assign(p),onAction:async p=>{if(E)return;let A=await n.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision,input:{type:"screen",output:p,answers:{}}});await ne(n.client.view??A.run)},onError:W,onDismiss:()=>{!E&&!h&&n.client.view?.visit===e.visit&&de()}});h?g.host?.destroy():(D=g.host,D?.setSuspended(E)),ge(d)}let o=e.instruction;if(o&&(o.type==="open_url"||o.type==="event")&&!Y.has(o.receiptId)){let g=I.createElement("button");g.type="button",g.textContent=o.type==="open_url"?`${i?"\u524D\u5F80":"Continue to"} ${new URL(o.url).host}`:i?"\u7EE7\u7EED":"Continue",g.onclick=()=>{let p=K(),A=o.type==="open_url"&&!n.onOpenUrl&&o.openIn==="new_window"?De(o.url):null;ee(async()=>{let u="success";if(o.type==="open_url")if(n.onOpenUrl)try{u=await n.onOpenUrl({receiptId:o.receiptId,url:o.url,openIn:o.openIn})===!1?"failed":"opened"}catch(f){re(n.onError,f),u="failed"}else u=o.openIn==="new_window"&&!A?"failed":"opened";if(o.type==="event"){if(!n.onEvent)throw new a("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(o.event)}if(h||n.client.view?.nodeId!==p.nodeId||n.client.view.visit!==p.visit)throw new a("PRECONDITION_FAILED","The client action visit changed");let b=await n.client.submit({operation:"submit",...p,input:{type:"client_action",receiptId:o.receiptId,outcome:u}});return Y.add(o.receiptId),o.type==="open_url"&&!n.onOpenUrl&&o.openIn==="same_window"&&I.defaultView?.location.assign(o.url),b})},F.replaceChildren(g)}!e.pendingRequest&&e.status==="completed"&&!Y.has(`complete:${e.id}`)&&(Y.add(`complete:${e.id}`),re(n.onComplete,structuredClone(e))),ce()}function De(e){let i=I.defaultView?.open(e,"_blank")??null;return i&&(i.opener=null),i}function ne(e){return w=w.catch(()=>{}).then(()=>Re(e)),w}async function ue(e){if(h||!n.client.review)return;E||(ae=ye(n.client.view),le.set(ae,structuredClone(x))),E=!0,he=e,F.hidden=!0,D?.setSuspended(!0),m.hidden=!1;let i=++z;try{let d=await n.client.review(e);if(h||i!==z||!E)return;if(!d.review)throw new a("INVALID_RESPONSE","Historical projection is missing");V?.destroy(),V=null,m.replaceChildren();let o=d.run.locale.startsWith("zh"),g=I.createElement("p");g.textContent=o?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",m.append(g);for(let[u,b]of d.review.pages.entries()){let f=I.createElement("button");f.type="button",f.textContent=o?`\u7B2C ${u+1} \u9875`:`Page ${u+1}`,f.onclick=()=>{ue(b.receiptId)},m.append(f)}if(d.review.page){let u=d.review.page,b=I.createElement("div");if(b.inert=!0,m.append(b),V=te(b,{mode:"live",rendererUrl:n.client.webViewUrl,title:u.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{},onEscape:()=>{fe()}}),V.update(u.document,d.run.locale,{serverInput:{bindings:u.inputs,answers:u.answers,values:u.values}}),await V.ready,h||i!==z||!E)return}let p=o?{issued:"\u5DF2\u9886\u53D6",reserved:"\u5DF2\u9884\u7559",redeemed:"\u5DF2\u4F7F\u7528",expired:"\u5DF2\u8FC7\u671F",revoked:"\u5DF2\u64A4\u9500",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},A=o?{pending:"\u5904\u7406\u4E2D",complete:"\u5DF2\u5B8C\u6210",cancelled:"\u5DF2\u53D6\u6D88",failed:"\u5931\u8D25",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{pending:"Processing",complete:"Completed",cancelled:"Cancelled",failed:"Failed",unknown:"Status unconfirmed"};for(let u of[...d.review.coupons.map((b,f)=>`${o?"\u4F18\u60E0\u5238":"Coupon"} ${f+1}: ${p[b.status]}`),...d.review.purchases.map((b,f)=>`${o?"\u8D2D\u4E70":"Purchase"} ${f+1}: ${A[b.status]}`)]){let b=I.createElement("p");b.textContent=u,m.append(b)}n.client.view&&await ne(n.client.view)}catch(d){if(i!==z||h)return;V?.destroy(),V=null,m.replaceChildren(),W(d)}}async function fe(){if(!E||h||!n.client.review)return;let e=++z;try{if(await n.client.review(),h||e!==z)return;E=!1,z++,V?.destroy(),V=null,m.replaceChildren(),m.hidden=!0,F.hidden=!1;let i=n.client.view;ye(i)!==ae?(le.set(ae,structuredClone(x)),L="",$=""):(le.delete(ae),D?.setSuspended(!1)),i&&await ne(i)}catch(i){if(e!==z||h)return;V?.destroy(),V=null,m.replaceChildren(),W(i)}}let Ne=n.client.subscribe(e=>{n.client.configurationReady===!1&&(v.hidden=!0,C?.destroy(),C=null,D?.destroy(),D=null,F.replaceChildren(),L="",$="",B="",R.open&&R.close()),ne(e).catch(W)}),Oe=n.client.subscribeError?.(W);function de(){return y||(h?Promise.resolve():n.client.view&&!["running","waiting"].includes(n.client.view.status)?(pe(),Promise.resolve()):(y=ee(()=>n.client.submit({operation:"close",...K()}),!0).then(()=>{n.client.view?.status==="closed"&&pe()}).finally(()=>{y=null}),y))}function pe(){h||(h=!0,r&&clearTimeout(r),Ne(),Oe?.(),C?.destroy(),z++,V?.destroy(),D?.destroy(),R.close(),R.remove(),v.remove(),Q instanceof HTMLElement&&Q.isConnected&&Q.focus(),re(n.onDismiss,j?structuredClone(j):null))}S.onclick=()=>{if(E){fe();return}ee(()=>n.client.submit({operation:"back",...K()}))},T.onclick=()=>{ue()},H.onclick=()=>{de()},k.onclick=()=>{ee(()=>n.client.retry())},R.addEventListener("cancel",e=>{e.preventDefault(),de()});try{let e=await n.client.get();await ne(n.client.view??e.run)}catch(e){throw pe(),e}return{destroy:pe,refresh:Ie,review:ue,exitReview:fe,get unappliedDrafts(){return new Map([...le].map(([e,i])=>[e,structuredClone(i)]))}}}export{Fe as showFunnelRun};