@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
@@ -0,0 +1,3 @@
1
+ // Generated from asyncapi.json by scripts/gen-events.mjs. Do not edit; run `npm run gen:events`.
2
+ /** @internal */
3
+ export const serverEventNames = ["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", "session.ended", "room.access_denied", "room.access_revoked", "room.snapshot_unavailable", "app.snapshot"];
@@ -1,368 +1,58 @@
1
- /** Activity a file, execution or entity tool declared public. */
2
- export interface ToolDisplay {
3
- /** Changed file paths for a file operation. Source bodies and diffs are never included. */
4
- file_paths?: string[];
5
- /** Whether a file write intentionally used empty content. */
6
- content_empty?: boolean;
7
- /** Reviewed execution activity summary. Commands and execution output are never included. */
8
- summary?: string;
9
- /** Whether a reviewed execution action changed entity data. */
10
- writes_entities?: boolean;
11
- /** Entity type affected by an entity operation. Records and query values are never included. */
12
- entity_name?: string;
13
- /** Number of records affected when supplied by the producer. */
14
- record_count?: number;
15
- }
16
- /** A selectable answer to a builder question. */
17
- export interface ToolQuestionOption {
18
- /** Visible option label. */
19
- label?: string;
20
- }
21
- /** A builder question. Image/HTML source and private design context are excluded. */
22
- export interface ToolQuestion {
23
- /** Visible question text. */
24
- question?: string;
25
- /** Question category. */
26
- type?: string;
27
- /** Optional visible supporting text. */
28
- description?: string;
29
- /** Whether more than one answer may be selected. */
30
- multi_select?: boolean;
31
- /** Plan section the question covers. */
32
- covers?: string;
33
- /** Selectable options; a bare string option is its label. */
34
- options?: (ToolQuestionOption | string)[];
35
- }
36
- /** `ask_clarifying_questions` and `ask_plan_questions` arguments. */
37
- export interface ToolQuestionArguments {
38
- /** Questions presented to the user. */
39
- questions?: ToolQuestion[];
40
- }
41
- /** A requested secret field. The secret value is never sent over the socket. */
42
- export interface ToolSecretField {
43
- /** Requested secret name. */
44
- secretName?: string;
45
- /** Optional explanation of where to obtain it. */
46
- description?: string;
47
- }
48
- /** `set_secrets` arguments. */
49
- export interface ToolSecretArguments {
50
- /** Requested secret fields. */
51
- secrets_schema?: ToolSecretField[];
52
- }
53
- /** A package operation. Versions and package-manager output are excluded. */
54
- export interface ToolPackageOperation {
55
- /** Package name. */
56
- name?: string;
57
- /** Requested package operation. */
58
- action?: string;
59
- }
60
- /** `install_npm_package` arguments. */
61
- export interface ToolPackageArguments {
62
- /** Requested package operations. */
63
- packages?: ToolPackageOperation[];
64
- }
65
- /** An add-only builder plan update. */
66
- export interface ToolPlanUpdate {
67
- /** Update action. */
68
- action?: string;
69
- /** Plan section key. */
70
- section?: string;
71
- /** Optional user-facing section label. */
72
- section_label?: string;
73
- /** Plan point. */
74
- text?: string;
75
- }
76
- /** `update_plan` arguments. */
77
- export interface ToolPlanArguments {
78
- /** Plan updates in their emitted order. */
79
- updates?: ToolPlanUpdate[];
80
- /** Base plan sections the builder considers sufficiently specified. */
81
- sections_with_enough?: string[];
82
- }
83
- /** `generate_prd` arguments: the user's own plan. In plan mode the message `content` beside it can be empty. */
84
- export interface ToolPrdArguments {
85
- /** App or feature name. */
86
- app_name?: string;
87
- /** What is being built and why. */
88
- intent_and_goal?: string;
89
- /** Who uses it and their roles. */
90
- audience_and_roles?: string;
91
- /** End-to-end user flows. */
92
- core_flows?: string[];
93
- /** Specific technical requirements. */
94
- technical_requirements?: string;
95
- /** Design preferences. */
96
- design_preferences?: string;
97
- /** Build or plan declaration, when the builder asks for one. */
98
- prd_type?: string;
99
- /** Store platform settled in planning, for e-commerce plans. */
100
- store_platform?: string;
101
- /** Engine settled in planning, for game plans. */
102
- game_engine?: string;
103
- }
104
- /** Image, game-image and video generation arguments. */
105
- export interface ToolMediaArguments {
106
- /** Visible media label. */
107
- label?: string;
108
- /** Requested image or video aspect ratio. */
109
- aspect_ratio?: string;
110
- }
111
- /** `update_entities` and `delete_entities` arguments; the entity is in `display.entity_name`. */
112
- export interface ToolEntityMutationArguments {
113
- /** The agent's summary of the change. Queries and record values are never included. */
114
- summary?: string;
115
- }
116
- /** The public arguments of a tool that declares them; narrow by the tool call's `name`. */
117
- export type ToolArguments = ToolQuestionArguments | ToolSecretArguments | ToolPackageArguments | ToolPlanArguments | ToolPrdArguments | ToolMediaArguments | ToolEntityMutationArguments;
118
- /** Generated-media state. Raw generation prompts and IDs are never included. */
119
- export interface ToolMediaResult {
120
- /** Placeholder URL, used to associate an `image.resolved` event with this tool. */
121
- placeholder_url?: string;
122
- /** Current media-generation status. */
123
- status?: "pending" | "completed" | "failed";
124
- /** Generated asset URL, once available. */
125
- image_url?: string | null;
126
- }
127
- /** An answer to a clarifying question. Secret-form input is never included. */
128
- export interface ToolQuestionAnswer {
129
- /** Zero-based question index. */
130
- question_index?: number;
131
- /** Label selected for a single-select question. */
132
- selected_label?: string;
133
- /** Labels selected for a multi-select question. */
134
- selected_labels?: string[];
135
- /** User-provided free-text answer. Structural filtering does not redact prose. */
136
- custom_text?: string;
137
- }
138
- /** Clarifying-question answers. */
139
- export interface ToolQuestionInput {
140
- /** Answers supplied to the question card. */
141
- answers?: ToolQuestionAnswer[];
142
- }
143
- /** Why a safety guard parked a call for approval. Only present while the call waits. */
144
- export interface ToolGuardApproval {
145
- /** Guard identifier, e.g. `exec_tool_send_email` or `bash_approval`. */
146
- guard: string;
147
- /** Human-readable reason, for guards whose reason never quotes input (not shell commands). */
148
- reason?: string;
149
- /** The details the guard declares public; commands and record data are never included. */
150
- details?: {
151
- /** Entity method the code calls, e.g. `delete`. */
152
- method?: string;
153
- /** The agent's summary of what the code does. */
154
- summary?: string;
155
- /** Entity whose access rules change. */
156
- entity_name?: string;
157
- /** How the access rules change. */
158
- change_type?: string;
159
- /** Access operations whose rules change. */
160
- changed_ops?: string[];
161
- /** Backend function under test. */
162
- function_name?: string;
163
- /** The guard could not verify the function's source. */
164
- inspection_failed?: boolean;
165
- };
166
- }
167
- /** Public progress of a builder tool call. Only what the tool and its guard declare public is present. */
168
- export interface ToolCall {
169
- /** Stable tool call identifier. */
170
- id?: string;
171
- /** Tool name. */
172
- name?: string;
173
- /** Current execution state. */
174
- status?: "running" | "success" | "error" | "stopped" | "waiting_for_user_input";
175
- /** Whether the tool needs a user response through the partner backend. */
176
- requires_user_input?: boolean;
177
- /** Whether the builder auto-approved the operation. */
178
- auto_approved?: boolean;
179
- /** Whether the mutation was applied. */
180
- mutation_applied?: boolean | null;
181
- /** Kind of response a parked call waits for. */
182
- waiting_on?: {
183
- /** Kind of response expected. */
184
- kind?: "approval" | "choice" | "input";
185
- };
186
- /** The tool's public arguments; absent for tools that declare none and for partial streaming arguments. */
187
- arguments?: ToolArguments;
188
- /** What a file, execution or entity tool touched. */
189
- display?: ToolDisplay;
190
- /** Clarifying-question answers. */
191
- user_input?: ToolQuestionInput;
192
- /** Generated media, once the call is not waiting on a guard: the image tool's state, or a URL alone
193
- * (a game asset's placeholder, which `image.resolved` replaces, or a finished video). */
194
- results?: ToolMediaResult | string;
195
- /** A parked call's guard, and its reason and details where the guard declares them. */
196
- approval?: ToolGuardApproval;
197
- }
198
- /** Scalar parameters a chat UI needs while a turn runs. */
199
- export interface MessageParams {
200
- /** Identifier the sending client attached, to match its optimistic message. */
201
- client_creation_id?: string;
202
- /** The message was sent in plan mode. */
203
- plan_mode?: boolean;
204
- /** The message approves a plan. */
205
- plan_approved?: boolean;
206
- /** The message expects no AI reply. */
207
- skip_ai_response?: boolean;
208
- /** System message category. */
209
- system_message_type?: string;
210
- }
211
- /** A public chat message. Replace the message with the same `id` as a whole. */
212
- export interface ChatMessage {
213
- /** Message identifier. */
214
- id?: string;
215
- /** Author category. System and hidden messages are never delivered. */
216
- role?: "user" | "assistant";
217
- /** Message text; structured content is withheld. Structural filtering is not prose redaction. */
218
- content?: string | null;
219
- /** Public tool progress. */
220
- tool_calls?: ToolCall[] | null;
221
- /** Message timestamp, without author identity. */
222
- metadata?: {
223
- /** ISO timestamp string. */
224
- created_date?: string;
225
- };
226
- /** Checkpoint reference; mutations remain on the partner backend. */
227
- checkpoint_id?: string | null;
228
- /** Scalar message parameters. */
229
- additional_message_params?: MessageParams;
230
- }
231
- /** Public builder state, without error diagnostics or billing context. */
232
- export interface AppStatus {
233
- /** Current builder state. */
234
- state?: "ready" | "processing" | "error";
235
- /** State timestamp. */
236
- last_updated_date?: string | null;
237
- /** The user message that started the turn, when a turn set this state. Quote it to Base44 support. */
238
- turn_id?: string | null;
239
- }
240
- /** Branch scope carried by app events. Null or absent is the main branch. */
241
- export interface BranchScoped {
242
- /** Branch the change belongs to; null is main. */
243
- branch_id?: string | null;
244
- }
245
- /** `message.updated`: a chat message was added or replaced. */
246
- export interface MessageUpdated extends BranchScoped {
247
- /** The whole message; replace the one with the same `id`. */
248
- message: ChatMessage;
249
- /** Conversation containing the message. */
250
- conversation_id?: string | null;
251
- }
252
- /** `message.removed`: a message was removed or hidden. An `id` the viewer never saw is a no-op. */
253
- export interface MessageRemoved extends BranchScoped {
254
- /** Identifier of the message to remove. */
255
- message_id: string;
256
- /** Conversation that contained the message. */
257
- conversation_id?: string | null;
258
- }
259
- /** `app.status_changed`: a turn started, finished or failed. */
260
- export interface AppStatusChanged extends BranchScoped {
261
- /** The new state; null clears it. */
262
- status: AppStatus | null;
263
- }
264
- /** `preview.navigation_requested`: show this page of the app in the preview. */
265
- export interface PreviewNavigationRequested extends BranchScoped {
266
- /** App path to show. */
267
- path: string;
268
- /** Navigate even when the user has moved away from the page. */
269
- force: boolean;
270
- }
271
- /** A queued builder request. */
272
- export interface QueueItem {
273
- /** Queue item identifier. */
274
- id?: string;
275
- /** User-authored request text. */
276
- content?: string;
277
- /** Creation timestamp. */
278
- created_at?: string;
279
- /** Branch the request belongs to. */
280
- branch_id?: string | null;
281
- }
282
- /** `queue.updated`: the whole prompt queue, replacing the previous one. */
283
- export interface QueueUpdated extends BranchScoped {
284
- /** Pending items. */
285
- items?: QueueItem[];
286
- /** Whether queue processing is paused. */
287
- is_paused?: boolean;
288
- /** Identifier of the item just processed, when supplied. */
289
- processed_item_id?: string | null;
290
- }
291
- /** `task.progressed`: progress of a long-running tool. */
292
- export interface TaskProgressed extends BranchScoped {
293
- /** Associated tool call. */
294
- tool_call_id?: string | null;
295
- /** Associated chat message. */
296
- message_id?: string | null;
297
- /** Task lifecycle event, e.g. `task_progress`. */
298
- event_type?: string | null;
299
- /** Numeric progress only; diagnostic text is withheld. */
300
- progress?: {
301
- /** Completed work units. */
302
- current?: number | null;
303
- /** Total work units, when known. */
304
- total?: number | null;
305
- /** Producer-supplied percentage. */
306
- percentage?: number | null;
307
- } | null;
308
- }
309
- /** `image.resolved`: a generated image finished or failed. Replace its `placeholder_url` wherever it appears. */
310
- export type ImageResolved = ToolMediaResult;
311
- /** Mapping of public event names to their payloads. */
312
- export interface PlatformEventMap {
313
- /** A chat message was added or replaced. */
314
- "message.updated": MessageUpdated;
315
- /** A chat message was removed or hidden. */
316
- "message.removed": MessageRemoved;
317
- /** The builder started, finished or failed a turn. */
318
- "app.status_changed": AppStatusChanged;
319
- /** Reload the app preview. */
320
- "preview.reload_requested": BranchScoped;
321
- /** Show a page of the app in the preview. */
322
- "preview.navigation_requested": PreviewNavigationRequested;
323
- /** The whole prompt queue. */
324
- "queue.updated": QueueUpdated;
325
- /** Progress of a long-running tool. */
326
- "task.progressed": TaskProgressed;
327
- /** A generated image finished or failed. */
328
- "image.resolved": ImageResolved;
329
- /** The conversation was rewritten (undo, restore, sync). On main, the SDK rejoins for a fresh snapshot. */
330
- "conversation.changed": BranchScoped;
331
- /** The app's files changed outside a chat turn. Re-read them. */
332
- "files.changed": BranchScoped;
333
- /** A branch was deleted. */
334
- "branch.deleted": BranchScoped;
335
- /** The imported app's repository changed. */
336
- "repository.changed": BranchScoped;
337
- /** The imported app's pull request changed. */
338
- "pull_request.changed": BranchScoped;
339
- }
340
- /** Ordered delivery of one public event. */
1
+ import type { Message, QueueState, ServerEventMap, Snapshot } from "./builder.events.generated.js";
2
+ /**
3
+ * Maps each live event name to the type of its `data` payload.
4
+ *
5
+ * Generated from the service's AsyncAPI document, so it covers every app event the service sends.
6
+ * The client handles the session events `app.snapshot`, `session.ended` and `room.*` itself, and
7
+ * reports them through `onSnapshot` and `onError` instead.
8
+ */
9
+ export type PlatformEventMap = {
10
+ [K in keyof ServerEventMap as K extends "app.snapshot" | "session.ended" | `room.${string}` ? never : K]: ServerEventMap[K];
11
+ };
12
+ /**
13
+ * One live event for a subscribed app.
14
+ *
15
+ * Check `type` to narrow `data` to that event's payload. A key missing from `data` means the value
16
+ * is unchanged, and an explicit `null` clears it. For every event and its payload, see
17
+ * [Socket messages](/developers/references/apps-api/sections/socket-messages).
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * // Narrow an event by type
22
+ * function onEvent(event: PlatformEvent) {
23
+ * if (event.type === "message.updated") {
24
+ * const { message } = event.data;
25
+ * console.log(`Message ${message.id} changed`);
26
+ * }
27
+ * }
28
+ * ```
29
+ */
341
30
  export type PlatformEvent = {
342
31
  [K in keyof PlatformEventMap]: {
343
- /** Public event name; narrows the payload type. */
32
+ /** Event name. Narrows the type of `data`. */
344
33
  type: K;
345
- /** Authorized app receiving this event. */
34
+ /** ID of the app the event belongs to. */
346
35
  appId: string;
347
- /** Event payload. Omitted keys mean unchanged; explicit null clears. */
36
+ /** Event payload. */
348
37
  data: PlatformEventMap[K];
349
38
  };
350
39
  }[keyof PlatformEventMap];
