@base44/sdk 0.8.5 → 0.8.7

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 (59) hide show
  1. package/README.md +47 -600
  2. package/dist/client.d.ts +90 -237
  3. package/dist/client.js +161 -29
  4. package/dist/client.types.d.ts +134 -0
  5. package/dist/client.types.js +1 -0
  6. package/dist/index.d.ts +12 -3
  7. package/dist/index.js +1 -1
  8. package/dist/modules/agents.d.ts +2 -23
  9. package/dist/modules/agents.js +3 -1
  10. package/dist/modules/agents.types.d.ts +330 -34
  11. package/dist/modules/analytics.d.ts +18 -0
  12. package/dist/modules/analytics.js +213 -0
  13. package/dist/modules/analytics.types.d.ts +42 -0
  14. package/dist/modules/analytics.types.js +1 -0
  15. package/dist/modules/app-logs.d.ts +8 -24
  16. package/dist/modules/app-logs.js +9 -19
  17. package/dist/modules/app-logs.types.d.ts +44 -0
  18. package/dist/modules/app-logs.types.js +1 -0
  19. package/dist/modules/app.types.d.ts +27 -0
  20. package/dist/modules/auth.d.ts +10 -78
  21. package/dist/modules/auth.js +24 -42
  22. package/dist/modules/auth.types.d.ts +436 -0
  23. package/dist/modules/auth.types.js +1 -0
  24. package/dist/modules/connectors.d.ts +6 -11
  25. package/dist/modules/connectors.js +6 -7
  26. package/dist/modules/connectors.types.d.ts +68 -2
  27. package/dist/modules/entities.d.ts +8 -5
  28. package/dist/modules/entities.js +22 -62
  29. package/dist/modules/entities.types.d.ts +293 -0
  30. package/dist/modules/entities.types.js +1 -0
  31. package/dist/modules/functions.d.ts +8 -7
  32. package/dist/modules/functions.js +7 -5
  33. package/dist/modules/functions.types.d.ts +50 -0
  34. package/dist/modules/functions.types.js +1 -0
  35. package/dist/modules/integrations.d.ts +8 -5
  36. package/dist/modules/integrations.js +7 -5
  37. package/dist/modules/integrations.types.d.ts +352 -0
  38. package/dist/modules/integrations.types.js +1 -0
  39. package/dist/modules/sso.d.ts +9 -14
  40. package/dist/modules/sso.js +9 -12
  41. package/dist/modules/sso.types.d.ts +44 -0
  42. package/dist/modules/sso.types.js +1 -0
  43. package/dist/modules/types.d.ts +1 -0
  44. package/dist/modules/types.js +1 -0
  45. package/dist/types.d.ts +65 -2
  46. package/dist/utils/auth-utils.d.ts +107 -45
  47. package/dist/utils/auth-utils.js +107 -33
  48. package/dist/utils/auth-utils.types.d.ts +146 -0
  49. package/dist/utils/auth-utils.types.js +1 -0
  50. package/dist/utils/axios-client.d.ts +84 -16
  51. package/dist/utils/axios-client.js +74 -13
  52. package/dist/utils/axios-client.types.d.ts +28 -0
  53. package/dist/utils/axios-client.types.js +1 -0
  54. package/dist/utils/common.d.ts +1 -0
  55. package/dist/utils/common.js +4 -0
  56. package/dist/utils/sharedInstance.d.ts +1 -0
  57. package/dist/utils/sharedInstance.js +15 -0
  58. package/dist/utils/socket-utils.d.ts +2 -2
  59. package/package.json +12 -3
