@bridgewise/embed-sdk-web 0.0.0-stage → 0.1.0-beta.1

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/dist/index.cjs ADDED
@@ -0,0 +1,544 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ EmbedClient: () => EmbedClient,
24
+ EmbedError: () => EmbedError,
25
+ SSO_LOGOUT_MESSAGE_TYPE: () => SSO_LOGOUT_MESSAGE_TYPE,
26
+ SSO_READY_MESSAGE_TYPE: () => SSO_READY_MESSAGE_TYPE,
27
+ SSO_TOKEN_MESSAGE_TYPE: () => SSO_TOKEN_MESSAGE_TYPE,
28
+ getApiBaseUrl: () => getApiBaseUrl,
29
+ getEmbeddedOrigin: () => getEmbeddedOrigin,
30
+ isPositionsTradeNow: () => isPositionsTradeNow
31
+ });
32
+ module.exports = __toCommonJS(index_exports);
33
+
34
+ // src/errors.ts
35
+ var EmbedError = class extends Error {
36
+ constructor(reason, message, cause) {
37
+ super(message);
38
+ this.reason = reason;
39
+ this.cause = cause;
40
+ this.name = "EmbedError";
41
+ }
42
+ };
43
+
44
+ // src/internal/Listeners.ts
45
+ var Listeners = class {
46
+ constructor() {
47
+ this.listeners = /* @__PURE__ */ new Set();
48
+ }
49
+ /** Adds a listener and returns a function that removes it again. */
50
+ add(listener) {
51
+ this.listeners.add(listener);
52
+ return () => {
53
+ this.listeners.delete(listener);
54
+ };
55
+ }
56
+ emit(value) {
57
+ for (const listener of this.listeners) listener(value);
58
+ }
59
+ };
60
+
61
+ // src/auth/tokens.ts
62
+ function parseTokenResponse(json, previous) {
63
+ const raw = json;
64
+ if (typeof raw.access_token !== "string" || typeof raw.expires_in !== "number") {
65
+ throw new Error("Unexpected token response shape");
66
+ }
67
+ return {
68
+ accessToken: raw.access_token,
69
+ // Refresh responses may omit these; keep the ones we already have.
70
+ refreshToken: raw.refresh_token ?? previous?.refreshToken,
71
+ userId: raw.user_id ?? previous?.userId,
72
+ tenantId: raw.tenant_id ?? previous?.tenantId,
73
+ expiresAtEpochSeconds: Math.floor(Date.now() / 1e3) + raw.expires_in
74
+ };
75
+ }
76
+ function readJwtExpiry(accessToken) {
77
+ try {
78
+ const payload = accessToken.split(".")[1];
79
+ const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/"));
80
+ const exp = JSON.parse(json).exp;
81
+ if (typeof exp === "number") return exp;
82
+ } catch {
83
+ }
84
+ throw new Error(
85
+ "Could not read the access token's expiry. Pass `expiresAtEpochSeconds` with the token."
86
+ );
87
+ }
88
+ function isExpired(tokens) {
89
+ return Math.floor(Date.now() / 1e3) >= tokens.expiresAtEpochSeconds;
90
+ }
91
+
92
+ // src/auth/AuthApi.ts
93
+ var AuthApi = class {
94
+ constructor(baseUrl, clientId) {
95
+ this.baseUrl = baseUrl;
96
+ this.clientId = clientId;
97
+ }
98
+ /** URL of the hosted login page, which returns the user to `path`. */
99
+ loginUrl(path) {
100
+ const url = new URL(`${this.baseUrl}/bridgewise-auth/login`);
101
+ url.searchParams.set("client_id", this.clientId);
102
+ url.searchParams.set("path", path);
103
+ return url.toString();
104
+ }
105
+ async exchangeCode(code, state) {
106
+ const response = await this.postToken({
107
+ grant_type: "authorization_code",
108
+ code,
109
+ state
110
+ });
111
+ if (!response.ok) {
112
+ throw new Error(`Token exchange failed with status ${response.status}`);
113
+ }
114
+ return parseTokenResponse(await response.json());
115
+ }
116
+ async refresh(refreshToken, previous) {
117
+ const response = await this.postToken(
118
+ { grant_type: "refresh_token", refresh_token: refreshToken },
119
+ { credentials: "include" }
120
+ );
121
+ if (!response.ok) {
122
+ throw new Error(`Token refresh failed with status ${response.status}`);
123
+ }
124
+ return parseTokenResponse(await response.json(), previous);
125
+ }
126
+ postToken(params, init) {
127
+ return fetch(`${this.baseUrl}/bridgewise-auth/token`, {
128
+ ...init,
129
+ method: "POST",
130
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
131
+ body: new URLSearchParams({ ...params, client_id: this.clientId })
132
+ });
133
+ }
134
+ };
135
+
136
+ // src/auth/callback.ts
137
+ var CALLBACK_PARAMS = ["code", "state", "error", "error_description"];
138
+ function readAuthCallback() {
139
+ const params = new URL(window.location.href).searchParams;
140
+ const error = params.get("error");
141
+ if (error) {
142
+ return {
143
+ status: "error",
144
+ message: params.get("error_description") ?? error
145
+ };
146
+ }
147
+ const code = params.get("code");
148
+ const state = params.get("state");
149
+ return code && state ? { status: "success", code, state } : null;
150
+ }
151
+ function removeAuthCallbackFromUrl() {
152
+ const url = new URL(window.location.href);
153
+ for (const param of CALLBACK_PARAMS) url.searchParams.delete(param);
154
+ window.history.replaceState(window.history.state, "", url.toString());
155
+ }
156
+
157
+ // src/auth/messages.ts
158
+ var SSO_TOKEN_MESSAGE_TYPE = "bridgewise:sso:token";
159
+ var SSO_READY_MESSAGE_TYPE = "bridgewise:sso:ready";
160
+ var SSO_LOGOUT_MESSAGE_TYPE = "bridgewise:sso:logout";
161
+ function toTokenMessage(tokens) {
162
+ return {
163
+ type: SSO_TOKEN_MESSAGE_TYPE,
164
+ accessToken: tokens.accessToken,
165
+ userId: tokens.userId,
166
+ tenantId: tokens.tenantId,
167
+ expiresAtEpochSeconds: tokens.expiresAtEpochSeconds
168
+ };
169
+ }
170
+ function isReadyMessage(data) {
171
+ return typeof data === "object" && data !== null && data.type === SSO_READY_MESSAGE_TYPE;
172
+ }
173
+
174
+ // src/auth/EmbedAuth.ts
175
+ var EmbedAuth = class {
176
+ /** @internal Created by `EmbedClient`. */
177
+ constructor(options, channel) {
178
+ this.options = options;
179
+ this.channel = channel;
180
+ this.tokens = null;
181
+ this.refreshTimer = null;
182
+ this.refreshInFlight = null;
183
+ this.successListeners = new Listeners();
184
+ this.refreshListeners = new Listeners();
185
+ this.errorListeners = new Listeners();
186
+ this.api = options.clientId ? new AuthApi(options.apiBaseUrl, options.clientId) : null;
187
+ channel.subscribe((data, source) => {
188
+ if (isReadyMessage(data)) void this.sendTokenTo(source);
189
+ });
190
+ }
191
+ /** Fires after `init()` completes a sign-in. Returns an unsubscribe function. */
192
+ onSuccess(listener) {
193
+ return this.successListeners.add(listener);
194
+ }
195
+ /** Fires after each successful token refresh. Returns an unsubscribe function. */
196
+ onTokenRefresh(listener) {
197
+ return this.refreshListeners.add(listener);
198
+ }
199
+ /** Fires when sign-in or refresh fails. Returns an unsubscribe function. */
200
+ onError(listener) {
201
+ return this.errorListeners.add(listener);
202
+ }
203
+ /**
204
+ * Uses an access token you already hold for the user, and shares it with
205
+ * the embeds. Call it again whenever you have a newer token. Replaces any
206
+ * existing session; the SDK does not refresh a token supplied this way.
207
+ */
208
+ setAccessToken(accessToken, options = {}) {
209
+ this.setTokens({
210
+ accessToken,
211
+ userId: options.userId,
212
+ tenantId: options.tenantId,
213
+ expiresAtEpochSeconds: options.expiresAtEpochSeconds ?? readJwtExpiry(accessToken)
214
+ });
215
+ }
216
+ /**
217
+ * Call once when the app loads. If the URL carries `code`/`state` from the
218
+ * hosted login page, exchanges them for tokens and removes them from the
219
+ * URL. Otherwise, when `autoLogin` is true, redirects to the hosted login
220
+ * page immediately; when false, resolves to null and leaves starting a
221
+ * sign-in up to an explicit `login()` call. Does nothing without a
222
+ * `clientId`.
223
+ */
224
+ async init() {
225
+ if (!this.api) return null;
226
+ const callback = readAuthCallback();
227
+ if (!callback) {
228
+ if (this.options.autoLogin) this.login();
229
+ return null;
230
+ }
231
+ if (callback.status === "error") {
232
+ this.errorListeners.emit(
233
+ new EmbedError("auth_callback_error", callback.message)
234
+ );
235
+ return null;
236
+ }
237
+ try {
238
+ const tokens = await this.api.exchangeCode(callback.code, callback.state);
239
+ this.setTokens(tokens);
240
+ removeAuthCallbackFromUrl();
241
+ this.successListeners.emit(tokens);
242
+ return tokens;
243
+ } catch (cause) {
244
+ this.errorListeners.emit(
245
+ new EmbedError(
246
+ "token_exchange_failed",
247
+ "Failed to exchange authorization code for tokens",
248
+ cause
249
+ )
250
+ );
251
+ return null;
252
+ }
253
+ }
254
+ /**
255
+ * Redirects the browser to the hosted login page. After sign-in the user
256
+ * returns to `path`, else `redirectPath`, else the current page. Requires
257
+ * a `clientId`.
258
+ */
259
+ login(path) {
260
+ if (!this.api) {
261
+ throw new Error("auth.login() needs `clientId` in the EmbedClient config");
262
+ }
263
+ const returnPath = path ?? this.options.redirectPath ?? window.location.pathname + window.location.search;
264
+ window.location.assign(this.api.loginUrl(returnPath));
265
+ }
266
+ /** Drops the in-memory session and tells embedded iframes to drop theirs. */
267
+ logout() {
268
+ this.tokens = null;
269
+ this.clearRefreshTimer();
270
+ this.channel.broadcast({ type: SSO_LOGOUT_MESSAGE_TYPE });
271
+ }
272
+ /**
273
+ * Returns a valid access token, refreshing first if expired. Null if there
274
+ * is no session, or the token has expired and can't be refreshed.
275
+ */
276
+ async getAccessToken() {
277
+ if (!this.tokens) return null;
278
+ if (isExpired(this.tokens)) await this.refresh();
279
+ return this.tokens?.accessToken ?? null;
280
+ }
281
+ /** Whether the SDK currently holds tokens (they don't survive a reload). */
282
+ hasSession() {
283
+ return this.tokens !== null;
284
+ }
285
+ /**
286
+ * Re-sends the current access token to embedded iframes. Embeds normally
287
+ * ask for it themselves when they load, so this is only needed for an
288
+ * embed that doesn't.
289
+ */
290
+ broadcastToken() {
291
+ if (this.tokens) this.channel.broadcast(toTokenMessage(this.tokens));
292
+ }
293
+ /** @internal Stops token refresh. Called by `EmbedClient.destroy()`. */
294
+ destroy() {
295
+ this.clearRefreshTimer();
296
+ }
297
+ setTokens(tokens) {
298
+ this.tokens = tokens;
299
+ this.scheduleRefresh(tokens);
300
+ this.broadcastToken();
301
+ }
302
+ async sendTokenTo(frame) {
303
+ await this.getAccessToken();
304
+ if (this.tokens) this.channel.send(frame, toTokenMessage(this.tokens));
305
+ }
306
+ /** Concurrent callers share a single in-flight refresh. */
307
+ refresh() {
308
+ this.refreshInFlight ?? (this.refreshInFlight = this.performRefresh().finally(() => {
309
+ this.refreshInFlight = null;
310
+ }));
311
+ return this.refreshInFlight;
312
+ }
313
+ async performRefresh() {
314
+ const session = this.tokens;
315
+ if (!this.api || !session?.refreshToken) {
316
+ this.tokens = null;
317
+ return null;
318
+ }
319
+ try {
320
+ const tokens = await this.api.refresh(session.refreshToken, session);
321
+ if (this.tokens !== session) return null;
322
+ this.setTokens(tokens);
323
+ this.refreshListeners.emit(tokens);
324
+ return tokens;
325
+ } catch (cause) {
326
+ if (this.tokens !== session) return null;
327
+ this.tokens = null;
328
+ this.clearRefreshTimer();
329
+ this.errorListeners.emit(
330
+ new EmbedError(
331
+ "token_refresh_failed",
332
+ "Failed to refresh access token",
333
+ cause
334
+ )
335
+ );
336
+ return null;
337
+ }
338
+ }
339
+ /** Refreshes at the moment the access token expires. */
340
+ scheduleRefresh(tokens) {
341
+ this.clearRefreshTimer();
342
+ if (!tokens.refreshToken) return;
343
+ const delayMs = Math.max(
344
+ 0,
345
+ tokens.expiresAtEpochSeconds * 1e3 - Date.now()
346
+ );
347
+ this.refreshTimer = setTimeout(() => void this.refresh(), delayMs);
348
+ }
349
+ clearRefreshTimer() {
350
+ if (this.refreshTimer !== null) {
351
+ clearTimeout(this.refreshTimer);
352
+ this.refreshTimer = null;
353
+ }
354
+ }
355
+ };
356
+
357
+ // src/config.ts
358
+ var API_BASE_URLS = {
359
+ dev: "https://rest.dev-bridgewise.com",
360
+ stage: "https://rest.stage-bridgewise.com",
361
+ prod: "https://rest.bridgewise.com"
362
+ };
363
+ var EMBEDDED_ORIGINS = {
364
+ dev: "https://embedded.dev-bridgewise.com",
365
+ stage: "https://embedded.stage-bridgewise.com",
366
+ prod: "https://embedded.bridgewise.com"
367
+ };
368
+ function getApiBaseUrl(environment) {
369
+ return API_BASE_URLS[environment];
370
+ }
371
+ function getEmbeddedOrigin(environment) {
372
+ return EMBEDDED_ORIGINS[environment];
373
+ }
374
+
375
+ // src/internal/FrameChannel.ts
376
+ var FrameChannel = class {
377
+ constructor(origin) {
378
+ this.origin = origin;
379
+ this.handlers = /* @__PURE__ */ new Set();
380
+ this.handleMessage = (event) => {
381
+ if (event.origin !== this.origin) return;
382
+ const source = event.source;
383
+ if (!source || !isChildFrame(source)) return;
384
+ for (const handler of this.handlers) handler(event.data, source);
385
+ };
386
+ window.addEventListener("message", this.handleMessage);
387
+ }
388
+ /** Receives every message from an embed. Returns an unsubscribe function. */
389
+ subscribe(handler) {
390
+ this.handlers.add(handler);
391
+ return () => {
392
+ this.handlers.delete(handler);
393
+ };
394
+ }
395
+ /**
396
+ * Posts a message to every frame on the page. `postMessage`'s
397
+ * `targetOrigin` is enforced by the browser at delivery time, so frames
398
+ * whose actual origin isn't the embed origin simply never receive it —
399
+ * no need to inspect the page to find which frames are embeds.
400
+ */
401
+ broadcast(message) {
402
+ for (let i = 0; i < window.frames.length; i++) {
403
+ this.send(window.frames[i], message);
404
+ }
405
+ }
406
+ send(frame, message) {
407
+ try {
408
+ frame.postMessage(message, this.origin);
409
+ } catch {
410
+ }
411
+ }
412
+ destroy() {
413
+ window.removeEventListener("message", this.handleMessage);
414
+ this.handlers.clear();
415
+ }
416
+ };
417
+ function isChildFrame(source) {
418
+ for (let i = 0; i < window.frames.length; i++) {
419
+ if (window.frames[i] === source) return true;
420
+ }
421
+ return false;
422
+ }
423
+
424
+ // src/widgets/events.ts
425
+ function isPositionsTradeNow(data, widget) {
426
+ return widget === "portfolio-positions" && data.id === "trade_now" && typeof data.currentAsset === "object" && data.currentAsset !== null && typeof data.targetAsset === "object" && data.targetAsset !== null;
427
+ }
428
+ var WIDGET_CALLBACK_NAMES = {
429
+ load: "onLoad",
430
+ resize: "onResize",
431
+ success: "onSuccess",
432
+ error: "onError",
433
+ "security-select": "onSecuritySelect",
434
+ "bridget-teaser-trigger": "onBridgetTeaserTrigger",
435
+ navigate: "onNavigate",
436
+ "trading-item-id-change": "onTradingItemIdChange",
437
+ "restricted-trigger": "onRestrictedTrigger",
438
+ click: "onClick",
439
+ hover: "onHover",
440
+ trigger: "onTrigger"
441
+ };
442
+ function parseWidgetMessage(raw) {
443
+ if (typeof raw !== "string") return null;
444
+ let msg;
445
+ try {
446
+ msg = JSON.parse(raw);
447
+ } catch {
448
+ return null;
449
+ }
450
+ if (typeof msg?.type !== "string" || typeof msg.widget !== "string" || !Object.prototype.hasOwnProperty.call(WIDGET_CALLBACK_NAMES, msg.type)) {
451
+ return null;
452
+ }
453
+ return msg;
454
+ }
455
+
456
+ // src/widgets/WidgetEvents.ts
457
+ var WidgetEvents = class {
458
+ /** @internal Created by `EmbedClient`. */
459
+ constructor(options, channel) {
460
+ this.options = options;
461
+ this.subscriptions = /* @__PURE__ */ new Set();
462
+ channel.subscribe((data, source) => {
463
+ const message = parseWidgetMessage(data);
464
+ if (message) this.handle(message, source);
465
+ });
466
+ }
467
+ /**
468
+ * Registers callbacks for events posted by embedded widgets (onLoad,
469
+ * onResize, onClick, ...). Returns an unsubscribe function.
470
+ */
471
+ on(callbacks) {
472
+ this.subscriptions.add(callbacks);
473
+ return () => {
474
+ this.subscriptions.delete(callbacks);
475
+ };
476
+ }
477
+ handle(message, source) {
478
+ if (this.options.autoResize && isSizeEvent(message)) {
479
+ setIframeHeight(source, message.data.height);
480
+ }
481
+ this.emit(message, source);
482
+ }
483
+ emit(message, source) {
484
+ const name = WIDGET_CALLBACK_NAMES[message.type];
485
+ const context = { widget: message.widget, event: message.event, source };
486
+ for (const callbacks of this.subscriptions) {
487
+ const callback = callbacks[name];
488
+ callback?.(message.data, context);
489
+ }
490
+ }
491
+ };
492
+ function isSizeEvent(message) {
493
+ return message.type === "load" || message.type === "resize" || message.type === "success";
494
+ }
495
+ function setIframeHeight(source, height) {
496
+ if (typeof height !== "number" || !Number.isFinite(height) || height < 0) {
497
+ return;
498
+ }
499
+ for (const iframe of document.querySelectorAll("iframe")) {
500
+ if (iframe.contentWindow === source) {
501
+ iframe.style.height = `${Math.ceil(height)}px`;
502
+ return;
503
+ }
504
+ }
505
+ }
506
+
507
+ // src/EmbedClient.ts
508
+ var EmbedClient = class {
509
+ constructor(config = {}) {
510
+ const environment = config.environment ?? "prod";
511
+ this.embeddedOrigin = config.embeddedOrigin ?? getEmbeddedOrigin(environment);
512
+ this.channel = new FrameChannel(this.embeddedOrigin);
513
+ this.auth = new EmbedAuth(
514
+ {
515
+ clientId: config.clientId,
516
+ apiBaseUrl: getApiBaseUrl(environment),
517
+ redirectPath: config.redirectPath,
518
+ autoLogin: config.autoLogin ?? false
519
+ },
520
+ this.channel
521
+ );
522
+ this.widgets = new WidgetEvents(
523
+ { autoResize: config.autoResize ?? true },
524
+ this.channel
525
+ );
526
+ if (config.accessToken) this.auth.setAccessToken(config.accessToken);
527
+ }
528
+ /** Stops listening to embeds and stops token refresh. */
529
+ destroy() {
530
+ this.channel.destroy();
531
+ this.auth.destroy();
532
+ }
533
+ };
534
+ // Annotate the CommonJS export names for ESM import in node:
535
+ 0 && (module.exports = {
536
+ EmbedClient,
537
+ EmbedError,
538
+ SSO_LOGOUT_MESSAGE_TYPE,
539
+ SSO_READY_MESSAGE_TYPE,
540
+ SSO_TOKEN_MESSAGE_TYPE,
541
+ getApiBaseUrl,
542
+ getEmbeddedOrigin,
543
+ isPositionsTradeNow
544
+ });