@tinkerlandai/longplay-sdk 0.10.34 → 0.10.36
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.
- package/CHANGELOG.md +7 -0
- package/README.md +83 -5
- package/README.zh-CN.md +26 -3
- package/dist/{ai-usage-T62xehqa.d.ts → ai-usage-DXwAGTxT.d.ts} +1 -1
- package/dist/{api-Do-6AyWa.d.ts → api-r6FfVQpg.d.ts} +6 -1
- package/dist/check-response-DHY6T5Z2.js +1 -0
- package/dist/{chunk-7MNJH5GB.js → chunk-2HSD2SEU.js} +1 -1
- package/dist/chunk-2KKLY323.js +1 -0
- package/dist/{chunk-BXPXJARS.js → chunk-35VG2IYD.js} +1 -1
- package/dist/chunk-3NCMYTNG.js +1 -0
- package/dist/{chunk-HQITRRHF.js → chunk-5XIKN35D.js} +1 -1
- package/dist/chunk-5XKFUFXK.js +1 -0
- package/dist/chunk-7ZEXY4GC.js +1 -0
- package/dist/chunk-BL7E4RZ2.js +1 -0
- package/dist/{chunk-FYQXSGRT.js → chunk-BTPEXSNY.js} +1 -1
- package/dist/chunk-C4GBV32U.js +10 -0
- package/dist/chunk-CGXNU5BC.js +1 -0
- package/dist/chunk-DB4EO3JG.js +1 -0
- package/dist/chunk-DHT3AWJQ.js +1 -0
- package/dist/chunk-GLYFT5WW.js +1 -0
- package/dist/chunk-HS56A4IK.js +1 -0
- package/dist/chunk-HVVJGLYZ.js +1 -0
- package/dist/chunk-HYE2YQYM.js +1 -0
- package/dist/chunk-I6D25FWU.js +1 -0
- package/dist/{chunk-TYY3MUTF.js → chunk-IOBB6KFK.js} +1 -1
- package/dist/chunk-JOIPLLHK.js +1 -0
- package/dist/{chunk-MIBRUDIS.js → chunk-LAGGWYH3.js} +1 -1
- package/dist/{chunk-6T575JKD.js → chunk-LVG5ED52.js} +1 -1
- package/dist/{chunk-I6TSQQ5N.js → chunk-M3GGR53D.js} +1 -1
- package/dist/chunk-MHWPEMX7.js +1 -0
- package/dist/chunk-MYBUQFTC.js +1 -0
- package/dist/{chunk-7QL4GF4C.js → chunk-O4KXODTJ.js} +1 -1
- package/dist/chunk-OL2AI6DA.js +1 -0
- package/dist/chunk-QHJWVLJC.js +1 -0
- package/dist/chunk-R3YVDRTB.js +1 -0
- package/dist/chunk-RHF4NFCZ.js +1 -0
- package/dist/{chunk-5HJYR6Z4.js → chunk-RHWZRHK7.js} +1 -1
- package/dist/{chunk-X4W22IH6.js → chunk-TIQS5DUF.js} +1 -1
- package/dist/chunk-U4WUX3WB.js +1 -0
- package/dist/chunk-UHTTCVSL.js +1 -0
- package/dist/{chunk-UWLEGMWX.js → chunk-UVUFJO2V.js} +1 -1
- package/dist/{chunk-7NELM6EH.js → chunk-VKG6BB3Z.js} +1 -1
- package/dist/chunk-VWMFR22O.js +1 -0
- package/dist/chunk-W32FI2A2.js +1 -0
- package/dist/chunk-W3K5ARMY.js +1 -0
- package/dist/chunk-WRLVPHPE.js +1 -0
- package/dist/chunk-XE7GU6FZ.js +1 -0
- package/dist/{chunk-EQPEUPMG.js → chunk-XQTCEQXI.js} +1 -1
- package/dist/chunk-YQX27SBG.js +1 -0
- package/dist/{chunk-VYFSRHXM.js → chunk-ZYF6TRJ3.js} +1 -1
- package/dist/{configuration-sync-DdTRUv7A.d.ts → configuration-sync-BHrAf-ql.d.ts} +10 -1
- package/dist/content-RGKTEV23.js +1 -0
- package/dist/funnel-host-purchase-M7MM33EC.js +1 -0
- package/dist/{funnel-local-client-BeGBvi3z.d.ts → funnel-local-client-DR8OpKGU.d.ts} +167 -25
- package/dist/funnel-paywall-prerender-OSBI4VMY.js +1 -0
- package/dist/{funnel-process-client-C6QKDZun.d.ts → funnel-process-client-C87U4r_G.d.ts} +17 -3
- package/dist/funnel-runtime-host-AMJXEASH.js +1 -0
- package/dist/index.d.ts +214 -63
- package/dist/index.js +1 -1
- package/dist/merchant-bridge-contracts-GJQVKEAG.js +1 -0
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.d.ts +3 -3
- package/dist/openrouter.js +1 -1
- package/dist/operation-contracts-MFK2KORK.js +1 -0
- package/dist/page.d.ts +2 -2
- package/dist/page.js +1 -1
- package/dist/paywall-ATZ2IZPS.js +1 -0
- package/dist/paywall-content-XERXGNND.js +1 -0
- package/dist/paywall-session-EMMF6IYS.js +1 -0
- package/dist/popup.d.ts +21 -3
- package/dist/popup.js +1 -1
- package/dist/{presentation-loading-CFSiS0VX.d.ts → presentation-loading-B_v5XZtM.d.ts} +11 -1
- package/dist/react-native.d.ts +7 -7
- package/dist/react-native.js +1 -1
- package/dist/{screen-CGCJ46b1.d.ts → screen-qUBRsUi9.d.ts} +26 -21
- package/dist/screen-renderer-B7LUTPTJ.js +1 -0
- package/dist/server.d.ts +37 -7
- package/dist/server.js +2 -2
- package/dist/{visual-dom-6DCUZGPB.js → visual-dom-5LUN4AHO.js} +1 -1
- package/dist/visual.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-3JJYWRA3.js +0 -1
- package/dist/chunk-4WZVC4TM.js +0 -1
- package/dist/chunk-5JWMP4YD.js +0 -1
- package/dist/chunk-7VRZYSTR.js +0 -1
- package/dist/chunk-EHDHWYVJ.js +0 -1
- package/dist/chunk-ERJP2GBD.js +0 -1
- package/dist/chunk-ILEDKSRQ.js +0 -1
- package/dist/chunk-ITGERPCJ.js +0 -1
- package/dist/chunk-N7YXDSQL.js +0 -1
- package/dist/chunk-NAZU3EEJ.js +0 -1
- package/dist/chunk-QBA3B4YK.js +0 -1
- package/dist/chunk-R23IGK5U.js +0 -1
- package/dist/chunk-R4FDIYMN.js +0 -1
- package/dist/chunk-RKPAIF6U.js +0 -1
- package/dist/chunk-SCC3O2RD.js +0 -1
- package/dist/chunk-TDSATEGE.js +0 -10
- package/dist/chunk-THMGTRXP.js +0 -1
- package/dist/chunk-U6UHASIB.js +0 -1
- package/dist/chunk-WKIR2EQG.js +0 -1
- package/dist/chunk-WTVLNUMS.js +0 -1
- package/dist/chunk-ZGCKQWQ5.js +0 -1
- package/dist/content-ORU4ODJQ.js +0 -1
- package/dist/funnel-host-purchase-BEFE3N3E.js +0 -1
- package/dist/funnel-runtime-host-V6TYIDX3.js +0 -1
- package/dist/merchant-bridge-contracts-ZUQ6SGXZ.js +0 -1
- package/dist/operation-contracts-443N2P3A.js +0 -1
- package/dist/paywall-HO4PS472.js +0 -1
- package/dist/paywall-session-MZXFOPTR.js +0 -1
- package/dist/screen-renderer-W7ZGBFIR.js +0 -1
- /package/dist/{chunk-BID4UGWB.js → chunk-CILM5XMH.js} +0 -0
- /package/dist/{chunk-UKMEW5I7.js → chunk-OJM6ORHE.js} +0 -0
- /package/dist/{chunk-VF6QMMEA.js → chunk-ZYN4CRHS.js} +0 -0
package/dist/visual.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as pe,c as fe}from"./chunk-
|
|
1
|
+
import{a as pe,c as fe}from"./chunk-OJM6ORHE.js";import{a as Ve,b as ce,c as de,d as ue}from"./chunk-SLUA7ABW.js";import{b as le}from"./chunk-J6KIN4RH.js";import{a as J,b as F,c as ge,e as me}from"./chunk-IOBB6KFK.js";import{a as re,b as ae,c as se,d as oe}from"./chunk-LVG5ED52.js";import"./chunk-3VUPVXAV.js";import"./chunk-RHF4NFCZ.js";import{b as o}from"./chunk-ZYN4CRHS.js";import{c as te,e as ie,g as M}from"./chunk-O4KXODTJ.js";import"./chunk-CILM5XMH.js";import"./chunk-DSPLGTQI.js";import"./chunk-WOT6VMZA.js";var K="indiana-visual-diagnostics-v1",Ae=o.strictObject({environmentId:o.string().uuid(),release:o.string().regex(/^[a-f0-9]{64}$/).nullable(),generation:o.string().regex(/^[a-f0-9]{64}$/).nullable(),publishedGeneration:o.string().regex(/^[a-f0-9]{64}$/).nullable(),checkedAt:o.string().datetime(),origin:o.string().url(),pathname:o.string().max(2048),urlMatches:o.boolean(),stopped:o.boolean(),rows:o.array(o.strictObject({changeId:o.string().regex(/^[a-f0-9]{64}$/),experimentKey:o.string().max(256),variationKey:o.string().max(256),inExperiment:o.boolean(),fingerprint:o.string().regex(/^[a-f0-9]{64}$/),status:o.enum(["inactive","waiting","partial","applied","mismatch","no_changes","unavailable","error"]),total:o.number().int().min(0).max(600),applied:o.number().int().min(0).max(600)})).max(100)});function ye(e){let l=n=>Array.isArray(n)?"["+n.map(l).join(",")+"]":n&&typeof n=="object"?"{"+Object.entries(n).filter(([,c])=>c!==void 0).sort(([c],[y])=>c.localeCompare(y)).map(([c,y])=>JSON.stringify(c)+":"+l(y)).join(",")+"}":JSON.stringify(n);return l({css:e.css,js:e.js,domMutations:e.domMutations,...e.renderGuard?{renderGuard:e.renderGuard}:{}})}function he(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,c=e.origins??(n?[`https://console.${n}`]:[]),y=new Set(c.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,k=0,T=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!==K||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()-k<250)){try{if(new URL(i.url).origin!==location.origin)return}catch{return}I=!0,k=Date.now();try{let x=await e.inspect(i.changeId,i.url);!v&&x.rows.some(S=>S.changeId===i.changeId)&&t.source.postMessage({channel:K,type:"result",nonce:i.nonce,snapshot:x},t.origin)}finally{I=!1}}},u=t=>{T(t).catch(()=>{})};return window.addEventListener("message",u),()=>{v=!0,window.removeEventListener("message",u)}}var R=e=>!!e&&typeof e=="object"&&!Array.isArray(e),E=(e,l)=>typeof e=="string"&&e.length<=l,Ee=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 ke(e){if(!R(e)||!E(e.css??"",1e5)||!E(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(!R(n)||!E(n.selector,2048)||!n.selector||!Ee(n.attribute)||!["set","append","remove"].includes(String(n.action))||n.value!==void 0&&!E(n.value,5e4)||n.parentSelector!==void 0&&!E(n.parentSelector,2048)||n.insertBeforeSelector!==void 0&&!E(n.insertBeforeSelector,2048))throw new Error("Invalid visual mutation");return{css:e.css??"",js:e.js??"",domMutations:l,...e.renderGuard===void 0?{}:{renderGuard:le(e.renderGuard)}}}function q(e){if(!R(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||!R(e.savedGroups))throw new Error("Invalid visual experiment payload");let l=e.experiments.map(n=>{if(!R(n)||!["key","changeId"].every(c=>typeof n[c]=="string"&&n[c])||!/^[a-f0-9]{64}$/.test(String(n.changeId))||["namespace","status","groups","url"].some(c=>Object.hasOwn(n,c))||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(ke)}});return{...e,experiments:l}}var ve=6e4;function qe(e){let l=se(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),c=F(n),y=F(n),v=`${l}/api/v1/visual-experiments/${e.environmentId}`,I=e.appManifestRelease?`${v}?iam=${e.appManifestRelease}`:v,k=re(e.deviceIdCookie??"indiana_did"),T=ae(),u=null,t=!1,i=!1,x="",S={...e.attributes??{}},G,B,D=0,H=-1/0,$,m=new Map,O=new Map,C=new Set,z=ge({endpoint:`${v}/events`,fetch:n,log:e.log,label:"Visual exposure"}),P=z.flush,W,b;function j(){clearTimeout(W),b?.remove(),b=void 0}function Y(s,d){let f=M(s,d);C.has(f)||e.trackExposures===!1||u?.trackExposures===!1||t||(C.add(f),z.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:k,...T?{sessionId:T}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:s.key,variationKey:d.key}))}function we(s){if(!u||t)return;let d=new Set,f={onExperimentViewed:(r,p)=>{d.add(M(r,p))},url:location.href,attributes:{...me(k,location),...S,indianaAppManifestRelease:e.appManifestRelease??null},savedGroups:te(u.savedGroups),log:e.log},h=new Set;for(let r of u.experiments){if(de(`${e.environmentId}:${r.key}`))continue;let p=r;try{let a=ie(p,f);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){d.has(M(p,a))&&s.push(()=>{U.applied()&&Y(p,a)});continue}m.get(r.changeId)?.revert(),m.delete(r.changeId);let A=fe(a.value,{requireUniqueTargets:!!e.appManifestRelease&&Array.isArray(r.condition?.$and)&&r.condition.$and.some(g=>g!==null&&typeof g=="object"&&!Array.isArray(g)&&g.indianaAppManifestRelease===e.appManifestRelease),boundVariations:r.variations,allowJs:e.disableJsInjection===!1,nonce:e.nonce,onApplied:()=>{d.has(M(p,a))&&Y(p,a)},onError:g=>e.log?.("Visual experiment stopped",{experiment:r.key,changeId:r.changeId,variation:a.key,error:String(g)}),onTargetStatus:e.log?g=>e.log?.("Visual target status changed",{experiment:r.key,changeId:r.changeId,variation:a.key,...g}):void 0});m.set(r.changeId,{signature:w,revert:A.revert,applied:()=>A.applied,inspect:()=>A.inspect()})}catch(a){e.log?.("Skipping visual experiment",{experiment:r.key,error:String(a)})}}for(let[r,p]of m)h.has(r)||(p.revert(),m.delete(r));j()}let V=()=>{let s=[];pe(()=>we(s));for(let d of s)d()};async function _(){let s=++D,d;try{d=await c.read(I,J)}catch(h){if(t||s!==D)return!1;throw h}let f=q(d);if(f.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Visual payload scope changed");return t||s!==D?!1:(u=f,H=performance.now(),!0)}async function Q(){!await _()||t||(N(),V())}function L(){clearTimeout($),$=setTimeout(()=>{if(document.visibilityState==="hidden")return L();Q().catch(s=>e.log?.("Visual payload refresh failed",{error:String(s)})).finally(()=>{t||L()})},ve)}let X=()=>{t||document.visibilityState==="hidden"||performance.now()-H<ve||(clearTimeout($),Q().catch(s=>e.log?.("Visual payload refresh failed",{error:String(s)})).finally(()=>{t||L()}))},Ie=()=>{x!==location.href&&(x=location.href,V())},Z=()=>{P(!0)},N=()=>{G||t||(G=oe(Ie),addEventListener("pagehide",Z),x=location.href)};async function ee(s,d){let f=location.href,h=u,r=[],p=null;if(!t)try{let a=q(await y.read(I,J));a.environmentId===e.environmentId&&(p=a.generation)}catch{}for(let a of h?.experiments??[]){if(s&&a.changeId!==s)continue;let w=O.get(a.changeId);if(!w)continue;let U=new TextEncoder().encode(ye(w.value)),A=[...new Uint8Array(await crypto.subtle.digest("SHA-256",U))].map(be=>be.toString(16).padStart(2,"0")).join(""),g=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:A,...g})}return{environmentId:e.environmentId,release:e.appManifestRelease??null,generation:h?.generation??null,publishedGeneration:p,checkedAt:new Date().toISOString(),origin:location.origin,pathname:location.pathname,urlMatches:location.href===f&&(!d||d===f)&&h===u,stopped:t,rows:r}}let ne,xe=ue(()=>{i&&!t&&V()});return{async start(){if(!(i||t)){i=!0,e.appManifestRelease&&(B=ce(e.appManifestRelease)),e.antiFlicker&&(b=document.createElement("style"),e.nonce&&(b.nonce=e.nonce),b.textContent="body { visibility: hidden !important }",document.head.append(b),W=setTimeout(j,Math.min(3e3,Math.max(0,e.antiFlickerTimeout??1e3))));try{if(!await _()||t)return;N(),V()}finally{j(),t||(L(),document.addEventListener("visibilitychange",X),ne=he({environmentId:e.environmentId,baseUrl:l,origins:e.diagnosticsOrigins,inspect:ee}))}}},async refresh(){t||await _()&&(i&&N(),V())},setAttributes(s){S={...s},V()},flush:()=>P(),getDiagnostics:ee,getResults(){return new Map(O)},get generation(){return u?.generation??null},destroy(){t=!0,clearTimeout($),document.removeEventListener("visibilitychange",X),xe(),ne?.(),D++,c.destroy(),y.destroy(),G?.(),B?.destroy(),removeEventListener("pagehide",Z),j();for(let s of m.values())s.revert();m.clear(),P(!0),u=null,O.clear(),C.clear(),S={}}}}export{qe as createVisualExperiments,Ve as loadAppManifestRelease};
|
package/package.json
CHANGED
package/dist/chunk-3JJYWRA3.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as ge}from"./chunk-I6TSQQ5N.js";import{a as J}from"./chunk-UWLEGMWX.js";import{A as Re,E as Q,G as Ce,d as fe,f as T,k as he,v as ye,w as Se,y as Pe}from"./chunk-QBA3B4YK.js";import{$ as N}from"./chunk-R23IGK5U.js";import{a as D,i as K}from"./chunk-EHDHWYVJ.js";import{b as we}from"./chunk-WTVLNUMS.js";import{a as l}from"./chunk-X4W22IH6.js";import{h as B}from"./chunk-R4FDIYMN.js";import{b as Ie}from"./chunk-WKIR2EQG.js";import{b as n}from"./chunk-VF6QMMEA.js";import{a as ie}from"./chunk-DSPLGTQI.js";var I=N.options,Ne=n.discriminatedUnion("operation",[I[1].omit({customerToken:!0}),I[2].omit({customerToken:!0}),I[3].omit({customerToken:!0}),I[4].omit({customerToken:!0}),I[5].omit({customerToken:!0}),I[6].omit({customerToken:!0}),I[7].omit({customerToken:!0}),I[8].omit({customerToken:!0}),he.omit({customerToken:!0})]),se=n.strictObject({receiptId:n.uuid(),operationId:n.uuid()}),Ge=n.discriminatedUnion("operation",[n.strictObject({operation:n.literal("find_purchase")}),n.strictObject({operation:n.literal("recover_start"),intent:n.enum(["lookup","resume"]),start:n.strictObject({requestId:I[0].shape.requestId,funnelId:I[0].shape.funnelId,locale:I[0].shape.locale,parameters:I[0].shape.parameters})}),n.strictObject({operation:n.literal("recover_run"),runId:n.uuid(),funnelId:n.uuid()}),n.strictObject({operation:n.literal("recover_purchase"),runId:n.uuid(),funnelId:n.uuid(),purchase:se}),n.strictObject({operation:n.literal("terminate_checkout"),runId:n.uuid(),funnelId:n.uuid(),purchase:se}),n.strictObject({operation:n.literal("settle_command"),runId:n.uuid(),funnelId:n.uuid(),requestId:n.uuid(),command:n.discriminatedUnion("operation",[I[3].omit({customerToken:!0}),I[4].omit({customerToken:!0}),I[5].omit({customerToken:!0}),I[6].omit({customerToken:!0}),I[7].omit({customerToken:!0})]).optional()}).refine(o=>!o.command||o.requestId===o.command.requestId),n.strictObject({operation:n.literal("run_command"),runId:n.uuid(),funnelId:n.uuid(),command:Ne})]),Y=n.strictObject({runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),startRequestId:n.uuid(),runExpiresAt:n.iso.datetime({offset:!0}),status:T.shape.run.shape.status}),A={scope:B,customerId:n.uuid()},be=n.discriminatedUnion("outcome",[n.strictObject({...A,outcome:n.literal("unknown"),target:n.null(),view:n.null(),access:n.null()}),n.strictObject({...A,outcome:n.literal("resolved"),target:Y,view:T.shape.run.nullable(),access:n.discriminatedUnion("type",[n.strictObject({type:n.literal("customer")}),n.strictObject({type:n.literal("operation_only"),cause:n.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((o,d)=>{o.outcome==="resolved"&&(o.access.type==="customer"!=(o.view!==null)||o.view&&(o.view.id!==o.target.runId||o.view.source.id!==o.target.funnelId||o.view.source.versionId!==o.target.versionId||o.view.status!==o.target.status||o.view.runExpiresAt!==o.target.runExpiresAt||o.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),ve=n.strictObject({...A,target:Y,view:T.shape.run.nullable(),settlement:n.strictObject({requestId:n.uuid(),state:n.enum(["pending","unknown","settled"]),acceptance:n.enum(["accepted","not_accepted","unknown"]),receiptPhase:n.enum(["accepted","processing","done"]).nullable(),basis:n.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:n.uuid().nullable(),operationId:n.uuid().nullable()}),purchase:T.shape.purchase.unwrap().nullable()}).superRefine((o,d)=>{let p=o.settlement;(p.acceptance==="accepted"!=(p.receiptPhase!==null)||p.acceptance==="accepted"&&p.basis!=="receipt"||p.acceptance==="unknown"&&(p.state!=="unknown"||p.basis!=="none")||p.acceptance!=="accepted"&&(p.operationId!==null||p.receiptId!==null)||p.acceptance==="not_accepted"&&(p.state!=="settled"||!["run_terminal","position_advanced"].includes(p.basis))||o.purchase&&(o.purchase.receiptId!==p.receiptId||o.purchase.operation&&o.purchase.operation.operationId!==p.operationId||o.purchase.quote&&o.purchase.quote.operationId!==p.operationId)||o.view&&(o.view.id!==o.target.runId||o.view.source.id!==o.target.funnelId||o.view.source.versionId!==o.target.versionId||o.view.status!==o.target.status||o.view.runExpiresAt!==o.target.runExpiresAt||o.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Ee=n.strictObject({...A,target:Y,purchase:T.shape.purchase.unwrap()}).superRefine((o,d)=>{(!o.purchase.operation||typeof o.purchase.canReselect!="boolean"||o.purchase.quote&&o.purchase.quote.operationId!==o.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})}),ze=n.discriminatedUnion("outcome",[n.strictObject({...A,outcome:n.literal("none")}),n.strictObject({...A,outcome:n.literal("blocked")}),n.strictObject({...A,outcome:n.literal("found"),target:Y,start:n.strictObject({locale:I[0].shape.locale,parameters:I[0].shape.parameters}),purchase:se})]);var Te=N.options[0].refine(o=>!o.customer&&!o.customerData),xe=n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),terminal:n.enum(["complete","native"]).nullable()}),Oe=n.strictObject({schemaVersion:n.literal(1),baseUrl:n.url(),scope:B,customerId:n.uuid(),sessionId:n.uuid(),start:Te,allowed:n.array(n.enum(["merchant","record_only","indiana","native"])),run:n.strictObject({id:n.uuid(),versionId:n.uuid(),status:fe.shape.status,revision:n.number().int().nonnegative(),runExpiresAt:n.iso.datetime({offset:!0}).optional()}).optional(),purchases:n.array(xe).max(100),operationCommand:n.strictObject({operationId:n.uuid(),intent:n.literal("confirm")}).optional(),journal:n.strictObject({revision:n.number().int().nonnegative(),entry:ye.nullable()})});function Fe(o){return Pe({...o,namespace:"purchases",identity:[o.scope.projectId,o.scope.environment,o.customerId]})}function qe(o){let d=new URL(o.baseUrl??Ie).href,p=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function b(){o.assertCurrent();try{let y=await o.storage.read();if(o.assertCurrent(),!Number.isSafeInteger(y.revision)||y.revision<0)throw p();let a=y.entry===null?null:Oe.parse(y.entry);if(a&&(a.baseUrl!==d||a.customerId!==o.customerId||a.scope.projectId!==o.scope.projectId||a.scope.environment!==o.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(a?.journal.entry&&(a.journal.entry.scope.projectId!==a.scope.projectId||a.journal.entry.scope.environment!==a.scope.environment||a.journal.entry.funnelId!==a.start.funnelId||a.journal.entry.runId!==a.run?.id||a.journal.entry.versionId!==a.run?.versionId)||a?.operationCommand&&!a.purchases.some(P=>P.operationId===a.operationCommand?.operationId))throw p();return{revision:y.revision,entry:a}}catch(y){throw y instanceof l?y:p()}}async function W(y){for(let a=0;a<8;a++){let P=await b(),E=y(structuredClone(P.entry));if(JSON.stringify(E)===JSON.stringify(P.entry))return E;E&&Oe.parse(E),o.assertCurrent();let v;try{v=await o.storage.write(P.revision,E)}catch{throw p()}if(o.assertCurrent(),v!==null){if(!Number.isSafeInteger(v)||v<=P.revision)throw p();return E}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:b,update:W,baseUrl:d}}function Ue(o){let d=o.purchases.find(p=>p.type==="checkout");if(!o.actions.includes("continue_checkout")||d?.type!=="checkout")throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return d.checkoutUrl}function ft(o){let d={...o,scope:{...o.scope},executionPolicy:structuredClone(o.executionPolicy)},p=d.session.snapshot();if(!p)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:b,sessionId:W}=p,y=!1,a=null,P,E=null,v=!1,q,H,L,F={mode:"idle",status:"idle",actions:["start"],purchases:[]},w=new Map,k=new Map,ue=new AbortController,M=new Set,$=we(d),ce=ge($.request);function V(e){return{code:e instanceof l?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof l&&e.status!==void 0?{status:e.status}:{}}}function R(){if(y||d.session.snapshot()?.customerId!==b)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let g=qe({...d,customerId:b,assertCurrent:R,storage:d.storage??Fe({baseUrl:d.baseUrl,scope:d.scope,customerId:b})}),_e=d.session.subscribeIdentity(le);function le(){y||(y=!0,clearTimeout(L),ue.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),_e(),a?.reset(),a=null,E=null,$.dispose(),M.clear(),w.clear(),k.clear())}function C(e){R();let t=JSON.stringify(e)!==JSON.stringify(F);F=e,clearTimeout(L),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(L=setTimeout(()=>{x().catch(()=>{})},5e3)),t&&ie(d.onRecovery,structuredClone(e));for(let r of t?M:[]){if(y)break;ie(r,structuredClone(e))}return structuredClone(e)}function h(e){if(R(),!e||e.start.requestId!==P)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function O(e){let t=[...e.purchases],r=e.journal.entry?.purchase;return r&&!t.some(u=>u.operationId===r.operationId)&&t.push({receiptId:r.receiptId,operationId:r.operationId,terminal:null}),t}function G(e){return e.run&&!["running","waiting"].includes(e.run.status)&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&O(e).every(t=>t.terminal!==null)}function X(e){if(e.journal.entry?.command||e.journal.entry?.closeCommand||e.operationCommand)return!1;let t=O(e).filter(r=>r.terminal===null);return t.length>0&&t.every(r=>{let u=w.get(r.operationId);return u?.executor==="merchant"&&D({quote:u.quote??null,operation:u,requestId:null,pending:!1,destroyed:!1,canReselect:!1}).type==="checkout"})}function _(e,t){let r=e.journal.entry?.command??e.journal.entry?.closeCommand,u=O(e).map(S=>{let ae=w.get(S.operationId);return S.terminal&&!ae?{type:S.terminal,operationId:S.operationId}:D({quote:ae?.quote??null,operation:ae??null,requestId:r?.requestId??null,pending:!1,destroyed:!1,canReselect:k.get(S.operationId)===!0})}),c=u.filter(S=>!["complete","native"].includes(S.type)),i=c[0],s=c.length===1&&i?.operationId?w.get(i.operationId):void 0;if(s&&(i?.type==="checkout"||i?.type==="cancel"))try{Q({allowed:e.allowed.filter(S=>d.executionPolicy.allowed.includes(S))},s.quote)}catch(S){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:u,error:V(S)}}let m;if(t==="operation"&&!r&&i?.type==="cancel"&&s?.quote&&!s.problem&&!s.confirmedAt)try{Q({allowed:e.allowed.filter(S=>d.executionPolicy.allowed.includes(S))},s.quote),Date.parse(s.quote.expiresAt)>Date.now()&&(m={operationId:s.operationId,quote:s.quote})}catch{}let f=u.length>0&&c.length===0,U=G(e)||t==="operation"&&f&&!r&&!e.operationCommand?"complete":i?.type==="checkout"?"checkout":i?.type==="fulfillment"?"fulfillment":i?.type==="recording"?"recording":r||e.operationCommand||i&&i.type!=="cancel"||t==="operation"&&!m?"waiting_result":"ready";return{mode:t,status:U,purchases:u,...m?{confirmation:structuredClone(m)}:{},actions:["refresh",...G(e)||X(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:m?["confirm"]:[],...c.length===1&&i?.type==="checkout"?["continue_checkout"]:[]]}}function Z(e){let t=D({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&k.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function ee(e){if(!e.operation)return;let t={...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}};if(t.merchantExecution&&t.merchantExecution.customerId!==b)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let r=K(w.get(t.operationId)??null,t);w.set(t.operationId,r),r===t&&k.set(t.operationId,e.canReselect===!0)}async function je(e){R();for(let r of[e.purchase,e.run.paywall])r&&ee(r);let t=await g.update(r=>{if(h(r),r.run&&(r.run.id!==e.run.id||r.run.versionId!==e.run.source.versionId))throw new l("SCOPE_MISMATCH","The original purchase Run changed");let u=O(r);for(let c of[e.purchase,e.run.paywall]){let i=c?.operation?.operationId??c?.quote?.operationId;if(!c||!i)continue;let s=u.find(f=>f.operationId===i);if(s&&s.receiptId!==c.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let m=Z(w.get(i));s?s.terminal??=m:u.push({receiptId:c.receiptId,operationId:i,terminal:m})}return{...r,purchases:u,run:r.run&&(r.run.revision>e.run.revision||!["running","waiting"].includes(r.run.status)&&["running","waiting"].includes(e.run.status))?r.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});h(t),t.run&&!["running","waiting"].includes(t.run.status)&&O(t).some(r=>!r.terminal)&&(t=await te(t,!t.journal.entry?.command&&!t.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(r=>!!r)))),h(t),C(_(t,"run"))}function Ae(){return{async read(){let{entry:e}=await g.read();return h(e),structuredClone(e.journal)},async write(e,t){let r=null;return await g.update(u=>{if(h(u),u.operationCommand&&t?.command&&t.command.operation!=="close")throw new l("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return r=null,u.journal.revision!==e?u:(r=e+1,{...u,journal:{revision:r,entry:t}})}),r}}}async function te(e,t=!1,r=new Set){h(e);let u=O(e);for(let i of u){if(i.terminal)continue;let s=r.has(i.operationId)?w.get(i.operationId):void 0;if(s??=await de(e,i),R(),s.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(s.merchantExecution&&s.merchantExecution.customerId!==b)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&D({quote:s.quote??null,operation:s,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){if({operation:s}=await ce.attach({operationId:i.operationId,intent:"cancel"}),R(),s.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");s=await de(e,i)}w.set(i.operationId,K(w.get(i.operationId)??null,s))}let c=await g.update(i=>{h(i);let s=i.operationCommand&&w.get(i.operationCommand.operationId);return{...i,...s&&(s.confirmedAt||s.merchantExecution||s.status!=="pending")?{operationCommand:void 0}:{},purchases:O(i).map(m=>({...m,terminal:m.terminal??Z(w.get(m.operationId))}))}});return h(c),c}async function ne(e){R();let t=await $.request("funnels",e);return R(),t}async function de(e,t){let r=J(Ee,await ne({operation:"recover_purchase",runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId}}));if(re(e,r),r.purchase.receiptId!==t.receiptId||r.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return ee(r.purchase),w.get(t.operationId)}async function pe(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let r=J(ve,await ne({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(re(e,r),r.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");r.purchase&&ee(r.purchase);let u=await g.update(c=>{h(c);let i=O(c),{receiptId:s,operationId:m}=r.settlement;if(s&&m){let U=i.find(S=>S.operationId===m);if(U&&U.receiptId!==s)throw new l("INVALID_RESPONSE","Original Receipt changed");U||i.push({receiptId:s,operationId:m,terminal:Z(w.get(m))})}let f=r.settlement.state==="settled"?Se(c.journal.entry,t.requestId):c.journal.entry;return{...c,purchases:i,journal:f===c.journal.entry?c.journal:{revision:c.journal.revision+1,entry:f}}});h(u),e=u}return e}function re(e,t){if(t.customerId!==b||t.scope.projectId!==d.scope.projectId||t.scope.environment!==d.scope.environment||t.target.funnelId!==e.start.funnelId||t.target.startRequestId!==e.start.requestId||e.run&&(t.target.runId!==e.run.id||t.target.versionId!==e.run.versionId))throw new l("SCOPE_MISMATCH","The original recovery binding changed")}async function oe(e,t){if(h(e),e.run&&(e=await pe(e)),!O(e).length&&G(e))return C(_(e,"operation"));if(!O(e).length)return C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:V(t)});v=!0;let r=await te(e);return C(_(r,"operation"))}async function z(e,t=!1,r=!0){if(P=e.start.requestId,E=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!a){let u=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:t?"resume":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},c;try{c=await ne(u)}catch(f){if(!e.run&&f instanceof l&&(f.status===void 0||f.status>=500))return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:F.purchases,error:V(f)});throw f}let i=J(be,c);if(i.customerId!==b||i.scope.projectId!==d.scope.projectId||i.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(i.outcome==="unknown")return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:F.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}});re(e,i);let s=await g.update(f=>(h(f),{...f,run:{id:i.target.runId,versionId:i.target.versionId,status:i.target.status,revision:i.view?.revision??f.run?.revision??0,runExpiresAt:i.target.runExpiresAt}}));if(h(s),e=s,i.access.type==="operation_only")return oe(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await pe(e);let m=i.view;if(m.locale!==e.start.locale||!Re(m.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");a=Ce({...d,customerRun:{runId:i.target.runId,customerId:b,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(f=>d.executionPolicy.allowed.includes(f))},funnelCommandStorage:Ae(),onAcceptedResponse:je},{scope:i.scope,run:m})}try{await a.get(),a.view?.pendingRequest?.requestId===e.start.requestId&&!a.pendingCommands?.length&&await a.resume(a.view.pendingRequest.requestId);for(let c of a.pendingCommands??[])c.operation!=="close"&&await a.settle?.(c.requestId);a.pendingCommands?.length&&await a.retry(),R();let u=(await g.read()).entry;return h(u),C(_(u,"run"))}catch(u){if(R(),r&&u instanceof l&&(u.status===401||u.status===409&&u.reason==="STATE_CHANGED")){a.reset(),a=null;let c=(await g.read()).entry;return h(c),z(c,!1,!1)}throw u}}function j(e,t="read"){if(R(),q)return t==="read"||t===H?q:q.then(()=>j(e,t),()=>j(e,t));clearTimeout(L);let r=e().catch(u=>{throw y||C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:F.purchases,error:V(u)}),u});return q=r,H=t,r.then(()=>{q===r&&(q=void 0,H=void 0)},()=>{q===r&&(q=void 0,H=void 0)}),r}function x(){return j(async()=>{let{entry:e}=await g.read();return e?(P&&e.start.requestId!==P&&(a?.reset(),a=null,w.clear(),k.clear()),v&&P===e.start.requestId?oe(e,F.error):z(e)):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}async function me(){let e=await x();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:j(async()=>{let t=(await g.read()).entry;if(h(t),!v){if(!a?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let s=a.view.paywall.operation;if(s?.confirmedAt||s?.merchantExecution||s&&s.status!=="pending")return C(_(t,"run"));if(a.pendingCommands?.length)await a.retry();else{let f=a.view;await a.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:f.nodeId,visit:f.visit,revision:f.revision,input:{type:"paywall_confirm",operationId:f.paywall.quote.operationId}})}let m=(await g.read()).entry;return h(m),C(_(m,"run"))}let r=t.operationCommand?.operationId??F.confirmation?.operationId,u=r&&w.get(r);if(!r||!u||t.journal.entry?.command||t.journal.entry?.closeCommand)throw new l("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");Q({allowed:t.allowed.filter(s=>d.executionPolicy.allowed.includes(s))},u.quote),await g.update(s=>{if(h(s),s.journal.entry?.command||s.journal.entry?.closeCommand||s.operationCommand&&s.operationCommand.operationId!==r)throw new l("PURCHASE_PENDING","Another original command is pending");return{...s,operationCommand:{operationId:r,intent:"confirm"}}});let c=await ce.attach({operationId:r,intent:"confirm"});if(R(),c.operation.operationId!==r)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");w.set(r,K(u,c.operation));let i=(await g.read()).entry;return h(i),C(_(await te(i,!1,new Set([r])),"operation"))},"confirm")}async function ke(){let e=a?.view;if(!(!a||!e||!["running","waiting"].includes(e.status)))try{await a.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:e.nodeId,visit:e.visit,revision:e.revision})}catch{}}return{get controller(){return a},get recovery(){return structuredClone(F)},get attempt(){return R(),structuredClone(E)},get identitySignal(){return ue.signal},start(e){let t=N.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(t.operation!=="start"||t.customer||t.customerData)throw new l("INVALID_REQUEST","A Customer-owned Funnel start is required");return j(async()=>{let r=(await g.read()).entry;r&&r.start.requestId===P&&X(r)&&await ke();let u=await g.update(c=>{if(c&&!G(c)&&!X(c)){if(c.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return c}return{schemaVersion:1,baseUrl:g.baseUrl,scope:d.scope,customerId:b,sessionId:W,start:t,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!u)throw new l("PURCHASE_STORAGE_INVALID","Original start was not retained");return P!==u.start.requestId&&(a?.reset(),a=null,w.clear(),k.clear(),v=!1),v?oe(u,F.error):z(u,!0)},`start:${t.funnelId}`)},refresh:x,confirm:me,retry:()=>v?me():j(async()=>{let{entry:e}=await g.read();return e?z(e,!0):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return a?.view?j(async()=>{if(!a?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(a.pendingCommands?.find(r=>r.operation==="close"))await a.retry();else if(["running","waiting"].includes(a.view.status)){let r=a.view;await a.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:r.nodeId,visit:r.visit,revision:r.revision})}let t=(await g.read()).entry;return h(t),C(_(t,"run"))},"close"):x()},async continueCheckout(e){let t=await x();R(),await e(Ue(t))},subscribe(e){return M.add(e),()=>{M.delete(e)}},destroy:le}}export{Fe as a,Ue as b,ft as c};
|
package/dist/chunk-4WZVC4TM.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{d as x}from"./chunk-U6UHASIB.js";import{a as g}from"./chunk-X4W22IH6.js";function z(e,n,i,s,o){let{presentation:t,screen:r}=i,p=Object.entries(i.buttons??{}).filter(([,l])=>l.type==="close").map(([l])=>l),a=e.ownerDocument.defaultView,u=r.pages.find(l=>l.id===r.initialPageId)?.theme??r.theme,b={background:r.theme.background,text:r.theme.text};n.inert=!0,n.style.cssText="width:100%;min-width:0;overflow:hidden;visibility:hidden";let m=!1,c,f=l=>{a&&c?.resizeViewport(Math.max(1,a.innerHeight-(l==="modal"?32:0)),a.innerWidth)},d=t.type==="inline"?void 0:x(e,{...r,presentation:t,theme:b},f);return d?.latch(),a&&d?.responsive&&d.setContentHeight(a.innerHeight-(d.type==="modal"?32:0)),e.style.background=u.background,e.style.color=u.text,d?(t.type==="fullscreen"||t.type==="sheet")&&(e.style.position="fixed"):e.style.position="relative",import("./screen-renderer-W7ZGBFIR.js").then(({mountScreenPreview:l})=>{m||(c=l(n,{mode:"live",skeleton:!0,closeActions:p,hostPresentation:()=>d?.type??t.type,reportContentHeight:d?.responsive,onResize(w){if(!a||!d?.responsive)return;let v=d.type==="modal"?32:0,y=Math.min(w,Math.max(0,a.innerHeight-v));n.style.height=`${y}px`,d.setContentHeight(y)},onRendered:o,onError(){c&&(c.destroy(),c=void 0)}}),d?.responsive&&f(d.type),c.update({...r,presentation:t},s,{serverInput:{bindings:[],answers:{}}}))}).catch(()=>{c?.destroy(),c=void 0}),()=>{m=!0,c?.destroy(),d?.destroy()}}var k={none:0,sm:4,md:8,lg:14,full:9999},T={system:"system-ui,sans-serif",serif:"Georgia,serif",rounded:"ui-rounded,system-ui,sans-serif",mono:"ui-monospace,monospace"},S={primary:"#172033",background:"#FFFFFF",text:"#172033",radius:"md",font:"system"};function h(e){let[n,i,s]=[1,3,5].map(o=>{let t=Number.parseInt(e.slice(o,o+2),16)/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4});return .2126*n+.7152*i+.0722*s}function F(e,n=!0){let i=h(e.primary),s=(i+.05)/.05>1.05/(i+.05)?"#111318":"#FFFFFF",o=`color-mix(in srgb, ${e.text} 22%, ${e.background})`,t=`${k[e.radius]}px`,r=`appearance:none;margin:0;min-height:44px;padding:10px 18px;border:0;border-radius:${t};font:inherit;font-size:15px;font-weight:600;line-height:1.25;cursor:pointer;touch-action:manipulation`;return{root:`width:100%;box-sizing:border-box;${n?`background:${e.background};`:""}color:${e.text};font:14px/1.5 ${T[e.font]}`,controls:"display:flex;gap:12px;padding:0 20px 12px;align-items:center;flex-wrap:wrap",pinned:`position:sticky;bottom:0;z-index:1;box-sizing:border-box;padding-top:12px;background:${e.background};border-top:1px solid ${o}`,bar:`display:flex;gap:8px;padding:12px 16px;align-items:center;flex-wrap:wrap;border-top:1px solid ${o}`,message:"flex:1 1 200px;min-width:0;margin:0;font-size:13px",status:"margin:0;font-size:13px;opacity:.72",alert:`flex:1 1 200px;min-width:0;margin:0;font-size:13px;font-weight:500;color:${h(e.background)>.4?"#B42318":"#FDA29B"}`,panel:`flex:1 0 100%;box-sizing:border-box;display:flex;flex-direction:column;gap:8px;padding:16px;border:1px solid ${o};border-radius:${t}`,summary:"margin:0;font-size:15px;font-weight:600",terms:"display:flex;flex-direction:column;gap:4px;font-size:13px;opacity:.72",actions:"display:flex;gap:8px;flex-wrap:wrap;margin-top:4px",primary:`${r};background:${e.primary};color:${s}`,secondary:`${r};background:transparent;color:${e.text};box-shadow:inset 0 0 0 1px ${o}`,link:`${r};background:transparent;color:${e.text};opacity:.72;font-weight:500`,stage:"display:flex;justify-content:center;padding:24px 20px",history:"display:flex;flex-direction:column;gap:12px;padding:20px",historyTitle:"margin:0;padding-inline-end:40px;font-size:17px;font-weight:600;line-height:1.3",historyNote:"margin:0;font-size:13px;opacity:.72",historyPages:"display:flex;gap:8px;flex-wrap:wrap;margin:0;padding:0;list-style:none",historyPage:`border:1px solid ${o};border-radius:${t};overflow:hidden`,historyRecords:`display:flex;flex-direction:column;gap:4px;margin:0;padding:12px 0 0;list-style:none;font-size:13px;border-top:1px solid ${o}`,focus:e.text}}function L(e){e.style.opacity=e.disabled?".55":"",e.style.cursor=e.disabled?"not-allowed":"pointer"}function H(e,n){e.addEventListener("focus",()=>{let i=!0;try{i=e.matches(":focus-visible")}catch{}i&&(e.style.outline=`2px solid ${n()}`,e.style.outlineOffset="2px")}),e.addEventListener("blur",()=>{e.style.outline="",e.style.outlineOffset=""})}var $={en:{network:"Connection problem. Check your network and try again.",timeout:"This is taking longer than expected. Try again.",other:"Something went wrong. Try again."},zh:{network:"\u7F51\u7EDC\u8FDE\u63A5\u5F02\u5E38\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u540E\u91CD\u8BD5\u3002",timeout:"\u54CD\u5E94\u65F6\u95F4\u8FC7\u957F\uFF0C\u8BF7\u91CD\u8BD5\u3002",other:"\u51FA\u4E86\u70B9\u95EE\u9898\uFF0C\u8BF7\u91CD\u8BD5\u3002"}};function O(e,n){let i=$[n?"zh":"en"],s=e instanceof g?e.code:void 0;return s==="NETWORK_ERROR"?i.network:s==="TIMEOUT"?i.timeout:i.other}function I(e){let n=!1,i,s,o=()=>{clearTimeout(i),i=void 0};function t(){if(o(),n)return;let a=e.document.visibilityState==="hidden"?e.hiddenDelay?.():e.delay();a!==void 0&&(i=setTimeout(()=>{r().catch(()=>{})},a))}function r(){if(n)return Promise.resolve();if(s)return s;o();let a=Promise.resolve().then(()=>n?void 0:e.run());s=a;let u=()=>{s===a&&(s=void 0),t()};return a.then(u,u),a}let p=()=>{e.document.visibilityState==="hidden"?t():r().catch(()=>{})};return e.document.addEventListener("visibilitychange",p),{schedule:t,refresh:r,destroy(){n=!0,o(),e.document.removeEventListener("visibilitychange",p)}}}function A(e,n,i){return new Promise(s=>{let o,t=()=>{clearTimeout(o),n.removeEventListener("visibilitychange",p),i.removeEventListener("abort",t),s()},r=()=>{clearTimeout(o),o=setTimeout(t,n.visibilityState==="hidden"?Math.max(e,3e4):e)},p=()=>{n.visibilityState==="visible"?t():r()};n.addEventListener("visibilitychange",p),i.addEventListener("abort",t,{once:!0}),r(),i.aborted&&t()})}var P={zh:{pending:"\u5904\u7406\u4E2D",complete:"\u5DF2\u5B8C\u6210",cancelled:"\u5DF2\u53D6\u6D88",failed:"\u5931\u8D25",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"},en:{pending:"Processing",complete:"Completed",cancelled:"Cancelled",failed:"Failed",unknown:"Status unconfirmed"}};function B(e,n){return P[n?"zh":"en"][e]}export{z as a,S as b,F as c,L as d,H as e,O as f,I as g,A as h,B as i};
|
package/dist/chunk-5JWMP4YD.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{p as n,s as t}from"./chunk-QBA3B4YK.js";function u(o,e,a){return n(o,e,a,t)}export{u as a};
|
package/dist/chunk-7VRZYSTR.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{A as et,B as fe,F as tt,c as Be,d as Je,e as we,i as qe,j as He,k as $e,o as Ke,r as We}from"./chunk-QBA3B4YK.js";import{d as Xe}from"./chunk-ITGERPCJ.js";import{c as Fe,d as Ne,e as Te,f as _e,g as Le,i as De,m as Me,n as k,o as ke,q as ye,r as N,t as Ge,u as je,v as ze}from"./chunk-NAZU3EEJ.js";import{$ as D,H as he,I as Ve,u as Ue}from"./chunk-R23IGK5U.js";import{a as de,b as Qe}from"./chunk-WTVLNUMS.js";import{a as ce}from"./chunk-VYFSRHXM.js";import{V as le}from"./chunk-N7YXDSQL.js";import{a as L}from"./chunk-X4W22IH6.js";import{h as oe}from"./chunk-R4FDIYMN.js";import{b as Ze}from"./chunk-3VUPVXAV.js";import{b as Ye}from"./chunk-WKIR2EQG.js";import{b as e}from"./chunk-VF6QMMEA.js";import{c as Ae,f as Pe}from"./chunk-7QL4GF4C.js";var G=e.literal(Ue),ft=e.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),Ie=e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),nt=e.discriminatedUnion("type",[e.strictObject({type:e.literal("guest"),guestToken:Ie}),e.strictObject({type:e.literal("customer"),customer:he,customerData:Ve.optional()})]),ve=e.strictObject({id:e.uuid(),runId:e.uuid(),customerId:e.uuid(),requestId:e.uuid(),acceptedAt:e.iso.datetime({offset:!0})}),mt=e.strictObject({participantId:e.uuid(),startedAs:e.enum(["guest","identified"]),binding:ve.omit({runId:!0,requestId:!0}).nullable()}),pt=e.union([Be,e.strictObject({type:e.literal("authentication_required"),reason:e.enum(["customer_required","customer_experiment_required"]),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative()})]),gt=Je.omit({authenticated:!0}).extend({identity:mt,instruction:pt.nullable()}),ht=e.discriminatedUnion("operation",[D.options[2].omit({customerToken:!0}),D.options[3].omit({customerToken:!0}),D.options[4].omit({customerToken:!0}),D.options[5].omit({customerToken:!0}),D.options[6].omit({customerToken:!0}),D.options[7].omit({customerToken:!0})]),me={contract:G,customerToken:e.string().regex(ce)},rt={contract:G,requestId:e.uuid(),runToken:ft,externalUserId:he.options[1].shape.value},ot=e.discriminatedUnion("operation",[e.strictObject({contract:G,operation:e.literal("describe")}),e.strictObject({contract:G,operation:e.literal("start"),source:nt,funnelId:D.options[0].shape.funnelId,requestId:e.uuid(),locale:D.options[0].shape.locale,parameters:D.options[0].shape.parameters}),qe.omit({operation:!0}).extend({contract:G,operation:e.literal("entry_start"),source:nt}),e.strictObject({...rt,operation:e.literal("bind_customer"),guestToken:Ie,claimRequestId:e.uuid(),expectedBindingId:e.null()}),e.strictObject({...rt,operation:e.literal("binding_status"),guestToken:Ie.optional()}),D.options[1].omit({operation:!0,customerToken:!0}).extend({...me,operation:e.literal("get"),settlementBindingId:e.uuid().nullable().optional()}),D.options[8].omit({operation:!0,customerToken:!0}).extend({...me,operation:e.literal("review")}),$e.omit({customerToken:!0}).extend(me),e.strictObject({...me,operation:e.literal("command"),identity:e.strictObject({bindingId:e.uuid().nullable()}),command:ht})]),yt=we.omit({run:!0}).extend({contract:G,run:gt,settlement:we.shape.settlement.unwrap().extend({accepted:e.boolean().nullable().optional()}).optional()}),Nt=He.extend({contract:G}),Tt=e.discriminatedUnion("operation",[ot.options[1].omit({contract:!0,source:!0,requestId:!0}),ot.options[2].omit({contract:!0,source:!0,requestId:!0})]),_t=yt.extend({binding:ve,outcome:e.enum(["bound","already_bound"]),replayed:e.boolean()}),Lt=e.discriminatedUnion("state",[e.strictObject({contract:G,scope:oe,state:e.literal("not_accepted")}),e.strictObject({contract:G,scope:oe,state:e.literal("conflict")}),e.strictObject({contract:G,scope:oe,state:e.literal("bound"),binding:ve})]),Dt=e.strictObject({contract:G,scope:oe,keyId:e.uuid(),operations:e.array(e.string()).max(20)});var it=e.string().regex(/^[a-f0-9]{64}$/),wt=Fe.omit({variations:!0,active:!0}).extend({changeId:it,variations:e.array(e.strictObject({urlRedirect:e.string().max(2048)})).min(2).max(20)}),at=e.strictObject({environmentId:e.uuid(),trackExposures:e.boolean(),generation:it,experiments:e.array(wt).max(100),savedGroups:Ne}),It=e.strictObject({eventUuid:e.uuid(),timestamp:e.iso.datetime({offset:!0}).optional(),deviceId:e.string().min(1).max(128),sessionId:e.string().min(1).max(128).optional(),url:e.url().max(2048),pageTitle:e.string().max(512).optional(),experimentKey:e.string().min(1).max(255),variationKey:e.string().min(1).max(64)}),kt=e.strictObject({events:e.array(It).min(1).max(20)}),Gt=e.strictObject({inserted:e.number().int().nonnegative(),duplicates:e.number().int().nonnegative(),skipped:e.number().int().nonnegative(),rejected:e.array(e.strictObject({index:e.number().int().nonnegative(),reason:e.string()}))});function Ht(r){let o=null,f=null,E=0,b=0,C=new Set,c=null,y=null,d=new Set,v=()=>{for(let s of d)try{s()}catch{}},l={attributes:le.parse(r.attributes??{}),onFeatureUsage:r.onFeatureUsage?(s,w)=>{!C.has(s)&&o&&(!("analyticsConfig"in o)||o.analyticsConfig.featureUsageEnabled)&&r.onFeatureUsage(s,structuredClone(w),structuredClone(l.attributes),o.generation)}:void 0,onExperimentViewed:r.onExperimentViewed?(s,w)=>o&&(!("analyticsConfig"in o)||o.analyticsConfig.experimentViewsEnabled)&&r.onExperimentViewed(structuredClone(s),structuredClone(w),structuredClone(l.attributes),o.generation):void 0,stickyBucketAssignmentDocs:structuredClone(r.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:r.saveStickyBucketAssignmentDoc?s=>r.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},S=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function p(s,w=new Set){return C.has(s)?!c||!c.features[s]||["unknownFeature","cyclicPrerequisite"].includes(c.features[s].source):w.has(s)?!1:(w.add(s),(o?.features[s]?.rules??[]).some(O=>[...O.parentConditions??[],...(O.tracks??[]).flatMap(A=>A.experiment.parentConditions??[])].some(A=>p(A.id,w))))}let x=s=>{if(r.assertUsable?.(o?.generation),!o)throw new Error("Initialize the Feature client before evaluation");if(o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return c?.expiresAt&&Date.parse(c.expiresAt)<=Date.now()&&(c=null,l.features=o.features),C.has(s)?!c||c.expiresAt&&Date.parse(c.expiresAt)<=Date.now()?S():structuredClone(c.features[s]??S()):r.evaluateRemote&&(l.attributes?.merchandise||l.attributes?.merchandiseId)&&!c||p(s)?S():structuredClone(Pe(s,l))};async function U(){if(!o||!C.size&&!l.attributes?.merchandise&&!l.attributes?.merchandiseId)return;if(!r.evaluateRemote){if(C.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=b;if(y?.revision===s)return y.loading;let w=E,O=o,A=[...C],R=(async()=>{let h=De.parse(await r.evaluateRemote({attributes:structuredClone(l.attributes),features:A}));if(!(w!==E||s!==b||O!==o)){if(r.assertUsable?.(O.generation),h.generation!==O.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(A.some(P=>!Object.hasOwn(h.features,P))||Object.keys(h.features).some(P=>!C.has(P)))throw new Error("Invalid remote Feature results");if(l.attributes?.merchandise||l.attributes?.merchandiseId){if(!h.merchandiseContext)throw new Error("Server did not resolve merchandise context");l.attributes=le.parse({...l.attributes,...h.merchandiseContext})}c=structuredClone(h),l.features={...O.features,...Object.fromEntries(Object.entries(c.features).map(([P,z])=>[P,{defaultValue:z.value}]))},v()}})();y={revision:s,loading:R};try{await R}finally{y?.loading===R&&(y=null)}}function T(){U().catch(s=>{try{r.onError?.(s)}catch{}})}async function M(){if(f)return f;let s=E,w=(async()=>{let O=await r.load(),A="remoteFeatures"in O?_e.parse(O):null,R=A??Te.parse(O);if(R.scope.projectId!==r.scope.projectId||R.scope.environment!==r.scope.environment)throw new Error("Feature payload scope changed");if(s!==E)throw new Error("Feature client was reset");if(r.assertUsable&&o?.generation===R.generation){let{evaluatedAt:P,expiresAt:z,...ie}=o,{evaluatedAt:Y,expiresAt:pe,...j}=R;if(N(ie)!==N(j))throw new Error("Immutable Feature generation changed content");return o.evaluatedAt=R.evaluatedAt,o.expiresAt=R.expiresAt,v(),(!c||c.expiresAt&&Date.parse(c.expiresAt)<=Date.now())&&T(),structuredClone(o)}let h=new Set(A?.remoteFeatures??[]);if([...h].some(P=>Object.hasOwn(R.features,P)))throw new Error("Remote Feature definitions must not be delivered locally");return o&&"analyticsConfig"in o&&"analyticsConfig"in R&&!o.analyticsConfig.experimentViewsEnabled&&A?.analyticsConfig.experimentViewsEnabled&&l.trackedExperiments?.clear(),o=structuredClone(R),C=h,c=null,y=null,b++,l.features=o.features,l.savedGroups=Ae(o.savedGroups),l.trackedFeatureUsage={},v(),T(),structuredClone(o)})();f=w;try{return await w}finally{f===w&&(f=null)}}return{init:M,refresh:M,refreshRemote:U,get generation(){return o?.generation??null},get expiresAt(){return o?.expiresAt??null},subscribe(s){return d.add(s),()=>{d.delete(s)}},setAttributes(s){let w=le.parse(s);(l.attributes?.merchandise||l.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&l.trackedExperiments?.clear(),l.attributes=w,b++,c=null,y=null,l.features=o?.features??{},l.trackedFeatureUsage={},v(),T()},evalFeature:x,isOn(s){return x(s).on},isOff(s){return x(s).off},getFeatureValue(s,w){let O=x(s).value;return structuredClone(O===null?w:O)},reset(){E++,b++,f=null,y=null,o=null,c=null,C.clear(),l.features={},l.savedGroups={},l.stickyBucketAssignmentDocs={},l.attributes={},l.trackedFeatureUsage={},l.trackedExperiments?.clear(),v()}}}var vt=e.record(e.string().regex(/^[a-f0-9]{64}$/),e.strictObject({at:e.number(),text:e.string()})),K=2*1048576,bt=100;function St(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function st(r,o){let f=o===void 0?St():o,E=new Map,b=0,C=!1,c=!1,y,d;async function v(S){if(!f)return null;let p;try{let x=await Promise.race([Promise.resolve().then(()=>f.getItem(S)),new Promise(U=>{p=setTimeout(()=>U(null),bt)})]);return typeof x=="string"&&x.length<=K&&new TextEncoder().encode(x).byteLength<=K?x:null}catch{return null}finally{clearTimeout(p)}}function l(){if(d)return d;let S=(async()=>{try{let p=await v(`${r}:artifacts`);if(p)return vt.parse(JSON.parse(p))}catch{}return{}})();return d=S,S.finally(()=>{d===S&&(d=void 0)}),S}return{async readManifest(){return v(r)},writeManifest(S){!f||S.length>K||new TextEncoder().encode(S).byteLength>K||(y=S,!c&&(c=!0,Promise.resolve().then(async()=>{try{for(;y!==void 0;){let p=y;try{await f.setItem(r,p)}catch{}y===p&&(y=void 0)}}finally{c=!1}})))},async readArtifact(S){let p=(await l())[S],x=Date.now();return p&&x>=p.at&&x-p.at<=k.retentionMs?p.text:void 0},writeArtifact(S,p){if(!f||p.length>K)return;let x=E.get(S);if(x?.text===p||!x&&E.size>=128)return;let U=new TextEncoder().encode(p).byteLength;b-(x?.byteLength??0)+U>K||(E.set(S,{text:p,byteLength:U}),b+=U-(x?.byteLength??0),!C&&(C=!0,Promise.resolve().then(async()=>{try{for(;E.size;){let T=new Map(E);try{let M={...await l()},s=Date.now();for(let[R,h]of T)M[R]={at:s,text:h.text};let w={},O=2,A=0;for(let[R,h]of Object.entries(M).sort(([,P],[,z])=>z.at-P.at)){if(h.at>s||s-h.at>k.retentionMs)continue;let P=new TextEncoder().encode(JSON.stringify({[R]:h})).byteLength;O+P>K||A>=128||(w[R]=h,O+=P,A++)}await f.setItem(`${r}:artifacts`,JSON.stringify(w))}catch{}finally{for(let[M,s]of T)E.get(M)===s&&(E.delete(M),b-=s.byteLength)}}}finally{C=!1}})))}}}var u=(r,o)=>new L(r,o),q=()=>performance.now(),ut=r=>{typeof r=="object"&&"unref"in r&&r.unref()};function ln(r){let o=ke.parse(r.scope),f=new de(r.origin??Ye);if(f.username||f.password||f.search||f.hash||f.pathname!=="/"||f.protocol!=="https:"&&!(f.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(f.hostname)))throw u("INVALID_URL","Configuration requires a trusted HTTPS origin");let E=new Set([f.origin,...(r.assetOrigins??[]).map(n=>{let t=new de(n);if(t.protocol!=="https:"||t.username||t.password||t.search||t.hash||t.pathname!=="/")throw u("INVALID_URL","Invalid configuration asset origin");return t.origin})]),b=r.fetch??globalThis.fetch.bind(globalThis),C=`/api/v1/configuration/${o.environmentId}`,c=`indiana:configuration:1:${f.origin}:${N(o)}`,y=st(c,r.storage),d,v=0,l=0,S=!1,p=!1,x=0,U=0,T,M,s,w,O=0,A=new Set,R=new Set,h=new Map,P=new Map,z=0,ie=!1;function Y(){for(let n of A)try{n()}catch{}}function pe(n){try{r.onError?.(n)}catch{}}let j=()=>!p&&!S&&!!d&&q()<v&&Date.now()<l;function ne(){if(!j())throw u("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function be(n,t,i){if(!h.has(n)){for(;h.size&&(h.size>=128||z+i>k.maxCacheBytes);){let a=h.entries().next().value;z-=a[1].byteLength,h.delete(a[0])}h.set(n,{text:t,byteLength:i}),z+=i}}function Se(n,t,i){return Ze(n,t,{signal:i,error:a=>u("INVALID_RESPONSE",a==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function xe(n){let t=new de(n,f);if(!E.has(t.origin)||t.username||t.password||t.hash||t.search)throw u("INVALID_URL","Configuration artifact origin is not trusted");return t.href}async function ge(n,t,i=!1){let a=await b(xe(n),{method:"GET",credentials:"omit",redirect:"error",cache:i?"default":"no-cache",signal:t,headers:{}});if(a.status===429){let g=a.headers.get("retry-after")??"";O=/^\d+$/.test(g)?Number(g)*1e3:Math.max(0,Date.parse(g)-Date.now())||15e3}if(!a.ok&&a.status!==304)throw u(`CONFIGURATION_HTTP_${a.status}`,"Configuration synchronization failed");return a}function lt(n,t,i){let a=Date.parse(n.headers.get("x-indiana-config-validated-at")??""),g=Date.parse(n.headers.get("x-indiana-config-valid-until")??""),I=Date.parse(n.headers.get("date")??""),m=n.headers.get("age"),V=m!==null&&/^\d+(\.\d+)?$/.test(m)?Number(m)*1e3:NaN;if(![a,g,I,V].every(Number.isFinite)||g<=a||g-a>k.maxControlAgeMs||a>I+1e3)throw u("INVALID_RESPONSE","Configuration freshness evidence is invalid");let F=Math.min(g-a,i.maxControlAgeSeconds*1e3,k.maxControlAgeMs)-Math.max(V,I-a,0)-(q()-t);if(F<=0)throw u("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return q()+F}function ae(){if(clearTimeout(s),clearTimeout(w),p||!A.size||(j()&&(w=setTimeout(()=>{j()?ae():Y()},Math.max(1,v-q())),ut(w)),typeof document<"u"&&document.visibilityState==="hidden"))return;let n=U?Math.min(15e3,1e3*2**Math.min(U-1,4)):Math.min(15e3,(d?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{Q().catch(pe)},Math.max(O,n*(.8+Math.random()*.2))),ut(s)}async function Q(){if(p)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(T)return T;let n=x,t=new AbortController;M=t;let i=(async()=>{if(!ie){ie=!0;try{let ue=await y.readManifest();if(ue&&!d){let J=ye.parse(JSON.parse(ue));N(J.scope)===N(o)&&(d=J)}}catch{}}t.signal.throwIfAborted();let m=d,V=q(),_=await ge(C,t.signal);_.status===304&&(!m||!_.headers.has("x-indiana-config-validated-at")||!_.headers.has("x-indiana-config-valid-until")||!_.headers.has("age"))&&(_=await ge(C,t.signal));let F=_.status===304?m:ye.parse(JSON.parse(await Se(_,k.maxManifestBytes,t.signal))),{generation:ee,...te}=F,B=_.headers.get("etag");if(N(F.scope)!==N(o)||Ge(te)!==ee||B!==`"${ee}"`&&B!==`W/"${ee}"`)throw u("INVALID_RESPONSE","Configuration scope or content identity changed");if(m&&(F.revision<m.revision||F.revision===m.revision&&F.generation!==m.generation))throw u("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[ue,J]of Object.entries(m?.funnels??{})){let $=F.funnels[ue];if($&&($.controlRevision<J.controlRevision||$.evaluationRevision<J.evaluationRevision||$.controlRevision===J.controlRevision&&$.state!==J.state||$.evaluationRevision===J.evaluationRevision&&$.evaluationMode!==J.evaluationMode))throw u("INVALID_RESPONSE","Funnel control revision changed identity")}let H=lt(_,V,F.policy);if(t.signal.throwIfAborted(),n!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return d=F,v=H,l=Date.now()+Math.max(0,H-q()),S=!1,U=0,O=0,y.writeManifest(N(F)),Y(),structuredClone(F)})(),a=setTimeout(()=>t.abort(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),k.initializationMs),g=new Promise((m,V)=>t.signal.addEventListener("abort",()=>V(t.signal.reason),{once:!0})),I=Promise.race([i,g]).catch(m=>{throw U++,(m instanceof e.ZodError||m instanceof SyntaxError||m instanceof L&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(m.code))&&(v=0,S=!0,Y()),m}).finally(()=>{clearTimeout(a),T===I&&(T=void 0),ae()});return T=I,I}async function se(n){let t=n.sha256,i=te=>Xe(te,n);xe(n.url);let a=h.get(t);if(a){if(a.byteLength!==n.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return h.delete(t),h.set(t,a),a.text}let g=P.get(t);if(g){if(g.byteLength!==n.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return g.promise}let I=new AbortController;R.add(I);let m=x,V=(async()=>{try{let H=await y.readArtifact(t);if(H&&i(H)){if(I.signal.throwIfAborted(),p||m!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return be(t,H,n.byteLength),H}}catch{}I.signal.throwIfAborted();let te=await ge(n.url,I.signal,!0),B=await Se(te,n.byteLength,I.signal);if(!i(B))throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(p||m!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return be(t,B,n.byteLength),y.writeArtifact(t,B),B})(),_=setTimeout(()=>I.abort(u("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),k.initializationMs),F=new Promise((te,B)=>I.signal.addEventListener("abort",()=>B(I.signal.reason),{once:!0})),ee=Promise.race([V,F]).finally(()=>{clearTimeout(_),R.delete(I),P.delete(t)});return P.set(t,{promise:ee,byteLength:n.byteLength}),ee}async function re(){return j()||await Q(),ne(),d}async function W(n){let t,i=new Promise((a,g)=>{t=setTimeout(()=>g(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),k.initializationMs)});try{return await Promise.race([n(),i])}finally{clearTimeout(t)}}function Z(n,t){if(ne(),d?.generation!==n.generation)throw u("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(t&&d.funnels[t]?.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Ee(n){let t=n.gb.features;if(!t)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let i=n.artifacts[t];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let a=Le.parse(JSON.parse(await se(i)));if(N(a.scope)!==N({projectId:o.projectId,environment:o.environment})||a.generation!==i.generation||a.remoteFeatures.some(g=>Object.hasOwn(a.features,g)))throw u("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return Z(n),{...a,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,v-q())).toISOString()}}async function Ce(n,t){let i=await re(),a=i.funnels[n];t&&(!a||a.evaluationMode==="local"&&!a.versions[t])&&(T&&await T,i=await Q()),Z(i,n);let g=i.funnels[n];if(g.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let I=t??g.currentVersionId,m=g.versions[I];if(!m)throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(i.artifacts[m.artifact].formatVersion!==3)throw u("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[V,_]=await Promise.all([se(i.artifacts[m.artifact]).then(F=>ze(JSON.parse(F))),g.evaluationMode==="local"?Ee(i):void 0]);if(_&&N(je(V,_))!==N(m.dependencies))throw u("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return Z(i,n),{document:V,growth:_,versionId:I,control:structuredClone(g),manifest:structuredClone(i)}}async function Re(n,t){try{return await Ce(n,t)}catch(i){if(!(i instanceof L)||!(i.code==="CONFIGURATION_CHANGED"||i.code==="CONFIGURATION_HTTP_404"&&j()))throw i;let a=d?.generation;if(T&&await T,await Q(),i.code!=="CONFIGURATION_CHANGED"&&d?.generation===a)throw i;return Ce(n,t)}}function X(){if(j()||Y(),typeof document<"u"&&document.visibilityState==="hidden"){ae();return}Q().catch(pe)}function dt(n){if(p)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return A.add(n),A.size===1&&(typeof window<"u"&&(window.addEventListener("online",X),window.addEventListener("focus",X),document.addEventListener("visibilitychange",X)),ae()),()=>{A.delete(n),A.size||(clearTimeout(s),clearTimeout(w),Oe())}}function Oe(){typeof window<"u"&&(window.removeEventListener("online",X),window.removeEventListener("focus",X),document.removeEventListener("visibilitychange",X))}return{scope:Object.freeze({...o}),refresh:Q,subscribe:dt,assertFresh:ne,assertFeatures(n){ne();let t=d.gb.features;if(!t)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(n!==void 0&&d.artifacts[t].generation!==n)throw u("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return j()},get snapshot(){return d?structuredClone(d):null},get remainingMs(){return j()?Math.max(0,v-q()):0},async features(){return W(async()=>Ee(await re()))},pageExperiments:()=>W(async()=>{let n=await re(),t=n.gb.pageExperiments;if(!t)throw u("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let i=n.artifacts[t];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let a=at.parse(JSON.parse(await se(i)));if(a.environmentId!==o.environmentId||a.generation!==i.generation)throw u("INVALID_RESPONSE","Page experiment scope or generation changed");return Z(n),a}),funnel:(n,t)=>W(()=>Re(n,t)),funnelControl:n=>W(async()=>{let t=await re();return Z(t,n),structuredClone(t.funnels[n])}),paywall:(n,t)=>W(async()=>{let i=await re(),a=i.paywalls?.[n];if(!a||!t&&a.state!=="published")throw u("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let g=t??a.currentVersionId,I=a.versions[g],m=I&&i.artifacts[I.artifact];if(!m||m.kind!=="paywall"||m.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let V=Me.parse(JSON.parse(await se(m)));return Z(i),{document:V,versionId:g,version:I.version,control:structuredClone(a),manifest:structuredClone(i)}}),async localFunnel(n,t){let i=await W(()=>Re(n,t));if(!i.growth)throw u("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:a,remoteFeatures:g,...I}=i.growth;return Ke({scope:{projectId:o.projectId,environment:o.environment},funnelId:n,versionId:i.versionId,evaluationMode:"local",evaluationRevision:i.control.evaluationRevision,document:i.document,payload:I})},assertFunnel(n,t,i){ne();let a=d.funnels[n];if(!a||a.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable");if(a.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel now executes at Longplay");if(t!==void 0&&a.controlRevision!==t)throw u("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(i!==void 0&&!a.versions[i])throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!p){p=!0,x++,v=0,M?.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(w),Oe(),Y(),A.clear();for(let n of R)n.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));h.clear(),z=0}}}}function ct(r){let o=ce.test(r.apiKey);if(typeof window<"u"&&!o)throw new L("SERVER_ONLY","Funnel starts are issued by your backend");if(!o&&!fe.test(r.apiKey))throw new L("INVALID_TOKEN","A customer credential or server API key is required");return{async start(f){let E=D.safeParse({...f,operation:"start"});if(!E.success||E.data.operation!=="start"||(o?E.data.customer!==void 0:E.data.customer===void 0))throw new L("INVALID_REQUEST","Invalid current Funnel start");let b=E.data,C=Qe({...r,timeoutMs:r.timeoutMs??35e3});try{r.session||C.identify(r.apiKey);let c=We(r,await C.request("funnels",b));if(!c.runToken)throw new L("INVALID_RESPONSE","Funnel start credentials are missing");if(c.run.source.id!==b.funnelId||c.run.locale!==(b.locale??"en")||!et(c.run.parameters,b.parameters??{})||(b.customer?!c.customerId||b.customer.type==="id"&&c.customerId!==b.customer.value:c.customerId!==void 0))throw new L("INVALID_RESPONSE","Funnel start contract changed");return{...c,runToken:c.runToken}}finally{C.dispose()}}}}async function En(r){r={...r};let o=r.configuration;if(!o)throw new L("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let f={projectId:o.scope.projectId,environment:o.scope.environment};if(r.scope&&N(f)!==N(r.scope))throw new L("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await o.funnelControl(r.funnelId)).evaluationMode!=="local")throw new L("EVALUATION_MODE","This Funnel uses Remote evaluation");let b=fe.test(r.credential);if(b?!r.customerId:r.customerId!==void 0)throw new L("INVALID_REQUEST","Only Server-Key starts name their Customer");let C=ct({...r,scope:f,apiKey:r.credential}),c=(y,d)=>{let v=tt({...r,scope:f,runToken:y,initialResponse:d,...b?{serverKey:r.credential}:{}});return b||v.identify(r.credential),v};return{async start(y){let d=await C.start({...y,funnelId:r.funnelId,...b?{customer:{type:"id",value:r.customerId}}:{}}),v=c(d.runToken,d),l=await v.get();return{...d,...l,controller:v}},async restore(y){let d=c(y),v=await d.get();if(v.run.source.id!==r.funnelId)throw d.reset(),new L("SCOPE_MISMATCH","Run belongs to another Funnel");return{...v,runToken:y,controller:d}}}}export{ot as a,yt as b,Nt as c,Tt as d,_t as e,Lt as f,Dt as g,Ht as h,ln as i,ct as j,En as k};
|
package/dist/chunk-EHDHWYVJ.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as c}from"./chunk-X4W22IH6.js";function d(t){let{quote:r,operation:e,requestId:i}=t,o={type:"recover",operationId:e?.operationId??r?.operationId??null,requestId:i};if(t.destroyed||t.pending)return o;if(!e)return r?{type:"cancel",operationId:r.operationId}:o;let n=e.merchantExecution;if(n?.type==="purchase"){if(["succeeded","not_required"].includes(n.paymentStatus))return!["applied","not_applicable"].includes(n.fulfillmentStatus)||e.problem?.phase==="fulfillment"||n.problem?.phase==="fulfillment"?{type:"fulfillment",operationId:e.operationId}:{type:n.recordingStatus==="accepted"&&e.status==="complete"&&!e.problem&&!n.problem?"complete":"recording",operationId:e.operationId};if(e.status==="pending"&&e.checkoutUrl&&n.checkoutUrl===e.checkoutUrl&&n.checkoutExpiresAt&&Date.parse(n.checkoutExpiresAt)>Date.now()&&["not_started","pending"].includes(n.paymentStatus))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl}}if(e.executor==="indiana"&&e.status==="pending"&&e.checkoutUrl&&!e.problem&&!e.nativePurchase&&(!r||Date.parse(r.expiresAt)>Date.now()))return{type:"checkout",operationId:e.operationId,checkoutUrl:e.checkoutUrl};let p=[e.problem,n?.problem],s=p.every(u=>!u||u.phase==="execution"&&u.reason!=="RESULT_UNKNOWN");return!p.some(Boolean)&&e.status==="complete"&&e.executor!=="merchant"?{type:"complete",operationId:e.operationId}:s&&t.canReselect!==!1&&["cancelled","failed"].includes(e.status)&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase&&(e.executor!=="merchant"?!e.confirmedAt&&(e.status==="cancelled"||!e.quoteFinalized):!n&&!e.quoteFinalized||n?.type==="purchase"&&["failed","expired"].includes(n.paymentStatus)&&n.fulfillmentStatus==="not_applicable"&&n.recordingStatus==="accepted")?{type:"native",operationId:e.operationId}:e.status==="pending"&&s&&!e.quoteFinalized&&!n&&!e.checkoutUrl&&!e.execution&&!e.nativePurchase?{type:"cancel",operationId:e.operationId}:o}function f(t,r=!0){if(!t)return!1;let e=d({quote:t.quote??null,operation:t,requestId:null,pending:!1,destroyed:!1,canReselect:r});return e.type==="complete"||e.type==="native"}function l(t){return t.recovery??{type:"recover",operationId:t.operation?.operationId??t.quote?.operationId??null,requestId:null}}async function y(t){let r=l(t);if(r.type==="recover"&&t.quote)try{await t.read(),r=l(t)}catch{return r}if(r.type!=="cancel"&&!(r.type==="recover"&&t.pendingCancellation))return r;try{await t.cancel();let e=l(t);return e.type==="cancel"?{type:"recover",operationId:r.operationId,requestId:null}:e}catch{let e=l(t);return e.type==="recover"?e:{type:"recover",operationId:r.operationId,requestId:null}}}function m(t,r){let e=structuredClone(t);for(let[i,a]of Object.entries(e.plans)){let o=r.plans[i];!o||o.versionId!==a.versionId||(o.amountMinor!==void 0&&(a.amountMinor=o.amountMinor),o.interval!==void 0&&(a.interval=o.interval),o.intervalCount!==void 0&&(a.intervalCount=o.intervalCount),o.prepaid!==void 0&&(a.prepaid=structuredClone(o.prepaid)))}return e}function b(t,r){let e=i=>"document"in i?i.offering.id:i.content.offeringVersionId;return t.id===r.id&&e(t)===e(r)&&t.content?.artifact.sha256===r.content?.artifact.sha256}function S(t,r,e){if(t.operationId!==r.operationId||r.currency!==void 0&&t.currency!==r.currency)throw new c("INVALID_RESPONSE",e)}function v(t,r,e){let i=Object.fromEntries((t.lines[0]?.prepaid??[]).map(a=>[a.internal_feature_id,a.quantity]));if(r.featureQuantities&&(Object.keys(i).length!==Object.keys(r.featureQuantities).length||Object.entries(r.featureQuantities).some(([a,o])=>i[a]!==o)))throw new c("INVALID_RESPONSE","The purchase quote changed its selected quantities");if(t.lines.length!==1||t.lines[0].productVersionId!==r.productVersionId||r.currency!==void 0&&t.currency!==r.currency||r.provider!==void 0&&t.provider!==r.provider&&!(r.provider==="stripe"&&t.provider==="merchant"&&t.execution?.provider==="merchant"))throw new c("INVALID_RESPONSE",e)}function g(t,r,e=!1){if(!t||t.operationId!==r?.operationId)return r;let i=t.merchantExecution,a=r.merchantExecution;return i&&(!a||Date.parse(a.updatedAt)<Date.parse(i.updatedAt))||t.status==="complete"&&r.status!=="complete"||t.status!=="pending"&&(r.status==="pending"||e&&r.status!=="complete")?t:r}function w(t){return t.screen.actions.some(r=>r.properties.closeControl==="content"&&t.buttons[r.id]?.type==="close")}export{d as a,f as b,l as c,y as d,m as e,b as f,S as g,v as h,g as i,w as j};
|
package/dist/chunk-ERJP2GBD.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{e as h}from"./chunk-ILEDKSRQ.js";import{b as J}from"./chunk-FYQXSGRT.js";import{c as N,e as x}from"./chunk-ITGERPCJ.js";import{v as Q}from"./chunk-SCC3O2RD.js";import{a as j,f as H,g as K,h as B,i as F}from"./chunk-EHDHWYVJ.js";import{b as L}from"./chunk-BXPXJARS.js";import{b as U}from"./chunk-WTVLNUMS.js";import{a as M}from"./chunk-VYFSRHXM.js";import{qa as G}from"./chunk-N7YXDSQL.js";import{a as l}from"./chunk-X4W22IH6.js";import{a as W}from"./chunk-DSPLGTQI.js";async function ce(I,o){if(!M.test(o.customerToken))throw new l("INVALID_TOKEN","A verified Customer credential is required");if(I.session&&I.session.peek()!==o.customerToken)throw new l("SCOPE_MISMATCH","Paywall credential does not match the shared session");let u=h.resolvePaywall.request.parse({funnelId:o.funnelId,funnelVersionId:o.funnelVersionId,selector:o.paywallVersionId?{type:"version",versionId:o.paywallVersionId}:{type:"paywall",paywallId:o.paywallId},commerce:o.commerce,locale:o.locale,...o.requirement?{requirement:o.requirement}:{}}),S=U(I);I.session||S.identify(o.customerToken);let r=null,P=!1,D=new AbortController,s=null,c=null,v=null,w=null,R=null,d=null,f=null,A=0,O=null,_="",V=0,b=new Map,q=new Set;function g(){if(P)throw new l("IDENTITY_CHANGED","Paywall is closed")}function k(){let e=JSON.stringify([A,f!==null]);if(!O||e!==_){_=e;let t=Y(++V);O=t;let a=()=>{O===t&&(O=null)};t.then(a,a)}return O.then(t=>structuredClone(t))}async function Y(e){g();let t=h.resolvePaywall,a=await N(S.request,t,{...u,selector:r?{type:"version",versionId:r.id}:u.selector});J(u,a.paywall.check,a.scope);let i=await x(I,a.paywall);if(g(),o.paywallVersionId?i.id!==o.paywallVersionId:i.paywallId!==o.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");if(r&&(!H(i,r)||i.paywallId!==r.paywallId))throw new l("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");if(e!==V)return structuredClone(r??i);r=i;for(let m of q)W(m,structuredClone(r));return structuredClone(r)}async function E(e){if(g(),w&&e!=="read")throw new l("COMMAND_PENDING","Wait for the original quote");if(!s)throw new l("INVALID_REQUEST","A quoted purchase is required");let t=s;if(e!=="read"){if(f){if(d===e)return f;throw new l("COMMAND_PENDING","Wait for the original purchase command")}if(d&&d!==e)throw new l("COMMAND_PENDING","Read the original purchase before changing an uncertain command");d=e,A++,V++}let a=d,i=A,m=e==="read"&&f===null,p=JSON.stringify([t.operationId,i,f!==null]);if(e==="read"&&b.has(p))return b.get(p).then(n=>structuredClone(n));let C=e==="read"?h.readSubscriptionOperation:h.attach,y=(async()=>{let n=await N(S.request,C,{operationId:t.operationId,...e==="read"?{}:{intent:e},...e==="confirm"&&t.merchantTerms?{merchantConfirmation:Q(t.merchantTerms)}:{}});return K(n.operation,{operationId:t.operationId,currency:u.commerce.currency},"The purchase operation changed"),g(),s?.operationId!==t.operationId?structuredClone(n.operation):(c=F(c,n.operation),(e!=="read"||m&&f===null)&&A===i&&d===a&&(d=null),structuredClone(c))})();if(e!=="read"){f=y;let n=()=>{f===y&&(f=null)};y.then(n,n)}else{b.set(p,y);let n=()=>{b.get(p)===y&&b.delete(p)};y.then(n,n)}return y.then(n=>structuredClone(n))}let T={signal:D.signal,get view(){return r?structuredClone(r):null},get quote(){return s?structuredClone(s):null},get operation(){return c?structuredClone(c):null},get webViewUrl(){return"bundled"},get recovery(){return j({quote:s,operation:c,requestId:R,pending:w!==null||d!==null,destroyed:P})},get pendingCancellation(){return!P&&d==="cancel"},refresh:k,subscribe(e){return P?()=>{}:(q.add(e),()=>q.delete(e))},async preview(e){if(g(),!r)throw new l("INVALID_REQUEST","Load the Paywall first");let t=r.document.buttons[e.actionId];if(t?.type!=="checkout")throw new l("INVALID_REQUEST","Choose an authored purchase action");let a=L(t.product,e.selection,r.capabilities);if(!a)throw new l("PRODUCT_UNAVAILABLE","Choose an available Product");let i=G(r.document.screen,a,e.selection,r.capabilities),m=h.previewAttach.request.parse({funnelId:u.funnelId,funnelVersionId:u.funnelVersionId,requestId:e.requestId,plans:[{productVersionId:a,...Object.keys(i).length?{featureQuantities:i}:{}}],provider:u.commerce.provider,currency:u.commerce.currency,...e.offerId?{offerId:e.offerId}:{},...e.nativeOffer?{nativeOffer:e.nativeOffer}:{}}),p=JSON.stringify(m);if(v&&v!==p&&(w||d||!c||c.status==="pending"))throw new l("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(v===p){if(w)return w;if(s)return structuredClone(s)}v!==p&&(s=null,c=null),v=p,R=m.requestId;let C=(async()=>{let y=h.previewAttach,n=await N(S.request,y,m);return g(),B(n.quote,{productVersionId:a,featureQuantities:i,currency:u.commerce.currency,provider:u.commerce.provider},"The purchase quote changed its selected Product or presentment"),s=n.quote,c=null,structuredClone(s)})();w=C;try{return await C}finally{w===C&&(w=null)}},confirm:()=>E("confirm"),cancel:()=>E("cancel"),read:()=>E("read"),destroy(){P||(P=!0,D.abort(),q.clear(),b.clear(),z?.(),S.dispose(),r=null,s=null,c=null,v=null,R=null)}},z=I.session?.subscribeIdentity(T.destroy);try{return await k(),T}catch(e){throw T.destroy(),e}}export{ce as a};
|
package/dist/chunk-ILEDKSRQ.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as tt,b as it}from"./chunk-EQPEUPMG.js";import{a as Ut,b as Mt,d as Et,h as Z,i as fe}from"./chunk-7MNJH5GB.js";import{a as V,b as rt,c as st,d as de,e as P,f as ot,g as I,h as ct,i as me,j as ut,k as dt,l as mt,m as pe,n as pt,o as lt,p as le,q as Tt,s as kt}from"./chunk-THMGTRXP.js";import{f as gt,h as ht,i as ft,j as bt,k as xt}from"./chunk-NAZU3EEJ.js";import{i as f,j as He,u as N}from"./chunk-SCC3O2RD.js";import{F as he,G as Ct,L as Q,M as _t,N as Rt,O as wt,P as Bt,Q as qt,o as nt,p as y,r as ue,s as at}from"./chunk-R23IGK5U.js";import{a as zt}from"./chunk-5HJYR6Z4.js";import{a as We,b as F}from"./chunk-VYFSRHXM.js";import{$ as yt,Z as B,_ as St,a as c,aa as It,ba as q,ca as vt,da as Ot,ea as ge,fa as j,ga as At,ha as Pt,ia as jt,j as Xe,k as Je,l as Ye,m as et,o as ce}from"./chunk-N7YXDSQL.js";import{h as se,i as p,j as s,k as oe,m as h}from"./chunk-R4FDIYMN.js";import{b as e}from"./chunk-VF6QMMEA.js";var be=e.strictObject({operationId:e.uuid(),customerId:e.uuid(),externalUserId:e.string().min(1).max(256),modelId:e.string().min(1).max(256),quantity:e.number().int().min(1).max(1e6),validForDays:e.number().int().min(1).max(3660)}),Dt=e.strictObject({operationId:e.uuid(),customerId:e.uuid(),status:e.literal("applied"),voucherId:e.uuid(),modelId:e.string().min(1).max(256),quantity:e.number().int().positive(),issuedAt:e.iso.datetime({offset:!0}),expiresAt:e.iso.datetime({offset:!0})}).refine(t=>Date.parse(t.expiresAt)>Date.parse(t.issuedAt),{message:"A benefit must expire after it is issued"}),Gt=e.strictObject({operationId:e.uuid(),customerId:e.uuid()}),xa=e.discriminatedUnion("lookup",[Gt.extend({lookup:e.literal("not_received")}),Gt.extend({lookup:e.literal("found"),result:Dt}).refine(t=>t.result.operationId===t.operationId&&t.result.customerId===t.customerId)]),$t=e.strictObject({customerId:e.string().min(1).max(256),modelId:e.string().min(1).max(256),quantity:be.shape.quantity,validForDays:be.shape.validForDays,requestId:e.uuid()}),Lt=e.strictObject({customerId:e.string().min(1).max(256),operationId:e.uuid()}),xe=e.strictObject({operationId:e.uuid(),customerId:e.uuid(),taskId:e.uuid(),status:e.enum(["pending","applied","rejected"]),terms:be,receipt:Dt.nullable(),failureCode:e.enum(["INVALID_REQUEST","CONNECTION_CHANGED"]).nullable()}).superRefine((t,n)=>{(t.terms.operationId!==t.operationId||t.terms.customerId!==t.customerId||t.status==="applied"!=(t.receipt!==null)||t.status==="rejected"!=(t.failureCode!==null)||t.receipt&&(t.receipt.operationId!==t.operationId||t.receipt.customerId!==t.customerId||t.receipt.modelId!==t.terms.modelId||t.receipt.quantity!==t.terms.quantity))&&n.addIssue({code:"custom",message:"Benefit result differs from the original accepted operation"})});var T=e.enum(["email","sms","voice","push"]),Ia=e.enum(["resend","twilio","fcm","apns"]);var va=e.string().regex(/^\+[1-9]\d{1,14}$/),Qr=e.enum(["email_recipient","sms_segment","voice_second","push_device"]);var Zr=e.string().trim().min(1).max(200).refine(t=>!/[\r\n\0]/.test(t),"Invalid email header"),Kr=e.strictObject({subject:Zr,html:e.string().min(1).max(131072).optional(),text:e.string().min(1).max(65536).optional()}).refine(t=>t.html!==void 0||t.text!==void 0,{message:"Email requires HTML or text content"}),Wr=e.strictObject({body:e.string().min(1).max(1600).refine(t=>t.trim().length>0)}),Hr=e.strictObject({text:e.string().trim().min(1).max(4e3),language:e.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:e.number().int().min(1).max(900)}),Xr=e.record(e.string().min(1).max(64),e.string().max(256)).refine(t=>Object.keys(t).length<=20&&Object.keys(t).every(n=>!/^(?:indiana_|google\.|gcm\.)/i.test(n)&&n!=="aps"),"Push data contains reserved fields or too many entries"),Jr=e.strictObject({title:e.string().trim().min(1).max(200),body:e.string().trim().min(1).max(2e3),url:e.url().max(2048).refine(t=>!/^(?:javascript|data|file|vbscript):/i.test(t)).optional(),data:Xr.optional()}).refine(t=>new TextEncoder().encode(JSON.stringify(t)).length<=3072,"Push content exceeds the provider payload budget"),Ft=e.discriminatedUnion("channel",[e.strictObject({channel:e.literal("email"),content:Kr}),e.strictObject({channel:e.literal("sms"),content:Wr}),e.strictObject({channel:e.literal("voice"),content:Hr}),e.strictObject({channel:e.literal("push"),content:Jr})]),Nt=e.strictObject({requestId:e.uuid(),customerId:e.uuid(),connectionId:e.uuid().optional(),message:Ft,expiresAt:e.iso.datetime({offset:!0})}),Yr=e.array(e.uuid()).min(1).max(1e4).refine(t=>new Set(t).size===t.length,"Duplicate Customer"),en=e.discriminatedUnion("kind",[e.strictObject({kind:e.literal("all")}),e.strictObject({kind:e.literal("customers"),customerIds:Yr})]),Oa=e.strictObject({name:e.string().trim().min(1).max(120),connectionId:e.uuid().optional(),message:Ft,audience:en,frequencyLimit:e.number().int().min(1).max(100)}),Vt=e.strictObject({requestId:e.uuid(),channel:T,state:e.enum(["allowed","denied"]),expectedRevision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),Qt=e.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Zt=e.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),Aa=e.strictObject({meter:Qr,estimatedUnits:e.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:e.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});var Kt=e.strictObject({requestId:e.uuid(),targets:e.array(e.strictObject({membershipId:e.uuid(),action:e.enum(["cancel","uncancel"]),timing:e.enum(["immediate","renewal"])}).refine(t=>t.action!=="uncancel"||t.timing==="immediate","Restoration is immediate")).min(1).max(100)}).refine(t=>new Set(t.targets.map(n=>n.membershipId)).size===t.targets.length,"Duplicate batch target"),K=e.strictObject({batchId:e.uuid()}),tn=e.strictObject({operationId:e.uuid(),membershipIds:e.array(e.uuid()).min(1).max(20),provider:e.enum(["stripe","apple","google"]),action:e.enum(["cancel","uncancel"]),timing:e.enum(["immediate","renewal"]),status:e.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:dt.nullable(),managementUrl:e.url().nullable(),failureCode:e.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),k=e.strictObject({batchId:e.uuid(),ready:e.boolean(),status:e.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:e.iso.datetime({offset:!0}),acceptedAt:e.iso.datetime({offset:!0}).nullable(),groups:e.array(tn).min(1).max(100)});var rn=e.string().trim().min(1).max(240),Se={requestId:e.uuid(),reason:rn},W=e.discriminatedUnion("action",[e.strictObject({...Se,action:e.literal("start"),productVersionId:e.uuid(),entityId:e.uuid().optional(),days:e.number().int().min(1).max(730).optional()}),e.strictObject({...Se,action:e.literal("extend"),membershipId:e.uuid(),days:e.number().int().min(1).max(730)}),e.strictObject({...Se,action:e.literal("end"),membershipId:e.uuid()})]),Wt=e.strictObject({operationId:e.uuid()}),Ht=e.iso.datetime({offset:!0}),nn=e.strictObject({provider:e.literal("stripe"),executor:e.enum(["indiana","merchant"]),accountId:e.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:e.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:e.union([e.literal("now"),Ht]),prorationBehavior:e.literal("none")}),ye=e.strictObject({operationId:e.uuid(),action:e.enum(["start","extend","end"]),status:e.enum(["pending","effective"]),managedBy:e.enum(["indiana","stripe"]),membershipIds:e.array(e.uuid()).min(1).max(20),endsAt:Ht.nullable(),execution:nn.nullable()}).refine(t=>t.execution!==null==(t.managedBy==="stripe"&&t.status==="pending")&&t.action==="end"==(t.endsAt===null)&&(t.action!=="start"||t.managedBy==="indiana")&&(t.execution===null||t.execution.trialEnd==="now"==(t.action==="end")),"Only a pending Stripe trial change carries execution instructions"),wa=e.strictObject({groupId:e.uuid(),productVersionId:e.uuid(),enabled:e.boolean()});var Xt=e.strictObject({requestId:e.uuid(),currency:c,makeDefault:e.boolean()}),Jt=e.strictObject({setupId:e.uuid()}),an=e.strictObject({provider:e.literal("stripe"),executor:e.literal("merchant"),accountId:e.string().regex(/^acct_[A-Za-z0-9]+$/),mode:e.literal("setup"),currency:e.string().regex(/^[a-z]{3}$/),customer:e.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:e.uuid(),metadata:e.strictObject({grooveProjectId:e.uuid(),grooveEnvironmentId:e.uuid(),grooveCustomerId:e.uuid(),groovePaymentSetupId:e.uuid()}),setDefaultPaymentMethod:e.boolean(),expiresAt:e.iso.datetime({offset:!0})}),Ie=e.strictObject({id:e.uuid(),provider:e.literal("stripe"),status:e.enum(["prepared","complete","expired"]),currency:c,makeDefault:e.boolean(),url:e.url().nullable(),createdAt:e.iso.datetime({offset:!0}),expiresAt:e.iso.datetime({offset:!0}),completedAt:e.iso.datetime({offset:!0}).nullable(),execution:an.nullable()});var Yt=e.union([e.string(),e.number(),e.boolean(),e.null()]),ei=e.strictObject({customerId:e.uuid()}),ti=e.strictObject({customerId:e.uuid(),provider:e.literal("stripe"),checkedAt:e.iso.datetime({offset:!0}),status:e.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:e.number().int().nonnegative(),differences:e.array(e.strictObject({subscriptionId:e.string().startsWith("sub_"),itemId:e.string().nullable(),field:e.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Yt,actual:Yt})).max(1e4)});var H=e.iso.datetime({offset:!0}),X=e.strictObject({createdAt:H,id:e.uuid()}),J=e.strictObject({customerId:e.uuid().optional(),entityId:e.uuid().optional(),productId:e.string().min(1).max(256).optional(),provider:e.enum(["stripe","apple","google","merchant","free"]).optional(),status:e.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:X.optional(),limit:e.number().int().min(1).max(100).optional()}),ve={id:e.uuid(),customerId:e.uuid(),entityId:e.uuid().nullable(),productId:e.string().min(1).max(256),productVersionId:e.uuid(),name:e.string().min(1).max(120),provider:e.enum(["stripe","apple","google","merchant","free"]),createdAt:H},sn=e.strictObject({...ve,status:e.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:e.boolean(),billingSubscriptionId:e.uuid().nullable()}),on=e.strictObject({...ve,status:e.enum(["active","ended","refunded"]),orderId:e.uuid().nullable(),transactionId:e.uuid().nullable(),currency:c.nullable(),amountMinor:e.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),cn=e.strictObject({...ve,status:e.enum(["blocked","resolved"]),conflict:e.strictObject({detectedAt:H,blockingMembershipIds:e.array(e.uuid()).min(1).max(100),transactionId:e.uuid()}),resolvedAt:H.nullable()}),ii=J.extend({status:e.enum(["blocked","resolved"]).optional()}),ri=e.strictObject({customerId:e.uuid(),orderId:e.uuid()}),ni=e.strictObject({orderId:e.uuid(),status:e.enum(["blocked","resolved"])}),ai=e.strictObject({items:e.array(sn).max(100),nextCursor:X.nullable()}),si=e.strictObject({items:e.array(on).max(100),nextCursor:X.nullable()}),oi=e.strictObject({items:e.array(cn).max(100),nextCursor:X.nullable()});var ci=e.union([e.strictObject({intent:e.literal("read"),requestId:e.uuid(),purchaseIntentId:e.uuid()}),e.strictObject({requestId:e.uuid(),provider:e.literal("apple"),purchaseIntentId:e.uuid(),productId:e.string().min(1).max(255).optional(),signedTransaction:e.string().min(1).max(131072)}),e.strictObject({requestId:e.uuid(),provider:e.literal("google"),purchaseIntentId:e.uuid(),productId:e.string().min(1).max(255).optional(),purchaseToken:e.string().min(1).max(16384)})]),ui=e.strictObject({requestId:e.uuid(),orderId:e.uuid(),purchaseIntentId:e.uuid(),status:e.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:c,refunded:e.boolean(),completion:e.strictObject({transactionIds:e.array(e.string().min(1).max(255)).min(1).max(50).refine(t=>new Set(t).size===t.length),membership:e.boolean()}).nullable()});var un=e.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),pi=e.enum(["single_use","continuous_use"]),Oe=e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string())),di=e.string().min(1).max(64).refine(t=>!t.includes("::")),li={credit_amount:e.number(),tier_behavior:e.never().optional(),tiers:e.never().optional()},gi={credit_amount:e.never().optional(),tier_behavior:e.literal("graduated"),tiers:e.array(e.strictObject({to:e.union([e.number(),e.literal("inf")]),credit_amount:e.number()}))},dn=e.union([e.strictObject({match:Oe,priority:e.number().int().optional(),...li}),e.strictObject({match:Oe,priority:e.number().int().optional(),...gi})]),mn=e.strictObject({match:Oe,factor:e.number().positive().optional(),add:e.number().optional()}).refine(t=>t.factor!==void 0||t.add!==void 0),mi={metered_feature_id:e.string(),feature_amount:e.number().optional(),dimensions:e.record(di,dn).optional(),multipliers:e.record(di,mn).optional()},Ae=e.union([e.strictObject({...mi,...li}),e.strictObject({...mi,...gi})]),ee=e.number().min(-100),hi=e.record(e.string(),e.strictObject({markup:ee})).nullish(),te=e.record(e.string().regex(/.+\/.+/),e.strictObject({markup:ee.optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish(),pn=e.strictObject({default_markup:ee.optional(),provider_markups:hi,model_markups:te}),Na=e.strictObject({schema:e.array(Ae).optional(),markups:pn.optional()}),ln=e.strictObject({filters:e.array(e.strictObject({property:e.string(),operator:e.string(),value:e.array(e.string())})),aggregate:e.strictObject({type:e.string(),property:e.string().nullable()}),usage_type:pi}),fi=e.strictObject({schema:e.array(Ae).min(1).refine(t=>new Set(t.map(n=>n.metered_feature_id)).size===t.length,"Credit rates must name each metered feature once"),invoice_credit:e.boolean().optional(),usage_type:pi.default("single_use").overwrite(()=>"single_use"),default_markup:ee.optional(),provider_markups:hi}),Pe=fi.safeExtend({schema:e.array(Ae).length(0)}),Y={id:un,name:e.string().min(1),display:e.strictObject({singular:e.string().optional(),plural:e.string().optional()}).nullish(),event_names:e.array(e.string()).default([]),model_markups:te,stripe_meter:e.strictObject({id:e.string(),event_name:e.string()}).nullish(),stripe_product_id:e.string().nullish()},je=t=>e.discriminatedUnion("type",[e.strictObject({...Y,...t,type:e.literal("boolean"),config:e.null()}),e.strictObject({...Y,...t,type:e.literal("metered"),config:ln}),e.strictObject({...Y,...t,type:e.literal("credit_system"),config:fi}),e.strictObject({...Y,...t,type:e.literal("ai_credit_system"),config:Pe})]),Va=je({}),gn=e.strictObject({id:e.boolean(),type:e.boolean(),usage_type:e.boolean()}),hn={internal_id:e.uuid(),org_id:e.uuid(),created_at:e.number(),env:e.enum(["sandbox","live"]),archived:e.boolean(),project_id:e.uuid(),environment_id:e.uuid(),revision:e.number().int().nonnegative(),update_rules:gn},bi=je(hn),Qa=e.strictObject({rows:e.array(bi).max(200),nextCursor:e.uuid().nullable()}),Za=e.strictObject({features:e.array(bi).max(500),limited:e.boolean()}),Ka=e.union([je({action:e.literal("save"),internal_id:e.uuid().nullable(),revision:e.number().int().nonnegative()}),e.strictObject({action:e.enum(["archive","restore","delete"]),internal_id:e.uuid(),revision:e.number().int().nonnegative()})]);var _e=e.uuid().refine(t=>t===t.toLowerCase(),"Product references require canonical lowercase UUIDs"),fn=e.record(e.string(),e.json()).refine(t=>Array.from(JSON.stringify(t)).length<=4e3,"Offering metadata exceeds 4000 characters"),bn=3,z=20,xn=bn*z,Ce=e.strictObject({type:e.literal("product"),productId:_e}),xi={type:e.literal("group"),key:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:e.string().trim().min(1).max(80)},Sn=e.discriminatedUnion("type",[Ce,e.strictObject({...xi,items:e.array(Ce).max(z)})]),yn=e.discriminatedUnion("type",[Ce,e.strictObject({...xi,items:e.array(Sn).max(z)})]),In=e.array(yn).max(z).superRefine((t,n)=>{let a=new Set,o=new Set,m=0;function Qe(Vr){for(let S of Vr){m++;let Ze=S.type==="product"?a:o,Ke=S.type==="product"?S.productId:S.key;Ze.has(Ke)&&n.addIssue({code:"custom",message:S.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),Ze.add(Ke),S.type==="group"&&Qe(S.items)}}Qe(t),(a.size>z||m>xn)&&n.addIssue({code:"custom",message:"Offering item limit exceeded"})});function Re(t){return t.items.flatMap(n=>n.type==="product"?[n.productId]:Re(n))}var C=e.strictObject({lookupKey:e.string().trim().min(1).max(200),displayName:e.string().trim().min(1).max(1500),items:In,metadata:fn}),vn=e.strictObject({product:e.record(e.string(),e.json()),prices:e.array(e.record(e.string(),e.json())),entitlements:e.array(e.record(e.string(),e.json())),freeTrials:e.array(e.record(e.string(),e.json())),licenses:e.array(e.record(e.string(),e.json()))}),Si=C.extend({id:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),state:e.enum(["active","archived"]),isCurrent:e.boolean(),revision:e.number().int().nonnegative(),publishedVersionId:e.uuid().nullable(),createdAt:e.iso.datetime({offset:!0})}).superRefine((t,n)=>{t.isCurrent&&(t.state!=="active"||!t.publishedVersionId)&&n.addIssue({code:"custom",message:"Current Offering must be active and published"})}),yi=e.strictObject({id:e.uuid(),offeringId:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),version:e.number().int().positive(),document:C,productEvidence:e.record(_e,vn),createdAt:e.iso.datetime({offset:!0})}).superRefine((t,n)=>{let a=Re(t.document);(!a.length||Pn(t.document).length>0||Object.keys(t.productEvidence).length!==a.length||a.some(o=>!Object.hasOwn(t.productEvidence,o)))&&n.addIssue({code:"custom",message:"Published Offering requires evidence for every Product"})}),On=e.strictObject({rows:e.array(Si).max(200),versions:e.array(yi).max(500)}),Xa=e.discriminatedUnion("action",[e.strictObject({action:e.literal("create"),document:C}),e.strictObject({action:e.literal("save"),id:e.uuid(),revision:e.number().int().nonnegative(),document:C}),e.strictObject({action:e.enum(["publish","set_current","archive","restore"]),id:e.uuid(),revision:e.number().int().nonnegative()})]),Ja=e.strictObject({record:Si,version:yi.nullable()}),Ii=e.discriminatedUnion("type",[e.strictObject({type:e.literal("current")}),e.strictObject({type:e.literal("id"),id:e.uuid()}),e.strictObject({type:e.literal("lookup_key"),lookupKey:e.string().min(1).max(200)}),e.strictObject({type:e.literal("version"),versionId:e.uuid()})]),An=e.strictObject({internalId:_e,id:e.string(),name:e.string().nullable(),version:e.number().int().positive(),archived:e.boolean()}),Ya=On.extend({products:e.array(An).max(500),pagination:e.strictObject({rows:e.string().nullable(),versions:e.string().nullable(),products:e.string().nullable()}).optional()});function Pn(t){let n=[];Re(t).length||n.push("Select at least one Product before publishing");function a(o){for(let m of o)m.type==="group"&&(m.items.length||n.push("Every published group requires a Product"),a(m.items))}return a(t.items),n}var vi=e.strictObject({id:e.uuid(),offeringId:e.uuid(),version:e.number().int().positive(),document:C});var Oi={requestId:e.uuid(),sourceId:e.uuid(),expectedAvailable:j},Ai=e.discriminatedUnion("action",[e.strictObject({...Oi,action:e.enum(["add","subtract","set_remaining"]),amount:s}),e.strictObject({...Oi,action:e.literal("edit"),granted:s,expiresAt:e.iso.datetime({offset:!0}).nullable(),nextResetAt:e.iso.datetime({offset:!0}).nullable(),expectedRevision:e.number().int().nonnegative()})]),we=e.strictObject({sourceId:e.uuid(),available:j,held:j,spent:j,adjustmentGrantId:e.uuid().nullable()}),Pi=we.extend({granted:j,expiresAt:e.iso.datetime({offset:!0}).nullable(),nextResetAt:e.iso.datetime({offset:!0}).nullable(),revision:e.number().int().nonnegative()});var ji=e.discriminatedUnion("action",[e.object({action:e.literal("upsert"),externalId:e.string().min(1).max(128),name:e.string().trim().min(1).max(80)}).strict(),e.object({action:e.literal("archive"),entityId:e.uuid()}).strict()]),Ci=e.object({id:e.uuid(),externalId:e.string().min(1).max(128),name:e.string().min(1).max(80),archived:e.boolean()}).strict();var _i=e.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),Ri=e.number().int().min(1).max(1e3),ie=e.object({cap:s.refine(t=>/[1-9]/.test(t)).nullable(),capPercentage:e.number().positive().max(1e4).nullable(),cycles:e.number().int().min(1).max(1200).nullable()}).strict().refine(t=>t.cap===null||t.capPercentage===null,"Choose a fixed or percentage cap");var v=e.iso.datetime({offset:!0}),wi=s.refine(t=>/[1-9]/.test(t)),Bi=e.strictObject({interval:_i.exclude(["lifetime"]),count:Ri}),jn=e.strictObject({action:e.literal("create"),requestId:e.uuid(),internal_feature_id:e.uuid(),entityId:e.uuid().nullable(),amount:wi.nullable(),expiresAt:v.nullable(),reset:Bi.nullable(),rollover:ie.nullable(),nextResetAt:v.nullable()}).refine(t=>t.amount!==null||t.reset===null&&t.rollover===null,"Unlimited grants cannot reset or roll over").refine(t=>!t.rollover||t.reset!==null,"Rollover requires a recurring grant").refine(t=>t.nextResetAt===null||t.reset!==null&&(t.expiresAt===null||Date.parse(t.nextResetAt)<Date.parse(t.expiresAt)),"The first reset needs a reset interval and must precede expiry"),qi=e.discriminatedUnion("action",[jn,e.strictObject({action:e.literal("update"),requestId:e.uuid(),grantId:e.uuid(),revision:e.number().int().nonnegative(),amount:wi.nullable(),expiresAt:v.nullable(),rollover:ie.nullable(),nextResetAt:v.nullable()}),e.strictObject({action:e.enum(["add","subtract","set_remaining"]),requestId:e.uuid(),grantId:e.uuid(),revision:e.number().int().nonnegative(),amount:s}),e.strictObject({action:e.literal("revoke"),requestId:e.uuid(),grantId:e.uuid(),revision:e.number().int().nonnegative()})]),Be=e.strictObject({id:e.uuid(),internal_feature_id:e.uuid(),entityId:e.uuid().nullable(),amount:s.nullable(),reset:Bi.nullable(),rollover:ie.nullable(),nextResetAt:v.nullable(),startsAt:v,expiresAt:v.nullable(),revision:e.number().int().nonnegative(),revoked:e.boolean(),available:p,held:p,spent:p}),Ti=e.strictObject({customerId:e.uuid(),after:e.uuid().nullable(),limit:e.number().int().min(1).max(100)}),ki=e.strictObject({rows:e.array(Be).max(100),nextCursor:e.uuid().nullable()});var O=e.iso.datetime({offset:!0}),x=e.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),Cn=e.discriminatedUnion("kind",[e.object({kind:e.literal("absolute"),from:O,to:O}).strict(),e.object({kind:e.literal("last_days"),days:e.union([e.literal(1),e.literal(7),e.literal(30),e.literal(90)])}).strict(),e.object({kind:e.literal("billing_cycles"),membershipId:e.uuid(),count:e.number().int().min(1).max(12),includeCurrent:e.boolean()}).strict()]),zi=e.string().max(100).refine(t=>{if(t!=="UTC"&&!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+\-]+)+$/.test(t))return!1;try{return new Intl.DateTimeFormat("en",{timeZone:t}),!0}catch{return!1}},"Use an IANA timezone"),_n=e.object({key:e.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:e.array(e.string().max(120)).min(1).max(20).refine(t=>new Set(t).size===t.length)}).strict(),A=e.object({range:Cn,timezone:zi,filterBy:e.array(_n).max(5).refine(t=>new Set(t.map(n=>n.key)).size===t.length),interval:e.enum(["hour","day","week","month"]),internal_feature_id:e.uuid().nullable(),entityId:e.uuid().nullable(),topN:e.number().int().min(1).max(50).nullable(),groupBy:e.union([e.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),e.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:e.object({bucket:O,group:e.string().max(240),isOther:e.boolean(),internal_feature_id:e.uuid(),resourceId:e.uuid()}).strict().nullable(),limit:e.number().int().min(1).max(100)}).strict().superRefine((t,n)=>{if(t.range.kind!=="absolute"){t.interval==="hour"&&t.range.kind==="last_days"&&t.range.days>31&&n.addIssue({code:"custom",message:"Hourly reports are bounded to 31 days"});return}let a=Date.parse(t.range.to)-Date.parse(t.range.from);(a<=0||a>366*864e5||t.interval==="hour"&&a>31*864e5)&&n.addIssue({code:"custom",message:"Reporting range must be positive and bounded (31 days hourly, 366 days otherwise)"})}),Ui=e.object({from:O,to:O,interval:e.enum(["hour","day","week","month"]),timezone:zi,rows:e.array(e.object({bucket:O,group:e.string().max(240),isOther:e.boolean(),internal_feature_id:e.uuid(),resourceId:e.uuid(),consumedUnits:x,refundedUnits:x,reservedUnits:x,charged:x,refunded:x,reserved:x,netUnits:x,netCharged:x}).strict()).max(100),nextCursor:e.object({bucket:O,group:e.string().max(240),isOther:e.boolean(),internal_feature_id:e.uuid(),resourceId:e.uuid()}).strict().nullable()}).strict();var _=e.string().regex(/^(0|[1-9]\d{0,29})$/),Mi=e.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),qe=e.strictObject({bucket:e.iso.datetime({offset:!0}),group:e.string().max(240),isOther:e.boolean(),internal_feature_id:e.uuid()}),Ei=e.strictObject({...A.shape,groupBy:e.union([e.enum(["customer","entity","entitlement"]),e.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:qe.nullable()}).superRefine((t,n)=>{let a=A.safeParse({...t,after:null});if(!a.success)for(let o of a.error.issues)n.addIssue({code:"custom",path:o.path,message:o.message})}),Gi=e.strictObject({from:e.iso.datetime({offset:!0}),to:e.iso.datetime({offset:!0}),interval:A.shape.interval,timezone:A.shape.timezone,rows:e.array(e.strictObject({...qe.shape,eventCount:_,units:Mi,tokenEventCount:_,tokens:e.strictObject(Object.fromEntries(zt.map(t=>[t,_]))),totalTokens:_,providerCostEventCount:_,providerCostUsd:Mi,invalidTelemetryEventCount:_})).max(100),nextCursor:qe.nullable()});var Di=e.object({requestId:e.uuid(),items:e.array(e.object({customerId:e.uuid(),command:B.options[1]}).strict()).min(1).max(1e3)}).strict().refine(t=>new Set(t.items.map(n=>n.customerId+":"+n.command.idempotencyKey)).size===t.items.length,"Each logical event must appear once in a batch"),$i=e.object({batchId:e.uuid(),after:e.number().int().min(-1).max(999),limit:e.number().int().min(1).max(100)}).strict(),Li=e.object({batchId:e.uuid(),status:e.enum(["queued","complete"]),total:e.number().int().min(1).max(1e3),processed:e.number().int().min(0).max(1e3),items:e.array(e.object({position:e.number().int().min(0).max(999),customerId:e.uuid(),idempotencyKey:e.string().min(1).max(120),status:e.enum(["queued","accepted","rejected","failed"]),receipt:q.nullable(),errorCode:e.enum(["invalid_request","forbidden","conflict","internal_error"]).nullable()}).strict().refine(t=>t.status==="queued"?t.receipt===null&&t.errorCode===null:t.status==="failed"?t.receipt===null&&t.errorCode!==null:t.receipt!==null&&t.errorCode===null&&t.receipt.accepted===(t.status==="accepted"))).max(100),nextAfter:e.number().int().min(0).max(999).nullable()}).strict();var Rn=e.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),Fi=e.enum(["draft","active","paused","archived"]),Ni=e.string().min(1).max(256),Vi=e.array(Ni).max(50).refine(t=>new Set(t).size===t.length,"Duplicate products"),wn=e.strictObject({duration:e.enum(["day","week","month","year"]),length:e.number().int().min(1).max(3660)}),Bn=e.strictObject({internal_feature_id:e.uuid(),allowance:e.number().nonnegative().max(1e15).nullable(),expiry:wn.nullable()}),qn=e.discriminatedUnion("type",[e.strictObject({type:e.literal("feature_grant"),grants:e.array(Bn).min(1).max(100).refine(t=>new Set(t.map(n=>n.internal_feature_id)).size===t.length,"Duplicate entitlement grants")}),e.strictObject({type:e.literal("free_product"),productId:Ni,duration:y}),e.strictObject({type:e.literal("invoice_credits"),amount:e.number().positive().max(1e8),duration:y,rollover:e.boolean(),productIds:Vi})]),Tn=e.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),Qi=e.object({key:Tn,name:e.string().trim().min(1).max(80),configuration:qn}).strict(),Zi=e.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),Te=e.object({code:Zi,maxUses:e.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:e.boolean()}).strict(),Ki=e.object({key:e.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:e.string().trim().min(1).max(80),rewardId:e.uuid(),redeemOn:e.enum(["customer_creation","checkout"]),receivedBy:e.enum(["referrer","all"]),maxRedemptions:e.number().int().min(1).max(1e6).nullable(),productIds:Vi,excludeTrial:e.boolean()}).strict().refine(t=>t.redeemOn==="checkout"||t.productIds.length===0&&!t.excludeTrial,"Purchase restrictions require checkout trigger"),Wi={id:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),revision:e.number().int().nonnegative(),status:Fi,createdAt:e.iso.datetime({offset:!0}),updatedAt:e.iso.datetime({offset:!0})},kn=Qi.extend(Wi).strict(),zn=Ki.safeExtend(Wi).strict(),Rs=e.strictObject({id:e.uuid(),key:e.string(),name:e.string(),type:Rn,status:Fi,ended:e.boolean()}),ws=e.discriminatedUnion("action",[e.object({action:e.literal("save"),id:e.uuid().nullable(),revision:e.number().int().nonnegative(),input:Qi}).strict(),e.object({action:e.enum(["activate","pause","resume","archive","delete"]),id:e.uuid(),revision:e.number().int().nonnegative()}).strict()]),Bs=e.discriminatedUnion("action",[e.object({action:e.literal("save"),id:e.uuid().nullable(),revision:e.number().int().nonnegative(),input:Ki}).strict(),e.object({action:e.enum(["activate","pause","resume","archive","delete"]),id:e.uuid(),revision:e.number().int().nonnegative()}).strict()]),Hi=e.object({id:e.uuid(),rewardId:e.uuid(),programId:e.uuid().nullable(),customerId:e.uuid(),referrerId:e.uuid().nullable(),status:e.enum(["pending","applied","unavailable"]),result:e.record(e.string(),e.unknown()).nullable(),createdAt:e.iso.datetime({offset:!0})}).strict(),Xi=e.object({code:Zi,requestId:e.uuid()}).strict(),Ji=e.strictObject({redemptionId:e.uuid(),currency:c,requestId:e.uuid(),accepted:e.literal(!0)}),Un=e.strictObject({type:e.literal("checkout"),orderId:e.uuid(),productVersionId:e.uuid(),currency:c,duration:y,renewalAmountMinor:e.number().int().positive().max(1e8),status:e.enum(["created","pending","trialing","paid","cancelled","failed"]),url:e.url().nullable()}),Yi=e.discriminatedUnion("type",[Un,e.strictObject({type:e.literal("subscription"),operationId:e.uuid(),membershipId:e.uuid(),productVersionId:e.uuid(),currency:c,duration:y,renewalAmountMinor:e.number().int().positive().max(1e8),status:e.enum(["pending","running","applied","failed"])})]),er=e.object({programId:e.uuid(),requestId:e.uuid()}).strict(),tr=e.object({id:e.uuid(),programId:e.uuid(),code:Te.shape.code,createdAt:e.iso.datetime({offset:!0})}).strict(),qs=e.object({rows:e.array(kn).max(100),nextCursor:e.uuid().nullable()}).strict(),Ts=e.object({rows:e.array(zn).max(100),nextCursor:e.uuid().nullable()}).strict(),Mn=Te.extend({id:e.uuid(),redemptions:e.number().int().nonnegative()}).strict(),En=e.strictObject({id:e.uuid(),programId:e.uuid().nullable(),customerId:e.uuid().nullable(),referrerId:e.uuid().nullable(),code:e.string().nullable(),status:e.enum(["pending","triggered","applied"]),createdAt:e.iso.datetime({offset:!0})}),ks=e.object({codes:e.array(Mn).max(100),redemptions:e.array(En).max(100),customers:e.record(e.uuid(),e.string()),codesCursor:e.uuid().nullable(),redemptionsCursor:e.uuid().nullable()}).strict(),zs=e.discriminatedUnion("action",[e.object({action:e.literal("create"),rewardId:e.uuid(),revision:e.number().int().nonnegative(),input:Te}).strict(),e.object({action:e.literal("remove"),rewardId:e.uuid(),revision:e.number().int().nonnegative(),codeId:e.uuid()}).strict()]);var rr=e.object({customerId:e.uuid()}).strict(),nr=e.discriminatedUnion("action",[e.object({customerId:e.uuid(),requestId:e.uuid(),action:e.literal("assign"),poolId:e.uuid(),memberCustomerId:e.uuid()}).strict(),e.strictObject({customerId:e.uuid(),requestId:e.uuid(),action:e.literal("assign_entity"),poolId:e.uuid(),entityId:e.uuid()}),e.object({customerId:e.uuid(),requestId:e.uuid(),action:e.literal("release"),poolId:e.uuid(),slotId:e.uuid()}).strict()]),U=e.number().int().nonnegative(),ke=e.iso.datetime({offset:!0}),ze=e.strictObject({internalId:e.uuid(),id:e.string(),name:e.string().nullable(),version:e.number().int().positive()}),ir=e.enum(["active","past_due"]),Ue=e.strictObject({customerId:e.uuid(),licenses:e.array(e.strictObject({id:e.uuid(),linkId:e.uuid(),parent:e.strictObject({customerProductId:e.uuid(),status:ir,product:ze}),product:ze,planLicense:e.strictObject({id:e.uuid(),prepaidOnly:e.boolean(),isCustom:e.boolean()}).nullable(),granted:U,included:U,paidQuantity:U,usage:U,remaining:U,createdAt:ke}).refine(t=>t.granted===t.included+t.paidQuantity&&t.granted===t.usage+t.remaining,"Granted seats are included plus paid, and usage plus remaining")).max(2e3),assignments:e.array(e.strictObject({id:e.uuid(),linkId:e.uuid(),status:ir,product:ze,entity:e.strictObject({internalId:e.uuid(),id:e.string().nullable(),name:e.string().nullable()}).nullable(),beneficiary:e.strictObject({internalId:e.uuid(),id:e.string().nullable(),name:e.string().nullable()}).nullable(),startedAt:ke.nullable(),endedAt:ke.nullable()}).refine(t=>t.entity!==null||t.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:e.boolean()});var ur=e.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),Me=e.string().regex(/^(0|[1-9]\d{0,14})$/),R=e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),Gn=e.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),M=Gn,b=s.refine(t=>/[1-9]/.test(t)),u=e.iso.datetime({offset:!0}),re=t=>{let[n,a=""]=t.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");return BigInt(n)*1000000n+BigInt(a.padEnd(6,"0"))},Dn=e.array(e.object({upTo:b.nullable(),unitAmountMinor:ur,flatAmountMinor:e.number().int().min(0).max(1e8).optional()}).strict()).min(1).max(12).refine(t=>{try{return t.at(-1)?.upTo===null&&t.slice(0,-1).every((n,a)=>{let o=t[a-1]?.upTo;return n.upTo!==null&&(a===0||o!=null&&re(n.upTo)>re(o))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),$n=e.discriminatedUnion("kind",[e.object({kind:e.literal("flat"),units:b,unitAmountMinor:ur}).strict(),e.object({kind:e.enum(["graduated","volume"]),units:b,tiers:Dn}).strict()]).refine(t=>t.kind==="flat"||!t.tiers.some(n=>(n.flatAmountMinor??0)>0)||t.kind==="volume"&&t.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers"),Ln=e.strictObject({interval:e.enum(["month","year"]),count:e.number().int().min(1).max(12),anchor:e.enum(["membership","calendar"])}),E=e.object({currency:c,pricing:$n,billingCycle:Ln.optional()}).strict().refine(t=>t.pricing.kind!=="volume"||t.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var ar={requestId:e.uuid(),productVersionId:e.uuid(),internal_feature_id:e.uuid(),currency:c},dr=e.strictObject({interval:e.enum(["hour","day","week","month"]),intervalCount:e.number().int().min(1).max(12),limit:e.number().int().min(1).max(1e6)}),mr=e.discriminatedUnion("kind",[e.object({...ar,kind:e.literal("auto_topup"),threshold:oe,quantity:b.refine(t=>Number(t)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:dr.optional()}).strict(),e.object({...ar,kind:e.literal("postpaid"),maxAmountMinorPerPeriod:M,maxOutstandingMinor:M}).strict()]),sr={productVersionId:e.uuid(),internal_feature_id:e.uuid(),currency:c},pr=e.discriminatedUnion("kind",[e.object({...sr,kind:e.literal("auto_topup"),threshold:oe,quantity:b.refine(t=>Number(t)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:dr.optional(),purchaseAmountMinor:M,purchaseUnits:b}).strict(),e.object({...sr,kind:e.literal("postpaid"),maxAmountMinorPerPeriod:M,maxOutstandingMinor:M,cashPrice:E}).strict().refine(t=>t.cashPrice.currency===t.currency,"Currency must match")]),ne=e.object({id:e.uuid(),terms:pr,status:e.enum(["prepared","active","revoked","blocked"]),createdAt:u,acceptedAt:u.nullable(),effectiveAt:u.nullable(),revokedAt:u.nullable()}).strict().refine(t=>(t.status==="prepared"?t.acceptedAt===null:!0)&&(t.status==="active"?t.acceptedAt!==null&&t.effectiveAt!==null:!0)&&(t.status==="revoked"?t.revokedAt!==null:t.revokedAt===null),"Authorization consent and revocation must be explicit"),lr=e.object({authorizationId:e.uuid(),terms:pr,setupUrl:e.url().nullable()}).strict(),gr=e.object({authorizationId:e.uuid(),accepted:e.literal(!0)}).strict(),hr=e.object({authorizationId:e.uuid(),requestId:e.uuid()}).strict(),fr=e.object({internal_feature_id:e.uuid(),entityId:e.uuid().nullable(),interval:e.enum(["day","week","month","year"]),anchor:e.enum(["billing_cycle","utc"]).optional(),basis:e.enum(["usage","credits"]),filter:h.optional(),limit:s.nullable(),thresholds:e.array(e.number().positive().max(1)).max(8),includedThresholds:e.array(e.number().positive().max(1)).max(8).optional(),absoluteThresholds:e.array(b).max(8).optional()}).strict().refine(t=>t.thresholds.every((n,a)=>{let o=t.thresholds[a-1];return a===0||o!==void 0&&n>o})&&(t.includedThresholds??[]).every((n,a,o)=>{let m=o[a-1];return a===0||m!==void 0&&n>m})&&(t.absoluteThresholds??[]).every((n,a,o)=>{let m=o[a-1];return a===0||m!==void 0&&re(n)>re(m)}),"Notification thresholds must increase"),Fn=fr.safeExtend({requestId:e.uuid()}),or={control:e.literal("overage"),requestId:e.uuid(),internal_feature_id:e.uuid(),entityId:e.uuid().nullable()},Nn=e.discriminatedUnion("action",[e.strictObject({...or,action:e.literal("set"),allowed:e.boolean().nullable(),overageLimit:s.nullable(),skipOverageBilling:e.boolean()}),e.strictObject({...or,action:e.literal("remove")})]),br=e.union([Fn,Nn]),Vn=e.strictObject({internal_feature_id:e.uuid(),entityId:e.uuid().nullable(),allowed:e.boolean().nullable(),overageLimit:s.nullable(),skipOverageBilling:e.boolean(),interval:e.enum(["day","week","month","year"]),startsAt:u,endsAt:u,used:e.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:e.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:e.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),Qn=e.object({internal_feature_id:e.uuid(),entityId:e.uuid().nullable(),interval:e.enum(["day","week","month","year"]),anchor:e.enum(["billing_cycle","utc"]).optional(),basis:e.enum(["usage","credits"]),filter:h.optional(),startsAt:u,endsAt:u,used:p,reserved:p,limit:s.nullable(),thresholds:e.array(e.number().positive().max(1)).max(8),notifiedThresholds:e.array(e.number().positive().max(1)).max(1024),includedThresholds:e.array(e.number().positive().max(1)).max(8).optional(),includedAllowance:e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:e.array(e.number().positive().max(1)).max(1024).optional(),absoluteThresholds:e.array(b).max(8).optional(),notifiedAbsoluteThresholds:e.array(b).max(1024).optional()}).strict().refine(t=>t.basis!=="usage"||s.safeParse(t.used).success&&s.safeParse(t.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),Zn=e.object({authorizationId:e.uuid(),status:e.enum(["idle","pending","blocked"]),taskId:e.uuid().nullable(),invoiceId:e.uuid().nullable(),hostedInvoiceUrl:e.url().nullable(),purchaseCount:e.number().int().nonnegative(),purchaseWindowEndsAt:u.nullable(),attemptCount:e.number().int().nonnegative(),failedAttemptCount:e.number().int().nonnegative(),suspendedAt:u.nullable(),nextAttemptAt:u.nullable(),failureReason:e.string().min(1).max(240).nullable()}).strict(),xr=e.object({internal_feature_id:e.uuid().optional(),entityId:e.uuid().optional()}).strict(),Ee=e.object({authorizations:e.array(ne).max(100),limits:e.array(fr).max(100),overages:e.array(Vn).max(100).optional(),windows:e.array(Qn).max(200),autoTopups:e.array(Zn).max(100),limited:e.boolean()}).strict(),Kn=e.object({id:e.uuid(),internal_feature_id:e.uuid(),productVersionId:e.uuid(),authorizationId:e.uuid(),entityId:e.uuid().nullable(),units:s,amountMinor:R,cashPrice:E}).strict(),G=e.object({id:e.uuid(),sourceKind:e.enum(["product","usage","manual"]),providerInvoiceId:e.string().min(1).max(240).nullable(),status:e.enum(["accruing","open","pending","paid","failed","void"]),currency:c,startsAt:u.nullable(),endsAt:u.nullable(),amountMinor:e.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:e.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:Me,paidAmountMinor:Me,refundedAmountMinor:Me,createdAt:u,hostedInvoiceUrl:e.url().nullable(),adjustment:e.object({originalInvoiceId:e.uuid(),amountMinor:e.string().regex(/^-?(0|[1-9]\d{0,8})$/).refine(t=>t!=="-0"&&/^-?(0|[1-9]\d{0,8})$/.test(t)&&BigInt(t)>=-200000000n&&BigInt(t)<=200000000n,"Invoice adjustment exceeds the bounded minor amount"),acceptedAt:u.nullable(),reason:e.string().min(1).max(500).optional()}).strict().nullable(),lines:e.array(Kn).max(100),linesLimited:e.boolean()}).strict(),Sr=e.object({invoiceId:e.uuid(),accepted:e.literal(!0)}).strict(),yr=e.strictObject({requestId:e.uuid(),originalInvoiceId:e.uuid(),amountMinor:e.string().regex(/^[1-9]\d{0,8}$/).refine(t=>/^[1-9]\d{0,8}$/.test(t)&&BigInt(t)<=200000000n,"Supplemental amount exceeds the bounded minor amount"),reason:e.string().trim().min(1).max(500)}),Ir=e.object({after:e.uuid().nullable(),limit:e.number().int().min(1).max(100)}).strict(),vr=e.object({rows:e.array(G).max(100),nextCursor:e.uuid().nullable()}).strict(),cr=e.strictObject({id:e.string(),coupon:e.string(),start:e.number().nonnegative(),end:e.number().nullable()}),Wn=e.strictObject({subscriptionId:e.string(),customerId:e.string(),accountId:e.string(),sourceItems:e.array(e.strictObject({id:e.string(),price_id:e.string(),quantity:e.number().int(),discounts:e.array(cr).optional()})).max(100),items:e.array(e.strictObject({id:e.string(),price:e.string(),quantity:e.number().int(),discounts:e.array(e.strictObject({coupon:e.string().optional(),terms:e.strictObject({id:e.string(),name:e.string().optional(),percent_off:e.number().optional(),amount_off:e.number().optional(),currency:e.string().optional(),duration:e.enum(["once","forever","repeating"]),duration_in_months:e.number().optional()}).optional(),discount:e.string().optional(),receipt:cr.optional()})).max(20)})).max(100)}),Or=e.strictObject({membershipId:e.uuid(),requestId:e.uuid(),grantIds:e.array(e.uuid()).max(20).refine(t=>new Set(t).size===t.length,"Duplicate Coupon grants")}),Ar=e.strictObject({membershipId:e.uuid(),operationId:e.uuid(),status:e.enum(["pending","effective"]),execution:Wn.nullable(),grants:e.array(e.strictObject({id:e.uuid(),couponId:e.uuid(),name:e.string(),discount:nt,duration:y,startedAt:u.nullable()})).max(20)});var l={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},D=t=>new Set(t).size===t.length,Ge=e.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),Hn=e.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(t=>!t.split("/").some(n=>n==="."||n==="..")),$=e.string().min(1).max(200).regex(/^[a-zA-Z0-9_./-]+$/).refine(t=>!t.includes("..")&&!t.endsWith(".")&&!t.split("/").some(n=>!n||n.startsWith(".")||n.endsWith(".lock"))),Xn=e.string().min(1).max(512).refine(t=>!/[\\\u0000-\u001f\u007f]/.test(t)&&!t.startsWith("/")&&!t.split("/").some(n=>!n||n==="."||n==="..")),Pr=e.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(t=>!t.startsWith("/")&&!t.split("/").some(n=>!n||n==="."||n===".."));var jr=e.strictObject({id:e.uuid(),repo:Hn,platform:e.enum(["github","gitlab","bitbucket"]),branches:e.array($).min(1).max(4).refine(D),workflow:e.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:e.array(e.uuid()).min(1).max(4).refine(D),include:e.array(Pr).min(1).max(16),exclude:e.array(Pr).max(16),methods:e.array(e.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(D),maxAgeHours:e.number().int().min(1).max(720)}),Cr=jr.extend({revision:e.number().int().positive()}),Qs=e.strictObject({repository:jr,expectedRevision:e.number().int().min(0)}).refine(({repository:t})=>t.platform==="gitlab"||t.repo.split("/").length===2,{path:["repository","repo"]}),_r=e.strictObject({repositoryId:e.uuid(),branch:$}),Jn=e.array(Ge).max(l.keys).refine(D),Rr=e.strictObject({repository:Cr.omit({keyIds:!0}),branch:$,keys:Jn,keySetHash:e.string().regex(/^[a-f0-9]{64}$/)}),Yn=e.strictObject({filePath:Xn,startingLineNumber:e.number().int().min(1).max(1e7)}),De=e.strictObject({protocol:e.literal(1),repositoryId:e.uuid(),branch:$,workflow:e.string().max(200),configurationRevision:e.number().int().positive(),keySetHash:e.string().regex(/^[a-f0-9]{64}$/),commit:e.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:e.uuid(),runNumber:e.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:e.number().int().min(1).max(1e4),scannerVersion:e.literal("1"),scannedAt:e.iso.datetime({offset:!0}),coverage:e.strictObject({complete:e.literal(!0),files:e.number().int().min(0).max(l.files),sourceBytes:e.number().int().min(0).max(l.sourceBytes),unresolvedCalls:e.number().int().min(0).max(1e6),unsupportedFiles:e.number().int().min(0).max(l.files)}),features:e.array(e.strictObject({key:Ge,refs:e.array(Yn).max(l.referencesPerKey)})).max(l.keys)}).superRefine((t,n)=>{D(t.features.map(a=>a.key))||n.addIssue({code:"custom",path:["features"],message:"Duplicate feature"}),t.features.reduce((a,o)=>a+o.refs.length,0)>l.references&&n.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),$e=e.strictObject({scanId:e.uuid(),commit:e.string(),receivedAt:e.string(),references:e.number().int().nonnegative(),removedReferences:e.number().int().nonnegative()}),ea=$e.extend({repositoryId:e.uuid(),branch:$,workflow:e.string(),digest:e.string(),configurationRevision:e.number().int().positive(),runNumber:e.number().int().positive(),runAttempt:e.number().int().positive(),scannedAt:e.string(),keySetHash:e.string(),coverage:De.shape.coverage}),ta=e.strictObject({repositories:e.array(Cr).max(l.repositories),scans:e.array(ea).max(l.repositories*l.branches)}),ia=e.strictObject({key:Ge,references:e.number().int().nonnegative(),coveredTargets:e.number().int().nonnegative(),expiredTargets:e.number().int().nonnegative(),uncertainTargets:e.number().int().nonnegative()}),Zs=e.strictObject({available:e.boolean().default(!0),settings:ta,expectedTargets:e.number().int().min(0).max(80),features:e.array(ia).max(2001),truncated:e.boolean()});var g=e.iso.datetime({offset:!0}),wr=e.strictObject({invoiceId:e.uuid(),after:e.string().min(1).max(180).nullable(),limit:e.number().int().min(1).max(100)}),ra=e.strictObject({kind:e.literal("product"),key:e.string(),productVersionId:e.uuid(),productName:e.string(),itemKey:e.string(),entityId:e.uuid().nullable(),quantity:e.number().positive(),subtotalMinor:e.string().regex(/^-?\d+$/),discountMinor:e.string().regex(/^\d+$/),taxMinor:e.string().regex(/^-?\d+$/).nullable(),totalMinor:e.string().regex(/^-?\d+$/),startsAt:g.nullable(),endsAt:g.nullable(),providerLineId:e.string().nullable(),providerItemId:e.string()}),Br=e.strictObject({invoice:G,items:e.array(e.discriminatedUnion("kind",[ra,e.strictObject({kind:e.literal("invoice_credit"),key:e.string(),internal_feature_id:e.uuid(),internal_credit_feature_id:e.uuid(),name:e.string(),units:s,reserved:s,amountMinor:R,grossAmountMinor:R,creditsAppliedMinor:R,properties:h,cashPrice:E,providerItemId:e.string().nullable(),creditProviderItemId:e.string().nullable()}),e.strictObject({kind:e.literal("usage"),key:e.string(),internal_feature_id:e.uuid(),name:e.string(),units:s,reserved:s,amountMinor:R,cashPrice:E})])).max(100),nextCursor:e.string().min(1).max(180).nullable()}),na=e.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(t=>!/^\-0(?:\.0+)?$/.test(t)),Le=e.strictObject({from:g,to:g,entityId:e.uuid().optional(),snapshotAt:g.nullable(),after:e.strictObject({at:g,id:e.uuid(),position:e.number().int().nonnegative()}).nullable(),limit:e.number().int().min(1).max(100)}).refine(t=>Date.parse(t.from)<Date.parse(t.to)&&Date.parse(t.to)-Date.parse(t.from)<=366*864e5,"Statement range must be positive and at most 366 days").refine(t=>t.after===null||t.snapshotAt!==null,"A cursor requires the original snapshot time"),qr=e.strictObject({customerId:e.uuid(),entityId:e.uuid().nullable(),from:g,to:g,snapshotAt:g,totals:e.array(e.strictObject({internal_credit_feature_id:e.uuid(),name:e.string(),consumed:p,refunded:p,net:na})).max(1e3),rows:e.array(e.strictObject({operationId:e.uuid(),position:e.number().int().nonnegative(),kind:e.enum(["consume","confirm","refund"]),originalId:e.uuid().nullable(),occurredAt:g,internal_feature_id:e.uuid(),entitlementName:e.string(),sourceId:e.uuid(),internal_credit_feature_id:e.uuid(),creditName:e.string(),units:yt,amount:p,pricing:e.array(St).max(12),properties:h})).max(100),nextCursor:Le.shape.after});var d=e.string().min(1).max(200),ae=e.iso.datetime({offset:!0}),L=e.number().int().min(1).max(Number.MAX_SAFE_INTEGER),Fe=e.number().int().min(0).max(1e12),zr=e.number().int().min(1).max(1e12),Tr={...f,type:e.literal("coupon.redeemed"),grantId:e.uuid()},kr={...f,type:e.literal("usage.observed"),merchantTransactionId:d,resource:d,unit:d,quantity:zr},aa=e.strictObject({...f,type:e.literal("fulfillment.updated"),operationId:e.uuid(),merchantFulfillmentId:d,status:e.enum(["pending","applied","failed"])}),sa=e.strictObject({...f,type:e.literal("benefit.claimed"),merchantBenefitId:d,resource:d,unit:d,quantity:zr,expiresAt:ae.nullable(),revision:L}),oa=e.strictObject({...f,type:e.literal("benefit.closed"),merchantBenefitId:d,status:e.enum(["failed","expired","canceled"]),revision:L}),ca=e.strictObject({...f,type:e.literal("benefit.updated"),merchantBenefitId:d,status:e.enum(["active","expired","revoked"]),remainingQuantity:Fe.nullable(),expiresAt:ae.nullable(),revision:L}),ua=e.strictObject({...f,type:e.literal("authorization.updated"),merchantAuthorizationId:d,kind:e.literal("auto_topup"),status:e.enum(["pending","effective","revoked","failed"]),termsReference:d.nullable(),revision:L}),da=e.strictObject({...f,type:e.literal("balance.observed"),resource:d,unit:d,availableQuantity:Fe,reservedQuantity:Fe,periodStartsAt:ae.nullable(),periodEndsAt:ae.nullable(),revision:L}),Ur=e.union([e.discriminatedUnion("type",[...He,aa,sa,oa,ca,ua,da]),e.strictObject({...Tr,productVersionId:e.uuid(),subscriptionId:e.string().trim().min(1).max(255)}),e.strictObject({...Tr,merchandiseId:e.uuid()}),e.strictObject({...kr,operation:e.literal("consume")}),e.strictObject({...kr,operation:e.literal("reverse"),reversalOf:d})]),Mr=e.strictObject({id:e.uuid(),eventId:e.string().min(1).max(200),source:e.literal("merchant"),providerVerified:e.literal(!1),outcome:e.string().min(1).max(100)});var Er=st,pa=Er.extend({invoice_id:Er.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),Ne=e.strictObject({name:e.string().trim().min(1).max(255),memo:e.string().max(1e4).nullable().optional(),footer:e.string().max(1e4).nullable().optional(),net_terms_days:e.number().int().positive().nullable().optional()}),la=Ne.extend({id:e.string().min(1).max(255),created_at:e.number().nullable()}),Gr=e.strictObject({items:e.array(la).max(50),nextCursor:e.uuid().nullable()}),so=e.discriminatedUnion("action",[e.strictObject({action:e.literal("create"),requestId:e.uuid(),values:Ne}),e.strictObject({action:e.literal("update"),id:e.string().min(1).max(255),values:Ne}),e.strictObject({action:e.literal("delete"),id:e.string().min(1).max(255)})]),Dr=e.discriminatedUnion("action",[e.strictObject({action:e.literal("create"),requestId:e.uuid(),params:P}),e.strictObject({action:e.enum(["finalize","send","pay","void"]),requestId:e.uuid(),invoiceId:e.uuid()}),e.strictObject({action:e.literal("reissue"),requestId:e.uuid(),invoiceId:e.uuid(),params:pa})]),Ve=e.strictObject({id:e.uuid(),customerId:e.uuid(),providerInvoiceId:e.string().nullable(),status:e.enum(["draft","open","paid","void","uncollectible"]),currency:e.string(),totalMinor:e.string().regex(/^-?\d+$/),paidMinor:e.string().regex(/^\d+$/),refundedMinor:e.string().regex(/^\d+$/),hostedInvoiceUrl:e.url().nullable(),createdAt:e.number(),collectionMethod:e.enum(["send_invoice","charge_automatically"]).nullable()}),$r=Ve.extend({lines:e.array(e.strictObject({id:e.uuid(),description:e.string(),amountMinor:e.string().regex(/^-?\d+$/),netAmountMinor:e.string().regex(/^-?\d+$/),quantity:e.number().nullable(),periodStart:e.number().nullable(),periodEnd:e.number().nullable()})).max(1e3)}),w=e.strictObject({taskId:e.uuid(),status:e.enum(["ready","running","done","dead"]),invoice:Ve.nullable(),errorCode:e.string().nullable()}),Lr=e.strictObject({items:e.array(Ve).max(50),nextCursor:e.uuid().nullable(),operations:e.array(w).max(50),operationsLimited:e.boolean()});var ga=e.enum(["customers:read","customers:write","entitlements:read","content:read","sessions:create","funnels:run","offers:resolve","offers:grant","billing:read","billing:write","credits:read","credits:consume","credits:manage","features:read","events:write","messaging:write","code-references:read","code-references:write","app-manifests:write"]),Fr={scope:se,permissions:e.array(ga),expiresAt:e.iso.datetime().nullable()},ec=e.discriminatedUnion("kind",[e.object({...Fr,kind:e.literal("server"),keyId:e.string().min(1)}),e.object({...Fr,kind:e.literal("customer"),customerId:e.string().min(1),identityKind:e.enum(["identified","guest"]),expiresAt:e.iso.datetime()})]),r=e.object({requestId:e.uuid(),scope:se}).strict(),ha=Ct.safeExtend({fingerprint:he.optional()}).strict(),fa=r.extend({customer:Q,created:e.boolean()});function Nr(){return r.extend({offer:ue.nullable(),reason:at.nullable()})}var i={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:Nt,response:r.extend({message:e.object({messageId:e.uuid(),channel:T,acceptedAt:e.iso.datetime({offset:!0}),status:e.enum(["accepted","sending","completed","canceled"]),replayed:e.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:e.strictObject({messageId:e.uuid()}),response:r.extend({message:e.object({id:e.uuid(),channel:T,status:e.enum(["accepted","sending","completed","canceled"]),deliveries:e.array(e.object({id:e.uuid(),status:Qt,attempts:e.number().int().nonnegative(),receipts:e.array(e.object({kind:Zt,occurredAt:e.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:Ut,response:r.extend({installation:Z})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:Mt,response:r.extend({installation:Z})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:Et,response:r.extend({installation:Z})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:e.strictObject({channel:T}),response:r.extend({preference:fe})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:Vt,response:r.extend({preference:fe})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:e.strictObject({cursor:e.uuid().optional()}),response:r.extend({templates:Gr})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:e.strictObject({customerId:e.uuid(),params:P}),response:r.extend({preview:de})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:e.strictObject({customerId:e.uuid(),requestId:e.uuid(),params:P}).refine(t=>t.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:r.extend({operation:w})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:e.strictObject({customerId:e.uuid(),command:Dr}).refine(t=>t.command.action!=="create"||t.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:r.extend({operation:w})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:e.strictObject({customerId:e.uuid(),taskId:e.uuid()}),response:r.extend({operation:w})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:e.strictObject({customerId:e.uuid(),cursor:e.uuid().optional()}),response:r.extend({invoices:Lr})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:e.strictObject({customerId:e.uuid(),invoiceId:e.uuid()}),response:r.extend({invoice:$r})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:_r,response:r.extend({config:Rr})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:De,response:r.extend({receipt:$e})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:e.strictObject({}),response:r.extend({payload:gt})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:ht,response:r.merge(ft)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:bt,response:r.merge(xt)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:e.strictObject({customerId:e.uuid(),sourceId:e.uuid()}),response:r.extend({balance:Pi})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:e.strictObject({customerId:e.uuid(),command:Ai}),response:r.extend({balance:we})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:e.strictObject({internal_feature_id:e.uuid(),customerId:e.uuid().optional(),entityId:e.uuid().optional()}).refine(t=>!t.entityId||!!t.customerId,"Entity pricing requires a customer"),response:r.extend({internal_feature_id:e.uuid(),config:Pe,model_markups:te})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:e.strictObject({customerId:e.uuid(),query:vt}),response:r.extend({usage:ge})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:e.strictObject({customerId:e.uuid(),command:Ot}),response:r.extend({usage:ge})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:e.strictObject({customerId:e.uuid(),command:qi}),response:r.extend({grant:Be})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:Ti,response:r.extend({grants:ki})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:e.union(ci.options.map(t=>t.extend({customerId:e.uuid().optional(),customerToken:e.string().regex(We).optional()}))),response:r.extend({operation:ui})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:Xt.extend({customerId:e.uuid().optional()}),response:r.extend({setup:Ie})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Jt.extend({customerId:e.uuid().optional()}),response:r.extend({setup:Ie})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:Kt.safeExtend({customerId:e.uuid()}),response:r.extend({batch:k})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:K.extend({customerId:e.uuid()}),response:r.extend({batch:k})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:K.extend({customerId:e.uuid()}),response:r.extend({batch:k})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:K.extend({customerId:e.uuid()}),response:r.extend({batch:k})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:e.discriminatedUnion("action",[W.options[0].extend({customerId:e.uuid()}),W.options[1].extend({customerId:e.uuid()}),W.options[2].extend({customerId:e.uuid()})]),response:r.extend({trial:ye})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Wt.extend({customerId:e.uuid()}),response:r.extend({trial:ye})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:J,response:r.extend({subscriptions:ai})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:J,response:r.extend({purchases:si})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:ii,response:r.extend({conflicts:oi})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:ri,response:r.extend({resolution:ni})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:ei,response:r.extend({verification:ti})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:ot.safeExtend({...V,customerId:e.uuid().optional()}),response:r.extend({quote:ct})},recordMerchantEvent:{replay:"immutable_event",method:"POST",path:"merchant/events/record",permission:"billing:write",audience:"server",request:Ur,response:r.extend({record:Mr})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:I.extend({customerId:e.uuid().optional(),intent:e.enum(["confirm","cancel"]).optional(),merchantConfirmation:N.optional()}),response:r.extend({operation:me})},readSubscriptionOperation:{replay:"read",method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:I.extend({customerId:e.uuid().optional()}),response:r.extend({operation:me})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:ut.safeExtend({customerId:e.uuid().optional()}),response:r.extend({quote:mt})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:I.extend({customerId:e.uuid().optional(),intent:e.enum(["confirm","cancel"]).optional(),merchantConfirmation:N.optional()}),response:r.extend({operation:pe})},readSubscriptionUpdate:{replay:"read",method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:I.extend({customerId:e.uuid().optional()}),response:r.extend({operation:pe})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:pt.safeExtend({customerId:e.uuid()}),response:r.extend({quote:lt})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:I.extend({customerId:e.uuid(),merchantConfirmation:N.optional()}),response:r.extend({operation:le})},readRefund:{replay:"read",method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:I.extend({customerId:e.uuid()}),response:r.extend({operation:le})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:xr,response:r.extend({controls:Ee})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:mr,response:r.extend({prepared:lr})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:gr,response:r.extend({authorization:ne})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Or,response:r.extend({coupons:Ar})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:hr,response:r.extend({authorization:ne})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:Ir,response:r.extend({invoices:vr})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:yr.extend({customerId:e.uuid()}),response:r.extend({operation:w})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:Sr,response:r.extend({invoice:G})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:e.object({customerId:e.uuid(),command:br}).strict(),response:r.extend({controls:Ee})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:e.object({customerId:e.uuid(),command:ji}).strict(),response:r.extend({entity:Ci})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:e.strictObject({customerId:e.uuid().nullable(),query:Ei}),response:r.extend({analytics:Gi})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:e.object({customerId:e.uuid().nullable(),query:A}).strict(),response:r.extend({analytics:Ui})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:Di,response:r.extend({batchId:e.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:$i,response:r.extend({batch:Li})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:Ye.extend({customerId:e.string().min(1).optional()}),response:r.extend({check:ce})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:e.strictObject({kind:tt,selector:e.discriminatedUnion("type",[e.strictObject({type:e.literal("resource"),id:e.uuid()}),e.strictObject({type:e.literal("version"),id:e.uuid()})]),customerId:e.string().min(1).optional()}),response:r.extend({content:it})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Tt,response:r.extend({paywall:kt})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:e.strictObject({processContext:rt.optional(),...V,selector:Ii,customerId:e.string().min(1).optional(),commerce:Xe,requirement:Je.optional()}),response:r.extend({offering:vi,candidates:e.array(et).max(20),availability:e.array(e.strictObject({productVersionId:e.uuid(),available:e.boolean(),reason:e.enum(["platform_binding_missing","commercial_runtime_pending","commerce_not_configured","currency_mismatch","product_unavailable","already_attached","attach_in_progress","already_scheduled","subscription_change_required","purchase_conflict"]).nullable()})).max(20),check:ce.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:e.object({customerId:e.uuid().optional(),entityId:e.uuid().optional()}).strict(),response:r.extend({holdings:At})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:e.object({customerId:e.uuid().optional(),query:Pt}).strict(),response:r.extend({ledger:jt})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:wr.extend({customerId:e.uuid().optional()}),response:r.extend({detail:Br})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:Le.safeExtend({customerId:e.uuid().optional()}),response:r.extend({statement:qr})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:e.object({customerId:e.uuid().optional(),command:B.options[0]}).strict(),response:r.extend({quote:It})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:e.strictObject({customerId:e.uuid(),command:e.union([e.strictObject({eventName:e.string().min(1),quantity:s.optional(),properties:h.optional(),entityId:e.uuid().optional(),idempotencyKey:e.string().min(1).max(120)}),e.strictObject({internal_feature_id:e.uuid(),quantity:s.optional(),properties:h.optional(),entityId:e.uuid().optional(),idempotencyKey:e.string().min(1).max(120)})])}),response:r.extend({receipts:e.array(q).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:e.object({customerId:e.uuid(),command:B.refine(t=>t.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:r.extend({receipt:q})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:Xi,response:r.extend({redemption:Hi})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:er,response:r.extend({referralCode:tr})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:Ji,response:r.extend({checkout:Yi})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:rr,response:r.extend({seats:Ue})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:nr,response:r.extend({seats:Ue})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:ha,response:fa},getCustomer:{replay:"read",method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Rt,response:r.extend({customer:Q})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:Bt,response:r.extend(qt.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:wt,response:r.extend(_t.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:e.object({customerId:e.uuid()}).strict(),response:r.extend(F.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:e.strictObject({}),response:r.extend(F.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:e.strictObject({customerId:e.uuid(),sessionId:e.uuid().optional()}),response:r.extend({revoked:e.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:e.strictObject({guestToken:e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:he.optional()}),response:r.extend({customerId:e.uuid(),guestToken:e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:e.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:e.strictObject({guestToken:e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:r.extend(F.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:e.strictObject({guestToken:e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:e.string().trim().min(1).max(255).refine(t=>!t.startsWith("gg_guest_")),requestId:e.uuid()}),response:r.extend({customer:Q,switched:e.boolean(),replayed:e.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:e.strictObject({code:e.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:e.uuid()}),response:Nr()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:e.object({}).strict(),response:r.extend({offers:e.array(ue)})},grantModelBenefit:{method:"POST",path:"benefits/model-usage/grant",permission:"offers:grant",audience:"server",request:$t,response:r.extend({operation:xe})},readModelBenefit:{method:"POST",path:"benefits/model-usage/read",permission:"offers:grant",audience:"server",request:Lt,response:r.extend({operation:xe})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:e.object({customerId:e.string().min(1).max(255).optional(),couponId:e.uuid(),...V,requestId:e.uuid(),couponContentDigest:e.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:Nr()}},tc={recordMerchantEvent:i.recordMerchantEvent,sendMessage:i.sendMessage,readMessage:i.readMessage,bindPushInstallation:i.bindPushInstallation,readPushInstallation:i.readPushInstallation,updatePushAddress:i.updatePushAddress,readMessagingPreference:i.readMessagingPreference,setMessagingPreference:i.setMessagingPreference,listInvoiceTemplates:i.listInvoiceTemplates,previewInvoice:i.previewInvoice,createInvoice:i.createInvoice,manageInvoice:i.manageInvoice,readInvoiceOperation:i.readInvoiceOperation,listInvoices:i.listInvoices,getInvoice:i.getInvoice,getCodeReferenceConfig:i.getCodeReferenceConfig,submitCodeReferences:i.submitCodeReferences,getFeatures:i.getFeatures,evaluateFeatures:i.evaluateFeatures,trackEvents:i.trackEvents,setupPayment:i.setupPayment,readPaymentSetup:i.readPaymentSetup,previewSubscriptionBatch:i.previewSubscriptionBatch,confirmSubscriptionBatch:i.confirmSubscriptionBatch,readSubscriptionBatch:i.readSubscriptionBatch,abandonSubscriptionBatch:i.abandonSubscriptionBatch,manageSubscriptionTrial:i.manageSubscriptionTrial,readSubscriptionTrial:i.readSubscriptionTrial,listSubscriptions:i.listSubscriptions,listPurchases:i.listPurchases,listSubscriptionConflicts:i.listSubscriptionConflicts,retrySubscriptionConflict:i.retrySubscriptionConflict,readAiPricing:i.readAiPricing,readUsage:i.readUsage,setUsage:i.setUsage,previewRefund:i.previewRefund,refund:i.refund,readRefund:i.readRefund,previewUpdate:i.previewUpdate,update:i.update,readSubscriptionUpdate:i.readSubscriptionUpdate,restoreNativePurchase:i.restoreNativePurchase,verifySubscriptions:i.verifySubscriptions,previewAttach:i.previewAttach,attach:i.attach,readSubscriptionOperation:i.readSubscriptionOperation,manageBalanceGrant:i.manageBalanceGrant,readBalanceSource:i.readBalanceSource,adjustBalance:i.adjustBalance,listBalanceGrants:i.listBalanceGrants,readBillingControls:i.readBillingControls,prepareBillingAuthorization:i.prepareBillingAuthorization,confirmBillingAuthorization:i.confirmBillingAuthorization,setBillingCoupons:i.setBillingCoupons,revokeBillingAuthorization:i.revokeBillingAuthorization,listBillingInvoices:i.listBillingInvoices,confirmBillingAdjustment:i.confirmBillingAdjustment,prepareBillingAdjustment:i.prepareBillingAdjustment,manageBillingLimits:i.manageBillingLimits,createCustomer:i.createCustomer,getCustomer:i.getCustomer,listCustomers:i.listCustomers,updateCustomer:i.updateCustomer,createSession:i.createSession,refreshSession:i.refreshSession,revokeSessions:i.revokeSessions,createGuestCustomer:i.createGuestCustomer,resumeGuestSession:i.resumeGuestSession,claimGuestCustomer:i.claimGuestCustomer,checkEntitlement:i.checkEntitlement,resolveOffering:i.resolveOffering,resolveContent:i.resolveContent,resolvePaywall:i.resolvePaywall,readHoldings:i.readHoldings,readLedger:i.readLedger,readBillingInvoice:i.readBillingInvoice,readCreditStatement:i.readCreditStatement,quoteBalance:i.quoteBalance,trackUsage:i.trackUsage,mutateBalance:i.mutateBalance,manageUsageEntity:i.manageUsageEntity,readUsageAnalytics:i.readUsageAnalytics,readCreditAnalytics:i.readCreditAnalytics,submitUsageBatch:i.submitUsageBatch,readUsageBatch:i.readUsageBatch,listOffers:i.listOffers,grantOffer:i.grantOffer,grantModelBenefit:i.grantModelBenefit,readModelBenefit:i.readModelBenefit,redeemCoupon:i.redeemCoupon,redeemReward:i.redeemReward,createReferralCode:i.createReferralCode,claimRewardProduct:i.claimRewardProduct,readSeats:i.readSeats,manageSeat:i.manageSeat};export{be as a,Dt as b,Gt as c,xa as d,i as e};
|
package/dist/chunk-ITGERPCJ.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{s as g,t as w}from"./chunk-THMGTRXP.js";import{n as I,s as h}from"./chunk-NAZU3EEJ.js";import{a as y}from"./chunk-WTVLNUMS.js";import{a}from"./chunk-X4W22IH6.js";import{a as T}from"./chunk-3VUPVXAV.js";import{b as P}from"./chunk-WKIR2EQG.js";import{a as f}from"./chunk-VF6QMMEA.js";function b(r,n,o){if(!["subscriptions/operations/read","subscriptions/updates/read","subscriptions/refunds/read"].includes(r))return;let e=n,c=o,s=c.operation;if(s.operationId!==e.operationId||[s.authority,s.merchantExecution].some(t=>t&&(t.operationId!==e.operationId||e.customerId!==void 0&&t.customerId!==e.customerId))||s.authority&&(s.authority.scope.projectId!==c.scope.projectId||s.authority.scope.environment!==c.scope.environment))throw new a("INVALID_RESPONSE","Original commerce operation changed")}function D(r){try{return structuredClone(r)}catch{return r}}async function q(r,n){let o=r.captureIdentity?.(),{apiOperations:e}=await import("./operation-contracts-443N2P3A.js");return o?.(),e[n]}function E(r,n,o,e){try{return r.parse(n)}catch(c){throw e&&c instanceof f?new a(o,e):c}}async function x(r,n,o,e={},c){let s=typeof e=="function"?{}:e,t=E(n.request,o,"INVALID_REQUEST",s.request);try{let i=await r(n.path,t,n.method,c),u=typeof e=="function"?e:e.parseResponse,d=u?u(n.response,i):E(n.response,i,"INVALID_RESPONSE",s.response);return b(n.path,t,d),d}catch(i){throw i instanceof a&&t!==null&&typeof t=="object"&&"requestId"in t&&typeof t.requestId=="string"&&(i.commandRequestId??=t.requestId),i}}function O(r,n){let o=typeof r=="string"?new TextEncoder().encode(r):r;return o.byteLength===n.byteLength&&h(o)===n.sha256}async function F(r,n){let o=g.parse(n),{artifact:e,environmentId:c}=o.content,s=new y(r.baseUrl??P).origin,t=new y(e.url,s);if(t.origin!==s||t.username||t.password||t.search||t.hash||t.pathname!==`/api/v1/configuration/${c}/artifacts/${e.sha256}`)throw new a("INVALID_RESPONSE","Public Paywall locator is not trusted");let i=new AbortController,u,d=new Promise((p,l)=>{u=setTimeout(()=>{let m=new a("TIMEOUT","Public Paywall read timed out");i.abort(m),l(m)},I.initializationMs)}),R=(async()=>{let p=await(r.fetch??globalThis.fetch)(t,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:i.signal});if(i.signal.aborted&&(p.body?.cancel().catch(()=>{}),i.signal.throwIfAborted()),!p.ok||!p.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(p.headers.get("content-length"))>e.byteLength)throw p.body?.cancel().catch(()=>{}),new a("INVALID_RESPONSE","Public Paywall is unavailable");let l=await T(p,e.byteLength,{signal:i.signal,error:m=>new a("INVALID_RESPONSE",m==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!O(l,e))throw new a("INVALID_RESPONSE","Public Paywall digest or size changed");return w(o,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l)))})();try{return await Promise.race([R,d])}finally{clearTimeout(u)}}export{D as a,q as b,x as c,O as d,F as e};
|