# @sailpoint/ui-plugin-sdk

Browser runtime library for SailPoint ISC UI plugins — COIP/iframe handshake and plugin integration.

## Getting Started

### Prerequisites

- [Node.js](https://nodejs.org/) >= 22
- [pnpm](https://pnpm.io/) 10 (`corepack enable`)

### Setup

```bash
pnpm install
```

### Usage

When the plugin is mounted inside ISC, the SDK resolves the App Shell origin from
the iframe context:

```typescript
import { createSDK } from '@sailpoint/ui-plugin-sdk';

const sdk = createSDK();
const context = await sdk.getContext();
```

The SDK reconciles the App Shell-provided `parentOrigin` query parameter with
the browser ancestor origin when available, then falls back to the document
referrer. It throws if no trusted origin can be resolved or if the query and
browser ancestor origins disagree.

This resolution is defense-in-depth for consistent postMessage targeting and
inbound origin validation. A plugin's `frame-ancestors` CSP remains the primary
control that prevents untrusted pages from embedding it.

Pass `targetOrigin` explicitly for tests, mocks, or non-standard embeddings:

```typescript
const sdk = createSDK({ targetOrigin: 'https://app-shell.example.com' });
```

### Color Theme Synchronization

The SDK starts with `window.matchMedia('(prefers-color-scheme: dark)')`. In browsers that propagate color scheme into embedded documents, this follows the parent App Shell; otherwise, it follows the operating-system or browser preference.

In Safari, including Safari 27.2, this fallback follows the operating-system preference rather than live App Shell theme changes. A valid App Shell color-scheme value still becomes authoritative when received through the SDK.

The effective value updates `document.documentElement.style.colorScheme` and `sdk.theme.getColorScheme()`. Theme subscribers receive later changes:

```typescript
const unsubscribe = sdk.events.onThemeChange(({ colorScheme }) => {
	chart.setTheme(colorScheme);
});

// Remove one callback when its owner is disposed.
unsubscribe();
```

Root synchronization defaults to on because it lets native controls and browser-provided UI match the App Shell. This can change the appearance of controls, scrollbars, and other browser-rendered elements in an existing plugin that only supports one scheme. Keep receiving the effective scheme without changing the document by opting out:

```typescript
const sdk = createSDK({ syncColorScheme: false });
```

`syncColorScheme` affects only `document.documentElement.style.colorScheme`. Theme state and events remain active, and `useSpds` separately controls the `spds-dark` class and branding styles.

When App Shell supplies a valid initial `colorScheme` or `SP_COLOR_SCHEME_UPDATE_EVT`, that value becomes authoritative and the SDK stops following `prefers-color-scheme`. Remove competing theme listeners and root `color-scheme` writes when adopting the SDK.

`useSpds` defaults to `false`. Set it to `true` only to apply the same effective scheme to the SPDS `spds-dark` class.

### Branding

`PluginContext.brand` exposes the optional App Shell colors for action buttons, active links, and navigation, regardless of `useSpds`. It also exposes `productName` and logo URLs.[^brand-logo-urls]

With `useSpds: true`, the SDK validates the colors, supplies SPDS defaults for missing or invalid values, injects the `--spds-branding-*` CSS variables, and redirects the supported PrimeNG tokens. Without `useSpds`, branding is available only through `PluginContext.brand`.

[^brand-logo-urls]: Logo URLs may not load from plugin applications yet. Support will be updated later.

The framework-neutral theme implementation is temporarily copied into this package. Maintainers can find its standalone exports, generated CSS contract, and removal instructions in [`src/design-system-theme/README.md`](./src/design-system-theme/README.md).

### Handling API Errors

Non-OK responses from `api.get` and `api.post` throw `ApiError`, which exposes the
HTTP status, status text, request path, and response body. JSON bodies are parsed;
non-JSON bodies remain strings, and empty or unreadable bodies are `null`.

```typescript
import { ApiError, createSDK } from '@sailpoint/ui-plugin-sdk';

const sdk = createSDK();

try {
	await sdk.api.get('/v3/accounts/missing');
} catch (error) {
	if (error instanceof ApiError) {
		handleRequestFailure(error.status, error.body);
	} else {
		throw error;
	}
}
```

Treat `body` as untrusted API data and avoid logging it without reviewing it for
sensitive content.

### Syncing Routes with App Shell

Full-page plugins with internal routing can report their current route so the
App Shell URL reflects it. Deep links, reloads, and shared URLs then land on the
same plugin sub-page. Call `navigation.setRoute` whenever the plugin's router
navigates:

```typescript
import { createSDK } from '@sailpoint/ui-plugin-sdk';

const sdk = createSDK();

router.afterEach(to => {
	void sdk.navigation.setRoute(to.fullPath);
});
```

- `subPath` is relative to `/plugin/{alias}/`. One leading `/` is stripped, so
  router paths such as `location.pathname` work as-is. `''` or `'/'` is the
  plugin home.
- Query and hash in `subPath` replace the plugin's previous ones. App Shell
  preserves its own host-owned query parameters.
- App Shell updates its URL with `history.replaceState`, so no browser history
  entry is added.
- The promise resolves once the event is sent. It waits for the SDK handshake
  and rejects if the handshake fails, or with `TypeError` if `subPath` is not a
  string.
- App Shell validates the path and **silently ignores** values it rejects:
  longer than 2048 characters, containing `..`, `%2e%2e`, `//`, `\`, or a scheme
  prefix, or resolving outside the plugin route. No error is sent back.
- Only full-page plugin mounts apply route changes. Slot mounts ignore them.

This replaces hand-written
`window.parent.postMessage({ type: 'SP_ROUTE_CHANGE_EVT', ... })` calls.

To restore the right view on reload or a deep link, read the route the host
mounted the plugin at from `page.subPath`. The SDK derives it from the App Shell
URL (`/ui/plugin/{alias-or-pluginId}/{subPath}`), so you don't have to parse
`page.route` yourself:

```typescript
const { page } = await sdk.getContext();

// 'settings/general' for .../ui/plugin/my-plugin/settings/general; '' for the start route.
router.navigateByUrl(`/${page.subPath}`);
```

- `subPath` holds path segments only, still percent-encoded, so
  `setRoute(page.subPath)` is a no-op round trip. Read query and hash from
  `new URL(page.route)`, which also contains App Shell's own parameters.
- It reflects the URL at mount time and does not follow later `setRoute` calls.
- It is `''` for slot mounts and for any route without a `/plugin/` segment.
- The SDK performs no navigation. How you route to `subPath` (path or hash
  location, suppressing the resulting `setRoute`) is up to your plugin.
- `page.route` is unchanged. Use it when you need the full host URL, for example
  to derive the tenant origin.

### Commands

| Command | Description |
|---------|-------------|
| `pnpm run build` | Compile TypeScript to `dist/` |
| `pnpm run lint` | Run ESLint |
| `pnpm run lint:fix` | Run ESLint with auto-fix |
| `pnpm run format` | Format code with Prettier |
| `pnpm run format:check` | Check formatting without writing |
| `pnpm run test` | Run Jest tests |
| `pnpm run typecheck` | TypeScript type checking (no emit) |

## Testing Plugins Offline

The `@sailpoint/ui-plugin-sdk/testing` subpath provides a framework-agnostic
mock App Shell for browser-like unit-test environments. Install the mock before
calling an SDK method that starts the handshake, then restore it after the test.

`context` is optional — the default models a valid least-privileged user, so pass
it only when the test depends on specific tenant or capability values.

```typescript
import { createSDK } from '@sailpoint/ui-plugin-sdk';
import type { UserCapabilities } from '@sailpoint/ui-plugin-sdk';
import { mockSdkContext } from '@sailpoint/ui-plugin-sdk/testing';

/**
 * Capability flags are exhaustive: App Shell always sends every key, so a mock
 * context must too. Start from all-false and enable what the test needs.
 */
const capabilities: UserCapabilities = {
	isOrgAdmin: true,
	isHelpdesk: false,
	isDashboard: false,
	isCertAdmin: false,
	isReportAdmin: false,
	isSourceAdmin: false,
	isSourceSubadmin: false,
	isRoleAdmin: false,
	isRoleSubadmin: false,
	isCloudGovAdmin: false,
	isCloudGovUser: false,
	isSaasManagementAdmin: false,
	isSaasManagementReader: false
};

const appShell = mockSdkContext({
	context: {
		tenant: {
			id: 'tenant-1',
			scriptName: 'acme',
			org: 'acme',
			name: 'Acme',
			pod: 'useast1',
			region: 'us-east-1',
			apiUrl: { idn: 'https://acme.api.identitynow.com' },
			products: []
		},
		user: { id: 'user-1', displayName: 'Test User', email: 'test@example.com', capabilities },
		page: { route: 'https://acme.identitynow.com/ui/plugin/example/settings' },
		slot: { id: 'slot-1' },
		pluginConfiguration: { pluginId: 'plugin-1' }
	}
});
const sdk = createSDK({ targetOrigin: appShell.targetOrigin });

expect(await sdk.getContext()).toEqual(appShell.context);

const onViewportChange = jest.fn();
sdk.events.onViewportChange(onViewportChange);
appShell.emitViewportChange({ width: 1280, height: 720 });

expect(onViewportChange).toHaveBeenCalledWith({ width: 1280, height: 720 });
appShell.restore();
```

The mock also supports `emitTokenUpdate()`, responds to forced token refreshes,
and exposes recorded outbound messages for protocol assertions. `routeChanges`
lists the `subPath` values sent through `navigation.setRoute`, in order and after
leading-slash normalization:

```typescript
await sdk.navigation.setRoute('/settings');
expect(appShell.routeChanges).toEqual(['settings']);
```

Appearance tests can start with separate operating-system and App Shell values, then drive either source:

```typescript
const appShell = mockSdkContext({
	osColorScheme: 'dark',
	appShellColorScheme: 'light',
	brand: { logoUrl: '/logo.svg', darkLogoUrl: '/logo-dark.svg' }
});
const sdk = createSDK({ targetOrigin: appShell.targetOrigin, useSpds: true });

appShell.emitOsColorSchemeChange('light');
appShell.emitThemeChange('dark');

appShell.restore();
```

`restore()` reinstates both the original parent `postMessage` implementation and the exact prior `window.matchMedia` property state.

`page.subPath` is optional in a mock context. The mock derives it from
`page.route` the same way the SDK does, so `appShell.context` always matches
`sdk.getContext()`. The default mock route is
`https://mock-app-shell.sailpoint.test/ui/plugin/mock-plugin/settings`, which
gives a `subPath` of `'settings'`.

The mock has no dependency on Jest, Vitest, or another test framework.

## Contributing

Contributions are welcome. See [CONTRIBUTING.md](./CONTRIBUTING.md) for how to report issues, propose changes, and run the project locally.

## License

[MIT](./LICENSE)

## Code of Conduct

This project follows the [Contributor Covenant](./CODE_OF_CONDUCT.md). Please read it before participating in issues, pull requests, or discussions.
