@base44-preview/platform 0.1.0-pr.316.f75d775 → 0.1.0-pr.319.32a35ed

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.
Files changed (38) hide show
  1. package/README.md +102 -54
  2. package/dist/client/client.d.ts +31 -3
  3. package/dist/client/client.js +35 -6
  4. package/dist/client/client.types.d.ts +28 -10
  5. package/dist/client/errors.d.ts +41 -4
  6. package/dist/client/errors.js +39 -2
  7. package/dist/client/errors.types.d.ts +96 -2
  8. package/dist/client/index.d.ts +5 -4
  9. package/dist/client/index.js +1 -1
  10. package/dist/client/modules/builder-protocol.d.ts +10 -4
  11. package/dist/client/modules/builder-protocol.js +11 -6
  12. package/dist/client/modules/builder-socket.js +4 -5
  13. package/dist/client/modules/builder-subscription.d.ts +2 -2
  14. package/dist/client/modules/builder.events.generated.d.ts +2194 -0
  15. package/dist/client/modules/builder.events.generated.js +3 -0
  16. package/dist/client/modules/builder.events.types.d.ts +50 -360
  17. package/dist/client/modules/builder.types.d.ts +138 -23
  18. package/dist/server/errors.d.ts +15 -0
  19. package/dist/server/errors.js +18 -0
  20. package/dist/server/errors.types.d.ts +4 -0
  21. package/dist/server/errors.types.js +1 -0
  22. package/dist/server/index.d.ts +5 -2
  23. package/dist/server/index.js +2 -1
  24. package/dist/server/modules/webhooks-signature.d.ts +11 -0
  25. package/dist/server/modules/webhooks-signature.js +65 -0
  26. package/dist/server/modules/webhooks.d.ts +3 -0
  27. package/dist/server/modules/webhooks.events.generated.d.ts +174 -0
  28. package/dist/server/modules/webhooks.events.generated.js +3 -0
  29. package/dist/server/modules/webhooks.js +77 -0
  30. package/dist/server/modules/webhooks.types.d.ts +100 -0
  31. package/dist/server/modules/webhooks.types.js +1 -0
  32. package/dist/server/server-url.d.ts +2 -0
  33. package/dist/{shared → server}/server-url.js +1 -1
  34. package/dist/server/server.d.ts +2 -2
  35. package/dist/server/server.js +6 -3
  36. package/dist/server/server.types.d.ts +5 -2
  37. package/package.json +23 -8
  38. package/dist/shared/server-url.d.ts +0 -2
package/README.md CHANGED
@@ -10,10 +10,10 @@ shared socket. It is independent of the app SDK (`@base44/sdk`).
10
10
  The workspace must have white-label sockets enabled; this SDK does not open sessions.
11
11
 
12
12
  ```ts
13
- import { createBase44PlatformClient } from "@base44/platform";
13
+ import { createPlatformClient } from "@base44/platform";
14
14
 
15
- const client = createBase44PlatformClient({
16
- serverUrl: "https://base44.app",
15
+ const client = createPlatformClient({
16
+ socketUrl, // the session's socket_url, from POST /api/service/socket-sessions
17
17
  async getSessionToken() {
18
18
  const response = await fetch("/api/builder-socket-session", { method: "POST" });
19
19
  if (!response.ok) throw new Error("Session request failed");
@@ -34,12 +34,67 @@ subscription.unsubscribe();
34
34
  builder.close();
35
35
  ```
36
36
 