351
- /** An app's current state: sent after every join and rejoin, and after a main-conversation rewrite. */
352
- export interface Snapshot {
353
- /** Canonical app room. */
40
+ /**
41
+ * An app's current state.
42
+ *
43
+ * Arrives after every join and rejoin, and after a rewrite of the main conversation. Replace
44
+ * everything you hold for the app with it. It holds only the last 50 messages.
45
+ */
46
+ export interface PlatformSnapshot extends Omit<Snapshot, "queue"> {
47
+ /** The app's room, `/apps/{app_id}`. */
354
48
  room: string;
355
- /** Current builder state. */
356
- status: AppStatus | null;
357
- /** The last 50 public messages, oldest first. */
358
- messages: ChatMessage[];
359
- /** The main branch's prompt queue. Replace it, as with `queue.updated`. Absent from older servers. */
360
- queue?: SnapshotQueue;
361
- }
362
- /** The prompt queue in a snapshot. */
363
- export interface SnapshotQueue {
364
- /** Pending items. */
365
- items: QueueItem[];
366
- /** Whether queue processing is paused. */
367
- is_paused: boolean;
368
- }
49
+ /** The main branch's prompt queue. Missing when the server sends none. */
50
+ queue?: QueueState;
51
+ }
52
+ /**
53
+ * One tool call in a message's `tool_calls`. Checking `name` narrows it to that tool's call and
54
+ * `OtherToolCall`, which covers tools the SDK doesn't know, so check a field with `in` before using it.
55
+ */
56
+ export type ToolCall = NonNullable<Message["tool_calls"]>[number];
57
+ /** Why a safety guard parked a tool call for approval. Check `guard` to narrow it. */
58
+ export type GuardApproval = NonNullable<ToolCall["approval"]>;
@@ -1,47 +1,162 @@
1
- import type { PlatformEvent, Snapshot } from "./builder.events.types.js";
1
+ import type { PlatformEvent, PlatformSnapshot } from "./builder.events.types.js";
2
2
  import type { PlatformSocketError } from "../errors.js";
