import { DestinationPlugin } from '../plugin' ; import { PluginType , SegmentAPIIntegrations , SegmentAPISettings , SegmentEvent , UpdateType , } from '../types' ; import { chunk } from '../util' ; import { sendEvents } from '../api' ; const MAX_EVENTS_PER_BATCH = 100 ; export class SegmentDestination extends DestinationPlugin { type = PluginType . destination ; key = 'Segment.io' ; update ( _ , __ ) { } execute ( event ) { const pluginSettings = this . analytics ?. settings . get ( ) ; const plugins = this . analytics ?. getPlugins ( PluginType . destination ) ; const deviceModePlugins = plugins ?. map ( ( plugin ) => ( plugin as DestinationPlugin ) . key ) ?? [ ] ; const cloudSettings = { ... pluginSettings , } ; for ( const key of deviceModePlugins ) { if ( key in cloudSettings ) { cloudSettings [ key ] = false ; } } const mergedEvent = { ... event , integrations : { ... cloudSettings , ... event ?. integrations , } , } ; this . analytics ?. queueEvent ( mergedEvent ) ; return mergedEvent ; } async flush ( ) { const events = this . analytics ?. events . get ( ) ?? [ ] ; const chunkedEvents = chunk ( events , this . analytics ?. getConfig ( ) . maxBatchSize ?? MAX_EVENTS_PER_BATCH ) ; let sentEvents = [ ] ; let numFailedEvents = 0 ; await Promise . all ( chunkedEvents . map ( async ( batch ) => { try { await sendEvents ( { config : this . analytics ?. getConfig ( ) ! , events : batch , } ) ; sentEvents = sentEvents . concat ( batch ) ; } catch ( e ) { console . warn ( e ) ; numFailedEvents += batch . length ; } finally { this . analytics ?. removeEvents ( sentEvents ) ; } } ) ) ; if ( sentEvents . length ) { console . warn ( `Sent ${ sentEvents . length } events` ) ; } if ( numFailedEvents ) { console . error ( `Failed to send ${ numFailedEvents } events.` ) ; } } }