37
+ ## Receiving webhooks (server)
38
+
39
+ `@base44/platform/server` verifies Base44 outbound webhooks and answers the endpoint
40
+ activation challenge. It uses WebCrypto only (Node 20+, Deno, Bun, Workers, edge runtimes) and
41
+ makes no network calls: pass your workspace's public keys (`whpk_…`) to each call that verifies.
42
+
43
+ The simplest route is `createHandler`. It reads the raw body, verifies it, answers the
44
+ activation challenge and picks the status code: 400 for a delivery that fails verification,
45
+ 500 when your keys are misconfigured or a callback throws (Base44 retries), 204 otherwise,
46
+ including for event types you have no handler for.
47
+
48
+ ```ts
49
+ import { createPlatformServer } from "@base44/platform/server";
50
+
51
+ const platform = createPlatformServer({
52
+ serverUrl: "https://base44.app",
53
+ apiKey: process.env.BASE44_API_KEY!,
54
+ });
55
+ const publicKeys = process.env.BASE44_WEBHOOK_PUBLIC_KEYS!; // two keys during a rotation
56
+
57
+ export const POST = platform.webhooks.createHandler({
58
+ publicKeys,
59
+ on: {
60
+ "app.deleted.v1": async event => forget(event.data.app_id), // event is narrowed per type
61
+ },
62
+ onEvent: event => log(event.type), // every event, before its handler
63
+ onSuccess: event => {}, // return a Response to replace the 204
64
+ onError: (error, event) => report(error), // return a Response to replace the 400/500
65
+ });
66
+ ```
67
+
68
+ For full control, verify and dispatch yourself:
69
+
70
+ ```ts
71
+ export async function POST(request: Request) {
72
+ const rawBody = await request.text(); // exactly as received
73
+ let event;
74
+ try {
75
+ event = await platform.webhooks.verifyEvent(rawBody, request.headers, { publicKeys });
76
+ } catch (error) {
77
+ if (error instanceof WebhookVerificationError) return new Response(null, { status: 400 });
78
+ throw error; // missing/malformed keys: a 500, so Base44 retries
79
+ }
80
+ switch (event.type) {
81
+ case "webhook.test.v1": return Response.json({ challenge: event.data.challenge }); // activates the endpoint
82
+ case "app.deleted.v1": await forget(event.data.app_id); break;
83
+ }
84
+ return new Response(null, { status: 204 });
85
+ }
86
+ ```
87
+
88
+ Delivery is at least once with no ordering guarantee: deduplicate on `event.id`, and answer
89
+ 2xx to event types you do not handle. Event types are generated from the schemas published at
90
+ `https://base44.com/webhooks/schemas`; run `npm run generate:webhooks` to refresh them.
91
+
37
92
  ## Sessions
38
93
 
39
94
  `/api/builder-socket-session` is your backend's route, not an SDK endpoint. It opens a
40
95
  socket session with its workspace key (`apps:watch` scope) through
41
96
  `POST /api/service/socket-sessions` with `{ app_ids }`, and returns only the
42
- `session_token` to the browser. Never pass the workspace key or any other server
97
+ `session_token` and `socket_url` to the browser. Pass `socket_url` as `socketUrl`. Never pass the workspace key or any other server
43
98
  credential to this client. Subscribe only to apps on the session's allowlist; your
44
99
  backend adds or removes apps with `PUT`/`DELETE /api/service/socket-sessions/{session_id}/rooms/{app_id}`.
45
100
 
@@ -55,7 +110,7 @@ older one, which stops with `session_replaced`. Open one session per page.
55
110
 
56
111
  ## Lifecycle
57
112
 
58
- `createBase44PlatformClient({ serverUrl, getSessionToken })` returns a lightweight module
113
+ `createPlatformClient({ socketUrl, getSessionToken })` creates a lightweight module
59
114
  container: no Socket.IO instance, timers, token request or network activity. Its
60
115
  `builder` module follows the server SDK's module-factory pattern.
61
116
 
@@ -94,60 +149,53 @@ their exceptions are isolated so they cannot interrupt another app's delivery.
94
149
 
95
150
  ## Public shapes
96
151
 
97
- - `PlatformClientOptions` (`client.types.ts`): `serverUrl`, `getSessionToken`.
152
+ - `PlatformClientOptions` (`client.types.ts`): `socketUrl`, `getSessionToken`.
98
153
  - `BuilderModule` (`modules/builder.types.ts`): lazy `init(options)` factory.
99
154
  - `BuilderInitOptions`: connection-level `onError` observer.
100
155
  - `BuilderSession`: `connect()`, `subscribe(appId, options)`, `close()`.
101
156
  - `SubscriptionOptions`: required `onSnapshot`, `onEvent` and `onError`.
102
157
  - `PlatformSubscription`: read-only `appId`, `active`, and `unsubscribe()`.