3
- /** Options for an independent builder socket session. */
3
+ /** Options for {@linkcode BuilderModule.init | init()}. */
4
4
  export interface BuilderInitOptions {
5
- /** Connection-level errors, sanitized to exclude tokens and server exception text. */
5
+ /**
6
+ * Called on errors that affect the whole session, such as a failed connection or an ended session.
7
+ * Errors for one app go to that subscription's `onError` instead. See the
8
+ * [error codes](/developers/references/platform-sdk/docs/classes/PlatformSocketError#platformsocketerrorcode).
9
+ */
6
10
  onError: (error: PlatformSocketError) => void;
7
11
  }
8
- /** Lazy builder module; no socket exists until init is called. */
12
+ /**
13
+ * Builder module for following the AI chat in your users' apps live.
14
+ *
15
+ * Each session holds one socket and up to eight app subscriptions. For each app you get a
16
+ * snapshot of its chat, then every change as it happens:
17
+ * - New and updated chat messages, with the AI's tool calls.
18
+ * - The AI's status, from processing to ready.
19
+ * - Preview reloads and navigation, the prompt queue, and generated images.
20
+ *
21
+ * The module does nothing until you call {@linkcode init | init()}.
22
+ */
9
23
  export interface BuilderModule {
10
- /** Create an independent session without connecting. Call connect on the returned session. */
24
+ /**
25
+ * Creates a builder session without connecting it.
26
+ *
27
+ * Call {@linkcode BuilderSession.connect | connect()} on the returned session to open the socket.
28
+ * Each session is independent, with its own socket, token and subscriptions.
29
+ *
30
+ * @param options - Session options.
31
+ * @returns The new session.
32
+ *
33
+ * @example
34
+ * ```typescript
35
+ * // Create and connect a session
36
+ * const builder = client.builder.init({
37
+ * onError(error) {
38
+ * console.error('Builder session error', error.code);
39
+ * },
40
+ * });
41
+ * await builder.connect();
42
+ * ```
43
+ */
11
44
  init(options: BuilderInitOptions): BuilderSession;
12
45
  }
