@swell/apps-sdk 2.0.0-alpha.6 → 2.0.0-alpha.8
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 +87 -1
- package/dist/components-client.d.cts +57 -3
- package/dist/components-client.d.ts +57 -3
- package/dist/components-client.js +169 -58
- package/dist/components-frame.js +25 -0
- package/dist/components-host.d.cts +2 -0
- package/dist/components-host.d.ts +2 -0
- package/dist/components-host.js +22 -1
- package/dist/components-payment.d.cts +11 -0
- package/dist/components-payment.d.ts +11 -0
- package/dist/components-payment.js +52 -0
- package/dist/components-protocol.d.cts +11 -0
- package/dist/components-protocol.d.ts +11 -0
- package/dist/components-types.d.cts +38 -0
- package/dist/components-types.d.ts +38 -0
- package/dist/components.d.cts +2 -2
- package/dist/components.d.ts +2 -2
- package/dist/index.d.cts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/jwks.d.cts +1 -1
- package/dist/jwks.d.ts +1 -1
- package/dist/jwks.js +2 -2
- package/dist/version.d.cts +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/webhook.d.cts +29 -0
- package/dist/webhook.d.ts +29 -0
- package/dist/webhook.js +110 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -31,7 +31,7 @@ store user access. Use the same pattern for Swell-hosted and self-hosted fronten
|
|
|
31
31
|
import { verifySwellContext } from '@swell/apps-sdk';
|
|
32
32
|
|
|
33
33
|
const context = await verifySwellContext(request.headers, {
|
|
34
|
-
appId: '
|
|
34
|
+
appId: 'my_app', // The id in your app's swell.json.
|
|
35
35
|
});
|
|
36
36
|
```
|
|
37
37
|
|
|
@@ -111,6 +111,20 @@ const storeUser = requireStoreUser(context); // { userId, storeId }, or a 401 Sw
|
|
|
111
111
|
const optional = context.storeUser; // null for a visitor; no exception needed.
|
|
112
112
|
```
|
|
113
113
|
|
|
114
|
+
### Webhooks
|
|
115
|
+
|
|
116
|
+
Swell signs each webhook request it sends. Verify the request against the body it
|
|
117
|
+
arrived with before acting on its event:
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
import { verifySwellWebhook } from '@swell/apps-sdk';
|
|
121
|
+
|
|
122
|
+
const webhook = await verifySwellWebhook(request.headers, await request.text(), {
|
|
123
|
+
appId: 'my_app', // The id in your app's swell.json.
|
|
124
|
+
});
|
|
125
|
+
// webhook.event is the event the body carries.
|
|
126
|
+
```
|
|
127
|
+
|
|
114
128
|
## Components
|
|
115
129
|
|
|
116
130
|
App components are small UI bundles from an app's `components/` folder. Swell renders each one in an isolated iframe on the app installation's origin, so app code never runs in the host page. `@swell/apps-sdk/components` is browser code and is only bundled when you import it.
|
|
@@ -138,8 +152,39 @@ export default function ColorPicker({ value, setValue, readonly }: ComponentProp
|
|
|
138
152
|
| `locale`, `readonly` | Display locale and read-only state |
|
|
139
153
|
| `setValidity(error)` | Report a validation error, or `null` when valid |
|
|
140
154
|
| `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` |
|
|
155
|
+
| `call(name, data)` | Calls a host action and resolves with its result; payment components get `createIntent` and `getIntent` |
|
|
141
156
|
| `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
157
|
|
|
158
|
+
### Payment components
|
|
159
|
+
|
|
160
|
+
A component becomes the UI of a payment method by declaring the extension it implements in `config`:
|
|
161
|
+
|
|
162
|
+
```tsx
|
|
163
|
+
import { useEffect } from 'preact/hooks';
|
|
164
|
+
import type { ComponentProps, PaymentContext, PaymentSubmitResult } from '@swell/apps-sdk/components';
|
|
165
|
+
|
|
166
|
+
export const config = {
|
|
167
|
+
extension: { id: 'card' },
|
|
168
|
+
targets: [{ id: 'checkout.payment.methods' }],
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
export default function Card({ call, on, context }: ComponentProps<never, PaymentContext>) {
|
|
172
|
+
// Register in an effect: the frame runs only the first handler registered for an event, and `on` returns the unsubscribe
|
|
173
|
+
useEffect(() => on('submit', async (): Promise<PaymentSubmitResult> => {
|
|
174
|
+
const intent = await call<{ id: string }>('createIntent', { amount: context.cart.capture_total });
|
|
175
|
+
return { billing: { intent } };
|
|
176
|
+
}), [on, call, context]);
|
|
177
|
+
return <div>Card form</div>;
|
|
178
|
+
}
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
- `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.
|
|
182
|
+
- `targets: [{ id: 'checkout.payment.methods' }]` opts the component into hosted checkout's payment methods place.
|
|
183
|
+
- `PaymentContext` is the `context`: the `cart` (with `account_id`, `currency`, `capture_total`) and the selected `method`. Pass your own cart type as its generic.
|
|
184
|
+
- `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.
|
|
185
|
+
- `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`.
|
|
186
|
+
- Render visible content before opening a modal, so the customer sees the component in the payment methods list.
|
|
187
|
+
|
|
143
188
|
### Rendering components
|
|
144
189
|
|
|
145
190
|
Hosts render installed apps' components with `createComponents`:
|
|
@@ -175,6 +220,8 @@ badge.unmount();
|
|
|
175
220
|
| `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
221
|
| `unmount()` | Removes the frame. Before the component list loads, it cancels the mount; `ready` and pending `emit` calls reject |
|
|
177
222
|
|
|
223
|
+
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.
|
|
224
|
+
|
|
178
225
|
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
226
|
|
|
180
227
|
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 +232,26 @@ When a component opens a modal (a payment SDK's 3D Secure challenge, a QR code),
|
|
|
185
232
|
|
|
186
233
|
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
234
|
|
|
235
|
+
#### Rendering a place
|
|
236
|
+
|
|
237
|
+
Hosts that render the components of a place, such as hosted checkout, mount the place instead of one component:
|
|
238
|
+
|
|
239
|
+
```ts
|
|
240
|
+
const methods = components.mount('#payment', {
|
|
241
|
+
target: 'checkout.payment.methods',
|
|
242
|
+
select: (c) => c.app === method.extension_app_id && c.extension?.id === method.id,
|
|
243
|
+
context: { cart },
|
|
244
|
+
});
|
|
245
|
+
methods.on('validity', (error) => { /* … */ });
|
|
246
|
+
const results = await methods.emit('submit', { billing });
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
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.
|
|
250
|
+
|
|
251
|
+
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.
|
|
252
|
+
|
|
253
|
+
Hosts cannot override the built-in payment actions: `createIntent` and `getIntent` win over `actions` of the same names.
|
|
254
|
+
|
|
188
255
|
## API reference
|
|
189
256
|
|
|
190
257
|
### Backend client
|
|
@@ -275,6 +342,24 @@ For server integrations, construct `SwellBackendAPI` with explicit credentials a
|
|
|
275
342
|
`createStorefrontClient` with explicit public configuration. These clients do not
|
|
276
343
|
require an HTTP request or a store user.
|
|
277
344
|
|
|
345
|
+
### Webhook options
|
|
346
|
+
|
|
347
|
+
`verifySwellWebhook(headers, body, { env?, appId?, storeId? })` returns the webhook or
|
|
348
|
+
throws if verification fails. Pass `appId`, `storeId` or both from trusted configuration:
|
|
349
|
+
`appId` accepts only webhooks of apps with that id, and `storeId` only the webhooks of
|
|
350
|
+
that store. Without either it throws, since any Swell store can send a signed webhook to
|
|
351
|
+
any address. An app id is unique to its developer and store, so another developer's
|
|
352
|
+
private app can have yours: check `storeId` against the stores your app is installed in
|
|
353
|
+
before acting for one.
|
|
354
|
+
|
|
355
|
+
It reads the same configuration as the request context. `SWELL_VERIFY_HEADERS=false`
|
|
356
|
+
also turns off webhook verification, so while it is set anyone can send a webhook your
|
|
357
|
+
endpoint accepts.
|
|
358
|
+
|
|
359
|
+
Swell retries a delivery that fails, and a signature stays valid for five minutes, so
|
|
360
|
+
one event can arrive more than once. Skip an `eventId` you have already handled. Order
|
|
361
|
+
webhooks, which an order's checkout calls as it runs, carry no `eventId` or `webhookId`.
|
|
362
|
+
|
|
278
363
|
### Store users
|
|
279
364
|
|
|
280
365
|
`requireStoreUser(context)` returns `{ userId, storeId }` or throws `SwellError` with
|
|
@@ -298,6 +383,7 @@ error handling; `message` is for people and may change.
|
|
|
298
383
|
when the payload is null or absent, in `body`.
|
|
299
384
|
- Header verification uses 401 / `invalid_swell_context` for absent, malformed, expired
|
|
300
385
|
or rejected tokens, and 503 / `swell_jwks_unavailable` for key-service failures.
|
|
386
|
+
Webhook verification uses 401 / `invalid_swell_webhook` and the same 503.
|
|
301
387
|
- Backend/storefront network errors remain native. Local configuration errors may be
|
|
302
388
|
ordinary `Error` instances; not every failure is a `SwellError`.
|
|
303
389
|
|
|
@@ -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
|
-
|
|
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:
|
|
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
|
-
|
|
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:
|
|
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
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
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
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
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
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
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
|
}
|
package/dist/components-frame.js
CHANGED
|
@@ -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';
|
package/dist/components-host.js
CHANGED
|
@@ -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
|
+
}
|
package/dist/components.d.cts
CHANGED
|
@@ -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';
|
package/dist/components.d.ts
CHANGED
|
@@ -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';
|
package/dist/index.d.cts
CHANGED
|
@@ -3,6 +3,8 @@ export { getStorefrontConfig } from './context.cjs';
|
|
|
3
3
|
export type { HeaderReader } from './context.cjs';
|
|
4
4
|
export { verifySwellContext } from './request-context.cjs';
|
|
5
5
|
export type { SwellRequestContext, SwellHeadersEnv, SwellSurface, VerifySwellContextOptions } from './request-context.cjs';
|
|
6
|
+
export { verifySwellWebhook } from './webhook.cjs';
|
|
7
|
+
export type { SwellWebhook, VerifySwellWebhookOptions } from './webhook.cjs';
|
|
6
8
|
export { SwellBackendAPI } from './backend.cjs';
|
|
7
9
|
export type { BackendOptions, SwellCollection, SwellData, TransactionOperation, TransactionOptions } from './backend.cjs';
|
|
8
10
|
export { SwellError } from './error.cjs';
|
package/dist/index.d.ts
CHANGED
|
@@ -3,6 +3,8 @@ export { getStorefrontConfig } from './context.js';
|
|
|
3
3
|
export type { HeaderReader } from './context.js';
|
|
4
4
|
export { verifySwellContext } from './request-context.js';
|
|
5
5
|
export type { SwellRequestContext, SwellHeadersEnv, SwellSurface, VerifySwellContextOptions } from './request-context.js';
|
|
6
|
+
export { verifySwellWebhook } from './webhook.js';
|
|
7
|
+
export type { SwellWebhook, VerifySwellWebhookOptions } from './webhook.js';
|
|
6
8
|
export { SwellBackendAPI } from './backend.js';
|
|
7
9
|
export type { BackendOptions, SwellCollection, SwellData, TransactionOperation, TransactionOptions } from './backend.js';
|
|
8
10
|
export { SwellError } from './error.js';
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import './guard.js';
|
|
2
2
|
export { getStorefrontConfig } from './context.js';
|
|
3
3
|
export { verifySwellContext } from './request-context.js';
|
|
4
|
+
export { verifySwellWebhook } from './webhook.js';
|
|
4
5
|
export { SwellBackendAPI } from './backend.js';
|
|
5
6
|
export { SwellError } from './error.js';
|
|
6
7
|
export { requireStoreUser } from './store-user.js';
|
package/dist/jwks.d.cts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare function getVerificationKey(url: string, kid: string): Promise<CryptoKey>;
|
|
1
|
+
export declare function getVerificationKey(url: string, kid: string, code?: string): Promise<CryptoKey>;
|
package/dist/jwks.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare function getVerificationKey(url: string, kid: string): Promise<CryptoKey>;
|
|
1
|
+
export declare function getVerificationKey(url: string, kid: string, code?: string): Promise<CryptoKey>;
|
package/dist/jwks.js
CHANGED
|
@@ -34,7 +34,7 @@ async function refresh(url, entry) {
|
|
|
34
34
|
throw entry.error;
|
|
35
35
|
}
|
|
36
36
|
}
|
|
37
|
-
export async function getVerificationKey(url, kid) {
|
|
37
|
+
export async function getVerificationKey(url, kid, code = 'invalid_swell_context') {
|
|
38
38
|
let entry = keySets.get(url);
|
|
39
39
|
if (!entry) {
|
|
40
40
|
if (keySets.size >= MAX_URLS)
|
|
@@ -65,6 +65,6 @@ export async function getVerificationKey(url, kid) {
|
|
|
65
65
|
}
|
|
66
66
|
const key = entry.keys.get(kid);
|
|
67
67
|
if (!key)
|
|
68
|
-
throw new SwellError('Unknown Swell signing key', { status: 401, code
|
|
68
|
+
throw new SwellError('Unknown Swell signing key', { status: 401, code });
|
|
69
69
|
return key;
|
|
70
70
|
}
|
package/dist/version.d.cts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const USER_AGENT = "swell-apps-sdk/2.0.0-alpha.
|
|
1
|
+
export declare const USER_AGENT = "swell-apps-sdk/2.0.0-alpha.8";
|
package/dist/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const USER_AGENT = "swell-apps-sdk/2.0.0-alpha.
|
|
1
|
+
export declare const USER_AGENT = "swell-apps-sdk/2.0.0-alpha.8";
|
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.
|
|
2
|
+
export const USER_AGENT = 'swell-apps-sdk/2.0.0-alpha.8';
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { HeaderReader } from './context.cjs';
|
|
2
|
+
import type { SwellHeadersEnv } from './request-context.cjs';
|
|
3
|
+
export interface VerifySwellWebhookOptions {
|
|
4
|
+
/** Explicit Worker bindings or server configuration. Omit to read process.env when available. */
|
|
5
|
+
env?: SwellHeadersEnv;
|
|
6
|
+
/** Expected sender from trusted configuration, never incoming headers. Pass this or `appId`. */
|
|
7
|
+
storeId?: string;
|
|
8
|
+
/** The id in swell.json of the app the webhook must belong to. Pass this or `storeId`. */
|
|
9
|
+
appId?: string;
|
|
10
|
+
}
|
|
11
|
+
/** A webhook request Swell sent, with its event. */
|
|
12
|
+
export interface SwellWebhook {
|
|
13
|
+
readonly storeId: string;
|
|
14
|
+
readonly environmentId?: string;
|
|
15
|
+
/** Set for an app's webhook: the id in the app's swell.json. */
|
|
16
|
+
readonly appId?: string;
|
|
17
|
+
readonly webhookId?: string;
|
|
18
|
+
readonly eventId?: string;
|
|
19
|
+
/** The event, as the body sent it. */
|
|
20
|
+
readonly event: Readonly<Record<string, unknown>>;
|
|
21
|
+
/** False only when trusted runtime configuration explicitly disables verification. */
|
|
22
|
+
readonly signatureVerified: boolean;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Verifies the Swell-Signature of a webhook request and reads its event. The
|
|
26
|
+
* body must be the bytes the request carried, before any parsing. Uses ES256
|
|
27
|
+
* and the same pinned JWKS endpoint as verifySwellContext.
|
|
28
|
+
*/
|
|
29
|
+
export declare function verifySwellWebhook(headers: HeaderReader, body: string | ArrayBuffer | ArrayBufferView, options?: VerifySwellWebhookOptions): Promise<SwellWebhook>;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { HeaderReader } from './context.js';
|
|
2
|
+
import type { SwellHeadersEnv } from './request-context.js';
|
|
3
|
+
export interface VerifySwellWebhookOptions {
|
|
4
|
+
/** Explicit Worker bindings or server configuration. Omit to read process.env when available. */
|
|
5
|
+
env?: SwellHeadersEnv;
|
|
6
|
+
/** Expected sender from trusted configuration, never incoming headers. Pass this or `appId`. */
|
|
7
|
+
storeId?: string;
|
|
8
|
+
/** The id in swell.json of the app the webhook must belong to. Pass this or `storeId`. */
|
|
9
|
+
appId?: string;
|
|
10
|
+
}
|
|
11
|
+
/** A webhook request Swell sent, with its event. */
|
|
12
|
+
export interface SwellWebhook {
|
|
13
|
+
readonly storeId: string;
|
|
14
|
+
readonly environmentId?: string;
|
|
15
|
+
/** Set for an app's webhook: the id in the app's swell.json. */
|
|
16
|
+
readonly appId?: string;
|
|
17
|
+
readonly webhookId?: string;
|
|
18
|
+
readonly eventId?: string;
|
|
19
|
+
/** The event, as the body sent it. */
|
|
20
|
+
readonly event: Readonly<Record<string, unknown>>;
|
|
21
|
+
/** False only when trusted runtime configuration explicitly disables verification. */
|
|
22
|
+
readonly signatureVerified: boolean;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Verifies the Swell-Signature of a webhook request and reads its event. The
|
|
26
|
+
* body must be the bytes the request carried, before any parsing. Uses ES256
|
|
27
|
+
* and the same pinned JWKS endpoint as verifySwellContext.
|
|
28
|
+
*/
|
|
29
|
+
export declare function verifySwellWebhook(headers: HeaderReader, body: string | ArrayBuffer | ArrayBufferView, options?: VerifySwellWebhookOptions): Promise<SwellWebhook>;
|
package/dist/webhook.js
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { requireString, validateUrl } from './context.js';
|
|
2
|
+
import { SwellError } from './error.js';
|
|
3
|
+
import { getVerificationKey } from './jwks.js';
|
|
4
|
+
const SIGNATURE_TYPE = 'swell-webhook+jwt';
|
|
5
|
+
function invalidWebhook() {
|
|
6
|
+
return new SwellError('Missing or invalid Swell webhook signature', { status: 401, code: 'invalid_swell_webhook' });
|
|
7
|
+
}
|
|
8
|
+
function decode(value) {
|
|
9
|
+
if (!/^[A-Za-z0-9_-]+$/.test(value))
|
|
10
|
+
throw invalidWebhook();
|
|
11
|
+
return Uint8Array.from(atob(value.replace(/-/g, '+').replace(/_/g, '/')), char => char.charCodeAt(0));
|
|
12
|
+
}
|
|
13
|
+
function object(value) {
|
|
14
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
15
|
+
throw invalidWebhook();
|
|
16
|
+
}
|
|
17
|
+
function optionalString(value, field) {
|
|
18
|
+
if (value == null)
|
|
19
|
+
return undefined;
|
|
20
|
+
requireString(value, field);
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
async function sha256(body) {
|
|
24
|
+
const hash = new Uint8Array(await crypto.subtle.digest('SHA-256', body));
|
|
25
|
+
return btoa(String.fromCharCode(...hash)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Verifies the Swell-Signature of a webhook request and reads its event. The
|
|
29
|
+
* body must be the bytes the request carried, before any parsing. Uses ES256
|
|
30
|
+
* and the same pinned JWKS endpoint as verifySwellContext.
|
|
31
|
+
*/
|
|
32
|
+
export async function verifySwellWebhook(headers, body, options = {}) {
|
|
33
|
+
const runtime = globalThis;
|
|
34
|
+
const env = options.env ?? runtime.process?.env ?? {};
|
|
35
|
+
const verify = env.SWELL_VERIFY_HEADERS !== 'false';
|
|
36
|
+
const jwksUrl = validateUrl(env.SWELL_HEADERS_JWKS_URL ?? 'https://keys.swell.store/jwks.json', 'SWELL_HEADERS_JWKS_URL');
|
|
37
|
+
for (const field of ['appId', 'storeId']) {
|
|
38
|
+
if (options[field] !== undefined)
|
|
39
|
+
requireString(options[field], field);
|
|
40
|
+
}
|
|
41
|
+
// A signature proves that Swell sent the request, not whose webhook it is:
|
|
42
|
+
// any store can point a webhook at any address
|
|
43
|
+
if (options.appId === undefined && options.storeId === undefined) {
|
|
44
|
+
throw new Error('verifySwellWebhook needs options.appId or options.storeId');
|
|
45
|
+
}
|
|
46
|
+
// A parsed body no longer has the bytes the signature covers
|
|
47
|
+
if (typeof body !== 'string' && !(body instanceof ArrayBuffer) && !ArrayBuffer.isView(body)) {
|
|
48
|
+
throw new TypeError('verifySwellWebhook needs the body as the request carried it, a string or bytes');
|
|
49
|
+
}
|
|
50
|
+
const bytes = typeof body === 'string' ? new TextEncoder().encode(body)
|
|
51
|
+
: body instanceof ArrayBuffer ? new Uint8Array(body)
|
|
52
|
+
: new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
|
|
53
|
+
const token = headers.get('Swell-Signature');
|
|
54
|
+
if (!token || token.length > 16_384)
|
|
55
|
+
throw invalidWebhook();
|
|
56
|
+
let payload;
|
|
57
|
+
let header;
|
|
58
|
+
let signature;
|
|
59
|
+
const parts = token.split('.');
|
|
60
|
+
try {
|
|
61
|
+
if (parts.length !== 3)
|
|
62
|
+
throw invalidWebhook();
|
|
63
|
+
header = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(decode(parts[0])));
|
|
64
|
+
payload = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(decode(parts[1])));
|
|
65
|
+
object(header);
|
|
66
|
+
object(payload);
|
|
67
|
+
signature = decode(parts[2]);
|
|
68
|
+
if (header.alg !== 'ES256' || header.typ !== SIGNATURE_TYPE || typeof header.kid !== 'string' || !header.kid ||
|
|
69
|
+
header.crit !== undefined || header.b64 !== undefined || signature.length !== 64)
|
|
70
|
+
throw invalidWebhook();
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
throw invalidWebhook();
|
|
74
|
+
}
|
|
75
|
+
if (verify) {
|
|
76
|
+
const key = await getVerificationKey(jwksUrl, header.kid, 'invalid_swell_webhook');
|
|
77
|
+
if (!await crypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, key, signature, new TextEncoder().encode(`${parts[0]}.${parts[1]}`)))
|
|
78
|
+
throw invalidWebhook();
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
const now = Date.now() / 1000;
|
|
82
|
+
// The issuer controls signature lifetime; allow five seconds for clock skew.
|
|
83
|
+
if (typeof payload.iat !== 'number' || !Number.isFinite(payload.iat) || payload.iat > now + 5 ||
|
|
84
|
+
typeof payload.exp !== 'number' || !Number.isFinite(payload.exp) || payload.exp <= now - 5 ||
|
|
85
|
+
payload.exp <= payload.iat)
|
|
86
|
+
throw invalidWebhook();
|
|
87
|
+
requireString(payload.store_id, 'store_id');
|
|
88
|
+
requireString(payload.body_sha256, 'body_sha256');
|
|
89
|
+
const appId = optionalString(payload.app_id, 'app_id');
|
|
90
|
+
if ((options.storeId !== undefined && payload.store_id !== options.storeId) ||
|
|
91
|
+
(options.appId !== undefined && appId !== options.appId))
|
|
92
|
+
throw invalidWebhook();
|
|
93
|
+
if (payload.body_sha256 !== await sha256(bytes))
|
|
94
|
+
throw invalidWebhook();
|
|
95
|
+
const event = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
|
|
96
|
+
object(event);
|
|
97
|
+
return Object.freeze({
|
|
98
|
+
storeId: payload.store_id,
|
|
99
|
+
environmentId: optionalString(payload.environment_id, 'environment_id'),
|
|
100
|
+
appId,
|
|
101
|
+
webhookId: optionalString(payload.webhook_id, 'webhook_id'),
|
|
102
|
+
eventId: optionalString(payload.event_id, 'event_id'),
|
|
103
|
+
event: Object.freeze(event),
|
|
104
|
+
signatureVerified: verify,
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
throw invalidWebhook();
|
|
109
|
+
}
|
|
110
|
+
}
|