103
- - Event/message models live in `modules/builder.events.types.ts`; error codes in `errors.types.ts`.
104
-
105
- Every exported shape and field has JSDoc. Run `npm run docs` for
106
- validated reference pages in `docs`. `PlatformEvent` is a
107
- **discriminated union**: switch on `event.type` to narrow `event.data`. Each delivery
108
- contains `type`, `appId` and `data`. On the wire every event is `{room, data}`; the SDK
109
- routes by `room` and validates the envelope, while payload schemas and private-field
110
- filtering are the server's. Omitted keys mean unchanged and explicit null clears.
111
- Events carrying `branch_id` belong to that branch; null or absent is main. Unknown
112
- event names are not forwarded.
113
-
114
- | Event | Data contract |
115
- | --- | --- |
116
- | `message.updated` | `MessageUpdated`: the whole `message`, optional `conversation_id`. Replace the message with the same `id`. |
117
- | `message.removed` | `MessageRemoved`: `message_id`, optional `conversation_id`. Sent when a message is deleted or hidden; an unknown ID is a no-op. |
118
- | `app.status_changed` | `AppStatusChanged`: `status` (`AppStatus`), null clears it. |
119
- | `preview.reload_requested` | Reload the app preview. |
120
- | `preview.navigation_requested` | `PreviewNavigationRequested`: `path`, and `force` to navigate even when the user moved away. |
121
- | `queue.updated` | `QueueUpdated`: `items`, `is_paused`, optional `processed_item_id`. Replaces the entire queue. |
122
- | `task.progressed` | `TaskProgressed`: optional `tool_call_id`, `message_id`, `event_type`, numeric `progress`. |
123
- | `image.resolved` | `ImageResolved`: `placeholder_url`, `status` (`pending`, `completed`, `failed`), nullable `image_url`. Replace the placeholder wherever it appears. |
124
- | `conversation.changed` | The conversation was rewritten. On main, a fresh snapshot follows. |
125
- | `files.changed`, `branch.deleted`, `repository.changed`, `pull_request.changed` | Re-read signals with no content. |
126
-
127
- `ChatMessage` has optional `id`, `role` (`user`/`assistant`), text/null `content`,
128
- `tool_calls`, timestamp-only `metadata.created_date`, `checkpoint_id`, and scalar
129
- `additional_message_params` (`client_creation_id`, `plan_mode`, `plan_approved`,
130
- `skip_ai_response`, `system_message_type`). `ToolCall` has optional `id`, `name`,
131
- `status`, `requires_user_input`, `auto_approved`, `mutation_applied` and
132
- `waiting_on.kind` (`approval`/`choice`/`input`). Each builder tool and guard declares
133
- which of its parts are public; a tool with no declaration shows only these fields.
134
-
135
- | Field | Public contract |
136
- | --- | --- |
137
- | `arguments` | One of `ToolQuestionArguments`, `ToolSecretArguments`, `ToolPackageArguments`, `ToolPlanArguments`, `ToolPrdArguments` (`generate_prd`, the plan in plan mode) or `ToolMediaArguments`, narrowed by the tool's `name`. Absent for other tools and partial streaming arguments. |
138
- | `display` | File activity has `file_paths` and optional `content_empty`; execution activity has `summary` and `writes_entities`; entity activity has `entity_name` and `record_count`. |
139
- | `user_input` | `ToolQuestionInput` only, for clarifying-question answers (`selected_label` for single-select, `selected_labels` for multi-select). Secret-form values are never exposed. |
140
- | `results` | Once the call is not waiting on a guard: `ToolMediaResult` for image generation, or a URL string for game images and backgrounds (the placeholder `image.resolved` replaces) and videos (the finished video). |
141
- | `approval` | While a call waits on a safety guard: `ToolGuardApproval` with `guard`, and `reason` and `details` where the guard declares them (shell-command approvals carry only `guard`). |
142
-
143
- In plan mode the message `content` beside a `generate_prd` call can be empty; render the
144
- plan from its arguments. Approving a plan, answering a question and approving a
145
- guarded call are HTTP actions of your backend. `Snapshot` contains `room`, `status`
146
- (`AppStatus`: optional `state` of `ready`/`processing`/`error`, nullable
147
- `last_updated_date`, and nullable `turn_id`, the user message that started the turn),
148
- `messages`, and `queue` (`SnapshotQueue`: the main branch's `items` and `is_paused`;
149
- absent from older servers). Dates remain wire strings. Structural filtering
150
- does not promise redaction of generated prose or user content.
158
+ - `PlatformEvent`, `PlatformEventMap`, `PlatformSnapshot`, `ToolCall`, `GuardApproval`
159
+ (`modules/builder.events.types.ts`), derived from the generated event types.
160
+ - Error codes in `errors.types.ts`.
161
+
162
+ `PlatformEvent` is a **discriminated union**: switch on `event.type` to narrow
163
+ `event.data`. Each delivery contains `type`, `appId` and `data`. On the wire every
164
+ event is `{room, data}`; the SDK routes by `room` and validates the envelope, while
165
+ payload schemas and private-field filtering are the server's. Omitted keys mean
166
+ unchanged and explicit null clears. Events carrying `branch_id` belong to that branch;
167
+ null or absent is main. Unknown event names are not forwarded. `PlatformSnapshot` is
168
+ the service's `Snapshot` plus the app's `room`. Structural filtering does not promise
169
+ redaction of generated prose or user content.
170
+
171
+ ## Event types
172
+
173
+ The socket protocol is defined by the service's AsyncAPI document, committed as
174
+ `asyncapi.json`. `src/client/modules/builder.events.generated.ts` is generated from it with
175
+ `json-schema-to-typescript`: one type per schema, named after the backend model
176
+ (`Message`, `StatusObject`, `QueueState`, one `*Call` per tool, one `*Approval` per
177
+ guard), plus `ServerEventMap` and `ClientMessageMap`. Never edit it by hand.
178
+
179
+ To pick up a protocol change:
180
+
181
+ ```sh
182
+ # Production serves only beta and GA events, so point at a dev backend while events are alpha.
183
+ npm run sync:asyncapi -w @base44/platform -- http://localhost:8000/api/asyncapi.json
184
+ npm run gen:events -w @base44/platform
185
+ ```
186
+
187
+ `sync:asyncapi` also reads `ASYNCAPI_URL`, defaults to production, and refuses a
188
+ document with no messages. CI runs `npm run check:events` and fails when the
189
+ generated file differs from what `asyncapi.json` produces.
190
+
191
+ ## Reference docs
192
+
193
+ Every exported shape and field has JSDoc. `npm run docs` validates it into `docs`.
194
+ `npm run create-docs` runs the app SDK's TypeDoc and Mintlify pipeline for this package,
195
+ and `npm run copy-docs-local -- --target <mintlify-docs>` copies the result into
196
+ `developers/references/platform-sdk/docs`. The pipeline's config for this package lives
197
+ in `scripts/mintlify-post-processing/`. The Socket messages page is built in mintlify-docs from
198
+ the service's AsyncAPI document, not here.
151
199
 
