@schematichq/schematic-js 1.3.1 → 1.4.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 ve=Object.create;var ie=Object.defineProperty;var qe=Object.getOwnPropertyDescriptor;var We=Object.getOwnPropertyNames;var $e=Object.getPrototypeOf,ze=Object.prototype.hasOwnProperty;var He=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var Qe=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of We(e))!ze.call(n,r)&&r!==t&&ie(n,r,{get:()=>e[r],enumerable:!(i=qe(e,r))||i.enumerable});return n};var Ke=(n,e,t)=>(t=n!=null?ve($e(n)):{},Qe(e||!n||!n.__esModule?ie(t,"default",{value:n,enumerable:!0}):t,n));var se=He(oe=>{(function(n){var e=(function(t){var i=typeof globalThis<"u"&&globalThis||typeof n<"u"&&n||typeof global<"u"&&global||{},r={searchParams:"URLSearchParams"in i,iterable:"Symbol"in i&&"iterator"in Symbol,blob:"FileReader"in i&&"Blob"in i&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in i,arrayBuffer:"ArrayBuffer"in i};function l(a){return a&&DataView.prototype.isPrototypeOf(a)}if(r.arrayBuffer)var s=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],p=ArrayBuffer.isView||function(a){return a&&s.indexOf(Object.prototype.toString.call(a))>-1};function u(a){if(typeof a!="string"&&(a=String(a)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(a)||a==="")throw new TypeError('Invalid character in header field name: "'+a+'"');return a.toLowerCase()}function f(a){return typeof a!="string"&&(a=String(a)),a}function P(a){var o={next:function(){var d=a.shift();return{done:d===void 0,value:d}}};return r.iterable&&(o[Symbol.iterator]=function(){return o}),o}function y(a){this.map={},a instanceof y?a.forEach(function(o,d){this.append(d,o)},this):Array.isArray(a)?a.forEach(function(o){if(o.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+o.length);this.append(o[0],o[1])},this):a&&Object.getOwnPropertyNames(a).forEach(function(o){this.append(o,a[o])},this)}y.prototype.append=function(a,o){a=u(a),o=f(o);var d=this.map[a];this.map[a]=d?d+", "+o:o},y.prototype.delete=function(a){delete this.map[u(a)]},y.prototype.get=function(a){return a=u(a),this.has(a)?this.map[a]:null},y.prototype.has=function(a){return this.map.hasOwnProperty(u(a))},y.prototype.set=function(a,o){this.map[u(a)]=f(o)},y.prototype.forEach=function(a,o){for(var d in this.map)this.map.hasOwnProperty(d)&&a.call(o,this.map[d],d,this)},y.prototype.keys=function(){var a=[];return this.forEach(function(o,d){a.push(d)}),P(a)},y.prototype.values=function(){var a=[];return this.forEach(function(o){a.push(o)}),P(a)},y.prototype.entries=function(){var a=[];return this.forEach(function(o,d){a.push([d,o])}),P(a)},r.iterable&&(y.prototype[Symbol.iterator]=y.prototype.entries);function D(a){if(!a._noBody){if(a.bodyUsed)return Promise.reject(new TypeError("Already read"));a.bodyUsed=!0}}function N(a){return new Promise(function(o,d){a.onload=function(){o(a.result)},a.onerror=function(){d(a.error)}})}function E(a){var o=new FileReader,d=N(o);return o.readAsArrayBuffer(a),d}function ee(a){var o=new FileReader,d=N(o),m=/charset=([A-Za-z0-9_-]+)/.exec(a.type),g=m?m[1]:"utf-8";return o.readAsText(a,g),d}function we(a){for(var o=new Uint8Array(a),d=new Array(o.length),m=0;m<o.length;m++)d[m]=String.fromCharCode(o[m]);return d.join("")}function te(a){if(a.slice)return a.slice(0);var o=new Uint8Array(a.byteLength);return o.set(new Uint8Array(a)),o.buffer}function ne(){return this.bodyUsed=!1,this._initBody=function(a){this.bodyUsed=this.bodyUsed,this._bodyInit=a,a?typeof a=="string"?this._bodyText=a:r.blob&&Blob.prototype.isPrototypeOf(a)?this._bodyBlob=a:r.formData&&FormData.prototype.isPrototypeOf(a)?this._bodyFormData=a:r.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)?this._bodyText=a.toString():r.arrayBuffer&&r.blob&&l(a)?(this._bodyArrayBuffer=te(a.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):r.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(a)||p(a))?this._bodyArrayBuffer=te(a):this._bodyText=a=Object.prototype.toString.call(a):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof a=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):r.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},r.blob&&(this.blob=function(){var a=D(this);if(a)return a;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 a=D(this);return a||(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(r.blob)return this.blob().then(E);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var a=D(this);if(a)return a;if(this._bodyBlob)return ee(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(we(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},r.formData&&(this.formData=function(){return this.text().then(Ge)}),this.json=function(){return this.text().then(JSON.parse)},this}var Ve=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function Ue(a){var o=a.toUpperCase();return Ve.indexOf(o)>-1?o:a}function _(a,o){if(!(this instanceof _))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');o=o||{};var d=o.body;if(a instanceof _){if(a.bodyUsed)throw new TypeError("Already read");this.url=a.url,this.credentials=a.credentials,o.headers||(this.headers=new y(a.headers)),this.method=a.method,this.mode=a.mode,this.signal=a.signal,!d&&a._bodyInit!=null&&(d=a._bodyInit,a.bodyUsed=!0)}else this.url=String(a);if(this.credentials=o.credentials||this.credentials||"same-origin",(o.headers||!this.headers)&&(this.headers=new y(o.headers)),this.method=Ue(o.method||this.method||"GET"),this.mode=o.mode||this.mode||null,this.signal=o.signal||this.signal||(function(){if("AbortController"in i){var c=new AbortController;return c.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&d)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(d),(this.method==="GET"||this.method==="HEAD")&&(o.cache==="no-store"||o.cache==="no-cache")){var m=/([?&])_=[^&]*/;if(m.test(this.url))this.url=this.url.replace(m,"$1_="+new Date().getTime());else{var g=/\?/;this.url+=(g.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}_.prototype.clone=function(){return new _(this,{body:this._bodyInit})};function Ge(a){var o=new FormData;return a.trim().split("&").forEach(function(d){if(d){var m=d.split("="),g=m.shift().replace(/\+/g," "),c=m.join("=").replace(/\+/g," ");o.append(decodeURIComponent(g),decodeURIComponent(c))}}),o}function Le(a){var o=new y,d=a.replace(/\r?\n[\t ]+/g," ");return d.split("\r").map(function(m){return m.indexOf(`
2
- `)===0?m.substr(1,m.length):m}).forEach(function(m){var g=m.split(":"),c=g.shift().trim();if(c){var J=g.join(":").trim();try{o.append(c,J)}catch(v){console.warn("Response "+v.message)}}}),o}ne.call(_.prototype);function R(a,o){if(!(this instanceof R))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(o||(o={}),this.type="default",this.status=o.status===void 0?200:o.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=o.statusText===void 0?"":""+o.statusText,this.headers=new y(o.headers),this.url=o.url||"",this._initBody(a)}ne.call(R.prototype),R.prototype.clone=function(){return new R(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new y(this.headers),url:this.url})},R.error=function(){var a=new R(null,{status:200,statusText:""});return a.ok=!1,a.status=0,a.type="error",a};var Me=[301,302,303,307,308];R.redirect=function(a,o){if(Me.indexOf(o)===-1)throw new RangeError("Invalid status code");return new R(null,{status:o,headers:{location:a}})},t.DOMException=i.DOMException;try{new t.DOMException}catch{t.DOMException=function(o,d){this.message=o,this.name=d;var m=Error(o);this.stack=m.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function M(a,o){return new Promise(function(d,m){var g=new _(a,o);if(g.signal&&g.signal.aborted)return m(new t.DOMException("Aborted","AbortError"));var c=new XMLHttpRequest;function J(){c.abort()}c.onload=function(){var T={statusText:c.statusText,headers:Le(c.getAllResponseHeaders()||"")};g.url.indexOf("file://")===0&&(c.status<200||c.status>599)?T.status=200:T.status=c.status,T.url="responseURL"in c?c.responseURL:T.headers.get("X-Request-URL");var O="response"in c?c.response:c.responseText;setTimeout(function(){d(new R(O,T))},0)},c.onerror=function(){setTimeout(function(){m(new TypeError("Network request failed"))},0)},c.ontimeout=function(){setTimeout(function(){m(new TypeError("Network request timed out"))},0)},c.onabort=function(){setTimeout(function(){m(new t.DOMException("Aborted","AbortError"))},0)};function v(T){try{return T===""&&i.location.href?i.location.href:T}catch{return T}}if(c.open(g.method,v(g.url),!0),g.credentials==="include"?c.withCredentials=!0:g.credentials==="omit"&&(c.withCredentials=!1),"responseType"in c&&(r.blob?c.responseType="blob":r.arrayBuffer&&(c.responseType="arraybuffer")),o&&typeof o.headers=="object"&&!(o.headers instanceof y||i.Headers&&o.headers instanceof i.Headers)){var re=[];Object.getOwnPropertyNames(o.headers).forEach(function(T){re.push(u(T)),c.setRequestHeader(T,f(o.headers[T]))}),g.headers.forEach(function(T,O){re.indexOf(O)===-1&&c.setRequestHeader(O,T)})}else g.headers.forEach(function(T,O){c.setRequestHeader(O,T)});g.signal&&(g.signal.addEventListener("abort",J),c.onreadystatechange=function(){c.readyState===4&&g.signal.removeEventListener("abort",J)}),c.send(typeof g._bodyInit>"u"?null:g._bodyInit)})}return M.polyfill=!0,i.fetch||(i.fetch=M,i.Headers=y,i.Request=_,i.Response=R),t.Headers=y,t.Request=_,t.Response=R,t.fetch=M,t})({})})(typeof self<"u"?self:oe)});var h=[];for(let n=0;n<256;++n)h.push((n+256).toString(16).slice(1));function ae(n,e=0){return(h[n[e+0]]+h[n[e+1]]+h[n[e+2]]+h[n[e+3]]+"-"+h[n[e+4]]+h[n[e+5]]+"-"+h[n[e+6]]+h[n[e+7]]+"-"+h[n[e+8]]+h[n[e+9]]+"-"+h[n[e+10]]+h[n[e+11]]+h[n[e+12]]+h[n[e+13]]+h[n[e+14]]+h[n[e+15]]).toLowerCase()}var q,Xe=new Uint8Array(16);function W(){if(!q){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");q=crypto.getRandomValues.bind(crypto)}return q(Xe)}var Ye=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),$={randomUUID:Ye};function Ze(n,e,t){n=n||{};let i=n.random??n.rng?.()??W();if(i.length<16)throw new Error("Random bytes length must be >= 16");if(i[6]=i[6]&15|64,i[8]=i[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 r=0;r<16;++r)e[t+r]=i[r];return e}return ae(i)}function je(n,e,t){return $.randomUUID&&!e&&!n?$.randomUUID():Ze(n,e,t)}var C=je;var Tm=Ke(se());function Q(n){return Dt(n,!1)}function Dt(n,e){return n}function ge(n){return Rt(n,!1)}function Rt(n,e){return n==null?n:{allocation:n.allocation==null?void 0:n.allocation,creditId:n.credit_id==null?void 0:n.credit_id,creditRemaining:n.credit_remaining==null?void 0:n.credit_remaining,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,featureId:n.feature_id,featureKey:n.feature_key,metricPeriod:n.metric_period==null?void 0:n.metric_period,metricResetAt:n.metric_reset_at==null?void 0:new Date(n.metric_reset_at),monthReset:n.month_reset==null?void 0:n.month_reset,softLimit:n.soft_limit==null?void 0:n.soft_limit,usage:n.usage==null?void 0:n.usage,valueType:Q(n.value_type)}}function B(n){return _t(n,!1)}function _t(n,e){return n==null?n:{companyId:n.company_id==null?void 0:n.company_id,entitlement:n.entitlement==null?void 0:ge(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.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:n.rule_type,userId:n.user_id==null?void 0:n.user_id,value:n.value}}function K(n){return Ct(n,!1)}function Ct(n,e){return n==null?n:{data:B(n.data),params:n.params}}function Te(n){return bt(n,!1)}function bt(n,e){return n}function F(n){return xt(n,!1)}function xt(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:Te(n.trial_status)}}function X(n){return Bt(n,!1)}function Bt(n,e){return n==null?n:{flags:n.flags.map(B),plan:n.plan==null?void 0:F(n.plan)}}function Y(n){return Ft(n,!1)}function Ft(n,e){return n==null?n:{data:X(n.data),params:n.params}}function I(n){return Et(n,!1)}function Et(n,e=!1){return n==null?n:{company_id:n.companyId,error:n.error,flag_id:n.flagId,flag_key:n.flagKey,reason:n.reason,req_company:n.reqCompany,req_user:n.reqUser,rule_id:n.ruleId,user_id:n.userId,value:n.value}}var Z=n=>{let{companyId:e,error:t,featureAllocation:i,featureUsage:r,featureUsageEvent:l,featureUsagePeriod:s,featureUsageResetAt:p,flag:u,flagId:f,reason:P,ruleId:y,ruleType:D,userId:N,value:E}=B(n);return{featureUsageExceeded:!E&&(D=="company_override_usage_exceeded"||D=="plan_entitlement_usage_exceeded"),companyId:e??void 0,error:t??void 0,featureAllocation:i??void 0,featureUsage:r??void 0,featureUsageEvent:l===null?void 0:l,featureUsagePeriod:s??void 0,featureUsageResetAt:p??void 0,flag:u,flagId:f??void 0,reason:P,ruleId:y??void 0,ruleType:D??void 0,userId:N??void 0,value:E}},Ae=n=>{let{id:e,name:t,trialEndDate:i,trialStatus:r}=F(n);return{id:e,name:t,trialEndDate:i??void 0,trialStatus:r??void 0}};function S(n){let e=Object.keys(n).reduce((t,i)=>{let l=Object.keys(n[i]||{}).sort().reduce((s,p)=>(s[p]=n[i][p],s),{});return t[i]=l,t},{});return JSON.stringify(e)}var j="1.3.1";var Ie="schematicId";var L=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;storage;useWebSocket=!1;checks={};featureUsageEventMap={};planChecks={};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.eventQueue=[],this.contextDependentEventQueue=[],this.useWebSocket=t?.useWebSocket??!1,this.debugEnabled=t?.debug??!1,this.offlineEnabled=t?.offline??!1,typeof window<"u"&&typeof window.location<"u"){let i=new URLSearchParams(window.location.search),r=i.get("schematic_debug");r!==null&&(r===""||r==="true"||r==="1")&&(this.debugEnabled=!0);let l=i.get("schematic_offline");l!==null&&(l===""||l==="true"||l==="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@${j}`,...t?.additionalHeaders??{}},t?.storage)this.storage=t.storage;else try{typeof localStorage<"u"&&(this.storage=localStorage)}catch{}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,i="Fallback value used",r){if(t!==void 0)return{flag:e,value:t,reason:i,error:r};if(e in this.flagCheckDefaults){let l=this.flagCheckDefaults[e];return{...l,flag:e,reason:r!==void 0?i:l.reason,error:r}}return e in this.flagValueDefaults?{flag:e,value:this.flagValueDefaults[e],reason:i,error:r}:{flag:e,value:!1,reason:i,error:r}}async checkFlag(e){let{fallback:t,key:i}=e,r=e.context||this.context,l=S(r);if(this.debug(`checkFlag: ${i}`,{context:r,fallback:t}),this.isOffline()){let s=this.resolveFallbackCheckFlagReturn(i,t,"Offline mode - using initialization defaults");return this.debug(`checkFlag offline result: ${i}`,{value:s.value,offlineMode:!0}),s.value}if(!this.useWebSocket){let s=`${this.apiUrl}/flags/${i}/check`;return fetch(s,{method:"POST",headers:{...this.additionalHeaders??{},"Content-Type":"application/json;charset=UTF-8","X-Schematic-Api-Key":this.apiKey},body:JSON.stringify(r)}).then(p=>{if(!p.ok)throw new Error("Network response was not ok");return p.json()}).then(p=>{let u=K(p);this.debug(`checkFlag result: ${i}`,u);let f=Z(u.data);return typeof f.featureUsageEvent=="string"&&this.updateFeatureUsageEventMap(f),this.submitFlagCheckEvent(i,f,r),f.value}).catch(p=>{console.warn("There was a problem with the fetch operation:",p);let u=this.resolveFallbackCheckFlagReturn(i,t,"API request failed",p instanceof Error?p.message:String(p));return this.submitFlagCheckEvent(i,u,r),u.value})}try{let s=this.checks[l];if(this.conn!==null&&typeof s<"u"&&typeof s[i]<"u")return this.debug(`checkFlag cached result: ${i}`,s[i]),s[i].value;if(this.isOffline())return this.resolveFallbackValue(i,t);try{await this.setContext(r)}catch(P){console.warn("WebSocket connection failed, using fallback value:",P);let y=this.resolveFallbackCheckFlagReturn(i,t,"WebSocket connection failed",P instanceof Error?P.message:String(P));return this.submitFlagCheckEvent(i,y,r),y.value}let u=(this.checks[l]??{})[i],f=u?.value??this.resolveFallbackValue(i,t);if(this.debug(`checkFlag WebSocket result: ${i}`,typeof u<"u"?u:{value:f,fallbackUsed:!0}),typeof u<"u")this.submitFlagCheckEvent(i,u,r);else{let P=this.resolveFallbackCheckFlagReturn(i,t,"No flag values available");this.submitFlagCheckEvent(i,P,r)}return f}catch(s){console.error("Unexpected error in checkFlag:",s);let p=this.resolveFallbackCheckFlagReturn(i,t,"Unexpected error in flag check",s instanceof Error?s.message:String(s));return this.submitFlagCheckEvent(i,p,r),p.value}}debug(e,...t){this.debugEnabled&&console.log(`[Schematic] ${e}`,...t)}createPersistentMessageHandler(e){return t=>{let i=JSON.parse(t.data);if(this.debug("WebSocket persistent message received:",i),S(e)in this.checks||(this.checks[S(e)]={}),(i.flags??[]).forEach(r=>{let l=Z(r),s=S(e);this.checks[s]===void 0&&(this.checks[s]={}),this.checks[s][l.flag]=l,typeof l.featureUsageEvent=="string"&&this.updateFeatureUsageEventMap(l),((this.flagCheckListeners[r.flag]?.size??0)>0||(this.flagValueListeners[r.flag]?.size??0)>0)&&this.submitFlagCheckEvent(l.flag,l,e),this.debug(`WebSocket flag update received. Notifying listeners for ${r.flag}`,{flag:r.flag,value:l.value,flagCheck:l}),this.notifyFlagCheckListeners(r.flag,l),this.notifyFlagValueListeners(r.flag,l.value)}),i.plan!==void 0&&i.plan!==null){let r=Ae(i.plan),l=S(e);this.planChecks[l]=r,this.debug("WebSocket plan update received. Notifying listeners",{plan:r}),this.notifyPlanListeners(r)}this.flushContextDependentEventQueue(),this.setIsPending(!1)}}isOffline(){return this.offlineEnabled}submitFlagCheckEvent(e,t,i){let r={flagKey:e,value:t.value,reason:t.reason,flagId:t.flagId,ruleId:t.ruleId,companyId:t.companyId,userId:t.userId,error:t.error,reqCompany:i.company,reqUser:i.user};return this.debug("submitting flag check event:",r),this.handleEvent("flag_check",I(r))}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`,i=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:i}).then(r=>{if(!r.ok)throw new Error("Network response was not ok");return r.json()}).then(r=>{let l=Y(r);return this.debug("checkFlags result:",l),(l?.data?.flags??[]).reduce((s,p)=>(s[p.flag]=p.value,s),{})}).catch(r=>(console.warn("There was a problem with the fetch operation:",r),{}))};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(!(S(e)===S(this.context)&&this.conn!==null&&!this.isPending))try{if(this.setIsPending(!0),!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(i=>setTimeout(i,10));if(this.conn!==null){let i=await this.conn;await this.wsSendMessage(i,e);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 i=await this.conn;this.isConnecting=!1,await this.wsSendMessage(i,e);return}catch(i){throw this.isConnecting=!1,i}}let t=await this.conn;await this.wsSendMessage(t,e)}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:i,event:r,traits:l,quantity:s=1}=e;if(!this.hasContext(t,i)){this.debug(`track: queuing event "${r}" until context is available`);let u={api_key:this.apiKey,body:{company:t,event:r,traits:l??{},user:i,quantity:s},sent_at:new Date().toISOString(),tracker_event_id:C(),tracker_user_id:this.getAnonymousId(),type:"track"};return this.contextDependentEventQueue.push(u),Promise.resolve()}let p={company:t??this.context.company,event:r,traits:l??{},user:i??this.context.user,quantity:s};return this.debug("track:",p),r in this.featureUsageEventMap&&this.optimisticallyUpdateFeatureUsage(r,s),this.handleEvent("track",p)};optimisticallyUpdateFeatureUsage=(e,t=1)=>{let i=this.featureUsageEventMap[e];i!=null&&(this.debug(`Optimistically updating feature usage for event: ${e}`,{quantity:t}),Object.entries(i).forEach(([r,l])=>{if(l===void 0)return;let s={...l};if(typeof s.featureUsage=="number"){if(s.featureUsage+=t,typeof s.featureAllocation=="number"){let u=s.featureUsageExceeded===!0,f=s.featureUsage>=s.featureAllocation;f!==u&&(s.featureUsageExceeded=f,f&&(s.value=!1),this.debug(`Usage limit status changed for flag: ${r}`,{was:u?"exceeded":"within limits",now:f?"exceeded":"within limits",featureUsage:s.featureUsage,featureAllocation:s.featureAllocation,value:s.value}))}this.featureUsageEventMap[e]!==void 0&&(this.featureUsageEventMap[e][r]=s);let p=S(this.context);this.checks[p]!==void 0&&this.checks[p]!==null&&(this.checks[p][r]=s),this.notifyFlagCheckListeners(r,s),this.notifyFlagValueListeners(r,s.value)}}))};hasContext=(e,t)=>{let i=e!=null&&Object.keys(e).length>0||t!=null&&Object.keys(t).length>0,r=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 i||r};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,i={...t,company:t.company??this.context.company,user:t.user??this.context.user},r={...e,body:i,sent_at:new Date().toISOString()};this.sendEvent(r)}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=[],i=[];for(let r of this.eventQueue)r.next_retry_at===void 0||r.next_retry_at<=e?t.push(r):i.push(r);if(t.length===0){this.debug(`No events ready for retry yet (${i.length} still in backoff)`);return}this.debug(`Flushing event queue: ${t.length} ready, ${i.length} waiting`),this.eventQueue=i;for(let r of t)try{await this.sendEvent(r),this.debug("Queued event sent successfully:",r.type)}catch(l){this.debug("Failed to send queued event:",l)}};getAnonymousId=()=>{if(!this.storage)return C();let e=this.storage.getItem(Ie);if(typeof e<"u")return e;let t=C();return this.storage.setItem(Ie,t),t};handleEvent=(e,t)=>{let i={api_key:this.apiKey,body:t,sent_at:new Date().toISOString(),tracker_event_id:C(),tracker_user_id:this.getAnonymousId(),type:e};return typeof document<"u"&&document?.hidden?this.storeEvent(i):this.sendEvent(i)};sendEvent=async e=>{let t=`${this.eventUrl}/e`,i=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 r=await fetch(t,{method:"POST",headers:{...this.additionalHeaders??{},"Content-Type":"application/json;charset=UTF-8"},body:i});if(!r.ok)throw new Error(`HTTP ${r.status}: ${r.statusText}`);this.debug("event sent:",{status:r.status,statusText:r.statusText})}catch(r){let l=(e.retry_count??0)+1;if(l<=this.maxEventRetries){this.debug(`Event failed to send (attempt ${l}/${this.maxEventRetries}), queueing for retry:`,r);let s=this.eventRetryInitialDelay*Math.pow(2,l-1),p=Math.min(s,this.eventRetryMaxDelay),u=Date.now()+p,f={...e,retry_count:l,next_retry_at:u};this.eventQueue.length<this.maxEventQueueSize?(this.eventQueue.push(f),this.debug(`Event queued for retry in ${p}ms (${this.eventQueue.length}/${this.maxEventQueueSize})`)):(this.debug(`Event queue full (${this.maxEventQueueSize}), dropping oldest event`),this.eventQueue.shift(),this.eventQueue.push(f)),this.startRetryTimer()}else this.debug(`Event failed permanently after ${this.maxEventRetries} attempts, dropping:`,r)}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,i=t?"forceReconnect":"reconnectIfNeeded";if(this.isOffline())return this.debug(`${i}: skipped (offline mode)`),Promise.resolve();if(!t&&this.conn!==null)try{if((await this.conn).readyState===WebSocket.OPEN)return this.debug(`${i}: connection is healthy, skipping`),Promise.resolve()}catch{}if(this.debug(`${i}: ${t?"forcing immediate reconnection":"reconnecting"}`),this.wsIntentionalDisconnect=!1,this.wsReconnectTimer!==null&&(this.debug(`${i}: cancelling pending reconnection timer`),clearTimeout(this.wsReconnectTimer),this.wsReconnectTimer=null),this.wsReconnectAttempts=0,this.conn!==null){this.debug(`${i}: closing existing connection`);try{let r=await this.conn;this.currentWebSocket===r&&(this.currentWebSocket=null),(r.readyState===WebSocket.OPEN||r.readyState===WebSocket.CONNECTING)&&r.close()}catch(r){this.debug(`${i}: error closing existing connection:`,r)}this.conn=null,this.isConnecting=!1}if(this.context.company!==void 0||this.context.user!==void 0){this.debug(`${i}: reconnecting with existing context`);try{this.isConnecting=!0,this.conn=this.wsConnect();let r=await this.conn;this.isConnecting=!1,await this.wsSendMessage(r,this.context,!0),this.debug(`${i}: reconnection successful`)}catch(r){this.isConnecting=!1,this.debug(`${i}: reconnection failed:`,r)}}else this.debug(`${i}: 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),i=Math.random()*t*.5,r=t+i;return this.debug(`Reconnect delay calculated: ${r.toFixed(0)}ms (attempt ${this.wsReconnectAttempts+1}/${this.webSocketMaxReconnectAttempts})`),r};handleNetworkOffline=async()=>{if(this.conn!==null){try{let e=await this.conn;(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(i=>{this.debug("Error flushing event queue after websocket reconnection:",i)}),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 i=0;i<t;i++)try{let r=await this.wsConnectOnce();return this.wsReconnectAttempts=0,r}catch(r){if(e=r instanceof Error?r:new Error(String(r)),!(e.message==="WebSocket connection timeout"))throw this.debug("WebSocket connection failed with non-timeout error, not retrying:",e.message),e;if(i<t-1){let s=this.webSocketInitialRetryDelay*Math.pow(2,i),p=Math.min(s,this.webSocketMaxRetryDelay),u=p*.2*Math.random(),f=p+u;this.debug(`WebSocket connection timeout (attempt ${i+1}/${t}), retrying in ${f.toFixed(0)}ms`),await new Promise(P=>setTimeout(P,f))}else this.debug(`WebSocket connection timeout (attempt ${i+1}/${t}), no more retries`)}throw e??new Error("WebSocket connection failed")};wsConnectOnce=()=>new Promise((e,t)=>{let i=`${this.webSocketUrl}/flags/bootstrap?apiKey=${this.apiKey}`;this.debug("connecting to WebSocket:",i);let r=new WebSocket(i),l=Math.random().toString(36).substring(7);this.debug(`Creating WebSocket connection ${l} to ${i}`);let s=null,p=!1;s=setTimeout(()=>{p||(p=!0,this.debug(`WebSocket connection timeout after ${this.webSocketConnectionTimeout}ms`),r.close(),t(new Error("WebSocket connection timeout")))},this.webSocketConnectionTimeout),r.onopen=()=>{p||(p=!0,s!==null&&clearTimeout(s),this.wsIntentionalDisconnect=!1,this.debug(`WebSocket connection ${l} opened successfully`),e(r))},r.onerror=u=>{if(p)return;p=!0,s!==null&&clearTimeout(s),this.debug(`WebSocket connection ${l} error:`,u);let f=new Error("WebSocket connection failed during handshake");t(f)},r.onclose=()=>{s!==null&&clearTimeout(s),this.debug(`WebSocket connection ${l} closed`),this.conn=null,this.currentWebSocket===r&&(this.currentWebSocket=null,this.isConnecting=!1),!p&&!this.wsIntentionalDisconnect&&this.webSocketReconnect&&this.attemptReconnect()}});wsSendMessage=(e,t,i=!1)=>this.isOffline()?(this.debug("wsSendMessage: skipped (offline mode)"),this.setIsPending(!1),Promise.resolve()):new Promise((r,l)=>{if(!i&&S(t)==S(this.context))return this.debug("WebSocket context unchanged, skipping update"),r(this.setIsPending(!1));this.debug(i?"WebSocket force sending context (reconnection):":"WebSocket context updated:",t),this.context=t;let s=()=>{let p=!1,u=this.createPersistentMessageHandler(t),f=D=>{u(D),p||(p=!0,r())};e.addEventListener("message",f),e.addEventListener("close",D=>{p||(p=!0,D.code===4001?l(new Error(`Authentication failed: ${D.reason!==""?D.reason:"Invalid API key"}`)):l(new Error("WebSocket connection closed unexpectedly")))}),this.currentWebSocket=e;let P=this.additionalHeaders["X-Schematic-Client-Version"]??`schematic-js@${j}`,y={apiKey:this.apiKey,clientVersion:P,data:t};this.debug("WebSocket sending message:",y),e.send(JSON.stringify(y))};e.readyState===WebSocket.OPEN?(this.debug("WebSocket already open, sending message"),s()):e.readyState===WebSocket.CONNECTING?(this.debug("WebSocket connecting, waiting for open to send message"),e.addEventListener("open",s)):(this.debug("WebSocket is closed, cannot send message"),l("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=>Qt(t,e)))};getPlan=()=>{let e=S(this.context);return this.planChecks[e]};getFlagCheck=e=>{let t=S(this.context),r=(this.checks[t]??{})[e];if(r!==void 0)return r;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=S(this.context),r=(this.checks[t]??{})[e];if(r?.value!==void 0)return r.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)});notifyFlagCheckListeners=(e,t)=>{let i=this.flagCheckListeners?.[e]??[];i.size>0&&this.debug(`Notifying ${i.size} flag check listeners for ${e}`,t),typeof t.featureUsageEvent=="string"&&this.updateFeatureUsageEventMap(t),i.forEach(r=>Kt(r,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 i=this.flagValueListeners?.[e]??[];i.size>0&&this.debug(`Notifying ${i.size} flag value listeners for ${e}`,{value:t}),i.forEach((r,l)=>{this.debug(`Calling listener ${l} for flag ${e}`,{flagKey:e,value:t}),Xt(r,t),this.debug(`Listener ${l} 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((i,r)=>{this.debug(`Calling listener ${r} for plan`,{value:e}),Yt(i,e),this.debug(`Listener ${r} for plan completed`,{value:e})})}},Qt=(n,e)=>{n.length>0?n(e):n()},Kt=(n,e)=>{n.length>0?n(e):n()},Xt=(n,e)=>{n.length>0?n(e):n()},Yt=(n,e)=>{n.length>0?n(e):n()};window.Schematic=L;})();
1
+ "use strict";(()=>{var ve=Object.create;var pe=Object.defineProperty;var qe=Object.getOwnPropertyDescriptor;var We=Object.getOwnPropertyNames;var $e=Object.getPrototypeOf,ze=Object.prototype.hasOwnProperty;var He=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var Qe=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of We(e))!ze.call(n,r)&&r!==t&&pe(n,r,{get:()=>e[r],enumerable:!(i=qe(e,r))||i.enumerable});return n};var Ke=(n,e,t)=>(t=n!=null?ve($e(n)):{},Qe(e||!n||!n.__esModule?pe(t,"default",{value:n,enumerable:!0}):t,n));var ue=He(ce=>{(function(n){var e=(function(t){var i=typeof globalThis<"u"&&globalThis||typeof n<"u"&&n||typeof global<"u"&&global||{},r={searchParams:"URLSearchParams"in i,iterable:"Symbol"in i&&"iterator"in Symbol,blob:"FileReader"in i&&"Blob"in i&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in i,arrayBuffer:"ArrayBuffer"in i};function l(a){return a&&DataView.prototype.isPrototypeOf(a)}if(r.arrayBuffer)var s=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],p=ArrayBuffer.isView||function(a){return a&&s.indexOf(Object.prototype.toString.call(a))>-1};function u(a){if(typeof a!="string"&&(a=String(a)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(a)||a==="")throw new TypeError('Invalid character in header field name: "'+a+'"');return a.toLowerCase()}function f(a){return typeof a!="string"&&(a=String(a)),a}function T(a){var o={next:function(){var d=a.shift();return{done:d===void 0,value:d}}};return r.iterable&&(o[Symbol.iterator]=function(){return o}),o}function y(a){this.map={},a instanceof y?a.forEach(function(o,d){this.append(d,o)},this):Array.isArray(a)?a.forEach(function(o){if(o.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+o.length);this.append(o[0],o[1])},this):a&&Object.getOwnPropertyNames(a).forEach(function(o){this.append(o,a[o])},this)}y.prototype.append=function(a,o){a=u(a),o=f(o);var d=this.map[a];this.map[a]=d?d+", "+o:o},y.prototype.delete=function(a){delete this.map[u(a)]},y.prototype.get=function(a){return a=u(a),this.has(a)?this.map[a]:null},y.prototype.has=function(a){return this.map.hasOwnProperty(u(a))},y.prototype.set=function(a,o){this.map[u(a)]=f(o)},y.prototype.forEach=function(a,o){for(var d in this.map)this.map.hasOwnProperty(d)&&a.call(o,this.map[d],d,this)},y.prototype.keys=function(){var a=[];return this.forEach(function(o,d){a.push(d)}),T(a)},y.prototype.values=function(){var a=[];return this.forEach(function(o){a.push(o)}),T(a)},y.prototype.entries=function(){var a=[];return this.forEach(function(o,d){a.push([d,o])}),T(a)},r.iterable&&(y.prototype[Symbol.iterator]=y.prototype.entries);function P(a){if(!a._noBody){if(a.bodyUsed)return Promise.reject(new TypeError("Already read"));a.bodyUsed=!0}}function O(a){return new Promise(function(o,d){a.onload=function(){o(a.result)},a.onerror=function(){d(a.error)}})}function A(a){var o=new FileReader,d=O(o);return o.readAsArrayBuffer(a),d}function w(a){var o=new FileReader,d=O(o),m=/charset=([A-Za-z0-9_-]+)/.exec(a.type),g=m?m[1]:"utf-8";return o.readAsText(a,g),d}function Q(a){for(var o=new Uint8Array(a),d=new Array(o.length),m=0;m<o.length;m++)d[m]=String.fromCharCode(o[m]);return d.join("")}function F(a){if(a.slice)return a.slice(0);var o=new Uint8Array(a.byteLength);return o.set(new Uint8Array(a)),o.buffer}function J(){return this.bodyUsed=!1,this._initBody=function(a){this.bodyUsed=this.bodyUsed,this._bodyInit=a,a?typeof a=="string"?this._bodyText=a:r.blob&&Blob.prototype.isPrototypeOf(a)?this._bodyBlob=a:r.formData&&FormData.prototype.isPrototypeOf(a)?this._bodyFormData=a:r.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)?this._bodyText=a.toString():r.arrayBuffer&&r.blob&&l(a)?(this._bodyArrayBuffer=F(a.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):r.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(a)||p(a))?this._bodyArrayBuffer=F(a):this._bodyText=a=Object.prototype.toString.call(a):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof a=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):r.searchParams&&URLSearchParams.prototype.isPrototypeOf(a)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},r.blob&&(this.blob=function(){var a=P(this);if(a)return a;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 a=P(this);return a||(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(r.blob)return this.blob().then(A);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var a=P(this);if(a)return a;if(this._bodyBlob)return w(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(Q(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},r.formData&&(this.formData=function(){return this.text().then(Ge)}),this.json=function(){return this.text().then(JSON.parse)},this}var V=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function U(a){var o=a.toUpperCase();return V.indexOf(o)>-1?o:a}function _(a,o){if(!(this instanceof _))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');o=o||{};var d=o.body;if(a instanceof _){if(a.bodyUsed)throw new TypeError("Already read");this.url=a.url,this.credentials=a.credentials,o.headers||(this.headers=new y(a.headers)),this.method=a.method,this.mode=a.mode,this.signal=a.signal,!d&&a._bodyInit!=null&&(d=a._bodyInit,a.bodyUsed=!0)}else this.url=String(a);if(this.credentials=o.credentials||this.credentials||"same-origin",(o.headers||!this.headers)&&(this.headers=new y(o.headers)),this.method=U(o.method||this.method||"GET"),this.mode=o.mode||this.mode||null,this.signal=o.signal||this.signal||(function(){if("AbortController"in i){var c=new AbortController;return c.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&d)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(d),(this.method==="GET"||this.method==="HEAD")&&(o.cache==="no-store"||o.cache==="no-cache")){var m=/([?&])_=[^&]*/;if(m.test(this.url))this.url=this.url.replace(m,"$1_="+new Date().getTime());else{var g=/\?/;this.url+=(g.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}_.prototype.clone=function(){return new _(this,{body:this._bodyInit})};function Ge(a){var o=new FormData;return a.trim().split("&").forEach(function(d){if(d){var m=d.split("="),g=m.shift().replace(/\+/g," "),c=m.join("=").replace(/\+/g," ");o.append(decodeURIComponent(g),decodeURIComponent(c))}}),o}function Le(a){var o=new y,d=a.replace(/\r?\n[\t ]+/g," ");return d.split("\r").map(function(m){return m.indexOf(`
2
+ `)===0?m.substr(1,m.length):m}).forEach(function(m){var g=m.split(":"),c=g.shift().trim();if(c){var G=g.join(":").trim();try{o.append(c,G)}catch(X){console.warn("Response "+X.message)}}}),o}J.call(_.prototype);function S(a,o){if(!(this instanceof S))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(o||(o={}),this.type="default",this.status=o.status===void 0?200:o.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=o.statusText===void 0?"":""+o.statusText,this.headers=new y(o.headers),this.url=o.url||"",this._initBody(a)}J.call(S.prototype),S.prototype.clone=function(){return new S(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new y(this.headers),url:this.url})},S.error=function(){var a=new S(null,{status:200,statusText:""});return a.ok=!1,a.status=0,a.type="error",a};var Me=[301,302,303,307,308];S.redirect=function(a,o){if(Me.indexOf(o)===-1)throw new RangeError("Invalid status code");return new S(null,{status:o,headers:{location:a}})},t.DOMException=i.DOMException;try{new t.DOMException}catch{t.DOMException=function(o,d){this.message=o,this.name=d;var m=Error(o);this.stack=m.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function K(a,o){return new Promise(function(d,m){var g=new _(a,o);if(g.signal&&g.signal.aborted)return m(new t.DOMException("Aborted","AbortError"));var c=new XMLHttpRequest;function G(){c.abort()}c.onload=function(){var h={statusText:c.statusText,headers:Le(c.getAllResponseHeaders()||"")};g.url.indexOf("file://")===0&&(c.status<200||c.status>599)?h.status=200:h.status=c.status,h.url="responseURL"in c?c.responseURL:h.headers.get("X-Request-URL");var b="response"in c?c.response:c.responseText;setTimeout(function(){d(new S(b,h))},0)},c.onerror=function(){setTimeout(function(){m(new TypeError("Network request failed"))},0)},c.ontimeout=function(){setTimeout(function(){m(new TypeError("Network request timed out"))},0)},c.onabort=function(){setTimeout(function(){m(new t.DOMException("Aborted","AbortError"))},0)};function X(h){try{return h===""&&i.location.href?i.location.href:h}catch{return h}}if(c.open(g.method,X(g.url),!0),g.credentials==="include"?c.withCredentials=!0:g.credentials==="omit"&&(c.withCredentials=!1),"responseType"in c&&(r.blob?c.responseType="blob":r.arrayBuffer&&(c.responseType="arraybuffer")),o&&typeof o.headers=="object"&&!(o.headers instanceof y||i.Headers&&o.headers instanceof i.Headers)){var le=[];Object.getOwnPropertyNames(o.headers).forEach(function(h){le.push(u(h)),c.setRequestHeader(h,f(o.headers[h]))}),g.headers.forEach(function(h,b){le.indexOf(b)===-1&&c.setRequestHeader(b,h)})}else g.headers.forEach(function(h,b){c.setRequestHeader(b,h)});g.signal&&(g.signal.addEventListener("abort",G),c.onreadystatechange=function(){c.readyState===4&&g.signal.removeEventListener("abort",G)}),c.send(typeof g._bodyInit>"u"?null:g._bodyInit)})}return K.polyfill=!0,i.fetch||(i.fetch=K,i.Headers=y,i.Request=_,i.Response=S),t.Headers=y,t.Request=_,t.Response=S,t.fetch=K,t})({})})(typeof self<"u"?self:ce)});var D=[];for(let n=0;n<256;++n)D.push((n+256).toString(16).slice(1));function de(n,e=0){return(D[n[e+0]]+D[n[e+1]]+D[n[e+2]]+D[n[e+3]]+"-"+D[n[e+4]]+D[n[e+5]]+"-"+D[n[e+6]]+D[n[e+7]]+"-"+D[n[e+8]]+D[n[e+9]]+"-"+D[n[e+10]]+D[n[e+11]]+D[n[e+12]]+D[n[e+13]]+D[n[e+14]]+D[n[e+15]]).toLowerCase()}var Y,Xe=new Uint8Array(16);function Z(){if(!Y){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Y=crypto.getRandomValues.bind(crypto)}return Y(Xe)}var Ye=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),j={randomUUID:Ye};function Ze(n,e,t){n=n||{};let i=n.random??n.rng?.()??Z();if(i.length<16)throw new Error("Random bytes length must be >= 16");if(i[6]=i[6]&15|64,i[8]=i[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 r=0;r<16;++r)e[t+r]=i[r];return e}return de(i)}function je(n,e,t){return j.randomUUID&&!e&&!n?j.randomUUID():Ze(n,e,t)}var C=je;var Cm=Ke(ue());function ne(n){return Rt(n,!1)}function Rt(n,e){return n}function Pe(n){return _t(n,!1)}function _t(n,e){return n==null?n:{allocation:n.allocation==null?void 0:n.allocation,creditId:n.credit_id==null?void 0:n.credit_id,creditRemaining:n.credit_remaining==null?void 0:n.credit_remaining,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,featureId:n.feature_id,featureKey:n.feature_key,metricPeriod:n.metric_period==null?void 0:n.metric_period,metricResetAt:n.metric_reset_at==null?void 0:new Date(n.metric_reset_at),monthReset:n.month_reset==null?void 0:n.month_reset,softLimit:n.soft_limit==null?void 0:n.soft_limit,usage:n.usage==null?void 0:n.usage,valueType:ne(n.value_type)}}function N(n){return St(n,!1)}function St(n,e){return n==null?n:{companyId:n.company_id==null?void 0:n.company_id,entitlement:n.entitlement==null?void 0:Pe(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.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:n.rule_type,userId:n.user_id==null?void 0:n.user_id,value:n.value}}function re(n){return bt(n,!1)}function bt(n,e){return n==null?n:{data:N(n.data),params:n.params}}function _e(n){return Ct(n,!1)}function Ct(n,e){return n}function I(n){return xt(n,!1)}function xt(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:_e(n.trial_status)}}function ie(n){return Bt(n,!1)}function Bt(n,e){return n==null?n:{flags:n.flags.map(N),plan:n.plan==null?void 0:I(n.plan)}}function ae(n){return Ft(n,!1)}function Ft(n,e){return n==null?n:{data:ie(n.data),params:n.params}}function L(n){return Jt(n,!1)}function Jt(n,e=!1){return n==null?n:{company_id:n.companyId,error:n.error,flag_id:n.flagId,flag_key:n.flagKey,reason:n.reason,req_company:n.reqCompany,req_user:n.reqUser,rule_id:n.ruleId,user_id:n.userId,value:n.value}}var oe=n=>{let{companyId:e,entitlement:t,error:i,featureAllocation:r,featureUsage:l,featureUsageEvent:s,featureUsagePeriod:p,featureUsageResetAt:u,flag:f,flagId:T,reason:y,ruleId:P,ruleType:O,userId:A,value:w}=N(n),Q=!w&&(O=="company_override_usage_exceeded"||O=="plan_entitlement_usage_exceeded"),F=t?.allocation??r,J=t?.usage??l,V=t?.eventName??s,U=t?.metricPeriod??p,_=t?.metricResetAt??u;return{featureUsageExceeded:Q,companyId:e??void 0,creditRemaining:t?.creditRemaining==null?void 0:t.creditRemaining,error:i??void 0,featureAllocation:F??void 0,featureUsage:J??void 0,featureUsageEvent:V??void 0,featureUsagePeriod:U??void 0,featureUsageResetAt:_??void 0,flag:f,flagId:T??void 0,reason:y,ruleId:P??void 0,ruleType:O??void 0,softLimit:t?.softLimit==null?void 0:t.softLimit,userId:A??void 0,value:w}},Ve=n=>{let{id:e,name:t,trialEndDate:i,trialStatus:r}=I(n);return{id:e,name:t,trialEndDate:i??void 0,trialStatus:r??void 0}};function R(n){let e=Object.keys(n).reduce((t,i)=>{let l=Object.keys(n[i]||{}).sort().reduce((s,p)=>(s[p]=n[i][p],s),{});return t[i]=l,t},{});return JSON.stringify(e)}var se="1.4.0";var Ue="schematicId";var H=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;storage;useWebSocket=!1;checks={};featureUsageEventMap={};planChecks={};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.eventQueue=[],this.contextDependentEventQueue=[],this.useWebSocket=t?.useWebSocket??!1,this.debugEnabled=t?.debug??!1,this.offlineEnabled=t?.offline??!1,typeof window<"u"&&typeof window.location<"u"){let i=new URLSearchParams(window.location.search),r=i.get("schematic_debug");r!==null&&(r===""||r==="true"||r==="1")&&(this.debugEnabled=!0);let l=i.get("schematic_offline");l!==null&&(l===""||l==="true"||l==="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@${se}`,...t?.additionalHeaders??{}},t?.storage)this.storage=t.storage;else try{typeof localStorage<"u"&&(this.storage=localStorage)}catch{}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,i="Fallback value used",r){if(t!==void 0)return{flag:e,value:t,reason:i,error:r};if(e in this.flagCheckDefaults){let l=this.flagCheckDefaults[e];return{...l,flag:e,reason:r!==void 0?i:l.reason,error:r}}return e in this.flagValueDefaults?{flag:e,value:this.flagValueDefaults[e],reason:i,error:r}:{flag:e,value:!1,reason:i,error:r}}async checkFlag(e){let{fallback:t,key:i}=e,r=e.context||this.context,l=R(r);if(this.debug(`checkFlag: ${i}`,{context:r,fallback:t}),this.isOffline()){let s=this.resolveFallbackCheckFlagReturn(i,t,"Offline mode - using initialization defaults");return this.debug(`checkFlag offline result: ${i}`,{value:s.value,offlineMode:!0}),s.value}if(!this.useWebSocket){let s=`${this.apiUrl}/flags/${i}/check`;return fetch(s,{method:"POST",headers:{...this.additionalHeaders??{},"Content-Type":"application/json;charset=UTF-8","X-Schematic-Api-Key":this.apiKey},body:JSON.stringify(r)}).then(p=>{if(!p.ok)throw new Error("Network response was not ok");return p.json()}).then(p=>{let u=re(p);this.debug(`checkFlag result: ${i}`,u);let f=oe(u.data);return typeof f.featureUsageEvent=="string"&&this.updateFeatureUsageEventMap(f),this.submitFlagCheckEvent(i,f,r),f.value}).catch(p=>{console.warn("There was a problem with the fetch operation:",p);let u=this.resolveFallbackCheckFlagReturn(i,t,"API request failed",p instanceof Error?p.message:String(p));return this.submitFlagCheckEvent(i,u,r),u.value})}try{let s=this.checks[l];if(this.conn!==null&&typeof s<"u"&&typeof s[i]<"u")return this.debug(`checkFlag cached result: ${i}`,s[i]),s[i].value;if(this.isOffline())return this.resolveFallbackValue(i,t);try{await this.setContext(r)}catch(T){console.warn("WebSocket connection failed, using fallback value:",T);let y=this.resolveFallbackCheckFlagReturn(i,t,"WebSocket connection failed",T instanceof Error?T.message:String(T));return this.submitFlagCheckEvent(i,y,r),y.value}let u=(this.checks[l]??{})[i],f=u?.value??this.resolveFallbackValue(i,t);if(this.debug(`checkFlag WebSocket result: ${i}`,typeof u<"u"?u:{value:f,fallbackUsed:!0}),typeof u<"u")this.submitFlagCheckEvent(i,u,r);else{let T=this.resolveFallbackCheckFlagReturn(i,t,"No flag values available");this.submitFlagCheckEvent(i,T,r)}return f}catch(s){console.error("Unexpected error in checkFlag:",s);let p=this.resolveFallbackCheckFlagReturn(i,t,"Unexpected error in flag check",s instanceof Error?s.message:String(s));return this.submitFlagCheckEvent(i,p,r),p.value}}debug(e,...t){this.debugEnabled&&console.log(`[Schematic] ${e}`,...t)}createPersistentMessageHandler(e){return t=>{let i=JSON.parse(t.data);if(this.debug("WebSocket persistent message received:",i),R(e)in this.checks||(this.checks[R(e)]={}),(i.flags??[]).forEach(r=>{let l=oe(r),s=R(e);this.checks[s]===void 0&&(this.checks[s]={}),this.checks[s][l.flag]=l,typeof l.featureUsageEvent=="string"&&this.updateFeatureUsageEventMap(l),((this.flagCheckListeners[r.flag]?.size??0)>0||(this.flagValueListeners[r.flag]?.size??0)>0)&&this.submitFlagCheckEvent(l.flag,l,e),this.debug(`WebSocket flag update received. Notifying listeners for ${r.flag}`,{flag:r.flag,value:l.value,flagCheck:l}),this.notifyFlagCheckListeners(r.flag,l),this.notifyFlagValueListeners(r.flag,l.value)}),i.plan!==void 0&&i.plan!==null){let r=Ve(i.plan),l=R(e);this.planChecks[l]=r,this.debug("WebSocket plan update received. Notifying listeners",{plan:r}),this.notifyPlanListeners(r)}this.flushContextDependentEventQueue(),this.setIsPending(!1)}}isOffline(){return this.offlineEnabled}submitFlagCheckEvent(e,t,i){let r={flagKey:e,value:t.value,reason:t.reason,flagId:t.flagId,ruleId:t.ruleId,companyId:t.companyId,userId:t.userId,error:t.error,reqCompany:i.company,reqUser:i.user};return this.debug("submitting flag check event:",r),this.handleEvent("flag_check",L(r))}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`,i=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:i}).then(r=>{if(!r.ok)throw new Error("Network response was not ok");return r.json()}).then(r=>{let l=ae(r);return this.debug("checkFlags result:",l),(l?.data?.flags??[]).reduce((s,p)=>(s[p.flag]=p.value,s),{})}).catch(r=>(console.warn("There was a problem with the fetch operation:",r),{}))};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(!(R(e)===R(this.context)&&this.conn!==null&&!this.isPending))try{if(this.setIsPending(!0),!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(i=>setTimeout(i,10));if(this.conn!==null){let i=await this.conn;await this.wsSendMessage(i,e);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 i=await this.conn;this.isConnecting=!1,await this.wsSendMessage(i,e);return}catch(i){throw this.isConnecting=!1,i}}let t=await this.conn;await this.wsSendMessage(t,e)}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:i,event:r,traits:l,quantity:s=1}=e;if(!this.hasContext(t,i)){this.debug(`track: queuing event "${r}" until context is available`);let u={api_key:this.apiKey,body:{company:t,event:r,traits:l??{},user:i,quantity:s},sent_at:new Date().toISOString(),tracker_event_id:C(),tracker_user_id:this.getAnonymousId(),type:"track"};return this.contextDependentEventQueue.push(u),Promise.resolve()}let p={company:t??this.context.company,event:r,traits:l??{},user:i??this.context.user,quantity:s};return this.debug("track:",p),r in this.featureUsageEventMap&&this.optimisticallyUpdateFeatureUsage(r,s),this.handleEvent("track",p)};optimisticallyUpdateFeatureUsage=(e,t=1)=>{let i=this.featureUsageEventMap[e];i!=null&&(this.debug(`Optimistically updating feature usage for event: ${e}`,{quantity:t}),Object.entries(i).forEach(([r,l])=>{if(l===void 0)return;let s={...l};if(typeof s.featureUsage=="number"){if(s.featureUsage+=t,typeof s.featureAllocation=="number"){let u=s.featureUsageExceeded===!0,f=s.featureUsage>=s.featureAllocation;f!==u&&(s.featureUsageExceeded=f,f&&(s.value=!1),this.debug(`Usage limit status changed for flag: ${r}`,{was:u?"exceeded":"within limits",now:f?"exceeded":"within limits",featureUsage:s.featureUsage,featureAllocation:s.featureAllocation,value:s.value}))}this.featureUsageEventMap[e]!==void 0&&(this.featureUsageEventMap[e][r]=s);let p=R(this.context);this.checks[p]!==void 0&&this.checks[p]!==null&&(this.checks[p][r]=s),this.notifyFlagCheckListeners(r,s),this.notifyFlagValueListeners(r,s.value)}}))};hasContext=(e,t)=>{let i=e!=null&&Object.keys(e).length>0||t!=null&&Object.keys(t).length>0,r=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 i||r};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,i={...t,company:t.company??this.context.company,user:t.user??this.context.user},r={...e,body:i,sent_at:new Date().toISOString()};this.sendEvent(r)}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=[],i=[];for(let r of this.eventQueue)r.next_retry_at===void 0||r.next_retry_at<=e?t.push(r):i.push(r);if(t.length===0){this.debug(`No events ready for retry yet (${i.length} still in backoff)`);return}this.debug(`Flushing event queue: ${t.length} ready, ${i.length} waiting`),this.eventQueue=i;for(let r of t)try{await this.sendEvent(r),this.debug("Queued event sent successfully:",r.type)}catch(l){this.debug("Failed to send queued event:",l)}};getAnonymousId=()=>{if(!this.storage)return C();let e=this.storage.getItem(Ue);if(typeof e<"u")return e;let t=C();return this.storage.setItem(Ue,t),t};handleEvent=(e,t)=>{let i={api_key:this.apiKey,body:t,sent_at:new Date().toISOString(),tracker_event_id:C(),tracker_user_id:this.getAnonymousId(),type:e};return typeof document<"u"&&document?.hidden?this.storeEvent(i):this.sendEvent(i)};sendEvent=async e=>{let t=`${this.eventUrl}/e`,i=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 r=await fetch(t,{method:"POST",headers:{...this.additionalHeaders??{},"Content-Type":"application/json;charset=UTF-8"},body:i});if(!r.ok)throw new Error(`HTTP ${r.status}: ${r.statusText}`);this.debug("event sent:",{status:r.status,statusText:r.statusText})}catch(r){let l=(e.retry_count??0)+1;if(l<=this.maxEventRetries){this.debug(`Event failed to send (attempt ${l}/${this.maxEventRetries}), queueing for retry:`,r);let s=this.eventRetryInitialDelay*Math.pow(2,l-1),p=Math.min(s,this.eventRetryMaxDelay),u=Date.now()+p,f={...e,retry_count:l,next_retry_at:u};this.eventQueue.length<this.maxEventQueueSize?(this.eventQueue.push(f),this.debug(`Event queued for retry in ${p}ms (${this.eventQueue.length}/${this.maxEventQueueSize})`)):(this.debug(`Event queue full (${this.maxEventQueueSize}), dropping oldest event`),this.eventQueue.shift(),this.eventQueue.push(f)),this.startRetryTimer()}else this.debug(`Event failed permanently after ${this.maxEventRetries} attempts, dropping:`,r)}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,i=t?"forceReconnect":"reconnectIfNeeded";if(this.isOffline())return this.debug(`${i}: skipped (offline mode)`),Promise.resolve();if(!t&&this.conn!==null)try{if((await this.conn).readyState===WebSocket.OPEN)return this.debug(`${i}: connection is healthy, skipping`),Promise.resolve()}catch{}if(this.debug(`${i}: ${t?"forcing immediate reconnection":"reconnecting"}`),this.wsIntentionalDisconnect=!1,this.wsReconnectTimer!==null&&(this.debug(`${i}: cancelling pending reconnection timer`),clearTimeout(this.wsReconnectTimer),this.wsReconnectTimer=null),this.wsReconnectAttempts=0,this.conn!==null){this.debug(`${i}: closing existing connection`);try{let r=await this.conn;this.currentWebSocket===r&&(this.currentWebSocket=null),(r.readyState===WebSocket.OPEN||r.readyState===WebSocket.CONNECTING)&&r.close()}catch(r){this.debug(`${i}: error closing existing connection:`,r)}this.conn=null,this.isConnecting=!1}if(this.context.company!==void 0||this.context.user!==void 0){this.debug(`${i}: reconnecting with existing context`);try{this.isConnecting=!0,this.conn=this.wsConnect();let r=await this.conn;this.isConnecting=!1,await this.wsSendMessage(r,this.context,!0),this.debug(`${i}: reconnection successful`)}catch(r){this.isConnecting=!1,this.debug(`${i}: reconnection failed:`,r)}}else this.debug(`${i}: 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),i=Math.random()*t*.5,r=t+i;return this.debug(`Reconnect delay calculated: ${r.toFixed(0)}ms (attempt ${this.wsReconnectAttempts+1}/${this.webSocketMaxReconnectAttempts})`),r};handleNetworkOffline=async()=>{if(this.conn!==null){try{let e=await this.conn;(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(i=>{this.debug("Error flushing event queue after websocket reconnection:",i)}),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 i=0;i<t;i++)try{let r=await this.wsConnectOnce();return this.wsReconnectAttempts=0,r}catch(r){if(e=r instanceof Error?r:new Error(String(r)),!(e.message==="WebSocket connection timeout"))throw this.debug("WebSocket connection failed with non-timeout error, not retrying:",e.message),e;if(i<t-1){let s=this.webSocketInitialRetryDelay*Math.pow(2,i),p=Math.min(s,this.webSocketMaxRetryDelay),u=p*.2*Math.random(),f=p+u;this.debug(`WebSocket connection timeout (attempt ${i+1}/${t}), retrying in ${f.toFixed(0)}ms`),await new Promise(T=>setTimeout(T,f))}else this.debug(`WebSocket connection timeout (attempt ${i+1}/${t}), no more retries`)}throw e??new Error("WebSocket connection failed")};wsConnectOnce=()=>new Promise((e,t)=>{let i=`${this.webSocketUrl}/flags/bootstrap?apiKey=${this.apiKey}`;this.debug("connecting to WebSocket:",i);let r=new WebSocket(i),l=Math.random().toString(36).substring(7);this.debug(`Creating WebSocket connection ${l} to ${i}`);let s=null,p=!1;s=setTimeout(()=>{p||(p=!0,this.debug(`WebSocket connection timeout after ${this.webSocketConnectionTimeout}ms`),r.close(),t(new Error("WebSocket connection timeout")))},this.webSocketConnectionTimeout),r.onopen=()=>{p||(p=!0,s!==null&&clearTimeout(s),this.wsIntentionalDisconnect=!1,this.debug(`WebSocket connection ${l} opened successfully`),e(r))},r.onerror=u=>{if(p)return;p=!0,s!==null&&clearTimeout(s),this.debug(`WebSocket connection ${l} error:`,u);let f=new Error("WebSocket connection failed during handshake");t(f)},r.onclose=()=>{s!==null&&clearTimeout(s),this.debug(`WebSocket connection ${l} closed`),this.conn=null,this.currentWebSocket===r&&(this.currentWebSocket=null,this.isConnecting=!1),!p&&!this.wsIntentionalDisconnect&&this.webSocketReconnect&&this.attemptReconnect()}});wsSendMessage=(e,t,i=!1)=>this.isOffline()?(this.debug("wsSendMessage: skipped (offline mode)"),this.setIsPending(!1),Promise.resolve()):new Promise((r,l)=>{if(!i&&R(t)==R(this.context))return this.debug("WebSocket context unchanged, skipping update"),r(this.setIsPending(!1));this.debug(i?"WebSocket force sending context (reconnection):":"WebSocket context updated:",t),this.context=t;let s=()=>{let p=!1,u=this.createPersistentMessageHandler(t),f=P=>{u(P),p||(p=!0,r())};e.addEventListener("message",f),e.addEventListener("close",P=>{p||(p=!0,P.code===4001?l(new Error(`Authentication failed: ${P.reason!==""?P.reason:"Invalid API key"}`)):l(new Error("WebSocket connection closed unexpectedly")))}),this.currentWebSocket=e;let T=this.additionalHeaders["X-Schematic-Client-Version"]??`schematic-js@${se}`,y={apiKey:this.apiKey,clientVersion:T,data:t};this.debug("WebSocket sending message:",y),e.send(JSON.stringify(y))};e.readyState===WebSocket.OPEN?(this.debug("WebSocket already open, sending message"),s()):e.readyState===WebSocket.CONNECTING?(this.debug("WebSocket connecting, waiting for open to send message"),e.addEventListener("open",s)):(this.debug("WebSocket is closed, cannot send message"),l("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=>Qt(t,e)))};getPlan=()=>{let e=R(this.context);return this.planChecks[e]};getFlagCheck=e=>{let t=R(this.context),r=(this.checks[t]??{})[e];if(r!==void 0)return r;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=R(this.context),r=(this.checks[t]??{})[e];if(r?.value!==void 0)return r.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)});notifyFlagCheckListeners=(e,t)=>{let i=this.flagCheckListeners?.[e]??[];i.size>0&&this.debug(`Notifying ${i.size} flag check listeners for ${e}`,t),typeof t.featureUsageEvent=="string"&&this.updateFeatureUsageEventMap(t),i.forEach(r=>Kt(r,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 i=this.flagValueListeners?.[e]??[];i.size>0&&this.debug(`Notifying ${i.size} flag value listeners for ${e}`,{value:t}),i.forEach((r,l)=>{this.debug(`Calling listener ${l} for flag ${e}`,{flagKey:e,value:t}),Xt(r,t),this.debug(`Listener ${l} 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((i,r)=>{this.debug(`Calling listener ${r} for plan`,{value:e}),Yt(i,e),this.debug(`Listener ${r} for plan completed`,{value:e})})}},Qt=(n,e)=>{n.length>0?n(e):n()},Kt=(n,e)=>{n.length>0?n(e):n()},Xt=(n,e)=>{n.length>0?n(e):n()},Yt=(n,e)=>{n.length>0?n(e):n()};window.Schematic=H;})();
3
3
  /* @preserve */
@@ -815,6 +815,7 @@ var UsagePeriod = /* @__PURE__ */ ((UsagePeriod2) => {
815
815
  var CheckFlagReturnFromJSON = (json) => {
816
816
  const {
817
817
  companyId,
818
+ entitlement,
818
819
  error,
819
820
  featureAllocation,
820
821
  featureUsage,
@@ -832,20 +833,27 @@ var CheckFlagReturnFromJSON = (json) => {
832
833
  const featureUsageExceeded = !value && // if flag is not false, then we haven't exceeded usage
833
834
  (ruleType == "company_override_usage_exceeded" /* COMPANY_OVERRIDE_USAGE_EXCEEDED */ || // if the rule type is one of these, then we have exceeded usage
834
835
  ruleType == "plan_entitlement_usage_exceeded" /* PLAN_ENTITLEMENT_USAGE_EXCEEDED */);
836
+ const resolvedAllocation = entitlement?.allocation ?? featureAllocation;
837
+ const resolvedUsage = entitlement?.usage ?? featureUsage;
838
+ const resolvedEvent = entitlement?.eventName ?? featureUsageEvent;
839
+ const resolvedPeriod = entitlement?.metricPeriod ?? featureUsagePeriod;
840
+ const resolvedResetAt = entitlement?.metricResetAt ?? featureUsageResetAt;
835
841
  return {
836
842
  featureUsageExceeded,
837
843
  companyId: companyId == null ? void 0 : companyId,
844
+ creditRemaining: entitlement?.creditRemaining == null ? void 0 : entitlement.creditRemaining,
838
845
  error: error == null ? void 0 : error,
839
- featureAllocation: featureAllocation == null ? void 0 : featureAllocation,
840
- featureUsage: featureUsage == null ? void 0 : featureUsage,
841
- featureUsageEvent: featureUsageEvent === null ? void 0 : featureUsageEvent,
842
- featureUsagePeriod: featureUsagePeriod == null ? void 0 : featureUsagePeriod,
843
- featureUsageResetAt: featureUsageResetAt == null ? void 0 : featureUsageResetAt,
846
+ featureAllocation: resolvedAllocation == null ? void 0 : resolvedAllocation,
847
+ featureUsage: resolvedUsage == null ? void 0 : resolvedUsage,
848
+ featureUsageEvent: resolvedEvent == null ? void 0 : resolvedEvent,
849
+ featureUsagePeriod: resolvedPeriod == null ? void 0 : resolvedPeriod,
850
+ featureUsageResetAt: resolvedResetAt == null ? void 0 : resolvedResetAt,
844
851
  flag,
845
852
  flagId: flagId == null ? void 0 : flagId,
846
853
  reason,
847
854
  ruleId: ruleId == null ? void 0 : ruleId,
848
855
  ruleType: ruleType == null ? void 0 : ruleType,
856
+ softLimit: entitlement?.softLimit == null ? void 0 : entitlement.softLimit,
849
857
  userId: userId == null ? void 0 : userId,
850
858
  value
851
859
  };
@@ -877,7 +885,7 @@ function contextString(context) {
877
885
  }
878
886
 
879
887
  // src/version.ts
880
- var version = "1.3.1";
888
+ var version = "1.4.0";
881
889
 
882
890
  // src/index.ts
883
891
  var anonymousIdKey = "schematicId";
@@ -130,6 +130,8 @@ export declare type CheckFlagReturn = {
130
130
  featureUsageExceeded?: boolean;
131
131
  /** If company keys were provided and matched a company, its ID */
132
132
  companyId?: string;
133
+ /** If the company has a credit-based entitlement for this feature, the remaining credit amount */
134
+ creditRemaining?: number;
133
135
  /** If an error occurred while checking the flag, the error message */
134
136
  error?: string;
135
137
  /** If a numeric feature entitlement rule was matched, its allocation */
@@ -152,6 +154,8 @@ export declare type CheckFlagReturn = {
152
154
  ruleId?: string;
153
155
  /** If a rule was found, its type */
154
156
  ruleType?: RuleType;
157
+ /** For usage-based pricing, the soft limit for overage charges or the next tier boundary */
158
+ softLimit?: number;
155
159
  /** If user keys were provided and matched a user, its ID */
156
160
  userId?: string;
157
161
  /** A boolean flag check result; for feature entitlements, this represents whether further consumption of the feature is permitted */
@@ -793,6 +793,7 @@ var UsagePeriod = /* @__PURE__ */ ((UsagePeriod2) => {
793
793
  var CheckFlagReturnFromJSON = (json) => {
794
794
  const {
795
795
  companyId,
796
+ entitlement,
796
797
  error,
797
798
  featureAllocation,
798
799
  featureUsage,
@@ -810,20 +811,27 @@ var CheckFlagReturnFromJSON = (json) => {
810
811
  const featureUsageExceeded = !value && // if flag is not false, then we haven't exceeded usage
811
812
  (ruleType == "company_override_usage_exceeded" /* COMPANY_OVERRIDE_USAGE_EXCEEDED */ || // if the rule type is one of these, then we have exceeded usage
812
813
  ruleType == "plan_entitlement_usage_exceeded" /* PLAN_ENTITLEMENT_USAGE_EXCEEDED */);
814
+ const resolvedAllocation = entitlement?.allocation ?? featureAllocation;
815
+ const resolvedUsage = entitlement?.usage ?? featureUsage;
816
+ const resolvedEvent = entitlement?.eventName ?? featureUsageEvent;
817
+ const resolvedPeriod = entitlement?.metricPeriod ?? featureUsagePeriod;
818
+ const resolvedResetAt = entitlement?.metricResetAt ?? featureUsageResetAt;
813
819
  return {
814
820
  featureUsageExceeded,
815
821
  companyId: companyId == null ? void 0 : companyId,
822
+ creditRemaining: entitlement?.creditRemaining == null ? void 0 : entitlement.creditRemaining,
816
823
  error: error == null ? void 0 : error,
817
- featureAllocation: featureAllocation == null ? void 0 : featureAllocation,
818
- featureUsage: featureUsage == null ? void 0 : featureUsage,
819
- featureUsageEvent: featureUsageEvent === null ? void 0 : featureUsageEvent,
820
- featureUsagePeriod: featureUsagePeriod == null ? void 0 : featureUsagePeriod,
821
- featureUsageResetAt: featureUsageResetAt == null ? void 0 : featureUsageResetAt,
824
+ featureAllocation: resolvedAllocation == null ? void 0 : resolvedAllocation,
825
+ featureUsage: resolvedUsage == null ? void 0 : resolvedUsage,
826
+ featureUsageEvent: resolvedEvent == null ? void 0 : resolvedEvent,
827
+ featureUsagePeriod: resolvedPeriod == null ? void 0 : resolvedPeriod,
828
+ featureUsageResetAt: resolvedResetAt == null ? void 0 : resolvedResetAt,
822
829
  flag,
823
830
  flagId: flagId == null ? void 0 : flagId,
824
831
  reason,
825
832
  ruleId: ruleId == null ? void 0 : ruleId,
826
833
  ruleType: ruleType == null ? void 0 : ruleType,
834
+ softLimit: entitlement?.softLimit == null ? void 0 : entitlement.softLimit,
827
835
  userId: userId == null ? void 0 : userId,
828
836
  value
829
837
  };
@@ -855,7 +863,7 @@ function contextString(context) {
855
863
  }
856
864
 
857
865
  // src/version.ts
858
- var version = "1.3.1";
866
+ var version = "1.4.0";
859
867
 
860
868
  // src/index.ts
861
869
  var anonymousIdKey = "schematicId";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@schematichq/schematic-js",
3
- "version": "1.3.1",
3
+ "version": "1.4.0",
4
4
  "main": "dist/schematic.cjs.js",
5
5
  "module": "dist/schematic.esm.js",
6
6
  "types": "dist/schematic.d.ts",
@@ -38,22 +38,23 @@
38
38
  },
39
39
  "devDependencies": {
40
40
  "@eslint/js": "^10.0.1",
41
- "@microsoft/api-extractor": "^7.58.1",
42
- "@openapitools/openapi-generator-cli": "^2.31.0",
43
- "@vitest/browser": "^4.0.18",
41
+ "@microsoft/api-extractor": "^7.58.2",
42
+ "@openapitools/openapi-generator-cli": "^2.31.1",
43
+ "@vitest/browser": "^4.1.4",
44
44
  "esbuild": "^0.28.0",
45
- "eslint": "^10.1.0",
46
- "globals": "^17.4.0",
47
- "happy-dom": "^20.8.9",
45
+ "eslint": "^10.2.0",
46
+ "globals": "^17.5.0",
47
+ "happy-dom": "^20.9.0",
48
48
  "husky": "^9.1.7",
49
- "jsdom": "^29.0.1",
49
+ "jsdom": "^29.0.2",
50
50
  "mock-socket": "^9.3.1",
51
- "prettier": "^3.8.1",
52
- "typescript": "^6.0.2",
53
- "typescript-eslint": "^8.58.0",
54
- "vitest": "^4.0.18"
51
+ "prettier": "^3.8.3",
52
+ "typescript": "^6.0.3",
53
+ "typescript-eslint": "^8.58.2",
54
+ "vitest": "^4.1.4"
55
55
  },
56
56
  "resolutions": {
57
+ "axios": ">=1.15.0",
57
58
  "basic-ftp": ">=5.2.0",
58
59
  "rollup": ">=4.59.0",
59
60
  "undici": ">=7.24.0"