-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkrenalis.js
More file actions
871 lines (814 loc) · 22.3 KB
/
krenalis.js
File metadata and controls
871 lines (814 loc) · 22.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
// MIT License
// Copyright (c) 2026 Open2b
// See the LICENSE file for full text.
import { campaign, debug, isPlainObject, isURL, onVisibilityChange, parseQueryString, uuid } from './utils.js'
import Elections from './elections.js'
import Group from './group.js'
import Options from './options.js'
import Queue, { ItemTooLargeError } from './queue.js'
import Sender from './sender.js'
import Session from './session.js'
import Storage from './storage.js'
import User from './user.js'
const version = '0.0.0'
const none = () => {}
// maxEventSize is the maximum size, in bytes, for a single JSON serialized
// event. Events exceeding this size will not be appended to the queue.
const maxEventSize = 32 * 1024
// maxSafeInteger is the maximum safe integer. It is the same as
// Number.MAX_SAFE_INTEGER, which is not available in Internet Explorer.
const maxSafeInteger = 9007199254740991
// queueKeyReg is the regexp for storage queue keys.
const queueKeyReg = /^krenalis\.[a-zA-Z0-9]{7}\.[a-zA-Z0-9]{8}(?:-[a-zA-Z0-9]{4}){3}-[a-zA-Z0-9]{12}\.queue$/
class EndpointURLError extends Error {
constructor(endpoint) {
super(`The endpoint URL '${endpoint}' is not valid.`)
this.name = this.constructor.name
}
}
class Krenalis {
#id
#writeKey
#endpoint
#ready
#options
#storage
#session
#keysPrefix
#queue
#sender
#user
#group
#elections
#isLeader = false
#onFollowerQueue = null // is null when it is not the leader
#debug
// constructor returns a new Krenalis instance. writeKey is the write key,
// endpoint denotes the endpoint URL, and options is an object containing
// the options, if any. If endpoint is not a valid URL, it raises an
// EndpointURLError error.
constructor(writeKey, endpoint, options) {
if (!isURL(endpoint)) {
throw new EndpointURLError(endpoint)
}
this.#id = uuid()
this.#writeKey = writeKey
this.#endpoint = endpoint
this.#ready = new Ready()
this.#options = new Options(writeKey, endpoint, options, (error) => {
if (this.#ready) {
if (error == null && this.#options.useQueryString != null) {
this.#processQuerystring()
}
this.#ready.emit(error)
}
})
this.#storage = new Storage(writeKey, this.#options)
this.#session = new Session(
this.#storage,
this.#options.sessions.autoTrack,
this.#options.sessions.timeout,
this.#options.debug,
)
this.#keysPrefix = `krenalis.${writeKey.slice(0, 7)}`
this.#queue = new Queue(localStorage, `${this.#keysPrefix}.*.queue`, maxEventSize)
this.#queue.debug(this.#options.debug)
this.#user = new User(this.#storage)
this.#group = new Group(this.#storage)
// Participate in leader elections.
const electionsState = new ElectionsState(this.#keysPrefix)
this.#elections = new Elections(this.#id, electionsState, this.#onElection.bind(this))
onVisibilityChange((visible) => {
if (!visible) {
this.#queue.save()
if (this.#isLeader) {
this.#sender.flush()
this.#elections.resign()
}
}
})
this.debug(this.#options.debug)
}
// alias sends an alias event.
alias() {
return this.#send('alias', this.#setAliasArguments, arguments)
}
// close closes the Krenalis instance.
// It tries to preserve the queue in the localStorage before returning.
close() {
this.#elections.close()
if (this.#isLeader) {
this.#sender.close()
}
this.#queue.close()
this.#ready.close()
this.#ready = null
this.#debug?.('Krenalis closed')
}
// debug toggles debug mode.
debug(on) {
this.#debug = debug(on)
this.#ready.debug(on)
this.#session.debug(on)
this.#queue.debug(on)
if (this.#isLeader) {
this.#sender.debug(on)
}
}
// endSession ends the session.
// If there is no session, it does nothing.
endSession() {
this.#session.end()
}
// getAnonymousId returns the current Anonymous ID. If no Anonymous ID
// exists, it generates one and returns it.
getAnonymousId() {
return this.#user.anonymousId()
}
// getSessionId returns the current session ID, or null if there is no
// session.
getSessionId() {
return this.#session.get()
}
// group sends a group event, if there is no arguments, it returns the
// current group as a value with methods 'id', to get the Group ID, and
// 'traits' to get the traits.
group() {
if (arguments.length === 0) {
return this.#group
}
return this.#send('group', this.#setGroupArguments, arguments)
}
// identify sends an identify event.
identify() {
return this.#send('identify', this.#setIdentifyArguments, arguments)
}
// page sends a page event.
page() {
return this.#send('page', this.#setPageScreenArguments, arguments)
}
// ready calls callback, if not null, after Krenalis finishes initializing.
// If promises are supported, it also returns a promise.
ready(callback) {
if (callback != null) {
this.#ready.addListener(callback)
}
if (typeof globalThis.Promise === 'function') {
return new Promise((resolve, reject) => {
this.#ready.addListener(resolve, reject)
})
}
}
// reset resets the user and group identifiers, and updates or
// removes the Anonymous ID and traits according to the strategy. If
// "all" is true it always resets the Anonymous ID by generating a
// new one, and ends the session if one exists, regardless of the
// strategy.
reset(all) {
this.#storage.setUserId()
const strategy = this.#options.strategy
if (!all && strategy === 'Preservation') {
this.#storage.restore()
return
}
this.#storage.setGroupId()
this.#storage.setTraits('user')
this.#storage.setTraits('group')
this.#storage.removeSuspended()
if (all || strategy === 'Conversion' || strategy === 'Isolation') {
this.#storage.setAnonymousId()
this.#session.reset()
}
}
// screen sends a screen event.
screen() {
return this.#send('screen', this.#setPageScreenArguments, arguments)
}
// setAnonymousId sets the default Anonymous ID or, if id is undefined,
// returns the default Anonymous ID.
setAnonymousId(id) {
return this.#user.anonymousId(id)
}
// startSession starts a new session.
startSession(id) {
if (id == null) {
id = null
} else {
// Check that it is a number and can be represented as a positive integer.
if (typeof id !== 'number' || id <= 0 || id > maxSafeInteger || id % 1 !== 0) {
throw new Error('sessionId must be a positive integer')
}
}
this.#session.start(id)
}
// track sends a track event.
track() {
return this.#send('track', this.#setTrackArguments, arguments)
}
// user returns the current user as a value with methods 'id', to get the
// User ID, 'traits' to get the traits, and 'anonymousId' to get the
// Anonymous ID.
user() {
return this.#user
}
// getAlias returns the userId or previousId arguments of the alias calls.
#getAlias(id) {
if ((typeof id === 'string' && id !== '') || typeof id === 'number') {
return String(id)
}
id = this.#storage.userId()
if (id == null) {
return this.#user.anonymousId()
}
return id
}
// normalizeOptions copies options and removes undefined values and invalid
// field types.
#normalizeOptions(options) {
const opts = {}
if (!isPlainObject(options) || Object.keys(options).length === 0) {
return opts
}
for (const k of Object.keys(options)) {
const v = options[k]
if (v !== void 0) {
opts[k] = v
}
}
if ('timestamp' in opts && !(opts.timestamp instanceof Date) && typeof opts.timestamp !== 'string') {
delete opts.timestamp
}
if ('messageId' in opts && typeof opts.messageId !== 'string') {
delete opts.messageId
}
if ('integrations' in opts && !isPlainObject(opts.integrations)) {
delete opts.integrations
}
if ('context' in opts && !isPlainObject(opts.context)) {
delete opts.context
}
return opts
}
// onElection is called when an election occurs. isLeader reports whether it
// is the leader.
#onElection(isLeader) {
if (isLeader === this.#isLeader) {
return
}
this.#isLeader = isLeader
if (!isLeader) {
this.#debug?.(`there is another leader`)
this.#sender.close()
this.#sender = null
this.#queue.setKey(`${this.#keysPrefix}.*.queue`)
removeEventListener('storage', this.#onFollowerQueue)
this.#onFollowerQueue = null
return
}
this.#debug?.(`elected as leader`)
this.#queue.setKey(`${this.#keysPrefix}.${this.#id}.queue`)
// Listen to new follower queues to merge.
const merged = new Set()
this.#onFollowerQueue = (event) => {
if (this.#isLeader && event.storageArea === localStorage && event.newValue != null) {
const key = event.key
if (!merged.has(key) && queueKeyReg.test(key)) {
this.#queue.load(key)
localStorage.removeItem(key)
}
}
}
addEventListener('storage', this.#onFollowerQueue)
// Merge existing follower queues.
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i)
if (queueKeyReg.test(key)) {
this.#queue.load(key)
merged.add(key)
}
}
if (merged.size > 0) {
this.#queue.save()
for (const key of merged) {
localStorage.removeItem(key)
}
}
this.#sender = new Sender(this.#writeKey, this.#endpoint, this.#queue)
if (this.#debug != null) {
this.#sender.debug(true)
}
}
// processQuerystring processes the query string according to the
// Querystring API.
#processQuerystring() {
const qs = parseQueryString(globalThis.location.search, 'ajs_')
if (qs.size > 0) {
const extract = (prefix) => {
const props = {}
for (const [k, v] of qs) {
// ES5: "startsWith" is not available.
if (k.indexOf(prefix) === 0) {
props[k.substring(prefix.length)] = v
}
}
return props
}
const aid = qs.get('aid')
if (this.#options.useQueryString.aid.test(aid)) {
this.#user.anonymousId(aid)
}
const uid = qs.get('uid')
if (this.#options.useQueryString.uid.test(uid)) {
void this.#send('identify', this.#setIdentifyArguments, [uid, extract('trait_')])
}
const event = qs.get('event')
if (event) {
void this.#send('track', this.#setTrackArguments, [event, extract('prop_')])
}
}
}
// send sends an event of the given type, setting the arguments args with
// the setArgs function.
#send(type, setArgs, args) {
const executor = (resolve, reject) => {
const event = { type }
// ES5: "Array.from" is not available.
args = Array.prototype.slice.call(args)
let callback
if (args.length > 0 && typeof args[args.length - 1] === 'function') {
callback = args.pop()
}
try {
const options = setArgs.call(this, event, args)
this.#sendEvent(event, this.#normalizeOptions(options))
} catch (error) {
reject(error)
return
}
if (callback) {
callback({ attempts: 1, event: event })
}
resolve({ attempts: 1, event: event })
}
if (typeof globalThis.Promise === 'function') {
return new Promise(executor)
}
executor(none, none)
}
// sendEvent sends an event with the given options.
#sendEvent(event, options) {
if ('timestamp' in options) {
event.timestamp = options.timestamp
} else {
event.timestamp = new Date()
}
const loc = globalThis.location
let url
let path
{
const canonical = document.querySelector('link[rel="canonical"]')
if (canonical == null) {
url = loc.href
path = loc.pathname
} else {
url = canonical.href
// IE11 does not support URL.
if (typeof globalThis.URL === 'function') {
path = new URL(url).pathname
} else {
const a = document.createElement('a')
a.href = url
path = a.pathname !== '' ? a.pathname : '/'
}
}
const p = url.indexOf('#')
if (p !== -1) {
url = url.substring(0, p)
}
}
const page = {
path: path,
referrer: document.referrer == null ? '' : document.referrer,
search: loc.search,
title: document.title,
url: url,
}
switch (event.type) {
case 'page': {
const p = isPlainObject(event.properties) ? event.properties : {}
for (const k in page) {
if (k in p) {
const v = p[k]
if (typeof v === 'string' && v !== '') {
page[k] = v
}
} else {
p[k] = page[k]
}
}
if ('category' in event) {
p.category = event.category
}
if ('name' in event && event.name !== '') {
p.name = event.name
}
event.properties = p
event.userId = this.#user.id()
break
}
case 'screen':
case 'track':
if (!isPlainObject(event.properties)) {
event.properties = {}
}
/* fallthrough */
case 'group':
event.userId = this.#user.id()
break
case 'identify': {
const strategy = this.#options.strategy
if (strategy === 'Isolation' || strategy === 'Preservation') {
if (strategy === 'Preservation') {
this.#storage.suspend()
} else {
this.#storage.removeSuspended()
}
this.#storage.setAnonymousId()
this.#storage.setTraits('user', event.traits)
this.#storage.setGroupId()
this.#storage.setTraits('group')
this.#session.reset()
} else {
event.traits = this.#mergeTraits(this.#user, event.traits)
}
}
}
event.messageId = options.messageId || uuid()
event.anonymousId = this.#user.anonymousId()
const n = navigator
event.context = {
library: {
name: 'krenalis.js',
version: version,
},
// According to caniuse.com, IE11 does not support the 'language' property but does support 'userLanguage'.
// However, empirical testing suggests that IE11 supports both.
locale: n.language || n.userLanguage,
page: page,
screen: {
width: globalThis.screen.width,
height: globalThis.screen.height,
density: Number((globalThis.devicePixelRatio || 1).toFixed(2)),
},
userAgent: n.userAgent,
}
const c = campaign()
if (c.size > 0) {
event.context.campaign = {}
for (const [k, v] of c) {
if (k !== '') {
event.context.campaign[k] = v
}
}
}
try {
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone
if (typeof tz === 'string') {
event.context.timezone = tz
}
} catch (_) {
// The browser may not support Intl.
}
event.integrations = {}
if (typeof options.integrations == 'object') {
for (const n in options.integrations) {
event.integrations[n] = options.integrations[n]
}
}
const [sessionId, sessionStart] = this.#session.getFresh()
if (sessionId != null) {
event.context.sessionId = sessionId
if (sessionStart) {
event.context.sessionStart = true
}
}
// Apply user-provided context last so it can override automatic
// enrichments (campaign, timezone, session, etc).
if ('context' in options) {
this.#mergeContext(event.context, options.context)
}
try {
this.#queue.append(event)
} catch (error) {
if (error instanceof TypeError) {
console.warn('cannot stringify the event to JSON:', error)
} else if (error instanceof ItemTooLargeError) {
console.warn('event size (' + error.size + 'bytes) is greater then 32KB')
} else {
throw error
}
}
}
// mergeContext deeply merges the source context object into target.
#mergeContext(target, source, visited) {
if (visited == null) {
visited = []
}
if (visited.indexOf(source) !== -1) {
return
}
visited.push(source)
for (const k of Object.keys(source)) {
if (k === '__proto__' || k === 'prototype' || k === 'constructor') {
continue
}
const v = source[k]
if (isPlainObject(v)) {
if (visited.indexOf(v) !== -1) {
continue
}
if (!isPlainObject(target[k])) {
target[k] = {}
}
this.#mergeContext(target[k], v, visited)
} else if (v !== void 0) {
target[k] = v
}
}
visited.pop()
}
// setAliasArguments sets the arguments for alias calls.
// It writes the 'userId' and 'previousId' arguments into event and
// returns the options.
#setAliasArguments(event, a) {
if (a.length === 0) {
throw new Error('User is missing')
}
event.userId = this.#getAlias(a.shift())
let options
switch (typesOf(a)) {
// (userId)
case '':
break
// (userId, previousId)
case 'string':
event.previousId = this.#getAlias(a[0])
break
// (userId, options)
case 'object':
options = a[0]
break
// (userId, previousId, options)
case 'string,object':
event.previousId = this.#getAlias(a[0])
options = a[1]
break
default:
throw new Error('Invalid arguments')
}
return options
}
// setIdentifyArguments sets the arguments for identify calls.
// It writes the 'userId' and 'traits' arguments into event and
// returns the options.
#setIdentifyArguments(event, a) {
let options
switch (typesOf(a)) {
// ()
case '':
event.userId = this.#user.id()
break
// (userId)
case 'string':
event.userId = this.#user.id(a[0] == null ? undefined : a[0])
break
// (traits)
case 'object':
event.userId = this.#user.id()
event.traits = a[0]
break
// (userId, traits)
case 'string,object':
event.userId = this.#user.id(a[0] == null ? undefined : a[0])
event.traits = a[1]
break
// (traits, options)
case 'object,object':
event.userId = this.#user.id()
event.traits = a[0]
options = a[1]
break
// (userId, traits, options)
case 'string,object,object':
event.userId = this.#user.id(a[0] == null ? undefined : a[0])
event.traits = a[1]
options = a[2]
break
default:
throw new Error('Invalid arguments')
}
return options
}
// setGroupArguments sets the arguments for group calls.
// It writes the 'groupId' and 'traits' arguments into event and
// returns the options.
#setGroupArguments(event, a) {
let options
switch (typesOf(a)) {
// (groupId)
case 'string':
event.groupId = this.#group.id(a[0] == null ? undefined : a[0])
event.traits = this.#group.traits()
break
// (traits)
case 'object':
event.traits = this.#mergeTraits(this.#group, a[0])
break
// (groupId, traits)
case 'string,object':
event.groupId = this.#group.id(a[0] == null ? undefined : a[0])
event.traits = this.#mergeTraits(this.#group, a[1])
break
// (traits, options)
case 'object,object':
event.traits = this.#mergeTraits(this.#group, a[0])
options = a[1]
break
// (groupId, traits, options)
case 'string,object,object':
event.groupId = this.#group.id(a[0] == null ? undefined : a[0])
event.traits = this.#mergeTraits(this.#group, a[1])
options = a[2]
break
default:
throw new Error('Invalid arguments')
}
return options
}
// setPageScreenArguments sets the arguments for page and screen calls.
// It writes the 'category', 'name', and 'properties' arguments into events
// and returns the options.
#setPageScreenArguments(event, a) {
let options
switch (typesOf(a)) {
// ()
case '':
break
// (name)
case 'string':
event.name = a[0]
break
// (properties)
case 'object':
event.properties = a[0]
break
// (category, name)
case 'string,string':
event.category = a[0]
event.name = a[1]
break
// (name, properties)
case 'string,object':
event.name = a[0]
event.properties = a[1]
break
// (properties, options)
case 'object,object':
event.properties = a[0]
options = a[1]
break
// (category, name, properties)
case 'string,string,object':
event.category = a[0]
event.name = a[1]
event.properties = a[2]
break
// (name, properties, options)
case 'string,object,object':
event.name = a[0]
event.properties = a[1]
options = a[2]
break
// (category, name, properties, options)
case 'string,string,object,object':
event.category = a[0]
event.name = a[1]
event.properties = a[2]
options = a[3]
break
default:
throw new Error('Invalid arguments')
}
return options
}
// setTrackArguments sets the arguments for track calls.
// It writes the 'event' and 'properties' arguments into events and
// returns the options.
#setTrackArguments(event, a) {
if (a.length === 0 || typeof a[0] != 'string') {
throw new Error('Event name is missing')
}
event.event = a.shift()
let options
switch (typesOf(a)) {
// (name)
case '':
break
// (name, properties)
case 'object':
event.properties = a[0]
break
// (name, properties, options)
case 'object,object':
event.properties = a[0]
options = a[1]
break
default:
throw new Error('Invalid arguments')
}
return options
}
// mergeTraits merges traits into the current user's or group's traits,
// stores them, and returns them. If traits is undefined, it only returns
// the current traits. k must be either '#user' or '#group'.
#mergeTraits(k, traits) {
const ts = k.traits()
if (traits === undefined) {
return ts
}
for (const k in traits) {
const v = traits[k]
if (v === undefined) {
delete ts[k]
} else {
ts[k] = v
}
}
k.traits(ts)
return k.traits()
}
}
// Ready handles the event that is fired when Krenalis finishes initializing.
class Ready {
#emitted = false
#listeners = []
#error
#debug
addListener(resolve, reject) {
this.#listeners.push([resolve, reject])
if (this.#emitted) {
this.#notify()
}
}
close() {
if (!this.#emitted) {
this.#error = new Error('Krenalis instance has been closed')
this.#notify()
}
}
debug(on) {
this.#debug = debug(on)
}
emit(error) {
this.#emitted = true
this.#error = error
this.#debug?.(error == null ? 'krenalis is ready' : `krenalis cannot be ready due to an error: ${error}`)
this.#notify()
}
#notify() {
for (let i = 0; i < this.#listeners.length; i++) {
const [resolve, reject] = this.#listeners[i]
if (this.#error == null || reject == null) {
setTimeout(resolve)
} else {
setTimeout(reject, 0, this.#error)
}
}
this.#listeners.length = 0
}
}
// ElectionsState represents the state of the elections.
class ElectionsState {
#keys
constructor(prefix) {
this.#keys = [`${prefix}.leader.beat`, `${prefix}.leader.election`]
}
read(_, location, cb) {
const value = localStorage.getItem(this.#keys[location - 1])
cb(value)
}
write(_, location, value, cb) {
localStorage.setItem(this.#keys[location - 1], value)
cb()
}
}
// typesOf returns a string representing the types of the elements of the array
// arr, 'object' for non-null Object values and 'string' for all the other
// values. If arr is empty, it returns an empty string. For example, if arr is
// ['a', null, 5, {}], it returns 'string,string,string,object'.
// If arr is not an array, it throws an error.
function typesOf(arr) {
return arr.map((v) => typeof v === 'object' && v != null ? 'object' : 'string').join(',')
}
export default Krenalis
export { EndpointURLError, Krenalis }