@tinkerlandai/indiana-sdk 0.6.3 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +19 -2
  2. package/README.md +8 -4
  3. package/README.zh-CN.md +7 -3
  4. package/THIRD_PARTY_NOTICES.md +28 -0
  5. package/dist/{ai-usage-B4W5m4Ie.d.ts → ai-usage-BsrSG955.d.ts} +334 -518
  6. package/dist/chunk-3SONNXFG.js +1 -0
  7. package/dist/chunk-467Z5ISI.js +11 -0
  8. package/dist/{chunk-QG4GM4RI.js → chunk-4AWSZWZD.js} +1 -1
  9. package/dist/{chunk-5TEZEOHX.js → chunk-6MO6Y24B.js} +1 -1
  10. package/dist/chunk-HD74AAFS.js +1 -0
  11. package/dist/chunk-J4RHVU3W.js +1 -0
  12. package/dist/chunk-KQCTDXVD.js +17 -0
  13. package/dist/chunk-NOFNOHUI.js +1 -0
  14. package/dist/chunk-QO4YQLZ4.js +1 -0
  15. package/dist/chunk-RRII2DMC.js +1 -0
  16. package/dist/chunk-WCFVNF5D.js +1 -0
  17. package/dist/chunk-YAFMBXIE.js +4 -0
  18. package/dist/{client-OYRHOMUQ.js → client-F6UPJMHR.js} +1 -1
  19. package/dist/{configuration-sync-C2mytNwU.d.ts → configuration-sync-Bvd956GL.d.ts} +333 -25
  20. package/dist/controls-XG46TKUU.js +2 -0
  21. package/dist/errors-DrdTlPwf.d.ts +57 -0
  22. package/dist/funnel-runtime-host-26QI2W3S.js +1 -0
  23. package/dist/{funnel-runtime-start-CVb2YonU.d.ts → funnel-runtime-start-ChVYbLzV.d.ts} +7604 -3787
  24. package/dist/iam.js +1 -1
  25. package/dist/index.d.ts +3635 -1485
  26. package/dist/index.js +1 -1
  27. package/dist/native-shell.js +1 -1
  28. package/dist/openrouter.d.ts +2 -3
  29. package/dist/openrouter.js +1 -1
  30. package/dist/page.d.ts +13 -13
  31. package/dist/page.js +1 -1
  32. package/dist/paywall-WKOHBYW7.js +1 -0
  33. package/dist/popup.d.ts +9 -16
  34. package/dist/popup.js +12 -12
  35. package/dist/react-native.d.ts +327 -0
  36. package/dist/react-native.js +1 -0
  37. package/dist/server.d.ts +6 -5
  38. package/dist/server.js +1 -1
  39. package/dist/src-UHLPVD6E.js +1 -0
  40. package/dist/visual.js +1 -1
  41. package/package.json +10 -3
  42. package/dist/chunk-CB63JLGT.js +0 -1
  43. package/dist/chunk-D7YHFS6B.js +0 -4
  44. package/dist/chunk-FF3LWJ26.js +0 -11
  45. package/dist/chunk-FVUPV6YE.js +0 -1
  46. package/dist/chunk-ISUXYPYL.js +0 -1
  47. package/dist/chunk-RMJJOSVZ.js +0 -1
  48. package/dist/chunk-S2MSIA57.js +0 -17
  49. package/dist/chunk-VVSQKVE7.js +0 -1
  50. package/dist/chunk-YAMBRNJ2.js +0 -1
  51. package/dist/funnel-runtime-host-KPYLOYYN.js +0 -1
  52. package/dist/paywall-5WU6PX5C.js +0 -1
  53. package/dist/src-U7PBAUBN.js +0 -1
  54. package/dist/{customer-page-B4FGCVpt.d.ts → customer-page-B4LkIr5q.d.ts} +4 -4
  55. package/dist/{screen-16d-xADb.d.ts → screen-iFngkxaL.d.ts} +185 -185