152
200
  `PlatformSocketError` extends `Error` with `code` and optional `appId`. Original
153
201
  exceptions, payloads and credentials are never attached.
@@ -1,3 +1,31 @@
1
- import type { Base44PlatformClient, PlatformClientOptions } from "./client.types.js";
2
- /** Create a browser platform client. Creates no sockets, timers or network requests; each module initializes its own resources. */
3
- export declare function createBase44PlatformClient(options: PlatformClientOptions): Base44PlatformClient;
1
+ import type { PlatformClient, PlatformClientOptions } from "./client.types.js";
2
+ /**
3
+ * Creates a platform client.
4
+ *
5
+ * This is the entry point of the Platform SDK. The client gives your white-label app editor
6
+ * access to the platform's modules, such as [`builder`](/developers/references/platform-sdk/docs/interfaces/builder).
7
+ *
8
+ * @param options - Configuration object for the client.
9
+ * @returns A configured platform client with access to the platform's modules.
10
+ * @throws {TypeError} When `socketUrl` isn't an HTTP or HTTPS origin.
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * // Create a client for your app editor
15
+ * import { createPlatformClient } from '@base44/platform';
16
+ *
17
+ * const client = createPlatformClient({
18
+ * socketUrl,
19
+ * async getSessionToken() {
20
+ * const response = await fetch('/api/builder-socket-session', { method: 'POST' });
21
+ * const { session_token } = await response.json();
22
+ * return session_token;
23
+ * },
24
+ * });
25
+ *
26
+ * // Use the client to follow the AI chat in an app
27
+ * const builder = client.builder.init({ onError: (error) => console.error(error.code) });
28
+ * await builder.connect();
29
+ * ```
30
+ */
31
+ export declare function createPlatformClient(options: PlatformClientOptions): PlatformClient;
@@ -1,8 +1,37 @@
1
- import { normalizeServerUrl } from "../shared/server-url.js";
2
1
  import { createBuilder } from "./modules/builder.js";
3
- /** Create a browser platform client. Creates no sockets, timers or network requests; each module initializes its own resources. */
4
- export function createBase44PlatformClient(options) {
5
- return Object.freeze({
6
- builder: Object.freeze(createBuilder({ ...options, serverUrl: normalizeServerUrl(options.serverUrl) })),
7
- });
2
+ /**
3
+ * Creates a platform client.
4
+ *
5
+ * This is the entry point of the Platform SDK. The client gives your white-label app editor
6
+ * access to the platform's modules, such as [`builder`](/developers/references/platform-sdk/docs/interfaces/builder).
7
+ *
8
+ * @param options - Configuration object for the client.
9
+ * @returns A configured platform client with access to the platform's modules.
10
+ * @throws {TypeError} When `socketUrl` isn't an HTTP or HTTPS origin.
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * // Create a client for your app editor
15
+ * import { createPlatformClient } from '@base44/platform';
16
+ *
17
+ * const client = createPlatformClient({
18
+ * socketUrl,
19
+ * async getSessionToken() {
20
+ * const response = await fetch('/api/builder-socket-session', { method: 'POST' });
21
+ * const { session_token } = await response.json();
22
+ * return session_token;
23
+ * },
24
+ * });
25
+ *
26
+ * // Use the client to follow the AI chat in an app
27
+ * const builder = client.builder.init({ onError: (error) => console.error(error.code) });
28
+ * await builder.connect();
29
+ * ```
30
+ */
31
+ export function createPlatformClient(options) {
32
+ const url = new URL(options.socketUrl);
33
+ if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || url.pathname !== "/") {
34
+ throw new TypeError("socketUrl must be an HTTP(S) origin without credentials, path, query or fragment");
35
+ }
36
+ return Object.freeze({ builder: Object.freeze(createBuilder({ ...options, socketUrl: url.origin })) });
8
37
  }
