@base44-preview/sdk 0.8.40-pr.212.c163c94 → 0.8.40-pr.212.d742832
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client.js +6 -7
- package/dist/client.types.d.ts +6 -20
- package/dist/modules/actors.d.ts +6 -20
- package/dist/modules/actors.js +106 -92
- package/dist/modules/actors.types.d.ts +38 -26
- package/dist/modules/ai-gateway.types.d.ts +70 -19
- package/dist/modules/sso.types.d.ts +28 -22
- package/package.json +1 -1
package/dist/client.js
CHANGED
|
@@ -52,19 +52,19 @@ import { createActorsModule } from "./modules/actors.js";
|
|
|
52
52
|
*/
|
|
53
53
|
export function createClient(config) {
|
|
54
54
|
var _a, _b;
|
|
55
|
-
const { serverUrl = "https://base44.app", appId, token, serviceToken, requiresAuth = false, appBaseUrl, options, functionsVersion, headers: optionalHeaders,
|
|
55
|
+
const { serverUrl = "https://base44.app", appId, token, serviceToken, requiresAuth = false, appBaseUrl, options, functionsVersion, headers: optionalHeaders, actorsWsUrl, } = config;
|
|
56
56
|
// Normalize appBaseUrl to always be a string (empty if not provided or invalid)
|
|
57
57
|
const normalizedAppBaseUrl = typeof appBaseUrl === "string" ? appBaseUrl : "";
|
|
58
|
-
// Derive the
|
|
58
|
+
// Derive the Actor WebSocket URL if not explicitly provided. Default to
|
|
59
59
|
// the app's OWN origin (the app URL proxies /parties to the backend) so the
|
|
60
60
|
// socket is same-origin with the running app, not the API host: prefer an
|
|
61
61
|
// explicit appBaseUrl, then the browser origin, then fall back to serverUrl
|
|
62
62
|
// (Node/SSR, where there's no window). Convert https:// → wss:// (http → ws)
|
|
63
63
|
// and strip the trailing slash.
|
|
64
|
-
const
|
|
64
|
+
const resolvedActorsWsUrl = (() => {
|
|
65
65
|
var _a, _b;
|
|
66
|
-
if (
|
|
67
|
-
return
|
|
66
|
+
if (actorsWsUrl)
|
|
67
|
+
return actorsWsUrl.replace(/\/$/, "");
|
|
68
68
|
const appOrigin = normalizedAppBaseUrl ||
|
|
69
69
|
// React Native has a bare `window` with no `location`, so guard both.
|
|
70
70
|
(typeof window !== "undefined" ? (_b = (_a = window.location) === null || _a === void 0 ? void 0 : _a.origin) !== null && _b !== void 0 ? _b : "" : "");
|
|
@@ -181,8 +181,7 @@ export function createClient(config) {
|
|
|
181
181
|
}),
|
|
182
182
|
actors: createActorsModule({
|
|
183
183
|
appId,
|
|
184
|
-
|
|
185
|
-
webSocketImpl,
|
|
184
|
+
actorsWsUrl: resolvedActorsWsUrl,
|
|
186
185
|
functionsVersion,
|
|
187
186
|
// Same credential as function calls; the platform proxy authenticates the
|
|
188
187
|
// WS connection with it (anonymous when absent) — no pre-connect token mint.
|
package/dist/client.types.d.ts
CHANGED
|
@@ -75,27 +75,15 @@ export interface CreateClientConfig {
|
|
|
75
75
|
*/
|
|
76
76
|
options?: CreateClientOptions;
|
|
77
77
|
/**
|
|
78
|
-
* Base WebSocket URL for
|
|
78
|
+
* Base WebSocket URL for Actor connections.
|
|
79
79
|
*
|
|
80
80
|
* Defaults to the app's own origin (`appBaseUrl`, else the browser's
|
|
81
81
|
* `window.location.origin`, else `serverUrl`) with `https://` replaced by
|
|
82
|
-
* `wss://` (or `http://` by `ws://`) — so the
|
|
83
|
-
* with the running app, which proxies `/parties` to the backend.
|
|
84
|
-
* Override when the
|
|
82
|
+
* `wss://` (or `http://` by `ws://`) — so the Actor socket is same-origin
|
|
83
|
+
* with the running app, which proxies `/parties` to the backend dispatcher.
|
|
84
|
+
* Override only when the Actor host differs from the app origin.
|
|
85
85
|
*/
|
|
86
|
-
|
|
87
|
-
/**
|
|
88
|
-
* WebSocket implementation for realtime subscriptions in environments
|
|
89
|
-
* without a global `WebSocket` (Node.js < 22). Browsers and Node ≥ 22
|
|
90
|
-
* don't need this.
|
|
91
|
-
*
|
|
92
|
-
* @example
|
|
93
|
-
* ```typescript
|
|
94
|
-
* import WS from "ws";
|
|
95
|
-
* const base44 = createClient({ appId, webSocketImpl: WS });
|
|
96
|
-
* ```
|
|
97
|
-
*/
|
|
98
|
-
webSocketImpl?: unknown;
|
|
86
|
+
actorsWsUrl?: string;
|
|
99
87
|
}
|
|
100
88
|
/**
|
|
101
89
|
* The Base44 client instance.
|
|
@@ -164,9 +152,7 @@ export interface Base44Client {
|
|
|
164
152
|
functions: FunctionsModule;
|
|
165
153
|
/** {@link IntegrationsModule | Integrations module} with elevated permissions. */
|
|
166
154
|
integrations: IntegrationsModule;
|
|
167
|
-
/** {@link SsoModule | SSO module} for generating SSO tokens.
|
|
168
|
-
* @internal
|
|
169
|
-
*/
|
|
155
|
+
/** {@link SsoModule | SSO module} for generating SSO tokens. */
|
|
170
156
|
sso: SsoModule;
|
|
171
157
|
/** Cleanup function to disconnect WebSocket connections. */
|
|
172
158
|
cleanup: () => void;
|
package/dist/modules/actors.d.ts
CHANGED
|
@@ -1,27 +1,13 @@
|
|
|
1
|
-
|
|
1
|
+
import type { ActorRoom } from "./actors.types.js";
|
|
2
|
+
interface ActorsConfig {
|
|
2
3
|
appId: string;
|
|
3
|
-
/** Current user access token, if authenticated. Rides the WS query
|
|
4
|
-
*
|
|
5
|
-
* connection like a backend-function call; anonymous connects omit it. */
|
|
4
|
+
/** Current user access token, if authenticated. Rides the WS query so the
|
|
5
|
+
* platform proxy can authenticate the connection; anonymous connects omit it. */
|
|
6
6
|
getAuthToken(): string | null | undefined;
|
|
7
7
|
/** Same semantics as function calls: editors with a non-prod version get the
|
|
8
8
|
* draft actor script; everyone else gets the published one. */
|
|
9
9
|
functionsVersion?: string;
|
|
10
|
-
|
|
11
|
-
/** WebSocket implementation for runtimes without a global one (Node < 22). */
|
|
12
|
-
webSocketImpl?: unknown;
|
|
13
|
-
}): Record<string, ActorClient>;
|
|
14
|
-
/** Handle for an active actor subscription. */
|
|
15
|
-
interface ActorSubscription {
|
|
16
|
-
/** This connection's id — the same value the actor receives as `conn.id`. */
|
|
17
|
-
id: string;
|
|
18
|
-
/** Close the subscription and its underlying socket. */
|
|
19
|
-
unsubscribe(): void;
|
|
20
|
-
}
|
|
21
|
-
interface ActorClient {
|
|
22
|
-
subscribe(instanceId: string, callback: (data: unknown) => void, options?: {
|
|
23
|
-
id?: string;
|
|
24
|
-
}): ActorSubscription;
|
|
25
|
-
send(instanceId: string, data: unknown): void;
|
|
10
|
+
actorsWsUrl: string;
|
|
26
11
|
}
|
|
12
|
+
export declare function createActorsModule(config: ActorsConfig): Record<string, (instanceId: string) => ActorRoom>;
|
|
27
13
|
export {};
|
package/dist/modules/actors.js
CHANGED
|
@@ -1,100 +1,114 @@
|
|
|
1
1
|
import PartySocket from "partysocket";
|
|
2
|
-
//
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
2
|
+
// Heartbeat / half-open detection: PartySocket only reconnects on a close/error
|
|
3
|
+
// event, so ping periodically and force a reconnect if nothing returns in DEAD_MS.
|
|
4
|
+
const PING_MS = 1000;
|
|
5
|
+
const DEAD_MS = 3000;
|
|
6
|
+
class Room {
|
|
7
|
+
constructor(actorName, instanceId, config) {
|
|
8
|
+
this.actorName = actorName;
|
|
9
|
+
this.instanceId = instanceId;
|
|
10
|
+
this.config = config;
|
|
11
|
+
this.ws = null;
|
|
12
|
+
this.listeners = new Set();
|
|
13
|
+
this.heartbeat = null;
|
|
14
|
+
this.connId = null;
|
|
15
|
+
}
|
|
16
|
+
get id() {
|
|
17
|
+
if (!this.connId) {
|
|
18
|
+
throw new Error(`${this.actorName}:${this.instanceId}: connect() before reading id`);
|
|
19
|
+
}
|
|
20
|
+
return this.connId;
|
|
21
|
+
}
|
|
22
|
+
connect(options) {
|
|
23
|
+
var _a;
|
|
24
|
+
if (this.ws)
|
|
25
|
+
return this;
|
|
26
|
+
// The client picks its own conn id; it becomes _pk → the actor's conn.id.
|
|
27
|
+
const connId = (_a = options === null || options === void 0 ? void 0 : options.id) !== null && _a !== void 0 ? _a : crypto.randomUUID();
|
|
28
|
+
this.connId = connId;
|
|
29
|
+
const ws = new PartySocket({
|
|
30
|
+
host: this.config.actorsWsUrl,
|
|
31
|
+
party: this.actorName,
|
|
32
|
+
room: this.instanceId,
|
|
33
|
+
id: connId,
|
|
34
|
+
// Re-read on every (re)connect so a login/logout is picked up.
|
|
35
|
+
query: () => {
|
|
36
|
+
const token = this.config.getAuthToken();
|
|
37
|
+
return {
|
|
38
|
+
app_id: this.config.appId,
|
|
39
|
+
handler: this.actorName,
|
|
40
|
+
...(token ? { token } : {}),
|
|
41
|
+
...(this.config.functionsVersion ? { fv: this.config.functionsVersion } : {}),
|
|
42
|
+
};
|
|
43
|
+
},
|
|
44
|
+
});
|
|
45
|
+
this.ws = ws;
|
|
46
|
+
let lastMsg = Date.now();
|
|
47
|
+
const bumpAlive = () => { lastMsg = Date.now(); };
|
|
48
|
+
ws.addEventListener("open", bumpAlive);
|
|
49
|
+
ws.addEventListener("message", (ev) => {
|
|
50
|
+
bumpAlive();
|
|
51
|
+
let data;
|
|
52
|
+
try {
|
|
53
|
+
data = JSON.parse(ev.data);
|
|
54
|
+
}
|
|
55
|
+
catch (_a) {
|
|
56
|
+
return; // ignore malformed
|
|
57
|
+
}
|
|
58
|
+
const msgType = data && typeof data === "object" ? data.type : undefined;
|
|
59
|
+
if (msgType === "__pong")
|
|
60
|
+
return; // platform message — never surface it
|
|
61
|
+
for (const listener of this.listeners)
|
|
62
|
+
listener(data);
|
|
63
|
+
});
|
|
64
|
+
this.heartbeat = setInterval(() => {
|
|
65
|
+
if (Date.now() - lastMsg > DEAD_MS) {
|
|
66
|
+
bumpAlive(); // avoid a reconnect storm while the new socket comes up
|
|
67
|
+
ws.reconnect();
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
// Server contract: the deployed Actor shim echoes __ping with __pong
|
|
72
|
+
// (see base44-userapp-bundler shim/actor.ts). If that ever stops, an
|
|
73
|
+
// idle room's lastMsg goes stale and this watchdog reconnects every DEAD_MS.
|
|
74
|
+
ws.send(JSON.stringify({ type: "__ping" }));
|
|
75
|
+
}
|
|
76
|
+
catch (_a) {
|
|
77
|
+
// socket not open; the watchdog above will force a reconnect
|
|
78
|
+
}
|
|
79
|
+
}, PING_MS);
|
|
80
|
+
return this;
|
|
81
|
+
}
|
|
82
|
+
subscribe(callback) {
|
|
83
|
+
if (!this.ws) {
|
|
84
|
+
throw new Error(`${this.actorName}:${this.instanceId}: connect() before subscribe()`);
|
|
85
|
+
}
|
|
86
|
+
this.listeners.add(callback);
|
|
87
|
+
return {
|
|
88
|
+
unsubscribe: () => { this.listeners.delete(callback); },
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
send(data) {
|
|
92
|
+
if (!this.ws) {
|
|
93
|
+
throw new Error(`${this.actorName}:${this.instanceId}: connect() before send()`);
|
|
94
|
+
}
|
|
95
|
+
this.ws.send(JSON.stringify(data));
|
|
96
|
+
}
|
|
97
|
+
close() {
|
|
98
|
+
var _a;
|
|
99
|
+
if (this.heartbeat) {
|
|
100
|
+
clearInterval(this.heartbeat);
|
|
101
|
+
this.heartbeat = null;
|
|
102
|
+
}
|
|
103
|
+
this.listeners.clear();
|
|
104
|
+
(_a = this.ws) === null || _a === void 0 ? void 0 : _a.close();
|
|
105
|
+
this.ws = null;
|
|
106
|
+
}
|
|
6
107
|
}
|
|
7
108
|
export function createActorsModule(config) {
|
|
8
109
|
return new Proxy({}, {
|
|
9
110
|
get(_, actorName) {
|
|
10
|
-
return
|
|
11
|
-
subscribe(instanceId, callback, options) {
|
|
12
|
-
var _a, _b;
|
|
13
|
-
const key = socketKey(actorName, instanceId);
|
|
14
|
-
// close existing if any
|
|
15
|
-
(_a = activeSockets.get(key)) === null || _a === void 0 ? void 0 : _a.close();
|
|
16
|
-
// Connection id: caller-supplied (stable — reuse across reconnects/tabs as
|
|
17
|
-
// you see fit) or auto-generated per subscription. PartySocket sends it
|
|
18
|
-
// as ?_pk=; the platform proxy validates it and the actor sees this exact
|
|
19
|
-
// value as conn.id, stable across reconnects.
|
|
20
|
-
const connId = (_b = options === null || options === void 0 ? void 0 : options.id) !== null && _b !== void 0 ? _b : crypto.randomUUID();
|
|
21
|
-
// No pre-connect token mint: the platform proxy authenticates the
|
|
22
|
-
// connection itself, exactly like a backend-function call. `handler`
|
|
23
|
-
// carries the case-preserved actor name (the `party` path segment is
|
|
24
|
-
// lowercased by PartySocket). query as fn: re-read on every (re)connect
|
|
25
|
-
// so a login/logout between reconnects is picked up.
|
|
26
|
-
const ws = new PartySocket({
|
|
27
|
-
host: config.dispatcherWsUrl,
|
|
28
|
-
party: actorName,
|
|
29
|
-
room: instanceId,
|
|
30
|
-
id: connId,
|
|
31
|
-
...(config.webSocketImpl ? { WebSocket: config.webSocketImpl } : {}),
|
|
32
|
-
query: () => {
|
|
33
|
-
const token = config.getAuthToken();
|
|
34
|
-
return {
|
|
35
|
-
app_id: config.appId,
|
|
36
|
-
handler: actorName,
|
|
37
|
-
...(token ? { token } : {}),
|
|
38
|
-
...(config.functionsVersion ? { fv: config.functionsVersion } : {}),
|
|
39
|
-
};
|
|
40
|
-
},
|
|
41
|
-
});
|
|
42
|
-
activeSockets.set(key, ws);
|
|
43
|
-
// Heartbeat / half-open detection. PartySocket only reconnects on a
|
|
44
|
-
// browser close/error event, so a silently-dead connection (TCP alive,
|
|
45
|
-
// no data — common behind proxies/LBs) hangs until the OS idle timeout
|
|
46
|
-
// (~60s). We ping periodically and force a reconnect if nothing comes
|
|
47
|
-
// back within DEAD_MS, cutting detection from ~60s to a few seconds.
|
|
48
|
-
const PING_MS = 1000;
|
|
49
|
-
const DEAD_MS = 3000;
|
|
50
|
-
let lastMsg = Date.now();
|
|
51
|
-
const bumpAlive = () => { lastMsg = Date.now(); };
|
|
52
|
-
ws.addEventListener("open", bumpAlive);
|
|
53
|
-
ws.addEventListener("message", (ev) => {
|
|
54
|
-
bumpAlive();
|
|
55
|
-
let data;
|
|
56
|
-
try {
|
|
57
|
-
data = JSON.parse(ev.data);
|
|
58
|
-
}
|
|
59
|
-
catch (_a) {
|
|
60
|
-
return; // ignore malformed
|
|
61
|
-
}
|
|
62
|
-
// Swallow platform messages — never surface them to the app.
|
|
63
|
-
const msgType = data && typeof data === "object" ? data.type : undefined;
|
|
64
|
-
if (msgType === "__pong")
|
|
65
|
-
return;
|
|
66
|
-
callback(data);
|
|
67
|
-
});
|
|
68
|
-
const heartbeat = setInterval(() => {
|
|
69
|
-
if (Date.now() - lastMsg > DEAD_MS) {
|
|
70
|
-
bumpAlive(); // avoid a reconnect storm while the new socket comes up
|
|
71
|
-
ws.reconnect();
|
|
72
|
-
return;
|
|
73
|
-
}
|
|
74
|
-
try {
|
|
75
|
-
ws.send(JSON.stringify({ type: "__ping" }));
|
|
76
|
-
}
|
|
77
|
-
catch (_a) {
|
|
78
|
-
// socket not open; the watchdog above will force a reconnect
|
|
79
|
-
}
|
|
80
|
-
}, PING_MS);
|
|
81
|
-
return {
|
|
82
|
-
id: connId, // the connection id (same value the actor sees as conn.id)
|
|
83
|
-
unsubscribe() {
|
|
84
|
-
clearInterval(heartbeat);
|
|
85
|
-
activeSockets.delete(key);
|
|
86
|
-
ws.close();
|
|
87
|
-
},
|
|
88
|
-
};
|
|
89
|
-
},
|
|
90
|
-
send(instanceId, data) {
|
|
91
|
-
const key = socketKey(actorName, instanceId);
|
|
92
|
-
const ws = activeSockets.get(key);
|
|
93
|
-
if (!ws)
|
|
94
|
-
throw new Error(`No active subscription for ${actorName}:${instanceId}`);
|
|
95
|
-
ws.send(JSON.stringify(data));
|
|
96
|
-
},
|
|
97
|
-
};
|
|
111
|
+
return (instanceId) => new Room(actorName, instanceId, config);
|
|
98
112
|
},
|
|
99
113
|
});
|
|
100
114
|
}
|
|
@@ -32,43 +32,55 @@ type ToClientFor<N extends string> = N extends keyof ActorRegistry ? ActorRegist
|
|
|
32
32
|
type ToServerFor<N extends string> = N extends keyof ActorRegistry ? ActorRegistry[N] extends {
|
|
33
33
|
toServer: infer O;
|
|
34
34
|
} ? O : unknown : unknown;
|
|
35
|
-
/**
|
|
36
|
-
|
|
37
|
-
* Typed automatically when the actor is registered in {@link ActorRegistry}.
|
|
38
|
-
*/
|
|
39
|
-
export interface ActorClient<N extends string = string> {
|
|
35
|
+
/** Options for {@link ActorRoom.connect}. */
|
|
36
|
+
export interface ActorConnectOptions {
|
|
40
37
|
/**
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
* Pass `options.id` to control the connection id (e.g. a stable per-tab id so a
|
|
45
|
-
* reconnect reuses the same server-side connection); omit it for an auto-generated
|
|
46
|
-
* per-connection id.
|
|
38
|
+
* The connection id — becomes the actor's `conn.id`. Supply a stable value
|
|
39
|
+
* (e.g. persisted per tab) so a reconnect reuses the same server-side
|
|
40
|
+
* identity; omit for an auto-generated per-connection id.
|
|
47
41
|
*/
|
|
48
|
-
|
|
49
|
-
id?: string;
|
|
50
|
-
}): ActorSubscription;
|
|
51
|
-
/** Send a message over the open socket. Throws if not subscribed. */
|
|
52
|
-
send(instanceId: string, data: ToServerFor<N>): void;
|
|
42
|
+
id?: string;
|
|
53
43
|
}
|
|
54
|
-
/** Handle for
|
|
44
|
+
/** Handle for one listener registered via {@link ActorRoom.subscribe}. */
|
|
55
45
|
export interface ActorSubscription {
|
|
56
|
-
/**
|
|
57
|
-
id: string;
|
|
58
|
-
/** Close the subscription and its underlying socket. */
|
|
46
|
+
/** Remove this listener; other listeners and the socket stay live. */
|
|
59
47
|
unsubscribe(): void;
|
|
60
48
|
}
|
|
49
|
+
/**
|
|
50
|
+
* A single actor room. Obtained from {@link ActorClient} (`actors.MyActor(id)`)
|
|
51
|
+
* and made live with {@link connect}. The handle IS the connection: one socket,
|
|
52
|
+
* any number of {@link subscribe} listeners.
|
|
53
|
+
*/
|
|
54
|
+
export interface ActorRoom<N extends string = string> {
|
|
55
|
+
/** The connection id (the value the actor sees as `conn.id`). Throws before {@link connect}. */
|
|
56
|
+
readonly id: string;
|
|
57
|
+
/** Open the WebSocket (required before subscribe/send). Idempotent; returns this. */
|
|
58
|
+
connect(options?: ActorConnectOptions): this;
|
|
59
|
+
/** Register a message listener. Multiple are allowed; returns a per-listener unsubscribe. */
|
|
60
|
+
subscribe(callback: (data: ToClientFor<N>) => void): ActorSubscription;
|
|
61
|
+
/** Send a message. Throws before {@link connect}; buffered by the socket until open. */
|
|
62
|
+
send(data: ToServerFor<N>): void;
|
|
63
|
+
/** Tear down the socket, heartbeat, and all listeners. */
|
|
64
|
+
close(): void;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Client for a single named Actor — call it with a room id to get an
|
|
68
|
+
* {@link ActorRoom}. Typed automatically when the actor is registered in
|
|
69
|
+
* {@link ActorRegistry}.
|
|
70
|
+
*/
|
|
71
|
+
export interface ActorClient<N extends string = string> {
|
|
72
|
+
(instanceId: string): ActorRoom<N>;
|
|
73
|
+
}
|
|
61
74
|
/**
|
|
62
75
|
* The actors module provides access to Cloudflare Durable Object-backed
|
|
63
76
|
* Actors deployed by the Base44 platform.
|
|
64
77
|
*
|
|
65
|
-
* Actor names are accessed as dynamic properties on this module:
|
|
66
78
|
* ```typescript
|
|
67
|
-
* const
|
|
68
|
-
*
|
|
69
|
-
* });
|
|
70
|
-
*
|
|
71
|
-
*
|
|
79
|
+
* const room = base44.actors.MyActor("room-1").connect();
|
|
80
|
+
* const sub = room.subscribe((msg) => console.log(msg)); // typed via ActorRegistry
|
|
81
|
+
* room.send({ type: "message", text: "hi" });
|
|
82
|
+
* sub.unsubscribe();
|
|
83
|
+
* room.close();
|
|
72
84
|
* ```
|
|
73
85
|
*/
|
|
74
86
|
export type ActorsModule = {
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
* Contains the base URL and bearer token to use with any OpenAI-compatible
|
|
5
|
-
* client pointed at the Base44 AI Gateway.
|
|
2
|
+
* Connection details for the Base44 AI Gateway.
|
|
6
3
|
*/
|
|
7
4
|
export interface AiGatewayConnection {
|
|
8
|
-
/** Base URL of the gateway's OpenAI-compatible endpoint. */
|
|
5
|
+
/** Base URL of the gateway's OpenAI-compatible Chat Completions endpoint. */
|
|
9
6
|
baseURL: string;
|
|
10
|
-
/**
|
|
7
|
+
/**
|
|
8
|
+
* Bearer token that authenticates the request. Empty string when the caller is
|
|
9
|
+
* unauthenticated.
|
|
10
|
+
*/
|
|
11
11
|
token: string;
|
|
12
12
|
}
|
|
13
13
|
/**
|
|
@@ -25,13 +25,45 @@ export interface AiGatewayModuleConfig {
|
|
|
25
25
|
/**
|
|
26
26
|
* AI Gateway module for calling Base44's managed AI models from your own code.
|
|
27
27
|
*
|
|
28
|
-
*
|
|
29
|
-
* OpenAI-compatible
|
|
30
|
-
*
|
|
31
|
-
*
|
|
28
|
+
* `connection()` hands you a `baseURL` and `token` that authenticate as your
|
|
29
|
+
* Base44 app. An OpenAI-compatible client is any library, such as the `openai`
|
|
30
|
+
* SDK or the Vercel AI SDK, that has the same request and response format
|
|
31
|
+
* as OpenAI's Chat Completions API and lets you point it at a custom `baseURL`
|
|
32
|
+
* instead of OpenAI's own servers. Pass `connection()`'s values to one of
|
|
33
|
+
* these clients and it works against Base44's gateway exactly as it would
|
|
34
|
+
* against the provider directly, no separate account, API key, or billing
|
|
35
|
+
* setup with the underlying model provider required.
|
|
36
|
+
*
|
|
37
|
+
* Call `connection()` from a backend function rather than the browser. This
|
|
38
|
+
* keeps your instructions, tools, and business logic server-side, and lets
|
|
39
|
+
* you enforce your own auth, rate, and spend limits around the call. The
|
|
40
|
+
* `token` it returns is the caller's regular session token, the same one
|
|
41
|
+
* used for every other SDK call.
|
|
42
|
+
*
|
|
43
|
+
* ## Models
|
|
44
|
+
*
|
|
45
|
+
* You can use any of the [models available through `InvokeLLM`](/developers/references/sdk/docs/type-aliases/integrations#invokellm).
|
|
46
|
+
* Pass `'automatic'` to let Base44 choose one, or pin a specific model such
|
|
47
|
+
* as `'claude_sonnet_4_6'`, `'gpt_5_5'`, or `'gemini_3_1_pro'`.
|
|
48
|
+
*
|
|
49
|
+
* ## Authentication Modes
|
|
50
|
+
*
|
|
51
|
+
* There's no permission difference between modes. Both just determine which
|
|
52
|
+
* token `connection()` returns:
|
|
53
|
+
*
|
|
54
|
+
* - **User authentication** (`base44.aiGateway`): Returns the signed-in app user's token.
|
|
55
|
+
* - **Service role authentication** (`base44.asServiceRole.aiGateway`): Returns the service-role token instead, for calling the gateway when there's no signed-in user, such as from a scheduled automation.
|
|
56
|
+
*
|
|
57
|
+
* ## Billing and limits
|
|
58
|
+
*
|
|
59
|
+
* Requests are billed to your app's credit quota, which is the same shared
|
|
60
|
+
* quota your app's built-in AI features use, and isn't split per user. If the
|
|
61
|
+
* app runs out of credits, the gateway stops working for every user of the
|
|
62
|
+
* app until the quota resets. A request is rejected before the model runs if
|
|
63
|
+
* the app is out of credits. If you need to cap usage per user, build that
|
|
64
|
+
* check yourself, for example by tracking calls per user in your own entity.
|
|
32
65
|
*
|
|
33
|
-
*
|
|
34
|
-
* service-role token via `base44.asServiceRole.aiGateway`.
|
|
66
|
+
* Streaming responses aren't supported yet, so leave `stream` unset on your requests.
|
|
35
67
|
*/
|
|
36
68
|
export interface AiGatewayModule {
|
|
37
69
|
/**
|
|
@@ -39,19 +71,38 @@ export interface AiGatewayModule {
|
|
|
39
71
|
*
|
|
40
72
|
* Returns the `baseURL` and `token` to pass to any OpenAI-compatible client.
|
|
41
73
|
*
|
|
42
|
-
* The `token` is the current caller's bearer token: the app user's token for
|
|
43
|
-
* `base44.aiGateway`, or the service-role token for `base44.asServiceRole.aiGateway`.
|
|
44
|
-
* When the caller is unauthenticated, `token` is an empty string.
|
|
45
|
-
*
|
|
46
74
|
* @returns The gateway {@linkcode AiGatewayConnection | connection} (`baseURL` and `token`).
|
|
47
75
|
*
|
|
48
76
|
* @example
|
|
49
77
|
* ```typescript
|
|
78
|
+
* // Call a model directly
|
|
79
|
+
* import { createClientFromRequest } from "@base44/sdk";
|
|
80
|
+
* import OpenAI from "openai";
|
|
81
|
+
*
|
|
82
|
+
* // Runs inside a backend function
|
|
83
|
+
* const base44 = createClientFromRequest(request);
|
|
84
|
+
* const { baseURL, token } = base44.aiGateway.connection();
|
|
85
|
+
* const openai = new OpenAI({ baseURL, apiKey: token });
|
|
86
|
+
*
|
|
87
|
+
* const response = await openai.chat.completions.create({
|
|
88
|
+
* model: "automatic",
|
|
89
|
+
* messages: [{ role: "user", content: "Summarize this week's top support tickets." }],
|
|
90
|
+
* });
|
|
91
|
+
*
|
|
92
|
+
* console.log(response.choices[0].message.content);
|
|
93
|
+
* ```
|
|
94
|
+
*
|
|
95
|
+
* @example
|
|
96
|
+
* ```typescript
|
|
97
|
+
* // Use a tool-calling agent
|
|
98
|
+
* import { createClientFromRequest } from "@base44/sdk";
|
|
50
99
|
* import { ToolLoopAgent, tool, stepCountIs, hasToolCall } from "ai";
|
|
51
100
|
* import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
|
|
52
101
|
* import { z } from "zod";
|
|
53
102
|
*
|
|
54
|
-
*
|
|
103
|
+
* // Runs inside a backend function, reviewing a return request
|
|
104
|
+
* const base44 = createClientFromRequest(request);
|
|
105
|
+
* const returnRequest = await base44.entities.ReturnRequest.get(returnId);
|
|
55
106
|
* const { baseURL, token } = base44.aiGateway.connection();
|
|
56
107
|
* // Point any OpenAI-compatible client at `baseURL` with `apiKey: token`.
|
|
57
108
|
* const models = createOpenAICompatible({ name: "base44", baseURL, apiKey: token });
|
|
@@ -66,7 +117,7 @@ export interface AiGatewayModule {
|
|
|
66
117
|
* description: "This customer's past orders, optionally filtered by status",
|
|
67
118
|
* inputSchema: z.object({ status: z.string().optional() }),
|
|
68
119
|
* execute: ({ status }) => {
|
|
69
|
-
* const query = { customer_email:
|
|
120
|
+
* const query = { customer_email: returnRequest.customer_email };
|
|
70
121
|
* if (status) query.status = status;
|
|
71
122
|
* return base44.entities.Order.filter(query, "-created_date", 50);
|
|
72
123
|
* },
|
|
@@ -81,7 +132,7 @@ export interface AiGatewayModule {
|
|
|
81
132
|
* stopWhen: [stepCountIs(8), hasToolCall("submitVerdict")],
|
|
82
133
|
* });
|
|
83
134
|
*
|
|
84
|
-
* await agent.generate({ prompt: `Review this return request: ${JSON.stringify(
|
|
135
|
+
* await agent.generate({ prompt: `Review this return request: ${JSON.stringify(returnRequest)}` });
|
|
85
136
|
* ```
|
|
86
137
|
*/
|
|
87
138
|
connection(): AiGatewayConnection;
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Response from SSO access token endpoint.
|
|
3
|
-
* @internal
|
|
4
3
|
*/
|
|
5
4
|
export interface SsoAccessTokenResponse {
|
|
6
5
|
access_token: string;
|
|
@@ -13,46 +12,53 @@ export interface SsoAccessTokenResponse {
|
|
|
13
12
|
* services.
|
|
14
13
|
*
|
|
15
14
|
* This module is only available to use with a client in service role authentication mode, which means it can only be used in backend environments.
|
|
16
|
-
*
|
|
17
|
-
* @internal
|
|
18
|
-
*
|
|
19
|
-
* @example
|
|
20
|
-
* ```typescript
|
|
21
|
-
* // Access SSO module with service role
|
|
22
|
-
* const response = await base44.asServiceRole.sso.getAccessToken('user_123');
|
|
23
|
-
* console.log(response.data.access_token);
|
|
24
|
-
* ```
|
|
25
15
|
*/
|
|
26
16
|
export interface SsoModule {
|
|
27
17
|
/**
|
|
28
|
-
* Gets SSO access token for
|
|
18
|
+
* Gets an SSO access token for the user who made the current request.
|
|
29
19
|
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
20
|
+
* Use this token to authenticate the user with external systems or services.
|
|
21
|
+
* This only works for that same user. Create the client with
|
|
22
|
+
* {@link createClientFromRequest} so it acts on behalf of the request's user,
|
|
23
|
+
* then pass that user's ID as `userid`. If `userid` is any other user, the
|
|
24
|
+
* call fails. An expired token is refreshed automatically when a refresh token
|
|
25
|
+
* is available.
|
|
32
26
|
*
|
|
33
|
-
* @param userid - The user
|
|
27
|
+
* @param userid - The ID of the user who made the current request, such as the
|
|
28
|
+
* `id` returned by {@link AuthModule | base44.auth.me()}.
|
|
34
29
|
* @returns Promise resolving to the SSO access token response.
|
|
35
30
|
*
|
|
36
31
|
* @example
|
|
37
32
|
* ```typescript
|
|
38
|
-
* // Get SSO access token
|
|
39
|
-
*
|
|
40
|
-
*
|
|
33
|
+
* // Get the user's SSO access token to call an external system
|
|
34
|
+
* import { createClientFromRequest } from 'npm:@base44/sdk';
|
|
35
|
+
*
|
|
36
|
+
* Deno.serve(async (req) => {
|
|
37
|
+
* const base44 = createClientFromRequest(req);
|
|
38
|
+
* const user = await base44.auth.me();
|
|
39
|
+
* const { access_token } = await base44.asServiceRole.sso.getAccessToken(user.id);
|
|
40
|
+
*
|
|
41
|
+
* return Response.json({ access_token });
|
|
42
|
+
* });
|
|
41
43
|
* ```
|
|
42
44
|
*/
|
|
43
45
|
getAccessToken(userid: string): Promise<SsoAccessTokenResponse>;
|
|
44
46
|
/**
|
|
45
|
-
* Gets the stored SSO OIDC ID token for the current
|
|
47
|
+
* Gets the stored SSO OIDC ID token for the user who made the current request.
|
|
46
48
|
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
*
|
|
49
|
+
* This only works for that same user, not for arbitrary users. Create the
|
|
50
|
+
* client with {@link createClientFromRequest} so it acts on behalf of the
|
|
51
|
+
* request's user, then pass that user's ID as `userid`. If `userid` is any
|
|
52
|
+
* other user, the call fails. The stored token is returned as-is and is never
|
|
53
|
+
* refreshed, so the call fails if the token has already expired.
|
|
50
54
|
*
|
|
51
|
-
* @param userid - The
|
|
55
|
+
* @param userid - The ID of the user who made the current request, such as the
|
|
56
|
+
* `id` returned by {@link AuthModule | base44.auth.me()}.
|
|
52
57
|
* @returns Promise resolving to the raw ID-token string.
|
|
53
58
|
*
|
|
54
59
|
* @example
|
|
55
60
|
* ```typescript
|
|
61
|
+
* // Get the user's ID token to read identity claims such as email
|
|
56
62
|
* import { createClientFromRequest } from 'npm:@base44/sdk';
|
|
57
63
|
*
|
|
58
64
|
* Deno.serve(async (req) => {
|