@tinkerlandai/indiana-sdk 0.6.4 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +15 -5
  2. package/README.md +11 -10
  3. package/README.zh-CN.md +16 -11
  4. package/dist/{ai-usage-B4W5m4Ie.d.ts → ai-usage-Bigjb8MS.d.ts} +570 -560
  5. package/dist/chunk-2A6UYUFA.js +1 -0
  6. package/dist/chunk-3BQFJANQ.js +1 -0
  7. package/dist/chunk-3ENVRJE6.js +350 -0
  8. package/dist/chunk-A3N4ZZTM.js +7 -0
  9. package/dist/chunk-AE4CUTUE.js +1 -0
  10. package/dist/chunk-CXYOZSOF.js +1 -0
  11. package/dist/{chunk-2EJSV6BA.js → chunk-G2R56FKU.js} +1 -1
  12. package/dist/chunk-KQCTDXVD.js +17 -0
  13. package/dist/{chunk-5TEZEOHX.js → chunk-OVMNCZYC.js} +1 -1
  14. package/dist/chunk-RRII2DMC.js +1 -0
  15. package/dist/chunk-YAFMBXIE.js +4 -0
  16. package/dist/{configuration-sync-C2mytNwU.d.ts → configuration-sync-VFbY1pCN.d.ts} +356 -49
  17. package/dist/content-K2HCZVC2.js +1 -0
  18. package/dist/{customer-page-B4FGCVpt.d.ts → customer-page-BrCZxcaQ.d.ts} +278 -5
  19. package/dist/funnel-runtime-host-HNZ47TZW.js +1 -0
  20. package/dist/{funnel-runtime-start-sZ8ZCNlq.d.ts → funnel-runtime-start-DKcTCRrd.d.ts} +6930 -3327
  21. package/dist/index.d.ts +17432 -14987
  22. package/dist/index.js +1 -1
  23. package/dist/native-shell.js +1 -1
  24. package/dist/openrouter.d.ts +2 -2
  25. package/dist/openrouter.js +1 -1
  26. package/dist/page.d.ts +17 -17
  27. package/dist/page.js +1 -1
  28. package/dist/paywall-PD62B2AY.js +1 -0
  29. package/dist/popup.d.ts +7 -282
  30. package/dist/popup.js +1 -350
  31. package/dist/react-native.d.ts +15 -15
  32. package/dist/react-native.js +1 -1
  33. package/dist/{screen-16d-xADb.d.ts → screen-BazUOjwM.d.ts} +163 -160
  34. package/dist/server.d.ts +5 -5
  35. package/dist/server.js +1 -1
  36. package/dist/src-4MRSESVS.js +1 -0
  37. package/dist/visual.d.ts +5 -2
  38. package/dist/visual.js +2 -2
  39. package/package.json +1 -7
  40. package/dist/chunk-4K25DELJ.js +0 -1
  41. package/dist/chunk-63BWE27V.js +0 -1
  42. package/dist/chunk-CB63JLGT.js +0 -1
  43. package/dist/chunk-D7YHFS6B.js +0 -4
  44. package/dist/chunk-HTRQPMJO.js +0 -11
  45. package/dist/chunk-ISUXYPYL.js +0 -1
  46. package/dist/chunk-QG3WUJG5.js +0 -1
  47. package/dist/chunk-RMJJOSVZ.js +0 -1
  48. package/dist/chunk-S2MSIA57.js +0 -17
  49. package/dist/chunk-U6S6AZM6.js +0 -1
  50. package/dist/chunk-VVSQKVE7.js +0 -1
  51. package/dist/client-OYRHOMUQ.js +0 -1
  52. package/dist/funnel-runtime-host-NWS3URFA.js +0 -1
  53. package/dist/iam.d.ts +0 -131
  54. package/dist/iam.js +0 -1
  55. package/dist/paywall-4XZ6NDMY.js +0 -1
  56. package/dist/src-WV6GZYWA.js +0 -1
  57. package/dist/{errors-DrdTlPwf.d.ts → errors-BpCmukJr.d.ts} +1 -1
