@base44-preview/platform 0.1.0-pr.319.cf89f7f → 0.1.0-pr.323.0c3777e

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 (56) hide show
  1. package/README.md +47 -108
  2. package/dist/client.d.ts +31 -0
  3. package/dist/client.js +37 -0
  4. package/dist/client.types.d.ts +36 -0
  5. package/dist/errors.d.ts +47 -0
  6. package/dist/errors.js +47 -0
  7. package/dist/errors.types.d.ts +96 -0
  8. package/dist/index.d.ts +8 -0
  9. package/dist/{client/index.js → index.js} +1 -1
  10. package/dist/modules/builder-protocol.d.ts +21 -0
  11. package/dist/{client/modules → modules}/builder-protocol.js +11 -6
  12. package/dist/{client/modules → modules}/builder-socket.js +4 -5
  13. package/dist/{client/modules → modules}/builder-subscription.d.ts +2 -2
  14. package/dist/modules/builder.events.generated.d.ts +2194 -0
  15. package/dist/modules/builder.events.generated.js +3 -0
  16. package/dist/modules/builder.events.types.d.ts +58 -0
  17. package/dist/modules/builder.types.d.ts +162 -0
  18. package/package.json +15 -22
  19. package/dist/client/client.d.ts +0 -9
  20. package/dist/client/client.js +0 -9
  21. package/dist/client/client.types.d.ts +0 -12
  22. package/dist/client/errors.d.ts +0 -10
  23. package/dist/client/errors.js +0 -10
  24. package/dist/client/errors.types.d.ts +0 -2
  25. package/dist/client/index.d.ts +0 -7
  26. package/dist/client/modules/builder-protocol.d.ts +0 -15
  27. package/dist/client/modules/builder.events.types.d.ts +0 -368
  28. package/dist/client/modules/builder.types.d.ts +0 -47
  29. package/dist/server/errors.d.ts +0 -15
  30. package/dist/server/errors.js +0 -18
  31. package/dist/server/errors.types.d.ts +0 -4
  32. package/dist/server/errors.types.js +0 -1
  33. package/dist/server/index.d.ts +0 -6
  34. package/dist/server/index.js +0 -3
  35. package/dist/server/modules/webhooks-signature.d.ts +0 -11
  36. package/dist/server/modules/webhooks-signature.js +0 -65
  37. package/dist/server/modules/webhooks.d.ts +0 -3
  38. package/dist/server/modules/webhooks.events.generated.d.ts +0 -174
  39. package/dist/server/modules/webhooks.events.generated.js +0 -3
  40. package/dist/server/modules/webhooks.js +0 -77
  41. package/dist/server/modules/webhooks.types.d.ts +0 -102
  42. package/dist/server/modules/webhooks.types.js +0 -1
  43. package/dist/server/server.d.ts +0 -3
  44. package/dist/server/server.js +0 -11
  45. package/dist/server/server.types.d.ts +0 -15
  46. package/dist/server/server.types.js +0 -1
  47. package/dist/shared/server-url.d.ts +0 -2
  48. package/dist/shared/server-url.js +0 -8
  49. /package/dist/{client/client.types.js → client.types.js} +0 -0
  50. /package/dist/{client/errors.types.js → errors.types.js} +0 -0
  51. /package/dist/{client/modules → modules}/builder-socket.d.ts +0 -0
  52. /package/dist/{client/modules → modules}/builder-subscription.js +0 -0
  53. /package/dist/{client/modules → modules}/builder.d.ts +0 -0
  54. /package/dist/{client/modules → modules}/builder.events.types.js +0 -0
  55. /package/dist/{client/modules → modules}/builder.js +0 -0
  56. /package/dist/{client/modules → modules}/builder.types.js +0 -0
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 { Base44PlatformClient } from "@base44/platform";
13
+ import { createPlatformClient } from "@base44/platform";
14
14
 
