@schematichq/schematic-js 1.6.0 → 1.7.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.
@@ -1,3 +1,3 @@
1
- "use strict";(()=>{var pt=Object.create;var Se=Object.defineProperty;var ct=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var ft=Object.getPrototypeOf,yt=Object.prototype.hasOwnProperty;var mt=(n,e)=>()=>{try{return e||n((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};var gt=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ut(e))!yt.call(n,i)&&i!==t&&Se(n,i,{get:()=>e[i],enumerable:!(r=ct(e,i))||r.enumerable});return n};var Tt=(n,e,t)=>(t=n!=null?pt(ft(n)):{},gt(e||!n||!n.__esModule?Se(t,"default",{value:n,enumerable:!0}):t,n));var Ce=mt(_e=>{(function(n){var e=(function(t){var r=typeof globalThis<"u"&&globalThis||typeof n<"u"&&n||typeof global<"u"&&global||{},i={searchParams:"URLSearchParams"in r,iterable:"Symbol"in r&&"iterator"in Symbol,blob:"FileReader"in r&&"Blob"in r&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in r,arrayBuffer:"ArrayBuffer"in r};function a(o){return o&&DataView.prototype.isPrototypeOf(o)}if(i.arrayBuffer)var d=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],s=ArrayBuffer.isView||function(o){return o&&d.indexOf(Object.prototype.toString.call(o))>-1};function p(o){if(typeof o!="string"&&(o=String(o)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(o)||o==="")throw new TypeError('Invalid character in header field name: "'+o+'"');return o.toLowerCase()}function c(o){return typeof o!="string"&&(o=String(o)),o}function y(o){var l={next:function(){var f=o.shift();return{done:f===void 0,value:f}}};return i.iterable&&(l[Symbol.iterator]=function(){return l}),l}function u(o){this.map={},o instanceof u?o.forEach(function(l,f){this.append(f,l)},this):Array.isArray(o)?o.forEach(function(l){if(l.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+l.length);this.append(l[0],l[1])},this):o&&Object.getOwnPropertyNames(o).forEach(function(l){this.append(l,o[l])},this)}u.prototype.append=function(o,l){o=p(o),l=c(l);var f=this.map[o];this.map[o]=f?f+", "+l:l},u.prototype.delete=function(o){delete this.map[p(o)]},u.prototype.get=function(o){return o=p(o),this.has(o)?this.map[o]:null},u.prototype.has=function(o){return this.map.hasOwnProperty(p(o))},u.prototype.set=function(o,l){this.map[p(o)]=c(l)},u.prototype.forEach=function(o,l){for(var f in this.map)this.map.hasOwnProperty(f)&&o.call(l,this.map[f],f,this)},u.prototype.keys=function(){var o=[];return this.forEach(function(l,f){o.push(f)}),y(o)},u.prototype.values=function(){var o=[];return this.forEach(function(l){o.push(l)}),y(o)},u.prototype.entries=function(){var o=[];return this.forEach(function(l,f){o.push([f,l])}),y(o)},i.iterable&&(u.prototype[Symbol.iterator]=u.prototype.entries);function R(o){if(!o._noBody){if(o.bodyUsed)return Promise.reject(new TypeError("Already read"));o.bodyUsed=!0}}function _(o){return new Promise(function(l,f){o.onload=function(){l(o.result)},o.onerror=function(){f(o.error)}})}function V(o){var l=new FileReader,f=_(l);return l.readAsArrayBuffer(o),f}function M(o){var l=new FileReader,f=_(l),g=/charset=([A-Za-z0-9_-]+)/.exec(o.type),T=g?g[1]:"utf-8";return l.readAsText(o,T),f}function ne(o){for(var l=new Uint8Array(o),f=new Array(l.length),g=0;g<l.length;g++)f[g]=String.fromCharCode(l[g]);return f.join("")}function A(o){if(o.slice)return o.slice(0);var l=new Uint8Array(o.byteLength);return l.set(new Uint8Array(o)),l.buffer}function k(){return this.bodyUsed=!1,this._initBody=function(o){this.bodyUsed=this.bodyUsed,this._bodyInit=o,o?typeof o=="string"?this._bodyText=o:i.blob&&Blob.prototype.isPrototypeOf(o)?this._bodyBlob=o:i.formData&&FormData.prototype.isPrototypeOf(o)?this._bodyFormData=o:i.searchParams&&URLSearchParams.prototype.isPrototypeOf(o)?this._bodyText=o.toString():i.arrayBuffer&&i.blob&&a(o)?(this._bodyArrayBuffer=A(o.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):i.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(o)||s(o))?this._bodyArrayBuffer=A(o):this._bodyText=o=Object.prototype.toString.call(o):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof o=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):i.searchParams&&URLSearchParams.prototype.isPrototypeOf(o)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},i.blob&&(this.blob=function(){var o=R(this);if(o)return o;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var o=R(this);return o||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(i.blob)return this.blob().then(V);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var o=R(this);if(o)return o;if(this._bodyBlob)return M(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(ne(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},i.formData&&(this.formData=function(){return this.text().then(st)}),this.json=function(){return this.text().then(JSON.parse)},this}var U=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function G(o){var l=o.toUpperCase();return U.indexOf(l)>-1?l:o}function C(o,l){if(!(this instanceof C))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');l=l||{};var f=l.body;if(o instanceof C){if(o.bodyUsed)throw new TypeError("Already read");this.url=o.url,this.credentials=o.credentials,l.headers||(this.headers=new u(o.headers)),this.method=o.method,this.mode=o.mode,this.signal=o.signal,!f&&o._bodyInit!=null&&(f=o._bodyInit,o.bodyUsed=!0)}else this.url=String(o);if(this.credentials=l.credentials||this.credentials||"same-origin",(l.headers||!this.headers)&&(this.headers=new u(l.headers)),this.method=G(l.method||this.method||"GET"),this.mode=l.mode||this.mode||null,this.signal=l.signal||this.signal||(function(){if("AbortController"in r){var m=new AbortController;return m.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&f)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(f),(this.method==="GET"||this.method==="HEAD")&&(l.cache==="no-store"||l.cache==="no-cache")){var g=/([?&])_=[^&]*/;if(g.test(this.url))this.url=this.url.replace(g,"$1_="+new Date().getTime());else{var T=/\?/;this.url+=(T.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}C.prototype.clone=function(){return new C(this,{body:this._bodyInit})};function st(o){var l=new FormData;return o.trim().split("&").forEach(function(f){if(f){var g=f.split("="),T=g.shift().replace(/\+/g," "),m=g.join("=").replace(/\+/g," ");l.append(decodeURIComponent(T),decodeURIComponent(m))}}),l}function lt(o){var l=new u,f=o.replace(/\r?\n[\t ]+/g," ");return f.split("\r").map(function(g){return g.indexOf(`
2
- `)===0?g.substr(1,g.length):g}).forEach(function(g){var T=g.split(":"),m=T.shift().trim();if(m){var L=T.join(":").trim();try{l.append(m,L)}catch(ie){console.warn("Response "+ie.message)}}}),l}k.call(C.prototype);function b(o,l){if(!(this instanceof b))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(l||(l={}),this.type="default",this.status=l.status===void 0?200:l.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=l.statusText===void 0?"":""+l.statusText,this.headers=new u(l.headers),this.url=l.url||"",this._initBody(o)}k.call(b.prototype),b.prototype.clone=function(){return new b(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new u(this.headers),url:this.url})},b.error=function(){var o=new b(null,{status:200,statusText:""});return o.ok=!1,o.status=0,o.type="error",o};var dt=[301,302,303,307,308];b.redirect=function(o,l){if(dt.indexOf(l)===-1)throw new RangeError("Invalid status code");return new b(null,{status:l,headers:{location:o}})},t.DOMException=r.DOMException;try{new t.DOMException}catch{t.DOMException=function(l,f){this.message=l,this.name=f;var g=Error(l);this.stack=g.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function re(o,l){return new Promise(function(f,g){var T=new C(o,l);if(T.signal&&T.signal.aborted)return g(new t.DOMException("Aborted","AbortError"));var m=new XMLHttpRequest;function L(){m.abort()}m.onload=function(){var P={statusText:m.statusText,headers:lt(m.getAllResponseHeaders()||"")};T.url.indexOf("file://")===0&&(m.status<200||m.status>599)?P.status=200:P.status=m.status,P.url="responseURL"in m?m.responseURL:P.headers.get("X-Request-URL");var x="response"in m?m.response:m.responseText;setTimeout(function(){f(new b(x,P))},0)},m.onerror=function(){setTimeout(function(){g(new TypeError("Network request failed"))},0)},m.ontimeout=function(){setTimeout(function(){g(new TypeError("Network request timed out"))},0)},m.onabort=function(){setTimeout(function(){g(new t.DOMException("Aborted","AbortError"))},0)};function ie(P){try{return P===""&&r.location.href?r.location.href:P}catch{return P}}if(m.open(T.method,ie(T.url),!0),T.credentials==="include"?m.withCredentials=!0:T.credentials==="omit"&&(m.withCredentials=!1),"responseType"in m&&(i.blob?m.responseType="blob":i.arrayBuffer&&(m.responseType="arraybuffer")),l&&typeof l.headers=="object"&&!(l.headers instanceof u||r.Headers&&l.headers instanceof r.Headers)){var Pe=[];Object.getOwnPropertyNames(l.headers).forEach(function(P){Pe.push(p(P)),m.setRequestHeader(P,c(l.headers[P]))}),T.headers.forEach(function(P,x){Pe.indexOf(x)===-1&&m.setRequestHeader(x,P)})}else T.headers.forEach(function(P,x){m.setRequestHeader(x,P)});T.signal&&(T.signal.addEventListener("abort",L),m.onreadystatechange=function(){m.readyState===4&&T.signal.removeEventListener("abort",L)}),m.send(typeof T._bodyInit>"u"?null:T._bodyInit)})}return re.polyfill=!0,r.fetch||(r.fetch=re,r.Headers=u,r.Request=C,r.Response=b),t.Headers=u,t.Request=C,t.Response=b,t.fetch=re,t})({})})(typeof self<"u"?self:_e)});var S=[];for(let n=0;n<256;++n)S.push((n+256).toString(16).slice(1));function Re(n,e=0){return(S[n[e+0]]+S[n[e+1]]+S[n[e+2]]+S[n[e+3]]+"-"+S[n[e+4]]+S[n[e+5]]+"-"+S[n[e+6]]+S[n[e+7]]+"-"+S[n[e+8]]+S[n[e+9]]+"-"+S[n[e+10]]+S[n[e+11]]+S[n[e+12]]+S[n[e+13]]+S[n[e+14]]+S[n[e+15]]).toLowerCase()}var ht=new Uint8Array(16);function oe(){return crypto.getRandomValues(ht)}function Pt(n,e,t){return!e&&!n&&crypto.randomUUID?crypto.randomUUID():St(n,e,t)}function St(n,e,t){n=n||{};let r=n.random??n.rng?.()??oe();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(t=t||0,t<0||t+16>e.length)throw new RangeError(`UUID byte range ${t}:${t+15} is out of buffer bounds`);for(let i=0;i<16;++i)e[t+i]=r[i];return e}return Re(r)}var B=Pt;var vS=Tt(Ce());function pe(n){return $t(n,!1)}function $t(n,e){return n}function w(n){return Ht(n,!1)}function Ht(n,e){return n}function Ne(n){return Qt(n,!1)}function Qt(n,e){return n==null?n:{key:n.key,value:n.value}}function N(n){return zt(n,!1)}function zt(n,e){return n}function Be(n){return Zt(n,!1)}function Zt(n,e){return n==null?n:{allocation:n.allocation==null?void 0:n.allocation,consumptionRate:n.consumption_rate==null?void 0:n.consumption_rate,creditId:n.credit_id==null?void 0:n.credit_id,creditRemaining:n.credit_remaining==null?void 0:n.credit_remaining,creditReserved:n.credit_reserved==null?void 0:n.credit_reserved,creditSettled:n.credit_settled==null?void 0:n.credit_settled,creditTotal:n.credit_total==null?void 0:n.credit_total,creditUsed:n.credit_used==null?void 0:n.credit_used,eventName:n.event_name==null?void 0:n.event_name,eventSubtype:n.event_subtype==null?void 0:n.event_subtype,featureId:n.feature_id,featureKey:n.feature_key,metricPeriod:n.metric_period==null?void 0:N(n.metric_period),metricResetAt:n.metric_reset_at==null?void 0:new Date(n.metric_reset_at),monthReset:n.month_reset==null?void 0:w(n.month_reset),softLimit:n.soft_limit==null?void 0:n.soft_limit,usage:n.usage==null?void 0:n.usage,valueType:pe(n.value_type),warningTiers:n.warning_tiers==null?void 0:n.warning_tiers.map(Ne)}}function H(n){return Xt(n,!1)}function Xt(n,e){return n}function E(n){return Yt(n,!1)}function Yt(n,e){return n==null?n:{companyId:n.company_id==null?void 0:n.company_id,entitlement:n.entitlement==null?void 0:Be(n.entitlement),error:n.error==null?void 0:n.error,featureAllocation:n.feature_allocation==null?void 0:n.feature_allocation,featureUsage:n.feature_usage==null?void 0:n.feature_usage,featureUsageEvent:n.feature_usage_event==null?void 0:n.feature_usage_event,featureUsagePeriod:n.feature_usage_period==null?void 0:N(n.feature_usage_period),featureUsageResetAt:n.feature_usage_reset_at==null?void 0:new Date(n.feature_usage_reset_at),flag:n.flag,flagId:n.flag_id==null?void 0:n.flag_id,reason:n.reason,ruleId:n.rule_id==null?void 0:n.rule_id,ruleType:n.rule_type==null?void 0:H(n.rule_type),userId:n.user_id==null?void 0:n.user_id,value:n.value}}function ue(n){return en(n,!1)}function en(n,e){return n==null?n:{data:E(n.data),params:n.params}}var tn="https://api.schematichq.com".replace(/\/+$/,""),fe=class{constructor(e={}){this.configuration=e}configuration;set config(e){this.configuration=e}get basePath(){return this.configuration.basePath!=null?this.configuration.basePath:tn}get fetchApi(){return this.configuration.fetchApi}get middleware(){return this.configuration.middleware||[]}get queryParamsStringify(){return this.configuration.queryParamsStringify||Ee}get username(){return this.configuration.username}get password(){return this.configuration.password}get apiKey(){let e=this.configuration.apiKey;if(e)return typeof e=="function"?e:()=>e}get accessToken(){let e=this.configuration.accessToken;if(e)return typeof e=="function"?e:async()=>e}get headers(){return this.configuration.headers}get credentials(){return this.configuration.credentials}},nn=new fe,Fe=class n{constructor(e=nn){this.configuration=e;this.middleware=e.middleware}configuration;static jsonRegex=new RegExp("^(:?application/json|[^;/ ]+/[^;/ ]+[+]json)[ ]*(:?;.*)?$","i");middleware;withMiddleware(...e){let t=this.clone();return t.middleware=t.middleware.concat(...e),t}withPreMiddleware(...e){let t=e.map(r=>({pre:r}));return this.withMiddleware(...t)}withPostMiddleware(...e){let t=e.map(r=>({post:r}));return this.withMiddleware(...t)}isJsonMime(e){return e?n.jsonRegex.test(e):!1}async request(e,t){let{url:r,init:i}=await this.createFetchParams(e,t),a=await this.fetchApi(r,i);if(a&&a.status>=200&&a.status<300)return a;throw new ye(a,"Response returned an error code")}async createFetchParams(e,t){let r=this.configuration.basePath+e.path;e.query!==void 0&&Object.keys(e.query).length!==0&&(r+="?"+this.configuration.queryParamsStringify(e.query));let i=Object.assign({},this.configuration.headers,e.headers);Object.keys(i).forEach(y=>i[y]===void 0?delete i[y]:{});let a=typeof t=="function"?t:async()=>t,d={method:e.method,headers:i,body:e.body,credentials:this.configuration.credentials},s={...d,...await a({init:d,context:e})},p;on(s.body)||s.body instanceof URLSearchParams||rn(s.body)?p=s.body:this.isJsonMime(i["Content-Type"])?p=JSON.stringify(s.body):p=s.body;let c={...s,body:p};return{url:r,init:c}}fetchApi=async(e,t)=>{let r={url:e,init:t};for(let a of this.middleware)a.pre&&(r=await a.pre({fetch:this.fetchApi,...r})||r);let i;try{i=await(this.configuration.fetchApi||fetch)(r.url,r.init)}catch(a){for(let d of this.middleware)d.onError&&(i=await d.onError({fetch:this.fetchApi,url:r.url,init:r.init,error:a,response:i?i.clone():void 0})||i);if(i===void 0)throw a instanceof Error?new me(a,"The request failed and the interceptors did not return an alternative response"):a}for(let a of this.middleware)a.post&&(i=await a.post({fetch:this.fetchApi,url:r.url,init:r.init,response:i.clone()})||i);return i};clone(){let e=this.constructor,t=new e(this.configuration);return t.middleware=this.middleware.slice(),t}};function rn(n){return typeof Blob<"u"&&n instanceof Blob}function on(n){return typeof FormData<"u"&&n instanceof FormData}var ye=class extends Error{constructor(t,r){super(r);this.response=t}response;name="ResponseError"},me=class extends Error{constructor(t,r){super(r);this.cause=t}cause;name="FetchError"};function Ee(n,e=""){return Object.keys(n).map(t=>Ie(t,n[t],e)).filter(t=>t.length>0).join("&")}function Ie(n,e,t=""){let r=t+(t.length?`[${n}]`:n);if(e instanceof Array){let i=e.map(a=>encodeURIComponent(String(a))).join(`&${encodeURIComponent(r)}=`);return`${encodeURIComponent(r)}=${i}`}if(e instanceof Set){let i=Array.from(e);return Ie(n,i,t)}return e instanceof Date?`${encodeURIComponent(r)}=${encodeURIComponent(e.toISOString())}`:e instanceof Object?Ee(e,r):`${encodeURIComponent(r)}=${encodeURIComponent(String(e))}`}function Ae(n,e){return Object.keys(n).reduce((t,r)=>({...t,[r]:e(n[r])}),{})}function Q(n){return an(n,!1)}function an(n,e){return n==null?n:{remaining:n.remaining,reserved:n.reserved,settled:n.settled}}function ke(n){return sn(n,!1)}function sn(n,e){return n}function v(n){return ln(n,!1)}function ln(n,e){return n==null?n:{id:n.id,name:n.name,trialEndDate:n.trial_end_date==null?void 0:new Date(n.trial_end_date),trialStatus:n.trial_status==null?void 0:ke(n.trial_status)}}function we(n){return dn(n,!1)}function dn(n,e){return n==null?n:{creditBalances:n.credit_balances==null?void 0:Ae(n.credit_balances,Q),flags:n.flags.map(E),plan:n.plan==null?void 0:v(n.plan)}}function ge(n){return pn(n,!1)}function pn(n,e){return n==null?n:{data:we(n.data),params:n.params}}function z(n){return cn(n,!1)}function cn(n,e=!1){return n==null?n:{company_id:n.companyId,error:n.error,flag_id:n.flagId,flag_key:n.flagKey,preflight:n.preflight,reason:n.reason,req_company:n.reqCompany,req_user:n.reqUser,rule_id:n.ruleId,user_id:n.userId,value:n.value}}var Te=n=>{let{companyId:e,entitlement:t,error:r,featureAllocation:i,featureUsage:a,featureUsageEvent:d,featureUsagePeriod:s,featureUsageResetAt:p,flag:c,flagId:y,reason:u,ruleId:R,ruleType:_,userId:V,value:M}=E(n),ne=!M&&(_=="company_override_usage_exceeded"||_=="plan_entitlement_usage_exceeded"),A=t?.allocation??i,k=t?.usage??a,U=t?.eventName??d,G=t?.metricPeriod??s,C=t?.metricResetAt??p;return{featureUsageExceeded:ne,companyId:e??void 0,creditId:t?.creditId==null?void 0:t.creditId,creditRemaining:t?.creditRemaining==null?void 0:t.creditRemaining,creditReserved:t?.creditReserved==null?void 0:t.creditReserved,creditSettled:t?.creditSettled==null?void 0:t.creditSettled,error:r??void 0,featureAllocation:A??void 0,featureUsage:k??void 0,featureUsageEvent:U??void 0,featureUsagePeriod:G??void 0,featureUsageResetAt:C??void 0,flag:c,flagId:y??void 0,reason:u,ruleId:R??void 0,ruleType:_??void 0,softLimit:t?.softLimit==null?void 0:t.softLimit,userId:V??void 0,value:M}},rt=n=>{let{id:e,name:t,trialEndDate:r,trialStatus:i}=v(n);return{id:e,name:t,trialEndDate:r??void 0,trialStatus:i??void 0}},it=n=>{if(n==null||typeof n!="object")return{};let e={};for(let[t,r]of Object.entries(n)){if(r==null||typeof r!="object")continue;let{remaining:i,reserved:a,settled:d}=Q(r);typeof i!="number"||typeof a!="number"||typeof d!="number"||(e[t]={remaining:i,reserved:a,settled:d})}return e};var I="bb56e75d";function h(n){let e=Object.keys(n).reduce((t,r)=>{let a=Object.keys(n[r]||{}).sort().reduce((d,s)=>(d[s]=n[r][s],d),{});return t[r]=a,t},{});return JSON.stringify(e)}var he="1.6.0";var ot="schematicId",wn="schematicCache",at=10,vn=10080*60*1e3,Vn=Object.freeze({});var te=class{additionalHeaders={};apiKey;apiUrl="https://api.schematichq.com";conn=null;context={};debugEnabled=!1;offlineEnabled=!1;eventQueue;contextDependentEventQueue;eventUrl="https://c.schematichq.com";flagCheckListeners={};flagValueListeners={};isPending=!0;isPendingListeners=new Set;planListeners=new Set;creditBalanceListeners=new Set;storage;persistFlagState=!0;flagStateCacheKey;flagStateCacheMaxAgeMs=vn;cachedFlagState=null;useWebSocket=!1;checks={};featureUsageEventMap={};planChecks={};creditBalances={};webSocketUrl="wss://api.schematichq.com";webSocketConnectionTimeout=1e4;webSocketReconnect=!0;webSocketMaxReconnectAttempts=7;webSocketMaxConnectionAttempts=3;webSocketInitialRetryDelay=1e3;webSocketMaxRetryDelay=3e4;wsReconnectAttempts=0;wsReconnectTimer=null;wsIntentionalDisconnect=!1;currentWebSocket=null;isConnecting=!1;maxEventQueueSize=100;maxEventRetries=5;eventRetryInitialDelay=1e3;eventRetryMaxDelay=3e4;retryTimer=null;flagValueDefaults={};flagCheckDefaults={};fallbackCheckCache={};constructor(e,t){if(this.apiKey=e,this.flagStateCacheKey=`${wn}:${e}`,this.eventQueue=[],this.contextDependentEventQueue=[],this.useWebSocket=t?.useWebSocket??!1,this.debugEnabled=t?.debug??!1,this.offlineEnabled=t?.offline??!1,this.persistFlagState=t?.persistFlagState??!0,typeof t?.flagStateCacheMaxAgeMs=="number"&&t.flagStateCacheMaxAgeMs>0&&(this.flagStateCacheMaxAgeMs=t.flagStateCacheMaxAgeMs),typeof window<"u"&&typeof window.location<"u"){let r=new URLSearchParams(window.location.search),i=r.get("schematic_debug");i!==null&&(i===""||i==="true"||i==="1")&&(this.debugEnabled=!0);let a=r.get("schematic_offline");a!==null&&(a===""||a==="true"||a==="1")&&(this.offlineEnabled=!0,this.debugEnabled=!0)}if(this.offlineEnabled&&t?.debug!==!1&&(this.debugEnabled=!0),this.offlineEnabled&&this.setIsPending(!1),this.additionalHeaders={"X-Schematic-Client-Version":`schematic-js@${he}`,...t?.additionalHeaders??{}},t?.storage)this.storage=t.storage;else try{typeof localStorage<"u"&&(this.storage=localStorage)}catch{}this.hydrateFlagStateFromCache(),t?.apiUrl!==void 0&&(this.apiUrl=t.apiUrl),t?.eventUrl!==void 0&&(this.eventUrl=t.eventUrl),t?.webSocketUrl!==void 0&&(this.webSocketUrl=t.webSocketUrl),t?.webSocketConnectionTimeout!==void 0&&(this.webSocketConnectionTimeout=t.webSocketConnectionTimeout),t?.webSocketReconnect!==void 0&&(this.webSocketReconnect=t.webSocketReconnect),t?.webSocketMaxReconnectAttempts!==void 0&&(this.webSocketMaxReconnectAttempts=t.webSocketMaxReconnectAttempts),t?.webSocketInitialRetryDelay!==void 0&&(this.webSocketInitialRetryDelay=t.webSocketInitialRetryDelay),t?.webSocketMaxRetryDelay!==void 0&&(this.webSocketMaxRetryDelay=t.webSocketMaxRetryDelay),t?.maxEventQueueSize!==void 0&&(this.maxEventQueueSize=t.maxEventQueueSize),t?.maxEventRetries!==void 0&&(this.maxEventRetries=t.maxEventRetries),t?.eventRetryInitialDelay!==void 0&&(this.eventRetryInitialDelay=t.eventRetryInitialDelay),t?.eventRetryMaxDelay!==void 0&&(this.eventRetryMaxDelay=t.eventRetryMaxDelay),t?.flagValueDefaults!==void 0&&(this.flagValueDefaults=t.flagValueDefaults),t?.flagCheckDefaults!==void 0&&(this.flagCheckDefaults=t.flagCheckDefaults),typeof window<"u"&&window?.addEventListener&&(window.addEventListener("beforeunload",()=>{this.flushEventQueue(),this.flushContextDependentEventQueue()}),this.useWebSocket&&(window.addEventListener("offline",()=>{this.debug("Browser went offline, closing WebSocket connection"),this.handleNetworkOffline()}),window.addEventListener("online",()=>{this.debug("Browser came online, attempting to reconnect WebSocket"),this.handleNetworkOnline()}))),this.offlineEnabled?this.debug("Initialized with offline mode enabled - no network requests will be made"):this.debugEnabled&&this.debug("Initialized with debug mode enabled")}resolveFallbackValue(e,t){return t!==void 0?t:e in this.flagCheckDefaults?this.flagCheckDefaults[e].value:e in this.flagValueDefaults?this.flagValueDefaults[e]:!1}resolveFallbackCheckFlagReturn(e,t,r="Fallback value used",i){if(t!==void 0)return{flag:e,value:t,reason:r,error:i};if(e in this.flagCheckDefaults){let a=this.flagCheckDefaults[e];return{...a,flag:e,reason:i!==void 0?r:a.reason,error:i}}return e in this.flagValueDefaults?{flag:e,value:this.flagValueDefaults[e],reason:r,error:i}:{flag:e,value:!1,reason:r,error:i}}async checkFlag(e){let{fallback:t,key:r}=e,i=e.context||this.context,a=h(i);if(this.debug(`checkFlag: ${r}`,{context:i,fallback:t}),this.isOffline()){let d=this.resolveFallbackCheckFlagReturn(r,t,"Offline mode - using initialization defaults");return this.debug(`checkFlag offline result: ${r}`,{value:d.value,offlineMode:!0}),d.value}if(!this.useWebSocket){let d=`${this.apiUrl}/flags/${r}/check`;return fetch(d,{method:"POST",headers:{...this.additionalHeaders??{},"Content-Type":"application/json;charset=UTF-8","X-Schematic-Api-Key":this.apiKey},body:JSON.stringify(i)}).then(s=>{if(!s.ok)throw new Error("Network response was not ok");return s.json()}).then(s=>{let p=ue(s);this.debug(`checkFlag result: ${r}`,p);let c=Te(p.data);return typeof c.featureUsageEvent=="string"&&this.updateFeatureUsageEventMap(c),this.submitFlagCheckEvent(r,c,i),c.value}).catch(s=>{console.warn("There was a problem with the fetch operation:",s);let p=this.resolveFallbackCheckFlagReturn(r,t,"API request failed",s instanceof Error?s.message:String(s));return this.submitFlagCheckEvent(r,p,i),p.value})}try{let d=this.checks[a];if(this.conn!==null&&typeof d<"u"&&typeof d[r]<"u")return this.debug(`checkFlag cached result: ${r}`,d[r]),d[r].value;if(this.isOffline())return this.resolveFallbackValue(r,t);try{await this.setContext(i)}catch(y){console.warn("WebSocket connection failed, using fallback value:",y);let u=this.resolveFallbackCheckFlagReturn(r,t,"WebSocket connection failed",y instanceof Error?y.message:String(y));return this.submitFlagCheckEvent(r,u,i),u.value}let p=(this.checks[a]??{})[r],c=p?.value??this.resolveFallbackValue(r,t);if(this.debug(`checkFlag WebSocket result: ${r}`,typeof p<"u"?p:{value:c,fallbackUsed:!0}),typeof p<"u")this.submitFlagCheckEvent(r,p,i);else{let y=this.resolveFallbackCheckFlagReturn(r,t,"No flag values available");this.submitFlagCheckEvent(r,y,i)}return c}catch(d){console.error("Unexpected error in checkFlag:",d);let s=this.resolveFallbackCheckFlagReturn(r,t,"Unexpected error in flag check",d instanceof Error?d.message:String(d));return this.submitFlagCheckEvent(r,s,i),s.value}}debug(e,...t){this.debugEnabled&&console.log(`[Schematic] ${e}`,...t)}createPersistentMessageHandler(e){return t=>{let r=JSON.parse(t.data);if(this.debug("WebSocket persistent message received:",r),h(e)in this.checks||(this.checks[h(e)]={}),(r.flags??[]).forEach(i=>{let a=Te(i),d=h(e);this.checks[d]===void 0&&(this.checks[d]={}),this.checks[d][a.flag]=a,typeof a.featureUsageEvent=="string"&&this.updateFeatureUsageEventMap(a),((this.flagCheckListeners[i.flag]?.size??0)>0||(this.flagValueListeners[i.flag]?.size??0)>0)&&this.submitFlagCheckEvent(a.flag,a,e),this.debug(`WebSocket flag update received. Notifying listeners for ${i.flag}`,{flag:i.flag,value:a.value,flagCheck:a}),this.notifyFlagCheckListeners(i.flag,a),this.notifyFlagValueListeners(i.flag,a.value)}),r.plan!==void 0&&r.plan!==null){let i=rt(r.plan),a=h(e);this.planChecks[a]=i,this.debug("WebSocket plan update received. Notifying listeners",{plan:i}),this.notifyPlanListeners(i)}if(r.credit_balances!==void 0&&r.credit_balances!==null){let i=h(e),a=it(r.credit_balances),d=this.creditBalances[i]??{},s=!1,p={...d};for(let[c,y]of Object.entries(a)){let u=d[c];(u===void 0||u.remaining!==y.remaining||u.reserved!==y.reserved||u.settled!==y.settled)&&(p[c]=y,s=!0)}s&&(this.creditBalances[i]=p,this.debug("WebSocket credit balance update received. Notifying listeners",{creditBalances:p}),this.notifyCreditBalanceListeners(p))}this.persistContextToCache(h(e)),this.flushContextDependentEventQueue(),this.setIsPending(!1)}}isOffline(){return this.offlineEnabled}submitFlagCheckEvent(e,t,r){let i={flagKey:e,value:t.value,reason:t.reason,flagId:t.flagId,ruleId:t.ruleId,companyId:t.companyId,userId:t.userId,error:t.error,reqCompany:r.company,reqUser:r.user};return this.debug("submitting flag check event:",i),this.handleEvent("flag_check",z(i))}checkFlags=async e=>{if(e=e||this.context,this.debug("checkFlags",{context:e}),this.isOffline())return this.debug("checkFlags offline result: returning empty object"),{};let t=`${this.apiUrl}/flags/check`,r=JSON.stringify(e);return fetch(t,{method:"POST",headers:{...this.additionalHeaders??{},"Content-Type":"application/json;charset=UTF-8","X-Schematic-Api-Key":this.apiKey},body:r}).then(i=>{if(!i.ok)throw new Error("Network response was not ok");return i.json()}).then(i=>{let a=ge(i);return this.debug("checkFlags result:",a),(a?.data?.flags??[]).reduce((d,s)=>(d[s.flag]=s.value,d),{})}).catch(i=>(console.warn("There was a problem with the fetch operation:",i),{}))};identify=e=>(this.debug("identify:",e),this.setContext({company:e.company?.keys,user:e.keys}).catch(t=>{console.warn("Error setting context:",t)}),this.handleEvent("identify",e));setContext=async e=>{if(this.isOffline()||!this.useWebSocket)return this.context=e,this.flushContextDependentEventQueue(),this.setIsPending(!1),Promise.resolve();if(!(h(e)===h(this.context)&&this.conn!==null&&!this.isPending))try{let t=h(e),r=this.hasCachedValuesForContext(t);if(r){this.debug("setContext: cache hit for context, pre-resolving from cached values"),this.context=e,this.flushContextDependentEventQueue(),this.setIsPending(!1);let a=this.checks[t]??{};for(let[p,c]of Object.entries(a))c!==void 0&&(this.notifyFlagCheckListeners(p,c),this.notifyFlagValueListeners(p,c.value));let d=this.planChecks[t];d!==void 0&&this.notifyPlanListeners(d);let s=this.creditBalances[t];s!==void 0&&this.notifyCreditBalanceListeners(s)}else this.setIsPending(!0);if(!this.conn){if(this.isConnecting){for(this.debug("Connection already in progress, waiting for it to complete");this.isConnecting&&this.conn===null;)await new Promise(a=>setTimeout(a,10));if(this.conn!==null){let a=await this.conn;await this.wsSendMessage(a,e,r);return}}this.wsReconnectTimer!==null&&(this.debug("Cancelling scheduled reconnection, connecting immediately"),clearTimeout(this.wsReconnectTimer),this.wsReconnectTimer=null),this.isConnecting=!0;try{this.conn=this.wsConnect();let a=await this.conn;this.isConnecting=!1,await this.wsSendMessage(a,e,r);return}catch(a){throw this.isConnecting=!1,a}}let i=await this.conn;await this.wsSendMessage(i,e,r)}catch(t){console.warn("Failed to establish WebSocket connection:",t),this.context=e,this.flushContextDependentEventQueue(),this.setIsPending(!1),this.attemptReconnect()}};track=e=>{let{company:t,user:r,event:i,traits:a,quantity:d=1}=e;if(!this.hasContext(t,r)){this.debug(`track: queuing event "${i}" until context is available`);let p={api_key:this.apiKey,body:{company:t,event:i,traits:a??{},user:r,quantity:d},sent_at:new Date().toISOString(),tracker_event_id:B(),tracker_user_id:this.getAnonymousId(),type:"track"};return this.contextDependentEventQueue.push(p),Promise.resolve()}let s={company:t??this.context.company,event:i,traits:a??{},user:r??this.context.user,quantity:d};return this.debug("track:",s),i in this.featureUsageEventMap&&this.optimisticallyUpdateFeatureUsage(i,d),this.handleEvent("track",s)};optimisticallyUpdateFeatureUsage=(e,t=1)=>{let r=this.featureUsageEventMap[e];if(r==null)return;this.debug(`Optimistically updating feature usage for event: ${e}`,{quantity:t});let i=!1;Object.entries(r).forEach(([a,d])=>{if(d===void 0)return;let s={...d};if(typeof s.featureUsage=="number"){if(i=!0,s.featureUsage+=t,typeof s.featureAllocation=="number"){let c=s.featureUsageExceeded===!0,y=s.featureUsage>=s.featureAllocation;y!==c&&(s.featureUsageExceeded=y,y&&(s.value=!1),this.debug(`Usage limit status changed for flag: ${a}`,{was:c?"exceeded":"within limits",now:y?"exceeded":"within limits",featureUsage:s.featureUsage,featureAllocation:s.featureAllocation,value:s.value}))}this.featureUsageEventMap[e]!==void 0&&(this.featureUsageEventMap[e][a]=s);let p=h(this.context);this.checks[p]!==void 0&&this.checks[p]!==null&&(this.checks[p][a]=s),this.notifyFlagCheckListeners(a,s),this.notifyFlagValueListeners(a,s.value)}}),i&&this.persistContextToCache(h(this.context))};hasContext=(e,t)=>{let r=e!=null&&Object.keys(e).length>0||t!=null&&Object.keys(t).length>0,i=this.context.company!==void 0&&this.context.company!==null&&Object.keys(this.context.company).length>0||this.context.user!==void 0&&this.context.user!==null&&Object.keys(this.context.user).length>0;return r||i};flushContextDependentEventQueue=()=>{for(this.debug(`flushing ${this.contextDependentEventQueue.length} context-dependent events`);this.contextDependentEventQueue.length>0;){let e=this.contextDependentEventQueue.shift();if(e)if(e.type==="track"&&typeof e.body=="object"&&e.body!==null){let t=e.body,r={...t,company:t.company??this.context.company,user:t.user??this.context.user},i={...e,body:r,sent_at:new Date().toISOString()};this.sendEvent(i)}else this.sendEvent(e)}};startRetryTimer=()=>{this.retryTimer===null&&(this.retryTimer=setInterval(()=>{this.flushEventQueue().catch(e=>{this.debug("Error in retry timer flush:",e)}),this.eventQueue.length===0&&this.stopRetryTimer()},5e3),this.debug("Started retry timer"))};stopRetryTimer=()=>{this.retryTimer!==null&&(clearInterval(this.retryTimer),this.retryTimer=null,this.debug("Stopped retry timer"))};flushEventQueue=async()=>{if(this.eventQueue.length===0)return;let e=Date.now(),t=[],r=[];for(let i of this.eventQueue)i.next_retry_at===void 0||i.next_retry_at<=e?t.push(i):r.push(i);if(t.length===0){this.debug(`No events ready for retry yet (${r.length} still in backoff)`);return}this.debug(`Flushing event queue: ${t.length} ready, ${r.length} waiting`),this.eventQueue=r;for(let i of t)try{await this.sendEvent(i),this.debug("Queued event sent successfully:",i.type)}catch(a){this.debug("Failed to send queued event:",a)}};getAnonymousId=()=>{if(!this.storage)return B();let e=this.storage.getItem(ot);if(typeof e<"u")return e;let t=B();return this.storage.setItem(ot,t),t};hasCachedValuesForContext=e=>{let t=this.checks[e];if(t!==void 0&&Object.keys(t).length>0||this.planChecks[e]!==void 0)return!0;let r=this.creditBalances[e];return r!==void 0&&Object.keys(r).length>0};readFlagStateCache=()=>{if(!this.persistFlagState||this.storage===void 0)return null;let e;try{e=this.storage.getItem(this.flagStateCacheKey)}catch(r){return this.debug("Failed to read flag state cache:",r),null}if(e==null)return null;let t;try{t=typeof e=="string"?JSON.parse(e):e}catch(r){return this.debug("Flag state cache is not valid JSON, ignoring:",r),null}return t===null||typeof t!="object"||t.version!==I||typeof t.contexts!="object"||t.contexts===null?(this.debug(`Flag state cache invalid or version mismatch (expected ${I}), ignoring`,{parsedType:typeof t,version:t?.version}),null):t};reviveCachedCheck=e=>{if(e===null||typeof e!="object")return null;let t=e;if(typeof t.flag!="string"||typeof t.value!="boolean"||typeof t.reason!="string")return null;let r={...t};if(typeof r.featureUsageResetAt=="string"){let i=new Date(r.featureUsageResetAt);r.featureUsageResetAt=isNaN(i.getTime())?void 0:i}return r};reviveCachedPlan=e=>{if(e===null||typeof e!="object")return null;let t=e;if(typeof t.id!="string"||typeof t.name!="string")return null;let r={...t};if(typeof r.trialEndDate=="string"){let i=new Date(r.trialEndDate);r.trialEndDate=isNaN(i.getTime())?void 0:i}return r};reviveCachedCreditBalances=e=>{if(e===null||typeof e!="object")return null;let t={};for(let[r,i]of Object.entries(e)){if(i===null||typeof i!="object")continue;let a=i;typeof a.remaining!="number"||typeof a.reserved!="number"||typeof a.settled!="number"||(t[r]={remaining:a.remaining,reserved:a.reserved,settled:a.settled})}return Object.keys(t).length>0?t:null};hydrateFlagStateFromCache=()=>{let e=this.readFlagStateCache();if(e===null)return;let t=Date.now()-this.flagStateCacheMaxAgeMs,r={},i=0,a=0;for(let[d,s]of Object.entries(e.contexts)){if(s===null||typeof s!="object"||typeof s.updatedAt!="number")continue;if(s.updatedAt<t){a+=1;continue}let p={};if(s.checks!==null&&typeof s.checks=="object"){for(let[u,R]of Object.entries(s.checks)){let _=this.reviveCachedCheck(R);_===null||_.flag!==u||(p[u]=_,typeof _.featureUsageEvent=="string"&&this.updateFeatureUsageEventMap(_))}Object.keys(p).length>0&&(this.checks[d]=p)}let c;if(s.plan!==void 0&&s.plan!==null){let u=this.reviveCachedPlan(s.plan);u!==null&&(c=u,this.planChecks[d]=u)}let y;if(s.creditBalances!==void 0&&s.creditBalances!==null){let u=this.reviveCachedCreditBalances(s.creditBalances);u!==null&&(y=u,this.creditBalances[d]=u)}r[d]={checks:p,plan:c,creditBalances:y,updatedAt:s.updatedAt},i+=1}this.cachedFlagState={version:I,contexts:r},this.debug(`Hydrated flag state cache: ${i} loaded, ${a} expired`)};persistContextToCache=e=>{let t=this.checks[e],r=this.planChecks[e],i=this.creditBalances[e];if(t===void 0&&r===void 0&&i===void 0)return;this.cachedFlagState===null&&(this.cachedFlagState=(this.persistFlagState?this.readFlagStateCache():null)??{version:I,contexts:{}});let a={};if(t!==void 0)for(let[s,p]of Object.entries(t))p!==void 0&&(a[s]=p);this.cachedFlagState.contexts[e]={checks:a,plan:r,creditBalances:i,updatedAt:Date.now()};let d=Object.entries(this.cachedFlagState.contexts);if(d.length>at){d.sort((c,y)=>y[1].updatedAt-c[1].updatedAt);let s=d.slice(0,at),p=new Set(s.map(([c])=>c));for(let c of Object.keys(this.checks))p.has(c)||delete this.checks[c];for(let c of Object.keys(this.planChecks))p.has(c)||delete this.planChecks[c];for(let c of Object.keys(this.creditBalances))p.has(c)||delete this.creditBalances[c];this.cachedFlagState={version:I,contexts:Object.fromEntries(s)}}if(!(!this.persistFlagState||this.storage===void 0))try{this.storage.setItem(this.flagStateCacheKey,JSON.stringify(this.cachedFlagState))}catch(s){this.debug("Failed to write flag state cache:",s)}};handleEvent=(e,t)=>{let r={api_key:this.apiKey,body:t,sent_at:new Date().toISOString(),tracker_event_id:B(),tracker_user_id:this.getAnonymousId(),type:e};return typeof document<"u"&&document?.hidden?this.storeEvent(r):this.sendEvent(r)};sendEvent=async e=>{let t=`${this.eventUrl}/e`,r=JSON.stringify(e);if(this.debug("sending event:",{url:t,event:e}),this.isOffline())return this.debug("event not sent (offline mode):",{event:e}),Promise.resolve();try{let i=await fetch(t,{method:"POST",headers:{...this.additionalHeaders??{},"Content-Type":"application/json;charset=UTF-8"},body:r});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);this.debug("event sent:",{status:i.status,statusText:i.statusText})}catch(i){let a=(e.retry_count??0)+1;if(a<=this.maxEventRetries){this.debug(`Event failed to send (attempt ${a}/${this.maxEventRetries}), queueing for retry:`,i);let d=this.eventRetryInitialDelay*Math.pow(2,a-1),s=Math.min(d,this.eventRetryMaxDelay),p=Date.now()+s,c={...e,retry_count:a,next_retry_at:p};this.eventQueue.length<this.maxEventQueueSize?(this.eventQueue.push(c),this.debug(`Event queued for retry in ${s}ms (${this.eventQueue.length}/${this.maxEventQueueSize})`)):(this.debug(`Event queue full (${this.maxEventQueueSize}), dropping oldest event`),this.eventQueue.shift(),this.eventQueue.push(c)),this.startRetryTimer()}else this.debug(`Event failed permanently after ${this.maxEventRetries} attempts, dropping:`,i)}return Promise.resolve()};storeEvent=e=>(this.eventQueue.push(e),Promise.resolve());forceReconnect=async()=>this.reconnect({force:!0});reconnectIfNeeded=async()=>this.reconnect({force:!1});reconnect=async e=>{let{force:t}=e,r=t?"forceReconnect":"reconnectIfNeeded";if(this.isOffline())return this.debug(`${r}: skipped (offline mode)`),Promise.resolve();if(!t&&this.conn!==null)try{if((await this.conn).readyState===WebSocket.OPEN)return this.debug(`${r}: connection is healthy, skipping`),Promise.resolve()}catch{}if(this.debug(`${r}: ${t?"forcing immediate reconnection":"reconnecting"}`),this.wsIntentionalDisconnect=!1,this.wsReconnectTimer!==null&&(this.debug(`${r}: cancelling pending reconnection timer`),clearTimeout(this.wsReconnectTimer),this.wsReconnectTimer=null),this.wsReconnectAttempts=0,this.conn!==null){this.debug(`${r}: closing existing connection`);try{let i=await this.conn;this.currentWebSocket===i&&(this.currentWebSocket=null),(i.readyState===WebSocket.OPEN||i.readyState===WebSocket.CONNECTING)&&i.close()}catch(i){this.debug(`${r}: error closing existing connection:`,i)}this.conn=null,this.isConnecting=!1}if(this.context.company!==void 0||this.context.user!==void 0){this.debug(`${r}: reconnecting with existing context`);try{this.isConnecting=!0,this.conn=this.wsConnect();let i=await this.conn;this.isConnecting=!1,await this.wsSendMessage(i,this.context,!0),this.debug(`${r}: reconnection successful`)}catch(i){this.isConnecting=!1,this.debug(`${r}: reconnection failed:`,i)}}else this.debug(`${r}: no context set, skipping reconnection`);return Promise.resolve()};cleanup=async()=>{if(this.isOffline())return this.debug("cleanup: skipped (offline mode)"),Promise.resolve();if(this.wsIntentionalDisconnect=!0,this.wsReconnectTimer!==null&&(clearTimeout(this.wsReconnectTimer),this.wsReconnectTimer=null),this.stopRetryTimer(),this.conn)try{let e=await this.conn;this.currentWebSocket===e&&(this.debug("Cleaning up current websocket tracking"),this.currentWebSocket=null),e.close()}catch(e){console.warn("Error during cleanup:",e)}finally{this.conn=null,this.currentWebSocket=null,this.isConnecting=!1}};calculateReconnectDelay=()=>{let e=this.webSocketInitialRetryDelay*Math.pow(2,this.wsReconnectAttempts),t=Math.min(e,this.webSocketMaxRetryDelay),r=Math.random()*t*.5,i=t+r;return this.debug(`Reconnect delay calculated: ${i.toFixed(0)}ms (attempt ${this.wsReconnectAttempts+1}/${this.webSocketMaxReconnectAttempts})`),i};handleNetworkOffline=async()=>{if(this.conn!==null){try{let e=await this.conn;this.currentWebSocket===e&&(this.currentWebSocket=null),(e.readyState===WebSocket.OPEN||e.readyState===WebSocket.CONNECTING)&&e.close()}catch(e){this.debug("Error closing connection on offline:",e)}this.conn=null}this.wsReconnectTimer!==null&&(clearTimeout(this.wsReconnectTimer),this.wsReconnectTimer=null)};handleNetworkOnline=()=>{this.debug("Network online, attempting reconnection and flushing queued events"),this.wsReconnectAttempts=0,this.wsReconnectTimer!==null&&(clearTimeout(this.wsReconnectTimer),this.wsReconnectTimer=null),this.flushEventQueue().catch(e=>{this.debug("Error flushing event queue on network online:",e)}),this.attemptReconnect()};attemptReconnect=()=>{if(this.wsReconnectAttempts>=this.webSocketMaxReconnectAttempts){this.debug(`Maximum reconnection attempts (${this.webSocketMaxReconnectAttempts}) reached, giving up`);return}if(this.wsReconnectTimer!==null){this.debug("Reconnection attempt already scheduled, ignoring duplicate request");return}let e=this.calculateReconnectDelay();this.debug(`Scheduling reconnection attempt ${this.wsReconnectAttempts+1}/${this.webSocketMaxReconnectAttempts} in ${e.toFixed(0)}ms`),this.wsReconnectTimer=setTimeout(async()=>{this.wsReconnectTimer=null,this.wsReconnectAttempts++,this.debug(`Attempting to reconnect (attempt ${this.wsReconnectAttempts}/${this.webSocketMaxReconnectAttempts})`);try{if(this.conn!==null){this.debug("Cleaning up existing connection before reconnection");try{let t=await this.conn;this.currentWebSocket===t&&(this.debug("Existing websocket is current, will be replaced"),this.currentWebSocket=null),(t.readyState===WebSocket.OPEN||t.readyState===WebSocket.CONNECTING)&&t.close()}catch(t){this.debug("Error cleaning up existing connection:",t)}this.conn=null,this.currentWebSocket=null,this.isConnecting=!1}this.isConnecting=!0;try{this.conn=this.wsConnect();let t=await this.conn;this.isConnecting=!1,this.debug("Reconnection context check:",{hasCompany:this.context.company!==void 0,hasUser:this.context.user!==void 0,context:this.context}),this.context.company!==void 0||this.context.user!==void 0?(this.debug("Reconnected, force re-sending context"),await this.wsSendMessage(t,this.context,!0)):(this.debug("No context to re-send after reconnection - websocket ready for new context"),this.debug("Setting up tracking for reconnected websocket (no context to send)"),this.currentWebSocket=t),this.flushEventQueue().catch(r=>{this.debug("Error flushing event queue after websocket reconnection:",r)}),this.debug("Reconnection successful")}catch(t){throw this.isConnecting=!1,t}}catch(t){this.debug("Reconnection attempt failed:",t)}},e)};wsConnect=async()=>{if(this.isOffline())throw this.debug("wsConnect: skipped (offline mode)"),new Error("WebSocket connection skipped in offline mode");let e=null,t=this.webSocketMaxConnectionAttempts;for(let r=0;r<t;r++)try{let i=await this.wsConnectOnce();return this.wsReconnectAttempts=0,i}catch(i){if(e=i instanceof Error?i:new Error(String(i)),!(e.message==="WebSocket connection timeout"))throw this.debug("WebSocket connection failed with non-timeout error, not retrying:",e.message),e;if(r<t-1){let d=this.webSocketInitialRetryDelay*Math.pow(2,r),s=Math.min(d,this.webSocketMaxRetryDelay),p=s*.2*Math.random(),c=s+p;this.debug(`WebSocket connection timeout (attempt ${r+1}/${t}), retrying in ${c.toFixed(0)}ms`),await new Promise(y=>setTimeout(y,c))}else this.debug(`WebSocket connection timeout (attempt ${r+1}/${t}), no more retries`)}throw e??new Error("WebSocket connection failed")};wsConnectOnce=()=>new Promise((e,t)=>{let r=`${this.webSocketUrl}/flags/bootstrap?apiKey=${this.apiKey}`;this.debug("connecting to WebSocket:",r);let i=new WebSocket(r),a=Math.random().toString(36).substring(7);this.debug(`Creating WebSocket connection ${a} to ${r}`);let d=null,s=!1,p=!1;d=setTimeout(()=>{s||(s=!0,this.debug(`WebSocket connection timeout after ${this.webSocketConnectionTimeout}ms`),i.close(),t(new Error("WebSocket connection timeout")))},this.webSocketConnectionTimeout),i.onopen=()=>{s||(s=!0,p=!0,d!==null&&clearTimeout(d),this.wsIntentionalDisconnect=!1,this.debug(`WebSocket connection ${a} opened successfully`),e(i))},i.onerror=c=>{if(s)return;s=!0,d!==null&&clearTimeout(d),this.debug(`WebSocket connection ${a} error:`,c);let y=new Error("WebSocket connection failed during handshake");t(y)},i.onclose=()=>{d!==null&&clearTimeout(d),this.debug(`WebSocket connection ${a} closed`),this.conn=null;let c=this.currentWebSocket===i;this.currentWebSocket===i&&(this.currentWebSocket=null,this.isConnecting=!1),c&&p&&!this.wsIntentionalDisconnect&&this.webSocketReconnect&&this.attemptReconnect()}});wsSendMessage=(e,t,r=!1)=>this.isOffline()?(this.debug("wsSendMessage: skipped (offline mode)"),this.setIsPending(!1),Promise.resolve()):new Promise((i,a)=>{if(!r&&h(t)==h(this.context))return this.debug("WebSocket context unchanged, skipping update"),i(this.setIsPending(!1));this.debug(r?"WebSocket force sending context (reconnection):":"WebSocket context updated:",t),this.context=t;let d=()=>{let s=!1,p=this.createPersistentMessageHandler(t),c=R=>{p(R),s||(s=!0,i())};e.addEventListener("message",c),e.addEventListener("close",R=>{s||(s=!0,R.code===4001?a(new Error(`Authentication failed: ${R.reason!==""?R.reason:"Invalid API key"}`)):a(new Error("WebSocket connection closed unexpectedly")))}),this.currentWebSocket=e;let y=this.additionalHeaders["X-Schematic-Client-Version"]??`schematic-js@${he}`,u={apiKey:this.apiKey,clientVersion:y,data:t};this.debug("WebSocket sending message:",u),e.send(JSON.stringify(u))};e.readyState===WebSocket.OPEN?(this.debug("WebSocket already open, sending message"),d()):e.readyState===WebSocket.CONNECTING?(this.debug("WebSocket connecting, waiting for open to send message"),e.addEventListener("open",d)):(this.debug("WebSocket is closed, cannot send message"),a("WebSocket is not open or connecting"))});getIsPending=()=>this.isPending;addIsPendingListener=e=>(this.isPendingListeners.add(e),()=>{this.isPendingListeners.delete(e)});setIsPending=e=>{this.isPending!==e&&(this.isPending=e,this.isPendingListeners.forEach(t=>Mn(t,e)))};getPlan=()=>{let e=h(this.context);return this.planChecks[e]};getCreditBalances=()=>{let e=h(this.context);return this.creditBalances[e]??Vn};getCreditBalance=e=>{let t=h(this.context);return this.creditBalances[t]?.[e]};getFlagCheck=e=>{let t=h(this.context),i=(this.checks[t]??{})[e];if(i!==void 0)return i;if(e in this.flagCheckDefaults||e in this.flagValueDefaults)return e in this.fallbackCheckCache||(this.fallbackCheckCache[e]=this.resolveFallbackCheckFlagReturn(e,void 0,"Default value used")),this.fallbackCheckCache[e]};getFlagValue=e=>{let t=h(this.context),i=(this.checks[t]??{})[e];if(i?.value!==void 0)return i.value;if(e in this.flagCheckDefaults||e in this.flagValueDefaults)return this.resolveFallbackValue(e)};addFlagValueListener=(e,t)=>(e in this.flagValueListeners||(this.flagValueListeners[e]=new Set),this.flagValueListeners[e].add(t),()=>{this.flagValueListeners[e].delete(t)});addFlagCheckListener=(e,t)=>(e in this.flagCheckListeners||(this.flagCheckListeners[e]=new Set),this.flagCheckListeners[e].add(t),()=>{this.flagCheckListeners[e].delete(t)});addPlanListener=e=>(this.planListeners.add(e),()=>{this.planListeners.delete(e)});addCreditBalanceListener=e=>(this.creditBalanceListeners.add(e),()=>{this.creditBalanceListeners.delete(e)});notifyFlagCheckListeners=(e,t)=>{let r=this.flagCheckListeners?.[e]??[];r.size>0&&this.debug(`Notifying ${r.size} flag check listeners for ${e}`,t),typeof t.featureUsageEvent=="string"&&this.updateFeatureUsageEventMap(t),r.forEach(i=>Un(i,t))};updateFeatureUsageEventMap=e=>{if(typeof e.featureUsageEvent!="string")return;let t=e.featureUsageEvent;(this.featureUsageEventMap[t]===void 0||this.featureUsageEventMap[t]===null)&&(this.featureUsageEventMap[t]={}),this.featureUsageEventMap[t]!==void 0&&(this.featureUsageEventMap[t][e.flag]=e),this.debug(`Updated featureUsageEventMap for event: ${t}, flag: ${e.flag}`,e)};notifyFlagValueListeners=(e,t)=>{let r=this.flagValueListeners?.[e]??[];r.size>0&&this.debug(`Notifying ${r.size} flag value listeners for ${e}`,{value:t}),r.forEach((i,a)=>{this.debug(`Calling listener ${a} for flag ${e}`,{flagKey:e,value:t}),Gn(i,t),this.debug(`Listener ${a} for flag ${e} completed`,{flagKey:e,value:t})})};notifyPlanListeners=e=>{let t=this.planListeners??[];t.size>0&&this.debug(`Notifying ${t.size} plan listeners`,{value:e}),t.forEach((r,i)=>{this.debug(`Calling listener ${i} for plan`,{value:e}),Ln(r,e),this.debug(`Listener ${i} for plan completed`,{value:e})})};notifyCreditBalanceListeners=e=>{let t=this.creditBalanceListeners??[];t.size>0&&this.debug(`Notifying ${t.size} credit balance listeners`,{value:e}),t.forEach(r=>qn(r,e))}},Mn=(n,e)=>{n.length>0?n(e):n()},Un=(n,e)=>{n.length>0?n(e):n()},Gn=(n,e)=>{n.length>0?n(e):n()},Ln=(n,e)=>{n.length>0?n(e):n()},qn=(n,e)=>{n.length>0?n(e):n()};window.Schematic=te;})();
1
+ "use strict";(()=>{var pt=Object.create;var Se=Object.defineProperty;var ct=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var ft=Object.getPrototypeOf,yt=Object.prototype.hasOwnProperty;var mt=(n,e)=>()=>{try{return e||n((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}};var gt=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ut(e))!yt.call(n,i)&&i!==t&&Se(n,i,{get:()=>e[i],enumerable:!(r=ct(e,i))||r.enumerable});return n};var Tt=(n,e,t)=>(t=n!=null?pt(ft(n)):{},gt(e||!n||!n.__esModule?Se(t,"default",{value:n,enumerable:!0}):t,n));var Ce=mt(Re=>{(function(n){var e=(function(t){var r=typeof globalThis<"u"&&globalThis||typeof n<"u"&&n||typeof global<"u"&&global||{},i={searchParams:"URLSearchParams"in r,iterable:"Symbol"in r&&"iterator"in Symbol,blob:"FileReader"in r&&"Blob"in r&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in r,arrayBuffer:"ArrayBuffer"in r};function a(o){return o&&DataView.prototype.isPrototypeOf(o)}if(i.arrayBuffer)var d=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],s=ArrayBuffer.isView||function(o){return o&&d.indexOf(Object.prototype.toString.call(o))>-1};function p(o){if(typeof o!="string"&&(o=String(o)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(o)||o==="")throw new TypeError('Invalid character in header field name: "'+o+'"');return o.toLowerCase()}function c(o){return typeof o!="string"&&(o=String(o)),o}function y(o){var l={next:function(){var f=o.shift();return{done:f===void 0,value:f}}};return i.iterable&&(l[Symbol.iterator]=function(){return l}),l}function u(o){this.map={},o instanceof u?o.forEach(function(l,f){this.append(f,l)},this):Array.isArray(o)?o.forEach(function(l){if(l.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+l.length);this.append(l[0],l[1])},this):o&&Object.getOwnPropertyNames(o).forEach(function(l){this.append(l,o[l])},this)}u.prototype.append=function(o,l){o=p(o),l=c(l);var f=this.map[o];this.map[o]=f?f+", "+l:l},u.prototype.delete=function(o){delete this.map[p(o)]},u.prototype.get=function(o){return o=p(o),this.has(o)?this.map[o]:null},u.prototype.has=function(o){return this.map.hasOwnProperty(p(o))},u.prototype.set=function(o,l){this.map[p(o)]=c(l)},u.prototype.forEach=function(o,l){for(var f in this.map)this.map.hasOwnProperty(f)&&o.call(l,this.map[f],f,this)},u.prototype.keys=function(){var o=[];return this.forEach(function(l,f){o.push(f)}),y(o)},u.prototype.values=function(){var o=[];return this.forEach(function(l){o.push(l)}),y(o)},u.prototype.entries=function(){var o=[];return this.forEach(function(l,f){o.push([f,l])}),y(o)},i.iterable&&(u.prototype[Symbol.iterator]=u.prototype.entries);function _(o){if(!o._noBody){if(o.bodyUsed)return Promise.reject(new TypeError("Already read"));o.bodyUsed=!0}}function R(o){return new Promise(function(l,f){o.onload=function(){l(o.result)},o.onerror=function(){f(o.error)}})}function V(o){var l=new FileReader,f=R(l);return l.readAsArrayBuffer(o),f}function M(o){var l=new FileReader,f=R(l),g=/charset=([A-Za-z0-9_-]+)/.exec(o.type),T=g?g[1]:"utf-8";return l.readAsText(o,T),f}function ne(o){for(var l=new Uint8Array(o),f=new Array(l.length),g=0;g<l.length;g++)f[g]=String.fromCharCode(l[g]);return f.join("")}function I(o){if(o.slice)return o.slice(0);var l=new Uint8Array(o.byteLength);return l.set(new Uint8Array(o)),l.buffer}function k(){return this.bodyUsed=!1,this._initBody=function(o){this.bodyUsed=this.bodyUsed,this._bodyInit=o,o?typeof o=="string"?this._bodyText=o:i.blob&&Blob.prototype.isPrototypeOf(o)?this._bodyBlob=o:i.formData&&FormData.prototype.isPrototypeOf(o)?this._bodyFormData=o:i.searchParams&&URLSearchParams.prototype.isPrototypeOf(o)?this._bodyText=o.toString():i.arrayBuffer&&i.blob&&a(o)?(this._bodyArrayBuffer=I(o.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):i.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(o)||s(o))?this._bodyArrayBuffer=I(o):this._bodyText=o=Object.prototype.toString.call(o):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof o=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):i.searchParams&&URLSearchParams.prototype.isPrototypeOf(o)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},i.blob&&(this.blob=function(){var o=_(this);if(o)return o;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var o=_(this);return o||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(i.blob)return this.blob().then(V);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var o=_(this);if(o)return o;if(this._bodyBlob)return M(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(ne(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},i.formData&&(this.formData=function(){return this.text().then(st)}),this.json=function(){return this.text().then(JSON.parse)},this}var U=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function G(o){var l=o.toUpperCase();return U.indexOf(l)>-1?l:o}function C(o,l){if(!(this instanceof C))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');l=l||{};var f=l.body;if(o instanceof C){if(o.bodyUsed)throw new TypeError("Already read");this.url=o.url,this.credentials=o.credentials,l.headers||(this.headers=new u(o.headers)),this.method=o.method,this.mode=o.mode,this.signal=o.signal,!f&&o._bodyInit!=null&&(f=o._bodyInit,o.bodyUsed=!0)}else this.url=String(o);if(this.credentials=l.credentials||this.credentials||"same-origin",(l.headers||!this.headers)&&(this.headers=new u(l.headers)),this.method=G(l.method||this.method||"GET"),this.mode=l.mode||this.mode||null,this.signal=l.signal||this.signal||(function(){if("AbortController"in r){var m=new AbortController;return m.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&f)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(f),(this.method==="GET"||this.method==="HEAD")&&(l.cache==="no-store"||l.cache==="no-cache")){var g=/([?&])_=[^&]*/;if(g.test(this.url))this.url=this.url.replace(g,"$1_="+new Date().getTime());else{var T=/\?/;this.url+=(T.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}C.prototype.clone=function(){return new C(this,{body:this._bodyInit})};function st(o){var l=new FormData;return o.trim().split("&").forEach(function(f){if(f){var g=f.split("="),T=g.shift().replace(/\+/g," "),m=g.join("=").replace(/\+/g," ");l.append(decodeURIComponent(T),decodeURIComponent(m))}}),l}function lt(o){var l=new u,f=o.replace(/\r?\n[\t ]+/g," ");return f.split("\r").map(function(g){return g.indexOf(`
2
+ `)===0?g.substr(1,g.length):g}).forEach(function(g){var T=g.split(":"),m=T.shift().trim();if(m){var L=T.join(":").trim();try{l.append(m,L)}catch(ie){console.warn("Response "+ie.message)}}}),l}k.call(C.prototype);function b(o,l){if(!(this instanceof b))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(l||(l={}),this.type="default",this.status=l.status===void 0?200:l.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=l.statusText===void 0?"":""+l.statusText,this.headers=new u(l.headers),this.url=l.url||"",this._initBody(o)}k.call(b.prototype),b.prototype.clone=function(){return new b(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new u(this.headers),url:this.url})},b.error=function(){var o=new b(null,{status:200,statusText:""});return o.ok=!1,o.status=0,o.type="error",o};var dt=[301,302,303,307,308];b.redirect=function(o,l){if(dt.indexOf(l)===-1)throw new RangeError("Invalid status code");return new b(null,{status:l,headers:{location:o}})},t.DOMException=r.DOMException;try{new t.DOMException}catch{t.DOMException=function(l,f){this.message=l,this.name=f;var g=Error(l);this.stack=g.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function re(o,l){return new Promise(function(f,g){var T=new C(o,l);if(T.signal&&T.signal.aborted)return g(new t.DOMException("Aborted","AbortError"));var m=new XMLHttpRequest;function L(){m.abort()}m.onload=function(){var P={statusText:m.statusText,headers:lt(m.getAllResponseHeaders()||"")};T.url.indexOf("file://")===0&&(m.status<200||m.status>599)?P.status=200:P.status=m.status,P.url="responseURL"in m?m.responseURL:P.headers.get("X-Request-URL");var x="response"in m?m.response:m.responseText;setTimeout(function(){f(new b(x,P))},0)},m.onerror=function(){setTimeout(function(){g(new TypeError("Network request failed"))},0)},m.ontimeout=function(){setTimeout(function(){g(new TypeError("Network request timed out"))},0)},m.onabort=function(){setTimeout(function(){g(new t.DOMException("Aborted","AbortError"))},0)};function ie(P){try{return P===""&&r.location.href?r.location.href:P}catch{return P}}if(m.open(T.method,ie(T.url),!0),T.credentials==="include"?m.withCredentials=!0:T.credentials==="omit"&&(m.withCredentials=!1),"responseType"in m&&(i.blob?m.responseType="blob":i.arrayBuffer&&(m.responseType="arraybuffer")),l&&typeof l.headers=="object"&&!(l.headers instanceof u||r.Headers&&l.headers instanceof r.Headers)){var Pe=[];Object.getOwnPropertyNames(l.headers).forEach(function(P){Pe.push(p(P)),m.setRequestHeader(P,c(l.headers[P]))}),T.headers.forEach(function(P,x){Pe.indexOf(x)===-1&&m.setRequestHeader(x,P)})}else T.headers.forEach(function(P,x){m.setRequestHeader(x,P)});T.signal&&(T.signal.addEventListener("abort",L),m.onreadystatechange=function(){m.readyState===4&&T.signal.removeEventListener("abort",L)}),m.send(typeof T._bodyInit>"u"?null:T._bodyInit)})}return re.polyfill=!0,r.fetch||(r.fetch=re,r.Headers=u,r.Request=C,r.Response=b),t.Headers=u,t.Request=C,t.Response=b,t.fetch=re,t})({})})(typeof self<"u"?self:Re)});var S=[];for(let n=0;n<256;++n)S.push((n+256).toString(16).slice(1));function _e(n,e=0){return(S[n[e+0]]+S[n[e+1]]+S[n[e+2]]+S[n[e+3]]+"-"+S[n[e+4]]+S[n[e+5]]+"-"+S[n[e+6]]+S[n[e+7]]+"-"+S[n[e+8]]+S[n[e+9]]+"-"+S[n[e+10]]+S[n[e+11]]+S[n[e+12]]+S[n[e+13]]+S[n[e+14]]+S[n[e+15]]).toLowerCase()}var ht=new Uint8Array(16);function oe(){return crypto.getRandomValues(ht)}function Pt(n,e,t){return!e&&!n&&crypto.randomUUID?crypto.randomUUID():St(n,e,t)}function St(n,e,t){n=n||{};let r=n.random??n.rng?.()??oe();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(t=t||0,t<0||t+16>e.length)throw new RangeError(`UUID byte range ${t}:${t+15} is out of buffer bounds`);for(let i=0;i<16;++i)e[t+i]=r[i];return e}return _e(r)}var N=Pt;var r_=Tt(Ce());function pe(n){return Kt(n,!1)}function Kt(n,e){return n}function w(n){return Zt(n,!1)}function Zt(n,e){return n}function Be(n){return Xt(n,!1)}function Xt(n,e){return n==null?n:{key:n.key,value:n.value}}function B(n){return Yt(n,!1)}function Yt(n,e){return n}function Ne(n){return en(n,!1)}function en(n,e){return n==null?n:{allocation:n.allocation==null?void 0:n.allocation,consumptionRate:n.consumption_rate==null?void 0:n.consumption_rate,creditId:n.credit_id==null?void 0:n.credit_id,creditRemaining:n.credit_remaining==null?void 0:n.credit_remaining,creditReserved:n.credit_reserved==null?void 0:n.credit_reserved,creditSettled:n.credit_settled==null?void 0:n.credit_settled,creditTotal:n.credit_total==null?void 0:n.credit_total,creditUsed:n.credit_used==null?void 0:n.credit_used,eventName:n.event_name==null?void 0:n.event_name,eventSubtype:n.event_subtype==null?void 0:n.event_subtype,featureId:n.feature_id,featureKey:n.feature_key,metricPeriod:n.metric_period==null?void 0:B(n.metric_period),metricResetAt:n.metric_reset_at==null?void 0:new Date(n.metric_reset_at),monthReset:n.month_reset==null?void 0:w(n.month_reset),softLimit:n.soft_limit==null?void 0:n.soft_limit,usage:n.usage==null?void 0:n.usage,valueType:pe(n.value_type),warningTiers:n.warning_tiers==null?void 0:n.warning_tiers.map(Be)}}function H(n){return tn(n,!1)}function tn(n,e){return n}function E(n){return nn(n,!1)}function nn(n,e){return n==null?n:{companyId:n.company_id==null?void 0:n.company_id,entitlement:n.entitlement==null?void 0:Ne(n.entitlement),error:n.error==null?void 0:n.error,featureAllocation:n.feature_allocation==null?void 0:n.feature_allocation,featureUsage:n.feature_usage==null?void 0:n.feature_usage,featureUsageEvent:n.feature_usage_event==null?void 0:n.feature_usage_event,featureUsagePeriod:n.feature_usage_period==null?void 0:B(n.feature_usage_period),featureUsageResetAt:n.feature_usage_reset_at==null?void 0:new Date(n.feature_usage_reset_at),flag:n.flag,flagId:n.flag_id==null?void 0:n.flag_id,reason:n.reason,ruleId:n.rule_id==null?void 0:n.rule_id,ruleType:n.rule_type==null?void 0:H(n.rule_type),userId:n.user_id==null?void 0:n.user_id,value:n.value}}function ue(n){return on(n,!1)}function on(n,e){return n==null?n:{data:E(n.data),params:n.params}}var an="https://api.schematichq.com".replace(/\/+$/,""),fe=class{constructor(e={}){this.configuration=e}configuration;set config(e){this.configuration=e}get basePath(){return this.configuration.basePath!=null?this.configuration.basePath:an}get fetchApi(){return this.configuration.fetchApi}get middleware(){return this.configuration.middleware||[]}get queryParamsStringify(){return this.configuration.queryParamsStringify||Ee}get username(){return this.configuration.username}get password(){return this.configuration.password}get apiKey(){let e=this.configuration.apiKey;if(e)return typeof e=="function"?e:()=>e}get accessToken(){let e=this.configuration.accessToken;if(e)return typeof e=="function"?e:async()=>e}get headers(){return this.configuration.headers}get credentials(){return this.configuration.credentials}},sn=new fe,Fe=class n{constructor(e=sn){this.configuration=e;this.middleware=e.middleware}configuration;static jsonRegex=new RegExp("^(:?application/json|[^;/ ]+/[^;/ ]+[+]json)[ ]*(:?;.*)?$","i");middleware;withMiddleware(...e){let t=this.clone();return t.middleware=t.middleware.concat(...e),t}withPreMiddleware(...e){let t=e.map(r=>({pre:r}));return this.withMiddleware(...t)}withPostMiddleware(...e){let t=e.map(r=>({post:r}));return this.withMiddleware(...t)}isJsonMime(e){return e?n.jsonRegex.test(e):!1}async request(e,t){let{url:r,init:i}=await this.createFetchParams(e,t),a=await this.fetchApi(r,i);if(a&&a.status>=200&&a.status<300)return a;throw new ye(a,"Response returned an error code")}async createFetchParams(e,t){let r=this.configuration.basePath+e.path;e.query!==void 0&&Object.keys(e.query).length!==0&&(r+="?"+this.configuration.queryParamsStringify(e.query));let i=Object.assign({},this.configuration.headers,e.headers);Object.keys(i).forEach(y=>i[y]===void 0?delete i[y]:{});let a=typeof t=="function"?t:async()=>t,d={method:e.method,headers:i,body:e.body,credentials:this.configuration.credentials},s={...d,...await a({init:d,context:e})},p;dn(s.body)||s.body instanceof URLSearchParams||ln(s.body)?p=s.body:this.isJsonMime(i["Content-Type"])?p=JSON.stringify(s.body):p=s.body;let c={...s,body:p};return{url:r,init:c}}fetchApi=async(e,t)=>{let r={url:e,init:t};for(let a of this.middleware)a.pre&&(r=await a.pre({fetch:this.fetchApi,...r})||r);let i;try{i=await(this.configuration.fetchApi||fetch)(r.url,r.init)}catch(a){for(let d of this.middleware)d.onError&&(i=await d.onError({fetch:this.fetchApi,url:r.url,init:r.init,error:a,response:i?i.clone():void 0})||i);if(i===void 0)throw a instanceof Error?new me(a,"The request failed and the interceptors did not return an alternative response"):a}for(let a of this.middleware)a.post&&(i=await a.post({fetch:this.fetchApi,url:r.url,init:r.init,response:i.clone()})||i);return i};clone(){let e=this.constructor,t=new e(this.configuration);return t.middleware=this.middleware.slice(),t}};function ln(n){return typeof Blob<"u"&&n instanceof Blob}function dn(n){return typeof FormData<"u"&&n instanceof FormData}var ye=class extends Error{constructor(t,r){super(r);this.response=t}response;name="ResponseError"},me=class extends Error{constructor(t,r){super(r);this.cause=t}cause;name="FetchError"};function Ee(n,e=""){return Object.keys(n).map(t=>Ae(t,n[t],e)).filter(t=>t.length>0).join("&")}function Ae(n,e,t=""){let r=t+(t.length?`[${n}]`:n);if(e instanceof Array){let i=e.map(a=>encodeURIComponent(String(a))).join(`&${encodeURIComponent(r)}=`);return`${encodeURIComponent(r)}=${i}`}if(e instanceof Set){let i=Array.from(e);return Ae(n,i,t)}return e instanceof Date?`${encodeURIComponent(r)}=${encodeURIComponent(e.toISOString())}`:e instanceof Object?Ee(e,r):`${encodeURIComponent(r)}=${encodeURIComponent(String(e))}`}function Ie(n,e){return Object.keys(n).reduce((t,r)=>({...t,[r]:e(n[r])}),{})}function Q(n){return pn(n,!1)}function pn(n,e){return n==null?n:{remaining:n.remaining,reserved:n.reserved,settled:n.settled}}function ke(n){return cn(n,!1)}function cn(n,e){return n}function v(n){return un(n,!1)}function un(n,e){return n==null?n:{id:n.id,name:n.name,trialEndDate:n.trial_end_date==null?void 0:new Date(n.trial_end_date),trialStatus:n.trial_status==null?void 0:ke(n.trial_status)}}function we(n){return fn(n,!1)}function fn(n,e){return n==null?n:{creditBalances:n.credit_balances==null?void 0:Ie(n.credit_balances,Q),flags:n.flags.map(E),plan:n.plan==null?void 0:v(n.plan)}}function ge(n){return yn(n,!1)}function yn(n,e){return n==null?n:{data:we(n.data),params:n.params}}function z(n){return mn(n,!1)}function mn(n,e=!1){return n==null?n:{company_id:n.companyId,error:n.error,flag_id:n.flagId,flag_key:n.flagKey,preflight:n.preflight,reason:n.reason,req_company:n.reqCompany,req_user:n.reqUser,rule_id:n.ruleId,user_id:n.userId,value:n.value}}var Te=n=>{let{companyId:e,entitlement:t,error:r,featureAllocation:i,featureUsage:a,featureUsageEvent:d,featureUsagePeriod:s,featureUsageResetAt:p,flag:c,flagId:y,reason:u,ruleId:_,ruleType:R,userId:V,value:M}=E(n),ne=!M&&(R=="company_override_usage_exceeded"||R=="plan_entitlement_usage_exceeded"),I=t?.allocation??i,k=t?.usage??a,U=t?.eventName??d,G=t?.metricPeriod??s,C=t?.metricResetAt??p;return{featureUsageExceeded:ne,companyId:e??void 0,creditId:t?.creditId==null?void 0:t.creditId,creditRemaining:t?.creditRemaining==null?void 0:t.creditRemaining,creditReserved:t?.creditReserved==null?void 0:t.creditReserved,creditSettled:t?.creditSettled==null?void 0:t.creditSettled,error:r??void 0,featureAllocation:I??void 0,featureUsage:k??void 0,featureUsageEvent:U??void 0,featureUsagePeriod:G??void 0,featureUsageResetAt:C??void 0,flag:c,flagId:y??void 0,reason:u,ruleId:_??void 0,ruleType:R??void 0,softLimit:t?.softLimit==null?void 0:t.softLimit,userId:V??void 0,value:M}},rt=n=>{let{id:e,name:t,trialEndDate:r,trialStatus:i}=v(n);return{id:e,name:t,trialEndDate:r??void 0,trialStatus:i??void 0}},it=n=>{if(n==null||typeof n!="object")return{};let e={};for(let[t,r]of Object.entries(n)){if(r==null||typeof r!="object")continue;let{remaining:i,reserved:a,settled:d}=Q(r);typeof i!="number"||typeof a!="number"||typeof d!="number"||(e[t]={remaining:i,reserved:a,settled:d})}return e};var A="bb56e75d";function h(n){let e=Object.keys(n).reduce((t,r)=>{let a=Object.keys(n[r]||{}).sort().reduce((d,s)=>(d[s]=n[r][s],d),{});return t[r]=a,t},{});return JSON.stringify(e)}var he="1.7.0";var ot="schematicId",Un="schematicCache",at=10,Gn=10080*60*1e3,Ln=Object.freeze({});var te=class{_additionalHeaders={};apiKey;_apiUrl="https://api.schematichq.com";conn=null;context={};debugEnabled=!1;offlineEnabled=!1;eventQueue;contextDependentEventQueue;eventUrl="https://c.schematichq.com";flagCheckListeners={};flagValueListeners={};isPending=!0;isPendingListeners=new Set;planListeners=new Set;creditBalanceListeners=new Set;storage;persistFlagState=!0;flagStateCacheKey;flagStateCacheMaxAgeMs=Gn;cachedFlagState=null;useWebSocket=!1;checks={};featureUsageEventMap={};planChecks={};creditBalances={};webSocketUrl="wss://api.schematichq.com";webSocketConnectionTimeout=1e4;webSocketReconnect=!0;webSocketMaxReconnectAttempts=7;webSocketMaxConnectionAttempts=3;webSocketInitialRetryDelay=1e3;webSocketMaxRetryDelay=3e4;wsReconnectAttempts=0;wsReconnectTimer=null;wsIntentionalDisconnect=!1;currentWebSocket=null;isConnecting=!1;maxEventQueueSize=100;maxEventRetries=5;eventRetryInitialDelay=1e3;eventRetryMaxDelay=3e4;retryTimer=null;flagValueDefaults={};flagCheckDefaults={};fallbackCheckCache={};constructor(e,t){if(this.apiKey=e,this.flagStateCacheKey=`${Un}:${e}`,this.eventQueue=[],this.contextDependentEventQueue=[],this.useWebSocket=t?.useWebSocket??!1,this.debugEnabled=t?.debug??!1,this.offlineEnabled=t?.offline??!1,this.persistFlagState=t?.persistFlagState??!0,typeof t?.flagStateCacheMaxAgeMs=="number"&&t.flagStateCacheMaxAgeMs>0&&(this.flagStateCacheMaxAgeMs=t.flagStateCacheMaxAgeMs),typeof window<"u"&&typeof window.location<"u"){let r=new URLSearchParams(window.location.search),i=r.get("schematic_debug");i!==null&&(i===""||i==="true"||i==="1")&&(this.debugEnabled=!0);let a=r.get("schematic_offline");a!==null&&(a===""||a==="true"||a==="1")&&(this.offlineEnabled=!0,this.debugEnabled=!0)}if(this.offlineEnabled&&t?.debug!==!1&&(this.debugEnabled=!0),this.offlineEnabled&&this.setIsPending(!1),this._additionalHeaders={"X-Schematic-Client-Version":`schematic-js@${he}`,...t?.additionalHeaders??{}},t?.storage)this.storage=t.storage;else try{typeof localStorage<"u"&&(this.storage=localStorage)}catch{}this.hydrateFlagStateFromCache(),t?.apiUrl!==void 0&&(this._apiUrl=t.apiUrl),t?.eventUrl!==void 0&&(this.eventUrl=t.eventUrl),t?.webSocketUrl!==void 0&&(this.webSocketUrl=t.webSocketUrl),t?.webSocketConnectionTimeout!==void 0&&(this.webSocketConnectionTimeout=t.webSocketConnectionTimeout),t?.webSocketReconnect!==void 0&&(this.webSocketReconnect=t.webSocketReconnect),t?.webSocketMaxReconnectAttempts!==void 0&&(this.webSocketMaxReconnectAttempts=t.webSocketMaxReconnectAttempts),t?.webSocketInitialRetryDelay!==void 0&&(this.webSocketInitialRetryDelay=t.webSocketInitialRetryDelay),t?.webSocketMaxRetryDelay!==void 0&&(this.webSocketMaxRetryDelay=t.webSocketMaxRetryDelay),t?.maxEventQueueSize!==void 0&&(this.maxEventQueueSize=t.maxEventQueueSize),t?.maxEventRetries!==void 0&&(this.maxEventRetries=t.maxEventRetries),t?.eventRetryInitialDelay!==void 0&&(this.eventRetryInitialDelay=t.eventRetryInitialDelay),t?.eventRetryMaxDelay!==void 0&&(this.eventRetryMaxDelay=t.eventRetryMaxDelay),t?.flagValueDefaults!==void 0&&(this.flagValueDefaults=t.flagValueDefaults),t?.flagCheckDefaults!==void 0&&(this.flagCheckDefaults=t.flagCheckDefaults),typeof window<"u"&&window?.addEventListener&&(window.addEventListener("beforeunload",()=>{this.flushEventQueue(),this.flushContextDependentEventQueue()}),this.useWebSocket&&(window.addEventListener("offline",()=>{this.debug("Browser went offline, closing WebSocket connection"),this.handleNetworkOffline()}),window.addEventListener("online",()=>{this.debug("Browser came online, attempting to reconnect WebSocket"),this.handleNetworkOnline()}))),this.offlineEnabled?this.debug("Initialized with offline mode enabled - no network requests will be made"):this.debugEnabled&&this.debug("Initialized with debug mode enabled")}get apiUrl(){return this._apiUrl}get additionalHeaders(){return{...this._additionalHeaders}}resolveFallbackValue(e,t){return t!==void 0?t:e in this.flagCheckDefaults?this.flagCheckDefaults[e].value:e in this.flagValueDefaults?this.flagValueDefaults[e]:!1}resolveFallbackCheckFlagReturn(e,t,r="Fallback value used",i){if(t!==void 0)return{flag:e,value:t,reason:r,error:i};if(e in this.flagCheckDefaults){let a=this.flagCheckDefaults[e];return{...a,flag:e,reason:i!==void 0?r:a.reason,error:i}}return e in this.flagValueDefaults?{flag:e,value:this.flagValueDefaults[e],reason:r,error:i}:{flag:e,value:!1,reason:r,error:i}}async checkFlag(e){let{fallback:t,key:r}=e,i=e.context||this.context,a=h(i);if(this.debug(`checkFlag: ${r}`,{context:i,fallback:t}),this.isOffline()){let d=this.resolveFallbackCheckFlagReturn(r,t,"Offline mode - using initialization defaults");return this.debug(`checkFlag offline result: ${r}`,{value:d.value,offlineMode:!0}),d.value}if(!this.useWebSocket){let d=`${this._apiUrl}/flags/${r}/check`;return fetch(d,{method:"POST",headers:{...this._additionalHeaders??{},"Content-Type":"application/json;charset=UTF-8","X-Schematic-Api-Key":this.apiKey},body:JSON.stringify(i)}).then(s=>{if(!s.ok)throw new Error("Network response was not ok");return s.json()}).then(s=>{let p=ue(s);this.debug(`checkFlag result: ${r}`,p);let c=Te(p.data);return typeof c.featureUsageEvent=="string"&&this.updateFeatureUsageEventMap(c),this.submitFlagCheckEvent(r,c,i),c.value}).catch(s=>{console.warn("There was a problem with the fetch operation:",s);let p=this.resolveFallbackCheckFlagReturn(r,t,"API request failed",s instanceof Error?s.message:String(s));return this.submitFlagCheckEvent(r,p,i),p.value})}try{let d=this.checks[a];if(this.conn!==null&&typeof d<"u"&&typeof d[r]<"u")return this.debug(`checkFlag cached result: ${r}`,d[r]),d[r].value;if(this.isOffline())return this.resolveFallbackValue(r,t);try{await this.setContext(i)}catch(y){console.warn("WebSocket connection failed, using fallback value:",y);let u=this.resolveFallbackCheckFlagReturn(r,t,"WebSocket connection failed",y instanceof Error?y.message:String(y));return this.submitFlagCheckEvent(r,u,i),u.value}let p=(this.checks[a]??{})[r],c=p?.value??this.resolveFallbackValue(r,t);if(this.debug(`checkFlag WebSocket result: ${r}`,typeof p<"u"?p:{value:c,fallbackUsed:!0}),typeof p<"u")this.submitFlagCheckEvent(r,p,i);else{let y=this.resolveFallbackCheckFlagReturn(r,t,"No flag values available");this.submitFlagCheckEvent(r,y,i)}return c}catch(d){console.error("Unexpected error in checkFlag:",d);let s=this.resolveFallbackCheckFlagReturn(r,t,"Unexpected error in flag check",d instanceof Error?d.message:String(d));return this.submitFlagCheckEvent(r,s,i),s.value}}debug(e,...t){this.debugEnabled&&console.log(`[Schematic] ${e}`,...t)}createPersistentMessageHandler(e){return t=>{let r=JSON.parse(t.data);if(this.debug("WebSocket persistent message received:",r),h(e)in this.checks||(this.checks[h(e)]={}),(r.flags??[]).forEach(i=>{let a=Te(i),d=h(e);this.checks[d]===void 0&&(this.checks[d]={}),this.checks[d][a.flag]=a,typeof a.featureUsageEvent=="string"&&this.updateFeatureUsageEventMap(a),((this.flagCheckListeners[i.flag]?.size??0)>0||(this.flagValueListeners[i.flag]?.size??0)>0)&&this.submitFlagCheckEvent(a.flag,a,e),this.debug(`WebSocket flag update received. Notifying listeners for ${i.flag}`,{flag:i.flag,value:a.value,flagCheck:a}),this.notifyFlagCheckListeners(i.flag,a),this.notifyFlagValueListeners(i.flag,a.value)}),r.plan!==void 0&&r.plan!==null){let i=rt(r.plan),a=h(e);this.planChecks[a]=i,this.debug("WebSocket plan update received. Notifying listeners",{plan:i}),this.notifyPlanListeners(i)}if(r.credit_balances!==void 0&&r.credit_balances!==null){let i=h(e),a=it(r.credit_balances),d=this.creditBalances[i]??{},s=!1,p={...d};for(let[c,y]of Object.entries(a)){let u=d[c];(u===void 0||u.remaining!==y.remaining||u.reserved!==y.reserved||u.settled!==y.settled)&&(p[c]=y,s=!0)}s&&(this.creditBalances[i]=p,this.debug("WebSocket credit balance update received. Notifying listeners",{creditBalances:p}),this.notifyCreditBalanceListeners(p))}this.persistContextToCache(h(e)),this.flushContextDependentEventQueue(),this.setIsPending(!1)}}isOffline(){return this.offlineEnabled}submitFlagCheckEvent(e,t,r){let i={flagKey:e,value:t.value,reason:t.reason,flagId:t.flagId,ruleId:t.ruleId,companyId:t.companyId,userId:t.userId,error:t.error,reqCompany:r.company,reqUser:r.user};return this.debug("submitting flag check event:",i),this.handleEvent("flag_check",z(i))}checkFlags=async e=>{if(e=e||this.context,this.debug("checkFlags",{context:e}),this.isOffline())return this.debug("checkFlags offline result: returning empty object"),{};let t=`${this._apiUrl}/flags/check`,r=JSON.stringify(e);return fetch(t,{method:"POST",headers:{...this._additionalHeaders??{},"Content-Type":"application/json;charset=UTF-8","X-Schematic-Api-Key":this.apiKey},body:r}).then(i=>{if(!i.ok)throw new Error("Network response was not ok");return i.json()}).then(i=>{let a=ge(i);return this.debug("checkFlags result:",a),(a?.data?.flags??[]).reduce((d,s)=>(d[s.flag]=s.value,d),{})}).catch(i=>(console.warn("There was a problem with the fetch operation:",i),{}))};identify=e=>(this.debug("identify:",e),this.setContext({company:e.company?.keys,user:e.keys}).catch(t=>{console.warn("Error setting context:",t)}),this.handleEvent("identify",e));setContext=async e=>{if(this.isOffline()||!this.useWebSocket)return this.context=e,this.flushContextDependentEventQueue(),this.setIsPending(!1),Promise.resolve();if(!(h(e)===h(this.context)&&this.conn!==null&&!this.isPending))try{let t=h(e),r=this.hasCachedValuesForContext(t);if(r){this.debug("setContext: cache hit for context, pre-resolving from cached values"),this.context=e,this.flushContextDependentEventQueue(),this.setIsPending(!1);let a=this.checks[t]??{};for(let[p,c]of Object.entries(a))c!==void 0&&(this.notifyFlagCheckListeners(p,c),this.notifyFlagValueListeners(p,c.value));let d=this.planChecks[t];d!==void 0&&this.notifyPlanListeners(d);let s=this.creditBalances[t];s!==void 0&&this.notifyCreditBalanceListeners(s)}else this.setIsPending(!0);if(!this.conn){if(this.isConnecting){for(this.debug("Connection already in progress, waiting for it to complete");this.isConnecting&&this.conn===null;)await new Promise(a=>setTimeout(a,10));if(this.conn!==null){let a=await this.conn;await this.wsSendMessage(a,e,r);return}}this.wsReconnectTimer!==null&&(this.debug("Cancelling scheduled reconnection, connecting immediately"),clearTimeout(this.wsReconnectTimer),this.wsReconnectTimer=null),this.isConnecting=!0;try{this.conn=this.wsConnect();let a=await this.conn;this.isConnecting=!1,await this.wsSendMessage(a,e,r);return}catch(a){throw this.isConnecting=!1,a}}let i=await this.conn;await this.wsSendMessage(i,e,r)}catch(t){console.warn("Failed to establish WebSocket connection:",t),this.context=e,this.flushContextDependentEventQueue(),this.setIsPending(!1),this.attemptReconnect()}};track=e=>{let{company:t,user:r,event:i,traits:a,quantity:d=1}=e;if(!this.hasContext(t,r)){this.debug(`track: queuing event "${i}" until context is available`);let p={api_key:this.apiKey,body:{company:t,event:i,traits:a??{},user:r,quantity:d},sent_at:new Date().toISOString(),tracker_event_id:N(),tracker_user_id:this.getAnonymousId(),type:"track"};return this.contextDependentEventQueue.push(p),Promise.resolve()}let s={company:t??this.context.company,event:i,traits:a??{},user:r??this.context.user,quantity:d};return this.debug("track:",s),i in this.featureUsageEventMap&&this.optimisticallyUpdateFeatureUsage(i,d),this.handleEvent("track",s)};optimisticallyUpdateFeatureUsage=(e,t=1)=>{let r=this.featureUsageEventMap[e];if(r==null)return;this.debug(`Optimistically updating feature usage for event: ${e}`,{quantity:t});let i=!1;Object.entries(r).forEach(([a,d])=>{if(d===void 0)return;let s={...d};if(typeof s.featureUsage=="number"){if(i=!0,s.featureUsage+=t,typeof s.featureAllocation=="number"){let c=s.featureUsageExceeded===!0,y=s.featureUsage>=s.featureAllocation;y!==c&&(s.featureUsageExceeded=y,y&&(s.value=!1),this.debug(`Usage limit status changed for flag: ${a}`,{was:c?"exceeded":"within limits",now:y?"exceeded":"within limits",featureUsage:s.featureUsage,featureAllocation:s.featureAllocation,value:s.value}))}this.featureUsageEventMap[e]!==void 0&&(this.featureUsageEventMap[e][a]=s);let p=h(this.context);this.checks[p]!==void 0&&this.checks[p]!==null&&(this.checks[p][a]=s),this.notifyFlagCheckListeners(a,s),this.notifyFlagValueListeners(a,s.value)}}),i&&this.persistContextToCache(h(this.context))};hasContext=(e,t)=>{let r=e!=null&&Object.keys(e).length>0||t!=null&&Object.keys(t).length>0,i=this.context.company!==void 0&&this.context.company!==null&&Object.keys(this.context.company).length>0||this.context.user!==void 0&&this.context.user!==null&&Object.keys(this.context.user).length>0;return r||i};flushContextDependentEventQueue=()=>{for(this.debug(`flushing ${this.contextDependentEventQueue.length} context-dependent events`);this.contextDependentEventQueue.length>0;){let e=this.contextDependentEventQueue.shift();if(e)if(e.type==="track"&&typeof e.body=="object"&&e.body!==null){let t=e.body,r={...t,company:t.company??this.context.company,user:t.user??this.context.user},i={...e,body:r,sent_at:new Date().toISOString()};this.sendEvent(i)}else this.sendEvent(e)}};startRetryTimer=()=>{this.retryTimer===null&&(this.retryTimer=setInterval(()=>{this.flushEventQueue().catch(e=>{this.debug("Error in retry timer flush:",e)}),this.eventQueue.length===0&&this.stopRetryTimer()},5e3),this.debug("Started retry timer"))};stopRetryTimer=()=>{this.retryTimer!==null&&(clearInterval(this.retryTimer),this.retryTimer=null,this.debug("Stopped retry timer"))};flushEventQueue=async()=>{if(this.eventQueue.length===0)return;let e=Date.now(),t=[],r=[];for(let i of this.eventQueue)i.next_retry_at===void 0||i.next_retry_at<=e?t.push(i):r.push(i);if(t.length===0){this.debug(`No events ready for retry yet (${r.length} still in backoff)`);return}this.debug(`Flushing event queue: ${t.length} ready, ${r.length} waiting`),this.eventQueue=r;for(let i of t)try{await this.sendEvent(i),this.debug("Queued event sent successfully:",i.type)}catch(a){this.debug("Failed to send queued event:",a)}};getAnonymousId=()=>{if(!this.storage)return N();let e=this.storage.getItem(ot);if(typeof e<"u")return e;let t=N();return this.storage.setItem(ot,t),t};hasCachedValuesForContext=e=>{let t=this.checks[e];if(t!==void 0&&Object.keys(t).length>0||this.planChecks[e]!==void 0)return!0;let r=this.creditBalances[e];return r!==void 0&&Object.keys(r).length>0};readFlagStateCache=()=>{if(!this.persistFlagState||this.storage===void 0)return null;let e;try{e=this.storage.getItem(this.flagStateCacheKey)}catch(r){return this.debug("Failed to read flag state cache:",r),null}if(e==null)return null;let t;try{t=typeof e=="string"?JSON.parse(e):e}catch(r){return this.debug("Flag state cache is not valid JSON, ignoring:",r),null}return t===null||typeof t!="object"||t.version!==A||typeof t.contexts!="object"||t.contexts===null?(this.debug(`Flag state cache invalid or version mismatch (expected ${A}), ignoring`,{parsedType:typeof t,version:t?.version}),null):t};reviveCachedCheck=e=>{if(e===null||typeof e!="object")return null;let t=e;if(typeof t.flag!="string"||typeof t.value!="boolean"||typeof t.reason!="string")return null;let r={...t};if(typeof r.featureUsageResetAt=="string"){let i=new Date(r.featureUsageResetAt);r.featureUsageResetAt=isNaN(i.getTime())?void 0:i}return r};reviveCachedPlan=e=>{if(e===null||typeof e!="object")return null;let t=e;if(typeof t.id!="string"||typeof t.name!="string")return null;let r={...t};if(typeof r.trialEndDate=="string"){let i=new Date(r.trialEndDate);r.trialEndDate=isNaN(i.getTime())?void 0:i}return r};reviveCachedCreditBalances=e=>{if(e===null||typeof e!="object")return null;let t={};for(let[r,i]of Object.entries(e)){if(i===null||typeof i!="object")continue;let a=i;typeof a.remaining!="number"||typeof a.reserved!="number"||typeof a.settled!="number"||(t[r]={remaining:a.remaining,reserved:a.reserved,settled:a.settled})}return Object.keys(t).length>0?t:null};hydrateFlagStateFromCache=()=>{let e=this.readFlagStateCache();if(e===null)return;let t=Date.now()-this.flagStateCacheMaxAgeMs,r={},i=0,a=0;for(let[d,s]of Object.entries(e.contexts)){if(s===null||typeof s!="object"||typeof s.updatedAt!="number")continue;if(s.updatedAt<t){a+=1;continue}let p={};if(s.checks!==null&&typeof s.checks=="object"){for(let[u,_]of Object.entries(s.checks)){let R=this.reviveCachedCheck(_);R===null||R.flag!==u||(p[u]=R,typeof R.featureUsageEvent=="string"&&this.updateFeatureUsageEventMap(R))}Object.keys(p).length>0&&(this.checks[d]=p)}let c;if(s.plan!==void 0&&s.plan!==null){let u=this.reviveCachedPlan(s.plan);u!==null&&(c=u,this.planChecks[d]=u)}let y;if(s.creditBalances!==void 0&&s.creditBalances!==null){let u=this.reviveCachedCreditBalances(s.creditBalances);u!==null&&(y=u,this.creditBalances[d]=u)}r[d]={checks:p,plan:c,creditBalances:y,updatedAt:s.updatedAt},i+=1}this.cachedFlagState={version:A,contexts:r},this.debug(`Hydrated flag state cache: ${i} loaded, ${a} expired`)};persistContextToCache=e=>{let t=this.checks[e],r=this.planChecks[e],i=this.creditBalances[e];if(t===void 0&&r===void 0&&i===void 0)return;this.cachedFlagState===null&&(this.cachedFlagState=(this.persistFlagState?this.readFlagStateCache():null)??{version:A,contexts:{}});let a={};if(t!==void 0)for(let[s,p]of Object.entries(t))p!==void 0&&(a[s]=p);this.cachedFlagState.contexts[e]={checks:a,plan:r,creditBalances:i,updatedAt:Date.now()};let d=Object.entries(this.cachedFlagState.contexts);if(d.length>at){d.sort((c,y)=>y[1].updatedAt-c[1].updatedAt);let s=d.slice(0,at),p=new Set(s.map(([c])=>c));for(let c of Object.keys(this.checks))p.has(c)||delete this.checks[c];for(let c of Object.keys(this.planChecks))p.has(c)||delete this.planChecks[c];for(let c of Object.keys(this.creditBalances))p.has(c)||delete this.creditBalances[c];this.cachedFlagState={version:A,contexts:Object.fromEntries(s)}}if(!(!this.persistFlagState||this.storage===void 0))try{this.storage.setItem(this.flagStateCacheKey,JSON.stringify(this.cachedFlagState))}catch(s){this.debug("Failed to write flag state cache:",s)}};handleEvent=(e,t)=>{let r={api_key:this.apiKey,body:t,sent_at:new Date().toISOString(),tracker_event_id:N(),tracker_user_id:this.getAnonymousId(),type:e};return typeof document<"u"&&document?.hidden?this.storeEvent(r):this.sendEvent(r)};sendEvent=async e=>{let t=`${this.eventUrl}/e`,r=JSON.stringify(e);if(this.debug("sending event:",{url:t,event:e}),this.isOffline())return this.debug("event not sent (offline mode):",{event:e}),Promise.resolve();try{let i=await fetch(t,{method:"POST",headers:{...this._additionalHeaders??{},"Content-Type":"application/json;charset=UTF-8"},body:r});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);this.debug("event sent:",{status:i.status,statusText:i.statusText})}catch(i){let a=(e.retry_count??0)+1;if(a<=this.maxEventRetries){this.debug(`Event failed to send (attempt ${a}/${this.maxEventRetries}), queueing for retry:`,i);let d=this.eventRetryInitialDelay*Math.pow(2,a-1),s=Math.min(d,this.eventRetryMaxDelay),p=Date.now()+s,c={...e,retry_count:a,next_retry_at:p};this.eventQueue.length<this.maxEventQueueSize?(this.eventQueue.push(c),this.debug(`Event queued for retry in ${s}ms (${this.eventQueue.length}/${this.maxEventQueueSize})`)):(this.debug(`Event queue full (${this.maxEventQueueSize}), dropping oldest event`),this.eventQueue.shift(),this.eventQueue.push(c)),this.startRetryTimer()}else this.debug(`Event failed permanently after ${this.maxEventRetries} attempts, dropping:`,i)}return Promise.resolve()};storeEvent=e=>(this.eventQueue.push(e),Promise.resolve());forceReconnect=async()=>this.reconnect({force:!0});reconnectIfNeeded=async()=>this.reconnect({force:!1});reconnect=async e=>{let{force:t}=e,r=t?"forceReconnect":"reconnectIfNeeded";if(this.isOffline())return this.debug(`${r}: skipped (offline mode)`),Promise.resolve();if(!t&&this.conn!==null)try{if((await this.conn).readyState===WebSocket.OPEN)return this.debug(`${r}: connection is healthy, skipping`),Promise.resolve()}catch{}if(this.debug(`${r}: ${t?"forcing immediate reconnection":"reconnecting"}`),this.wsIntentionalDisconnect=!1,this.wsReconnectTimer!==null&&(this.debug(`${r}: cancelling pending reconnection timer`),clearTimeout(this.wsReconnectTimer),this.wsReconnectTimer=null),this.wsReconnectAttempts=0,this.conn!==null){this.debug(`${r}: closing existing connection`);try{let i=await this.conn;this.currentWebSocket===i&&(this.currentWebSocket=null),(i.readyState===WebSocket.OPEN||i.readyState===WebSocket.CONNECTING)&&i.close()}catch(i){this.debug(`${r}: error closing existing connection:`,i)}this.conn=null,this.isConnecting=!1}if(this.context.company!==void 0||this.context.user!==void 0){this.debug(`${r}: reconnecting with existing context`);try{this.isConnecting=!0,this.conn=this.wsConnect();let i=await this.conn;this.isConnecting=!1,await this.wsSendMessage(i,this.context,!0),this.debug(`${r}: reconnection successful`)}catch(i){this.isConnecting=!1,this.debug(`${r}: reconnection failed:`,i)}}else this.debug(`${r}: no context set, skipping reconnection`);return Promise.resolve()};cleanup=async()=>{if(this.isOffline())return this.debug("cleanup: skipped (offline mode)"),Promise.resolve();if(this.wsIntentionalDisconnect=!0,this.wsReconnectTimer!==null&&(clearTimeout(this.wsReconnectTimer),this.wsReconnectTimer=null),this.stopRetryTimer(),this.conn)try{let e=await this.conn;this.currentWebSocket===e&&(this.debug("Cleaning up current websocket tracking"),this.currentWebSocket=null),e.close()}catch(e){console.warn("Error during cleanup:",e)}finally{this.conn=null,this.currentWebSocket=null,this.isConnecting=!1}};calculateReconnectDelay=()=>{let e=this.webSocketInitialRetryDelay*Math.pow(2,this.wsReconnectAttempts),t=Math.min(e,this.webSocketMaxRetryDelay),r=Math.random()*t*.5,i=t+r;return this.debug(`Reconnect delay calculated: ${i.toFixed(0)}ms (attempt ${this.wsReconnectAttempts+1}/${this.webSocketMaxReconnectAttempts})`),i};handleNetworkOffline=async()=>{if(this.conn!==null){try{let e=await this.conn;this.currentWebSocket===e&&(this.currentWebSocket=null),(e.readyState===WebSocket.OPEN||e.readyState===WebSocket.CONNECTING)&&e.close()}catch(e){this.debug("Error closing connection on offline:",e)}this.conn=null}this.wsReconnectTimer!==null&&(clearTimeout(this.wsReconnectTimer),this.wsReconnectTimer=null)};handleNetworkOnline=()=>{this.debug("Network online, attempting reconnection and flushing queued events"),this.wsReconnectAttempts=0,this.wsReconnectTimer!==null&&(clearTimeout(this.wsReconnectTimer),this.wsReconnectTimer=null),this.flushEventQueue().catch(e=>{this.debug("Error flushing event queue on network online:",e)}),this.attemptReconnect()};attemptReconnect=()=>{if(this.wsReconnectAttempts>=this.webSocketMaxReconnectAttempts){this.debug(`Maximum reconnection attempts (${this.webSocketMaxReconnectAttempts}) reached, giving up`);return}if(this.wsReconnectTimer!==null){this.debug("Reconnection attempt already scheduled, ignoring duplicate request");return}let e=this.calculateReconnectDelay();this.debug(`Scheduling reconnection attempt ${this.wsReconnectAttempts+1}/${this.webSocketMaxReconnectAttempts} in ${e.toFixed(0)}ms`),this.wsReconnectTimer=setTimeout(async()=>{this.wsReconnectTimer=null,this.wsReconnectAttempts++,this.debug(`Attempting to reconnect (attempt ${this.wsReconnectAttempts}/${this.webSocketMaxReconnectAttempts})`);try{if(this.conn!==null){this.debug("Cleaning up existing connection before reconnection");try{let t=await this.conn;this.currentWebSocket===t&&(this.debug("Existing websocket is current, will be replaced"),this.currentWebSocket=null),(t.readyState===WebSocket.OPEN||t.readyState===WebSocket.CONNECTING)&&t.close()}catch(t){this.debug("Error cleaning up existing connection:",t)}this.conn=null,this.currentWebSocket=null,this.isConnecting=!1}this.isConnecting=!0;try{this.conn=this.wsConnect();let t=await this.conn;this.isConnecting=!1,this.debug("Reconnection context check:",{hasCompany:this.context.company!==void 0,hasUser:this.context.user!==void 0,context:this.context}),this.context.company!==void 0||this.context.user!==void 0?(this.debug("Reconnected, force re-sending context"),await this.wsSendMessage(t,this.context,!0)):(this.debug("No context to re-send after reconnection - websocket ready for new context"),this.debug("Setting up tracking for reconnected websocket (no context to send)"),this.currentWebSocket=t),this.flushEventQueue().catch(r=>{this.debug("Error flushing event queue after websocket reconnection:",r)}),this.debug("Reconnection successful")}catch(t){throw this.isConnecting=!1,t}}catch(t){this.debug("Reconnection attempt failed:",t)}},e)};wsConnect=async()=>{if(this.isOffline())throw this.debug("wsConnect: skipped (offline mode)"),new Error("WebSocket connection skipped in offline mode");let e=null,t=this.webSocketMaxConnectionAttempts;for(let r=0;r<t;r++)try{let i=await this.wsConnectOnce();return this.wsReconnectAttempts=0,i}catch(i){if(e=i instanceof Error?i:new Error(String(i)),!(e.message==="WebSocket connection timeout"))throw this.debug("WebSocket connection failed with non-timeout error, not retrying:",e.message),e;if(r<t-1){let d=this.webSocketInitialRetryDelay*Math.pow(2,r),s=Math.min(d,this.webSocketMaxRetryDelay),p=s*.2*Math.random(),c=s+p;this.debug(`WebSocket connection timeout (attempt ${r+1}/${t}), retrying in ${c.toFixed(0)}ms`),await new Promise(y=>setTimeout(y,c))}else this.debug(`WebSocket connection timeout (attempt ${r+1}/${t}), no more retries`)}throw e??new Error("WebSocket connection failed")};wsConnectOnce=()=>new Promise((e,t)=>{let r=`${this.webSocketUrl}/flags/bootstrap?apiKey=${this.apiKey}`;this.debug("connecting to WebSocket:",r);let i=new WebSocket(r),a=Math.random().toString(36).substring(7);this.debug(`Creating WebSocket connection ${a} to ${r}`);let d=null,s=!1,p=!1;d=setTimeout(()=>{s||(s=!0,this.debug(`WebSocket connection timeout after ${this.webSocketConnectionTimeout}ms`),i.close(),t(new Error("WebSocket connection timeout")))},this.webSocketConnectionTimeout),i.onopen=()=>{s||(s=!0,p=!0,d!==null&&clearTimeout(d),this.wsIntentionalDisconnect=!1,this.debug(`WebSocket connection ${a} opened successfully`),e(i))},i.onerror=c=>{if(s)return;s=!0,d!==null&&clearTimeout(d),this.debug(`WebSocket connection ${a} error:`,c);let y=new Error("WebSocket connection failed during handshake");t(y)},i.onclose=()=>{d!==null&&clearTimeout(d),this.debug(`WebSocket connection ${a} closed`),this.conn=null;let c=this.currentWebSocket===i;this.currentWebSocket===i&&(this.currentWebSocket=null,this.isConnecting=!1),c&&p&&!this.wsIntentionalDisconnect&&this.webSocketReconnect&&this.attemptReconnect()}});wsSendMessage=(e,t,r=!1)=>this.isOffline()?(this.debug("wsSendMessage: skipped (offline mode)"),this.setIsPending(!1),Promise.resolve()):new Promise((i,a)=>{if(!r&&h(t)==h(this.context))return this.debug("WebSocket context unchanged, skipping update"),i(this.setIsPending(!1));this.debug(r?"WebSocket force sending context (reconnection):":"WebSocket context updated:",t),this.context=t;let d=()=>{let s=!1,p=this.createPersistentMessageHandler(t),c=_=>{p(_),s||(s=!0,i())};e.addEventListener("message",c),e.addEventListener("close",_=>{s||(s=!0,_.code===4001?a(new Error(`Authentication failed: ${_.reason!==""?_.reason:"Invalid API key"}`)):a(new Error("WebSocket connection closed unexpectedly")))}),this.currentWebSocket=e;let y=this._additionalHeaders["X-Schematic-Client-Version"]??`schematic-js@${he}`,u={apiKey:this.apiKey,clientVersion:y,data:t};this.debug("WebSocket sending message:",u),e.send(JSON.stringify(u))};e.readyState===WebSocket.OPEN?(this.debug("WebSocket already open, sending message"),d()):e.readyState===WebSocket.CONNECTING?(this.debug("WebSocket connecting, waiting for open to send message"),e.addEventListener("open",d)):(this.debug("WebSocket is closed, cannot send message"),a("WebSocket is not open or connecting"))});getIsPending=()=>this.isPending;addIsPendingListener=e=>(this.isPendingListeners.add(e),()=>{this.isPendingListeners.delete(e)});setIsPending=e=>{this.isPending!==e&&(this.isPending=e,this.isPendingListeners.forEach(t=>qn(t,e)))};getPlan=()=>{let e=h(this.context);return this.planChecks[e]};getCreditBalances=()=>{let e=h(this.context);return this.creditBalances[e]??Ln};getCreditBalance=e=>{let t=h(this.context);return this.creditBalances[t]?.[e]};getFlagCheck=e=>{let t=h(this.context),i=(this.checks[t]??{})[e];if(i!==void 0)return i;if(e in this.flagCheckDefaults||e in this.flagValueDefaults)return e in this.fallbackCheckCache||(this.fallbackCheckCache[e]=this.resolveFallbackCheckFlagReturn(e,void 0,"Default value used")),this.fallbackCheckCache[e]};getFlagValue=e=>{let t=h(this.context),i=(this.checks[t]??{})[e];if(i?.value!==void 0)return i.value;if(e in this.flagCheckDefaults||e in this.flagValueDefaults)return this.resolveFallbackValue(e)};addFlagValueListener=(e,t)=>(e in this.flagValueListeners||(this.flagValueListeners[e]=new Set),this.flagValueListeners[e].add(t),()=>{this.flagValueListeners[e].delete(t)});addFlagCheckListener=(e,t)=>(e in this.flagCheckListeners||(this.flagCheckListeners[e]=new Set),this.flagCheckListeners[e].add(t),()=>{this.flagCheckListeners[e].delete(t)});addPlanListener=e=>(this.planListeners.add(e),()=>{this.planListeners.delete(e)});addCreditBalanceListener=e=>(this.creditBalanceListeners.add(e),()=>{this.creditBalanceListeners.delete(e)});notifyFlagCheckListeners=(e,t)=>{let r=this.flagCheckListeners?.[e]??[];r.size>0&&this.debug(`Notifying ${r.size} flag check listeners for ${e}`,t),typeof t.featureUsageEvent=="string"&&this.updateFeatureUsageEventMap(t),r.forEach(i=>Wn(i,t))};updateFeatureUsageEventMap=e=>{if(typeof e.featureUsageEvent!="string")return;let t=e.featureUsageEvent;(this.featureUsageEventMap[t]===void 0||this.featureUsageEventMap[t]===null)&&(this.featureUsageEventMap[t]={}),this.featureUsageEventMap[t]!==void 0&&(this.featureUsageEventMap[t][e.flag]=e),this.debug(`Updated featureUsageEventMap for event: ${t}, flag: ${e.flag}`,e)};notifyFlagValueListeners=(e,t)=>{let r=this.flagValueListeners?.[e]??[];r.size>0&&this.debug(`Notifying ${r.size} flag value listeners for ${e}`,{value:t}),r.forEach((i,a)=>{this.debug(`Calling listener ${a} for flag ${e}`,{flagKey:e,value:t}),$n(i,t),this.debug(`Listener ${a} for flag ${e} completed`,{flagKey:e,value:t})})};notifyPlanListeners=e=>{let t=this.planListeners??[];t.size>0&&this.debug(`Notifying ${t.size} plan listeners`,{value:e}),t.forEach((r,i)=>{this.debug(`Calling listener ${i} for plan`,{value:e}),Hn(r,e),this.debug(`Listener ${i} for plan completed`,{value:e})})};notifyCreditBalanceListeners=e=>{let t=this.creditBalanceListeners??[];t.size>0&&this.debug(`Notifying ${t.size} credit balance listeners`,{value:e}),t.forEach(r=>Qn(r,e))}},qn=(n,e)=>{n.length>0?n(e):n()},Wn=(n,e)=>{n.length>0?n(e):n()},$n=(n,e)=>{n.length>0?n(e):n()},Hn=(n,e)=>{n.length>0?n(e):n()},Qn=(n,e)=>{n.length>0?n(e):n()};window.Schematic=te;})();
3
3
  /* @preserve */
@@ -1223,7 +1223,7 @@ function contextString(context) {
1223
1223
  }
1224
1224
 
1225
1225
  // src/version.ts
1226
- var version = "1.6.0";
1226
+ var version = "1.7.0";
1227
1227
 
1228
1228
  // src/billing/api/generated/models/index.ts
1229
1229
  var models_exports = {};
@@ -1815,9 +1815,9 @@ var flagStateCacheMaxContexts = 10;
1815
1815
  var flagStateCacheDefaultMaxAgeMs = 7 * 24 * 60 * 60 * 1e3;
1816
1816
  var emptyCreditBalances = Object.freeze({});
1817
1817
  var Schematic = class {
1818
- additionalHeaders = {};
1818
+ _additionalHeaders = {};
1819
1819
  apiKey;
1820
- apiUrl = "https://api.schematichq.com";
1820
+ _apiUrl = "https://api.schematichq.com";
1821
1821
  conn = null;
1822
1822
  context = {};
1823
1823
  debugEnabled = false;
@@ -1897,7 +1897,7 @@ var Schematic = class {
1897
1897
  if (this.offlineEnabled) {
1898
1898
  this.setIsPending(false);
1899
1899
  }
1900
- this.additionalHeaders = {
1900
+ this._additionalHeaders = {
1901
1901
  "X-Schematic-Client-Version": `schematic-js@${version}`,
1902
1902
  ...options?.additionalHeaders ?? {}
1903
1903
  };
@@ -1913,7 +1913,7 @@ var Schematic = class {
1913
1913
  }
1914
1914
  this.hydrateFlagStateFromCache();
1915
1915
  if (options?.apiUrl !== void 0) {
1916
- this.apiUrl = options.apiUrl;
1916
+ this._apiUrl = options.apiUrl;
1917
1917
  }
1918
1918
  if (options?.eventUrl !== void 0) {
1919
1919
  this.eventUrl = options.eventUrl;
@@ -1978,6 +1978,12 @@ var Schematic = class {
1978
1978
  this.debug("Initialized with debug mode enabled");
1979
1979
  }
1980
1980
  }
1981
+ get apiUrl() {
1982
+ return this._apiUrl;
1983
+ }
1984
+ get additionalHeaders() {
1985
+ return { ...this._additionalHeaders };
1986
+ }
1981
1987
  /**
1982
1988
  * Resolve fallback value according to priority order:
1983
1989
  * 1. Callsite fallback value (if provided)
@@ -2063,11 +2069,11 @@ var Schematic = class {
2063
2069
  return resolvedFallbackResult.value;
2064
2070
  }
2065
2071
  if (!this.useWebSocket) {
2066
- const requestUrl = `${this.apiUrl}/flags/${key}/check`;
2072
+ const requestUrl = `${this._apiUrl}/flags/${key}/check`;
2067
2073
  return fetch(requestUrl, {
2068
2074
  method: "POST",
2069
2075
  headers: {
2070
- ...this.additionalHeaders ?? {},
2076
+ ...this._additionalHeaders ?? {},
2071
2077
  "Content-Type": "application/json;charset=UTF-8",
2072
2078
  "X-Schematic-Api-Key": this.apiKey
2073
2079
  },
@@ -2270,12 +2276,12 @@ var Schematic = class {
2270
2276
  this.debug(`checkFlags offline result: returning empty object`);
2271
2277
  return {};
2272
2278
  }
2273
- const requestUrl = `${this.apiUrl}/flags/check`;
2279
+ const requestUrl = `${this._apiUrl}/flags/check`;
2274
2280
  const requestBody = JSON.stringify(context);
2275
2281
  return fetch(requestUrl, {
2276
2282
  method: "POST",
2277
2283
  headers: {
2278
- ...this.additionalHeaders ?? {},
2284
+ ...this._additionalHeaders ?? {},
2279
2285
  "Content-Type": "application/json;charset=UTF-8",
2280
2286
  "X-Schematic-Api-Key": this.apiKey
2281
2287
  },
@@ -2822,7 +2828,7 @@ var Schematic = class {
2822
2828
  const response = await fetch(captureUrl, {
2823
2829
  method: "POST",
2824
2830
  headers: {
2825
- ...this.additionalHeaders ?? {},
2831
+ ...this._additionalHeaders ?? {},
2826
2832
  "Content-Type": "application/json;charset=UTF-8"
2827
2833
  },
2828
2834
  body: payload
@@ -3318,7 +3324,7 @@ var Schematic = class {
3318
3324
  }
3319
3325
  });
3320
3326
  this.currentWebSocket = socket;
3321
- const clientVersion = this.additionalHeaders["X-Schematic-Client-Version"] ?? `schematic-js@${version}`;
3327
+ const clientVersion = this._additionalHeaders["X-Schematic-Client-Version"] ?? `schematic-js@${version}`;
3322
3328
  const messagePayload = {
3323
3329
  apiKey: this.apiKey,
3324
3330
  clientVersion,
@@ -1084,9 +1084,9 @@ declare const RuleType_2: {
1084
1084
  declare type RuleType_2 = (typeof RuleType_2)[keyof typeof RuleType_2];
1085
1085
 
1086
1086
  export declare class Schematic {
1087
- private additionalHeaders;
1087
+ private _additionalHeaders;
1088
1088
  private apiKey;
1089
- private apiUrl;
1089
+ private _apiUrl;
1090
1090
  private conn;
1091
1091
  private context;
1092
1092
  private debugEnabled;
@@ -1131,6 +1131,8 @@ export declare class Schematic {
1131
1131
  private flagCheckDefaults;
1132
1132
  private fallbackCheckCache;
1133
1133
  constructor(apiKey: string, options?: SchematicOptions);
1134
+ get apiUrl(): string;
1135
+ get additionalHeaders(): Record<string, string>;
1134
1136
  /**
1135
1137
  * Resolve fallback value according to priority order:
1136
1138
  * 1. Callsite fallback value (if provided)
@@ -1192,7 +1192,7 @@ function contextString(context) {
1192
1192
  }
1193
1193
 
1194
1194
  // src/version.ts
1195
- var version = "1.6.0";
1195
+ var version = "1.7.0";
1196
1196
 
1197
1197
  // src/billing/api/generated/models/index.ts
1198
1198
  var models_exports = {};
@@ -1784,9 +1784,9 @@ var flagStateCacheMaxContexts = 10;
1784
1784
  var flagStateCacheDefaultMaxAgeMs = 7 * 24 * 60 * 60 * 1e3;
1785
1785
  var emptyCreditBalances = Object.freeze({});
1786
1786
  var Schematic = class {
1787
- additionalHeaders = {};
1787
+ _additionalHeaders = {};
1788
1788
  apiKey;
1789
- apiUrl = "https://api.schematichq.com";
1789
+ _apiUrl = "https://api.schematichq.com";
1790
1790
  conn = null;
1791
1791
  context = {};
1792
1792
  debugEnabled = false;
@@ -1866,7 +1866,7 @@ var Schematic = class {
1866
1866
  if (this.offlineEnabled) {
1867
1867
  this.setIsPending(false);
1868
1868
  }
1869
- this.additionalHeaders = {
1869
+ this._additionalHeaders = {
1870
1870
  "X-Schematic-Client-Version": `schematic-js@${version}`,
1871
1871
  ...options?.additionalHeaders ?? {}
1872
1872
  };
@@ -1882,7 +1882,7 @@ var Schematic = class {
1882
1882
  }
1883
1883
  this.hydrateFlagStateFromCache();
1884
1884
  if (options?.apiUrl !== void 0) {
1885
- this.apiUrl = options.apiUrl;
1885
+ this._apiUrl = options.apiUrl;
1886
1886
  }
1887
1887
  if (options?.eventUrl !== void 0) {
1888
1888
  this.eventUrl = options.eventUrl;
@@ -1947,6 +1947,12 @@ var Schematic = class {
1947
1947
  this.debug("Initialized with debug mode enabled");
1948
1948
  }
1949
1949
  }
1950
+ get apiUrl() {
1951
+ return this._apiUrl;
1952
+ }
1953
+ get additionalHeaders() {
1954
+ return { ...this._additionalHeaders };
1955
+ }
1950
1956
  /**
1951
1957
  * Resolve fallback value according to priority order:
1952
1958
  * 1. Callsite fallback value (if provided)
@@ -2032,11 +2038,11 @@ var Schematic = class {
2032
2038
  return resolvedFallbackResult.value;
2033
2039
  }
2034
2040
  if (!this.useWebSocket) {
2035
- const requestUrl = `${this.apiUrl}/flags/${key}/check`;
2041
+ const requestUrl = `${this._apiUrl}/flags/${key}/check`;
2036
2042
  return fetch(requestUrl, {
2037
2043
  method: "POST",
2038
2044
  headers: {
2039
- ...this.additionalHeaders ?? {},
2045
+ ...this._additionalHeaders ?? {},
2040
2046
  "Content-Type": "application/json;charset=UTF-8",
2041
2047
  "X-Schematic-Api-Key": this.apiKey
2042
2048
  },
@@ -2239,12 +2245,12 @@ var Schematic = class {
2239
2245
  this.debug(`checkFlags offline result: returning empty object`);
2240
2246
  return {};
2241
2247
  }
2242
- const requestUrl = `${this.apiUrl}/flags/check`;
2248
+ const requestUrl = `${this._apiUrl}/flags/check`;
2243
2249
  const requestBody = JSON.stringify(context);
2244
2250
  return fetch(requestUrl, {
2245
2251
  method: "POST",
2246
2252
  headers: {
2247
- ...this.additionalHeaders ?? {},
2253
+ ...this._additionalHeaders ?? {},
2248
2254
  "Content-Type": "application/json;charset=UTF-8",
2249
2255
  "X-Schematic-Api-Key": this.apiKey
2250
2256
  },
@@ -2791,7 +2797,7 @@ var Schematic = class {
2791
2797
  const response = await fetch(captureUrl, {
2792
2798
  method: "POST",
2793
2799
  headers: {
2794
- ...this.additionalHeaders ?? {},
2800
+ ...this._additionalHeaders ?? {},
2795
2801
  "Content-Type": "application/json;charset=UTF-8"
2796
2802
  },
2797
2803
  body: payload
@@ -3287,7 +3293,7 @@ var Schematic = class {
3287
3293
  }
3288
3294
  });
3289
3295
  this.currentWebSocket = socket;
3290
- const clientVersion = this.additionalHeaders["X-Schematic-Client-Version"] ?? `schematic-js@${version}`;
3296
+ const clientVersion = this._additionalHeaders["X-Schematic-Client-Version"] ?? `schematic-js@${version}`;
3291
3297
  const messagePayload = {
3292
3298
  apiKey: this.apiKey,
3293
3299
  clientVersion,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@schematichq/schematic-js",
3
- "version": "1.6.0",
3
+ "version": "1.7.0",
4
4
  "main": "dist/schematic.cjs.js",
5
5
  "module": "dist/schematic.esm.js",
6
6
  "types": "dist/schematic.d.ts",
@@ -42,7 +42,7 @@
42
42
  "@eslint/js": "^10.0.1",
43
43
  "@microsoft/api-extractor": "^7.59.0",
44
44
  "@openapitools/openapi-generator-cli": "^2.41.0",
45
- "@types/node": "^26.4.0",
45
+ "@types/node": "^26.5.0",
46
46
  "@vitest/browser": "^5.0.0",
47
47
  "esbuild": "^0.28.2",
48
48
  "eslint": "^10.10.0",
@@ -54,7 +54,7 @@
54
54
  "mock-socket": "^9.3.1",
55
55
  "prettier": "^3.9.6",
56
56
  "typescript": "^6.0.3",
57
- "typescript-eslint": "^8.69.0",
57
+ "typescript-eslint": "^8.70.0",
58
58
  "vitest": "^5.0.0"
59
59
  },
60
60
  "packageManager": "pnpm@11.9.0+sha512.bd682d5d03fe525ef7c9fd6780c6884d1e756ac4c9c9fe00c538782824310dcf90e3ddc4f53835f06dfaebd5085e41855e0bcbb3b60de2ac5bbab89e5036f03b"