@@ -1,18 +1,36 @@
1
1
  import type { BuilderModule } from "./modules/builder.types.js";
2
- /** Shared configuration for browser platform modules. Never supply an API key. */
2
+ /**
3
+ * Options for {@linkcode createPlatformClient | createPlatformClient()}.
4
+ *
5
+ * The client runs in the browser and never sees your workspace API key. Your server opens a socket
6
+ * session with the key and hands the browser only the session's token and socket URL.
7
+ */
3
8
  export interface PlatformClientOptions {
4
- /** Origin of the platform service, e.g. https://base44.app. No path/query/credentials. */
5
- serverUrl: string;
6
9
  /**
7
- * Return a socket-session token from your backend, which opens the session with its
8
- * workspace key (`POST /api/service/socket-sessions`) for the apps this page watches.
9
- * Called when a builder session first connects, and again only after the server
10
- * rejects or expires the current session. Sessions last one hour.
10
+ * Origin of the platform socket.
11
+ *
12
+ * Use the `socket_url` your server receives from `POST /api/service/socket-sessions`. It's the same
13
+ * for every session in an environment, so your server can pass it to the page once. It must be an
14
+ * origin with no path, query, fragment, or credentials.
15
+ */
16
+ socketUrl: string;
17
+ /**
18
+ * Returns a socket session token from your server.
19
+ *
20
+ * Your server opens a session with `POST /api/service/socket-sessions` and returns its
21
+ * `session_token`. The client calls this when it connects, and again when the token expires.
22
+ * Return a new token on every call.
23
+ *
24
+ * @returns The session token, or a promise resolving to it.
11
25
  */
12
26
  getSessionToken: () => string | Promise<string>;
13
27
  }