package/dist/client.d.ts CHANGED
@@ -1,239 +1,92 @@
1
- export type CreateClientOptions = {
2
- onError?: (error: Error) => void;
3
- };
4
- export type Base44Client = ReturnType<typeof createClient>;
1
+ import type { Base44Client, CreateClientConfig, CreateClientOptions } from "./client.types.js";
2
+ export type { Base44Client, CreateClientConfig, CreateClientOptions };
5
3
  /**
6
- * Create a Base44 client instance
7
- * @param {Object} config - Client configuration
8
- * @param {string} [config.serverUrl='https://base44.app'] - API server URL
9
- * @param {string} [config.appBaseUrl] - Application base URL
10
- * @param {string|number} config.appId - Application ID
11
- * @param {string} [config.token] - Authentication token
12
- * @param {string} [config.serviceToken] - Service role authentication token
13
- * @param {boolean} [config.requiresAuth=false] - Whether the app requires authentication
14
- * @returns {Object} Base44 client instance
4
+ * Creates a Base44 client.
5
+ *
6
+ * This is the main entry point for the Base44 SDK. It creates a client that provides access to the SDK's modules, such as {@linkcode EntitiesModule | entities}, {@linkcode AuthModule | auth}, and {@linkcode FunctionsModule | functions}.
7
+ *
8
+ * Typically, you don't need to call this function because Base44 creates the client for you. You can then import and use the client to make API calls. The client takes care of managing authentication for you.
9
+ *
10
+ * The client supports three authentication modes:
11
+ * - **Anonymous**: Access modules anonymously without authentication using `base44.moduleName`. Operations are scoped to public data and permissions.
12
+ * - **User authentication**: Access modules with user-level permissions using `base44.moduleName`. Operations are scoped to the authenticated user's data and permissions.
13
+ * - **Service role authentication**: Access modules with elevated permissions using `base44.asServiceRole.moduleName`. Operations can access any data available to the app's admin. Can only be used in the backend. Typically, you create a client with service role authentication using the {@linkcode createClientFromRequest | createClientFromRequest()} function in your backend functions.
14
+ *
15
+ * For example, when using the {@linkcode EntitiesModule | entities} module:
16
+ * - **Anonymous**: Can only read public data.
17
+ * - **User authentication**: Can access the current user's data.
18
+ * - **Service role authentication**: Can access all data that admins can access.
19
+ *
20
+ * Most modules are available in all three modes, but with different permission levels. However, some modules are only available in specific authentication modes.
21
+ *
22
+ * @param config - Configuration object for the client.
23
+ * @returns A configured Base44 client instance with access to all SDK modules.
24
+ *
25
+ * @example
26
+ * ```typescript
27
+ * // Create a client for your app
28
+ * import { createClient } from '@base44/sdk';
29
+ *
30
+ * const base44 = createClient({
31
+ * appId: 'my-app-id'
32
+ * });
33
+ *
34
+ * // Use the client to access your data
35
+ * const products = await base44.entities.Products.list();
36
+ * ```
15
37
  */
