@servicetitan/docs-uikit 36.1.1 → 36.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.
@@ -8,7 +8,7 @@ sidebar_position: 0
8
8
  ### [@servicetitan/startup](./startup/)
9
9
 
10
10
  - `mfe-publish` now throws an error instead of silently succeeding when the branch is not configured for publishing (without `--force`).
11
- If your CI workflow calls `mfe-publish` on an unconfigured branch, either add the branch to the `web-component.branches` configuration in `package.json`, or pass `--force` to bypass the check.
11
+ If your CI workflow calls `mfe-publish` on an unrecognized branch, either add the branch to the `web-component.branches` configuration in `package.json`, or pass `--force` to bypass the check.
12
12
 
13
13
  ## v35.0.0
14
14
 
@@ -19,7 +19,7 @@ sidebar_position: 0
19
19
 
20
20
  ### [@servicetitan/launchdarkly-service](./launchdarkly-service.mdx)
21
21
 
22
- - Added `mobx-react` peer dependency. If your project does not already depend on `mobx-react`, add version `~9.2.0`.
22
+ - Added `mobx-react` peer dependency. If your project does not already depend on `mobx-react`, add version `~9.2.0`.
23
23
 
24
24
  ## v34.0.0
25
25
 
@@ -87,6 +87,7 @@ Shared uikit skills for ServiceTitan repos.
87
87
 
88
88
  #### Skills
89
89
 
90
- | Name | Description |
91
- | :------------ | :---------------------------------------- |
92
- | `spell-check` | Check for spelling errors in code changes |
90
+ | Name | Description |
91
+ | :------------------ | :------------------------------------------------------------------------------------------------------- |
92
+ | `spell-check` | Check for spelling errors in code changes |
93
+ | `switching-to-pnpm` | Migrate a project from npm to pnpm (see [migration guide](/docs/frontend/switching-to-pnpm)) |
@@ -18,8 +18,12 @@ title: ESLint & Stylelint configurations
18
18
 
19
19
  ### ESLint
20
20
 
21
+ The ESLint config bundles rules from ESLint core, `eslint-plugin-import`, `eslint-plugin-react`, `eslint-plugin-react-hooks`, `typescript-eslint`, and Prettier, along with the ServiceTitan rules from `@servicetitan/eslint-plugin`. Pick the entry point that matches your repo layout.
22
+
21
23
  #### In the Lerna project
22
24
 
25
+ Use `mono` in a workspace-based monorepo. It discovers every workspace package at lint time and wires up `import/no-extraneous-dependencies` for each one, so imports are checked against both the package's own `package.json` and the repo root.
26
+
23
27
  ```js title="eslint.config.js"
24
28
  import { defineConfig } from 'eslint/config';
25
29
  import mono from '@servicetitan/eslint-config/mono';
@@ -29,6 +33,8 @@ export default defineConfig(mono);
29
33
 
30
34
  #### Without Lerna
31
35
 
36
+ Use `single` in a standalone project. It points the TypeScript parser at `./tsconfig.json` and skips the per-package dependency check.
37
+
32
38
  ```js title="eslint.config.js"
33
39
  import { defineConfig } from 'eslint/config';
34
40
  import single from '@servicetitan/eslint-config/single';
@@ -36,8 +42,80 @@ import single from '@servicetitan/eslint-config/single';
36
42
  export default defineConfig(single);
37
43
  ```
38
44
 
45
+ ### QA lint rules
46
+
47
+ The `qa` config adds lint rules that help keep user interfaces testable by automated suites. Apply it to component and feature files; test files themselves do not need it.
48
+
49
+ `qa` accepts a single optional options object of type `Omit<Linter.Config, 'name' \| 'plugins'>`.
50
+
51
+ #### Common options
52
+
53
+ The options object accepts any property from the ESLint [Linter.Config](https://eslint.org/docs/latest/use/configure/configuration-files#configuration-objects) type. The properties below are the ones you are most likely to set.
54
+
55
+ | Name | Type | Description |
56
+ | :-------- | :--------- | :---------------------------------------------------------------------- |
57
+ | `files` | `string[]` | (optional) Glob patterns for files to lint. Defaults to `['**/*.tsx']`. |
58
+ | `rules` | `object` | (optional) Rule overrides, merged with the default rules. |
59
+ | `ignores` | `string[]` | (optional) Glob patterns for files to exclude. |
60
+
61
+ #### Rules
62
+
63
+ ##### `@servicetitan/qa/require-qa-attr`
64
+
65
+ Automated test suites such as Cypress target interactive elements through dedicated selector attributes like `data-cy`. When these attributes are missing, tests have to rely on brittle selectors (class names, text content, DOM position) that break whenever surrounding markup changes.
66
+
67
+ This rule requires a QA selector attribute on interactive elements so tests can target them reliably as the UI evolves. It reports an error in three cases.
68
+
69
+ **1. Interactive Anvil2 components.** The rule tracks imports from `@servicetitan/anvil2` and `@servicetitan/anvil2/beta`, then flags any of these components when rendered without a QA attribute. Aliased imports (for example, `Button as Btn`) resolve to the original export name before the check runs.
70
+
71
+ | Category | Components |
72
+ | :------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
73
+ | Form inputs | `Checkbox`, `Radio`, `Switch`, `TextField`, `Textarea`, `NumberField`, `SearchField`, `TimeField`, `DateField`, `DateFieldRange`, `DateFieldSingle`, `DateFieldYearless`, `Calendar`, `Pagination` |
74
+ | Selection | `SelectCard`, `SegmentedControl`, `DaysOfTheWeek`, `SelectTrigger`, `Combobox.SearchField`, `Combobox.SelectTrigger` |
75
+ | Actions | `Button`, `ButtonToggle`, `Link`, `Toolbar.Button`, `Toolbar.ButtonToggle`, `Toolbar.ButtonLink`, `Toolbar.Select` |
76
+ | Navigation | `SideNavLink`, `SideNavCollapsible`, `SideNav.Link`, `SideNav.Collapsible`, `BreadcrumbsLink`, `Breadcrumbs.Link`, `Stepper.PrevButton`, `Stepper.NextButton`, `Stepper.Step` |
77
+ | Overlays, menus | `Menu`, `Menu.Item`, `Popover.Button`, `Popover.Close`, `Tab.Button`, `EditCard`, `Chip` |
78
+
79
+ **2. Direct children of `Tooltip.Trigger` or `Popover.Trigger`.** The trigger forwards interactions to its child, so the attribute belongs on the child element rather than the trigger itself.
80
+
81
+ **3. Any JSX element with an `onClick` handler.** This catches custom interactive elements that fall outside the Anvil2 component list, including native elements such as `div` or `span` that receive click handlers.
82
+
83
+ The rule skips elements that use JSX spread (`{...props}`), since the QA attribute or `onClick` handler may come from the spread object.
84
+
85
+ ###### Options
86
+
87
+ | Name | Type | Default | Description |
88
+ | :----------- | :--------- | :----------- | :------------------------------------------------------------------------------------- |
89
+ | `attributes` | `string[]` | `['data-cy']` | Acceptable attribute names. At least one must be present on the flagged element. |
90
+
91
+ The example below shows two ways to enable the rule. The first call uses the defaults and requires `data-cy`. The second call passes a `rules` override so the rule accepts `data-testid` instead, which is useful for projects that already use a different attribute convention.
92
+
93
+ ```js title="eslint.config.js"
94
+ import { defineConfig } from 'eslint/config';
95
+ import mono from '@servicetitan/eslint-config/mono';
96
+ import qa from '@servicetitan/eslint-config/qa';
97
+
98
+ // Default usage requires data-cy
99
+ export default defineConfig([mono, qa()]);
100
+
101
+ // Accept data-testid in place of data-cy
102
+ export default defineConfig([
103
+ mono,
104
+ qa({
105
+ rules: {
106
+ '@servicetitan/qa/require-qa-attr': ['error', { attributes: ['data-testid'] }],
107
+ },
108
+ }),
109
+ ]);
110
+ ```
111
+
39
112
  ### Stylelint
40
113
 
114
+ The Stylelint config extends [`stylelint-config-standard`](https://github.com/stylelint/stylelint-config-standard) and [`stylelint-prettier`](https://github.com/prettier/stylelint-prettier), applies the matching standard extensions for `.scss` and `.less` files, and adds two ServiceTitan rules:
115
+
116
+ - `@servicetitan/function-url-no-absolute` rejects absolute paths inside `url()` values.
117
+ - `@servicetitan/use-tokens` requires design tokens from `@servicetitan/tokens` for colors, spacing, border radii, font families and weights, line heights, opacities, type scales, and z-indexes, instead of raw values.
118
+
41
119
  ```json title=".stylelintrc.json"
