From 76713d79675e31bcde37cc565e649e4389b30a79 Mon Sep 17 00:00:00 2001 From: Will Binns-Smith Date: Tue, 22 Mar 2022 18:40:53 -0700 Subject: [PATCH] Prevent analytics-node from creating unhandled promise rejections --- .../atlassian-reporter-analytics/package.json | 1 + .../src/analytics.js | 20 ++++++++++++++++--- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/packages/reporters/atlassian-reporter-analytics/package.json b/packages/reporters/atlassian-reporter-analytics/package.json index 8b808294525..1504fb07169 100644 --- a/packages/reporters/atlassian-reporter-analytics/package.json +++ b/packages/reporters/atlassian-reporter-analytics/package.json @@ -15,6 +15,7 @@ "@atlassiansox/analytics-node-client": "^2.2.2", "@parcel/hash": "2.0.20", "@parcel/plugin": "2.0.20", + "analytics-node": "^5.2.0", "execa": "^5.1.1", "uuid": "^3.3.3" } diff --git a/packages/reporters/atlassian-reporter-analytics/src/analytics.js b/packages/reporters/atlassian-reporter-analytics/src/analytics.js index fc9892e82e3..a8c33f0ffbd 100644 --- a/packages/reporters/atlassian-reporter-analytics/src/analytics.js +++ b/packages/reporters/atlassian-reporter-analytics/src/analytics.js @@ -2,12 +2,26 @@ // flowlint-next-line untyped-import:off import {analyticsClient, userTypes} from '@atlassiansox/analytics-node-client'; +// flowlint-next-line untyped-import:off +import SegmentAnalytics from 'analytics-node'; import os from 'os'; import {hashString} from '@parcel/hash'; import getMachineModel from './getMachineModel'; const HASHED_EMAIL = hashString(`${os.userInfo().username}@${os.hostname()}`); +// Monkeypatch SegmentAnalytics not to create unhandled promise rejections. +// TODO: Remove when https://github.com/segmentio/analytics-node/issues/326 +// is resolved +const originalSegmentAnalyticsFlush = SegmentAnalytics.prototype.flush; +SegmentAnalytics.prototype.flush = function flush(callback, ...rest) { + return originalSegmentAnalyticsFlush + .call(this, callback, ...rest) + .catch(err => { + callback(null, err); + }); +}; + let client; if ( process.env.PARCEL_BUILD_ENV === 'production' && @@ -74,13 +88,13 @@ const analytics = { if (client != null) { try { - return await client.sendTrackEvent(trackEvent); + await client.sendTrackEvent(trackEvent); } catch (err) { - if (process.env.ANALYTICS_DEBUG != null) { + // Don't let a failure to report analytics crash Parcel + if (process.env.PARCEL_ANALYTICS_DEBUG != null) { // eslint-disable-next-line no-console console.error('Failed to send analytics', err); } - // Don't let a failure to report analytics crash Parcel } } },