15
- const client = new Base44PlatformClient({
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,66 +34,12 @@ 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_…`) explicitly.
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 { createBase44PlatformServer } from "@base44/platform/server";
50
-
51
- const platform = createBase44PlatformServer({
52
- serverUrl: "https://base44.app",
53
- apiKey: process.env.BASE44_API_KEY!,
54
- webhooks: { publicKeys: process.env.BASE44_WEBHOOK_PUBLIC_KEYS },
55
- });
56
-
57
- export const POST = platform.webhooks.createHandler({
58
- on: {
59
- "app.deleted.v1": async event => forget(event.data.app_id), // event is narrowed per type
60
- },
61
- onEvent: event => log(event.type), // every event, before its handler
62
- onSuccess: event => {}, // return a Response to replace the 204
63
- onError: (error, event) => report(error), // return a Response to replace the 400/500
64
- });
65
- ```
66
-
67
- For full control, verify and dispatch yourself:
68
-
69
- ```ts
70
- export async function POST(request: Request) {
71
- const rawBody = await request.text(); // exactly as received
72
- let event;
73
- try {
74
- event = await platform.webhooks.verifyEvent(rawBody, request.headers);
75
- } catch (error) {
76
- if (error instanceof WebhookVerificationError) return new Response(null, { status: 400 });
77
- throw error; // missing/malformed keys: a 500, so Base44 retries
78
- }
79
- switch (event.type) {
80
- case "webhook.test.v1": return Response.json({ challenge: event.data.challenge }); // activates the endpoint
81
- case "app.deleted.v1": await forget(event.data.app_id); break;
82
- }
83
- return new Response(null, { status: 204 });
84
- }
85
- ```
86
-
87
- Delivery is at least once with no ordering guarantee: deduplicate on `event.id`, and answer
88
- 2xx to event types you do not handle. Event types are generated from the schemas published at
89
- `https://base44.com/webhooks/schemas`; run `npm run generate:webhooks` to refresh them.
90
-
91
37
  ## Sessions
92
38
 
93
39
  `/api/builder-socket-session` is your backend's route, not an SDK endpoint. It opens a
94
40
  socket session with its workspace key (`apps:watch` scope) through
95
41
  `POST /api/service/socket-sessions` with `{ app_ids }`, and returns only the
96
- `session_token` to the browser. Never pass the workspace key or any other server
42
+ `session_token` and `socket_url` to the browser. Pass `socket_url` as `socketUrl`. Never pass the workspace key or any other server
97
43
  credential to this client. Subscribe only to apps on the session's allowlist; your
98
44
  backend adds or removes apps with `PUT`/`DELETE /api/service/socket-sessions/{session_id}/rooms/{app_id}`.
99
45
 
@@ -109,7 +55,7 @@ older one, which stops with `session_replaced`. Open one session per page.
109
55
 
110
56
  ## Lifecycle
111
57
 
112
- `new Base44PlatformClient({ serverUrl, getSessionToken })` creates a lightweight module
58
+ `createPlatformClient({ socketUrl, getSessionToken })` creates a lightweight module
113
59
  container: no Socket.IO instance, timers, token request or network activity. Its
114
60
  `builder` module follows the server SDK's module-factory pattern.
115
61
 
@@ -148,60 +94,53 @@ their exceptions are isolated so they cannot interrupt another app's delivery.
148
94
 
149
95
  ## Public shapes
150
96
 
151
- - `PlatformClientOptions` (`client.types.ts`): `serverUrl`, `getSessionToken`.
97
+ - `PlatformClientOptions` (`client.types.ts`): `socketUrl`, `getSessionToken`.
152
98
  - `BuilderModule` (`modules/builder.types.ts`): lazy `init(options)` factory.
153
99
  - `BuilderInitOptions`: connection-level `onError` observer.
154
100
  - `BuilderSession`: `connect()`, `subscribe(appId, options)`, `close()`.
155
101
  - `SubscriptionOptions`: required `onSnapshot`, `onEvent` and `onError`.
156
102
  - `PlatformSubscription`: read-only `appId`, `active`, and `unsubscribe()`.
157
- - Event/message models live in `modules/builder.events.types.ts`; error codes in `errors.types.ts`.
158
-
159
- Every exported shape and field has JSDoc. Run `npm run docs` for
160
- validated reference pages in `docs`. `PlatformEvent` is a
161
- **discriminated union**: switch on `event.type` to narrow `event.data`. Each delivery
162
- contains `type`, `appId` and `data`. On the wire every event is `{room, data}`; the SDK
163
- routes by `room` and validates the envelope, while payload schemas and private-field
164
- filtering are the server's. Omitted keys mean unchanged and explicit null clears.
165
- Events carrying `branch_id` belong to that branch; null or absent is main. Unknown
166
- event names are not forwarded.
167
-
168
- | Event | Data contract |
169
- | --- | --- |
170
- | `message.updated` | `MessageUpdated`: the whole `message`, optional `conversation_id`. Replace the message with the same `id`. |
171
- | `message.removed` | `MessageRemoved`: `message_id`, optional `conversation_id`. Sent when a message is deleted or hidden; an unknown ID is a no-op. |
172
- | `app.status_changed` | `AppStatusChanged`: `status` (`AppStatus`), null clears it. |
173
- | `preview.reload_requested` | Reload the app preview. |
174
- | `preview.navigation_requested` | `PreviewNavigationRequested`: `path`, and `force` to navigate even when the user moved away. |
175
- | `queue.updated` | `QueueUpdated`: `items`, `is_paused`, optional `processed_item_id`. Replaces the entire queue. |
176
- | `task.progressed` | `TaskProgressed`: optional `tool_call_id`, `message_id`, `event_type`, numeric `progress`. |
177
- | `image.resolved` | `ImageResolved`: `placeholder_url`, `status` (`pending`, `completed`, `failed`), nullable `image_url`. Replace the placeholder wherever it appears. |
178
- | `conversation.changed` | The conversation was rewritten. On main, a fresh snapshot follows. |
179
- | `files.changed`, `branch.deleted`, `repository.changed`, `pull_request.changed` | Re-read signals with no content. |
180
-
181
- `ChatMessage` has optional `id`, `role` (`user`/`assistant`), text/null `content`,
182
- `tool_calls`, timestamp-only `metadata.created_date`, `checkpoint_id`, and scalar
183
- `additional_message_params` (`client_creation_id`, `plan_mode`, `plan_approved`,
184
- `skip_ai_response`, `system_message_type`). `ToolCall` has optional `id`, `name`,
185
- `status`, `requires_user_input`, `auto_approved`, `mutation_applied` and
186
- `waiting_on.kind` (`approval`/`choice`/`input`). Each builder tool and guard declares
187
- which of its parts are public; a tool with no declaration shows only these fields.
188
-
189
- | Field | Public contract |
190
- | --- | --- |
191
- | `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. |
192
- | `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`. |
193
- | `user_input` | `ToolQuestionInput` only, for clarifying-question answers (`selected_label` for single-select, `selected_labels` for multi-select). Secret-form values are never exposed. |
194
- | `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). |
195
- | `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`). |
196
-
197
- In plan mode the message `content` beside a `generate_prd` call can be empty; render the
198
- plan from its arguments. Approving a plan, answering a question and approving a
199
- guarded call are HTTP actions of your backend. `Snapshot` contains `room`, `status`
200
- (`AppStatus`: optional `state` of `ready`/`processing`/`error`, nullable
201
- `last_updated_date`, and nullable `turn_id`, the user message that started the turn),
202
- `messages`, and `queue` (`SnapshotQueue`: the main branch's `items` and `is_paused`;
203
- absent from older servers). Dates remain wire strings. Structural filtering
204
- does not promise redaction of generated prose or user content.
103
+ - `PlatformEvent`, `PlatformEventMap`, `PlatformSnapshot`, `ToolCall`, `GuardApproval`
104
+ (`modules/builder.events.types.ts`), derived from the generated event types.
105
+ - Error codes in `errors.types.ts`.
106
+
107
+ `PlatformEvent` is a **discriminated union**: switch on `event.type` to narrow
108
+ `event.data`. Each delivery contains `type`, `appId` and `data`. On the wire every
109
+ event is `{room, data}`; the SDK routes by `room` and validates the envelope, while
110
+ payload schemas and private-field filtering are the server's. Omitted keys mean
111
+ unchanged and explicit null clears. Events carrying `branch_id` belong to that branch;
112
+ null or absent is main. Unknown event names are not forwarded. `PlatformSnapshot` is
113
+ the service's `Snapshot` plus the app's `room`. Structural filtering does not promise
114
+ redaction of generated prose or user content.
115
+
116
+ ## Event types
117
+
118
+ The socket protocol is defined by the service's AsyncAPI document, committed as
119
+ `asyncapi.json`. `src/modules/builder.events.generated.ts` is generated from it with
120
+ `json-schema-to-typescript`: one type per schema, named after the backend model
121
+ (`Message`, `StatusObject`, `QueueState`, one `*Call` per tool, one `*Approval` per
122
+ guard), plus `ServerEventMap` and `ClientMessageMap`. Never edit it by hand.
123
+
124
+ To pick up a protocol change:
125
+
126
+ ```sh
127
+ # Production serves only beta and GA events, so point at a dev backend while events are alpha.
128
+ npm run sync:asyncapi -w @base44/platform -- http://localhost:8000/api/asyncapi.json
129
+ npm run gen:events -w @base44/platform
130
+ ```
131
+
132
+ `sync:asyncapi` also reads `ASYNCAPI_URL`, defaults to production, and refuses a
133
+ document with no messages. CI runs `npm run check:events` and fails when the
134
+ generated file differs from what `asyncapi.json` produces.
135
+
136
+ ## Reference docs
137
+
138
+ Every exported shape and field has JSDoc. `npm run docs` validates it into `docs`.
139
+ `npm run create-docs` runs the app SDK's TypeDoc and Mintlify pipeline for this package,
140
+ and `npm run copy-docs-local -- --target <mintlify-docs>` copies the result into
141
+ `developers/references/platform-sdk/docs`. The pipeline's config for this package lives
142
+ in `scripts/mintlify-post-processing/`. The Socket messages page is built in mintlify-docs from
143
+ the service's AsyncAPI document, not here.
205
144
 
