@tinkerlandai/longplay-sdk 0.10.4 → 0.10.5

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 (36) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/README.md +6 -2
  3. package/dist/{chunk-ACF2FBUB.js → chunk-5BWSWP6H.js} +1 -1
  4. package/dist/{chunk-KBM7BYQY.js → chunk-5FAUO337.js} +1 -1
  5. package/dist/{chunk-HOW7NIIR.js → chunk-ABL2UMTI.js} +1 -1
  6. package/dist/{chunk-SBPTOOYB.js → chunk-BEBSMWPR.js} +1 -1
  7. package/dist/{chunk-2HFA34QO.js → chunk-EK6IPAY5.js} +2 -2
  8. package/dist/chunk-FSTRGSM5.js +1 -0
  9. package/dist/{chunk-RE6BIFLN.js → chunk-KMCA4Y2Q.js} +1 -1
  10. package/dist/{chunk-MRN4HP4W.js → chunk-MSOVR5KN.js} +1 -1
  11. package/dist/{chunk-G56XGVMS.js → chunk-O3FHA25D.js} +1 -1
  12. package/dist/{chunk-VMM3GA3L.js → chunk-OHYC6K3A.js} +1 -1
  13. package/dist/{chunk-ZPZVSC4J.js → chunk-QOUOTUVB.js} +1 -1
  14. package/dist/{chunk-X6BCUINI.js → chunk-ZDT32X4G.js} +1 -1
  15. package/dist/{chunk-YQHPEP4X.js → chunk-ZEEDAM4H.js} +1 -1
  16. package/dist/{chunk-JB46ZKGZ.js → chunk-ZIUBXO6M.js} +1 -1
  17. package/dist/{content-NYMIZRNR.js → content-QPJOW6OT.js} +1 -1
  18. package/dist/funnel-runtime-host-EHYY7OIZ.js +1 -0
  19. package/dist/index.js +1 -1
  20. package/dist/openrouter.js +1 -1
  21. package/dist/page.js +1 -1
  22. package/dist/{paywall-EJCNWDHK.js → paywall-EYRLWKC5.js} +1 -1
  23. package/dist/popup.js +1 -1
  24. package/dist/react-native.js +1 -1
  25. package/dist/screen-renderer-KOKMHO6R.js +1 -0
  26. package/dist/server.js +1 -1
  27. package/dist/visual-dom-YGLIHSKU.js +1 -0
  28. package/dist/visual.js +1 -1
  29. package/package.json +10 -9
  30. package/dist/chunk-VOEFXEPP.js +0 -1
  31. package/dist/funnel-runtime-host-UL4DEJDU.js +0 -1
  32. package/dist/screen-renderer-JMHV4GPP.js +0 -1
  33. package/dist/visual-dom-DQLPBZ2Z.js +0 -1
  34. /package/dist/{chunk-XSVQHPQT.js → chunk-BI4R5Q7Z.js} +0 -0
  35. /package/dist/{chunk-CLXORAOK.js → chunk-MPE7OZTE.js} +0 -0
  36. /package/dist/{chunk-7DXL3LHT.js → chunk-XVT5BKJW.js} +0 -0
