@schematichq/schematic-js 0.1.12 → 0.1.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/schematic.browser.js +2 -1
- package/dist/schematic.cjs.js +616 -38
- package/dist/schematic.d.ts +23 -4
- package/dist/schematic.esm.js +629 -38
- package/package.json +3 -1
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
"use strict";(()=>{var
|
|
1
|
+
"use strict";(()=>{var G=Object.create;var C=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var z=Object.getOwnPropertyNames;var Y=Object.getPrototypeOf,Z=Object.prototype.hasOwnProperty;var ee=(s,t)=>()=>(t||s((t={exports:{}}).exports,t),t.exports);var te=(s,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of z(t))!Z.call(s,o)&&o!==n&&C(s,o,{get:()=>t[o],enumerable:!(i=X(t,o))||i.enumerable});return s};var re=(s,t,n)=>(n=s!=null?G(Y(s)):{},te(t||!s||!s.__esModule?C(n,"default",{value:s,enumerable:!0}):n,s));var j=ee(F=>{(function(s){var t=function(n){var i=typeof globalThis<"u"&&globalThis||typeof s<"u"&&s||typeof i<"u"&&i,o={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 y(e){return e&&DataView.prototype.isPrototypeOf(e)}if(o.arrayBuffer)var f=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],E=ArrayBuffer.isView||function(e){return e&&f.indexOf(Object.prototype.toString.call(e))>-1};function b(e){if(typeof e!="string"&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(e)||e==="")throw new TypeError('Invalid character in header field name: "'+e+'"');return e.toLowerCase()}function S(e){return typeof e!="string"&&(e=String(e)),e}function w(e){var r={next:function(){var a=e.shift();return{done:a===void 0,value:a}}};return o.iterable&&(r[Symbol.iterator]=function(){return r}),r}function d(e){this.map={},e instanceof d?e.forEach(function(r,a){this.append(a,r)},this):Array.isArray(e)?e.forEach(function(r){this.append(r[0],r[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(r){this.append(r,e[r])},this)}d.prototype.append=function(e,r){e=b(e),r=S(r);var a=this.map[e];this.map[e]=a?a+", "+r:r},d.prototype.delete=function(e){delete this.map[b(e)]},d.prototype.get=function(e){return e=b(e),this.has(e)?this.map[e]:null},d.prototype.has=function(e){return this.map.hasOwnProperty(b(e))},d.prototype.set=function(e,r){this.map[b(e)]=S(r)},d.prototype.forEach=function(e,r){for(var a in this.map)this.map.hasOwnProperty(a)&&e.call(r,this.map[a],a,this)},d.prototype.keys=function(){var e=[];return this.forEach(function(r,a){e.push(a)}),w(e)},d.prototype.values=function(){var e=[];return this.forEach(function(r){e.push(r)}),w(e)},d.prototype.entries=function(){var e=[];return this.forEach(function(r,a){e.push([a,r])}),w(e)},o.iterable&&(d.prototype[Symbol.iterator]=d.prototype.entries);function B(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function I(e){return new Promise(function(r,a){e.onload=function(){r(e.result)},e.onerror=function(){a(e.error)}})}function N(e){var r=new FileReader,a=I(r);return r.readAsArrayBuffer(e),a}function q(e){var r=new FileReader,a=I(r);return r.readAsText(e),a}function M(e){for(var r=new Uint8Array(e),a=new Array(r.length),u=0;u<r.length;u++)a[u]=String.fromCharCode(r[u]);return a.join("")}function D(e){if(e.slice)return e.slice(0);var r=new Uint8Array(e.byteLength);return r.set(new Uint8Array(e)),r.buffer}function R(){return this.bodyUsed=!1,this._initBody=function(e){this.bodyUsed=this.bodyUsed,this._bodyInit=e,e?typeof e=="string"?this._bodyText=e:o.blob&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:o.formData&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:o.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():o.arrayBuffer&&o.blob&&y(e)?(this._bodyArrayBuffer=D(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):o.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(e)||E(e))?this._bodyArrayBuffer=D(e):this._bodyText=e=Object.prototype.toString.call(e):this._bodyText="",this.headers.get("content-type")||(typeof e=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):o.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},o.blob&&(this.blob=function(){var e=B(this);if(e)return e;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 e=B(this);return e||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else return this.blob().then(N)}),this.text=function(){var e=B(this);if(e)return e;if(this._bodyBlob)return q(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(M(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},o.formData&&(this.formData=function(){return this.text().then(K)}),this.json=function(){return this.text().then(JSON.parse)},this}var H=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function W(e){var r=e.toUpperCase();return H.indexOf(r)>-1?r:e}function v(e,r){if(!(this instanceof v))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');r=r||{};var a=r.body;if(e instanceof v){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,r.headers||(this.headers=new d(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,!a&&e._bodyInit!=null&&(a=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=r.credentials||this.credentials||"same-origin",(r.headers||!this.headers)&&(this.headers=new d(r.headers)),this.method=W(r.method||this.method||"GET"),this.mode=r.mode||this.mode||null,this.signal=r.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&a)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(a),(this.method==="GET"||this.method==="HEAD")&&(r.cache==="no-store"||r.cache==="no-cache")){var u=/([?&])_=[^&]*/;if(u.test(this.url))this.url=this.url.replace(u,"$1_="+new Date().getTime());else{var h=/\?/;this.url+=(h.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}v.prototype.clone=function(){return new v(this,{body:this._bodyInit})};function K(e){var r=new FormData;return e.trim().split("&").forEach(function(a){if(a){var u=a.split("="),h=u.shift().replace(/\+/g," "),c=u.join("=").replace(/\+/g," ");r.append(decodeURIComponent(h),decodeURIComponent(c))}}),r}function J(e){var r=new d,a=e.replace(/\r?\n[\t ]+/g," ");return a.split("\r").map(function(u){return u.indexOf(`
|
|
2
|
+
`)===0?u.substr(1,u.length):u}).forEach(function(u){var h=u.split(":"),c=h.shift().trim();if(c){var T=h.join(":").trim();r.append(c,T)}}),r}R.call(v.prototype);function m(e,r){if(!(this instanceof m))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');r||(r={}),this.type="default",this.status=r.status===void 0?200:r.status,this.ok=this.status>=200&&this.status<300,this.statusText=r.statusText===void 0?"":""+r.statusText,this.headers=new d(r.headers),this.url=r.url||"",this._initBody(e)}R.call(m.prototype),m.prototype.clone=function(){return new m(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new d(this.headers),url:this.url})},m.error=function(){var e=new m(null,{status:0,statusText:""});return e.type="error",e};var Q=[301,302,303,307,308];m.redirect=function(e,r){if(Q.indexOf(r)===-1)throw new RangeError("Invalid status code");return new m(null,{status:r,headers:{location:e}})},n.DOMException=i.DOMException;try{new n.DOMException}catch{n.DOMException=function(r,a){this.message=r,this.name=a;var u=Error(r);this.stack=u.stack},n.DOMException.prototype=Object.create(Error.prototype),n.DOMException.prototype.constructor=n.DOMException}function O(e,r){return new Promise(function(a,u){var h=new v(e,r);if(h.signal&&h.signal.aborted)return u(new n.DOMException("Aborted","AbortError"));var c=new XMLHttpRequest;function T(){c.abort()}c.onload=function(){var p={status:c.status,statusText:c.statusText,headers:J(c.getAllResponseHeaders()||"")};p.url="responseURL"in c?c.responseURL:p.headers.get("X-Request-URL");var P="response"in c?c.response:c.responseText;setTimeout(function(){a(new m(P,p))},0)},c.onerror=function(){setTimeout(function(){u(new TypeError("Network request failed"))},0)},c.ontimeout=function(){setTimeout(function(){u(new TypeError("Network request failed"))},0)},c.onabort=function(){setTimeout(function(){u(new n.DOMException("Aborted","AbortError"))},0)};function $(p){try{return p===""&&i.location.href?i.location.href:p}catch{return p}}c.open(h.method,$(h.url),!0),h.credentials==="include"?c.withCredentials=!0:h.credentials==="omit"&&(c.withCredentials=!1),"responseType"in c&&(o.blob?c.responseType="blob":o.arrayBuffer&&h.headers.get("Content-Type")&&h.headers.get("Content-Type").indexOf("application/octet-stream")!==-1&&(c.responseType="arraybuffer")),r&&typeof r.headers=="object"&&!(r.headers instanceof d)?Object.getOwnPropertyNames(r.headers).forEach(function(p){c.setRequestHeader(p,S(r.headers[p]))}):h.headers.forEach(function(p,P){c.setRequestHeader(P,p)}),h.signal&&(h.signal.addEventListener("abort",T),c.onreadystatechange=function(){c.readyState===4&&h.signal.removeEventListener("abort",T)}),c.send(typeof h._bodyInit>"u"?null:h._bodyInit)})}return O.polyfill=!0,i.fetch||(i.fetch=O,i.Headers=d,i.Request=v,i.Response=m),n.Headers=d,n.Request=v,n.Response=m,n.fetch=O,n}({})})(typeof self<"u"?self:F)});var U,ne=new Uint8Array(16);function k(){if(!U&&(U=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!U))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return U(ne)}var l=[];for(let s=0;s<256;++s)l.push((s+256).toString(16).slice(1));function L(s,t=0){return l[s[t+0]]+l[s[t+1]]+l[s[t+2]]+l[s[t+3]]+"-"+l[s[t+4]]+l[s[t+5]]+"-"+l[s[t+6]]+l[s[t+7]]+"-"+l[s[t+8]]+l[s[t+9]]+"-"+l[s[t+10]]+l[s[t+11]]+l[s[t+12]]+l[s[t+13]]+l[s[t+14]]+l[s[t+15]]}var ie=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),_={randomUUID:ie};function se(s,t,n){if(_.randomUUID&&!t&&!s)return _.randomUUID();s=s||{};let i=s.random||(s.rng||k)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){n=n||0;for(let o=0;o<16;++o)t[n+o]=i[o];return t}return L(i)}var x=se;var ge=re(j());function g(s){let t=Object.keys(s).reduce((n,i)=>{let y=Object.keys(s[i]||{}).sort().reduce((f,E)=>(f[E]=s[i][E],f),{});return n[i]=y,n},{});return JSON.stringify(t)}var V="schematicId";var A=class{apiKey;apiUrl="https://api.schematichq.com";conn=null;context={};eventQueue;eventUrl="https://c.schematichq.com";flagListener;flagValueListeners={};isPending=!0;isPendingListeners=new Set;storage;useWebSocket=!1;values={};webSocketUrl="wss://api.schematichq.com";constructor(t,n){this.apiKey=t,this.eventQueue=[],this.useWebSocket=n?.useWebSocket??!1,this.flagListener=n?.flagListener,n?.storage?this.storage=n.storage:typeof localStorage<"u"&&(this.storage=localStorage),n?.apiUrl!==void 0&&(this.apiUrl=n.apiUrl),n?.eventUrl!==void 0&&(this.eventUrl=n.eventUrl),n?.webSocketUrl!==void 0&&(this.webSocketUrl=n.webSocketUrl),typeof window<"u"&&window?.addEventListener&&window.addEventListener("beforeunload",()=>{this.flushEventQueue()})}async checkFlag(t){let{fallback:n=!1,key:i}=t,o=t.context||this.context;if(this.useWebSocket){let f=this.values[g(o)]??{};return typeof f[i]>"u"?n:f[i]}let y=`${this.apiUrl}/flags/${i}/check`;return fetch(y,{method:"POST",headers:{"X-Schematic-Api-Key":this.apiKey,"Content-Type":"application/json;charset=UTF-8"},body:JSON.stringify(o)}).then(f=>{if(!f.ok)throw new Error("Network response was not ok");return f.json()}).then(f=>f.data.value).catch(f=>(console.error("There was a problem with the fetch operation:",f),n))}checkFlags=async t=>{t=t||this.context;let n=`${this.apiUrl}/flags/check`,i=JSON.stringify(t);return fetch(n,{method:"POST",headers:{"Content-Type":"application/json;charset=UTF-8","X-Schematic-Api-Key":this.apiKey},body:i}).then(o=>{if(!o.ok)throw new Error("Network response was not ok");return o.json()}).then(o=>(o?.data?.flags??[]).reduce((y,f)=>(y[f.flag]=f.value,y),{})).catch(o=>(console.error("There was a problem with the fetch operation:",o),!1))};identify=t=>(this.setContext({company:t.company?.keys,user:t.keys}),this.handleEvent("identify",t));setContext=async t=>{if(!this.useWebSocket)return this.context=t,Promise.resolve();try{this.setIsPending(!0),this.conn||(this.conn=this.wsConnect());let n=await this.conn;await this.wsSendMessage(n,t)}catch(n){console.error("Error setting Schematic context:",n)}};track=t=>{let{company:n,user:i,event:o,traits:y}=t;return this.handleEvent("track",{company:n??this.context.company,event:o,traits:y??{},user:i??this.context.user})};flushEventQueue=()=>{for(;this.eventQueue.length>0;){let t=this.eventQueue.shift();t&&this.sendEvent(t)}};getAnonymousId=()=>{if(!this.storage)return x();let t=this.storage.getItem(V);if(typeof t<"u")return t;let n=x();return this.storage.setItem(V,n),n};handleEvent=(t,n)=>{let i={api_key:this.apiKey,body:n,sent_at:new Date().toISOString(),tracker_event_id:x(),tracker_user_id:this.getAnonymousId(),type:t};return document?.hidden?this.storeEvent(i):this.sendEvent(i)};sendEvent=async t=>{let n=`${this.eventUrl}/e`,i=JSON.stringify(t);try{await fetch(n,{method:"POST",headers:{"Content-Type":"application/json;charset=UTF-8"},body:i})}catch(o){console.error("Error sending Schematic event: ",o)}return Promise.resolve()};storeEvent=t=>(this.eventQueue.push(t),Promise.resolve());cleanup=async()=>{if(this.conn)try{(await this.conn).close()}catch(t){console.error("Error during cleanup:",t)}finally{this.conn=null}};wsConnect=()=>new Promise((t,n)=>{let i=`${this.webSocketUrl}/flags/bootstrap`,o=new WebSocket(i);o.onopen=()=>{t(o)},o.onerror=y=>{n(y)},o.onclose=()=>{this.conn=null}});wsSendMessage=(t,n)=>new Promise((i,o)=>{if(g(n)==g(this.context)){i();return}this.context=n;let y=()=>{let f=!1,E=b=>{let S=JSON.parse(b.data);g(n)in this.values||(this.values[g(n)]={}),(S.flags??[]).forEach(w=>{this.values[g(n)][w.flag]=w.value,this.notifyFlagValueListeners(w.flag)}),this.flagListener&&this.flagListener(this.getFlagValues()),this.setIsPending(!1),f||(f=!0,i())};t.addEventListener("message",E),t.send(JSON.stringify({apiKey:this.apiKey,data:n}))};t.readyState===WebSocket.OPEN?y():t.readyState===WebSocket.CONNECTING?t.addEventListener("open",y):o("WebSocket is not open or connecting")});getIsPending=()=>this.isPending;addIsPendingListener=t=>(this.isPendingListeners.add(t),()=>{this.isPendingListeners.delete(t)});setIsPending=t=>{this.isPending=t,this.isPendingListeners.forEach(n=>n())};getFlagValue=t=>this.getFlagValues()[t];getFlagValues=()=>{let t=g(this.context);return this.values[t]??{}};addFlagValueListener=(t,n)=>(t in this.flagValueListeners||(this.flagValueListeners[t]=new Set),this.flagValueListeners[t].add(n),()=>{this.flagValueListeners[t].delete(n)});notifyFlagValueListeners=t=>{(this.flagValueListeners?.[t]??[]).forEach(i=>i())}};window.Schematic=A;})();
|
|
2
3
|
/* @preserve */
|