@tinkerlandai/indiana-sdk 0.5.0 → 0.6.1

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 (48) hide show
  1. package/CHANGELOG.md +31 -2
  2. package/README.md +178 -7
  3. package/README.zh-CN.md +96 -6
  4. package/dist/{ai-usage-BzydP8eN.d.ts → ai-usage-C4Eg6sSr.d.ts} +366 -349
  5. package/dist/chunk-46S4DTCD.js +11 -0
  6. package/dist/chunk-4JBIKJMU.js +4 -0
  7. package/dist/chunk-5TEZEOHX.js +1 -0
  8. package/dist/chunk-FRZNOXK6.js +1 -0
  9. package/dist/chunk-GJGI34Q7.js +1 -0
  10. package/dist/chunk-OHDY27EI.js +1 -0
  11. package/dist/chunk-RMJJOSVZ.js +1 -0
  12. package/dist/chunk-S2MSIA57.js +17 -0
  13. package/dist/chunk-S5TVMQRC.js +1 -0
  14. package/dist/chunk-U3TULZCD.js +1 -0
  15. package/dist/configuration-sync-BWn1YZ78.d.ts +1314 -0
  16. package/dist/{customer-page-aZb5Twue.d.ts → customer-page-OBB82t8_.d.ts} +7 -4
  17. package/dist/funnel-runtime-host-YXWVCKAJ.js +1 -0
  18. package/dist/funnel-runtime-start-CKVuIOFs.d.ts +30920 -0
  19. package/dist/{growth-rules-D64pEvg9.d.ts → growth-rules-B4YYy64R.d.ts} +8 -1
  20. package/dist/index.d.ts +15126 -5369
  21. package/dist/index.js +1 -1
  22. package/dist/native-shell.js +1 -1
  23. package/dist/openrouter.d.ts +2 -2
  24. package/dist/openrouter.js +1 -1
  25. package/dist/page.d.ts +21 -23
  26. package/dist/page.js +1 -1
  27. package/dist/paywall-GRSGZLVG.js +1 -0
  28. package/dist/popup.d.ts +10 -7
  29. package/dist/popup.js +6 -6
  30. package/dist/server.d.ts +5 -4
  31. package/dist/server.js +1 -1
  32. package/dist/src-UWBQFGYH.js +1 -0
  33. package/dist/{visual-editor-agent-FDCV3BXP.js → visual-editor-agent-WW65CMKW.js} +1 -1
  34. package/dist/visual.d.ts +4 -2
  35. package/dist/visual.js +1 -1
  36. package/package.json +1 -1
  37. package/dist/chunk-3OSMEG44.js +0 -17
  38. package/dist/chunk-GA6X57BO.js +0 -1
  39. package/dist/chunk-GTBD4BJ4.js +0 -11
  40. package/dist/chunk-QUW4UOKZ.js +0 -4
  41. package/dist/chunk-RMFH5TWV.js +0 -1
  42. package/dist/chunk-YNUVRZRQ.js +0 -1
  43. package/dist/funnel-runtime-host-RZRB2CY6.js +0 -1
  44. package/dist/funnel-runtime-start-JHA9ES24.d.ts +0 -9199
  45. package/dist/paywall-MYBEOVTQ.js +0 -1
  46. package/dist/src-E2GXK6WA.js +0 -1
  47. package/dist/{chunk-ZT523F45.js → chunk-BIFEEVQO.js} +0 -0
  48. package/dist/{screen-16d-xADb.d.ts → screen-BbLE1OMn.d.ts} +160 -160
