@base44-preview/platform 0.1.0-pr.323.0c3777e → 0.1.0-pr.332.30ac6b3

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 (40) hide show
  1. package/README.md +31 -23
  2. package/dist/client/client.d.ts +30 -0
  3. package/dist/client/client.js +32 -0
  4. package/dist/client/client.types.d.ts +10 -0
  5. package/dist/{errors.types.d.ts → client/errors.types.d.ts} +4 -2
  6. package/dist/{index.d.ts → client/index.d.ts} +2 -2
  7. package/dist/{modules → client/modules}/builder-protocol.d.ts +7 -2
  8. package/dist/{modules → client/modules}/builder-protocol.js +19 -2
  9. package/dist/{modules → client/modules}/builder-socket.d.ts +10 -5
  10. package/dist/{modules → client/modules}/builder-socket.js +112 -84
  11. package/dist/client/modules/builder.d.ts +3 -0
  12. package/dist/client/modules/builder.events.generated.d.ts +2194 -0
  13. package/dist/{modules → client/modules}/builder.events.types.d.ts +20 -1
  14. package/dist/client/modules/builder.js +7 -0
  15. package/dist/{modules → client/modules}/builder.types.d.ts +35 -4
  16. package/dist/server/index.d.ts +3 -0
  17. package/dist/server/index.js +2 -0
  18. package/dist/server/server-url.d.ts +2 -0
  19. package/dist/server/server-url.js +8 -0
  20. package/dist/server/server.d.ts +3 -0
  21. package/dist/server/server.js +8 -0
  22. package/dist/server/server.types.d.ts +10 -0
  23. package/dist/server/server.types.js +1 -0
  24. package/package.json +17 -6
  25. package/dist/client.d.ts +0 -31
  26. package/dist/client.js +0 -37
  27. package/dist/client.types.d.ts +0 -36
  28. package/dist/modules/builder.d.ts +0 -4
  29. package/dist/modules/builder.events.generated.d.ts +0 -2194
  30. package/dist/modules/builder.js +0 -7
  31. /package/dist/{client.types.js → client/client.types.js} +0 -0
  32. /package/dist/{errors.d.ts → client/errors.d.ts} +0 -0
  33. /package/dist/{errors.js → client/errors.js} +0 -0
  34. /package/dist/{errors.types.js → client/errors.types.js} +0 -0
  35. /package/dist/{index.js → client/index.js} +0 -0
  36. /package/dist/{modules → client/modules}/builder-subscription.d.ts +0 -0
  37. /package/dist/{modules → client/modules}/builder-subscription.js +0 -0
  38. /package/dist/{modules → client/modules}/builder.events.generated.js +0 -0
  39. /package/dist/{modules → client/modules}/builder.events.types.js +0 -0
  40. /package/dist/{modules → client/modules}/builder.types.js +0 -0
