@amaster.ai/client 1.0.0-alpha.1

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/index.cjs ADDED
@@ -0,0 +1,162 @@
1
+ 'use strict';
2
+
3
+ var authClient = require('@amaster.ai/auth-client');
4
+ var entityClient = require('@amaster.ai/entity-client');
5
+ var bpmClient = require('@amaster.ai/bpm-client');
6
+ var workflowClient = require('@amaster.ai/workflow-client');
7
+ var asrClient = require('@amaster.ai/asr-client');
8
+ var copilotClient = require('@amaster.ai/copilot-client');
9
+ var functionClient = require('@amaster.ai/function-client');
10
+ var ttsClient = require('@amaster.ai/tts-client');
11
+ var s3Client = require('@amaster.ai/s3-client');
12
+ var httpClient = require('@amaster.ai/http-client');
13
+
14
+ // src/client.ts
15
+ function createClient(options) {
16
+ const {
17
+ baseURL,
18
+ headers = {},
19
+ onUnauthorized,
20
+ onTokenExpired,
21
+ autoHandleOAuthCallback
22
+ } = options;
23
+ const baseHttpClient = httpClient.createHttpClient({
24
+ baseURL,
25
+ headers
26
+ });
27
+ const auth = authClient.createAuthClient({
28
+ baseURL,
29
+ headers,
30
+ onTokenExpired,
31
+ onUnauthorized,
32
+ autoHandleOAuthCallback
33
+ });
34
+ const createAuthenticatedHttpClient = () => {
35
+ let isRefreshing = false;
36
+ let refreshPromise = null;
37
+ function isTokenExpired(result) {
38
+ if (result.status !== 401) return false;
39
+ if (result.error?.message && /expired/i.test(result.error.message)) {
40
+ return true;
41
+ }
42
+ if (result.error?.details) {
43
+ const details = result.error.details;
44
+ if (typeof details === "string" && /expired/i.test(details)) {
45
+ return true;
46
+ }
47
+ if (typeof details === "object" && details !== null) {
48
+ const detailsObj = details;
49
+ if (typeof detailsObj.message === "string" && /expired/i.test(detailsObj.message)) {
50
+ return true;
51
+ }
52
+ }
53
+ }
54
+ if (typeof result.data === "string" && /expired/i.test(result.data)) {
55
+ return true;
56
+ }
57
+ return !!auth.getAccessToken();
58
+ }
59
+ return {
60
+ async request(config) {
61
+ const token = auth.getAccessToken();
62
+ const authHeaders = token ? { Authorization: `Bearer ${token}` } : {};
63
+ const mergedConfig = {
64
+ ...config,
65
+ headers: {
66
+ ...config.headers,
67
+ ...authHeaders
68
+ }
69
+ };
70
+ let result = await baseHttpClient.request(mergedConfig);
71
+ if (result.status === 401 && isTokenExpired(result)) {
72
+ if (!isRefreshing) {
73
+ isRefreshing = true;
74
+ refreshPromise = (async () => {
75
+ try {
76
+ const refreshResult = await auth.refreshToken();
77
+ return !!refreshResult.data;
78
+ } finally {
79
+ isRefreshing = false;
80
+ refreshPromise = null;
81
+ }
82
+ })();
83
+ }
84
+ const refreshed = await refreshPromise;
85
+ if (refreshed) {
86
+ const newToken = auth.getAccessToken();
87
+ result = await baseHttpClient.request({
88
+ ...config,
89
+ headers: {
90
+ ...config.headers,
91
+ ...newToken ? { Authorization: `Bearer ${newToken}` } : {}
92
+ }
93
+ });
94
+ }
95
+ }
96
+ if (result.status === 401 && onUnauthorized) {
97
+ onUnauthorized();
98
+ }
99
+ return result;
100
+ }
101
+ };
102
+ };
103
+ const authenticatedHttpClient = createAuthenticatedHttpClient();
104
+ let cachedUserUid = null;
105
+ auth.on("login", (user) => {
106
+ cachedUserUid = user?.uid ?? null;
107
+ });
108
+ auth.on("logout", () => {
109
+ cachedUserUid = null;
110
+ });
111
+ if (auth.isAuthenticated()) {
112
+ auth.getMe().then((result) => {
113
+ if (result.data?.uid) {
114
+ cachedUserUid = result.data.uid;
115
+ }
116
+ }).catch(() => {
117
+ });
118
+ }
119
+ const entity = entityClient.createEntityClient(authenticatedHttpClient);
120
+ const bpm = bpmClient.createBpmClient(authenticatedHttpClient);
121
+ const workflow = workflowClient.createWorkflowClient(authenticatedHttpClient);
122
+ const functionClient$1 = functionClient.createFunctionClient(authenticatedHttpClient);
123
+ const copilot = copilotClient.createCopilotClient(
124
+ authenticatedHttpClient,
125
+ baseURL,
126
+ () => auth.getAccessToken(),
127
+ () => cachedUserUid
128
+ );
129
+ const s3 = s3Client.createS3Client(authenticatedHttpClient);
130
+ const asr = asrClient.createASRClient({
131
+ getAccessToken: () => auth.getAccessToken()
132
+ });
133
+ const asrHttp = asrClient.createASRHttpClient({
134
+ getAccessToken: () => auth.getAccessToken()
135
+ });
136
+ const tts = ttsClient.createTTSClient({
137
+ getAccessToken: () => auth.getAccessToken()
138
+ });
139
+ const client = {
140
+ auth,
141
+ entity,
142
+ bpm,
143
+ workflow,
144
+ asr,
145
+ asrHttp,
146
+ copilot,
147
+ function: functionClient$1,
148
+ tts,
149
+ s3,
150
+ http: authenticatedHttpClient,
151
+ // Expose token management methods from auth client
152
+ isAuthenticated: () => auth.isAuthenticated(),
153
+ getAccessToken: () => auth.getAccessToken(),
154
+ setAccessToken: (token) => auth.setAccessToken(token),
155
+ clearAuth: () => auth.clearAuth()
156
+ };
157
+ return client;
158
+ }
159
+
160
+ exports.createClient = createClient;
161
+ //# sourceMappingURL=index.cjs.map
162
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts"],"names":["createHttpClient","createAuthClient","createEntityClient","createBpmClient","createWorkflowClient","functionClient","createFunctionClient","createCopilotClient","createS3Client","createASRClient","createASRHttpClient","createTTSClient"],"mappings":";;;;;;;;;;;;;;AA2GO,SAAS,aAAa,OAAA,EAA8C;AACzE,EAAA,MAAM;AAAA,IACJ,OAAA;AAAA,IACA,UAAU,EAAC;AAAA,IACX,cAAA;AAAA,IACA,cAAA;AAAA,IACA;AAAA,GACF,GAAI,OAAA;AAGJ,EAAA,MAAM,iBAAiBA,2BAAA,CAAiB;AAAA,IACtC,OAAA;AAAA,IACA;AAAA,GACD,CAAA;AAGD,EAAA,MAAM,OAAmBC,2BAAA,CAAiB;AAAA,IACxC,OAAA;AAAA,IACA,OAAA;AAAA,IACA,cAAA;AAAA,IACA,cAAA;AAAA,IACA;AAAA,GACD,CAAA;AAGD,EAAA,MAAM,gCAAgC,MAAkB;AAEtD,IAAA,I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M,MAA8CC,yBAAA,CAAgB;AAAA,IAClE,cAAA,EAAgB,MAAM,IAAA,CAAK,cAAA;AAAe,GAC3C,CAAA;AAGD,EAAA,MAAM,MAAA,GAAwB;AAAA,IAC5B,IAAA;AAAA,IACA,MAAA;AAAA,IACA,GAAA;AAAA,IACA,QAAA;AAAA,IACA,GAAA;AAAA,IACA,OAAA;AAAA,IACA,OAAA;AAAA,IACA,QAAA,EAAUN,gBAAA;AAAA,IACV,GAAA;AAAA,IACA,EAAA;AAAA,IACA,IAAA,EAAM,uBAAA;AAAA;AAAA,IAGN,eAAA,EAAiB,MAAM,IAAA,CAAK,eAAA,EAAgB;AAAA,IAC5C,cAAA,EAAgB,MAAM,IAAA,CAAK,cAAA,EAAe;AAAA,IAC1C,cAAA,EAAgB,CAAC,KAAA,KAAkB,IAAA,CAAK,eAAe,KAAK,CAAA;AAAA,IAC5D,SAAA,EAAW,MAAM,IAAA,CAAK,SAAA;AAAU,GAClC;AAEA,EAAA,OAAO,MAAA;AACT","file":"index.cjs","sourcesContent":["/**\n * ============================================================================\n * @amaster.ai/client - Unified Amaster Client\n * ============================================================================\n *\n * Supabase-inspired unified API client for the Amaster platform\n *\n * Features:\n * - Single client instance for all services (auth, entity, bpm, workflow)\n * - Automatic token management and refresh\n * - Auto-attach authentication to all requests\n * - Centralized error handling\n *\n * @example\n * ```typescript\n * // With explicit baseURL\n * const client = createClient({\n * baseURL: 'https://api.amaster.ai',\n * onUnauthorized: () => window.location.href = '/login'\n * });\n *\n * // Auto-detect baseURL from env (Taro/Mini-program)\n * const client = createClient({\n * onUnauthorized: () => window.location.href = '/login'\n * });\n *\n * // Login\n * await client.auth.login({ email, password });\n *\n * // All subsequent requests automatically include auth token\n * await client.entity.list('default', 'users');\n * await client.bpm.startProcess({ processKey: 'approval' });\n * ```\n */\n\nimport { createAuthClient, type AuthClient } from \"@amaster.ai/auth-client\";\nimport { createEntityClient, type EntityClient } from \"@amaster.ai/entity-client\";\nimport { createBpmClient, type BpmClient } from \"@amaster.ai/bpm-client\";\nimport { createWorkflowClient, type WorkflowClient } from \"@amaster.ai/workflow-client\";\nimport {\n createASRClient,\n createASRHttpClient,\n type ASRClientConfig,\n type ASRClient,\n type ASRHttpClientConfig,\n type ASRHttpClient,\n} from \"@amaster.ai/asr-client\";\nimport { createCopilotClient, type CopilotClient } from \"@amaster.ai/copilot-client\";\nimport { createFunctionClient, type FunctionClient } from \"@amaster.ai/function-client\";\nimport { createTTSClient, TTSClientConfig, type TTSClient } from \"@amaster.ai/tts-client\";\nimport { createS3Client, type S3Client } from \"@amaster.ai/s3-client\";\nimport {\n createHttpClient,\n type HttpClient,\n type RequestConfig,\n type ClientResult,\n} from \"@amaster.ai/http-client\";\nimport type { AmasterClient, AmasterClientOptions } from \"./types\";\n\n/**\n * Create a unified Amaster client instance\n *\n * This function creates a single client that provides access to all Amaster services:\n * - Authentication (login, register, logout)\n * - Entity CRUD operations\n * - BPM (Business Process Management)\n * - Workflow execution\n *\n * All sub-clients automatically share the same HTTP client and authentication state,\n * ensuring that tokens are consistently attached to all requests.\n *\n * @param options - Client configuration options\n * @returns A unified Amaster client instance\n *\n * @example\n * ```typescript\n * // Basic usage with explicit baseURL\n * const client = createClient({\n * baseURL: 'https://api.amaster.ai'\n * });\n *\n * // Auto-detect baseURL (for Taro/Mini-program or dev proxy)\n * const client = createClient({});\n *\n * // With authentication callbacks\n * const client = createClient({\n * baseURL: 'https://api.amaster.ai',\n * onUnauthorized: () => {\n * // Redirect to login or show auth modal\n * window.location.href = '/login';\n * },\n * onTokenExpired: () => {\n * console.log('Token expired, refreshing...');\n * }\n * });\n *\n * // Login\n * await client.auth.login({\n * email: 'user@example.com',\n * password: 'password123'\n * });\n *\n * // Now all requests automatically include the auth token\n * const users = await client.entity.list('default', 'users');\n * const tasks = await client.bpm.getMyTasks();\n * ```\n */\nexport function createClient(options: AmasterClientOptions): AmasterClient {\n const {\n baseURL,\n headers = {},\n onUnauthorized,\n onTokenExpired,\n autoHandleOAuthCallback,\n } = options;\n\n // Create the base HTTP client\n const baseHttpClient = createHttpClient({\n baseURL,\n headers,\n });\n\n // Create the auth client first (it manages its own HTTP client internally)\n const auth: AuthClient = createAuthClient({\n baseURL,\n headers,\n onTokenExpired,\n onUnauthorized,\n autoHandleOAuthCallback,\n });\n\n // Create a wrapper HTTP client that automatically adds the auth token\n const createAuthenticatedHttpClient = (): HttpClient => {\n // Track if we're currently refreshing to avoid multiple simultaneous refreshes\n let isRefreshing = false;\n let refreshPromise: Promise<boolean> | null = null;\n\n /**\n * Check if 401 error is due to token expiration\n * Traefik JWT plugin returns plain text like \"Jwt is expired\" or \"Token is expired\"\n */\n function isTokenExpired(result: ClientResult<unknown>): boolean {\n if (result.status !== 401) return false;\n\n // Check error message (could be from backend JSON response)\n if (result.error?.message && /expired/i.test(result.error.message)) {\n return true;\n }\n\n // Check error details (traefik returns plain text in details)\n if (result.error?.details) {\n const details = result.error.details;\n if (typeof details === \"string\" && /expired/i.test(details)) {\n return true;\n }\n // Also check if details is an object with message field\n if (typeof details === \"object\" && details !== null) {\n const detailsObj = details as Record<string, unknown>;\n if (typeof detailsObj.message === \"string\" && /expired/i.test(detailsObj.message)) {\n return true;\n }\n }\n }\n\n // Check raw data (could be plain text from traefik)\n if (typeof result.data === \"string\" && /expired/i.test(result.data)) {\n return true;\n }\n\n // If we have a token but got 401, assume it might be expired\n return !!auth.getAccessToken();\n }\n\n return {\n async request<T>(config: RequestConfig): Promise<ClientResult<T>> {\n // Get the current token from auth client\n const token = auth.getAccessToken();\n\n // Merge Authorization header with existing headers\n const authHeaders = token ? { Authorization: `Bearer ${token}` } : {};\n const mergedConfig: RequestConfig = {\n ...config,\n headers: {\n ...config.headers,\n ...authHeaders,\n },\n };\n\n // Make the request with the updated config\n let result = await baseHttpClient.request<T>(mergedConfig);\n\n // Handle 401 errors with automatic token refresh\n if (result.status === 401 && isTokenExpired(result)) {\n // Attempt to refresh token\n if (!isRefreshing) {\n isRefreshing = true;\n refreshPromise = (async () => {\n try {\n const refreshResult = await auth.refreshToken();\n return !!refreshResult.data;\n } finally {\n isRefreshing = false;\n refreshPromise = null;\n }\n })();\n }\n\n const refreshed = await refreshPromise;\n\n if (refreshed) {\n // Retry with new token\n const newToken = auth.getAccessToken();\n result = await baseHttpClient.request<T>({\n ...config,\n headers: {\n ...config.headers,\n ...(newToken ? { Authorization: `Bearer ${newToken}` } : {}),\n },\n });\n }\n }\n\n // Trigger unauthorized if still 401\n if (result.status === 401 && onUnauthorized) {\n onUnauthorized();\n }\n\n return result;\n },\n };\n };\n\n const authenticatedHttpClient = createAuthenticatedHttpClient();\n\n let cachedUserUid: string | null = null;\n\n auth.on(\"login\", (user: { uid?: string }) => {\n cachedUserUid = user?.uid ?? null;\n });\n auth.on(\"logout\", () => {\n cachedUserUid = null;\n });\n\n if (auth.isAuthenticated()) {\n auth\n .getMe()\n .then((result) => {\n if (result.data?.uid) {\n cachedUserUid = result.data.uid;\n }\n })\n .catch(() => {});\n }\n\n // Create other clients using the authenticated HTTP client\n const entity: EntityClient = createEntityClient(authenticatedHttpClient);\n const bpm: BpmClient = createBpmClient(authenticatedHttpClient);\n const workflow: WorkflowClient = createWorkflowClient(authenticatedHttpClient);\n const functionClient: FunctionClient = createFunctionClient(authenticatedHttpClient);\n const copilot: CopilotClient = createCopilotClient(\n authenticatedHttpClient,\n baseURL,\n () => auth.getAccessToken(),\n () => cachedUserUid\n );\n const s3: S3Client = createS3Client(authenticatedHttpClient);\n\n // ASR and TTS clients use WebSocket, pass token getter for authentication\n // Token can be appended to WebSocket URL as query parameter\n const asr: (config: ASRClientConfig) => ASRClient = createASRClient({\n getAccessToken: () => auth.getAccessToken(),\n });\n const asrHttp: (config: ASRHttpClientConfig) => ASRHttpClient = createASRHttpClient({\n getAccessToken: () => auth.getAccessToken(),\n });\n const tts: (config: TTSClientConfig) => TTSClient = createTTSClient({\n getAccessToken: () => auth.getAccessToken(),\n });\n\n // Return unified client interface\n const client: AmasterClient = {\n auth,\n entity,\n bpm,\n workflow,\n asr,\n asrHttp,\n copilot,\n function: functionClient,\n tts,\n s3,\n http: authenticatedHttpClient,\n\n // Expose token management methods from auth client\n isAuthenticated: () => auth.isAuthenticated(),\n getAccessToken: () => auth.getAccessToken(),\n setAccessToken: (token: string) => auth.setAccessToken(token),\n clearAuth: () => auth.clearAuth(),\n };\n\n return client;\n}\n"]}
@@ -0,0 +1,421 @@
1
+ import { AuthClient } from '@amaster.ai/auth-client';
2
+ export { LoginParams, LoginResponse, OAuthProvider, Permission, RegisterParams, Role, Session, User } from '@amaster.ai/auth-client';
3
+ import { EntityClient } from '@amaster.ai/entity-client';
4
+ export { EntityListResponse, EntityQueryParams, FilterGroup, FilterItem, FilterOperator } from '@amaster.ai/entity-client';
5
+ import { BpmClient } from '@amaster.ai/bpm-client';
6
+ export { ActivityInstanceTree, CamundaVariable, HistoryActivityInstance, HistoryProcessInstance, HistoryTask, ProcessInstance, ProcessVariable, Task, TaskFormSchema, TaskQueryParams, UserOperationLog } from '@amaster.ai/bpm-client';
7
+ import { WorkflowClient } from '@amaster.ai/workflow-client';
8
+ export { WorkflowFile, WorkflowInputValue, WorkflowRunRequest, WorkflowRunResponse } from '@amaster.ai/workflow-client';
9
+ import { ASRClientConfig, ASRClient, ASRHttpClientConfig, ASRHttpClient } from '@amaster.ai/asr-client';
10
+ export { ASRClient, ASRClientConfig, ASRHttpClient, ASRHttpClientConfig, ASRLanguage } from '@amaster.ai/asr-client';
11
+ import { CopilotClient } from '@amaster.ai/copilot-client';
12
+ export { ChatMessage, ChatOptions, CopilotClient, FileContent, ImageContent, MessageContent, TextContent } from '@amaster.ai/copilot-client';
13
+ import { FunctionClient } from '@amaster.ai/function-client';
14
+ export { FunctionClient } from '@amaster.ai/function-client';
15
+ import { TTSClientConfig, TTSClient } from '@amaster.ai/tts-client';
16
+ export { TTSClient, TTSClientConfig } from '@amaster.ai/tts-client';
17
+ import { S3Client } from '@amaster.ai/s3-client';
18
+ export { S3Client, S3Metadata, UploadRes } from '@amaster.ai/s3-client';
19
+ import { HttpClient } from '@amaster.ai/http-client';
20
+ export { ClientError, ClientResult, HttpClient, RequestConfig } from '@amaster.ai/http-client';
21
+
22
+ /**
23
+ * Amaster Client Configuration Options
24
+ */
25
+ interface AmasterClientOptions {
26
+ /**
27
+ * Base URL for the Amaster API (optional)
28
+ *
29
+ * If not provided:
30
+ * - Browser/H5: Uses dev proxy or relative URLs
31
+ * - Taro/Mini-program: Auto-reads from process.env.TARO_APP_API_BASE_URL or VITE_API_BASE_URL
32
+ *
33
+ * @example 'https://api.amaster.ai'
34
+ */
35
+ baseURL?: string;
36
+ /**
37
+ * Optional custom headers to include in all requests
38
+ */
39
+ headers?: Record<string, string>;
40
+ /**
41
+ * Callback function triggered when a 401 Unauthorized response is received
42
+ * Useful for redirecting to login page or showing auth modal
43
+ * @example () => window.location.href = '/login'
44
+ */
45
+ onUnauthorized?: () => void;
46
+ /**
47
+ * Callback function triggered when the access token expires
48
+ * Auto-refresh is handled internally, this is for additional actions
49
+ */
50
+ onTokenExpired?: () => void;
51
+ /**
52
+ * Enable automatic token refresh (default: true)
53
+ */
54
+ autoRefresh?: boolean;
55
+ /**
56
+ * Token refresh threshold in seconds (default: 300 = 5 minutes)
57
+ * Tokens will be refreshed this many seconds before expiry
58
+ */
59
+ refreshThreshold?: number;
60
+ /**
61
+ * Automatically handle OAuth callback on initialization (default: true)
62
+ *
63
+ * When enabled, the client will automatically detect and process OAuth
64
+ * callback URLs containing #access_token. After processing, the hash
65
+ * is automatically cleared from the URL for security.
66
+ *
67
+ * Set to false if you want to manually handle OAuth callbacks.
68
+ *
69
+ * @default true
70
+ */
71
+ autoHandleOAuthCallback?: boolean;
72
+ }
73
+ /**
74
+ * Unified Amaster Client
75
+ *
76
+ * Provides a simplified, Supabase-style API to access all Amaster services
77
+ */
78
+ interface AmasterClient {
79
+ /**
80
+ * Authentication module
81
+ *
82
+ * @example
83
+ * ```typescript
84
+ * // Login
85
+ * await client.auth.login({ email, password });
86
+ *
87
+ * // Register
88
+ * await client.auth.register({ username, email, password });
89
+ *
90
+ * // Logout
91
+ * await client.auth.logout();
92
+ *
93
+ * // Get current user
94
+ * const user = await client.auth.getMe();
95
+ * ```
96
+ */
97
+ auth: AuthClient;
98
+ /**
99
+ * Entity CRUD operations module
100
+ *
101
+ * @example
102
+ * ```typescript
103
+ * // List entities
104
+ * const result = await client.entity.list('default', 'users', {
105
+ * page: 1,
106
+ * perPage: 20,
107
+ * orderBy: 'createdAt',
108
+ * orderDir: 'desc'
109
+ * });
110
+ *
111
+ * // Get single entity
112
+ * const user = await client.entity.get('default', 'users', 1);
113
+ *
114
+ * // Create entity
115
+ * await client.entity.create('default', 'users', { name: 'John' });
116
+ *
117
+ * // Update entity
118
+ * await client.entity.update('default', 'users', 1, { name: 'Jane' });
119
+ *
120
+ * // Delete entity
121
+ * await client.entity.delete('default', 'users', 1);
122
+ * ```
123
+ */
124
+ entity: EntityClient;
125
+ /**
126
+ * BPM (Business Process Management) module
127
+ *
128
+ * @example
129
+ * ```typescript
130
+ * // Start a process
131
+ * await client.bpm.startProcess({
132
+ * processKey: 'approval-process',
133
+ * variables: { amount: 1000 }
134
+ * });
135
+ *
136
+ * // Get my tasks
137
+ * const tasks = await client.bpm.getMyTasks();
138
+ *
139
+ * // Complete a task
140
+ * await client.bpm.completeTask(taskId, { approved: true });
141
+ * ```
142
+ */
143
+ bpm: BpmClient;
144
+ /**
145
+ * Workflow execution module
146
+ *
147
+ * @example
148
+ * ```typescript
149
+ * // Execute a workflow
150
+ * const result = await client.workflow.execute('my-workflow', {
151
+ * input: { data: 'value' }
152
+ * });
153
+ * ```
154
+ */
155
+ workflow: WorkflowClient;
156
+ /**
157
+ * ASR (Automatic Speech Recognition) module - WebSocket-based real-time speech recognition
158
+ *
159
+ * Suitable for scenarios requiring real-time transcription results, such as voice input, live captions, etc.
160
+ *
161
+ * @example
162
+ * ```typescript
163
+ * // Real-time streaming recognition
164
+ * const asrClient = client.asr({
165
+ * onReady() {
166
+ * console.log('ASR Ready');
167
+ * },
168
+ * onTranscript(text, isFinal) {
169
+ * console.log(isFinal ? '[Final]' : '[Interim]', text);
170
+ * },
171
+ * onError(err) {
172
+ * console.error('ASR Error:', err);
173
+ * },
174
+ * onClose() {
175
+ * console.log('ASR Connection Closed');
176
+ * },
177
+ * });
178
+ *
179
+ * await asrClient.connect();
180
+ * await asrClient.startRecording();
181
+ *
182
+ * // Stop and close
183
+ * asrClient.stopRecording();
184
+ * asrClient.close();
185
+ * ```
186
+ */
187
+ asr: (config: ASRClientConfig) => ASRClient;
188
+ /**
189
+ * ASR Http module - HTTP-based press-to-talk speech recognition
190
+ *
191
+ * Suitable for press-to-talk scenarios where you hold to speak and release to recognize,
192
+ * such as voice messages, voice search, etc.
193
+ *
194
+ * @example
195
+ * ```typescript
196
+ * // Press-to-talk recognition
197
+ * const asrHttpClient = client.asrHttp({
198
+ * onRecordingStart() {
199
+ * console.log('Recording started');
200
+ * },
201
+ * onRecordingStop() {
202
+ * console.log('Recording stopped');
203
+ * },
204
+ * onResult(text) {
205
+ * console.log('Recognition result:', text);
206
+ * },
207
+ * onError(err) {
208
+ * console.error('ASR HTTP Error:', err);
209
+ * },
210
+ * });
211
+ *
212
+ * await asrHttpClient.startRecording();
213
+ * // ... user speaks ...
214
+ * const result = await asrHttpClient.stopRecording();
215
+ * ```
216
+ */
217
+ asrHttp: (config: ASRHttpClientConfig) => ASRHttpClient;
218
+ /**
219
+ * Copilot AI assistant module
220
+ *
221
+ * @example
222
+ * ```typescript
223
+ * // Send a message
224
+ * const result = await client.copilot.sendMessage([
225
+ * { role: 'user', content: 'Hello' }
226
+ * ]);
227
+ * ```
228
+ */
229
+ copilot: CopilotClient;
230
+ /**
231
+ * Function invocation module
232
+ *
233
+ * @example
234
+ * ```typescript
235
+ * // Call a function
236
+ * const result = await client.function.invoke('myFunction', {
237
+ * param: 'value'
238
+ * });
239
+ * ```
240
+ */
241
+ function: FunctionClient;
242
+ /**
243
+ * TTS (Text-to-Speech) module - WebSocket-based real-time speech synthesis
244
+ *
245
+ * Supports multiple voices and audio formats. Built-in playback only supports PCM format.
246
+ *
247
+ * @example
248
+ * ```typescript
249
+ * // Connect and speak
250
+ * const ttsClient = client.tts({
251
+ * voice: 'Cherry',
252
+ * autoPlay: true,
253
+ * onReady() {
254
+ * console.log('TTS Ready');
255
+ * },
256
+ * onAudioStart() {
257
+ * console.log('Playing audio');
258
+ * },
259
+ * onAudioEnd() {
260
+ * console.log('Audio playback ended');
261
+ * },
262
+ * });
263
+ *
264
+ * await ttsClient.connect();
265
+ * await ttsClient.speak('Hello, welcome to Amaster!');
266
+ *
267
+ * // Close when done
268
+ * ttsClient.close();
269
+ * ```
270
+ */
271
+ tts: (config: TTSClientConfig) => TTSClient;
272
+ /**
273
+ * S3 Storage module
274
+ *
275
+ * @example
276
+ * ```typescript
277
+ * // Upload file
278
+ * await client.s3.upload(file);
279
+ *
280
+ * // Download file
281
+ * await client.s3.download('path/to/file');
282
+ * ```
283
+ */
284
+ s3: S3Client;
285
+ /**
286
+ * HTTP client for custom requests
287
+ *
288
+ * Provides direct access to the underlying HTTP client with automatic
289
+ * authentication token attachment. Useful for calling custom endpoints
290
+ * or APIs not covered by the specialized clients.
291
+ *
292
+ * Supports both `data` (Axios style) and `body` (Fetch API style) for request payload.
293
+ *
294
+ * @example
295
+ * ```typescript
296
+ * // Make a custom GET request
297
+ * const { data, error } = await client.http.request({
298
+ * url: '/custom/endpoint',
299
+ * method: 'GET'
300
+ * });
301
+ *
302
+ * // Make a POST request with data (Axios style)
303
+ * const { data, error } = await client.http.request({
304
+ * url: '/custom/endpoint',
305
+ * method: 'POST',
306
+ * data: { key: 'value' }
307
+ * });
308
+ *
309
+ * // Make a POST request with body (Fetch API style, auto-converted to data)
310
+ * const { data, error } = await client.http.request({
311
+ * url: '/custom/endpoint',
312
+ * method: 'POST',
313
+ * body: { key: 'value' }
314
+ * });
315
+ * ```
316
+ */
317
+ http: HttpClient;
318
+ /**
319
+ * Check if the user is currently authenticated
320
+ */
321
+ isAuthenticated(): boolean;
322
+ /**
323
+ * Get the current access token
324
+ */
325
+ getAccessToken(): string | null;
326
+ /**
327
+ * Manually set an access token (useful for SSR or token from external auth)
328
+ */
329
+ setAccessToken(token: string): void;
330
+ /**
331
+ * Clear all authentication data
332
+ */
333
+ clearAuth(): void;
334
+ }
335
+
336
+ /**
337
+ * ============================================================================
338
+ * @amaster.ai/client - Unified Amaster Client
339
+ * ============================================================================
340
+ *
341
+ * Supabase-inspired unified API client for the Amaster platform
342
+ *
343
+ * Features:
344
+ * - Single client instance for all services (auth, entity, bpm, workflow)
345
+ * - Automatic token management and refresh
346
+ * - Auto-attach authentication to all requests
347
+ * - Centralized error handling
348
+ *
349
+ * @example
350
+ * ```typescript
351
+ * // With explicit baseURL
352
+ * const client = createClient({
353
+ * baseURL: 'https://api.amaster.ai',
354
+ * onUnauthorized: () => window.location.href = '/login'
355
+ * });
356
+ *
357
+ * // Auto-detect baseURL from env (Taro/Mini-program)
358
+ * const client = createClient({
359
+ * onUnauthorized: () => window.location.href = '/login'
360
+ * });
361
+ *
362
+ * // Login
363
+ * await client.auth.login({ email, password });
364
+ *
365
+ * // All subsequent requests automatically include auth token
366
+ * await client.entity.list('default', 'users');
367
+ * await client.bpm.startProcess({ processKey: 'approval' });
368
+ * ```
369
+ */
370
+
371
+ /**
372
+ * Create a unified Amaster client instance
373
+ *
374
+ * This function creates a single client that provides access to all Amaster services:
375
+ * - Authentication (login, register, logout)
376
+ * - Entity CRUD operations
377
+ * - BPM (Business Process Management)
378
+ * - Workflow execution
379
+ *
380
+ * All sub-clients automatically share the same HTTP client and authentication state,
381
+ * ensuring that tokens are consistently attached to all requests.
382
+ *
383
+ * @param options - Client configuration options
384
+ * @returns A unified Amaster client instance
385
+ *
386
+ * @example
387
+ * ```typescript
388
+ * // Basic usage with explicit baseURL
389
+ * const client = createClient({
390
+ * baseURL: 'https://api.amaster.ai'
391
+ * });
392
+ *
393
+ * // Auto-detect baseURL (for Taro/Mini-program or dev proxy)
394
+ * const client = createClient({});
395
+ *
396
+ * // With authentication callbacks
397
+ * const client = createClient({
398
+ * baseURL: 'https://api.amaster.ai',
399
+ * onUnauthorized: () => {
400
+ * // Redirect to login or show auth modal
401
+ * window.location.href = '/login';
402
+ * },
403
+ * onTokenExpired: () => {
404
+ * console.log('Token expired, refreshing...');
405
+ * }
406
+ * });
407
+ *
408
+ * // Login
409
+ * await client.auth.login({
410
+ * email: 'user@example.com',
411
+ * password: 'password123'
412
+ * });
413
+ *
414
+ * // Now all requests automatically include the auth token
415
+ * const users = await client.entity.list('default', 'users');
416
+ * const tasks = await client.bpm.getMyTasks();
417
+ * ```
418
+ */
419
+ declare function createClient(options: AmasterClientOptions): AmasterClient;
420
+
421
+ export { type AmasterClient, type AmasterClientOptions, createClient };