@@ -0,0 +1 @@
1
+ import{a as u,c as d}from"./chunk-RRII2DMC.js";import{z as b}from"zod";var z=b.enum(["sandbox","live"]),k=b.object({projectId:b.string().min(1),environment:z}).strict();import{z as t}from"zod";var f=t.tuple([t.number().min(0).max(1),t.number().min(0).max(1)]).refine(([n,g])=>n<=g),C=t.strictObject({attribute:t.string().optional(),seed:t.string(),hashVersion:t.literal(2),ranges:t.array(f).max(100)}),E=t.strictObject({id:t.string().min(1).max(255),condition:d,gate:t.boolean().optional()}),H=t.strictObject({key:t.string().optional(),name:t.string().optional(),passthrough:t.boolean().optional()}),M={condition:d.optional(),parentConditions:t.array(E).max(100).optional(),weights:t.array(t.number().min(0).max(1)).max(20).optional(),coverage:t.number().min(0).max(1).optional(),hashAttribute:t.string().optional(),fallbackAttribute:t.string().optional(),hashVersion:t.literal(2).optional(),disableStickyBucketing:t.boolean().optional(),bucketVersion:t.number().int().nonnegative().optional(),minBucketVersion:t.number().int().nonnegative().optional(),filters:t.array(C).max(100).optional(),ranges:t.array(f).max(20).optional(),meta:t.array(H).max(20).optional(),seed:t.string().optional(),name:t.string().optional(),phase:t.string().optional()},y=t.strictObject({...M,key:t.string().min(1).max(255),variations:t.tuple([u,u]).rest(u).refine(n=>n.length<=20),urlPatterns:t.array(t.strictObject({include:t.boolean(),type:t.enum(["regex","simple"]),pattern:t.string()})).max(100).optional(),force:t.number().int().nonnegative().optional(),active:t.boolean().optional(),persistQueryString:t.boolean().optional()}),N=t.strictObject({value:u,variationId:t.number().int(),key:t.string(),name:t.string().optional(),bucket:t.number().optional(),passthrough:t.boolean().optional(),inExperiment:t.boolean(),hashUsed:t.boolean().optional(),hashAttribute:t.string(),hashValue:t.string(),featureId:t.string().nullable(),stickyBucketUsed:t.boolean().optional()}),U=t.strictObject({...M,id:t.string().max(255).optional(),force:u.optional(),variations:t.array(u).min(2).max(20).optional(),key:t.string().optional(),range:f.optional(),tracks:t.array(t.strictObject({experiment:y,result:N})).max(100).optional()}),D=t.strictObject({defaultValue:u.optional(),rules:t.array(U).max(500).optional()}),h=t.record(t.string(),t.union([t.strictObject({type:t.literal("hashed"),attributeKey:t.string(),values:t.array(t.string().regex(/^[a-f0-9]{64}$/))}),t.strictObject({type:t.literal("list"),attributeKey:t.string(),values:t.array(t.union([t.string(),t.number()]))}),t.strictObject({type:t.literal("condition"),condition:d})])),te=t.strictObject({scope:k,generation:t.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:t.iso.datetime({offset:!0}),expiresAt:t.iso.datetime({offset:!0}).nullable(),features:t.record(t.string(),D),savedGroups:h,experiments:t.record(t.uuid(),y)});import{z as a}from"zod";import{z as e}from"zod";import{z as r}from"zod";var P=r.strictObject({schemaVersion:r.literal(1),renderKey:r.string().min(1).max(256),routeTemplate:r.string().startsWith("/").max(2048),selectors:r.array(r.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:r.array(r.number().int().min(0)).min(1),absent:r.array(r.number().int().min(0))}).superRefine((n,g)=>{let s=[...n.present,...n.absent];(new Set(n.selectors).size!==n.selectors.length||new Set(s).size!==s.length||s.length!==n.selectors.length||s.some(o=>o>=n.selectors.length))&&g.addIssue({code:"custom",message:"Incomplete or ambiguous render signature"})}),w=r.strictObject({renderKey:r.string().min(1).max(256),routeKey:r.string().min(1).max(256),stateKey:r.string().min(1).max(256),documentKey:r.string().min(1).max(256),documentHash:r.string().regex(/^[a-f0-9]{64}$/),compositionKey:r.string().min(1).max(256),entryMode:r.enum(["hard","soft"]),match:r.strictObject({present:r.array(r.number().int().min(0)),absent:r.array(r.number().int().min(0))})});import{z as m}from"zod";var B={"enterprise-internal-indiana-test":"indiana-admin-vercel@enterprise-internal-490516.iam.gserviceaccount.com","tinkerland-indiana-prod":"indiana-admin-vercel@tinkerland-indiana.iam.gserviceaccount.com"},x="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",T=m.string().regex(new RegExp(`^${x}/${x}/${x}/manifest\\.json$`)),X="content-length;content-type;host;x-goog-if-generation-match",A=m.strictObject({kind:m.literal("gcs-v4-put"),url:m.url(),bucket:m.enum(["enterprise-internal-indiana-test","tinkerland-indiana-prod"]),objectKey:T,byteLength:m.number().int().min(1),expiresAt:m.iso.datetime(),headers:m.strictObject({"Content-Type":m.literal("application/json"),"x-goog-if-generation-match":m.literal("0")})}).superRefine((n,g)=>{let s=new URL(n.url),o=s.searchParams,R=["X-Goog-Algorithm","X-Goog-Credential","X-Goog-Date","X-Goog-Expires","X-Goog-Signature","X-Goog-SignedHeaders"],l=o.get("X-Goog-Date")??"",O=/^\d{8}T\d{6}Z$/.test(l)?Date.parse(`${l.slice(0,4)}-${l.slice(4,6)}-${l.slice(6,8)}T${l.slice(9,11)}:${l.slice(11,13)}:${l.slice(13,15)}Z`):NaN,p=Number(o.get("X-Goog-Expires"));(s.origin!=="https://storage.googleapis.com"||s.username||s.password||s.hash||s.pathname!==`/${n.bucket}/app-manifests/${n.objectKey}`||[...o.keys()].length!==R.length||R.some($=>o.getAll($).length!==1)||o.get("X-Goog-Algorithm")!=="GOOG4-RSA-SHA256"||o.get("X-Goog-Credential")!==`${B[n.bucket]}/${l.slice(0,8)}/auto/storage/goog4_request`||o.get("X-Goog-SignedHeaders")!==X||!/^[a-f0-9]{512,1024}$/.test(o.get("X-Goog-Signature")??"")||!Number.isFinite(O)||!Number.isInteger(p)||p<1||p>900||O+p*1e3!==Date.parse(n.expiresAt))&&g.addIssue({code:"custom",message:"Invalid IAM upload capability"})});var i=e.string().min(1).max(256),c=e.string().regex(/^[a-f0-9]{64}$/),le=e.strictObject({versionId:e.uuid(),manifestDigest:c,sourceGraphDigest:c,pageKey:i,stateKey:i,documentKey:i,documentHash:c,elementKey:i.optional(),nodeId:i.optional(),contentHash:c.optional(),renderKey:i.optional()}),G=e.strictObject({pageKey:i,documentKey:i,expectedDocumentHash:c,renderKey:i.optional(),nodeId:i,elementKey:i,expectedContentHash:c,property:e.enum(["text","fontSize","color"]),value:e.union([e.string().max(4e3),e.number().finite()])}),V=e.strictObject({versionId:e.uuid(),manifestDigest:c,sourceGraphDigest:c,pageKey:i,stateKey:i,documentKey:i,documentHash:c,renderKey:i.optional(),patches:e.array(G.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),_=/^[a-z][a-z0-9-]{0,39}$/,K=e.string().regex(_),I=e.enum(["web","ios","android"]),ue=e.discriminatedUnion("action",[e.strictObject({action:e.literal("register"),requestId:e.uuid(),client:K,platform:I,label:e.string().trim().min(1).max(100),sha256:c,bytes:e.number().int().min(1),transferBytes:e.number().int().min(1)}),e.strictObject({action:e.literal("complete"),versionId:e.uuid()}),e.strictObject({action:e.literal("current"),versionId:e.uuid(),expectedCurrent:e.uuid().nullable()}),e.strictObject({action:e.literal("delivery"),enabled:e.boolean()}),e.strictObject({action:e.literal("changes"),versionId:e.uuid(),experimentId:e.uuid(),variationId:i,changesetId:e.uuid().nullable(),expectedRevision:c.nullable(),editorUrl:e.string().url().max(2048),patches:e.array(G).min(1).max(200)})]),S=e.strictObject({id:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),clientKey:K,platform:I,label:e.string(),sha256:c,bytes:e.number().int().positive(),objectKey:e.string(),state:e.enum(["uploading","ready","rejected"]),isCurrent:e.boolean(),revision:e.number().int().nonnegative(),createdAt:e.string(),expiresAt:e.string(),readyAt:e.string().nullable(),summary:e.record(e.string(),e.json()),routeTree:e.json().nullable(),validation:e.record(e.string(),e.json())}),F=e.strictObject({key:K,platform:I,currentId:e.uuid().nullable()}),ge=e.strictObject({rows:e.array(S).max(100),nextCursor:e.uuid().nullable(),clients:e.array(F).max(20)}),v=e.strictObject({storedBytes:e.number().int().nonnegative(),reservedBytes:e.number().int().nonnegative(),chargedBytes:e.number().int().nonnegative(),versions:e.number().int().nonnegative(),objects:e.number().int().nonnegative(),orphanObjects:e.number().int().nonnegative(),missingReadyObjects:e.number().int().nonnegative(),unknownObjectSizes:e.number().int().nonnegative(),byteLimit:e.number().int().positive(),versionLimit:e.number().int().positive(),remainingBytes:e.number().int().nonnegative()}),pe=e.strictObject({asOf:e.iso.datetime({offset:!0}),reclamation:e.literal("manual-review-required"),buckets:e.strictObject({source:v,runtime:v,previews:v})}),de=e.strictObject({asOf:e.iso.datetime({offset:!0}),reviewOnly:e.literal(!0),complete:e.boolean(),issues:e.strictObject({scanLimit:e.boolean(),invalidReferences:e.number().int().nonnegative(),missingVersions:e.number().int().nonnegative()}),totals:e.strictObject({versions:e.number().int().nonnegative(),protected:e.number().int().nonnegative(),reviewCandidates:e.number().int().nonnegative()}),rows:e.array(e.strictObject({versionId:e.uuid(),kind:e.enum(["source","runtime"]),state:e.enum(["uploading","ready","rejected"]),createdAt:e.iso.datetime({offset:!0}),reviewAfter:e.iso.datetime({offset:!0}),reasons:e.array(e.enum(["current","upload-capability","retention-grace","incomplete-inventory","retained-observation","gb","gb-observation","funnel-draft","funnel-draft-observation","funnel-version","funnel-version-observation"])).max(11)})).max(50),nextCursor:e.uuid().nullable()}),ye=e.strictObject({version:S,actorId:e.uuid(),claims:e.record(e.string(),e.json())}),be=e.strictObject({version:S,upload:A.nullable()}),fe=e.object({format:e.literal("indiana-route-state-index"),schemaVersion:e.literal(3),routes:e.array(e.object({routeKey:i,path:e.string(),documentKey:i,documentHash:c,initialStateKey:i,initialRenderKey:i})),renders:e.array(w)}).loose().superRefine((n,g)=>{(!n.renders||n.routes.some(s=>!n.renders?.some(o=>o.renderKey===s.initialRenderKey&&o.routeKey===s.routeKey&&o.documentKey===s.documentKey&&o.stateKey===s.initialStateKey&&o.documentHash===s.documentHash&&o.entryMode==="hard")))&&g.addIssue({code:"custom",message:"Incomplete render catalog"})}),he=e.strictObject({rows:e.array(e.object({id:e.uuid(),name:e.string(),status:e.string(),variations:e.array(e.object({id:i,key:i,name:e.string().optional()}).loose())}).loose()),limited:e.boolean()}),xe=e.strictObject({enabled:e.boolean(),allowedOrigins:e.array(e.string())});var L=a.strictObject({selector:a.string().min(1).max(2048),action:a.enum(["set","append","remove"]),attribute:a.string().min(1).max(128).refine(n=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(n)||/^(aria|data)-[a-z0-9_-]+$/.test(n)),value:a.string().max(5e4).optional(),parentSelector:a.string().max(2048).optional(),insertBeforeSelector:a.string().max(2048).optional()}),q=a.strictObject({variation:a.string().min(1).max(128),description:a.string().max(2e3).default(""),css:a.string().max(1e5).default(""),js:a.string().max(1e5).default(""),domMutations:a.array(L).max(200).default([]),iam:V.optional(),renderGuard:P.optional()}),j=q.omit({variation:!0,description:!0,iam:!0}),J=y.omit({variations:!0,active:!0}).extend({changeId:a.string().regex(/^[a-f0-9]{64}$/),variations:a.tuple([j,j]).rest(j).refine(n=>n.length<=20)}),Re=a.strictObject({trackExposures:a.boolean(),environmentId:a.uuid(),generation:a.string().regex(/^[a-f0-9]{64}$/),experiments:a.array(J).max(100),savedGroups:h});export{z as a,k as b,y as c,N as d,U as e,D as f,h as g,te as h,le as i,L as j,q as k,j as l,J as m,Re as n};
@@ -0,0 +1 @@
1
+ import{a as T,b as C,e as E}from"./chunk-A3N4ZZTM.js";import{a as t}from"./chunk-OVMNCZYC.js";import{a as A,j as N,m as D,p as O}from"./chunk-3BQFJANQ.js";import{b as I}from"./chunk-AE4CUTUE.js";import{a as k}from"./chunk-S5TVMQRC.js";var _={name:"@tinkerlandai/indiana-sdk",version:"0.8.0",description:"Framework-independent Indiana SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.5"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var F=Symbol("IndianaNoContent");function J(d,j,P=URL){let a=d.scope?I.parse(d.scope):void 0,o=new P(d.baseUrl??k);if(o.username||o.password||o.search||o.hash)throw new t("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(o.protocol!=="https:"&&!(o.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(o.hostname)))throw new t("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let L=d.fetch??globalThis.fetch.bind(globalThis),u=d.timeoutMs??1e4;if(!Number.isFinite(u)||u<=0||u>12e4)throw new t("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let p=null,c=0,l=null,m=new Set;function b(){c+=1,p=null,l=null;for(let i of m)i.abort();m.clear()}async function M(i,U={},v="POST",H={}){if(!p)throw new t("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let w=c,n=new AbortController;m.add(n);let f=()=>w!==c?new t("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new t("TIMEOUT","Indiana request timed out"),y,q=new Promise((r,s)=>{y=()=>s(f()),n.signal.addEventListener("abort",y,{once:!0})}),K=setTimeout(()=>n.abort(),u),x=async()=>{let r=await L(`${o.href.replace(/\/$/,"")}/api/v1/${i}`,{method:v,headers:{"Content-Type":"application/json",Authorization:`Bearer ${p}`,[T]:E.current,[C]:_.version,...a?{"X-Indiana-Project":a.projectId,"X-Indiana-Environment":a.environment}:{}},body:v==="POST"?JSON.stringify(U):void 0,signal:n.signal,credentials:"omit",cache:"no-store",redirect:"error",...H.keepalive?{keepalive:!0}:{}});if(n.signal.aborted)throw f();let s;try{s=r.status===204?F:await r.json()}catch{throw n.signal.aborted?f():new t(r.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",r.status,r.headers.get("X-Request-Id")??void 0)}if(n.signal.aborted)throw f();if(w!==c)throw new t("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!r.ok){let e=D.safeParse(s),g=e.success&&(!A.safeParse(e.data.error.code).success||N(e.data.error.code,r.status)),S=g?e.data.error.code:"HTTP_ERROR",R=O(S,r.status,{retryAfter:r.headers.get("Retry-After"),recovery:g?e.data.error.recovery:void 0,reason:g?e.data.error.reason:void 0});throw new t(S,g?e.data.error.message:"Indiana request failed",r.status,r.headers.get("X-Request-Id")??(e.success?e.data.requestId:void 0),{...R,...e.success&&e.data.error.retryable===!1?{retryable:!1}:{},...R.retryAfterSeconds===void 0&&e.success&&e.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:e.data.error.retryAfterSeconds}:{}})}if(r.headers.get(T)!==E.current)throw new t("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&s&&typeof s=="object"&&"scope"in s){let e=I.safeParse(s.scope);if(!e.success||e.data.projectId!==a.projectId||e.data.environment!==a.environment)throw new t("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let h=r.headers.get("X-Indiana-Telemetry-Subject");if(h){if(!/^[a-f0-9]{64}$/.test(h))throw new t("INVALID_RESPONSE","Invalid telemetry identity");l!==h&&(l=h,j?.(l))}return s};try{return await Promise.race([x(),q])}catch(r){throw w!==c?new t("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):r instanceof t?r:new t(n.signal.aborted?"TIMEOUT":"NETWORK_ERROR",n.signal.aborted?"Indiana request timed out":"Unable to read the Indiana response")}finally{clearTimeout(K),n.signal.removeEventListener("abort",y),m.delete(n)}}return{subjectKey:()=>l,identify(i){if(!i.trim()||/\s/.test(i)||i.length>4096)throw new t("INVALID_TOKEN","A nonempty server-issued token is required");b(),p=i},reset:b,request:M}}export{J as a};
@@ -1 +1 @@
1
- import{$d as M,_d as E,ae as j,be as O,ce as T}from"./chunk-HTRQPMJO.js";import{a as u}from"./chunk-5TEZEOHX.js";import{h as w}from"./chunk-RMJJOSVZ.js";import{z as t}from"zod";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Y(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Y as d};
1
+ import{Jg as E,Kg as M,Lg as j,Mg as O,Ng as T}from"./chunk-A3N4ZZTM.js";import{a as u}from"./chunk-OVMNCZYC.js";import{x as w}from"./chunk-3BQFJANQ.js";import{z as t}from"zod";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Y(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Y as d};
@@ -0,0 +1,17 @@
1
+ function G(e){let t=2166136261,n=e.length;for(let r=0;r<n;r++)t^=e.charCodeAt(r),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);return t>>>0}function C(e,t,n){return n===2?G(G(e+t)+"")%1e4/1e4:null}function ae(e){return e<=0?[]:new Array(e).fill(1/e)}function V(e,t){return e>=t[0]&&e<t[1]}function N(e,t){for(let[n,r]of t.entries())if(V(e,r))return n;return-1}function M(e,t,n){t=t===void 0?1:t,t<0?t=0:t>1&&(t=1);let r=ae(e);n=n||r,n.length!==e&&(n=r);let o=n.reduce((a,u)=>u+a,0);(o<.99||o>1.01)&&(n=r);let i=0,s=t;return n.map(a=>{let u=i;return i+=a,[u,u+s*a]})}function I(e,t,n){if(!t)return null;let r=t.split("?")[1];if(!r)return null;let i=r.replace(/#.*/,"").split("&").map(s=>s.split("=",2)).filter(([s])=>s===e).map(([,s])=>s===void 0?NaN:parseInt(s))[0];return i!==void 0&&i>=0&&i<n?i:null}function q(e){try{return e()}catch{return!1}}function B(e){return typeof e=="string"?e:JSON.stringify(e)}function p(e){typeof e=="number"&&(e=e+""),(!e||typeof e!="string")&&(e="0");let t=e.replace(/(^v|\+.*$)/g,"").split(/[-.]/);return t.length===3&&t.push("~"),t.map(n=>n.match(/^[0-9]+$/)?n.padStart(5," "):n).join("-")}function ue(e){try{let t=e.replace(/([^\\])\//g,"$1\\/");return new RegExp(t)}catch{return}}function W(e,t){if(!t.length)return!1;let n=!1,r=!1;for(let o of t){let i=De(e,o.type,o.pattern);if(o.include===!1){if(i)return!1}else n=!0,i&&(r=!0)}return r||!n}function Ue(e,t,n){try{let r=t.replace(/[*.+?^${}()|[\]\\]/g,"\\$&").replace(/_____/g,".*");return n&&(r="\\/?"+r.replace(/(^\/|\/$)/g,"")+"\\/?"),new RegExp("^"+r+"$","i").test(e)}catch{return!1}}function _e(e,t){try{let n=new URL(t.replace(/^([^:/?]*)\./i,"https://$1.").replace(/\*/g,"_____"),"https://_____"),r=[[e.host,n.host,!1],[e.pathname,n.pathname,!0]];return n.hash&&r.push([e.hash,n.hash,!1]),n.searchParams.forEach((o,i)=>{r.push([e.searchParams.get(i)||"",o,!1])}),!r.some(o=>!Ue(o[0],o[1],o[2]))}catch{return!1}}function De(e,t,n){try{let r=new URL(e,"https://_");if(t==="regex"){let o=ue(n);return o?o.test(r.href)||o.test(r.href.substring(r.origin.length)):!1}else if(t==="simple")return _e(r,n);return!1}catch{return!1}}function J(e){for(let n of["namespace","status","url","groups"])if(Object.hasOwn(e,n))throw new TypeError(`Retired experiment field: ${n}`);let t=e;if(t.hashVersion!==void 0&&t.hashVersion!==2)throw new TypeError("Only hash version 2 is supported");if(t.filters?.some(n=>n.hashVersion!==2))throw new TypeError("Only hash version 2 is supported")}function H(e){for(let t of Object.values(e)){if(Array.isArray(t))throw new TypeError("Saved groups require typed list or condition entries");if(t&&Object.hasOwn(t,"useEmptyListGroup"))throw new TypeError("Retired saved group field: useEmptyListGroup")}}function ce(e){for(let t of["overrides","groups"])if(Object.hasOwn(e,t))throw new TypeError(`Retired evaluation context field: ${t}`);H(e.savedGroups??{})}var je=e=>e/2**32|0,Pe=e=>e>>>0;function fe(e,t,n,r){let o=je(n),i=Pe(n);e.setUint32(t,r?i:o,r),e.setUint32(t+4,r?o:i,r)}function le(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var Q=e=>e?`"${e}" `:"";function Ke(e,t=""){if(typeof e!="number")throw new TypeError(Q(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(Q(t)+"expected integer >= 0, got "+e);return e}function L(e,t,n=""){if(le(e)&&(t===void 0||e.length===t))return e;t!==void 0&&Ke(t,"length");let r=le(e),o=t!==void 0?` of length ${t}`:"",i=r?`length=${e.length}`:`type=${typeof e}`,s=Q(n)+"expected Uint8Array"+o+", got "+i;throw r?new RangeError(s):new TypeError(s)}var Ge=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},de=(e,t)=>{Ge(e,t);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function X(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function he(e,t){L(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function z(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function U(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function x(e,t){return e<<32-t|e>>>t}var Ne=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Me=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function be(e){if(L(e),Ne)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Me[e[n]];return t}function Ie(e,t,n="opts"){return de(e,"defaults"),t!==void 0&&de(t,n),Object.assign(Object.create(null),e,t)}function pe(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=Ie({},t,"info");let n=(o,i)=>e(i).update(o).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=o=>e(o),Object.assign(n,t),Object.freeze(n)}var ge=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function xe(e,t,n){return e&t^~e&n}function ye(e,t,n){return e&t^e&n^t&n}var _=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,n,r,o){this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(t),this.view=U(this.buffer)}update(t){X(this),L(t);let{view:n,buffer:r,blockLen:o}=this,i=t.length,s=!1;for(let a=0;a<i;){let u=Math.min(o-this.pos,i-a);if(u===o){let f=U(t);for(;o<=i-a;a+=o)this.process(f,a);s=!0;continue}r.set(a===0&&u===i?t:t.subarray(a,a+u),this.pos),this.pos+=u,a+=u,this.pos===o&&(this.process(n,0),this.pos=0,s=!0)}return this.length+=t.length,s&&this.roundClean(),this}digestInto(t){X(this),he(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,n.fill(0,s),this.padOffset>o-s&&(this.process(r,0),n.fill(0)),fe(r,o-8,this.length*8,i),this.process(r,0),this.roundClean();let a=t===n?r:U(t),u=this.outputLen,f=u/4,d=this.get();if(u%4||f>d.length)throw new Error("invalid outputLen");for(let c=0;c<f;c++)a.setUint32(4*c,d[c],i)}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneIntoMeta(t){let{buffer:n,length:r,finished:o,destroyed:i,pos:s}=this;return t.destroyed=i,t.finished=o,t.length=r,t.pos=s,s&&t.buffer.set(n),t}clone(){return this._cloneInto()}},ke=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var qe=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),E=new Uint32Array(64),Y=class extends _{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(t,n){super(64,t,8,!1),this.A=n[0]|0,this.B=n[1]|0,this.C=n[2]|0,this.D=n[3]|0,this.E=n[4]|0,this.F=n[5]|0,this.G=n[6]|0,this.H=n[7]|0}get(){let{A:t,B:n,C:r,D:o,E:i,F:s,G:a,H:u}=this;return[t,n,r,o,i,s,a,u]}set(t,n,r,o,i,s,a,u){this.A=t|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=u|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,n){for(let c=0;c<16;c++,n+=4)E[c]=t.getUint32(n,!1);for(let c=16;c<64;c++){let h=E[c-15],g=E[c-2],w=x(h,7)^x(h,18)^h>>>3,S=x(g,17)^x(g,19)^g>>>10;E[c]=S+E[c-7]+w+E[c-16]|0}let{A:r,B:o,C:i,D:s,E:a,F:u,G:f,H:d}=this;for(let c=0;c<64;c++){let h=x(a,6)^x(a,11)^x(a,25),g=d+h+xe(a,u,f)+qe[c]+E[c]|0,S=(x(r,2)^x(r,13)^x(r,22))+ye(r,o,i)|0;d=f,f=u,u=a,a=s+g|0,s=i,i=o,o=r,r=g+S|0}r=r+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,u=u+this.F|0,f=f+this.G|0,d=d+this.H|0,this.set(r,o,i,s,a,u,f,d)}roundClean(){z(E)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),z(this.buffer)}},Z=class extends Y{constructor(){super(32,ke)}};var me=pe(()=>new Z,ge(1));var we=new Map,ee=32,Se=new WeakMap,Ae=new WeakMap;function We(e){return be(me(new TextEncoder().encode(String(e))))}var j=e=>Array.isArray(e)?e.map(j):typeof e=="string"||typeof e=="number"?We(e):null,D=e=>typeof e=="string"?e.toLowerCase():e;function Fe(e){let t=Se.get(e);return t||(t=new Set(e),Se.set(e,t)),t}function Je(e){let t=Ae.get(e);return t||(t=new Set(e.map(D)),Ae.set(e,t)),t}function Qe(e){H(e);for(let t of Object.values(e)){let n=t?.type==="list"||t?.type==="hashed"?t.values:null;n&&n.length>=ee&&Fe(n)}return e}function k(e,t,n,r){n=n||{},r||H(n),r=r||new Set;for(let[o,i]of Object.entries(t))switch(o){case"$or":if(!Te(e,i,n,r))return!1;break;case"$nor":if(Te(e,i,n,r))return!1;break;case"$and":if(!et(e,i,n,r))return!1;break;case"$not":if(k(e,i,n,r))return!1;break;case"$savedGroup":if(!Xe(e,i,n,r))return!1;break;default:if(!O(i,Re(e,o),n,!1,r))return!1}return!0}function Xe(e,t,n,r){if(!t||typeof t!="object"||Array.isArray(t))return!1;let{id:o,attributeKey:i}=t;if(typeof o!="string"||r.has(o)||i!==void 0&&typeof i!="string")return!1;let s=n[o];if(!s||Array.isArray(s)||typeof s!="object")return!1;let a=new Set(r).add(o);if(s.type==="list"||s.type==="hashed"){let u=i??s.attributeKey;if(typeof u!="string"||!Array.isArray(s.values))return!1;let f=Re(e,u);return T(s.type==="hashed"?j(f):f,s.values)}return s.type==="condition"?!s.condition||typeof s.condition!="object"?!1:k(e,s.condition,n,a):!1}function Re(e,t){let n=t.split("."),r=e;for(let o of n)if(r&&typeof r=="object"&&o in r)r=r[o];else return null;return r}function Ee(e,t=!1){let n=`${e}${t?"/i":""}`,r=we.get(n);return r||(r=new RegExp(e.replace(/([^\\])\//g,"$1\\/"),t?"i":void 0),we.set(n,r)),r}function O(e,t,n,r=!1,o=new Set){if(typeof e=="string")return r?String(t).toLowerCase()===e.toLowerCase():t+""===e;if(typeof e=="number")return t*1===e;if(typeof e=="boolean")return t!==null&&!!t===e;if(e===null)return t===null;if(Array.isArray(e)||!Ce(e))return JSON.stringify(t)===JSON.stringify(e);let i=e;for(let s in i)if(!Ze(s,t,i[s],n,o))return!1;return!0}function Ce(e){let t=Object.keys(e);return t.length>0&&t.filter(n=>n[0]==="$").length===t.length}function ze(e){if(e===null)return"null";if(Array.isArray(e))return"array";let t=typeof e;return["string","number","boolean","object","undefined"].includes(t)?t:"unknown"}function Ye(e,t,n,r){if(!Array.isArray(e))return!1;let o=Ce(t)?i=>O(t,i,n,!1,r):i=>k(i,t,n,r);for(let i=0;i<e.length;i++)if((e[i]??null)!==null&&o(e[i]))return!0;return!1}function T(e,t,n=!1){if(n){let o;if(t.length>=ee){let i=Je(t);o=s=>{let a=D(s);return!(typeof a=="number"&&Number.isNaN(a))&&i.has(a)}}else o=i=>t.some(s=>D(i)===D(s));return Array.isArray(e)?e.some(i=>o(i)):o(e)}let r=t.length>=ee?(o=>i=>o.has(i))(Fe(t)):o=>t.includes(o);return Array.isArray(e)?e.some(o=>r(o)):r(e)}function ve(e){return e===void 0?[]:e&&typeof e=="object"&&(e.type==="list"||e.type==="hashed")&&Array.isArray(e.values)?e.values:null}function Be(e,t,n,r=!1,o=new Set){if(!Array.isArray(e))return!1;for(let i=0;i<t.length;i++){let s=!1;for(let a=0;a<e.length;a++)if(O(t[i],e[a],n,r,o)){s=!0;break}if(!s)return!1}return!0}function Ze(e,t,n,r,o=new Set){let i=t,s=n;switch(e){case"$veq":return p(t)===p(n);case"$vne":return p(t)!==p(n);case"$vgt":return p(t)>p(n);case"$vgte":return p(t)>=p(n);case"$vlt":return p(t)<p(n);case"$vlte":return p(t)<=p(n);case"$eq":return t===n;case"$ne":return t!==n;case"$lt":return i<s;case"$lte":return i<=s;case"$gt":return i>s;case"$gte":return i>=s;case"$exists":return n?t!=null:t==null;case"$in":return Array.isArray(n)?T(t,n):!1;case"$ini":return Array.isArray(n)?T(t,n,!0):!1;case"$inGroup":{let a=r[n],u=ve(a);return u===null?!1:T(a?.type==="hashed"?j(t):t,u)}case"$notInGroup":{let a=r[n],u=ve(a);return u===null?!1:!T(a?.type==="hashed"?j(t):t,u)}case"$nin":return Array.isArray(n)?!T(t,n):!1;case"$nini":return Array.isArray(n)?!T(t,n,!0):!1;case"$not":return!O(n,t,r,!1,o);case"$size":return Array.isArray(t)?O(n,t.length,r,!1,o):!1;case"$elemMatch":return Ye(t,n,r,o);case"$all":return Array.isArray(n)?Be(t,n,r,!1,o):!1;case"$alli":return Array.isArray(n)?Be(t,n,r,!0,o):!1;case"$regex":try{return Ee(n).test(t)}catch{return!1}case"$regexi":try{return Ee(n,!0).test(t)}catch{return!1}case"$type":return ze(t)===n;default:return!1}}function Te(e,t,n,r){if(!t.length)return!0;for(let o of t)if(k(e,o,n,r))return!0;return!1}function et(e,t,n,r){for(let o of t)if(!k(e,o,n,r))return!1;return!0}function te(e){return ce(e),{context:e,stack:{evaluatedFeatures:new Set}}}function ne(e){return{...e.attributes,...e.attributeOverrides}}function m(e,t,n){let r=t||"id",o="",i=ne(e);return i[r]&&(o=i[r]),!o&&n&&(i[n]&&(o=i[n]),o&&(r=n)),{hashAttribute:r,hashValue:o}}function l(e,t,n){e.context.log?.(t,n)}function $(e,t){return t=t||0,`${e}__${t}`}function P(e,t){return`${e}||${t}`}function tt(e,t,n){let r=e.stickyBucketAssignmentDocs;if(!r)return{};let{hashAttribute:o,hashValue:i}=m(e,t),s=P(o,B(i)),{hashAttribute:a,hashValue:u}=m(e,n),f=u?P(a,B(u)):null,d={};return f&&r[f]&&Object.assign(d,r[f].assignments||{}),r[s]&&Object.assign(d,r[s].assignments||{}),d}function re({context:e,expKey:t,expBucketVersion:n,expHashAttribute:r,expFallbackAttribute:o,expMinBucketVersion:i,expMeta:s}){n=n||0,i=i||0,r=r||"id",s=s||[];let a=$(t,n),u=tt(e,r,o);if(i>0)for(let c=0;c<i;c++){let h=$(t,c);if(u[h]!==void 0)return{variation:-1,versionIsBlocked:!0}}let f=u[a];if(f===void 0)return{variation:-1};let d=s.findIndex(c=>c.key===f);return d<0?{variation:-1}:{variation:d}}function oe(e,t,n,r){let o=P(t,n),i=e.stickyBucketAssignmentDocs,s=i&&i[o]?i[o].assignments||{}:{},a={...s,...r},u=JSON.stringify(s)!==JSON.stringify(a);return{key:o,doc:{attributeName:t,attributeValue:n,assignments:a},changed:u}}function nt(e){let t=new Set;return Object.values(e).forEach(n=>{if(n.rules)for(let r of n.rules)r.variations&&(t.add(r.hashAttribute||"id"),r.fallbackAttribute&&t.add(r.fallbackAttribute))}),Array.from(t)}function rt(e,t=e.features||{}){let n={};return nt(t).forEach(r=>{let{hashValue:o}=m(e,r);n[r]=B(o)}),n}function y(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function ot(e){return y({...e,parentConditions:e.parentConditions?.map(t=>y(t)),filters:e.filters?.map(t=>y(t)),meta:e.meta?.map(t=>y(t))})}function Ht(e){return y({...e,parentConditions:e.parentConditions?.map(t=>y(t)),filters:e.filters?.map(t=>y(t)),meta:e.meta?.map(t=>y(t)),tracks:e.tracks?.map(t=>({experiment:ot(t.experiment),result:y(t.result)}))})}function st(e,t){let n=te(t),r=Oe(e,null,n);return t.onExperimentEval?.(e,r),r}function it(e,t){return ie(e,te(t))}function at(e){return e.forcedVariations||{}}function Ve(e,t,n){let{context:r}=e;if(r.trackedExperiments){let o=Le(t,n);if(r.trackedExperiments.has(o))return;r.trackedExperiments.add(o)}se(()=>r.onExperimentViewed?.(t,n))}function ut(e,t,n){let{context:r}=e;if(r.trackedFeatureUsage){let o=JSON.stringify(n.value);if(r.trackedFeatureUsage[t]===o)return;r.trackedFeatureUsage[t]=o}se(()=>r.onFeatureUsage?.(t,n))}function se(e){try{let t=e();t&&typeof t.catch=="function"&&t.catch(()=>{})}catch{}}function ie(e,t){let{context:n}=t;if(t.stack.evaluatedFeatures.has(e))return l(t,`evalFeature: circular dependency detected: ${t.stack.id} -> ${e}`,{from:t.stack.id,to:e}),v(t,e,null,"cyclicPrerequisite");t.stack.evaluatedFeatures.add(e),t.stack.id=e;let r=n.features?.[e];for(let i of r?.rules??[])J(i);let o=n.forcedFeatureValues;if(o&&o.has(e))return l(t,"Global override",{id:e,value:o.get(e)}),v(t,e,o.get(e),"override");if(!r)return l(t,"Unknown feature",{id:e}),v(t,e,null,"unknownFeature");if(r.rules){let i=new Set(t.stack.evaluatedFeatures);e:for(let s of r.rules){if(s.parentConditions)for(let f of s.parentConditions){t.stack.evaluatedFeatures=new Set(i);let d=ie(f.id,t);if(d.source==="cyclicPrerequisite")return v(t,e,null,"cyclicPrerequisite");let c={value:d.value};if(!k(c,f.condition||{},n.savedGroups||{})){if(f.gate)return l(t,"Feature blocked by prerequisite",{id:e,rule:s}),v(t,e,null,"prerequisite");l(t,"Skip rule because prerequisite evaluation fails",{id:e,rule:s});continue e}}if(s.filters&&He(s.filters,t)){l(t,"Skip rule because of filters",{id:e,rule:s});continue}if("force"in s){if(s.condition&&!$e(s.condition,t)){l(t,"Skip rule because of condition ff",{id:e,rule:s});continue}if(!ct(t,s.seed||e,s.hashAttribute,n.saveStickyBucketAssignmentDoc&&!s.disableStickyBucketing?s.fallbackAttribute:void 0,s.range,s.coverage,s.hashVersion)){l(t,"Skip rule because user not included in rollout",{id:e,rule:s});continue}return l(t,"Force value from rule",{id:e,rule:s}),s.tracks&&s.tracks.forEach(f=>{Ve(t,f.experiment,f.result)}),v(t,e,s.force,"force",s.id)}if(!s.variations){l(t,"Skip invalid rule",{id:e,rule:s});continue}let a={variations:s.variations,key:s.key||e};"coverage"in s&&(a.coverage=s.coverage),s.weights&&(a.weights=s.weights),s.hashAttribute&&(a.hashAttribute=s.hashAttribute),s.fallbackAttribute&&(a.fallbackAttribute=s.fallbackAttribute),s.disableStickyBucketing&&(a.disableStickyBucketing=s.disableStickyBucketing),s.bucketVersion!==void 0&&(a.bucketVersion=s.bucketVersion),s.minBucketVersion!==void 0&&(a.minBucketVersion=s.minBucketVersion),s.meta&&(a.meta=s.meta),s.ranges&&(a.ranges=s.ranges),s.name&&(a.name=s.name),s.phase&&(a.phase=s.phase),s.seed&&(a.seed=s.seed),s.hashVersion&&(a.hashVersion=s.hashVersion),s.filters&&(a.filters=s.filters),s.condition&&(a.condition=s.condition);let u=Oe(a,e,t);if(n.onExperimentEval?.(a,u),u.inExperiment&&!u.passthrough)return v(t,e,u.value,"experiment",s.id,a,u)}}return l(t,"Use default value",{id:e,value:r.defaultValue}),v(t,e,r.defaultValue===void 0?null:r.defaultValue,"defaultValue")}function Oe(e,t,n){let{context:r}=n;J(e);let o=e.key,i=e.variations.length;if(i<2)return l(n,"Invalid experiment",{id:o}),b(n,e,-1,!1,t);if(r.enabled===!1)return l(n,"Context disabled",{id:o}),b(n,e,-1,!1,t);if(e.urlPatterns&&!W(r.url||"",e.urlPatterns))return l(n,"Skip because of url targeting",{id:o}),b(n,e,-1,!1,t);let s=I(o,r.url||"",i);if(s!==null)return l(n,"Force via querystring",{id:o,variation:s}),b(n,e,s,!1,t);let u=at(r)[o];if(u!==void 0)return l(n,"Force via dev tools",{id:o,variation:u}),b(n,e,u,!1,t);if(e.active===!1)return l(n,"Skip because inactive",{id:o}),b(n,e,-1,!1,t);let{hashAttribute:f,hashValue:d}=m(r,e.hashAttribute,r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0);if(!d)return l(n,"Skip because missing hashAttribute",{id:o}),b(n,e,-1,!1,t);let c=-1,h=!1,g=!1;if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{variation:A,versionIsBlocked:F}=re(y({context:r,expKey:e.key,expBucketVersion:e.bucketVersion,expHashAttribute:e.hashAttribute,expFallbackAttribute:e.fallbackAttribute,expMinBucketVersion:e.minBucketVersion,expMeta:e.meta}));h=A>=0,c=A,g=!!F}if(!h){if(e.filters&&He(e.filters,n))return l(n,"Skip because of filters",{id:o}),b(n,e,-1,!1,t);if(e.include&&!q(e.include))return l(n,"Skip because of include function",{id:o}),b(n,e,-1,!1,t);if(e.condition&&!$e(e.condition,n))return l(n,"Skip because of condition exp",{id:o}),b(n,e,-1,!1,t);if(e.parentConditions){let A=new Set(n.stack.evaluatedFeatures);for(let F of e.parentConditions){n.stack.evaluatedFeatures=new Set(A);let R=ie(F.id,n);if(R.source==="cyclicPrerequisite")return b(n,e,-1,!1,t);let K={value:R.value};if(!k(K,F.condition||{},r.savedGroups||{}))return l(n,"Skip because prerequisite evaluation fails",{id:o}),b(n,e,-1,!1,t)}}}let w=C(e.seed||o,d,e.hashVersion??2);if(w===null)return l(n,"Skip because of invalid hash version",{id:o}),b(n,e,-1,!1,t);if(!h){let A=e.ranges||M(i,e.coverage===void 0?1:e.coverage,e.weights);c=N(w,A)}if(g)return l(n,"Skip because sticky bucket version is blocked",{id:o}),b(n,e,-1,!1,t,void 0,!0);if(c<0)return l(n,"Skip because of coverage",{id:o}),b(n,e,-1,!1,t);if("force"in e)return l(n,"Force variation",{id:o,variation:e.force}),b(n,e,e.force===void 0?-1:e.force,!1,t);if(r.qaMode)return l(n,"Skip because QA mode",{id:o}),b(n,e,-1,!1,t);let S=b(n,e,c,!0,t,w,h);if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{changed:A,key:F,doc:R}=oe(r,f,B(d),{[$(e.key,e.bucketVersion)]:S.key});if(A){r.stickyBucketAssignmentDocs=r.stickyBucketAssignmentDocs||{},r.stickyBucketAssignmentDocs[F]=R;let K=r.saveStickyBucketAssignmentDoc;se(()=>K(R))}}return Ve(n,e,S),l(n,"In experiment",{id:o,variation:S.variationId}),S}function v(e,t,n,r,o,i,s){let a={value:n,on:!!n,off:!n,source:r,ruleId:o||""};return i&&(a.experiment=i),s&&(a.experimentResult=s),r!=="override"&&ut(e,t,a),a}function $e(e,t){return k(ne(t.context),e,t.context.savedGroups||{})}function He(e,t){return e.some(n=>{let{hashValue:r}=m(t.context,n.attribute);if(!r)return!0;let o=C(n.seed,r,n.hashVersion||2);return o===null?!0:!n.ranges.some(i=>V(o,i))})}function ct(e,t,n,r,o,i,s){if(!o&&i===void 0)return!0;if(!o&&i===0)return!1;let{hashValue:a}=m(e.context,n,r);if(!a)return!1;let u=C(t,a,s??2);return u===null?!1:o?V(u,o):i!==void 0?u<=i:!0}function b(e,t,n,r,o,i,s){let a=!0;(n<0||n>=t.variations.length)&&(n=0,a=!1);let{hashAttribute:u,hashValue:f}=m(e.context,t.hashAttribute,e.context.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0),d=t.meta?.[n]??{},c=t.variations[0];for(let[g,w]of t.variations.entries())if(g===n){c=w;break}let h={key:d.key||""+n,featureId:o,inExperiment:a,hashUsed:r,variationId:n,value:c,hashAttribute:u,hashValue:f,stickyBucketUsed:!!s};return d.name&&(h.name=d.name),i!==void 0&&(h.bucket=i),d.passthrough&&(h.passthrough=d.passthrough),h}function Le(e,t){return t.hashAttribute+t.hashValue+e.key+t.variationId}/*!
2
+ Copyright (c) 2025 GrowthBook, Inc.
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
5
+ furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all
8
+ copies or substantial portions of the Software.
9
+
10
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
11
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
13
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
14
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
15
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
16
+ SOFTWARE.
17
+ */export{y as a,Ht as b,I as c,B as d,W as e,be as f,me as g,Qe as h,k as i,rt as j,st as k,it as l,Le as m};
@@ -1 +1 @@
1
- import{J as o}from"./chunk-RMJJOSVZ.js";var n=class extends Error{constructor(t,s,y,i,r){super(s);this.code=t;this.status=y;this.requestId=i;this.name="IndianaError",this.reason=r?.reason;let e=o(t,y??0,{...r,retryAfter:r?.retryAfterSeconds===void 0?void 0:String(r.retryAfterSeconds)});this.retryable=e.retryable,this.recovery=e.recovery,this.retryAfterSeconds=e.retryAfterSeconds}code;status;requestId;retryable;recovery;retryAfterSeconds;reason};export{n as a};
1
+ import{p as o}from"./chunk-3BQFJANQ.js";var n=class extends Error{constructor(t,s,y,i,r){super(s);this.code=t;this.status=y;this.requestId=i;this.name="IndianaError",this.reason=r?.reason;let e=o(t,y??0,{...r,retryAfter:r?.retryAfterSeconds===void 0?void 0:String(r.retryAfterSeconds)});this.retryable=e.retryable,this.recovery=e.recovery,this.retryAfterSeconds=e.retryAfterSeconds}code;status;requestId;retryable;recovery;retryAfterSeconds;reason};export{n as a};
@@ -0,0 +1 @@
1
+ import{a as m,b as j}from"./chunk-KQCTDXVD.js";import{z as e}from"zod";var f=e.json().superRefine((t,a)=>{let r=0;function i(o,s){if(++r>1e4||s>20){a.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof o=="string"&&(o.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(o))&&a.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(o))o.forEach(n=>i(n,s+1));else if(o&&typeof o=="object")for(let[n,c]of Object.entries(o))(n.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(n)||["__proto__","prototype","constructor"].includes(n))&&a.addIssue({code:"custom",message:"Reserved JSON property"}),i(c,s+1)}i(t,0),new TextEncoder().encode(JSON.stringify(t)).byteLength>65536&&a.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),$=e.record(e.string().min(1).max(128),f).superRefine((t,a)=>{(!f.safeParse(t).success||Object.keys(t).length>128||new TextEncoder().encode(JSON.stringify(t)).byteLength>65536||["__proto__","constructor","prototype"].some(r=>Object.hasOwn(t,r)))&&a.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),D=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),h=$.superRefine((t,a)=>{function r(i){if(Array.isArray(i))i.forEach(r);else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i)){if(o==="$savedGroup"&&!e.strictObject({id:e.uuid(),attributeKey:e.string().min(1).max(128).optional()}).safeParse(s).success&&a.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!o.startsWith("$")&&o.split(".").some(n=>["__proto__","prototype","constructor"].includes(n))&&a.addIssue({code:"custom",message:"Reserved attribute path"}),o.startsWith("$")&&!D.has(o)&&a.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${o}`}),["$regex","$regexi"].includes(o)&&typeof s=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(s)||[...s.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(n=>Number(n[1])>255||Number(n[2]||0)>255)||o==="$regexi"&&/[^\x00-\x7f]/.test(s.replace(/\\u([0-9a-f]{4})/gi,(n,c)=>String.fromCharCode(Number.parseInt(c,16)))))&&a.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(s)}catch{a.addIssue({code:"custom",message:"Invalid regular expression"})}}r(s)}}typeof t.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(t.source)&&("operator"in t||"predicates"in t||"groupId"in t)&&a.addIssue({code:"custom",message:"Obsolete condition protocol"}),r(t)}),V=e.discriminatedUnion("type",[e.strictObject({type:e.literal("condition"),condition:h}),e.strictObject({type:e.literal("list"),attributeKey:e.string().min(1).max(128),values:e.array(e.union([e.string(),e.number().finite()])).max(1e5)})]).refine(t=>t.type!=="list"||new TextEncoder().encode(JSON.stringify(t.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function C(t){let a=new Set;function r(i){if(Array.isArray(i))i.forEach(r);else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))o==="$savedGroup"&&s&&typeof s=="object"&&!Array.isArray(s)&&typeof s.id=="string"?a.add(s.id):["$inGroup","$notInGroup"].includes(o)&&typeof s=="string"?a.add(s):["$eq","$ne","$in","$nin","$ini","$nini"].includes(o)||r(s)}return r(t),[...a]}var G=e.record(e.uuid(),V).superRefine((t,a)=>{let r=new Set,i=new Set;function o(s){if(r.has(s)){a.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(i.has(s))return;let n=t[s];if(!n){a.addIssue({code:"custom",message:"Missing saved group dependency"});return}r.add(s),n.type==="condition"&&C(n.condition).forEach(o),r.delete(s),i.add(s)}Object.keys(t).forEach(o)}),k=e.tuple([e.number().min(0).max(1),e.number().min(0).max(1)]).refine(([t,a])=>t<=a),A=e.strictObject({attribute:e.string().optional(),seed:e.string().min(1),hashVersion:e.literal(2),ranges:e.array(k).min(1).max(100)}),R=e.strictObject({id:e.string().min(1).max(128),condition:h,gate:e.boolean().optional()}),w={id:e.string().max(128).optional(),condition:h.optional(),parentConditions:e.array(R).max(50).optional(),filters:e.array(A).max(20).optional()},B=e.union([e.strictObject({...w}),e.strictObject({...w,force:f,coverage:e.number().min(0).max(1).optional(),range:k.optional(),seed:e.string().min(1).optional(),hashAttribute:e.string().optional(),hashVersion:e.literal(2).optional()}),e.strictObject({...w,type:e.literal("experiment-ref"),experimentId:e.uuid(),values:e.record(e.string().min(1),f),meta:e.record(e.string().min(1),e.strictObject({passthrough:e.boolean()})).optional()})]),_=e.strictObject({defaultValue:f,rules:e.array(B).max(100)}),X=e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),_).superRefine((t,a)=>{Object.keys(t).length>100&&a.addIssue({code:"custom",message:"Too many Features"});let r=new Set,i=new Set;function o(s){if(r.has(s)){a.addIssue({code:"custom",message:`Cyclic Feature dependency: ${s}`});return}if(i.has(s))return;let n=t[s];if(!n){a.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${s}`});return}r.add(s);for(let c of n.rules)for(let d of c.parentConditions??[])o(d.id);r.delete(s),i.add(s)}Object.keys(t).forEach(o)}),z=e.strictObject({name:e.string().max(80),reason:e.string().max(500),dateStarted:e.iso.datetime({offset:!0}),dateEnded:e.iso.datetime({offset:!0}).nullable(),coverage:e.number().min(0).max(1),variationWeights:e.array(e.number().min(0).max(1)).min(2).max(20).refine(t=>Math.abs(t.reduce((a,r)=>a+r,0)-1)<=.01),condition:h,savedGroups:e.array(e.strictObject({match:e.enum(["any","all","none"]),ids:e.array(e.uuid()).min(1)})).max(50),namespace:e.strictObject({id:e.uuid(),ranges:e.array(k).min(1)}).nullable(),seed:e.string().min(1).max(128)}),J=e.strictObject({key:e.string().min(1).max(128),name:e.string().min(1).max(80),hypothesis:e.string().max(2e3),status:e.enum(["draft","running","stopped"]),hashAttribute:e.string().min(1).max(128),fallbackAttribute:e.string().max(128).nullable(),hashVersion:e.literal(2),disableStickyBucketing:e.boolean(),bucketVersion:e.number().int().min(0).max(1e3),minBucketVersion:e.number().int().min(0).max(1e3),variations:e.array(e.strictObject({id:e.string().min(1),key:e.string().min(1),name:e.string().max(80),description:e.string().max(500)})).min(2).max(20),phases:e.array(z).min(1).max(100),releasedVariationId:e.string().nullable(),excludeFromPayload:e.boolean(),statusSchedule:e.strictObject({startAt:e.iso.datetime({offset:!0}).nullable(),stopAt:e.iso.datetime({offset:!0}).nullable(),stopAfter:e.strictObject({value:e.number().int().positive().max(36500),unit:e.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((t,a)=>{(t.minBucketVersion>t.bucketVersion||t.statusSchedule?.stopAt&&t.statusSchedule?.stopAfter||t.phases.some((r,i)=>{if(i===0)return!1;let o=t.phases[i-1];return!o?.dateEnded||Date.parse(r.dateStarted)<Date.parse(o.dateStarted)||Date.parse(o.dateEnded)>Date.parse(r.dateStarted)})||new Set(t.variations.map(r=>r.key)).size!==t.variations.length||new Set(t.variations.map(r=>r.id)).size!==t.variations.length||t.releasedVariationId!==null&&!t.variations.some(r=>r.id===t.releasedVariationId)||t.statusSchedule?.startAt&&t.statusSchedule?.stopAt&&Date.parse(t.statusSchedule.startAt)>=Date.parse(t.statusSchedule.stopAt)||t.phases.some(r=>r.dateEnded&&Date.parse(r.dateStarted)>=Date.parse(r.dateEnded)||r.namespace?.ranges.some(([i,o],s,n)=>i>=o||n.some(([c,d],g)=>g!==s&&i<d&&c<o)))||t.phases.some(r=>r.variationWeights.length!==t.variations.length))&&a.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});function Y(t,a,r=Date.now()){return Object.fromEntries(Object.entries(t).map(([i,o])=>[i,{defaultValue:o.defaultValue,rules:o.rules.flatMap(s=>{if(!("experimentId"in s))return[j({...s,hashVersion:2})];let n=a[s.experimentId];if(!n)throw new Error(`Missing experiment: ${s.experimentId}`);let c=n.phases.at(-1);if(!c)throw new Error("Experiment requires an active phase");let d=n.statusSchedule?.startAt?Date.parse(n.statusSchedule.startAt):null,g=E(n),F=n.status!=="stopped"&&(n.status==="running"||d!==null&&r>=d)&&(d===null||r>=d)&&(g===null||r<g),{type:M,experimentId:U,values:b,meta:y,...x}=s,p=m({...x,parentConditions:x.parentConditions?.map(u=>m(u)),filters:x.filters?.map(u=>m(u))});if(n.variations.some(u=>!Object.hasOwn(b,u.key))||Object.keys(b).length!==n.variations.length||Object.keys(y??{}).some(u=>!n.variations.some(l=>l.key===u)))throw new Error("Every variation needs a Feature value");let O=u=>{let l=b[u];if(l===void 0)throw new Error("Every variation needs a Feature value");return l},S={$and:[c.condition,...p.condition?[p.condition]:[],...c.savedGroups.map(u=>{let l=u.ids.map(I=>({$savedGroup:{id:I}}));return u.match==="all"?{$and:l}:u.match==="none"?{$nor:l}:{$or:l}})]},v=n.variations.find(u=>u.id===n.releasedVariationId);return v&&!n.excludeFromPayload?y?.[v.key]?.passthrough?[{...p,condition:S}]:[{...p,condition:S,force:O(v.key)}]:[{...p,condition:S,key:n.key,variations:n.variations.map(u=>O(u.key)),meta:n.variations.map(u=>({key:u.key,name:u.name,...m(y?.[u.key]??{})})),weights:c.variationWeights,coverage:F?c.coverage:0,seed:c.seed,hashVersion:2,hashAttribute:n.hashAttribute,...n.fallbackAttribute===null?{}:{fallbackAttribute:n.fallbackAttribute},disableStickyBucketing:!F||n.disableStickyBucketing,bucketVersion:n.bucketVersion,minBucketVersion:n.minBucketVersion,filters:[...p.filters??[],...(n.filters??[]).map(u=>m(u))]}]})}]))}function E(t){if(t.statusSchedule?.stopAt)return Date.parse(t.statusSchedule.stopAt);let a=t.statusSchedule?.stopAfter;if(!a||t.status==="draft"&&!t.statusSchedule?.startAt)return null;let r=t.statusSchedule?.startAt??t.phases.at(-1)?.dateStarted;if(!r)throw new Error("Experiment requires an active phase");return Date.parse(r)+a.value*(a.unit==="days"?864e5:36e5)}function ee(t,a=Date.now()){let r=Object.values(t).filter(i=>i.status!=="stopped"&&!(i.releasedVariationId&&!i.excludeFromPayload)).flatMap(i=>[i.statusSchedule?.startAt?Date.parse(i.statusSchedule.startAt):null,E(i)]).filter(i=>i!==null&&i>a);return r.length?new Date(Math.min(...r)).toISOString():null}var N=J.safeExtend({filters:e.array(A).optional()}),q=e.strictObject({experiments:e.record(e.uuid(),N),savedGroups:G}),P=e.strictObject({attributeName:e.string(),attributeValue:e.string(),assignments:e.record(e.string(),e.string())}),te=e.strictObject({snapshot:q,attributes:$,results:$,stickyBucketAssignmentDocs:e.record(e.string(),P)}),re=e.strictObject({variantKey:e.string().nullable(),bucketVersion:e.number().int().min(0),source:e.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:e.number().min(0).max(1).optional(),stickyBucketUsed:e.boolean().optional(),hashUsed:e.boolean().optional()});export{f as a,$ as b,h as c,V as d,C as e,G as f,B as g,_ as h,X as i,z as j,J as k,Y as l,E as m,ee as n,N as o,q as p,P as q,te as r,re as s};
@@ -0,0 +1,4 @@
1
+ import{a as U}from"./chunk-S5TVMQRC.js";import{e as T,h as I,k as A}from"./chunk-KQCTDXVD.js";function L(e){if(!/^[A-Za-z0-9_-]{1,64}$/.test(e))throw new Error("Invalid device cookie name");let t="";for(let r of document.cookie.split(";"))if(r.trim().startsWith(`${e}=`))try{t=decodeURIComponent(r.trim().slice(e.length+1))}catch{}return/^[A-Za-z0-9_-]{8,128}$/.test(t)||(t=crypto.randomUUID(),document.cookie=`${e}=${encodeURIComponent(t)}; path=/; max-age=${400*24*3600}; SameSite=Lax`),t}function C(){try{let e=sessionStorage.getItem("indiana_sid");return e||(e=crypto.randomUUID(),sessionStorage.setItem("indiana_sid",e)),e}catch{return}}function _(e=U){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname))||t.username||t.password||t.search||t.hash)throw new Error("baseUrl must be an https origin without credentials");return t.origin}var y=new Set,E;function $(e){if(y.add(e),!E){let t=history.pushState,r=history.replaceState,n=()=>{for(let c of y)c()},a=function(...c){t.apply(this,c),n()},d=function(...c){r.apply(this,c),n()};history.pushState=a,history.replaceState=d,addEventListener("popstate",n),addEventListener("hashchange",n),E=()=>{history.pushState===a&&(history.pushState=t),history.replaceState===d&&(history.replaceState=r),removeEventListener("popstate",n),removeEventListener("hashchange",n)}}return()=>{y.delete(e),y.size||(E?.(),E=void 0)}}var G=e=>new TextEncoder().encode(JSON.stringify({events:e})).length;function Y(e,t){let r=e,n=a=>Number.isInteger(a)&&a>=0;return!!r&&typeof r=="object"&&n(r.inserted)&&n(r.duplicates)&&n(r.skipped)&&Array.isArray(r.rejected)&&r.inserted+r.duplicates+r.skipped+r.rejected.length===t}function D(e){let t=[],r,n=(s,o)=>e.log?.(`${e.label} ${s}`,o);function a(s){r===void 0&&t.length&&(r=setTimeout(()=>{c()},s))}async function d(s){let o;try{o=await e.fetch(e.endpoint,{method:"POST",body:JSON.stringify({events:s}),headers:{"Content-Type":"text/plain"},keepalive:!0,credentials:"omit"})}catch(g){return n("not sent",{error:g}),!1}if(o.status===408||o.status===429||o.status>=500)return n("not sent",{status:o.status}),!1;if(!o.ok)return n("rejected",{status:o.status,events:s.length}),!0;let l;try{l=await o.json()}catch{l=void 0}return Y(l,s.length)?(l.rejected.length&&n("rejected",{rejected:l.rejected}),!0):(n("not acknowledged",{status:o.status}),!1)}function c(){clearTimeout(r),r=void 0;let s=[];for(;t.length&&s.length<20&&(!s.length||G([...s,t[0]].map(o=>o.event))<=65536);)s.push(t.shift());return s.length?d(s.map(o=>o.event)).then(o=>{if(o)return a(1e3);let l=s.filter(g=>++g.attempts<5);l.length<s.length&&n("dropped after retries",{events:s.length-l.length}),t.unshift(...l),a(5e3)}):Promise.resolve()}return{push(s){t.push({event:s,attempts:0}),t.length>=20?c():a(1e3)},flush:c}}/*!
2
+ Portions ported from GrowthBook sdk-js @ ed29827 (GrowthBook.ts auto experiments, util.ts mergeQueryStrings,
3
+ plugins/auto-attributes.ts). Copyright (c) GrowthBook, Inc. MIT License.
4
+ */function J(e,t){let r,n;try{r=new URL(e),n=new URL(t)}catch{return t}return r.searchParams.forEach((a,d)=>{n.searchParams.has(d)||n.searchParams.set(d,a)}),n.toString()}function Q(e,t){let r=navigator.userAgent,n=new URLSearchParams(t.search),a={};for(let d of["source","medium","campaign","term","content"]){let c=n.get(`utm_${d}`);c!==null&&(a[`utm${d[0].toUpperCase()}${d.slice(1)}`]=c)}return{id:e,deviceId:e,url:t.href,path:t.pathname,host:t.host,query:t.search,pageTitle:typeof document>"u"?"":document.title,browser:/Edg/.test(r)?"edge":/Chrome/.test(r)?"chrome":/Firefox/.test(r)?"firefox":/Safari/.test(r)?"safari":"unknown",deviceType:/Mobi/.test(r)?"mobile":"desktop",...a}}function z(e){let t=e;if(!(!!t&&typeof t=="object"&&typeof t.environmentId=="string"&&typeof t.trackExposures=="boolean"&&/^[a-f0-9]{64}$/.test(t.generation??"")&&Array.isArray(t.experiments)&&t.experiments.length<=100&&t.experiments.every(n=>!!n&&!["namespace","status","url","groups"].some(a=>Object.hasOwn(n,a))&&(n.hashVersion===void 0||n.hashVersion===2)&&typeof n.key=="string"&&Array.isArray(n.variations)&&n.variations.length>=2&&n.variations.every(a=>!!a&&typeof a.urlRedirect=="string")&&(n.urlPatterns===void 0||Array.isArray(n.urlPatterns)))&&!!t.savedGroups&&typeof t.savedGroups=="object"&&!Array.isArray(t.savedGroups)))throw new Error("Invalid page experiment payload");return t}function ee(e){if(e.configuration&&e.configuration.scope.environmentId!==e.environmentId)throw new Error("Page configuration belongs to another App environment");let t=_(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("environmentId must be the App environment ID");let r=e.fetch??globalThis.fetch.bind(globalThis),n=`${t}/api/v1/page-experiments/${e.environmentId}`,a=L(e.deviceIdCookie??"indiana_did"),d=C(),c=null,s={...e.attributes??{}},o="",l=!1,g=new Map,P=D({endpoint:`${n}/events`,fetch:r,log:e.log,label:"Exposure"}),x=P.flush,f={trackedExperiments:new Set,log:e.log,onExperimentViewed:(i,u)=>{e.trackExposures===!1||c?.trackExposures===!1||P.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:a,...d?{sessionId:d}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:i.key,variationKey:u.key})}},j=()=>{f.url=location.href,f.attributes={...Q(a,location),...s}};function O(i){if(!e.disableCrossOriginUrlRedirects)return!1;try{let u=new URL(location.href);return i.variations.some(p=>{if(!p.urlRedirect)return!1;let v=new URL(p.urlRedirect);return v.protocol!==u.protocol||v.host!==u.host})}catch{return!0}}function N(i,u){let p=e.configuration?.snapshot?.generation;o=i;let v=e.navigate??(m=>location.replace(m)),M=e.navigateDelay??(e.navigate?0:100),V=e.maxNavigateDelay??1e3;Promise.all([Promise.race([u,new Promise(m=>setTimeout(m,V))]),new Promise(m=>setTimeout(m,M))]).then(()=>{!l&&(!e.configuration||e.configuration.fresh&&e.configuration.snapshot?.generation===p)&&v(i)})}function h(){if(!(!c||l||e.configuration&&!e.configuration.fresh)){j();for(let i of c.experiments){if(O(i)){e.log?.("Auto experiment blocked",{id:i.key});continue}let u;try{u=A(i,f)}catch(p){e.log?.("Skipping page experiment",{id:i.key,error:String(p)});continue}if(g.set(i.key,u),!!u.inExperiment){if(u.value.urlRedirect){let p=i.persistQueryString?J(location.href,u.value.urlRedirect):u.value.urlRedirect;T(p,i.urlPatterns??[])?e.log?.("Skipping redirect because original URL matches redirect URL",{id:i.key}):p!==o&&N(p,x())}break}}}}let b="",H=()=>{location.href!==b&&(b=location.href,o="",h())},R,S;function B(){R??=$(H),addEventListener("pagehide",k)}let k=()=>{x()};async function w(){let i=e.configuration?null:await r(n,{cache:"no-cache",credentials:"omit"});if(i&&!i.ok)throw new Error(`Page experiments unavailable (${i.status})`);let u=z(e.configuration?await e.configuration.pageExperiments():await i.json());if(u.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Page experiment payload scope changed");c?.trackExposures===!1&&u.trackExposures&&f.trackedExperiments?.clear(),c=u,f.savedGroups=I(u.savedGroups)}return{async start(){await w(),S??=e.configuration?.subscribe(()=>{!l&&e.configuration?.fresh&&w().then(h).catch(i=>e.log?.("Page configuration unavailable",{error:String(i)}))}),B(),b=location.href,h()},async refresh(){await w(),o="",h()},setAttributes(i){s={...i},h()},getResults(){return new Map(g)},get generation(){return c?.generation??null},destroy(){l=!0,S?.(),R?.(),removeEventListener("pagehide",k),x()}}}export{L as a,C as b,_ as c,$ as d,J as e,Q as f,z as g,ee as h};