package/README.md CHANGED
@@ -12,15 +12,14 @@ The workspace must have white-label sockets enabled; this SDK does not open sess
12
12
  ```ts
13
13
  import { createPlatformClient } from "@base44/platform";
14
14
 
15
- const client = createPlatformClient({
16
- socketUrl, // the session's socket_url, from POST /api/service/socket-sessions
17
- async getSessionToken() {
15
+ const client = createPlatformClient();
16
+ const builder = client.builder.init({
17
+ // Returns the body of POST /api/service/socket-sessions, unchanged.
18
+ async getSession() {
18
19
  const response = await fetch("/api/builder-socket-session", { method: "POST" });
19
20
  if (!response.ok) throw new Error("Session request failed");
20
- return (await response.json()).session_token;
21
+ return response.json();
21
22
  },
22
- });
23
- const builder = client.builder.init({
24
23
  onError(error) { showConnectionError(error.code); },
25
24
  });
26
25
  const subscription = builder.subscribe(appId, {
@@ -38,34 +37,40 @@ builder.close();
38
37
 
39
38
  `/api/builder-socket-session` is your backend's route, not an SDK endpoint. It opens a
40
39
  socket session with its workspace key (`apps:watch` scope) through
41
- `POST /api/service/socket-sessions` with `{ app_ids }`, and returns only the
42
- `session_token` and `socket_url` to the browser. Pass `socket_url` as `socketUrl`. Never pass the workspace key or any other server
43
- credential to this client. Subscribe only to apps on the session's allowlist; your
40
+ `POST /api/service/socket-sessions` with `{ app_ids }`, and returns the response body
41
+ to the browser. `getSession` returns that body unchanged: the SDK reads `session_token`,
42
+ `socket_url` and `socket_path` and ignores other keys such as `session_id` and
43
+ `expires_in`. Never pass the workspace key or any other server credential to this client. Subscribe only to apps on the session's allowlist; your
44
44
  backend adds or removes apps with `PUT`/`DELETE /api/service/socket-sessions/{session_id}/rooms/{app_id}`.
45
45
 
46
46
  A session lasts one hour and is never extended. The token goes exclusively in
47
47
  CONNECT `auth.session_token`, never a URL, and the SDK keeps it in memory only. It
48
- is reused across automatic reconnects. `getSessionToken` is called when a builder
48
+ is reused across automatic reconnects. `getSession` is called when a builder
49
49
  session first connects, and again only when the server rejects the cached token or
50
- expires the session; the SDK then reconnects once with the new token. Retrieval has
51
- a twenty-second timeout and reports `session_unavailable` on failure.
50
+ expires the session; the SDK then reconnects once with the new session. If the new
51
+ session has a different `socket_url` or `socket_path`, the SDK closes the old socket,
52
+ opens one at the new address and rejoins every active subscription. Retrieval has a
53
+ twenty-second timeout. A failure, a timeout, or a session without a token, an
54
+ HTTP(S) origin as `socket_url` (no credentials, path, query or fragment) or an
55
+ absolute `socket_path` reports `session_unavailable`.
52
56
 
53
57
  One live socket per session: a newer connection with the same token replaces the
54
58
  older one, which stops with `session_replaced`. Open one session per page.
55
59
 
56
60
  ## Lifecycle
57
61
 
58
- `createPlatformClient({ socketUrl, getSessionToken })` creates a lightweight module
59
- container: no Socket.IO instance, timers, token request or network activity. Its
62
+ `createPlatformClient()` creates a lightweight module container: no Socket.IO
63
+ instance, timers, session request or network activity. It takes no options. Its
60
64
  `builder` module follows the server SDK's module-factory pattern.
61
65
 
62
- `client.builder.init({ onError })` synchronously creates an independent `BuilderSession`
63
- without connecting. Repeated calls create separate sessions, each owning its own
66
+ `client.builder.init({ getSession, onError })` synchronously creates an independent
67
+ `BuilderSession` without connecting or creating a socket. Repeated calls create separate sessions, each owning its own
64
68
  socket, listeners, subscriptions and cleanup. Close the returned session when its
65
69
  view is disposed; the root client and other sessions remain usable.
66
70
 
67
- `builder.connect()` resolves on CONNECT, before any snapshot. The socket uses the
68
- default namespace on `/ws/socket.io/`, WebSocket only, with a dedicated manager.
71
+ `builder.connect()` fetches the first session, creates the socket at its address and
72
+ resolves on CONNECT, before any snapshot. The socket uses the default namespace on the
73
+ session's `socket_path`, WebSocket only, with a dedicated manager.
69
74
  Transport reconnection uses five attempts, starting at one second and capped at ten
70
75
  seconds with jitter; each attempt has a twenty-second timeout. A temporary server
71
76
  refusal is retried the same way. After exhaustion, a refusal or `session_replaced`,
@@ -94,9 +99,10 @@ their exceptions are isolated so they cannot interrupt another app's delivery.
94
99
 
95
100
  ## Public shapes
96
101
 
97
- - `PlatformClientOptions` (`client.types.ts`): `socketUrl`, `getSessionToken`.
102
+ - `PlatformClient` (`client.types.ts`): the `builder` module.
98
103
  - `BuilderModule` (`modules/builder.types.ts`): lazy `init(options)` factory.
99
- - `BuilderInitOptions`: connection-level `onError` observer.
104
+ - `BuilderInitOptions`: `getSession` and the connection-level `onError` observer.
105
+ - `SocketSession`: the `session_token`, `socket_url` and `socket_path` that `getSession` returns.
100
106
  - `BuilderSession`: `connect()`, `subscribe(appId, options)`, `close()`.
101
107
  - `SubscriptionOptions`: required `onSnapshot`, `onEvent` and `onError`.
102
108
  - `PlatformSubscription`: read-only `appId`, `active`, and `unsubscribe()`.
@@ -109,14 +115,16 @@ their exceptions are isolated so they cannot interrupt another app's delivery.
109
115
  event is `{room, data}`; the SDK routes by `room` and validates the envelope, while
110
116
  payload schemas and private-field filtering are the server's. Omitted keys mean
111
117
  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
118
+ null or absent is main. An event name the SDK doesn't know is forwarded as
119
+ `{type: "unknown", name, appId, data}` with only the envelope validated, so a new event reaches
120
+ partners when the service deploys it; new `room.*` notices are dropped. `PlatformSnapshot` is
113
121
  the service's `Snapshot` plus the app's `room`. Structural filtering does not promise
114
122
  redaction of generated prose or user content.
115
123
 
116
124
  ## Event types
117
125
 
118
126
  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
127
+ `asyncapi.json`. `src/client/modules/builder.events.generated.ts` is generated from it with
120
128
  `json-schema-to-typescript`: one type per schema, named after the backend model
121
129
  (`Message`, `StatusObject`, `QueueState`, one `*Call` per tool, one `*Approval` per
122
130
  guard), plus `ServerEventMap` and `ClientMessageMap`. Never edit it by hand.
@@ -148,7 +156,7 @@ exceptions, payloads and credentials are never attached.
148
156
  | Error code | Action |
149
157
  | --- | --- |
150
158
  | `connection_denied` | The session was rejected even with a fresh token: the workspace, key or session is not usable. |
151
- | `session_unavailable` | `getSessionToken` failed or timed out; no provider details are forwarded. |
159
+ | `session_unavailable` | `getSession` failed, timed out or returned an invalid session; no provider details are forwarded. |
152
160
  | `session_replaced` | Another connection with the same session took over. Stop, or open a new session. |
153
161
  | `connection_failed` | Transport failure or exhausted retries; call `connect()` after fixing connectivity. |
154
162
  | `access_denied` | The join was refused: the app is not on the session's allowlist, or joins were rate limited. |
@@ -0,0 +1,30 @@
1
+ import type { PlatformClient } 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
+ * It takes no options and opens nothing: each builder session gets its socket session from the
8
+ * `getSession` you pass to `init()`.
9
+ *
10
+ * @returns A platform client with access to the platform's modules.
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
+ *
19
+ * // Use the client to follow the AI chat in an app
20
+ * const builder = client.builder.init({
21
+ * async getSession() {
22
+ * const response = await fetch('/api/builder-socket-session', { method: 'POST' });
23
+ * return response.json();
24
+ * },
25
+ * onError: (error) => console.error(error.code),
26
+ * });
27
+ * await builder.connect();
28
+ * ```
29
+ */
30
+ export declare function createPlatformClient(): PlatformClient;
@@ -0,0 +1,32 @@
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
+ * It takes no options and opens nothing: each builder session gets its socket session from the
8
+ * `getSession` you pass to `init()`.
9
+ *
10
+ * @returns A platform client with access to the platform's modules.
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
+ *
19
+ * // Use the client to follow the AI chat in an app
20
+ * const builder = client.builder.init({
21
+ * async getSession() {
22
+ * const response = await fetch('/api/builder-socket-session', { method: 'POST' });
23
+ * return response.json();
24
+ * },
25
+ * onError: (error) => console.error(error.code),
26
+ * });
27
+ * await builder.connect();
28
+ * ```
29
+ */
30
+ export function createPlatformClient() {
31
+ return Object.freeze({ builder: Object.freeze(createBuilder()) });
32
+ }
@@ -0,0 +1,10 @@
1
+ import type { BuilderModule } from "./modules/builder.types.js";
2
+ /**
3
+ * The platform client.
4
+ *
5
+ * Provides access to the platform's modules.
6
+ */
7
+ export interface PlatformClient {
8
+ /** [Builder module](/developers/references/platform-sdk/docs/interfaces/builder) for following the AI chat in your users' apps live. */
9
+ readonly builder: BuilderModule;
10
+ }
@@ -4,9 +4,11 @@
4
4
  */
5
5
  export type SessionErrorCode =
6
6
  /**
7
- * `getSessionToken` threw, took longer than 20 seconds or returned no token.
7
+ * `getSession` threw, took longer than 20 seconds, or returned a session without a valid
8
+ * `session_token`, `socket_url` (an HTTP or HTTPS origin) or `socket_path` (an absolute path).
8
9
  *
9
- * Check the endpoint that opens sessions, then call `connect()` again. Retryable.
10
+ * Check the endpoint that opens sessions, then call `connect()` again. Retryable, except that an
11
+ * invalid field needs a fix on your server first.
10
12
  */
11
13
  "session_unavailable"
12
14
  /**
@@ -2,7 +2,7 @@
2
2
  export { createPlatformClient } from "./client.js";
3
3
  export { PlatformSocketError } from "./errors.js";
4
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";
5
+ export type { PlatformClient } from "./client.types.js";
6
+ export type { BuilderModule, BuilderInitOptions, BuilderSession, PlatformSubscription, SocketSession, SubscriptionOptions } from "./modules/builder.types.js";
7
7
  export type { GuardApproval, PlatformEvent, PlatformEventMap, PlatformSnapshot, ToolCall } from "./modules/builder.events.types.js";
8
8
  export type * from "./modules/builder.events.generated.js";
@@ -1,6 +1,9 @@
1
- import type { PlatformEvent, PlatformEventMap, PlatformSnapshot } from "./builder.events.types.js";
1
+ import type { PlatformEvent, PlatformSnapshot } from "./builder.events.types.js";
2
+ import type { SocketSession } from "./builder.types.js";
2
3
  /** App events delivered to `onEvent`: every server event except the session events the socket handles. */
3
4
  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")[];
5
+ /** A name newer than this SDK's protocol, delivered to `onEvent` as `unknown`. New `room.*` notices have no error code, so they are dropped. */
6
+ export declare const isUnknownEvent: (name: string) => boolean;
4
7
  /** Notices that name an app room, by the error code each one reports. A new notice fails to compile until it has one. */
5
8
  export declare const roomNotices: {
6
9
  readonly "room.access_denied": "access_denied";
@@ -17,5 +20,7 @@ export declare const roomFor: (appId: string) => string;
17
20
  export declare function object(value: unknown): Record<string, unknown>;
18
21
  export declare function appFromRoom(value: unknown): string | undefined;
19
22
  /** 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;
23
+ export declare function decode(name: string, appId: string, raw: unknown): PlatformEvent;
21
24
  export declare function decodeSnapshot(raw: unknown): PlatformSnapshot;
25
+ /** Keeps only the fields the socket needs; a URL with credentials, a path, query or fragment is refused. */
26
+ export declare function decodeSession(raw: unknown): SocketSession;
@@ -2,6 +2,9 @@ import { serverEventNames } from "./builder.events.generated.js";
2
2
  const sessionEvents = ["app.snapshot", "session.ended"];
3
3
  /** App events delivered to `onEvent`: every server event except the session events the socket handles. */
4
4
  export const eventNames = serverEventNames.filter((name) => !sessionEvents.includes(name) && !name.startsWith("room."));
5
+ const knownNames = serverEventNames;
6
+ /** A name newer than this SDK's protocol, delivered to `onEvent` as `unknown`. New `room.*` notices have no error code, so they are dropped. */
7
+ export const isUnknownEvent = (name) => !knownNames.includes(name) && !name.startsWith("room.");
5
8
  /** Notices that name an app room, by the error code each one reports. A new notice fails to compile until it has one. */
6
9
  export const roomNotices = {
7
10
  "room.access_denied": "access_denied",
@@ -25,8 +28,9 @@ export function appFromRoom(value) {
25
28
  return typeof value === "string" && /^\/apps\/[a-f0-9]{24}$/.test(value) ? value.slice(6) : undefined;
26
29
  }
27
30
  /** Every event is `{room, data}`; payload schemas are the service's, so only the envelope is validated. */
28
- export function decode(type, appId, raw) {
29
- return { type, appId, data: object(object(raw).data) };
31
+ export function decode(name, appId, raw) {
32
+ const data = object(object(raw).data);
33
+ return (knownNames.includes(name) ? { type: name, appId, data } : { type: "unknown", name, appId, data });
30
34
  }
31
35
  export function decodeSnapshot(raw) {
32
36
  const frame = object(raw);
@@ -37,3 +41,16 @@ export function decodeSnapshot(raw) {
37
41
  const queue = data.queue !== null && typeof data.queue === "object" ? { queue: data.queue } : {};
38
42
  return { room: frame.room, status: data.status, messages: data.messages, ...queue };
39
43
  }
44
+ /** Keeps only the fields the socket needs; a URL with credentials, a path, query or fragment is refused. */
45
+ export function decodeSession(raw) {
46
+ const { session_token, socket_url, socket_path } = object(raw);
47
+ if (typeof session_token !== "string" || !session_token.trim())
48
+ throw new Error("Invalid session token");
49
+ if (typeof socket_url !== "string" || typeof socket_path !== "string" || !/^\/(?!\/)[^?#\s]*$/.test(socket_path))
50
+ throw new Error("Invalid socket address");
51
+ const url = new URL(socket_url);
52
+ if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || url.pathname !== "/") {
53
+ throw new Error("Invalid socket URL");
54
+ }
55
+ return { session_token, socket_url: url.origin, socket_path };
56
+ }
@@ -1,12 +1,12 @@
1
- import type { PlatformClientOptions } from "../client.types.js";
2
1
  import type { BuilderInitOptions, BuilderSession, PlatformSubscription, SubscriptionOptions } from "./builder.types.js";
3
2
  /** @internal */
4
3
  export declare class BuilderSocket implements BuilderSession {
5
- private readonly socket;
4
+ private socket?;
5
+ private address?;
6
6
  private readonly subscriptions;
7
7
  private readonly options;
8
8
  private closed;
9
- private token?;
9
+ private session?;
10
10
  private tokenFresh;
11
11
  private ending?;
12
12
  private denialRetries;
@@ -16,8 +16,9 @@ export declare class BuilderSocket implements BuilderSession {
16
16
  private connecting?;
17
17
  private resolveConnect?;
18
18
  private rejectConnect?;
19
- constructor(config: PlatformClientOptions, options: BuilderInitOptions);
20
- /** Connect with the session token. Resolves on CONNECT, before snapshots arrive.
19
+ constructor(options: BuilderInitOptions);
20
+ /** Connect with the session's token. Resolves on CONNECT, before snapshots arrive.
21
+ * The first call fetches the session, whose address the socket opens on.
21
22
  * Transport loss retries up to five times and rejoins active subscriptions.
22
23
  * Call again after a failure or `session_replaced`; concurrent calls share one attempt.
23
24
  */
@@ -29,7 +30,11 @@ export declare class BuilderSocket implements BuilderSession {
29
30
  subscribe(appId: string, options: SubscriptionOptions): PlatformSubscription;
30
31
  /** Stop delivery, cancel reconnection and release all listeners. Idempotent and terminal. */
31
32
  close(): void;
33
+ private open;
34
+ private appEvent;
35
+ private discard;
32
36
  private join;
37
+ /** Without a callback, or when a new session moves the socket, opens a socket at the session's address. */
33
38
  private authenticate;
34
39
  /** A connect the server refused. Transport errors are Socket.IO's to retry. */
35
40
  private refused;
@@ -1,84 +1,28 @@
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, sessionEndings } from "./builder-protocol.js";
3
+ import { appFromRoom, appPattern, decode, decodeSession, decodeSnapshot, eventNames, isUnknownEvent, 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 */
7
7
  export class BuilderSocket {
8
- constructor(config, options) {
8
+ constructor(options) {
9
9
  this.subscriptions = new Map();
10
10
  this.closed = false;
11
11
  this.tokenFresh = false;
12
12
  this.denialRetries = 0;
13
13
  this.authAttempt = 0;
14
- this.options = { ...config, onError: options.onError };
15
- this.socket = io(config.socketUrl, {
16
- path: "/ws/socket.io/", transports: ["websocket"], autoConnect: false,
17
- forceNew: true, reconnectionAttempts: 5, reconnectionDelay: 1000, reconnectionDelayMax: 10000,
18
- timeout: 20000,
19
- auth: (callback) => { void this.authenticate(callback); },
20
- });
21
- this.socket.on("connect", () => {
22
- var _a;
23
- this.tokenFresh = false;
24
- this.denialRetries = 0;
25
- for (const subscription of this.subscriptions.values())
26
- this.join(subscription);
27
- (_a = this.resolveConnect) === null || _a === void 0 ? void 0 : _a.call(this);
28
- this.clearConnecting();
29
- });
30
- this.socket.on("disconnect", (reason) => {
31
- ++this.authAttempt;
32
- if (this.closed || reason !== "io server disconnect")
33
- return; // Transport loss reconnects by itself.
34
- const ending = this.ending;
35
- this.ending = undefined;
36
- if (ending === "session_expired")
37
- this.socket.connect(); // Renew through getSessionToken.
38
- else
39
- this.connectionError(new PlatformSocketError(ending !== null && ending !== void 0 ? ending : "connection_failed"));
40
- });
41
- this.socket.on("connect_error", (error) => this.refused(error));
42
- this.socket.io.on("reconnect_failed", () => this.connectionError(new PlatformSocketError("connection_failed")));
43
- this.socket.on("app.snapshot", (raw) => {
44
- var _a;
45
- try {
46
- const snapshot = decodeSnapshot(raw);
47
- (_a = this.subscriptions.get(appFromRoom(snapshot.room))) === null || _a === void 0 ? void 0 : _a.snapshot(snapshot);
48
- }
49
- catch (_b) {
50
- this.protocolError(raw);
51
- }
52
- });
53
- this.socket.on("session.ended", (raw) => this.sessionEnded(raw));
54
- for (const [name, code] of Object.entries(roomNotices))
55
- this.socket.on(name, (raw) => this.roomNotice(code, raw));
56
- for (const type of eventNames)
57
- this.socket.on(type, (raw) => {
58
- try {
59
- const appId = appFromRoom(object(raw).room);
60
- if (!appId)
61
- throw new Error("Invalid app");
62
- const event = decode(type, appId, raw);
63
- const subscription = this.subscriptions.get(appId);
64
- subscription === null || subscription === void 0 ? void 0 : subscription.event(event);
65
- // The server does not resend a snapshot after a rewrite of main: rejoining asks for one.
66
- if (subscription && event.type === "conversation.changed" && event.data.branch_id == null)
67
- this.join(subscription);
68
- }
69
- catch (_a) {
70
- this.protocolError(raw);
71
- }
72
- });
73
- }
74
- /** Connect with the session token. Resolves on CONNECT, before snapshots arrive.
14
+ this.options = { getSession: options.getSession, onError: options.onError };
15
+ }
16
+ /** Connect with the session's token. Resolves on CONNECT, before snapshots arrive.
17
+ * The first call fetches the session, whose address the socket opens on.
75
18
  * Transport loss retries up to five times and rejoins active subscriptions.
76
19
  * Call again after a failure or `session_replaced`; concurrent calls share one attempt.
77
20
  */
78
21
  connect() {
22
+ var _a;
79
23
  if (this.closed)
80
24
  return Promise.reject(new PlatformSocketError("client_closed"));
81
- if (this.socket.connected)
25
+ if ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.connected)
82
26
  return Promise.resolve();
83
27
  if (this.connecting)
84
28
  return this.connecting;
@@ -87,7 +31,10 @@ export class BuilderSocket {
87
31
  this.rejectConnect = reject;
88
32
  });
89
33
  this.connecting = promise;
90
- this.socket.connect();
34
+ if (this.socket)
35
+ this.socket.connect();
36
+ else
37
+ void this.authenticate();
91
38
  return promise;
92
39
  }
93
40
  /** Subscribe before or after connecting. One subscription per app, maximum eight, each on the
@@ -95,6 +42,7 @@ export class BuilderSocket {
95
42
  * an invalid frame or a server refusal ends the subscription.
96
43
  */
97
44
  subscribe(appId, options) {
45
+ var _a;
98
46
  if (this.closed)
99
47
  throw new PlatformSocketError("client_closed");
100
48
  if (!appPattern.test(appId))
@@ -104,12 +52,13 @@ export class BuilderSocket {
104
52
  if (this.subscriptions.size >= 8)
105
53
  throw new PlatformSocketError("subscription_limit", appId);
106
54
  const subscription = new Subscription(appId, { ...options }, () => {
55
+ var _a;
107
56
  this.subscriptions.delete(appId);
108
- if (this.socket.connected)
57
+ if ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.connected)
109
58
  this.socket.emit("leave", roomFor(appId));
110
59
  });
111
60
  this.subscriptions.set(appId, subscription);
112
- if (this.socket.connected)
61
+ if ((_a = this.socket) === null || _a === void 0 ? void 0 : _a.connected)
113
62
  this.join(subscription);
114
63
  return subscription;
115
64
  }
@@ -126,38 +75,117 @@ export class BuilderSocket {
126
75
  subscription.unsubscribe();
127
76
  (_b = this.rejectConnect) === null || _b === void 0 ? void 0 : _b.call(this, new PlatformSocketError("client_closed"));
128
77
  this.clearConnecting();
78
+ this.discard();
79
+ }
80
+ open(url, path) {
81
+ this.discard();
82
+ const socket = this.socket = io(url, {
83
+ path, transports: ["websocket"], autoConnect: false,
84
+ forceNew: true, reconnectionAttempts: 5, reconnectionDelay: 1000, reconnectionDelayMax: 10000,
85
+ timeout: 20000,
86
+ auth: (callback) => { void this.authenticate(callback); },
87
+ });
88
+ this.address = url + path;
89
+ socket.on("connect", () => {
90
+ var _a;
91
+ this.tokenFresh = false;
92
+ this.denialRetries = 0;
93
+ for (const subscription of this.subscriptions.values())
94
+ this.join(subscription);
95
+ (_a = this.resolveConnect) === null || _a === void 0 ? void 0 : _a.call(this);
96
+ this.clearConnecting();
97
+ });
98
+ socket.on("disconnect", (reason) => {
99
+ ++this.authAttempt;
100
+ if (this.closed || reason !== "io server disconnect")
101
+ return; // Transport loss reconnects by itself.
102
+ const ending = this.ending;
103
+ this.ending = undefined;
104
+ if (ending === "session_expired")
105
+ socket.connect(); // Renew through getSession.
106
+ else
107
+ this.connectionError(new PlatformSocketError(ending !== null && ending !== void 0 ? ending : "connection_failed"));
108
+ });
109
+ socket.on("connect_error", (error) => this.refused(error));
110
+ socket.io.on("reconnect_failed", () => this.connectionError(new PlatformSocketError("connection_failed")));
111
+ socket.on("app.snapshot", (raw) => {
112
+ var _a;
113
+ try {
114
+ const snapshot = decodeSnapshot(raw);
115
+ (_a = this.subscriptions.get(appFromRoom(snapshot.room))) === null || _a === void 0 ? void 0 : _a.snapshot(snapshot);
116
+ }
117
+ catch (_b) {
118
+ this.protocolError(raw);
119
+ }
120
+ });
121
+ socket.on("session.ended", (raw) => this.sessionEnded(raw));
122
+ for (const [name, code] of Object.entries(roomNotices))
123
+ socket.on(name, (raw) => this.roomNotice(code, raw));
124
+ for (const name of eventNames)
125
+ socket.on(name, (raw) => this.appEvent(name, raw));
126
+ // An unknown event with no app room (a future session-wide event) has nowhere to go: ignore it.
127
+ socket.onAny((name, raw) => {
128
+ if (isUnknownEvent(name) && appFromRoom(raw === null || raw === void 0 ? void 0 : raw.room))
129
+ this.appEvent(name, raw);
130
+ });
131
+ socket.connect();
132
+ }
133
+ appEvent(name, raw) {
134
+ try {
135
+ const appId = appFromRoom(object(raw).room);
136
+ if (!appId)
137
+ throw new Error("Invalid app");
138
+ const event = decode(name, appId, raw);
139
+ const subscription = this.subscriptions.get(appId);
140
+ subscription === null || subscription === void 0 ? void 0 : subscription.event(event);
141
+ // The server does not resend a snapshot after a rewrite of main: rejoining asks for one.
142
+ if (subscription && event.type === "conversation.changed" && event.data.branch_id == null)
143
+ this.join(subscription);
144
+ }
145
+ catch (_a) {
146
+ this.protocolError(raw);
147
+ }
148
+ }
149
+ discard() {
150
+ if (!this.socket)
151
+ return;
129
152
  this.socket.removeAllListeners();
153
+ this.socket.offAny();
130
154
  this.socket.io.removeAllListeners();
131
155
  this.socket.disconnect();
132
156
  }
133
157
  join(subscription) {
134
- this.socket.emit("join", roomFor(subscription.appId));
158
+ var _a;
159
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.emit("join", roomFor(subscription.appId));
135
160
  }
161
+ /** Without a callback, or when a new session moves the socket, opens a socket at the session's address. */
136
162
  async authenticate(callback) {
137
- var _a;
163
+ var _a, _b;
138
164
  const attempt = ++this.authAttempt;
139
165
  (_a = this.cancelAuth) === null || _a === void 0 ? void 0 : _a.call(this);
140
166
  let timer;
141
167
  const timeout = new Promise((_, reject) => {
142
- timer = setTimeout(() => reject(new Error("Session token timeout")), 20000);
168
+ timer = setTimeout(() => reject(new Error("Session timeout")), 20000);
143
169
  this.cancelAuth = () => { clearTimeout(timer); reject(new Error("Cancelled")); };
144
170
  });
145
171
  try {
146
- if (!this.token) {
147
- const token = await Promise.race([Promise.resolve().then(() => this.options.getSessionToken()), timeout]);
172
+ if (!this.session) {
173
+ const session = await Promise.race([Promise.resolve().then(() => this.options.getSession()), timeout]);
148
174
  if (this.closed || attempt !== this.authAttempt)
149
175
  return;
150
- if (typeof token !== "string" || !token.trim())
151
- throw new Error("Missing session token");
152
- this.token = token;
176
+ this.session = decodeSession(session);
153
177
  this.tokenFresh = true;
154
178
  }
155
- callback({ session_token: this.token });
179
+ const { session_token, socket_url, socket_path } = this.session;
180
+ if (callback && this.address === socket_url + socket_path)
181
+ callback({ session_token });
182
+ else
183
+ this.open(socket_url, socket_path);
156
184
  }
157
- catch (_b) {
185
+ catch (_c) {
158
186
  if (this.closed || attempt !== this.authAttempt)
159
187
  return;
160
- this.socket.disconnect();
188
+ (_b = this.socket) === null || _b === void 0 ? void 0 : _b.disconnect();
161
189
  this.connectionError(new PlatformSocketError("session_unavailable"));
162
190
  }
163
191
  finally {
@@ -168,7 +196,7 @@ export class BuilderSocket {
168
196
  }
169
197
  /** A connect the server refused. Transport errors are Socket.IO's to retry. */
170
198
  refused(error) {
171
- var _a;
199
+ var _a, _b;
172
200
  if (this.closed || error.message !== "connection_denied")
173
201
  return;
174
202
  if (((_a = error.data) === null || _a === void 0 ? void 0 : _a.retryable) === true) {
@@ -177,9 +205,9 @@ export class BuilderSocket {
177
205
  }
178
206
  // A token this attempt did not just fetch may have expired: renew it once.
179
207
  const renew = !this.tokenFresh;
180
- this.token = undefined;
208
+ this.session = undefined;
181
209
  if (renew)
182
- this.socket.connect();
210
+ (_b = this.socket) === null || _b === void 0 ? void 0 : _b.connect();
183
211
  else
184
212
  this.connectionError(new PlatformSocketError("connection_denied"));
185
213
  }
@@ -190,8 +218,8 @@ export class BuilderSocket {
190
218
  return;
191
219
  }
192
220
  const delay = Math.min(1000 * 2 ** (this.denialRetries - 1), 10000) * (0.5 + Math.random() / 2);
193
- this.retryTimer = setTimeout(() => { this.retryTimer = undefined; if (!this.closed)
194
- this.socket.connect(); }, delay);
221
+ this.retryTimer = setTimeout(() => { var _a; this.retryTimer = undefined; if (!this.closed)
222
+ (_a = this.socket) === null || _a === void 0 ? void 0 : _a.connect(); }, delay);
195
223
  }
196
224
  clearConnecting() {
197
225
  this.connecting = undefined;
@@ -213,7 +241,7 @@ export class BuilderSocket {
213
241
  if (!ending)
214
242
  throw new Error("Unknown reason");
215
243
  // The server disconnects next; the disconnect handler renews or stops.
216
- this.token = undefined;
244
+ this.session = undefined;
217
245
  this.ending = ending;
218
246
  }
219
247
  catch (_a) {
@@ -0,0 +1,3 @@
1
+ import type { BuilderModule } from "./builder.types.js";
2
+ /** @internal */
3
+ export declare function createBuilder(): BuilderModule;