13
- /** One builder socket session. Owns its subscriptions and connection lifecycle. */
46
+ /**
47
+ * A `BuilderSession`: one socket with its app subscriptions and its reconnection. Use its methods
48
+ * to connect, follow apps and close.
49
+ */
14
50
  export interface BuilderSession {
15
- /** Connect with the session token; resolves on CONNECT, before snapshots arrive.
16
- * Transport loss retries five times and rejoins active subscriptions, each with a fresh
17
- * snapshot. An expired or rejected session is replaced once through `getSessionToken`.
18
- * Call again after a failure or `session_replaced`. Concurrent calls share one attempt.
51
+ /**
52
+ * Connects the session's socket.
53
+ *
54
+ * Resolves once the socket connects, before any snapshot arrives. If the connection drops, the
55
+ * session retries five times and rejoins every active subscription, each with a fresh snapshot.
56
+ * An expired or rejected token is replaced once through `getSessionToken`. Concurrent calls share
57
+ * one attempt. Call it again after a failure or a `session_replaced` error.
58
+ *
59
+ * @returns Promise that resolves when the socket connects.
60
+ * @throws {PlatformSocketError} With `connection_denied`, `connection_failed` or `session_unavailable`
61
+ * when the session can't connect, or `client_closed` when the session is closed first.
62
+ *
63
+ * @example
64
+ * ```typescript
65
+ * // Connect and handle failure
66
+ * try {
67
+ * await builder.connect();
68
+ * } catch (error) {
69
+ * console.error('Could not connect', error.code);
70
+ * }
71
+ * ```
19
72
  */
20
73
  connect(): Promise<void>;
21
- /** Subscribe before or after connecting. One subscription per app, up to eight per session,
22
- * and each app must be on the session's allowlist. Callbacks run serially per app.
74
+ /**
75
+ * Subscribes to one app's chat.
76
+ *
77
+ * You can subscribe before or after connecting. Each app can have one subscription per session,
78
+ * and a session can have up to eight. The app must be on the session's allowlist. The
79
+ * subscription first receives a snapshot of the app, then each live event.
80
+ *
81
+ * Callbacks for an app run one at a time, in order, and the session waits for a returned promise
82
+ * before the next one. A slow app doesn't hold up the others. If more than 1,000 deliveries wait
83
+ * for one app, its subscription ends with `delivery_overflow`.
84
+ *
85
+ * @param appId - ID of the app to follow, 24 lowercase hexadecimal characters.
86
+ * @param options - Callbacks for the app's snapshots, events and errors.
87
+ * @returns The subscription.
88
+ * @throws {TypeError} When `appId` isn't a valid app ID or the app already has a subscription.
89
+ * @throws {PlatformSocketError} With `subscription_limit` when the session has eight subscriptions.
90
+ *
91
+ * @example
92
+ * ```typescript
93
+ * // Follow an app
94
+ * const subscription = builder.subscribe(appId, {
95
+ * onSnapshot(snapshot) {
96
+ * renderChat(snapshot.messages);
97
+ * },
98
+ * onEvent(event) {
99
+ * if (event.type === 'message.updated') upsertMessage(event.data.message);
100
+ * },
101
+ * onError(error) {
102
+ * console.error(`App ${error.appId}`, error.code);
103
+ * },
104
+ * });
105
+ * ```
23
106
  */
24
107
  subscribe(appId: string, options: SubscriptionOptions): PlatformSubscription;
25
- /** Stop this session, its subscriptions and reconnection. Idempotent and terminal. */
108
+ /**
109
+ * Closes the session.
110
+ *
111
+ * Ends every subscription, stops reconnecting and disconnects the socket. Calling it again does
112
+ * nothing. A closed session can't be reused, so call [`init()`](/developers/references/platform-sdk/docs/interfaces/builder#init)
113
+ * for a new one.
114
+ *
115
+ * @example
116
+ * ```typescript
117
+ * // Close a session
118
+ * builder.close();
119
+ * ```
120
+ */
26
121
  close(): void;
27
122
  }
