@tinkerlandai/indiana-sdk 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ import{a as o,b as E}from"./chunk-2HEB2TPD.js";import{Bj as D,Dj as N,Fh as m,Me as b,lj as O,ma as I,na as k,oa as x,pa as h,ra as v,wj as V}from"./chunk-FMAMDKAV.js";async function q(n,t){if(!/^gg_ct_[A-Za-z0-9_-]{43}$/.test(t.customerToken))throw new o("INVALID_TOKEN","A verified Customer credential is required");let a=E(n);a.identify(t.customerToken);let i=m.resolvePaywall.request.parse({selector:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale,...t.requirement?{requirement:t.requirement}:{}}),e=null,s=null,u=null,r=null,c=null;async function d(){let l=m.resolvePaywall,y=l.response.parse(await a.request(l.path,l.request.parse({...i,selector:e?{type:"version",versionId:e.id}:i.selector})));if(y.paywall.paywallId!==t.paywallId)throw new o("INVALID_RESPONSE","The requested Paywall changed");if(e&&(y.paywall.id!==e.id||y.paywall.paywallId!==e.paywallId||y.paywall.offering.id!==e.offering.id))throw new o("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return e=y.paywall,structuredClone(e)}async function p(l){if(!s)throw new o("INVALID_REQUEST","A quoted purchase is required");let y=l==="read"?m.readSubscriptionOperation:m.attach,w=y.response.parse(await a.request(y.path,y.request.parse({operationId:s.operationId,...l==="read"?{}:{intent:l}})));if(w.operation.operationId!==s.operationId||w.operation.currency!==i.commerce.currency)throw new o("INVALID_RESPONSE","The purchase operation changed");return u?.status==="complete"&&w.operation.status!=="complete"||u&&u.status!=="pending"&&w.operation.status==="pending"||(u=w.operation),structuredClone(u)}let f={get view(){return e?structuredClone(e):null},get quote(){return s?structuredClone(s):null},get operation(){return u?structuredClone(u):null},get webViewUrl(){return a.webViewUrl()},refresh:d,async preview(l){if(!e)throw new o("INVALID_REQUEST","Load the Paywall first");let y=e.document.buttons[l.actionId];if(y?.type!=="checkout")throw new o("INVALID_REQUEST","Choose an authored purchase action");let w=b(y.product,l.selection,e.capabilities);if(!w)throw new o("PRODUCT_UNAVAILABLE","Choose an available Product");let C=m.previewAttach.request.parse({requestId:l.requestId,plans:[{productVersionId:w}],provider:i.commerce.provider,currency:i.commerce.currency,...l.offerId?{offerId:l.offerId}:{},...l.nativeOffer?{nativeOffer:l.nativeOffer}:{}}),A=JSON.stringify(C);if(r&&r!==A&&(!u||u.status==="pending"))throw new o("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(r===A){if(c)return c;if(s)return structuredClone(s)}r=A;let P=(async()=>{let F=m.previewAttach,g=F.response.parse(await a.request(F.path,C));if(g.quote.currency!==i.commerce.currency||g.quote.provider!==i.commerce.provider||g.quote.lines.length!==1||g.quote.lines[0].productVersionId!==w)throw new o("INVALID_RESPONSE","The purchase quote changed its selected Product or presentment");return s=g.quote,u=null,structuredClone(s)})();c=P;try{return await P}finally{c===P&&(c=null)}},confirm:()=>p("confirm"),cancel:()=>p("cancel"),read:()=>p("read"),destroy(){a.reset(),e=null,s=null,u=null,r=null}};return await d(),f}function L(n){let t=null,a=null,i=0,e={attributes:v.parse(n.attributes??{}),onFeatureUsage:n.onFeatureUsage?(r,c)=>n.onFeatureUsage(r,structuredClone(c)):void 0,onExperimentViewed:n.onExperimentViewed?(r,c)=>n.onExperimentViewed(structuredClone(r),structuredClone(c)):void 0,stickyBucketAssignmentDocs:structuredClone(n.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:n.saveStickyBucketAssignmentDoc?r=>n.saveStickyBucketAssignmentDoc(structuredClone(r)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},s=r=>{if(!t)throw new Error("Initialize the Feature client before evaluation");if(t.expiresAt&&Date.parse(t.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return structuredClone(h(r,e))};async function u(){if(a)return a;let r=i,c=(async()=>{let d=D.parse(await n.load());if(d.scope.projectId!==n.scope.projectId||d.scope.environment!==n.scope.environment)throw new Error("Feature payload scope changed");if(r!==i)throw new Error("Feature client was reset");return t=structuredClone(d),e.features=t.features,e.savedGroups=I(t.savedGroups),e.trackedFeatureUsage={},structuredClone(t)})();a=c;try{return await c}finally{a===c&&(a=null)}}return{init:u,refresh:u,get generation(){return t?.generation??null},setAttributes(r){e.attributes=v.parse(r)},evalFeature:s,getFeatureValue(r,c){let d=s(r).value;return d===null?structuredClone(c):structuredClone(d)},reset(){i++,a=null,t=null,e.features={},e.savedGroups={},e.stickyBucketAssignmentDocs={},e.attributes={},e.trackedFeatureUsage={},e.trackedExperiments?.clear()}}}function Q(n,t,a){let i=N.parse(n);if(i.evaluationMode!=="local")throw new o("EVALUATION_MODE","Remote nodes are evaluated by Grow");if(i.expiresAt&&Date.parse(i.expiresAt)<=Date.now())throw new o("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition");let e=i.topology.nodes.find(p=>p.id===t);if(!e)throw new o("NOT_FOUND","Funnel node is unavailable");let s=v.parse(a.attributes??{}),u={attributes:s,saveStickyBucketAssignmentDoc:a.saveStickyBucketAssignmentDoc?p=>a.saveStickyBucketAssignmentDoc(structuredClone(p)):void 0,onFeatureUsage:a.onFeatureUsage?(p,f)=>a.onFeatureUsage(p,structuredClone(f)):void 0,onExperimentViewed:a.onExperimentViewed?(p,f)=>a.onExperimentViewed(structuredClone(p),structuredClone(f)):void 0,features:structuredClone(i.growth.features),savedGroups:I(i.growth.savedGroups),stickyBucketAssignmentDocs:structuredClone(a.stickyBucketAssignmentDocs)},r,c;if(e.type==="condition"){let p=i.conditions[e.id];if(!p)throw new o("INVALID_RESPONSE","Local condition rules are unavailable");r=p.find(f=>k(s,f.condition,u.savedGroups))?.port??"default"}else if(e.type==="feature"){if(!e.resources.featureKey)throw new o("INVALID_RESPONSE","Feature reference is unavailable");c=h(e.resources.featureKey,u).value,r="next"}else if(e.type==="split"){let p=e.resources.experimentId,f=p?i.growth.experiments[p]:null;if(!f||!p)throw new o("INVALID_RESPONSE","Experiment reference is unavailable");let l=x(f,u);c=l.value,r=l.inExperiment&&!l.passthrough&&typeof l.value=="string"?l.value:"notParticipating"}else throw new o("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let d=e.outputs[r];if(!d)throw new o("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:t,port:r,target:d,...c===void 0?{}:{value:c}}}function S(n,t){if(n===t)return!0;if(Array.isArray(n)||Array.isArray(t))return Array.isArray(n)&&Array.isArray(t)&&n.length===t.length&&n.every((e,s)=>S(e,t[s]));if(!n||!t||typeof n!="object"||typeof t!="object")return!1;let a=Object.entries(n),i=Object.entries(t);return a.length===i.length&&a.every(([e,s])=>Object.hasOwn(t,e)&&S(s,Reflect.get(t,e)))}function $(n){let t=/^gg_ct_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey);if(typeof window<"u"&&!t)throw new o("SERVER_ONLY","Funnel starts are issued by your backend");if(!t&&!/^gg_sk_[A-Za-z0-9_-]{32,128}$/.test(n.apiKey))throw new o("INVALID_TOKEN","A customer credential or server API key is required");let a=E({...n,timeoutMs:n.timeoutMs??35e3});return a.identify(n.apiKey),{async start(i){let e=O.safeParse({...i,operation:"start"});if(!e.success||e.data.operation!=="start")throw new o("INVALID_REQUEST","Invalid current Funnel start");let s=e.data,u=V.safeParse(await a.request("funnels",s));if(!u.success||!u.data.runToken)throw new o("INVALID_RESPONSE","Funnel start credentials are missing");let r=u.data;if(r.run.source.id!==s.funnelId||r.run.locale!==(s.locale??"en")||!S(r.run.parameters,s.parameters??{}))throw new o("INVALID_RESPONSE","Funnel start contract changed");return{...r,runToken:r.runToken}}}}export{S as a,q as b,L as c,Q as d,$ as e};
@@ -78,11 +78,11 @@ declare const offerSchema: z.ZodObject<{
78
78
  id: z.ZodUUID;
79
79
  couponId: z.ZodUUID;
80
80
  status: z.ZodEnum<{
81
- reserved: "reserved";
81
+ revoked: "revoked";
82
82
  expired: "expired";
83
+ reserved: "reserved";
83
84
  issued: "issued";
84
85
  redeemed: "redeemed";
85
- revoked: "revoked";
86
86
  }>;
87
87
  issuedAt: z.ZodISODateTime;
88
88
  expiresAt: z.ZodISODateTime;
@@ -158,4 +158,123 @@ declare const offerUnavailableReasonSchema: z.ZodEnum<{
158
158
  }>;
159
159
  type OfferUnavailableReason = z.infer<typeof offerUnavailableReasonSchema>;
160
160
 
161
- export type { CouponInput as C, Offer as O, OfferUnavailableReason as a };
161
+ declare const customerPageDataSchema: z.ZodObject<{
162
+ nodes: z.ZodRecord<z.ZodString, z.ZodObject<{
163
+ source: z.ZodEnum<{
164
+ membership: "membership";
165
+ credit_balance: "credit_balance";
166
+ credit_transactions: "credit_transactions";
167
+ billing: "billing";
168
+ billing_controls: "billing_controls";
169
+ customer_plans: "customer_plans";
170
+ credit_packs: "credit_packs";
171
+ credit_pack_orders: "credit_pack_orders";
172
+ offer_history: "offer_history";
173
+ }>;
174
+ status: z.ZodEnum<{
175
+ error: "error";
176
+ ready: "ready";
177
+ idle: "idle";
178
+ loading: "loading";
179
+ }>;
180
+ stale: z.ZodBoolean;
181
+ preview: z.ZodBoolean;
182
+ errorCode: z.ZodOptional<z.ZodString>;
183
+ errorMessage: z.ZodOptional<z.ZodString>;
184
+ resources: z.ZodArray<z.ZodObject<{
185
+ key: z.ZodString;
186
+ name: z.ZodString;
187
+ spendable: z.ZodString;
188
+ reserved: z.ZodString;
189
+ available: z.ZodString;
190
+ expiry: z.ZodNullable<z.ZodString>;
191
+ sources: z.ZodArray<z.ZodObject<{
192
+ id: z.ZodString;
193
+ label: z.ZodString;
194
+ detail: z.ZodArray<z.ZodString>;
195
+ value: z.ZodOptional<z.ZodString>;
196
+ status: z.ZodOptional<z.ZodString>;
197
+ facts: z.ZodArray<z.ZodObject<{
198
+ label: z.ZodString;
199
+ value: z.ZodString;
200
+ }, z.core.$strict>>;
201
+ purchaseId: z.ZodOptional<z.ZodUUID>;
202
+ invoiceUrl: z.ZodOptional<z.ZodURL>;
203
+ billingActions: z.ZodOptional<z.ZodArray<z.ZodObject<{
204
+ action: z.ZodLiteral<"invoice_open">;
205
+ label: z.ZodString;
206
+ }, z.core.$strict>>>;
207
+ membershipActions: z.ZodOptional<z.ZodArray<z.ZodObject<{
208
+ value: z.ZodString;
209
+ label: z.ZodString;
210
+ }, z.core.$strict>>>;
211
+ }, z.core.$strict>>;
212
+ sourceCount: z.ZodNumber;
213
+ sourcePage: z.ZodNumber;
214
+ hasNextSources: z.ZodBoolean;
215
+ hasPreviousSources: z.ZodBoolean;
216
+ }, z.core.$strict>>;
217
+ rows: z.ZodArray<z.ZodObject<{
218
+ id: z.ZodString;
219
+ label: z.ZodString;
220
+ detail: z.ZodArray<z.ZodString>;
221
+ value: z.ZodOptional<z.ZodString>;
222
+ status: z.ZodOptional<z.ZodString>;
223
+ facts: z.ZodArray<z.ZodObject<{
224
+ label: z.ZodString;
225
+ value: z.ZodString;
226
+ }, z.core.$strict>>;
227
+ purchaseId: z.ZodOptional<z.ZodUUID>;
228
+ invoiceUrl: z.ZodOptional<z.ZodURL>;
229
+ billingActions: z.ZodOptional<z.ZodArray<z.ZodObject<{
230
+ action: z.ZodLiteral<"invoice_open">;
231
+ label: z.ZodString;
232
+ }, z.core.$strict>>>;
233
+ membershipActions: z.ZodOptional<z.ZodArray<z.ZodObject<{
234
+ value: z.ZodString;
235
+ label: z.ZodString;
236
+ }, z.core.$strict>>>;
237
+ }, z.core.$strict>>;
238
+ hasNext: z.ZodBoolean;
239
+ hasPrevious: z.ZodBoolean;
240
+ page: z.ZodNumber;
241
+ filter: z.ZodString;
242
+ updatedAt: z.ZodOptional<z.ZodISODateTime>;
243
+ buyingId: z.ZodOptional<z.ZodUUID>;
244
+ membershipBusy: z.ZodOptional<z.ZodBoolean>;
245
+ billingBusy: z.ZodOptional<z.ZodBoolean>;
246
+ membershipReview: z.ZodOptional<z.ZodObject<{
247
+ title: z.ZodString;
248
+ note: z.ZodString;
249
+ facts: z.ZodArray<z.ZodObject<{
250
+ label: z.ZodString;
251
+ value: z.ZodString;
252
+ }, z.core.$strict>>;
253
+ }, z.core.$strict>>;
254
+ membershipResult: z.ZodOptional<z.ZodString>;
255
+ }, z.core.$strict>>;
256
+ }, z.core.$strict>;
257
+ type CustomerPageData = z.infer<typeof customerPageDataSchema>;
258
+ declare const customerDataIntentSchema: z.ZodObject<{
259
+ nodeId: z.ZodString;
260
+ action: z.ZodEnum<{
261
+ filter: "filter";
262
+ billing_adjustment: "billing_adjustment";
263
+ billing_authorization: "billing_authorization";
264
+ buy_pack: "buy_pack";
265
+ billing_portal: "billing_portal";
266
+ invoice_open: "invoice_open";
267
+ refresh: "refresh";
268
+ next: "next";
269
+ previous: "previous";
270
+ membership_preview: "membership_preview";
271
+ membership_confirm: "membership_confirm";
272
+ membership_dismiss: "membership_dismiss";
273
+ sources_next: "sources_next";
274
+ sources_previous: "sources_previous";
275
+ }>;
276
+ value: z.ZodOptional<z.ZodString>;
277
+ }, z.core.$strict>;
278
+ type CustomerDataIntent = z.infer<typeof customerDataIntentSchema>;
279
+
280
+ export type { CouponInput as C, Offer as O, CustomerDataIntent as a, OfferUnavailableReason as b, CustomerPageData as c };
@@ -0,0 +1 @@
1
+ import{a as $}from"./chunk-6X42DWOM.js";import{a}from"./chunk-2HEB2TPD.js";import{Me as Z,dg as K}from"./chunk-FMAMDKAV.js";function ee(I){let n=I.view;if(!n?.paywall)throw new a("INVALID_REQUEST","The current node is not a Paywall");let T=n.paywall.receiptId,Q=n.nodeId,w=n.visit,v=n.paywall.resolution,r=n.paywall.quote,c=n.paywall.operation,_=!1,R=n.paywall.purchaseRequestId,h=null,D=new Map,S=new Map;function E(t){let s=t.run.paywall;if(s?.receiptId===T){if(s.resolution.id!==v.id||s.resolution.offering.id!==v.offering.id)throw new a("INVALID_RESPONSE","The pinned Paywall binding changed");v=s.resolution}if(t.purchase&&t.purchase.receiptId!==T)throw new a("INVALID_RESPONSE","Purchase receipt changed");let l=t.purchase??(s?.receiptId===T?s:null),i=l?.quote??r,u=l?.operation??(i?.operationId===r?.operationId?c:null);if(i&&u&&i.operationId!==u.operationId)throw new a("INVALID_RESPONSE","Purchase operation changed");r=i,(c?.operationId!==u?.operationId||c?.status==="pending"||u?.status==="complete")&&(c=u)}async function m(t,s){if(_)throw new a("IDENTITY_CHANGED","Paywall presentation has closed");let l=D.get(t);if(l){if(JSON.stringify(l.input)!==JSON.stringify(s))throw new a("CONFLICT","A purchase request cannot change its input")}else{let P=I.view;if(!P||P.nodeId!==Q||P.visit!==w||P.paywall?.receiptId!==T)throw new a("PRECONDITION_FAILED","The Paywall visit has changed");l={operation:"submit",requestId:t,nodeId:Q,visit:w,revision:P.revision,input:s},D.set(t,l)}let i=await I.submit(l),u=Date.now()+3e4;for(;i.run.pendingRequest?.requestId===t&&Date.now()<u&&!_;)await new Promise(P=>setTimeout(P,1e3)),i=await I.resume(t);if(i.run.pendingRequest?.requestId===t)throw new a("COMMAND_PENDING","The purchase command is still pending; retry the original request",202);E(i)}async function C(t){if(!r)throw new a("INVALID_REQUEST","A quoted purchase is required");let s=`${t}:${r.operationId}`,l=S.get(s);if(l||(l=crypto.randomUUID(),S.set(s,l)),await m(l,{type:t==="confirm"?"paywall_confirm":"paywall_cancel",operationId:r.operationId}),!c)throw new a("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(c)}return{get view(){return structuredClone(v)},get quote(){return r?structuredClone(r):null},get operation(){return c?structuredClone(c):null},get webViewUrl(){return I.webViewUrl},async refresh(){return E(await I.get()),structuredClone(v)},preview(t){if(R&&R!==t.requestId&&(!c||c.status==="pending"))return Promise.reject(new a("COMMAND_PENDING","Retry the original purchase before starting another"));if(R===t.requestId&&h)return h;let s=v.document.buttons[t.actionId],l=s?.type==="checkout"?Z(s.product,t.selection,v.capabilities):null;if(!l)return Promise.reject(new a("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));R=t.requestId;let i=(async()=>{if(await m(t.requestId,{type:"paywall_quote",actionId:t.actionId,productVersionId:l,...t.offerId?{offerId:t.offerId}:{},...t.nativeOffer?{nativeOffer:t.nativeOffer}:{}}),!r)throw new a("INVALID_RESPONSE","The accepted quote is missing");return structuredClone(r)})();return h=i,i.then(()=>{h===i&&(h=null)},u=>{h===i&&(h=null),u instanceof a&&u.status!==void 0&&u.status<500&&![401,425].includes(u.status)&&(R=null)}),i},confirm:()=>C("confirm"),cancel:()=>C("cancel"),async read(){if(!r)throw new a("INVALID_REQUEST","A quoted purchase is required");if(E(await I.get(void 0,{receiptId:T,operationId:r.operationId})),!c)throw new a("INVALID_RESPONSE","The current purchase result is missing");return structuredClone(c)},destroy(){_=!0,D.clear(),S.clear()}}}async function we(I,n){let{mountScreenPreview:T}=await import("./popup.js"),{showPaywall:Q}=await import("./paywall-6HHA4OJV.js"),w=I.ownerDocument,v=w.activeElement,r=w.createElement("section"),c=w.createElement("div"),_=w.createElement("div"),R=w.createElement("p"),h=w.createElement("p"),D=w.createElement("button"),S=w.createElement("button"),E=w.createElement("button"),m=w.createElement("dialog");r.dataset.indianaFunnel="",r.setAttribute("aria-busy","false"),r.style.cssText="box-sizing:border-box;width:100%;min-width:0;font:14px/1.5 system-ui,sans-serif;color:#172033;background:#fff",_.style.cssText="display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:12px 20px",R.setAttribute("role","status"),h.setAttribute("role","alert"),h.hidden=!0,D.type=S.type=E.type="button",_.append(D,R,h,E,S),r.append(c,_),I.append(r);let C=null,t=null,s=null,l="",i=!1,u=0,P="",O=null,G=Promise.resolve(),q=null,V={},j=new Map,J=new Set,H=new Set,M=new Set,A={},k=e=>{i||(h.textContent=e instanceof Error?e.message:"Request failed",h.hidden=!1,E.hidden=n.client.pendingCommand===null,$(n.onError,e))};function U(){let e=n.client.view;if(!e)throw new a("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision}}async function N(e,o=!1){if(!(u&&!o||i)){u++,r.setAttribute("aria-busy","true"),h.hidden=!0;try{let d=await e();i||await z(n.client.view??d.run)}catch(d){k(d)}finally{u=Math.max(0,u-1),r.setAttribute("aria-busy",String(u>0)),i||(E.hidden=n.client.pendingCommand===null)}}}function Y(e){if(J.has(e)||H.has(e)||i)return;H.add(e);let o=async()=>{if(i||l!==e){H.delete(e);return}if(u||n.client.pendingCommand){setTimeout(()=>{o()},250);return}try{await n.client.submit({operation:"shown",...U()}),J.add(e)}catch(d){k(d)}finally{H.delete(e)}};o()}function X(){O&&clearTimeout(O),!(i||!s||!["running","waiting"].includes(s.status))&&(O=setTimeout(()=>{O=null,N(()=>n.client.get()).finally(X)},s.pendingRequest?1500:5e3))}async function ne(e){let o=n.client.view,d=o?.screen,y=d?.customerData.nodes[e.nodeId];if(!o||!d||!y)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(e.action)){let g=K(d.document,e.nodeId),F=g?.type==="customer_data"?g.data.outputs?.[e.action]:void 0;F&&d.outputs.includes(F)?await N(()=>n.client.submit({operation:"submit",...U(),input:{type:"screen",output:F,answers:A,selection:e.value?{[e.nodeId]:e.value}:{}}})):await n.onCustomerDataIntent?.(e,o);return}let p=e.action.startsWith("sources_")?y.resources.find(g=>g.key===e.value):null;if(e.action.startsWith("sources_")&&!p)throw new a("INVALID_REQUEST","Choose a current resource");let x=`${o.visit}:${e.nodeId}:${p?.key??""}`,L=j.get(x)??[null],b=V[e.nodeId]??{page:1,after:null,filter:"all",...p?{resourceKey:p.key}:{}};if(e.action==="filter"){let g=e.value;if(!g||!["all","purchase","refund","source","usage","debt","settlement"].includes(g))throw new a("INVALID_REQUEST","Unknown data filter");b={page:1,after:null,filter:g},L.splice(0,L.length,null)}else if(e.action==="next"||e.action==="sources_next"){let g=p?.sources.at(-1),F=p?g?{kind:"ledger",cursor:{at:g.detail[0],id:g.id,type:"source"}}:null:d.dataCursors[e.nodeId];if(!F||!p&&!y.hasNext)return;L[b.page]=F,b={...b,page:b.page+1,after:F}}else if(e.action==="previous"||e.action==="sources_previous"){if(b.page<=1)return;b={...b,page:b.page-1,after:L[b.page-2]??null}}j.set(x,L),V={...V,[e.nodeId]:b},await N(()=>n.client.get({nodeId:o.nodeId,visit:o.visit,revision:o.revision,components:V}))}function te(e){let o=e.screen?.presentation;if(!o||o.type==="inline"){m.open&&m.close(),r.parentElement!==I&&I.append(r);return}r.parentElement!==m&&(m.append(r),I.append(m));let d={sm:420,md:640,lg:900};m.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in o?d[o.size]+"px":"100vw"}`,m.setAttribute("aria-label",e.screen?.document.name??"Funnel"),m.open||m.showModal()}async function ie(e){if(i)return;s=e;let o=e.locale.startsWith("zh");D.textContent=o?"\u8FD4\u56DE":"Back",S.textContent=o?"\u5173\u95ED":"Close",E.textContent=o?"\u91CD\u8BD5":"Retry",D.disabled=u>0||!!n.client.pendingCommand||!e.canBack,E.hidden=n.client.pendingCommand===null,R.textContent=e.pendingRequest?o?"\u6B63\u5728\u5904\u7406":"Processing":e.instruction?.type==="wait"?o?"\u7B49\u5F85\u4E2D":"Waiting":"",P!==`${e.revision}:${e.visit}:${e.status}`&&(P=`${e.revision}:${e.visit}:${e.status}`,$(n.onState,structuredClone(e)));let d=e.screen||e.paywall?`${e.id}:${e.nodeId}:${e.visit}`:"";if(d!==l&&(C?.destroy(),C=null,t?.destroy(),t=null,c.replaceChildren(),l=d,A={...e.answers},V={},j.clear()),te(e),e.screen)C||(C=T(c,{mode:"live",rendererUrl:n.client.webViewUrl,title:e.screen.document.name,onAction(f,p={},x={}){A={...A,...x},N(()=>n.client.submit({operation:"submit",...U(),input:{type:"screen",output:f,answers:A,selection:p}}))},onAnswers:f=>{A={...A,...f}},onCustomerDataIntent:f=>{ne(f).catch(k)},onEscape:()=>{W()},onError:f=>k(new Error(f)),onRendered:()=>Y(d)})),C.update(e.screen.document,e.locale,{capabilities:e.screen.capabilities,customerData:e.screen.customerData,parameters:e.parameters,serverInput:{bindings:e.screen.inputs,answers:A}}),await C.ready;else if(e.paywall&&!t){let f=await Q(c,{start:async()=>ee(n.client),onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,onEvent:n.onEvent,onOpenUrl:p=>n.onOpenUrl?n.onOpenUrl({receiptId:e.paywall.receiptId,url:p}):w.defaultView?.location.assign(p),onAction:async p=>{let x=await n.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision,input:{type:"screen",output:p,answers:{}}});await z(n.client.view??x.run)},onError:k,onDismiss:()=>{!i&&n.client.view?.visit===e.visit&&W()}});i?f.host?.destroy():t=f.host,Y(d)}let y=e.instruction;if(y&&["open_url","event"].includes(y.type)&&!M.has(y.receiptId)){let f=w.createElement("button");f.type="button",f.textContent=o?"\u7EE7\u7EED":"Continue",f.onclick=()=>{let p=U();N(async()=>{if(y.type==="open_url"&&(n.onOpenUrl?await n.onOpenUrl({receiptId:y.receiptId,url:y.url}):w.defaultView?.location.assign(y.url)),y.type==="event"){if(!n.onEvent)throw new a("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(y.event)}if(i||n.client.view?.nodeId!==p.nodeId||n.client.view.visit!==p.visit)throw new a("PRECONDITION_FAILED","The client action visit changed");let x=await n.client.submit({operation:"submit",...p,input:{type:"client_action",receiptId:y.receiptId,outcome:"success"}});return M.add(y.receiptId),x})},c.replaceChildren(f)}!e.pendingRequest&&e.status==="completed"&&!M.has(`complete:${e.id}`)&&(M.add(`complete:${e.id}`),$(n.onComplete,structuredClone(e))),X()}function z(e){return G=G.catch(()=>{}).then(()=>ie(e)),G}let re=n.client.subscribe(e=>{z(e).catch(k)});function W(){return q||(i?Promise.resolve():n.client.view&&!["running","waiting"].includes(n.client.view.status)?(B(),Promise.resolve()):(q=N(()=>n.client.submit({operation:"close",...U()}),!0).then(()=>{n.client.view?.status==="closed"&&B()}).finally(()=>{q=null}),q))}function B(){i||(i=!0,O&&clearTimeout(O),re(),C?.destroy(),t?.destroy(),m.close(),m.remove(),r.remove(),v instanceof HTMLElement&&v.isConnected&&v.focus(),$(n.onDismiss,s?structuredClone(s):null))}D.onclick=()=>{N(()=>n.client.submit({operation:"back",...U()}))},S.onclick=()=>{W()},E.onclick=()=>{N(()=>n.client.retry())},m.addEventListener("cancel",e=>{e.preventDefault(),W()});try{let e=await n.client.get();await z(n.client.view??e.run)}catch(e){throw B(),e}return{destroy:B,refresh:()=>N(()=>n.client.get())}}export{we as showFunnelRun};