|
| 1 | +// Unless explicitly stated otherwise all files in this repository are licensed under the MIT License. |
| 2 | +// This product includes software developed at Datadog (https://www.datadoghq.com/). |
| 3 | +// Copyright 2019-Present Datadog, Inc. |
| 4 | + |
| 5 | +import { doRequest } from '@dd/core/helpers'; |
| 6 | +import type { GlobalContext, InjectedValue } from '@dd/core/types'; |
| 7 | + |
| 8 | +import type { RumOptionsWithDefaults, RumOptionsWithSdk } from './types'; |
| 9 | + |
| 10 | +type RumAppResponse = { |
| 11 | + data: { |
| 12 | + attributes: { |
| 13 | + client_token: string; |
| 14 | + }; |
| 15 | + }; |
| 16 | +}; |
| 17 | + |
| 18 | +const getContent = (opts: RumOptionsWithDefaults) => { |
| 19 | + const pluginContent = opts.react |
| 20 | + ? // @ts-ignore |
| 21 | + `, plugins: [reactPlugin({router: ${opts.react.router}})]` |
| 22 | + : ''; |
| 23 | + const sessionReplayStartCommand = opts.startSessionReplayRecording |
| 24 | + ? 'DD_RUM.startSessionReplayRecording();\n' |
| 25 | + : ''; |
| 26 | + |
| 27 | + return `DD_RUM.init({${JSON.stringify(opts.sdk).replace(/(^{|}$)/g, '')}${pluginContent}});${sessionReplayStartCommand} |
| 28 | + `; |
| 29 | +}; |
| 30 | + |
| 31 | +export const getInjectionValue = ( |
| 32 | + options: RumOptionsWithSdk, |
| 33 | + context: GlobalContext, |
| 34 | +): InjectedValue => { |
| 35 | + const sdkOpts = options.sdk; |
| 36 | + // We already have the clientToken, we can inject it directly. |
| 37 | + if (sdkOpts.clientToken) { |
| 38 | + return getContent(options); |
| 39 | + } |
| 40 | + |
| 41 | + // Let's fetch the clientToken from the API. |
| 42 | + if (!context.auth?.apiKey || !context.auth?.appKey) { |
| 43 | + throw new Error('Missing auth.apiKey and/or auth.appKey to fetch clientToken.'); |
| 44 | + } |
| 45 | + |
| 46 | + let clientToken: string; |
| 47 | + |
| 48 | + return async () => { |
| 49 | + try { |
| 50 | + // Fetch the client token from the API. |
| 51 | + const appResponse = await doRequest<RumAppResponse>({ |
| 52 | + url: `https://api.datadoghq.com/api/v2/rum/applications/${sdkOpts.applicationId}`, |
| 53 | + type: 'json', |
| 54 | + auth: context.auth, |
| 55 | + }); |
| 56 | + |
| 57 | + clientToken = appResponse.data?.attributes?.client_token; |
| 58 | + } catch (e: any) { |
| 59 | + // Could not fetch the clientToken. |
| 60 | + // Let's crash the build. |
| 61 | + throw new Error(`Could not fetch the clientToken: ${e.message}`); |
| 62 | + } |
| 63 | + |
| 64 | + // Still no clientToken. |
| 65 | + if (!clientToken) { |
| 66 | + throw new Error('Missing clientToken in the API response.'); |
| 67 | + } |
| 68 | + |
| 69 | + return getContent({ |
| 70 | + ...options, |
| 71 | + sdk: { |
| 72 | + clientToken, |
| 73 | + ...sdkOpts, |
| 74 | + }, |
| 75 | + }); |
| 76 | + }; |
| 77 | +}; |
0 commit comments