UNPKG

2.13 kBJavaScriptView Raw
1'use strict';
2
3const pkg = require('../package.json');
4
5const uuid = require('uuid');
6
7const ua = require('universal-analytics');
8const _ = require('lodash');
9const ci = require('ci-info');
10const Conf = require('conf');
11const { yellow } = require('colors');
12const osName = require('os-name');
13const getProfileFromFile = require('../lib/profile').getProfileFromFile;
14
15const detectMocha = require('detect-mocha');
16
17const os = osName();
18const packageName = pkg.name;
19const nodeVersion = process.version;
20const appVersion = pkg.version;
21
22const conf = new Conf({
23 configName: `ga-${packageName}`,
24 projectName: packageName,
25 defaults: {
26 cid: uuid.v4()
27 }
28});
29
30process.on('unhandledRejection', error => {
31 require('../lib/exception-handler')(error);
32});
33
34var fake = {
35 pageview: () => {
36 return {
37 send: () => { return 'fake'; }
38 };
39 },
40 event: () => {
41 return {
42 send: () => { return 'fake'; }
43 };
44 }
45};
46
47var fakeMocha = {
48 pageview: () => {
49 return {
50 send: () => { return 'fakeMocha'; }
51 };
52 },
53 event: () => {
54 return {
55 send: () => { return 'fakeMocha'; }
56 };
57 }
58};
59
60var real = ua('UA-139874201-1', conf.get('cid'));
61
62real.set('cd1', os);
63real.set('cd2', nodeVersion);
64real.set('cd3', appVersion);
65
66var visitor;
67
68async function getVisitor(returnFakeIfMissingConfig = false) {
69
70 if (!visitor) {
71 const profile = await getProfileFromFile();
72
73 // use fake if it is in a ci environment or has never been configured
74 if (_.isEmpty(profile)) {
75
76 if (detectMocha()) {
77 return fakeMocha;
78 }
79
80 if (ci.isCI) {
81 real.pageview(`/downloaded/ci/${ci.name}`).send();
82 }
83
84 return fake;
85 }
86
87 if (profile.report === undefined) {
88 if (returnFakeIfMissingConfig) { return fake; }
89
90 if (detectMocha()) {
91 return fakeMocha;
92 }
93
94 real.pageview('/downloaded').send();
95 throw new Error(`Please re-execute ${yellow('fun config')} command`);
96 }
97
98 if (profile.report === true) {
99 visitor = real;
100 } else {
101 visitor = fake;
102 }
103 }
104
105 return visitor;
106}
107
108module.exports = { getVisitor };