@schematichq/schematic-js 0.1.10 → 0.1.12

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,2 +1,2 @@
1
- "use strict";(()=>{var l,f=new Uint8Array(16);function u(){if(!l&&(l=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!l))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return l(f)}var s=[];for(let n=0;n<256;++n)s.push((n+256).toString(16).slice(1));function v(n,e=0){return s[n[e+0]]+s[n[e+1]]+s[n[e+2]]+s[n[e+3]]+"-"+s[n[e+4]]+s[n[e+5]]+"-"+s[n[e+6]]+s[n[e+7]]+"-"+s[n[e+8]]+s[n[e+9]]+"-"+s[n[e+10]]+s[n[e+11]]+s[n[e+12]]+s[n[e+13]]+s[n[e+14]]+s[n[e+15]]}var m=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),y={randomUUID:m};function k(n,e,t){if(y.randomUUID&&!e&&!n)return y.randomUUID();n=n||{};let r=n.random||(n.rng||u)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){t=t||0;for(let o=0;o<16;++o)e[t+o]=r[o];return e}return v(r)}var h=k;var g="schematicId";var p=class{apiKey;apiUrl="https://api.schematichq.com";webSocketUrl="wss://api.schematichq.com";eventUrl="https://c.schematichq.com";conn=null;context={};eventQueue;storage;useWebSocket=!1;values={};flagListener;constructor(e,t){this.apiKey=e,this.eventQueue=[],this.useWebSocket=t?.useWebSocket??!1,this.flagListener=t?.flagListener,t?.storage?this.storage=t.storage:typeof localStorage<"u"&&(this.storage=localStorage),t?.apiUrl!==void 0&&(this.apiUrl=t.apiUrl),t?.eventUrl!==void 0&&(this.eventUrl=t.eventUrl),t?.webSocketUrl!==void 0&&(this.webSocketUrl=t.webSocketUrl),window?.addEventListener&&window.addEventListener("beforeunload",()=>{this.flushEventQueue()})}async checkFlag(e){let{fallback:t=!1,key:r}=e,o=e.context||this.context;if(this.useWebSocket){let i=this.values[c(o)]??{};return typeof i[r]>"u"?t:i[r]}let a=`${this.apiUrl}/flags/${r}/check`;return fetch(a,{method:"POST",headers:{"X-Schematic-Api-Key":this.apiKey,"Content-Type":"application/json;charset=UTF-8"},body:JSON.stringify(o)}).then(i=>{if(!i.ok)throw new Error("Network response was not ok");return i.json()}).then(i=>i.data.value).catch(i=>(console.error("There was a problem with the fetch operation:",i),t))}checkFlags=async e=>{e=e||this.context;let t=`${this.apiUrl}/flags/check`,r=JSON.stringify(e);return fetch(t,{method:"POST",headers:{"Content-Type":"application/json;charset=UTF-8","X-Schematic-Api-Key":this.apiKey},body:r}).then(o=>{if(!o.ok)throw new Error("Network response was not ok");return o.json()}).then(o=>(o?.data?.flags??[]).reduce((a,i)=>(a[i.flag]=i.value,a),{})).catch(o=>(console.error("There was a problem with the fetch operation:",o),!1))};cleanup=()=>{this.conn&&this.conn.close()};identify=e=>{this.handleEvent("identify",e)};setContext=e=>this.useWebSocket?new Promise(t=>{this.wsConnect().then(()=>{this.wsSendMessage(e),t()})}):(this.context=e,Promise.resolve());track=e=>{this.handleEvent("track",e)};flushEventQueue=()=>{for(;this.eventQueue.length>0;){let e=this.eventQueue.shift();e&&this.sendEvent(e)}};getAnonymousId=()=>{if(!this.storage)return h();let e=this.storage.getItem(g);if(typeof e<"u")return e;let t=h();return this.storage.setItem(g,t),t};handleEvent=(e,t)=>{let r={api_key:this.apiKey,body:t,sent_at:new Date().toISOString(),tracker_event_id:h(),tracker_user_id:this.getAnonymousId(),type:e};document?.hidden?this.storeEvent(r):this.sendEvent(r)};sendEvent=e=>{let t=`${this.eventUrl}/e`,r=JSON.stringify(e);fetch(t,{method:"POST",headers:{"Content-Type":"application/json;charset=UTF-8"},body:r}).then(o=>{if(!o.ok)throw new Error(`Network response was not ok: ${o.statusText}`)}).catch(o=>{console.error("There was a problem with the fetch operation:",o)})};storeEvent=e=>{this.eventQueue.push(e)};wsConnect=()=>new Promise(e=>{this.conn&&e();let t=`${this.webSocketUrl}/flags/bootstrap`,r=new WebSocket(t);this.conn=r,r.onopen=()=>{e()},r.onclose=()=>{this.conn=null}});wsSendMessage=e=>new Promise((t,r)=>{if(c(e)==c(this.context)){t();return}if(this.context=e,!this.conn){r("Not connected");return}if(this.conn.readyState===WebSocket.OPEN){let o=!1;this.conn.onmessage=a=>{let i=JSON.parse(a.data);c(e)in this.values||(this.values[c(e)]={}),(i.flags??[]).forEach(d=>{this.values[c(e)][d.flag]=d.value}),this.flagListener&&this.flagListener(this.values[c(e)]),o||(o=!0,t())},this.conn.onerror=a=>{console.error("Schematic websocket error: ",a)},this.conn.send(JSON.stringify({apiKey:this.apiKey,data:e}))}else this.conn.readyState===WebSocket.CONNECTING?this.conn.onopen=()=>{this.wsSendMessage(e)}:r("Not connected")})};function c(n){let e=Object.keys(n).reduce((t,r)=>{let a=Object.keys(n[r]||{}).sort().reduce((i,d)=>(i[d]=n[r][d],i),{});return t[r]=a,t},{});return JSON.stringify(e)}window.Schematic=p;})();
1
+ "use strict";(()=>{var l,k=new Uint8Array(16);function p(){if(!l&&(l=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!l))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return l(k)}var i=[];for(let r=0;r<256;++r)i.push((r+256).toString(16).slice(1));function m(r,e=0){return i[r[e+0]]+i[r[e+1]]+i[r[e+2]]+i[r[e+3]]+"-"+i[r[e+4]]+i[r[e+5]]+"-"+i[r[e+6]]+i[r[e+7]]+"-"+i[r[e+8]]+i[r[e+9]]+"-"+i[r[e+10]]+i[r[e+11]]+i[r[e+12]]+i[r[e+13]]+i[r[e+14]]+i[r[e+15]]}var x=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),y={randomUUID:x};function b(r,e,t){if(y.randomUUID&&!e&&!r)return y.randomUUID();r=r||{};let n=r.random||(r.rng||p)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){t=t||0;for(let s=0;s<16;++s)e[t+s]=n[s];return e}return m(n)}var u=b;var g="schematicId";var h=class{apiKey;apiUrl="https://api.schematichq.com";webSocketUrl="wss://api.schematichq.com";eventUrl="https://c.schematichq.com";conn=null;context={};eventQueue;storage;useWebSocket=!1;values={};flagListener;constructor(e,t){this.apiKey=e,this.eventQueue=[],this.useWebSocket=t?.useWebSocket??!1,this.flagListener=t?.flagListener,t?.storage?this.storage=t.storage:typeof localStorage<"u"&&(this.storage=localStorage),t?.apiUrl!==void 0&&(this.apiUrl=t.apiUrl),t?.eventUrl!==void 0&&(this.eventUrl=t.eventUrl),t?.webSocketUrl!==void 0&&(this.webSocketUrl=t.webSocketUrl),window?.addEventListener&&window.addEventListener("beforeunload",()=>{this.flushEventQueue()})}async checkFlag(e){let{fallback:t=!1,key:n}=e,s=e.context||this.context;if(this.useWebSocket){let o=this.values[c(s)]??{};return typeof o[n]>"u"?t:o[n]}let a=`${this.apiUrl}/flags/${n}/check`;return fetch(a,{method:"POST",headers:{"X-Schematic-Api-Key":this.apiKey,"Content-Type":"application/json;charset=UTF-8"},body:JSON.stringify(s)}).then(o=>{if(!o.ok)throw new Error("Network response was not ok");return o.json()}).then(o=>o.data.value).catch(o=>(console.error("There was a problem with the fetch operation:",o),t))}checkFlags=async e=>{e=e||this.context;let t=`${this.apiUrl}/flags/check`,n=JSON.stringify(e);return fetch(t,{method:"POST",headers:{"Content-Type":"application/json;charset=UTF-8","X-Schematic-Api-Key":this.apiKey},body:n}).then(s=>{if(!s.ok)throw new Error("Network response was not ok");return s.json()}).then(s=>(s?.data?.flags??[]).reduce((a,o)=>(a[o.flag]=o.value,a),{})).catch(s=>(console.error("There was a problem with the fetch operation:",s),!1))};cleanup=async()=>{if(this.conn)try{(await this.conn).close()}catch(e){console.error("Error during cleanup:",e)}finally{this.conn=null}};identify=e=>(this.setContext({company:e.company?.keys,user:e.keys}),this.handleEvent("identify",e));setContext=async e=>this.useWebSocket?(this.conn||(this.conn=this.wsConnect()),this.conn.then(t=>this.wsSendMessage(t,e))):(this.context=e,Promise.resolve());track=e=>{let{company:t,user:n,event:s,traits:a}=e;return this.handleEvent("track",{company:t??this.context.company,event:s,traits:a??{},user:n??this.context.user})};flushEventQueue=()=>{for(;this.eventQueue.length>0;){let e=this.eventQueue.shift();e&&this.sendEvent(e)}};getAnonymousId=()=>{if(!this.storage)return u();let e=this.storage.getItem(g);if(typeof e<"u")return e;let t=u();return this.storage.setItem(g,t),t};handleEvent=(e,t)=>{let n={api_key:this.apiKey,body:t,sent_at:new Date().toISOString(),tracker_event_id:u(),tracker_user_id:this.getAnonymousId(),type:e};return document?.hidden?this.storeEvent(n):this.sendEvent(n)};sendEvent=async e=>{let t=`${this.eventUrl}/e`,n=JSON.stringify(e);try{await fetch(t,{method:"POST",headers:{"Content-Type":"application/json;charset=UTF-8"},body:n})}catch(s){console.error("Error sending Schematic event: ",s)}return Promise.resolve()};storeEvent=e=>(this.eventQueue.push(e),Promise.resolve());wsConnect=()=>new Promise((e,t)=>{let n=`${this.webSocketUrl}/flags/bootstrap`,s=new WebSocket(n);s.onopen=()=>{e(s)},s.onerror=a=>{t(a)},s.onclose=()=>{this.conn=null}});wsSendMessage=(e,t)=>new Promise((n,s)=>{if(c(t)==c(this.context)){n();return}this.context=t;let a=()=>{let o=!1,d=f=>{let S=JSON.parse(f.data);c(t)in this.values||(this.values[c(t)]={}),(S.flags??[]).forEach(v=>{this.values[c(t)][v.flag]=v.value}),this.flagListener&&this.flagListener(this.values[c(t)]),o||(o=!0,n()),e.removeEventListener("message",d)};e.addEventListener("message",d),e.send(JSON.stringify({apiKey:this.apiKey,data:t}))};e.readyState===WebSocket.OPEN?a():e.readyState===WebSocket.CONNECTING?e.addEventListener("open",a):s("WebSocket is not open or connecting")})};function c(r){let e=Object.keys(r).reduce((t,n)=>{let a=Object.keys(r[n]||{}).sort().reduce((o,d)=>(o[d]=r[n][d],o),{});return t[n]=a,t},{});return JSON.stringify(e)}window.Schematic=h;})();
2
2
  /* @preserve */
