@@ -25,6 +25,11 @@ export async function setupIntercom(
2525 return ;
2626 }
2727
28+ if ( ! ( await isIntercomAllowed ( ) ) ) {
29+ debug ( 'skipping Intercom (not allowed)' ) ;
30+ return ;
31+ }
32+
2833 const user = getActiveUser ( preferences ) ;
2934
3035 const metadata : IntercomMetadata = {
@@ -80,3 +85,61 @@ export async function setupIntercom(
8085 }
8186 ) ;
8287}
88+
89+ /**
90+ * Memoized promise that resolves to whether the intercom integration is allowed.
91+ * Access this through `this.isAllowed` to fire the request only once.
92+ */
93+ let isIntercomAllowedResponse : null | Promise < boolean > = null ;
94+
95+ function isIntercomAllowed ( ) : Promise < boolean > {
96+ if ( ! isIntercomAllowedResponse ) {
97+ isIntercomAllowedResponse = fetchIntegrations ( ) . then (
98+ ( { intercom } ) => intercom ,
99+ ( error ) => {
100+ debug (
101+ 'Failed to fetch intercom integration status, defaulting to false' ,
102+ { error : error instanceof Error && error . message }
103+ ) ;
104+ return false ;
105+ }
106+ ) ;
107+ }
108+ return isIntercomAllowedResponse ;
109+ }
110+
111+ /**
112+ * TODO: Move this to a shared package if we start using it to toggle other integrations.
113+ */
114+ function getAutoUpdateEndpoint ( ) {
115+ const { HADRON_AUTO_UPDATE_ENDPOINT , HADRON_AUTO_UPDATE_ENDPOINT_OVERRIDE } =
116+ process . env ;
117+ const result =
118+ HADRON_AUTO_UPDATE_ENDPOINT_OVERRIDE || HADRON_AUTO_UPDATE_ENDPOINT ;
119+ if ( ! result ) {
120+ throw new Error (
121+ 'Expected HADRON_AUTO_UPDATE_ENDPOINT or HADRON_AUTO_UPDATE_ENDPOINT_OVERRIDE to be set'
122+ ) ;
123+ }
124+ return result ;
125+ }
126+
127+ /**
128+ * Fetches the integrations configuration from the update server.
129+ * TODO: Move this to a shared package if we start using it to toggle other integrations.
130+ */
131+ async function fetchIntegrations ( ) : Promise < { intercom : boolean } > {
132+ const url = `${ getAutoUpdateEndpoint ( ) } /api/v2/integrations` ;
133+ const response = await fetch ( url ) ;
134+ if ( ! response . ok ) {
135+ throw new Error (
136+ `Expected an OK response, got ${ response . status } '${ response . statusText } '`
137+ ) ;
138+ }
139+ const result = await response . json ( ) ;
140+ debug ( 'Got integrations response' , { result } ) ;
141+ if ( typeof result . intercom !== 'boolean' ) {
142+ throw new Error ( `Expected 'intercom' to be a boolean` ) ;
143+ }
144+ return result ;
145+ }
0 commit comments