@base44-preview/sdk 0.8.48-pr.281.97e1467 → 0.8.48-pr.282.8affbe6

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/client.js CHANGED
@@ -5,6 +5,7 @@ import { createAuthModule } from "./modules/auth.js";
5
5
  import { createSsoModule } from "./modules/sso.js";
6
6
  import { createConnectorsModule, createUserConnectorsModule, } from "./modules/connectors.js";
7
7
  import { getAccessToken } from "./utils/auth-utils.js";
8
+ import { exchangeEmbedToken, isEmbeddedTab, markEmbeddedTab, takeEmbedTokenFromUrl, } from "./utils/embed-session.js";
8
9
  import { createFetchWithAuth } from "./utils/fetch-with-auth.js";
9
10
  import { createFunctionsModule } from "./modules/functions.js";
10
11
  import { createAgentsModule } from "./modules/agents.js";
@@ -57,12 +58,28 @@ export function createClient(config) {
57
58
  const { serverUrl = "https://base44.app", appId, analytics, token, serviceToken, requiresAuth = false, appBaseUrl, options, functionsVersion, headers: optionalHeaders, } = config;
58
59
  // Normalize appBaseUrl to always be a string (empty if not provided or invalid)
59
60
  const normalizedAppBaseUrl = typeof appBaseUrl === "string" ? appBaseUrl : "";
61
+ const inBrowser = typeof window !== "undefined";
62
+ // A host platform embeds the app with a one-time token on the iframe URL.
63
+ // It comes off the URL here, before any other code can read it; the
64
+ // exchange that turns it into a session runs once the modules exist.
65
+ const embedOtt = inBrowser ? takeEmbedTokenFromUrl() : null;
66
+ const embedded = embedOtt !== null || (inBrowser && isEmbeddedTab());
67
+ if (embedOtt) {
68
+ markEmbeddedTab();
69
+ }
70
+ // What an app passes as `token` is whatever getAccessToken() returned as the
71
+ // page loaded. In an embedded frame that is the one-time token itself, or a
72
+ // token an earlier visitor left in storage; neither is this session.
73
+ const configToken = embedded ? undefined : token;
74
+ let currentToken = configToken !== null && configToken !== void 0 ? configToken : null;
60
75
  const socketConfig = {
61
76
  serverUrl,
62
77
  mountPath: "/ws-user-apps/socket.io/",
63
78
  transports: ["websocket"],
64
79
  appId,
65
- token,
80
+ // null (not undefined): an embedded frame's only identity is the one the
81
+ // platform minted, so the socket must not fall back to a stored token.
82
+ token: embedded ? null : configToken,
66
83
  };
67
84
  let socket = null;
68
85
  const getSocket = () => {
@@ -86,19 +103,19 @@ export function createClient(config) {
86
103
  const axiosClient = createAxiosClient({
87
104
  baseURL: `${serverUrl}/api`,
88
105
  headers,
89
- token,
106
+ token: configToken,
90
107
  onError: options === null || options === void 0 ? void 0 : options.onError,
91
108
  });
92
109
  const functionsAxiosClient = createAxiosClient({
93
110
  baseURL: `${serverUrl}/api`,
94
111
  headers: functionHeaders,
95
- token,
112
+ token: configToken,
96
113
  interceptResponses: false,
97
114
  onError: options === null || options === void 0 ? void 0 : options.onError,
98
115
  });
99
116
  const serviceRoleHeaders = {
100
117
  ...headers,
101
- ...(token ? { "on-behalf-of": `Bearer ${token}` } : {}),
118
+ ...(configToken ? { "on-behalf-of": `Bearer ${configToken}` } : {}),
102
119
  };
103
120
  const serviceRoleAxiosClient = createAxiosClient({
104
121
  baseURL: `${serverUrl}/api`,
@@ -124,27 +141,74 @@ export function createClient(config) {
124
141
  const userAuthModule = createAuthModule(axiosClient, functionsAxiosClient, appId, {
125
142
  appBaseUrl: normalizedAppBaseUrl,
126
143
  serverUrl,
127
- token,
144
+ token: configToken,
145
+ embedded,
128
146
  });
129
147
  // Apply the access token before any module that may issue authenticated
130
148
  // requests during construction (notably analytics, which fires an init
131
149
  // event whose flush calls auth.me()). Without this, the first User/me
132
150
  // request is built before setToken runs and goes out unauthenticated.
133
- if (typeof window !== "undefined") {
134
- const accessToken = token || getAccessToken();
151
+ // An embedded load skips this: its session comes from the exchange below,
152
+ // and a token an earlier visitor left in storage must not become it.
153
+ if (inBrowser && !embedded) {
154
+ const accessToken = configToken || getAccessToken();
135
155
  if (accessToken) {
156
+ currentToken = accessToken;
136
157
  userAuthModule.setToken(accessToken);
137
158
  }
138
159
  }
160
+ // The one answer every module reads. Follows setToken and logout; outside an
161
+ // embedded frame it still falls back to storage, so a login in another tab is
162
+ // picked up on the next connection, as before.
163
+ const getToken = () => {
164
+ if (userAuthModule.hasToken()) {
165
+ return currentToken;
166
+ }
167
+ return embedded || !inBrowser ? null : getAccessToken();
168
+ };
169
+ const applyToken = (newToken, saveToStorage) => {
170
+ userAuthModule.setToken(newToken, saveToStorage);
171
+ currentToken = newToken;
172
+ socketConfig.token = newToken;
173
+ if (socket) {
174
+ socket.updateConfig({ token: newToken });
175
+ }
176
+ };
177
+ // Resolves once the embedded session is in hand (or known not to be coming);
178
+ // immediately for every other client. The exchanged token is applied without
179
+ // persisting it: the session must not outlive the frame it was minted for.
180
+ const authReady = embedOtt
181
+ ? exchangeEmbedToken({ serverUrl, appId, ott: embedOtt }).then((sessionToken) => {
182
+ if (sessionToken) {
183
+ applyToken(sessionToken, false);
184
+ }
185
+ })
186
+ : Promise.resolve();
187
+ if (embedOtt) {
188
+ // Requests issued while the exchange is in flight wait for it and carry the
189
+ // session it produces. Registered after createAxiosClient's interceptors,
190
+ // so it runs first and the anonymous-visitor header sees the Authorization.
191
+ for (const client of [axiosClient, functionsAxiosClient]) {
192
+ client.interceptors.request.use(async (requestConfig) => {
193
+ await authReady;
194
+ const sessionToken = getToken();
195
+ if (sessionToken && !requestConfig.headers.get("Authorization")) {
196
+ requestConfig.headers.set("Authorization", `Bearer ${sessionToken}`);
197
+ }
198
+ return requestConfig;
199
+ });
200
+ }
201
+ }
139
202
  const actorsModule = createActorsModule({
140
203
  appId,
141
204
  // serverUrl is often relative/empty (same-origin app); the proxy-fallback
142
205
  // URL needs an absolute host, so fall back to the page origin.
143
206
  host: resolveActorsHost(serverUrl, typeof window !== "undefined" ? (_a = window.location) === null || _a === void 0 ? void 0 : _a.origin : undefined),
144
207
  functionsVersion,
145
- getAuthToken: () => token || getAccessToken(),
208
+ getAuthToken: getToken,
146
209
  mintConnectionToken: async (actorName, room, connectionId) => {
147
- const authToken = token || getAccessToken();
210
+ await authReady;
211
+ const authToken = getToken();
148
212
  return await actorsAxiosClient.post(`/apps/${appId}/actors/${encodeURIComponent(actorName)}/connection-token`, { room, connection_id: connectionId }, {
149
213
  headers: {
150
214
  ...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),
@@ -171,10 +235,9 @@ export function createClient(config) {
171
235
  functions: createFunctionsModule(functionsAxiosClient, appId, {
172
236
  getAuthHeaders: () => {
173
237
  const headers = {};
174
- // Get current token from storage or initial config
175
- const currentToken = token || getAccessToken();
176
- if (currentToken) {
177
- headers["Authorization"] = `Bearer ${currentToken}`;
238
+ const sessionToken = getToken();
239
+ if (sessionToken) {
240
+ headers["Authorization"] = `Bearer ${sessionToken}`;
178
241
  }
179
242
  return headers;
180
243
  },
@@ -185,9 +248,9 @@ export function createClient(config) {
185
248
  getSocket,
186
249
  appId,
187
250
  serverUrl,
188
- token,
251
+ getToken,
189
252
  }),
190
- aiGateway: createAiGatewayModule({ serverUrl, token, appId }),
253
+ aiGateway: createAiGatewayModule({ serverUrl, getToken, appId }),
191
254
  appLogs: createAppLogsModule(axiosClient, appId),
192
255
  app: createAppModule(axiosClient, appId),
193
256
  users: createUsersModule(axiosClient, appId),
@@ -232,9 +295,13 @@ export function createClient(config) {
232
295
  getSocket,
233
296
  appId,
234
297
  serverUrl,
235
- token,
298
+ getToken: () => token,
299
+ }),
300
+ aiGateway: createAiGatewayModule({
301
+ serverUrl,
302
+ getToken: () => serviceToken,
303
+ appId,
236
304
  }),
237
- aiGateway: createAiGatewayModule({ serverUrl, token: serviceToken, appId }),
238
305
  appLogs: createAppLogsModule(serviceRoleAxiosClient, appId),
239
306
  cleanup: () => {
240
307
  if (socket) {
@@ -274,6 +341,7 @@ export function createClient(config) {
274
341
  * Sets a new authentication token for all subsequent requests.
275
342
  *
276
343
  * @param newToken - The new authentication token
344
+ * @param saveToStorage - Whether to also keep the token in local storage. Defaults to `true`.
277
345
  *
278
346
  * @example
279
347
  * ```typescript
@@ -285,14 +353,8 @@ export function createClient(config) {
285
353
  * base44.setToken(access_token);
286
354
  * ```
287
355
  */
288
- setToken(newToken) {
289
- userModules.auth.setToken(newToken);
290
- if (socket) {
291
- socket.updateConfig({
292
- token: newToken,
293
- });
294
- }
295
- socketConfig.token = newToken;
356
+ setToken(newToken, saveToStorage = true) {
357
+ applyToken(newToken, saveToStorage);
296
358
  },
297
359
  /**
298
360
  * Gets the current client configuration.
@@ -200,8 +200,9 @@ export interface Base44Client {
200
200
  * Updates the token for both HTTP requests and WebSocket connections.
201
201
  *
202
202
  * @param newToken - The new authentication token.
203
+ * @param saveToStorage - Whether to also keep the token in local storage so it survives a page load. Defaults to `true`.
203
204
  */
204
- setToken(newToken: string): void;
205
+ setToken(newToken: string, saveToStorage?: boolean): void;
205
206
  /**
206
207
  * Gets the current client configuration.
207
208
  * @internal
@@ -1,2 +1,2 @@
1
1
  import { AgentsModule, AgentsModuleConfig } from "./agents.types.js";
2
- export declare function createAgentsModule({ axios, getSocket, appId, serverUrl, token, }: AgentsModuleConfig): AgentsModule;
2
+ export declare function createAgentsModule({ axios, getSocket, appId, serverUrl, getToken, }: AgentsModuleConfig): AgentsModule;
@@ -1,5 +1,4 @@
1
- import { getAccessToken } from "../utils/auth-utils.js";
2
- export function createAgentsModule({ axios, getSocket, appId, serverUrl, token, }) {
1
+ export function createAgentsModule({ axios, getSocket, appId, serverUrl, getToken, }) {
3
2
  const baseURL = `/apps/${appId}/agents`;
4
3
  // Track active conversations
5
4
  const currentConversations = {};
@@ -56,7 +55,7 @@ export function createAgentsModule({ axios, getSocket, appId, serverUrl, token,
56
55
  };
57
56
  const getWhatsAppConnectURL = (agentName) => {
58
57
  const baseUrl = `${serverUrl}/api/apps/${appId}/agents/${encodeURIComponent(agentName)}/whatsapp`;
59
- const accessToken = token !== null && token !== void 0 ? token : getAccessToken();
58
+ const accessToken = getToken();
60
59
  if (accessToken) {
61
60
  return `${baseUrl}?token=${accessToken}`;
62
61
  }
@@ -67,7 +66,7 @@ export function createAgentsModule({ axios, getSocket, appId, serverUrl, token,
67
66
  };
68
67
  const getTelegramConnectURL = (agentName) => {
69
68
  const baseUrl = `${serverUrl}/api/apps/${appId}/agents/${encodeURIComponent(agentName)}/telegram`;
70
- const accessToken = token !== null && token !== void 0 ? token : getAccessToken();
69
+ const accessToken = getToken();
71
70
  if (accessToken) {
72
71
  return `${baseUrl}?token=${accessToken}`;
73
72
  }
@@ -160,8 +160,8 @@ export interface AgentsModuleConfig {
160
160
  appId: string;
161
161
  /** Server URL */
162
162
  serverUrl?: string;
163
- /** Authentication token */
164
- token?: string;
163
+ /** Returns the current authentication token, if any */
164
+ getToken: () => string | null | undefined;
165
165
  }
166
166
  /**
167
167
  * Agents module for managing AI agent conversations.
@@ -1,2 +1,2 @@
1
1
  import { AiGatewayModule, AiGatewayModuleConfig } from "./ai-gateway.types.js";
2
- export declare function createAiGatewayModule({ serverUrl, token, appId, }: AiGatewayModuleConfig): AiGatewayModule;
2
+ export declare function createAiGatewayModule({ serverUrl, getToken, appId, }: AiGatewayModuleConfig): AiGatewayModule;
@@ -1,10 +1,9 @@
1
- import { getAccessToken } from "../utils/auth-utils.js";
2
- export function createAiGatewayModule({ serverUrl, token, appId, }) {
1
+ export function createAiGatewayModule({ serverUrl, getToken, appId, }) {
3
2
  const connection = () => {
4
3
  var _a;
5
4
  return ({
6
5
  baseURL: `${serverUrl}/api/apps/${appId}/ai/openai/v1`,
7
- token: (_a = token !== null && token !== void 0 ? token : getAccessToken()) !== null && _a !== void 0 ? _a : "",
6
+ token: (_a = getToken()) !== null && _a !== void 0 ? _a : "",
8
7
  });
9
8
  };
10
9
  return {
@@ -17,8 +17,8 @@ export interface AiGatewayConnection {
17
17
  export interface AiGatewayModuleConfig {
18
18
  /** Server URL */
19
19
  serverUrl?: string;
20
- /** Authentication token */
21
- token?: string;
20
+ /** Returns the current authentication token, if any */
21
+ getToken: () => string | null | undefined;
22
22
  /** Application ID */
23
23
  appId: string;
24
24
  }
@@ -1,4 +1,5 @@
1
1
  import { resetAnalyticsSessionContext } from "./analytics.js";
2
+ import { showEmbedSessionEnded } from "../utils/embed-session.js";
2
3
  function isInsideIframe() {
3
4
  if (typeof window === "undefined")
4
5
  return false;
@@ -86,6 +87,9 @@ export function createAuthModule(axios, functionsAxiosClient, appId, options) {
86
87
  hasToken() {
87
88
  return hasAccessToken;
88
89
  },
90
+ isEmbedded() {
91
+ return Boolean(options.embedded);
92
+ },
89
93
  // Get current user information
90
94
  async me() {
91
95
  const request = pendingMe !== null && pendingMe !== void 0 ? pendingMe : axios.get(`/apps/${appId}/entities/User/me`).finally(() => {
@@ -109,6 +113,12 @@ export function createAuthModule(axios, functionsAxiosClient, appId, options) {
109
113
  if (typeof window === "undefined") {
110
114
  throw new Error("Login method can only be used in a browser environment");
111
115
  }
116
+ // An embedded session can only be renewed by the host platform; the
117
+ // login round trip cannot complete inside its frame.
118
+ if (options.embedded) {
119
+ showEmbedSessionEnded();
120
+ return;
121
+ }
112
122
  // If nextUrl is not provided, use the current URL
113
123
  const redirectUrl = nextUrl
114
124
  ? new URL(nextUrl, window.location.origin).toString()
@@ -98,6 +98,11 @@ export interface AuthModuleOptions {
98
98
  * which is how the server-side SDK reports a token it never sets explicitly.
99
99
  */
100
100
  token?: string;
101
+ /**
102
+ * Whether this client runs embedded in a host platform's frame, where a
103
+ * session is minted by the platform and cannot be renewed by a login redirect.
104
+ */
105
+ embedded?: boolean;
101
106
  }
102
107
  /**
103
108
  * Authentication module for managing user authentication and authorization. The module automatically stores tokens in local storage when available and manages authorization headers for API requests.
@@ -179,6 +184,22 @@ export interface AuthModule {
179
184
  * ```
180
185
  */
181
186
  redirectToLogin(nextUrl: string): void;
187
+ /**
188
+ * Whether the app is running embedded in a host platform.
189
+ *
190
+ * A platform embeds an app in an iframe and signs its user in by minting a one-time token onto the frame's URL; the SDK trades it for a session as the client is created. That session is held in memory only and can be renewed only by the platform, so when it ends there is no login page to send the user to — {@linkcode AuthModule.redirectToLogin | redirectToLogin()} shows a "session ended" notice instead. Use this to render your own notice or to hide sign-in and sign-out controls that cannot work inside the frame.
191
+ *
192
+ * @returns `true` when the app was embedded by a host platform, `false` otherwise.
193
+ *
194
+ * @example
195
+ * ```typescript
196
+ * // Show your own message instead of a login screen
197
+ * if (!user && base44.auth.isEmbedded()) {
198
+ * return <SessionEnded />;
199
+ * }
200
+ * ```
201
+ */
202
+ isEmbedded(): boolean;
182
203
  /**
183
204
  * Redirects the user to a third-party authentication provider's login page.
184
205
  *
@@ -5,6 +5,8 @@ import { GetAccessTokenOptions, SaveAccessTokenOptions, RemoveAccessTokenOptions
5
5
  * Low-level utility for manually retrieving tokens. In most cases, the Base44 client handles
6
6
  * token management automatically. This function is useful for custom authentication flows or when you need direct access to stored tokens. Requires a browser environment and can't be used in the backend.
7
7
  *
8
+ * When a host platform has embedded the app with a one-time token (`?ott=`), that token is returned as it stands: it is what {@linkcode createClient} trades for the session, so a page that gates on "is there a token?" as it loads sees one. It is neither stored nor removed from the URL here.
9
+ *
8
10
  * @internal
9
11
  *
10
12
  * @param options - Configuration options for token retrieval.
@@ -1,9 +1,12 @@
1
+ import { EMBED_TOKEN_PARAM } from "./embed-session.js";
1
2
  /**
2
3
  * Retrieves an access token from URL parameters or local storage.
3
4
  *
4
5
  * Low-level utility for manually retrieving tokens. In most cases, the Base44 client handles
5
6
  * token management automatically. This function is useful for custom authentication flows or when you need direct access to stored tokens. Requires a browser environment and can't be used in the backend.
6
7
  *
8
+ * When a host platform has embedded the app with a one-time token (`?ott=`), that token is returned as it stands: it is what {@linkcode createClient} trades for the session, so a page that gates on "is there a token?" as it loads sees one. It is neither stored nor removed from the URL here.
9
+ *
7
10
  * @internal
8
11
  *
9
12
  * @param options - Configuration options for token retrieval.
@@ -56,6 +59,14 @@ export function getAccessToken(options = {}) {
56
59
  }
57
60
  return token;
58
61
  }
62
+ // A platform-embedded load carries a one-time token instead. It is not a
63
+ // session yet — createClient takes it off the URL and exchanges it — but
64
+ // it is the identity this load arrives with, and callers that read this
65
+ // once as the page loads must not conclude there is none.
66
+ const embedToken = urlParams.get(EMBED_TOKEN_PARAM);
67
+ if (embedToken) {
68
+ return embedToken;
69
+ }
59
70
  }
60
71
  catch (e) {
61
72
  console.error("Error retrieving token from URL:", e);
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Sessions for apps embedded in a host platform.
3
+ *
4
+ * The platform's server mints a one-time token for one of its users and puts
5
+ * it on the iframe URL as `?ott=`. The client takes it off the URL as it is
6
+ * created, trades it for an app-user session through the OAuth token-exchange
7
+ * grant (RFC 8693), and keeps the result in memory only — never in storage — so
8
+ * the session lives and dies with the frame.
9
+ *
10
+ * @internal
11
+ */
12
+ /** The query parameter a host platform puts the one-time token on. @internal */
13
+ export declare const EMBED_TOKEN_PARAM = "ott";
14
+ /**
15
+ * Reads the one-time token off the current URL and strips it, so it is never
16
+ * left in the address bar, in history, or in a shared link.
17
+ *
18
+ * @internal
19
+ */
20
+ export declare function takeEmbedTokenFromUrl(): string | null;
21
+ /**
22
+ * Whether this tab previously redeemed an embed token. Counts only inside a
23
+ * frame: a top-level tab that once carried a token must fall back to the
24
+ * regular login, or it could never sign in again.
25
+ *
26
+ * @internal
27
+ */
28
+ export declare function isEmbeddedTab(): boolean;
29
+ /** @internal */
30
+ export declare function markEmbeddedTab(): void;
31
+ /**
32
+ * Trades a one-time embed token for an app-user session token. Resolves to
33
+ * `null` when the platform refuses the token; never throws.
34
+ *
35
+ * @internal
36
+ */
37
+ export declare function exchangeEmbedToken({ serverUrl, appId, ott, fetchImpl, }: {
38
+ serverUrl: string;
39
+ appId: string;
40
+ ott: string;
41
+ fetchImpl?: typeof fetch;
42
+ }): Promise<string | null>;
43
+ /**
44
+ * Covers the page with a plain "session ended" notice. An embedded session can
45
+ * only be renewed by the host platform (by reloading its own page), so this
46
+ * stands in for the login redirect, which cannot complete inside a frame.
47
+ *
48
+ * @internal
49
+ */
50
+ export declare function showEmbedSessionEnded(): void;
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Sessions for apps embedded in a host platform.
3
+ *
4
+ * The platform's server mints a one-time token for one of its users and puts
5
+ * it on the iframe URL as `?ott=`. The client takes it off the URL as it is
6
+ * created, trades it for an app-user session through the OAuth token-exchange
7
+ * grant (RFC 8693), and keeps the result in memory only — never in storage — so
8
+ * the session lives and dies with the frame.
9
+ *
10
+ * @internal
11
+ */
12
+ /** The query parameter a host platform puts the one-time token on. @internal */
13
+ export const EMBED_TOKEN_PARAM = "ott";
14
+ const EMBED_TAB_KEY = "base44_embed_session";
15
+ const GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange";
16
+ const SUBJECT_TOKEN_TYPE = "urn:base44:params:oauth:token-type:embed-ott";
17
+ const RATE_LIMITED = 429;
18
+ const RATE_LIMIT_RETRY_MS = 1000;
19
+ const SESSION_ENDED_ELEMENT_ID = "base44-embed-session-ended";
20
+ /**
21
+ * Reads the one-time token off the current URL and strips it, so it is never
22
+ * left in the address bar, in history, or in a shared link.
23
+ *
24
+ * @internal
25
+ */
26
+ export function takeEmbedTokenFromUrl() {
27
+ if (typeof window === "undefined" || !window.location) {
28
+ return null;
29
+ }
30
+ try {
31
+ const url = new URL(window.location.href);
32
+ const ott = url.searchParams.get(EMBED_TOKEN_PARAM);
33
+ if (!ott) {
34
+ return null;
35
+ }
36
+ url.searchParams.delete(EMBED_TOKEN_PARAM);
37
+ window.history.replaceState(window.history.state, "", url.toString());
38
+ return ott;
39
+ }
40
+ catch (e) {
41
+ console.error("Error retrieving embed token from URL:", e);
42
+ return null;
43
+ }
44
+ }
45
+ /**
46
+ * Whether this tab previously redeemed an embed token. Counts only inside a
47
+ * frame: a top-level tab that once carried a token must fall back to the
48
+ * regular login, or it could never sign in again.
49
+ *
50
+ * @internal
51
+ */
52
+ export function isEmbeddedTab() {
53
+ if (typeof window === "undefined") {
54
+ return false;
55
+ }
56
+ // A cross-site frame is third-party storage, which some browsers block
57
+ // outright — every access can throw, and the marker is then unavailable.
58
+ try {
59
+ return (window.self !== window.top &&
60
+ window.sessionStorage.getItem(EMBED_TAB_KEY) === "1");
61
+ }
62
+ catch (_a) {
63
+ return false;
64
+ }
65
+ }
66
+ /** @internal */
67
+ export function markEmbeddedTab() {
68
+ try {
69
+ window.sessionStorage.setItem(EMBED_TAB_KEY, "1");
70
+ }
71
+ catch (_a) {
72
+ /* storage blocked */
73
+ }
74
+ }
75
+ /**
76
+ * Trades a one-time embed token for an app-user session token. Resolves to
77
+ * `null` when the platform refuses the token; never throws.
78
+ *
79
+ * @internal
80
+ */
81
+ export async function exchangeEmbedToken({ serverUrl, appId, ott, fetchImpl = fetch, }) {
82
+ const post = () => fetchImpl(`${serverUrl}/api/apps/${appId}/auth/embed/token`, {
83
+ method: "POST",
84
+ headers: { "X-App-Id": String(appId) },
85
+ body: new URLSearchParams({
86
+ grant_type: GRANT_TYPE,
87
+ subject_token: ott,
88
+ subject_token_type: SUBJECT_TOKEN_TYPE,
89
+ }),
90
+ });
91
+ try {
92
+ let response = await post();
93
+ // The limiter refuses before the token is redeemed, so it is still valid.
94
+ if (response.status === RATE_LIMITED) {
95
+ await new Promise((resolve) => setTimeout(resolve, RATE_LIMIT_RETRY_MS));
96
+ response = await post();
97
+ }
98
+ if (!response.ok) {
99
+ return null;
100
+ }
101
+ const { access_token: token } = (await response.json());
102
+ return token || null;
103
+ }
104
+ catch (e) {
105
+ console.error("Embed token exchange failed:", e);
106
+ return null;
107
+ }
108
+ }
109
+ /**
110
+ * Covers the page with a plain "session ended" notice. An embedded session can
111
+ * only be renewed by the host platform (by reloading its own page), so this
112
+ * stands in for the login redirect, which cannot complete inside a frame.
113
+ *
114
+ * @internal
115
+ */
116
+ export function showEmbedSessionEnded() {
117
+ if (typeof document === "undefined" || !document.body) {
118
+ return;
119
+ }
120
+ if (document.getElementById(SESSION_ENDED_ELEMENT_ID)) {
121
+ return;
122
+ }
123
+ const overlay = document.createElement("div");
124
+ overlay.id = SESSION_ENDED_ELEMENT_ID;
125
+ overlay.setAttribute("role", "alert");
126
+ overlay.style.cssText =
127
+ "position:fixed;inset:0;z-index:2147483647;display:flex;align-items:center;" +
128
+ "justify-content:center;background:#fff;color:#0f172a;" +
129
+ "font-family:ui-sans-serif,system-ui,sans-serif;text-align:center;padding:2rem;";
130
+ const title = document.createElement("h1");
131
+ title.textContent = "Session ended";
132
+ title.style.cssText = "font-size:1.5rem;font-weight:700;margin:0 0 .75rem;";
133
+ const body = document.createElement("p");
134
+ body.textContent = "Refresh the page to continue.";
135
+ body.style.cssText = "margin:0;color:#475569;";
136
+ const card = document.createElement("div");
137
+ card.append(title, body);
138
+ overlay.append(card);
139
+ document.body.append(overlay);
140
+ }
@@ -4,7 +4,9 @@ export interface RoomsSocketConfig {
4
4
  mountPath: string;
5
5
  transports: string[];
6
6
  appId: string;
7
- token?: string;
7
+ /** `undefined` means unknown — the socket looks in storage; `null` means
8
+ * known to be anonymous, so storage is never consulted. */
9
+ token?: string | null;
8
10
  }
9
11
  export type TSocketRoom = string;
10
12
  export type TJsonStr = string;
@@ -3,12 +3,11 @@ import { getAccessToken } from "./auth-utils.js";
3
3
  import { getAnalyticsSessionId } from "../modules/analytics.js";
4
4
  const ROOM_LEAVE_GRACE_MS = 250;
5
5
  function initializeSocket(config, handlers) {
6
- var _a;
7
6
  // On unauthenticated clients, send a stable anonymous visitor id on the
8
7
  // handshake so the backend can verify room access for anonymous agent
9
8
  // conversations (mirrors the X-Base44-Anonymous-Id HTTP header). Authenticated
10
9
  // clients are identified by their token instead.
11
- const resolvedToken = (_a = config.token) !== null && _a !== void 0 ? _a : getAccessToken();
10
+ const resolvedToken = config.token === undefined ? getAccessToken() : config.token;
12
11
  const query = {
13
12
  app_id: config.appId,
14
13
  token: resolvedToken,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@base44-preview/sdk",
3
- "version": "0.8.48-pr.281.97e1467",
3
+ "version": "0.8.48-pr.282.8affbe6",
4
4
  "description": "JavaScript SDK for Base44 API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",