42
120
  {
43
121
  "extends": ["@servicetitan/stylelint-config"]
@@ -0,0 +1,172 @@
1
+ ---
2
+ title: ESLint plugins
3
+ ---
4
+
5
+ #### [CHANGELOG (@servicetitan/eslint-plugin)](https://github.com/servicetitan/uikit/blob/master/packages/eslint-plugin/CHANGELOG.md)
6
+
7
+ `@servicetitan/eslint-plugin` contains custom ESLint rules for React, MobX, TypeScript, and testing best practices used across ServiceTitan frontend projects.
8
+ Rules are included in `@servicetitan/eslint-config` by default (except the QA rules), but can also be used separately if you want to apply them selectively.
9
+
10
+ ## Rules
11
+
12
+ ### Base rules
13
+
14
+ #### `@servicetitan/no-async-in-foreach`
15
+
16
+ Disallows passing async callbacks to `Array.forEach`. Async callbacks in `forEach` cause unhandled promise rejections because `forEach` ignores the returned promise. Use `reduce` for sequential execution or `Promise.all` with `.map` for parallel execution instead.
17
+
18
+ ```ts
19
+ // Bad
20
+ items.forEach(async item => {
21
+ await doSomething(item);
22
+ });
23
+
24
+ // Good
25
+ await items.reduce(async (promise, item) => {
26
+ await promise;
27
+ await doSomething(item);
28
+ }, Promise.resolve());
29
+ ```
30
+
31
+ #### `@servicetitan/use-declare-with-decorators`
32
+
33
+ Requires the `declare` keyword when using `@injectDependency` or `@koObservableToMobx` decorators on class fields. Without `declare`, TypeScript emits a class field initializer that overwrites the decorator's effect.
34
+
35
+ ```ts
36
+ // Bad
37
+ class MyService {
38
+ @injectDependency(OtherService)
39
+ private otherService: OtherService;
40
+ }
41
+
42
+ // Good
43
+ class MyService {
44
+ @injectDependency(OtherService)
45
+ declare private otherService: OtherService;
46
+ }
47
+ ```
48
+
49
+ ---
50
+
51
+ ### MobX rules
52
+
53
+ #### `@servicetitan/mobx/no-abstract-decorators`
54
+
55
+ Disallows MobX decorators (`@observable`, `@action`, `@computed`, `@override`) on abstract class fields or methods. Abstract members have no implementation, so MobX decorators have no effect on them.
56
+
57
+ ```ts
58
+ // Bad
59
+ abstract class BaseStore {
60
+ @observable abstract count: number;
61
+ }
62
+
63
+ // Good
64
+ abstract class BaseStore {
65
+ abstract count: number;
66
+ }
67
+ ```
68
+
69
+ #### `@servicetitan/mobx/use-makeObservable-with-decorators`
70
+
71
+ Requires a `makeObservable(this)` call in the constructor when a class uses MobX decorators. Without it, decorators are not activated at runtime.
72
+
73
+ ```ts
74
+ // Bad
75
+ class CounterStore {
76
+ @observable count = 0;
77
+ }
78
+
79
+ // Good
80
+ class CounterStore {
81
+ @observable count = 0;
82
+
83
+ constructor() {
84
+ makeObservable(this);
85
+ }
86
+ }
87
+ ```
88
+
89
+ ---
90
+
91
+ ### React rules
92
+
93
+ #### `@servicetitan/react/destructure-default-import`
94
+
95
+ Disallows importing the React default export (`import React from 'react'` or `import * as React from 'react'`). With modern JSX transform, the default import is unnecessary. Import only what you need.
96
+
97
+ ```ts
98
+ // Bad
99
+ import React from 'react';
100
+ import * as React from 'react';
101
+
102
+ // Good
103
+ import { useState, useEffect } from 'react';
104
+ ```
105
+
106
+ #### `@servicetitan/react/no-qualified-type`
107
+
108
+ Disallows using React types via the qualified name `React.XXX` in type annotations. Import specific types from `react` instead.
109
+
110
+ ```ts
111
+ // Bad
112
+ const MyComponent: React.FC = () => null;
113
+ const ref: React.RefObject<HTMLDivElement> = createRef();
114
+
115
+ // Good
116
+ import { FC, RefObject } from 'react';
117
+ const MyComponent: FC = () => null;
118
+ const ref: RefObject<HTMLDivElement> = createRef();
119
+ ```
120
+
121
+ ---
122
+
123
+ ### QA rules
124
+
125
+ #### `@servicetitan/qa/require-qa-attr`
126
+
127
+ Requires a QA selector attribute on interactive Anvil2 components and any JSX element with an `onClick` handler, so automated tests can reliably select them.
128
+
129
+ The rule tracks imports from `@servicetitan/anvil2` and `@servicetitan/anvil2/beta`. Elements with JSX spread attributes are skipped (the attribute may come from the spread).
130
+
131
+ By default the rule expects `data-cy`. Use the `attributes` option to accept a different attribute or a list of alternatives (the rule passes if any one is present):
132
+
133
+ ```js
134
+ '@servicetitan/qa/require-qa-attr': ['error', { attributes: ['data-testid'] }]
135
+ // or accept either:
136
+ '@servicetitan/qa/require-qa-attr': ['error', { attributes: ['data-cy', 'data-testid'] }]
137
+ ```
138
+
139
+ **Components that always require a QA selector attribute** (when imported from Anvil2):
140
+
141
+ | Category | Components |
142
+ | :----------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
143
+ | Form inputs | `Checkbox`, `Radio`, `Switch`, `TextField`, `Textarea`, `NumberField`, `SearchField`, `TimeField`, `DateField`, `DateFieldRange`, `DateFieldSingle`, `DateFieldYearless`, `Calendar`, `Pagination` |
144
+ | Selection | `SelectCard`, `SegmentedControl`, `DaysOfTheWeek`, `SelectTrigger` |
145
+ | Actions | `Button`, `ButtonToggle`, `Link` |
146
+ | Complex | `Menu`, `EditCard`, `Chip` |
147
+ | Standalone | `SideNavLink`, `SideNavCollapsible`, `BreadcrumbsLink` |
148
+ | Member expressions | `Popover.Button`, `Popover.Close`, `Menu.Item`, `Tab.Button`, `SideNav.Link`, `SideNav.Collapsible`, `Breadcrumbs.Link`, `Stepper.PrevButton`, `Stepper.NextButton`, `Stepper.Step`, `Toolbar.Button`, `Toolbar.ButtonToggle`, `Toolbar.ButtonLink`, `Toolbar.Select`, `Combobox.SearchField`, `Combobox.SelectTrigger` |
149
+
150
+ **Trigger children**: The direct child of `Tooltip.Trigger` or `Popover.Trigger` must also have a QA selector attribute, because automated tests interact with the child element.
151
+
152
+ **`onClick` fallback**: Any JSX element (including native DOM elements) with an `onClick` prop must have a QA selector attribute.
153
+
154
+ ```tsx
155
+ // Bad
156
+ import { Button, Tooltip } from '@servicetitan/anvil2';
157
+
158
+ <Button onClick={save} />
159
+ <Tooltip.Trigger>
160
+ <span>Hover me</span>
161
+ </Tooltip.Trigger>
162
+ <div onClick={handleClick} />
163
+
164
+ // Good
165
+ import { Button, Tooltip } from '@servicetitan/anvil2';
166
+
167
+ <Button data-cy="save-button" onClick={save} />
168
+ <Tooltip.Trigger>
169
+ <span data-cy="tooltip-trigger">Hover me</span>
170
+ </Tooltip.Trigger>
171
+ <div data-cy="clickable-area" onClick={handleClick} />
172
+ ```
package/docs/install.mdx CHANGED
@@ -7,7 +7,7 @@ import TabItem from '@theme/TabItem';
7
7
 
8
8
  #### [CHANGELOG (@servicetitan/install)](https://github.com/servicetitan/uikit/blob/master/packages/install/CHANGELOG.md)
9
9
 
10
- `@servicetitan/install` is a lightweight wrapper around `npm install` that automatically configures access to private ServiceTitan packages and runs `npm install` with ServiceTitan's standard options. Use it instead of plain `npm install` to guarantee that all packages are installed correctly and any necessary pre- and post-installation steps are performed.
10
+ `@servicetitan/install` is a lightweight wrapper that automatically configures access to private ServiceTitan packages and installs dependencies using your project's package manager. Use it instead of running your package manager directly to guarantee that all packages are installed correctly and any necessary pre- and post-installation steps are performed.
11
11
 
12
12
  ```sh
13
13
  npx --yes @servicetitan/install
@@ -22,12 +22,73 @@ The dedicated `@servicetitan/install` package performs a single task and runs qu
22
22
  And because it has no runtime dependencies, also eliminates risks from third-party changes.
23
23
  :::
24
24
 
25
+ ## Package Manager Support
26
+
27
+ `@servicetitan/install` supports both **npm** and **pnpm**. It reads the `cli.packageManager` field in your project's `package.json` to determine which package manager to use. When the field is absent, it defaults to npm.
28
+
29
+ ```json title="package.json"
30
+ {
31
+ "cli": {
32
+ "packageManager": "pnpm"
33
+ }
34
+ }
35
+ ```
36
+
37
+ :::note
38
+ The `npx --yes @servicetitan/install` command works regardless of which package manager your project uses. `npx` is only used to download and run the install CLI itself; the actual dependency installation uses whichever package manager is configured.
39
+ :::
40
+
41
+ ### pnpm support
42
+
43
+ ✨ New in **36.2.0** ✨
44
+
45
+ `@servicetitan/startup` includes experimental pnpm support. See the [Switching to pnpm](/docs/frontend/switching-to-pnpm) migration guide to get started.
46
+
47
+ :::caution
48
+ pnpm support is experimental. It has been validated against several internal repos but may require adjustments for your project. Please report any issues you encounter.
49
+ :::
50
+
25
51
  ## Options
26
52
 
27
- | Option | Description |
28
- | :----------- | :----------------------------------------------------------------------- |
29
- | `--no-token` | Only install dependencies. Don't configure the npm authentication token. |
30
- | `--token` | Only configure the npm authentication token. Don't install dependencies. |
53
+ | Option | Description |
54
+ | :------------------- | :--------------------------------------------------------------------------------------------------------------------- |
55
+ | `--allow-scripts` | Additional packages allowed to run install scripts. Accepts a comma-separated list or can be specified multiple times. |
56
+ | `--no-allow-scripts` | Disable all install scripts, including the default allowlist. |
57
+ | `--no-token` | Only install dependencies. Don't configure the npm authentication token. |
58
+ | `--token` | Only configure the npm authentication token. Don't install dependencies. |
59
+ | `--fix` | Update the lock file without installing packages. |
60
+
61
+ ## Install Script Protection (Preview)
62
+
63
+ In npm projects `@servicetitan/install` runs all install scripts by default. A future release will flip this default to block untrusted packages from running any install script (`preinstall`, `install`, and `postinstall`), protecting against supply chain attacks. To help teams prepare, `@servicetitan/install` warns about installed packages with untrusted install scripts:
64
+
65
+ ```
66
+ WARNING: The following packages have untrusted install scripts.
67
+ Review and add trusted packages to --allow-scripts:
68
+ - some-package@1.2.3
69
+ ```
70
+
71
+ :::caution
72
+ Audit each package in the warning. Verify it is trustworthy or remove the dependency.
73
+ :::
74
+
75
+ :::tip
76
+ Not sure what an install script does? Ask Claude: "What does the install script for _X_ do?". Claude reads the package source and summarizes the behavior, so you can decide whether to trust it.
77
+ :::
78
+
79
+ To disable all install scripts, including the default allowlist, use `--no-allow-scripts`:
80
+
81
+ ```sh
82
+ npx --yes @servicetitan/install --no-allow-scripts
83
+ ```
84
+
85
+ :::tip
86
+ `@servicetitan/install` checks for untrusted install scripts when the lockfile changes. If you see the warning after adding a new dependency, verify the package is trustworthy or remove it.
87
+ :::
88
+
89
+ ### Pnpm projects
90
+
91
+ pnpm blocks install scripts by default and emits a "Ignored build scripts" warning for packages whose scripts were skipped and must be approved.
31
92
 
32
93
  ## Configuring NPM Token in Development
33
94
 
@@ -79,6 +140,10 @@ RUN npm run build
79
140
  </TabItem>
80
141
  </Tabs>
81
142
 
143
+ :::tip
144
+ This step uses `npm config set` regardless of your project's package manager. Npm and pnpm read the same configuration for registry authentication.
145
+ :::
146
+
82
147
  ### Option 2: Use environment variable
83
148
 
84
149
  :::caution
@@ -41,6 +41,8 @@ and automatically [provides a store](#use-flags-in-mobx-store) that allows flag
41
41
  | `context` | `object` | (Optional) Context for targeting rules. Defaults to anonymous user. Use LaunchDarkly's [`identify`](https://docs.launchdarkly.com/sdk/features/identify) method to change the context after initialization. |
42
42
  | `waitForInitialization` | `boolean` | (Optional) Whether or not to wait until flags values are available before rendering children. Defaults to `true`. |
43
43
 
44
+ To configure additional [`LDOptions`](https://launchdarkly.github.io/js-client-sdk/interfaces/LDOptions.html) (for example, inspectors that forward flag evaluations to Datadog RUM), pass them to [`LDServiceProvider`](#ldserviceprovider) at the host level. They apply to every nested `LDProvider`.
45
+
44
46
  :::caution
45
47
  When a `context` is provided, only the initial value takes affect. Subsequent calls with the same client-side ID reuse the client that was created with the initial context.
46
48
 
@@ -142,9 +144,10 @@ export const HostApp: FC = () => {
142
144
 
143
145
  #### Props
144
146
 
145
- | Name | Type | Description |
146
- | :------------ | :-------------- | :--------------------------------------------------------------------- |
147
- | `application` | `LDApplication` | (Optional) Application and version details to provide to LaunchDarkly. |
147
+ | Name | Type | Description |
148
+ | :------------ | :-------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
149
+ | `application` | `LDApplication` | (Optional) Application and version details to provide to LaunchDarkly. |
150
+ | `options` | `Omit<LDOptions, 'application'>` | (Optional) Default [`LDOptions`](https://launchdarkly.github.io/js-client-sdk/interfaces/LDOptions.html) applied to every [`LDProvider`](#ldprovider) within the host. Set [`application`](#application) via the dedicated prop. |
148
151
 
149
152
  #### LDApplication
150
153
 
@@ -158,7 +161,7 @@ export interface LDApplication {
158
161
  Use `application` to make the application id and version available for flag evaluations in LaunchDarkly. Every LaunchDarkly client created by [LDProvider](#ldprovider) (within the host and within MFEs) will automatically pass through the application metadata to LaunchDarkly.
159
162
 
160
163
  :::caution
161
- `LDServiceProvider` should not be used in MFEs. If an MFE does use `LDServiceProvider`, the host's `application` overrides the MFE's.
164
+ `LDServiceProvider` should not be used in MFEs. If an MFE does use `LDServiceProvider`, the host's `application` and `options` override the MFE's.
162
165
  :::
163
166
 
164
167
  #### Example
@@ -177,6 +180,7 @@ The `LDService` interface enables [headless bundles](./microfrontends/developing
177
180
  export interface LDService {
178
181
  getClient: (config: ClientConfig) => LDClient;
179
182
  application?: LDApplication;
183
+ options?: Omit<LDOptions, 'application'>;
180
184
  }
181
185
 
182
186
  export interface ClientConfig {
@@ -200,6 +204,10 @@ Returns an `LDClient` instance configured with the following parameters.
200
204
 
201
205
  Optional [LDApplication](#ldapplication) that was passed to [LDServiceProvider](#ldserviceprovider).
202
206
 
207
+ #### options
208
+
209
+ Optional default `LDOptions` (excluding `application`) that were passed to [LDServiceProvider](#ldserviceprovider). Applied to every [LDProvider](#ldprovider) within the host.
210
+
203
211
  ### FeatureFlagStore
204
212
 
205
213
  `LDProvider` automatically provides a `FeatureFlagStore` that allows you to access
@@ -271,6 +279,43 @@ Render component when flag is on, and render other component when flag is turned
271
279
  <WithFeatureFlag flagKey={flagKey} on={() => 'Flag is ON'} off={() => 'Flag is OFF'} />
272
280
  ```
273
281
 
282
+ ### createDatadogInspector
283
+
284
+ `createDatadogInspector` creates an inspector that forwards feature flag evaluations to Datadog RUM via [`datadogRum.addFeatureFlagEvaluation`](https://docs.datadoghq.com/real_user_monitoring/feature_flag_tracking/?tab=browserrum). Register it once at the host via [`LDServiceProvider`](#ldserviceprovider)'s `options.inspectors`; every nested `LDProvider` picks it up automatically.
285
+
286
+ This helper requires `@datadog/browser-rum` as a peer dependency. It is available as a subpath import so it is only loaded when used:
287
+
288
+ ```tsx
289
+ import { createDatadogInspector } from '@servicetitan/launchdarkly-service/datadog-rum';
290
+ ```
291
+
292
+ #### Options
293
+
294
+ | Name | Type | Description |
295
+ | :----- | :------- | :--------------------------------------------------------------------------------------------------- |
296
+ | `name` | `string` | (Optional) Inspector name reported in LaunchDarkly logs. Defaults to `datadog-feature-flag-tracking`. |
297
+
298
+ #### Example
299
+
300
+ ```tsx title="host-app.tsx"
301
+ import { LDServiceProvider } from '@servicetitan/launchdarkly-service';
302
+ import { createDatadogInspector } from '@servicetitan/launchdarkly-service/datadog-rum';
303
+ import { FC, StrictMode } from 'react';
304
+
305
+ const datadogInspector = createDatadogInspector();
306
+
307
+ export const HostApp: FC = () => (
308
+ <StrictMode>
309
+ <LDServiceProvider
310
+ application={{ id: 'app', version: '71' }}
311
+ options={{ inspectors: [datadogInspector] }}
312
+ >
313
+ {...}
314
+ </LDServiceProvider>
315
+ </StrictMode>
316
+ );
317
+ ```
318
+
274
319
  ## Examples
275
320
 
276
321
  ### Using flag values in React component
@@ -4,55 +4,121 @@ title: React IoC
4
4
 
5
5
  #### [CHANGELOG (@servicetitan/react-ioc)](https://github.com/servicetitan/uikit/blob/master/packages/react-ioc/CHANGELOG.md)
6
6
 
7
- `@servicetitan/react-ioc` is an implementation of [InversifyJS](https://github.com/inversify/InversifyJS) for react applications, it uses Context API of React 16 to manage containers.
7
+ `@servicetitan/react-ioc` is an implementation of [InversifyJS](https://inversify.io/) for React applications. It uses the React Context API to manage hierarchical dependency injection containers, so services declared higher in the component tree are visible to descendants and can be overridden in sub-trees.
8
8
 
9
9
  ## Features
10
10
 
11
- - Supports hierarchical Dependency Injection
12
- - Easy API that supports Singleton and Transient patterns
13
- - Support for decorator and JSX based injection
14
- - Automatic cleaning of injected properties on unmounting of React components
11
+ - Hierarchical dependency injection mirroring the React tree
12
+ - Singleton and transient (per-resolve) bindings
13
+ - Decorator-based and JSX-based providers and injections
14
+ - Hook and decorator consumers for function and class components
15
+ - Automatic disposal of provided services on unmount
16
+ - Async store initialization with loading and error fallbacks
15
17
 
16
- ## Examples
18
+ ## Setup
17
19
 
18
- ### @injectable
20
+ ### Install
19
21
 
20
- Alias for [@injectable](https://github.com/inversify/InversifyJS#step-2-declare-dependencies-using-the-injectable--inject-decorators) from InversifyJS.
22
+ ```bash
23
+ npm install @servicetitan/react-ioc
24
+ ```
21
25
 
22
- ```tsx
23
- @injectable()
24
- class Store {
25
- value = 123;
26
+ The package imports `reflect-metadata` for you. Do not import it again in your application.
27
+
28
+ ### TypeScript configuration
29
+
30
+ Decorator-based APIs (`@injectable`, `@inject`, `@injectDependency`, `@provide`) require these compiler options:
31
+
32
+ ```json title="tsconfig.json"
33
+ {
34
+ "compilerOptions": {
35
+ "experimentalDecorators": true,
36
+ "emitDecoratorMetadata": true
37
+ }
26
38
  }
27
39
  ```
28
40
 
29
- ### Container
41
+ :::note
42
+ Projects extending `@servicetitan/startup/tsconfig/base` already have both flags enabled and need no further configuration.
43
+ :::
30
44
 
31
- Alias for [Container](https://github.com/inversify/InversifyJS/blob/master/wiki/container_api.md) from InversifyJS, could be used for testing purposes.
45
+ The hook-based APIs (`useDependencies`, `useOptionalDependencies`) and the JSX `<Provider>` work without decorators.
32
46
 
33
- ```tsx
34
- const rootContainer = new Container();
47
+ ## Concepts
48
+
49
+ ### Container hierarchy
50
+
51
+ Every `<Provider>` (or `@provide`-decorated component) creates a new InversifyJS [Container](https://inversify.io/docs/6.x/api/container/) whose parent is the container from the nearest ancestor Provider. When a consumer asks for a token, the container walks up the chain until a match is found, exactly like React Context lookup.
52
+
53
+ This means you can re-provide a service for a sub-tree without disturbing the rest of the app. See [Reusing a parent binding](#inherit) for the `inherit` flag that opts back in to the parent's instance.
54
+
55
+ #### `rootContainer`
56
+
57
+ The chain terminates at `rootContainer`, an InversifyJS `Container` created at module load. It is also the default value of the underlying `ContainerContext`, so a consumer rendered without any `<Provider>` above it resolves against `rootContainer`. Two cases where you might bind directly into it:
58
+
59
+ - **App-wide globals without wrapping the whole tree.** Calling `rootContainer.bind(Logger).toConstantValue(...)` once at startup makes the binding visible to every consumer in the app, even ones rendered outside a `<Provider>`.
60
+ - **Resolving from non-React code** that runs before the React tree mounts.
61
+
62
+ Prefer `<Provider>` in normal application code. Bindings on `rootContainer` are global, persist for the lifetime of the process, and cannot be overridden by descendants the way Provider bindings can.
63
+
64
+ ### Singletons vs instances
65
+
66
+ `<Provider>` accepts two lists, with different scopes.
67
+
68
+ | List | Scope | When to use |
69
+ | :----------- | :------------------------------------------------------------------------------- | :----------------------------------------------------------------------- |
70
+ | `singletons` | One instance per container. Every consumer in the sub-tree gets the same object. | Stores, services, anything that holds state shared across the sub-tree. |
71
+ | `instances` | A new instance per resolution (transient). | Stateless helpers, per-call value objects. Rare for typical store usage. |
72
+
73
+ ### Tokens
74
+
75
+ A token identifies a binding. Three shapes are supported:
76
+
77
+ | Token form | Example | Notes |
78
+ | :------------------ | :------------------------------- | :----------------------------------------------------------------------------------------- |
79
+ | Class (constructor) | `Store` | Most common. The class itself is the token and the implementation. |
80
+ | Symbol token | `symbolToken<ILogger>('LOGGER')` | Use when there is no concrete class (interface only) or you need multiple implementations. |
81
+ | Function | A function reference | Allowed by the type, mainly for interop. Prefer classes or symbol tokens. |
82
+
83
+ ## Providing services
84
+
85
+ ### `Provider` {#provider}
86
+
87
+ JSX provider. Use anywhere in your tree.
35
88
 
36
- rootContainer.bind(Store).toSelf();
89
+ ```tsx
90
+ import { Provider } from '@servicetitan/react-ioc';
37
91
 
38
- const store = container.get(Store);
92
+ <Provider singletons={[Store]}>
93
+ <Component />
94
+ </Provider>;
39
95
  ```
40
96
 
41
- ### @provide
97
+ #### Props
98
+
99
+ | Name | Type | Description |
100
+ | :---------------- | :--------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------- |
101
+ | `singletons` | [`ProviderConfigEntry[]`](#entry-shapes) | (optional) Singleton-scoped bindings. |
102
+ | `instances` | [`ProviderConfigEntry[]`](#entry-shapes) | (optional) Transient-scoped bindings. |
103
+ | `loadingFallback` | `ReactNode` | (optional) Rendered while [`Store.initialize`](#store-lifecycle) promises are pending. Defaults to `<h2>Loading...</h2>`. |
104
+ | `errorFallback` | `ReactNode` | (optional) Rendered when initialization throws or [duplicate tokens](#runtime-checks) are found. Defaults to `<h2>Error</h2>`. |
105
+ | `children` | `ReactNode` | The sub-tree that can consume the bindings. |
42
106
 
43
- A decorator used to inject the required information in the current level of hierarchy.
107
+ ### `@provide` {#provide}
44
108
 
45
- _NOTE:_ `@provide` creates new InversifyJS container with a link to a parent one meaning that all React components below `@provide` will try to resolve stores from closest container first. Using this mechanism you can re-provide the same store just for the sub-part of React component tree if needed. More info about hierarchical DI can be found [here](https://github.com/inversify/InversifyJS/blob/master/wiki/hierarchical_di.md).
109
+ Decorator equivalent of `<Provider>`. Wraps a function or class component.
46
110
 
47
111
  ```tsx
48
- const Component: React.FC = provide({
112
+ import { provide } from '@servicetitan/react-ioc';
113
+
114
+ const Component = provide({
49
115
  singletons: [Store],
50
- })(() => {
51
- return <SubComponent />;
52
- });
116
+ })(() => <SubComponent />);
53
117
  ```
54
118
 
55
119
  ```tsx
120
+ import { provide } from '@servicetitan/react-ioc';
121
+
56
122
  @provide({
57
123
  singletons: [Store],
58
124
  })
@@ -63,43 +129,150 @@ class Component extends React.Component {
63
129
  }
64
130
  ```
65
131
 
66
- ### Provider
132
+ #### Parameters
133
+
134
+ | Name | Type | Description |
135
+ | :-------- | :---------------------------------------------------- | :----------------------------------------------------------------------------------------------------- |
136
+ | `entries` | `{ singletons?, instances? }` | Same shape as the [`Provider`](#provider) `singletons` / `instances` props. |
137
+ | `options` | [`FallbackOptions`](#fallback-options) \| `ReactNode` | (optional) Fallback configuration. Passing a `ReactNode` is shorthand for `{ loadingFallback: node }`. |
138
+
139
+ #### `FallbackOptions` {#fallback-options}
140
+
141
+ | Name | Type | Description |
142
+ | :---------------- | :---------- | :----------------------------------------------------------------------------- |
143
+ | `loadingFallback` | `ReactNode` | (optional) Forwarded to [`Provider`](#provider) as the `loadingFallback` prop. |
144
+ | `errorFallback` | `ReactNode` | (optional) Forwarded to [`Provider`](#provider) as the `errorFallback` prop. |
145
+
146
+ ```tsx
147
+ import { Spinner } from '@servicetitan/anvil2';
148
+ import { provide } from '@servicetitan/react-ioc';
149
+
150
+ // shorthand: ReactNode is treated as loadingFallback
151
+ const A = provide({ singletons: [Store] }, <Spinner />)(App);
152
+
153
+ // full options
154
+ const B = provide(
155
+ { singletons: [Store] },
156
+ { loadingFallback: <Spinner />, errorFallback: <ErrorScreen /> }
157
+ )(App);
158
+ ```
159
+
160
+ ### Provider entry shapes {#entry-shapes}
161
+
162
+ The four ways to write a binding in `singletons` or `instances`.
163
+
164
+ ```tsx
165
+ import { Provider, symbolToken } from '@servicetitan/react-ioc';
166
+
167
+ // 1. Bare class. Token and implementation are the same.
168
+ <Provider singletons={[Store]} />;
169
+
170
+ // 2. Different implementation for a class token.
171
+ <Provider singletons={[{ provide: Store, useClass: StoreV2 }]} />;
172
+
173
+ // 3. Constant value for a symbol or function token.
174
+ const CONFIG_TOKEN = symbolToken<AppConfig>('APP_CONFIG');
175
+ <Provider singletons={[{ provide: CONFIG_TOKEN, useValue: { apiUrl: '/api' } }]} />;
176
+
177
+ // 4. Object form with only `provide`. Same as a bare class.
178
+ <Provider singletons={[{ provide: Store }]} />;
179
+ ```
180
+
181
+ | Field | Type | Description |
182
+ | :--------- | :-------------------- | :---------------------------------------------------------------------------------------------------------------- |
183
+ | `provide` | [`Token<T>`](#tokens) | The identifier consumers ask for. |
184
+ | `useClass` | `Newable<T>` | (optional) Class to instantiate. If omitted on a class token, `provide` is used as both token and implementation. |
185
+ | `useValue` | `T` | (optional) Pre-built value. Cannot be combined with `useClass`. Only valid in `singletons`. |
186
+ | `inherit` | `true` | (optional) See [Reusing a parent binding](#inherit). Only valid in `singletons`. |
187
+
188
+ ### Reusing a parent binding {#inherit}
67
189
 
68
- A functional component equivalent to [@provide](#provide)
190
+ `inherit: true` makes a binding skip itself if the token is already bound in an ancestor container. The descendant consumer ends up with the parent's instance.
69
191
 
70
192
  ```tsx
193
+ import { Provider } from '@servicetitan/react-ioc';
194
+
71
195
  <Provider singletons={[Store]}>
72
- <Component />
73
- </Provider>
196
+ <Inner />
197
+ </Provider>;
198
+
199
+ // inside Inner:
200
+ <Provider singletons={[{ provide: Store, inherit: true }]}>
201
+ <Leaf /> {/* receives the outer Store instance */}
202
+ </Provider>;
74
203
  ```
75
204
 
76
- ### @inject
205
+ Use this as a defensive measure when a component must declare its own dependency list to work standalone, but should reuse an ancestor's instance whenever one is present. Without `inherit`, the child would always create a fresh container-local instance and silently fork state from the enclosing scope.
206
+
207
+ ### Runtime checks {#runtime-checks}
208
+
209
+ `Provider` validates `singletons` and `instances` at mount.
210
+
211
+ #### Duplicate entries
212
+
213
+ When a token is listed more than once, InversifyJS reports an "Ambiguous match" error at injection time, far from the offending list. `Provider` catches the duplicate at mount instead.
77
214
 
78
- Alias for [@inject](https://github.com/inversify/InversifyJS#step-2-declare-dependencies-using-the-injectable--inject-decorators) from InversifyJS, could be used for injecting information in not React classes.
215
+ - In development, the provider renders `errorFallback` and throws an error that names every duplicated token.
216
+ - In production, it emits `console.warn` and binds only the first occurrence (singletons before instances).
79
217
 
80
218
  ```tsx
81
- class ConsumerStore {
82
- constructor(@inject(Store) private readonly store: Store) {}
83
- }
219
+ import { Provider } from '@servicetitan/react-ioc';
220
+
221
+ // SomeStore listed twice: throws in development, warns in production.
222
+ <Provider singletons={[SomeStore, SomeStore]}>
223
+ <Children />
224
+ </Provider>;
84
225
  ```
85
226
 
86
- ### useDependencies
227
+ :::note
228
+ The same token appearing in both `singletons` and `instances` is also flagged.
229
+ :::
87
230
 
88
- A Hook that can be used in order to consume IoC container in any child functional component.
231
+ ## Consuming services
232
+
233
+ ### `useDependencies` {#use-dependencies}
234
+
235
+ Hook for function components. Returns a tuple in the order of the tokens passed.
89
236
 
90
237
  ```tsx
91
- const SubComponent: React.FC = () => {
92
- const [store] = useDependencies(Store);
238
+ import { useDependencies } from '@servicetitan/react-ioc';
93
239
 
240
+ const SubComponent: React.FC = () => {
241
+ const [store, logger] = useDependencies(Store, LOGGER_TOKEN);
94
242
  return <div>{store.value}</div>;
95
243
  };
96
244
  ```
97
245
 
98
- ### injectDependency
246
+ Throws if any token is not bound in the container hierarchy.
247
+
248
+ ### `useOptionalDependencies` {#use-optional-dependencies}
99
249
 
100
- A Hook that can be used in order to consume IoC container in any child component.
250
+ Same shape as `useDependencies`, but returns `undefined` for tokens that are not bound instead of throwing.
101
251
 
102
252
  ```tsx
253
+ import { useOptionalDependencies } from '@servicetitan/react-ioc';
254
+
255
+ const SaveButton: React.FC = () => {
256
+ const [log] = useOptionalDependencies(Log);
257
+
258
+ const onClick = () => {
259
+ log?.info('save clicked');
260
+ save();
261
+ };
262
+
263
+ return <button onClick={onClick}>Save</button>;
264
+ };
265
+ ```
266
+
267
+ Use this when a service is genuinely optional, for example a logger that is only bound in production builds. The component works either way and skips the call when `Log` is not provided.
268
+
269
+ ### `@injectDependency` {#inject-dependency}
270
+
271
+ Property decorator for class components.
272
+
273
+ ```tsx
274
+ import { injectDependency } from '@servicetitan/react-ioc';
275
+
103
276
  class SubComponent extends React.Component {
104
277
  @injectDependency(Store)
105
278
  store!: Store;
@@ -110,11 +283,148 @@ class SubComponent extends React.Component {
110
283
  }
111
284
  ```
112
285
 
113
- ### Using tokens
286
+ Combine with InversifyJS `@optional()` for optional bindings:
287
+
288
+ ```tsx
289
+ import { injectDependency, optional } from '@servicetitan/react-ioc';
290
+
291
+ class SubComponent extends React.Component {
292
+ @injectDependency(LOGGER_TOKEN)
293
+ @optional()
294
+ logger?: ILogger;
295
+ }
296
+ ```
297
+
298
+ :::caution
299
+ `@injectDependency` reads the component's `context`. If you override the constructor and access an injected property in it, you must forward `context` to `super`:
300
+
301
+ ```tsx
302
+ constructor(props: Props, context: any) {
303
+ super(props, context);
304
+ this.store.doSomething(); // safe
305
+ }
306
+ ```
307
+
308
+ Without this, you will see `"Context doesn't exist on a target class."` at runtime.
309
+ :::
310
+
311
+ ### `@inject`
312
+
313
+ Re-exported [from InversifyJS](https://inversify.io/docs/6.x/introduction/getting-started/). Attaches an explicit token to a constructor parameter or property so the container knows which binding to resolve.
314
+
315
+ :::tip
316
+ Only needed when the identifier isn't a class reference, for example a [`Symbol` token](#tokens) representing an interface. For class parameters, InversifyJS infers the token from the parameter type, so prefer omitting `@inject`.
317
+ :::
318
+
319
+ For a non-class token, the container needs the explicit identifier:
320
+
321
+ ```tsx
322
+ import { inject, injectable } from '@servicetitan/react-ioc';
323
+
324
+ @injectable()
325
+ class Analytics {
326
+ constructor(@inject(LOGGER_TOKEN) private readonly logger: ILogger) {}
327
+ }
328
+ ```
329
+
330
+ For a class token, the decorator is redundant:
331
+
332
+ ```tsx
333
+ import { injectable } from '@servicetitan/react-ioc';
334
+
335
+ @injectable()
336
+ class ConsumerStore {
337
+ // No `@inject` needed: the parameter type `Store` is the token.
338
+ constructor(private readonly store: Store) {}
339
+ }
340
+ ```
341
+
342
+ ### `@optional`
343
+
344
+ Re-exported [from InversifyJS](https://inversify.io/docs/6.x/api/decorator/#optional). Marks a constructor parameter or property injection as optional, so the container will not throw when the token is unbound.
345
+
346
+ ```tsx
347
+ import { inject, injectable, optional } from '@servicetitan/react-ioc';
348
+
349
+ @injectable()
350
+ class Analytics {
351
+ constructor(@inject(LOGGER_TOKEN) @optional() private readonly logger?: ILogger) {}
352
+ }
353
+ ```
354
+
355
+ ### `@unmanaged`
356
+
357
+ Re-exported [from InversifyJS](https://inversify.io/docs/6.x/api/decorator/#unmanaged). Marks a constructor parameter as not managed by the container. Useful when extending a base class whose constructor takes arguments the DI container should ignore.
358
+
359
+ ```tsx
360
+ import { injectable, unmanaged } from '@servicetitan/react-ioc';
361
+
362
+ @injectable()
363
+ abstract class Base {
364
+ constructor(@unmanaged() protected readonly tag: string) {}
365
+ }
366
+
367
+ @injectable()
368
+ class Concrete extends Base {
369
+ constructor(store: Store) {
370
+ super('concrete');
371
+ }
372
+ }
373
+ ```
374
+
375
+ ## Defining services
376
+
377
+ ### `@injectable`
378
+
379
+ Re-exported [from InversifyJS](https://inversify.io/docs/6.x/api/decorator/#injectable). Marks a class as something the container is allowed to construct.
380
+
381
+ ```tsx
382
+ import { injectable } from '@servicetitan/react-ioc';
383
+
384
+ @injectable()
385
+ class Store {
386
+ value = 123;
387
+ }
388
+ ```
389
+
390
+ Required on every class you want to bind, including those that only use `@injectDependency` for property injection.
391
+
392
+ ### `Store` {#store-lifecycle}
114
393
 
115
- #### Creating a token
394
+ Abstract base class for stores that need async setup or cleanup. Already `@injectable`.
116
395
 
117
396
  ```tsx
397
+ import { Store } from '@servicetitan/react-ioc';
398
+
399
+ class UserStore extends Store {
400
+ user?: User;
401
+
402
+ async initialize() {
403
+ this.user = await fetchUser();
404
+ }
405
+
406
+ dispose() {
407
+ this.user = undefined;
408
+ }
409
+ }
410
+ ```
411
+
412
+ When a `Store` subclass is bound on a `<Provider>`:
413
+
414
+ 1. The provider calls `initialize()` after binding.
415
+ 2. If it returns a promise, the provider renders `loadingFallback` until the promise settles.
416
+ 3. If the promise rejects (or `initialize()` throws), the provider renders `errorFallback` and rethrows asynchronously so global error handlers fire.
417
+ 4. On unmount, `dispose()` runs after the container is unbound.
418
+
419
+ `initialize` and `dispose` are both optional.
420
+
421
+ ### Tokens for interfaces
422
+
423
+ When you need to bind an interface rather than a concrete class, create a symbol token.
424
+
425
+ ```tsx
426
+ import { symbolToken } from '@servicetitan/react-ioc';
427
+
118
428
  interface ILogger {
119
429
  error(e: Error): void;
120
430
  }
@@ -122,9 +432,26 @@ interface ILogger {
122
432
  const LOGGER_TOKEN = symbolToken<ILogger>('LOGGER_TOKEN');
123
433
  ```
124
434
 
125
- #### Injecting a service by token
435
+ #### `symbolToken<T>(key, global?)`
436
+
437
+ | Name | Type | Description |
438
+ | :------- | :-------- | :------------------------------------------------------------------------------------------------------ |
439
+ | `key` | `string` | Human-readable identifier. Appears in error messages. |
440
+ | `global` | `boolean` | (optional, default `true`) When `true`, uses `Symbol.for(key)` so two modules can share the same token. |
441
+
442
+ Use a token to provide and inject the interface:
126
443
 
127
444
  ```tsx
445
+ import { injectDependency, provide, symbolToken } from '@servicetitan/react-ioc';
446
+
447
+ // Implementation of the interface.
448
+ class Logger implements ILogger {
449
+ error(e: Error) {
450
+ console.log(e);
451
+ }
452
+ }
453
+
454
+ // Consumer: asks for the token, gets whatever implementation is bound.
128
455
  class ErrorBoundary extends React.Component {
129
456
  state = { hasError: false };
130
457
 
@@ -137,24 +464,11 @@ class ErrorBoundary extends React.Component {
137
464
  }
138
465
 
139
466
  render() {
140
- if (this.state.hasError) {
141
- return <div>Something went wrong...</div>;
142
- }
143
-
144
- return this.props.children;
145
- }
146
- }
147
- ```
148
-
149
- #### Providing a service
150
-
151
- ```tsx
152
- class Logger implements ILogger {
153
- error(e: Error) {
154
- console.log(e);
467
+ return this.state.hasError ? <div>Something went wrong...</div> : this.props.children;
155
468
  }
156
469
  }
157
470
 
471
+ // Provider: binds the token to a concrete implementation for the sub-tree.
158
472
  const App = provide({ singletons: [{ provide: LOGGER_TOKEN, useClass: Logger }] })(() => (
159
473
  <ErrorBoundary>
160
474
  <Router />
@@ -162,44 +476,89 @@ const App = provide({ singletons: [{ provide: LOGGER_TOKEN, useClass: Logger }]
162
476
  ));
163
477
  ```
164
478
 
165
- #### Reusing a service
479
+ ## Testing
480
+
481
+ For component tests, render under a `<Provider>` with mocks in place of the real bindings. For service-only tests with no React in the picture, build an InversifyJS `Container` directly.
482
+
483
+ ### Overriding a binding for a test
166
484
 
167
- You can use the inherit option to reuse existing services that are already provided. In this case, service is only created if it is not already provided in a parent container.
485
+ Render the component under test inside a `<Provider>` that binds mocks.
168
486
 
169
487
  ```tsx
170
- class SomeStore {}
488
+ import { render, screen } from '@testing-library/react';
489
+ import { Provider } from '@servicetitan/react-ioc';
171
490
 
172
- class SomeOtherStore {}
491
+ class UserStoreMock {
492
+ user = { id: 1, name: 'Test' };
493
+ }
494
+
495
+ test('renders the user name', () => {
496
+ render(
497
+ <Provider singletons={[{ provide: UserStore, useClass: UserStoreMock }]}>
498
+ <UserBadge />
499
+ </Provider>
500
+ );
173
501
 
174
- const App = provide({
175
- singletons: [
176
- { provide: SomeStore, useClass: SomeOtherStore, inherit: true },
177
- { provide: SomeOtherStore, inherit: true },
178
- ],
179
- })(() => <div />);
502
+ expect(screen.getByText('Test')).toBeInTheDocument();
503
+ });
180
504
  ```
181
505
 
182
- #### Service initialization
506
+ ### Providing a constant value
183
507
 
184
- If a service inherits from Store, react-ioc calls the optional `initialize` method before rendering content and calls `dispose` after unbind. Also, you can pass a loading fallback that will be rendered during initialization.
508
+ `useValue` is the right tool for fixtures and config objects.
185
509
 
186
510
  ```tsx
187
- import { Spinner } from '@servicetitan/design-system';
188
- import { Store } from '@servicetitan/react-ioc';
511
+ import { Provider, symbolToken } from '@servicetitan/react-ioc';
189
512
 
190
- class SomeStore extends Store {
191
- constructor() {
192
- super();
193
- }
513
+ render(
514
+ <Provider singletons={[{ provide: CONFIG_TOKEN, useValue: { apiUrl: '/test' } }]}>
515
+ <SettingsPanel />
516
+ </Provider>
517
+ );
518
+ ```
194
519
 
195
- async initialize() {
196
- // do some initialization
197
- }
520
+ ### Using `Container` directly
198
521
 
199
- dispose() {
200
- // implement disposal
522
+ For unit tests of services that resolve other services, you can skip React entirely. Build a fresh `Container`, bind real and fake collaborators, resolve the subject, then exercise it.
523
+
524
+ Given an `Analytics` service that depends on `Logger`:
525
+
526
+ ```tsx
527
+ import { injectable } from '@servicetitan/react-ioc';
528
+
529
+ @injectable()
530
+ class Analytics {
531
+ constructor(private readonly logger: Logger) {}
532
+
533
+ track(event: string) {
534
+ this.logger.info(event);
201
535
  }
202
536
  }
537
+ ```
538
+
539
+ ```tsx
540
+ import { Container } from '@servicetitan/react-ioc';
541
+
542
+ describe('Analytics', () => {
543
+ let container: Container;
544
+ let logger: Logger;
203
545
 
204
- const App = provide({ singletons: [SomeStore] }, { loadingFallback: <Spinner /> })(() => <div />);
546
+ const subject = () => container.get(Analytics);
547
+
548
+ beforeEach(() => {
549
+ jest.clearAllMocks();
550
+
551
+ logger = { info: jest.fn() } as Logger;
552
+
553
+ container = new Container();
554
+ container.bind(Logger).toConstantValue(logger);
555
+ container.bind(Analytics).toSelf();
556
+ });
557
+
558
+ test('forwards tracked events to the logger', () => {
559
+ subject().track('signup');
560
+
561
+ expect(logger.info).toHaveBeenCalledWith('signup');
562
+ });
563
+ });
205
564
  ```
@@ -5,7 +5,7 @@ title: clean
5
5
  Resets project workspace to a fresh state by clearing build caches and removing untracked files.
6
6
 
7
7
  It runs tools like `nx reset` and `jest --clearCache` to clear project and test
8
- caches, clears the npm and npx caches, and then uses `git clean -fdX` to delete
8
+ caches, clears the package manager and npx caches, and then uses `git clean -fdX` to delete
9
9
  all files ignored by Git (such as build outputs and temporary files).
10
10
 
11
11
  ```sh
@@ -12,7 +12,7 @@ This helps maintain consistency, avoid dependency hell, and enforce best practic
12
12
  npx startup review
13
13
  ```
14
14
 
15
- - Run from the root of your workspace (where your root `package.json` and `package-lock.json` are located).
15
+ - Run from the root of your workspace (where your root `package.json` and lock file are located).
16
16
  - The command will scan all packages (as defined by your workspace configuration) and report any errors or warnings found by the enabled rules.
17
17
 
18
18
  ---
@@ -20,7 +20,7 @@ npx startup review
20
20
  ## How It Works
21
21
 
22
22
  1. **Workspace Discovery**: Finds all packages in your monorepo using your workspace configuration.
23
- 2. **Dependency Analysis**: Builds a dependency graph and collects all installed versions from `package-lock.json`.
23
+ 2. **Dependency Analysis**: Builds a dependency graph and collects all installed versions from the lock file (`package-lock.json` or `pnpm-lock.yaml`).
24
24
  3. **Rule Execution**: Runs each enabled rule against your project and packages.
25
25
  4. **Reporting**: Outputs a summary of all problems found, grouped by file and severity.
26
26
 
@@ -37,7 +37,7 @@ npx startup review
37
37
  ## Troubleshooting
38
38
 
39
39
  - Make sure you run the command from the workspace root.
40
- - If you see unexpected results, check your configuration and ensure your `package-lock.json` is up to date.
40
+ - If you see unexpected results, check your configuration and ensure your lock file is up to date.
41
41
 
42
42
  ---
43
43
 
@@ -424,18 +424,20 @@ npm pkg set sideEffects=false -w @servicetitan/package
424
424
 
425
425
  ### require-npmrc
426
426
 
427
- Checks that your project contains a `.npmrc` file with `legacy-peer-deps=true`.
427
+ Checks that your project contains a `.npmrc` file with the following required and recommended settings:
428
428
 
429
429
  ```text title=".npmrc"
430
430
  legacy-peer-deps=true
431
431
  ```
432
432
 
433
- Setting `legacy-peer-deps=true` tells npm to use the older, more permissive peer dependency resolution algorithm (as in npm v6). This can help avoid installation failures when packages in your dependency tree have conflicting or unmet peer dependencies, which is common in large monorepos or when using older packages.
433
+ | Setting | Description |
434
+ | :----------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
435
+ | `legacy-peer-deps` | (Recommended) Tells npm to use the older, more permissive peer dependency resolution algorithm (as in npm v6). This can help avoid installation failures when packages in your dependency tree have conflicting or unmet peer dependencies, which is common in large monorepos or when using older packages. |
434
436
 
435
437
  #### ✅ Autofix
436
438
 
437
439
  This rule supports autofix.
438
- It creates or updates your `.npmrc` file to include `legacy-peer-deps=true`. E.g.,
440
+ It creates or updates your `.npmrc` file to include the missing settings. E.g.,
439
441
 
440
442
  ```sh
441
443
  npm config set --location=project legacy-peer-deps=true
@@ -536,24 +538,26 @@ To manually hoist packages to the root `node_modules`:
536
538
 
537
539
  Where `<name>` is the package name and `<version>` is the package version to hoist.
538
540
 
539
- 2. Update the `package-lock.json`:
541
+ 2. Update the lock file:
540
542
 
541
543
  ```sh
542
544
  npm install --legacy-peer-deps --package-lock-only --prefer-dedupe
543
545
  ```
544
546
 
545
- 3. Remove the package(s) from the root `package.json`. E.g.,
547
+ Or, for pnpm projects:
546
548
 
547
549
  ```sh
548
- npm pkg delete dependencies[<name>]
550
+ pnpm install --lockfile-only
549
551
  ```
550
552
 
551
- 4. Update `package-lock.json` a final time:
553
+ 3. Remove the package(s) from the root `package.json`. E.g.,
552
554
 
553
555
  ```sh
554
- npm install --legacy-peer-deps --package-lock-only --prefer-dedupe
556
+ npm pkg delete dependencies[<name>]
555
557
  ```
556
558
 
559
+ 4. Update the lock file a final time using the same command from step 2.
560
+
557
561
  ---
558
562
 
559
563
  ### require-tsconfig-references
@@ -112,6 +112,56 @@ Renders,
112
112
  <img src="@servicetitan/anvil2/assets/icons/material/round/expand_more.svg" />
113
113
  ```
114
114
 
115
+ ## Debugging tests
116
+
117
+ You can debug tests in your IDE while still running them through `startup test`.
118
+
119
+ ### VS Code
120
+
121
+ Add a Node launch configuration that runs the `startup` binary with the `test` command. The same configuration works for both Jest and Vitest.
122
+
123
+ ```json title=".vscode/launch.json"
124
+ {
125
+ "version": "0.2.0",
126
+ "configurations": [
127
+ {
128
+ "type": "node",
129
+ "request": "launch",
130
+ "name": "Test All",
131
+ "program": "${workspaceFolder}/node_modules/.bin/startup",
132
+ "args": ["test", "--runInBand"],
133
+ "console": "integratedTerminal",
134
+ "internalConsoleOptions": "neverOpen",
135
+ "windows": {
136
+ "program": "${workspaceFolder}/node_modules/@servicetitan/startup/dist/cli"
137
+ }
138
+ },
139
+ {
140
+ "type": "node",
141
+ "request": "launch",
142
+ "name": "Test Current File",
143
+ "program": "${workspaceFolder}/node_modules/.bin/startup",
144
+ "args": ["test", "${file}", "--runInBand"],
145
+ "console": "integratedTerminal",
146
+ "internalConsoleOptions": "neverOpen",
147
+ "windows": {
148
+ "program": "${workspaceFolder}/node_modules/@servicetitan/startup/dist/cli"
149
+ }
150
+ }
151
+ ]
152
+ }
153
+ ```
154
+
155
+ :::note
156
+ On Windows, `node_modules/.bin/startup` is a wrapper script generated by npm, not a JavaScript file. Node's launch configuration cannot execute it directly, so the `windows` override points at the underlying JavaScript entry instead.
157
+ :::
158
+
159
+ To debug Vitest tests, add `--runner vitest` to `args` and replace `--runInBand` with `--no-file-parallelism`. See [Vitest's debugging guide](https://vitest.dev/guide/debugging.html) for more options.
160
+
161
+ ### WebStorm / Rider
162
+
163
+ For Jest, install [`@servicetitan/startup-jest`](/docs/frontend/anvil-uikit-contrib/startup-jest) and set it as the Jest package in your Run/Debug Configuration. There is no equivalent wrapper for Vitest.
164
+
115
165
  ## Configuration
116
166
 
117
167
  - [Jest](./jest)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@servicetitan/docs-uikit",
3
- "version": "36.1.1",
3
+ "version": "36.3.0",
4
4
  "description": "Documentation content for Uikit packages published at docs.st.dev",
5
5
  "repository": {
6
6
  "type": "git",
@@ -16,5 +16,5 @@
16
16
  "cli": {
17
17
  "webpack": false
18
18
  },
19
- "gitHead": "613ecdc5bb02a009292843c9674bcd18f408bcfa"
19
+ "gitHead": "5c664540fe1fa530da3b311b28941e2fb26c6cff"
20
20
  }