@swell/apps-sdk 2.0.0-alpha.5 → 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.
Files changed (38) hide show
  1. package/README.md +129 -0
  2. package/dist/component-frame.html +13 -0
  3. package/dist/components-client.d.cts +85 -0
  4. package/dist/components-client.d.ts +85 -0
  5. package/dist/components-client.js +196 -0
  6. package/dist/components-focus.d.cts +2 -0
  7. package/dist/components-focus.d.ts +2 -0
  8. package/dist/components-focus.js +68 -0
  9. package/dist/components-frame.d.cts +18 -0
  10. package/dist/components-frame.d.ts +18 -0
  11. package/dist/components-frame.js +251 -0
  12. package/dist/components-host.d.cts +60 -0
  13. package/dist/components-host.d.ts +60 -0
  14. package/dist/components-host.js +315 -0
  15. package/dist/components-payment.d.cts +11 -0
  16. package/dist/components-payment.d.ts +11 -0
  17. package/dist/components-payment.js +52 -0
  18. package/dist/components-placement.d.cts +18 -0
  19. package/dist/components-placement.d.ts +18 -0
  20. package/dist/components-placement.js +131 -0
  21. package/dist/components-protocol.d.cts +89 -0
  22. package/dist/components-protocol.d.ts +89 -0
  23. package/dist/components-protocol.js +20 -0
  24. package/dist/components-types.d.cts +84 -0
  25. package/dist/components-types.d.ts +84 -0
  26. package/dist/components-types.js +1 -0
  27. package/dist/components.d.cts +6 -0
  28. package/dist/components.d.ts +6 -0
  29. package/dist/components.js +2 -0
  30. package/dist/index.d.cts +1 -1
  31. package/dist/index.d.ts +1 -1
  32. package/dist/request-context.d.cts +4 -0
  33. package/dist/request-context.d.ts +4 -0
  34. package/dist/request-context.js +4 -0
  35. package/dist/version.d.cts +1 -1
  36. package/dist/version.d.ts +1 -1
  37. package/dist/version.js +1 -1
  38. package/package.json +11 -1