28
- /** One app subscription; at most eight may be active per builder session. */
123
+ /** Callbacks for one app subscription. */
29
124
  export interface SubscriptionOptions {
30
- /** Replace this app's state. Arrives after every join and rejoin, and after a main-conversation
31
- * rewrite (undo, restore, sync). Live events follow it; it holds only the last 50 messages.
125
+ /**
126
+ * Called with the app's current state, a [`PlatformSnapshot`](#platformsnapshot). Replace everything you hold for the app with it.
127
+ *
128
+ * Arrives after every join and rejoin, and after the main conversation is rewritten by an undo,
129
+ * restore or sync. Live events follow it. It holds only the last 50 messages, so merge by message
130
+ * ID to keep older history.
131
+ */
132
+ onSnapshot: (snapshot: PlatformSnapshot) => void | Promise<void>;
133
+ /**
134
+ * Called with each live event, a [`PlatformEvent`](#platformevent). Events for an app arrive one at a time, in order. If the callback
135
+ * throws or rejects, the subscription ends with `handler_failed`. New event types can be added at
136
+ * any time, so ignore types you don't handle. For every event and its payload,
137
+ * see [Socket messages](/developers/references/apps-api/sections/socket-messages).
32
138
  */
33
- onSnapshot: (snapshot: Snapshot) => void | Promise<void>;
34
- /** Apply each live event. Delivery is serial per app; a rejection ends this subscription. */
35
139
  onEvent: (event: PlatformEvent) => void | Promise<void>;
36
- /** Subscription errors. Only `snapshot_unavailable` leaves the subscription active. */
140
+ /**
141
+ * Called on errors for this app. Every error ends the subscription except `snapshot_unavailable`.
142
+ * See the [error codes](/developers/references/platform-sdk/docs/classes/PlatformSocketError#platformsocketerrorcode).
143
+ */
37
144
  onError: (error: PlatformSocketError) => void;
38
145
  }
