@servicetitan/docs-uikit 40.2.2 → 40.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/BREAKING_CHANGES.mdx +1 -1
- package/docs/ajax-handlers/ajax-handlers.mdx +5 -2
- package/docs/ajax-handlers/init-ajax-handlers-common.mdx +22 -0
- package/docs/ajax-handlers/init-ajax-handlers-csrf-token.mdx +24 -0
- package/docs/ajax-handlers/init-ajax-handlers-login-required.mdx +2 -2
- package/docs/ajax-handlers/init-ajax-handlers-parse-dates.mdx +2 -1
- package/docs/ajax-handlers/init-ajax-handlers.mdx +186 -0
- package/docs/ajax-handlers/silent-login.mdx +41 -0
- package/docs/datadog-rum/api/api.mdx +24 -0
- package/docs/datadog-rum/api/before-send.mdx +36 -0
- package/docs/datadog-rum/api/datadog-provider.mdx +106 -0
- package/docs/datadog-rum/api/init.mdx +129 -0
- package/docs/datadog-rum/api/set-user.mdx +15 -0
- package/docs/datadog-rum/api/use-rum-service.mdx +33 -0
- package/docs/datadog-rum/datadog-rum.mdx +156 -0
- package/docs/datadog-rum/dev-runtime-enable.mdx +25 -0
- package/docs/launchdarkly-service.mdx +6 -0
- package/docs/startup/build/build.mdx +25 -1
- package/docs/startup/mfe-publish.mdx +2 -0
- package/docs/web-components/use-prefetch.mdx +2 -0
- package/package.json +1 -1
- package/docs/ajax-handlers/cancelation-handling.mdx +0 -43
- package/docs/datadog-rum.mdx +0 -465
|
@@ -51,7 +51,7 @@ sidebar_position: 0
|
|
|
51
51
|
Any code that makes cancelable requests must guard against the cancelation error using `axios.isCancel`.
|
|
52
52
|
:::
|
|
53
53
|
|
|
54
|
-
See [
|
|
54
|
+
See [Canceled requests](./ajax-handlers/init-ajax-handlers#cancelation-handling) for the correct patterns, or use the `fix-cancelable-requests` skill to automatically find and fix affected call sites. Install it from the [uikit AI Marketplace](./ai-marketplace).
|
|
55
55
|
|
|
56
56
|
### [@servicetitan/startup](./startup/)
|
|
57
57
|
|
|
@@ -7,13 +7,16 @@ title: AJAX Handlers
|
|
|
7
7
|
`@servicetitan/ajax-handlers` provides utilities for handling AJAX requests, authentication, and response processing in ServiceTitan applications. It includes automatic date parsing, authentication wrappers for protected resources, and comprehensive error handling.
|
|
8
8
|
|
|
9
9
|
:::caution
|
|
10
|
-
See [
|
|
10
|
+
See [Canceled requests](./init-ajax-handlers.mdx#cancelation-handling) for how to handle cancelable requests.
|
|
11
11
|
:::
|
|
12
12
|
|
|
13
13
|
## API
|
|
14
14
|
|
|
15
|
-
- initAjaxHandlers - Use to register axios interceptors for authentication, error handling, and loading state; pass a notifier to receive error details including the full `AxiosError`.
|
|
15
|
+
- [initAjaxHandlers](./init-ajax-handlers.mdx) - Use to register axios interceptors for authentication, error handling, and loading state; pass a notifier to receive error details including the full `AxiosError`.
|
|
16
|
+
- [initAjaxHandlersCommon](./init-ajax-handlers-common.mdx) - Use to register default headers, CSRF tokens, and date parsing without the rest of `initAjaxHandlers`.
|
|
17
|
+
- [initAjaxHandlersCSRFToken](./init-ajax-handlers-csrf-token.mdx) - Use to add CSRF headers to same-origin requests without the rest of `initAjaxHandlersCommon`.
|
|
16
18
|
- [withMicroservice](./with-microservice.mdx) - Use to wrap components and authenticate requests to protected resources with support for Bearer and Token Server authentication.
|
|
17
19
|
- [initAjaxHandlersLoginRequired](./init-ajax-handlers-login-required.mdx) - Use to register handler for invalid TokenServer session.
|
|
18
20
|
- [initAjaxHandlersParseDates](./init-ajax-handlers-parse-dates.mdx) - Use to automatically transform date strings in axios responses into JavaScript Date objects.
|
|
19
21
|
- [blockGlobalAssignments](./block-global-assignments.mdx) - Use to block assignments to browser globals, such as `fetch`, from the scripts that you choose.
|
|
22
|
+
- [silentLogin](./silent-login.mdx) - (Deprecated) Use to run the Token Server silent login flow without `withMicroservice`.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: initAjaxHandlersCommon
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
`initAjaxHandlersCommon` registers axios interceptors and defaults for requests to ServiceTitan APIs. [`initAjaxHandlers`](./init-ajax-handlers.mdx) calls it for you. Call it directly only when you don't use `initAjaxHandlers`.
|
|
6
|
+
|
|
7
|
+
## Usage
|
|
8
|
+
|
|
9
|
+
Call `initAjaxHandlersCommon` once in your application's initialization code, before making any requests.
|
|
10
|
+
|
|
11
|
+
```tsx
|
|
12
|
+
import { initAjaxHandlersCommon } from '@servicetitan/ajax-handlers';
|
|
13
|
+
|
|
14
|
+
initAjaxHandlersCommon();
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
`initAjaxHandlersCommon`:
|
|
18
|
+
|
|
19
|
+
- calls [`initAjaxHandlersCSRFToken`](./init-ajax-handlers-csrf-token.mdx)
|
|
20
|
+
- calls [`initAjaxHandlersParseDates`](./init-ajax-handlers-parse-dates.mdx)
|
|
21
|
+
- sets `Content-Type: application/json;charset=UTF-8` and `Accept: application/json` on requests that don't already set them, except when the request body is `FormData`
|
|
22
|
+
- sets axios's `validateStatus` so responses with status `200`–`399` resolve and others reject
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: initAjaxHandlersCSRFToken
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
`initAjaxHandlersCSRFToken` adds headers to same-origin requests that the server uses to reject cross-site request forgery. [`initAjaxHandlersCommon`](./init-ajax-handlers-common.mdx) calls it for you. Call it directly only when you don't use `initAjaxHandlersCommon` or [`initAjaxHandlers`](./init-ajax-handlers.mdx).
|
|
6
|
+
|
|
7
|
+
## Usage
|
|
8
|
+
|
|
9
|
+
Call `initAjaxHandlersCSRFToken` once in your application's initialization code, before making any requests.
|
|
10
|
+
|
|
11
|
+
```tsx
|
|
12
|
+
import { initAjaxHandlersCSRFToken } from '@servicetitan/ajax-handlers';
|
|
13
|
+
|
|
14
|
+
initAjaxHandlersCSRFToken();
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Headers
|
|
18
|
+
|
|
19
|
+
`initAjaxHandlersCSRFToken` adds these headers to same-origin requests:
|
|
20
|
+
|
|
21
|
+
- `X-Requested-With: XMLHttpRequest`
|
|
22
|
+
- `X-CSRF-Token`, with the value of the `X-CSRF-Token` cookie, when the cookie exists
|
|
23
|
+
|
|
24
|
+
It doesn't replace a header the request already sets, and it doesn't add headers to cross-origin requests.
|
|
@@ -17,7 +17,7 @@ import { initAjaxHandlersLoginRequired } from '@servicetitan/ajax-handlers';
|
|
|
17
17
|
|
|
18
18
|
// Register handler for "login required" scenario
|
|
19
19
|
|
|
20
|
-
initAjaxHandlersLoginRequired(
|
|
21
|
-
window.location.assign('/#/Auth/Logout')
|
|
20
|
+
initAjaxHandlersLoginRequired({
|
|
21
|
+
loginRequired: () => window.location.assign('/#/Auth/Logout'),
|
|
22
22
|
});
|
|
23
23
|
```
|
|
@@ -39,10 +39,11 @@ Supports standard ISO date strings with optional time zones and milliseconds:
|
|
|
39
39
|
|
|
40
40
|
### .NET JSON Date Format
|
|
41
41
|
|
|
42
|
-
Supports the legacy .NET JSON date format:
|
|
42
|
+
Supports the legacy .NET JSON date format, when it is the entire string value:
|
|
43
43
|
|
|
44
44
|
- `/Date(1710504645000)/`
|
|
45
45
|
- `/Date(1710504645000-0800)/`
|
|
46
|
+
- `/Date(1710504645000+0530)/`
|
|
46
47
|
- `/Date(-62135596800000)/` (negative timestamps for dates before 1970)
|
|
47
48
|
|
|
48
49
|
## Example
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: initAjaxHandlers
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
`initAjaxHandlers` registers axios interceptors that show a global loading indicator while requests are pending, report failed requests to a notifier, and optionally reload the page when the server responds with `401 Unauthorized`. It also registers the [common handlers](./init-ajax-handlers-common.mdx), which add default headers, CSRF tokens, and date parsing.
|
|
6
|
+
|
|
7
|
+
## Usage
|
|
8
|
+
|
|
9
|
+
Call `initAjaxHandlers` once in your application's initialization code, before making any requests.
|
|
10
|
+
|
|
11
|
+
This example shows error notifications as Anvil2 toasts. Anvil2's `toast` works outside React components, so the notifier can call it directly.
|
|
12
|
+
|
|
13
|
+
```tsx title="index.tsx"
|
|
14
|
+
import { initAjaxHandlers, Status } from '@servicetitan/ajax-handlers';
|
|
15
|
+
import { toast } from '@servicetitan/anvil2';
|
|
16
|
+
|
|
17
|
+
initAjaxHandlers({
|
|
18
|
+
notifier: {
|
|
19
|
+
show: ({ status, title, message, duration, action }) => {
|
|
20
|
+
const showToast = status === Status.Error ? toast.danger : toast.warning;
|
|
21
|
+
showToast({
|
|
22
|
+
title,
|
|
23
|
+
message,
|
|
24
|
+
duration: duration === 0 ? false : duration,
|
|
25
|
+
actions: action && 'onClick' in action ? { primary: action } : undefined,
|
|
26
|
+
});
|
|
27
|
+
},
|
|
28
|
+
},
|
|
29
|
+
unauthorizedHandler: true,
|
|
30
|
+
});
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
The toasts render in a `Toaster`, so mount one in your app.
|
|
34
|
+
|
|
35
|
+
```tsx title="app.tsx"
|
|
36
|
+
import { AnvilProvider, Toaster } from '@servicetitan/anvil2';
|
|
37
|
+
|
|
38
|
+
export const App = () => (
|
|
39
|
+
<AnvilProvider>
|
|
40
|
+
<Toaster id="app-toaster" />
|
|
41
|
+
{/* Your app */}
|
|
42
|
+
</AnvilProvider>
|
|
43
|
+
);
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Options
|
|
47
|
+
|
|
48
|
+
| Name | Type | Description |
|
|
49
|
+
| :-------------------- | :------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
50
|
+
| `notifier` | [`INotifier`](#notifier) | (optional) Receives error notifications and connection error logs |
|
|
51
|
+
| `errorFilteredUrls` | `string[]` | (optional) URL prefixes for which failed requests don't send an error notification |
|
|
52
|
+
| `unauthorizedHandler` | `true` \| [`UnauthorizedHandler`](#unauthorized-handler) | (optional) Handles `401` responses. Pass `true` to use the [default behavior](#unauthorized-handler). When omitted, `401` responses aren't handled |
|
|
53
|
+
|
|
54
|
+
### `INotifier` {#notifier}
|
|
55
|
+
|
|
56
|
+
| Name | Type | Description |
|
|
57
|
+
| :----- | :-------------------------- | :----------------------------------------------------------------------------------------------------------------------------- |
|
|
58
|
+
| `show` | `(options: object) => void` | (optional) Called with an [error notification](#error-notifications) to show the user. See [`show` arguments](#show-arguments) |
|
|
59
|
+
| `log` | `(options: object) => void` | (optional) Called when a request fails with a connection error (status `0`). See [`log` arguments](#log-arguments) |
|
|
60
|
+
|
|
61
|
+
#### `show` arguments {#show-arguments}
|
|
62
|
+
|
|
63
|
+
`initAjaxHandlers` calls `show` with an object containing:
|
|
64
|
+
|
|
65
|
+
| Name | Type | Value |
|
|
66
|
+
| :--------- | :--------------- | :------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
67
|
+
| `status` | `Status` | `Status.Error` for hard errors, `Status.Warning` otherwise |
|
|
68
|
+
| `title` | `string` | `'Application error'` for hard errors, `'Action cancelled'` otherwise |
|
|
69
|
+
| `message` | `string` | The error message. Hard errors don't include it |
|
|
70
|
+
| `duration` | `number` | `0` for hard errors. Other errors don't include it |
|
|
71
|
+
| `action` | `FunctionAction` | For hard errors, a "Show details" action that dispatches a `report_error` event. Other errors don't include it |
|
|
72
|
+
| `detail` | `object` | `isHardError`, `isReportable` (hard errors only), `isConnectionError` (other errors only), `baseUrl`, `url`, and the `AxiosError` as `error` |
|
|
73
|
+
|
|
74
|
+
#### `log` arguments {#log-arguments}
|
|
75
|
+
|
|
76
|
+
`initAjaxHandlers` calls `log` with an object containing:
|
|
77
|
+
|
|
78
|
+
| Name | Type | Value |
|
|
79
|
+
| :---------- | :------- | :--------------------------------------------------------------------------- |
|
|
80
|
+
| `exception` | `string` | The request's error message |
|
|
81
|
+
| `category` | `string` | `'NetworkConnection'` |
|
|
82
|
+
| `message` | `string` | `'Network Connection Error'` |
|
|
83
|
+
| `data` | `object` | The request's `status` and `readyState`, and the request URL as `requestUrl` |
|
|
84
|
+
|
|
85
|
+
### `UnauthorizedHandler` {#unauthorized-handler}
|
|
86
|
+
|
|
87
|
+
| Name | Type | Description |
|
|
88
|
+
| :-------------------- | :-------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------- |
|
|
89
|
+
| `isUnauthorized` | `(response: AxiosResponse, defaultHandler: () => boolean) => boolean` | (optional) Returns whether the response is unauthorized. Call `defaultHandler` to apply the default check |
|
|
90
|
+
| `unauthorizedHandler` | `() => void` | (optional) Called when a response is unauthorized |
|
|
91
|
+
|
|
92
|
+
The defaults are:
|
|
93
|
+
|
|
94
|
+
- `isUnauthorized` returns `true` for a `401` response to a request with a relative URL.
|
|
95
|
+
- `unauthorizedHandler` reloads the page, at most once every five minutes, so a persistent `401` doesn't cause a reload loop.
|
|
96
|
+
|
|
97
|
+
## Error notifications
|
|
98
|
+
|
|
99
|
+
When a request fails, `initAjaxHandlers` calls `notifier.show` unless:
|
|
100
|
+
|
|
101
|
+
- the request was [canceled](#cancelation-handling)
|
|
102
|
+
- the request's [`suppressShowError`](#request-options) option suppresses it
|
|
103
|
+
- the request URL starts with one of the `errorFilteredUrls`
|
|
104
|
+
- the response body has an error code, such as `{ "Error": { "Code": "UsernameAlreadyExists", "Message": "..." } }`. The server returns an error code for expected errors, such as a validation failure, that the calling code handles with its own message
|
|
105
|
+
|
|
106
|
+
When the response has a `harderror` header, `show` receives an "Application error" with `duration: 0` and a "Show details" action. Otherwise, it receives an "Action cancelled" warning. The error message is the first of these that's present: the `Message` in the response body's `Error` object, the `x-message` response header, or the response status text.
|
|
107
|
+
|
|
108
|
+
## Canceled requests {#cancelation-handling}
|
|
109
|
+
|
|
110
|
+
When a request is canceled via `CancelToken` or `AbortController`, `initAjaxHandlers` rejects the promise with the cancelation error. Code that makes cancelable requests must handle this error to avoid unhandled promise rejections and spurious error UI.
|
|
111
|
+
|
|
112
|
+
Use `axios.isCancel` to distinguish cancelations from real errors:
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
import axios from 'axios';
|
|
116
|
+
|
|
117
|
+
async loadData() {
|
|
118
|
+
this.cancelToken?.cancel();
|
|
119
|
+
this.cancelToken = axios.CancelToken.source();
|
|
120
|
+
|
|
121
|
+
try {
|
|
122
|
+
const res = await this.api.getData(this.cancelToken.token);
|
|
123
|
+
runInAction(() => { this.data = res.data; });
|
|
124
|
+
} catch (e) {
|
|
125
|
+
if (!axios.isCancel(e)) {
|
|
126
|
+
throw e;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
If loading state is set before the `await`, reset it in a `finally` block so it clears even when the request is canceled:
|
|
133
|
+
|
|
134
|
+
```ts
|
|
135
|
+
this.isLoading = true;
|
|
136
|
+
try {
|
|
137
|
+
const res = await this.api.getData(this.cancelToken.token);
|
|
138
|
+
runInAction(() => {
|
|
139
|
+
this.data = res.data;
|
|
140
|
+
});
|
|
141
|
+
} catch (e) {
|
|
142
|
+
if (!axios.isCancel(e)) {
|
|
143
|
+
throw e;
|
|
144
|
+
}
|
|
145
|
+
} finally {
|
|
146
|
+
this.isLoading = false;
|
|
147
|
+
}
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
## Request options {#request-options}
|
|
151
|
+
|
|
152
|
+
`@servicetitan/ajax-handlers` adds these options to axios's `AxiosRequestConfig`:
|
|
153
|
+
|
|
154
|
+
| Name | Type | Description |
|
|
155
|
+
| :------------------ | :---------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
156
|
+
| `suppressShowError` | `boolean` \| `number[]` \| `(error: AxiosError) => boolean` | (optional) Suppresses the error notification. Pass `true` to suppress all errors, an array of status codes to suppress errors with those statuses, or a function that returns `true` for each error to suppress |
|
|
157
|
+
| `hideGlobalLoader` | `boolean` | (optional) Don't show the global loading indicator for this request |
|
|
158
|
+
|
|
159
|
+
```tsx
|
|
160
|
+
import axios from 'axios';
|
|
161
|
+
|
|
162
|
+
// Handle 404 in the caller instead of showing a notification
|
|
163
|
+
await axios.get('/api/customers/123', { suppressShowError: [404] });
|
|
164
|
+
|
|
165
|
+
// Poll in the background without showing the loading indicator
|
|
166
|
+
await axios.get('/api/status', { hideGlobalLoader: true });
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
## Global loading indicator
|
|
170
|
+
|
|
171
|
+
While requests are pending, `initAjaxHandlers` shows the element with id `global-loading`, and creates `<div id="global-loading" class="global-loading circle">` if the page has none. It adds the `loading-visible` class and fades the element in when the first request starts, then removes the class and fades it out when the last request finishes.
|
|
172
|
+
|
|
173
|
+
`@servicetitan/ajax-handlers` doesn't style the element. Add CSS for `.global-loading` in your application.
|
|
174
|
+
|
|
175
|
+
Use the exported `loader` to show the indicator for work that isn't an axios request. Each `loader.show()` needs a matching `loader.hide()`.
|
|
176
|
+
|
|
177
|
+
```tsx
|
|
178
|
+
import { loader } from '@servicetitan/ajax-handlers';
|
|
179
|
+
|
|
180
|
+
loader.show();
|
|
181
|
+
try {
|
|
182
|
+
await doWork();
|
|
183
|
+
} finally {
|
|
184
|
+
loader.hide();
|
|
185
|
+
}
|
|
186
|
+
```
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: silentLogin
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
:::caution
|
|
6
|
+
Silent login is deprecated. The [BFF Gateway](https://servicetitan.atlassian.net/wiki/spaces/IUM/pages/4367482962) replaces it, and MFEs that use silent login should migrate. See the [announcement](https://servicetitan.atlassian.net/wiki/spaces/IUM/pages/4368564323/Bff+Gateway+Announcement) for details.
|
|
7
|
+
:::
|
|
8
|
+
|
|
9
|
+
`silentLogin` runs the Token Server's [silent login](/docs/projects/ium/mfe-silent-login/) flow in a hidden iframe, setting the session cookie for a microservice's backend for frontend (BFF). [`withMicroservice`](./with-microservice.mdx) calls it for you when you use Token Server authentication. Call it directly when you manage authentication yourself.
|
|
10
|
+
|
|
11
|
+
It has no React or axios dependencies.
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```tsx
|
|
16
|
+
import { silentLogin, TokenServerAuthError } from '@servicetitan/ajax-handlers/silent-login';
|
|
17
|
+
|
|
18
|
+
try {
|
|
19
|
+
await silentLogin({ baseURL: 'https://my-service.servicetitan.com' });
|
|
20
|
+
} catch (error) {
|
|
21
|
+
if (error instanceof TokenServerAuthError) {
|
|
22
|
+
console.error(error.message, error.data);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
`silentLogin` returns a promise that resolves when the user is logged in. It rejects with:
|
|
28
|
+
|
|
29
|
+
- `TokenServerAuthError` when the user isn't authenticated or the Token Server reports the user isn't logged in. Its `data` property holds the response, including `errorCode` when the Token Server sends one.
|
|
30
|
+
- `Error('Authentication timed out')` when the iframe doesn't respond within the [`timeout`](#options) option.
|
|
31
|
+
- A `DOMException` named `AbortError` when the `AbortSignal` passed as the [`signal`](#options) option aborts.
|
|
32
|
+
|
|
33
|
+
## Options {#options}
|
|
34
|
+
|
|
35
|
+
| Name | Type | Description |
|
|
36
|
+
| :------------ | :------------ | :---------------------------------------------------------------------------------------------------------------------------------------- |
|
|
37
|
+
| `baseURL` | `string` | (optional) Base URL of the microservice BFF, used to build the default `authURL`. Defaults to the page's origin |
|
|
38
|
+
| `authURL` | `string` | (optional) Silent login URL. Defaults to `${baseURL}/bff/silent-login` |
|
|
39
|
+
| `authInfoURL` | `string` | (optional) URL to fetch the user's session information from. Defaults to `/bff/authInfo` on the page's origin, even when `baseURL` is set |
|
|
40
|
+
| `timeout` | `number` | (optional) Milliseconds to wait for the iframe to respond. Defaults to `60000` |
|
|
41
|
+
| `signal` | `AbortSignal` | (optional) Cancels the silent login |
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: API
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
| Name | Description |
|
|
6
|
+
| :------------------------------------------ | :---------------------------------------------------------- |
|
|
7
|
+
| [`init`](./init.mdx) | Registers a service and optionally initializes the SDK |
|
|
8
|
+
| [`useRumService`](./use-rum-service.mdx) | React hook that registers a service and disposes on unmount |
|
|
9
|
+
| [`DatadogProvider`](./datadog-provider.mdx) | Identifies the current user to RUM (React component) |
|
|
10
|
+
| [`setUser`](./set-user.mdx) | Sets the current session user |
|
|
11
|
+
| [`getEnv`](./init.mdx#env) | Maps a hostname to its deployment stage for `env` |
|
|
12
|
+
| [`beforeSend`](./before-send.mdx) | Legacy event-enrichment helper |
|
|
13
|
+
|
|
14
|
+
## Service names
|
|
15
|
+
|
|
16
|
+
Each app or MFE has a **service name** that attributes every RUM event to its source. The name is the key for per-service `beforeSend`, `allowedTracingUrls`, and persistent context lookups.
|
|
17
|
+
|
|
18
|
+
For MFEs loaded from unpkg, RUM infers the name at event time from the package slug, for example `'task-hub'` for `@servicetitan/task-hub`. The name you pass to [`init`](./init.mdx) or [`useRumService`](./use-rum-service.mdx) must exactly match this slug, that is, the unscoped name in the MFE's `package.json`.
|
|
19
|
+
|
|
20
|
+
:::caution
|
|
21
|
+
If the names don't match, per-service handlers silently don't run for that MFE's events.
|
|
22
|
+
:::
|
|
23
|
+
|
|
24
|
+
`setServiceContext` is a property of the registration that [`init`](./init.mdx) and [`useRumService`](./use-rum-service.mdx) return. It captures the name once, at registration, so the name can't drift.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: beforeSend
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
:::caution
|
|
6
|
+
This is the legacy API, kept for backward compatibility. New applications should use [`init`](./init.mdx), which lets MFEs share a host's RUM session.
|
|
7
|
+
:::
|
|
8
|
+
|
|
9
|
+
`beforeSend` is a callback that enriches RUM events:
|
|
10
|
+
|
|
11
|
+
- Adds MFE name and version for error and resource events coming from MFEs (`@error.service`, `@resource.service`, `@error.version`, and `@resource.version`)
|
|
12
|
+
- Adds Cloudflare Ray ID for resource events (`@resource.cfRay`)
|
|
13
|
+
|
|
14
|
+
## Usage
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import { beforeSend, getEnv } from '@servicetitan/datadog-rum';
|
|
18
|
+
import { datadogRum } from '@datadog/browser-rum';
|
|
19
|
+
|
|
20
|
+
const isEnabled = /(?:^|\.)go\d*\.servicetitan\.com\.?$/i.test(window.location.hostname);
|
|
21
|
+
|
|
22
|
+
if (isEnabled) {
|
|
23
|
+
datadogRum.init({
|
|
24
|
+
applicationId: '<APPLICATION_ID>',
|
|
25
|
+
clientToken: '<CLIENT_TOKEN>',
|
|
26
|
+
site: 'datadoghq.com',
|
|
27
|
+
service: '<SERVICE_NAME>',
|
|
28
|
+
env: getEnv(),
|
|
29
|
+
version: '<APPLICATION_VERSION>',
|
|
30
|
+
sessionSampleRate: 100,
|
|
31
|
+
sessionReplaySampleRate: 0,
|
|
32
|
+
defaultPrivacyLevel: 'mask-user-input',
|
|
33
|
+
beforeSend: beforeSend(), // beforeSend() returns a handler that enriches events
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
```
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: DatadogProvider
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
`DatadogProvider` provides the RUM SDK with:
|
|
6
|
+
|
|
7
|
+
- Information about the user session
|
|
8
|
+
- Sanitized view event names (`@view.name`) for hash-based routing
|
|
9
|
+
|
|
10
|
+
:::note
|
|
11
|
+
`DatadogProvider` sets the user via [`setUser`](./set-user.mdx), so the same gating rules apply.
|
|
12
|
+
:::
|
|
13
|
+
|
|
14
|
+
## Usage
|
|
15
|
+
|
|
16
|
+
Wrap your application with `DatadogProvider` close to the root. For example,
|
|
17
|
+
|
|
18
|
+
```tsx
|
|
19
|
+
import { DatadogProvider } from '@servicetitan/datadog-rum';
|
|
20
|
+
|
|
21
|
+
const Root = () => {
|
|
22
|
+
return (
|
|
23
|
+
<DatadogProvider isEnabled={isEnabled} user={user}>
|
|
24
|
+
...
|
|
25
|
+
</DatadogProvider>
|
|
26
|
+
);
|
|
27
|
+
};
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
If your application uses hash-based routing, place `DatadogProvider` inside `HashRouter`. For example,
|
|
31
|
+
|
|
32
|
+
```tsx
|
|
33
|
+
import { HashRouter } from 'react-router-dom';
|
|
34
|
+
import { DatadogProvider } from '@servicetitan/datadog-rum';
|
|
35
|
+
|
|
36
|
+
const Root = () => {
|
|
37
|
+
return (
|
|
38
|
+
<HashRouter>
|
|
39
|
+
<DatadogProvider isEnabled={isEnabled} user={user} options={{ hashRouting: true }}>
|
|
40
|
+
...
|
|
41
|
+
</DatadogProvider>
|
|
42
|
+
</HashRouter>
|
|
43
|
+
);
|
|
44
|
+
};
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
:::caution
|
|
48
|
+
`hashRouting` requires `trackViewsManually: true` in the [`application`](./init.mdx#applicationconfig) config. Otherwise the SDK also starts a view for each URL change, and RUM records each route twice.
|
|
49
|
+
:::
|
|
50
|
+
|
|
51
|
+
## Parameters
|
|
52
|
+
|
|
53
|
+
| Name | Type | Description |
|
|
54
|
+
| :---------- | :-------------------- | :------------------------------------------ |
|
|
55
|
+
| `isEnabled` | `boolean` | Activates the provider's instrumentation |
|
|
56
|
+
| `user` | [`RumUser`](#rumuser) | (optional) User session information |
|
|
57
|
+
| `options` | [`Options`](#options) | (optional) Additional configuration options |
|
|
58
|
+
|
|
59
|
+
### `RumUser` {#rumuser}
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
import type { RumUser } from '@servicetitan/datadog-rum';
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
| Name | Type | Description |
|
|
66
|
+
| :-------------- | :----------------------------- | :-------------------------------------- |
|
|
67
|
+
| `id` | `string` | User ID |
|
|
68
|
+
| `[key: string]` | `string \| number \| string[]` | (optional) Session-wide user attributes |
|
|
69
|
+
|
|
70
|
+
### `Options`
|
|
71
|
+
|
|
72
|
+
| Name | Type | Description |
|
|
73
|
+
| :------------ | :------------------------------------------------------- | :---------------------------------------------------------------------- |
|
|
74
|
+
| `hashRouting` | `boolean \| `[`HashRoutingOptions`](#hashroutingoptions) | (optional) Tracks hash-based routes as RUM views (with sanitized names) |
|
|
75
|
+
|
|
76
|
+
### `HashRoutingOptions` {#hashroutingoptions}
|
|
77
|
+
|
|
78
|
+
✨ New in **v40.3.0** ✨
|
|
79
|
+
|
|
80
|
+
| Name | Type | Description |
|
|
81
|
+
| :---------------- | :--------- | :------------------------------------------------------------------ |
|
|
82
|
+
| `redirectedViews` | `string[]` | (optional) View names of routes that only redirect to another route |
|
|
83
|
+
|
|
84
|
+
A redirected route still starts a view. When it redirects, `DatadogProvider` renames that view to the destination with [`setViewName`](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/browser/advanced_configuration/#set-view-name), so the view's time counts toward the destination.
|
|
85
|
+
|
|
86
|
+
Resources and actions collected before the redirect keep the redirected route's name, so filtering by `@view.name` misses them. To find every resource and action in the view, filter by `@view.id`.
|
|
87
|
+
|
|
88
|
+
For example, to report a `/` route that redirects to the user's landing page as the landing page,
|
|
89
|
+
|
|
90
|
+
```tsx
|
|
91
|
+
import { DatadogProvider } from '@servicetitan/datadog-rum';
|
|
92
|
+
|
|
93
|
+
<DatadogProvider
|
|
94
|
+
isEnabled={isEnabled}
|
|
95
|
+
user={user}
|
|
96
|
+
options={{ hashRouting: { redirectedViews: ['/'] } }}
|
|
97
|
+
>
|
|
98
|
+
...
|
|
99
|
+
</DatadogProvider>;
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
List each route by its RUM view name (`@view.name`), with IDs written as `{id}`, for example `/lead/index/{id}`.
|
|
103
|
+
|
|
104
|
+
:::caution
|
|
105
|
+
List only routes that always redirect. If a listed route renders a page, the user's next navigation renames that page's view instead of starting a new one.
|
|
106
|
+
:::
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: init
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
Registers a service and, optionally, initializes the Datadog RUM SDK. Returns a [`RumServiceRegistration`](#rumserviceregistration) — `{ cleanup, setServiceContext }`, both bound to this service.
|
|
6
|
+
|
|
7
|
+
Any caller — host or MFE — may pass `application`. The first `application` passed wins, and a later caller's `application` config is ignored. The SDK starts on the first call that asks for a session, which is not always the call that supplied the winning `application`. Callers that omit `application` register their service without attempting SDK init.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { init } from '@servicetitan/datadog-rum';
|
|
11
|
+
|
|
12
|
+
const isEnabled = /(?:^|\.)go\d*\.servicetitan\.com\.?$/i.test(window.location.hostname);
|
|
13
|
+
|
|
14
|
+
const { cleanup, setServiceContext } = init({
|
|
15
|
+
service: {
|
|
16
|
+
name: 'task-hub',
|
|
17
|
+
allowedTracingUrls: {
|
|
18
|
+
tracecontext: [url => /\/api\/task-hub\//.test(url)],
|
|
19
|
+
},
|
|
20
|
+
beforeSend: event => {
|
|
21
|
+
// transform-only (return value ignored)
|
|
22
|
+
},
|
|
23
|
+
},
|
|
24
|
+
application: {
|
|
25
|
+
applicationId: '<APPLICATION_ID>',
|
|
26
|
+
clientToken: '<CLIENT_TOKEN>',
|
|
27
|
+
version: '<APPLICATION_VERSION>',
|
|
28
|
+
excludedActivityUrls: [/fullstory\.com/, /pendo\.io/, /\/Log\/Send/],
|
|
29
|
+
beforeSend: event => {
|
|
30
|
+
return true; // return false to drop the event app-wide
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
enabled: isEnabled,
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
// Attach session-lifetime context merged into every 'task-hub'-tagged event
|
|
37
|
+
setServiceContext({ logicalEnvironment: 'go5', orgId: '123' });
|
|
38
|
+
|
|
39
|
+
// On teardown (e.g. MFE unmount):
|
|
40
|
+
cleanup();
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Parameters
|
|
44
|
+
|
|
45
|
+
`init` accepts an [`InitRumOptions`](#initrumoptions) object and returns a [`RumServiceRegistration`](#rumserviceregistration).
|
|
46
|
+
|
|
47
|
+
### `InitRumOptions` {#initrumoptions}
|
|
48
|
+
|
|
49
|
+
| Name | Type | Description |
|
|
50
|
+
| :------------ | :---------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
51
|
+
| `service` | [`ServiceConfig`](#serviceconfig) | Per-service handlers and tracing URL matchers |
|
|
52
|
+
| `application` | [`ApplicationConfig`](#applicationconfig) | (optional) SDK initialization config. See the description above for which caller starts the session |
|
|
53
|
+
| `enabled` | `boolean` | (optional) Controls whether Datadog RUM data collection is turned on. Defaults to `true`. Set this instead of gating the `init` call to allow [runtime enablement for development](../dev-runtime-enable.mdx). |
|
|
54
|
+
|
|
55
|
+
### `RumServiceRegistration` {#rumserviceregistration}
|
|
56
|
+
|
|
57
|
+
| Name | Type | Description |
|
|
58
|
+
| :------------------ | :--------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
59
|
+
| `cleanup` | `() => void` | Removes this service's `beforeSend`, `allowedTracingUrls`, and persistent context. Idempotent. |
|
|
60
|
+
| `setServiceContext` | `(context: Context) => void` | Sets session-lifetime context merged into every event whose `event.service` matches this service's name. Replace semantics: a second call replaces the previous bag with no merge. |
|
|
61
|
+
|
|
62
|
+
### `ServiceConfig` {#serviceconfig}
|
|
63
|
+
|
|
64
|
+
| Name | Type | Description |
|
|
65
|
+
| :------------------- | :------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
66
|
+
| `name` | `string` | Service name. For MFEs loaded from unpkg, must exactly match the unscoped `package.json` `name` (e.g. `'task-hub'` for `@servicetitan/task-hub`). |
|
|
67
|
+
| `beforeSend` | `ServiceBeforeSendHandler` | (optional) Transform-only per-service handler. Return value is **ignored** — services cannot drop events. |
|
|
68
|
+
| `allowedTracingUrls` | `Partial<Record<PropagatorType, TracingMatchOption[]>>` | (optional) URL matchers grouped by propagator type |
|
|
69
|
+
|
|
70
|
+
:::caution
|
|
71
|
+
A service's `beforeSend` cannot drop events. This is intentional: services share a session with the host and any other MFEs, so a bug in one service must not silently hide its own events from the host's monitoring. Use `application.beforeSend` for app-wide drop decisions.
|
|
72
|
+
:::
|
|
73
|
+
|
|
74
|
+
### `ApplicationConfig` {#applicationconfig}
|
|
75
|
+
|
|
76
|
+
Same shape as `datadogRum.init` config, minus `allowedTracingUrls` (built from service registrations) and `service` (derived from `service.name`), plus:
|
|
77
|
+
|
|
78
|
+
| Name | Type | Description |
|
|
79
|
+
| :----------- | :----------------------------- | :---------------------------------------------------------------------------------------------------------------------------- |
|
|
80
|
+
| `beforeSend` | `ApplicationBeforeSendHandler` | (optional) Application-level handler; runs for all events before service handlers. Return `false` to drop the event app-wide. |
|
|
81
|
+
|
|
82
|
+
Opinionated defaults (overridable):
|
|
83
|
+
|
|
84
|
+
- `sessionSampleRate: 100`
|
|
85
|
+
- `sessionReplaySampleRate: 0`
|
|
86
|
+
- `defaultPrivacyLevel: 'mask-user-input'`
|
|
87
|
+
|
|
88
|
+
Where:
|
|
89
|
+
|
|
90
|
+
- `PropagatorType` is `'datadog' | 'tracecontext' | 'b3' | 'b3multi'`.
|
|
91
|
+
- `TracingMatchOption` is `string` (prefix match), `RegExp`, or `(url: string) => boolean`.
|
|
92
|
+
- `ApplicationBeforeSendHandler` is `(event: RumEvent, context: RumEventDomainContext) => boolean | void`.
|
|
93
|
+
- `ServiceBeforeSendHandler` is `(event: RumEvent, context: RumEventDomainContext) => void`.
|
|
94
|
+
|
|
95
|
+
:::caution
|
|
96
|
+
`excludedActivityUrls` tells RUM which URLs not to count toward view-loading time. The exclusion applies app-wide; the `application` config that starts the session locks the list, so the host should set the complete list there. If an MFE set it, its choices would distort view metrics for the host and any other MFEs sharing the session.
|
|
97
|
+
:::
|
|
98
|
+
|
|
99
|
+
### `env` {#env}
|
|
100
|
+
|
|
101
|
+
✨ New in **v40.3.0** ✨
|
|
102
|
+
|
|
103
|
+
When `application.env` is omitted, `init` sets `env` to the deployment stage of `window.location.hostname`. Pass `env` only to report a different value.
|
|
104
|
+
|
|
105
|
+
| Hostname | `env` |
|
|
106
|
+
| :------------------------------------------------------- | :------------ |
|
|
107
|
+
| `go.servicetitan.com`, `go2.servicetitan.com` | `go` |
|
|
108
|
+
| `<tenant>.eh.go.servicetitan.com` | `go` |
|
|
109
|
+
| `stage.servicetitan.com`, `<sub>.stage.servicetitan.com` | `stage` |
|
|
110
|
+
| `next.servicetitan.com` | `next` |
|
|
111
|
+
| `practice.servicetitan.com` | `practice` |
|
|
112
|
+
| `integration.servicetitan.com` | `integration` |
|
|
113
|
+
| `qa.servicetitan.com`, `<sub>.qa.st.dev` | `qa` |
|
|
114
|
+
| `test.servicetitan.com` | `test` |
|
|
115
|
+
| `localhost`, `127.0.0.1`, `app-web`, `<sub>.st.dev` | `dev` |
|
|
116
|
+
| Any other hostname | unset |
|
|
117
|
+
|
|
118
|
+
:::caution
|
|
119
|
+
Do not use the raw hostname as `env`. Each tenant subdomain, such as `acme.eh.go.servicetitan.com`, then reports its own `env`, and dashboards and monitors that filter on `env:go` miss those tenants.
|
|
120
|
+
:::
|
|
121
|
+
|
|
122
|
+
`getEnv` returns the same value, for code that calls `datadogRum.init` directly:
|
|
123
|
+
|
|
124
|
+
```ts
|
|
125
|
+
import { getEnv } from '@servicetitan/datadog-rum';
|
|
126
|
+
|
|
127
|
+
getEnv(); // reads window.location.hostname
|
|
128
|
+
getEnv('acme.eh.go.servicetitan.com'); // 'go'
|
|
129
|
+
```
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: setUser
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
Sets the session user (see [`RumUser`](./datadog-provider.mdx#rumuser) for the accepted shape). Behavior depends on initialization state:
|
|
6
|
+
|
|
7
|
+
- **SDK initialized via `init`**: only the bundle whose `init` call initialized the SDK may set the user. That bundle can re-set freely (for example, login, logout, identity switch). Calls from any other bundle are silent no-ops.
|
|
8
|
+
- **SDK initialized directly via `datadogRum.init`**: `setUser` delegates straight to `datadogRum.setUser` without gating.
|
|
9
|
+
- **Neither initialized**: no-op.
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { setUser } from '@servicetitan/datadog-rum';
|
|
13
|
+
|
|
14
|
+
setUser({ id: '7', email: 'user@example.com' });
|
|
15
|
+
```
|