package/dist/server.js CHANGED
@@ -1 +1 @@
1
- import{a as cn}from"./chunk-VOEFXEPP.js";import{a as dn,b as ln,c as mn,d as fn}from"./chunk-YQHPEP4X.js";import{a as s,b as ue,c as Y,d as Ue,e as He,f as Ge,h as J,i as Ve,j as D,k as F,m as je,n as sn,o as un,p as pn}from"./chunk-JB46ZKGZ.js";import"./chunk-SBPTOOYB.js";import{A as ge,B as he,C as te,Ca as Be,D as re,Da as ke,E as oe,Ha as Le,I as ae,J as Ee,Ja as Pe,K as Re,R as Ae,S as ie,T as _e,U as Fe,V as Q,W as P,X as be,g as le,h as me,i as W,k as Z,l as fe,n as ee,na as r,oa as se,p as ye,ta as De,u as z,ua as Me,v as K,va as ce,w as Ie,wa as Te,xa as xe,ya as V,z as ne,za as Ne}from"./chunk-2HFA34QO.js";import{ja as Oe,qa as d}from"./chunk-ACF2FBUB.js";import{a as de,e as Ce}from"./chunk-G56XGVMS.js";import"./chunk-MRN4HP4W.js";import{b as we,e as Se}from"./chunk-7DXL3LHT.js";import{a as ve}from"./chunk-XSVQHPQT.js";function qe(e){return{async getCustomer(t){let n=r.getCustomer;return s(e,n,t,{request:"Invalid customer lookup",response:"Invalid customer response"})},async listCustomers(t={}){let n=r.listCustomers;return s(e,n,t,{request:"Invalid customer filters",response:"Invalid customer response"})},async updateCustomer(t){let n=r.updateCustomer;return s(e,n,t,{request:"Invalid customer patch",response:"Invalid customer response"})},async createGuestCustomer(t){let n=r.createGuestCustomer;return s(e,n,t)},async resumeGuestSession(t){let n=r.resumeGuestSession;return s(e,n,t)},async claimGuestCustomer(t){let n=r.claimGuestCustomer;return s(e,n,t)},async revokeCustomerSessions(t){let n=r.revokeSessions;return s(e,n,t)},async createCustomerSession(t){return s(e,r.createSession,{customerId:t},{request:"A customer ID is required",response:"Invalid customer session response"})},async getOrCreateCustomer(t){return s(e,r.createCustomer,t,{request:"Invalid customer input",response:"Invalid customer response"})}}}function p(e,t){try{return e.parse(t)}catch{throw new d("INVALID_RESPONSE","Invalid gateway response")}}function ze(e){return{async checkEntitlement(t){let n=r.checkEntitlement;return s(e,n,t,p)},async readHoldings(t){let n=r.readHoldings;return s(e,n,t,p)},async readSeats(t){let n=r.readSeats;return s(e,n,t,p)},async manageSeat(t){let n=r.manageSeat;return s(e,n,t,p)}}}function Ke(e){return{async readAiPricing(t){let n=r.readAiPricing;return s(e,n,t,p)},async readUsage(t){let n=r.readUsage;return s(e,n,t,p)},async setUsage(t){let n=r.setUsage;return s(e,n,t,p)},async manageBalanceGrant(t){let n=r.manageBalanceGrant;return s(e,n,t,p)},async readBalanceSource(t){let n=r.readBalanceSource;return s(e,n,t,p)},async adjustBalance(t){let n=r.adjustBalance;return s(e,n,t,p)},async listBalanceGrants(t){let n=r.listBalanceGrants;return s(e,n,t,p)},async manageBillingLimits(t){let n=r.manageBillingLimits;return s(e,n,t,p)},async manageUsageEntity(t){let n=r.manageUsageEntity;return s(e,n,t,p)},async readUsageAnalytics(t){let n=r.readUsageAnalytics;return s(e,n,t,p)},async readCreditAnalytics(t){let n=r.readCreditAnalytics;return s(e,n,t,p)},async submitUsageBatch(t){let n=r.submitUsageBatch;return s(e,n,t,p)},async readUsageBatch(t){let n=r.readUsageBatch;return s(e,n,t,p)},async readLedger(t){let n=r.readLedger;return s(e,n,t,p)},async readCreditStatement(t){let n=r.readCreditStatement;return s(e,n,t,p)},async quoteBalance(t){let n=r.quoteBalance;return s(e,n,t,p)},async trackUsage(t){let n=r.trackUsage;return s(e,n,t,p)},async mutateBalance(t){let n=r.mutateBalance;return s(e,n,t,p)}}}function Qe(e){return{async listInvoiceTemplates(t={}){let n=r.listInvoiceTemplates;return s(e,n,t,p)},async previewInvoice(t){let n=r.previewInvoice;return s(e,n,t,p)},async createInvoice(t){let n=r.createInvoice;return s(e,n,t,p)},async prepareBillingAdjustment(t){let n=r.prepareBillingAdjustment;return s(e,n,t,p)},async manageInvoice(t){let n=r.manageInvoice;return s(e,n,t,p)},async readInvoiceOperation(t){let n=r.readInvoiceOperation;return s(e,n,t,p)},async listInvoices(t){let n=r.listInvoices;return s(e,n,t,p)},async getInvoice(t){let n=r.getInvoice;return s(e,n,t,p)},async setupPayment(t){let n=r.setupPayment;return s(e,n,t,p)},async readPaymentSetup(t){let n=r.readPaymentSetup;return s(e,n,t,p)},async readBillingInvoice(t){let n=r.readBillingInvoice;return s(e,n,t,p)},async previewRefund(t){let n=r.previewRefund;return s(e,n,t,p)},async refund(t){let n=r.refund;return s(e,n,t,p)},async readRefund(t){let n=r.readRefund;return s(e,n,t,p)}}}function Ye(e){return{async previewSubscriptionBatch(t){let n=r.previewSubscriptionBatch;return s(e,n,t,p)},async confirmSubscriptionBatch(t){let n=r.confirmSubscriptionBatch;return s(e,n,t,p)},async readSubscriptionBatch(t){let n=r.readSubscriptionBatch;return s(e,n,t,p)},async abandonSubscriptionBatch(t){let n=r.abandonSubscriptionBatch;return s(e,n,t,p)},async manageSubscriptionTrial(t){let n=r.manageSubscriptionTrial;return s(e,n,t,p)},async readSubscriptionTrial(t){let n=r.readSubscriptionTrial;return s(e,n,t,p)},async listSubscriptions(t){let n=r.listSubscriptions;return s(e,n,t,p)},async listPurchases(t){let n=r.listPurchases;return s(e,n,t,p)},async listSubscriptionConflicts(t){let n=r.listSubscriptionConflicts;return s(e,n,t,p)},async retrySubscriptionConflict(t){let n=r.retrySubscriptionConflict;return s(e,n,t,p)},async previewUpdate(t){let n=r.previewUpdate;return s(e,n,t,p)},async update(t){let n=r.update;return s(e,n,t,p)},async readSubscriptionUpdate(t){let n=r.readSubscriptionUpdate;return s(e,n,t,p)},async restoreNativePurchase(t){let n=r.restoreNativePurchase;return s(e,n,t,p)},async verifySubscriptions(t){let n=r.verifySubscriptions;return s(e,n,t,p)},async previewAttach(t){let n=r.previewAttach;return s(e,n,t,p)},async recordBillingEvent(t){let n=r.recordBillingEvent;return s(e,n,t,p)},async attach(t){let n=r.attach;return s(e,n,t,p)},async readSubscriptionOperation(t){let n=r.readSubscriptionOperation;return s(e,n,t,p)}}}function Je(e){return{async recordCouponRedemption(t){return s(e,r.recordCouponRedemption,t,{request:"Invalid Coupon redemption facts",parseResponse:p})},async grantOffer(t){let n=r.grantOffer;return s(e,{...n,request:n.request.refine(c=>!!c.customerId)},{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid offer grant",response:"Invalid offer response"})}}}function $e(e){return{...ze(e),...Ke(e),...Qe(e),...Ye(e),...Je(e)}}function Xe(e){return{async getFeatures(t={}){let n=r.getFeatures;return s(e,n,t,p)},async evaluateFeatures(t){let n=r.evaluateFeatures;return s(e,n,t,p)}}}function We(e){return{async trackEvents(t){let n=r.trackEvents;return s(e,n,t,p)}}}function Ze(e){return{async resolveContent(t){let n=r.resolveContent;return s(e,n,t,p)},async resolvePaywall(t){let n=r.resolvePaywall;return s(e,n,t,p)},async resolveOffering(t){let n=r.resolveOffering;return s(e,n,t,p)}}}function en(e){D(e.apiKey,"Secret API keys must stay on your backend");let n=F(e).request;return{async sendMessage(c){let i=r.sendMessage;return i.response.parse(await n(i.path,i.request.parse(c)))},async readMessage(c){let i=r.readMessage;return i.response.parse(await n(i.path,i.request.parse(c)))},...qe(n),...$e(n),...Xe(n),...We(n),...Ze(n)}}function yn(){if(typeof window<"u")throw new d("SERVER_ONLY","Guest identity is issued by your backend");let e=crypto.getRandomValues(new Uint8Array(32));return"gg_gc_"+btoa(String.fromCharCode(...e)).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}async function In(e,t){D(e.apiKey,"Renewal requires your backend");let n=F(e),c=Me.parse(await Y(e,await n.request("funnels",De.parse({...t,operation:"renew_run"}))));if(c.run.id!==t.runId)throw new d("INVALID_RESPONSE","Run renewal identity changed");return c}function nn(e){let t=He(e),n=u=>{throw new d("INVALID_RESPONSE",u)};t.nodes.size!==e.topology.nodes.length&&n("Duplicate local node identity"),t.nodes.get(e.topology.entry)?.type!=="entry"&&n("A local Funnel must start at Entry");let c=new Set(["entry","condition","feature","split","end","output"]);for(let u of t.nodes.values()){if(!c.has(u.type))throw new d("SERVER_REQUIRED","This Funnel requires authoritative server execution");if(u.type==="entry"&&u.id!==e.topology.entry&&n("Unexpected Entry node"),["entry","feature"].includes(u.type)&&!u.outputs.next&&n("Local next exit is unavailable"),u.type==="feature"){let a=u.resources.featureKey;(!a||!Object.hasOwn(e.evaluation.variables,u.writes.value)||!Object.hasOwn(t.features,a))&&n("Local Feature definition or declaration is unavailable")}if(u.type==="condition"){let a=e.conditions[u.id];(!a||!u.outputs.default||a.some((f,m)=>f.port!==`case:${m}`||!u.outputs[f.port]))&&n("Local Condition exits are unavailable")}if(u.type==="split"&&(!u.resources.experimentId||!Object.hasOwn(e.growth.experiments,u.resources.experimentId)||!u.outputs.notParticipating)&&n("Local Experiment definition or exit is unavailable"),u.type==="end"||u.type==="output"){let a=e.evaluation.terminals[u.id];if(!a)throw new d("SERVER_REQUIRED","Terminal resource delivery requires the server");Object.keys(u.outputs).length&&n("A terminal cannot have outgoing edges"),a.output?.type==="feature"&&!Object.hasOwn(t.features,a.output.featureKey)&&n("Terminal Feature definition is unavailable")}for(let a of Object.values(u.outputs))t.nodes.has(a)||n("Local target is unavailable")}let i=new Set,o=new Set;function l(u){if(o.has(u)&&n("Local graph contains a cycle"),!i.has(u)){o.add(u);for(let a of Object.values(t.nodes.get(u).outputs))l(a);o.delete(u),i.add(u)}}return l(e.topology.entry),i.size!==t.nodes.size&&n("Local graph contains unreachable nodes"),{evaluate(u){let a={},f=u.context;f.features=t.features,f.savedGroups=t.savedGroups;let m=()=>{f.attributes=Ae({declarations:e.evaluation.variables,attributes:u.attributes,parameters:u.parameters,answers:{},results:a,savedGroups:t.savedGroups})};m();let g=e.topology.entry,y=0;for(;;){let h=t.nodes.get(g);if(h.type==="end"||h.type==="output"){let v=e.evaluation.terminals[g],I=v.output,O=I?.type==="feature"?t.feature(I.featureKey,f):I?.type==="variable"?Re({source:"variable",key:I.key,...I.path?{path:I.path}:{}},{declarations:e.evaluation.variables,answers:{},results:a,parameters:u.parameters,attributes:u.attributes,savedGroups:t.savedGroups}):I?.value??null;return ae(e.evaluation.outputSchema,O)||n("Local output does not match its declaration"),{outcome:v.outcome,value:O}}if(y++>=e.evaluation.maxTransitions)throw new d("TRANSITION_LIMIT","Local Funnel transition budget exceeded");if(h.type==="entry")g=h.outputs.next;else{let v=t.evaluate(g,f);if(h.type==="feature"){let I=h.writes.value,O=v.value??null;ae(e.evaluation.variables[I],O)||n("Local Feature value does not match its declaration"),Ee(e.evaluation.variables,{writes:h.writes},{[I]:O}),a[I]=O,m()}g=v.target}}}}}import{z as tn}from"zod";function rn(e,t,n){let c=we.parse(e.attributes);if(["parameters","answers","results"].some(A=>Object.hasOwn(c,A)))throw new d("INVALID_REQUEST","Flow namespaces cannot be caller attributes");let i=Oe.parse(e.parameters??{}),o=tn.record(tn.string(),Se).parse(e.stickyBucketAssignmentDocs??{});for(let[A,R]of Object.entries(o))if(A!==`${R.attributeName}||${R.attributeValue}`||!Object.hasOwn(c,R.attributeName)||ve(c[R.attributeName])!==R.attributeValue)throw new d("INVALID_REQUEST","Sticky document identity does not match this session");let l=e.saveStickyBucketAssignmentDoc,u=e.onFeatureUsage,a=e.onExperimentViewed,f=e.onError,m=new Map,g=new Set,y={},h=Promise.resolve();function v(A){let R=h.then(()=>(n(),A()));return h=R.catch(()=>{}),R}function I(A){try{f?.(A)}catch{}}function O(A){try{let R=A();R&&typeof R.catch=="function"&&R.catch(I)}catch(R){I(R)}}async function M(){for(let[A,R]of m){if(n(),l)try{await l(structuredClone(R))}catch{throw new d("STICKY_SAVE_FAILED","Persist the pending Sticky assignment before using this evaluation")}n(),m.delete(A)}}return{evaluate(A={}){let R=A.track===!0;return v(async()=>{let C=await t();n(C);let N=new Set(g),B={...y},H=new Map,j=[],G={stickyBucketAssignmentDocs:structuredClone(o),saveStickyBucketAssignmentDoc(S){H.set(`${S.attributeName}||${S.attributeValue}`,structuredClone(S))},...R?{trackedExperiments:N,trackedFeatureUsage:B,onExperimentViewed(S,E){let _=structuredClone(S),q=structuredClone(E);a&&j.push(()=>a(structuredClone(_),structuredClone(q)))},onFeatureUsage(S,E){let _=structuredClone(E);u&&j.push(()=>u(S,structuredClone(_)))}}:{}},k=C.program.evaluate({attributes:c,parameters:i,context:G});n(C);for(let[S,E]of H)o[S]=E,m.set(S,E);await M(),n(C),R&&(g=N,y=B);for(let S of j)O(S);let b=C.configuration;return structuredClone({evaluationMode:"local",scope:b.scope,funnelId:b.funnelId,versionId:b.versionId,evaluationRevision:b.evaluationRevision,generation:b.growth.generation,...k})})},flush:()=>v(M),get stickyBucketAssignmentDocs(){return n(),structuredClone(o)}}}var gn=6e4;function $(e){if(typeof window<"u")throw new d("SERVER_ONLY","Local Funnel sessions run on your backend");let t=de.parse(e.scope),n=e.funnelId,c=e.load,i,o,l,u=0,a=g=>Date.now()>=g.expiresAt;async function f(){if(o)return o;let g=u;i=void 0;let y=(async()=>{let h=await c();if(g!==u)throw new d("IDENTITY_CHANGED","Local evaluator was reset");if(h&&typeof h=="object"&&"evaluationMode"in h&&h.evaluationMode==="remote")throw p(V,h),new d("EVALUATION_MODE","This Funnel requires remote decide");let v=p(Ne,h);if(g!==u)throw new d("IDENTITY_CHANGED","Local evaluator was reset");if(v.scope.projectId!==t.projectId||v.scope.environment!==t.environment||v.funnelId!==n)throw new d("SCOPE_MISMATCH","Local configuration scope changed");if(v.growth.scope.projectId!==t.projectId||v.growth.scope.environment!==t.environment||v.growth.expiresAt!==v.expiresAt)throw new d("INVALID_RESPONSE","GB configuration scope or expiry changed");let I=Math.min(Date.now()+gn,v.expiresAt?Date.parse(v.expiresAt):1/0);if(Date.now()>=I)throw new d("CONFIGURATION_EXPIRED","Refresh expired local rules");let O=JSON.stringify([t.projectId,t.environment,n,v.versionId,v.evaluationRevision,v.growth.generation]),M=[v.topology,v.conditions,v.evaluation,v.growth.features,v.growth.experiments,v.growth.savedGroups];if(l?.key===O&&!Ve(l.body,M))throw new d("INVALID_RESPONSE","Immutable local configuration identity changed");return l?.key!==O&&(l={key:O,body:M,program:nn(v)}),i={key:O,configuration:v,expiresAt:I,program:l.program},i})();o=y;try{return await y}finally{o===y&&(o=void 0)}}function m(){return o??(i&&!a(i)?Promise.resolve(i):f())}return{session(g){let y=u;return rn(g,m,h=>{if(e.assertUsable?.(),y!==u)throw new d("IDENTITY_CHANGED","Local evaluator was reset");if(h&&(a(h)||i?.key!==h.key))throw new d("CONFIGURATION_EXPIRED","Refresh local rules before using this result")})},async refresh(){return structuredClone((await f()).configuration)},reset(){u++,i=void 0,o=void 0,l=void 0}}}function hn(e,t){let n=e.snapshot?.generation,c=$({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t,load:()=>e.localFunnel(t),assertUsable:()=>e.assertFunnel(t)}),i=e.subscribe(()=>{let l=e.snapshot?.generation;e.fresh&&l!==n&&(n=l,c.refresh().catch(()=>{}))}),o=c.session;return Object.assign(c,{session(l){let u=o(l),a=u.evaluate;return Object.assign(u,{async evaluate(...f){return e.fresh||await e.refresh(),a(...f)}})},destroy(){i(),c.reset()}})}function vn(e){if(typeof window<"u")throw new d("SERVER_ONLY","Secret API keys must stay on the backend");return{start:t=>je(e,t)}}function on(e,t,n){return Le(e,t,n,Ue)}var U=class extends d{constructor(n,c){super("DECISION_PENDING","Decision is still pending; read this decision ID or retry the original request ID",202,c);this.decisionId=n;this.decisionRequestId=c}decisionId;decisionRequestId};async function X(e,t,n,c){let{decisionId:i,requestId:o}=e,l=e,u=250,a=0;for(;;){if(l.decisionId!==i||l.requestId!==o||l.decision&&!J(l.decision,t))throw new d("INVALID_RESPONSE","Decision request or customer changed");if(l.decision)return l.decision;if(l.status==="failed")throw new d("DECISION_FAILED","Decision execution failed",503,o);if(Date.now()>=n)throw new U(i,o);if(await new Promise(f=>setTimeout(f,Math.min(Math.max(u,a-Date.now()),n-Date.now()))),Date.now()>=n)throw new U(i,o);u=Math.min(1e3,u*2);try{l=await c(i,n)}catch(f){if(f instanceof d&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE","RATE_LIMITED"].includes(f.code)){a=Date.now()+(f.retryAfterSeconds??0)*1e3;continue}throw f}}}function pe(e){if("remoteEval"in e)throw new d("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");D(e.apiKey,"Funnel decisions are requested by your backend");let t,n,c=new Map;async function i(a,f){let m=a;m.status!=="pending"&&c.delete(m.decisionId);for(let g=0;g<32&&m.evaluation;g++){let y=m.evaluation;if(y.runId!==m.decisionId)throw new d("INVALID_RESPONSE","Local evaluation Run changed");let h=c.get(m.decisionId);if(!h&&y.type==="evaluate_segment"){let I=Pe.parse(await o({operation:"segment_configuration",funnelId:e.funnelId,versionId:y.versionId},f));if(I.configuration.scope.projectId!==e.scope.projectId||I.configuration.scope.environment!==e.scope.environment||I.configuration.funnelId!==e.funnelId||I.configuration.versionId!==y.versionId||I.configuration.evaluationRevision!==y.policyRevision)throw new d("SCOPE_MISMATCH","Original decision segment configuration changed");if(c.size>=128)throw new d("COMMAND_PENDING","Reconcile outstanding decisions first");h={operation:"commit_decision_segment",decisionId:m.decisionId,requestId:se(m.decisionId,y.visit,`segment:${y.revision}`),nodeId:y.nodeId,visit:y.visit,revision:y.revision,policyRevision:y.policyRevision,generation:I.configuration.growth.generation,...Ge(I.configuration,I.document,y)},c.set(m.decisionId,h)}if(!h){if(y.type!=="evaluate")throw new d("INVALID_RESPONSE","Unknown decision instruction");if((!n||n.versionId!==y.versionId||n.evaluationRevision!==y.policyRevision||n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())&&(n=V.parse(await o({operation:"configuration",funnelId:e.funnelId,versionId:y.versionId},f))),n.scope.projectId!==e.scope.projectId||n.scope.environment!==e.scope.environment||n.funnelId!==e.funnelId)throw new d("SCOPE_MISMATCH","Local evaluation configuration scope changed");if(n.evaluationMode!=="local"||n.versionId!==y.versionId||n.evaluationRevision!==y.policyRevision)throw new d("EVALUATION_MODE","Original Local evaluation policy is unavailable");if(c.size>=128)throw new d("COMMAND_PENDING","Reconcile outstanding Local decisions first");h={operation:"evaluate_decision",decisionId:m.decisionId,requestId:se(m.decisionId,y.visit,"evaluation"),nodeId:y.nodeId,visit:y.visit,revision:y.revision,receiptId:y.receiptId,policyRevision:y.policyRevision,generation:n.growth.generation,result:on(n,y.nodeId,y)},c.set(m.decisionId,h)}let v=P.parse(await o(h,f));if(v.decisionId!==a.decisionId||v.requestId!==a.requestId)throw new d("INVALID_RESPONSE","Decision identity changed during local evaluation");c.delete(m.decisionId),m=v}return m}async function o(a,f,m=!1){return F({...e,fetch:(y,h)=>{let v=new Headers(h?.headers);return v.set("Accept-Encoding","identity"),m&&v.set("Prefer","respond-async"),(e.fetch??globalThis.fetch)(y,{...h,headers:v})},timeoutMs:Math.min(e.timeoutMs??1e4,f?Math.max(1,f-Date.now()):12e4)}).request("funnels",a)}async function l(a,f){let m=P.parse(await o(Q.parse({operation:"read_decision",decisionId:a}),f));if(m.decisionId!==a)throw new d("INVALID_RESPONSE","Decision identity changed");return i(m,f)}async function u(a,f,m=!1){let g=Q.options[0].parse({...a,operation:"decide",funnelId:e.funnelId}),y;try{y=P.parse(await o(g,f,m))}catch(h){throw h instanceof d&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE"].includes(h.code)?new d("DECISION_ACCEPTANCE_UNKNOWN","Decision acceptance is unknown; retry the original request ID and input",h.status,a.requestId):h}if(y.requestId!==a.requestId||y.decision&&!J(y.decision,g.customer))throw new d("INVALID_RESPONSE","Decision request or customer changed");return{response:await i(y,f),customer:g.customer}}return{local(){return t??=$({scope:e.scope,funnelId:e.funnelId,load:()=>o({operation:"local_configuration",funnelId:e.funnelId})})},async configuration(){let a=V.parse(await o({operation:"configuration",funnelId:e.funnelId}));if(a.scope.projectId!==e.scope.projectId||a.scope.environment!==e.scope.environment||a.funnelId!==e.funnelId)throw new d("SCOPE_MISMATCH","Configuration scope changed");return a},features(a={}){return ue({...a,scope:e.scope,load:async()=>Ce.parse(await o({operation:"feature_config",funnelId:e.funnelId}))})},read:a=>l(a),async submit(a){return(await u(a,void 0,!0)).response},async decide(a){let f=Date.now()+3e4,m=await u(a,f);return X(m.response,m.customer,f,l)},async reportUsed(a){let f=be.parse(await o(Q.parse({...a,operation:"report_used"})));if(f.decisionId!==a.decisionId||f.eventId!==a.eventId)throw new d("INVALID_RESPONSE","Usage receipt identity changed");return f}}}function wn(e){D(e.apiKey,"Native receipts are verified by your backend","Server API key required");let t=F({...e,timeoutMs:e.timeoutMs??35e3});return{async recover(n){let c=Be.parse(n);if(c.orderId!==c.receiptId)throw new d("INVALID_REQUEST","Native recovery requires the accepted commercial intent");let i=c.nativeEvidence,o={requestId:c.requestId,customerToken:c.customerToken,purchaseIntentId:c.orderId,...i===null?{intent:"read"}:i.provider==="apple"?{provider:"apple",signedTransaction:i.signedTransaction}:{provider:"google",purchaseToken:i.purchaseToken}},l=r.restoreNativePurchase.response.parse(await t.request(r.restoreNativePurchase.path,o));if(l.operation.requestId!==c.requestId||l.operation.purchaseIntentId!==c.orderId)throw new d("INVALID_RESPONSE","Native receipt request identity changed");let u=ke.parse({scope:l.scope,requestId:c.requestId,orderId:l.operation.orderId,receiptId:l.operation.orderId,orderStatus:l.operation.status,refunded:l.operation.refunded,...l.operation.completion===null?{}:{nativeCompletion:{orderId:l.operation.orderId,receiptId:l.operation.orderId,...l.operation.completion}}});if(u.requestId!==c.requestId||u.orderId!==c.orderId||u.receiptId!==c.receiptId||u.scope.projectId!==e.scope.projectId||u.scope.environment!==e.scope.environment)throw new d("INVALID_RESPONSE","Current order receipt scope changed");return u}}}import{z as Sn}from"zod";var x=Sn.number().int().min(0).max(Number.MAX_SAFE_INTEGER);function En(e,t){let n=x.parse(e.inputTokens.total),c=x.parse(e.outputTokens.total),i=x.parse(e.inputTokens.cacheRead??0),o=x.parse(e.inputTokens.cacheWrite??0),l=x.parse(e.outputTokens.reasoning??0);if(i+o>n||l>c||e.inputTokens.noCache!==void 0&&x.parse(e.inputTokens.noCache)!==n-i-o||e.outputTokens.text!==void 0&&x.parse(e.outputTokens.text)!==c-l)throw new d("AI_USAGE_UNAVAILABLE","Provider token counts do not conserve total usage");return{input:n-i-o,cache_read:i,cache_write:o,output:t==="output"?c:c-l,reasoning:t==="separate"?l:0,input_audio:0,output_audio:0}}function Rn(e){if(typeof window<"u")throw new d("SERVER_ONLY","AI usage belongs on the trusted backend");if(!e.modelId||!["output","separate"].includes(e.reasoning))throw new d("INVALID_REQUEST","Model ID and reasoning pricing are required");async function t(c){await e.persist({context:c,modelId:e.modelId,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"})}async function n(c,i){let o={context:c,modelId:e.modelId,usage:i,tokens:null,quote:null,receipt:null,phase:"captured"};await e.persist(o);let l=e.mapTokens?e.mapTokens(i):En(i,e.reasoning),u=await e.pricing.quoteTokens({modelId:e.modelId,tokens:l});await e.persist({...o,tokens:l,quote:u,phase:"quoted"});let a=await e.pricing.trackTokens(e.client,{...c,quote:u});if(!a.receipt.accepted)throw new d("AI_BALANCE_REJECTED","AI usage was captured but the balance operation was rejected");await e.persist({...o,tokens:l,quote:u,receipt:a,phase:"settled"})}return{specificationVersion:"v4",async wrapGenerate({doGenerate:c}){let i=await e.context(),o;try{o=await c()}catch(l){throw await t(i),l}return await n(i,o.usage),o},async wrapStream({doStream:c}){let i=await e.context(),o;try{o=await c()}catch(m){throw await t(i),m}let l=!1,u=!1,a=o.stream.getReader();async function f(){l||u||(u=!0,await t(i))}return{...o,stream:new ReadableStream({async pull(m){try{let{value:g,done:y}=await a.read();if(y){if(!l)throw await f(),new d("AI_USAGE_UNAVAILABLE","Stream ended without final usage; no amount was invented");m.close();return}if(g.type==="finish"){if(l)throw new d("AI_USAGE_UNAVAILABLE","Provider sent more than one final usage record");l=!0,await n(i,g.usage)}m.enqueue(g)}catch(g){try{await f()}finally{m.error(g),await a.cancel(g)}}},async cancel(m){try{await f()}finally{await a.cancel(m)}}})}}}}function Cn(e){D(e.apiKey,"Funnel receipts are sent by your backend");let t=F(e);return{async signal(n){let c=ie.parse({...n,operation:"signal"}),i=_e.parse(await t.request("funnels",c));if(i.runId!==n.runId||i.eventId!==n.eventId||i.scope.projectId!==e.scope.projectId||i.scope.environment!==e.scope.environment)throw new d("INVALID_RESPONSE","Receipt identity changed");return i},async readResults(n){let c=ie.parse({operation:"read_results",runId:n}),i=Fe.parse(await t.request("funnels",c));if(i.runId!==n||i.scope.projectId!==e.scope.projectId||i.scope.environment!==e.scope.environment)throw new d("INVALID_RESPONSE","Result identity changed");return i}}}function An(e){if("remoteEval"in e)throw new d("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");D(e.apiKey,"Campaign entry requires your backend");let t=F({...e,timeoutMs:e.timeoutMs??35e3});return{async decide(n){let c=Date.now()+(e.timeoutMs??3e4),i=ce.parse({...n,funnelId:e.funnelId,operation:"campaign_decide"}),o=F({...e,timeoutMs:Math.min(e.timeoutMs??35e3,Math.max(1,c-Date.now()))}),l=P.parse(await o.request("funnels",i));if(l.scope.projectId!==e.scope.projectId||l.scope.environment!==e.scope.environment)throw new d("SCOPE_MISMATCH","Campaign scope changed");return X(l,i.customer,c,(u,a)=>pe({...e,timeoutMs:Math.min(e.timeoutMs??1e4,Math.max(1,a-Date.now()))}).read(u))},async start(n){let c=ce.parse({...n,funnelId:e.funnelId,operation:"campaign_start"}),i=xe.parse(await t.request("funnels",c)),o=Te.parse("suppressed"in i?i:await Y(e,i));if(o.scope.projectId!==e.scope.projectId||o.scope.environment!==e.scope.environment)throw new d("SCOPE_MISMATCH","Campaign scope changed");if(!("suppressed"in o)&&(o.run.source.id!==e.funnelId||!o.customerId||c.customer.type==="id"&&o.customerId!==c.customer.value))throw new d("INVALID_RESPONSE","Campaign Funnel or Customer changed");return o}}}import{z as On}from"zod";var w=class extends Error{constructor(n,c=409,i=!1,o="fix_request"){super(n);this.code=n;this.status=c;this.retryable=i;this.recovery=o}code;status;retryable;recovery};function _n(e){if(typeof window<"u")throw new Error("Merchant bridge credentials require a trusted server");let t=ye.parse(e.manifest),n={projectId:t.projectId,environmentId:t.environmentId,environment:t.environment},c=t.capabilities.some(i=>["purchases","subscription_changes","refunds","operation_status"].includes(i));for(let[i,o]of Object.entries(ee))if(o.command&&t.capabilities.includes(i)&&!(i==="catalog"&&t.catalog==="static")&&!e.handlers[o.command])throw new Error(`Missing merchant command handler: ${o.command}`);if(c&&(!e.resolveOperationAuthority||!e.handlers["operation.read"]||!t.capabilities.includes("operation_status")))throw new Error("Merchant operations require fresh Longplay authority and an operation lookup handler");return async function(o){let l=crypto.randomUUID(),u="bridge.ping",a,f=async(m,g,y=!1)=>{let h=JSON.stringify({bridgeVersion:Z,requestId:l,command:u,scope:n,[y?"error":"data"]:m});if(new TextEncoder().encode(h).byteLength>262144)throw new Error("Merchant response exceeds limit");return new Response(h,{status:g,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store","X-Request-Id":l,...a?await re(h,a,"response"):{}}})};try{if(o.headers.get("X-Indiana-Merchant-Bridge-Version")!==String(Z)||o.method!=="POST"||new URL(o.url).pathname!==fe)throw new w("MERCHANT_BRIDGE_INVALID_REQUEST",400);if(!/^application\/json(?:\s*;|$)/i.test(o.headers.get("Content-Type")??""))throw new w("MERCHANT_BRIDGE_INVALID_REQUEST",400);let m=o.body?.getReader();if(!m)throw new w("MERCHANT_BRIDGE_INVALID_REQUEST",400);let g=new TextDecoder("utf-8",{fatal:!0}),y="",h=0;try{for(;;){let E=await m.read();if(E.done)break;if(h+=E.value.byteLength,h>16384)throw new w("MERCHANT_BRIDGE_INVALID_REQUEST",413);y+=g.decode(E.value,{stream:!0})}y+=g.decode()}finally{await m.cancel().catch(()=>{}),m.releaseLock()}let v=he.safeParse(JSON.parse(y));if(!v.success)throw new w("MERCHANT_BRIDGE_INVALID_REQUEST",400);let I=v.data;if(l=I.requestId,u=I.command,Object.keys(n).some(E=>I.scope[E]!==n[E]))throw new w("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);let O=I.command==="bridge.ping"||I.command==="bridge.describe",M=I.command==="catalog.read";if((O||M||o.headers.has(te))&&(a=e.authentication.find(E=>E.keyId===o.headers.get(te)),!a||!await oe(y,o.headers,a,"request")))throw a=void 0,new w("MERCHANT_BRIDGE_AUTHENTICATION_FAILED",401);if(I.command==="bridge.ping")return f(ne["bridge.ping"].parse(I.data),200);if(I.command==="bridge.describe")return f(t,200);let A=Object.entries(ee).find(([,E])=>E.command===I.command);if(!A||!t.capabilities.includes(A[0]))throw new w("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let R=e.handlers[I.command];if(!R)throw new w("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);if(!M&&o.headers.has("Cookie")&&(o.headers.get("Origin")!==new URL(o.url).origin||["cross-site","same-site"].includes(o.headers.get("Sec-Fetch-Site")??"")))throw new w("MERCHANT_BRIDGE_FORBIDDEN",403);let C=M?{kind:"service"}:await e.authorize(o,I),N=C.kind,B=["purchase.execute","subscription.change","refund.execute"].includes(I.command),H=B||I.command==="operation.read";if(!(H&&a!==void 0&&N==="service")&&(I.command==="refund.execute"?N!=="administrator":!M&&N!=="user"))throw new w("MERCHANT_BRIDGE_FORBIDDEN",403);if(C.kind==="user"&&["purchase.execute","operation.read","subscription.change","customer.commerce.read","presentation.report"].includes(I.command)&&!On.uuid().safeParse(C.customerId).success)throw new w("MERCHANT_BRIDGE_UNAUTHENTICATED",401);let G=R,k=ne[I.command].parse(I.data),b={request:o,command:I.command,scope:n,principal:C},S;if(H){let E=z.parse(k);if(C.kind==="user"&&C.customerId!==E.customerId)throw new w("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!e.resolveOperationAuthority)throw new w("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let _=K.parse(await e.resolveOperationAuthority(E,b));if(_.operationId!==E.operationId||_.customerId!==E.customerId||Object.keys(n).some(T=>_.scope[T]!==n[T]))throw new w("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);b.authority=_;let q=I.command==="purchase.execute"?"purchase":I.command==="subscription.change"?"subscription_change":I.command==="refund.execute"?"refund":_.instruction.type;if(_.instruction.type!==q)throw new w("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!B)S=W.parse(await G(k,b));else{if(_.confirmedAt===null)throw new w("MERCHANT_BRIDGE_OPERATION_NOT_CONFIRMED",409);let T=W.parse(await e.handlers["operation.read"](E,{...b,command:"operation.read"}));if(T.operationId!==E.operationId||T.customerId!==E.customerId)throw new w("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(T.lookup==="found")S=T.execution;else{if(!_.initialExecutionAllowed)throw new w("MERCHANT_BRIDGE_RECOVERY_REQUIRED",409,!1,"recover_operation");if(Date.parse(_.instruction.expiresAt)<=Date.now())throw new w("MERCHANT_BRIDGE_OPERATION_EXPIRED",409,!1,"reload_state");if(!t.capabilities.includes("billing_records")||me(_.instruction).some(L=>!t.billingEvents.some(an=>an===L))||le(_.instruction).some(L=>!t.profiles.includes(L)))throw new w("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");try{S=Ie.parse(await G(k,b))}catch(L){throw L instanceof w?L:new w("MERCHANT_BRIDGE_RESULT_UNKNOWN",503,!1,"recover_operation")}}if(S.type!==q)throw new w("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}}else S=ge[I.command].parse(await G(k,b));if(C.kind==="user"){if("nativeUserId"in S&&S.nativeUserId!==C.nativeUserId)throw new w("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("customerId"in S&&S.customerId!==C.customerId)throw new w("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("session"in S&&C.customerId&&S.session.customerId!==C.customerId)throw new w("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("presentation"in S&&S.presentation&&C.customerId&&S.presentation.customerId!==C.customerId)throw new w("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}if("operationId"in S&&(S.operationId!==z.parse(I.data).operationId||S.customerId!==z.parse(I.data).customerId))throw new w("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return f(S,B&&("paymentStatus"in S&&["pending","unknown"].includes(S.paymentStatus)||"status"in S&&["pending","unknown","scheduled"].includes(S.status))?202:200)}catch(m){let g=m instanceof w?m:m instanceof SyntaxError?new w("MERCHANT_BRIDGE_INVALID_REQUEST",400):new w("MERCHANT_BRIDGE_INVALID_RESPONSE",500);return f({code:g.code,message:g.code,retryable:g.retryable,recovery:g.recovery},g.status,!0)}}}function Fn(e){return async(t,n)=>{let c=()=>e.readSubscriptionOperation(t),i=()=>e.readSubscriptionUpdate(t),o=()=>e.readRefund(t),l=n.command==="purchase.execute"?[c]:n.command==="subscription.change"?[i]:n.command==="refund.execute"?[o]:[c,i,o];for(let u of l)try{let a=await u(),f="authority"in a.operation?a.operation.authority:void 0;if(!f)throw new w("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");let m=K.parse(f);if(m.customerId!==t.customerId||m.operationId!==t.operationId||Object.keys(n.scope).some(g=>m.scope[g]!==n.scope[g]))throw new w("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return m}catch(a){if(n.command==="operation.read"&&a instanceof d&&a.code==="NOT_FOUND")continue;throw a}throw new w("MERCHANT_BRIDGE_OPERATION_NOT_FOUND",404,!1,"reload_state")}}export{U as FunnelDecisionTimeoutError,d as IndianaError,d as LongplayError,w as MerchantBridgeHandlerError,dn as aiPriceSnapshotSchema,ln as aiTokenQuoteSchema,mn as createAiPricing,Rn as createAiUsageMiddleware,sn as createConfigurationSync,fn as createConfiguredAiPricing,ue as createFeatureClient,An as createFunnelCampaignClient,pe as createFunnelDecisionClient,$ as createFunnelLocalEvaluator,Cn as createFunnelOrchestrationClient,un as createFunnelStartClient,yn as createGuestToken,en as createIndianaServer,pn as createLocalFunnelClient,en as createLongplayServer,Fn as createMerchantBridgeAuthorityResolver,_n as createMerchantBridgeHandler,wn as createNativeReceiptClient,vn as createPaywallStartClient,hn as createSynchronizedFunnelLocalEvaluator,cn as evaluateFunnelNode,In as renewFunnelRun,re as signMerchantBridgeMessage,oe as verifyMerchantBridgeMessage};
1
+ import{a as cn}from"./chunk-FSTRGSM5.js";import{a as dn,b as ln,c as mn,d as fn}from"./chunk-ZEEDAM4H.js";import{a as s,b as ue,c as Y,d as Ue,e as He,f as Ge,h as J,i as Ve,j as D,k as F,m as je,n as sn,o as un,p as pn}from"./chunk-ZIUBXO6M.js";import"./chunk-BEBSMWPR.js";import{A as ge,B as he,C as te,Ca as Be,D as re,Da as ke,E as oe,Ha as Le,I as ae,J as Ee,Ja as Pe,K as Re,R as Ae,S as ie,T as _e,U as Fe,V as Q,W as P,X as be,g as le,h as me,i as W,k as Z,l as fe,n as ee,na as r,oa as se,p as ye,ta as De,u as z,ua as Me,v as K,va as ce,w as Ie,wa as Te,xa as xe,ya as V,z as ne,za as Ne}from"./chunk-EK6IPAY5.js";import{ja as Oe,qa as d}from"./chunk-5BWSWP6H.js";import{a as de,e as Ce}from"./chunk-O3FHA25D.js";import"./chunk-MSOVR5KN.js";import{b as we,e as Se}from"./chunk-XVT5BKJW.js";import{a as ve}from"./chunk-BI4R5Q7Z.js";function qe(e){return{async getCustomer(t){let n=r.getCustomer;return s(e,n,t,{request:"Invalid customer lookup",response:"Invalid customer response"})},async listCustomers(t={}){let n=r.listCustomers;return s(e,n,t,{request:"Invalid customer filters",response:"Invalid customer response"})},async updateCustomer(t){let n=r.updateCustomer;return s(e,n,t,{request:"Invalid customer patch",response:"Invalid customer response"})},async createGuestCustomer(t){let n=r.createGuestCustomer;return s(e,n,t)},async resumeGuestSession(t){let n=r.resumeGuestSession;return s(e,n,t)},async claimGuestCustomer(t){let n=r.claimGuestCustomer;return s(e,n,t)},async revokeCustomerSessions(t){let n=r.revokeSessions;return s(e,n,t)},async createCustomerSession(t){return s(e,r.createSession,{customerId:t},{request:"A customer ID is required",response:"Invalid customer session response"})},async getOrCreateCustomer(t){return s(e,r.createCustomer,t,{request:"Invalid customer input",response:"Invalid customer response"})}}}function p(e,t){try{return e.parse(t)}catch{throw new d("INVALID_RESPONSE","Invalid gateway response")}}function ze(e){return{async checkEntitlement(t){let n=r.checkEntitlement;return s(e,n,t,p)},async readHoldings(t){let n=r.readHoldings;return s(e,n,t,p)},async readSeats(t){let n=r.readSeats;return s(e,n,t,p)},async manageSeat(t){let n=r.manageSeat;return s(e,n,t,p)}}}function Ke(e){return{async readAiPricing(t){let n=r.readAiPricing;return s(e,n,t,p)},async readUsage(t){let n=r.readUsage;return s(e,n,t,p)},async setUsage(t){let n=r.setUsage;return s(e,n,t,p)},async manageBalanceGrant(t){let n=r.manageBalanceGrant;return s(e,n,t,p)},async readBalanceSource(t){let n=r.readBalanceSource;return s(e,n,t,p)},async adjustBalance(t){let n=r.adjustBalance;return s(e,n,t,p)},async listBalanceGrants(t){let n=r.listBalanceGrants;return s(e,n,t,p)},async manageBillingLimits(t){let n=r.manageBillingLimits;return s(e,n,t,p)},async manageUsageEntity(t){let n=r.manageUsageEntity;return s(e,n,t,p)},async readUsageAnalytics(t){let n=r.readUsageAnalytics;return s(e,n,t,p)},async readCreditAnalytics(t){let n=r.readCreditAnalytics;return s(e,n,t,p)},async submitUsageBatch(t){let n=r.submitUsageBatch;return s(e,n,t,p)},async readUsageBatch(t){let n=r.readUsageBatch;return s(e,n,t,p)},async readLedger(t){let n=r.readLedger;return s(e,n,t,p)},async readCreditStatement(t){let n=r.readCreditStatement;return s(e,n,t,p)},async quoteBalance(t){let n=r.quoteBalance;return s(e,n,t,p)},async trackUsage(t){let n=r.trackUsage;return s(e,n,t,p)},async mutateBalance(t){let n=r.mutateBalance;return s(e,n,t,p)}}}function Qe(e){return{async listInvoiceTemplates(t={}){let n=r.listInvoiceTemplates;return s(e,n,t,p)},async previewInvoice(t){let n=r.previewInvoice;return s(e,n,t,p)},async createInvoice(t){let n=r.createInvoice;return s(e,n,t,p)},async prepareBillingAdjustment(t){let n=r.prepareBillingAdjustment;return s(e,n,t,p)},async manageInvoice(t){let n=r.manageInvoice;return s(e,n,t,p)},async readInvoiceOperation(t){let n=r.readInvoiceOperation;return s(e,n,t,p)},async listInvoices(t){let n=r.listInvoices;return s(e,n,t,p)},async getInvoice(t){let n=r.getInvoice;return s(e,n,t,p)},async setupPayment(t){let n=r.setupPayment;return s(e,n,t,p)},async readPaymentSetup(t){let n=r.readPaymentSetup;return s(e,n,t,p)},async readBillingInvoice(t){let n=r.readBillingInvoice;return s(e,n,t,p)},async previewRefund(t){let n=r.previewRefund;return s(e,n,t,p)},async refund(t){let n=r.refund;return s(e,n,t,p)},async readRefund(t){let n=r.readRefund;return s(e,n,t,p)}}}function Ye(e){return{async previewSubscriptionBatch(t){let n=r.previewSubscriptionBatch;return s(e,n,t,p)},async confirmSubscriptionBatch(t){let n=r.confirmSubscriptionBatch;return s(e,n,t,p)},async readSubscriptionBatch(t){let n=r.readSubscriptionBatch;return s(e,n,t,p)},async abandonSubscriptionBatch(t){let n=r.abandonSubscriptionBatch;return s(e,n,t,p)},async manageSubscriptionTrial(t){let n=r.manageSubscriptionTrial;return s(e,n,t,p)},async readSubscriptionTrial(t){let n=r.readSubscriptionTrial;return s(e,n,t,p)},async listSubscriptions(t){let n=r.listSubscriptions;return s(e,n,t,p)},async listPurchases(t){let n=r.listPurchases;return s(e,n,t,p)},async listSubscriptionConflicts(t){let n=r.listSubscriptionConflicts;return s(e,n,t,p)},async retrySubscriptionConflict(t){let n=r.retrySubscriptionConflict;return s(e,n,t,p)},async previewUpdate(t){let n=r.previewUpdate;return s(e,n,t,p)},async update(t){let n=r.update;return s(e,n,t,p)},async readSubscriptionUpdate(t){let n=r.readSubscriptionUpdate;return s(e,n,t,p)},async restoreNativePurchase(t){let n=r.restoreNativePurchase;return s(e,n,t,p)},async verifySubscriptions(t){let n=r.verifySubscriptions;return s(e,n,t,p)},async previewAttach(t){let n=r.previewAttach;return s(e,n,t,p)},async recordBillingEvent(t){let n=r.recordBillingEvent;return s(e,n,t,p)},async attach(t){let n=r.attach;return s(e,n,t,p)},async readSubscriptionOperation(t){let n=r.readSubscriptionOperation;return s(e,n,t,p)}}}function Je(e){return{async recordCouponRedemption(t){return s(e,r.recordCouponRedemption,t,{request:"Invalid Coupon redemption facts",parseResponse:p})},async grantOffer(t){let n=r.grantOffer;return s(e,{...n,request:n.request.refine(c=>!!c.customerId)},{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid offer grant",response:"Invalid offer response"})}}}function $e(e){return{...ze(e),...Ke(e),...Qe(e),...Ye(e),...Je(e)}}function Xe(e){return{async getFeatures(t={}){let n=r.getFeatures;return s(e,n,t,p)},async evaluateFeatures(t){let n=r.evaluateFeatures;return s(e,n,t,p)}}}function We(e){return{async trackEvents(t){let n=r.trackEvents;return s(e,n,t,p)}}}function Ze(e){return{async resolveContent(t){let n=r.resolveContent;return s(e,n,t,p)},async resolvePaywall(t){let n=r.resolvePaywall;return s(e,n,t,p)},async resolveOffering(t){let n=r.resolveOffering;return s(e,n,t,p)}}}function en(e){D(e.apiKey,"Secret API keys must stay on your backend");let n=F(e).request;return{async sendMessage(c){let i=r.sendMessage;return i.response.parse(await n(i.path,i.request.parse(c)))},async readMessage(c){let i=r.readMessage;return i.response.parse(await n(i.path,i.request.parse(c)))},...qe(n),...$e(n),...Xe(n),...We(n),...Ze(n)}}function yn(){if(typeof window<"u")throw new d("SERVER_ONLY","Guest identity is issued by your backend");let e=crypto.getRandomValues(new Uint8Array(32));return"gg_gc_"+btoa(String.fromCharCode(...e)).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}async function In(e,t){D(e.apiKey,"Renewal requires your backend");let n=F(e),c=Me.parse(await Y(e,await n.request("funnels",De.parse({...t,operation:"renew_run"}))));if(c.run.id!==t.runId)throw new d("INVALID_RESPONSE","Run renewal identity changed");return c}function nn(e){let t=He(e),n=u=>{throw new d("INVALID_RESPONSE",u)};t.nodes.size!==e.topology.nodes.length&&n("Duplicate local node identity"),t.nodes.get(e.topology.entry)?.type!=="entry"&&n("A local Funnel must start at Entry");let c=new Set(["entry","condition","feature","split","end","output"]);for(let u of t.nodes.values()){if(!c.has(u.type))throw new d("SERVER_REQUIRED","This Funnel requires authoritative server execution");if(u.type==="entry"&&u.id!==e.topology.entry&&n("Unexpected Entry node"),["entry","feature"].includes(u.type)&&!u.outputs.next&&n("Local next exit is unavailable"),u.type==="feature"){let a=u.resources.featureKey;(!a||!Object.hasOwn(e.evaluation.variables,u.writes.value)||!Object.hasOwn(t.features,a))&&n("Local Feature definition or declaration is unavailable")}if(u.type==="condition"){let a=e.conditions[u.id];(!a||!u.outputs.default||a.some((f,m)=>f.port!==`case:${m}`||!u.outputs[f.port]))&&n("Local Condition exits are unavailable")}if(u.type==="split"&&(!u.resources.experimentId||!Object.hasOwn(e.growth.experiments,u.resources.experimentId)||!u.outputs.notParticipating)&&n("Local Experiment definition or exit is unavailable"),u.type==="end"||u.type==="output"){let a=e.evaluation.terminals[u.id];if(!a)throw new d("SERVER_REQUIRED","Terminal resource delivery requires the server");Object.keys(u.outputs).length&&n("A terminal cannot have outgoing edges"),a.output?.type==="feature"&&!Object.hasOwn(t.features,a.output.featureKey)&&n("Terminal Feature definition is unavailable")}for(let a of Object.values(u.outputs))t.nodes.has(a)||n("Local target is unavailable")}let i=new Set,o=new Set;function l(u){if(o.has(u)&&n("Local graph contains a cycle"),!i.has(u)){o.add(u);for(let a of Object.values(t.nodes.get(u).outputs))l(a);o.delete(u),i.add(u)}}return l(e.topology.entry),i.size!==t.nodes.size&&n("Local graph contains unreachable nodes"),{evaluate(u){let a={},f=u.context;f.features=t.features,f.savedGroups=t.savedGroups;let m=()=>{f.attributes=Ae({declarations:e.evaluation.variables,attributes:u.attributes,parameters:u.parameters,answers:{},results:a,savedGroups:t.savedGroups})};m();let g=e.topology.entry,y=0;for(;;){let h=t.nodes.get(g);if(h.type==="end"||h.type==="output"){let v=e.evaluation.terminals[g],I=v.output,O=I?.type==="feature"?t.feature(I.featureKey,f):I?.type==="variable"?Re({source:"variable",key:I.key,...I.path?{path:I.path}:{}},{declarations:e.evaluation.variables,answers:{},results:a,parameters:u.parameters,attributes:u.attributes,savedGroups:t.savedGroups}):I?.value??null;return ae(e.evaluation.outputSchema,O)||n("Local output does not match its declaration"),{outcome:v.outcome,value:O}}if(y++>=e.evaluation.maxTransitions)throw new d("TRANSITION_LIMIT","Local Funnel transition budget exceeded");if(h.type==="entry")g=h.outputs.next;else{let v=t.evaluate(g,f);if(h.type==="feature"){let I=h.writes.value,O=v.value??null;ae(e.evaluation.variables[I],O)||n("Local Feature value does not match its declaration"),Ee(e.evaluation.variables,{writes:h.writes},{[I]:O}),a[I]=O,m()}g=v.target}}}}}import{z as tn}from"zod";function rn(e,t,n){let c=we.parse(e.attributes);if(["parameters","answers","results"].some(A=>Object.hasOwn(c,A)))throw new d("INVALID_REQUEST","Flow namespaces cannot be caller attributes");let i=Oe.parse(e.parameters??{}),o=tn.record(tn.string(),Se).parse(e.stickyBucketAssignmentDocs??{});for(let[A,R]of Object.entries(o))if(A!==`${R.attributeName}||${R.attributeValue}`||!Object.hasOwn(c,R.attributeName)||ve(c[R.attributeName])!==R.attributeValue)throw new d("INVALID_REQUEST","Sticky document identity does not match this session");let l=e.saveStickyBucketAssignmentDoc,u=e.onFeatureUsage,a=e.onExperimentViewed,f=e.onError,m=new Map,g=new Set,y={},h=Promise.resolve();function v(A){let R=h.then(()=>(n(),A()));return h=R.catch(()=>{}),R}function I(A){try{f?.(A)}catch{}}function O(A){try{let R=A();R&&typeof R.catch=="function"&&R.catch(I)}catch(R){I(R)}}async function M(){for(let[A,R]of m){if(n(),l)try{await l(structuredClone(R))}catch{throw new d("STICKY_SAVE_FAILED","Persist the pending Sticky assignment before using this evaluation")}n(),m.delete(A)}}return{evaluate(A={}){let R=A.track===!0;return v(async()=>{let C=await t();n(C);let N=new Set(g),B={...y},H=new Map,j=[],G={stickyBucketAssignmentDocs:structuredClone(o),saveStickyBucketAssignmentDoc(S){H.set(`${S.attributeName}||${S.attributeValue}`,structuredClone(S))},...R?{trackedExperiments:N,trackedFeatureUsage:B,onExperimentViewed(S,E){let _=structuredClone(S),q=structuredClone(E);a&&j.push(()=>a(structuredClone(_),structuredClone(q)))},onFeatureUsage(S,E){let _=structuredClone(E);u&&j.push(()=>u(S,structuredClone(_)))}}:{}},k=C.program.evaluate({attributes:c,parameters:i,context:G});n(C);for(let[S,E]of H)o[S]=E,m.set(S,E);await M(),n(C),R&&(g=N,y=B);for(let S of j)O(S);let b=C.configuration;return structuredClone({evaluationMode:"local",scope:b.scope,funnelId:b.funnelId,versionId:b.versionId,evaluationRevision:b.evaluationRevision,generation:b.growth.generation,...k})})},flush:()=>v(M),get stickyBucketAssignmentDocs(){return n(),structuredClone(o)}}}var gn=6e4;function $(e){if(typeof window<"u")throw new d("SERVER_ONLY","Local Funnel sessions run on your backend");let t=de.parse(e.scope),n=e.funnelId,c=e.load,i,o,l,u=0,a=g=>Date.now()>=g.expiresAt;async function f(){if(o)return o;let g=u;i=void 0;let y=(async()=>{let h=await c();if(g!==u)throw new d("IDENTITY_CHANGED","Local evaluator was reset");if(h&&typeof h=="object"&&"evaluationMode"in h&&h.evaluationMode==="remote")throw p(V,h),new d("EVALUATION_MODE","This Funnel requires remote decide");let v=p(Ne,h);if(g!==u)throw new d("IDENTITY_CHANGED","Local evaluator was reset");if(v.scope.projectId!==t.projectId||v.scope.environment!==t.environment||v.funnelId!==n)throw new d("SCOPE_MISMATCH","Local configuration scope changed");if(v.growth.scope.projectId!==t.projectId||v.growth.scope.environment!==t.environment||v.growth.expiresAt!==v.expiresAt)throw new d("INVALID_RESPONSE","GB configuration scope or expiry changed");let I=Math.min(Date.now()+gn,v.expiresAt?Date.parse(v.expiresAt):1/0);if(Date.now()>=I)throw new d("CONFIGURATION_EXPIRED","Refresh expired local rules");let O=JSON.stringify([t.projectId,t.environment,n,v.versionId,v.evaluationRevision,v.growth.generation]),M=[v.topology,v.conditions,v.evaluation,v.growth.features,v.growth.experiments,v.growth.savedGroups];if(l?.key===O&&!Ve(l.body,M))throw new d("INVALID_RESPONSE","Immutable local configuration identity changed");return l?.key!==O&&(l={key:O,body:M,program:nn(v)}),i={key:O,configuration:v,expiresAt:I,program:l.program},i})();o=y;try{return await y}finally{o===y&&(o=void 0)}}function m(){return o??(i&&!a(i)?Promise.resolve(i):f())}return{session(g){let y=u;return rn(g,m,h=>{if(e.assertUsable?.(),y!==u)throw new d("IDENTITY_CHANGED","Local evaluator was reset");if(h&&(a(h)||i?.key!==h.key))throw new d("CONFIGURATION_EXPIRED","Refresh local rules before using this result")})},async refresh(){return structuredClone((await f()).configuration)},reset(){u++,i=void 0,o=void 0,l=void 0}}}function hn(e,t){let n=e.snapshot?.generation,c=$({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t,load:()=>e.localFunnel(t),assertUsable:()=>e.assertFunnel(t)}),i=e.subscribe(()=>{let l=e.snapshot?.generation;e.fresh&&l!==n&&(n=l,c.refresh().catch(()=>{}))}),o=c.session;return Object.assign(c,{session(l){let u=o(l),a=u.evaluate;return Object.assign(u,{async evaluate(...f){return e.fresh||await e.refresh(),a(...f)}})},destroy(){i(),c.reset()}})}function vn(e){if(typeof window<"u")throw new d("SERVER_ONLY","Secret API keys must stay on the backend");return{start:t=>je(e,t)}}function on(e,t,n){return Le(e,t,n,Ue)}var U=class extends d{constructor(n,c){super("DECISION_PENDING","Decision is still pending; read this decision ID or retry the original request ID",202,c);this.decisionId=n;this.decisionRequestId=c}decisionId;decisionRequestId};async function X(e,t,n,c){let{decisionId:i,requestId:o}=e,l=e,u=250,a=0;for(;;){if(l.decisionId!==i||l.requestId!==o||l.decision&&!J(l.decision,t))throw new d("INVALID_RESPONSE","Decision request or customer changed");if(l.decision)return l.decision;if(l.status==="failed")throw new d("DECISION_FAILED","Decision execution failed",503,o);if(Date.now()>=n)throw new U(i,o);if(await new Promise(f=>setTimeout(f,Math.min(Math.max(u,a-Date.now()),n-Date.now()))),Date.now()>=n)throw new U(i,o);u=Math.min(1e3,u*2);try{l=await c(i,n)}catch(f){if(f instanceof d&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE","RATE_LIMITED"].includes(f.code)){a=Date.now()+(f.retryAfterSeconds??0)*1e3;continue}throw f}}}function pe(e){if("remoteEval"in e)throw new d("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");D(e.apiKey,"Funnel decisions are requested by your backend");let t,n,c=new Map;async function i(a,f){let m=a;m.status!=="pending"&&c.delete(m.decisionId);for(let g=0;g<32&&m.evaluation;g++){let y=m.evaluation;if(y.runId!==m.decisionId)throw new d("INVALID_RESPONSE","Local evaluation Run changed");let h=c.get(m.decisionId);if(!h&&y.type==="evaluate_segment"){let I=Pe.parse(await o({operation:"segment_configuration",funnelId:e.funnelId,versionId:y.versionId},f));if(I.configuration.scope.projectId!==e.scope.projectId||I.configuration.scope.environment!==e.scope.environment||I.configuration.funnelId!==e.funnelId||I.configuration.versionId!==y.versionId||I.configuration.evaluationRevision!==y.policyRevision)throw new d("SCOPE_MISMATCH","Original decision segment configuration changed");if(c.size>=128)throw new d("COMMAND_PENDING","Reconcile outstanding decisions first");h={operation:"commit_decision_segment",decisionId:m.decisionId,requestId:se(m.decisionId,y.visit,`segment:${y.revision}`),nodeId:y.nodeId,visit:y.visit,revision:y.revision,policyRevision:y.policyRevision,generation:I.configuration.growth.generation,...Ge(I.configuration,I.document,y)},c.set(m.decisionId,h)}if(!h){if(y.type!=="evaluate")throw new d("INVALID_RESPONSE","Unknown decision instruction");if((!n||n.versionId!==y.versionId||n.evaluationRevision!==y.policyRevision||n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())&&(n=V.parse(await o({operation:"configuration",funnelId:e.funnelId,versionId:y.versionId},f))),n.scope.projectId!==e.scope.projectId||n.scope.environment!==e.scope.environment||n.funnelId!==e.funnelId)throw new d("SCOPE_MISMATCH","Local evaluation configuration scope changed");if(n.evaluationMode!=="local"||n.versionId!==y.versionId||n.evaluationRevision!==y.policyRevision)throw new d("EVALUATION_MODE","Original Local evaluation policy is unavailable");if(c.size>=128)throw new d("COMMAND_PENDING","Reconcile outstanding Local decisions first");h={operation:"evaluate_decision",decisionId:m.decisionId,requestId:se(m.decisionId,y.visit,"evaluation"),nodeId:y.nodeId,visit:y.visit,revision:y.revision,receiptId:y.receiptId,policyRevision:y.policyRevision,generation:n.growth.generation,result:on(n,y.nodeId,y)},c.set(m.decisionId,h)}let v=P.parse(await o(h,f));if(v.decisionId!==a.decisionId||v.requestId!==a.requestId)throw new d("INVALID_RESPONSE","Decision identity changed during local evaluation");c.delete(m.decisionId),m=v}return m}async function o(a,f,m=!1){return F({...e,fetch:(y,h)=>{let v=new Headers(h?.headers);return v.set("Accept-Encoding","identity"),m&&v.set("Prefer","respond-async"),(e.fetch??globalThis.fetch)(y,{...h,headers:v})},timeoutMs:Math.min(e.timeoutMs??1e4,f?Math.max(1,f-Date.now()):12e4)}).request("funnels",a)}async function l(a,f){let m=P.parse(await o(Q.parse({operation:"read_decision",decisionId:a}),f));if(m.decisionId!==a)throw new d("INVALID_RESPONSE","Decision identity changed");return i(m,f)}async function u(a,f,m=!1){let g=Q.options[0].parse({...a,operation:"decide",funnelId:e.funnelId}),y;try{y=P.parse(await o(g,f,m))}catch(h){throw h instanceof d&&["TIMEOUT","NETWORK_ERROR","SERVICE_UNAVAILABLE"].includes(h.code)?new d("DECISION_ACCEPTANCE_UNKNOWN","Decision acceptance is unknown; retry the original request ID and input",h.status,a.requestId):h}if(y.requestId!==a.requestId||y.decision&&!J(y.decision,g.customer))throw new d("INVALID_RESPONSE","Decision request or customer changed");return{response:await i(y,f),customer:g.customer}}return{local(){return t??=$({scope:e.scope,funnelId:e.funnelId,load:()=>o({operation:"local_configuration",funnelId:e.funnelId})})},async configuration(){let a=V.parse(await o({operation:"configuration",funnelId:e.funnelId}));if(a.scope.projectId!==e.scope.projectId||a.scope.environment!==e.scope.environment||a.funnelId!==e.funnelId)throw new d("SCOPE_MISMATCH","Configuration scope changed");return a},features(a={}){return ue({...a,scope:e.scope,load:async()=>Ce.parse(await o({operation:"feature_config",funnelId:e.funnelId}))})},read:a=>l(a),async submit(a){return(await u(a,void 0,!0)).response},async decide(a){let f=Date.now()+3e4,m=await u(a,f);return X(m.response,m.customer,f,l)},async reportUsed(a){let f=be.parse(await o(Q.parse({...a,operation:"report_used"})));if(f.decisionId!==a.decisionId||f.eventId!==a.eventId)throw new d("INVALID_RESPONSE","Usage receipt identity changed");return f}}}function wn(e){D(e.apiKey,"Native receipts are verified by your backend","Server API key required");let t=F({...e,timeoutMs:e.timeoutMs??35e3});return{async recover(n){let c=Be.parse(n);if(c.orderId!==c.receiptId)throw new d("INVALID_REQUEST","Native recovery requires the accepted commercial intent");let i=c.nativeEvidence,o={requestId:c.requestId,customerToken:c.customerToken,purchaseIntentId:c.orderId,...i===null?{intent:"read"}:i.provider==="apple"?{provider:"apple",signedTransaction:i.signedTransaction}:{provider:"google",purchaseToken:i.purchaseToken}},l=r.restoreNativePurchase.response.parse(await t.request(r.restoreNativePurchase.path,o));if(l.operation.requestId!==c.requestId||l.operation.purchaseIntentId!==c.orderId)throw new d("INVALID_RESPONSE","Native receipt request identity changed");let u=ke.parse({scope:l.scope,requestId:c.requestId,orderId:l.operation.orderId,receiptId:l.operation.orderId,orderStatus:l.operation.status,refunded:l.operation.refunded,...l.operation.completion===null?{}:{nativeCompletion:{orderId:l.operation.orderId,receiptId:l.operation.orderId,...l.operation.completion}}});if(u.requestId!==c.requestId||u.orderId!==c.orderId||u.receiptId!==c.receiptId||u.scope.projectId!==e.scope.projectId||u.scope.environment!==e.scope.environment)throw new d("INVALID_RESPONSE","Current order receipt scope changed");return u}}}import{z as Sn}from"zod";var x=Sn.number().int().min(0).max(Number.MAX_SAFE_INTEGER);function En(e,t){let n=x.parse(e.inputTokens.total),c=x.parse(e.outputTokens.total),i=x.parse(e.inputTokens.cacheRead??0),o=x.parse(e.inputTokens.cacheWrite??0),l=x.parse(e.outputTokens.reasoning??0);if(i+o>n||l>c||e.inputTokens.noCache!==void 0&&x.parse(e.inputTokens.noCache)!==n-i-o||e.outputTokens.text!==void 0&&x.parse(e.outputTokens.text)!==c-l)throw new d("AI_USAGE_UNAVAILABLE","Provider token counts do not conserve total usage");return{input:n-i-o,cache_read:i,cache_write:o,output:t==="output"?c:c-l,reasoning:t==="separate"?l:0,input_audio:0,output_audio:0}}function Rn(e){if(typeof window<"u")throw new d("SERVER_ONLY","AI usage belongs on the trusted backend");if(!e.modelId||!["output","separate"].includes(e.reasoning))throw new d("INVALID_REQUEST","Model ID and reasoning pricing are required");async function t(c){await e.persist({context:c,modelId:e.modelId,usage:null,tokens:null,quote:null,receipt:null,phase:"incomplete"})}async function n(c,i){let o={context:c,modelId:e.modelId,usage:i,tokens:null,quote:null,receipt:null,phase:"captured"};await e.persist(o);let l=e.mapTokens?e.mapTokens(i):En(i,e.reasoning),u=await e.pricing.quoteTokens({modelId:e.modelId,tokens:l});await e.persist({...o,tokens:l,quote:u,phase:"quoted"});let a=await e.pricing.trackTokens(e.client,{...c,quote:u});if(!a.receipt.accepted)throw new d("AI_BALANCE_REJECTED","AI usage was captured but the balance operation was rejected");await e.persist({...o,tokens:l,quote:u,receipt:a,phase:"settled"})}return{specificationVersion:"v4",async wrapGenerate({doGenerate:c}){let i=await e.context(),o;try{o=await c()}catch(l){throw await t(i),l}return await n(i,o.usage),o},async wrapStream({doStream:c}){let i=await e.context(),o;try{o=await c()}catch(m){throw await t(i),m}let l=!1,u=!1,a=o.stream.getReader();async function f(){l||u||(u=!0,await t(i))}return{...o,stream:new ReadableStream({async pull(m){try{let{value:g,done:y}=await a.read();if(y){if(!l)throw await f(),new d("AI_USAGE_UNAVAILABLE","Stream ended without final usage; no amount was invented");m.close();return}if(g.type==="finish"){if(l)throw new d("AI_USAGE_UNAVAILABLE","Provider sent more than one final usage record");l=!0,await n(i,g.usage)}m.enqueue(g)}catch(g){try{await f()}finally{m.error(g),await a.cancel(g)}}},async cancel(m){try{await f()}finally{await a.cancel(m)}}})}}}}function Cn(e){D(e.apiKey,"Funnel receipts are sent by your backend");let t=F(e);return{async signal(n){let c=ie.parse({...n,operation:"signal"}),i=_e.parse(await t.request("funnels",c));if(i.runId!==n.runId||i.eventId!==n.eventId||i.scope.projectId!==e.scope.projectId||i.scope.environment!==e.scope.environment)throw new d("INVALID_RESPONSE","Receipt identity changed");return i},async readResults(n){let c=ie.parse({operation:"read_results",runId:n}),i=Fe.parse(await t.request("funnels",c));if(i.runId!==n||i.scope.projectId!==e.scope.projectId||i.scope.environment!==e.scope.environment)throw new d("INVALID_RESPONSE","Result identity changed");return i}}}function An(e){if("remoteEval"in e)throw new d("INVALID_REQUEST","Configure evaluation mode on the Funnel; remoteEval is not supported");D(e.apiKey,"Campaign entry requires your backend");let t=F({...e,timeoutMs:e.timeoutMs??35e3});return{async decide(n){let c=Date.now()+(e.timeoutMs??3e4),i=ce.parse({...n,funnelId:e.funnelId,operation:"campaign_decide"}),o=F({...e,timeoutMs:Math.min(e.timeoutMs??35e3,Math.max(1,c-Date.now()))}),l=P.parse(await o.request("funnels",i));if(l.scope.projectId!==e.scope.projectId||l.scope.environment!==e.scope.environment)throw new d("SCOPE_MISMATCH","Campaign scope changed");return X(l,i.customer,c,(u,a)=>pe({...e,timeoutMs:Math.min(e.timeoutMs??1e4,Math.max(1,a-Date.now()))}).read(u))},async start(n){let c=ce.parse({...n,funnelId:e.funnelId,operation:"campaign_start"}),i=xe.parse(await t.request("funnels",c)),o=Te.parse("suppressed"in i?i:await Y(e,i));if(o.scope.projectId!==e.scope.projectId||o.scope.environment!==e.scope.environment)throw new d("SCOPE_MISMATCH","Campaign scope changed");if(!("suppressed"in o)&&(o.run.source.id!==e.funnelId||!o.customerId||c.customer.type==="id"&&o.customerId!==c.customer.value))throw new d("INVALID_RESPONSE","Campaign Funnel or Customer changed");return o}}}import{z as On}from"zod";var w=class extends Error{constructor(n,c=409,i=!1,o="fix_request"){super(n);this.code=n;this.status=c;this.retryable=i;this.recovery=o}code;status;retryable;recovery};function _n(e){if(typeof window<"u")throw new Error("Merchant bridge credentials require a trusted server");let t=ye.parse(e.manifest),n={projectId:t.projectId,environmentId:t.environmentId,environment:t.environment},c=t.capabilities.some(i=>["purchases","subscription_changes","refunds","operation_status"].includes(i));for(let[i,o]of Object.entries(ee))if(o.command&&t.capabilities.includes(i)&&!(i==="catalog"&&t.catalog==="static")&&!e.handlers[o.command])throw new Error(`Missing merchant command handler: ${o.command}`);if(c&&(!e.resolveOperationAuthority||!e.handlers["operation.read"]||!t.capabilities.includes("operation_status")))throw new Error("Merchant operations require fresh Longplay authority and an operation lookup handler");return async function(o){let l=crypto.randomUUID(),u="bridge.ping",a,f=async(m,g,y=!1)=>{let h=JSON.stringify({bridgeVersion:Z,requestId:l,command:u,scope:n,[y?"error":"data"]:m});if(new TextEncoder().encode(h).byteLength>262144)throw new Error("Merchant response exceeds limit");return new Response(h,{status:g,headers:{"Content-Type":"application/json","Cache-Control":"private, no-store","X-Request-Id":l,...a?await re(h,a,"response"):{}}})};try{if(o.headers.get("X-Indiana-Merchant-Bridge-Version")!==String(Z)||o.method!=="POST"||new URL(o.url).pathname!==fe)throw new w("MERCHANT_BRIDGE_INVALID_REQUEST",400);if(!/^application\/json(?:\s*;|$)/i.test(o.headers.get("Content-Type")??""))throw new w("MERCHANT_BRIDGE_INVALID_REQUEST",400);let m=o.body?.getReader();if(!m)throw new w("MERCHANT_BRIDGE_INVALID_REQUEST",400);let g=new TextDecoder("utf-8",{fatal:!0}),y="",h=0;try{for(;;){let E=await m.read();if(E.done)break;if(h+=E.value.byteLength,h>16384)throw new w("MERCHANT_BRIDGE_INVALID_REQUEST",413);y+=g.decode(E.value,{stream:!0})}y+=g.decode()}finally{await m.cancel().catch(()=>{}),m.releaseLock()}let v=he.safeParse(JSON.parse(y));if(!v.success)throw new w("MERCHANT_BRIDGE_INVALID_REQUEST",400);let I=v.data;if(l=I.requestId,u=I.command,Object.keys(n).some(E=>I.scope[E]!==n[E]))throw new w("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);let O=I.command==="bridge.ping"||I.command==="bridge.describe",M=I.command==="catalog.read";if((O||M||o.headers.has(te))&&(a=e.authentication.find(E=>E.keyId===o.headers.get(te)),!a||!await oe(y,o.headers,a,"request")))throw a=void 0,new w("MERCHANT_BRIDGE_AUTHENTICATION_FAILED",401);if(I.command==="bridge.ping")return f(ne["bridge.ping"].parse(I.data),200);if(I.command==="bridge.describe")return f(t,200);let A=Object.entries(ee).find(([,E])=>E.command===I.command);if(!A||!t.capabilities.includes(A[0]))throw new w("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let R=e.handlers[I.command];if(!R)throw new w("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);if(!M&&o.headers.has("Cookie")&&(o.headers.get("Origin")!==new URL(o.url).origin||["cross-site","same-site"].includes(o.headers.get("Sec-Fetch-Site")??"")))throw new w("MERCHANT_BRIDGE_FORBIDDEN",403);let C=M?{kind:"service"}:await e.authorize(o,I),N=C.kind,B=["purchase.execute","subscription.change","refund.execute"].includes(I.command),H=B||I.command==="operation.read";if(!(H&&a!==void 0&&N==="service")&&(I.command==="refund.execute"?N!=="administrator":!M&&N!=="user"))throw new w("MERCHANT_BRIDGE_FORBIDDEN",403);if(C.kind==="user"&&["purchase.execute","operation.read","subscription.change","customer.commerce.read","presentation.report"].includes(I.command)&&!On.uuid().safeParse(C.customerId).success)throw new w("MERCHANT_BRIDGE_UNAUTHENTICATED",401);let G=R,k=ne[I.command].parse(I.data),b={request:o,command:I.command,scope:n,principal:C},S;if(H){let E=z.parse(k);if(C.kind==="user"&&C.customerId!==E.customerId)throw new w("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!e.resolveOperationAuthority)throw new w("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501);let _=K.parse(await e.resolveOperationAuthority(E,b));if(_.operationId!==E.operationId||_.customerId!==E.customerId||Object.keys(n).some(T=>_.scope[T]!==n[T]))throw new w("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);b.authority=_;let q=I.command==="purchase.execute"?"purchase":I.command==="subscription.change"?"subscription_change":I.command==="refund.execute"?"refund":_.instruction.type;if(_.instruction.type!==q)throw new w("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(!B)S=W.parse(await G(k,b));else{if(_.confirmedAt===null)throw new w("MERCHANT_BRIDGE_OPERATION_NOT_CONFIRMED",409);let T=W.parse(await e.handlers["operation.read"](E,{...b,command:"operation.read"}));if(T.operationId!==E.operationId||T.customerId!==E.customerId)throw new w("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if(T.lookup==="found")S=T.execution;else{if(!_.initialExecutionAllowed)throw new w("MERCHANT_BRIDGE_RECOVERY_REQUIRED",409,!1,"recover_operation");if(Date.parse(_.instruction.expiresAt)<=Date.now())throw new w("MERCHANT_BRIDGE_OPERATION_EXPIRED",409,!1,"reload_state");if(!t.capabilities.includes("billing_records")||me(_.instruction).some(L=>!t.billingEvents.some(an=>an===L))||le(_.instruction).some(L=>!t.profiles.includes(L)))throw new w("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");try{S=Ie.parse(await G(k,b))}catch(L){throw L instanceof w?L:new w("MERCHANT_BRIDGE_RESULT_UNKNOWN",503,!1,"recover_operation")}}if(S.type!==q)throw new w("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}}else S=ge[I.command].parse(await G(k,b));if(C.kind==="user"){if("nativeUserId"in S&&S.nativeUserId!==C.nativeUserId)throw new w("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("customerId"in S&&S.customerId!==C.customerId)throw new w("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("session"in S&&C.customerId&&S.session.customerId!==C.customerId)throw new w("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);if("presentation"in S&&S.presentation&&C.customerId&&S.presentation.customerId!==C.customerId)throw new w("MERCHANT_BRIDGE_SCOPE_MISMATCH",403)}if("operationId"in S&&(S.operationId!==z.parse(I.data).operationId||S.customerId!==z.parse(I.data).customerId))throw new w("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return f(S,B&&("paymentStatus"in S&&["pending","unknown"].includes(S.paymentStatus)||"status"in S&&["pending","unknown","scheduled"].includes(S.status))?202:200)}catch(m){let g=m instanceof w?m:m instanceof SyntaxError?new w("MERCHANT_BRIDGE_INVALID_REQUEST",400):new w("MERCHANT_BRIDGE_INVALID_RESPONSE",500);return f({code:g.code,message:g.code,retryable:g.retryable,recovery:g.recovery},g.status,!0)}}}function Fn(e){return async(t,n)=>{let c=()=>e.readSubscriptionOperation(t),i=()=>e.readSubscriptionUpdate(t),o=()=>e.readRefund(t),l=n.command==="purchase.execute"?[c]:n.command==="subscription.change"?[i]:n.command==="refund.execute"?[o]:[c,i,o];for(let u of l)try{let a=await u(),f="authority"in a.operation?a.operation.authority:void 0;if(!f)throw new w("MERCHANT_BRIDGE_CAPABILITY_UNSUPPORTED",501,!1,"check_availability");let m=K.parse(f);if(m.customerId!==t.customerId||m.operationId!==t.operationId||Object.keys(n.scope).some(g=>m.scope[g]!==n.scope[g]))throw new w("MERCHANT_BRIDGE_SCOPE_MISMATCH",403);return m}catch(a){if(n.command==="operation.read"&&a instanceof d&&a.code==="NOT_FOUND")continue;throw a}throw new w("MERCHANT_BRIDGE_OPERATION_NOT_FOUND",404,!1,"reload_state")}}export{U as FunnelDecisionTimeoutError,d as IndianaError,d as LongplayError,w as MerchantBridgeHandlerError,dn as aiPriceSnapshotSchema,ln as aiTokenQuoteSchema,mn as createAiPricing,Rn as createAiUsageMiddleware,sn as createConfigurationSync,fn as createConfiguredAiPricing,ue as createFeatureClient,An as createFunnelCampaignClient,pe as createFunnelDecisionClient,$ as createFunnelLocalEvaluator,Cn as createFunnelOrchestrationClient,un as createFunnelStartClient,yn as createGuestToken,en as createIndianaServer,pn as createLocalFunnelClient,en as createLongplayServer,Fn as createMerchantBridgeAuthorityResolver,_n as createMerchantBridgeHandler,wn as createNativeReceiptClient,vn as createPaywallStartClient,hn as createSynchronizedFunnelLocalEvaluator,cn as evaluateFunnelNode,In as renewFunnelRun,re as signMerchantBridgeMessage,oe as verifyMerchantBridgeMessage};
@@ -0,0 +1 @@
1
+ import{b as a,c as b}from"./chunk-KMCA4Y2Q.js";import"./chunk-MPE7OZTE.js";export{b as applyVisualVariation,a as safeVisualMutation};
package/dist/visual.js CHANGED
@@ -1 +1 @@
1
- import{a as le,c as ce}from"./chunk-RE6BIFLN.js";import{b as oe}from"./chunk-CLXORAOK.js";import{a as ve,b as ee,c as ae,d as se}from"./chunk-EARSGITJ.js";import{a as N,b as de,c as J,e as ue}from"./chunk-VMM3GA3L.js";import{a as ne,b as te,c as ie,d as re}from"./chunk-HOW7NIIR.js";import"./chunk-DSPLGTQI.js";import"./chunk-G56XGVMS.js";import"./chunk-MRN4HP4W.js";import"./chunk-7DXL3LHT.js";import{e as X,g as Z,i as R}from"./chunk-XSVQHPQT.js";import{z as s}from"zod";var _="indiana-visual-diagnostics-v1",be=s.strictObject({environmentId:s.string().uuid(),release:s.string().regex(/^[a-f0-9]{64}$/).nullable(),generation:s.string().regex(/^[a-f0-9]{64}$/).nullable(),publishedGeneration:s.string().regex(/^[a-f0-9]{64}$/).nullable(),checkedAt:s.string().datetime(),origin:s.string().url(),pathname:s.string().max(2048),urlMatches:s.boolean(),stopped:s.boolean(),rows:s.array(s.strictObject({changeId:s.string().regex(/^[a-f0-9]{64}$/),experimentKey:s.string().max(256),variationKey:s.string().max(256),inExperiment:s.boolean(),fingerprint:s.string().regex(/^[a-f0-9]{64}$/),status:s.enum(["inactive","waiting","partial","applied","mismatch","no_changes","unavailable","error"]),total:s.number().int().min(0).max(600),applied:s.number().int().min(0).max(600)})).max(100)});function pe(e){let l=n=>Array.isArray(n)?"["+n.map(l).join(",")+"]":n&&typeof n=="object"?"{"+Object.entries(n).filter(([,d])=>d!==void 0).sort(([d],[y])=>d.localeCompare(y)).map(([d,y])=>JSON.stringify(d)+":"+l(y)).join(",")+"}":JSON.stringify(n);return l({css:e.css,js:e.js,domMutations:e.domMutations,...e.renderGuard?{renderGuard:e.renderGuard}:{}})}function ge(e){let l=new URL(e.baseUrl),n=l.origin==="https://api.longplayai.com"||l.origin==="https://api.dev.longplayai.com"?l.hostname.slice(4):void 0,d=e.origins??(n?[`https://${n}`,`https://app.${n}`]:[]),y=new Set(d.filter(t=>{try{let i=new URL(t);return i.origin===t&&(i.protocol==="https:"||i.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(i.hostname))}catch{return!1}})),v=!1,I=!1,E=0,D=async t=>{if(v||I||!t.source||!y.has(t.origin)||!t.data||typeof t.data!="object")return;let i=t.data;if(!(i.channel!==_||i.type!=="inspect"||i.environmentId!==e.environmentId||typeof i.nonce!="string"||!/^[a-f0-9-]{36}$/i.test(i.nonce)||typeof i.changeId!="string"||!/^[a-f0-9]{64}$/.test(i.changeId)||typeof i.url!="string"||i.url.length>2048||Date.now()-E<250)){try{if(new URL(i.url).origin!==location.origin)return}catch{return}I=!0,E=Date.now();try{let x=await e.inspect(i.changeId,i.url);!v&&x.rows.some(k=>k.changeId===i.changeId)&&t.source.postMessage({channel:_,type:"result",nonce:i.nonce,snapshot:x},t.origin)}finally{I=!1}}},u=t=>{D(t).catch(()=>{})};return window.addEventListener("message",u),()=>{v=!0,window.removeEventListener("message",u)}}var T=e=>!!e&&typeof e=="object"&&!Array.isArray(e),V=(e,l)=>typeof e=="string"&&e.length<=l,we=e=>typeof e=="string"&&(["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e));function Ie(e){if(!T(e)||!V(e.css??"",1e5)||!V(e.js??"",1e5)||!Array.isArray(e.domMutations??[])||Array.isArray(e.domMutations)&&e.domMutations.length>200)throw new Error("Invalid visual variation");let l=e.domMutations??[];for(let n of l)if(!T(n)||!V(n.selector,2048)||!n.selector||!we(n.attribute)||!["set","append","remove"].includes(String(n.action))||n.value!==void 0&&!V(n.value,5e4)||n.parentSelector!==void 0&&!V(n.parentSelector,2048)||n.insertBeforeSelector!==void 0&&!V(n.insertBeforeSelector,2048))throw new Error("Invalid visual mutation");return{css:e.css??"",js:e.js??"",domMutations:l,...e.renderGuard===void 0?{}:{renderGuard:oe(e.renderGuard)}}}function K(e){if(!T(e)||typeof e.environmentId!="string"||typeof e.trackExposures!="boolean"||!/^[-a-f0-9]{36}$/i.test(e.environmentId)||typeof e.generation!="string"||!/^[a-f0-9]{64}$/.test(e.generation)||!Array.isArray(e.experiments)||e.experiments.length>100||!T(e.savedGroups))throw new Error("Invalid visual experiment payload");let l=e.experiments.map(n=>{if(!T(n)||!["key","changeId"].every(d=>typeof n[d]=="string"&&n[d])||!/^[a-f0-9]{64}$/.test(String(n.changeId))||["namespace","status","groups","url"].some(d=>Object.hasOwn(n,d))||n.hashVersion!==void 0&&n.hashVersion!==2||!Array.isArray(n.variations)||n.variations.length<2||n.variations.length>20||n.urlPatterns!==void 0&&!Array.isArray(n.urlPatterns))throw new Error("Invalid visual experiment");return{...n,variations:n.variations.map(Ie)}});return{...e,experiments:l}}function Ce(e){let l=ie(e.baseUrl);if(e.appManifestRelease!==void 0&&!/^[a-f0-9]{64}$/.test(e.appManifestRelease))throw new Error("Invalid IAM manifest digest");if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("Invalid App environment ID");let n=e.fetch??globalThis.fetch.bind(globalThis),d=J(n),y=J(n),v=`${l}/api/v1/visual-experiments/${e.environmentId}`,I=e.appManifestRelease?`${v}?iam=${e.appManifestRelease}`:v,E=ne(e.deviceIdCookie??"indiana_did"),D=te(),u=null,t=!1,i=!1,x="",k={...e.attributes??{}},G,q,$=0,m=new Map,O=new Map,L=new Set,P=[],C,F,b;function j(){clearTimeout(F),b?.remove(),b=void 0}function A(o=!1){clearTimeout(C),C=void 0;let c=P.splice(0,20);return c.length?de(n,`${v}/events`,JSON.stringify({events:c}),o).catch(p=>e.log?.("Visual exposure not sent",{error:p})):Promise.resolve()}function B(o,c){let p=R(o,c);L.has(p)||e.trackExposures===!1||u?.trackExposures===!1||t||(L.add(p),P.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:E,...D?{sessionId:D}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:o.key,variationKey:c.key}),P.length>=20?A():C??=setTimeout(()=>{A()},1e3))}function fe(o){if(!u||t)return;let c=new Set,p={onExperimentViewed:(r,g)=>{c.add(R(r,g))},url:location.href,attributes:{...ue(E,location),...k,indianaAppManifestRelease:e.appManifestRelease??null},savedGroups:X(u.savedGroups),log:e.log},h=new Set;for(let r of u.experiments){if(ae(`${e.environmentId}:${r.key}`))continue;let g=r;try{let a=Z(g,p);if(O.set(r.changeId,a),!a.inExperiment)continue;h.add(r.changeId);let w=JSON.stringify([a.key,a.value]),U=m.get(r.changeId);if(U?.signature===w){c.has(R(g,a))&&o.push(()=>{U.applied()&&B(g,a)});continue}m.get(r.changeId)?.revert(),m.delete(r.changeId);let M=ce(a.value,{requireUniqueTargets:!!e.appManifestRelease&&Array.isArray(r.condition?.$and)&&r.condition.$and.some(f=>f!==null&&typeof f=="object"&&!Array.isArray(f)&&f.indianaAppManifestRelease===e.appManifestRelease),boundVariations:r.variations,allowJs:e.disableJsInjection===!1,nonce:e.nonce,onApplied:()=>{c.has(R(g,a))&&B(g,a)},onError:f=>e.log?.("Visual experiment stopped",{experiment:r.key,changeId:r.changeId,variation:a.key,error:String(f)}),onTargetStatus:e.log?f=>e.log?.("Visual target status changed",{experiment:r.key,changeId:r.changeId,variation:a.key,...f}):void 0});m.set(r.changeId,{signature:w,revert:M.revert,applied:()=>M.applied,inspect:()=>M.inspect()})}catch(a){e.log?.("Skipping visual experiment",{experiment:r.key,error:String(a)})}}for(let[r,g]of m)h.has(r)||(g.revert(),m.delete(r));j()}let S=()=>{let o=[];le(()=>fe(o));for(let c of o)c()};async function H(){let o=++$,c;try{c=await d.read(I,N)}catch(h){if(t||o!==$)return!1;throw h}let p=K(c);if(p.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Visual payload scope changed");return t||o!==$?!1:(u=p,!0)}let me=()=>{x!==location.href&&(x=location.href,S())},z=()=>{A(!0)},W=()=>{G||t||(G=re(me),addEventListener("pagehide",z),x=location.href)};async function Y(o,c){let p=location.href,h=u,r=[],g=null;if(!t)try{let a=K(await y.read(I,N));a.environmentId===e.environmentId&&(g=a.generation)}catch{}for(let a of h?.experiments??[]){if(o&&a.changeId!==o)continue;let w=O.get(a.changeId);if(!w)continue;let U=new TextEncoder().encode(pe(w.value)),M=[...new Uint8Array(await crypto.subtle.digest("SHA-256",U))].map(he=>he.toString(16).padStart(2,"0")).join(""),f=m.get(a.changeId)?.inspect()??{status:"inactive",total:0,applied:0};r.push({changeId:a.changeId,experimentKey:a.key,variationKey:w.key,inExperiment:w.inExperiment,fingerprint:M,...f})}return{environmentId:e.environmentId,release:e.appManifestRelease??null,generation:h?.generation??null,publishedGeneration:g,checkedAt:new Date().toISOString(),origin:location.origin,pathname:location.pathname,urlMatches:location.href===p&&(!c||c===p)&&h===u,stopped:t,rows:r}}let Q,ye=se(()=>{i&&!t&&S()});return{async start(){if(!(i||t)){i=!0,e.appManifestRelease&&(q=ee(e.appManifestRelease)),e.antiFlicker&&(b=document.createElement("style"),e.nonce&&(b.nonce=e.nonce),b.textContent="body { visibility: hidden !important }",document.head.append(b),F=setTimeout(j,Math.min(3e3,Math.max(0,e.antiFlickerTimeout??1e3))));try{if(!await H()||t)return;W(),S()}finally{j(),t||(Q=ge({environmentId:e.environmentId,baseUrl:l,origins:e.diagnosticsOrigins,inspect:Y}))}}},async refresh(){t||await H()&&(i&&W(),S())},setAttributes(o){k={...o},S()},flush:()=>A(),getDiagnostics:Y,getResults(){return new Map(O)},get generation(){return u?.generation??null},destroy(){t=!0,ye(),Q?.(),$++,d.destroy(),y.destroy(),G?.(),q?.destroy(),removeEventListener("pagehide",z),j();for(let o of m.values())o.revert();m.clear(),A(!0),u=null,O.clear(),L.clear(),k={}}}}export{Ce as createVisualExperiments,ve as loadAppManifestRelease};
1
+ import{a as le,c as ce}from"./chunk-KMCA4Y2Q.js";import{b as oe}from"./chunk-MPE7OZTE.js";import{a as ve,b as ee,c as ae,d as se}from"./chunk-EARSGITJ.js";import{a as N,b as de,c as J,e as ue}from"./chunk-OHYC6K3A.js";import{a as ne,b as te,c as ie,d as re}from"./chunk-ABL2UMTI.js";import"./chunk-DSPLGTQI.js";import"./chunk-O3FHA25D.js";import"./chunk-MSOVR5KN.js";import"./chunk-XVT5BKJW.js";import{e as X,g as Z,i as R}from"./chunk-BI4R5Q7Z.js";import{z as s}from"zod";var _="indiana-visual-diagnostics-v1",be=s.strictObject({environmentId:s.string().uuid(),release:s.string().regex(/^[a-f0-9]{64}$/).nullable(),generation:s.string().regex(/^[a-f0-9]{64}$/).nullable(),publishedGeneration:s.string().regex(/^[a-f0-9]{64}$/).nullable(),checkedAt:s.string().datetime(),origin:s.string().url(),pathname:s.string().max(2048),urlMatches:s.boolean(),stopped:s.boolean(),rows:s.array(s.strictObject({changeId:s.string().regex(/^[a-f0-9]{64}$/),experimentKey:s.string().max(256),variationKey:s.string().max(256),inExperiment:s.boolean(),fingerprint:s.string().regex(/^[a-f0-9]{64}$/),status:s.enum(["inactive","waiting","partial","applied","mismatch","no_changes","unavailable","error"]),total:s.number().int().min(0).max(600),applied:s.number().int().min(0).max(600)})).max(100)});function pe(e){let l=n=>Array.isArray(n)?"["+n.map(l).join(",")+"]":n&&typeof n=="object"?"{"+Object.entries(n).filter(([,d])=>d!==void 0).sort(([d],[y])=>d.localeCompare(y)).map(([d,y])=>JSON.stringify(d)+":"+l(y)).join(",")+"}":JSON.stringify(n);return l({css:e.css,js:e.js,domMutations:e.domMutations,...e.renderGuard?{renderGuard:e.renderGuard}:{}})}function ge(e){let l=new URL(e.baseUrl),n=l.origin==="https://api.longplayai.com"||l.origin==="https://api.dev.longplayai.com"?l.hostname.slice(4):void 0,d=e.origins??(n?[`https://${n}`,`https://app.${n}`]:[]),y=new Set(d.filter(t=>{try{let i=new URL(t);return i.origin===t&&(i.protocol==="https:"||i.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(i.hostname))}catch{return!1}})),v=!1,I=!1,E=0,D=async t=>{if(v||I||!t.source||!y.has(t.origin)||!t.data||typeof t.data!="object")return;let i=t.data;if(!(i.channel!==_||i.type!=="inspect"||i.environmentId!==e.environmentId||typeof i.nonce!="string"||!/^[a-f0-9-]{36}$/i.test(i.nonce)||typeof i.changeId!="string"||!/^[a-f0-9]{64}$/.test(i.changeId)||typeof i.url!="string"||i.url.length>2048||Date.now()-E<250)){try{if(new URL(i.url).origin!==location.origin)return}catch{return}I=!0,E=Date.now();try{let x=await e.inspect(i.changeId,i.url);!v&&x.rows.some(k=>k.changeId===i.changeId)&&t.source.postMessage({channel:_,type:"result",nonce:i.nonce,snapshot:x},t.origin)}finally{I=!1}}},u=t=>{D(t).catch(()=>{})};return window.addEventListener("message",u),()=>{v=!0,window.removeEventListener("message",u)}}var T=e=>!!e&&typeof e=="object"&&!Array.isArray(e),V=(e,l)=>typeof e=="string"&&e.length<=l,we=e=>typeof e=="string"&&(["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e));function Ie(e){if(!T(e)||!V(e.css??"",1e5)||!V(e.js??"",1e5)||!Array.isArray(e.domMutations??[])||Array.isArray(e.domMutations)&&e.domMutations.length>200)throw new Error("Invalid visual variation");let l=e.domMutations??[];for(let n of l)if(!T(n)||!V(n.selector,2048)||!n.selector||!we(n.attribute)||!["set","append","remove"].includes(String(n.action))||n.value!==void 0&&!V(n.value,5e4)||n.parentSelector!==void 0&&!V(n.parentSelector,2048)||n.insertBeforeSelector!==void 0&&!V(n.insertBeforeSelector,2048))throw new Error("Invalid visual mutation");return{css:e.css??"",js:e.js??"",domMutations:l,...e.renderGuard===void 0?{}:{renderGuard:oe(e.renderGuard)}}}function K(e){if(!T(e)||typeof e.environmentId!="string"||typeof e.trackExposures!="boolean"||!/^[-a-f0-9]{36}$/i.test(e.environmentId)||typeof e.generation!="string"||!/^[a-f0-9]{64}$/.test(e.generation)||!Array.isArray(e.experiments)||e.experiments.length>100||!T(e.savedGroups))throw new Error("Invalid visual experiment payload");let l=e.experiments.map(n=>{if(!T(n)||!["key","changeId"].every(d=>typeof n[d]=="string"&&n[d])||!/^[a-f0-9]{64}$/.test(String(n.changeId))||["namespace","status","groups","url"].some(d=>Object.hasOwn(n,d))||n.hashVersion!==void 0&&n.hashVersion!==2||!Array.isArray(n.variations)||n.variations.length<2||n.variations.length>20||n.urlPatterns!==void 0&&!Array.isArray(n.urlPatterns))throw new Error("Invalid visual experiment");return{...n,variations:n.variations.map(Ie)}});return{...e,experiments:l}}function Ce(e){let l=ie(e.baseUrl);if(e.appManifestRelease!==void 0&&!/^[a-f0-9]{64}$/.test(e.appManifestRelease))throw new Error("Invalid IAM manifest digest");if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("Invalid App environment ID");let n=e.fetch??globalThis.fetch.bind(globalThis),d=J(n),y=J(n),v=`${l}/api/v1/visual-experiments/${e.environmentId}`,I=e.appManifestRelease?`${v}?iam=${e.appManifestRelease}`:v,E=ne(e.deviceIdCookie??"indiana_did"),D=te(),u=null,t=!1,i=!1,x="",k={...e.attributes??{}},G,q,$=0,m=new Map,O=new Map,L=new Set,P=[],C,F,b;function j(){clearTimeout(F),b?.remove(),b=void 0}function A(o=!1){clearTimeout(C),C=void 0;let c=P.splice(0,20);return c.length?de(n,`${v}/events`,JSON.stringify({events:c}),o).catch(p=>e.log?.("Visual exposure not sent",{error:p})):Promise.resolve()}function B(o,c){let p=R(o,c);L.has(p)||e.trackExposures===!1||u?.trackExposures===!1||t||(L.add(p),P.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:E,...D?{sessionId:D}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:o.key,variationKey:c.key}),P.length>=20?A():C??=setTimeout(()=>{A()},1e3))}function fe(o){if(!u||t)return;let c=new Set,p={onExperimentViewed:(r,g)=>{c.add(R(r,g))},url:location.href,attributes:{...ue(E,location),...k,indianaAppManifestRelease:e.appManifestRelease??null},savedGroups:X(u.savedGroups),log:e.log},h=new Set;for(let r of u.experiments){if(ae(`${e.environmentId}:${r.key}`))continue;let g=r;try{let a=Z(g,p);if(O.set(r.changeId,a),!a.inExperiment)continue;h.add(r.changeId);let w=JSON.stringify([a.key,a.value]),U=m.get(r.changeId);if(U?.signature===w){c.has(R(g,a))&&o.push(()=>{U.applied()&&B(g,a)});continue}m.get(r.changeId)?.revert(),m.delete(r.changeId);let M=ce(a.value,{requireUniqueTargets:!!e.appManifestRelease&&Array.isArray(r.condition?.$and)&&r.condition.$and.some(f=>f!==null&&typeof f=="object"&&!Array.isArray(f)&&f.indianaAppManifestRelease===e.appManifestRelease),boundVariations:r.variations,allowJs:e.disableJsInjection===!1,nonce:e.nonce,onApplied:()=>{c.has(R(g,a))&&B(g,a)},onError:f=>e.log?.("Visual experiment stopped",{experiment:r.key,changeId:r.changeId,variation:a.key,error:String(f)}),onTargetStatus:e.log?f=>e.log?.("Visual target status changed",{experiment:r.key,changeId:r.changeId,variation:a.key,...f}):void 0});m.set(r.changeId,{signature:w,revert:M.revert,applied:()=>M.applied,inspect:()=>M.inspect()})}catch(a){e.log?.("Skipping visual experiment",{experiment:r.key,error:String(a)})}}for(let[r,g]of m)h.has(r)||(g.revert(),m.delete(r));j()}let S=()=>{let o=[];le(()=>fe(o));for(let c of o)c()};async function H(){let o=++$,c;try{c=await d.read(I,N)}catch(h){if(t||o!==$)return!1;throw h}let p=K(c);if(p.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Visual payload scope changed");return t||o!==$?!1:(u=p,!0)}let me=()=>{x!==location.href&&(x=location.href,S())},z=()=>{A(!0)},W=()=>{G||t||(G=re(me),addEventListener("pagehide",z),x=location.href)};async function Y(o,c){let p=location.href,h=u,r=[],g=null;if(!t)try{let a=K(await y.read(I,N));a.environmentId===e.environmentId&&(g=a.generation)}catch{}for(let a of h?.experiments??[]){if(o&&a.changeId!==o)continue;let w=O.get(a.changeId);if(!w)continue;let U=new TextEncoder().encode(pe(w.value)),M=[...new Uint8Array(await crypto.subtle.digest("SHA-256",U))].map(he=>he.toString(16).padStart(2,"0")).join(""),f=m.get(a.changeId)?.inspect()??{status:"inactive",total:0,applied:0};r.push({changeId:a.changeId,experimentKey:a.key,variationKey:w.key,inExperiment:w.inExperiment,fingerprint:M,...f})}return{environmentId:e.environmentId,release:e.appManifestRelease??null,generation:h?.generation??null,publishedGeneration:g,checkedAt:new Date().toISOString(),origin:location.origin,pathname:location.pathname,urlMatches:location.href===p&&(!c||c===p)&&h===u,stopped:t,rows:r}}let Q,ye=se(()=>{i&&!t&&S()});return{async start(){if(!(i||t)){i=!0,e.appManifestRelease&&(q=ee(e.appManifestRelease)),e.antiFlicker&&(b=document.createElement("style"),e.nonce&&(b.nonce=e.nonce),b.textContent="body { visibility: hidden !important }",document.head.append(b),F=setTimeout(j,Math.min(3e3,Math.max(0,e.antiFlickerTimeout??1e3))));try{if(!await H()||t)return;W(),S()}finally{j(),t||(Q=ge({environmentId:e.environmentId,baseUrl:l,origins:e.diagnosticsOrigins,inspect:Y}))}}},async refresh(){t||await H()&&(i&&W(),S())},setAttributes(o){k={...o},S()},flush:()=>A(),getDiagnostics:Y,getResults(){return new Map(O)},get generation(){return u?.generation??null},destroy(){t=!0,ye(),Q?.(),$++,d.destroy(),y.destroy(),G?.(),q?.destroy(),removeEventListener("pagehide",z),j();for(let o of m.values())o.revert();m.clear(),A(!0),u=null,O.clear(),L.clear(),k={}}}}export{Ce as createVisualExperiments,ve as loadAppManifestRelease};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tinkerlandai/longplay-sdk",
3
- "version": "0.10.4",
3
+ "version": "0.10.5",
4
4
  "description": "Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -60,6 +60,12 @@
60
60
  "import": "./dist/visual.js"
61
61
  }
62
62
  },
63
+ "scripts": {
64
+ "build": "tsup",
65
+ "prepack": "pnpm run build",
66
+ "typecheck": "tsc --noEmit",
67
+ "lint": "node ../../scripts/ci/lint.mjs --workspace packages/sdk"
68
+ },
63
69
  "dependencies": {
64
70
  "@ai-sdk/provider": "4.0.26",
65
71
  "@types/json-schema": "7.0.15",
@@ -69,13 +75,13 @@
69
75
  "zod": "4.6.6"
70
76
  },
71
77
  "devDependencies": {
78
+ "@indiana/contracts": "workspace:*",
72
79
  "@openrouter/sdk": "^1.4.25",
73
80
  "@types/css-tree": "^3.2.0",
74
81
  "ai": "7.0.136",
75
82
  "tsup": "^8.5.1",
76
83
  "typescript": "^5.9.3",
77
- "whatwg-url-minimum": "0.2.0",
78
- "@indiana/contracts": "0.1.0"
84
+ "whatwg-url-minimum": "0.2.0"
79
85
  },
80
86
  "peerDependencies": {
81
87
  "@openrouter/sdk": "^1.4.25"
@@ -84,10 +90,5 @@
84
90
  "@openrouter/sdk": {
85
91
  "optional": true
86
92
  }
87
- },
88
- "scripts": {
89
- "build": "tsup",
90
- "typecheck": "tsc --noEmit",
91
- "lint": "node ../../scripts/ci/lint.mjs --workspace packages/sdk"
92
93
  }
93
- }
94
+ }
@@ -1 +0,0 @@
1
- import{d as t}from"./chunk-JB46ZKGZ.js";import{Ga as n}from"./chunk-2HFA34QO.js";function r(e,o,a){return n(e,o,a,t)}export{r as a};
@@ -1 +0,0 @@
1
- import{b as a}from"./chunk-ZPZVSC4J.js";import"./chunk-SBPTOOYB.js";import"./chunk-2HFA34QO.js";import"./chunk-ACF2FBUB.js";import"./chunk-EARSGITJ.js";import"./chunk-HOW7NIIR.js";import"./chunk-DSPLGTQI.js";import"./chunk-G56XGVMS.js";import"./chunk-MRN4HP4W.js";import"./chunk-7DXL3LHT.js";import"./chunk-XSVQHPQT.js";export{a as showFunnelRun};
@@ -1 +0,0 @@
1
- import{a,b,c,d,e,g as f,h as g,i as h,j as i}from"./chunk-X6BCUINI.js";import"./chunk-SSLZKIIU.js";import"./chunk-ACF2FBUB.js";import"./chunk-DSPLGTQI.js";import"./chunk-7DXL3LHT.js";import"./chunk-XSVQHPQT.js";export{f as formatCustomerDecimal,b as hostedRendererScript,a as hostedRendererShell,d as inspectCustomHtml,i as mountScreenPreview,h as preparePopup,e as prepareScreen,c as sanitizeCustomHtml,g as showPopup};
@@ -1 +0,0 @@
1
- import{b as a,c as b}from"./chunk-RE6BIFLN.js";import"./chunk-CLXORAOK.js";export{b as applyVisualVariation,a as safeVisualMutation};
File without changes
File without changes
File without changes