UNPKG

2.97 kBJavaScriptView Raw
1"use strict";
2
3var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
5var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
6
7const os = require(`os`);
8
9const path = require(`path`);
10
11const Store = require(`./store`);
12
13const fetch = require(`node-fetch`);
14
15const Configstore = require(`configstore`);
16
17const {
18 ensureDirSync
19} = require(`fs-extra`);
20
21const isTruthy = require(`./is-truthy`);
22/* The events data collection is a spooled process that
23 * buffers events to a local fs based buffer
24 * which then is asynchronously flushed to the server.
25 * This both increases the fault tolerancy and allows collection
26 * to continue even when working offline.
27 */
28
29
30module.exports = class EventStorage {
31 constructor() {
32 (0, _defineProperty2.default)(this, "analyticsApi", process.env.GATSBY_TELEMETRY_API || `https://analytics.gatsbyjs.com/events`);
33
34 try {
35 this.config = new Configstore(`gatsby`, {}, {
36 globalConfigPath: true
37 });
38 } catch (e) {
39 // This should never happen
40 this.config = {
41 get: key => this.config[key],
42 set: (key, value) => this.config[key] = value,
43 all: this.config,
44 path: path.join(os.tmpdir(), `gatsby`),
45 "telemetry.enabled": true,
46 "telemetry.machineId": `not-a-machine-id`
47 };
48 }
49
50 const baseDir = path.dirname(this.config.path);
51
52 try {
53 ensureDirSync(baseDir);
54 } catch (e) {// TODO: Log this event
55 }
56
57 this.store = new Store(baseDir);
58 this.verbose = isTruthy(process.env.GATSBY_TELEMETRY_VERBOSE);
59 this.debugEvents = isTruthy(process.env.GATSBY_TELEMETRY_DEBUG);
60 this.disabled = isTruthy(process.env.GATSBY_TELEMETRY_DISABLED);
61 }
62
63 isTrackingDisabled() {
64 return this.disabled;
65 }
66
67 addEvent(event) {
68 if (this.disabled) {
69 return;
70 }
71
72 const eventString = JSON.stringify(event);
73
74 if (this.debugEvents || this.verbose) {
75 console.error(`Captured event:`, JSON.parse(eventString));
76
77 if (this.debugEvents) {
78 // Bail because we don't want to send debug events
79 return;
80 }
81 }
82
83 this.store.appendToBuffer(eventString + `\n`);
84 }
85
86 async sendEvents() {
87 return this.store.startFlushEvents(async eventsData => {
88 const events = eventsData.split(`\n`).filter(e => e && e.length > 2) // drop empty lines
89 .map(e => JSON.parse(e));
90 return this.submitEvents(events);
91 });
92 }
93
94 async submitEvents(events) {
95 try {
96 const res = await fetch(this.analyticsApi, {
97 method: `POST`,
98 headers: {
99 "content-type": `application/json`
100 },
101 body: JSON.stringify(events)
102 });
103 return res.ok;
104 } catch (e) {
105 return false;
106 }
107 }
108
109 getConfig(key) {
110 if (key) {
111 return this.config.get(key);
112 }
113
114 return this.config.all;
115 }
116
117 updateConfig(key, value) {
118 return this.config.set(key, value);
119 }
120
121};
\No newline at end of file