@@ -0,0 +1,251 @@
1
+ import { firstTabbable } from './components-focus.js';
2
+ import { TOKEN_HEADER, unwrap, wrap } from './components-protocol.js';
3
+ // #root is a flow root, so its children's margins count in the height reported to the host
4
+ const BASE_STYLE = 'html,body{margin:0;padding:0;background:transparent}#root{display:flow-root}';
5
+ function isModule(value) {
6
+ const module = value;
7
+ return !!module && typeof module.mount === 'function' && typeof module.update === 'function' && typeof module.unmount === 'function';
8
+ }
9
+ const errorMessage = (error) => (error instanceof Error ? error.message : String(error));
10
+ // Only the platform knows which build the installation runs, so it answers next to the shell page
11
+ async function fetchBundleUrl(win) {
12
+ const response = await win.fetch(new URL(`${win.location.pathname}.json`, win.location.href).href, { headers: { Accept: 'application/json' } });
13
+ if (response.status === 404)
14
+ throw new Error('Component not found');
15
+ if (!response.ok)
16
+ throw new Error(`Component metadata failed (${response.status})`);
17
+ const { bundleUrl } = (await response.json());
18
+ if (typeof bundleUrl !== 'string' || !bundleUrl)
19
+ throw new Error('Component metadata has no bundle URL');
20
+ return new URL(bundleUrl, win.location.href).href;
21
+ }
22
+ /** Runs inside the component frame: connects to the host page and renders the component bundle. */
23
+ export function startComponentFrame(options = {}) {
24
+ const win = options.window ?? window;
25
+ const parent = options.parent ?? win.parent;
26
+ const params = new URLSearchParams(win.location.search);
27
+ const parentOrigin = params.get('parent');
28
+ const channel = params.get('channel');
29
+ if (!parentOrigin || !channel || parent === win)
30
+ throw new Error('App component frames must be embedded by a Swell host');
31
+ // Asked right away, so the answer arrives while the host handshake runs; a failure is reported when the bundle loads
32
+ const bundleUrl = options.bundleUrl !== undefined
33
+ ? Promise.resolve(new URL(options.bundleUrl, win.location.href).href)
34
+ : fetchBundleUrl(win);
35
+ bundleUrl.catch(() => { });
36
+ const document = win.document;
37
+ const style = document.createElement('style');
38
+ style.textContent = BASE_STYLE;
39
+ document.head.appendChild(style);
40
+ let root = options.root ?? document.getElementById('root');
41
+ if (!root) {
42
+ root = document.createElement('div');
43
+ root.id = 'root';
44
+ document.body.appendChild(root);
45
+ }
46
+ const target = root;
47
+ const importModule = options.importModule ?? ((url) => import(/* webpackIgnore: true */ /* @vite-ignore */ url));
48
+ let props = null;
49
+ let token = null;
50
+ let module = null;
51
+ let mounting = null;
52
+ let overlay = false;
53
+ let lastHeight = -1;
54
+ let scheduled = 0;
55
+ let mayTurnOn = false;
56
+ // The viewport-covering element while overlay is on
57
+ let blocker = null;
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();
63
+ const post = (message) => parent.postMessage(wrap(channel, message), parentOrigin);
64
+ const fail = (error) => post({ type: 'error', message: errorMessage(error) });
65
+ // The token only goes to the app origin (functions, /app-api), never to third parties.
66
+ const fetchWithToken = (input, init) => {
67
+ const url = new URL(input instanceof Request ? input.url : String(input), win.location.href);
68
+ if (!token || url.origin !== win.location.origin)
69
+ return win.fetch(input, init);
70
+ const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));
71
+ headers.set(TOKEN_HEADER, token);
72
+ return win.fetch(input, { ...init, headers });
73
+ };
74
+ // Created once, so the component gets the same functions on every render
75
+ const callbacks = {
76
+ // The component sees its own value before the next event; hosts only send values that change
77
+ // elsewhere. The re-render runs in a microtask, so setValue during a render does not re-enter it
78
+ setValue: (value) => {
79
+ if (props) {
80
+ props = { ...props, value };
81
+ Promise.resolve().then(() => module?.update(target, componentProps())).catch(fail);
82
+ }
83
+ post({ type: 'change', value });
84
+ },
85
+ setValidity: (error) => post({ type: 'validity', error: typeof error === 'string' ? error : null }),
86
+ fetch: fetchWithToken,
87
+ on(event, handler) {
88
+ handlers.set(event, [...(handlers.get(event) ?? []), handler]);
89
+ return () => {
90
+ handlers.set(event, (handlers.get(event) ?? []).filter(item => item !== handler));
91
+ };
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
+ },
102
+ };
103
+ const componentProps = () => ({ ...props, ...callbacks });
104
+ const reportHeight = () => {
105
+ if (overlay)
106
+ return;
107
+ const height = Math.ceil(target.getBoundingClientRect().height);
108
+ if (height !== lastHeight) {
109
+ lastHeight = height;
110
+ post({ type: 'resize', height });
111
+ }
112
+ };
113
+ const placeRoot = (rect) => Object.assign(target.style, { position: 'absolute', top: `${rect.top}px`, left: `${rect.left}px`, width: `${rect.width}px` });
114
+ const focusModal = () => blocker && firstTabbable(blocker)?.focus();
115
+ const setOverlay = (on) => {
116
+ if (overlay === on)
117
+ return;
118
+ overlay = on;
119
+ // The component's own controls are under the modal's backdrop: out of the Tab order and the pointer's reach
120
+ if (on)
121
+ target.setAttribute('inert', '');
122
+ else
123
+ target.removeAttribute('inert');
124
+ // The modal takes focus from the component under it, or when nothing has focus, unless it took focus itself
125
+ const active = document.activeElement;
126
+ if (on && (!active || active === document.body || target.contains(active)))
127
+ focusModal();
128
+ document.documentElement.style.overflow = on ? 'hidden' : '';
129
+ post({ type: 'overlay', on });
130
+ if (!on) {
131
+ Object.assign(target.style, { position: '', top: '', left: '', width: '' });
132
+ lastHeight = -1;
133
+ reportHeight();
134
+ }
135
+ };
136
+ // An SDK opened a modal: a fixed element covering the frame viewport (Stripe 3DS, QR codes, vendor modals).
137
+ // An element without area covers nothing, even while the frame itself is zero high.
138
+ const isBlocking = (element) => {
139
+ if (element === target || element.tagName === 'SCRIPT' || element.tagName === 'STYLE')
140
+ return false;
141
+ const computed = win.getComputedStyle(element);
142
+ if (computed.position !== 'fixed' || computed.display === 'none' || computed.visibility === 'hidden' || computed.opacity === '0')
143
+ return false;
144
+ const box = element.getBoundingClientRect();
145
+ return box.width > 0 && box.height > 0 && box.width >= win.innerWidth * 0.9 && box.height >= win.innerHeight * 0.9;
146
+ };
147
+ // DOM changes can switch overlay on and off. A frame resize can only switch it off: overlay itself
148
+ // resizes the frame, and an element that covers only the small frame would otherwise flip it forever.
149
+ const detectOverlay = (turnOn) => {
150
+ mayTurnOn ||= turnOn;
151
+ win.cancelAnimationFrame(scheduled);
152
+ scheduled = win.requestAnimationFrame(() => {
153
+ blocker = Array.from(document.body.children).find(isBlocking) ?? null;
154
+ if (mayTurnOn || !blocker)
155
+ setOverlay(!!blocker);
156
+ mayTurnOn = false;
157
+ });
158
+ };
159
+ // The frame moves the root itself during overlay; that is no new modal
160
+ new win.MutationObserver((records) => {
161
+ if (records.some(record => record.target !== target || record.type !== 'attributes'))
162
+ detectOverlay(true);
163
+ }).observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });
164
+ win.addEventListener('resize', () => detectOverlay(false));
165
+ new win.ResizeObserver(reportHeight).observe(target);
166
+ let loading = null;
167
+ // One import per frame: an init that arrives while the bundle loads waits for the same import
168
+ const loadModule = () => {
169
+ loading ??= bundleUrl.then(importModule).then((loaded) => {
170
+ if (!isModule(loaded))
171
+ throw new Error('Component bundle must export mount, update and unmount');
172
+ return loaded;
173
+ });
174
+ return loading;
175
+ };
176
+ // Mounts with the latest props (updates may arrive while the bundle loads) and reports ready once mount resolves
177
+ async function mount() {
178
+ const loaded = await loadModule();
179
+ const mountedProps = props;
180
+ await loaded.mount(target, componentProps());
181
+ module = loaded;
182
+ if (props !== mountedProps)
183
+ await loaded.update(target, componentProps());
184
+ post({ type: 'ready' });
185
+ reportHeight();
186
+ }
187
+ async function handle(message) {
188
+ switch (message.type) {
189
+ case 'init':
190
+ actions = Array.isArray(message.actions) ? message.actions.filter(name => typeof name === 'string') : [];
191
+ props = message.props;
192
+ token = message.token;
193
+ if (!mounting) {
194
+ mounting = mount();
195
+ return mounting;
196
+ }
197
+ await mounting;
198
+ await module?.update(target, componentProps());
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
+ }
211
+ case 'update':
212
+ if (!props)
213
+ return;
214
+ props = { ...props, ...message.props };
215
+ await module?.update(target, componentProps());
216
+ return;
217
+ case 'token':
218
+ token = message.token;
219
+ return;
220
+ case 'event': {
221
+ const [handler] = handlers.get(message.name) ?? [];
222
+ try {
223
+ post({ type: 'result', call: message.call, result: handler ? await handler(message.data) : undefined });
224
+ }
225
+ catch (error) {
226
+ post({ type: 'result', call: message.call, error: errorMessage(error) });
227
+ }
228
+ return;
229
+ }
230
+ case 'rect':
231
+ if (overlay)
232
+ placeRoot(message.rect);
233
+ return;
234
+ case 'focus':
235
+ // During overlay the modal takes focus, never the component under its backdrop
236
+ if (overlay)
237
+ focusModal();
238
+ else
239
+ firstTabbable(target)?.focus();
240
+ return;
241
+ }
242
+ }
243
+ win.addEventListener('message', (event) => {
244
+ if (event.source !== parent || event.origin !== parentOrigin)
245
+ return;
246
+ const message = unwrap(event.data, channel);
247
+ if (message)
248
+ handle(message).catch(fail);
249
+ });
250
+ post({ type: 'hello' });
251
+ }
@@ -0,0 +1,60 @@
1
+ import type { ComponentInput, ComponentToken } from './components-types.cjs';
2
+ import type { WireProps } from './components-protocol.cjs';
3
+ /** Controls one mounted component. */
4
+ export interface ComponentHandle<TValue = unknown> {
5
+ /**
6
+ * Resolves when the component has mounted in its frame. Rejects when the component cannot be
7
+ * loaded or started; the `error` event fires as well. `unmount` also rejects it, without an
8
+ * `error` event. A frame `error` is final: a later `ready` from that frame does not revive the
9
+ * handle. A frame that only missed the 10 s start timeout can still start later and then serves `emit`.
10
+ */
11
+ readonly ready: Promise<void>;
12
+ /**
13
+ * Listens to the component. Returns a function that removes the listener; unknown events are ignored.
14
+ * A listener that throws is caught and logged with `console.error`; the other listeners still run.
15
+ */
16
+ on(event: 'change', handler: (value: TValue) => void): () => void;
17
+ on(event: 'validity', handler: (error: string | null) => void): () => void;
18
+ on(event: 'error', handler: (error: Error) => void): () => void;
19
+ /** Re-renders the component with new data. */
20
+ update(input: ComponentInput<TValue>): void;
21
+ /**
22
+ * Sends an event to the component and resolves with its handler's result. Rejects when the frame
23
+ * does not start in time, reports an error (final) or is unmounted.
24
+ */
25
+ emit<T = unknown>(event: string, data?: unknown): Promise<T>;
26
+ /**
27
+ * Moves keyboard focus to the component's first control, as a form does for its first invalid field.
28
+ * During overlay, to the component's modal. A component without controls keeps focus on its frame.
29
+ */
30
+ focus(): void;
31
+ unmount(): void;
32
+ }
33
+ export interface EmbedOptions<TValue = unknown, TContext = Record<string, unknown>> extends ComponentInput<TValue, TContext> {
34
+ /** Frame URL from the component metadata. */
35
+ src: string;
36
+ settings?: Record<string, unknown>;
37
+ title?: string;
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>;
41
+ }
42
+ type Listener = (value: never) => void;
43
+ type HandleEvent = 'change' | 'validity' | 'error';
44
+ export declare const toError: (error: unknown) => Error;
45
+ /** The props a handle update changes: only the keys the host passed. */
46
+ export declare function pickInput(input: ComponentInput<unknown, unknown>): Partial<WireProps>;
47
+ /** Handle event listeners. Unknown event names subscribe to nothing. */
48
+ export declare function createListeners(): {
49
+ on(event: string, handler: Listener): () => void;
50
+ notify(event: HandleEvent, value: unknown): void;
51
+ };
52
+ /** A promise with its settle functions. Rejections are handled, so an unobserved one is not reported. */
53
+ export declare function deferred(): {
54
+ promise: Promise<void>;
55
+ resolve: () => void;
56
+ reject: (error: Error) => void;
57
+ };
58
+ /** Embeds a component frame in `placeholder`. Internal: hosts use createComponents().mount(). */
59
+ export declare function embedComponent<TValue = unknown, TContext = Record<string, unknown>>(placeholder: HTMLElement, options: EmbedOptions<TValue, TContext>): ComponentHandle<TValue>;
60
+ export {};
@@ -0,0 +1,60 @@
1
+ import type { ComponentInput, ComponentToken } from './components-types.js';
2
+ import type { WireProps } from './components-protocol.js';
3
+ /** Controls one mounted component. */
4
+ export interface ComponentHandle<TValue = unknown> {
5
+ /**
6
+ * Resolves when the component has mounted in its frame. Rejects when the component cannot be
7
+ * loaded or started; the `error` event fires as well. `unmount` also rejects it, without an
8
+ * `error` event. A frame `error` is final: a later `ready` from that frame does not revive the
9
+ * handle. A frame that only missed the 10 s start timeout can still start later and then serves `emit`.
10
+ */
11
+ readonly ready: Promise<void>;
12
+ /**
13
+ * Listens to the component. Returns a function that removes the listener; unknown events are ignored.
14
+ * A listener that throws is caught and logged with `console.error`; the other listeners still run.
15
+ */
16
+ on(event: 'change', handler: (value: TValue) => void): () => void;
17
+ on(event: 'validity', handler: (error: string | null) => void): () => void;
18
+ on(event: 'error', handler: (error: Error) => void): () => void;
19
+ /** Re-renders the component with new data. */
20
+ update(input: ComponentInput<TValue>): void;
21
+ /**
22
+ * Sends an event to the component and resolves with its handler's result. Rejects when the frame
23
+ * does not start in time, reports an error (final) or is unmounted.
24
+ */
25
+ emit<T = unknown>(event: string, data?: unknown): Promise<T>;
26
+ /**
27
+ * Moves keyboard focus to the component's first control, as a form does for its first invalid field.
28
+ * During overlay, to the component's modal. A component without controls keeps focus on its frame.
29
+ */
30
+ focus(): void;
31
+ unmount(): void;
32
+ }
33
+ export interface EmbedOptions<TValue = unknown, TContext = Record<string, unknown>> extends ComponentInput<TValue, TContext> {
34
+ /** Frame URL from the component metadata. */
35
+ src: string;
36
+ settings?: Record<string, unknown>;
37
+ title?: string;
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>;
41
+ }
42
+ type Listener = (value: never) => void;
43
+ type HandleEvent = 'change' | 'validity' | 'error';
44
+ export declare const toError: (error: unknown) => Error;
45
+ /** The props a handle update changes: only the keys the host passed. */
46
+ export declare function pickInput(input: ComponentInput<unknown, unknown>): Partial<WireProps>;
47
+ /** Handle event listeners. Unknown event names subscribe to nothing. */
48
+ export declare function createListeners(): {
49
+ on(event: string, handler: Listener): () => void;
50
+ notify(event: HandleEvent, value: unknown): void;
51
+ };
52
+ /** A promise with its settle functions. Rejections are handled, so an unobserved one is not reported. */
53
+ export declare function deferred(): {
54
+ promise: Promise<void>;
55
+ resolve: () => void;
56
+ reject: (error: Error) => void;
57
+ };
58
+ /** Embeds a component frame in `placeholder`. Internal: hosts use createComponents().mount(). */
59
+ export declare function embedComponent<TValue = unknown, TContext = Record<string, unknown>>(placeholder: HTMLElement, options: EmbedOptions<TValue, TContext>): ComponentHandle<TValue>;
60
+ export {};
@@ -0,0 +1,315 @@
1
+ import { placeFrame } from './components-placement.js';
2
+ import { unwrap, wrap } from './components-protocol.js';
3
+ const REFRESH_SECONDS = 60;
4
+ const MIN_REFRESH_MS = 5_000;
5
+ const RETRY_MS = 10_000;
6
+ const MAX_RETRY_MS = 5 * 60_000;
7
+ const MAX_TIMEOUT = 2 ** 31 - 1;
8
+ const START_MS = 10_000;
9
+ const INPUT_KEYS = ['value', 'context', 'params', 'readonly', 'locale'];
10
+ export const toError = (error) => (error instanceof Error ? error : new Error(String(error)));
11
+ /** The props a handle update changes: only the keys the host passed. */
12
+ export function pickInput(input) {
13
+ const changed = {};
14
+ for (const key of INPUT_KEYS) {
15
+ if (key in input)
16
+ Object.assign(changed, { [key]: input[key] });
17
+ }
18
+ return changed;
19
+ }
20
+ /** Handle event listeners. Unknown event names subscribe to nothing. */
21
+ export function createListeners() {
22
+ const sets = new Map([['change', new Set()], ['validity', new Set()], ['error', new Set()]]);
23
+ return {
24
+ on(event, handler) {
25
+ const set = sets.get(event);
26
+ set?.add(handler);
27
+ return () => {
28
+ set?.delete(handler);
29
+ };
30
+ },
31
+ notify(event, value) {
32
+ for (const handler of sets.get(event) ?? []) {
33
+ // A throwing listener must not stop the others or break the failure path that notified it
34
+ try {
35
+ handler(value);
36
+ }
37
+ catch (error) {
38
+ console.error(error);
39
+ }
40
+ }
41
+ },
42
+ };
43
+ }
44
+ /** A promise with its settle functions. Rejections are handled, so an unobserved one is not reported. */
45
+ export function deferred() {
46
+ let resolve;
47
+ let reject;
48
+ const promise = new Promise((done, fail) => {
49
+ resolve = done;
50
+ reject = fail;
51
+ });
52
+ promise.catch(() => { });
53
+ return { promise, resolve, reject };
54
+ }
55
+ // randomUUID exists only in secure contexts; hosts served over plain http (local development) still get
56
+ // a random channel
57
+ function randomChannel() {
58
+ if (typeof crypto.randomUUID === 'function')
59
+ return crypto.randomUUID();
60
+ return Array.from(crypto.getRandomValues(new Uint8Array(16)), byte => byte.toString(16).padStart(2, '0')).join('');
61
+ }
62
+ /** Embeds a component frame in `placeholder`. Internal: hosts use createComponents().mount(). */
63
+ export function embedComponent(placeholder, options) {
64
+ const window = placeholder.ownerDocument.defaultView;
65
+ if (!window)
66
+ throw new Error('Component placeholder must be attached to a window');
67
+ const channel = randomChannel();
68
+ const url = new URL(options.src);
69
+ url.searchParams.set('parent', window.location.origin);
70
+ url.searchParams.set('channel', channel);
71
+ const frameOrigin = url.origin;
72
+ const props = {
73
+ value: options.value, context: options.context ?? {}, params: options.params ?? {},
74
+ settings: options.settings ?? {}, locale: options.locale ?? 'en', readonly: options.readonly ?? false,
75
+ };
76
+ const { on, notify } = createListeners();
77
+ const pending = new Map();
78
+ let calls = 0;
79
+ let token = null;
80
+ let tokenTimer;
81
+ let tokenFailures = 0;
82
+ let startTimer;
83
+ let greeted = false;
84
+ let started = false;
85
+ let destroyed = false;
86
+ // The component has rendered once: a later frame error leaves it usable, and in the Tab order
87
+ let rendered = false;
88
+ const { promise: ready, resolve: markReady, reject: failReady } = deferred();
89
+ // Settles on the frame's own `ready` message, so a frame that starts after the start timeout still serves `emit`
90
+ const { promise: live, resolve: markLive, reject: failLive } = deferred();
91
+ // Rejects at the start timeout, so `emit` fails instead of waiting for a frame that never starts
92
+ const { promise: startFailed, reject: failStart } = deferred();
93
+ const stop = (error) => {
94
+ failReady(error);
95
+ failLive(error);
96
+ };
97
+ const fail = (error) => {
98
+ const reported = toError(error);
99
+ notify('error', reported);
100
+ return reported;
101
+ };
102
+ const rejectPending = (error) => {
103
+ for (const call of pending.values())
104
+ call.reject(error);
105
+ pending.clear();
106
+ };
107
+ const placed = placeFrame(placeholder, url.href, options.title ?? 'App component', rect => send({ type: 'rect', rect }));
108
+ // A Tab stop only while the frame runs: from its first hello until it fails to start, or reports an error
109
+ // before it rendered, so Tab skips a frame that shows an error page
110
+ placed.iframe.tabIndex = -1;
111
+ const skipInTabOrder = () => {
112
+ placed.iframe.tabIndex = -1;
113
+ };
114
+ const focusFrame = () => {
115
+ placed.iframe.focus();
116
+ send({ type: 'focus' });
117
+ };
118
+ // Throws when the message cannot be cloned
119
+ function post(message) {
120
+ if (started && !destroyed)
121
+ placed.iframe.contentWindow?.postMessage(wrap(channel, message), frameOrigin);
122
+ }
123
+ function send(message) {
124
+ try {
125
+ post(message);
126
+ }
127
+ catch (error) {
128
+ fail(error);
129
+ }
130
+ }
131
+ // A failed refresh keeps the current token, which can still be valid, and retries with backoff
132
+ async function loadToken() {
133
+ if (!options.getToken || destroyed)
134
+ return;
135
+ let next;
136
+ let error;
137
+ try {
138
+ next = await options.getToken();
139
+ if (!next || typeof next.token !== 'string' || !Number.isFinite(next.expires)) {
140
+ throw new TypeError('getToken must resolve to { token: string, expires: number }');
141
+ }
142
+ }
143
+ catch (caught) {
144
+ next = undefined;
145
+ error = caught;
146
+ }
147
+ if (destroyed)
148
+ return;
149
+ const delay = next
150
+ ? Math.max(MIN_REFRESH_MS, (next.expires - REFRESH_SECONDS) * 1000 - Date.now())
151
+ : Math.min(MAX_RETRY_MS, RETRY_MS * 2 ** tokenFailures);
152
+ tokenFailures = next ? 0 : tokenFailures + 1;
153
+ tokenTimer = setTimeout(() => void loadToken(), Math.min(MAX_TIMEOUT, delay));
154
+ if (next) {
155
+ token = next.token;
156
+ send({ type: 'token', token });
157
+ }
158
+ else {
159
+ fail(error);
160
+ }
161
+ }
162
+ // On a microtask, so listeners added right after mount see a getToken that throws at once
163
+ const tokenLoaded = Promise.resolve().then(loadToken);
164
+ // A frame page that never says hello (404, CSP, frame-ancestors) fails ready instead of leaving it pending
165
+ placed.iframe.addEventListener('load', () => {
166
+ if (greeted || destroyed)
167
+ return;
168
+ clearTimeout(startTimer);
169
+ startTimer = setTimeout(() => {
170
+ if (greeted || destroyed)
171
+ return;
172
+ const error = new Error('Component frame did not start');
173
+ skipInTabOrder();
174
+ failReady(error);
175
+ failStart(error);
176
+ fail(error);
177
+ }, START_MS);
178
+ });
179
+ async function onMessage(event) {
180
+ if (event.origin !== frameOrigin || event.source !== placed.iframe.contentWindow)
181
+ return;
182
+ const message = unwrap(event.data, channel);
183
+ if (!message)
184
+ return;
185
+ switch (message.type) {
186
+ case 'hello':
187
+ clearTimeout(startTimer);
188
+ if (greeted) {
189
+ // The frame reloaded: its new runtime starts without overlay and cannot answer earlier events
190
+ placed.setOverlay(false);
191
+ rejectPending(new Error('Component reloaded'));
192
+ }
193
+ if (!greeted)
194
+ placed.iframe.removeAttribute('tabindex');
195
+ greeted = true;
196
+ await tokenLoaded;
197
+ started = true;
198
+ try {
199
+ post({ type: 'init', props, token, actions: Object.keys(options.actions ?? {}) });
200
+ }
201
+ catch (error) {
202
+ const reported = toError(error);
203
+ skipInTabOrder();
204
+ stop(reported);
205
+ fail(reported);
206
+ }
207
+ return;
208
+ case 'ready':
209
+ rendered = true;
210
+ markReady();
211
+ markLive();
212
+ return;
213
+ case 'change':
214
+ notify('change', message.value);
215
+ return;
216
+ case 'validity':
217
+ notify('validity', typeof message.error === 'string' ? message.error : null);
218
+ return;
219
+ case 'resize':
220
+ if (Number.isFinite(message.height))
221
+ placed.setHeight(Math.max(0, Math.ceil(message.height)));
222
+ return;
223
+ case 'overlay': {
224
+ const on = message.on === true;
225
+ send({ type: 'rect', rect: placed.setOverlay(on) });
226
+ // The component's modal takes focus, unless focus is already in its frame
227
+ if (on && placeholder.ownerDocument.activeElement !== placed.iframe)
228
+ focusFrame();
229
+ return;
230
+ }
231
+ case 'result': {
232
+ const call = pending.get(message.call);
233
+ if (!call)
234
+ return;
235
+ pending.delete(message.call);
236
+ if (typeof message.error === 'string')
237
+ call.reject(new Error(message.error));
238
+ else
239
+ call.resolve(message.result);
240
+ return;
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
+ }
263
+ case 'error': {
264
+ const error = new Error(String(message.message));
265
+ if (!rendered)
266
+ skipInTabOrder();
267
+ stop(error);
268
+ fail(error);
269
+ return;
270
+ }
271
+ }
272
+ }
273
+ window.addEventListener('message', onMessage);
274
+ return {
275
+ ready,
276
+ on,
277
+ update(input) {
278
+ const changed = pickInput(input);
279
+ Object.assign(props, changed);
280
+ send({ type: 'update', props: changed });
281
+ },
282
+ async emit(name, data) {
283
+ await Promise.race([live, startFailed]);
284
+ if (destroyed)
285
+ throw new Error('Component unmounted');
286
+ const call = ++calls;
287
+ const result = new Promise((resolve, reject) => {
288
+ pending.set(call, { resolve: resolve, reject });
289
+ });
290
+ try {
291
+ post({ type: 'event', call, name, data });
292
+ }
293
+ catch (error) {
294
+ pending.delete(call);
295
+ throw error;
296
+ }
297
+ return result;
298
+ },
299
+ focus() {
300
+ if (!destroyed)
301
+ focusFrame();
302
+ },
303
+ unmount() {
304
+ if (destroyed)
305
+ return;
306
+ destroyed = true;
307
+ window.removeEventListener('message', onMessage);
308
+ clearTimeout(tokenTimer);
309
+ clearTimeout(startTimer);
310
+ rejectPending(new Error('Component unmounted'));
311
+ stop(new Error('Component unmounted'));
312
+ placed.destroy();
313
+ },
314
+ };
315
+ }