Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 22 additions & 30 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
},
"dependencies": {
"axios": "^1.17.0",
"partysocket": "^0.0.23",
"socket.io-client": "^4.8.3",
"uuid": "^13.0.2"
},
Expand Down
24 changes: 24 additions & 0 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import type {
CreateClientOptions,
} from "./client.types.js";
import { createAnalyticsModule } from "./modules/analytics.js";
import { createRealtimeModule } from "./modules/realtime.js";

// Re-export client types
export type { Base44Client, CreateClientConfig, CreateClientOptions };
Expand Down Expand Up @@ -71,11 +72,22 @@ export function createClient(config: CreateClientConfig): Base44Client {
options,
functionsVersion,
headers: optionalHeaders,
dispatcherWsUrl,
} = config;

// Normalize appBaseUrl to always be a string (empty if not provided or invalid)
const normalizedAppBaseUrl = typeof appBaseUrl === "string" ? appBaseUrl : "";

// Derive the dispatcher WebSocket URL from serverUrl if not explicitly provided.
// Convert https:// → wss:// (or http:// → ws://) and strip trailing slash.
const resolvedDispatcherWsUrl = (() => {
if (dispatcherWsUrl) return dispatcherWsUrl.replace(/\/$/, "");
return serverUrl
.replace(/\/$/, "")
.replace(/^https:\/\//, "wss://")
.replace(/^http:\/\//, "ws://");
})();

const socketConfig: RoomsSocketConfig = {
serverUrl,
mountPath: "/ws-user-apps/socket.io/",
Expand Down Expand Up @@ -198,6 +210,18 @@ export function createClient(config: CreateClientConfig): Base44Client {
appId,
userAuthModule,
}),
realtime: createRealtimeModule({
appId,
dispatcherWsUrl: resolvedDispatcherWsUrl,
getToken: async (handlerName, instanceId) => {
// axiosClient interceptors unwrap response.data, so the result is the body directly
const data = await axiosClient.post<any, { token: string }>(
`/apps/${appId}/realtime-token`,
{ handler_name: handlerName, instance_id: instanceId }
);
return data.token;
},
}),
cleanup: () => {
userModules.analytics.cleanup();
if (socket) {
Expand Down
10 changes: 10 additions & 0 deletions src/client.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type { FunctionsModule } from "./modules/functions.types.js";
import type { AgentsModule } from "./modules/agents.types.js";
import type { AppLogsModule } from "./modules/app-logs.types.js";
import type { AnalyticsModule } from "./modules/analytics.types.js";
import type { RealtimeModule } from "./modules/realtime.types.js";

/**
* Options for creating a Base44 client.
Expand Down Expand Up @@ -77,6 +78,13 @@ export interface CreateClientConfig {
* Additional client options.
*/
options?: CreateClientOptions;
/**
* Base WebSocket URL for the Cloudflare Durable Object dispatcher.
*
* Defaults to the `serverUrl` with `https://` replaced by `wss://` (or `http://` by `ws://`).
* Override when the dispatcher lives at a different host than the API.
*/
dispatcherWsUrl?: string;
}

/**
Expand All @@ -91,6 +99,8 @@ export interface Base44Client {
analytics: AnalyticsModule;
/** {@link AppLogsModule | App logs module} for tracking app usage. */
appLogs: AppLogsModule;
/** {@link RealtimeModule | Realtime module} for subscribing to and sending messages via Cloudflare Durable Object-backed RealtimeHandlers. */
realtime: RealtimeModule;
/** {@link AuthModule | Auth module} for user authentication and management. */
auth: AuthModule;
/** {@link UserConnectorsModule | Connectors module} for app-user OAuth flows. */
Expand Down
9 changes: 9 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,17 @@ export type {

export type { AppLogsModule } from "./modules/app-logs.types.js";

export type {
RealtimeModule,
RealtimeHandlerClient,
RealtimeHandlerNameRegistry,
RealtimeHandlerRegistry,
} from "./modules/realtime.types.js";

export type { SsoModule, SsoAccessTokenResponse } from "./modules/sso.types.js";

export { RealtimeHandler, type Conn } from "./realtime-handler.js";

export type {
ConnectorsModule,
UserConnectorsModule,
Expand Down
92 changes: 92 additions & 0 deletions src/modules/realtime.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import PartySocket from "partysocket";

// Module-level map: "HandlerName:instanceId" → active socket
const activeSockets = new Map<string, PartySocket>();

function socketKey(handlerName: string, instanceId: string) {
return `${handlerName}:${instanceId}`;
}

export function createRealtimeModule(config: {
appId: string;
getToken(handlerName: string, instanceId: string): Promise<string>;
dispatcherWsUrl: string;
}) {
return new Proxy({} as Record<string, RealtimeHandler>, {
get(_, handlerName: string) {
return {
subscribe(instanceId: string, callback: (data: unknown) => void): () => void {
const key = socketKey(handlerName, instanceId);
// close existing if any
activeSockets.get(key)?.close();

// query as async fn: called on every (re)connect, fetches a fresh token each time
const ws = new PartySocket({
host: config.dispatcherWsUrl,
party: handlerName,
room: instanceId,
query: () => config.getToken(handlerName, instanceId).then((token) => ({ token })),
});

activeSockets.set(key, ws);

// Heartbeat / half-open detection. PartySocket only reconnects on a
// browser close/error event, so a silently-dead connection (TCP alive,
// no data — common behind proxies/LBs) hangs until the OS idle timeout
// (~60s). We ping periodically and force a reconnect if nothing comes
// back within DEAD_MS, cutting detection from ~60s to a few seconds.
// Pairs with the handler's setWebSocketAutoResponse("__ping"→"__pong"),
// so idle handlers (no app broadcasts) still keep the connection proven.
const PING_MS = 1_000;
const DEAD_MS = 3_000;
let lastMsg = Date.now();
const bumpAlive = () => { lastMsg = Date.now(); };

ws.addEventListener("open", bumpAlive);
ws.addEventListener("message", (ev) => {
bumpAlive();
let data: unknown;
try {
data = JSON.parse(ev.data);
} catch {
return; // ignore malformed
}
// Swallow heartbeat acks — never surface them to the app.
if (data && typeof data === "object" && (data as { type?: unknown }).type === "__pong") return;
callback(data);
});

const heartbeat = setInterval(() => {
if (Date.now() - lastMsg > DEAD_MS) {
bumpAlive(); // avoid a reconnect storm while the new socket comes up
ws.reconnect();
return;
}
try {
ws.send(JSON.stringify({ type: "__ping" }));
} catch {
// socket not open; the watchdog above will force a reconnect
}
}, PING_MS);

return () => {
clearInterval(heartbeat);
activeSockets.delete(key);
ws.close();
};
},
send(instanceId: string, data: unknown) {
const key = socketKey(handlerName, instanceId);
const ws = activeSockets.get(key);
if (!ws) throw new Error(`No active subscription for ${handlerName}:${instanceId}`);
ws.send(JSON.stringify(data));
},
};
},
});
}

interface RealtimeHandler {
subscribe(instanceId: string, callback: (data: unknown) => void): () => void;
send(instanceId: string, data: unknown): void;
}
Loading