1 | const os = require(`os`)
|
2 | const path = require(`path`)
|
3 | const Store = require(`./store`)
|
4 | const fetch = require(`node-fetch`)
|
5 | const Configstore = require(`configstore`)
|
6 | const { ensureDirSync } = require(`fs-extra`)
|
7 |
|
8 | const isTruthy = require(`./is-truthy`)
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | module.exports = class EventStorage {
|
17 | analyticsApi =
|
18 | process.env.GATSBY_TELEMETRY_API || `https://analytics.gatsbyjs.com/events`
|
19 | constructor() {
|
20 | try {
|
21 | this.config = new Configstore(`gatsby`, {}, { globalConfigPath: true })
|
22 | } catch (e) {
|
23 |
|
24 | this.config = {
|
25 | get: key => this.config[key],
|
26 | set: (key, value) => (this.config[key] = value),
|
27 | all: this.config,
|
28 | path: path.join(os.tmpdir(), `gatsby`),
|
29 | "telemetry.enabled": true,
|
30 | "telemetry.machineId": `not-a-machine-id`,
|
31 | }
|
32 | }
|
33 |
|
34 | const baseDir = path.dirname(this.config.path)
|
35 |
|
36 | try {
|
37 | ensureDirSync(baseDir)
|
38 | } catch (e) {
|
39 |
|
40 | }
|
41 |
|
42 | this.store = new Store(baseDir)
|
43 | this.verbose = isTruthy(process.env.GATSBY_TELEMETRY_VERBOSE)
|
44 | this.debugEvents = isTruthy(process.env.GATSBY_TELEMETRY_DEBUG)
|
45 | this.disabled = isTruthy(process.env.GATSBY_TELEMETRY_DISABLED)
|
46 | }
|
47 |
|
48 | isTrackingDisabled() {
|
49 | return this.disabled
|
50 | }
|
51 |
|
52 | addEvent(event) {
|
53 | if (this.disabled) {
|
54 | return
|
55 | }
|
56 |
|
57 | const eventString = JSON.stringify(event)
|
58 |
|
59 | if (this.debugEvents || this.verbose) {
|
60 | console.error(`Captured event:`, JSON.parse(eventString))
|
61 |
|
62 | if (this.debugEvents) {
|
63 |
|
64 | return
|
65 | }
|
66 | }
|
67 |
|
68 | this.store.appendToBuffer(eventString + `\n`)
|
69 | }
|
70 |
|
71 | async sendEvents() {
|
72 | return this.store.startFlushEvents(async eventsData => {
|
73 | const events = eventsData
|
74 | .split(`\n`)
|
75 | .filter(e => e && e.length > 2)
|
76 | .map(e => JSON.parse(e))
|
77 |
|
78 | return this.submitEvents(events)
|
79 | })
|
80 | }
|
81 |
|
82 | async submitEvents(events) {
|
83 | try {
|
84 | const res = await fetch(this.analyticsApi, {
|
85 | method: `POST`,
|
86 | headers: {
|
87 | "content-type": `application/json`,
|
88 | "user-agent": this.getUserAgent(),
|
89 | },
|
90 | body: JSON.stringify(events),
|
91 | })
|
92 | return res.ok
|
93 | } catch (e) {
|
94 | return false
|
95 | }
|
96 | }
|
97 |
|
98 | getUserAgent() {
|
99 | try {
|
100 | const { name, version } = require(`../package.json`)
|
101 | return `${name}:${version}`
|
102 | } catch (e) {
|
103 | return `Gatsby Telemetry`
|
104 | }
|
105 | }
|
106 |
|
107 | getConfig(key) {
|
108 | if (key) {
|
109 | return this.config.get(key)
|
110 | }
|
111 | return this.config.all
|
112 | }
|
113 |
|
114 | updateConfig(key, value) {
|
115 | return this.config.set(key, value)
|
116 | }
|
117 | }
|