206
145
  `PlatformSocketError` extends `Error` with `code` and optional `appId`. Original
207
146
  exceptions, payloads and credentials are never attached.
@@ -0,0 +1,31 @@
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;
package/dist/client.js ADDED
@@ -0,0 +1,37 @@
1
+ import { createBuilder } from "./modules/builder.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 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 })) });
37
+ }
@@ -0,0 +1,36 @@
1
+ import type { BuilderModule } from "./modules/builder.types.js";
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
+ */
8
+ export interface PlatformClientOptions {
9
+ /**
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.
25
+ */
26
+ getSessionToken: () => string | Promise<string>;
27
+ }
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. */
35
+ readonly builder: BuilderModule;
36
+ }
@@ -0,0 +1,47 @@
1
+ import type { PlatformSocketErrorCode } from "./errors.types.js";
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
+ */
34
+ export declare class PlatformSocketError extends Error {
35
+ /** What happened. One of the [session error codes](#sessionerrorcode) or [app error codes](#apperrorcode). */
36
+ readonly code: PlatformSocketErrorCode;
37
+ /** ID of the app the error is about. Set for app error codes, and not set for session error codes. */
38
+ readonly appId?: string;
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
+ */
46
+ constructor(code: PlatformSocketErrorCode, appId?: string);
47
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,47 @@
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
+ */
33
+ export class PlatformSocketError extends Error {
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
+ */
41
+ constructor(code, appId) {
42
+ super(`Platform socket: ${code}`);
43
+ this.name = "PlatformSocketError";
44
+ this.code = code;
45
+ this.appId = appId;
46
+ }
47
+ }
@@ -0,0 +1,96 @@
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;
@@ -0,0 +1,8 @@
1
+ /** Browser platform modules, separate from the runtime and server SDKs. */
2
+ export { createPlatformClient } from "./client.js";
3
+ export { PlatformSocketError } from "./errors.js";
4
+ export type { AppErrorCode, PlatformSocketErrorCode, SessionErrorCode } from "./errors.types.js";
5
+ export type { PlatformClient, PlatformClientOptions } from "./client.types.js";
6
+ export type { BuilderModule, BuilderInitOptions, BuilderSession, PlatformSubscription, SubscriptionOptions } from "./modules/builder.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 { Base44PlatformClient } from "./client.js";
2
+ export { createPlatformClient } from "./client.js";
3
3
  export { PlatformSocketError } from "./errors.js";
@@ -0,0 +1,21 @@
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. */
5
+ export declare const roomNotices: {
6
+ readonly "room.access_denied": "access_denied";
7
+ readonly "room.access_revoked": "access_revoked";
8
+ readonly "room.snapshot_unavailable": "snapshot_unavailable";
9
+ };
10
+ export declare const sessionEndings: {
11
+ readonly expired: "session_expired";
12
+ readonly revoked: "session_revoked";
13
+ readonly replaced: "session_replaced";
14
+ };
15
+ export declare const appPattern: RegExp;
16
+ export declare const roomFor: (appId: string) => string;
17
+ export declare function object(value: unknown): Record<string, unknown>;
18
+ export declare function appFromRoom(value: unknown): string | undefined;
19
+ /** Every event is `{room, data}`; payload schemas are the service's, so only the envelope is validated. */
20
+ export declare function decode(type: keyof PlatformEventMap, appId: string, raw: unknown): PlatformEvent;
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.
@@ -1,4 +1,4 @@
1
- import type { PlatformEvent, Snapshot } from "./builder.events.types.js";
1
+ import type { PlatformEvent, PlatformSnapshot } from "./builder.events.types.js";
2
2
  import { PlatformSocketError } from "../errors.js";
3
3
  import type { PlatformSocketErrorCode } from "../errors.types.js";
4
4
  import type { PlatformSubscription, SubscriptionOptions } from "./builder.types.js";
@@ -15,7 +15,7 @@ export declare class Subscription implements PlatformSubscription {
15
15
  constructor(appId: string, options: SubscriptionOptions, remove: () => void);
16
16
  private enqueue;
17
17
  event(event: PlatformEvent): void;
18
- snapshot(snapshot: Snapshot): void;
18
+ snapshot(snapshot: PlatformSnapshot): void;
19
19
  /** A non-fatal problem; the subscription keeps receiving events. */
20
20
  warn(code: PlatformSocketErrorCode): void;
21
21
  fail(code: PlatformSocketErrorCode): void;