@@ -168,34 +168,51 @@ var Schematic = class {
168
168
  return false;
169
169
  });
170
170
  };
171
- cleanup = () => {
171
+ cleanup = async () => {
172
172
  if (this.conn) {
173
- this.conn.close();
173
+ try {
174
+ const socket = await this.conn;
175
+ socket.close();
176
+ } catch (error) {
177
+ console.error("Error during cleanup:", error);
178
+ } finally {
179
+ this.conn = null;
180
+ }
174
181
  }
175
182
  };
176
183
  // Send an identify event
177
184
  identify = (body) => {
178
- this.handleEvent("identify", body);
185
+ this.setContext({
186
+ company: body.company?.keys,
187
+ user: body.keys
188
+ });
189
+ return this.handleEvent("identify", body);
179
190
  };
180
191
  // Set the flag evaluation context; if the context has changed,
181
192
  // this will open a websocket connection (if not already open)
182
193
  // and submit this context. The promise will resolve when the
183
194
  // websocket sends back an initial set of flag values.
184
- setContext = (context) => {
195
+ setContext = async (context) => {
185
196
  if (!this.useWebSocket) {
186
197
  this.context = context;
187
198
  return Promise.resolve();
188
199
  }
189
- return new Promise((resolve) => {
190
- this.wsConnect().then(() => {
191
- this.wsSendMessage(context);
192
- resolve();
193
- });
200
+ if (!this.conn) {
201
+ this.conn = this.wsConnect();
202
+ }
203
+ return this.conn.then((socket) => {
204
+ return this.wsSendMessage(socket, context);
194
205
  });
195
206
  };
196
207
  // Send track event
197
208
  track = (body) => {
198
- this.handleEvent("track", body);
209
+ const { company, user, event, traits } = body;
210
+ return this.handleEvent("track", {
211
+ company: company ?? this.context.company,
212
+ event,
213
+ traits: traits ?? {},
214
+ user: user ?? this.context.user
215
+ });
199
216
  };
200
217
  flushEventQueue = () => {
201
218
  while (this.eventQueue.length > 0) {
@@ -227,64 +244,56 @@ var Schematic = class {
227
244
  type: eventType
228
245
  };
229
246
  if (document?.hidden) {
230
- this.storeEvent(event);
247
+ return this.storeEvent(event);
231
248
  } else {
232
- this.sendEvent(event);
249
+ return this.sendEvent(event);
233
250
  }
234
251
  };
235
- sendEvent = (event) => {
252
+ sendEvent = async (event) => {
236
253
  const captureUrl = `${this.eventUrl}/e`;
237
254
  const payload = JSON.stringify(event);
238
- fetch(captureUrl, {
239
- method: "POST",
240
- headers: {
241
- "Content-Type": "application/json;charset=UTF-8"
242
- },
243
- body: payload
244
- }).then((response) => {
245
- if (!response.ok) {
246
- throw new Error(
247
- `Network response was not ok: ${response.statusText}`
248
- );
249
- }
250
- }).catch((error) => {
251
- console.error("There was a problem with the fetch operation:", error);
252
- });
255
+ try {
256
+ await fetch(captureUrl, {
257
+ method: "POST",
258
+ headers: {
259
+ "Content-Type": "application/json;charset=UTF-8"
260
+ },
261
+ body: payload
262
+ });
263
+ } catch (error) {
264
+ console.error("Error sending Schematic event: ", error);
265
+ }
266
+ return Promise.resolve();
253
267
  };
254
268
  storeEvent = (event) => {
255
269
  this.eventQueue.push(event);
270
+ return Promise.resolve();
256
271
  };
257
272
  wsConnect = () => {
258
- return new Promise((resolve) => {
259
- if (this.conn) {
260
- resolve();
261
- }
273
+ return new Promise((resolve, reject) => {
262
274
  const wsUrl = `${this.webSocketUrl}/flags/bootstrap`;
263
275
  const webSocket = new WebSocket(wsUrl);
264
- this.conn = webSocket;
265
276
  webSocket.onopen = () => {
266
- resolve();
277
+ resolve(webSocket);
278
+ };
279
+ webSocket.onerror = (error) => {
280
+ reject(error);
267
281
  };
268
282
  webSocket.onclose = () => {
269
283
  this.conn = null;
270
284
  };
271
285
  });
272
286
  };
273
- // Sends a message with a new context over the websocket connection
274
- wsSendMessage = (context) => {
287
+ wsSendMessage = (socket, context) => {
275
288
  return new Promise((resolve, reject) => {
276
289
  if (contextString(context) == contextString(this.context)) {
277
290
  resolve();
278
291
  return;
279
292
  }
280
293
  this.context = context;
281
- if (!this.conn) {
282
- reject("Not connected");
283
- return;
284
- }
285
- if (this.conn.readyState === WebSocket.OPEN) {
294
+ const sendMessage = () => {
286
295
  let resolved = false;
287
- this.conn.onmessage = (event) => {
296
+ const messageHandler = (event) => {
288
297
  const message = JSON.parse(event.data);
289
298
  if (!(contextString(context) in this.values)) {
290
299
  this.values[contextString(context)] = {};
@@ -301,22 +310,22 @@ var Schematic = class {
301
310
  resolved = true;
302
311
  resolve();
303
312
  }
313
+ socket.removeEventListener("message", messageHandler);
304
314
  };
305
- this.conn.onerror = (error) => {
306
- console.error("Schematic websocket error: ", error);
307
- };
308
- this.conn.send(
315
+ socket.addEventListener("message", messageHandler);
316
+ socket.send(
309
317
  JSON.stringify({
310
318
  apiKey: this.apiKey,
311
319
  data: context
312
320
  })
313
321
  );
314
- } else if (this.conn.readyState === WebSocket.CONNECTING) {
315
- this.conn.onopen = () => {
316
- this.wsSendMessage(context);
317
- };
322
+ };
323
+ if (socket.readyState === WebSocket.OPEN) {
324
+ sendMessage();
325
+ } else if (socket.readyState === WebSocket.CONNECTING) {
326
+ socket.addEventListener("open", sendMessage);
318
327
  } else {
319
- reject("Not connected");
328
+ reject("WebSocket is not open or connecting");
320
329
  }
321
330
  });
322
331
  };
@@ -16,22 +16,20 @@ export { Event_2 as Event }
16
16
 
17
17
  export declare type EventBody = EventBodyIdentify | EventBodyTrack;
18
18
 
19
- export declare type EventBodyCompany = {
20
- keys: Keys;
21
- name?: string;
22
- traits: Traits;
23
- };
24
-
25
19
  export declare type EventBodyIdentify = {
26
- company?: EventBodyCompany;
27
- keys: Keys;
20
+ company?: {
21
+ keys?: Keys;
22
+ name?: string;
23
+ traits?: Traits;
24
+ };
25
+ keys?: Keys;
28
26
  name?: string;
29
- traits: Traits;
27
+ traits?: Traits;
30
28
  };
31
29
 
32
30
  export declare type EventBodyTrack = SchematicContext & {
33
31
  event: string;
34
- traits: Traits;
32
+ traits?: Traits;
35
33
  };
36
34
 
37
35
  export declare type EventType = "identify" | "track";
@@ -66,10 +64,10 @@ export declare class Schematic {
66
64
  constructor(apiKey: string, options?: SchematicOptions);
67
65
  checkFlag(options: CheckOptions): Promise<boolean>;
68
66
  checkFlags: (context?: SchematicContext) => Promise<Record<string, boolean>>;
69
- cleanup: () => void;
70
- identify: (body: EventBodyIdentify) => void;
67
+ cleanup: () => Promise<void>;
68
+ identify: (body: EventBodyIdentify) => Promise<void>;
71
69
  setContext: (context: SchematicContext) => Promise<void>;
72
- track: (body: EventBodyTrack) => void;
70
+ track: (body: EventBodyTrack) => Promise<void>;
73
71
  private flushEventQueue;
74
72
  private getAnonymousId;
75
73
  private handleEvent;
@@ -142,34 +142,51 @@ var Schematic = class {
142
142
  return false;
143
143
  });
144
144
  };
145
- cleanup = () => {
145
+ cleanup = async () => {
146
146
  if (this.conn) {
147
- this.conn.close();
147
+ try {
148
+ const socket = await this.conn;
149
+ socket.close();
150
+ } catch (error) {
151
+ console.error("Error during cleanup:", error);
152
+ } finally {
153
+ this.conn = null;
154
+ }
148
155
  }
149
156
  };
150
157
  // Send an identify event
151
158
  identify = (body) => {
152
- this.handleEvent("identify", body);
159
+ this.setContext({
160
+ company: body.company?.keys,
161
+ user: body.keys
162
+ });
163
+ return this.handleEvent("identify", body);
153
164
  };
154
165
  // Set the flag evaluation context; if the context has changed,
155
166
  // this will open a websocket connection (if not already open)
156
167
  // and submit this context. The promise will resolve when the
157
168
  // websocket sends back an initial set of flag values.
158
- setContext = (context) => {
169
+ setContext = async (context) => {
159
170
  if (!this.useWebSocket) {
160
171
  this.context = context;
161
172
  return Promise.resolve();
162
173
  }
163
- return new Promise((resolve) => {
164
- this.wsConnect().then(() => {
165
- this.wsSendMessage(context);
166
- resolve();
167
- });
174
+ if (!this.conn) {
175
+ this.conn = this.wsConnect();
176
+ }
177
+ return this.conn.then((socket) => {
178
+ return this.wsSendMessage(socket, context);
168
179
  });
169
180
  };
170
181
  // Send track event
171
182
  track = (body) => {
172
- this.handleEvent("track", body);
183
+ const { company, user, event, traits } = body;
184
+ return this.handleEvent("track", {
185
+ company: company ?? this.context.company,
186
+ event,
187
+ traits: traits ?? {},
188
+ user: user ?? this.context.user
189
+ });
173
190
  };
174
191
  flushEventQueue = () => {
175
192
  while (this.eventQueue.length > 0) {
@@ -201,64 +218,56 @@ var Schematic = class {
201
218
  type: eventType
202
219
  };
203
220
  if (document?.hidden) {
204
- this.storeEvent(event);
221
+ return this.storeEvent(event);
205
222
  } else {
206
- this.sendEvent(event);
223
+ return this.sendEvent(event);
207
224
  }
208
225
  };
209
- sendEvent = (event) => {
226
+ sendEvent = async (event) => {
210
227
  const captureUrl = `${this.eventUrl}/e`;
211
228
  const payload = JSON.stringify(event);
212
- fetch(captureUrl, {
213
- method: "POST",
214
- headers: {
215
- "Content-Type": "application/json;charset=UTF-8"
216
- },
217
- body: payload
218
- }).then((response) => {
219
- if (!response.ok) {
220
- throw new Error(
221
- `Network response was not ok: ${response.statusText}`
222
- );
223
- }
224
- }).catch((error) => {
225
- console.error("There was a problem with the fetch operation:", error);
226
- });
229
+ try {
230
+ await fetch(captureUrl, {
231
+ method: "POST",
232
+ headers: {
233
+ "Content-Type": "application/json;charset=UTF-8"
234
+ },
235
+ body: payload
236
+ });
237
+ } catch (error) {
238
+ console.error("Error sending Schematic event: ", error);
239
+ }
240
+ return Promise.resolve();
227
241
  };
228
242
  storeEvent = (event) => {
229
243
  this.eventQueue.push(event);
244
+ return Promise.resolve();
230
245
  };
231
246
  wsConnect = () => {
232
- return new Promise((resolve) => {
233
- if (this.conn) {
234
- resolve();
235
- }
247
+ return new Promise((resolve, reject) => {
236
248
  const wsUrl = `${this.webSocketUrl}/flags/bootstrap`;
237
249
  const webSocket = new WebSocket(wsUrl);
238
- this.conn = webSocket;
239
250
  webSocket.onopen = () => {
240
- resolve();
251
+ resolve(webSocket);
252
+ };
253
+ webSocket.onerror = (error) => {
254
+ reject(error);
241
255
  };
242
256
  webSocket.onclose = () => {
243
257
  this.conn = null;
244
258
  };
245
259
  });
246
260
  };
247
- // Sends a message with a new context over the websocket connection
248
- wsSendMessage = (context) => {
261
+ wsSendMessage = (socket, context) => {
249
262
  return new Promise((resolve, reject) => {
250
263
  if (contextString(context) == contextString(this.context)) {
251
264
  resolve();
252
265
  return;
253
266
  }
254
267
  this.context = context;
255
- if (!this.conn) {
256
- reject("Not connected");
257
- return;
258
- }
259
- if (this.conn.readyState === WebSocket.OPEN) {
268
+ const sendMessage = () => {
260
269
  let resolved = false;
261
- this.conn.onmessage = (event) => {
270
+ const messageHandler = (event) => {
262
271
  const message = JSON.parse(event.data);
263
272
  if (!(contextString(context) in this.values)) {
264
273
  this.values[contextString(context)] = {};
@@ -275,22 +284,22 @@ var Schematic = class {
275
284
  resolved = true;
276
285
  resolve();
277
286
  }
287
+ socket.removeEventListener("message", messageHandler);
278
288
  };
279
- this.conn.onerror = (error) => {
280
- console.error("Schematic websocket error: ", error);
281
- };
282
- this.conn.send(
289
+ socket.addEventListener("message", messageHandler);
290
+ socket.send(
283
291
  JSON.stringify({
284
292
  apiKey: this.apiKey,
285
293
  data: context
286
294
  })
287
295
  );
288
- } else if (this.conn.readyState === WebSocket.CONNECTING) {
289
- this.conn.onopen = () => {
290
- this.wsSendMessage(context);
291
- };
296
+ };
297
+ if (socket.readyState === WebSocket.OPEN) {
298
+ sendMessage();
299
+ } else if (socket.readyState === WebSocket.CONNECTING) {
300
+ socket.addEventListener("open", sendMessage);
292
301
  } else {
293
- reject("Not connected");
302
+ reject("WebSocket is not open or connecting");
294
303
  }
295
304
  });
296
305
  };
package/package.json CHANGED
@@ -46,5 +46,5 @@
46
46
  "test": "jest --config jest.config.js"
47
47
  },
48
48
  "types": "dist/schematic.d.ts",
49
- "version": "0.1.10"
49
+ "version": "0.1.12"
50
50
  }