(options: TrackerCoreOptions)
| 52 | * Create a tracker core instance with batch support |
| 53 | */ |
| 54 | export function createTrackerCore(options: TrackerCoreOptions) { |
| 55 | const { |
| 56 | serverUrl, |
| 57 | websiteId, |
| 58 | batchDelay = 200, |
| 59 | disableBatch = false, |
| 60 | } = options; |
| 61 | const endpoint = `${serverUrl}/api/website/send`; |
| 62 | const batchEndpoint = `${serverUrl}/api/website/batch`; |
| 63 | |
| 64 | const sendSingle = async ( |
| 65 | type: 'event' | 'identify', |
| 66 | payload: WebsiteEventPayload |
| 67 | ): Promise<void> => { |
| 68 | try { |
| 69 | await fetch(endpoint, { |
| 70 | method: 'POST', |
| 71 | headers: { 'Content-Type': 'application/json' }, |
| 72 | body: JSON.stringify({ type, payload }), |
| 73 | }); |
| 74 | } catch (e) { |
| 75 | // Silent fail for tracking |
| 76 | } |
| 77 | }; |
| 78 | |
| 79 | const sendBatch = async (items: BatchItem[]): Promise<void> => { |
| 80 | try { |
| 81 | await fetch(batchEndpoint, { |
| 82 | method: 'POST', |
| 83 | headers: { 'Content-Type': 'application/json' }, |
| 84 | body: JSON.stringify({ events: items }), |
| 85 | }); |
| 86 | } catch (e) { |
| 87 | // Silent fail for tracking |
| 88 | } |
| 89 | }; |
| 90 | |
| 91 | const batchManager = new BatchManager<WebsiteEventPayload>({ |
| 92 | batchDelay, |
| 93 | disableBatch, |
| 94 | onBatchSend: sendBatch, |
| 95 | onSingleSend: (item) => |
| 96 | sendSingle(item.type as 'event' | 'identify', item.payload), |
| 97 | }); |
| 98 | |
| 99 | const getPayload = ( |
| 100 | overrides?: Partial<WebsiteEventPayload> |
| 101 | ): WebsiteEventPayload => ({ |
| 102 | website: websiteId, |
| 103 | ...getBrowserInfo(), |
| 104 | ...overrides, |
| 105 | }); |
| 106 | |
| 107 | return { |
| 108 | track: ( |
| 109 | eventNameOrPayload?: string | WebsiteEventPayload, |
| 110 | eventData?: Record<string, any> |
| 111 | ) => { |
no test coverage detected