@tinkerlandai/longplay-sdk 0.10.29 → 0.10.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/dist/{chunk-VSWKFI3L.js → chunk-23WNEOK4.js} +1 -1
- package/dist/{chunk-S4JIOALC.js → chunk-2QQZSMTB.js} +1 -1
- package/dist/{chunk-PQJJ5BSY.js → chunk-2TPPGW7V.js} +1 -1
- package/dist/{chunk-TNN4S6VO.js → chunk-4ZVVG5LM.js} +1 -1
- package/dist/{chunk-FDCINOOI.js → chunk-5N7QFF5M.js} +1 -1
- package/dist/{chunk-O4KXODTJ.js → chunk-6BTJNSQQ.js} +1 -1
- package/dist/{chunk-JPHYIUIR.js → chunk-7Z7JT4HE.js} +1 -1
- package/dist/{chunk-AZ53RDWO.js → chunk-ACFQLHJR.js} +1 -1
- package/dist/{chunk-KAXKYBSI.js → chunk-B3KFE57L.js} +1 -1
- package/dist/{chunk-EUVKRGMO.js → chunk-BQLT2LDP.js} +1 -1
- package/dist/{chunk-VKDBROTE.js → chunk-D3UU546S.js} +1 -1
- package/dist/{chunk-Q2TQLDEH.js → chunk-EZ5RCVVY.js} +1 -1
- package/dist/{chunk-HZYCK4XJ.js → chunk-FJGJQGYF.js} +1 -1
- package/dist/{chunk-5X6WAPH3.js → chunk-FVGUBIVT.js} +1 -1
- package/dist/{chunk-7EPE2PUN.js → chunk-HJLGRW4A.js} +1 -1
- package/dist/{chunk-2JTMXZ5M.js → chunk-ITVSLSRM.js} +1 -1
- package/dist/{chunk-TLGKBSXC.js → chunk-J4VTKRH7.js} +1 -1
- package/dist/{chunk-MBKZYWPF.js → chunk-JNSU2AP2.js} +1 -1
- package/dist/{chunk-PNHGULO2.js → chunk-LZV4QJ5E.js} +1 -1
- package/dist/chunk-NH5ML5SB.js +1 -0
- package/dist/chunk-PI25NLDV.js +1 -0
- package/dist/{chunk-UWAZDSWO.js → chunk-QPHT6QHE.js} +1 -1
- package/dist/{chunk-GOYKJHDV.js → chunk-RBMOWJGE.js} +1 -1
- package/dist/{chunk-77GCT2VP.js → chunk-S57HRPT2.js} +1 -1
- package/dist/{chunk-SBSLHDBE.js → chunk-S5H3WJVQ.js} +1 -1
- package/dist/chunk-SJSCROSL.js +1 -0
- package/dist/{chunk-4OBCF5H3.js → chunk-TF2OFTYS.js} +1 -1
- package/dist/{chunk-6QJRT23Q.js → chunk-TMZGZAWM.js} +1 -1
- package/dist/{chunk-K72QA2PO.js → chunk-UWYL2QCF.js} +1 -1
- package/dist/{chunk-PKY55SBA.js → chunk-WK4WQZHK.js} +1 -1
- package/dist/{chunk-4WBIACS2.js → chunk-WRUW2UIJ.js} +1 -1
- package/dist/{chunk-VC2H3LFP.js → chunk-XIP32WI7.js} +1 -1
- package/dist/{chunk-YBX2LLRG.js → chunk-XZEGVBAI.js} +1 -1
- package/dist/chunk-YEXRETKV.js +1 -0
- package/dist/{chunk-CGSZBPSX.js → chunk-YXCEZAQL.js} +1 -1
- package/dist/{chunk-QZG2YXM4.js → chunk-ZYTT7ZAB.js} +1 -1
- package/dist/{content-S5MXIR7Y.js → content-OY5MRXF5.js} +1 -1
- package/dist/{funnel-host-purchase-7BRXGIJX.js → funnel-host-purchase-IRFPNIZY.js} +1 -1
- package/dist/{funnel-local-client-DoYVcZ1z.d.ts → funnel-local-client-D7e3rP5-.d.ts} +1 -1
- package/dist/{funnel-process-client-DtXNiFQ-.d.ts → funnel-process-client-BEPv6guV.d.ts} +1 -1
- package/dist/funnel-runtime-host-CJTPLZ4N.js +1 -0
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/merchant-bridge-contracts-LJKL7PNJ.js +1 -0
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/operation-contracts-SP2RZUT3.js +1 -0
- package/dist/page.js +1 -1
- package/dist/paywall-DI62MX5L.js +1 -0
- package/dist/paywall-session-AW6R3PJB.js +1 -0
- package/dist/popup.js +1 -1
- package/dist/react-native.d.ts +4 -4
- package/dist/react-native.js +1 -1
- package/dist/screen-renderer-W5MP4KVG.js +1 -0
- package/dist/server.d.ts +2 -2
- package/dist/server.js +1 -1
- package/dist/{visual-dom-5LUN4AHO.js → visual-dom-32PB6MMP.js} +1 -1
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-3GT4A3TA.js +0 -1
- package/dist/chunk-IDMOAV63.js +0 -1
- package/dist/chunk-JAUJZWYJ.js +0 -1
- package/dist/chunk-MMZR4I5X.js +0 -1
- package/dist/funnel-runtime-host-ITKTYBDS.js +0 -1
- package/dist/merchant-bridge-contracts-JCDMP54Z.js +0 -1
- package/dist/operation-contracts-B7I45NS3.js +0 -1
- package/dist/paywall-BEFHTZW7.js +0 -1
- package/dist/paywall-session-YVGZPSFM.js +0 -1
- package/dist/screen-renderer-ITUUNF4E.js +0 -1
- /package/dist/{chunk-CILM5XMH.js → chunk-PWXN3W4Q.js} +0 -0
- /package/dist/{chunk-OJM6ORHE.js → chunk-RFUXSC52.js} +0 -0
- /package/dist/{chunk-7GD2UTBU.js → chunk-ZY4XAKNQ.js} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as kn,b as rn,c as on,d as _e,e as Fn,f as We,h as Dn}from"./chunk-UWYL2QCF.js";import{c as Cn,d as Pn,e as Rn,f as Ae,g as Be,h as En,i as je,k as qn}from"./chunk-RBMOWJGE.js";import{$ as Qe}from"./chunk-ITVSLSRM.js";import{a as ze,e as gn,f as vn,g as hn,h as In,i as bn}from"./chunk-B3KFE57L.js";import{b as wn}from"./chunk-ACFQLHJR.js";import{R as fn,qa as yn}from"./chunk-WRUW2UIJ.js";import{a as P}from"./chunk-HJLGRW4A.js";import{b as Sn,e as On}from"./chunk-SLUA7ABW.js";import{d as Tn}from"./chunk-ZYTT7ZAB.js";import{a as le}from"./chunk-DSPLGTQI.js";import{b as mn}from"./chunk-6BTJNSQQ.js";var Te=new WeakMap;function Bn(n){let g=n.view,w=g?.paywall?.resolution;if(!g||!["running","waiting"].includes(g.status)||g.stopped||!w||"document"in w||!n.resolvePaywall||n.identitySignal?.aborted)return;let e=JSON.stringify(w);if(Te.get(n)?.key===e)return;let p=JSON.parse(e),D=n.identitySignal,a=Promise.resolve().then(async()=>{D?.throwIfAborted();let s=await n.resolvePaywall(p);return D?.throwIfAborted(),s}),S={key:e,content:a};return Te.set(n,S),a.catch(()=>{}),()=>{Te.get(n)===S&&Te.delete(n)}}function Nn(n,g){let w=Te.get(n);return Te.delete(n),w?.key===JSON.stringify(g)?w.content:n.resolvePaywall(g)}async function An(n){let{session:g,load:w}=Qn(n);try{return await w(),g}catch(e){throw g.destroy(),e}}function Qn(n){let g=n.view;if(!g?.paywall)throw new P("INVALID_REQUEST","The current node is not a Paywall");let w=g.paywall.receiptId,e=g.nodeId,p=g.visit,D=g.paywall.resolution,a=g.paywall,S="document"in D?{document:D.document,offering:D.offering,capabilities:D.capabilities}:null;function s(){let i=a.resolution;return"document"in i?i:S&&{...i,document:S.document,offering:S.offering,capabilities:gn(i.capabilities,S.capabilities)}}function v(i){if(!vn(i,D))throw new P("INVALID_RESPONSE","The pinned Paywall binding changed")}let u=!1,q=new Set,A=null;function V(){let i=s();if(i&&!u)for(let l of q)le(l,structuredClone(i))}async function k(){J();let i=s();if(i)return structuredClone(i);if(!A){let l=(async()=>{if("document"in a.resolution||!n.resolvePaywall)throw new P("INVALID_RESPONSE","Public Paywall reader is unavailable");let c=await Nn(n,a.resolution);return J(),v(c),S={document:c.document,offering:c.offering,capabilities:c.capabilities},V(),s()})();A=l;let o=()=>{A===l&&(A=null)};l.then(o,o)}return A.then(l=>structuredClone(l))}let d=new AbortController,F=(n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])).find(i=>i.operation==="submit"&&i.nodeId===e&&i.visit===p&&i.input.type==="paywall_quote")?.requestId??g.paywall.purchaseRequestId,R=0,M=null,C=new Set,H=null,h=new Map;function _(i){if(i.purchase&&i.purchase.receiptId!==w)throw new P("INVALID_RESPONSE","Purchase receipt changed");let l=i.run.paywall;return i.purchase??(l?.receiptId===w?l:null)}function J(){if(u)throw new P("IDENTITY_CHANGED","Paywall presentation has closed")}function z(i,l,o){if(J(),l!==R||o!==void 0&&a.quote?.operationId!==o)return!1;let c=a.selectionGeneration??0,y=i.run.paywall;if(y?.receiptId===w){if((y.selectionGeneration??0)<(a.selectionGeneration??0))return!1;v(y.resolution)}let I=_(i),B=y?.receiptId===w&&(y.selectionGeneration??0)>c,G=B?I?.quote??null:I?.quote??a.quote,b=I?.operation??(G?.operationId===a.quote?.operationId?a.operation:null);return G&&b&&hn(b,{operationId:G.operationId},"Purchase operation changed"),(B||G?.operationId!==a.quote?.operationId)&&(R++,y?.receiptId===w&&(F=y.purchaseRequestId)),y?.canReselect===!0&&y.purchaseRequestId===H&&!(n.pendingCommands??[n.pendingCommand]).some($=>$?.requestId===H)&&(H=null),a={...a,...y?.receiptId===w?y:{},quote:G,operation:bn(a.operation,b,!0)},V(),!0}function L(i,l,o){return new Promise((c,y)=>{let I=!1,B=()=>{clearTimeout(Re),d.signal.removeEventListener("abort",$)},G=Ee=>{I||(I=!0,B(),c(Ee))},b=Ee=>{I||(I=!0,B(),y(Ee))},$=()=>b(new P("IDENTITY_CHANGED","Paywall presentation has closed")),Re=setTimeout(()=>b(new P("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,o)),Math.max(0,l-Date.now()));d.signal.addEventListener("abort",$,{once:!0}),d.signal.aborted&&$(),i.then(G,b)})}function de(i){return new Promise(l=>{let o=()=>{clearTimeout(c),d.signal.removeEventListener("abort",o),l()},c=setTimeout(o,i);d.signal.addEventListener("abort",o,{once:!0}),d.signal.aborted&&o()})}function Y(i,l){J();let o=h.get(i)??n.pendingCommands?.find(I=>I.requestId===i)??n.pendingCommand;if(o?.operation==="submit"&&o.requestId===i&&o.nodeId===e&&o.visit===p){l.type==="paywall_quote"&&o.input.type==="paywall_quote"&&o.input.predecessor&&!l.predecessor&&(l={...l,predecessor:o.input.predecessor});let I=Qe.parse(o),B=Qe.parse({...o,input:l});if(I.operation!=="submit"||B.operation!=="submit"||JSON.stringify(I.input)!==JSON.stringify(B.input))throw new P("CONFLICT","A purchase request cannot change its input");return h.set(i,I),I}let c=n.view;if(!c||c.nodeId!==e||c.visit!==p||c.paywall?.receiptId!==w)throw new P("PRECONDITION_FAILED","The Paywall visit has changed");let y=Qe.parse({operation:"submit",requestId:i,nodeId:e,visit:p,revision:c.revision,input:structuredClone(l)});if(y.operation!=="submit")throw new P("INVALID_REQUEST","A purchase submission is required");return h.set(i,y),y}async function ce(i,l){J();let{requestId:o,input:c}=i,y=Date.now()+3e4;C.add(o);try{let I=await L(n.submit(i),y,o);for(;I.run.pendingRequest?.requestId===o&&Date.now()<y&&!u&&(await de(Math.min(1e3,y-Date.now())),!(u||Date.now()>=y));)I=await L(n.resume(o),y,o);if(u)throw new P("IDENTITY_CHANGED","Paywall presentation has closed");if(I.run.pendingRequest?.requestId===o)throw new P("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,o);if(!z(I,l,c.type==="paywall_confirm"||c.type==="paywall_cancel"?c.operationId:void 0))throw new P("PRECONDITION_FAILED","The purchase selection has changed");H===o&&(H=null)}catch(I){if(H=o,c.type==="paywall_quote"&&n.settle&&!u&&I instanceof P&&I.status!==void 0&&![401,425].includes(I.status)&&!I.retryable&&I.recovery!=="recover_operation")try{if((await L(n.settle(o),y,o)).settlement?.state==="settled"){let G=await L(n.get(),y,o);z(G,l)&&G.run.paywall?.purchaseRequestId===o&&a.canReselect===!0&&h.delete(o)}}catch{}throw I instanceof P&&I.code==="COMMAND_PENDING"&&I.status===void 0&&h.delete(o),I}finally{C.delete(o)}}async function re(i){if(!a.quote)throw new P("INVALID_REQUEST","A quoted purchase is required");let l=i==="confirm"?"paywall_confirm":"paywall_cancel",o=[...h.values(),...n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])].find(y=>y.operation==="submit"&&y.input.type===l&&"operationId"in y.input&&y.input.operationId===a.quote.operationId),c=o?.operation==="submit"&&o.input.type===l&&"operationId"in o.input&&o.input.operationId===a.quote.operationId?o.requestId:crypto.randomUUID();if(await ce(Y(c,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:a.quote.operationId}),R),!a.operation)throw new P("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(a.operation)}let T={get view(){return structuredClone(s())},get quote(){return a.quote?structuredClone(a.quote):null},get operation(){return a.operation?structuredClone(a.operation):null},get webViewUrl(){return n.webViewUrl},get canReselect(){return a.canReselect===!0&&H===null},get recovery(){let i=n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[]),l=n.pendingPurchase;if(l&&(l.receiptId!==w||l.operationId!==a.quote?.operationId))return{type:"recover",operationId:l.operationId,requestId:i[0]?.requestId??null};let o=ze({quote:a.quote,operation:a.operation,requestId:i[0]?.requestId??H??F,pending:C.size>0||i.length>0||H!==null,destroyed:u,canReselect:a.canReselect});return o.type==="recover"&&o.requestId===null&&!u&&n.hasDurableJournal===!0&&!a.quote&&!a.operation&&(a.selectionGeneration??0)===0&&!l&&!i.length&&!C.size&&!F?{type:"native",operationId:null}:o},get pendingCancellation(){return!u&&(n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])).some(i=>i.operation==="submit"&&i.nodeId===e&&i.visit===p&&i.input.type==="paywall_cancel"&&i.input.operationId===a.quote?.operationId)},subscribe(i){return u?()=>{}:(q.add(i),()=>q.delete(i))},async refresh(){J();let i=R,l=await n.get();if(z(l,i),l.run.paywall?.receiptId!==w)throw new P("PRECONDITION_FAILED","Paywall presentation has changed");return k()},preview(i){let l=s();if(!l)return Promise.reject(new P("PRECONDITION_FAILED","Load the Paywall presentation first"));if(F&&F!==i.requestId&&(M||a.canReselect!==!0))return Promise.reject(new P("COMMAND_PENDING","Retry the original purchase before starting another"));let o=l.document.buttons[i.actionId],c=o?.type==="checkout"?wn(o.product,i.selection,l.capabilities):null;if(!c)return Promise.reject(new P("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let y=yn(l.document.screen,c,i.selection,l.capabilities),I=F!==i.requestId&&(a.selectionGeneration??0)>0?{operationId:a.quote?.operationId??null,generation:a.selectionGeneration??0}:void 0;if(I&&a.canReselect!==!0)return Promise.reject(new P("COMMAND_PENDING","Original purchase requires authoritative termination"));let B;try{B=Y(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:c,...Object.keys(y).length?{featureQuantities:y}:{},...I?{predecessor:I}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{}})}catch($){return Promise.reject($)}if(F===i.requestId&&M)return M;F!==i.requestId&&R++;let G=R;F=i.requestId;let b=(async()=>{if(await ce(B,G),!a.quote)throw new P("INVALID_RESPONSE","The accepted quote is missing");return In(a.quote,{productVersionId:c,featureQuantities:y},"The selected purchase changed"),structuredClone(a.quote)})();return M=b,b.then(()=>{M===b&&(M=null)},$=>{M===b&&(M=null),F===i.requestId&&n.pendingCommand?.requestId!==i.requestId&&$ instanceof P&&$.status!==void 0&&$.status<500&&![401,425].includes($.status)&&(F=null)}),b},confirm:()=>re("confirm"),cancel:()=>re("cancel"),async read(){if(J(),!a.quote)throw new P("INVALID_REQUEST","A quoted purchase is required");let i=a.quote.operationId,l=R,o=n.pendingCommands?.find(G=>G.operation==="submit"&&(G.input.type==="paywall_confirm"||G.input.type==="paywall_cancel")&&G.input.operationId===i)??n.pendingCommand;o?.operation==="submit"&&(o.input.type==="paywall_confirm"||o.input.type==="paywall_cancel")&&o.input.operationId===i&&await n.settle?.(o.requestId);let c=await n.get(void 0,{receiptId:w,operationId:i});J();let y=_(c);if(y?.quote&&y.quote.operationId!==i||y?.operation&&y.operation.operationId!==i)throw new P("INVALID_RESPONSE","Purchase operation changed");let I=z(c,l,i),B=I?a.operation:y?.operation;if(!B)throw new P("INVALID_RESPONSE","The current purchase result is missing");return I&&C.size===0&&!(n.pendingCommands?.length??(n.pendingCommand?1:0))&&(H=null),structuredClone(B)},destroy(){u=!0,E(),q.clear(),d.abort(),h.clear()}},E=n.subscribe(i=>{u||i.nodeId!==e||i.visit!==p||i.paywall?.receiptId!==w||(i.paywall.selectionGeneration??0)<(a.selectionGeneration??0)||(v(i.paywall.resolution),a={...a,resolution:i.paywall.resolution},V())});return{session:T,load:k}}function _n(n){let g=new Set,w=new Set,e=null;async function p(s,v){let u=!1;for(;!n.stopped&&n.key===s&&n.client.pendingCommand?.requestId===v;){if(!n.client.settle)throw new P("COMMAND_PENDING","The original display acknowledgement is still pending");await n.client.settle(v),u=!0,n.client.pendingCommand?.requestId===v&&await new Promise(q=>setTimeout(q,1500))}n.stopped||n.key!==s||(u&&await n.client.get(),!(n.stopped||n.key!==s)&&g.add(s))}function D(s,v){e=v;let u=()=>{e===v&&(e=null),w.delete(s)};return v.then(u,q=>{u(),n.busy||n.fail(q)}),v}function a(s){if(n.reviewing||g.has(s)||w.has(s)||n.stopped)return;w.add(s);let v=async()=>{if(n.reviewing||n.stopped||n.key!==s||g.has(s)){w.delete(s);return}if(n.busy||n.client.pendingCommand){setTimeout(()=>{v()},250);return}let u=(async()=>{if(n.staleRead){if(await n.staleRead,n.stopped||n.key!==s)return;if(n.client.pendingCommand){setTimeout(()=>{v()},250);return}}let q=n.client.view,A=n.expected(),V=A.requestId;try{await n.client.submit({operation:"shown",...A})}catch(k){if(!(k instanceof P)||k.code!=="CONFLICT"||k.status!==409||n.client.pendingCommand)throw k;await n.client.get();let d=n.client.view;if(n.stopped||n.reviewing||n.key!==s||!d||!q||d.id!==q.id||d.source.versionId!==q.source.versionId||d.nodeId!==A.nodeId||d.visit!==A.visit||d.revision<=A.revision||d.stopped||!d.screen&&(!d.paywall||d.paywall.receiptId!==q.paywall?.receiptId)||!["running","waiting"].includes(d.status)||n.client.pendingCommand)throw k;let O=n.expected();V=O.requestId,await n.client.submit({operation:"shown",...O})}await p(s,V)})();D(s,u)};v()}function S(){if(e)return e;let s=n.client.pendingCommand;if(s?.operation!=="shown")return null;let v=n.key;return w.add(v),D(v,(async()=>{await n.client.retry(),await p(v,s.requestId)})())}return{report:a,settled:S,get inFlight(){return e}}}function Ln(n){let g={},w=new Map;async function e(p){let D=n.client.view,a=D?.screen,S=a?.customerData.nodes[p.nodeId];if(n.stopped||n.busy||!D||!a||!S)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(p.action)){let k=n.document,d=k?fn(k,p.nodeId):null,O=d?.type==="customer_data"?d.data.outputs?.[p.action]:void 0;O&&a.outputs.includes(O)?await n.perform(()=>n.client.submit({operation:"submit",...n.expected(),input:{type:"screen",output:O,answers:n.answers,selection:p.value?{[p.nodeId]:p.value}:{}}})):await n.onIntent?.(p,D);return}let v=p.action.startsWith("sources_")?S.resources.find(k=>k.key===p.value):null;if(p.action.startsWith("sources_")&&!v)throw new P("INVALID_REQUEST","Choose a current resource");let u=`${D.visit}:${p.nodeId}:${v?.key??""}`,q=w.get(u)??[null],V=g[p.nodeId]??{page:1,after:null,filter:"all",...v?{resourceKey:v.key}:{}};if(p.action==="filter"){let k=p.value;if(!k||!(S.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(k))throw new P("INVALID_REQUEST","Unknown data filter");V={page:1,after:null,filter:k},q.splice(0,q.length,null)}else if(p.action==="next"||p.action==="sources_next"){let k=v?.sources.at(-1),d=v?k?{kind:"ledger",cursor:{at:k.detail[0],id:k.id,type:"source"}}:null:a.dataCursors[p.nodeId];if(!d||!v&&!S.hasNext)return;q[V.page]=d,V={...V,page:V.page+1,after:d}}else if(p.action==="previous"||p.action==="sources_previous"){if(V.page<=1)return;V={...V,page:V.page-1,after:q[V.page-2]??null}}w.set(u,q),g={...g,[p.nodeId]:V},await n.perform(()=>n.client.get({nodeId:D.nodeId,visit:D.visit,revision:D.revision,components:g}))}return{get queries(){return g},intent:e,reset(){g={},w.clear()}}}function Vn(n){let{doc:g,holder:w,reviewHolder:e,mountScreenPreview:p}=n,D=!1,a,S=0,s=null,v="",u,q=new Map,A=d=>d?`${d.id}:${d.nodeId}:${d.visit}:${d.revision}:${d.paywall?.quote?.operationId??""}`:"";async function V(d){if(n.stopped||!n.client.review||D&&d===a&&u?.active)return;let O=!D||d!==a;D||(v=A(n.client.view),q.set(v,structuredClone(n.answers))),D=!0,a=d,w.hidden=!0,n.suspend(!0),e.hidden=!1;let F=++S;O&&(u?.finish("dismissed"),s?.destroy(),s=null,e.replaceChildren(),u=Be(e,n.loadingOptions,"funnel",()=>{k()}));let R=O?u:void 0;try{if(R?.start(!1,n.client.view?.locale),F!==S||n.stopped)return;let M=n.client.review(d),C=await(R?.wait(M,Ae)??M);if(n.stopped||F!==S||!D)return;if(!C.review)throw new P("INVALID_RESPONSE","Historical projection is missing");s?.destroy(),s=null,R||e.replaceChildren();let H=g.createElement("div"),h=R?je(H,e):()=>{};e.append(H);let _=C.run.locale.startsWith("zh"),J=n.chrome;H.style.cssText=J.history;let z=g.createElement("p");z.textContent=_?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",z.style.cssText=J.historyTitle,H.append(z);let L=g.createElement("p");L.style.cssText=J.historyNote,L.textContent=C.review.pages.length?_?"\u9009\u62E9\u4E00\u9875\u67E5\u770B\u5F53\u65F6\u7684\u5185\u5BB9\uFF0C\u56DE\u770B\u4E0D\u4F1A\u6539\u52A8\u4EFB\u4F55\u4FE1\u606F\u3002":"Choose a page to see it as it was. Nothing here can be changed.":_?"\u8FD8\u6CA1\u6709\u53EF\u56DE\u770B\u7684\u9875\u9762\u3002":"There are no earlier pages yet.",H.append(L);let de=C.review.page?.receiptId,Y=g.createElement("div");Y.style.cssText=J.historyPages;for(let[T,E]of C.review.pages.entries()){let i=g.createElement("button");i.type="button",i.textContent=_?`\u7B2C ${T+1} \u9875`:`Page ${T+1}`;let l=de!==void 0&&E.receiptId===de;i.style.cssText=l?J.primary:J.secondary,l&&i.setAttribute("aria-current","page"),_e(i,()=>n.chrome.focus),i.onclick=()=>{V(E.receiptId)},Y.append(i)}if(Y.childElementCount&&H.append(Y),C.review.page){let T=C.review.page,E=g.createElement("div");E.inert=!0,E.style.cssText=J.historyPage,H.append(E),s=p(E,{mode:"live",rendererUrl:n.client.webViewUrl,title:T.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{F===S&&!n.stopped&&R?.present(h)},onError:l=>{if(F!==S||n.stopped)return;let o=new Error(l);R?.finish("error",o),s?.destroy(),s=null,H.remove(),n.fail(o)},onEscape:()=>{k()}});let i=s;if(i.update(T.document,C.run.locale,{serverInput:{bindings:T.inputs,answers:T.answers,values:T.values}}),await i.ready,n.stopped||F!==S||!D)return}let ce=_?{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"},re=g.createElement("div");re.style.cssText=J.historyRecords;for(let T of[...C.review.coupons.map((E,i)=>`${_?"\u4F18\u60E0\u5238":"Coupon"} ${i+1}: ${ce[E.status]}`),...C.review.purchases.map((E,i)=>`${_?"\u8D2D\u4E70":"Purchase"} ${i+1}: ${Dn(E.status,_)}`)]){let E=g.createElement("p");E.textContent=T,E.style.margin="0",re.append(E)}re.childElementCount&&H.append(re),C.review.page||R?.present(h),n.client.view&&await n.enqueue(n.client.view)}catch(M){if(F!==S||n.stopped)return;R?.finish("error",M),s?.destroy(),s=null,e.replaceChildren(),n.fail(M)}}async function k(){if(!D||n.stopped||!n.client.review)return;let d=++S;u?.finish("dismissed");try{if(await n.client.review(),n.stopped||d!==S)return;D=!1,S++,u?.finish("dismissed"),s?.destroy(),s=null,e.replaceChildren(),e.hidden=!0,w.hidden=!1;let O=n.client.view;A(O)!==v?(q.set(v,structuredClone(n.answers)),n.resetScreen()):(q.delete(v),n.suspend(!1)),O&&await n.enqueue(O)}catch(O){if(d!==S||n.stopped)return;s?.destroy(),s=null,e.replaceChildren(),n.fail(O)}}return{get active(){return D},get receipt(){return a},open:V,exit:k,get drafts(){return new Map([...q].map(([d,O])=>[d,structuredClone(O)]))},stop(){D=!1,S++,u?.finish("dismissed"),s?.destroy(),s=null,e.replaceChildren(),e.hidden=!0,w.hidden=!1}}}function Mn(n){if(!n.client.pageExperiments)throw new Error("The Run controller does not support page experiments");let g=n.client.pageExperiments.bind(n.client),w=!1,e=!1,p=0,D=!1,a=!1,S="",s=()=>{let h=n.client.view;return JSON.stringify([h?.id,h?.source.versionId,h?.visit,h?.revision,h?.status,h?.stopped])},v=new Map,u=new Set,q={},A=new Map,V=Sn(n.appManifestRelease),k=()=>{for(let h of v.values())h.effect.revert();v.clear()},d=()=>{k();for(let h of A.values())h();A.clear()};function O(h){if(w||u.has(h))return;u.add(h);let _=p;g(n.appManifestRelease,[h]).catch(J=>{u.delete(h),!w&&_===p&&le(n.onError,J)})}async function F(){if(w)return;S=s();let h=n.client.view;if(!h||h.stopped||!["running","waiting"].includes(h.status)){p++,d();return}if(document.visibilityState==="hidden")return;if(D){a=!0;return}D=!0;let _=++p,J=`${h.id}:${h.visit}:${h.revision}`,z=location.href;try{let[L,{applyVisualVariation:de}]=await Promise.all([g(n.appManifestRelease),import("./visual-dom-32PB6MMP.js")]),Y=n.client.view;if(w||_!==p||!Y||Y.stopped||!["running","waiting"].includes(Y.status)||`${Y.id}:${Y.visit}:${Y.revision}`!==J||location.href!==z)return;let ce=new Set,re=new Set;for(let T of L.assignments){let E=`${L.payload.environmentId}:${T.experimentKey}`;if(re.add(E),A.has(E)||A.set(E,On(E,q)),!!T.inExperiment)for(let i of L.payload.experiments){if(i.key!==T.experimentKey||!mn(location.href,i.urlPatterns??[]))continue;let l=i.meta?.findIndex(G=>G.key===T.variationKey)??-1,o=i.variations[l];if(!o?.renderGuard)continue;let c=T.receiptId+":"+i.changeId,y=JSON.stringify([T.variationKey,o]);ce.add(c);let I=v.get(c);if(I?.signature===y){I.effect.applied&&O(T.receiptId);continue}v.get(c)?.effect.revert(),v.delete(c);let B=de(o,{requireUniqueTargets:!0,boundVariations:i.variations,allowJs:!1,onApplied:()=>O(T.receiptId),onError:G=>le(n.onError,G)});v.set(c,{signature:y,effect:B}),B.applied&&O(T.receiptId)}}for(let[T,E]of v)ce.has(T)||(E.effect.revert(),v.delete(T));for(let[T,E]of A)re.has(T)||(E(),A.delete(T))}catch(L){_===p&&d(),!w&&_===p&&le(n.onError,L)}finally{D=!1,a&&!w&&(a=!1,F())}}let R=n.client.subscribe(()=>{if(s()===S)return;S=s(),p++;let h=n.client.view;(!h||h.stopped||!["running","waiting"].includes(h.status))&&d(),e&&F()}),M=Tn(()=>{p++,d(),e&&F()}),C=()=>{p++,k()};document.addEventListener("visibilitychange",C);let H=We({document,run:async()=>{e&&await F()},delay:()=>e&&!w?15e3:void 0});return{async start(){e||w||(e=!0,await H.refresh())},refresh:F,destroy(){w=!0,p++,H.destroy(),document.removeEventListener("visibilitychange",C),R(),M(),d(),V.destroy()}}}var sn=5e3;async function zn(n,g,w){let e=g,[{mountScreenPreview:p},{showPaywall:D}]=await Promise.all([import("./screen-renderer-W5MP4KVG.js"),import("./paywall-DI62MX5L.js")]),a=e.client.identitySignal;e.signal?.throwIfAborted(),a?.throwIfAborted();let S=e.appManifestRelease?Mn({client:e.client,appManifestRelease:e.appManifestRelease,onError:e.onError}):void 0;S?.start();let s=n.ownerDocument,v=qn(s),u=s.createElement("section"),q=s.createElement("div"),A=s.createElement("div"),V=s.createElement("div"),k=s.createElement("button");V.hidden=!0,k.type="button";let d=s.createElement("p"),O=s.createElement("p"),F=s.createElement("button"),R=s.createElement("button"),M=s.createElement("button"),C=s.createElement("dialog"),H;u.dataset.indianaFunnel="",u.setAttribute("aria-busy","false"),d.setAttribute("role","status"),O.setAttribute("role","alert"),O.hidden=!0,F.type=R.type=M.type="button",A.append(F,k,d,O,M,R),u.append(q,V,A),n.append(u);let h=kn,_=rn(h),J="",z=(s.documentElement.lang||"").startsWith("zh"),L,de="",Y;for(let t of[F,k,M,R])_e(t,()=>_.focus);function ce(){let t=z?"\u5173\u95ED":"Close";R.parentElement===C?(R.textContent="\xD7",R.setAttribute("aria-label",t),Rn(R,h)):(R.textContent=t,R.removeAttribute("aria-label"),R.style.cssText=_.link+";margin-inline-start:auto")}function re(t){let r=t?.screen?.content.document.theme??h,f=JSON.stringify([r.primary,r.background,r.text,r.radius,r.font,R.parentElement===C]);f!==J&&(J=f,h=r,_=rn(h,R.parentElement===C),u.style.cssText=_.root+";min-width:0",A.style.cssText=_.bar,F.style.cssText=k.style.cssText=_.secondary,M.style.cssText=_.primary,d.style.cssText=_.status,O.style.cssText=_.alert,ce(),on(F))}function T(){A.hidden=F.hidden&&k.hidden&&M.hidden&&O.hidden&&!d.textContent&&(R.hidden||R.parentElement!==A),L?.responsive&&Y!==void 0&&L.setContentHeight(Y+A.getBoundingClientRect().height)}re();let E=null,i=null,l=null,o="",c="",y=!1,I="",B="",G="",b=!1,$=0,Re=!1,Ee="",Ke=null,Ye=Promise.resolve(),an=!e.client.view,W=w,qe,Oe,Le="",Ve,pe=!1,Ie=null,ye=!1,Me=()=>e.client.pendingCommand?.operation==="close",se=null,K=null,ln=We({document:s,run:async()=>{(!i?.observing||e.client.pendingCommand)&&await Ze()},delay:()=>{if(!(b||!l||!["running","waiting"].includes(l.status)&&!e.client.pendingCommand)&&!(i?.observing&&!e.client.pendingCommand))return l.pendingRequest||e.client.pendingCommand?1500:sn},hiddenDelay:()=>!b&&e.client.pendingCommand?15e3:void 0}),X=null;function Xe(){return K&&e.client.hasDurableJournal===!0&&X?.acknowledged===!0&&X.operationId===K.operationId&&e.client.view?.id===X.runId&&e.client.view?.status==="closed"&&e.client.view.revision===X.revision+1&&!(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0))&&!e.client.pendingPurchase?K:null}function un(t){let r=t.run.paywall;if(X&&t.settlement?.requestId===X.requestId&&t.settlement.state==="settled"&&t.settlement.operationId===null&&t.run.id===X.runId&&t.run.status==="closed"&&!t.run.pendingRequest&&t.run.revision===X.revision+1&&t.run.nodeId===X.nodeId&&t.run.visit===X.visit&&r?.receiptId===X.receiptId&&r.selectionGeneration===X.selectionGeneration&&(r.quote?.operationId??null)===X.operationId&&(r.operation?.operationId??r.quote?.operationId??null)===X.operationId){let f=X.operationId===null&&r.selectionGeneration===0&&!r.quote&&!r.operation&&!r.purchaseRequestId,ne=ze({quote:r.quote,operation:r.operation,requestId:r.purchaseRequestId,pending:!1,destroyed:!1,canReselect:r.canReselect});(f||r.canReselect===!0&&ne.type==="native")&&(X.acknowledged=!0)}}let ke=null,He=new Set,fe={},Fe=!1,ue=(t,r=null)=>{b||(ke=r,Fe=!1,O.textContent=Fn(t,z),O.hidden=!1,M.hidden=e.client.pendingCommand===null,T(),le(e.onError,t))};function be(){let t=e.client.view;if(!t)throw new P("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision}}let U=Vn({client:e.client,doc:s,holder:q,reviewHolder:V,mountScreenPreview:p,loadingOptions:e,get chrome(){return _},get stopped(){return b},get answers(){return fe},suspend(t){i?.setSuspended(t)},resetScreen(){o="",c="",I=""},enqueue:me,fail:ue}),$e=_n({client:e.client,expected:be,fail:ue,get stopped(){return b},get reviewing(){return U.active},get key(){return o},get busy(){return $},get staleRead(){return Ke}}),Ue=Ln({client:e.client,expected:be,perform:Se,onIntent:e.onCustomerDataIntent,get stopped(){return b},get busy(){return $},get document(){return E?.document},get answers(){return fe}}),xe=t=>`${t.id}:${t.nodeId}:${t.visit}`,De=t=>t&&(t.screen||t.paywall)?xe(t):"";function Ce(){let t=e.client.view;F.disabled=!U.active&&($>0||!!e.client.pendingCommand||!t?.canBack||t.stopped||!["running","waiting"].includes(t.status)||!De(t)||c!==De(t)),F.hidden=!U.active&&!t?.canBack,on(F);let r=!!i&&!U.active;R.hidden=r&&!W?.active,k.hidden=!e.client.review||r&&!t?.canBack,r&&(d.textContent=""),T()}async function dn(t){if(!t)return;let r=e.client.view;await t;let f=e.client.view;if(!r||!f||f.id!==r.id||f.nodeId!==r.nodeId||f.visit!==r.visit||f.stopped||!["running","waiting"].includes(f.status))throw new P("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Se(t,r=!1){if(!(($||ye||se||K)&&!r||b||U.active&&!r)){$++,u.setAttribute("aria-busy","true"),O.hidden=!0,ke=null,Fe=!1,Ce();try{if(r||await dn($e.inFlight),b)return;let f=await t();b||await me(e.client.view??f.run)}catch(f){ue(f,e.client.pendingCommand?.requestId??null)}finally{$=Math.max(0,$-1),u.setAttribute("aria-busy",String($>0)),b||(M.hidden=e.client.pendingCommand===null,Ce())}}}function Ne(){ln.schedule()}async function Ze(){if(!(b||Re||$)){if(U.active){await U.open(U.receipt);return}Re=!0;try{let t=e.client.pendingCommand;t&&e.client.settle&&await e.client.settle(t.requestId);let r=e.client.view,f=Ue.queries,ne=await e.client.get(r?.screen&&Object.keys(f).length?{nodeId:r.nodeId,visit:r.visit,revision:r.revision,components:f}:void 0);Fe&&!b&&(Fe=!1,O.hidden=!0,T()),!b&&f===Ue.queries&&await me(e.client.view??ne.run)}catch(t){ue(t),Fe=!b}finally{Re=!1}}}function Ge(t,r){if(W?.active){let ne=W;return ne.setDismissHandler(()=>cn(ne)),ne}let f=Be(n,e,"funnel",()=>cn(f));return W=f,f.start(t,r),f}function cn(t){b||pe||(pe=!0,t.finish("dismissed"),ve(),u.hidden=!0,e.client.view?Pe().finally(ae):ae())}function en(){clearTimeout(Ve?.timeout),Ve=void 0}function ve(){en(),qe?.abort(),qe=void 0,E?.destroy(),E=null,i?.destroy(),i=null,Oe?.(),Oe=void 0,C.open&&C.close(),q.replaceChildren(),q.style.cssText="",Y=void 0,o="",c="",y=!1,I="",G=""}function pn(){let t=s.defaultView;L?.responsive&&t&&E?.resizeViewport?.(t.innerHeight,t.innerWidth)}function nn(){L?.destroy(),L=void 0,de=""}function tn(t){let r=t.screen?.presentation;if(!r||r.type==="inline"){C.open&&C.close(),nn(),R.parentElement!==A&&A.append(R),u.parentElement!==n&&n.append(u),re(t),T();return}u.parentElement!==C&&(C.append(R,u),n.append(C)),re(t);let f=t.screen.content.document,ne=JSON.stringify([r,J]);if(ne!==de){nn(),de=ne;let ge={sm:420,md:640,lg:900},we="size"in r&&!r.backdrop?",0 0 0 100vmax #16142566":"";C.style.cssText=`box-sizing:border-box;padding:0;border:0;overflow:auto;background:${h.background};color:${h.text};`+(r.type==="fullscreen"?"width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;margin:0;border-radius:0":`width:${ge[r.size]}px;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0003${we};`+(r.type==="sheet"?"margin:auto auto 0;border-radius:14px 14px 0 0":"border-radius:14px")),L=Cn(C,{presentation:r,theme:f.theme,pages:f.pages},pn),L.latch()}T(),C.setAttribute("aria-label",(H?.screen===t.screen?.content.document.name?H?.label:void 0)??E?.document?.name??t.screen?.content.document.name??"Funnel")}async function Hn(t){if(b||pe||ye&&(Me()||["running","waiting"].includes(t.status))||(l=t,ke&&e.client.pendingCommand?.requestId!==ke&&(O.hidden=!0,ke=null),z=t.locale.startsWith("zh"),k.textContent=z?"\u56DE\u770B":"History",F.textContent=U.active?z?"\u8FD4\u56DE\u5F53\u524D":"Return to current":z?"\u8FD4\u56DE":"Back",ce(),M.textContent=z?"\u91CD\u8BD5":"Retry",M.hidden=e.client.pendingCommand===null,d.textContent=t.pendingRequest?z?"\u6B63\u5728\u5904\u7406":"Processing":t.instruction?.type==="wait"?z?"\u7B49\u5F85\u4E2D":"Waiting":"",Ce(),Ee!==`${t.revision}:${t.visit}:${t.status}:${t.stopped}`&&(Ee=`${t.revision}:${t.visit}:${t.status}:${t.stopped}`,le(e.onState,structuredClone(t))),b||pe))return;if((!t.pendingRequest||ye&&t.status==="closed")&&["closed","ineligible","failed"].includes(t.status)){ae();return}if(t.stopped||e.client.configurationReady===!1){U.stop(),ve(),W?.finish("skipped"),u.hidden=!0,Ne();return}if(u.hidden=!1,U.active){Ne();return}let r=De(t),f=e.client.view;if(f&&f.revision>t.revision&&De(f)!==r)return;let ne=!t.instruction&&!t.pendingRequest&&t.nodeType==="screen"&&["running","waiting"].includes(t.status);r!==o&&(o&&W?.finish("dismissed"),ve(),o=r,fe={...t.answers},Ue.reset());let ge=xe(t);if(Le===ge){u.hidden=!0;return}if(ne&&!r){u.hidden=!0;let Q=Ge(!0,t.locale);!b&&!pe&&Ve?.key!==ge&&(en(),Ve={key:ge,timeout:setTimeout(()=>{let m=e.client.view;if(!Q.active||!m||xe(m)!==ge)return;Le=ge;let j=new Error("Funnel screen preparation timed out");Q.finish("error",j),ve(),ue(j)},Ae)}),Ne();return}en();let Z=Q=>{let m=e.client.view;return!b&&!pe&&!Ie&&!Q.aborted&&e.client.configurationReady!==!1&&!!m&&!m.stopped&&!["closed","ineligible","failed"].includes(m.status)&&De(m)===r},we=(Q,m)=>{Z(m)&&(Le=r,W?.finish("error",Q),ve(),u.hidden=!0,ue(Q))};if(r||(tn(t),t.instruction?.type!=="event"&&t.instruction?.type!=="open_url"&&W?.finish("skipped")),t.screen){let Q=t.screen.content;if(!E){let te=t.screen.presentation.type!=="inline",oe=Ge(te,t.locale);if(b||pe)return;let ie=(qe=new AbortController).signal;tn(t),Oe=te?En(C):je(u,n),E=p(q,{mode:"live",rendererUrl:e.client.webViewUrl,title:Q.document.name,...te?{hostPresentation:()=>L?.type??t.screen.presentation.type}:{},onResize:ee=>{Y=ee,L?.responsive&&L.setContentHeight(ee+A.getBoundingClientRect().height)},onAction(ee,he={},Gn={}){if(U.active||!Z(ie)||c!==r)return;fe={...fe,...Gn};let Jn=Object.fromEntries((t.screen?.inputs??[]).filter(({variable:Je})=>Object.hasOwn(fe,Je)).map(({variable:Je})=>[Je,fe[Je]]));Se(()=>e.client.submit({operation:"submit",...be(),input:{type:"screen",output:ee,answers:Jn,selection:he}}))},onAnswers:ee=>{U.active||!Z(ie)||c!==r||(fe={...fe,...ee})},onCustomerDataIntent:ee=>{U.active||!Z(ie)||c!==r||Ue.intent(ee).catch(ue)},onEscape:()=>{!Z(ie)||c!==r||U.active||se||K||Pe()},onError:ee=>{let he=new Error(ee);c===r?ue(he):we(he,ie)},onRendered:ee=>{if(!(!Z(ie)||c===r))try{oe.present(he=>{Oe?.(),Oe=void 0,ee&&(H={screen:Q.document.name,label:ee},C.setAttribute("aria-label",ee)),te&&(C.showModal(),L?.responsive&&C.focus({preventScroll:!0}),!he&&e.loading!=="host"&&Pn(C,L?.type??t.screen.presentation.type,L?.responsive)),c=r,y=te,Ce()}),Z(ie)&&$e.report(r)}catch(he){we(he,ie)}}}),pn()}let m={capabilities:t.screen.capabilities,customerData:t.screen.customerData,parameters:t.parameters,serverInput:{bindings:t.screen.inputs,answers:fe,values:t.screen.values}},j=JSON.stringify([Q,t.locale,m.parameters,t.screen.inputs,t.screen.values]);if(j!==I)E.update(Q.document,t.locale,m),I=j,B=JSON.stringify(m.capabilities),G=JSON.stringify(m.customerData);else{let te=JSON.stringify(m.capabilities);te!==B&&(E.updateCapabilities(m.capabilities),B=te),JSON.stringify(m.customerData)!==G&&(E.updateCustomerData(m.customerData),G=JSON.stringify(m.customerData))}let x=E;if(x)try{await(W?.wait(x.ready)??x.ready)}catch(te){qe&&we(te,qe.signal)}}else if(t.paywall&&!i){let Q=Ge(!0,t.locale);if(b||pe)return;let m=(qe=new AbortController).signal;tn(t);let j=await D(q,{loading:"host",signal:m,canInteract:()=>Z(m)&&!U.active&&!se&&!K,beforeAction:async()=>{$++;try{await dn($e.settled()),O.hidden=!0,ke=null,Fe=!1,T()}finally{$=Math.max(0,$-1)}},start:()=>An(e.client),onObservationChange:Ne,onPurchase:e.onPurchase,onCheckoutUrl:e.onCheckoutUrl,checkoutNavigation:e.checkoutNavigation,confirmOnHostedCheckout:e.confirmOnHostedCheckout,resolveOfferId:e.resolveOfferId,onEvent:e.onEvent,onOpenUrl:x=>e.onOpenUrl?e.onOpenUrl({receiptId:t.paywall.receiptId,url:x,openIn:"same_window"}):s.defaultView?.location.assign(x),onAction:async x=>{if(U.active)return;let te=await e.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:e.client.view?.revision??t.revision,input:{type:"screen",output:x,answers:{}}});await me(e.client.view??te.run)},onError:x=>{c===r?ue(x):we(x,m)}},{quoteError:x=>le(e.onError,x),present(x){Z(m)&&(Q.present(()=>{x(),c=r,y=!!q.querySelector("dialog[open]"),Ce()}),Z(m)&&$e.report(r))},async dismiss(){b||m.aborted||U.active||se||K||!ye&&!Z(m)||(ye=!0,await Pe())}}).catch(x=>(we(x,m),null));!Z(m)&&!(ye&&!b&&!m.aborted)?j?.host?.destroy():j&&(i=j.host,i?.setSuspended(U.active))}if(b||pe)return;Ce();let N=t.instruction;if(N&&(N.type==="open_url"||N.type==="event")&&!He.has(N.receiptId)){let Q=s.createElement("button");Q.type="button",Q.style.cssText=_.primary,_e(Q,()=>_.focus),q.style.cssText=_.stage,Q.textContent=N.type==="open_url"?`${z?"\u524D\u5F80":"Continue to"} ${new URL(N.url).host}`:z?"\u7EE7\u7EED":"Continue",Q.onclick=()=>{let m=be(),j=N.type==="open_url"&&!e.onOpenUrl&&N.openIn==="new_window"?$n(N.url):null;Se(async()=>{let x="success";if(N.type==="open_url")if(e.onOpenUrl)try{x=await e.onOpenUrl({receiptId:N.receiptId,url:N.url,openIn:N.openIn})===!1?"failed":"opened"}catch(oe){le(e.onError,oe),x="failed"}else x=N.openIn==="new_window"&&!j?"failed":"opened";if(N.type==="event"){if(!e.onEvent)throw new P("EVENT_HANDLER_REQUIRED","Provide the event handler");await e.onEvent(N.event)}if(b||e.client.view?.nodeId!==m.nodeId||e.client.view.visit!==m.visit)throw new P("PRECONDITION_FAILED","The client action visit changed");let te=await e.client.submit({operation:"submit",...m,input:{type:"client_action",receiptId:N.receiptId,outcome:x}});return He.add(N.receiptId),N.type==="open_url"&&!e.onOpenUrl&&N.openIn==="same_window"&&s.defaultView?.location.assign(N.url),te})},W?.active?W.present(()=>q.replaceChildren(Q)):q.replaceChildren(Q)}!t.pendingRequest&&t.status==="completed"&&!He.has(`complete:${t.id}`)&&(He.add(`complete:${t.id}`),le(e.onComplete,structuredClone(t))),Ne()}function $n(t){let r=s.defaultView?.open(t,"_blank")??null;return r&&(r.opener=null),r}function me(t){return Ce(),Ye=Ye.catch(()=>{}).then(async()=>{try{await Hn(t)}catch(r){throw W?.active&&(Le=xe(t),W.finish("error",r),ve(),u.hidden=!0),r}}),Ye}let Un=e.client.subscribe(t=>{if(!an){if(t.stopped&&y&&!ye){l=t,ae();return}!ye&&(t.stopped||e.client.configurationReady===!1||o&&c!==o&&(De(t)!==o||["closed","ineligible","failed"].includes(t.status)))&&(ve(),W?.finish("dismissed"),u.hidden=!0),me(t).catch(ue)}}),xn=e.client.subscribeError?.(ue);function Pe(t){if(Ie)return Ie;if(b||!t&&(se||K))return Promise.resolve();let r=!t&&Me();return!r&&e.client.view&&!["running","waiting"].includes(e.client.view.status)?(l=e.client.view,ae(),Promise.resolve()):(Ie=Se(async()=>{let f=r?await e.client.retry():await e.client.submit({operation:"close",...t??be()});return t&&un(f),f},!0).then(()=>{let f=e.client.view;f?.status==="closed"&&!Me()&&(l=f,ae())}).finally(()=>{Ie=null}),Ie)}function ae(){S?.destroy(),!b&&(b=!0,e.signal?.removeEventListener("abort",ae),a?.removeEventListener("abort",ae),W?.finish("dismissed"),ln.destroy(),Un(),xn?.(),ve(),nn(),U.stop(),C.remove(),u.remove(),v(),le(e.onDismiss,l?structuredClone(l):null))}F.onclick=()=>{if(!F.disabled){if(U.active){U.exit();return}Se(()=>e.client.submit({operation:"back",...be()}))}},k.onclick=()=>{U.open()},R.onclick=()=>{W?.active?W.dismiss():se||Pe()},M.onclick=()=>{Me()?Pe():Se(()=>e.client.retry())},C.addEventListener("cancel",t=>{t.preventDefault(),W?.active?W.dismiss():se||Pe()}),e.signal?.addEventListener("abort",ae,{once:!0}),a?.addEventListener("abort",ae,{once:!0});try{let t=e.client.view;if(t)((e.client.viewAgeMs??sn)>=sn||t.instruction?.type==="evaluate_segment")&&(Ke=Ze().finally(()=>{Ke=null})),await me(t);else{u.hidden=!0;let r=Ge(e.client.view?.screen?.presentation.type!=="inline",e.client.view?.locale);if(b||pe)throw new DOMException("Presentation cancelled","AbortError");let f=await r.wait(e.client.get(),Ae);an=!1,await me(e.client.view??f.run)}}catch(t){throw W?.finish("error",t),ae(),t}return{destroy:ae,refresh:Ze,get recovery(){let t=Xe();if(t)return t;if(!b&&!$&&!ye&&!se&&i){let r=i.recovery;if(r.type!=="native")return r}return{type:"recover",operationId:e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??K?.operationId??null,requestId:e.client.pendingCommand?.requestId??null}},prepareFallback(){if(se)return se;let t=Xe();if(t)return Promise.resolve(t);let r=e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??K?.operationId??null,f=()=>({type:"recover",operationId:r,requestId:e.client.pendingCommand?.requestId??null});if(e.client.hasDurableJournal!==!0){let N=i?.recovery;return Promise.resolve(N&&N.type!=="native"&&N.type!=="cancel"?N:f())}let ne=(e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[])).some(N=>N.operation==="close");if(b&&!(ne||K&&e.client.view?.status==="closed")||$||Re||Ie||U.active||!i&&!K&&!ne)return Promise.resolve(f());let ge=i,Z=(async()=>{try{if(!K&&ne){let m=await e.client.retry();return await me(e.client.view??m.run),f()}if(!K){let m=await ge.prepareFallback();if(m.type!=="native")return m;if(e.client.hasDurableJournal!==!0)return f();K=m}let N=e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[]);if(N.length){let m=N.find(x=>x.operation==="close");if(!m||!X||m.requestId!==X.requestId)return f();let j=await e.client.retry();un(j),await me(e.client.view??j.run)}else{let m=e.client.view,j=m?.paywall;if(!m||!j||j.selectionGeneration===void 0||(j.quote?.operationId??null)!==K.operationId||K.operationId!==null&&j.canReselect!==!0)return f();let x=j.selectionGeneration,te=await e.client.get();await me(e.client.view??te.run);let oe=e.client.view,ie=oe?.paywall;if(!oe||!ie||!["running","waiting"].includes(oe.status)||oe.stopped||oe.id!==m.id||oe.nodeId!==m.nodeId||oe.visit!==m.visit||ie.receiptId!==j.receiptId||ie.selectionGeneration!==x||(ie.quote?.operationId??null)!==K.operationId||K.operationId!==null&&ie.canReselect!==!0||e.client.pendingPurchase||(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0)))return f();let ee=be();X={runId:oe.id,operationId:K.operationId,revision:ee.revision,requestId:ee.requestId,nodeId:oe.nodeId,visit:oe.visit,receiptId:ie.receiptId,selectionGeneration:x,acknowledged:!1},await Pe(ee)}let Q=Xe();return Q?(ae(),Q):f()}catch(N){return ue(N),f()}})();se=Z;let we=()=>{se===Z&&(se=null)};return Z.then(we,we),Z},review:U.open,exitReview:U.exit,get unappliedDrafts(){return U.drafts}}}function Vt(n,g,w){return zn(n,g,w)}export{Bn as a,Mn as b,zn as c,Vt as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as $,m as K,p as Z}from"./chunk-TNN4S6VO.js";import{M as S,a as v,b as A,c as C,f as h,g as f,k as j,l as R,m as D,n as P,o as M,q as b,r as y}from"./chunk-PNHGULO2.js";import{j as O,o as Q,p as G}from"./chunk-2JTMXZ5M.js";import{a as u,d as k,e as g,f as N,g as U,i as q,j as B,k as V,o as F,t as L}from"./chunk-4WBIACS2.js";import{b as t}from"./chunk-7GD2UTBU.js";var W={funnelId:t.uuid().optional(),funnelVersionId:t.uuid().optional()};var Y=t.strictObject({runId:t.uuid(),bindingId:t.uuid(),receiptId:t.uuid()});var _e=t.registry(),{BillingInterval:H}=(()=>{var e;return(function(i){i.OneOff="one_off",i.Week="week",i.Month="month",i.Quarter="quarter",i.SemiAnnual="semi_annual",i.Year="year"})(e||(e={})),{BillingInterval:e}})(),{DisplaySchema:Ie}=(e=>({DisplaySchema:e.object({primary_text:e.string().meta({description:"Main display text (e.g. '$10' or '100 messages')."}),secondary_text:e.string().optional().meta({description:"Secondary display text (e.g. 'per month' or 'then $0.5 per 100')."})})}))(t),{withSpecDefault:xe}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:a})=>(e.add(n,{description:a,default:r}),n)}))(_e),{COMMON:X}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:ve}={STRIPE_PRESENTMENT_CURRENCIES:["usd","aed","afn","all","amd","ang","aoa","ars","aud","awg","azn","bam","bbd","bdt","bif","bmd","bnd","bob","brl","bsd","bwp","byn","bzd","cad","cdf","chf","clp","cny","cop","crc","cve","czk","djf","dkk","dop","dzd","egp","etb","eur","fjd","fkp","gbp","gel","gip","gmd","gnf","gtq","gyd","hkd","hnl","htg","huf","idr","ils","inr","isk","jmd","jpy","kes","kgs","khr","kmf","krw","kyd","kzt","lak","lbp","lkr","lrd","lsl","mad","mdl","mga","mkd","mmk","mnt","mop","mur","mvr","mwk","mxn","myr","mzn","nad","ngn","nio","nok","npr","nzd","pab","pen","pgk","php","pkr","pln","pyg","qar","ron","rsd","rub","rwf","sar","sbd","scr","sek","sgd","shp","sle","sos","srd","std","szl","thb","tjs","top","try","ttd","twd","tzs","uah","ugx","uyu","uzs","vnd","vuv","wst","xaf","xcd","xcg","xof","xpf","yer","zar","zmw"]},{COMMON_SET:Ae}=(e=>({COMMON_SET:new Set(e)}))(X),{hasNoDuplicateCurrencies:J}={hasNoDuplicateCurrencies:i=>{let n=new Set;for(let{currency:r}of i){let a=r.toLowerCase();if(n.has(a))return!1;n.add(a)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:z}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:Ce}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(t),{Infinite:Pe}={Infinite:"inf"},{TierBehavior:Me}=(()=>{var e;return(function(i){i.Graduated="graduated",i.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:ee}=(()=>{var e;return(function(i){i.Prepaid="prepaid",i.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Oe}=(()=>{var e;return(function(i){i.Arrear="arrear",i.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:we}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:Ee}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Te}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(t),{ApiCreditTierSchema:te}=(e=>({ApiCreditTierSchema:e.object({to:e.union([e.number().positive(),e.enum(["inf"])]).meta({description:"Inclusive upper usage boundary for this graduated tier. The final tier must be 'inf'."}),credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group within this tier."})})}))(t),{VIOLATION_MESSAGES:je}={VIOLATION_MESSAGES:{non_final_infinity:"Only the final tier may use an 'inf' boundary.",not_increasing:"Tier boundaries must be strictly increasing.",final_not_infinity:"The final tier must use an 'inf' boundary."}},{MarkupEntrySchema:ie}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(t),{ModelMarkupsSchema:Re}=((e,i)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),i.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(t,ie),{InvoiceUsageEntrySchema:De}=(e=>({InvoiceUsageEntrySchema:e.object({feature_id:e.string().meta({description:"The metered feature whose units are being converted."}),quantity:e.number().nonnegative().meta({description:"Billable units of the metered feature. Converted to the credit-system feature through its rate card."}),properties:e.record(e.string(),e.unknown()).optional().meta({description:"Event properties used to pick the rate card dimension and multipliers."})}).strict()}))(t),{AttachDiscountSchema:ne}=(e=>({AttachDiscountSchema:e.object({reward_id:e.string().optional().meta({description:"The ID of the reward to apply as a discount."}),promotion_code:e.string().optional().meta({description:"The promotion code to apply as a discount."})}).refine(n=>n.reward_id||n.promotion_code,{message:"Either reward_id or promotion_code must be provided."}).meta({title:"AttachDiscount",description:"A discount to apply. Can be either a reward ID or a promotion code."})}))(t),{CustomLineItemSchema:ke}=(e=>({CustomLineItemSchema:e.object({amount:e.number().meta({description:"Amount in dollars for this line item (e.g. 10.50). Can be negative for credits."}),description:e.string().meta({description:"Description for the line item."})})}))(t),{UnixMsTimestampSchema:Ne}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(t),{CreateInvoicePreviewLineSchema:Ue}=(e=>({CreateInvoicePreviewLineSchema:e.object({plan_id:e.string().nullable(),feature_id:e.string().nullable(),description:e.string(),amount:e.number(),amount_after_discounts:e.number(),quantity:e.number().nullable(),prorated:e.boolean(),period_start:e.number().nullable(),period_end:e.number().nullable()})}))(t),{ReissueInvoiceParamsSchema:Ot}=(e=>({ReissueInvoiceParamsSchema:e.object({invoice_id:e.string().meta({description:"The Autumn invoice ID to void and replace.",example:"inv_2b3c4d5e6f7g8h"}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer and memo are applied to the replacement invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the replacement invoice. Defaults to the original invoice's due date; required when that date has already passed."}),update_customer_email:e.email().optional().meta({description:"Updates the customer's billing email before the replacement is issued, so Stripe sends the new invoice to this address."})})}))(t),{InvoiceModeParamsSchema:l}=(e=>({InvoiceModeParamsSchema:e.object({enabled:e.boolean().meta({description:"When true, creates an invoice and sends it to the customer instead of charging their card immediately. Uses Stripe's send_invoice collection method."}),enable_plan_immediately:e.boolean().default(!1).meta({description:"If true, enables the plan immediately even though the invoice is not paid yet."}),finalize:e.boolean().default(!0).meta({description:"If true, finalizes the invoice so it can be sent to the customer. If false, keeps it as a draft for manual review."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer (e.g. bank details) is applied to the invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the invoice before it is due (Stripe days_until_due)."})}).meta({title:"InvoiceMode",description:"Invoice mode configuration. Creates an invoice instead of charging the card immediately."})}))(t),{InvoiceTemplateSchema:wt}=(e=>({InvoiceTemplateSchema:e.object({id:e.string().meta({description:"Unique identifier for the invoice template."}),name:e.string().meta({description:"User-defined name to distinguish this template when sending an invoice."}),footer:e.string().optional().meta({description:"Footer text rendered on the invoice, typically bank details so customers can pay directly."}),memo:e.string().optional().meta({description:"Memo shown near the top of the invoice (Stripe invoice description), e.g. a contact line for payment questions."}),net_terms_days:e.number().int().positive().optional().meta({description:"Default number of days the customer has to pay before the invoice is due. Overridable when sending."}),created_at:e.number().optional().meta({description:"Timestamp (ms) when the template was created."})})}))(t),{BasePriceSchema:qe}=((e,i,n)=>({BasePriceSchema:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),interval:e.enum(i).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),display:n.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(t,H,Ie),{CURRENCY_CODES:Be}=((e,i,n)=>({CURRENCY_CODES:[...e,...i.filter(a=>!n.has(a)).sort()]}))(X,ve,Ae),{ApiPriceProcessorsSchema:re}=((e,i)=>({ApiPriceProcessorsSchema:e.object({stripe:i.nullish()}).meta({"x-atmn-mapping":!0})}))(t,Ce),{AllocatedBillingFieldSchema:Ve}=((e,i)=>({AllocatedBillingFieldSchema:e.enum(i).optional().meta({internal:!0,description:"How an allocated usage_based price bills mid-cycle quantity changes. 'arrear' (default) bills at period end. 'prorated_legacy' is only returned for prices still on the legacy immediate-proration behavior; omit it to migrate the price to 'arrear'."})}))(t,Oe),{CreditDimensionNameSchema:Fe}=((e,i,n)=>({CreditDimensionNameSchema:e.string().min(1).max(i).refine(a=>!a.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(t,we,Ee),{ApiCreditMatchSchema:ae}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Te),{findCreditTierViolations:Le}=(e=>({findCreditTierViolations:n=>{let r=[],a=(o,m)=>r.push({index:o,reason:m,message:e[m]}),s=0;for(let[o,m]of n.entries()){let p=o===n.length-1;if(m==="inf"){p||a(o,"non_final_infinity");continue}(!Number.isFinite(m)||m<=s)&&a(o,"not_increasing"),s=m,p&&a(o,"final_not_infinity")}return r}}))(je),{ApiCreditMultiplierSchema:Qe}=((e,i)=>({ApiCreditMultiplierSchema:e.object({match:i,factor:e.number().positive().optional().meta({description:"Multiplies the matched rate. All matching multipliers stack."}),add:e.number().optional().meta({description:"Added to the rate after every factor is applied, in credits per billing-unit group."})}).strict().refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(t,ae),{ProviderMarkupsSchema:Ge}=((e,i)=>({ProviderMarkupsSchema:e.record(e.string(),i).nullish()}))(t,ie),{InvoiceFeatureQuantitySchema:oe}=((e,i,n)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(i).meta({description:"Which of the feature's prices to use: 'prepaid' or 'usage_based'."}),quantity:e.number().nonnegative().optional().meta({description:"Billable feature units in total, exclusive of any included usage. Not per seat or per entity. For a credit-system feature this is the number of credits."}),usage:e.array(n).optional().meta({description:"For credit-system features: billable units of the source features, converted through the credit rate card. Mutually exclusive with quantity."}),prorate:e.boolean().optional().meta({description:"Whether to prorate this line against period_start / period_end. Defaults to true for prepaid and false for usage-based."})}).strict().refine(a=>a.quantity!==void 0!=(a.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(t,ee,De),{CreateInvoicePreviewSchema:Et}=((e,i)=>({CreateInvoicePreviewSchema:e.object({currency:e.string(),lines:e.array(i),subtotal:e.number(),discount_total:e.number(),tax:e.object({total:e.number(),amount_inclusive:e.number(),amount_exclusive:e.number(),status:e.enum(["complete","incomplete"])}).nullable(),total:e.number(),due_date:e.number().nullable()})}))(t,Ue),{SUPPORTED_SET:$e}=(e=>({SUPPORTED_SET:new Set(e)}))(Be),{ApiCreditDimensionBaseSchema:Ke}=((e,i)=>({ApiCreditDimensionBaseSchema:e.object({match:i,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(t,ae),{refineGraduatedTiers:ce}=(e=>({refineGraduatedTiers:(n,r)=>{let a=e(n.tiers.map(s=>s.to));for(let{index:s,message:o}of a)r.addIssue({code:"custom",message:o,path:["tiers",s,"to"]})}}))(Le),{ApiFeatureMarkupsOverrideSchema:Ze}=((e,i,n)=>({ApiFeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional().meta({description:"Default percentage markup for customers on this plan. Use -100 to make usage free."}),provider_markups:i.meta({description:"Per-provider markup percentages for customers on this plan."}),model_markups:n.meta({description:"Per-model markup overrides for customers on this plan."})})}))(t,Ge,Re),{isValidCurrencyCode:We}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))($e),{ApiCreditDimensionSchema:Ye}=((e,i,n,r)=>({ApiCreditDimensionSchema:e.union([i.extend({tier_behavior:e.literal("graduated"),tiers:e.array(n).min(1)}).strict().superRefine(r),i.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(t,Ke,te,ce),{CurrencyCodeSchema:se}=((e,i)=>({CurrencyCodeSchema:e.string().refine(i,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(t,We),{AdditionalCurrencyTierSchema:He}=((e,i)=>({AdditionalCurrencyTierSchema:e.object({currency:i,amount:e.number().optional().meta({description:"Per-unit amount for this tier in this currency."}),flat_amount:e.number().optional().meta({description:"Flat amount for this tier in this currency, if the tier uses one."})}).refine(r=>r.amount!==void 0||r.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(t,se),{ApiCreditSchemaItemBaseSchema:ue}=((e,i,n,r)=>({ApiCreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string().nonempty().meta({description:"ID of the metered feature that draws from this credit system."}),billing_units:e.number().positive().optional().meta({description:"Number of metered-feature units priced together. Defaults to one when omitted."}),dimensions:e.record(i,n).optional().meta({description:"Named rates chosen by event properties. The most specific match sets the rate; with no match the item's own rate applies."}),multipliers:e.record(i,r).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(t,Fe,Ye,Qe),{ApiFlatCreditSchemaItemSchema:Xe}=((e,i)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:i.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(ue,t),{AdditionalCurrencyPriceSchema:Je}=((e,i)=>({AdditionalCurrencyPriceSchema:e.object({currency:i,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(t,se),{AdditionalCurrencyTierArraySchema:ze}=((e,i,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(i).refine(n,{message:r})}))(t,He,J,z),{ApiGraduatedCreditSchemaItemSchema:et}=((e,i,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:i.literal("graduated"),tiers:i.array(n).min(1)}).strict().superRefine(r)}))(ue,t,te,ce),{AdditionalCurrencyPriceArraySchema:me}=((e,i,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(i).refine(n,{message:r})}))(t,Je,J,z),{ApiUsageTierWithCurrenciesSchema:tt}=((e,i,n)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(i)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:n.optional().meta({description:"Per-currency amounts for this tier. Tier boundaries ('to') are shared across all currencies."})}).refine(a=>a.amount!==void 0||a.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(a=>({...a,amount:a.amount??0})).pipe(e.object({to:e.number().or(e.literal(i)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:n.optional()}))}))(t,Pe,ze),{ApiCreditSchemaItemSchema:it}=((e,i,n)=>({ApiCreditSchemaItemSchema:e.union([i,n])}))(t,et,Xe),{BasePriceParamsSchema:nt}=((e,i,n,r)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:i({schema:n.number().optional(),defaultValue:1,description:"Number of intervals per billing cycle. Defaults to 1."}),additional_currencies:r.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),base_currency:n.string().optional().meta({internal:!0}),entitlement_id:n.string().optional().meta({internal:!0}),price_id:n.string().optional().meta({internal:!0}),stripe_price_id:n.string().optional().meta({description:"Stripe price id this base price is billed under. Set by sync flows to capture the actual Stripe price when it differs from the catalog default.",internal:!0})}).meta({title:"BasePrice",description:"Base price configuration for a plan."})}))(qe,xe,t,me),{PlanItemPriceParamsSchema:rt}=((e,i,n,r,a,s,o)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(p=>p??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:i.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(a).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(s).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:o,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(t,me,tt,Me,H,ee,Ve),{ApiFeatureOverrideSchema:at}=((e,i,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(i).optional().meta({description:"For credit system features: replaces the feature's credit_schema entirely for customers on this plan."}),markups:n.optional().meta({description:"For AI credit system features: replaces the feature's markup chain entirely for customers on this plan. An unset level means no markup at that level rather than inheriting the feature's."})})}))(t,it,Ze),{InvoiceBasePriceParamsSchema:de}=((e,i)=>({InvoiceBasePriceParamsSchema:e.pick({amount:!0,interval:!0,interval_count:!0}).extend({processors:i.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(nt,re),{InvoiceItemPriceParamsSchema:ot}=((e,i)=>({InvoiceItemPriceParamsSchema:e.pick({amount:!0,tiers:!0,tier_behavior:!0,interval:!0,interval_count:!0,billing_units:!0,billing_method:!0}).extend({processors:i.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(rt,re),{InvoiceLicenseQuantitySchema:ct}=((e,i,n)=>({InvoiceLicenseQuantitySchema:e.object({license_plan_id:e.string().meta({description:"The license plan linked to the parent plan."}),quantity:e.number().int().nonnegative().meta({description:"Billable seats, exclusive of any included seats."}),customize:e.object({price:i.nullable().optional()}).strict().optional().meta({description:"Override the license's per-seat price on this invoice."}),feature_quantities:e.array(n).optional().meta({description:"Feature charges priced through the license plan."}),prorate:e.boolean().optional().meta({description:"Whether to prorate seat charges against period_start / period_end. Defaults to true."})}).strict()}))(t,de,oe),{InvoiceCustomizeItemSchema:st}=((e,i,n)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:i.optional().meta({description:"Pricing to use for this feature on this invoice."}),feature_override:n.pick({credit_schema:!0}).strict().optional().meta({description:"For credit-system features: a credit rate card to use when converting `usage` on this invoice."})}).strict()}))(t,ot,at),{InvoiceCustomizeSchema:ut}=((e,i,n)=>({InvoiceCustomizeSchema:e.object({price:i.nullable().optional().meta({description:"Override the plan's base price for this invoice. Pass null or an amount of 0 to omit the base price line."}),items:e.array(n).optional().meta({description:"Override feature pricing for this invoice. Only pricing fields are accepted; grants, resets and rollovers are not part of an invoice."})}).strict().meta({title:"InvoiceCustomize",description:"Pricing overrides applied to this invoice only. The catalog and the customer's plan are not changed."})}))(t,de,st),{InvoicePlanParamsSchema:mt}=((e,i,n,r,a)=>({InvoicePlanParamsSchema:e.object({plan_id:e.string().meta({description:"The catalog plan (or variant) whose pricing to use."}),version:e.number().optional().meta({description:"Plan version. Defaults to the active version."}),customize:i.optional(),feature_quantities:e.array(n).optional(),license_quantities:e.array(r).optional(),discounts:e.array(a).optional().meta({description:"Discounts applied only to this plan's lines."}),prorate:e.boolean().optional().meta({description:"Whether to prorate the base price against period_start / period_end. Defaults to true."})}).strict()}))(t,ut,oe,ct,ne),{CreateInvoiceParamsSchema:Tt}=((e,i,n,r,a)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(i).optional(),custom_line_items:e.array(n).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(r).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:a.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start \u2192 period_end against one price interval starting at period_start."}),period_end:a.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(o=>o.period_start===void 0==(o.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(o=>o.period_start===void 0||o.period_end===void 0||o.period_end>o.period_start,{message:"period_end must be after period_start."})}))(t,mt,ke,ne,Ne);var w=t.object({type:t.literal("native_purchase"),receiptId:t.uuid(),orderId:t.uuid(),productVersionId:t.uuid(),provider:t.enum(["apple","google"]),productId:t.string().min(1).max(255),productKind:q,replacement:t.strictObject({sourceOrderId:t.uuid(),sourceProductId:t.string().min(1).max(255),policy:t.enum(["apple_store","google_full_price"]),sourceAccountTokens:t.array(t.uuid()).max(50)}).nullable(),appAccountToken:t.uuid().optional(),obfuscatedAccountId:t.string().min(1).max(64).optional(),obfuscatedProfileId:t.uuid().optional(),basePlanId:t.string().min(1).max(255).optional(),offerId:t.string().min(1).max(255).optional(),offerKind:t.enum(["none","introductory","promotional"]),currency:u,catalogAmountMinor:t.number().int().nonnegative().max(1e8),discountMinor:t.number().int().nonnegative().max(1e8),trialDays:t.number().int().min(1).max(730).nullable(),seatBundle:t.array(t.strictObject({key:t.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:t.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:t.strictObject({offerId:t.string().min(1).max(255),keyId:t.string().min(1).max(255),nonce:t.uuid(),signature:t.string().min(1).max(1024),timestamp:t.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,i)=>{let n=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(n?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!n&&e.productKind==="membership"&&e.basePlanId===void 0||e.discountMinor>e.catalogAmountMinor||new Set(e.seatBundle.map(a=>a.key)).size!==e.seatBundle.length||e.trialDays!==null&&(e.discountMinor!==0||e.offerKind==="none")||e.offerKind==="none"&&e.discountMinor!==0||(n?!e.appAccountToken||e.obfuscatedAccountId!==void 0||e.obfuscatedProfileId!==void 0||e.basePlanId!==void 0||e.offerKind==="promotional"!=(e.applePromotionalOffer!==null)||e.offerKind==="promotional"!=(e.offerId!==void 0)||e.applePromotionalOffer!==null&&e.applePromotionalOffer.offerId!==e.offerId:e.appAccountToken!==void 0||!e.obfuscatedAccountId||!e.obfuscatedProfileId||e.applePromotionalOffer!==null||e.offerKind==="none"!=(e.offerId===void 0)))&&i.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});var pe=t.strictObject({itemKey:t.string().regex(/^paid:feature:[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),internal_feature_id:t.uuid(),includedAmount:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:t.number().int().min(0).max(1e4),terms:N,pricing:k.optional(),unitAmountMinor:t.number().int().min(0).max(1e8),productId:t.string().min(1).max(255).nullable(),priceId:t.string().min(1).max(255).nullable()}).superRefine((e,i)=>{(e.quantity<e.terms.minimumQuantity||e.quantity>e.terms.maximumQuantity||e.productId===null!=(e.priceId===null)||e.quantity>0&&(e.pricing||e.unitAmountMinor>0)&&e.priceId===null)&&i.addIssue({code:"custom",message:"Purchased quantities need their published bounds and immutable price binding"});try{U(e.includedAmount,e.terms.units,e.quantity),g({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{i.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});var _=t.string().trim().min(1).max(64).regex(/^[a-z][a-z0-9_]*$/,"ID \u4F7F\u7528\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u4E0B\u5212\u7EBF\uFF0C\u5E76\u4EE5\u5B57\u6BCD\u5F00\u5934"),Qt=t.object({amountCents:t.number().int().min(0).max(1e8),currency:u,interval:t.enum(["free","month","year"]),currencyOptions:t.partialRecord(u,t.number().int().min(1).max(1e8)).optional()}).refine(e=>e.interval==="free"?e.amountCents===0:e.amountCents>0,"\u514D\u8D39\u5957\u9910\u91D1\u989D\u5FC5\u987B\u4E3A 0\uFF0C\u4ED8\u8D39\u91D1\u989D\u5FC5\u987B\u5927\u4E8E 0").refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency)&&(e.interval!=="free"||Object.keys(e.currencyOptions).length===0),"\u9644\u52A0\u5E01\u79CD\u4E0D\u80FD\u91CD\u590D\u9ED8\u8BA4\u5E01\u79CD\uFF1B\u514D\u8D39\u5957\u9910\u4E0D\u8BBE\u7F6E\u9644\u52A0\u4EF7\u683C");var ai=t.strictObject({requestId:t.uuid(),predecessorOperationId:t.uuid().optional(),invoiceMode:l.optional(),entityId:t.uuid().optional(),billingSubscriptionId:t.uuid().optional(),newBillingSubscription:t.literal(!0).optional(),offerId:t.uuid().optional(),nativeOffer:O.optional(),plans:t.array(t.strictObject({productVersionId:t.uuid(),seatQuantities:t.record(_,t.number().int().min(0).max(1e4)).optional(),featureQuantities:t.record(t.uuid(),t.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100,"At most 100 feature quantities").optional()})).min(1).max(20).refine(e=>new Set(e.map(i=>i.productVersionId)).size===e.length,"Plan versions must be unique"),provider:t.enum(["stripe","apple","google","merchant"]),currency:u}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||["apple","google"].includes(e.provider)&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||["stripe","merchant"].includes(e.provider)&&!e.billingSubscriptionId,"A new billing subscription has no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),oi=t.strictObject({operationId:t.uuid()}),c=t.number().int().min(0).max(1e8),dt=t.strictObject({lineId:t.uuid(),productVersionId:t.uuid(),productName:t.string().min(1).max(80),interval:t.enum(["free","week","month","year","one_time"]),intervalCount:t.number().int().min(1).max(156).optional(),baseAmountMinor:c,seats:t.array(t.strictObject({key:_,quantity:t.number().int().min(0).max(1e4),includedQuantity:t.number().int().min(0).max(1e4),maximumQuantity:t.number().int().min(0).max(1e4),unitAmountMinor:c})).max(20),prepaid:t.array(pe).max(100).optional(),catalogAmountMinor:c,trial:j.nullable()}).refine(e=>new Set(e.seats.map(i=>i.key)).size===e.seats.length&&e.seats.every(i=>i.quantity>=i.includedQuantity&&i.quantity<=i.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((i,n)=>i+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((i,n)=>i+g({quantity:n.quantity,unitAmountMinor:n.unitAmountMinor,...n.pricing===void 0?{}:{pricing:n.pricing}}),0)===e.catalogAmountMinor,"Quote must retain its published base price and component quantities"),fe=t.string().regex(/^[A-Za-z0-9_-]{1,200}$/),pt=t.strictObject({id:fe,name:t.string().min(1).max(40),percent_off:t.number().gt(0).max(100).optional(),amount_off:t.number().int().positive().optional(),currency:t.string().regex(/^[a-z]{3}$/).optional(),duration:t.enum(["once","repeating","forever"]),duration_in_months:t.number().int().min(1).max(36).optional()}).refine(e=>e.percent_off===void 0!=(e.amount_off===void 0)&&e.amount_off===void 0==(e.currency===void 0)&&e.duration==="repeating"==(e.duration_in_months!==void 0),"A Stripe coupon has one percentage or amount and months only when repeating"),lt=t.strictObject({subscriptionId:t.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:t.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:t.array(t.strictObject({id:t.string(),price_id:t.string(),quantity:t.number().int().nonnegative(),discounts:t.array(t.strictObject({id:t.string(),coupon:t.string(),start:t.number(),end:t.number().nullable()})).optional()})).min(1).max(100),prorationDate:t.number().int().nonnegative(),amountMinor:t.number().int().positive(),periodStartMs:t.number(),periodEndMs:t.number()}),be=t.strictObject({invoiceMode:l.optional(),append:lt.optional(),provider:t.literal("stripe"),executor:t.enum(["indiana","merchant"]),accountId:t.string().regex(/^acct_[A-Za-z0-9]+$/),mode:t.enum(["payment","subscription"]),lineItems:t.array(t.strictObject({price:t.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:t.number().int().min(1).max(1e4),priceId:t.uuid(),productName:t.string().min(1).max(80),amountMinor:t.number().int().min(0).max(1e8),currency:t.string().regex(/^[a-z]{3}$/),interval:t.enum(["week","month","year","one_off"]),intervalCount:t.number().int().min(1).max(52),slot:t.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:t.strictObject({mode:t.enum(["graduated","volume"]),tiers:t.array(t.strictObject({upTo:t.number().int().min(1).max(1e6).nullable(),unitAmountMinor:t.number().int().min(0).max(1e8),flatAmountMinor:t.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:t.array(t.strictObject({coupon:fe,terms:pt})).max(1),trialPeriodDays:t.number().int().min(1).max(730).nullable(),metadata:t.strictObject({grooveCheckoutId:t.uuid(),grooveCustomerId:t.uuid()}),expiresAt:t.iso.datetime({offset:!0})}),ht=t.strictObject({operationId:t.uuid(),merchantTerms:b.optional(),entityId:t.uuid().nullable(),billingSubscriptionId:t.uuid().nullable(),discount:t.strictObject({offerId:t.uuid(),couponId:t.uuid(),discount:Q,duration:G,amountMinor:c,allocations:t.array(t.strictObject({productVersionId:t.uuid(),amountMinor:c})).min(1).max(20),expiresAt:t.iso.datetime({offset:!0})}).nullable(),charge:t.strictObject({effectiveAt:t.iso.datetime({offset:!0}),periodEndsAt:t.iso.datetime({offset:!0}),debitMinor:c,discountMinor:c,taxMinor:c,totalMinor:c}).nullable(),expiresAt:t.iso.datetime({offset:!0}),provider:t.enum(["stripe","apple","google","merchant"]),nativeOffer:O.optional(),currency:u,lines:t.array(dt).min(1).max(20),catalogAmountMinor:c,nativeDiscountMinor:c.optional(),automaticTax:t.boolean(),execution:t.union([be,v]).nullable()}).refine(e=>!e.merchantTerms||e.provider==="merchant"&&y(e.merchantTerms,e.operationId,"purchase",e.currency)).refine(e=>e.provider==="merchant"?e.execution?.provider==="merchant"&&e.execution.operationId===e.operationId&&e.execution.catalogAmountMinor===e.catalogAmountMinor&&e.execution.currency===e.currency&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&e.execution.discount?.grantId===e.discount?.offerId:e.provider==="stripe"?e.execution?.provider!=="merchant"&&(e.lines[0]?.trial?.cardRequired===!1&&!e.execution?.invoiceMode?.enabled?e.execution===null&&e.discount===null:e.execution!==null&&e.execution.metadata.grooveCheckoutId===e.operationId&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.mode===(e.lines.some(i=>!["one_time","free"].includes(i.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(i=>i.price!==null))&&e.execution.discounts.every(i=>i.coupon===i.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(i=>e.discount!==null&&(i.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&i.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${i.terms.amount_off}`&&i.terms.amount_off===e.discount.discount.amountOffCents&&i.terms.currency?.toUpperCase()===e.currency&&i.terms.duration==="once"))):e.execution===null,"Stripe execution must carry the quote identity, expiry, mode, trial and held coupon").refine(e=>(!e.discount||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.discount.duration.type==="once")&&e.discount.amountMinor<=e.catalogAmountMinor&&e.discount.allocations.length===e.lines.length&&e.discount.allocations.every((i,n)=>{let r=e.lines[n];return r!==void 0&&i.productVersionId===r.productVersionId&&i.amountMinor<=r.catalogAmountMinor})&&e.discount.allocations.reduce((i,n)=>i+n.amountMinor,0)===e.discount.amountMinor)&&(["stripe","merchant"].includes(e.provider)?e.nativeOffer===void 0:e.nativeOffer!==void 0&&e.lines.length===1&&e.nativeOffer.discountMinor<=e.catalogAmountMinor&&e.nativeOffer.trialDays===(e.lines[0]?.trial?.days??null)&&(!e.discount||e.nativeOffer.discountMinor===e.discount.amountMinor))&&(!e.charge||e.billingSubscriptionId!==null&&e.charge.totalMinor===e.charge.debitMinor-e.charge.discountMinor+e.charge.taxMinor&&e.charge.discountMinor<=e.charge.debitMinor&&Date.parse(e.charge.periodEndsAt)>Date.parse(e.charge.effectiveAt))&&new Set(e.lines.map(i=>i.lineId)).size===e.lines.length&&e.lines.reduce((i,n)=>i+n.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),ci=t.strictObject({operationId:t.uuid(),orderId:t.uuid(),append:t.boolean().optional(),invoiceMode:t.boolean().optional(),status:t.enum(["pending","complete","cancelled","failed"]),executor:t.enum(["indiana","merchant"]),checkoutUrl:t.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:t.union([be,v]).nullable(),currency:u,catalogAmountMinor:c,taxMinor:c,totalMinor:t.number().int().min(0).max(2e8).nullable(),quoteFinalized:t.boolean(),nativePurchase:w.nullable(),confirmedAt:t.iso.datetime({offset:!0}).nullable().optional(),quote:ht.optional(),merchantExecution:f.nullable().optional(),problem:h.nullable().optional(),authority:S.optional()}).refine(e=>(e.checkoutUrl===null||e.executor==="indiana"||e.merchantExecution?.type==="purchase")&&(e.execution===null||e.executor==="merchant"),"Only Indiana-executed purchases carry a Checkout URL and only record-only purchases carry execution instructions"),x=t.strictObject({enabled:t.literal(!0),featureIds:t.array(t.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),si=t.strictObject({requestId:t.uuid(),offerId:t.uuid().optional(),invoiceMode:l.optional(),membershipId:t.uuid(),carryOverBalances:x.optional(),carryOverUsages:x.optional(),membershipIds:t.array(t.uuid()).min(1).max(20).optional(),prorationBehavior:t.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:t.enum(["immediate","renewal","store"]),change:t.discriminatedUnion("type",[t.strictObject({type:t.literal("plan"),productVersionId:t.uuid()}),t.strictObject({type:t.literal("seats"),licenseKey:_,quantity:t.number().int().min(0).max(1e4)}),t.strictObject({type:t.literal("quantity"),internal_feature_id:t.uuid(),quantity:t.number().int().min(0).max(1e4)}),t.strictObject({type:t.literal("cancel")}),t.strictObject({type:t.literal("uncancel")}),t.strictObject({type:t.literal("billing_cycle"),billingCycleAnchor:t.union([t.literal("now"),t.number().int().positive().max(0xe677d21fdbff)])})])}).refine(e=>!e.offerId||e.change.type==="plan"&&e.timing!=="store","A selected plan-change offer requires a merchant target Product").refine(e=>e.timing!=="store"||e.change.type==="plan","Store timing applies to a native plan replacement").refine(e=>e.change.type!=="billing_cycle"||e.timing===(e.change.billingCycleAnchor==="now"?"immediate":"renewal"),"Use immediate for now and renewal for a future millisecond anchor").refine(e=>!e.membershipIds||["cancel","uncancel"].includes(e.change.type)&&e.membershipIds.includes(e.membershipId)&&new Set(e.membershipIds).size===e.membershipIds.length,"Grouped actions require unique cancel/uncancel targets including the primary membership").refine(e=>!e.carryOverBalances&&!e.carryOverUsages||e.change.type==="plan"&&e.timing==="immediate","Carry applies only to immediate upgrades").refine(e=>!e.prorationBehavior||e.change.type==="quantity","prorationBehavior applies to prepaid quantity changes"),I=t.string().regex(/^price_[A-Za-z0-9]+$/),le=t.strictObject({grooveUpdateId:t.uuid(),grooveCustomerId:t.uuid()}),he=t.strictObject({price:I.nullable(),priceId:t.uuid().optional(),quantity:t.number().int().min(0).max(1e4)}),ye=t.strictObject({provider:t.literal("stripe"),invoiceMode:l.optional(),executor:t.enum(["indiana","merchant"]),accountId:t.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:t.string().regex(/^sub_[A-Za-z0-9]+$/),action:t.enum(["update","cancel","schedule","release"]),update:t.strictObject({items:t.array(he).max(20),remove:t.array(I).max(20),restoreItems:t.array(t.strictObject({price:I,quantity:t.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:t.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:t.number().int().positive().optional(),paymentBehavior:t.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:t.boolean().optional(),clearCancelAt:t.literal(!0).optional(),billingCycleAnchorNow:t.literal(!0).optional(),metadata:le}).nullable(),cancel:t.strictObject({prorate:t.literal(!1),invoiceNow:t.literal(!1)}).nullable(),schedule:t.strictObject({currentItems:t.array(t.strictObject({price:I,quantity:t.number().int().min(0).max(1e4)})).max(20),nextItems:t.array(he).min(1).max(20),switchAt:t.number().int().positive(),interval:t.enum(["week","month","year"]),intervalCount:t.number().int().min(1).max(52),resetBillingCycleAnchor:t.literal(!0).optional(),metadata:le}).nullable(),release:t.strictObject({schedule:t.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:t.iso.datetime({offset:!0})}).refine(e=>["update","cancel","schedule","release"].every(i=>e[i]!==null==(e.action===i))&&(e.executor==="indiana"||[...e.update?.items??[],...e.schedule?.nextItems??[]].every(i=>i.price!==null)),"Stripe update execution carries exactly its action, with bound Prices for the merchant"),ge=t.strictObject({merchantTerms:b.optional(),carryOverBalances:x.optional(),carryOverUsages:x.optional(),operationId:t.uuid(),membershipId:t.uuid(),productVersionId:t.uuid(),timing:t.enum(["immediate","renewal"]),effectiveAt:t.iso.datetime({offset:!0}),expiresAt:t.iso.datetime({offset:!0}),currency:u,creditMinor:c,debitMinor:c,discountMinor:c,taxMinor:c,totalMinor:c,retainedProductVersionIds:t.array(t.uuid()).max(19),execution:t.union([ye,A])}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&y(e.merchantTerms,e.operationId,"subscription_change",e.currency)),ft=t.strictObject({operationId:t.uuid(),invoiceMode:t.boolean().optional(),membershipId:t.uuid(),productVersionId:t.uuid(),status:t.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:t.enum(["immediate","renewal"]),effectiveAt:t.iso.datetime({offset:!0}),checkoutUrl:t.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:t.enum(["indiana","merchant"]),execution:t.union([ye,A]).nullable(),confirmedAt:t.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:f.nullable().optional(),problem:h.nullable().optional(),quote:ge.optional(),authority:S.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),bt=t.strictObject({operationId:t.uuid(),membershipId:t.uuid(),productVersionId:t.uuid(),timing:t.literal("store"),effectiveAt:t.null(),expiresAt:t.iso.datetime({offset:!0}),currency:u,creditMinor:t.null(),debitMinor:t.null(),discountMinor:t.null(),taxMinor:t.null(),totalMinor:t.null(),retainedProductVersionIds:t.array(t.uuid()).max(19),store:t.strictObject({provider:t.enum(["apple","google"]),productId:t.string().min(1).max(255),catalogAmountMinor:c,policy:t.enum(["apple_store","google_full_price"])})}),yt=t.strictObject({operationId:t.uuid(),membershipId:t.uuid(),productVersionId:t.uuid(),status:t.enum(["prepared","pending","effective","cancelled","failed"]),timing:t.literal("store"),effectiveAt:t.iso.datetime({offset:!0}).nullable(),checkoutUrl:t.null(),nativePurchase:w.nullable()}),ui=t.union([ge,bt]),mi=t.union([ft,yt]),E=R,d=D,di=t.strictObject({requestId:t.uuid(),invoiceId:t.uuid(),...M.shape}).refine(P,"A partial refund states amountMinor; a full refund refunds the remaining amount"),Se=t.strictObject({provider:t.literal("stripe"),executor:t.enum(["indiana","merchant"]),accountId:t.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:t.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:E,currency:t.string().regex(/^[a-z]{3}$/),metadata:t.strictObject({indianaRefundId:t.uuid()}),idempotencyKey:t.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:t.array(t.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),gt=t.strictObject({operationId:t.uuid(),merchantTerms:b.optional(),invoiceId:t.uuid(),providerInvoiceId:t.string().min(1).max(200),currency:u,paidMinor:d,refundedMinor:d,pendingMinor:d,amountMinor:E,mode:t.enum(["full","partial"]),entitlementAction:t.enum(["retain","revoke"]),revokes:t.strictObject({customerProductIds:t.array(t.uuid()).max(100),subscriptionIds:t.array(t.string().min(1).max(200)).max(20)}),execution:t.union([Se,C]),expiresAt:t.iso.datetime({offset:!0})}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&y(e.merchantTerms,e.operationId,"refund",e.currency)).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&(e.execution.provider==="merchant"?e.execution.merchantInvoiceId===e.providerInvoiceId&&e.execution.operationId===e.operationId&&e.execution.currency===e.currency:e.execution.invoice===e.providerInvoiceId&&e.execution.metadata.indianaRefundId===e.operationId&&e.execution.currency===e.currency.toLowerCase())&&(e.entitlementAction==="revoke"||e.revokes.customerProductIds.length===0&&e.revokes.subscriptionIds.length===0),"Refund quote must stay within the refundable amount and match its execution"),St=t.strictObject({operationId:t.uuid(),invoiceId:t.uuid(),providerInvoiceId:t.string().min(1).max(200),status:t.enum(["quoted","pending","succeeded","failed","expired"]),executor:t.enum(["indiana","merchant"]),currency:u,amountMinor:E,mode:t.enum(["full","partial"]),entitlementAction:t.enum(["retain","revoke"]),refundId:t.string().min(1).max(200).nullable(),quote:gt.optional(),execution:t.union([Se,C]).nullable(),confirmedAt:t.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:f.nullable().optional(),problem:h.nullable().optional(),authority:S.optional(),failureReason:t.string().min(1).max(200).nullable(),createdAt:t.iso.datetime({offset:!0}),completedAt:t.iso.datetime({offset:!0}).nullable()}).refine(e=>(e.execution===null||e.executor==="merchant"&&e.status==="quoted")&&(e.status!=="succeeded"||e.refundId!==null),"Only quoted record-only refunds carry instructions; a succeeded refund names its Stripe refund"),pi=t.strictObject({invoiceId:t.uuid(),currency:u,paidMinor:d,refundedMinor:d,pendingMinor:d,refundableMinor:d,executor:t.enum(["indiana","merchant"]).nullable(),canRefund:t.boolean(),operations:t.array(St).max(50)}).refine(e=>e.operations.every(i=>i.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),li=t.strictObject({requestId:t.uuid(),...M.shape}).refine(P,"A partial refund states amountMinor; a full refund refunds the remaining amount");var Ai=t.strictObject({processContext:Y.optional(),...W,selector:t.discriminatedUnion("type",[t.strictObject({type:t.literal("paywall"),paywallId:t.uuid()}),t.strictObject({type:t.literal("version"),versionId:t.uuid()})]),customerId:t.uuid().optional(),commerce:B,locale:t.string().min(1).max(35),requirement:V.optional()}),T=t.strictObject({id:t.uuid(),paywallId:t.uuid(),version:t.number().int().positive(),document:$.omit({requirement:!0,offeringId:!0}),offering:t.strictObject({id:t.uuid()}),content:t.strictObject({environmentId:t.uuid(),offeringVersionId:t.uuid(),artifact:Z.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:L,check:F.nullable()}).superRefine((e,i)=>{let n=new Set(e.document.products.items.map(r=>r.productVersionId));(e.document.offeringVersionId!==e.offering.id||Object.values(e.capabilities.plans).some(r=>!n.has(r.versionId)))&&i.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})}),Ci=t.strictObject(T.shape).omit({document:!0,offering:!0}).extend({content:T.shape.content.unwrap()});function Pi(e,i){let n=K.parse(i);if(n.offeringVersionId!==e.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");let r=structuredClone(e.capabilities);for(let[a,s]of Object.entries(n.catalog)){let o=r.plans[a],m=s.channels.stripe?.prices.find(p=>p.currency===o?.currency);o&&m&&Object.assign(o,{amountMinor:m.amountMinor,interval:s.interval,intervalCount:s.intervalCount,...s.prepaid?.length?{prepaid:s.prepaid}:{}})}return T.parse({...e,capabilities:r,document:{schemaVersion:3,kind:n.kind,name:n.name,presentation:n.presentation,products:n.products,offeringVersionId:n.offeringVersionId,screen:n.screen,buttons:n.buttons},offering:{id:n.offeringVersionId}})}export{W as a,Y as b,Ot as c,Et as d,Tt as e,ai as f,oi as g,ht as h,ci as i,si as j,ge as k,ui as l,mi as m,di as n,gt as o,St as p,Ai as q,T as r,Ci as s,Pi as t};
|
|
1
|
+
import{a as $,m as K,p as Z}from"./chunk-4ZVVG5LM.js";import{M as S,a as v,b as A,c as C,f as h,g as f,k as j,l as R,m as D,n as P,o as M,q as b,r as y}from"./chunk-LZV4QJ5E.js";import{j as O,o as Q,p as G}from"./chunk-ITVSLSRM.js";import{a as u,d as k,e as g,f as N,g as U,i as q,j as B,k as V,o as F,t as L}from"./chunk-WRUW2UIJ.js";import{b as t}from"./chunk-ZY4XAKNQ.js";var W={funnelId:t.uuid().optional(),funnelVersionId:t.uuid().optional()};var Y=t.strictObject({runId:t.uuid(),bindingId:t.uuid(),receiptId:t.uuid()});var _e=t.registry(),{BillingInterval:H}=(()=>{var e;return(function(i){i.OneOff="one_off",i.Week="week",i.Month="month",i.Quarter="quarter",i.SemiAnnual="semi_annual",i.Year="year"})(e||(e={})),{BillingInterval:e}})(),{DisplaySchema:Ie}=(e=>({DisplaySchema:e.object({primary_text:e.string().meta({description:"Main display text (e.g. '$10' or '100 messages')."}),secondary_text:e.string().optional().meta({description:"Secondary display text (e.g. 'per month' or 'then $0.5 per 100')."})})}))(t),{withSpecDefault:xe}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:a})=>(e.add(n,{description:a,default:r}),n)}))(_e),{COMMON:X}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:ve}={STRIPE_PRESENTMENT_CURRENCIES:["usd","aed","afn","all","amd","ang","aoa","ars","aud","awg","azn","bam","bbd","bdt","bif","bmd","bnd","bob","brl","bsd","bwp","byn","bzd","cad","cdf","chf","clp","cny","cop","crc","cve","czk","djf","dkk","dop","dzd","egp","etb","eur","fjd","fkp","gbp","gel","gip","gmd","gnf","gtq","gyd","hkd","hnl","htg","huf","idr","ils","inr","isk","jmd","jpy","kes","kgs","khr","kmf","krw","kyd","kzt","lak","lbp","lkr","lrd","lsl","mad","mdl","mga","mkd","mmk","mnt","mop","mur","mvr","mwk","mxn","myr","mzn","nad","ngn","nio","nok","npr","nzd","pab","pen","pgk","php","pkr","pln","pyg","qar","ron","rsd","rub","rwf","sar","sbd","scr","sek","sgd","shp","sle","sos","srd","std","szl","thb","tjs","top","try","ttd","twd","tzs","uah","ugx","uyu","uzs","vnd","vuv","wst","xaf","xcd","xcg","xof","xpf","yer","zar","zmw"]},{COMMON_SET:Ae}=(e=>({COMMON_SET:new Set(e)}))(X),{hasNoDuplicateCurrencies:J}={hasNoDuplicateCurrencies:i=>{let n=new Set;for(let{currency:r}of i){let a=r.toLowerCase();if(n.has(a))return!1;n.add(a)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:z}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:Ce}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(t),{Infinite:Pe}={Infinite:"inf"},{TierBehavior:Me}=(()=>{var e;return(function(i){i.Graduated="graduated",i.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:ee}=(()=>{var e;return(function(i){i.Prepaid="prepaid",i.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Oe}=(()=>{var e;return(function(i){i.Arrear="arrear",i.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:we}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:Ee}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Te}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(t),{ApiCreditTierSchema:te}=(e=>({ApiCreditTierSchema:e.object({to:e.union([e.number().positive(),e.enum(["inf"])]).meta({description:"Inclusive upper usage boundary for this graduated tier. The final tier must be 'inf'."}),credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group within this tier."})})}))(t),{VIOLATION_MESSAGES:je}={VIOLATION_MESSAGES:{non_final_infinity:"Only the final tier may use an 'inf' boundary.",not_increasing:"Tier boundaries must be strictly increasing.",final_not_infinity:"The final tier must use an 'inf' boundary."}},{MarkupEntrySchema:ie}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(t),{ModelMarkupsSchema:Re}=((e,i)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),i.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(t,ie),{InvoiceUsageEntrySchema:De}=(e=>({InvoiceUsageEntrySchema:e.object({feature_id:e.string().meta({description:"The metered feature whose units are being converted."}),quantity:e.number().nonnegative().meta({description:"Billable units of the metered feature. Converted to the credit-system feature through its rate card."}),properties:e.record(e.string(),e.unknown()).optional().meta({description:"Event properties used to pick the rate card dimension and multipliers."})}).strict()}))(t),{AttachDiscountSchema:ne}=(e=>({AttachDiscountSchema:e.object({reward_id:e.string().optional().meta({description:"The ID of the reward to apply as a discount."}),promotion_code:e.string().optional().meta({description:"The promotion code to apply as a discount."})}).refine(n=>n.reward_id||n.promotion_code,{message:"Either reward_id or promotion_code must be provided."}).meta({title:"AttachDiscount",description:"A discount to apply. Can be either a reward ID or a promotion code."})}))(t),{CustomLineItemSchema:ke}=(e=>({CustomLineItemSchema:e.object({amount:e.number().meta({description:"Amount in dollars for this line item (e.g. 10.50). Can be negative for credits."}),description:e.string().meta({description:"Description for the line item."})})}))(t),{UnixMsTimestampSchema:Ne}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(t),{CreateInvoicePreviewLineSchema:Ue}=(e=>({CreateInvoicePreviewLineSchema:e.object({plan_id:e.string().nullable(),feature_id:e.string().nullable(),description:e.string(),amount:e.number(),amount_after_discounts:e.number(),quantity:e.number().nullable(),prorated:e.boolean(),period_start:e.number().nullable(),period_end:e.number().nullable()})}))(t),{ReissueInvoiceParamsSchema:Ot}=(e=>({ReissueInvoiceParamsSchema:e.object({invoice_id:e.string().meta({description:"The Autumn invoice ID to void and replace.",example:"inv_2b3c4d5e6f7g8h"}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer and memo are applied to the replacement invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the replacement invoice. Defaults to the original invoice's due date; required when that date has already passed."}),update_customer_email:e.email().optional().meta({description:"Updates the customer's billing email before the replacement is issued, so Stripe sends the new invoice to this address."})})}))(t),{InvoiceModeParamsSchema:l}=(e=>({InvoiceModeParamsSchema:e.object({enabled:e.boolean().meta({description:"When true, creates an invoice and sends it to the customer instead of charging their card immediately. Uses Stripe's send_invoice collection method."}),enable_plan_immediately:e.boolean().default(!1).meta({description:"If true, enables the plan immediately even though the invoice is not paid yet."}),finalize:e.boolean().default(!0).meta({description:"If true, finalizes the invoice so it can be sent to the customer. If false, keeps it as a draft for manual review."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer (e.g. bank details) is applied to the invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the invoice before it is due (Stripe days_until_due)."})}).meta({title:"InvoiceMode",description:"Invoice mode configuration. Creates an invoice instead of charging the card immediately."})}))(t),{InvoiceTemplateSchema:wt}=(e=>({InvoiceTemplateSchema:e.object({id:e.string().meta({description:"Unique identifier for the invoice template."}),name:e.string().meta({description:"User-defined name to distinguish this template when sending an invoice."}),footer:e.string().optional().meta({description:"Footer text rendered on the invoice, typically bank details so customers can pay directly."}),memo:e.string().optional().meta({description:"Memo shown near the top of the invoice (Stripe invoice description), e.g. a contact line for payment questions."}),net_terms_days:e.number().int().positive().optional().meta({description:"Default number of days the customer has to pay before the invoice is due. Overridable when sending."}),created_at:e.number().optional().meta({description:"Timestamp (ms) when the template was created."})})}))(t),{BasePriceSchema:qe}=((e,i,n)=>({BasePriceSchema:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),interval:e.enum(i).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),display:n.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(t,H,Ie),{CURRENCY_CODES:Be}=((e,i,n)=>({CURRENCY_CODES:[...e,...i.filter(a=>!n.has(a)).sort()]}))(X,ve,Ae),{ApiPriceProcessorsSchema:re}=((e,i)=>({ApiPriceProcessorsSchema:e.object({stripe:i.nullish()}).meta({"x-atmn-mapping":!0})}))(t,Ce),{AllocatedBillingFieldSchema:Ve}=((e,i)=>({AllocatedBillingFieldSchema:e.enum(i).optional().meta({internal:!0,description:"How an allocated usage_based price bills mid-cycle quantity changes. 'arrear' (default) bills at period end. 'prorated_legacy' is only returned for prices still on the legacy immediate-proration behavior; omit it to migrate the price to 'arrear'."})}))(t,Oe),{CreditDimensionNameSchema:Fe}=((e,i,n)=>({CreditDimensionNameSchema:e.string().min(1).max(i).refine(a=>!a.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(t,we,Ee),{ApiCreditMatchSchema:ae}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Te),{findCreditTierViolations:Le}=(e=>({findCreditTierViolations:n=>{let r=[],a=(o,m)=>r.push({index:o,reason:m,message:e[m]}),s=0;for(let[o,m]of n.entries()){let p=o===n.length-1;if(m==="inf"){p||a(o,"non_final_infinity");continue}(!Number.isFinite(m)||m<=s)&&a(o,"not_increasing"),s=m,p&&a(o,"final_not_infinity")}return r}}))(je),{ApiCreditMultiplierSchema:Qe}=((e,i)=>({ApiCreditMultiplierSchema:e.object({match:i,factor:e.number().positive().optional().meta({description:"Multiplies the matched rate. All matching multipliers stack."}),add:e.number().optional().meta({description:"Added to the rate after every factor is applied, in credits per billing-unit group."})}).strict().refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(t,ae),{ProviderMarkupsSchema:Ge}=((e,i)=>({ProviderMarkupsSchema:e.record(e.string(),i).nullish()}))(t,ie),{InvoiceFeatureQuantitySchema:oe}=((e,i,n)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(i).meta({description:"Which of the feature's prices to use: 'prepaid' or 'usage_based'."}),quantity:e.number().nonnegative().optional().meta({description:"Billable feature units in total, exclusive of any included usage. Not per seat or per entity. For a credit-system feature this is the number of credits."}),usage:e.array(n).optional().meta({description:"For credit-system features: billable units of the source features, converted through the credit rate card. Mutually exclusive with quantity."}),prorate:e.boolean().optional().meta({description:"Whether to prorate this line against period_start / period_end. Defaults to true for prepaid and false for usage-based."})}).strict().refine(a=>a.quantity!==void 0!=(a.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(t,ee,De),{CreateInvoicePreviewSchema:Et}=((e,i)=>({CreateInvoicePreviewSchema:e.object({currency:e.string(),lines:e.array(i),subtotal:e.number(),discount_total:e.number(),tax:e.object({total:e.number(),amount_inclusive:e.number(),amount_exclusive:e.number(),status:e.enum(["complete","incomplete"])}).nullable(),total:e.number(),due_date:e.number().nullable()})}))(t,Ue),{SUPPORTED_SET:$e}=(e=>({SUPPORTED_SET:new Set(e)}))(Be),{ApiCreditDimensionBaseSchema:Ke}=((e,i)=>({ApiCreditDimensionBaseSchema:e.object({match:i,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(t,ae),{refineGraduatedTiers:ce}=(e=>({refineGraduatedTiers:(n,r)=>{let a=e(n.tiers.map(s=>s.to));for(let{index:s,message:o}of a)r.addIssue({code:"custom",message:o,path:["tiers",s,"to"]})}}))(Le),{ApiFeatureMarkupsOverrideSchema:Ze}=((e,i,n)=>({ApiFeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional().meta({description:"Default percentage markup for customers on this plan. Use -100 to make usage free."}),provider_markups:i.meta({description:"Per-provider markup percentages for customers on this plan."}),model_markups:n.meta({description:"Per-model markup overrides for customers on this plan."})})}))(t,Ge,Re),{isValidCurrencyCode:We}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))($e),{ApiCreditDimensionSchema:Ye}=((e,i,n,r)=>({ApiCreditDimensionSchema:e.union([i.extend({tier_behavior:e.literal("graduated"),tiers:e.array(n).min(1)}).strict().superRefine(r),i.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(t,Ke,te,ce),{CurrencyCodeSchema:se}=((e,i)=>({CurrencyCodeSchema:e.string().refine(i,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(t,We),{AdditionalCurrencyTierSchema:He}=((e,i)=>({AdditionalCurrencyTierSchema:e.object({currency:i,amount:e.number().optional().meta({description:"Per-unit amount for this tier in this currency."}),flat_amount:e.number().optional().meta({description:"Flat amount for this tier in this currency, if the tier uses one."})}).refine(r=>r.amount!==void 0||r.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(t,se),{ApiCreditSchemaItemBaseSchema:ue}=((e,i,n,r)=>({ApiCreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string().nonempty().meta({description:"ID of the metered feature that draws from this credit system."}),billing_units:e.number().positive().optional().meta({description:"Number of metered-feature units priced together. Defaults to one when omitted."}),dimensions:e.record(i,n).optional().meta({description:"Named rates chosen by event properties. The most specific match sets the rate; with no match the item's own rate applies."}),multipliers:e.record(i,r).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(t,Fe,Ye,Qe),{ApiFlatCreditSchemaItemSchema:Xe}=((e,i)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:i.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(ue,t),{AdditionalCurrencyPriceSchema:Je}=((e,i)=>({AdditionalCurrencyPriceSchema:e.object({currency:i,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(t,se),{AdditionalCurrencyTierArraySchema:ze}=((e,i,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(i).refine(n,{message:r})}))(t,He,J,z),{ApiGraduatedCreditSchemaItemSchema:et}=((e,i,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:i.literal("graduated"),tiers:i.array(n).min(1)}).strict().superRefine(r)}))(ue,t,te,ce),{AdditionalCurrencyPriceArraySchema:me}=((e,i,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(i).refine(n,{message:r})}))(t,Je,J,z),{ApiUsageTierWithCurrenciesSchema:tt}=((e,i,n)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(i)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:n.optional().meta({description:"Per-currency amounts for this tier. Tier boundaries ('to') are shared across all currencies."})}).refine(a=>a.amount!==void 0||a.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(a=>({...a,amount:a.amount??0})).pipe(e.object({to:e.number().or(e.literal(i)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:n.optional()}))}))(t,Pe,ze),{ApiCreditSchemaItemSchema:it}=((e,i,n)=>({ApiCreditSchemaItemSchema:e.union([i,n])}))(t,et,Xe),{BasePriceParamsSchema:nt}=((e,i,n,r)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:i({schema:n.number().optional(),defaultValue:1,description:"Number of intervals per billing cycle. Defaults to 1."}),additional_currencies:r.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),base_currency:n.string().optional().meta({internal:!0}),entitlement_id:n.string().optional().meta({internal:!0}),price_id:n.string().optional().meta({internal:!0}),stripe_price_id:n.string().optional().meta({description:"Stripe price id this base price is billed under. Set by sync flows to capture the actual Stripe price when it differs from the catalog default.",internal:!0})}).meta({title:"BasePrice",description:"Base price configuration for a plan."})}))(qe,xe,t,me),{PlanItemPriceParamsSchema:rt}=((e,i,n,r,a,s,o)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(p=>p??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:i.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(a).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(s).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:o,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(t,me,tt,Me,H,ee,Ve),{ApiFeatureOverrideSchema:at}=((e,i,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(i).optional().meta({description:"For credit system features: replaces the feature's credit_schema entirely for customers on this plan."}),markups:n.optional().meta({description:"For AI credit system features: replaces the feature's markup chain entirely for customers on this plan. An unset level means no markup at that level rather than inheriting the feature's."})})}))(t,it,Ze),{InvoiceBasePriceParamsSchema:de}=((e,i)=>({InvoiceBasePriceParamsSchema:e.pick({amount:!0,interval:!0,interval_count:!0}).extend({processors:i.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(nt,re),{InvoiceItemPriceParamsSchema:ot}=((e,i)=>({InvoiceItemPriceParamsSchema:e.pick({amount:!0,tiers:!0,tier_behavior:!0,interval:!0,interval_count:!0,billing_units:!0,billing_method:!0}).extend({processors:i.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(rt,re),{InvoiceLicenseQuantitySchema:ct}=((e,i,n)=>({InvoiceLicenseQuantitySchema:e.object({license_plan_id:e.string().meta({description:"The license plan linked to the parent plan."}),quantity:e.number().int().nonnegative().meta({description:"Billable seats, exclusive of any included seats."}),customize:e.object({price:i.nullable().optional()}).strict().optional().meta({description:"Override the license's per-seat price on this invoice."}),feature_quantities:e.array(n).optional().meta({description:"Feature charges priced through the license plan."}),prorate:e.boolean().optional().meta({description:"Whether to prorate seat charges against period_start / period_end. Defaults to true."})}).strict()}))(t,de,oe),{InvoiceCustomizeItemSchema:st}=((e,i,n)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:i.optional().meta({description:"Pricing to use for this feature on this invoice."}),feature_override:n.pick({credit_schema:!0}).strict().optional().meta({description:"For credit-system features: a credit rate card to use when converting `usage` on this invoice."})}).strict()}))(t,ot,at),{InvoiceCustomizeSchema:ut}=((e,i,n)=>({InvoiceCustomizeSchema:e.object({price:i.nullable().optional().meta({description:"Override the plan's base price for this invoice. Pass null or an amount of 0 to omit the base price line."}),items:e.array(n).optional().meta({description:"Override feature pricing for this invoice. Only pricing fields are accepted; grants, resets and rollovers are not part of an invoice."})}).strict().meta({title:"InvoiceCustomize",description:"Pricing overrides applied to this invoice only. The catalog and the customer's plan are not changed."})}))(t,de,st),{InvoicePlanParamsSchema:mt}=((e,i,n,r,a)=>({InvoicePlanParamsSchema:e.object({plan_id:e.string().meta({description:"The catalog plan (or variant) whose pricing to use."}),version:e.number().optional().meta({description:"Plan version. Defaults to the active version."}),customize:i.optional(),feature_quantities:e.array(n).optional(),license_quantities:e.array(r).optional(),discounts:e.array(a).optional().meta({description:"Discounts applied only to this plan's lines."}),prorate:e.boolean().optional().meta({description:"Whether to prorate the base price against period_start / period_end. Defaults to true."})}).strict()}))(t,ut,oe,ct,ne),{CreateInvoiceParamsSchema:Tt}=((e,i,n,r,a)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(i).optional(),custom_line_items:e.array(n).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(r).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:a.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start \u2192 period_end against one price interval starting at period_start."}),period_end:a.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(o=>o.period_start===void 0==(o.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(o=>o.period_start===void 0||o.period_end===void 0||o.period_end>o.period_start,{message:"period_end must be after period_start."})}))(t,mt,ke,ne,Ne);var w=t.object({type:t.literal("native_purchase"),receiptId:t.uuid(),orderId:t.uuid(),productVersionId:t.uuid(),provider:t.enum(["apple","google"]),productId:t.string().min(1).max(255),productKind:q,replacement:t.strictObject({sourceOrderId:t.uuid(),sourceProductId:t.string().min(1).max(255),policy:t.enum(["apple_store","google_full_price"]),sourceAccountTokens:t.array(t.uuid()).max(50)}).nullable(),appAccountToken:t.uuid().optional(),obfuscatedAccountId:t.string().min(1).max(64).optional(),obfuscatedProfileId:t.uuid().optional(),basePlanId:t.string().min(1).max(255).optional(),offerId:t.string().min(1).max(255).optional(),offerKind:t.enum(["none","introductory","promotional"]),currency:u,catalogAmountMinor:t.number().int().nonnegative().max(1e8),discountMinor:t.number().int().nonnegative().max(1e8),trialDays:t.number().int().min(1).max(730).nullable(),seatBundle:t.array(t.strictObject({key:t.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:t.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:t.strictObject({offerId:t.string().min(1).max(255),keyId:t.string().min(1).max(255),nonce:t.uuid(),signature:t.string().min(1).max(1024),timestamp:t.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,i)=>{let n=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(n?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!n&&e.productKind==="membership"&&e.basePlanId===void 0||e.discountMinor>e.catalogAmountMinor||new Set(e.seatBundle.map(a=>a.key)).size!==e.seatBundle.length||e.trialDays!==null&&(e.discountMinor!==0||e.offerKind==="none")||e.offerKind==="none"&&e.discountMinor!==0||(n?!e.appAccountToken||e.obfuscatedAccountId!==void 0||e.obfuscatedProfileId!==void 0||e.basePlanId!==void 0||e.offerKind==="promotional"!=(e.applePromotionalOffer!==null)||e.offerKind==="promotional"!=(e.offerId!==void 0)||e.applePromotionalOffer!==null&&e.applePromotionalOffer.offerId!==e.offerId:e.appAccountToken!==void 0||!e.obfuscatedAccountId||!e.obfuscatedProfileId||e.applePromotionalOffer!==null||e.offerKind==="none"!=(e.offerId===void 0)))&&i.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});var pe=t.strictObject({itemKey:t.string().regex(/^paid:feature:[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),internal_feature_id:t.uuid(),includedAmount:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:t.number().int().min(0).max(1e4),terms:N,pricing:k.optional(),unitAmountMinor:t.number().int().min(0).max(1e8),productId:t.string().min(1).max(255).nullable(),priceId:t.string().min(1).max(255).nullable()}).superRefine((e,i)=>{(e.quantity<e.terms.minimumQuantity||e.quantity>e.terms.maximumQuantity||e.productId===null!=(e.priceId===null)||e.quantity>0&&(e.pricing||e.unitAmountMinor>0)&&e.priceId===null)&&i.addIssue({code:"custom",message:"Purchased quantities need their published bounds and immutable price binding"});try{U(e.includedAmount,e.terms.units,e.quantity),g({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{i.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});var _=t.string().trim().min(1).max(64).regex(/^[a-z][a-z0-9_]*$/,"ID \u4F7F\u7528\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u4E0B\u5212\u7EBF\uFF0C\u5E76\u4EE5\u5B57\u6BCD\u5F00\u5934"),Qt=t.object({amountCents:t.number().int().min(0).max(1e8),currency:u,interval:t.enum(["free","month","year"]),currencyOptions:t.partialRecord(u,t.number().int().min(1).max(1e8)).optional()}).refine(e=>e.interval==="free"?e.amountCents===0:e.amountCents>0,"\u514D\u8D39\u5957\u9910\u91D1\u989D\u5FC5\u987B\u4E3A 0\uFF0C\u4ED8\u8D39\u91D1\u989D\u5FC5\u987B\u5927\u4E8E 0").refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency)&&(e.interval!=="free"||Object.keys(e.currencyOptions).length===0),"\u9644\u52A0\u5E01\u79CD\u4E0D\u80FD\u91CD\u590D\u9ED8\u8BA4\u5E01\u79CD\uFF1B\u514D\u8D39\u5957\u9910\u4E0D\u8BBE\u7F6E\u9644\u52A0\u4EF7\u683C");var ai=t.strictObject({requestId:t.uuid(),predecessorOperationId:t.uuid().optional(),invoiceMode:l.optional(),entityId:t.uuid().optional(),billingSubscriptionId:t.uuid().optional(),newBillingSubscription:t.literal(!0).optional(),offerId:t.uuid().optional(),nativeOffer:O.optional(),plans:t.array(t.strictObject({productVersionId:t.uuid(),seatQuantities:t.record(_,t.number().int().min(0).max(1e4)).optional(),featureQuantities:t.record(t.uuid(),t.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100,"At most 100 feature quantities").optional()})).min(1).max(20).refine(e=>new Set(e.map(i=>i.productVersionId)).size===e.length,"Plan versions must be unique"),provider:t.enum(["stripe","apple","google","merchant"]),currency:u}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||["apple","google"].includes(e.provider)&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||["stripe","merchant"].includes(e.provider)&&!e.billingSubscriptionId,"A new billing subscription has no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),oi=t.strictObject({operationId:t.uuid()}),c=t.number().int().min(0).max(1e8),dt=t.strictObject({lineId:t.uuid(),productVersionId:t.uuid(),productName:t.string().min(1).max(80),interval:t.enum(["free","week","month","year","one_time"]),intervalCount:t.number().int().min(1).max(156).optional(),baseAmountMinor:c,seats:t.array(t.strictObject({key:_,quantity:t.number().int().min(0).max(1e4),includedQuantity:t.number().int().min(0).max(1e4),maximumQuantity:t.number().int().min(0).max(1e4),unitAmountMinor:c})).max(20),prepaid:t.array(pe).max(100).optional(),catalogAmountMinor:c,trial:j.nullable()}).refine(e=>new Set(e.seats.map(i=>i.key)).size===e.seats.length&&e.seats.every(i=>i.quantity>=i.includedQuantity&&i.quantity<=i.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((i,n)=>i+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((i,n)=>i+g({quantity:n.quantity,unitAmountMinor:n.unitAmountMinor,...n.pricing===void 0?{}:{pricing:n.pricing}}),0)===e.catalogAmountMinor,"Quote must retain its published base price and component quantities"),fe=t.string().regex(/^[A-Za-z0-9_-]{1,200}$/),pt=t.strictObject({id:fe,name:t.string().min(1).max(40),percent_off:t.number().gt(0).max(100).optional(),amount_off:t.number().int().positive().optional(),currency:t.string().regex(/^[a-z]{3}$/).optional(),duration:t.enum(["once","repeating","forever"]),duration_in_months:t.number().int().min(1).max(36).optional()}).refine(e=>e.percent_off===void 0!=(e.amount_off===void 0)&&e.amount_off===void 0==(e.currency===void 0)&&e.duration==="repeating"==(e.duration_in_months!==void 0),"A Stripe coupon has one percentage or amount and months only when repeating"),lt=t.strictObject({subscriptionId:t.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:t.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:t.array(t.strictObject({id:t.string(),price_id:t.string(),quantity:t.number().int().nonnegative(),discounts:t.array(t.strictObject({id:t.string(),coupon:t.string(),start:t.number(),end:t.number().nullable()})).optional()})).min(1).max(100),prorationDate:t.number().int().nonnegative(),amountMinor:t.number().int().positive(),periodStartMs:t.number(),periodEndMs:t.number()}),be=t.strictObject({invoiceMode:l.optional(),append:lt.optional(),provider:t.literal("stripe"),executor:t.enum(["indiana","merchant"]),accountId:t.string().regex(/^acct_[A-Za-z0-9]+$/),mode:t.enum(["payment","subscription"]),lineItems:t.array(t.strictObject({price:t.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:t.number().int().min(1).max(1e4),priceId:t.uuid(),productName:t.string().min(1).max(80),amountMinor:t.number().int().min(0).max(1e8),currency:t.string().regex(/^[a-z]{3}$/),interval:t.enum(["week","month","year","one_off"]),intervalCount:t.number().int().min(1).max(52),slot:t.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:t.strictObject({mode:t.enum(["graduated","volume"]),tiers:t.array(t.strictObject({upTo:t.number().int().min(1).max(1e6).nullable(),unitAmountMinor:t.number().int().min(0).max(1e8),flatAmountMinor:t.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:t.array(t.strictObject({coupon:fe,terms:pt})).max(1),trialPeriodDays:t.number().int().min(1).max(730).nullable(),metadata:t.strictObject({grooveCheckoutId:t.uuid(),grooveCustomerId:t.uuid()}),expiresAt:t.iso.datetime({offset:!0})}),ht=t.strictObject({operationId:t.uuid(),merchantTerms:b.optional(),entityId:t.uuid().nullable(),billingSubscriptionId:t.uuid().nullable(),discount:t.strictObject({offerId:t.uuid(),couponId:t.uuid(),discount:Q,duration:G,amountMinor:c,allocations:t.array(t.strictObject({productVersionId:t.uuid(),amountMinor:c})).min(1).max(20),expiresAt:t.iso.datetime({offset:!0})}).nullable(),charge:t.strictObject({effectiveAt:t.iso.datetime({offset:!0}),periodEndsAt:t.iso.datetime({offset:!0}),debitMinor:c,discountMinor:c,taxMinor:c,totalMinor:c}).nullable(),expiresAt:t.iso.datetime({offset:!0}),provider:t.enum(["stripe","apple","google","merchant"]),nativeOffer:O.optional(),currency:u,lines:t.array(dt).min(1).max(20),catalogAmountMinor:c,nativeDiscountMinor:c.optional(),automaticTax:t.boolean(),execution:t.union([be,v]).nullable()}).refine(e=>!e.merchantTerms||e.provider==="merchant"&&y(e.merchantTerms,e.operationId,"purchase",e.currency)).refine(e=>e.provider==="merchant"?e.execution?.provider==="merchant"&&e.execution.operationId===e.operationId&&e.execution.catalogAmountMinor===e.catalogAmountMinor&&e.execution.currency===e.currency&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&e.execution.discount?.grantId===e.discount?.offerId:e.provider==="stripe"?e.execution?.provider!=="merchant"&&(e.lines[0]?.trial?.cardRequired===!1&&!e.execution?.invoiceMode?.enabled?e.execution===null&&e.discount===null:e.execution!==null&&e.execution.metadata.grooveCheckoutId===e.operationId&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.mode===(e.lines.some(i=>!["one_time","free"].includes(i.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(i=>i.price!==null))&&e.execution.discounts.every(i=>i.coupon===i.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(i=>e.discount!==null&&(i.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&i.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${i.terms.amount_off}`&&i.terms.amount_off===e.discount.discount.amountOffCents&&i.terms.currency?.toUpperCase()===e.currency&&i.terms.duration==="once"))):e.execution===null,"Stripe execution must carry the quote identity, expiry, mode, trial and held coupon").refine(e=>(!e.discount||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.discount.duration.type==="once")&&e.discount.amountMinor<=e.catalogAmountMinor&&e.discount.allocations.length===e.lines.length&&e.discount.allocations.every((i,n)=>{let r=e.lines[n];return r!==void 0&&i.productVersionId===r.productVersionId&&i.amountMinor<=r.catalogAmountMinor})&&e.discount.allocations.reduce((i,n)=>i+n.amountMinor,0)===e.discount.amountMinor)&&(["stripe","merchant"].includes(e.provider)?e.nativeOffer===void 0:e.nativeOffer!==void 0&&e.lines.length===1&&e.nativeOffer.discountMinor<=e.catalogAmountMinor&&e.nativeOffer.trialDays===(e.lines[0]?.trial?.days??null)&&(!e.discount||e.nativeOffer.discountMinor===e.discount.amountMinor))&&(!e.charge||e.billingSubscriptionId!==null&&e.charge.totalMinor===e.charge.debitMinor-e.charge.discountMinor+e.charge.taxMinor&&e.charge.discountMinor<=e.charge.debitMinor&&Date.parse(e.charge.periodEndsAt)>Date.parse(e.charge.effectiveAt))&&new Set(e.lines.map(i=>i.lineId)).size===e.lines.length&&e.lines.reduce((i,n)=>i+n.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),ci=t.strictObject({operationId:t.uuid(),orderId:t.uuid(),append:t.boolean().optional(),invoiceMode:t.boolean().optional(),status:t.enum(["pending","complete","cancelled","failed"]),executor:t.enum(["indiana","merchant"]),checkoutUrl:t.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:t.union([be,v]).nullable(),currency:u,catalogAmountMinor:c,taxMinor:c,totalMinor:t.number().int().min(0).max(2e8).nullable(),quoteFinalized:t.boolean(),nativePurchase:w.nullable(),confirmedAt:t.iso.datetime({offset:!0}).nullable().optional(),quote:ht.optional(),merchantExecution:f.nullable().optional(),problem:h.nullable().optional(),authority:S.optional()}).refine(e=>(e.checkoutUrl===null||e.executor==="indiana"||e.merchantExecution?.type==="purchase")&&(e.execution===null||e.executor==="merchant"),"Only Indiana-executed purchases carry a Checkout URL and only record-only purchases carry execution instructions"),x=t.strictObject({enabled:t.literal(!0),featureIds:t.array(t.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),si=t.strictObject({requestId:t.uuid(),offerId:t.uuid().optional(),invoiceMode:l.optional(),membershipId:t.uuid(),carryOverBalances:x.optional(),carryOverUsages:x.optional(),membershipIds:t.array(t.uuid()).min(1).max(20).optional(),prorationBehavior:t.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:t.enum(["immediate","renewal","store"]),change:t.discriminatedUnion("type",[t.strictObject({type:t.literal("plan"),productVersionId:t.uuid()}),t.strictObject({type:t.literal("seats"),licenseKey:_,quantity:t.number().int().min(0).max(1e4)}),t.strictObject({type:t.literal("quantity"),internal_feature_id:t.uuid(),quantity:t.number().int().min(0).max(1e4)}),t.strictObject({type:t.literal("cancel")}),t.strictObject({type:t.literal("uncancel")}),t.strictObject({type:t.literal("billing_cycle"),billingCycleAnchor:t.union([t.literal("now"),t.number().int().positive().max(0xe677d21fdbff)])})])}).refine(e=>!e.offerId||e.change.type==="plan"&&e.timing!=="store","A selected plan-change offer requires a merchant target Product").refine(e=>e.timing!=="store"||e.change.type==="plan","Store timing applies to a native plan replacement").refine(e=>e.change.type!=="billing_cycle"||e.timing===(e.change.billingCycleAnchor==="now"?"immediate":"renewal"),"Use immediate for now and renewal for a future millisecond anchor").refine(e=>!e.membershipIds||["cancel","uncancel"].includes(e.change.type)&&e.membershipIds.includes(e.membershipId)&&new Set(e.membershipIds).size===e.membershipIds.length,"Grouped actions require unique cancel/uncancel targets including the primary membership").refine(e=>!e.carryOverBalances&&!e.carryOverUsages||e.change.type==="plan"&&e.timing==="immediate","Carry applies only to immediate upgrades").refine(e=>!e.prorationBehavior||e.change.type==="quantity","prorationBehavior applies to prepaid quantity changes"),I=t.string().regex(/^price_[A-Za-z0-9]+$/),le=t.strictObject({grooveUpdateId:t.uuid(),grooveCustomerId:t.uuid()}),he=t.strictObject({price:I.nullable(),priceId:t.uuid().optional(),quantity:t.number().int().min(0).max(1e4)}),ye=t.strictObject({provider:t.literal("stripe"),invoiceMode:l.optional(),executor:t.enum(["indiana","merchant"]),accountId:t.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:t.string().regex(/^sub_[A-Za-z0-9]+$/),action:t.enum(["update","cancel","schedule","release"]),update:t.strictObject({items:t.array(he).max(20),remove:t.array(I).max(20),restoreItems:t.array(t.strictObject({price:I,quantity:t.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:t.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:t.number().int().positive().optional(),paymentBehavior:t.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:t.boolean().optional(),clearCancelAt:t.literal(!0).optional(),billingCycleAnchorNow:t.literal(!0).optional(),metadata:le}).nullable(),cancel:t.strictObject({prorate:t.literal(!1),invoiceNow:t.literal(!1)}).nullable(),schedule:t.strictObject({currentItems:t.array(t.strictObject({price:I,quantity:t.number().int().min(0).max(1e4)})).max(20),nextItems:t.array(he).min(1).max(20),switchAt:t.number().int().positive(),interval:t.enum(["week","month","year"]),intervalCount:t.number().int().min(1).max(52),resetBillingCycleAnchor:t.literal(!0).optional(),metadata:le}).nullable(),release:t.strictObject({schedule:t.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:t.iso.datetime({offset:!0})}).refine(e=>["update","cancel","schedule","release"].every(i=>e[i]!==null==(e.action===i))&&(e.executor==="indiana"||[...e.update?.items??[],...e.schedule?.nextItems??[]].every(i=>i.price!==null)),"Stripe update execution carries exactly its action, with bound Prices for the merchant"),ge=t.strictObject({merchantTerms:b.optional(),carryOverBalances:x.optional(),carryOverUsages:x.optional(),operationId:t.uuid(),membershipId:t.uuid(),productVersionId:t.uuid(),timing:t.enum(["immediate","renewal"]),effectiveAt:t.iso.datetime({offset:!0}),expiresAt:t.iso.datetime({offset:!0}),currency:u,creditMinor:c,debitMinor:c,discountMinor:c,taxMinor:c,totalMinor:c,retainedProductVersionIds:t.array(t.uuid()).max(19),execution:t.union([ye,A])}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&y(e.merchantTerms,e.operationId,"subscription_change",e.currency)),ft=t.strictObject({operationId:t.uuid(),invoiceMode:t.boolean().optional(),membershipId:t.uuid(),productVersionId:t.uuid(),status:t.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:t.enum(["immediate","renewal"]),effectiveAt:t.iso.datetime({offset:!0}),checkoutUrl:t.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:t.enum(["indiana","merchant"]),execution:t.union([ye,A]).nullable(),confirmedAt:t.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:f.nullable().optional(),problem:h.nullable().optional(),quote:ge.optional(),authority:S.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),bt=t.strictObject({operationId:t.uuid(),membershipId:t.uuid(),productVersionId:t.uuid(),timing:t.literal("store"),effectiveAt:t.null(),expiresAt:t.iso.datetime({offset:!0}),currency:u,creditMinor:t.null(),debitMinor:t.null(),discountMinor:t.null(),taxMinor:t.null(),totalMinor:t.null(),retainedProductVersionIds:t.array(t.uuid()).max(19),store:t.strictObject({provider:t.enum(["apple","google"]),productId:t.string().min(1).max(255),catalogAmountMinor:c,policy:t.enum(["apple_store","google_full_price"])})}),yt=t.strictObject({operationId:t.uuid(),membershipId:t.uuid(),productVersionId:t.uuid(),status:t.enum(["prepared","pending","effective","cancelled","failed"]),timing:t.literal("store"),effectiveAt:t.iso.datetime({offset:!0}).nullable(),checkoutUrl:t.null(),nativePurchase:w.nullable()}),ui=t.union([ge,bt]),mi=t.union([ft,yt]),E=R,d=D,di=t.strictObject({requestId:t.uuid(),invoiceId:t.uuid(),...M.shape}).refine(P,"A partial refund states amountMinor; a full refund refunds the remaining amount"),Se=t.strictObject({provider:t.literal("stripe"),executor:t.enum(["indiana","merchant"]),accountId:t.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:t.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:E,currency:t.string().regex(/^[a-z]{3}$/),metadata:t.strictObject({indianaRefundId:t.uuid()}),idempotencyKey:t.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:t.array(t.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),gt=t.strictObject({operationId:t.uuid(),merchantTerms:b.optional(),invoiceId:t.uuid(),providerInvoiceId:t.string().min(1).max(200),currency:u,paidMinor:d,refundedMinor:d,pendingMinor:d,amountMinor:E,mode:t.enum(["full","partial"]),entitlementAction:t.enum(["retain","revoke"]),revokes:t.strictObject({customerProductIds:t.array(t.uuid()).max(100),subscriptionIds:t.array(t.string().min(1).max(200)).max(20)}),execution:t.union([Se,C]),expiresAt:t.iso.datetime({offset:!0})}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&y(e.merchantTerms,e.operationId,"refund",e.currency)).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&(e.execution.provider==="merchant"?e.execution.merchantInvoiceId===e.providerInvoiceId&&e.execution.operationId===e.operationId&&e.execution.currency===e.currency:e.execution.invoice===e.providerInvoiceId&&e.execution.metadata.indianaRefundId===e.operationId&&e.execution.currency===e.currency.toLowerCase())&&(e.entitlementAction==="revoke"||e.revokes.customerProductIds.length===0&&e.revokes.subscriptionIds.length===0),"Refund quote must stay within the refundable amount and match its execution"),St=t.strictObject({operationId:t.uuid(),invoiceId:t.uuid(),providerInvoiceId:t.string().min(1).max(200),status:t.enum(["quoted","pending","succeeded","failed","expired"]),executor:t.enum(["indiana","merchant"]),currency:u,amountMinor:E,mode:t.enum(["full","partial"]),entitlementAction:t.enum(["retain","revoke"]),refundId:t.string().min(1).max(200).nullable(),quote:gt.optional(),execution:t.union([Se,C]).nullable(),confirmedAt:t.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:f.nullable().optional(),problem:h.nullable().optional(),authority:S.optional(),failureReason:t.string().min(1).max(200).nullable(),createdAt:t.iso.datetime({offset:!0}),completedAt:t.iso.datetime({offset:!0}).nullable()}).refine(e=>(e.execution===null||e.executor==="merchant"&&e.status==="quoted")&&(e.status!=="succeeded"||e.refundId!==null),"Only quoted record-only refunds carry instructions; a succeeded refund names its Stripe refund"),pi=t.strictObject({invoiceId:t.uuid(),currency:u,paidMinor:d,refundedMinor:d,pendingMinor:d,refundableMinor:d,executor:t.enum(["indiana","merchant"]).nullable(),canRefund:t.boolean(),operations:t.array(St).max(50)}).refine(e=>e.operations.every(i=>i.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),li=t.strictObject({requestId:t.uuid(),...M.shape}).refine(P,"A partial refund states amountMinor; a full refund refunds the remaining amount");var Ai=t.strictObject({processContext:Y.optional(),...W,selector:t.discriminatedUnion("type",[t.strictObject({type:t.literal("paywall"),paywallId:t.uuid()}),t.strictObject({type:t.literal("version"),versionId:t.uuid()})]),customerId:t.uuid().optional(),commerce:B,locale:t.string().min(1).max(35),requirement:V.optional()}),T=t.strictObject({id:t.uuid(),paywallId:t.uuid(),version:t.number().int().positive(),document:$.omit({requirement:!0,offeringId:!0}),offering:t.strictObject({id:t.uuid()}),content:t.strictObject({environmentId:t.uuid(),offeringVersionId:t.uuid(),artifact:Z.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:L,check:F.nullable()}).superRefine((e,i)=>{let n=new Set(e.document.products.items.map(r=>r.productVersionId));(e.document.offeringVersionId!==e.offering.id||Object.values(e.capabilities.plans).some(r=>!n.has(r.versionId)))&&i.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})}),Ci=t.strictObject(T.shape).omit({document:!0,offering:!0}).extend({content:T.shape.content.unwrap()});function Pi(e,i){let n=K.parse(i);if(n.offeringVersionId!==e.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");let r=structuredClone(e.capabilities);for(let[a,s]of Object.entries(n.catalog)){let o=r.plans[a],m=s.channels.stripe?.prices.find(p=>p.currency===o?.currency);o&&m&&Object.assign(o,{amountMinor:m.amountMinor,interval:s.interval,intervalCount:s.intervalCount,...s.prepaid?.length?{prepaid:s.prepaid}:{}})}return T.parse({...e,capabilities:r,document:{schemaVersion:3,kind:n.kind,name:n.name,presentation:n.presentation,products:n.products,offeringVersionId:n.offeringVersionId,screen:n.screen,buttons:n.buttons},offering:{id:n.offeringVersionId}})}export{W as a,Y as b,Ot as c,Et as d,Tt as e,ai as f,oi as g,ht as h,ci as i,si as j,ge as k,ui as l,mi as m,di as n,gt as o,St as p,Ai as q,T as r,Ci as s,Pi as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{E as S}from"./chunk-
|
|
1
|
+
import{E as S}from"./chunk-WRUW2UIJ.js";import{a as P}from"./chunk-DSPLGTQI.js";var D=767;function ne(e,r,o=()=>!0,l="Close"){let n=e.ownerDocument.defaultView,i=e.ownerDocument.createElement("button");i.type="button",i.setAttribute("aria-label",l),i.style.cssText="position:absolute;inset:0 48px auto;z-index:2;height:24px;border:0;padding:0;background:transparent;touch-action:none;cursor:grab";let a=e.ownerDocument.createElement("span");a.style.cssText="display:block;width:36px;height:4px;border-radius:4px;margin:8px auto 12px;background:currentColor;opacity:.22;pointer-events:none",i.append(a),e.prepend(i);let p,s=0,c=!1,h=()=>{i.hidden=e.dataset.presentation!=="sheet",i.setAttribute("aria-disabled",String(!o()))},b=t=>{h(),!(i.hidden||!o()||t.button!==0)&&(p={y:t.clientY,time:Date.now(),id:t.pointerId},s=0,c=!1,i.setPointerCapture?.(t.pointerId))},x=t=>{!p||t.pointerId!==p.id||(s=Math.max(0,t.clientY-p.y),e.style.transform=`translateY(${s}px)`)},d=t=>{if(!p||t.pointerId!==p.id)return;let m=Math.max(1,Date.now()-p.time),y=t.type!=="pointercancel"&&o()&&(s>120||s>40&&s/m>.5);c=s>6,p=void 0,i.releasePointerCapture?.(t.pointerId),e.style.transform="",y?r():s&&typeof e.animate=="function"&&!n?.matchMedia?.("(prefers-reduced-motion: reduce)").matches&&e.animate([{transform:`translateY(${s}px)`},{transform:"none"}],{duration:200,easing:"cubic-bezier(.2,.8,.2,1)"}),s=0},u=()=>{if(c){c=!1;return}!p&&s===0&&o()&&r()};i.addEventListener("pointerdown",b),i.addEventListener("pointermove",x),i.addEventListener("pointerup",d),i.addEventListener("pointercancel",d),i.addEventListener("click",u);let f=typeof MutationObserver=="function"?new MutationObserver(h):void 0;return f?.observe(e,{attributes:!0,attributeFilter:["data-presentation"]}),n?.addEventListener("resize",h),h(),()=>{f?.disconnect(),n?.removeEventListener("resize",h),i.remove(),e.style.transform=""}}function I(e,r,o=!1){return(e.type==="modal"||e.type==="sheet")&&e.mobile&&o&&r<=D?e.mobile:e.type}function re(e,r,o){let l=e.ownerDocument.defaultView,n=r.presentation,i;if((n.type==="modal"||n.type==="sheet")&&n.backdrop){let t=`lp-backdrop-${crypto.randomUUID()}`,m={none:"transparent",scrim:"#f2f2f2cc",dim:"#0006","strong-dim":"#000000bf",blur:"#0006"};e.dataset.indianaBackdrop=t,i=e.ownerDocument.createElement("style"),i.textContent=`dialog[data-indiana-backdrop="${t}"]::backdrop{background:${m[n.backdrop]};backdrop-filter:${n.backdrop==="blur"?"blur(16px)":"none"}}`,e.append(i)}let a=r.pages?.[0]?.root.style?.shape,p=a?.type==="pill"?"9999px":a?.type==="rect"?typeof a.radius=="number"?`${a.radius}px`:[a.radius.topLeft,a.radius.topRight,a.radius.bottomRight,a.radius.bottomLeft].map(t=>`${t}px`).join(" "):void 0,s=(n.type==="modal"||n.type==="sheet")&&(n.desktopWidth!==void 0||n.mobile!==void 0),c=n.type,h,b,x=!1,d=t=>{x||!Number.isFinite(t)||t<0||(b=t,c!=="fullscreen"&&c!=="inline"&&(e.style.height=`min(${Math.max(t,40)}px, calc(100dvh - ${c==="sheet"?0:32}px))`))},u=()=>{if(!x&&(c=h??I(n,l?.innerWidth??1024,l?.matchMedia?.("(pointer: coarse)").matches===!0),e.dataset.presentation=c,!(!s||n.type!=="modal"&&n.type!=="sheet"))){if(e.style.boxSizing="border-box",e.style.padding="0",e.style.border="0",e.style.overflow="hidden",e.style.outline="none",e.tabIndex=-1,e.style.background=r.theme.background,e.style.color=r.theme.text,c==="fullscreen")e.style.width="100vw",e.style.height="100dvh",e.style.maxWidth="100vw",e.style.maxHeight="100dvh",e.style.margin="0",e.style.borderRadius="0";else{let t=n.mobile==="sheet"&&c==="sheet",m=n.desktopWidth,y=l?.innerWidth??1024;e.style.width=t?`${y}px`:m?`${Math.min(m.max,Math.max(y*m.viewport/100,m.min))}px`:`${S[n.size]}px`,e.style.maxWidth=`${Math.max(0,y-(c==="sheet"?0:32))}px`,e.style.maxHeight=c==="sheet"?"100dvh":"calc(100dvh - 32px)",e.style.margin=c==="sheet"?"auto auto 0":"auto",e.style.borderRadius=p??(c==="sheet"?"16px 16px 0 0":"24px"),e.style.height="",b!==void 0&&d(b)}o?.(c)}},f=s?[l?.matchMedia?.(`(max-width: ${D}px)`),l?.matchMedia?.("(pointer: coarse)")].filter(t=>t!==void 0):[];if(s){l?.addEventListener("resize",u);for(let t of f)t.addEventListener?t.addEventListener("change",u):t.addListener?.(u)}return u(),{responsive:s,get type(){return c},latch(){x||h!==void 0||(u(),h=c)},setContentHeight:d,destroy(){if(!x){x=!0,i?.remove(),delete e.dataset.indianaBackdrop,l?.removeEventListener("resize",u);for(let t of f)t.removeEventListener?t.removeEventListener("change",u):t.removeListener?.(u)}}}}function oe(e,r,o=!1){let l=e.ownerDocument.defaultView;if(typeof e.animate!="function"||l?.matchMedia?.("(prefers-reduced-motion: reduce)").matches)return;let n=o?{duration:300,easing:"cubic-bezier(0.23, 1, 0.32, 1)"}:{duration:240,easing:"cubic-bezier(0.2, 0.8, 0.2, 1)"};e.animate(r==="sheet"?[{transform:"translateY(100%)"},{transform:"none"}]:r==="modal"?[{opacity:0,transform:o?"translateY(12px) scale(0.96)":"translateY(8px) scale(0.98)"},{opacity:1,transform:"none"}]:[{opacity:0},{opacity:1}],n);try{e.animate([{opacity:0},{opacity:1}],{...n,pseudoElement:"::backdrop"})}catch{}}function T(e,r){e.style.cssText=["position:absolute","z-index:1","top:calc(4px + env(safe-area-inset-top, 0px))","inset-inline-end:calc(4px + env(safe-area-inset-right, 0px))","width:44px","height:44px","padding:0","border:0",`background:radial-gradient(circle, ${r.background} 0 15px, color-mix(in srgb, ${r.text} 22%, ${r.background}) 15px 16px, transparent 16.5px)`,`color:${r.text}`,"font:400 20px/1 system-ui,sans-serif","cursor:pointer","touch-action:manipulation"].join(";")}var ce=15e3;function de(e,r,o,l){let n=e.ownerDocument,i=new AbortController,a=!1,p=!1,s;function c(){s?.tagName==="DIALOG"&&s.close?.(),s?.remove(),s=void 0}function h(d,u){p||(p=!0,c(),(d==="dismissed"||d==="error")&&i.abort(u??new DOMException("Presentation cancelled","AbortError")),!(!a&&d!=="ready")&&P(r.onPresentationState,d==="error"?{surface:o,state:d,error:u}:{surface:o,state:d}))}let b=l,x=()=>{p||b()};return{setDismissHandler(d){b=d},get active(){return a&&!p},get cancelled(){return i.signal.aborted},start(d,u){if(!(a||p)){if(a=!0,r.loading!=="host"){let f=(u??n.documentElement.lang)||"en",t=n.createElement(d?"dialog":"div");s=t,t.dataset.longplayLoading=o;let m=f.startsWith("zh")?"\u6B63\u5728\u52A0\u8F7D":"Loading";t.setAttribute("aria-label",m),t.style.cssText="position:relative;box-sizing:border-box;background:Canvas;color:CanvasText;padding:24px 48px 24px 24px;"+(d?"position:fixed;width:min(480px,calc(100% - 32px));border:0;border-radius:16px;max-height:calc(100dvh - 32px)":"width:100%");let y=n.createElement("div");y.setAttribute("role","status"),y.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)",y.textContent=m;let v=n.createElement("div");v.setAttribute("aria-hidden","true"),v.style.cssText="display:grid;gap:12px";let E=o==="banner"?[["72%",12],["44%",10]]:[["46%",20],["84%",12],["65%",12],["100%",o==="paywall"?96:64]];for(let[g,M]of E){let k=n.createElement("div");k.style.cssText=`width:${g};height:${M}px;background:currentColor;opacity:.11;border-radius:6px`,v.append(k)}let w=n.createElement("button");w.type="button",w.textContent="\xD7",w.setAttribute("aria-label",f.startsWith("zh")?"\u53D6\u6D88\u52A0\u8F7D":"Cancel loading"),T(w,{background:"Canvas",text:"CanvasText"}),w.addEventListener("click",x),t.addEventListener("cancel",g=>{g.preventDefault(),x()}),t.append(y,v,w),e.append(t),t instanceof n.defaultView.HTMLDialogElement&&(t.showModal?t.showModal():t.open=!0,w.focus({preventScroll:!0}))}P(r.onPresentationState,{surface:o,state:"loading",dismiss:x})}},present(d){if(p)return;let u=!!s;c(),d(u),h("ready")},dismiss:x,finish:h,async wait(d,u){let f=i.signal,t,m,y=new Promise((v,E)=>{m=()=>E(f.reason),f.aborted?m():f.addEventListener("abort",m,{once:!0}),u!==void 0&&(t=setTimeout(()=>E(new Error("Presentation data timed out")),u))});try{let v=await Promise.race([y,d]);return f.throwIfAborted(),v}finally{f.removeEventListener("abort",m),clearTimeout(t)}}}}function C(e){let r={display:"block",position:"fixed",top:"0",left:"0",opacity:"0",pointerEvents:"none",zIndex:"-1"},o=Object.keys(r).map(i=>{let a=i,p=e.style[a];return e.style[a]=r[a],[a,p]}),l=e.inert??!1,n=e.getAttribute("aria-hidden");return e.inert=!0,e.setAttribute("aria-hidden","true"),()=>{for(let[i,a]of o)e.style[i]=a;e.inert=l,n===null?e.removeAttribute("aria-hidden"):e.setAttribute("aria-hidden",n)}}function ue(e,r){let o=e.style.width;e.style.width=`${r.getBoundingClientRect().width||r.ownerDocument.defaultView?.innerWidth||800}px`;let l=C(e);return()=>{l(),e.style.width=o}}var L=new WeakMap;function me(e,r){return L.set(e,r),()=>L.delete(e)}function fe(e){let r=e.defaultView?.HTMLElement,o=e.activeElement;for(let n=0;n<16&&o?.shadowRoot?.activeElement;n++)o=o.shadowRoot.activeElement;let l=o?L.get(o)?.():void 0;return()=>{!o?.isConnected||!r||!(o instanceof r)||(o.focus({preventScroll:!0}),l?.())}}export{ne as a,I as b,re as c,oe as d,T as e,ce as f,de as g,C as h,ue as i,me as j,fe as k};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e as h}from"./chunk-
|
|
1
|
+
import{e as h}from"./chunk-EZ5RCVVY.js";import{b as J}from"./chunk-23WNEOK4.js";import{c as N,e as x}from"./chunk-WK4WQZHK.js";import{v as Q}from"./chunk-LZV4QJ5E.js";import{a as j,f as H,g as K,h as B,i as F}from"./chunk-B3KFE57L.js";import{b as L}from"./chunk-ACFQLHJR.js";import{b as U}from"./chunk-XZEGVBAI.js";import{a as M}from"./chunk-J4VTKRH7.js";import{qa as G}from"./chunk-WRUW2UIJ.js";import{a as l}from"./chunk-HJLGRW4A.js";import{a as W}from"./chunk-DSPLGTQI.js";async function ce(I,o){if(!M.test(o.customerToken))throw new l("INVALID_TOKEN","A verified Customer credential is required");if(I.session&&I.session.peek()!==o.customerToken)throw new l("SCOPE_MISMATCH","Paywall credential does not match the shared session");let u=h.resolvePaywall.request.parse({funnelId:o.funnelId,funnelVersionId:o.funnelVersionId,selector:o.paywallVersionId?{type:"version",versionId:o.paywallVersionId}:{type:"paywall",paywallId:o.paywallId},commerce:o.commerce,locale:o.locale,...o.requirement?{requirement:o.requirement}:{}}),S=U(I);I.session||S.identify(o.customerToken);let r=null,P=!1,D=new AbortController,s=null,c=null,v=null,w=null,R=null,d=null,f=null,A=0,O=null,_="",V=0,b=new Map,q=new Set;function g(){if(P)throw new l("IDENTITY_CHANGED","Paywall is closed")}function k(){let e=JSON.stringify([A,f!==null]);if(!O||e!==_){_=e;let t=Y(++V);O=t;let a=()=>{O===t&&(O=null)};t.then(a,a)}return O.then(t=>structuredClone(t))}async function Y(e){g();let t=h.resolvePaywall,a=await N(S.request,t,{...u,selector:r?{type:"version",versionId:r.id}:u.selector});J(u,a.paywall.check,a.scope);let i=await x(I,a.paywall);if(g(),o.paywallVersionId?i.id!==o.paywallVersionId:i.paywallId!==o.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");if(r&&(!H(i,r)||i.paywallId!==r.paywallId))throw new l("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");if(e!==V)return structuredClone(r??i);r=i;for(let m of q)W(m,structuredClone(r));return structuredClone(r)}async function E(e){if(g(),w&&e!=="read")throw new l("COMMAND_PENDING","Wait for the original quote");if(!s)throw new l("INVALID_REQUEST","A quoted purchase is required");let t=s;if(e!=="read"){if(f){if(d===e)return f;throw new l("COMMAND_PENDING","Wait for the original purchase command")}if(d&&d!==e)throw new l("COMMAND_PENDING","Read the original purchase before changing an uncertain command");d=e,A++,V++}let a=d,i=A,m=e==="read"&&f===null,p=JSON.stringify([t.operationId,i,f!==null]);if(e==="read"&&b.has(p))return b.get(p).then(n=>structuredClone(n));let C=e==="read"?h.readSubscriptionOperation:h.attach,y=(async()=>{let n=await N(S.request,C,{operationId:t.operationId,...e==="read"?{}:{intent:e},...e==="confirm"&&t.merchantTerms?{merchantConfirmation:Q(t.merchantTerms)}:{}});return K(n.operation,{operationId:t.operationId,currency:u.commerce.currency},"The purchase operation changed"),g(),s?.operationId!==t.operationId?structuredClone(n.operation):(c=F(c,n.operation),(e!=="read"||m&&f===null)&&A===i&&d===a&&(d=null),structuredClone(c))})();if(e!=="read"){f=y;let n=()=>{f===y&&(f=null)};y.then(n,n)}else{b.set(p,y);let n=()=>{b.get(p)===y&&b.delete(p)};y.then(n,n)}return y.then(n=>structuredClone(n))}let T={signal:D.signal,get view(){return r?structuredClone(r):null},get quote(){return s?structuredClone(s):null},get operation(){return c?structuredClone(c):null},get webViewUrl(){return"bundled"},get recovery(){return j({quote:s,operation:c,requestId:R,pending:w!==null||d!==null,destroyed:P})},get pendingCancellation(){return!P&&d==="cancel"},refresh:k,subscribe(e){return P?()=>{}:(q.add(e),()=>q.delete(e))},async preview(e){if(g(),!r)throw new l("INVALID_REQUEST","Load the Paywall first");let t=r.document.buttons[e.actionId];if(t?.type!=="checkout")throw new l("INVALID_REQUEST","Choose an authored purchase action");let a=L(t.product,e.selection,r.capabilities);if(!a)throw new l("PRODUCT_UNAVAILABLE","Choose an available Product");let i=G(r.document.screen,a,e.selection,r.capabilities),m=h.previewAttach.request.parse({funnelId:u.funnelId,funnelVersionId:u.funnelVersionId,requestId:e.requestId,plans:[{productVersionId:a,...Object.keys(i).length?{featureQuantities:i}:{}}],provider:u.commerce.provider,currency:u.commerce.currency,...e.offerId?{offerId:e.offerId}:{},...e.nativeOffer?{nativeOffer:e.nativeOffer}:{}}),p=JSON.stringify(m);if(v&&v!==p&&(w||d||!c||c.status==="pending"))throw new l("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(v===p){if(w)return w;if(s)return structuredClone(s)}v!==p&&(s=null,c=null),v=p,R=m.requestId;let C=(async()=>{let y=h.previewAttach,n=await N(S.request,y,m);return g(),B(n.quote,{productVersionId:a,featureQuantities:i,currency:u.commerce.currency,provider:u.commerce.provider},"The purchase quote changed its selected Product or presentment"),s=n.quote,c=null,structuredClone(s)})();w=C;try{return await C}finally{w===C&&(w=null)}},confirm:()=>E("confirm"),cancel:()=>E("cancel"),read:()=>E("read"),destroy(){P||(P=!0,D.abort(),q.clear(),b.clear(),z?.(),S.dispose(),r=null,s=null,c=null,v=null,R=null)}},z=I.session?.subscribeIdentity(T.destroy);try{return await k(),T}catch(e){throw T.destroy(),e}}export{ce as a};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as $,b as N,c as J,d as q}from"./chunk-
|
|
1
|
+
import{a as $,b as N,c as J,d as q}from"./chunk-ZYTT7ZAB.js";import{a as P}from"./chunk-3VUPVXAV.js";import{a as D}from"./chunk-FVGUBIVT.js";import{a as _}from"./chunk-DSPLGTQI.js";import{b as C,c as O,e as j}from"./chunk-6BTJNSQQ.js";async function B(e,t,o,n={}){let r=n.message??"Invalid SDK JSON response",s=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||s!==null&&(!/^\d+$/.test(s)||Number(s)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(r);let u;try{u=await P(e,t,{signal:o,error:()=>Error(r)})}catch(p){throw o.aborted?Error(r):p}return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(u))}async function G(e,t){if(!e?.body)return;let o=new AbortController,n=()=>o.abort(t?.reason);t?.addEventListener("abort",n,{once:!0}),t?.aborted&&n();let r=setTimeout(()=>o.abort(Error("Exposure response timeout")),2e3);try{return await P(e,16384,{signal:o.signal,error:()=>Error("Exposure response budget")})}finally{clearTimeout(r),t?.removeEventListener("abort",n)}}var be=2*1024*1024,V=256*1024;async function Y(e,t,o,n){let r=()=>{},s=new Promise((u,p)=>{r=()=>p(n.reason),n.addEventListener("abort",r,{once:!0}),n.aborted&&r()});try{let u=e(t,{...o,signal:n});return u.then(p=>{n.aborted&&p.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([u,s])}finally{n.removeEventListener("abort",r)}}async function M(e,t,o,n=!1){if(new TextEncoder().encode(o).byteLength>65536)throw Error("Exposure request budget");let r=new URL(t);r.searchParams.set("sdkVersion",D.version);let s=new AbortController,u=setTimeout(()=>s.abort(Error("Exposure request timeout")),5e3);try{let p=await Y(e,r.href,{method:"POST",headers:{"Content-Type":"text/plain"},body:o,credentials:"omit",keepalive:n,redirect:"error"},s.signal),a=await G(p,s.signal),c;try{c=a&&JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch{}return{response:p,receipt:c}}finally{clearTimeout(u)}}function H(e){let t,o=!1;return{async read(n,r){if(o)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let s=new AbortController;t=s;let{signal:u}=s,p=setTimeout(()=>s.abort(Error("Experiment request timeout")),5e3);try{let a=await Y(e,n,{cache:"no-cache",credentials:"omit",redirect:"error"},u),c=await B(a,r,u);return u.throwIfAborted(),c}finally{clearTimeout(p),t===s&&(t=void 0)}},destroy(){o=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}var Q=20,ie=65536,se=5e3,ae=5,K=e=>new TextEncoder().encode(JSON.stringify(e)).length;function ce(e,t){let o=e,n=r=>Number.isSafeInteger(r)&&r>=0;return!!o&&typeof o=="object"&&n(o.inserted)&&n(o.duplicates)&&n(o.skipped)&&Array.isArray(o.rejected)&&o.inserted+o.duplicates+o.skipped+o.rejected.length===t&&o.rejected.every(r=>!!r&&typeof r=="object"&&n(r.index)&&r.index<t&&typeof r.reason=="string")&&new Set(o.rejected.map(r=>r.index)).size===o.rejected.length}function F(e){let t=[],o,n,r=(a,c)=>{try{e.log?.(`${e.label} ${a}`,c)}catch{}};function s(a){o===void 0&&!n&&t.length&&(o=setTimeout(()=>{p()},a))}async function u(a,c){let g,f;try{({response:g,receipt:f}=await M(e.fetch,e.endpoint,JSON.stringify({events:a}),c))}catch(h){return r("not sent",{error:h}),!1}return g.status===408||g.status===429||g.status>=500?(r("not sent",{status:g.status}),!1):g.ok?ce(f,a.length)?(f.rejected.length&&r("rejected",{rejected:f.rejected}),!0):(r("not acknowledged",{status:g.status}),!1):(r("rejected",{status:g.status,events:a.length}),!0)}function p(a=!0){if(n)return n;clearTimeout(o),o=void 0;let c=[],g=K({events:[]});for(;t.length&&c.length<Q;){let m=K(t[0].event)+(c.length?1:0);if(c.length&&g+m>ie)break;c.push(t.shift()),g+=m}if(!c.length)return Promise.resolve();let f=1e3,h=u(c.map(m=>m.event),a).then(m=>{if(m)return;f=se;let y=c.filter(b=>++b.attempts<ae);y.length<c.length&&r("dropped after retries",{events:c.length-y.length}),t.unshift(...y)}).finally(()=>{n===h&&(n=void 0),s(f)});return n=h,h}return{push(a){t.push({event:structuredClone(a),attempts:0}),t.length>=Q?p():s(1e3)},flush:p}}/*!
|
|
2
2
|
Portions ported from GrowthBook sdk-js @ ed29827 (GrowthBook.ts auto experiments, util.ts mergeQueryStrings,
|
|
3
3
|
plugins/auto-attributes.ts). Copyright (c) GrowthBook, Inc. MIT License.
|
|
4
4
|
*/function ue(e,t){let o,n;try{o=new URL(e),n=new URL(t)}catch{return t}return o.searchParams.forEach((r,s)=>{n.searchParams.has(s)||n.searchParams.set(s,r)}),n.toString()}function de(e,t){let o=navigator.userAgent,n=new URLSearchParams(t.search),r={};for(let s of["source","medium","campaign","term","content"]){let u=n.get(`utm_${s}`);u!==null&&(r[`utm${s[0].toUpperCase()}${s.slice(1)}`]=u)}return{id:e,deviceId:e,url:t.href,path:t.pathname,host:t.host,query:t.search,pageTitle:typeof document>"u"?"":document.title,browser:/Edg/.test(o)?"edge":/Chrome/.test(o)?"chrome":/Firefox/.test(o)?"firefox":/Safari/.test(o)?"safari":"unknown",deviceType:/Mobi/.test(o)?"mobile":"desktop",...r}}function le(e){let t=e;if(!(!!t&&typeof t=="object"&&typeof t.environmentId=="string"&&typeof t.trackExposures=="boolean"&&/^[a-f0-9]{64}$/.test(t.generation??"")&&Array.isArray(t.experiments)&&t.experiments.length<=100&&t.experiments.every(n=>!!n&&!["namespace","status","url","groups"].some(r=>Object.hasOwn(n,r))&&(n.hashVersion===void 0||n.hashVersion===2)&&typeof n.key=="string"&&Array.isArray(n.variations)&&n.variations.length>=2&&n.variations.every(r=>!!r&&typeof r.urlRedirect=="string")&&(n.urlPatterns===void 0||Array.isArray(n.urlPatterns)))&&!!t.savedGroups&&typeof t.savedGroups=="object"&&!Array.isArray(t.savedGroups)))throw new Error("Invalid page experiment payload");return t}function Te(e){if(e.configuration&&e.configuration.scope.environmentId!==e.environmentId)throw new Error("Page configuration belongs to another App environment");let t=J(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("environmentId must be the App environment ID");let o=e.fetch??globalThis.fetch.bind(globalThis),n=H(async(i,d)=>{let l=await o(i,d);if(!l.ok)throw l.body?.cancel().catch(()=>{}),new Error(`Page experiments unavailable (${l.status})`);return l}),r=e.log?(i,d)=>_(e.log,i,d):void 0,s=`${t}/api/v1/page-experiments/${e.environmentId}`,u=$(e.deviceIdCookie??"indiana_did"),p=N(),a=null,c={...e.attributes??{}},g="",f=!1,h=!1,m=0,y=0,b=new Map,S=F({endpoint:`${s}/events`,fetch:o,log:r,label:"Exposure"}),k=S.flush,E={trackedExperiments:new Set,log:r,onExperimentViewed:(i,d)=>{e.trackExposures===!1||a?.trackExposures===!1||S.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:u,...p?{sessionId:p}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:i.key,variationKey:d.key})}},z=()=>{E.url=location.href,E.attributes={...de(u,location),...c}};function W(i){if(!e.disableCrossOriginUrlRedirects)return!1;try{let d=new URL(location.href);return i.variations.some(l=>{if(!l.urlRedirect)return!1;let v=new URL(l.urlRedirect);return v.protocol!==d.protocol||v.host!==d.host})}catch{return!0}}function X(i,d){let l=e.configuration?.snapshot?.generation,v=y,te=location.href;g=i;let re=e.navigate??(w=>location.replace(w)),ne=e.navigateDelay??(e.navigate?0:100),oe=e.maxNavigateDelay??1e3;Promise.all([Promise.race([d,new Promise(w=>setTimeout(w,oe))]),new Promise(w=>setTimeout(w,ne))]).then(()=>{!f&&v===y&&location.href===te&&(!e.configuration||e.configuration.fresh&&e.configuration.snapshot?.generation===l)&&re(i)})}function x(){if(!(!a||f||e.configuration&&!e.configuration.fresh)){z();for(let i of a.experiments){if(W(i)){r?.("Auto experiment blocked",{id:i.key});continue}let d;try{d=j(i,E)}catch(l){r?.("Skipping page experiment",{id:i.key,error:String(l)});continue}if(b.set(i.key,d),!!d.inExperiment){if(d.value.urlRedirect){let l=i.persistQueryString?ue(location.href,d.value.urlRedirect):d.value.urlRedirect;C(l,i.urlPatterns??[])?r?.("Skipping redirect because original URL matches redirect URL",{id:i.key}):l!==g&&X(l,k())}break}}}}let R="",Z=()=>{location.href!==R&&(y++,R=location.href,g="",x())},T,L;function ee(){T??=q(Z),addEventListener("pagehide",I)}let I=()=>{k()};async function A(){if(f)return!1;let i=++m,d;try{d=e.configuration?await e.configuration.pageExperiments():await n.read(s,V)}catch(v){if(f||i!==m)return!1;throw v}if(f||i!==m)return!1;let l=le(d);if(l.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Page experiment payload scope changed");return a?.trackExposures===!1&&l.trackExposures&&E.trackedExperiments?.clear(),a=l,E.savedGroups=O(l.savedGroups),!0}function U(){f||(L??=e.configuration?.subscribe(()=>{!f&&e.configuration?.fresh&&A().then(i=>{i&&x()}).catch(i=>r?.("Page configuration unavailable",{error:String(i)}))}),ee(),R=location.href)}return{async start(){h||f||(h=!0,await A()&&(U(),x()))},async refresh(){await A()&&(y++,h&&U(),g="",x())},setAttributes(i){y++,g="",c={...i},x()},getResults(){return new Map(b)},get generation(){return a?.generation??null},destroy(){f||(f=!0,m++,n.destroy(),L?.(),T?.(),removeEventListener("pagehide",I),a=null,b.clear(),k())}}}export{be as a,H as b,F as c,ue as d,de as e,le as f,Te as g};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as e}from"./chunk-ZY4XAKNQ.js";var c=e.enum(["replace","stack_native"]);export{c as a};
|