@tinkerlandai/longplay-sdk 0.10.22 → 0.10.23-rc.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.
@@ -1 +1 @@
1
- import{a as p,b as ne,c as j,d as re,n as B,q as ie}from"./chunk-O5XTOWFZ.js";import{b as te}from"./chunk-KLP5TN5O.js";import{a as o}from"./chunk-QVGTHPWT.js";import{Da as u,Fa as G,Qa as ee,_ as $,a as K,b as Q,c as W,d as M,e as H,f as X,ia as Z,q as L}from"./chunk-KSCITFNQ.js";import{a as J}from"./chunk-DSPLGTQI.js";import{a as Y}from"./chunk-HDVLCRC6.js";var U=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new o("INVALID_STATE","Installation sequence exhausted");return t+1},ve=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function F(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new o("INVALID_STATE","Installation journal is invalid");return e({...n})})}function se(t,e,n){let r=null,s=0,a=0,l=0,y=Promise.resolve(),w=!1;if(t&&(!n||Y.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new o("SCOPE_MISMATCH","Push installation belongs to another scope");let f=()=>{if(w)throw new o("CLOSED","SDK client was destroyed");if(!t)throw new o("NOT_CONFIGURED","Configure this client's native Push host first");return t},O=i=>{if(i!==s)throw new o("IDENTITY_CHANGED","Identity changed during Push operation")};async function D(i){let c=f();if(!c.sha256&&!globalThis.crypto?.subtle)throw new o("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let d=c.sha256?await c.sha256(Uint8Array.from(i,E=>E.charCodeAt(0))):await ve(i);if(!/^[a-f0-9]{64}$/.test(d))throw new o("INVALID_STATE","Push credential digest is invalid");return d}function m(i){let c=H.parse(i);if(c.installationId.toLowerCase()!==f().installationId.toLowerCase())throw new o("INVALID_RESPONSE","Push response belongs to another installation");return c}async function S(i,c){let d=f(),E={installationId:d.installationId,publicKey:d.publicKey,issuedAt:new Date().toISOString(),...c},C=await d.sign(X(i,d.scope,E));return{...E,signature:C}}let I=(i,c,d)=>e.requestWithCredential?e.requestWithCredential(i,c,d):e.request(i,c);async function q(){let i=f(),c=s,d=r?await(e.session?.access()??r):null,E=F(i,g=>g),C;if(E.detachSeq!==null){let g=E.detachSeq,x=K.parse(await S("detach",{sequence:g,platform:i.platform}));try{let N=await e.request("push/installations/detach",{...i.scope,...x},"POST",{installationDetach:!0});if(!N||typeof N!="object"||!("installation"in N))throw new o("INVALID_RESPONSE","Push detach acknowledgement is invalid");let _=m(N.installation);if(_.bound||_.identitySeq!==g)throw new o("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(N){if(N instanceof o&&N.status===404)C=N;else if(!(N instanceof o)||N.status!==412)throw N}C||F(i,N=>({...N,detachSeq:N.detachSeq===g?null:N.detachSeq}))}if(O(c),!d){if(C)throw C;return null}let A=u.bindPushInstallation,k=A.request.parse(await S("bind",{sequence:l,platform:i.platform,credentialDigest:await D(d)}));O(c);let T=A.response.parse(await I(A.path,k,d));O(c);let R=m(T.installation);if(!R.bound||R.identitySeq!==l)throw new o("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return C&&E.detachSeq!==null&&l>E.detachSeq&&F(i,g=>({...g,detachSeq:g.detachSeq===E.detachSeq?null:g.detachSeq})),R}async function h(){f();let i=s,c=r?await(e.session?.access()??r):null;if(!c)throw new o("NOT_IDENTIFIED","Identify before reading this installation");let d=u.readPushInstallation,E=d.request.parse(await S("read",{credentialDigest:await D(c)}));O(i);let C=d.response.parse(await I(d.path,E,c));return O(i),m(C.installation)}function P(i=q){let c=y.catch(()=>{}).then(i);return y=c,c.catch(d=>{try{t?.onError?.(d instanceof Error?d:new Error("Push synchronization failed"))}catch{}}),c}async function v(i,c,d){let E=f(),C=c.identity,A=c.observation,k=r?await(e.session?.access()??r):null;if(O(C),A!==a)throw new o("INVALID_STATE","Push observation changed during recovery");if(!k)throw new o("NOT_IDENTIFIED","Identify before recovering a Push address");if(!i.connectionId||!i.kind||!i.token||!["granted","provisional"].includes(i.permission))throw new o("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await P(async()=>{if(O(C),await q(),O(C),A!==a)throw new o("INVALID_STATE","Push observation changed during recovery");let T=F(E,_=>d?_:{..._,addressSeq:U(_.addressSeq)}),g=await S(d?"recovery_confirm":"recovery_request",{...i,sequence:T.addressSeq,credentialDigest:await D(k),...d?{challenge:d}:{}}),x=d?W.parse(g):Q.parse(g);if(O(C),A!==a)throw new o("INVALID_STATE","Push observation changed during recovery");let N=await I(`push/installations/recovery/${d?"confirm":"request"}`,x,k);if(O(C),A!==a||F(E,_=>_).addressSeq!==T.addressSeq)throw new o("INVALID_STATE","Push observation changed during recovery");if(d){let _=u.updatePushAddress.response.parse(N),V=m(_.installation);if(!V.bound||V.identitySeq!==l||V.addressSeq!==T.addressSeq||V.connectionId!==i.connectionId||V.addressStatus!=="active")throw new o("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return V}if(!N||typeof N!="object"||!("recovery"in N))throw new o("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return M.parse(N.recovery)})}return{recoveryObserver(){f();let i={identity:s,observation:++a};return{async request(c){return M.parse(await v(c,i))},async confirm(c,d){return H.parse(await v(d,i,c))}}},identify(i){if(!t)return;l=F(t,d=>({...d,identitySeq:U(d.identitySeq)})).identitySeq,r=i,s++,a++},reset(){if(t)try{F(t,i=>{let c=U(i.identitySeq);return{...i,identitySeq:c,detachSeq:c}})}finally{r=null,s++,a++}},start(){t&&!w&&P()},destroy(){w=!0,r=null,s++,a++},async sync(){return await P()},read:h,async recover(){let i=f(),c=s,d=l;return a++,await P(async()=>{O(c);let E=await h();return O(c),l=F(i,A=>{if(A.identitySeq!==d)throw new o("IDENTITY_CHANGED","A newer installation intent exists");return{...A,identitySeq:U(Math.max(A.identitySeq,E.identitySeq)),addressSeq:Math.max(A.addressSeq,E.addressSeq)}}).identitySeq,await q()})},tokenObserver(){f();let i=++a,c=s;return async d=>{if(i!==a||c!==s)return null;let E=f(),C=r?await(e.session?.access()??r):null;if(!C)throw new o("NOT_IDENTIFIED","Identify before registering a Push token");if(await P(),O(c),i!==a)return null;let A=F(E,g=>({...g,addressSeq:U(g.addressSeq)})),k=u.updatePushAddress,T=k.request.parse(await S("address",{...d,sequence:A.addressSeq,credentialDigest:await D(C)}));if(O(c),i!==a)return null;let R=await I(k.path,T,C);return O(c),i!==a||F(E,g=>g).addressSeq!==A.addressSeq?null:m(k.response.parse(R).installation)}}}}function oe(t,e){let n={async preference(r){let s=u.readMessagingPreference;return(await p(t,s,{channel:r})).preference},async setPreference(r){let s=u.setMessagingPreference;return(await p(t,s,r)).preference}};return{messaging:n,push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return n.setPreference({...r,channel:"push"})}}}}function ae(t,e,n={}){let r=!1;function s(){if(r)throw new o("CLOSED","SDK client was destroyed")}let a=new Set,l=w=>{for(let f of a)try{f(w)}catch{}},y=t.session.subscribeIdentity(()=>{l(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:s,isIdentified:()=>!r&&!!t.session.peek(),methods:{subscribeIdentity(w){return s(),a.add(w),()=>{a.delete(w)}},identify(w){s();let f=typeof w=="string"?w:w.accessToken;if(!L.test(f))throw new o("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(f),t.identify(w)},reset(){if(!r)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!r){r=!0,y(),a.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}function b(t){if(t!==null&&typeof t=="object"&&"customerId"in t)throw new o("INVALID_REQUEST","Customer requests use the verified session identity")}var Ae={...u.readHoldings,request:u.readHoldings.request.omit({customerId:!0})};function ce(t){return{async checkEntitlement(e){b(e);let n=u.checkEntitlement,r=n.request.parse(e),s=await p(t,n,r);return ne(r.requirement,s.check,void 0,s.scope),s},async readHoldings(e={}){return p(t,Ae,e)}}}function ue(t){return{async readLedger(e){let n=u.readLedger;return p(t,n,{query:e})},async readCreditStatement(e){b(e);let n=u.readCreditStatement;return p(t,n,e)},async quoteBalance(e){b(e);let n=u.quoteBalance;return p(t,n,{command:e})}}}function de(t){return{async setupPayment(e){b(e);let n=u.setupPayment;return p(t,n,e)},async readPaymentSetup(e){b(e);let n=u.readPaymentSetup;return p(t,n,e)},async readBillingInvoice(e){b(e);let n=u.readBillingInvoice;return p(t,n,e)},async readBillingControls(e={}){b(e);let n=u.readBillingControls;return p(t,n,e)},async prepareBillingAuthorization(e){b(e);let n=u.prepareBillingAuthorization;return p(t,n,e)},async confirmBillingAuthorization(e){b(e);let n=u.confirmBillingAuthorization;return p(t,n,e)},async setBillingCoupons(e){b(e);let n=u.setBillingCoupons;return p(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){b(e);let n=u.revokeBillingAuthorization;return p(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){b(e);let n=u.listBillingInvoices;return p(t,n,e)},async confirmBillingAdjustment(e){b(e);let n=u.confirmBillingAdjustment;return p(t,n,e)}}}function pe(t){return{async previewUpdate(e){b(e);let n=u.previewUpdate;return p(t,n,e)},async update(e){b(e);let n=u.update;return p(t,n,e)},async readSubscriptionUpdate(e){b(e);let n=u.readSubscriptionUpdate;return p(t,n,e)},async restoreNativePurchase(e){b(e);let n=u.restoreNativePurchase;return p(t,n,e)},async previewAttach(e){b(e);let n=u.previewAttach;return p(t,n,e)},async attach(e){b(e);let n=u.attach;return p(t,n,e)},async readSubscriptionOperation(e){b(e);let n=u.readSubscriptionOperation;return p(t,n,e)}}}function le(t){return{async redeemReward(e){return b(e),(await p(t,u.redeemReward,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return b(e),(await p(t,u.claimRewardProduct,e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return b(e),(await p(t,u.createReferralCode,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){let r=await p(t,u.redeemCoupon,{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await p(t,u.grantOffer,{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await p(t,u.listOffers,{},{response:"Invalid offers response"})).offers}}}function fe(t){return{...ce(t),...ue(t),...de(t),...pe(t),...le(t)}}function me(t){return{async resolveContent(e){b(e);let n=u.resolveContent;return p(t,n,e)},async resolvePaywall(e){b(e);let n=u.resolvePaywall,r=n.request.parse(e),s=await p(t,n,r);return j(r,s.paywall.check,s.scope),s},async resolveOffering(e){b(e);let n=u.resolveOffering,r=n.request.parse(e),s=await p(t,n,r);return j(r,s.check,s.scope),s}}}var z=t=>new TextEncoder().encode(JSON.stringify(t)).length,ye=16384,be=5e3,Ee=6e4,Oe=5;function Se(t){return t instanceof o&&t.status!==void 0&&t.status>=400&&t.status<500&&!t.retryable}function Ie(t,e){let n=0,r,s=h=>{r={config:structuredClone(h),until:Date.now()+3e4}},a=[],l=null,y,w=0;function f(){if(!e())throw new o("NOT_IDENTIFIED","Call identify before using Features or events")}function O(){y||!a.length||!e()||(y=setTimeout(()=>{y=void 0,S().catch(()=>{}).finally(O)},Math.min(be*2**w,Ee)),typeof y=="object"&&"unref"in y&&y.unref())}function D(h){if(f(),r&&Date.now()<r.until&&!$(r.config,h.kind))return;q();let P=u.trackEvents.request.parse({events:[{...h,eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString()}]}).events[0];if(z({events:[P]})>ye)throw new o("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new o("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(P)),O()}function m(h,P={},v={}){D({kind:"custom",name:h,properties:P,...v})}async function S(h=!1){if(f(),l)return l;let P=n,v=(async()=>{let i={inserted:0,duplicates:0,rejected:0,skipped:0,rejections:[]},c=a.length;for(;c&&P===n;){let d=[],E=z({events:[]});for(let k of a.slice(0,Math.min(c,100))){let T=z(k)+(d.length?1:0);if(d.length&&E+T>ye)break;d.push(k),E+=T}let C=u.trackEvents,A;try{if(A=await p(t,C,{events:d},void 0,{keepalive:h}),P!==n)throw new o("IDENTITY_CHANGED","Event identity changed during delivery");if(A.inserted+A.duplicates+A.rejected+A.skipped!==d.length||A.rejections.length!==A.rejected)throw new o("INVALID_RESPONSE","Incomplete event acknowledgement")}catch(k){throw P===n&&(w++,(Se(k)||w>=Oe)&&(a.splice(0,d.length),w=0)),k}w=0,s(A.analyticsConfig),a.splice(0,d.length),c-=d.length,i.inserted+=A.inserted,i.duplicates+=A.duplicates,i.rejected+=A.rejected,i.skipped+=A.skipped,i.rejections.push(...A.rejections)}return i})();l=v;try{return await v}finally{l===v&&(l=null)}}let I;function q(){if(I||typeof document>"u")return;let h=()=>{document.visibilityState==="hidden"&&e()&&a.length&&S(!0).catch(()=>{})};document.addEventListener("visibilitychange",h),I=()=>document.removeEventListener("visibilitychange",h)}return{rememberConfiguration:s,track:m,observe:D,flush:S,reset(){n++,r=void 0,clearTimeout(y),y=void 0,a=[],w=0,l=null},detachVisibility(){I?.(),I=void 0}}}function he(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}var Pe=new Set([...Z,"merchandiseId","merchandise"]);function Ce(t){let e=he(t);return{...Object.fromEntries(Object.entries(t).filter(([r])=>!Pe.has(r))),...e?{merchandise:e}:{}}}function we(t,e,n,r,s){if(s&&r&&(s.scope.projectId!==r.projectId||s.scope.environment!==r.environment))throw new o("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,l=new Set;function y(){if(!e())throw new o("NOT_IDENTIFIED","Call identify before using Features or events")}async function w(f={}){s||y();let O=a,D=!1,m=async()=>{if(D||O!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");let T=u.getFeatures,R=s?{scope:{projectId:s.scope.projectId,environment:s.scope.environment},payload:await s.features()}:await p(t,T,{});if(O!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");if(r&&(R.scope.projectId!==r.projectId||R.scope.environment!==r.environment))throw new o("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(R.payload.analyticsConfig),R},S=await m(),I=!0,q,h=T=>{try{f.onError?.(T)}catch{}},P=(T,R)=>{try{let g=he(R);n.observe({...T,...g?{merchandise:g}:{}})}catch(g){h(g)}},v=re({assertUsable:s?.assertFeatures,scope:S.scope,attributes:f.attributes,onError:f.onError,load:async()=>I?(I=!1,S.payload):(await m()).payload,evaluateRemote:async T=>{if(O!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");let R=u.evaluateFeatures,g=await p(t,R,{...T,attributes:Ce(T.attributes)});if(g.scope.projectId!==S.scope.projectId||g.scope.environment!==S.scope.environment)throw new o("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:g.generation,evaluatedAt:g.evaluatedAt,expiresAt:g.expiresAt,features:g.features,...g.merchandiseContext?{merchandiseContext:g.merchandiseContext}:{}}},onExperimentViewed:(T,R,g,x)=>P({kind:"experiment_exposure",generation:x,experimentId:T.key,variationId:R.key},g),onFeatureUsage:(T,R,g,x)=>P({kind:"feature_usage",generation:x,feature:T,value:R.value??null,source:R.source,ruleId:R.ruleId,...R.experimentResult?{variationId:R.experimentResult.key}:{}},g)}),i=v.refresh;function c(){clearTimeout(q),!s&&(D||O!==a||!v.expiresAt||(q=setTimeout(()=>{d().catch(h)},Math.min(2147483647,Math.max(1e3,Date.parse(v.expiresAt)-Date.now()))),typeof q=="object"&&"unref"in q&&q.unref()))}async function d(){try{return await i()}finally{c()}}let E=()=>{D||d().catch(h)},C=v.subscribe(c),A=s?.subscribe(()=>{!D&&s.fresh&&d().catch(h)});function k(){D||(D=!0,clearTimeout(q),typeof window<"u"&&window.removeEventListener("focus",E),C(),A?.(),v.reset(),l.delete(k))}l.add(k);try{await v.init(),(f.attributes?.merchandise||f.attributes?.merchandiseId)&&await v.refreshRemote()}catch(T){throw k(),T}return c(),!s&&typeof window<"u"&&window.addEventListener("focus",E),Object.assign(v,{refresh:d,destroy:k})}return{features:w,reset(f){a++,f();for(let O of l)O()}}}import{z as Te}from"zod";function ge(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=Te.object({funnelId:G.shape.id,funnelVersionId:G.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new o("INVALID_REQUEST","A valid Funnel source is required");let s=Object.freeze(r.data);function a(l){if("customerId"in l)throw new o("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in l&&l.funnelId!==void 0&&l.funnelId!==s.funnelId||"funnelVersionId"in l&&l.funnelVersionId!==void 0&&l.funnelVersionId!==s.funnelVersionId)throw new o("SCOPE_MISMATCH","The original Funnel source cannot change");return{...l,...s}}return{async claimCoupon(l,y=crypto.randomUUID()){let w=u.grantOffer,f=await p(t,w,a({couponId:l,requestId:y}));return{offer:f.offer,reason:f.reason}},async resolveOffering(l){let y=u.resolveOffering,w=y.request.parse(a(l)),f=await p(t,y,w);return j(w,f.check,f.scope),f},async resolvePaywall(l){let y=u.resolvePaywall,w=y.request.parse(a(l)),f=await p(t,y,w);return j(w,f.paywall.check,f.scope),f},async previewAttach(l){let y=u.previewAttach;return p(t,y,a(l))}}}function Ht(t){return Re(t)}function Re(t){let e=te(t),n=e.request,r;try{r=se(t.push,e,t.scope??t.configuration?.scope)}catch(y){throw e.dispose(),y}let s=ae(e,()=>{l.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=Ie(n,s.isIdentified),l=we(n,s.isIdentified,a,t.scope,t.configuration);return{session:e.session,...oe(n,r),...fe(n),...me(n),forFunnel(y){return s.assertActive(),ge(n,y)},async features(y={}){return s.assertActive(),l.features(y)},track(y,w,f={}){return a.track(y,w,f)},flush(){return a.flush()},...s.methods}}function Qt(t){if(!L.test(t.customerToken))throw new o("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new o("INVALID_REQUEST","An explicit App and environment scope is required");let e=ie({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),s=B({...t,runToken:r.runToken,initialResponse:r});s.identify(t.customerToken);let a=await s.get();return{...r,...a,controller:s}}}}function tn(t){if(!t.scope)throw new o("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new o("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,r=0,s=new Set,a=new Map,l=new Map;async function y(m){let S,I=new Promise((q,h)=>{S=setTimeout(()=>h(new o("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(m),I])}finally{clearTimeout(S)}}function w(m){throw m instanceof o&&(m.status===401||m.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,e=null,a.clear(),l.clear()),m}function f(m,S){if(S!==r)throw new o("IDENTITY_CHANGED","Process was detached during a request");let I=ee.parse(m);if(I.scope.projectId!==t.scope.projectId||I.scope.environment!==t.scope.environment)throw new o("SCOPE_MISMATCH","Process response belongs to another App/environment");if(e&&(e.run.id!==I.run.id||e.run.source.versionId!==I.run.source.versionId||e.run.source.id!==I.run.source.id||e.run.runExpiresAt!==I.run.runExpiresAt||e.run.identity.startedAs!==I.run.identity.startedAs||e.run.identity.participantId!==I.run.identity.participantId||e.run.identity.binding&&I.run.identity.binding&&e.run.identity.binding.id!==I.run.identity.binding.id))throw new o("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!e||I.run.revision>=e.run.revision){if(e?.run.identity.binding&&!I.run.identity.binding)throw new o("INVALID_RESPONSE","The process lost its Customer binding");e=I;for(let E of s)J(E,I.run);I.run.instruction?.type==="authentication_required"&&J(t.onAuthenticationRequired,I.run)}I.settlement?.accepted!==void 0&&l.set(I.settlement.requestId,I.settlement.accepted);let{identity:q,instruction:h,...P}=I.run,{contract:v,settlement:i,...c}=I,d=i&&(({accepted:E,...C})=>C)(i);return{...c,run:{...P,authenticated:q.binding!==null,instruction:h?.type==="authentication_required"?null:h},...d?{settlement:d}:{}}}let O=m=>(a.has(m)||a.set(m,e?.run.identity.binding?.id??null),a.get(m));async function D(m){let S=r,I=e?.run.identity.binding?.id??null,q=P=>{if(I!==(e?.run.identity.binding?.id??null))throw P;return w(P)};if(m.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new o("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return y(()=>t.adapter.pageExperiments(m.release,m.usedReceiptIds)).catch(q)}let h;if(m.operation==="get"){let{operation:P,customerToken:v,...i}=m;h=await y(()=>t.adapter.get({...i,...i.settlementRequestId?{settlementBindingId:O(i.settlementRequestId)}:{}})).catch(q)}else if(m.operation==="review")h=await y(()=>t.adapter.review(m.receiptId)).catch(q);else{if(m.operation==="start")throw new o("INVALID_REQUEST","Use process.open for entry");{let{customerToken:P,...v}=m;h=await y(()=>t.adapter.command(v,O(v.requestId))).catch(q)}}return f(h,S)}return{get view(){return e?.run??null},get controller(){return n},async open(m){let S=r,I=await y(()=>t.adapter.open(m)).catch(w),q=f(I,S);if(!n){n=B({...t,runToken:I.runToken,initialResponse:q,process:{request:D,binding:O,restore(v){for(let[i,c]of Object.entries(v))a.set(i,c)}}});let h=n,P=h.submit;h.submit=async v=>{try{return await P(v)}catch(i){if(!(i instanceof o)||i.reason!=="IDENTITY_CONTEXT_CHANGED"||v.operation!=="submit"||v.input.type!=="screen"||a.get(v.requestId)!==null)throw i;await h.settle?.(v.requestId),await h.get();let c=h.view;if(l.get(v.requestId)!==!1||!c||c.id!==e?.run.id||c.nodeId!==v.nodeId||c.visit!==v.visit||!e?.run.identity.binding)throw i;return P({...v,requestId:crypto.randomUUID(),revision:c.revision})}}}await n.get();for(let h of n.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(e?.run.identity.binding?.id??null)&&await n.settle?.(h.requestId);return{run:e.run,controller:n}},async syncIdentity(){let m=r;f(await y(()=>t.adapter.syncIdentity()).catch(w),m),await n?.get();for(let S of n?.pendingCommands??[])a.has(S.requestId)&&a.get(S.requestId)!==(e?.run.identity.binding?.id??null)&&await n?.settle?.(S.requestId);return e.run},async detach(){r++,n?.reset(),n=void 0,e=null,a.clear(),l.clear(),await y(()=>t.adapter.detach())},forProcess(m){if(!e?.run.identity.binding)throw new o("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:m}},subscribe(m){return s.add(m),()=>{s.delete(m)}},destroy(){r++,n?.reset(),n=void 0,e=null,a.clear(),l.clear(),s.clear()}}}export{Ht as a,Re as b,Qt as c,tn as d};
1
+ import{a as p,b as ne,c as j,d as re,n as B,q as ie}from"./chunk-A7CDFKPQ.js";import{b as te}from"./chunk-QTA627VF.js";import{a as o}from"./chunk-QVGTHPWT.js";import{Da as u,Fa as G,Qa as ee,_ as $,a as K,b as Q,c as W,d as M,e as H,f as X,ia as Z,q as L}from"./chunk-LPMYELUB.js";import{a as J}from"./chunk-DSPLGTQI.js";import{a as Y}from"./chunk-HDVLCRC6.js";var U=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new o("INVALID_STATE","Installation sequence exhausted");return t+1},ve=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function F(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new o("INVALID_STATE","Installation journal is invalid");return e({...n})})}function se(t,e,n){let r=null,s=0,a=0,l=0,y=Promise.resolve(),w=!1;if(t&&(!n||Y.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new o("SCOPE_MISMATCH","Push installation belongs to another scope");let f=()=>{if(w)throw new o("CLOSED","SDK client was destroyed");if(!t)throw new o("NOT_CONFIGURED","Configure this client's native Push host first");return t},O=i=>{if(i!==s)throw new o("IDENTITY_CHANGED","Identity changed during Push operation")};async function D(i){let c=f();if(!c.sha256&&!globalThis.crypto?.subtle)throw new o("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let d=c.sha256?await c.sha256(Uint8Array.from(i,E=>E.charCodeAt(0))):await ve(i);if(!/^[a-f0-9]{64}$/.test(d))throw new o("INVALID_STATE","Push credential digest is invalid");return d}function m(i){let c=H.parse(i);if(c.installationId.toLowerCase()!==f().installationId.toLowerCase())throw new o("INVALID_RESPONSE","Push response belongs to another installation");return c}async function S(i,c){let d=f(),E={installationId:d.installationId,publicKey:d.publicKey,issuedAt:new Date().toISOString(),...c},C=await d.sign(X(i,d.scope,E));return{...E,signature:C}}let I=(i,c,d)=>e.requestWithCredential?e.requestWithCredential(i,c,d):e.request(i,c);async function q(){let i=f(),c=s,d=r?await(e.session?.access()??r):null,E=F(i,g=>g),C;if(E.detachSeq!==null){let g=E.detachSeq,x=K.parse(await S("detach",{sequence:g,platform:i.platform}));try{let N=await e.request("push/installations/detach",{...i.scope,...x},"POST",{installationDetach:!0});if(!N||typeof N!="object"||!("installation"in N))throw new o("INVALID_RESPONSE","Push detach acknowledgement is invalid");let _=m(N.installation);if(_.bound||_.identitySeq!==g)throw new o("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(N){if(N instanceof o&&N.status===404)C=N;else if(!(N instanceof o)||N.status!==412)throw N}C||F(i,N=>({...N,detachSeq:N.detachSeq===g?null:N.detachSeq}))}if(O(c),!d){if(C)throw C;return null}let A=u.bindPushInstallation,k=A.request.parse(await S("bind",{sequence:l,platform:i.platform,credentialDigest:await D(d)}));O(c);let T=A.response.parse(await I(A.path,k,d));O(c);let R=m(T.installation);if(!R.bound||R.identitySeq!==l)throw new o("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return C&&E.detachSeq!==null&&l>E.detachSeq&&F(i,g=>({...g,detachSeq:g.detachSeq===E.detachSeq?null:g.detachSeq})),R}async function h(){f();let i=s,c=r?await(e.session?.access()??r):null;if(!c)throw new o("NOT_IDENTIFIED","Identify before reading this installation");let d=u.readPushInstallation,E=d.request.parse(await S("read",{credentialDigest:await D(c)}));O(i);let C=d.response.parse(await I(d.path,E,c));return O(i),m(C.installation)}function P(i=q){let c=y.catch(()=>{}).then(i);return y=c,c.catch(d=>{try{t?.onError?.(d instanceof Error?d:new Error("Push synchronization failed"))}catch{}}),c}async function v(i,c,d){let E=f(),C=c.identity,A=c.observation,k=r?await(e.session?.access()??r):null;if(O(C),A!==a)throw new o("INVALID_STATE","Push observation changed during recovery");if(!k)throw new o("NOT_IDENTIFIED","Identify before recovering a Push address");if(!i.connectionId||!i.kind||!i.token||!["granted","provisional"].includes(i.permission))throw new o("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await P(async()=>{if(O(C),await q(),O(C),A!==a)throw new o("INVALID_STATE","Push observation changed during recovery");let T=F(E,_=>d?_:{..._,addressSeq:U(_.addressSeq)}),g=await S(d?"recovery_confirm":"recovery_request",{...i,sequence:T.addressSeq,credentialDigest:await D(k),...d?{challenge:d}:{}}),x=d?W.parse(g):Q.parse(g);if(O(C),A!==a)throw new o("INVALID_STATE","Push observation changed during recovery");let N=await I(`push/installations/recovery/${d?"confirm":"request"}`,x,k);if(O(C),A!==a||F(E,_=>_).addressSeq!==T.addressSeq)throw new o("INVALID_STATE","Push observation changed during recovery");if(d){let _=u.updatePushAddress.response.parse(N),V=m(_.installation);if(!V.bound||V.identitySeq!==l||V.addressSeq!==T.addressSeq||V.connectionId!==i.connectionId||V.addressStatus!=="active")throw new o("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return V}if(!N||typeof N!="object"||!("recovery"in N))throw new o("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return M.parse(N.recovery)})}return{recoveryObserver(){f();let i={identity:s,observation:++a};return{async request(c){return M.parse(await v(c,i))},async confirm(c,d){return H.parse(await v(d,i,c))}}},identify(i){if(!t)return;l=F(t,d=>({...d,identitySeq:U(d.identitySeq)})).identitySeq,r=i,s++,a++},reset(){if(t)try{F(t,i=>{let c=U(i.identitySeq);return{...i,identitySeq:c,detachSeq:c}})}finally{r=null,s++,a++}},start(){t&&!w&&P()},destroy(){w=!0,r=null,s++,a++},async sync(){return await P()},read:h,async recover(){let i=f(),c=s,d=l;return a++,await P(async()=>{O(c);let E=await h();return O(c),l=F(i,A=>{if(A.identitySeq!==d)throw new o("IDENTITY_CHANGED","A newer installation intent exists");return{...A,identitySeq:U(Math.max(A.identitySeq,E.identitySeq)),addressSeq:Math.max(A.addressSeq,E.addressSeq)}}).identitySeq,await q()})},tokenObserver(){f();let i=++a,c=s;return async d=>{if(i!==a||c!==s)return null;let E=f(),C=r?await(e.session?.access()??r):null;if(!C)throw new o("NOT_IDENTIFIED","Identify before registering a Push token");if(await P(),O(c),i!==a)return null;let A=F(E,g=>({...g,addressSeq:U(g.addressSeq)})),k=u.updatePushAddress,T=k.request.parse(await S("address",{...d,sequence:A.addressSeq,credentialDigest:await D(C)}));if(O(c),i!==a)return null;let R=await I(k.path,T,C);return O(c),i!==a||F(E,g=>g).addressSeq!==A.addressSeq?null:m(k.response.parse(R).installation)}}}}function oe(t,e){let n={async preference(r){let s=u.readMessagingPreference;return(await p(t,s,{channel:r})).preference},async setPreference(r){let s=u.setMessagingPreference;return(await p(t,s,r)).preference}};return{messaging:n,push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return n.setPreference({...r,channel:"push"})}}}}function ae(t,e,n={}){let r=!1;function s(){if(r)throw new o("CLOSED","SDK client was destroyed")}let a=new Set,l=w=>{for(let f of a)try{f(w)}catch{}},y=t.session.subscribeIdentity(()=>{l(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:s,isIdentified:()=>!r&&!!t.session.peek(),methods:{subscribeIdentity(w){return s(),a.add(w),()=>{a.delete(w)}},identify(w){s();let f=typeof w=="string"?w:w.accessToken;if(!L.test(f))throw new o("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(f),t.identify(w)},reset(){if(!r)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!r){r=!0,y(),a.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}function b(t){if(t!==null&&typeof t=="object"&&"customerId"in t)throw new o("INVALID_REQUEST","Customer requests use the verified session identity")}var Ae={...u.readHoldings,request:u.readHoldings.request.omit({customerId:!0})};function ce(t){return{async checkEntitlement(e){b(e);let n=u.checkEntitlement,r=n.request.parse(e),s=await p(t,n,r);return ne(r.requirement,s.check,void 0,s.scope),s},async readHoldings(e={}){return p(t,Ae,e)}}}function ue(t){return{async readLedger(e){let n=u.readLedger;return p(t,n,{query:e})},async readCreditStatement(e){b(e);let n=u.readCreditStatement;return p(t,n,e)},async quoteBalance(e){b(e);let n=u.quoteBalance;return p(t,n,{command:e})}}}function de(t){return{async setupPayment(e){b(e);let n=u.setupPayment;return p(t,n,e)},async readPaymentSetup(e){b(e);let n=u.readPaymentSetup;return p(t,n,e)},async readBillingInvoice(e){b(e);let n=u.readBillingInvoice;return p(t,n,e)},async readBillingControls(e={}){b(e);let n=u.readBillingControls;return p(t,n,e)},async prepareBillingAuthorization(e){b(e);let n=u.prepareBillingAuthorization;return p(t,n,e)},async confirmBillingAuthorization(e){b(e);let n=u.confirmBillingAuthorization;return p(t,n,e)},async setBillingCoupons(e){b(e);let n=u.setBillingCoupons;return p(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){b(e);let n=u.revokeBillingAuthorization;return p(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){b(e);let n=u.listBillingInvoices;return p(t,n,e)},async confirmBillingAdjustment(e){b(e);let n=u.confirmBillingAdjustment;return p(t,n,e)}}}function pe(t){return{async previewUpdate(e){b(e);let n=u.previewUpdate;return p(t,n,e)},async update(e){b(e);let n=u.update;return p(t,n,e)},async readSubscriptionUpdate(e){b(e);let n=u.readSubscriptionUpdate;return p(t,n,e)},async restoreNativePurchase(e){b(e);let n=u.restoreNativePurchase;return p(t,n,e)},async previewAttach(e){b(e);let n=u.previewAttach;return p(t,n,e)},async attach(e){b(e);let n=u.attach;return p(t,n,e)},async readSubscriptionOperation(e){b(e);let n=u.readSubscriptionOperation;return p(t,n,e)}}}function le(t){return{async redeemReward(e){return b(e),(await p(t,u.redeemReward,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return b(e),(await p(t,u.claimRewardProduct,e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return b(e),(await p(t,u.createReferralCode,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){let r=await p(t,u.redeemCoupon,{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(e,n=crypto.randomUUID()){let r=await p(t,u.grantOffer,{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await p(t,u.listOffers,{},{response:"Invalid offers response"})).offers}}}function fe(t){return{...ce(t),...ue(t),...de(t),...pe(t),...le(t)}}function me(t){return{async resolveContent(e){b(e);let n=u.resolveContent;return p(t,n,e)},async resolvePaywall(e){b(e);let n=u.resolvePaywall,r=n.request.parse(e),s=await p(t,n,r);return j(r,s.paywall.check,s.scope),s},async resolveOffering(e){b(e);let n=u.resolveOffering,r=n.request.parse(e),s=await p(t,n,r);return j(r,s.check,s.scope),s}}}var z=t=>new TextEncoder().encode(JSON.stringify(t)).length,ye=16384,be=5e3,Ee=6e4,Oe=5;function Se(t){return t instanceof o&&t.status!==void 0&&t.status>=400&&t.status<500&&!t.retryable}function Ie(t,e){let n=0,r,s=h=>{r={config:structuredClone(h),until:Date.now()+3e4}},a=[],l=null,y,w=0;function f(){if(!e())throw new o("NOT_IDENTIFIED","Call identify before using Features or events")}function O(){y||!a.length||!e()||(y=setTimeout(()=>{y=void 0,S().catch(()=>{}).finally(O)},Math.min(be*2**w,Ee)),typeof y=="object"&&"unref"in y&&y.unref())}function D(h){if(f(),r&&Date.now()<r.until&&!$(r.config,h.kind))return;q();let P=u.trackEvents.request.parse({events:[{...h,eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString()}]}).events[0];if(z({events:[P]})>ye)throw new o("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new o("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(P)),O()}function m(h,P={},v={}){D({kind:"custom",name:h,properties:P,...v})}async function S(h=!1){if(f(),l)return l;let P=n,v=(async()=>{let i={inserted:0,duplicates:0,rejected:0,skipped:0,rejections:[]},c=a.length;for(;c&&P===n;){let d=[],E=z({events:[]});for(let k of a.slice(0,Math.min(c,100))){let T=z(k)+(d.length?1:0);if(d.length&&E+T>ye)break;d.push(k),E+=T}let C=u.trackEvents,A;try{if(A=await p(t,C,{events:d},void 0,{keepalive:h}),P!==n)throw new o("IDENTITY_CHANGED","Event identity changed during delivery");if(A.inserted+A.duplicates+A.rejected+A.skipped!==d.length||A.rejections.length!==A.rejected)throw new o("INVALID_RESPONSE","Incomplete event acknowledgement")}catch(k){throw P===n&&(w++,(Se(k)||w>=Oe)&&(a.splice(0,d.length),w=0)),k}w=0,s(A.analyticsConfig),a.splice(0,d.length),c-=d.length,i.inserted+=A.inserted,i.duplicates+=A.duplicates,i.rejected+=A.rejected,i.skipped+=A.skipped,i.rejections.push(...A.rejections)}return i})();l=v;try{return await v}finally{l===v&&(l=null)}}let I;function q(){if(I||typeof document>"u")return;let h=()=>{document.visibilityState==="hidden"&&e()&&a.length&&S(!0).catch(()=>{})};document.addEventListener("visibilitychange",h),I=()=>document.removeEventListener("visibilitychange",h)}return{rememberConfiguration:s,track:m,observe:D,flush:S,reset(){n++,r=void 0,clearTimeout(y),y=void 0,a=[],w=0,l=null},detachVisibility(){I?.(),I=void 0}}}function he(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}var Pe=new Set([...Z,"merchandiseId","merchandise"]);function Ce(t){let e=he(t);return{...Object.fromEntries(Object.entries(t).filter(([r])=>!Pe.has(r))),...e?{merchandise:e}:{}}}function we(t,e,n,r,s){if(s&&r&&(s.scope.projectId!==r.projectId||s.scope.environment!==r.environment))throw new o("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,l=new Set;function y(){if(!e())throw new o("NOT_IDENTIFIED","Call identify before using Features or events")}async function w(f={}){s||y();let O=a,D=!1,m=async()=>{if(D||O!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");let T=u.getFeatures,R=s?{scope:{projectId:s.scope.projectId,environment:s.scope.environment},payload:await s.features()}:await p(t,T,{});if(O!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");if(r&&(R.scope.projectId!==r.projectId||R.scope.environment!==r.environment))throw new o("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(R.payload.analyticsConfig),R},S=await m(),I=!0,q,h=T=>{try{f.onError?.(T)}catch{}},P=(T,R)=>{try{let g=he(R);n.observe({...T,...g?{merchandise:g}:{}})}catch(g){h(g)}},v=re({assertUsable:s?.assertFeatures,scope:S.scope,attributes:f.attributes,onError:f.onError,load:async()=>I?(I=!1,S.payload):(await m()).payload,evaluateRemote:async T=>{if(O!==a)throw new o("IDENTITY_CHANGED","Feature identity changed");let R=u.evaluateFeatures,g=await p(t,R,{...T,attributes:Ce(T.attributes)});if(g.scope.projectId!==S.scope.projectId||g.scope.environment!==S.scope.environment)throw new o("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:g.generation,evaluatedAt:g.evaluatedAt,expiresAt:g.expiresAt,features:g.features,...g.merchandiseContext?{merchandiseContext:g.merchandiseContext}:{}}},onExperimentViewed:(T,R,g,x)=>P({kind:"experiment_exposure",generation:x,experimentId:T.key,variationId:R.key},g),onFeatureUsage:(T,R,g,x)=>P({kind:"feature_usage",generation:x,feature:T,value:R.value??null,source:R.source,ruleId:R.ruleId,...R.experimentResult?{variationId:R.experimentResult.key}:{}},g)}),i=v.refresh;function c(){clearTimeout(q),!s&&(D||O!==a||!v.expiresAt||(q=setTimeout(()=>{d().catch(h)},Math.min(2147483647,Math.max(1e3,Date.parse(v.expiresAt)-Date.now()))),typeof q=="object"&&"unref"in q&&q.unref()))}async function d(){try{return await i()}finally{c()}}let E=()=>{D||d().catch(h)},C=v.subscribe(c),A=s?.subscribe(()=>{!D&&s.fresh&&d().catch(h)});function k(){D||(D=!0,clearTimeout(q),typeof window<"u"&&window.removeEventListener("focus",E),C(),A?.(),v.reset(),l.delete(k))}l.add(k);try{await v.init(),(f.attributes?.merchandise||f.attributes?.merchandiseId)&&await v.refreshRemote()}catch(T){throw k(),T}return c(),!s&&typeof window<"u"&&window.addEventListener("focus",E),Object.assign(v,{refresh:d,destroy:k})}return{features:w,reset(f){a++,f();for(let O of l)O()}}}import{z as Te}from"zod";function ge(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,r=Te.object({funnelId:G.shape.id,funnelVersionId:G.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new o("INVALID_REQUEST","A valid Funnel source is required");let s=Object.freeze(r.data);function a(l){if("customerId"in l)throw new o("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in l&&l.funnelId!==void 0&&l.funnelId!==s.funnelId||"funnelVersionId"in l&&l.funnelVersionId!==void 0&&l.funnelVersionId!==s.funnelVersionId)throw new o("SCOPE_MISMATCH","The original Funnel source cannot change");return{...l,...s}}return{async claimCoupon(l,y=crypto.randomUUID()){let w=u.grantOffer,f=await p(t,w,a({couponId:l,requestId:y}));return{offer:f.offer,reason:f.reason}},async resolveOffering(l){let y=u.resolveOffering,w=y.request.parse(a(l)),f=await p(t,y,w);return j(w,f.check,f.scope),f},async resolvePaywall(l){let y=u.resolvePaywall,w=y.request.parse(a(l)),f=await p(t,y,w);return j(w,f.paywall.check,f.scope),f},async previewAttach(l){let y=u.previewAttach;return p(t,y,a(l))}}}function Ht(t){return Re(t)}function Re(t){let e=te(t),n=e.request,r;try{r=se(t.push,e,t.scope??t.configuration?.scope)}catch(y){throw e.dispose(),y}let s=ae(e,()=>{l.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=Ie(n,s.isIdentified),l=we(n,s.isIdentified,a,t.scope,t.configuration);return{session:e.session,...oe(n,r),...fe(n),...me(n),forFunnel(y){return s.assertActive(),ge(n,y)},async features(y={}){return s.assertActive(),l.features(y)},track(y,w,f={}){return a.track(y,w,f)},flush(){return a.flush()},...s.methods}}function Qt(t){if(!L.test(t.customerToken))throw new o("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new o("INVALID_REQUEST","An explicit App and environment scope is required");let e=ie({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let r=await e.start(n),s=B({...t,runToken:r.runToken,initialResponse:r});s.identify(t.customerToken);let a=await s.get();return{...r,...a,controller:s}}}}function tn(t){if(!t.scope)throw new o("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new o("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,r=0,s=new Set,a=new Map,l=new Map;async function y(m){let S,I=new Promise((q,h)=>{S=setTimeout(()=>h(new o("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(m),I])}finally{clearTimeout(S)}}function w(m){throw m instanceof o&&(m.status===401||m.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,e=null,a.clear(),l.clear()),m}function f(m,S){if(S!==r)throw new o("IDENTITY_CHANGED","Process was detached during a request");let I=ee.parse(m);if(I.scope.projectId!==t.scope.projectId||I.scope.environment!==t.scope.environment)throw new o("SCOPE_MISMATCH","Process response belongs to another App/environment");if(e&&(e.run.id!==I.run.id||e.run.source.versionId!==I.run.source.versionId||e.run.source.id!==I.run.source.id||e.run.runExpiresAt!==I.run.runExpiresAt||e.run.identity.startedAs!==I.run.identity.startedAs||e.run.identity.participantId!==I.run.identity.participantId||e.run.identity.binding&&I.run.identity.binding&&e.run.identity.binding.id!==I.run.identity.binding.id))throw new o("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!e||I.run.revision>=e.run.revision){if(e?.run.identity.binding&&!I.run.identity.binding)throw new o("INVALID_RESPONSE","The process lost its Customer binding");e=I;for(let E of s)J(E,I.run);I.run.instruction?.type==="authentication_required"&&J(t.onAuthenticationRequired,I.run)}I.settlement?.accepted!==void 0&&l.set(I.settlement.requestId,I.settlement.accepted);let{identity:q,instruction:h,...P}=I.run,{contract:v,settlement:i,...c}=I,d=i&&(({accepted:E,...C})=>C)(i);return{...c,run:{...P,authenticated:q.binding!==null,instruction:h?.type==="authentication_required"?null:h},...d?{settlement:d}:{}}}let O=m=>(a.has(m)||a.set(m,e?.run.identity.binding?.id??null),a.get(m));async function D(m){let S=r,I=e?.run.identity.binding?.id??null,q=P=>{if(I!==(e?.run.identity.binding?.id??null))throw P;return w(P)};if(m.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new o("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return y(()=>t.adapter.pageExperiments(m.release,m.usedReceiptIds)).catch(q)}let h;if(m.operation==="get"){let{operation:P,customerToken:v,...i}=m;h=await y(()=>t.adapter.get({...i,...i.settlementRequestId?{settlementBindingId:O(i.settlementRequestId)}:{}})).catch(q)}else if(m.operation==="review")h=await y(()=>t.adapter.review(m.receiptId)).catch(q);else{if(m.operation==="start")throw new o("INVALID_REQUEST","Use process.open for entry");{let{customerToken:P,...v}=m;h=await y(()=>t.adapter.command(v,O(v.requestId))).catch(q)}}return f(h,S)}return{get view(){return e?.run??null},get controller(){return n},async open(m){let S=r,I=await y(()=>t.adapter.open(m)).catch(w),q=f(I,S);if(!n){n=B({...t,runToken:I.runToken,initialResponse:q,process:{request:D,binding:O,restore(v){for(let[i,c]of Object.entries(v))a.set(i,c)}}});let h=n,P=h.submit;h.submit=async v=>{try{return await P(v)}catch(i){if(!(i instanceof o)||i.reason!=="IDENTITY_CONTEXT_CHANGED"||v.operation!=="submit"||v.input.type!=="screen"||a.get(v.requestId)!==null)throw i;await h.settle?.(v.requestId),await h.get();let c=h.view;if(l.get(v.requestId)!==!1||!c||c.id!==e?.run.id||c.nodeId!==v.nodeId||c.visit!==v.visit||!e?.run.identity.binding)throw i;return P({...v,requestId:crypto.randomUUID(),revision:c.revision})}}}await n.get();for(let h of n.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(e?.run.identity.binding?.id??null)&&await n.settle?.(h.requestId);return{run:e.run,controller:n}},async syncIdentity(){let m=r;f(await y(()=>t.adapter.syncIdentity()).catch(w),m),await n?.get();for(let S of n?.pendingCommands??[])a.has(S.requestId)&&a.get(S.requestId)!==(e?.run.identity.binding?.id??null)&&await n?.settle?.(S.requestId);return e.run},async detach(){r++,n?.reset(),n=void 0,e=null,a.clear(),l.clear(),await y(()=>t.adapter.detach())},forProcess(m){if(!e?.run.identity.binding)throw new o("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:m}},subscribe(m){return s.add(m),()=>{s.delete(m)}},destroy(){r++,n?.reset(),n=void 0,e=null,a.clear(),l.clear(),s.clear()}}}export{Ht as a,Re as b,Qt as c,tn as d};
@@ -1 +1 @@
1
- import{a as u}from"./chunk-QVGTHPWT.js";import{Aa as j,Ba as O,Ca as T,ya as E,za as M}from"./chunk-KSCITFNQ.js";import{q as w}from"./chunk-HDVLCRC6.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
+ import{a as u}from"./chunk-QVGTHPWT.js";import{Aa as j,Ba as O,Ca as T,ya as E,za as M}from"./chunk-LPMYELUB.js";import{q as w}from"./chunk-HDVLCRC6.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};