@swell/apps-sdk 2.0.0-alpha.6 → 2.0.0-alpha.7

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
@@ -138,8 +138,39 @@ export default function ColorPicker({ value, setValue, readonly }: ComponentProp
138
138
  | `locale`, `readonly` | Display locale and read-only state |
139
139
  | `setValidity(error)` | Report a validation error, or `null` when valid |
140
140
  | `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` |
141
+ | `call(name, data)` | Calls a host action and resolves with its result; payment components get `createIntent` and `getIntent` |
141
142
  | `on(event, handler)` | Handle a host event. Only the first handler registered for an event runs; its return value, or the error it throws, answers the host's `emit` |
142
143
 
144
+ ### Payment components
145
+
146
+ A component becomes the UI of a payment method by declaring the extension it implements in `config`:
147
+
148
+ ```tsx
149
+ import { useEffect } from 'preact/hooks';
150
+ import type { ComponentProps, PaymentContext, PaymentSubmitResult } from '@swell/apps-sdk/components';
151
+
152
+ export const config = {
153
+ extension: { id: 'card' },
154
+ targets: [{ id: 'checkout.payment.methods' }],
155
+ };
156
+
157
+ export default function Card({ call, on, context }: ComponentProps<never, PaymentContext>) {
158
+ // Register in an effect: the frame runs only the first handler registered for an event, and `on` returns the unsubscribe
159
+ useEffect(() => on('submit', async (): Promise<PaymentSubmitResult> => {
160
+ const intent = await call<{ id: string }>('createIntent', { amount: context.cart.capture_total });
161
+ return { billing: { intent } };
162
+ }), [on, call, context]);
163
+ return <div>Card form</div>;
164
+ }
165
+ ```
166
+
167
+ - `extension: { id }` ties the component to an extension of the app's `swell.json`. An object is the new contract; a string is the legacy `swell.app` contract.
168
+ - `targets: [{ id: 'checkout.payment.methods' }]` opts the component into hosted checkout's payment methods place.
169
+ - `PaymentContext` is the `context`: the `cart` (with `account_id`, `currency`, `capture_total`) and the selected `method`. Pass your own cart type as its generic.
170
+ - `submit` (data `PaymentSubmitData`) and `redirect` (data `PaymentRedirectData`, after a redirect back to checkout) handlers return `{ billing }` (`PaymentSubmitResult`), which is merged into the cart's billing.
171
+ - `call('createIntent' | 'getIntent', data)` creates or reads a payment intent through the Swell vault; the account comes from `context.cart.account_id`. The cart in `context` comes from the host page, so when the amount matters, compute or verify it on the server in `create_intent`.
172
+ - Render visible content before opening a modal, so the customer sees the component in the payment methods list.
173
+
143
174
  ### Rendering components
144
175
 
145
176
  Hosts render installed apps' components with `createComponents`:
@@ -175,6 +206,8 @@ badge.unmount();
175
206
  | `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 |
176
207
  | `unmount()` | Removes the frame. Before the component list loads, it cancels the mount; `ready` and pending `emit` calls reject |
177
208
 
209
+ 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.
210
+
178
211
  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.
179
212
 
180
213
  Hosts that have their own session, like the Swell admin, pass `getToken: (app) => Promise<{ token, expires }>`. The token is refreshed a minute before it expires; if a refresh fails, the component keeps the current token and the host retries. Without `getToken` the frame gets no token, and `props.fetch` sends requests without a token header.
@@ -185,6 +218,26 @@ When a component opens a modal (a payment SDK's 3D Secure challenge, a QR code),
185
218
 
186
219
  Component frames load from the app installation's origin, a subdomain of `swell.store`. If the host page has a Content Security Policy, allow these origins in `frame-src`, for example `frame-src https://*.swell.store`.
187
220
 
221
+ #### Rendering a place
222
+
223
+ Hosts that render the components of a place, such as hosted checkout, mount the place instead of one component:
224
+
225
+ ```ts
226
+ const methods = components.mount('#payment', {
227
+ target: 'checkout.payment.methods',
228
+ select: (c) => c.app === method.extension_app_id && c.extension?.id === method.id,
229
+ context: { cart },
230
+ });
231
+ methods.on('validity', (error) => { /* … */ });
232
+ const results = await methods.emit('submit', { billing });
233
+ ```
234
+
235
+ 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.
236
+
237
+ 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.
238
+
239
+ Hosts cannot override the built-in payment actions: `createIntent` and `getIntent` win over `actions` of the same names.
240
+
188
241
  ## API reference
189
242
 
190
243
  ### Backend client
@@ -1,4 +1,4 @@
1
- import type { ComponentInput, ComponentToken } from './components-types.cjs';
1
+ import type { ComponentInput, ComponentTarget, ComponentToken } from './components-types.cjs';
2
2
  import type { ComponentHandle } from './components-host.cjs';
3
3
  export interface ComponentsOptions {
4
4
  storeId: string;
@@ -10,22 +10,76 @@ export interface ComponentsOptions {
10
10
  * Without it the frame gets no token, and `props.fetch` sends no token header.
11
11
  */
12
12
  getToken?: (app: string) => Promise<ComponentToken>;
13
+ /** Vault origin for payment intents. Defaults to https://vault.schema.io */
14
+ vaultUrl?: string;
13
15
  }
14
- export interface MountOptions<TValue = unknown, TContext = Record<string, unknown>> extends ComponentInput<TValue, TContext> {
16
+ type HostActions = Record<string, (data: unknown) => unknown>;
17
+ export interface NamedMountOptions<TValue = unknown, TContext = Record<string, unknown>> extends ComponentInput<TValue, TContext> {
15
18
  /** App id or slug. */
16
19
  app: string;
17
20
  /** Component name: the file name in the app's components/ folder. */
18
21
  component: string;
19
22
  /** Accessible title of the frame. Defaults to the component name. */
20
23
  title?: string;
24
+ /** Host actions the component can call. Built-in actions of payment components win over the same names. */
25
+ actions?: HostActions;
26
+ }
27
+ /** A component the platform returned for a place, as `select` sees it. */
28
+ export interface PlaceComponent {
29
+ /** Component name: the file name in the app's components/ folder. */
30
+ readonly name: string;
31
+ /** Id of the app the component belongs to. */
32
+ readonly app: string;
33
+ /** Host places the component opts into. */
34
+ readonly targets: readonly {
35
+ readonly id: string;
36
+ }[];
37
+ /** The extension of the app's swell.json the component is the UI of. */
38
+ readonly extension?: {
39
+ readonly id: string;
40
+ readonly type?: string;
41
+ };
42
+ }
43
+ export interface TargetMountOptions<TContext = Record<string, unknown>> extends ComponentInput<never, TContext> {
44
+ /** The host place whose components the platform returns. */
45
+ target: ComponentTarget;
46
+ /**
47
+ * Picks the components to mount, e.g. the one of the chosen payment method. Called once per component
48
+ * the platform returns, before any frame is created; without it every component mounts. Fixed at mount.
49
+ */
50
+ select?: (component: PlaceComponent) => boolean;
51
+ /** Accessible title of the frames. Defaults to each component's name. */
52
+ title?: string;
53
+ /** Host actions the components can call. Built-in actions of payment components win over the same names. */
54
+ actions?: HostActions;
55
+ }
56
+ /** Options of mounting one component by name. Mounting by place takes `TargetMountOptions`. */
57
+ export type MountOptions<TValue = unknown, TContext = Record<string, unknown>> = NamedMountOptions<TValue, TContext>;
58
+ export interface TargetHandle {
59
+ readonly ready: Promise<void>;
60
+ /** What the place rendered, known once `ready` settles; empty when nothing matched. */
61
+ readonly components: readonly {
62
+ app: string;
63
+ name: string;
64
+ }[];
65
+ on(event: 'validity', handler: (error: string | null) => void): () => void;
66
+ on(event: 'error', handler: (error: Error) => void): () => void;
67
+ update(input: ComponentInput<never>): void;
68
+ /** Sends an event to every component of the place; resolves with their results in order. */
69
+ emit<T = unknown>(event: string, data?: unknown): Promise<T[]>;
70
+ focus(): void;
71
+ unmount(): void;
21
72
  }
22
73
  export interface Components {
23
74
  /**
24
75
  * Renders a component in `target` and returns its handle right away. The app's component list
25
76
  * loads in the background: `update` calls made meanwhile are kept, `unmount` cancels, and a failure
26
77
  * fires `error` and rejects `handle.ready`. Throws when `target` does not exist.
78
+ * With `target` in the options it renders the components the platform returns for that place, those `select` accepts.
27
79
  */
28
- mount<TValue = unknown, TContext = Record<string, unknown>>(target: string | HTMLElement, options: MountOptions<TValue, TContext>): ComponentHandle<TValue>;
80
+ mount<TValue = unknown, TContext = Record<string, unknown>>(target: string | HTMLElement, options: NamedMountOptions<TValue, TContext>): ComponentHandle<TValue>;
81
+ mount<TContext = Record<string, unknown>>(target: string | HTMLElement, options: TargetMountOptions<TContext>): TargetHandle;
29
82
  }
30
83
  /** Renders installed apps' components. Create one instance per store. */
31
84
  export declare function createComponents(options: ComponentsOptions): Components;
85
+ export {};
@@ -1,4 +1,4 @@
1
- import type { ComponentInput, ComponentToken } from './components-types.js';
1
+ import type { ComponentInput, ComponentTarget, ComponentToken } from './components-types.js';
2
2
  import type { ComponentHandle } from './components-host.js';
3
3
  export interface ComponentsOptions {
4
4
  storeId: string;
@@ -10,22 +10,76 @@ export interface ComponentsOptions {
10
10
  * Without it the frame gets no token, and `props.fetch` sends no token header.
11
11
  */
12
12
  getToken?: (app: string) => Promise<ComponentToken>;
13
+ /** Vault origin for payment intents. Defaults to https://vault.schema.io */
14
+ vaultUrl?: string;
13
15
  }
14
- export interface MountOptions<TValue = unknown, TContext = Record<string, unknown>> extends ComponentInput<TValue, TContext> {
16
+ type HostActions = Record<string, (data: unknown) => unknown>;
17
+ export interface NamedMountOptions<TValue = unknown, TContext = Record<string, unknown>> extends ComponentInput<TValue, TContext> {
15
18
  /** App id or slug. */
16
19
  app: string;
17
20
  /** Component name: the file name in the app's components/ folder. */
18
21
  component: string;
19
22
  /** Accessible title of the frame. Defaults to the component name. */
20
23
  title?: string;
24
+ /** Host actions the component can call. Built-in actions of payment components win over the same names. */
25
+ actions?: HostActions;
26
+ }
27
+ /** A component the platform returned for a place, as `select` sees it. */
28
+ export interface PlaceComponent {
29
+ /** Component name: the file name in the app's components/ folder. */
30
+ readonly name: string;
31
+ /** Id of the app the component belongs to. */
32
+ readonly app: string;
33
+ /** Host places the component opts into. */
34
+ readonly targets: readonly {
35
+ readonly id: string;
36
+ }[];
37
+ /** The extension of the app's swell.json the component is the UI of. */
38
+ readonly extension?: {
39
+ readonly id: string;
40
+ readonly type?: string;
41
+ };
42
+ }
43
+ export interface TargetMountOptions<TContext = Record<string, unknown>> extends ComponentInput<never, TContext> {
44
+ /** The host place whose components the platform returns. */
45
+ target: ComponentTarget;
46
+ /**
47
+ * Picks the components to mount, e.g. the one of the chosen payment method. Called once per component
48
+ * the platform returns, before any frame is created; without it every component mounts. Fixed at mount.
49
+ */
50
+ select?: (component: PlaceComponent) => boolean;
51
+ /** Accessible title of the frames. Defaults to each component's name. */
52
+ title?: string;
53
+ /** Host actions the components can call. Built-in actions of payment components win over the same names. */
54
+ actions?: HostActions;
55
+ }
56
+ /** Options of mounting one component by name. Mounting by place takes `TargetMountOptions`. */
57
+ export type MountOptions<TValue = unknown, TContext = Record<string, unknown>> = NamedMountOptions<TValue, TContext>;
58
+ export interface TargetHandle {
59
+ readonly ready: Promise<void>;
60
+ /** What the place rendered, known once `ready` settles; empty when nothing matched. */
61
+ readonly components: readonly {
62
+ app: string;
63
+ name: string;
64
+ }[];
65
+ on(event: 'validity', handler: (error: string | null) => void): () => void;
66
+ on(event: 'error', handler: (error: Error) => void): () => void;
67
+ update(input: ComponentInput<never>): void;
68
+ /** Sends an event to every component of the place; resolves with their results in order. */
69
+ emit<T = unknown>(event: string, data?: unknown): Promise<T[]>;
70
+ focus(): void;
71
+ unmount(): void;
21
72
  }
22
73
  export interface Components {
23
74
  /**
24
75
  * Renders a component in `target` and returns its handle right away. The app's component list
25
76
  * loads in the background: `update` calls made meanwhile are kept, `unmount` cancels, and a failure
26
77
  * fires `error` and rejects `handle.ready`. Throws when `target` does not exist.
78
+ * With `target` in the options it renders the components the platform returns for that place, those `select` accepts.
27
79
  */
28
- mount<TValue = unknown, TContext = Record<string, unknown>>(target: string | HTMLElement, options: MountOptions<TValue, TContext>): ComponentHandle<TValue>;
80
+ mount<TValue = unknown, TContext = Record<string, unknown>>(target: string | HTMLElement, options: NamedMountOptions<TValue, TContext>): ComponentHandle<TValue>;
81
+ mount<TContext = Record<string, unknown>>(target: string | HTMLElement, options: TargetMountOptions<TContext>): TargetHandle;
29
82
  }
30
83
  /** Renders installed apps' components. Create one instance per store. */
31
84
  export declare function createComponents(options: ComponentsOptions): Components;
85
+ export {};
@@ -1,4 +1,6 @@
1
1
  import { createListeners, deferred, embedComponent, pickInput, toError } from './components-host.js';
2
+ import { paymentActions } from './components-payment.js';
3
+ const DEFAULT_VAULT_URL = 'https://vault.schema.io';
2
4
  /** Renders installed apps' components. Create one instance per store. */
3
5
  export function createComponents(options) {
4
6
  if (!options?.storeId || !options.publicKey)
@@ -20,66 +22,175 @@ export function createComponents(options) {
20
22
  }
21
23
  return request;
22
24
  };
23
- return {
24
- mount(target, mountOptions) {
25
- const placeholder = typeof target === 'string' ? globalThis.document?.querySelector(target) : target;
26
- if (!placeholder)
27
- throw new Error(`Component container "${String(target)}" not found`);
28
- const { app, component, title, ...input } = mountOptions;
29
- const { getToken } = options;
30
- const { on, notify } = createListeners();
31
- const { promise: ready, resolve: markReady, reject: failReady } = deferred();
32
- // Settles once the frame is embedded, so `emit` still works when the frame starts after `ready` failed
33
- const { promise: embedded, resolve: markEmbedded, reject: failEmbedded } = deferred();
34
- let inner = null;
35
- let unmounted = false;
36
- load(app).then(({ settings, components = [] }) => {
25
+ // Embeds one component: payment components also get the intent actions, read with the latest cart
26
+ const embed = (placeholder, meta, app, input, title, actions) => {
27
+ const current = { context: input.context };
28
+ const payment = meta.extension?.type === 'payment' && meta.gateway
29
+ ? paymentActions({
30
+ vaultUrl: options.vaultUrl ?? DEFAULT_VAULT_URL,
31
+ publicKey: options.publicKey,
32
+ gateway: meta.gateway,
33
+ accountId: () => current.context?.cart?.account_id,
34
+ })
35
+ : {};
36
+ const handle = embedComponent(placeholder, {
37
+ ...input, src: meta.src, settings: meta.settings, title,
38
+ actions: { ...actions, ...payment },
39
+ getToken: options.getToken && (() => options.getToken(app)),
40
+ });
41
+ return {
42
+ ...handle,
43
+ update(next) {
44
+ if ('context' in next)
45
+ current.context = next.context;
46
+ handle.update(next);
47
+ },
48
+ };
49
+ };
50
+ const loadPlace = async (target) => {
51
+ const query = new URLSearchParams({ target });
52
+ const response = await fetch(`${base}/api/apps/components?${query}`, {
53
+ headers: { Authorization: `Basic ${btoa(options.publicKey)}` },
54
+ });
55
+ if (!response.ok)
56
+ throw new Error(`Cannot load components of place "${target}" (${response.status})`);
57
+ const { components = [] } = (await response.json());
58
+ return components;
59
+ };
60
+ function mountNamed(placeholder, mountOptions) {
61
+ const { app, component, title, actions, ...input } = mountOptions;
62
+ const { on, notify } = createListeners();
63
+ const { promise: ready, resolve: markReady, reject: failReady } = deferred();
64
+ // Settles once the frame is embedded, so `emit` still works when the frame starts after `ready` failed
65
+ const { promise: embedded, resolve: markEmbedded, reject: failEmbedded } = deferred();
66
+ let inner = null;
67
+ let unmounted = false;
68
+ load(app).then(({ settings, components = [] }) => {
69
+ if (unmounted)
70
+ return;
71
+ const found = components.find(item => item.name === component);
72
+ if (!found)
73
+ throw new Error(`Component "${component}" not found in app "${app}"`);
74
+ // `input` carries the updates made while the metadata loaded
75
+ inner = embed(placeholder, { ...found, settings: found.settings ?? settings }, app, input, title ?? component, actions);
76
+ inner.on('change', value => notify('change', value));
77
+ inner.on('validity', error => notify('validity', error));
78
+ inner.on('error', error => notify('error', error));
79
+ markEmbedded();
80
+ inner.ready.then(markReady, failReady);
81
+ }).catch((error) => {
82
+ if (unmounted)
83
+ return;
84
+ const reported = toError(error);
85
+ failReady(reported);
86
+ failEmbedded(reported);
87
+ notify('error', reported);
88
+ });
89
+ return {
90
+ ready,
91
+ on,
92
+ update(next) {
93
+ if (inner)
94
+ inner.update(next);
95
+ else
96
+ Object.assign(input, pickInput(next));
97
+ },
98
+ async emit(name, data) {
99
+ await embedded;
100
+ return inner.emit(name, data);
101
+ },
102
+ // Before the component list loads there is no frame to focus yet
103
+ focus() {
104
+ inner?.focus();
105
+ },
106
+ unmount() {
37
107
  if (unmounted)
38
108
  return;
39
- const found = components.find(item => item.name === component);
40
- if (!found)
41
- throw new Error(`Component "${component}" not found in app "${app}"`);
42
- // `input` carries the updates made while the metadata loaded
43
- inner = embedComponent(placeholder, { ...input, src: found.src, settings, title: title ?? component, getToken: getToken && (() => getToken(app)) });
44
- inner.on('change', value => notify('change', value));
45
- inner.on('validity', error => notify('validity', error));
46
- inner.on('error', error => notify('error', error));
47
- markEmbedded();
48
- inner.ready.then(markReady, failReady);
49
- }).catch((error) => {
109
+ unmounted = true;
110
+ inner?.unmount();
111
+ failReady(new Error('Component unmounted'));
112
+ failEmbedded(new Error('Component unmounted'));
113
+ },
114
+ };
115
+ }
116
+ function mountTarget(placeholder, mountOptions) {
117
+ const { target, select, title, actions, ...input } = mountOptions;
118
+ const { on, notify } = createListeners();
119
+ const { promise: ready, resolve: markReady, reject: failReady } = deferred();
120
+ let handles = [];
121
+ let slots = [];
122
+ let rendered = [];
123
+ let unmounted = false;
124
+ const loaded = loadPlace(target).then((returned) => {
125
+ if (unmounted)
126
+ return;
127
+ // The host sees the metadata without the app settings; a throwing `select` fails the place before any frame
128
+ const components = select
129
+ ? returned.filter(({ settings, ...component }) => select(component))
130
+ : returned;
131
+ try {
132
+ for (const meta of components) {
133
+ const slot = placeholder.ownerDocument.createElement('div');
134
+ placeholder.appendChild(slot);
135
+ slots.push(slot);
136
+ const handle = embed(slot, meta, meta.app ?? '', input, title ?? meta.name, actions);
137
+ handle.on('validity', error => notify('validity', error));
138
+ handle.on('error', error => notify('error', error));
139
+ handles.push(handle);
140
+ }
141
+ }
142
+ catch (error) {
143
+ // A component that cannot embed must not leave the earlier frames running
144
+ handles.forEach(handle => handle.unmount());
145
+ slots.forEach(slot => slot.remove());
146
+ handles = [];
147
+ slots = [];
148
+ throw error;
149
+ }
150
+ rendered = components.map(meta => ({ app: meta.app ?? '', name: meta.name }));
151
+ Promise.all(handles.map(handle => handle.ready)).then(() => markReady(), failReady);
152
+ });
153
+ loaded.catch((error) => {
154
+ if (unmounted)
155
+ return;
156
+ const reported = toError(error);
157
+ failReady(reported);
158
+ notify('error', reported);
159
+ });
160
+ return {
161
+ ready,
162
+ get components() { return rendered; },
163
+ on,
164
+ update(next) {
165
+ if (handles.length)
166
+ handles.forEach(handle => handle.update(next));
167
+ else
168
+ Object.assign(input, pickInput(next));
169
+ },
170
+ async emit(name, data) {
171
+ await loaded;
172
+ if (unmounted)
173
+ throw new Error('Component unmounted');
174
+ return Promise.all(handles.map(handle => handle.emit(name, data)));
175
+ },
176
+ focus() {
177
+ handles[0]?.focus();
178
+ },
179
+ unmount() {
50
180
  if (unmounted)
51
181
  return;
52
- const reported = toError(error);
53
- failReady(reported);
54
- failEmbedded(reported);
55
- notify('error', reported);
56
- });
57
- return {
58
- ready,
59
- on,
60
- update(next) {
61
- if (inner)
62
- inner.update(next);
63
- else
64
- Object.assign(input, pickInput(next));
65
- },
66
- async emit(name, data) {
67
- await embedded;
68
- return inner.emit(name, data);
69
- },
70
- // Before the component list loads there is no frame to focus yet
71
- focus() {
72
- inner?.focus();
73
- },
74
- unmount() {
75
- if (unmounted)
76
- return;
77
- unmounted = true;
78
- inner?.unmount();
79
- failReady(new Error('Component unmounted'));
80
- failEmbedded(new Error('Component unmounted'));
81
- },
82
- };
83
- },
84
- };
182
+ unmounted = true;
183
+ handles.forEach(handle => handle.unmount());
184
+ slots.forEach(slot => slot.remove());
185
+ failReady(new Error('Component unmounted'));
186
+ },
187
+ };
188
+ }
189
+ function mount(target, mountOptions) {
190
+ const placeholder = typeof target === 'string' ? globalThis.document?.querySelector(target) : target;
191
+ if (!placeholder)
192
+ throw new Error(`Component container "${String(target)}" not found`);
193
+ return 'target' in mountOptions ? mountTarget(placeholder, mountOptions) : mountNamed(placeholder, mountOptions);
194
+ }
195
+ return { mount };
85
196
  }
@@ -56,6 +56,10 @@ export function startComponentFrame(options = {}) {
56
56
  // The viewport-covering element while overlay is on
57
57
  let blocker = null;
58
58
  const handlers = new Map();
59
+ // Host actions announced in init, and calls waiting for their reply
60
+ let actions = [];
61
+ let calls = 0;
62
+ const replies = new Map();
59
63
  const post = (message) => parent.postMessage(wrap(channel, message), parentOrigin);
60
64
  const fail = (error) => post({ type: 'error', message: errorMessage(error) });
61
65
  // The token only goes to the app origin (functions, /app-api), never to third parties.
@@ -86,6 +90,15 @@ export function startComponentFrame(options = {}) {
86
90
  handlers.set(event, (handlers.get(event) ?? []).filter(item => item !== handler));
87
91
  };
88
92
  },
93
+ call(name, data) {
94
+ if (!actions.includes(name))
95
+ return Promise.reject(new Error(`Unknown host action "${name}"`));
96
+ const call = ++calls;
97
+ return new Promise((resolve, reject) => {
98
+ replies.set(call, { resolve: resolve, reject });
99
+ post({ type: 'call', call, name, data });
100
+ });
101
+ },
89
102
  };
90
103
  const componentProps = () => ({ ...props, ...callbacks });
91
104
  const reportHeight = () => {
@@ -174,6 +187,7 @@ export function startComponentFrame(options = {}) {
174
187
  async function handle(message) {
175
188
  switch (message.type) {
176
189
  case 'init':
190
+ actions = Array.isArray(message.actions) ? message.actions.filter(name => typeof name === 'string') : [];
177
191
  props = message.props;
178
192
  token = message.token;
179
193
  if (!mounting) {
@@ -183,6 +197,17 @@ export function startComponentFrame(options = {}) {
183
197
  await mounting;
184
198
  await module?.update(target, componentProps());
185
199
  return;
200
+ case 'reply': {
201
+ const pending = replies.get(message.call);
202
+ if (!pending)
203
+ return;
204
+ replies.delete(message.call);
205
+ if (typeof message.error === 'string')
206
+ pending.reject(new Error(message.error));
207
+ else
208
+ pending.resolve(message.result);
209
+ return;
210
+ }
186
211
  case 'update':
187
212
  if (!props)
188
213
  return;
@@ -36,6 +36,8 @@ export interface EmbedOptions<TValue = unknown, TContext = Record<string, unknow
36
36
  settings?: Record<string, unknown>;
37
37
  title?: string;
38
38
  getToken?: () => Promise<ComponentToken>;
39
+ /** Actions the component can call with `props.call`. Results must be structured-cloneable. */
40
+ actions?: Record<string, (data: unknown) => unknown>;
39
41
  }
40
42
  type Listener = (value: never) => void;
41
43
  type HandleEvent = 'change' | 'validity' | 'error';
@@ -36,6 +36,8 @@ export interface EmbedOptions<TValue = unknown, TContext = Record<string, unknow
36
36
  settings?: Record<string, unknown>;
37
37
  title?: string;
38
38
  getToken?: () => Promise<ComponentToken>;
39
+ /** Actions the component can call with `props.call`. Results must be structured-cloneable. */
40
+ actions?: Record<string, (data: unknown) => unknown>;
39
41
  }
40
42
  type Listener = (value: never) => void;
41
43
  type HandleEvent = 'change' | 'validity' | 'error';
@@ -196,7 +196,7 @@ export function embedComponent(placeholder, options) {
196
196
  await tokenLoaded;
197
197
  started = true;
198
198
  try {
199
- post({ type: 'init', props, token });
199
+ post({ type: 'init', props, token, actions: Object.keys(options.actions ?? {}) });
200
200
  }
201
201
  catch (error) {
202
202
  const reported = toError(error);
@@ -239,6 +239,27 @@ export function embedComponent(placeholder, options) {
239
239
  call.resolve(message.result);
240
240
  return;
241
241
  }
242
+ case 'call': {
243
+ const { actions } = options;
244
+ const action = actions && Object.hasOwn(actions, message.name) ? actions[message.name] : undefined;
245
+ let reply;
246
+ try {
247
+ if (!action)
248
+ throw new Error(`Unknown host action "${message.name}"`);
249
+ reply = { type: 'reply', call: message.call, result: await action(message.data) };
250
+ }
251
+ catch (error) {
252
+ reply = { type: 'reply', call: message.call, error: toError(error).message };
253
+ }
254
+ try {
255
+ post(reply);
256
+ }
257
+ catch (error) {
258
+ // The result cannot be cloned: the component still gets an answer
259
+ send({ type: 'reply', call: message.call, error: toError(error).message });
260
+ }
261
+ return;
262
+ }
242
263
  case 'error': {
243
264
  const error = new Error(String(message.message));
244
265
  if (!rendered)
@@ -0,0 +1,11 @@
1
+ export interface PaymentActionsOptions {
2
+ vaultUrl: string;
3
+ publicKey: string;
4
+ gateway: string;
5
+ /** The current cart's account, read at call time */
6
+ accountId: () => string | undefined;
7
+ }
8
+ export declare function paymentActions(options: PaymentActionsOptions): {
9
+ createIntent: (data: unknown) => Promise<unknown>;
10
+ getIntent: (data: unknown) => Promise<unknown>;
11
+ };
@@ -0,0 +1,11 @@
1
+ export interface PaymentActionsOptions {
2
+ vaultUrl: string;
3
+ publicKey: string;
4
+ gateway: string;
5
+ /** The current cart's account, read at call time */
6
+ accountId: () => string | undefined;
7
+ }
8
+ export declare function paymentActions(options: PaymentActionsOptions): {
9
+ createIntent: (data: unknown) => Promise<unknown>;
10
+ getIntent: (data: unknown) => Promise<unknown>;
11
+ };
@@ -0,0 +1,52 @@
1
+ // Payment intents of payment components, through the vault exactly as swell-js sends them
2
+ const TIMEOUT_MS = 20_000;
3
+ function serialize(key, value, out) {
4
+ if (Array.isArray(value)) {
5
+ value.forEach((item, index) => serialize(`${key}[${item !== null && typeof item === 'object' ? index : ''}]`, item, out));
6
+ }
7
+ else if (value !== null && typeof value === 'object') {
8
+ for (const [name, item] of Object.entries(value))
9
+ serialize(`${key}[${name}]`, item, out);
10
+ }
11
+ else if (value !== undefined) {
12
+ out.push(`${encodeURIComponent(key)}=${encodeURIComponent(value === null ? '' : String(value))}`);
13
+ }
14
+ }
15
+ async function vaultRequest(options, method, intent) {
16
+ const accountId = options.accountId();
17
+ const data = { gateway: options.gateway, ...(accountId ? { account_id: accountId } : {}), intent };
18
+ const query = [];
19
+ serialize('$jsonp', { method, callback: 'none' }, query);
20
+ serialize('$data', data, query);
21
+ serialize('$key', options.publicKey, query);
22
+ // AbortSignal.timeout is missing in Safari before 16
23
+ const controller = new AbortController();
24
+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
25
+ let result;
26
+ try {
27
+ const response = await fetch(`${options.vaultUrl.replace(/\/+$/, '')}/intent?${query.join('&')}`, { signal: controller.signal });
28
+ result = (await response.json());
29
+ }
30
+ catch (error) {
31
+ if (error?.name === 'AbortError')
32
+ throw new Error('Request timed out after 20 seconds');
33
+ throw error;
34
+ }
35
+ finally {
36
+ clearTimeout(timer);
37
+ }
38
+ if (result?.$error)
39
+ throw new Error(result.$error);
40
+ if (!result || (result.$status ?? 0) >= 300)
41
+ throw new Error('A connection error occurred while making the request');
42
+ const errors = result.$data?.errors;
43
+ if (errors)
44
+ throw new Error(Object.values(errors)[0]?.message || 'Unknown error');
45
+ return result.$data;
46
+ }
47
+ export function paymentActions(options) {
48
+ return {
49
+ createIntent: (data) => vaultRequest(options, 'post', data),
50
+ getIntent: (data) => vaultRequest(options, 'get', data),
51
+ };
52
+ }
@@ -25,6 +25,7 @@ export type HostMessage = {
25
25
  type: 'init';
26
26
  props: WireProps;
27
27
  token: string | null;
28
+ actions?: string[];
28
29
  } | {
29
30
  type: 'update';
30
31
  props: Partial<WireProps>;
@@ -36,6 +37,11 @@ export type HostMessage = {
36
37
  call: number;
37
38
  name: string;
38
39
  data: unknown;
40
+ } | {
41
+ type: 'reply';
42
+ call: number;
43
+ result?: unknown;
44
+ error?: string;
39
45
  } | {
40
46
  type: 'rect';
41
47
  rect: Rect;
@@ -63,6 +69,11 @@ export type FrameMessage = {
63
69
  call: number;
64
70
  result?: unknown;
65
71
  error?: string;
72
+ } | {
73
+ type: 'call';
74
+ call: number;
75
+ name: string;
76
+ data: unknown;
66
77
  } | {
67
78
  type: 'error';
68
79
  message: string;
@@ -25,6 +25,7 @@ export type HostMessage = {
25
25
  type: 'init';
26
26
  props: WireProps;
27
27
  token: string | null;
28
+ actions?: string[];
28
29
  } | {
29
30
  type: 'update';
30
31
  props: Partial<WireProps>;
@@ -36,6 +37,11 @@ export type HostMessage = {
36
37
  call: number;
37
38
  name: string;
38
39
  data: unknown;
40
+ } | {
41
+ type: 'reply';
42
+ call: number;
43
+ result?: unknown;
44
+ error?: string;
39
45
  } | {
40
46
  type: 'rect';
41
47
  rect: Rect;
@@ -63,6 +69,11 @@ export type FrameMessage = {
63
69
  call: number;
64
70
  result?: unknown;
65
71
  error?: string;
72
+ } | {
73
+ type: 'call';
74
+ call: number;
75
+ name: string;
76
+ data: unknown;
66
77
  } | {
67
78
  type: 'error';
68
79
  message: string;
@@ -19,10 +19,23 @@ export interface ComponentProps<TValue = unknown, TContext = Record<string, unkn
19
19
  * (or thrown error) answers the host's `emit`; later handlers for the same event are not called.
20
20
  */
21
21
  on(event: string, handler: (data: unknown) => unknown): () => void;
22
+ /**
23
+ * Calls an action the host offers, such as `createIntent` for payment components, and resolves
24
+ * with its result. Rejects with the host's error, or with `Unknown host action "<name>"`.
25
+ */
26
+ call<T = unknown>(name: string, data?: unknown): Promise<T>;
22
27
  }
23
28
  /** Optional static metadata a component file exports as `config`. */
24
29
  export interface ComponentConfig {
25
30
  readonly description?: string;
31
+ /** Makes the component the UI of an extension of the app's swell.json. A string is the legacy swell.app contract. */
32
+ readonly extension?: {
33
+ readonly id: string;
34
+ };
35
+ /** Host places the component opts into. */
36
+ readonly targets?: readonly {
37
+ readonly id: ComponentTarget;
38
+ }[];
26
39
  }
27
40
  /** Module the CLI builds for each component. */
28
41
  export interface ComponentModule {
@@ -44,3 +57,28 @@ export interface ComponentToken {
44
57
  readonly token: string;
45
58
  readonly expires: number;
46
59
  }
60
+ /** A host place id. The SDK knows no list: the platform defines places and validates ids on push. */
61
+ export type ComponentTarget = string;
62
+ export interface PaymentMethodInfo {
63
+ readonly id: string;
64
+ readonly name?: string;
65
+ readonly mode?: string;
66
+ }
67
+ export interface PaymentContext<TCart extends object = Record<string, unknown>> {
68
+ readonly cart: TCart & {
69
+ readonly account_id?: string;
70
+ readonly currency?: string;
71
+ readonly capture_total?: number;
72
+ };
73
+ readonly method?: PaymentMethodInfo;
74
+ }
75
+ export interface PaymentSubmitData {
76
+ readonly billing: Record<string, unknown>;
77
+ }
78
+ export interface PaymentRedirectData {
79
+ readonly params: Record<string, string>;
80
+ }
81
+ /** What a payment component's `submit` and `redirect` handlers return: merged into the cart's billing. */
82
+ export interface PaymentSubmitResult {
83
+ readonly billing: Record<string, unknown>;
84
+ }
@@ -19,10 +19,23 @@ export interface ComponentProps<TValue = unknown, TContext = Record<string, unkn
19
19
  * (or thrown error) answers the host's `emit`; later handlers for the same event are not called.
20
20
  */
21
21
  on(event: string, handler: (data: unknown) => unknown): () => void;
22
+ /**
23
+ * Calls an action the host offers, such as `createIntent` for payment components, and resolves
24
+ * with its result. Rejects with the host's error, or with `Unknown host action "<name>"`.
25
+ */
26
+ call<T = unknown>(name: string, data?: unknown): Promise<T>;
22
27
  }
23
28
  /** Optional static metadata a component file exports as `config`. */
24
29
  export interface ComponentConfig {
25
30
  readonly description?: string;
31
+ /** Makes the component the UI of an extension of the app's swell.json. A string is the legacy swell.app contract. */
32
+ readonly extension?: {
33
+ readonly id: string;
34
+ };
35
+ /** Host places the component opts into. */
36
+ readonly targets?: readonly {
37
+ readonly id: ComponentTarget;
38
+ }[];
26
39
  }
27
40
  /** Module the CLI builds for each component. */
28
41
  export interface ComponentModule {
@@ -44,3 +57,28 @@ export interface ComponentToken {
44
57
  readonly token: string;
45
58
  readonly expires: number;
46
59
  }
60
+ /** A host place id. The SDK knows no list: the platform defines places and validates ids on push. */
61
+ export type ComponentTarget = string;
62
+ export interface PaymentMethodInfo {
63
+ readonly id: string;
64
+ readonly name?: string;
65
+ readonly mode?: string;
66
+ }
67
+ export interface PaymentContext<TCart extends object = Record<string, unknown>> {
68
+ readonly cart: TCart & {
69
+ readonly account_id?: string;
70
+ readonly currency?: string;
71
+ readonly capture_total?: number;
72
+ };
73
+ readonly method?: PaymentMethodInfo;
74
+ }
75
+ export interface PaymentSubmitData {
76
+ readonly billing: Record<string, unknown>;
77
+ }
78
+ export interface PaymentRedirectData {
79
+ readonly params: Record<string, string>;
80
+ }
81
+ /** What a payment component's `submit` and `redirect` handlers return: merged into the cart's billing. */
82
+ export interface PaymentSubmitResult {
83
+ readonly billing: Record<string, unknown>;
84
+ }
@@ -1,6 +1,6 @@
1
- export type { ComponentConfig, ComponentInput, ComponentModule, ComponentProps, ComponentToken } from './components-types.cjs';
1
+ export type { ComponentConfig, ComponentInput, ComponentModule, ComponentProps, ComponentTarget, ComponentToken, PaymentContext, PaymentMethodInfo, PaymentRedirectData, PaymentSubmitData, PaymentSubmitResult } from './components-types.cjs';
2
2
  export { createComponents } from './components-client.cjs';
3
- export type { Components, ComponentsOptions, MountOptions } from './components-client.cjs';
3
+ export type { Components, ComponentsOptions, MountOptions, NamedMountOptions, PlaceComponent, TargetMountOptions, TargetHandle } from './components-client.cjs';
4
4
  export type { ComponentHandle } from './components-host.cjs';
5
5
  export { startComponentFrame } from './components-frame.cjs';
6
6
  export type { FrameOptions } from './components-frame.cjs';
@@ -1,6 +1,6 @@
1
- export type { ComponentConfig, ComponentInput, ComponentModule, ComponentProps, ComponentToken } from './components-types.js';
1
+ export type { ComponentConfig, ComponentInput, ComponentModule, ComponentProps, ComponentTarget, ComponentToken, PaymentContext, PaymentMethodInfo, PaymentRedirectData, PaymentSubmitData, PaymentSubmitResult } from './components-types.js';
2
2
  export { createComponents } from './components-client.js';
3
- export type { Components, ComponentsOptions, MountOptions } from './components-client.js';
3
+ export type { Components, ComponentsOptions, MountOptions, NamedMountOptions, PlaceComponent, TargetMountOptions, TargetHandle } from './components-client.js';
4
4
  export type { ComponentHandle } from './components-host.js';
5
5
  export { startComponentFrame } from './components-frame.js';
6
6
  export type { FrameOptions } from './components-frame.js';
@@ -1 +1 @@
1
- export declare const USER_AGENT = "swell-apps-sdk/2.0.0-alpha.6";
1
+ export declare const USER_AGENT = "swell-apps-sdk/2.0.0-alpha.7";
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const USER_AGENT = "swell-apps-sdk/2.0.0-alpha.6";
1
+ export declare const USER_AGENT = "swell-apps-sdk/2.0.0-alpha.7";
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-alpha.6';
2
+ export const USER_AGENT = 'swell-apps-sdk/2.0.0-alpha.7';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@swell/apps-sdk",
3
- "version": "2.0.0-alpha.6",
3
+ "version": "2.0.0-alpha.7",
4
4
  "description": "Server SDK for Swell apps.",
5
5
  "type": "module",
6
6
  "license": "MIT",