39
- /** One app subscription's lifetime. */
146
+ /** One app subscription. */
40
147
  export interface PlatformSubscription {
41
- /** App identifier. */
148
+ /** ID of the app. */
42
149
  readonly appId: string;
43
- /** True while subscribed; false after an error or explicit unsubscribe. */
150
+ /** Whether the subscription still receives updates. It turns false after an error or {@linkcode unsubscribe | unsubscribe()}. */
44
151
  readonly active: boolean;
45
- /** Stop this app's delivery and release its subscription slot. Idempotent. */
152
+ /**
153
+ * Stops updates for the app and frees its subscription slot. Calling it again does nothing.
154
+ *
155
+ * @example
156
+ * ```typescript
157
+ * // Stop following an app
158
+ * subscription.unsubscribe();
159
+ * ```
160
+ */
46
161
  unsubscribe(): void;
47
162
  }
@@ -0,0 +1,15 @@
1
+ import type { WebhookConfigurationErrorCode, WebhookVerificationErrorCode } from "./errors.types.js";
2
+ /** A webhook delivery that cannot be trusted. The message never includes the body or signature. */
3
+ export declare class WebhookVerificationError extends Error {
4
+ /** Stable machine-readable reason. */
5
+ readonly code: WebhookVerificationErrorCode;
6
+ /** Create an error carrying only the reason. */
7
+ constructor(code: WebhookVerificationErrorCode);
8
+ }
9
+ /** Webhook public keys are missing or malformed, so no delivery can be verified. */
10
+ export declare class WebhookConfigurationError extends Error {
11
+ /** Stable machine-readable reason. */
12
+ readonly code: WebhookConfigurationErrorCode;
13
+ /** Create an error describing the misconfiguration. */
14
+ constructor(code: WebhookConfigurationErrorCode, detail: string);
15
+ }
@@ -0,0 +1,18 @@
1
+ /** A webhook delivery that cannot be trusted. The message never includes the body or signature. */
2
+ export class WebhookVerificationError extends Error {
3
+ /** Create an error carrying only the reason. */
4
+ constructor(code) {
5
+ super(`Webhook verification failed: ${code}`);
6
+ this.name = "WebhookVerificationError";
7
+ this.code = code;
8
+ }
9
+ }
10
+ /** Webhook public keys are missing or malformed, so no delivery can be verified. */
11
+ export class WebhookConfigurationError extends Error {
12
+ /** Create an error describing the misconfiguration. */
13
+ constructor(code, detail) {
14
+ super(`Webhook configuration: ${detail}`);
15
+ this.name = "WebhookConfigurationError";
16
+ this.code = code;
17
+ }
18
+ }
@@ -0,0 +1,4 @@
1
+ /** Why a delivery was refused. Respond 400: the request is not a genuine, current Base44 event. */
2
+ export type WebhookVerificationErrorCode = "missing_headers" | "timestamp_outside_tolerance" | "no_signature_entries" | "signature_mismatch" | "invalid_payload";
3
+ /** Why verification could not run at all. This is your deployment, not the request: let it surface as a 500 so Base44 retries. */
4
+ export type WebhookConfigurationErrorCode = "missing_public_keys" | "invalid_public_key";
@@ -0,0 +1 @@
1
+ export {};