16
- export declare function createClient(config: {
17
- serverUrl?: string;
18
- appBaseUrl?: string;
19
- appId: string;
20
- token?: string;
21
- serviceToken?: string;
22
- requiresAuth?: boolean;
23
- functionsVersion?: string;
24
- headers?: Record<string, string>;
25
- options?: CreateClientOptions;
26
- }): {
27
- /**
28
- * Set authentication token for all requests
29
- * @param {string} newToken - New auth token
30
- */
31
- setToken(newToken: string): void;
32
- /**
33
- * Get current configuration
34
- * @returns {Object} Current configuration
35
- */
36
- getConfig(): {
37
- serverUrl: string;
38
- appId: string;
39
- requiresAuth: boolean;
40
- };
41
- asServiceRole: {
42
- entities: {};
43
- integrations: {};
44
- sso: {
45
- getAccessToken(userid: string): Promise<import("axios").AxiosResponse<any, any>>;
46
- };
47
- connectors: {
48
- getAccessToken(integrationType: import("./types.js").ConnectorIntegrationType): Promise<import("./types.js").ConnectorAccessTokenResponse>;
49
- };
50
- functions: {
51
- invoke(functionName: string, data: Record<string, any>): Promise<import("axios").AxiosResponse<any, any>>;
52
- };
53
- agents: {
54
- getConversations: () => Promise<import("./types.js").AgentConversation[]>;
55
- getConversation: (conversationId: string) => Promise<import("./types.js").AgentConversation | undefined>;
56
- listConversations: (filterParams: import("./types.js").ModelFilterParams) => Promise<import("./types.js").AgentConversation[]>;
57
- createConversation: (conversation: {
58
- agent_name: string;
59
- metadata?: Record<string, any>;
60
- }) => Promise<import("./types.js").AgentConversation>;
61
- addMessage: (conversation: import("./types.js").AgentConversation, message: import("./types.js").AgentMessage) => Promise<import("./types.js").AgentMessage>;
62
- subscribeToConversation: (conversationId: string, onUpdate?: (conversation: import("./types.js").AgentConversation) => void) => () => void;
63
- getWhatsAppConnectURL: (agentName: string) => string;
64
- };
65
- appLogs: {
66
- logUserInApp(pageName: string): Promise<void>;
67
- fetchLogs(params?: Record<string, any>): Promise<any>;
68
- getStats(params?: Record<string, any>): Promise<any>;
69
- };
70
- cleanup: () => void;
71
- };
72
- entities: {};
73
- integrations: {};
74
- auth: {
75
- me(): Promise<import("axios").AxiosResponse<any, any>>;
76
- updateMe(data: Record<string, any>): Promise<import("axios").AxiosResponse<any, any>>;
77
- redirectToLogin(nextUrl: string): void;
78
- logout(redirectUrl?: string): void;
79
- setToken(token: string, saveToStorage?: boolean): void;
80
- loginViaEmailPassword(email: string, password: string, turnstileToken?: string): Promise<{
81
- access_token: string;
82
- user: any;
83
- }>;
84
- isAuthenticated(): Promise<boolean>;
85
- inviteUser(userEmail: string, role: string): Promise<import("axios").AxiosResponse<any, any>>;
86
- register(payload: {
87
- email: string;
88
- password: string;
89
- turnstile_token?: string | null;
90
- referral_code?: string | null;
91
- }): Promise<import("axios").AxiosResponse<any, any>>;
92
- verifyOtp({ email, otpCode }: {
93
- email: string;
94
- otpCode: string;
95
- }): Promise<import("axios").AxiosResponse<any, any>>;
96
- resendOtp(email: string): Promise<import("axios").AxiosResponse<any, any>>;
97
- resetPasswordRequest(email: string): Promise<import("axios").AxiosResponse<any, any>>;
98
- resetPassword({ resetToken, newPassword, }: {
99
- resetToken: string;
100
- newPassword: string;
101
- }): Promise<import("axios").AxiosResponse<any, any>>;
102
- changePassword({ userId, currentPassword, newPassword, }: {
103
- userId: string;
104
- currentPassword: string;
105
- newPassword: string;
106
- }): Promise<import("axios").AxiosResponse<any, any>>;
107
- };
108
- functions: {
109
- invoke(functionName: string, data: Record<string, any>): Promise<import("axios").AxiosResponse<any, any>>;
110
- };
111
- agents: {
112
- getConversations: () => Promise<import("./types.js").AgentConversation[]>;
113
- getConversation: (conversationId: string) => Promise<import("./types.js").AgentConversation | undefined>;
114
- listConversations: (filterParams: import("./types.js").ModelFilterParams) => Promise<import("./types.js").AgentConversation[]>;
115
- createConversation: (conversation: {
116
- agent_name: string;
117
- metadata?: Record<string, any>;
118
- }) => Promise<import("./types.js").AgentConversation>;
119
- addMessage: (conversation: import("./types.js").AgentConversation, message: import("./types.js").AgentMessage) => Promise<import("./types.js").AgentMessage>;
120
- subscribeToConversation: (conversationId: string, onUpdate?: (conversation: import("./types.js").AgentConversation) => void) => () => void;
121
- getWhatsAppConnectURL: (agentName: string) => string;
122
- };
123
- appLogs: {
124
- logUserInApp(pageName: string): Promise<void>;
125
- fetchLogs(params?: Record<string, any>): Promise<any>;
126
- getStats(params?: Record<string, any>): Promise<any>;
127
- };
128
- users: {
129
- inviteUser(user_email: string, role: "user" | "admin"): Promise<any>;
130
- };
131
- cleanup: () => void;
132
- };
133
- export declare function createClientFromRequest(request: Request): {
134
- /**
135
- * Set authentication token for all requests
136
- * @param {string} newToken - New auth token
137
- */
138
- setToken(newToken: string): void;
139
- /**
140
- * Get current configuration
141
- * @returns {Object} Current configuration
142
- */
143
- getConfig(): {
144
- serverUrl: string;
145
- appId: string;
146
- requiresAuth: boolean;
147
- };
148
- asServiceRole: {
149
- entities: {};
150
- integrations: {};
151
- sso: {
152
- getAccessToken(userid: string): Promise<import("axios").AxiosResponse<any, any>>;
153
- };
154
- connectors: {
155
- getAccessToken(integrationType: import("./types.js").ConnectorIntegrationType): Promise<import("./types.js").ConnectorAccessTokenResponse>;
156
- };
157
- functions: {
158
- invoke(functionName: string, data: Record<string, any>): Promise<import("axios").AxiosResponse<any, any>>;
159
- };
160
- agents: {
161
- getConversations: () => Promise<import("./types.js").AgentConversation[]>;
162
- getConversation: (conversationId: string) => Promise<import("./types.js").AgentConversation | undefined>;
163
- listConversations: (filterParams: import("./types.js").ModelFilterParams) => Promise<import("./types.js").AgentConversation[]>;
164
- createConversation: (conversation: {
165
- agent_name: string;
166
- metadata?: Record<string, any>;
167
- }) => Promise<import("./types.js").AgentConversation>;
168
- addMessage: (conversation: import("./types.js").AgentConversation, message: import("./types.js").AgentMessage) => Promise<import("./types.js").AgentMessage>;
169
- subscribeToConversation: (conversationId: string, onUpdate?: (conversation: import("./types.js").AgentConversation) => void) => () => void;
170
- getWhatsAppConnectURL: (agentName: string) => string;
171
- };
172
- appLogs: {
173
- logUserInApp(pageName: string): Promise<void>;
174
- fetchLogs(params?: Record<string, any>): Promise<any>;
175
- getStats(params?: Record<string, any>): Promise<any>;
176
- };
177
- cleanup: () => void;
178
- };
179
- entities: {};
180
- integrations: {};
181
- auth: {
182
- me(): Promise<import("axios").AxiosResponse<any, any>>;
183
- updateMe(data: Record<string, any>): Promise<import("axios").AxiosResponse<any, any>>;
184
- redirectToLogin(nextUrl: string): void;
185
- logout(redirectUrl?: string): void;
186
- setToken(token: string, saveToStorage?: boolean): void;
187
- loginViaEmailPassword(email: string, password: string, turnstileToken?: string): Promise<{
188
- access_token: string;
189
- user: any;
190
- }>;
191
- isAuthenticated(): Promise<boolean>;
192
- inviteUser(userEmail: string, role: string): Promise<import("axios").AxiosResponse<any, any>>;
193
- register(payload: {
194
- email: string;
195
- password: string;
196
- turnstile_token?: string | null;
197
- referral_code?: string | null;
198
- }): Promise<import("axios").AxiosResponse<any, any>>;
199
- verifyOtp({ email, otpCode }: {
200
- email: string;
201
- otpCode: string;
202
- }): Promise<import("axios").AxiosResponse<any, any>>;
203
- resendOtp(email: string): Promise<import("axios").AxiosResponse<any, any>>;
204
- resetPasswordRequest(email: string): Promise<import("axios").AxiosResponse<any, any>>;
205
- resetPassword({ resetToken, newPassword, }: {
206
- resetToken: string;
207
- newPassword: string;
208
- }): Promise<import("axios").AxiosResponse<any, any>>;
209
- changePassword({ userId, currentPassword, newPassword, }: {
210
- userId: string;
211
- currentPassword: string;
212
- newPassword: string;
213
- }): Promise<import("axios").AxiosResponse<any, any>>;
214
- };
215
- functions: {
216
- invoke(functionName: string, data: Record<string, any>): Promise<import("axios").AxiosResponse<any, any>>;
217
- };
218
- agents: {
219
- getConversations: () => Promise<import("./types.js").AgentConversation[]>;
220
- getConversation: (conversationId: string) => Promise<import("./types.js").AgentConversation | undefined>;
221
- listConversations: (filterParams: import("./types.js").ModelFilterParams) => Promise<import("./types.js").AgentConversation[]>;
222
- createConversation: (conversation: {
223
- agent_name: string;
224
- metadata?: Record<string, any>;
225
- }) => Promise<import("./types.js").AgentConversation>;
226
- addMessage: (conversation: import("./types.js").AgentConversation, message: import("./types.js").AgentMessage) => Promise<import("./types.js").AgentMessage>;
227
- subscribeToConversation: (conversationId: string, onUpdate?: (conversation: import("./types.js").AgentConversation) => void) => () => void;
228
- getWhatsAppConnectURL: (agentName: string) => string;
229
- };
230
- appLogs: {
231
- logUserInApp(pageName: string): Promise<void>;
232
- fetchLogs(params?: Record<string, any>): Promise<any>;
233
- getStats(params?: Record<string, any>): Promise<any>;
234
- };
235
- users: {
236
- inviteUser(user_email: string, role: "user" | "admin"): Promise<any>;
237
- };
238
- cleanup: () => void;
239
- };
38
+ export declare function createClient(config: CreateClientConfig): Base44Client;
39
+ /**
40
+ * Creates a Base44 client from an HTTP request.
41
+ *
42
+ * The client is created by automatically extracting authentication tokens from a request to a backend function. Base44 inserts the necessary headers when forwarding requests to backend functions.
43
+ *
44
+ * To learn more about the Base44 client, see {@linkcode createClient | createClient()}.
45
+ *
46
+ * @param request - The incoming HTTP request object containing Base44 authentication headers.
47
+ * @returns A configured Base44 client instance with authentication from the incoming request.
48
+ *
49
+ * @example
50
+ * ```typescript
51
+ * // User authentication in backend function
52
+ * import { createClientFromRequest } from 'npm:@base44/sdk';
53
+ *
54
+ * Deno.serve(async (req) => {
55
+ * try {
56
+ * const base44 = createClientFromRequest(req);
57
+ * const user = await base44.auth.me();
58
+ *
59
+ * if (!user) {
60
+ * return Response.json({ error: 'Unauthorized' }, { status: 401 });
61
+ * }
62
+ *
63
+ * // Access user's data
64
+ * const userOrders = await base44.entities.Orders.filter({ userId: user.id });
65
+ * return Response.json({ orders: userOrders });
66
+ * } catch (error) {
67
+ * return Response.json({ error: error.message }, { status: 500 });
68
+ * }
69
+ * });
70
+ * ```
71
+ *
72
+ * @example
73
+ * ```typescript
74
+ * // Service role authentication in backend function
75
+ * import { createClientFromRequest } from 'npm:@base44/sdk';
76
+ *
77
+ * Deno.serve(async (req) => {
78
+ * try {
79
+ * const base44 = createClientFromRequest(req);
80
+ *
81
+ * // Access admin data with service role permissions
82
+ * const recentOrders = await base44.asServiceRole.entities.Orders.list('-created_at', 50);
83
+ *
84
+ * return Response.json({ orders: recentOrders });
85
+ * } catch (error) {
86
+ * return Response.json({ error: error.message }, { status: 500 });
87
+ * }
88
+ * });
89
+ * ```
90
+ *
91
+ */
92
+ export declare function createClientFromRequest(request: Request): Base44Client;
package/dist/client.js CHANGED
@@ -10,16 +10,41 @@ import { createAgentsModule } from "./modules/agents.js";
10
10
  import { createAppLogsModule } from "./modules/app-logs.js";
