@swell/apps-sdk 2.0.0 → 2.1.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/README.md CHANGED
@@ -152,11 +152,35 @@ export default function ColorPicker({ value, setValue, readonly }: ComponentProp
152
152
  | `settings` | The app's public settings |
153
153
  | `locale`, `readonly` | Display locale and read-only state |
154
154
  | `theme` | The host's color theme, `'light'` or `'dark'`, re-rendered when it changes. The frame sets it as `data-theme` and `color-scheme` on its root from its start, so CSS can follow it with `:root[data-theme="dark"]` |
155
+ | `ui` | The host's UI kit settings (`{ config }`), for a component that uses the kit (see [Using the host's UI kit](#using-the-hosts-ui-kit)) |
155
156
  | `setValidity(error)` | Report a validation error, or `null` when valid |
156
157
  | `fetch` | Like `fetch`, but requests to the app's own origin (app functions, `/app-api`) carry a platform token when the host provides one, so they receive a verified `Swell-Context` with `surface` |
157
158
  | `call(name, data)` | Calls a host action and resolves with its result; payment components get `createIntent` and `getIntent` |
158
159
  | `on(event, handler)` | Handle a host event. Returns a function that removes the handler. Every handler of the event runs, in the order registered, each after the previous one settles; the first error thrown answers the host's `emit`, otherwise the last result other than `undefined` does. A handler registered again, as an effect does on a re-render, moves to the end, so keep steps that depend on each other in one handler. One removed while the event runs is skipped, and one registered meanwhile runs from the next event |
159
160
 
161
+ ### Using the host's UI kit
162
+
163
+ A component that sets `ui: true` in its `config` gets the host's UI kit, Swell UI, configured like the host's, so its controls look like the host page:
164
+
165
+ ```tsx
166
+ // The global SwellUI is ready at the first render; each <swell-*> element loads when its tag first appears
167
+ export const config = { ui: true };
168
+ ```
169
+
170
+ - The platform answers the frame's `<page>.json` with `ui: { url }` for such a component, and the frame imports the kit's loader from it alongside the component bundle, without waiting for the host.
171
+ - The loader watches the frame's document: each kit element loads on the first use of its tag, and until then it is hidden and keeps its place in the layout.
172
+ - A component that renders kit elements inside a shadow root of its own passes that root to the loader, which then watches it as it watches the document:
173
+
174
+ ```ts
175
+ SwellUI.load(shadowRoot);
176
+ ```
177
+
178
+ - A component that needs elements defined, for example to call their methods, awaits `SwellUI.ready()` (every kit element on the page now) or `SwellUI.ready(['swell-input'])`. It rejects when an element cannot load.
179
+ - The types come from `@swell/swell-ui`, which declares the global `SwellUI`, and `@swell/swell-ui/preact`, which types the elements in Preact's JSX. Install the package as a dev dependency, `npm install -D @swell/swell-ui`, and add both to `compilerOptions.types` in `tsconfig.json`. The platform loads the kit's code, so a component imports the kit only as types: the Swell CLI leaves a value import of `@swell/swell-ui` out of the bundle and warns.
180
+ - Before the first render the frame calls `SwellUI.configure(config)` with the config the host passed as `ui.config`; without one the kit keeps its defaults. When the host updates `ui`, the frame configures the kit again and the kit restyles in place; the component re-renders as for any update.
181
+ - When the kit fails to load, the component still mounts without it and reports ready, and then the frame reports the error, which reaches the host's `error` listeners. The component keeps working, including `emit`.
182
+ - A component without `ui: true` never loads the kit.
183
+
160
184
  ### Payment components
161
185
 
162
186
  A component becomes the UI of a payment method by declaring the extension it implements in `config`:
@@ -217,11 +241,13 @@ badge.unmount();
217
241
  | --- | --- |
218
242
  | `ready` | Resolves when the component has mounted in its frame. Rejects when the app or component cannot be loaded, when the frame page does not start within 10 seconds of loading, when the props cannot be sent, or when you unmount first |
219
243
  | `on(event, handler)` | Listen to `change` (new value), `validity` (error or `null`) and `error` (load, start, token and component failures, including the ones that reject `ready`). Returns a function that removes the listener; other event names are ignored |
220
- | `update(input)` | Re-render with new `value`, `context`, `params`, `readonly`, `locale` or `theme`. Updates made before the component list loads are kept |
244
+ | `update(input)` | Re-render with new `value`, `context`, `params`, `readonly`, `locale`, `theme` or `ui`. Updates made before the component list loads are kept |
221
245
  | `emit(event, data)` | Waits for `ready`, then resolves with the last result other than `undefined` of the component's `on` handlers for the event, or rejects with the first error one throws |
222
246
  | `focus()` | Moves keyboard focus to the component's first control, for example when your form focuses its first invalid field. During overlay, to the component's modal |
223
247
  | `unmount()` | Removes the frame. Before the component list loads, it cancels the mount; `ready` and pending `emit` calls reject |
224
248
 
249
+ Pass `ui: { config }` to `mount` with the config your page gives Swell UI (a plain, structured-cloneable object), and update it when it changes. Components that use the kit apply it in their frames; others ignore it.
250
+
225
251
  Pass `actions` to `mount` to offer host actions that components reach with `call(name, data)`. Payment components also get built-in `createIntent` and `getIntent`, served by the Swell vault at `vaultUrl` (default `https://vault.schema.io`). Set `vaultUrl` in `createComponents` to use another vault.
226
252
 
227
253
  Props and event data must be structured-cloneable. Props that cannot be cloned fire `error`, and at mount they also reject `ready`; event data that cannot be cloned rejects that `emit` call.
@@ -248,7 +274,7 @@ methods.on('validity', (error) => { /* … */ });
248
274
  const results = await methods.emit('submit', { billing });
249
275
  ```
250
276
 
251
- The handle has `ready`, `components` (the mounted components), `on('validity' | 'error')`, `update` (context, params, readonly and locale; a place has no bound value), `emit`, `focus` and `unmount`. `emit` waits for `ready` and resolves with an array, one result per component that handled the event.
277
+ The handle has `ready`, `components` (the mounted components), `on('validity' | 'error')`, `update` (context, params, readonly, locale, theme and ui; a place has no bound value), `emit`, `focus` and `unmount`. `emit` waits for `ready` and resolves with an array, one result per component that handled the event.
252
278
 
253
279
  The platform returns every component of the store's active installed apps that declares the target; the host decides which of them to mount. `select` is called once for each of them before any frame is created, with its `name`, `app` (the app id), `targets` and `extension` (`id` and `type`), but not the app settings. It returns `true` for the components to mount; without `select` the place mounts all of them. A `select` that throws fails the place like a failed load: `ready` rejects, `error` fires, and no frames are created. `select` is fixed at mount; remount the place to change the method.
254
280
 
@@ -2,7 +2,8 @@ export interface FrameOptions {
2
2
  /**
3
3
  * URL of the component bundle: an ES module exporting mount, update and unmount. Relative URLs resolve against the
4
4
  * frame page. Without it the frame asks the platform: `<page path>.json` answers `{ bundleUrl }` for the build the
5
- * installation runs, as the platform's shell page (`component-frame.html`) expects.
5
+ * installation runs, as the platform's shell page (`component-frame.html`) expects, and `ui: { url }` when the
6
+ * component uses the host's UI kit.
6
7
  */
7
8
  bundleUrl?: string;
8
9
  /** Render target. Defaults to #root, created when missing. */
@@ -11,7 +12,7 @@ export interface FrameOptions {
11
12
  window?: Window & typeof globalThis;
12
13
  /** @internal Test seam: the host window. Defaults to window.parent. */
13
14
  parent?: Pick<Window, 'postMessage'>;
14
- /** @internal Test seam: loads the bundle. */
15
+ /** @internal Test seam: loads the bundle and the UI kit. */
15
16
  importModule?: (url: string) => Promise<unknown>;
16
17
  }
17
18
  /** Runs inside the component frame: connects to the host page and renders the component bundle. */
@@ -2,7 +2,8 @@ export interface FrameOptions {
2
2
  /**
3
3
  * URL of the component bundle: an ES module exporting mount, update and unmount. Relative URLs resolve against the
4
4
  * frame page. Without it the frame asks the platform: `<page path>.json` answers `{ bundleUrl }` for the build the
5
- * installation runs, as the platform's shell page (`component-frame.html`) expects.
5
+ * installation runs, as the platform's shell page (`component-frame.html`) expects, and `ui: { url }` when the
6
+ * component uses the host's UI kit.
6
7
  */
7
8
  bundleUrl?: string;
8
9
  /** Render target. Defaults to #root, created when missing. */
@@ -11,7 +12,7 @@ export interface FrameOptions {
11
12
  window?: Window & typeof globalThis;
12
13
  /** @internal Test seam: the host window. Defaults to window.parent. */
13
14
  parent?: Pick<Window, 'postMessage'>;
14
- /** @internal Test seam: loads the bundle. */
15
+ /** @internal Test seam: loads the bundle and the UI kit. */
15
16
  importModule?: (url: string) => Promise<unknown>;
16
17
  }
17
18
  /** Runs inside the component frame: connects to the host page and renders the component bundle. */
@@ -8,16 +8,17 @@ function isModule(value) {
8
8
  }
9
9
  const errorMessage = (error) => (error instanceof Error ? error.message : String(error));
10
10
  // Only the platform knows which build the installation runs, so it answers next to the shell page
11
- async function fetchBundleUrl(win) {
11
+ async function fetchMeta(win) {
12
12
  const response = await win.fetch(new URL(`${win.location.pathname}.json`, win.location.href).href, { headers: { Accept: 'application/json' } });
13
13
  if (response.status === 404)
14
14
  throw new Error('Component not found');
15
15
  if (!response.ok)
16
16
  throw new Error(`Component metadata failed (${response.status})`);
17
- const { bundleUrl } = (await response.json());
17
+ const { bundleUrl, ui } = (await response.json());
18
18
  if (typeof bundleUrl !== 'string' || !bundleUrl)
19
19
  throw new Error('Component metadata has no bundle URL');
20
- return new URL(bundleUrl, win.location.href).href;
20
+ const uiUrl = typeof ui?.url === 'string' && ui.url ? new URL(ui.url, win.location.href).href : undefined;
21
+ return { bundleUrl: new URL(bundleUrl, win.location.href).href, uiUrl };
21
22
  }
22
23
  /** Runs inside the component frame: connects to the host page and renders the component bundle. */
23
24
  export function startComponentFrame(options = {}) {
@@ -29,10 +30,20 @@ export function startComponentFrame(options = {}) {
29
30
  if (!parentOrigin || !channel || parent === win)
30
31
  throw new Error('App component frames must be embedded by a Swell host');
31
32
  // Asked right away, so the answer arrives while the host handshake runs; a failure is reported when the bundle loads
32
- const bundleUrl = options.bundleUrl !== undefined
33
- ? Promise.resolve(new URL(options.bundleUrl, win.location.href).href)
34
- : fetchBundleUrl(win);
35
- bundleUrl.catch(() => { });
33
+ const meta = options.bundleUrl !== undefined
34
+ ? Promise.resolve({ bundleUrl: new URL(options.bundleUrl, win.location.href).href })
35
+ : fetchMeta(win);
36
+ meta.catch(() => { });
37
+ const importModule = options.importModule ?? ((url) => import(/* webpackIgnore: true */ /* @vite-ignore */ url));
38
+ // The UI kit loads alongside the host handshake and the bundle. It resolves to the kit, or to null when the
39
+ // component does not use it; it rejects when the kit fails, and the component then mounts without it.
40
+ const kit = meta.then(({ uiUrl }) => uiUrl ? importModule(uiUrl).then(() => {
41
+ const ui = win.SwellUI;
42
+ if (typeof ui?.configure !== 'function')
43
+ throw new Error('the module defines no SwellUI');
44
+ return ui;
45
+ }) : null, () => null);
46
+ kit.catch(() => { });
36
47
  const document = win.document;
37
48
  const style = document.createElement('style');
38
49
  style.textContent = BASE_STYLE;
@@ -58,11 +69,12 @@ export function startComponentFrame(options = {}) {
58
69
  win.history.replaceState(win.history.state, '', url.href);
59
70
  };
60
71
  showTheme(params.get('theme') === 'dark' ? 'dark' : 'light');
61
- const importModule = options.importModule ?? ((url) => import(/* webpackIgnore: true */ /* @vite-ignore */ url));
62
72
  let props = null;
63
73
  let token = null;
64
74
  let module = null;
65
75
  let mounting = null;
76
+ // The loaded UI kit, set before the first render
77
+ let ui = null;
66
78
  let overlay = false;
67
79
  let lastHeight = -1;
68
80
  let scheduled = 0;
@@ -189,16 +201,31 @@ export function startComponentFrame(options = {}) {
189
201
  let loading = null;
190
202
  // One import per frame: an init that arrives while the bundle loads waits for the same import
191
203
  const loadModule = () => {
192
- loading ??= bundleUrl.then(importModule).then((loaded) => {
204
+ loading ??= meta.then(({ bundleUrl }) => importModule(bundleUrl)).then((loaded) => {
193
205
  if (!isModule(loaded))
194
206
  throw new Error('Component bundle must export mount, update and unmount');
195
207
  return loaded;
196
208
  });
197
209
  return loading;
198
210
  };
199
- // Mounts with the latest props (updates may arrive while the bundle loads) and reports ready once mount resolves
211
+ // Without a host config the kit keeps its defaults
212
+ const configureUi = () => {
213
+ const config = props?.ui?.config;
214
+ if (ui && config)
215
+ ui.configure(config);
216
+ };
217
+ // Mounts with the latest props (updates may arrive while the bundle loads) and reports ready once mount resolves.
218
+ // A kit that fails is reported after ready: the component works without it, and the host keeps it usable.
200
219
  async function mount() {
201
220
  const loaded = await loadModule();
221
+ let uiError = null;
222
+ try {
223
+ ui = await kit;
224
+ configureUi();
225
+ }
226
+ catch (error) {
227
+ uiError = error;
228
+ }
202
229
  const mountedProps = props;
203
230
  await loaded.mount(target, componentProps());
204
231
  module = loaded;
@@ -206,6 +233,8 @@ export function startComponentFrame(options = {}) {
206
233
  await loaded.update(target, componentProps());
207
234
  post({ type: 'ready' });
208
235
  reportHeight();
236
+ if (uiError)
237
+ post({ type: 'error', message: `Swell UI failed to load: ${errorMessage(uiError)}` });
209
238
  }
210
239
  async function handle(message) {
211
240
  switch (message.type) {
@@ -237,6 +266,9 @@ export function startComponentFrame(options = {}) {
237
266
  return;
238
267
  props = { ...props, ...message.props };
239
268
  applyTheme();
269
+ // The kit restyles live; the component re-renders with the new props as for any update
270
+ if ('ui' in message.props)
271
+ configureUi();
240
272
  await module?.update(target, componentProps());
241
273
  return;
242
274
  case 'token':
@@ -6,7 +6,7 @@ const RETRY_MS = 10_000;
6
6
  const MAX_RETRY_MS = 5 * 60_000;
7
7
  const MAX_TIMEOUT = 2 ** 31 - 1;
8
8
  const START_MS = 10_000;
9
- const INPUT_KEYS = ['value', 'context', 'params', 'readonly', 'locale', 'theme'];
9
+ const INPUT_KEYS = ['value', 'context', 'params', 'readonly', 'locale', 'theme', 'ui'];
10
10
  export const toError = (error) => (error instanceof Error ? error : new Error(String(error)));
11
11
  /** The theme a host shows: dark, or light for anything else. */
12
12
  const toTheme = (theme) => (theme === 'dark' ? 'dark' : 'light');
@@ -75,6 +75,7 @@ export function embedComponent(placeholder, options) {
75
75
  value: options.value, context: options.context ?? {}, params: options.params ?? {},
76
76
  settings: options.settings ?? {}, locale: options.locale ?? 'en', readonly: options.readonly ?? false,
77
77
  theme: toTheme(options.theme),
78
+ ...(options.ui !== undefined && { ui: options.ui }),
78
79
  };
79
80
  // The frame shows the theme from its start, before the host's init reaches it
80
81
  url.searchParams.set('theme', props.theme);
@@ -21,6 +21,9 @@ export interface WireProps {
21
21
  locale: string;
22
22
  readonly: boolean;
23
23
  theme: 'light' | 'dark';
24
+ ui?: {
25
+ config?: object;
26
+ };
24
27
  }
25
28
  export type HostMessage = {
26
29
  type: 'init';
@@ -21,6 +21,9 @@ export interface WireProps {
21
21
  locale: string;
22
22
  readonly: boolean;
23
23
  theme: 'light' | 'dark';
24
+ ui?: {
25
+ config?: object;
26
+ };
24
27
  }
25
28
  export type HostMessage = {
26
29
  type: 'init';
@@ -16,6 +16,11 @@ export interface ComponentProps<TValue = unknown, TContext = Record<string, unkn
16
16
  * can follow it with `:root[data-theme="dark"]`. `'light'` when the host passes none.
17
17
  */
18
18
  readonly theme: ComponentTheme;
19
+ /**
20
+ * The host's UI kit settings, for a component whose `config` has `ui: true`. The frame has already applied
21
+ * `ui.config` to the kit (`globalThis.SwellUI`) before the first render and on every change.
22
+ */
23
+ readonly ui?: ComponentUi;
19
24
  setValidity(error: string | null): void;
20
25
  /** fetch that adds the component token to requests to the frame's own origin. */
21
26
  readonly fetch: typeof fetch;
@@ -34,6 +39,10 @@ export interface ComponentProps<TValue = unknown, TContext = Record<string, unkn
34
39
  call<T = unknown>(name: string, data?: unknown): Promise<T>;
35
40
  }
36
41
  export type ComponentTheme = 'light' | 'dark';
42
+ /** The host's UI kit settings. `config` is the kit config the host runs with, a plain structured-cloneable object passed to `SwellUI.configure`. */
43
+ export interface ComponentUi {
44
+ readonly config?: Readonly<object>;
45
+ }
37
46
  /** Optional static metadata a component file exports as `config`. */
38
47
  export interface ComponentConfig {
39
48
  readonly description?: string;
@@ -45,6 +54,8 @@ export interface ComponentConfig {
45
54
  readonly targets?: readonly {
46
55
  readonly id: ComponentTarget;
47
56
  }[];
57
+ /** Loads the host's UI kit (Swell UI) into the frame, configured like the host's, before the first render. */
58
+ readonly ui?: boolean;
48
59
  }
49
60
  /** Module the CLI builds for each component. */
50
61
  export interface ComponentModule {
@@ -62,6 +73,10 @@ export interface ComponentInput<TValue = unknown, TContext = Record<string, unkn
62
73
  locale?: string;
63
74
  /** The host's color theme, light by default. Update it when the host switches. */
64
75
  theme?: ComponentTheme;
76
+ /** The host's UI kit config, a plain structured-cloneable object, applied in the frames of components that use the kit. Update it when it changes. */
77
+ ui?: {
78
+ config?: object;
79
+ };
65
80
  }
66
81
  /** Short-lived platform token. `expires` is in epoch seconds. */
67
82
  export interface ComponentToken {
@@ -16,6 +16,11 @@ export interface ComponentProps<TValue = unknown, TContext = Record<string, unkn
16
16
  * can follow it with `:root[data-theme="dark"]`. `'light'` when the host passes none.
17
17
  */
18
18
  readonly theme: ComponentTheme;
19
+ /**
20
+ * The host's UI kit settings, for a component whose `config` has `ui: true`. The frame has already applied
21
+ * `ui.config` to the kit (`globalThis.SwellUI`) before the first render and on every change.
22
+ */
23
+ readonly ui?: ComponentUi;
19
24
  setValidity(error: string | null): void;
20
25
  /** fetch that adds the component token to requests to the frame's own origin. */
21
26
  readonly fetch: typeof fetch;
@@ -34,6 +39,10 @@ export interface ComponentProps<TValue = unknown, TContext = Record<string, unkn
34
39
  call<T = unknown>(name: string, data?: unknown): Promise<T>;
35
40
  }
36
41
  export type ComponentTheme = 'light' | 'dark';
42
+ /** The host's UI kit settings. `config` is the kit config the host runs with, a plain structured-cloneable object passed to `SwellUI.configure`. */
43
+ export interface ComponentUi {
44
+ readonly config?: Readonly<object>;
45
+ }
37
46
  /** Optional static metadata a component file exports as `config`. */
38
47
  export interface ComponentConfig {
39
48
  readonly description?: string;
@@ -45,6 +54,8 @@ export interface ComponentConfig {
45
54
  readonly targets?: readonly {
46
55
  readonly id: ComponentTarget;
47
56
  }[];
57
+ /** Loads the host's UI kit (Swell UI) into the frame, configured like the host's, before the first render. */
58
+ readonly ui?: boolean;
48
59
  }
49
60
  /** Module the CLI builds for each component. */
50
61
  export interface ComponentModule {
@@ -62,6 +73,10 @@ export interface ComponentInput<TValue = unknown, TContext = Record<string, unkn
62
73
  locale?: string;
63
74
  /** The host's color theme, light by default. Update it when the host switches. */
64
75
  theme?: ComponentTheme;
76
+ /** The host's UI kit config, a plain structured-cloneable object, applied in the frames of components that use the kit. Update it when it changes. */
77
+ ui?: {
78
+ config?: object;
79
+ };
65
80
  }
66
81
  /** Short-lived platform token. `expires` is in epoch seconds. */
67
82
  export interface ComponentToken {
@@ -1,4 +1,4 @@
1
- export type { ComponentConfig, ComponentInput, ComponentModule, ComponentProps, ComponentTarget, ComponentTheme, ComponentToken, PaymentContext, PaymentMethodInfo, PaymentRedirectData, PaymentSubmitData, PaymentSubmitResult } from './components-types.cjs';
1
+ export type { ComponentConfig, ComponentInput, ComponentModule, ComponentProps, ComponentTarget, ComponentTheme, ComponentToken, ComponentUi, PaymentContext, PaymentMethodInfo, PaymentRedirectData, PaymentSubmitData, PaymentSubmitResult } from './components-types.cjs';
2
2
  export { createComponents } from './components-client.cjs';
3
3
  export type { Components, ComponentsOptions, MountOptions, NamedMountOptions, PlaceComponent, TargetMountOptions, TargetHandle } from './components-client.cjs';
4
4
  export type { ComponentHandle } from './components-host.cjs';
@@ -1,4 +1,4 @@
1
- export type { ComponentConfig, ComponentInput, ComponentModule, ComponentProps, ComponentTarget, ComponentTheme, ComponentToken, PaymentContext, PaymentMethodInfo, PaymentRedirectData, PaymentSubmitData, PaymentSubmitResult } from './components-types.js';
1
+ export type { ComponentConfig, ComponentInput, ComponentModule, ComponentProps, ComponentTarget, ComponentTheme, ComponentToken, ComponentUi, PaymentContext, PaymentMethodInfo, PaymentRedirectData, PaymentSubmitData, PaymentSubmitResult } from './components-types.js';
2
2
  export { createComponents } from './components-client.js';
3
3
  export type { Components, ComponentsOptions, MountOptions, NamedMountOptions, PlaceComponent, TargetMountOptions, TargetHandle } from './components-client.js';
4
4
  export type { ComponentHandle } from './components-host.js';
@@ -1 +1 @@
1
- export declare const USER_AGENT = "swell-apps-sdk/2.0.0";
1
+ export declare const USER_AGENT = "swell-apps-sdk/2.1.0";
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const USER_AGENT = "swell-apps-sdk/2.0.0";
1
+ export declare const USER_AGENT = "swell-apps-sdk/2.1.0";
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // Replaced with the package version by the build.
2
- export const USER_AGENT = 'swell-apps-sdk/2.0.0';
2
+ export const USER_AGENT = 'swell-apps-sdk/2.1.0';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@swell/apps-sdk",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
4
  "description": "Server SDK for Swell apps.",
5
5
  "type": "module",
6
6
  "license": "MIT",