@base44-preview/sdk 0.8.40-pr.212.c163c94 → 0.8.40-pr.238.591b34c

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
@@ -12,7 +12,6 @@ import { createAppLogsModule } from "./modules/app-logs.js";
12
12
  import { createUsersModule } from "./modules/users.js";
13
13
  import { RoomsSocket } from "./utils/socket-utils.js";
14
14
  import { createAnalyticsModule } from "./modules/analytics.js";
15
- import { createActorsModule } from "./modules/actors.js";
16
15
  /**
17
16
  * Creates a Base44 client.
18
17
  *
@@ -52,27 +51,9 @@ import { createActorsModule } from "./modules/actors.js";
52
51
  */
53
52
  export function createClient(config) {
54
53
  var _a, _b;
55
- const { serverUrl = "https://base44.app", appId, token, serviceToken, requiresAuth = false, appBaseUrl, options, functionsVersion, headers: optionalHeaders, dispatcherWsUrl, webSocketImpl, } = config;
54
+ const { serverUrl = "https://base44.app", appId, token, serviceToken, requiresAuth = false, appBaseUrl, options, functionsVersion, headers: optionalHeaders, } = config;
56
55
  // Normalize appBaseUrl to always be a string (empty if not provided or invalid)
57
56
  const normalizedAppBaseUrl = typeof appBaseUrl === "string" ? appBaseUrl : "";
58
- // Derive the dispatcher WebSocket URL if not explicitly provided. Default to
59
- // the app's OWN origin (the app URL proxies /parties to the backend) so the
60
- // socket is same-origin with the running app, not the API host: prefer an
61
- // explicit appBaseUrl, then the browser origin, then fall back to serverUrl
62
- // (Node/SSR, where there's no window). Convert https:// → wss:// (http → ws)
63
- // and strip the trailing slash.
64
- const resolvedDispatcherWsUrl = (() => {
65
- var _a, _b;
66
- if (dispatcherWsUrl)
67
- return dispatcherWsUrl.replace(/\/$/, "");
68
- const appOrigin = normalizedAppBaseUrl ||
69
- // React Native has a bare `window` with no `location`, so guard both.
70
- (typeof window !== "undefined" ? (_b = (_a = window.location) === null || _a === void 0 ? void 0 : _a.origin) !== null && _b !== void 0 ? _b : "" : "");
71
- return (appOrigin || serverUrl)
72
- .replace(/\/$/, "")
73
- .replace(/^https:\/\//, "wss://")
74
- .replace(/^http:\/\//, "ws://");
75
- })();
76
57
  const socketConfig = {
77
58
  serverUrl,
78
59
  mountPath: "/ws-user-apps/socket.io/",
@@ -179,15 +160,6 @@ export function createClient(config) {
179
160
  appId,
180
161
  userAuthModule,
181
162
  }),
182
- actors: createActorsModule({
183
- appId,
184
- dispatcherWsUrl: resolvedDispatcherWsUrl,
185
- webSocketImpl,
186
- functionsVersion,
187
- // Same credential as function calls; the platform proxy authenticates the
188
- // WS connection with it (anonymous when absent) — no pre-connect token mint.
189
- getAuthToken: () => token || getAccessToken(),
190
- }),
191
163
  cleanup: () => {
192
164
  userModules.analytics.cleanup();
193
165
  if (socket) {
@@ -8,7 +8,6 @@ import type { AgentsModule } from "./modules/agents.types.js";
8
8
  import type { AiGatewayModule } from "./modules/ai-gateway.types.js";
9
9
  import type { AppLogsModule } from "./modules/app-logs.types.js";
10
10
  import type { AnalyticsModule } from "./modules/analytics.types.js";
11
- import type { ActorsModule } from "./modules/actors.types.js";
12
11
  /**
13
12
  * Options for creating a Base44 client.
14
13
  */
@@ -74,28 +73,6 @@ export interface CreateClientConfig {
74
73
  * Additional client options.
75
74
  */
76
75
  options?: CreateClientOptions;
77
- /**
78
- * Base WebSocket URL for the Cloudflare Durable Object dispatcher.
79
- *
80
- * Defaults to the app's own origin (`appBaseUrl`, else the browser's
81
- * `window.location.origin`, else `serverUrl`) with `https://` replaced by
82
- * `wss://` (or `http://` by `ws://`) — so the realtime socket is same-origin
83
- * with the running app, which proxies `/parties` to the backend.
84
- * Override when the dispatcher lives at a different host than the app.
85
- */
86
- dispatcherWsUrl?: string;
87
- /**
88
- * WebSocket implementation for realtime subscriptions in environments
89
- * without a global `WebSocket` (Node.js < 22). Browsers and Node ≥ 22
90
- * don't need this.
91
- *
92
- * @example
93
- * ```typescript
94
- * import WS from "ws";
95
- * const base44 = createClient({ appId, webSocketImpl: WS });
96
- * ```
97
- */
98
- webSocketImpl?: unknown;
99
76
  }
100
77
  /**
101
78
  * The Base44 client instance.
@@ -111,8 +88,6 @@ export interface Base44Client {
111
88
  analytics: AnalyticsModule;
112
89
  /** {@link AppLogsModule | App logs module} for tracking app usage. */
113
90
  appLogs: AppLogsModule;
114
- /** {@link ActorsModule | Actors module} for subscribing to and sending messages via Cloudflare Durable Object-backed Actors. */
115
- actors: ActorsModule;
116
91
  /** {@link AuthModule | Auth module} for user authentication and management. */
117
92
  auth: AuthModule;
118
93
  /** {@link UserConnectorsModule | Connectors module} for app-user OAuth flows. */
package/dist/index.d.ts CHANGED
@@ -11,9 +11,7 @@ export type { FunctionsModule, FunctionName, FunctionNameRegistry, } from "./mod
11
11
  export type { AgentsModule, AgentName, AgentNameRegistry, AgentConversation, AgentMessage, AgentMessageReasoning, AgentMessageToolCall, AgentMessageUsage, AgentMessageCustomContext, AgentMessageMetadata, CreateConversationParams, } from "./modules/agents.types.js";
12
12
  export type { AiGatewayModule, AiGatewayConnection, } from "./modules/ai-gateway.types.js";
13
13
  export type { AppLogsModule } from "./modules/app-logs.types.js";
14
- export type { ActorsModule, ActorClient, ActorNameRegistry, ActorRegistry, } from "./modules/actors.types.js";
15
14
  export type { SsoModule, SsoAccessTokenResponse } from "./modules/sso.types.js";
16
- export { Actor, type Conn } from "./actor.js";
17
15
  export type { ConnectorsModule, UserConnectorsModule, } from "./modules/connectors.types.js";
18
16
  export type { CustomIntegrationsModule, CustomIntegrationCallParams, CustomIntegrationCallResponse, } from "./modules/custom-integrations.types.js";
19
17
  export type { GetAccessTokenOptions, SaveAccessTokenOptions, RemoveAccessTokenOptions, GetLoginUrlOptions, } from "./utils/auth-utils.types.js";
package/dist/index.js CHANGED
@@ -3,4 +3,3 @@ import { Base44Error } from "./utils/axios-client.js";
3
3
  import { getAccessToken, saveAccessToken, removeAccessToken, getLoginUrl, } from "./utils/auth-utils.js";
4
4
  export { createClient, createClientFromRequest, Base44Error, getAccessToken, saveAccessToken, removeAccessToken, getLoginUrl, };
5
5
  export * from "./types.js";
6
- export { Actor } from "./actor.js";
@@ -53,11 +53,14 @@ export interface AppUserConnectorConnectionResponse {
53
53
  *
54
54
  * ## Shared connectors
55
55
  *
56
- * All app users share a single OAuth token. Use this for shared accounts. For example, posting to a company Slack channel or reading from a shared Google Calendar. To use a shared connector:
56
+ * All app users share a single OAuth token. Use this for shared accounts. For example, posting to a company Slack channel or reading from a shared Google Calendar.
57
57
  *
58
- * 1. Connect the external service account in the app's Integration settings or using the [`connectors push`](/developers/references/cli/commands/connectors-push) CLI command.
59
- * 2. In a backend function, call {@linkcode getConnection | getConnection()} using the service role client (`base44.asServiceRole.connectors`) with an [integration type](#available-connectors) string to retrieve the shared OAuth token.
60
- * 3. Use the returned `accessToken` to call the external service's API directly. Some connectors also return a `connectionConfig` with additional values such as a subdomain for building the API URL.
58
+ * Shared connectors come in two forms, depending on how the connector is set up. Both return the same app-wide token, so they differ only in how you identify the connector in code:
59
+ *
60
+ * - **Platform connectors** are connected from the app's Integration settings or with the [`connectors push`](/developers/references/cli/commands/connectors-push) CLI command, and are identified by an [integration type](#available-connectors) string. Retrieve them with {@linkcode getConnection | getConnection()}.
61
+ * - **Workspace-registered connectors** are backed by your own OAuth app, registered once in Workspace Settings and consented to by the app builder. They are identified by a connector ID instead of an integration type. Retrieve them with {@linkcode getWorkspaceConnection | getWorkspaceConnection()}. Connectors whose OAuth app is specific to your own account, such as Databricks and Snowflake, work this way.
62
+ *
63
+ * To use a shared connector, call the matching method on the service role client `base44.asServiceRole.connectors` from a backend function, then use the returned `accessToken` to call the external service's API directly. Some connectors also return a `connectionConfig` with additional values, such as a subdomain, that you need to build the API URL.
61
64
  *
62
65
  * ## App user connectors
63
66
  *
@@ -70,7 +73,7 @@ export interface AppUserConnectorConnectionResponse {
70
73
  *
71
74
  * ## Available connectors
72
75
  *
73
- * All connectors listed below support both shared and app user connections. For shared connectors, pass the integration type string to {@linkcode getConnection | getConnection()}. For app user connectors, register the connector in Workspace Settings and use the connector ID with {@linkcode getCurrentAppUserConnection | getCurrentAppUserConnection()}.
76
+ * The connectors below can be used as shared connectors or as app user connectors. For a shared platform connector, pass the integration type string to {@linkcode getConnection | getConnection()}. For a connector you register in Workspace Settings with your own OAuth app, use the connector ID with {@linkcode getWorkspaceConnection | getWorkspaceConnection()} for a shared token, or with {@linkcode getCurrentAppUserConnection | getCurrentAppUserConnection()} for a per-user token.
74
77
  *
75
78
  * | Service | Type identifier |
76
79
  * |---|---|
@@ -204,6 +207,8 @@ export interface ConnectorsModule {
204
207
  *
205
208
  * Use this when a single shared account is connected and all app users access the same token. For per-user tokens, use [`getCurrentAppUserConnection()`](#getcurrentappuserconnection) instead.
206
209
  *
210
+ * This form is for platform connectors identified by an integration type. Connectors backed by your own OAuth app registered in Workspace Settings, such as Databricks and Snowflake, are retrieved by connector ID with {@linkcode getWorkspaceConnection | getWorkspaceConnection()} instead.
211
+ *
207
212
  * Some connectors require connection-specific parameters to build API calls.
208
213
  * In such cases, the returned `connectionConfig` is an object with the additional parameters. If there are no extra parameters needed for the connection, the `connectionConfig` is `null`.
209
214
  *
@@ -257,28 +262,27 @@ export interface ConnectorsModule {
257
262
  */
258
263
  getConnection(integrationType: ConnectorIntegrationType): Promise<ConnectorConnectionResponse>;
259
264
  /**
260
- * Retrieves the OAuth access token and connection configuration for a **workspace-registered** connector
261
- * (a connector backed by an OAuth app registered in the workspace, consented to once by the app builder).
265
+ * Retrieves the shared OAuth access token and connection configuration for a [workspace-registered connector](#shared-connectors).
262
266
  *
263
- * Use this method when the app's backend function needs to use a connector identified by its
264
- * workspace-connector ID rather than a platform integration type. The token returned represents
265
- * the app builder's consent against the workspace's OAuth app and is shared across all app users
266
- * of the app — identical semantics to the platform-shared {@link getConnection} form,
267
- * differing only in which OAuth app was used to produce the token.
267
+ * Use this for a connector backed by your own OAuth app that you register in Workspace Settings, such as Databricks or Snowflake. The app builder consents to the connector once, and the returned token is shared across all app users of the app. This is the shared-token counterpart to {@linkcode getCurrentAppUserConnection | getCurrentAppUserConnection()}, which returns a per-user token for the same kind of connector. The semantics match {@linkcode getConnection | getConnection()}, except that you identify the connector by ID rather than by integration type.
268
268
  *
269
- * @param connectorId - The ID of the workspace connector (the `OrganizationConnector` database ID) as surfaced in the builder chat context.
269
+ * Some connectors require connection-specific parameters to build API calls. In such cases, the returned `connectionConfig` is an object with those parameters, such as the account subdomain used to construct the API URL. When no extra parameters are needed, `connectionConfig` is `null`.
270
+ *
271
+ * @param connectorId - The ID of the workspace connector, not the integration type string. You can find it on the connector's settings page in Workspace Settings.
270
272
  * @returns Promise resolving to a {@link ConnectorConnectionResponse} with `accessToken` and `connectionConfig`.
271
273
  *
272
274
  * @example
273
275
  * ```typescript
274
- * // Get the connection for a workspace-registered connector
275
- * const { accessToken, connectionConfig } = await base44.asServiceRole.connectors.getWorkspaceConnection(
276
- * 'abc123def',
276
+ * // Snowflake connection
277
+ * // Retrieve the shared token and run a statement against the account
278
+ * const { accessToken, connectionConfig } = await base44.asServiceRole.connectors.getWorkspaceConnection('abc123def');
279
+ *
280
+ * const response = await fetch(
281
+ * `https://${connectionConfig?.subdomain}.snowflakecomputing.com/api/v2/statements`,
282
+ * { headers: { Authorization: `Bearer ${accessToken}` } }
277
283
  * );
278
284
  *
279
- * const response = await fetch(`https://${connectionConfig?.subdomain}.snowflakecomputing.com/api/v2/statements`, {
280
- * headers: { Authorization: `Bearer ${accessToken}` },
281
- * });
285
+ * const data = await response.json();
282
286
  * ```
283
287
  */
284
288
  getWorkspaceConnection(connectorId: string): Promise<ConnectorConnectionResponse>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@base44-preview/sdk",
3
- "version": "0.8.40-pr.212.c163c94",
3
+ "version": "0.8.40-pr.238.591b34c",
4
4
  "description": "JavaScript SDK for Base44 API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -27,7 +27,6 @@
27
27
  },
28
28
  "dependencies": {
29
29
  "axios": "^1.18.1",
30
- "partysocket": "^0.0.23",
31
30
  "socket.io-client": "^4.8.3",
32
31
  "uuid": "^13.0.2"
33
32
  },
package/dist/actor.d.ts DELETED
@@ -1,77 +0,0 @@
1
- /**
2
- * Type-only base class for Actors.
3
- *
4
- * Import and extend this in your actor files:
5
- * import { Actor } from "@base44/sdk";
6
- * export class MyActor extends Actor { ... }
7
- *
8
- * At deploy time the bundler replaces this import with the compiled
9
- * Cloudflare Durable Object implementation — this file provides types only.
10
- */
11
- /**
12
- * A single client connection. `Send` is the message type this connection accepts
13
- * via {@link send} — the actor's *outgoing* (server→client) messages.
14
- */
15
- export interface Conn<Send = unknown> {
16
- /** Unique per-connection id (one per socket/tab), the same value the client
17
- * receives from `subscribe()`. Use this — not userId — to identify a distinct
18
- * client, so multiple tabs of the same user are separate connections. */
19
- id: string;
20
- userId: string;
21
- appId: string;
22
- instanceId: string;
23
- send(data: Send): void;
24
- reject(code: number, reason: string): void;
25
- }
26
- export interface Storage {
27
- get<T>(key: string): Promise<T | undefined>;
28
- put(key: string, value: unknown): Promise<void>;
29
- delete(key: string): Promise<boolean>;
30
- /** Wipe the room's entire persisted storage (match-end cleanup). Safe: a
31
- * later rejoin re-bootstraps exactly like a brand-new room. */
32
- deleteAll(): Promise<void>;
33
- }
34
- /**
35
- * Base class for an Actor.
36
- *
37
- * @typeParam Incoming - messages this actor *receives* from clients
38
- * (`handleMessage`'s `msg`) — the schema's `toServer` section.
39
- * @typeParam Outgoing - messages this actor *sends* to clients
40
- * (`conn.send`/`broadcast`) — the schema's `toClient` section.
41
- *
42
- * With a generated `schema.jsonc`, wire both from the registry so they can't drift
43
- * from the client's types:
44
- * ```ts
45
- * type Reg = ActorRegistry["MyActor"];
46
- * class MyActor extends Actor<Reg["toServer"], Reg["toClient"]> { ... }
47
- * ```
48
- */
49
- export declare abstract class Actor<Incoming = unknown, Outgoing = unknown> {
50
- abstract handleConnect(conn: Conn<Outgoing>): void | Promise<void>;
51
- abstract handleMessage(conn: Conn<Outgoing>, msg: Incoming): void | Promise<void>;
52
- abstract handleClose(conn: Conn<Outgoing>): void | Promise<void>;
53
- abstract handleTick(): void | Promise<void>;
54
- /**
55
- * Optional wake hook: runs once when the instance starts, before any
56
- * connection is handled — safe to load persisted state here.
57
- */
58
- handleStart(): void | Promise<void>;
59
- /**
60
- * Managed ticker (opt-in). Override {@link shouldTick} and the platform runs
61
- * {@link handleTick} on a timer of {@link tickIntervalMs} while it returns true,
62
- * and stops (letting the Durable Object hibernate — no compute cost) when it
63
- * returns false. The platform owns scheduling, rescheduling, self-heal, and
64
- * error-safety — you don't call {@link startLoop}/{@link stopLoop}.
65
- *
66
- * Re-evaluated after every connect/message/close and on every tick, so keep it
67
- * cheap and pure (no async, no side effects). Example: `return this.players >= 2`.
68
- */
69
- protected tickIntervalMs: number;
70
- protected shouldTick?(): boolean;
71
- protected broadcast(_data: Outgoing): void;
72
- protected getConnections(): Conn<Outgoing>[];
73
- protected startLoop(_ms: number): Promise<void>;
74
- protected stopLoop(): Promise<void>;
75
- protected get instanceId(): string;
76
- protected get storage(): Storage;
77
- }
package/dist/actor.js DELETED
@@ -1,63 +0,0 @@
1
- /**
2
- * Type-only base class for Actors.
3
- *
4
- * Import and extend this in your actor files:
5
- * import { Actor } from "@base44/sdk";
6
- * export class MyActor extends Actor { ... }
7
- *
8
- * At deploy time the bundler replaces this import with the compiled
9
- * Cloudflare Durable Object implementation — this file provides types only.
10
- */
11
- /**
12
- * Base class for an Actor.
13
- *
14
- * @typeParam Incoming - messages this actor *receives* from clients
15
- * (`handleMessage`'s `msg`) — the schema's `toServer` section.
16
- * @typeParam Outgoing - messages this actor *sends* to clients
17
- * (`conn.send`/`broadcast`) — the schema's `toClient` section.
18
- *
19
- * With a generated `schema.jsonc`, wire both from the registry so they can't drift
20
- * from the client's types:
21
- * ```ts
22
- * type Reg = ActorRegistry["MyActor"];
23
- * class MyActor extends Actor<Reg["toServer"], Reg["toClient"]> { ... }
24
- * ```
25
- */
26
- export class Actor {
27
- constructor() {
28
- /**
29
- * Managed ticker (opt-in). Override {@link shouldTick} and the platform runs
30
- * {@link handleTick} on a timer of {@link tickIntervalMs} while it returns true,
31
- * and stops (letting the Durable Object hibernate — no compute cost) when it
32
- * returns false. The platform owns scheduling, rescheduling, self-heal, and
33
- * error-safety — you don't call {@link startLoop}/{@link stopLoop}.
34
- *
35
- * Re-evaluated after every connect/message/close and on every tick, so keep it
36
- * cheap and pure (no async, no side effects). Example: `return this.players >= 2`.
37
- */
38
- this.tickIntervalMs = 100;
39
- }
40
- /**
41
- * Optional wake hook: runs once when the instance starts, before any
42
- * connection is handled — safe to load persisted state here.
43
- */
44
- handleStart() { }
45
- broadcast(_data) {
46
- throw new Error("Actor.broadcast() is only available inside a deployed actor");
47
- }
48
- getConnections() {
49
- throw new Error("Actor.getConnections() is only available inside a deployed actor");
50
- }
51
- startLoop(_ms) {
52
- throw new Error("Actor.startLoop() is only available inside a deployed actor");
53
- }
54
- stopLoop() {
55
- throw new Error("Actor.stopLoop() is only available inside a deployed actor");
56
- }
57
- get instanceId() {
58
- throw new Error("Actor.instanceId is only available inside a deployed actor");
59
- }
60
- get storage() {
61
- throw new Error("Actor.storage is only available inside a deployed actor");
62
- }
63
- }
@@ -1,27 +0,0 @@
1
- export declare function createActorsModule(config: {
2
- appId: string;
3
- /** Current user access token, if authenticated. Rides the WS query (same
4
- * pattern as the entities socket) so the platform proxy can authenticate the
5
- * connection like a backend-function call; anonymous connects omit it. */
6
- getAuthToken(): string | null | undefined;
7
- /** Same semantics as function calls: editors with a non-prod version get the
8
- * draft actor script; everyone else gets the published one. */
9
- functionsVersion?: string;
10
- dispatcherWsUrl: string;
11
- /** WebSocket implementation for runtimes without a global one (Node < 22). */
12
- webSocketImpl?: unknown;
13
- }): Record<string, ActorClient>;
14
- /** Handle for an active actor subscription. */
15
- interface ActorSubscription {
16
- /** This connection's id — the same value the actor receives as `conn.id`. */
17
- id: string;
18
- /** Close the subscription and its underlying socket. */
19
- unsubscribe(): void;
20
- }
21
- interface ActorClient {
22
- subscribe(instanceId: string, callback: (data: unknown) => void, options?: {
23
- id?: string;
24
- }): ActorSubscription;
25
- send(instanceId: string, data: unknown): void;
26
- }
27
- export {};
@@ -1,100 +0,0 @@
1
- import PartySocket from "partysocket";
2
- // Module-level map: "ActorName:instanceId" → active socket
3
- const activeSockets = new Map();
4
- function socketKey(actorName, instanceId) {
5
- return `${actorName}:${instanceId}`;
6
- }
7
- export function createActorsModule(config) {
8
- return new Proxy({}, {
9
- get(_, actorName) {
10
- return {
11
- subscribe(instanceId, callback, options) {
12
- var _a, _b;
13
- const key = socketKey(actorName, instanceId);
14
- // close existing if any
15
- (_a = activeSockets.get(key)) === null || _a === void 0 ? void 0 : _a.close();
16
- // Connection id: caller-supplied (stable — reuse across reconnects/tabs as
17
- // you see fit) or auto-generated per subscription. PartySocket sends it
18
- // as ?_pk=; the platform proxy validates it and the actor sees this exact
19
- // value as conn.id, stable across reconnects.
20
- const connId = (_b = options === null || options === void 0 ? void 0 : options.id) !== null && _b !== void 0 ? _b : crypto.randomUUID();
21
- // No pre-connect token mint: the platform proxy authenticates the
22
- // connection itself, exactly like a backend-function call. `handler`
23
- // carries the case-preserved actor name (the `party` path segment is
24
- // lowercased by PartySocket). query as fn: re-read on every (re)connect
25
- // so a login/logout between reconnects is picked up.
26
- const ws = new PartySocket({
27
- host: config.dispatcherWsUrl,
28
- party: actorName,
29
- room: instanceId,
30
- id: connId,
31
- ...(config.webSocketImpl ? { WebSocket: config.webSocketImpl } : {}),
32
- query: () => {
33
- const token = config.getAuthToken();
34
- return {
35
- app_id: config.appId,
36
- handler: actorName,
37
- ...(token ? { token } : {}),
38
- ...(config.functionsVersion ? { fv: config.functionsVersion } : {}),
39
- };
40
- },
41
- });
42
- activeSockets.set(key, ws);
43
- // Heartbeat / half-open detection. PartySocket only reconnects on a
44
- // browser close/error event, so a silently-dead connection (TCP alive,
45
- // no data — common behind proxies/LBs) hangs until the OS idle timeout
46
- // (~60s). We ping periodically and force a reconnect if nothing comes
47
- // back within DEAD_MS, cutting detection from ~60s to a few seconds.
48
- const PING_MS = 1000;
49
- const DEAD_MS = 3000;
50
- let lastMsg = Date.now();
51
- const bumpAlive = () => { lastMsg = Date.now(); };
52
- ws.addEventListener("open", bumpAlive);
53
- ws.addEventListener("message", (ev) => {
54
- bumpAlive();
55
- let data;
56
- try {
57
- data = JSON.parse(ev.data);
58
- }
59
- catch (_a) {
60
- return; // ignore malformed
61
- }
62
- // Swallow platform messages — never surface them to the app.
63
- const msgType = data && typeof data === "object" ? data.type : undefined;
64
- if (msgType === "__pong")
65
- return;
66
- callback(data);
67
- });
68
- const heartbeat = setInterval(() => {
69
- if (Date.now() - lastMsg > DEAD_MS) {
70
- bumpAlive(); // avoid a reconnect storm while the new socket comes up
71
- ws.reconnect();
72
- return;
73
- }
74
- try {
75
- ws.send(JSON.stringify({ type: "__ping" }));
76
- }
77
- catch (_a) {
78
- // socket not open; the watchdog above will force a reconnect
79
- }
80
- }, PING_MS);
81
- return {
82
- id: connId, // the connection id (same value the actor sees as conn.id)
83
- unsubscribe() {
84
- clearInterval(heartbeat);
85
- activeSockets.delete(key);
86
- ws.close();
87
- },
88
- };
89
- },
90
- send(instanceId, data) {
91
- const key = socketKey(actorName, instanceId);
92
- const ws = activeSockets.get(key);
93
- if (!ws)
94
- throw new Error(`No active subscription for ${actorName}:${instanceId}`);
95
- ws.send(JSON.stringify(data));
96
- },
97
- };
98
- },
99
- });
100
- }
@@ -1,77 +0,0 @@
1
- /**
2
- * Extend this interface to add typed `subscribe` callbacks and `send` payloads
3
- * for your deployed Actors.
4
- *
5
- * This is separate from {@link ActorNameRegistry} (which is auto-generated
6
- * by `base44 types generate`), so there are no conflicts.
7
- *
8
- * @example
9
- * ```typescript
10
- * declare module "@base44/sdk" {
11
- * interface ActorRegistry {
12
- * ChatRoom: {
13
- * toClient: { type: "joined" | "left" | "message"; userId?: string; from?: string; text?: string };
14
- * toServer: { type: "message"; text: string };
15
- * };
16
- * }
17
- * }
18
- * ```
19
- */
20
- export interface ActorRegistry {
21
- }
22
- /**
23
- * Auto-populated by `base44 types generate` with the names of your deployed actors.
24
- * Do not edit this interface manually — use {@link ActorRegistry} for message types.
25
- */
26
- export interface ActorNameRegistry {
27
- }
28
- type AllActorNames = keyof ActorRegistry | keyof ActorNameRegistry;
29
- type ToClientFor<N extends string> = N extends keyof ActorRegistry ? ActorRegistry[N] extends {
30
- toClient: infer I;
31
- } ? I : unknown : unknown;
32
- type ToServerFor<N extends string> = N extends keyof ActorRegistry ? ActorRegistry[N] extends {
33
- toServer: infer O;
34
- } ? O : unknown : unknown;
35
- /**
36
- * Client for a single named Actor.
37
- * Typed automatically when the actor is registered in {@link ActorRegistry}.
38
- */
39
- export interface ActorClient<N extends string = string> {
40
- /**
41
- * Open a WebSocket subscription. Returns a {@link ActorSubscription} with the
42
- * connection `id` (same value the actor sees as `conn.id`) and an `unsubscribe()` method.
43
- *
44
- * Pass `options.id` to control the connection id (e.g. a stable per-tab id so a
45
- * reconnect reuses the same server-side connection); omit it for an auto-generated
46
- * per-connection id.
47
- */
48
- subscribe(instanceId: string, callback: (data: ToClientFor<N>) => void, options?: {
49
- id?: string;
50
- }): ActorSubscription;
51
- /** Send a message over the open socket. Throws if not subscribed. */
52
- send(instanceId: string, data: ToServerFor<N>): void;
53
- }
54
- /** Handle for an active actor subscription. */
55
- export interface ActorSubscription {
56
- /** This connection's id — the same value the actor receives as `conn.id`. */
57
- id: string;
58
- /** Close the subscription and its underlying socket. */
59
- unsubscribe(): void;
60
- }
61
- /**
62
- * The actors module provides access to Cloudflare Durable Object-backed
63
- * Actors deployed by the Base44 platform.
64
- *
65
- * Actor names are accessed as dynamic properties on this module:
66
- * ```typescript
67
- * const sub = await base44.actors.MyActor.subscribe("room-1", (msg) => {
68
- * console.log(msg); // typed if MyActor is in ActorRegistry
69
- * });
70
- * const { id, unsubscribe } = sub;
71
- * unsubscribe();
72
- * ```
73
- */
74
- export type ActorsModule = {
75
- [K in AllActorNames]: K extends keyof ActorRegistry ? ActorClient<string & K> : ActorClient;
76
- } & Record<string, ActorClient>;
77
- export {};
@@ -1 +0,0 @@
1
- export {};