@@ -1,4 +0,0 @@
1
- import{e as U,f as L,i as A}from"./chunk-3OSMEG44.js";function T(e){if(!/^[A-Za-z0-9_-]{1,64}$/.test(e))throw new Error("Invalid device cookie name");let t="";for(let i of document.cookie.split(";"))if(i.trim().startsWith(`${e}=`))try{t=decodeURIComponent(i.trim().slice(e.length+1))}catch{}return/^[A-Za-z0-9_-]{8,128}$/.test(t)||(t=crypto.randomUUID(),document.cookie=`${e}=${encodeURIComponent(t)}; path=/; max-age=${400*24*3600}; SameSite=Lax`),t}function V(){try{let e=sessionStorage.getItem("indiana_sid");return e||(e=crypto.randomUUID(),sessionStorage.setItem("indiana_sid",e)),e}catch{return}}function $(e){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname))||t.username||t.password||t.search||t.hash)throw new Error("baseUrl must be an https origin without credentials");return t.origin}var v=new Set,x;function D(e){if(v.add(e),!x){let t=history.pushState,i=history.replaceState,r=()=>{for(let s of v)s()},o=function(...s){t.apply(this,s),r()},c=function(...s){i.apply(this,s),r()};history.pushState=o,history.replaceState=c,addEventListener("popstate",r),addEventListener("hashchange",r),x=()=>{history.pushState===o&&(history.pushState=t),history.replaceState===c&&(history.replaceState=i),removeEventListener("popstate",r),removeEventListener("hashchange",r)}}return()=>{v.delete(e),v.size||(x?.(),x=void 0)}}var C="__indiana_visual_editor",d;function M(e,t){if(d&&d.origin===e&&d.environmentId===t&&d.expiresAt>Date.now())return d;try{let i=new URL(location.href).searchParams.get(C);if(!i||i.length>2048)return null;let r=JSON.parse(i);return r.origin!==e||r.environmentId!==t||!/^[a-f0-9-]{36}$/i.test(r.nonce)||r.expiresAt<=Date.now()||r.expiresAt>Date.now()+900*1e3?null:(d=r,r)}catch{return null}}function O(e,t){return!!M(e,t)}function Q(){let e=new URL(location.href);e.searchParams.delete(C),history.replaceState(history.state,"",e.href)}/*!
2
- Portions ported from GrowthBook sdk-js @ ed29827 (GrowthBook.ts auto experiments, util.ts mergeQueryStrings,
3
- plugins/auto-attributes.ts). Copyright (c) GrowthBook, Inc. MIT License.
4
- */function z(e,t){let i,r;try{i=new URL(e),r=new URL(t)}catch{return t}return i.searchParams.forEach((o,c)=>{r.searchParams.has(c)||r.searchParams.set(c,o)}),r.toString()}function W(e,t){let i=navigator.userAgent,r=new URLSearchParams(t.search),o={};for(let c of["source","medium","campaign","term","content"]){let s=r.get(`utm_${c}`);s!==null&&(o[`utm${c[0].toUpperCase()}${c.slice(1)}`]=s)}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(i)?"edge":/Chrome/.test(i)?"chrome":/Firefox/.test(i)?"firefox":/Safari/.test(i)?"safari":"unknown",deviceType:/Mobi/.test(i)?"mobile":"desktop",...o}}function F(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(r=>!!r&&!["namespace","status","url","groups"].some(o=>Object.hasOwn(r,o))&&(r.hashVersion===void 0||r.hashVersion===2)&&typeof r.key=="string"&&Array.isArray(r.variations)&&r.variations.length>=2&&r.variations.every(o=>!!o&&typeof o.urlRedirect=="string")&&(r.urlPatterns===void 0||Array.isArray(r.urlPatterns)))&&!!t.savedGroups&&typeof t.savedGroups=="object"&&!Array.isArray(t.savedGroups)))throw new Error("Invalid page experiment payload");return t}function ee(e){let t=$(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("environmentId must be the App environment ID");let i=e.fetch??globalThis.fetch.bind(globalThis),r=`${t}/api/v1/page-experiments/${e.environmentId}`,o=T(e.deviceIdCookie??"indiana_did"),c=V(),s=null,R={...e.attributes??{}},m="",E=!1,I=new Map,P=[],g;function _(n){return n.length?i(`${r}/events`,{method:"POST",body:JSON.stringify({events:n}),headers:{"Content-Type":"text/plain"},keepalive:!0,credentials:"omit"}).then(()=>{}).catch(a=>e.log?.("Exposure not sent",{error:a})):Promise.resolve()}function f(){return clearTimeout(g),g=void 0,_(P.splice(0,20))}let l={trackedExperiments:new Set,log:e.log,onExperimentViewed:(n,a)=>{e.trackExposures===!1||s?.trackExposures===!1||(P.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:o,...c?{sessionId:c}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:n.key,variationKey:a.key}),g||(g=setTimeout(()=>{f()},1e3)))}},N=()=>{l.url=location.href,l.attributes={...W(o,location),...R}};function G(n){if(!e.disableCrossOriginUrlRedirects)return!1;try{let a=new URL(location.href);return n.variations.some(u=>{if(!u.urlRedirect)return!1;let y=new URL(u.urlRedirect);return y.protocol!==a.protocol||y.host!==a.host})}catch{return!0}}function J(n,a){m=n;let u=e.navigate??(p=>location.replace(p)),y=e.navigateDelay??(e.navigate?0:100),q=e.maxNavigateDelay??1e3;Promise.all([Promise.race([a,new Promise(p=>setTimeout(p,q))]),new Promise(p=>setTimeout(p,y))]).then(()=>{E||u(n)})}function h(){if(!(!s||E||O(t,e.environmentId))){N();for(let n of s.experiments){if(G(n)){e.log?.("Auto experiment blocked",{id:n.key});continue}let a;try{a=A(n,l)}catch(u){e.log?.("Skipping page experiment",{id:n.key,error:String(u)});continue}if(I.set(n.key,a),!!a.inExperiment){if(a.value.urlRedirect){let u=n.persistQueryString?z(location.href,a.value.urlRedirect):a.value.urlRedirect;U(u,n.urlPatterns??[])?e.log?.("Skipping redirect because original URL matches redirect URL",{id:n.key}):u!==m&&J(u,f())}break}}}}let w="",H=()=>{location.href!==w&&(w=location.href,m="",h())},b;function j(){b??=D(H),addEventListener("pagehide",S)}let S=()=>{f()};async function k(){let n=await i(r,{cache:"no-cache",credentials:"omit"});if(!n.ok)throw new Error(`Page experiments unavailable (${n.status})`);let a=F(await n.json());if(a.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Page experiment payload scope changed");s?.trackExposures===!1&&a.trackExposures&&l.trackedExperiments?.clear(),s=a,l.savedGroups=L(a.savedGroups)}return{async start(){await k(),j(),w=location.href,h()},async refresh(){await k(),m="",h()},setAttributes(n){R={...n},h()},getResults(){return new Map(I)},get generation(){return s?.generation??null},destroy(){E=!0,b?.(),removeEventListener("pagehide",S),f()}}}export{T as a,V as b,$ as c,D as d,M as e,Q as f,z as g,W as h,F as i,ee as j};
@@ -1 +0,0 @@
1
- import{a as u}from"./chunk-YNUVRZRQ.js";import{G as w,Hg as E,Ig as M,Jg as j,Kg as O,Lg as T}from"./chunk-GTBD4BJ4.js";import{z as t}from"zod";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Y(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Y as d};
@@ -1 +0,0 @@
1
- import{Fb as k,Fi as V,Nb as C,Qb as j,Tb as T,Ub as v,Vb as L,Yb as R}from"./chunk-GTBD4BJ4.js";import{b as S}from"./chunk-3OSMEG44.js";var U={name:"@tinkerlandai/indiana-sdk",version:"0.5.0",description:"Framework-independent Indiana SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.5"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var e=class extends Error{constructor(h,d,n,N,i){super(d);this.code=h;this.status=n;this.requestId=N;this.name="IndianaError",this.reason=i?.reason;let c=T(h,n??0,{...i,retryAfter:i?.retryAfterSeconds===void 0?void 0:String(i.retryAfterSeconds)});this.retryable=c.retryable,this.recovery=c.recovery,this.retryAfterSeconds=c.retryAfterSeconds}code;status;requestId;retryable;recovery;retryAfterSeconds;reason},$=Symbol("IndianaNoContent");function J(l,A){let h=l.webView??"hosted";if(!["hosted","embedded"].includes(h))throw new e("INVALID_REQUEST","Invalid Web View mode");let d=l.scope?S.parse(l.scope):void 0,n=new URL(l.baseUrl);if(n.username||n.password||n.search||n.hash)throw new e("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(n.protocol!=="https:"&&!(n.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(n.hostname)))throw new e("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let N=l.fetch??globalThis.fetch.bind(globalThis),i=l.timeoutMs??1e4;if(!Number.isFinite(i)||i<=0||i>12e4)throw new e("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let c=null,b,u=0,p=null,f=new Set;function D(){u+=1,c=null,p=null;for(let s of f)s.abort();f.clear()}async function M(s,q={},O="POST",H={}){if(!c)throw new e("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let g=u,o=new AbortController;f.add(o);let y=()=>g!==u?new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new e("TIMEOUT","Indiana request timed out"),I,x=new Promise((r,a)=>{I=()=>a(y()),o.signal.addEventListener("abort",I,{once:!0})}),K=setTimeout(()=>o.abort(),i),G=async()=>{let r=await N(`${n.href.replace(/\/$/,"")}/api/v1/${s}`,{method:O,headers:{"Content-Type":"application/json",Authorization:`Bearer ${c}`,[v]:R.current,[L]:U.version,...d?{"X-Indiana-Project":d.projectId,"X-Indiana-Environment":d.environment}:{}},body:O==="POST"?JSON.stringify(q):void 0,signal:o.signal,credentials:"omit",cache:"no-store",redirect:"error",...H.keepalive?{keepalive:!0}:{}});if(o.signal.aborted)throw y();let a;try{a=r.status===204?$:await r.json()}catch{throw o.signal.aborted?y():new e(r.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",r.status,r.headers.get("X-Request-Id")??void 0)}if(o.signal.aborted)throw y();if(g!==u)throw new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!r.ok){let t=j.safeParse(a),m=t.success&&(!k.safeParse(t.data.error.code).success||C(t.data.error.code,r.status)),_=m?t.data.error.code:"HTTP_ERROR",P=T(_,r.status,{retryAfter:r.headers.get("Retry-After"),recovery:m?t.data.error.recovery:void 0,reason:m?t.data.error.reason:void 0});throw new e(_,m?t.data.error.message:"Indiana request failed",r.status,r.headers.get("X-Request-Id")??(t.success?t.data.requestId:void 0),{...P,...t.success&&t.data.error.retryable===!1?{retryable:!1}:{},...P.retryAfterSeconds===void 0&&t.success&&t.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:t.data.error.retryAfterSeconds}:{}})}if(r.headers.get(v)!==R.current)throw new e("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(d&&a&&typeof a=="object"&&"scope"in a){let t=S.safeParse(a.scope);if(!t.success||t.data.projectId!==d.projectId||t.data.environment!==d.environment)throw new e("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let E=r.headers.get("X-Indiana-Web-View");if(E){if(!/^\/web-view\/renderer\/[a-f0-9]{64}$/.test(E))throw new e("INVALID_RESPONSE","Invalid Web View renderer metadata");b=E}let w=r.headers.get("X-Indiana-Telemetry-Subject");if(w){if(!/^[a-f0-9]{64}$/.test(w))throw new e("INVALID_RESPONSE","Invalid telemetry identity");p!==w&&(p=w,A?.(p))}return a};try{return await Promise.race([G(),x])}catch(r){throw g!==u?new e("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):r instanceof e?r:new e(o.signal.aborted?"TIMEOUT":"NETWORK_ERROR",o.signal.aborted?"Indiana request timed out":"Unable to read the Indiana response")}finally{clearTimeout(K),o.signal.removeEventListener("abort",I),f.delete(o)}}return{subjectKey:()=>p,screenUrl(s){if(!V.safeParse(s).success)throw new e("INVALID_RESPONSE","Invalid published screen render address");return new URL(s,n).href},webViewUrl(){if(h!=="embedded"){if(!b)throw new e("INVALID_RESPONSE","The gateway did not provide a hosted Web View renderer");return new URL(b,n).href}},identify(s){if(!s.trim()||/\s/.test(s)||s.length>4096)throw new e("INVALID_TOKEN","A nonempty server-issued token is required");D(),c=s},reset:D,request:M}}export{e as a,J as b};
@@ -1 +0,0 @@
1
- import{a as V}from"./chunk-6X42DWOM.js";import{a}from"./chunk-YNUVRZRQ.js";import{Te as oe,lg as se}from"./chunk-GTBD4BJ4.js";import"./chunk-3OSMEG44.js";function le(b){let n=b.view;if(!n?.paywall)throw new a("INVALID_REQUEST","The current node is not a Paywall");let A=n.paywall.receiptId,z=n.nodeId,m=n.visit,P=n.paywall.resolution,s=n.paywall.quote,f=n.paywall.operation,x=!1,O=n.paywall.purchaseRequestId,g=null,D=new Map,_=new Map;function R(t){let u=t.run.paywall;if(u?.receiptId===A){if(u.resolution.id!==P.id||u.resolution.offering.id!==P.offering.id)throw new a("INVALID_RESPONSE","The pinned Paywall binding changed");P=u.resolution}if(t.purchase&&t.purchase.receiptId!==A)throw new a("INVALID_RESPONSE","Purchase receipt changed");let c=t.purchase??(u?.receiptId===A?u:null),p=c?.quote??s,o=c?.operation??(p?.operationId===s?.operationId?f:null);if(p&&o&&p.operationId!==o.operationId)throw new a("INVALID_RESPONSE","Purchase operation changed");s=p,(f?.operationId!==o?.operationId||f?.status==="pending"||o?.status==="complete")&&(f=o)}async function I(t,u){if(x)throw new a("IDENTITY_CHANGED","Paywall presentation has closed");let c=D.get(t);if(c){if(JSON.stringify(c.input)!==JSON.stringify(u))throw new a("CONFLICT","A purchase request cannot change its input")}else{let h=b.view;if(!h||h.nodeId!==z||h.visit!==m||h.paywall?.receiptId!==A)throw new a("PRECONDITION_FAILED","The Paywall visit has changed");c={operation:"submit",requestId:t,nodeId:z,visit:m,revision:h.revision,input:u},D.set(t,c)}let p=await b.submit(c),o=Date.now()+3e4;for(;p.run.pendingRequest?.requestId===t&&Date.now()<o&&!x;)await new Promise(h=>setTimeout(h,1e3)),p=await b.resume(t);if(p.run.pendingRequest?.requestId===t)throw new a("COMMAND_PENDING","The purchase command is still pending; retry the original request",202);R(p)}async function E(t){if(!s)throw new a("INVALID_REQUEST","A quoted purchase is required");let u=`${t}:${s.operationId}`,c=_.get(u);if(c||(c=crypto.randomUUID(),_.set(u,c)),await I(c,{type:t==="confirm"?"paywall_confirm":"paywall_cancel",operationId:s.operationId}),!f)throw new a("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(f)}return{get view(){return structuredClone(P)},get quote(){return s?structuredClone(s):null},get operation(){return f?structuredClone(f):null},get webViewUrl(){return b.webViewUrl},async refresh(){return R(await b.get()),structuredClone(P)},preview(t){if(O&&O!==t.requestId&&(!f||f.status==="pending"))return Promise.reject(new a("COMMAND_PENDING","Retry the original purchase before starting another"));if(O===t.requestId&&g)return g;let u=P.document.buttons[t.actionId],c=u?.type==="checkout"?oe(u.product,t.selection,P.capabilities):null;if(!c)return Promise.reject(new a("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));O=t.requestId;let p=(async()=>{if(await I(t.requestId,{type:"paywall_quote",actionId:t.actionId,productVersionId:c,...t.offerId?{offerId:t.offerId}:{},...t.nativeOffer?{nativeOffer:t.nativeOffer}:{}}),!s)throw new a("INVALID_RESPONSE","The accepted quote is missing");return structuredClone(s)})();return g=p,p.then(()=>{g===p&&(g=null)},o=>{g===p&&(g=null),o instanceof a&&o.status!==void 0&&o.status<500&&![401,425].includes(o.status)&&(O=null)}),p},confirm:()=>E("confirm"),cancel:()=>E("cancel"),async read(){if(!s)throw new a("INVALID_REQUEST","A quoted purchase is required");if(R(await b.get(void 0,{receiptId:A,operationId:s.operationId})),!f)throw new a("INVALID_RESPONSE","The current purchase result is missing");return structuredClone(f)},destroy(){x=!0,D.clear(),_.clear()}}}async function Ee(b,n){let{mountScreenPreview:A}=await import("./popup.js"),{showPaywall:z}=await import("./paywall-MYBEOVTQ.js"),m=b.ownerDocument,P=m.activeElement,s=m.createElement("section"),f=m.createElement("div"),x=m.createElement("div"),O=m.createElement("p"),g=m.createElement("p"),D=m.createElement("button"),_=m.createElement("button"),R=m.createElement("button"),I=m.createElement("dialog");s.dataset.indianaFunnel="",s.setAttribute("aria-busy","false"),s.style.cssText="box-sizing:border-box;width:100%;min-width:0;font:14px/1.5 system-ui,sans-serif;color:#172033;background:#fff",x.style.cssText="display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:12px 20px",O.setAttribute("role","status"),g.setAttribute("role","alert"),g.hidden=!0,D.type=_.type=R.type="button",x.append(D,O,g,R,_),s.append(f,x),b.append(s);let E=null,t=null,u=null,c="",p="",o=!1,h=0,Y=!1,ne="",k=null,X=Promise.resolve(),L=null,$=null,Q={},Z=new Map,te=new Set,W=new Set,B=new Set,H=null,S={},F=(e,r=null)=>{o||($=r,g.textContent=e instanceof Error?e.message:"Request failed",g.hidden=!1,R.hidden=n.client.pendingCommand===null,V(n.onError,e))};function T(){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 U(e,r=!1){if(!(h&&!r||o)){h++,s.setAttribute("aria-busy","true"),g.hidden=!0,$=null;try{if(!r&&H){let i=n.client.view;await H;let l=n.client.view;if(!i||!l||l.id!==i.id||l.nodeId!==i.nodeId||l.visit!==i.visit||l.stopped||!["running","waiting"].includes(l.status))throw new a("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}if(o)return;let w=await e();o||await M(n.client.view??w.run)}catch(w){F(w,n.client.pendingCommand?.requestId??null)}finally{h=Math.max(0,h-1),s.setAttribute("aria-busy",String(h>0)),o||(R.hidden=n.client.pendingCommand===null,D.disabled=h>0||!!n.client.pendingCommand||!n.client.view?.canBack)}}}function ie(e){if(te.has(e)||W.has(e)||o)return;W.add(e);let r=async()=>{if(o||c!==e){W.delete(e);return}if(h||n.client.pendingCommand){setTimeout(()=>{r()},250);return}let w=(async()=>{await n.client.submit({operation:"shown",...T()}),te.add(e)})();H=w;let i=()=>{H===w&&(H=null),W.delete(e)};w.then(i,l=>{i(),h||F(l)})};r()}function K(){k&&clearTimeout(k),!(o||!u||!["running","waiting"].includes(u.status))&&(k=setTimeout(()=>{k=null,re().finally(K)},u.pendingRequest?1500:5e3))}async function re(){if(!(o||Y||h)){Y=!0;try{let e=await n.client.get();o||await M(n.client.view??e.run)}catch(e){F(e)}finally{Y=!1}}}async function ae(e){let r=n.client.view,w=r?.screen,i=w?.customerData.nodes[e.nodeId];if(!r||!w||!i)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(e.action)){let C=E?.document,q=C?se(C,e.nodeId):null,ee=q?.type==="customer_data"?q.data.outputs?.[e.action]:void 0;ee&&w.outputs.includes(ee)?await U(()=>n.client.submit({operation:"submit",...T(),input:{type:"screen",output:ee,answers:S,selection:e.value?{[e.nodeId]:e.value}:{}}})):await n.onCustomerDataIntent?.(e,r);return}let d=e.action.startsWith("sources_")?i.resources.find(C=>C.key===e.value):null;if(e.action.startsWith("sources_")&&!d)throw new a("INVALID_REQUEST","Choose a current resource");let N=`${r.visit}:${e.nodeId}:${d?.key??""}`,y=Z.get(N)??[null],v=Q[e.nodeId]??{page:1,after:null,filter:"all",...d?{resourceKey:d.key}:{}};if(e.action==="filter"){let C=e.value;if(!C||!(i.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(C))throw new a("INVALID_REQUEST","Unknown data filter");v={page:1,after:null,filter:C},y.splice(0,y.length,null)}else if(e.action==="next"||e.action==="sources_next"){let C=d?.sources.at(-1),q=d?C?{kind:"ledger",cursor:{at:C.detail[0],id:C.id,type:"source"}}:null:w.dataCursors[e.nodeId];if(!q||!d&&!i.hasNext)return;y[v.page]=q,v={...v,page:v.page+1,after:q}}else if(e.action==="previous"||e.action==="sources_previous"){if(v.page<=1)return;v={...v,page:v.page-1,after:y[v.page-2]??null}}Z.set(N,y),Q={...Q,[e.nodeId]:v},await U(()=>n.client.get({nodeId:r.nodeId,visit:r.visit,revision:r.revision,components:Q}))}function ue(e){let r=e.screen?.presentation;if(!r||r.type==="inline"){I.open&&I.close(),s.parentElement!==b&&b.append(s);return}s.parentElement!==I&&(I.append(s),b.append(I));let w={sm:420,md:640,lg:900};I.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in r?w[r.size]+"px":"100vw"}`,I.setAttribute("aria-label",E?.document?.name??(e.screen?.content.type==="document"?e.screen.content.document.name:"Funnel")),I.open||I.showModal()}async function ce(e){if(o)return;u=e,$&&n.client.pendingCommand?.requestId!==$&&(g.hidden=!0,$=null);let r=e.locale.startsWith("zh");if(D.textContent=r?"\u8FD4\u56DE":"Back",_.textContent=r?"\u5173\u95ED":"Close",R.textContent=r?"\u91CD\u8BD5":"Retry",D.disabled=h>0||!!n.client.pendingCommand||!e.canBack,R.hidden=n.client.pendingCommand===null,O.textContent=e.pendingRequest?r?"\u6B63\u5728\u5904\u7406":"Processing":e.instruction?.type==="wait"?r?"\u7B49\u5F85\u4E2D":"Waiting":"",ne!==`${e.revision}:${e.visit}:${e.status}:${e.stopped}`&&(ne=`${e.revision}:${e.visit}:${e.status}:${e.stopped}`,V(n.onState,structuredClone(e))),e.stopped){E?.destroy(),E=null,t?.destroy(),t=null,f.replaceChildren(),c="",p="",I.open&&I.close(),s.hidden=!0,K();return}s.hidden=!1;let w=e.screen||e.paywall?`${e.id}:${e.nodeId}:${e.visit}`:"";if(w!==c&&(E?.destroy(),E=null,t?.destroy(),t=null,f.replaceChildren(),c=w,p="",S={...e.answers},Q={},Z.clear()),ue(e),e.screen){let l=e.screen.content;E||(E=A(f,{mode:"live",...l.type==="render"?{screenUrl:pe(l.url)}:{rendererUrl:n.client.webViewUrl,title:l.document.name},onAction(y,J={},v={}){S={...S,...v},U(()=>n.client.submit({operation:"submit",...T(),input:{type:"screen",output:y,answers:S,selection:J}}))},onAnswers:y=>{S={...S,...y}},onCustomerDataIntent:y=>{ae(y).catch(F)},onEscape:()=>{j()},onError:y=>F(new Error(y)),onRendered:()=>ie(w)}));let d={capabilities:e.screen.capabilities,customerData:e.screen.customerData,parameters:e.parameters,serverInput:{bindings:e.screen.inputs,answers:S}},N=JSON.stringify([l,e.locale,d.capabilities,d.customerData,d.parameters,e.screen.inputs]);N!==p&&(E.update(l.type==="document"?l.document:null,e.locale,d),p=N),await E.ready}else if(e.paywall&&!t){let l=await z(f,{start:async()=>le(n.client),onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,resolveOfferId:n.resolveOfferId,onEvent:n.onEvent,onOpenUrl:d=>n.onOpenUrl?n.onOpenUrl({receiptId:e.paywall.receiptId,url:d,openIn:"same_window"}):m.defaultView?.location.assign(d),onAction:async d=>{let N=await n.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision,input:{type:"screen",output:d,answers:{}}});await M(n.client.view??N.run)},onError:F,onDismiss:()=>{!o&&n.client.view?.visit===e.visit&&j()}});o?l.host?.destroy():t=l.host,ie(w)}let i=e.instruction;if(i&&["open_url","event"].includes(i.type)&&!B.has(i.receiptId)){let l=m.createElement("button");l.type="button",l.textContent=i.type==="open_url"?`${r?"\u524D\u5F80":"Continue to"} ${new URL(i.url).host}`:r?"\u7EE7\u7EED":"Continue",l.onclick=()=>{let d=T(),N=i.type==="open_url"&&!n.onOpenUrl&&i.openIn==="new_window"?de(i.url):null;U(async()=>{let y="success";if(i.type==="open_url")if(n.onOpenUrl)try{y=await n.onOpenUrl({receiptId:i.receiptId,url:i.url,openIn:i.openIn})===!1?"failed":"opened"}catch(v){V(n.onError,v),y="failed"}else y=i.openIn==="new_window"&&!N?"failed":"opened";if(i.type==="event"){if(!n.onEvent)throw new a("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(i.event)}if(o||n.client.view?.nodeId!==d.nodeId||n.client.view.visit!==d.visit)throw new a("PRECONDITION_FAILED","The client action visit changed");let J=await n.client.submit({operation:"submit",...d,input:{type:"client_action",receiptId:i.receiptId,outcome:y}});return B.add(i.receiptId),i.type==="open_url"&&!n.onOpenUrl&&i.openIn==="same_window"&&m.defaultView?.location.assign(i.url),J})},f.replaceChildren(l)}!e.pendingRequest&&e.status==="completed"&&!B.has(`complete:${e.id}`)&&(B.add(`complete:${e.id}`),V(n.onComplete,structuredClone(e))),K()}function de(e){let r=m.defaultView?.open(e,"_blank")??null;return r&&(r.opener=null),r}function pe(e){return n.client.screenUrl?n.client.screenUrl(e):new URL(e,m.defaultView?.location.href).href}function M(e){return X=X.catch(()=>{}).then(()=>ce(e)),X}let fe=n.client.subscribe(e=>{M(e).catch(F)});function j(){return L||(o?Promise.resolve():n.client.view&&!["running","waiting"].includes(n.client.view.status)?(G(),Promise.resolve()):(L=U(()=>n.client.submit({operation:"close",...T()}),!0).then(()=>{n.client.view?.status==="closed"&&G()}).finally(()=>{L=null}),L))}function G(){o||(o=!0,k&&clearTimeout(k),fe(),E?.destroy(),t?.destroy(),I.close(),I.remove(),s.remove(),P instanceof HTMLElement&&P.isConnected&&P.focus(),V(n.onDismiss,u?structuredClone(u):null))}D.onclick=()=>{U(()=>n.client.submit({operation:"back",...T()}))},_.onclick=()=>{j()},R.onclick=()=>{U(()=>n.client.retry())},I.addEventListener("cancel",e=>{e.preventDefault(),j()});try{let e=await n.client.get();await M(n.client.view??e.run)}catch(e){throw G(),e}return{destroy:G,refresh:re}}export{Ee as showFunnelRun};