14
- /** Browser platform client, returned by `createBase44PlatformClient`. */
15
- export interface Base44PlatformClient {
16
- /** Lazy builder subscriptions with independent session lifecycles. */
28
+ /**
29
+ * The platform client.
30
+ *
31
+ * Provides access to the platform's modules.
32
+ */
33
+ export interface PlatformClient {
34
+ /** [Builder module](/developers/references/platform-sdk/docs/interfaces/builder) for following the AI chat in your users' apps live. */
17
35
  readonly builder: BuilderModule;
18
36
  }
@@ -1,10 +1,47 @@
1
1
  import type { PlatformSocketErrorCode } from "./errors.types.js";
2
- /** Sanitized failure. Original session-token provider, handler and server exceptions are not retained. */
2
+ /**
3
+ * The error the SDK reports when something goes wrong in a builder session.
4
+ *
5
+ * You don't create it. The SDK passes it to your `onError` callbacks, `connect()` rejects with it,
6
+ * and `subscribe()` throws it. Check `code` to see what happened, then look the code up below:
7
+ * - [Session error codes](#sessionerrorcode) go to the `onError` you pass to `init()`. The whole
8
+ * session is affected, and `appId` isn't set.
9
+ * - [App error codes](#apperrorcode) go to the subscription's `onError`. Only that app is affected,
10
+ * and `appId` says which one.
11
+ *
12
+ * The error never carries the session token, a callback's exception, or the server's exception text.
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * // Handle session and app errors
17
+ * const builder = client.builder.init({
18
+ * // Session error codes: the whole session is affected
19
+ * onError(error) {
20
+ * if (error.code === 'session_revoked') showSignedOut();
21
+ * },
22
+ * });
23
+ *
24
+ * builder.subscribe(appId, {
25
+ * onSnapshot: renderChat,
26
+ * onEvent: applyEvent,
27
+ * // App error codes: only this app is affected, and error.appId says which
28
+ * onError(error) {
29
+ * if (error.code === 'access_revoked') hideLiveUpdates(error.appId);
30
+ * },
31
+ * });
32
+ * ```
33
+ */
3
34
  export declare class PlatformSocketError extends Error {
4
- /** Stable machine-readable category. */
35
+ /** What happened. One of the [session error codes](#sessionerrorcode) or [app error codes](#apperrorcode). */
5
36
  readonly code: PlatformSocketErrorCode;
6
- /** Associated app, when the server identifies a valid room. */
37
+ /** ID of the app the error is about. Set for app error codes, and not set for session error codes. */
7
38
  readonly appId?: string;
8
- /** Create a sanitized error with no credential-bearing cause or payload. */
39
+ /**
40
+ * Creates an error. The SDK creates these; you don't need to.
41
+ *
42
+ * @param code - Error code.
43
+ * @param appId - ID of the app the error is about.
44
+ * @internal
45
+ */
9
46
  constructor(code: PlatformSocketErrorCode, appId?: string);
10
47
  }
@@ -1,6 +1,43 @@
1
- /** Sanitized failure. Original session-token provider, handler and server exceptions are not retained. */
1
+ /**
2
+ * The error the SDK reports when something goes wrong in a builder session.
3
+ *
4
+ * You don't create it. The SDK passes it to your `onError` callbacks, `connect()` rejects with it,
5
+ * and `subscribe()` throws it. Check `code` to see what happened, then look the code up below:
6
+ * - [Session error codes](#sessionerrorcode) go to the `onError` you pass to `init()`. The whole
7
+ * session is affected, and `appId` isn't set.
8
+ * - [App error codes](#apperrorcode) go to the subscription's `onError`. Only that app is affected,
9
+ * and `appId` says which one.
10
+ *
11
+ * The error never carries the session token, a callback's exception, or the server's exception text.
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * // Handle session and app errors
16
+ * const builder = client.builder.init({
17
+ * // Session error codes: the whole session is affected
18
+ * onError(error) {
19
+ * if (error.code === 'session_revoked') showSignedOut();
20
+ * },
21
+ * });
22
+ *
23
+ * builder.subscribe(appId, {
24
+ * onSnapshot: renderChat,
25
+ * onEvent: applyEvent,
26
+ * // App error codes: only this app is affected, and error.appId says which
27
+ * onError(error) {
28
+ * if (error.code === 'access_revoked') hideLiveUpdates(error.appId);
29
+ * },
30
+ * });
31
+ * ```
32
+ */
2
33
  export class PlatformSocketError extends Error {
3
- /** Create a sanitized error with no credential-bearing cause or payload. */
34
+ /**
35
+ * Creates an error. The SDK creates these; you don't need to.
36
+ *
37
+ * @param code - Error code.
38
+ * @param appId - ID of the app the error is about.
39
+ * @internal
40
+ */
4
41
  constructor(code, appId) {
5
42
  super(`Platform socket: ${code}`);
6
43
  this.name = "PlatformSocketError";
@@ -1,2 +1,96 @@
1
- /** Server refusals and client transport/processing failures. */
2
- export type PlatformSocketErrorCode = "connection_denied" | "connection_failed" | "session_unavailable" | "session_revoked" | "session_replaced" | "access_denied" | "access_revoked" | "snapshot_unavailable" | "subscription_limit" | "delivery_overflow" | "protocol_error" | "handler_failed" | "client_closed";
1
+ /**
2
+ * Codes of errors that affect the whole session. They go to the `onError` you pass to `init()`, and
3
+ * `connect()` rejects with them. Retryable means the same call can succeed again without changing anything.
4
+ */
5
+ export type SessionErrorCode =
6
+ /**
7
+ * `getSessionToken` threw, took longer than 20 seconds or returned no token.
8
+ *
9
+ * Check the endpoint that opens sessions, then call `connect()` again. Retryable.
10
+ */
11
+ "session_unavailable"
12
+ /**
13
+ * Base44 refused the session even with a fresh token: the token is invalid, or live updates aren't enabled for the workspace.
14
+ *
15
+ * Check that your server opens a new session on every call. Not retryable.
16
+ */
17
+ | "connection_denied"
18
+ /**
19
+ * The socket couldn't connect after five retries, or the server closed it.
20
+ *
21
+ * Call `connect()` again, for example when the tab next gets focus. Retryable.
22
+ */
23
+ | "connection_failed"
24
+ /**
25
+ * Your server or an admin ended the session, or its key lost access.
26
+ *
27
+ * Open a new session from your server if the page should still follow apps. Not retryable.
28
+ */
29
+ | "session_revoked"
30
+ /**
31
+ * Another socket connected with the same session token.
32
+ *
33
+ * Use one session per tab. Don't reconnect automatically; call `connect()` only to take the session back on purpose. Not retryable.
34
+ */
35
+ | "session_replaced"
36
+ /**
37
+ * A session frame didn't match the protocol.
38
+ *
39
+ * Update the SDK, then call `connect()` again. Not retryable.
40
+ */
41
+ | "protocol_error"
42
+ /**
43
+ * You called `connect()` or `subscribe()` after `close()`.
44
+ *
45
+ * Create a new session with `init()`. Not retryable.
46
+ */
47
+ | "client_closed";
48
+ /**
49
+ * Codes of errors for one app. They go to the subscription's `onError`, and `subscribe()` throws
50
+ * `subscription_limit`. Every one ends the subscription except `snapshot_unavailable`.
51
+ */
52
+ export type AppErrorCode =
53
+ /**
54
+ * The app isn't on the session's allowlist, or the socket joins too often.
55
+ *
56
+ * Add the app to the session from your server, then subscribe again. Not retryable.
57
+ */
58
+ "access_denied"
59
+ /**
60
+ * The app left the session's allowlist, or its workspace.
61
+ *
62
+ * Stop showing the app's live updates. Not retryable.
63
+ */
64
+ | "access_revoked"
65
+ /**
66
+ * The subscription is active but its snapshot failed. Events keep arriving.
67
+ *
68
+ * Load the app's messages over the Apps API instead.
69
+ */
70
+ | "snapshot_unavailable"
71
+ /**
72
+ * The session already has eight subscriptions.
73
+ *
74
+ * Unsubscribe from an app, or open another session. Not retryable.
75
+ */
76
+ | "subscription_limit"
77
+ /**
78
+ * More than 1,000 deliveries waited for your callbacks.
79
+ *
80
+ * Make the callbacks faster, then subscribe again for a fresh snapshot. Retryable.
81
+ */
82
+ | "delivery_overflow"
83
+ /**
84
+ * Your `onSnapshot` or `onEvent` callback threw or rejected.
85
+ *
86
+ * Fix the callback, then subscribe again. Not retryable.
87
+ */
88
+ | "handler_failed"
89
+ /**
90
+ * An event for this app didn't match the protocol.
91
+ *
92
+ * Update the SDK, then subscribe again. Not retryable.
93
+ */
94
+ | "protocol_error";
95
+ /** Every code a {@link PlatformSocketError} reports. */
96
+ export type PlatformSocketErrorCode = SessionErrorCode | AppErrorCode;
@@ -1,7 +1,8 @@
1
1
  /** Browser platform modules, separate from the runtime and server SDKs. */
2
- export { createBase44PlatformClient } from "./client.js";
2
+ export { createPlatformClient } from "./client.js";
3
3
  export { PlatformSocketError } from "./errors.js";
4
- export type { PlatformSocketErrorCode } from "./errors.types.js";
5
- export type { Base44PlatformClient, PlatformClientOptions } from "./client.types.js";
4
+ export type { AppErrorCode, PlatformSocketErrorCode, SessionErrorCode } from "./errors.types.js";
5
+ export type { PlatformClient, PlatformClientOptions } from "./client.types.js";
6
6
  export type { BuilderModule, BuilderInitOptions, BuilderSession, PlatformSubscription, SubscriptionOptions } from "./modules/builder.types.js";
7
- export type { AppStatus, AppStatusChanged, BranchScoped, ChatMessage, ImageResolved, MessageParams, MessageRemoved, MessageUpdated, PlatformEvent, PlatformEventMap, PreviewNavigationRequested, QueueItem, QueueUpdated, Snapshot, SnapshotQueue, TaskProgressed, ToolArguments, ToolCall, ToolDisplay, ToolEntityMutationArguments, ToolGuardApproval, ToolMediaArguments, ToolMediaResult, ToolPackageArguments, ToolPackageOperation, ToolPlanArguments, ToolPlanUpdate, ToolPrdArguments, ToolQuestion, ToolQuestionAnswer, ToolQuestionArguments, ToolQuestionInput, ToolQuestionOption, ToolSecretArguments, ToolSecretField, } from "./modules/builder.events.types.js";
7
+ export type { GuardApproval, PlatformEvent, PlatformEventMap, PlatformSnapshot, ToolCall } from "./modules/builder.events.types.js";
8
+ export type * from "./modules/builder.events.generated.js";
@@ -1,3 +1,3 @@
1
1
  /** Browser platform modules, separate from the runtime and server SDKs. */
2
- export { createBase44PlatformClient } from "./client.js";
2
+ export { createPlatformClient } from "./client.js";
3
3
  export { PlatformSocketError } from "./errors.js";
@@ -1,15 +1,21 @@
1
- import type { PlatformEvent, PlatformEventMap, Snapshot } from "./builder.events.types.js";
2
- export declare const eventNames: readonly ["message.updated", "message.removed", "app.status_changed", "preview.reload_requested", "preview.navigation_requested", "queue.updated", "task.progressed", "image.resolved", "conversation.changed", "files.changed", "branch.deleted", "repository.changed", "pull_request.changed"];
3
- /** Notices that name an app room, by the error code each one reports. */
1
+ import type { PlatformEvent, PlatformEventMap, PlatformSnapshot } from "./builder.events.types.js";
2
+ /** App events delivered to `onEvent`: every server event except the session events the socket handles. */
3
+ export declare const eventNames: ("message.updated" | "message.removed" | "app.status_changed" | "preview.reload_requested" | "preview.navigation_requested" | "queue.updated" | "task.progressed" | "image.resolved" | "conversation.changed" | "files.changed" | "branch.deleted" | "repository.changed" | "pull_request.changed")[];
4
+ /** Notices that name an app room, by the error code each one reports. A new notice fails to compile until it has one. */
4
5
  export declare const roomNotices: {
5
6
  readonly "room.access_denied": "access_denied";
6
7
  readonly "room.access_revoked": "access_revoked";
7
8
  readonly "room.snapshot_unavailable": "snapshot_unavailable";
8
9
  };
10
+ export declare const sessionEndings: {
11
+ readonly expired: "session_expired";
12
+ readonly revoked: "session_revoked";
13
+ readonly replaced: "session_replaced";
14
+ };
9
15
  export declare const appPattern: RegExp;
10
16
  export declare const roomFor: (appId: string) => string;
11
17
  export declare function object(value: unknown): Record<string, unknown>;
12
18
  export declare function appFromRoom(value: unknown): string | undefined;
13
19
  /** Every event is `{room, data}`; payload schemas are the service's, so only the envelope is validated. */
14
20
  export declare function decode(type: keyof PlatformEventMap, appId: string, raw: unknown): PlatformEvent;
15
- export declare function decodeSnapshot(raw: unknown): Snapshot;
21
+ export declare function decodeSnapshot(raw: unknown): PlatformSnapshot;
@@ -1,14 +1,19 @@
1
- export const eventNames = [
2
- "message.updated", "message.removed", "app.status_changed", "preview.reload_requested",
3
- "preview.navigation_requested", "queue.updated", "task.progressed", "image.resolved",
4
- "conversation.changed", "files.changed", "branch.deleted", "repository.changed", "pull_request.changed",
5
- ];
6
- /** Notices that name an app room, by the error code each one reports. */
1
+ import { serverEventNames } from "./builder.events.generated.js";
2
+ const sessionEvents = ["app.snapshot", "session.ended"];
3
+ /** App events delivered to `onEvent`: every server event except the session events the socket handles. */
4
+ export const eventNames = serverEventNames.filter((name) => !sessionEvents.includes(name) && !name.startsWith("room."));
5
+ /** Notices that name an app room, by the error code each one reports. A new notice fails to compile until it has one. */
7
6
  export const roomNotices = {
8
7
  "room.access_denied": "access_denied",
9
8
  "room.access_revoked": "access_revoked",
10
9
  "room.snapshot_unavailable": "snapshot_unavailable",
11
10
  };
11
+ // `expired` never reaches the partner: the session renews its token.
12
+ export const sessionEndings = {
13
+ expired: "session_expired",
14
+ revoked: "session_revoked",
15
+ replaced: "session_replaced",
16
+ };
12
17
  export const appPattern = /^[a-f0-9]{24}$/;
13
18
  export const roomFor = (appId) => `/apps/${appId}`;
14
19
  export function object(value) {
@@ -1,6 +1,6 @@
1
1
  import { io } from "socket.io-client";
2
2
  import { PlatformSocketError } from "../errors.js";
3
- import { appFromRoom, appPattern, decode, decodeSnapshot, eventNames, object, roomFor, roomNotices } from "./builder-protocol.js";
3
+ import { appFromRoom, appPattern, decode, decodeSnapshot, eventNames, object, roomFor, roomNotices, sessionEndings } from "./builder-protocol.js";
4
4
  import { notify, Subscription } from "./builder-subscription.js";
5
5
  const MAX_DENIAL_RETRIES = 5;
6
6
  /** @internal */
@@ -12,7 +12,7 @@ export class BuilderSocket {
12
12
  this.denialRetries = 0;
13
13
  this.authAttempt = 0;
14
14
  this.options = { ...config, onError: options.onError };
15
- this.socket = io(config.serverUrl, {
15
+ this.socket = io(config.socketUrl, {
16
16
  path: "/ws/socket.io/", transports: ["websocket"], autoConnect: false,
17
17
  forceNew: true, reconnectionAttempts: 5, reconnectionDelay: 1000, reconnectionDelayMax: 10000,
18
18
  timeout: 20000,
@@ -208,9 +208,8 @@ export class BuilderSocket {
208
208
  sessionEnded(raw) {
209
209
  try {
210
210
  const reason = object(object(raw).data).reason;
211
- const ending = reason === "expired" ? "session_expired"
212
- : reason === "revoked" ? "session_revoked"
213
- : reason === "replaced" ? "session_replaced" : undefined;
211
+ const ending = typeof reason === "string" && Object.prototype.hasOwnProperty.call(sessionEndings, reason)
212
+ ? sessionEndings[reason] : undefined;
214
213
  if (!ending)
215
214
  throw new Error("Unknown reason");
216
215
  // The server disconnects next; the disconnect handler renews or stops.