@@ -0,0 +1,57 @@
1
+ import { z } from 'zod';
2
+
3
+ declare const scopeSchema: z.ZodObject<{
4
+ projectId: z.ZodString;
5
+ environment: z.ZodEnum<{
6
+ sandbox: "sandbox";
7
+ live: "live";
8
+ }>;
9
+ }, z.core.$strict>;
10
+ type Scope = z.infer<typeof scopeSchema>;
11
+
12
+ declare const errorRecoverySchema: z.ZodEnum<{
13
+ fix_request: "fix_request";
14
+ authenticate: "authenticate";
15
+ check_permissions: "check_permissions";
16
+ check_scope: "check_scope";
17
+ resolve_conflict: "resolve_conflict";
18
+ reload_state: "reload_state";
19
+ retry_same_request: "retry_same_request";
20
+ configure_integration: "configure_integration";
21
+ check_availability: "check_availability";
22
+ upgrade_sdk: "upgrade_sdk";
23
+ recover_operation: "recover_operation";
24
+ contact_support: "contact_support";
25
+ }>;
26
+ type ErrorRecovery = z.infer<typeof errorRecoverySchema>;
27
+ /** Safe business reasons; never SQL text, resource IDs or provider responses. */
28
+ declare const errorReasonSchema: z.ZodEnum<{
29
+ CAPABILITY_NOT_ENABLED: "CAPABILITY_NOT_ENABLED";
30
+ INTEGRATION_MISSING: "INTEGRATION_MISSING";
31
+ PROVIDER_CREDENTIAL_REJECTED: "PROVIDER_CREDENTIAL_REJECTED";
32
+ PRICE_BINDING_REQUIRED: "PRICE_BINDING_REQUIRED";
33
+ IDEMPOTENCY_CONFLICT: "IDEMPOTENCY_CONFLICT";
34
+ RESULT_UNKNOWN: "RESULT_UNKNOWN";
35
+ STATE_CHANGED: "STATE_CHANGED";
36
+ OPERATION_IN_PROGRESS: "OPERATION_IN_PROGRESS";
37
+ FUNNEL_VERSION_RETIRED: "FUNNEL_VERSION_RETIRED";
38
+ }>;
39
+ type ErrorReason = z.infer<typeof errorReasonSchema>;
40
+
41
+ declare class IndianaError extends Error {
42
+ readonly code: string;
43
+ readonly status?: number | undefined;
44
+ readonly requestId?: string | undefined;
45
+ readonly retryable: boolean;
46
+ readonly recovery: ErrorRecovery;
47
+ readonly retryAfterSeconds?: number;
48
+ readonly reason?: ErrorReason;
49
+ constructor(code: string, message: string, status?: number | undefined, requestId?: string | undefined, metadata?: {
50
+ retryable?: boolean;
51
+ recovery?: ErrorRecovery;
52
+ retryAfterSeconds?: number;
53
+ reason?: ErrorReason;
54
+ });
55
+ }
56
+
57
+ export { IndianaError as I, type Scope as S };
@@ -0,0 +1 @@
1
+ import{a as re}from"./chunk-6X42DWOM.js";import"./chunk-QO4YQLZ4.js";import{Gd as ve,ig as me}from"./chunk-467Z5ISI.js";import"./chunk-3SONNXFG.js";import"./chunk-U6S6AZM6.js";import"./chunk-4K25DELJ.js";import"./chunk-S5TVMQRC.js";import{a}from"./chunk-6MO6Y24B.js";import{Hb as Ce}from"./chunk-HD74AAFS.js";import"./chunk-RRII2DMC.js";import"./chunk-KQCTDXVD.js";function be(P){let M=P.view;if(!M?.paywall)throw new a("INVALID_REQUEST","The current node is not a Paywall");let n=M.paywall.receiptId,te=M.nodeId,se=M.visit,I=M.paywall.resolution,Q=I,v="document"in I?I:null;function F(t){return"document"in t?t.offering.id:t.content.offeringVersionId}function ie(t){if(t.id!==I.id||F(t)!==F(I)||t.content?.artifact.sha256!==I.content?.artifact.sha256)throw new a("INVALID_RESPONSE","The pinned Paywall binding changed")}let m=M.paywall.quote,T=M.paywall.operation,J=!1,q=new AbortController,S=M.paywall.purchaseRequestId,H=0,k=M.paywall.selectionGeneration??0,R=M.paywall.canReselect===!0,C=null,D=new Map,j=new Map;function L(t){if(t.purchase&&t.purchase.receiptId!==n)throw new a("INVALID_RESPONSE","Purchase receipt changed");let r=t.run.paywall;return t.purchase??(r?.receiptId===n?r:null)}function $(){if(J)throw new a("IDENTITY_CHANGED","Paywall presentation has closed")}function X(t,r,w){if($(),r!==H||w!==void 0&&m?.operationId!==w)return!1;let y=k,s=t.run.paywall;if(s?.receiptId===n){if((s.selectionGeneration??0)<k)return!1;k=s.selectionGeneration??0,R=s.canReselect===!0,ie(s.resolution)}let l=L(t),c=k>y,_=c?l?.quote??null:l?.quote??m,N=l?.operation??(_?.operationId===m?.operationId?T:null);if(_&&N&&_.operationId!==N.operationId)throw new a("INVALID_RESPONSE","Purchase operation changed");return s?.receiptId===n&&(Q=s.resolution,v="document"in Q?Q:v?{...Q,document:v.document,offering:v.offering}:null),(c||_?.operationId!==m?.operationId)&&(H++,s?.receiptId===n&&(S=s.purchaseRequestId)),m=_,(T?.operationId!==N?.operationId||T?.status==="pending"||N?.status==="complete")&&(T=N),!0}function B(t,r,w){return new Promise((y,s)=>{let l=!1,c=()=>{clearTimeout(Z),q.signal.removeEventListener("abort",Y)},_=x=>{l||(l=!0,c(),y(x))},N=x=>{l||(l=!0,c(),s(x))},Y=()=>N(new a("IDENTITY_CHANGED","Paywall presentation has closed")),Z=setTimeout(()=>N(new a("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,w)),Math.max(0,r-Date.now()));q.signal.addEventListener("abort",Y,{once:!0}),q.signal.aborted&&Y(),t.then(_,N)})}function h(t){return new Promise(r=>{let w=()=>{clearTimeout(y),q.signal.removeEventListener("abort",w),r()},y=setTimeout(w,t);q.signal.addEventListener("abort",w,{once:!0}),q.signal.aborted&&w()})}async function U(t,r,w){$();let y=D.get(t);if(!y){let c=P.pendingCommands?.find(_=>_.requestId===t)??P.pendingCommand;if(c?.operation==="submit"&&c.requestId===t&&c.nodeId===te&&c.visit===se){r.type==="paywall_quote"&&c.input.type==="paywall_quote"&&c.input.predecessor&&!r.predecessor&&(r={...r,predecessor:c.input.predecessor});let _=me.parse(c),N=me.parse({...c,input:r});if(N.operation!=="submit"||_.operation!=="submit"||JSON.stringify(N.input)!==JSON.stringify(_.input))throw new a("CONFLICT","A restored purchase request cannot change its input");r=N.input,y=_,D.set(t,y)}}if(y){if(JSON.stringify(y.input)!==JSON.stringify(r))throw new a("CONFLICT","A purchase request cannot change its input")}else{let c=P.view;if(!c||c.nodeId!==te||c.visit!==se||c.paywall?.receiptId!==n)throw new a("PRECONDITION_FAILED","The Paywall visit has changed");y={operation:"submit",requestId:t,nodeId:te,visit:se,revision:c.revision,input:r},D.set(t,y)}let s=Date.now()+3e4,l=await B(P.submit(y),s,t);for(;l.run.pendingRequest?.requestId===t&&Date.now()<s&&!J&&(await h(Math.min(1e3,s-Date.now())),!(J||Date.now()>=s));)l=await B(P.resume(t),s,t);if(J)throw new a("IDENTITY_CHANGED","Paywall presentation has closed");if(l.run.pendingRequest?.requestId===t)throw new a("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,t);if(!X(l,w,r.type==="paywall_confirm"||r.type==="paywall_cancel"?r.operationId:void 0))throw new a("PRECONDITION_FAILED","The purchase selection has changed")}async function oe(t){if(!m)throw new a("INVALID_REQUEST","A quoted purchase is required");let r=`${t}:${m.operationId}`,w=j.get(r);if(!w){let y=t==="confirm"?"paywall_confirm":"paywall_cancel",s=P.pendingCommands?.find(l=>l.operation==="submit"&&l.input.type===y&&"operationId"in l.input&&l.input.operationId===m.operationId)??P.pendingCommand;w=s?.operation==="submit"&&s.input.type===y&&"operationId"in s.input&&s.input.operationId===m.operationId?s.requestId:crypto.randomUUID(),j.set(r,w)}if(await U(w,{type:t==="confirm"?"paywall_confirm":"paywall_cancel",operationId:m.operationId},H),!T)throw new a("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(T)}return{get view(){return structuredClone(v)},get quote(){return m?structuredClone(m):null},get operation(){return T?structuredClone(T):null},get webViewUrl(){return P.webViewUrl},get canReselect(){return R},async refresh(){$();let t=H,r=await P.get();if(X(r,t),r.run.paywall?.receiptId!==n)throw new a("PRECONDITION_FAILED","Paywall presentation has changed");if(!v){if("document"in Q||!P.resolvePaywall)throw new a("INVALID_RESPONSE","Public Paywall reader is unavailable");let w=await P.resolvePaywall(Q);$(),ie(w),v={...Q,document:w.document,offering:w.offering}}return structuredClone(v)},preview(t){if(!v)return Promise.reject(new a("PRECONDITION_FAILED","Load the Paywall presentation first"));if(S&&S!==t.requestId&&(C||!R))return Promise.reject(new a("COMMAND_PENDING","Retry the original purchase before starting another"));if(S===t.requestId&&C)return C;let r=v.document.buttons[t.actionId],w=r?.type==="checkout"?ve(r.product,t.selection,v.capabilities):null;if(!w)return Promise.reject(new a("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let y=S!==t.requestId&&k>0?{operationId:m?.operationId??null,generation:k}:void 0;if(y&&(!R||k<=0))return Promise.reject(new a("COMMAND_PENDING","Original purchase requires authoritative termination"));S!==t.requestId&&H++;let s=H;S=t.requestId;let l=(async()=>{if(await U(t.requestId,{type:"paywall_quote",actionId:t.actionId,productVersionId:w,...y?{predecessor:y}:{},...t.offerId?{offerId:t.offerId}:{},...t.nativeOffer?{nativeOffer:t.nativeOffer}:{}},s),!m)throw new a("INVALID_RESPONSE","The accepted quote is missing");return structuredClone(m)})();return C=l,l.then(()=>{C===l&&(C=null)},c=>{C===l&&(C=null),S===t.requestId&&P.pendingCommand?.requestId!==t.requestId&&c instanceof a&&c.status!==void 0&&c.status<500&&![401,425].includes(c.status)&&(S=null)}),l},confirm:()=>oe("confirm"),cancel:()=>oe("cancel"),async read(){if($(),!m)throw new a("INVALID_REQUEST","A quoted purchase is required");let t=m.operationId,r=H,w=P.pendingCommands?.find(c=>c.operation==="submit"&&(c.input.type==="paywall_confirm"||c.input.type==="paywall_cancel")&&c.input.operationId===t)??P.pendingCommand;w?.operation==="submit"&&(w.input.type==="paywall_confirm"||w.input.type==="paywall_cancel")&&w.input.operationId===t&&await P.settle?.(w.requestId);let y=await P.get(void 0,{receiptId:n,operationId:t});$();let s=L(y);if(s?.quote&&s.quote.operationId!==t||s?.operation&&s.operation.operationId!==t)throw new a("INVALID_RESPONSE","Purchase operation changed");let l=X(y,r,t)?T:s?.operation;if(!l)throw new a("INVALID_RESPONSE","The current purchase result is missing");return structuredClone(l)},destroy(){J=!0,q.abort(),D.clear(),j.clear()}}}async function Fe(P,M){let n=M,{mountScreenPreview:te}=await import("./popup.js"),{showPaywall:se}=await import("./paywall-WKOHBYW7.js"),I=P.ownerDocument,Q=I.activeElement,v=I.createElement("section"),F=I.createElement("div"),ie=I.createElement("div"),m=I.createElement("div"),T=I.createElement("button");m.hidden=!0,T.type="button";let J=I.createElement("p"),q=I.createElement("p"),S=I.createElement("button"),H=I.createElement("button"),k=I.createElement("button"),R=I.createElement("dialog");v.dataset.indianaFunnel="",v.setAttribute("aria-busy","false"),v.style.cssText="box-sizing:border-box;width:100%;min-width:0;font:14px/1.5 system-ui,sans-serif;color:#172033;background:#fff",ie.style.cssText="display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:12px 20px",J.setAttribute("role","status"),q.setAttribute("role","alert"),q.hidden=!0,S.type=H.type=k.type="button",ie.append(S,J,q,k,T,H),v.append(F,m,ie),P.append(v);let C=null,D=null,j=null,L="",$="",X="",B="",h=!1,U=0,oe=!1,t="",r=null,w=Promise.resolve(),y=null,s=null,l={},c=new Map,_=new Set,N=new Set,Y=new Set,Z=null,x={},E=!1,he,z=0,V=null,ae="",le=new Map,ye=e=>e?`${e.id}:${e.nodeId}:${e.visit}:${e.revision}:${e.paywall?.quote?.operationId??""}`:"",W=(e,i=null)=>{h||(s=i,q.textContent=e instanceof Error?e.message:"Request failed",q.hidden=!1,k.hidden=n.client.pendingCommand===null,re(n.onError,e))};function K(){let e=n.client.view;if(!e)throw new a("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision}}async function ee(e,i=!1){if(!(U&&!i||h||(E||n.client.view?.recoveryRestricted)&&!i)){U++,v.setAttribute("aria-busy","true"),q.hidden=!0,s=null;try{if(!i&&Z){let o=n.client.view;await Z;let g=n.client.view;if(!o||!g||g.id!==o.id||g.nodeId!==o.nodeId||g.visit!==o.visit||g.stopped||!["running","waiting"].includes(g.status))throw new a("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}if(h)return;let d=await e();h||await ne(n.client.view??d.run)}catch(d){W(d,n.client.pendingCommand?.requestId??null)}finally{U=Math.max(0,U-1),v.setAttribute("aria-busy",String(U>0)),h||(k.hidden=n.client.pendingCommand===null,S.disabled=U>0||!!n.client.pendingCommand||!n.client.view?.canBack)}}}function ge(e){if(E||_.has(e)||N.has(e)||h)return;N.add(e);let i=async()=>{if(E||h||L!==e){N.delete(e);return}if(U||n.client.pendingCommand){setTimeout(()=>{i()},250);return}let d=(async()=>{let g=n.client.view,p=K(),A=p.requestId,u=!1;try{await n.client.submit({operation:"shown",...p})}catch(b){if(!(b instanceof a)||b.code!=="CONFLICT"||b.status!==409||n.client.pendingCommand)throw b;await n.client.get();let f=n.client.view;if(h||E||L!==e||!f||!g||f.id!==g.id||f.source.versionId!==g.source.versionId||f.nodeId!==p.nodeId||f.visit!==p.visit||f.revision<=p.revision||f.stopped||!f.screen||!["running","waiting"].includes(f.status)||n.client.pendingCommand)throw b;let O=K();A=O.requestId,await n.client.submit({operation:"shown",...O})}for(;!h&&L===e&&n.client.pendingCommand?.requestId===A;){if(!n.client.settle)throw new a("COMMAND_PENDING","The original display acknowledgement is still pending");await n.client.settle(A),u=!0,n.client.pendingCommand?.requestId===A&&await new Promise(b=>setTimeout(b,1500))}h||L!==e||(u&&await n.client.get(),!(h||L!==e)&&_.add(e))})();Z=d;let o=()=>{Z===d&&(Z=null),N.delete(e)};d.then(o,g=>{o(),U||W(g)})};i()}function ce(){r&&clearTimeout(r),!(h||!j||!["running","waiting"].includes(j.status)&&!n.client.pendingCommand)&&(r=setTimeout(()=>{r=null,Ie().finally(ce)},j.pendingRequest||n.client.pendingCommand?1500:5e3))}async function Ie(){if(!(h||oe||U)){if(E){await ue(he);return}oe=!0;try{let e=n.client.pendingCommand;e&&n.client.settle&&await n.client.settle(e.requestId);let i=n.client.view,d=l,o=await n.client.get(i?.screen&&Object.keys(d).length?{nodeId:i.nodeId,visit:i.visit,revision:i.revision,components:d}:void 0);!h&&d===l&&await ne(n.client.view??o.run)}catch(e){W(e)}finally{oe=!1}}}async function Ee(e){let i=n.client.view,d=i?.screen,o=d?.customerData.nodes[e.nodeId];if(h||U||!i||!d||!o)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(e.action)){let O=C?.document,G=O?Ce(O,e.nodeId):null,we=G?.type==="customer_data"?G.data.outputs?.[e.action]:void 0;we&&d.outputs.includes(we)?await ee(()=>n.client.submit({operation:"submit",...K(),input:{type:"screen",output:we,answers:x,selection:e.value?{[e.nodeId]:e.value}:{}}})):await n.onCustomerDataIntent?.(e,i);return}let p=e.action.startsWith("sources_")?o.resources.find(O=>O.key===e.value):null;if(e.action.startsWith("sources_")&&!p)throw new a("INVALID_REQUEST","Choose a current resource");let A=`${i.visit}:${e.nodeId}:${p?.key??""}`,u=c.get(A)??[null],f=l[e.nodeId]??{page:1,after:null,filter:"all",...p?{resourceKey:p.key}:{}};if(e.action==="filter"){let O=e.value;if(!O||!(o.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(O))throw new a("INVALID_REQUEST","Unknown data filter");f={page:1,after:null,filter:O},u.splice(0,u.length,null)}else if(e.action==="next"||e.action==="sources_next"){let O=p?.sources.at(-1),G=p?O?{kind:"ledger",cursor:{at:O.detail[0],id:O.id,type:"source"}}:null:d.dataCursors[e.nodeId];if(!G||!p&&!o.hasNext)return;u[f.page]=G,f={...f,page:f.page+1,after:G}}else if(e.action==="previous"||e.action==="sources_previous"){if(f.page<=1)return;f={...f,page:f.page-1,after:u[f.page-2]??null}}c.set(A,u),l={...l,[e.nodeId]:f},await ee(()=>n.client.get({nodeId:i.nodeId,visit:i.visit,revision:i.revision,components:l}))}function Pe(e){let i=e.screen?.presentation;if(!i||i.type==="inline"){R.open&&R.close(),v.parentElement!==P&&P.append(v);return}v.parentElement!==R&&(R.append(v),P.append(R));let d={sm:420,md:640,lg:900};R.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in i?d[i.size]+"px":"100vw"}`,R.setAttribute("aria-label",C?.document?.name??e.screen?.content.document.name??"Funnel"),R.open||R.showModal()}async function Re(e){if(h)return;j=e,s&&n.client.pendingCommand?.requestId!==s&&(q.hidden=!0,s=null);let i=e.locale.startsWith("zh");if(T.textContent=i?"\u56DE\u770B":"History",T.hidden=!n.client.review,S.textContent=E?i?"\u8FD4\u56DE\u5F53\u524D":"Return to current":i?"\u8FD4\u56DE":"Back",H.textContent=i?"\u5173\u95ED":"Close",k.textContent=i?"\u91CD\u8BD5":"Retry",S.disabled=!E&&(U>0||!!n.client.pendingCommand||!e.canBack),k.hidden=n.client.pendingCommand===null,J.textContent=e.pendingRequest?i?"\u6B63\u5728\u5904\u7406":"Processing":e.instruction?.type==="wait"?i?"\u7B49\u5F85\u4E2D":"Waiting":"",t!==`${e.revision}:${e.visit}:${e.status}:${e.stopped}`&&(t=`${e.revision}:${e.visit}:${e.status}:${e.stopped}`,re(n.onState,structuredClone(e))),e.stopped||n.client.configurationReady===!1){E=!1,z++,V?.destroy(),V=null,m.replaceChildren(),m.hidden=!0,F.hidden=!1,C?.destroy(),C=null,D?.destroy(),D=null,F.replaceChildren(),L="",$="",B="",R.open&&R.close(),v.hidden=!0,ce();return}if(v.hidden=!1,E){ce();return}if(e.recoveryRestricted){C?.destroy(),C=null,D?.destroy(),D=null,F.replaceChildren(),L="",J.textContent=i?"\u539F\u8BB0\u5F55\u9700\u8981\u6838\u5BF9\uFF0C\u53EF\u53EA\u8BFB\u56DE\u770B":"Original records require reconciliation; read-only history is available";return}let d=e.screen||e.paywall?`${e.id}:${e.nodeId}:${e.visit}`:"";if(d!==L&&(C?.destroy(),C=null,D?.destroy(),D=null,F.replaceChildren(),L=d,$="",B="",x={...e.answers},l={},c.clear()),Pe(e),e.screen){let g=e.screen.content;C||(C=te(F,{mode:"live",rendererUrl:n.client.webViewUrl,title:g.document.name,onAction(u,b={},f={}){if(E)return;x={...x,...f};let O=Object.fromEntries((e.screen?.inputs??[]).filter(({variable:G})=>Object.hasOwn(x,G)).map(({variable:G})=>[G,x[G]]));ee(()=>n.client.submit({operation:"submit",...K(),input:{type:"screen",output:u,answers:O,selection:b}}))},onAnswers:u=>{E||(x={...x,...u})},onCustomerDataIntent:u=>{E||Ee(u).catch(W)},onEscape:()=>{E||de()},onError:u=>W(new Error(u)),onRendered:()=>ge(d)}));let p={capabilities:e.screen.capabilities,customerData:e.screen.customerData,parameters:e.parameters,serverInput:{bindings:e.screen.inputs,answers:x,values:e.screen.values}},A=JSON.stringify([g,e.locale,p.parameters,e.screen.inputs,e.screen.values]);if(A!==$)C.update(g.document,e.locale,p),$=A,X=JSON.stringify(p.capabilities),B=JSON.stringify(p.customerData);else{let u=JSON.stringify(p.capabilities);u!==X&&(C.updateCapabilities(p.capabilities),X=u),JSON.stringify(p.customerData)!==B&&(C.updateCustomerData(p.customerData),B=JSON.stringify(p.customerData))}await C.ready}else if(e.paywall&&!D){let g=await se(F,{canInteract:()=>!E&&!h&&!n.client.view?.recoveryRestricted,start:async()=>be(n.client),onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,resolveOfferId:n.resolveOfferId,onEvent:n.onEvent,onOpenUrl:p=>n.onOpenUrl?n.onOpenUrl({receiptId:e.paywall.receiptId,url:p,openIn:"same_window"}):I.defaultView?.location.assign(p),onAction:async p=>{if(E)return;let A=await n.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision,input:{type:"screen",output:p,answers:{}}});await ne(n.client.view??A.run)},onError:W,onDismiss:()=>{!E&&!h&&n.client.view?.visit===e.visit&&de()}});h?g.host?.destroy():(D=g.host,D?.setSuspended(E)),ge(d)}let o=e.instruction;if(o&&(o.type==="open_url"||o.type==="event")&&!Y.has(o.receiptId)){let g=I.createElement("button");g.type="button",g.textContent=o.type==="open_url"?`${i?"\u524D\u5F80":"Continue to"} ${new URL(o.url).host}`:i?"\u7EE7\u7EED":"Continue",g.onclick=()=>{let p=K(),A=o.type==="open_url"&&!n.onOpenUrl&&o.openIn==="new_window"?De(o.url):null;ee(async()=>{let u="success";if(o.type==="open_url")if(n.onOpenUrl)try{u=await n.onOpenUrl({receiptId:o.receiptId,url:o.url,openIn:o.openIn})===!1?"failed":"opened"}catch(f){re(n.onError,f),u="failed"}else u=o.openIn==="new_window"&&!A?"failed":"opened";if(o.type==="event"){if(!n.onEvent)throw new a("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(o.event)}if(h||n.client.view?.nodeId!==p.nodeId||n.client.view.visit!==p.visit)throw new a("PRECONDITION_FAILED","The client action visit changed");let b=await n.client.submit({operation:"submit",...p,input:{type:"client_action",receiptId:o.receiptId,outcome:u}});return Y.add(o.receiptId),o.type==="open_url"&&!n.onOpenUrl&&o.openIn==="same_window"&&I.defaultView?.location.assign(o.url),b})},F.replaceChildren(g)}!e.pendingRequest&&e.status==="completed"&&!Y.has(`complete:${e.id}`)&&(Y.add(`complete:${e.id}`),re(n.onComplete,structuredClone(e))),ce()}function De(e){let i=I.defaultView?.open(e,"_blank")??null;return i&&(i.opener=null),i}function ne(e){return w=w.catch(()=>{}).then(()=>Re(e)),w}async function ue(e){if(h||!n.client.review)return;E||(ae=ye(n.client.view),le.set(ae,structuredClone(x))),E=!0,he=e,F.hidden=!0,D?.setSuspended(!0),m.hidden=!1;let i=++z;try{let d=await n.client.review(e);if(h||i!==z||!E)return;if(!d.review)throw new a("INVALID_RESPONSE","Historical projection is missing");V?.destroy(),V=null,m.replaceChildren();let o=d.run.locale.startsWith("zh"),g=I.createElement("p");g.textContent=o?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",m.append(g);for(let[u,b]of d.review.pages.entries()){let f=I.createElement("button");f.type="button",f.textContent=o?`\u7B2C ${u+1} \u9875`:`Page ${u+1}`,f.onclick=()=>{ue(b.receiptId)},m.append(f)}if(d.review.page){let u=d.review.page,b=I.createElement("div");if(b.inert=!0,m.append(b),V=te(b,{mode:"live",rendererUrl:n.client.webViewUrl,title:u.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{},onEscape:()=>{fe()}}),V.update(u.document,d.run.locale,{serverInput:{bindings:u.inputs,answers:u.answers,values:u.values}}),await V.ready,h||i!==z||!E)return}let p=o?{issued:"\u5DF2\u9886\u53D6",reserved:"\u5DF2\u9884\u7559",redeemed:"\u5DF2\u4F7F\u7528",expired:"\u5DF2\u8FC7\u671F",revoked:"\u5DF2\u64A4\u9500",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},A=o?{pending:"\u5904\u7406\u4E2D",complete:"\u5DF2\u5B8C\u6210",cancelled:"\u5DF2\u53D6\u6D88",failed:"\u5931\u8D25",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{pending:"Processing",complete:"Completed",cancelled:"Cancelled",failed:"Failed",unknown:"Status unconfirmed"};for(let u of[...d.review.coupons.map((b,f)=>`${o?"\u4F18\u60E0\u5238":"Coupon"} ${f+1}: ${p[b.status]}`),...d.review.purchases.map((b,f)=>`${o?"\u8D2D\u4E70":"Purchase"} ${f+1}: ${A[b.status]}`)]){let b=I.createElement("p");b.textContent=u,m.append(b)}n.client.view&&await ne(n.client.view)}catch(d){if(i!==z||h)return;V?.destroy(),V=null,m.replaceChildren(),W(d)}}async function fe(){if(!E||h||!n.client.review)return;let e=++z;try{if(await n.client.review(),h||e!==z)return;E=!1,z++,V?.destroy(),V=null,m.replaceChildren(),m.hidden=!0,F.hidden=!1;let i=n.client.view;ye(i)!==ae?(le.set(ae,structuredClone(x)),L="",$=""):(le.delete(ae),D?.setSuspended(!1)),i&&await ne(i)}catch(i){if(e!==z||h)return;V?.destroy(),V=null,m.replaceChildren(),W(i)}}let Ne=n.client.subscribe(e=>{n.client.configurationReady===!1&&(v.hidden=!0,C?.destroy(),C=null,D?.destroy(),D=null,F.replaceChildren(),L="",$="",B="",R.open&&R.close()),ne(e).catch(W)}),Oe=n.client.subscribeError?.(W);function de(){return y||(h?Promise.resolve():n.client.view&&!["running","waiting"].includes(n.client.view.status)?(pe(),Promise.resolve()):(y=ee(()=>n.client.submit({operation:"close",...K()}),!0).then(()=>{n.client.view?.status==="closed"&&pe()}).finally(()=>{y=null}),y))}function pe(){h||(h=!0,r&&clearTimeout(r),Ne(),Oe?.(),C?.destroy(),z++,V?.destroy(),D?.destroy(),R.close(),R.remove(),v.remove(),Q instanceof HTMLElement&&Q.isConnected&&Q.focus(),re(n.onDismiss,j?structuredClone(j):null))}S.onclick=()=>{if(E){fe();return}ee(()=>n.client.submit({operation:"back",...K()}))},T.onclick=()=>{ue()},H.onclick=()=>{de()},k.onclick=()=>{ee(()=>n.client.retry())},R.addEventListener("cancel",e=>{e.preventDefault(),de()});try{let e=await n.client.get();await ne(n.client.view??e.run)}catch(e){throw pe(),e}return{destroy:pe,refresh:Ie,review:ue,exitReview:fe,get unappliedDrafts(){return new Map([...le].map(([e,i])=>[e,structuredClone(i)]))}}}export{Fe as showFunnelRun};