first commit

This commit is contained in:
2026-06-24 09:48:54 +02:00
commit 41e62ddcad
33739 changed files with 4266226 additions and 0 deletions
+117
View File
@@ -0,0 +1,117 @@
import { GetAccessTokenOptions, SaveAccessTokenOptions, RemoveAccessTokenOptions, GetLoginUrlOptions } from "./auth-utils.types.js";
/**
* Retrieves an access token from URL parameters or local storage.
*
* Low-level utility for manually retrieving tokens. In most cases, the Base44 client handles
* 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.
*
* @internal
*
* @param options - Configuration options for token retrieval.
* @returns The access token string if found, null otherwise.
*
* @example
* ```typescript
* // Get access token from URL or local storage
* const token = getAccessToken();
*
* if (token) {
* console.log('User is authenticated');
* } else {
* console.log('No token found, redirect to login');
* }
* ```
* @example
* ```typescript
* // Get access token from custom local storage key
* const token = getAccessToken({ storageKey: 'my_app_token' });
* ```
* @example
* ```typescript
* // Get access token from URL but don't save or remove it
* const token = getAccessToken({
* saveToStorage: false,
* removeFromUrl: false
* });
* ```
*/
export declare function getAccessToken(options?: GetAccessTokenOptions): string | null;
/**
* Saves an access token to local storage.
*
* Low-level utility for manually saving tokens. In most cases, the Base44 client handles token management automatically. This function is useful for custom authentication flows or managing custom tokens. Requires a browser environment and can't be used in the backend.
*
* @internal
*
* @param token - The access token string to save.
* @param options - Configuration options for saving the token.
* @returns Returns`true` if the token was saved successfully, `false` otherwise.
*
* @example
* ```typescript
* // Save access token after login
* const response = await base44.auth.loginViaEmailPassword(email, password);
* const success = saveAccessToken(response.access_token, {});
*
* if (success) {
* console.log('User is now authenticated');
* // Token is now available for future page loads
* }
* ```
* @example
* ```typescript
* // Save access token to local storage using custom key
* const success = saveAccessToken(token, {
* storageKey: `my_custom_token_key`
* });
* ```
*/
export declare function saveAccessToken(token: string, options: SaveAccessTokenOptions): boolean;
/**
* Removes the access token from local storage.
*
* Low-level utility for manually removing tokens from the browser's local storage. In most cases, the Base44 client handles token management automatically. For standard logout flows, use {@linkcode AuthModule.logout | base44.auth.logout()} instead, which handles token removal and redirects automatically. This function is useful for custom authentication flows or when you need to manually remove tokens. Requires a browser environment and can't be used in the backend.
*
* @internal
*
* @param options - Configuration options for token removal.
* @returns Returns `true` if the token was removed successfully, `false` otherwise.
*
* @example
* ```typescript
* // Remove custom token key
* const success = removeAccessToken({
* storageKey: 'my_custom_token_key'
* });
* ```
*
* @example
* ```typescript
* // Standard logout flow with token removal and redirect
* base44.auth.logout('/login');
* ```
*/
export declare function removeAccessToken(options: RemoveAccessTokenOptions): boolean;
/**
* Constructs the absolute URL for the login page with a redirect parameter.
*
* Low-level utility for building login URLs. For standard login redirects, use {@linkcode AuthModule.redirectToLogin | base44.auth.redirectToLogin()} instead, which handles this automatically. This function is useful when you need to construct login URLs without a client instance or for custom authentication flows.
*
* @internal
*
* @param nextUrl - The URL to redirect to after successful login.
* @param options - Configuration options.
* @returns The complete login URL with encoded redirect parameters.
*
* @example
* ```typescript
* // Redirect to login page
* const loginUrl = getLoginUrl('/dashboard', {
* serverUrl: 'https://base44.app',
* appId: 'my-app-123'
* });
* window.location.href = loginUrl;
* // User will be redirected back to /dashboard after login
* ```
*/
export declare function getLoginUrl(nextUrl: string, options: GetLoginUrlOptions): string;
+189
View File
@@ -0,0 +1,189 @@
/**
* Retrieves an access token from URL parameters or local storage.
*
* Low-level utility for manually retrieving tokens. In most cases, the Base44 client handles
* 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.
*
* @internal
*
* @param options - Configuration options for token retrieval.
* @returns The access token string if found, null otherwise.
*
* @example
* ```typescript
* // Get access token from URL or local storage
* const token = getAccessToken();
*
* if (token) {
* console.log('User is authenticated');
* } else {
* console.log('No token found, redirect to login');
* }
* ```
* @example
* ```typescript
* // Get access token from custom local storage key
* const token = getAccessToken({ storageKey: 'my_app_token' });
* ```
* @example
* ```typescript
* // Get access token from URL but don't save or remove it
* const token = getAccessToken({
* saveToStorage: false,
* removeFromUrl: false
* });
* ```
*/
export function getAccessToken(options = {}) {
const { storageKey = "base44_access_token", paramName = "access_token", saveToStorage = true, removeFromUrl = true, } = options;
let token = null;
// Try to get token from URL parameters
if (typeof window !== "undefined" && window.location) {
try {
const urlParams = new URLSearchParams(window.location.search);
token = urlParams.get(paramName);
// If token found in URL
if (token) {
// Save token to local storage if requested
if (saveToStorage) {
saveAccessToken(token, { storageKey });
}
// Remove token from URL for security if requested
if (removeFromUrl) {
urlParams.delete(paramName);
const newUrl = `${window.location.pathname}${urlParams.toString() ? `?${urlParams.toString()}` : ""}${window.location.hash}`;
window.history.replaceState({}, document.title, newUrl);
}
return token;
}
}
catch (e) {
console.error("Error retrieving token from URL:", e);
}
}
// If no token in URL, try local storage
if (typeof window !== "undefined" && window.localStorage) {
try {
token = window.localStorage.getItem(storageKey);
return token;
}
catch (e) {
console.error("Error retrieving token from local storage:", e);
}
}
return null;
}
/**
* Saves an access token to local storage.
*
* Low-level utility for manually saving tokens. In most cases, the Base44 client handles token management automatically. This function is useful for custom authentication flows or managing custom tokens. Requires a browser environment and can't be used in the backend.
*
* @internal
*
* @param token - The access token string to save.
* @param options - Configuration options for saving the token.
* @returns Returns`true` if the token was saved successfully, `false` otherwise.
*
* @example
* ```typescript
* // Save access token after login
* const response = await base44.auth.loginViaEmailPassword(email, password);
* const success = saveAccessToken(response.access_token, {});
*
* if (success) {
* console.log('User is now authenticated');
* // Token is now available for future page loads
* }
* ```
* @example
* ```typescript
* // Save access token to local storage using custom key
* const success = saveAccessToken(token, {
* storageKey: `my_custom_token_key`
* });
* ```
*/
export function saveAccessToken(token, options) {
const { storageKey = "base44_access_token" } = options;
if (typeof window === "undefined" || !window.localStorage || !token) {
return false;
}
try {
window.localStorage.setItem(storageKey, token);
// Set "token" that is set by the built-in SDK of platform version 2
window.localStorage.setItem("token", token);
return true;
}
catch (e) {
console.error("Error saving token to local storage:", e);
return false;
}
}
/**
* Removes the access token from local storage.
*
* Low-level utility for manually removing tokens from the browser's local storage. In most cases, the Base44 client handles token management automatically. For standard logout flows, use {@linkcode AuthModule.logout | base44.auth.logout()} instead, which handles token removal and redirects automatically. This function is useful for custom authentication flows or when you need to manually remove tokens. Requires a browser environment and can't be used in the backend.
*
* @internal
*
* @param options - Configuration options for token removal.
* @returns Returns `true` if the token was removed successfully, `false` otherwise.
*
* @example
* ```typescript
* // Remove custom token key
* const success = removeAccessToken({
* storageKey: 'my_custom_token_key'
* });
* ```
*
* @example
* ```typescript
* // Standard logout flow with token removal and redirect
* base44.auth.logout('/login');
* ```
*/
export function removeAccessToken(options) {
const { storageKey = "base44_access_token" } = options;
if (typeof window === "undefined" || !window.localStorage) {
return false;
}
try {
window.localStorage.removeItem(storageKey);
return true;
}
catch (e) {
console.error("Error removing token from local storage:", e);
return false;
}
}
/**
* Constructs the absolute URL for the login page with a redirect parameter.
*
* Low-level utility for building login URLs. For standard login redirects, use {@linkcode AuthModule.redirectToLogin | base44.auth.redirectToLogin()} instead, which handles this automatically. This function is useful when you need to construct login URLs without a client instance or for custom authentication flows.
*
* @internal
*
* @param nextUrl - The URL to redirect to after successful login.
* @param options - Configuration options.
* @returns The complete login URL with encoded redirect parameters.
*
* @example
* ```typescript
* // Redirect to login page
* const loginUrl = getLoginUrl('/dashboard', {
* serverUrl: 'https://base44.app',
* appId: 'my-app-123'
* });
* window.location.href = loginUrl;
* // User will be redirected back to /dashboard after login
* ```
*/
export function getLoginUrl(nextUrl, options) {
const { serverUrl, appId, loginPath = "/login" } = options;
if (!serverUrl || !appId) {
throw new Error("serverUrl and appId are required to construct login URL");
}
const encodedRedirectUrl = encodeURIComponent(nextUrl || (typeof window !== "undefined" ? window.location.href : ""));
return `${serverUrl}${loginPath}?from_url=${encodedRedirectUrl}&app_id=${appId}`;
}
+146
View File
@@ -0,0 +1,146 @@
/**
* Configuration options for retrieving an access token.
*
* @internal
*
* @example
* ```typescript
* // Get access token from URL or local storage using default options
* const token = getAccessToken();
* ```
*
* @example
* ```typescript
* // Get access token from custom local storage key
* const token = getAccessToken({ storageKey: 'my_app_token' });
* ```
*
* @example
* ```typescript
* // Get token from URL but don't save or remove from URL
* const token = getAccessToken({
* saveToStorage: false,
* removeFromUrl: false
* });
* ```
*/
export interface GetAccessTokenOptions {
/**
* The key to use when storing or retrieving the token in local storage.
* @default 'base44_access_token'
*/
storageKey?: string;
/**
* The URL parameter name to check for the access token.
* @default 'access_token'
*/
paramName?: string;
/**
* Whether to save the token to local storage if found in the URL.
* @default true
*/
saveToStorage?: boolean;
/**
* Whether to remove the token from the URL after retrieval for security.
* @default true
*/
removeFromUrl?: boolean;
}
/**
* Configuration options for saving an access token.
*
* @internal
*
* @example
* ```typescript
* // Use default storage key
* saveAccessToken('my-token-123', {});
*
* // Use custom storage key
* saveAccessToken('my-token-123', { storageKey: 'my_app_token' });
* ```
*/
export interface SaveAccessTokenOptions {
/**
* The key to use when storing the token in local storage.
* @default 'base44_access_token'
*/
storageKey?: string;
}
/**
* Configuration options for removing an access token.
*
* @internal
*
* @example
* ```typescript
* // Remove token from default storage key
* removeAccessToken({});
*
* // Remove token from custom storage key
* removeAccessToken({ storageKey: 'my_app_token' });
* ```
*/
export interface RemoveAccessTokenOptions {
/**
* The key to use when removing the token from local storage.
* @default 'base44_access_token'
*/
storageKey?: string;
}
/**
* Configuration options for constructing a login URL.
*
* @internal
*
* @example
* ```typescript
* const loginUrl = getLoginUrl('/dashboard', {
* serverUrl: 'https://base44.app',
* appId: 'my-app-123'
* });
* // Returns: 'https://base44.app/login?from_url=%2Fdashboard&app_id=my-app-123'
*
* // Custom login path
* const loginUrl = getLoginUrl('/dashboard', {
* serverUrl: 'https://base44.app',
* appId: 'my-app-123',
* loginPath: '/auth/login'
* });
* ```
*/
export interface GetLoginUrlOptions {
/**
* The base server URL (e.g., 'https://base44.app').
*/
serverUrl: string;
/**
* The app ID.
*/
appId: string;
/**
* The path to the login endpoint.
* @default '/login'
*/
loginPath?: string;
}
/**
* Type definition for getAccessToken function.
* @internal
*/
export type GetAccessTokenFunction = (options?: GetAccessTokenOptions) => string | null;
/**
* Type definition for saveAccessToken function.
* @internal
*/
export type SaveAccessTokenFunction = (token: string, options: SaveAccessTokenOptions) => boolean;
/**
* Type definition for removeAccessToken function.
* @internal
*/
export type RemoveAccessTokenFunction = (options: RemoveAccessTokenOptions) => boolean;
/**
* Type definition for getLoginUrl function.
* @internal
*/
export type GetLoginUrlFunction = (nextUrl: string, options: GetLoginUrlOptions) => string;
+1
View File
@@ -0,0 +1 @@
export {};
+100
View File
@@ -0,0 +1,100 @@
import type { Base44ErrorJSON } from "./axios-client.types.js";
/**
* Custom error class for Base44 SDK errors.
*
* This error is thrown when API requests fail. It extends the standard `Error` class and includes additional information about the HTTP status, error code, and response data from the server.
*
* @example
* ```typescript
* try {
* await client.entities.Todo.get('invalid-id');
* } catch (error) {
* if (error instanceof Base44Error) {
* console.error('Status:', error.status); // 404
* console.error('Message:', error.message); // "Not found"
* console.error('Code:', error.code); // "NOT_FOUND"
* console.error('Data:', error.data); // Full response data
* }
* }
* ```
*
*/
export declare class Base44Error extends Error {
/**
* HTTP status code of the error.
*/
status: number;
/**
* Error code from the API.
*/
code: string;
/**
* Full response data from the server containing error details.
*/
data: any;
/**
* The original error object from Axios.
*/
originalError: unknown;
/**
* Creates a new Base44Error instance.
*
* @param message - Human-readable error message
* @param status - HTTP status code
* @param code - Error code from the API
* @param data - Full response data from the server
* @param originalError - Original axios error object
* @internal
*/
constructor(message: string, status: number, code: string, data: any, originalError: unknown);
/**
* Serializes the error to a JSON-safe object.
*
* Useful for logging or sending error information to external services
* without circular reference issues.
*
* @returns JSON-safe representation of the error.
*
* @example
* ```typescript
* try {
* await client.entities.Todo.get('invalid-id');
* } catch (error) {
* if (error instanceof Base44Error) {
* const json = error.toJSON();
* console.log(json);
* // {
* // name: "Base44Error",
* // message: "Not found",
* // status: 404,
* // code: "NOT_FOUND",
* // data: { ... }
* // }
* }
* }
* ```
*/
toJSON(): Base44ErrorJSON;
}
/**
* Creates an axios client with default configuration and interceptors.
*
* Sets up an axios instance with:
* - Default headers
* - Authentication token injection
* - Response data unwrapping
* - Error transformation to Base44Error
* - iframe messaging support
*
* @param options - Client configuration options
* @returns Configured axios instance
* @internal
*/
export declare function createAxiosClient({ baseURL, headers, token, interceptResponses, onError, }: {
baseURL: string;
headers?: Record<string, string>;
token?: string;
interceptResponses?: boolean;
onError?: (error: Error) => void;
}): import("axios").AxiosInstance;
export type { Base44ErrorJSON } from "./axios-client.types.js";
+193
View File
@@ -0,0 +1,193 @@
import axios from "axios";
import { isInIFrame } from "./common.js";
import { v4 as uuidv4 } from "uuid";
/**
* Custom error class for Base44 SDK errors.
*
* This error is thrown when API requests fail. It extends the standard `Error` class and includes additional information about the HTTP status, error code, and response data from the server.
*
* @example
* ```typescript
* try {
* await client.entities.Todo.get('invalid-id');
* } catch (error) {
* if (error instanceof Base44Error) {
* console.error('Status:', error.status); // 404
* console.error('Message:', error.message); // "Not found"
* console.error('Code:', error.code); // "NOT_FOUND"
* console.error('Data:', error.data); // Full response data
* }
* }
* ```
*
*/
export class Base44Error extends Error {
/**
* Creates a new Base44Error instance.
*
* @param message - Human-readable error message
* @param status - HTTP status code
* @param code - Error code from the API
* @param data - Full response data from the server
* @param originalError - Original axios error object
* @internal
*/
constructor(message, status, code, data, originalError) {
super(message);
this.name = "Base44Error";
this.status = status;
this.code = code;
this.data = data;
this.originalError = originalError;
}
/**
* Serializes the error to a JSON-safe object.
*
* Useful for logging or sending error information to external services
* without circular reference issues.
*
* @returns JSON-safe representation of the error.
*
* @example
* ```typescript
* try {
* await client.entities.Todo.get('invalid-id');
* } catch (error) {
* if (error instanceof Base44Error) {
* const json = error.toJSON();
* console.log(json);
* // {
* // name: "Base44Error",
* // message: "Not found",
* // status: 404,
* // code: "NOT_FOUND",
* // data: { ... }
* // }
* }
* }
* ```
*/
toJSON() {
return {
name: this.name,
message: this.message,
status: this.status,
code: this.code,
data: this.data,
};
}
}
/**
* Safely logs error information without circular references.
*
* @param prefix - Prefix for the log message
* @param error - The error to log
* @internal
*/
function safeErrorLog(prefix, error) {
if (error instanceof Base44Error) {
console.error(`${prefix} ${error.status}: ${error.message}`);
if (error.data) {
try {
console.error("Error data:", JSON.stringify(error.data, null, 2));
}
catch (e) {
console.error("Error data: [Cannot stringify error data]");
}
}
}
else {
console.error(`${prefix} ${error instanceof Error ? error.message : String(error)}`);
}
}
/**
* Creates an axios client with default configuration and interceptors.
*
* Sets up an axios instance with:
* - Default headers
* - Authentication token injection
* - Response data unwrapping
* - Error transformation to Base44Error
* - iframe messaging support
*
* @param options - Client configuration options
* @returns Configured axios instance
* @internal
*/
export function createAxiosClient({ baseURL, headers = {}, token, interceptResponses = true, onError, }) {
const client = axios.create({
baseURL,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
...headers,
},
});
// Add token to requests if available
if (token) {
client.defaults.headers.common["Authorization"] = `Bearer ${token}`;
}
// Add origin URL in browser environment
client.interceptors.request.use((config) => {
if (typeof window !== "undefined") {
config.headers.set("X-Origin-URL", window.location.href);
}
const requestId = uuidv4();
config.requestId = requestId;
if (isInIFrame) {
try {
window.parent.postMessage({
type: "api-request-start",
requestId,
data: {
url: baseURL + config.url,
method: config.method,
body: config.data instanceof FormData
? "[FormData object]"
: config.data,
},
}, "*");
}
catch (_a) {
/* skip the logging */
}
}
return config;
});
// Handle responses
if (interceptResponses) {
client.interceptors.response.use((response) => {
var _a;
const requestId = (_a = response.config) === null || _a === void 0 ? void 0 : _a.requestId;
try {
if (isInIFrame && requestId) {
window.parent.postMessage({
type: "api-request-end",
requestId,
data: {
statusCode: response.status,
response: response.data,
},
}, "*");
}
}
catch (_b) {
/* do nothing */
}
return response.data;
}, (error) => {
var _a, _b, _c, _d, _e, _f, _g, _h;
const message = ((_b = (_a = error.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.message) ||
((_d = (_c = error.response) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.detail) ||
error.message;
const base44Error = new Base44Error(message, (_e = error.response) === null || _e === void 0 ? void 0 : _e.status, (_g = (_f = error.response) === null || _f === void 0 ? void 0 : _f.data) === null || _g === void 0 ? void 0 : _g.code, (_h = error.response) === null || _h === void 0 ? void 0 : _h.data, error);
// Log errors in development
if (process.env.NODE_ENV !== "production") {
safeErrorLog("[Base44 SDK Error]", base44Error);
}
onError === null || onError === void 0 ? void 0 : onError(base44Error);
return Promise.reject(base44Error);
});
}
return client;
}
+28
View File
@@ -0,0 +1,28 @@
/**
* JSON representation of a Base44Error.
*
* This is the structure returned by {@linkcode Base44Error.toJSON | Base44Error.toJSON()}.
* Useful for logging or sending error information to external services.
*/
export interface Base44ErrorJSON {
/**
* The error name, always "Base44Error".
*/
name: string;
/**
* Human-readable error message.
*/
message: string;
/**
* HTTP status code of the error.
*/
status: number;
/**
* Error code from the API.
*/
code: string;
/**
* Full response data from the server containing error details.
*/
data: any;
}
+1
View File
@@ -0,0 +1 @@
export {};
+3
View File
@@ -0,0 +1,3 @@
export declare const isNode: boolean;
export declare const isInIFrame: boolean;
export declare const generateUuid: () => string;
+6
View File
@@ -0,0 +1,6 @@
export const isNode = typeof window === "undefined";
export const isInIFrame = !isNode && window.self !== window.top;
export const generateUuid = () => {
return (Math.random().toString(36).substring(2, 15) +
Math.random().toString(36).substring(2, 15));
};
+1
View File
@@ -0,0 +1 @@
export declare function getSharedInstance<T>(name: string, factory: () => T): T;
+15
View File
@@ -0,0 +1,15 @@
const windowObj = typeof window !== "undefined"
? window
: { base44SharedInstances: {} };
// Singleton (shared between sdk instances)//
export function getSharedInstance(name, factory) {
if (!windowObj.base44SharedInstances) {
windowObj.base44SharedInstances = {};
}
if (!windowObj.base44SharedInstances[name]) {
windowObj.base44SharedInstances[name] = {
instance: factory(),
};
}
return windowObj.base44SharedInstances[name].instance;
}
+47
View File
@@ -0,0 +1,47 @@
import { Socket } from "socket.io-client";
export interface RoomsSocketConfig {
serverUrl: string;
mountPath: string;
transports: string[];
appId: string;
token?: string;
}
export type TSocketRoom = string;
export type TJsonStr = string;
type RoomsSocketEventsMap = {
listen: {
connect: () => Promise<void> | void;
update_model: (msg: {
room: string;
data: TJsonStr;
}) => Promise<void> | void;
error: (error: Error) => Promise<void> | void;
};
emit: {
join: (room: string) => void;
leave: (room: string) => void;
};
};
type TEvent = keyof RoomsSocketEventsMap["listen"];
type THandler<E extends TEvent> = RoomsSocketEventsMap["listen"][E];
export type RoomsSocket = ReturnType<typeof RoomsSocket>;
export declare function RoomsSocket({ config }: {
config: RoomsSocketConfig;
}): {
socket: Socket<{
connect: () => Promise<void> | void;
update_model: (msg: {
room: string;
data: TJsonStr;
}) => Promise<void> | void;
error: (error: Error) => Promise<void> | void;
}, {
join: (room: string) => void;
leave: (room: string) => void;
}>;
subscribeToRoom: (room: TSocketRoom, handlers: Partial<{ [k in TEvent]: THandler<k>; }>) => () => void;
updateConfig: (config: Partial<RoomsSocketConfig>) => void;
updateModel: (room: string, data: any) => Promise<void>;
disconnect: () => void;
};
export {};
+160
View File
@@ -0,0 +1,160 @@
import { io } from "socket.io-client";
import { getAccessToken } from "./auth-utils.js";
const ROOM_LEAVE_GRACE_MS = 250;
function initializeSocket(config, handlers) {
var _a;
const socket = io(config.serverUrl, {
path: config.mountPath,
transports: config.transports,
query: {
app_id: config.appId,
token: (_a = config.token) !== null && _a !== void 0 ? _a : getAccessToken(),
},
});
socket.on("connect", async () => {
var _a;
console.log("connect", socket.id);
return (_a = handlers.connect) === null || _a === void 0 ? void 0 : _a.call(handlers);
});
socket.on("update_model", async (msg) => {
var _a;
return (_a = handlers.update_model) === null || _a === void 0 ? void 0 : _a.call(handlers, msg);
});
socket.on("error", async (error) => {
var _a;
return (_a = handlers.error) === null || _a === void 0 ? void 0 : _a.call(handlers, error);
});
socket.on("connect_error", async (error) => {
var _a;
console.error("connect_error", error);
return (_a = handlers.error) === null || _a === void 0 ? void 0 : _a.call(handlers, error);
});
return socket;
}
export function RoomsSocket({ config }) {
let currentConfig = { ...config };
const roomsToListeners = {};
const pendingRoomLeaves = {};
const handlers = {
connect: async () => {
const promises = [];
Object.keys(roomsToListeners).forEach((room) => {
const listeners = getListeners(room);
if (listeners.length === 0) {
return;
}
joinRoom(room);
listeners.forEach(({ connect }) => {
const promise = async () => connect === null || connect === void 0 ? void 0 : connect();
promises.push(promise());
});
});
await Promise.all(promises);
},
update_model: async (msg) => {
const listeners = getListeners(msg.room);
const promises = listeners.map((listener) => { var _a; return (_a = listener.update_model) === null || _a === void 0 ? void 0 : _a.call(listener, msg); });
await Promise.all(promises);
},
error: async (error) => {
console.error("error", error);
const promises = Object.values(roomsToListeners)
.flat()
.map((listener) => { var _a; return (_a = listener.error) === null || _a === void 0 ? void 0 : _a.call(listener, error); });
await Promise.all(promises);
},
};
let socket = initializeSocket(config, handlers);
function cleanup() {
disconnect();
}
function disconnect() {
clearPendingRoomLeaves();
if (socket) {
socket.disconnect();
}
}
function updateConfig(config) {
cleanup();
currentConfig = {
...currentConfig,
...config,
};
socket = initializeSocket(currentConfig, handlers);
}
function joinRoom(room) {
socket.emit("join", room);
}
function leaveRoom(room) {
socket.emit("leave", room);
}
async function updateModel(room, data) {
var _a;
const dataStr = JSON.stringify(data);
return (_a = handlers.update_model) === null || _a === void 0 ? void 0 : _a.call(handlers, { room, data: dataStr });
}
function getListeners(room) {
var _a;
return (_a = roomsToListeners[room]) !== null && _a !== void 0 ? _a : [];
}
function cancelPendingRoomLeave(room) {
const pendingLeave = pendingRoomLeaves[room];
if (!pendingLeave) {
return;
}
clearTimeout(pendingLeave);
delete pendingRoomLeaves[room];
}
function clearPendingRoomLeaves() {
Object.keys(pendingRoomLeaves).forEach((room) => {
var _a, _b;
clearTimeout(pendingRoomLeaves[room]);
delete pendingRoomLeaves[room];
if (((_b = (_a = roomsToListeners[room]) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) === 0) {
delete roomsToListeners[room];
}
});
}
function scheduleRoomLeave(room) {
cancelPendingRoomLeave(room);
pendingRoomLeaves[room] = setTimeout(() => {
var _a, _b;
delete pendingRoomLeaves[room];
if (((_b = (_a = roomsToListeners[room]) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) > 0) {
return;
}
leaveRoom(room);
delete roomsToListeners[room];
}, ROOM_LEAVE_GRACE_MS);
}
const subscribeToRoom = (room, handlers) => {
if (roomsToListeners[room]) {
cancelPendingRoomLeave(room);
}
else {
joinRoom(room);
roomsToListeners[room] = [];
}
roomsToListeners[room].push(handlers);
let unsubscribed = false;
return () => {
var _a, _b;
if (unsubscribed) {
return;
}
unsubscribed = true;
roomsToListeners[room] =
(_b = (_a = roomsToListeners[room]) === null || _a === void 0 ? void 0 : _a.filter((listener) => listener !== handlers)) !== null && _b !== void 0 ? _b : [];
if (roomsToListeners[room].length === 0) {
scheduleRoomLeave(room);
}
};
};
return {
socket,
subscribeToRoom,
updateConfig,
updateModel,
disconnect,
};
}