1import $ from 'jquery';
2import { EchoBackend, EchoEventType, isInteractionEvent, isPageviewEvent, PageviewEchoEvent } from '@grafana/runtime';
3import { User } from '../sentry/types';
4
5export interface RudderstackBackendOptions {
6  writeKey: string;
7  dataPlaneUrl: string;
8  user?: User;
9}
10
11export class RudderstackBackend implements EchoBackend<PageviewEchoEvent, RudderstackBackendOptions> {
12  supportedEvents = [EchoEventType.Pageview, EchoEventType.Interaction];
13
14  constructor(public options: RudderstackBackendOptions) {
15    const url = `https://cdn.rudderlabs.com/v1/rudder-analytics.min.js`;
16
17    $.ajax({
18      url,
19      dataType: 'script',
20      cache: true,
21    });
22
23    const rds = ((window as any).rudderanalytics = []);
24
25    var methods = [
26      'load',
27      'page',
28      'track',
29      'identify',
30      'alias',
31      'group',
32      'ready',
33      'reset',
34      'getAnonymousId',
35      'setAnonymousId',
36    ];
37
38    for (let i = 0; i < methods.length; i++) {
39      const method = methods[i];
40      (rds as Record<string, any>)[method] = (function (methodName) {
41        return function () {
42          // @ts-ignore
43          rds.push([methodName].concat(Array.prototype.slice.call(arguments)));
44        };
45      })(method);
46    }
47
48    (rds as any).load(options.writeKey, options.dataPlaneUrl);
49
50    if (options.user) {
51      (rds as any).identify(options.user.email, {
52        email: options.user.email,
53        orgId: options.user.orgId,
54      });
55    }
56  }
57
58  addEvent = (e: PageviewEchoEvent) => {
59    if (!(window as any).rudderanalytics) {
60      return;
61    }
62
63    if (isPageviewEvent(e)) {
64      (window as any).rudderanalytics.page();
65    }
66
67    if (isInteractionEvent(e)) {
68      (window as any).rudderanalytics.track(e.payload.interactionName, e.payload.properties);
69    }
70  };
71
72  // Not using Echo buffering, addEvent above sends events to GA as soon as they appear
73  flush = () => {};
74}
75