11
11
  import { createUsersModule } from "./modules/users.js";
12
12
  import { RoomsSocket } from "./utils/socket-utils.js";
13
+ import { createAnalyticsModule } from "./modules/analytics.js";
13
14
  /**
14
- * Create a Base44 client instance
15
- * @param {Object} config - Client configuration
16
- * @param {string} [config.serverUrl='https://base44.app'] - API server URL
17
- * @param {string} [config.appBaseUrl] - Application base URL
18
- * @param {string|number} config.appId - Application ID
19
- * @param {string} [config.token] - Authentication token
20
- * @param {string} [config.serviceToken] - Service role authentication token
21
- * @param {boolean} [config.requiresAuth=false] - Whether the app requires authentication
22
- * @returns {Object} Base44 client instance
15
+ * Creates a Base44 client.
16
+ *
17
+ * This is the main entry point for the Base44 SDK. It creates a client that provides access to the SDK's modules, such as {@linkcode EntitiesModule | entities}, {@linkcode AuthModule | auth}, and {@linkcode FunctionsModule | functions}.
18
+ *
19
+ * Typically, you don't need to call this function because Base44 creates the client for you. You can then import and use the client to make API calls. The client takes care of managing authentication for you.
20
+ *
21
+ * The client supports three authentication modes:
22
+ * - **Anonymous**: Access modules anonymously without authentication using `base44.moduleName`. Operations are scoped to public data and permissions.
23
+ * - **User authentication**: Access modules with user-level permissions using `base44.moduleName`. Operations are scoped to the authenticated user's data and permissions.
24
+ * - **Service role authentication**: Access modules with elevated permissions using `base44.asServiceRole.moduleName`. Operations can access any data available to the app's admin. Can only be used in the backend. Typically, you create a client with service role authentication using the {@linkcode createClientFromRequest | createClientFromRequest()} function in your backend functions.
25
+ *
26
+ * For example, when using the {@linkcode EntitiesModule | entities} module:
27
+ * - **Anonymous**: Can only read public data.
28
+ * - **User authentication**: Can access the current user's data.
29
+ * - **Service role authentication**: Can access all data that admins can access.
30
+ *
31
+ * Most modules are available in all three modes, but with different permission levels. However, some modules are only available in specific authentication modes.
32
+ *
33
+ * @param config - Configuration object for the client.
34
+ * @returns A configured Base44 client instance with access to all SDK modules.
35
+ *
36
+ * @example
37
+ * ```typescript
38
+ * // Create a client for your app
39
+ * import { createClient } from '@base44/sdk';
40
+ *
41
+ * const base44 = createClient({
42
+ * appId: 'my-app-id'
43
+ * });
44
+ *
45
+ * // Use the client to access your data
46
+ * const products = await base44.entities.Products.list();
47
+ * ```
23
48
  */
24
49
  export function createClient(config) {
25
50
  const { serverUrl = "https://base44.app", appId, token, serviceToken, requiresAuth = false, appBaseUrl, options, functionsVersion, headers: optionalHeaders, } = config;
@@ -30,9 +55,15 @@ export function createClient(config) {
30
55
  appId,
31
56
  token,
32
57
  };
33
- const socket = RoomsSocket({
34
- config: socketConfig,
35
- });
58
+ let socket = null;
59
+ const getSocket = () => {
60
+ if (!socket) {
61
+ socket = RoomsSocket({
62
+ config: socketConfig,
63
+ });
64
+ }
65
+ return socket;
66
+ };
36
67
  const headers = {
37
68
  ...optionalHeaders,
38
69
  "X-App-Id": String(appId),
@@ -68,25 +99,35 @@ export function createClient(config) {
68
99
  token: serviceToken,
69
100
  interceptResponses: false,
70
101
  });
102
+ const userAuthModule = createAuthModule(axiosClient, functionsAxiosClient, appId, {
103
+ appBaseUrl,
104
+ serverUrl,
105
+ });
71
106
  const userModules = {
72
107
  entities: createEntitiesModule(axiosClient, appId),
73
108
  integrations: createIntegrationsModule(axiosClient, appId),
74
- auth: createAuthModule(axiosClient, functionsAxiosClient, appId, {
75
- appBaseUrl,
76
- serverUrl,
77
- }),
109
+ auth: userAuthModule,
78
110
  functions: createFunctionsModule(functionsAxiosClient, appId),
79
111
  agents: createAgentsModule({
80
112
  axios: axiosClient,
81
- socket,
113
+ getSocket,
82
114
  appId,
83
115
  serverUrl,
84
116
  token,
85
117
  }),
86
118
  appLogs: createAppLogsModule(axiosClient, appId),
87
119
  users: createUsersModule(axiosClient, appId),
120
+ analytics: createAnalyticsModule({
121
+ axiosClient,
122
+ serverUrl,
123
+ appId,
124
+ userAuthModule,
125
+ }),
88
126
  cleanup: () => {
89
- socket.disconnect();
127
+ userModules.analytics.cleanup();
128
+ if (socket) {
129
+ socket.disconnect();
130
+ }
90
131
  },
91
132
  };
92
133
  const serviceRoleModules = {
@@ -97,14 +138,16 @@ export function createClient(config) {
97
138
  functions: createFunctionsModule(serviceRoleFunctionsAxiosClient, appId),
98
139
  agents: createAgentsModule({
99
140
  axios: serviceRoleAxiosClient,
100
- socket,
141
+ getSocket,
101
142
  appId,
102
143
  serverUrl,
103
144
  token,
104
145
  }),
105
146
  appLogs: createAppLogsModule(serviceRoleAxiosClient, appId),
106
147
  cleanup: () => {
107
- socket.disconnect();
148
+ if (socket) {
149
+ socket.disconnect();
150
+ }
108
151
  },
109
152
  };
110
153
  // Always try to get token from localStorage or URL parameters
@@ -135,18 +178,33 @@ export function createClient(config) {
135
178
  const client = {
136
179
  ...userModules,
137
180
  /**
138
- * Set authentication token for all requests
139
- * @param {string} newToken - New auth token
181
+ * Sets a new authentication token for all subsequent requests.
182
+ *
183
+ * @param newToken - The new authentication token
184
+ *
185
+ * @example
186
+ * ```typescript
187
+ * // Update token after login
188
+ * const { access_token } = await base44.auth.loginViaEmailPassword(
189
+ * 'user@example.com',
190
+ * 'password'
191
+ * );
192
+ * base44.setToken(access_token);
193
+ * ```
140
194
  */
141
195
  setToken(newToken) {
142
196
  userModules.auth.setToken(newToken);
143
- socket.updateConfig({
144
- token: newToken,
145
- });
197
+ if (socket) {
198
+ socket.updateConfig({
199
+ token: newToken,
200
+ });
201
+ }
202
+ socketConfig.token = newToken;
146
203
  },
147
204
  /**
148
- * Get current configuration
149
- * @returns {Object} Current configuration
205
+ * Gets the current client configuration.
206
+ *
207
+ * @internal
150
208
  */
151
209
  getConfig() {
152
210
  return {
@@ -156,8 +214,22 @@ export function createClient(config) {
156
214
  };
157
215
  },
158
216
  /**
159
- * Access service role modules - throws error if no service token was provided
160
- * @throws {Error} When accessed without a service token
217
+ * Provides access to service role modules.
218
+ *
219
+ * Service role authentication provides elevated permissions for server-side operations. Unlike user authentication, which is scoped to a specific user's permissions, service role authentication has access to the data and operations available to the app's admin.
220
+ *
221
+ * @throws {Error} When accessed without providing a serviceToken during client creation.
222
+ *
223
+ * @example
224
+ * ```typescript
225
+ * const base44 = createClient({
226
+ * appId: 'my-app-id',
227
+ * serviceToken: 'service-role-token'
228
+ * });
229
+ *
230
+ * // Also access a module with elevated permissions
231
+ * const allUsers = await base44.asServiceRole.entities.User.list();
232
+ * ```
161
233
  */
162
234
  get asServiceRole() {
163
235
  if (!serviceToken) {
@@ -168,12 +240,66 @@ export function createClient(config) {
168
240
  };
169
241
  return client;
170
242
  }
243
+ /**
244
+ * Creates a Base44 client from an HTTP request.
245
+ *
246
+ * The client is created by automatically extracting authentication tokens from a request to a backend function. Base44 inserts the necessary headers when forwarding requests to backend functions.
247
+ *
248
+ * To learn more about the Base44 client, see {@linkcode createClient | createClient()}.
249
+ *
250
+ * @param request - The incoming HTTP request object containing Base44 authentication headers.
251
+ * @returns A configured Base44 client instance with authentication from the incoming request.
252
+ *
253
+ * @example
254
+ * ```typescript
255
+ * // User authentication in backend function
256
+ * import { createClientFromRequest } from 'npm:@base44/sdk';
257
+ *
258
+ * Deno.serve(async (req) => {
259
+ * try {
260
+ * const base44 = createClientFromRequest(req);
261
+ * const user = await base44.auth.me();
262
+ *
263
+ * if (!user) {
264
+ * return Response.json({ error: 'Unauthorized' }, { status: 401 });
265
+ * }
266
+ *
267
+ * // Access user's data
268
+ * const userOrders = await base44.entities.Orders.filter({ userId: user.id });
269
+ * return Response.json({ orders: userOrders });
270
+ * } catch (error) {
271
+ * return Response.json({ error: error.message }, { status: 500 });
272
+ * }
273
+ * });
274
+ * ```
275
+ *
276
+ * @example
277
+ * ```typescript
278
+ * // Service role authentication in backend function
279
+ * import { createClientFromRequest } from 'npm:@base44/sdk';
280
+ *
281
+ * Deno.serve(async (req) => {
282
+ * try {
283
+ * const base44 = createClientFromRequest(req);
284
+ *
285
+ * // Access admin data with service role permissions
286
+ * const recentOrders = await base44.asServiceRole.entities.Orders.list('-created_at', 50);
287
+ *
288
+ * return Response.json({ orders: recentOrders });
289
+ * } catch (error) {
290
+ * return Response.json({ error: error.message }, { status: 500 });
291
+ * }
292
+ * });
293
+ * ```
294
+ *
295
+ */
171
296
  export function createClientFromRequest(request) {
172
297
  const authHeader = request.headers.get("Authorization");
173
298
  const serviceRoleAuthHeader = request.headers.get("Base44-Service-Authorization");
174
299
  const appId = request.headers.get("Base44-App-Id");
175
300
  const serverUrlHeader = request.headers.get("Base44-Api-Url");
176
301
  const functionsVersion = request.headers.get("Base44-Functions-Version");
302
+ const stateHeader = request.headers.get("Base44-State");
177
303
  if (!appId) {
178
304
  throw new Error("Base44-App-Id header is required, but is was not found on the request");
179
305
  }
@@ -196,11 +322,17 @@ export function createClientFromRequest(request) {
196
322
  }
197
323
  userToken = authHeader.split(" ")[1];
198
324
  }
325
+ // Prepare additional headers to propagate
326
+ const additionalHeaders = {};
327
+ if (stateHeader) {
328
+ additionalHeaders["Base44-State"] = stateHeader;
329
+ }
199
330
  return createClient({
200
331
  serverUrl: serverUrlHeader || "https://base44.app",
201
332
  appId,
202
333
  token: userToken,
203
334
  serviceToken: serviceRoleToken,
204
335
  functionsVersion: functionsVersion !== null && functionsVersion !== void 0 ? functionsVersion : undefined,
336
+ headers: additionalHeaders,
205
337
  });
206
338
  }