@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.
@@ -0,0 +1,95 @@
1
+ import { AxiosRequestConfig, AxiosInstance } from 'axios';
2
+
3
+ type ClientError = {
4
+ message: string;
5
+ status?: number;
6
+ code?: string;
7
+ details?: unknown;
8
+ };
9
+ type ClientResult<T> = {
10
+ data: T | null;
11
+ error: ClientError | null;
12
+ status: number;
13
+ };
14
+ type RequestConfig = AxiosRequestConfig & {
15
+ url: string;
16
+ method: NonNullable<AxiosRequestConfig["method"]> | string;
17
+ };
18
+ type AdapterResponse = {
19
+ status: number;
20
+ data: unknown;
21
+ headers?: unknown;
22
+ };
23
+ type HttpAdapter = (_config: RequestConfig) => Promise<AdapterResponse>;
24
+ type HttpClientOptions = {
25
+ /**
26
+ * HTTP adapter to use:
27
+ * - undefined: auto-detect (taro if mini-program APIs exist, otherwise axios)
28
+ * - "taro": force mini-program request (wx/tt/my/...) or global Taro.request
29
+ * - "axios": force axios
30
+ * - AxiosInstance: use provided axios instance
31
+ * - function: custom adapter
32
+ */
33
+ adapter?: "taro" | "axios" | AxiosInstance | HttpAdapter;
34
+ /**
35
+ * Base URL to prefix when `config.url` is relative (e.g. "/api/...").
36
+ *
37
+ * If not provided:
38
+ * - Taro/mini-program: auto-reads from process.env.TARO_APP_API_BASE_URL or process.env.VITE_API_BASE_URL
39
+ * - H5/Browser: no baseURL (expects dev proxy or absolute URLs)
40
+ */
41
+ baseURL?: string;
42
+ /** Default headers merged into each request */
43
+ headers?: Record<string, string>;
44
+ /**
45
+ * Custom response transform function to extract/modify data from backend response
46
+ * If not provided, uses default transform logic for { status: 0/1, data: {...} }
47
+ *
48
+ * Similar to axios's transformResponse option
49
+ *
50
+ * @example
51
+ * ```typescript
52
+ * // For backend that returns: { statusCode: 200, data: {...} }
53
+ * const client = createHttpClient({
54
+ * transformResponse: (response) => {
55
+ * if (response && typeof response === 'object' && 'data' in response) {
56
+ * return response.data;
57
+ * }
58
+ * return response;
59
+ * }
60
+ * });
61
+ * ```
62
+ */
63
+ transformResponse?: <T>(responseData: unknown) => T;
64
+ /**
65
+ * Whether to log errors to console (default: true)
66
+ * Set to false to disable automatic error logging
67
+ */
68
+ logErrors?: boolean;
69
+ };
70
+ type HttpClient = {
71
+ request<T>(_config: RequestConfig): Promise<ClientResult<T>>;
72
+ };
73
+ /**
74
+ * Create an HTTP client instance
75
+ *
76
+ * @param axiosInstance - Optional axios instance to use (defaults to a basic axios instance)
77
+ * @returns HttpClient with request method
78
+ *
79
+ * @example
80
+ * ```typescript
81
+ * import axios from "axios";
82
+ * import { createHttpClient } from "@amaster.ai/http-client";
83
+ *
84
+ * const instance = axios.create({ baseURL: "https://api.example.com" });
85
+ * const client = createHttpClient(instance);
86
+ *
87
+ * const result = await client.request({
88
+ * url: "/users",
89
+ * method: "get",
90
+ * });
91
+ * ```
92
+ */
93
+ declare function createHttpClient(axiosInstanceOrOptions?: AxiosInstance | HttpClientOptions): HttpClient;
94
+
95
+ export { type AdapterResponse, type ClientError, type ClientResult, type HttpAdapter, type HttpClient, type HttpClientOptions, type RequestConfig, createHttpClient };
@@ -0,0 +1,338 @@
1
+ /**
2
+ * * A Supabase-inspired unified client for the Amaster platform.
3
+ *
4
+ * ## Features
5
+ * - Single client instance for all services (auth, entity, bpm, workflow)
6
+ * - Automatic token management and refresh
7
+ * - Auto-attach authentication to all requests
8
+ * - Centralized error handling
9
+ *
10
+ * ## Quick Start
11
+ * ```typescript
12
+ * import { createClient } from '@amaster.ai/client';
13
+ *
14
+ * const client = createClient({
15
+ * baseURL: 'https://api.amaster.ai',
16
+ * onUnauthorized: () => window.location.href = '/login'
17
+ * });
18
+ *
19
+ * // Login
20
+ * await client.auth.login({ email, password });
21
+ *
22
+ * // All subsequent requests automatically include auth token
23
+ * await client.entity.list('default', 'users');
24
+ * await client.bpm.startProcess('approval', {});
25
+ * ```
26
+ *
27
+ * ## Module Documentation
28
+ * For detailed API documentation, see individual module type definitions:
29
+ * - **Authentication**: {@link ./auth/index.d.ts} (split into user, password-auth, code-auth, oauth, permissions, profile)
30
+ * - **Entity Operations**: {@link ./entity.d.ts}
31
+ * - **BPM (Business Process)**: {@link ./bpm.d.ts}
32
+ * - **Workflow Execution**: {@link ./workflow.d.ts}
33
+ *
34
+ * ## AI-Friendly Type Structure
35
+ * This package provides modular type definitions optimized for AI tools and large language models.
36
+ * Types are split into focused modules that can be loaded on-demand:
37
+ *
38
+ * **Authentication Types** (70-88% token savings):
39
+ * - `@amaster.ai/client/auth/user` - User types (100 lines)
40
+ * - `@amaster.ai/client/auth/password-auth` - Login/register (200 lines)
41
+ * - `@amaster.ai/client/auth/code-auth` - Verification code (150 lines)
42
+ * - `@amaster.ai/client/auth/oauth` - OAuth providers (120 lines)
43
+ * - `@amaster.ai/client/auth/permissions` - Permission helpers (80 lines)
44
+ * - `@amaster.ai/client/auth/profile` - Profile management (100 lines)
45
+ * */
46
+
47
+ import type { AuthClientAPI } from "./auth/index";
48
+ import type { EntityClientAPI } from "./entity";
49
+ import type { BpmClientAPI } from "./bpm";
50
+ import type { WorkflowClientAPI } from "./workflow";
51
+ import type { ASRClientConfig, ASRClient, ASRHttpClientConfig, ASRHttpClient } from "./asr";
52
+ import type { CopilotClientAPI } from "./copilot";
53
+ import type { FunctionClientAPI } from "./function";
54
+ import type { TTSClientAPI } from "./tts";
55
+ import type { S3ClientAPI } from "./s3";
56
+ import type { HttpClient } from "./http";
57
+
58
+ /**
59
+ * Configuration options for creating an Amaster client
60
+ *
61
+ */
62
+ export interface AmasterClientOptions {
63
+ /**
64
+ * Base URL for the Amaster API
65
+ *
66
+ */
67
+ baseURL: string;
68
+
69
+ /**
70
+ * Optional custom headers to include in ALL requests
71
+ *
72
+ * These headers will be merged with authentication headers.
73
+ * Useful for tenant IDs, API keys, or application metadata.
74
+ *
75
+ */
76
+ headers?: Record<string, string>;
77
+
78
+ /**
79
+ * Callback triggered when a 401 Unauthorized response is received
80
+ *
81
+ * Use this to redirect to login page or show authentication modal.
82
+ * This callback is invoked BEFORE the request promise rejects.
83
+ *
84
+ */
85
+ onUnauthorized?: () => void;
86
+
87
+ /**
88
+ * Callback triggered when the access token expires
89
+ *
90
+ * Note: Token refresh is handled automatically by the client.
91
+ * This callback is for additional actions like logging or analytics.
92
+ *
93
+ */
94
+ onTokenExpired?: () => void;
95
+
96
+ /**
97
+ * Enable automatic token refresh (default: true)
98
+ *
99
+ * When enabled, tokens are automatically refreshed before expiry.
100
+ *
101
+ * @default true
102
+ */
103
+ autoRefresh?: boolean;
104
+
105
+ /**
106
+ * Token refresh threshold in seconds (default: 300)
107
+ *
108
+ * Tokens will be refreshed this many seconds before expiry.
109
+ * For example, if set to 300 (5 minutes), a token expiring at
110
+ * 10:00:00 will be refreshed at 9:55:00.
111
+ *
112
+ * @default 300
113
+ */
114
+ refreshThreshold?: number;
115
+
116
+ /**
117
+ * Auto-handle OAuth callback on page load (default: true)
118
+ *
119
+ * Automatically detects and processes `#access_token` in URL hash,
120
+ * then clears the hash for security. Set to `false` to manually
121
+ * call `client.auth.handleOAuthCallback()`.
122
+ *
123
+ * @default true
124
+ */
125
+ autoHandleOAuthCallback?: boolean;
126
+ }
127
+
128
+ /**
129
+ * Unified Amaster Client interface
130
+ *
131
+ * This is the main client object returned by `createClient()`.
132
+ * It provides access to all Amaster services through a unified interface.
133
+ *
134
+ * ## Core Modules
135
+ * - {@link auth} - Authentication and user management
136
+ * - {@link entity} - CRUD operations for entities
137
+ * - {@link bpm} - Business process management
138
+ * - {@link workflow} - Workflow execution
139
+ *
140
+ * ## Token Management
141
+ * - {@link isAuthenticated} - Check if user is authenticated
142
+ * - {@link getAccessToken} - Get current access token
143
+ * - {@link setAccessToken} - Set access token manually
144
+ * - {@link clearAuth} - Clear all authentication state
145
+ *
146
+ */
147
+ export interface AmasterClient {
148
+ /**
149
+ * Authentication module
150
+ *
151
+ * Provides methods for user authentication, registration, and management.
152
+ *
153
+ * For detailed documentation, see {@link ./auth.d.ts}
154
+ *
155
+ */
156
+ auth: AuthClientAPI;
157
+
158
+ /**
159
+ * Entity CRUD operations module
160
+ *
161
+ * Provides methods for creating, reading, updating, and deleting entities.
162
+ *
163
+ * For detailed documentation, see {@link ./entity.d.ts}
164
+ *
165
+ */
166
+ entity: EntityClientAPI;
167
+
168
+ /**
169
+ * Business Process Management (BPM) module
170
+ *
171
+ * Provides methods for managing BPMN processes and tasks.
172
+ *
173
+ * For detailed documentation, see {@link ./bpm.d.ts}
174
+ *
175
+ */
176
+ bpm: BpmClientAPI;
177
+
178
+ /**
179
+ * Workflow execution module
180
+ *
181
+ * Provides methods for executing Dify-style workflows.
182
+ *
183
+ * For detailed documentation, see {@link ./workflow.d.ts}
184
+ *
185
+ */
186
+ workflow: WorkflowClientAPI;
187
+
188
+ /**
189
+ * ASR (Automatic Speech Recognition) module
190
+ *
191
+ * Provides methods for real-time speech-to-text conversion via WebSocket.
192
+ *
193
+ * For detailed documentation, see {@link ./asr.d.ts}
194
+ */
195
+ asr: (config: ASRClientConfig) => ASRClient;
196
+
197
+ /**
198
+ * ASR HTTP module
199
+ *
200
+ * Provides methods for speech-to-text conversion via HTTP API.
201
+ *
202
+ * For detailed documentation, see
203
+ */
204
+ asrHttp: (config: ASRHttpClientConfig) => ASRHttpClient;
205
+
206
+ /**
207
+ * Copilot AI Assistant module
208
+ *
209
+ * Provides methods for interactive AI conversations with a2a streaming.
210
+ *
211
+ * For detailed documentation, see {@link ./copilot.d.ts}
212
+ *
213
+ */
214
+ copilot: CopilotClientAPI;
215
+
216
+ /**
217
+ * Serverless Function module
218
+ *
219
+ * Provides methods for invoking serverless functions.
220
+ *
221
+ * For detailed documentation, see {@link ./function.d.ts}
222
+ */
223
+ function: FunctionClientAPI;
224
+
225
+ /**
226
+ * TTS (Text-to-Speech) module
227
+ *
228
+ * Provides methods for real-time text-to-speech conversion via WebSocket.
229
+ *
230
+ * For detailed documentation, see {@link ./tts.d.ts}
231
+ */
232
+ tts: TTSClientAPI;
233
+
234
+ /**
235
+ * S3 Storage module
236
+ *
237
+ * Provides methods for file upload, download, and management.
238
+ *
239
+ * For detailed documentation, see {@link ./s3.d.ts}
240
+ */
241
+ s3: S3ClientAPI;
242
+
243
+ /**
244
+ * HTTP client instance used for all requests
245
+ *
246
+ * This is the underlying HTTP client that handles all API requests.
247
+ * It automatically includes authentication headers and base URL.
248
+ * You can use this client to make custom requests to the Amaster API
249
+ * or your own backend while still benefiting from automatic token management.
250
+ * For example:
251
+ * ```typescript
252
+ * const response = await client.http.request({
253
+ * url: '/api/custom-endpoint',
254
+ * method: 'POST',
255
+ * data: { key: 'value' }
256
+ * });
257
+ * console.log(response.data);
258
+ * ```
259
+ * Note: The `http` client is an instance of the same HTTP client used internally by the Amaster client.
260
+ * It automatically includes the base URL and authentication headers configured in `createClient()`.
261
+ */
262
+ http: HttpClient;
263
+
264
+ /**
265
+ * Check if the user is currently authenticated
266
+ *
267
+ * @returns `true` if a valid access token exists, `false` otherwise
268
+ *
269
+ */
270
+ isAuthenticated(): boolean;
271
+
272
+ /**
273
+ * Get the current access token
274
+ *
275
+ * @returns The access token string, or `null` if not authenticated
276
+ *
277
+ */
278
+ getAccessToken(): string | null;
279
+
280
+ /**
281
+ * Manually set the access token
282
+ *
283
+ * Useful when you have a token from another source (e.g., SSO, OAuth).
284
+ * After setting the token, all requests will use it automatically.
285
+ *
286
+ * @param token - The JWT access token to set
287
+ *
288
+ */
289
+ setAccessToken(token: string): void;
290
+
291
+ /**
292
+ * Clear all authentication state
293
+ *
294
+ * This removes:
295
+ * - Access token
296
+ * - User information
297
+ * - Auto-refresh timers
298
+ *
299
+ * After calling this, `isAuthenticated()` will return `false`
300
+ * and all requests will be unauthenticated.
301
+ *
302
+ */
303
+ clearAuth(): void;
304
+ }
305
+
306
+ /**
307
+ * Factory function to create a unified Amaster client
308
+ *
309
+ * This is the main entry point for using the Amaster client library.
310
+ * It returns a client instance that provides access to all Amaster services.
311
+ *
312
+ * @param options - Configuration options for the client
313
+ * @returns A configured Amaster client instance
314
+ *
315
+ */
316
+ export declare function createClient(options: AmasterClientOptions): AmasterClient;
317
+
318
+ // Re-export shared common types
319
+ export type { ClientResult } from "./common";
320
+
321
+ // Re-export main client interfaces
322
+ export type { AuthClientAPI } from "./auth";
323
+ export type { EntityClientAPI } from "./entity";
324
+ export type { BpmClientAPI } from "./bpm";
325
+ export type { WorkflowClientAPI } from "./workflow";
326
+ export type { ASRClient, ASRClientConfig, ASRHttpClient, ASRHttpClientConfig } from "./asr";
327
+ export type { CopilotClientAPI } from "./copilot";
328
+ export type { FunctionClientAPI } from "./function";
329
+ export type { TTSClientAPI } from "./tts";
330
+ export type { S3ClientAPI } from "./s3";
331
+ export type { HttpClient } from "./http";
332
+
333
+ // For detailed types, import directly from submodules:
334
+ // import type { LoginParams, User } from '@amaster.ai/client/auth'
335
+ // import type { EntityQueryParams } from '@amaster.ai/client/entity'
336
+ // import type { Task, ProcessInstance } from '@amaster.ai/client/bpm'
337
+ // import type { WorkflowRunRequest } from '@amaster.ai/client/workflow'
338
+ // import type { ServerToClientMessage } from '@amaster.ai/client/copilot'
package/types/s3.d.ts ADDED
@@ -0,0 +1,96 @@
1
+ /**
2
+ *
3
+ * @module s3
4
+ */
5
+
6
+ import type { ClientResult } from './common';
7
+
8
+ // ==================== Response Types ====================
9
+
10
+ /**
11
+ * Upload response data
12
+ *
13
+ */
14
+ export interface UploadRes {
15
+ /** File key in storage */
16
+ key: string;
17
+ /** Full access URL */
18
+ url: string;
19
+ }
20
+
21
+ /**
22
+ * File metadata
23
+ *
24
+ */
25
+ export interface S3Metadata {
26
+ contentType?: string;
27
+ contentLength?: number;
28
+ lastModified?: string;
29
+ [key: string]: any;
30
+ }
31
+
32
+ // ==================== S3 Client API ====================
33
+
34
+ /**
35
+ * S3 Storage Client API
36
+ *
37
+ * Provides methods for uploading, downloading, and managing files in object storage.
38
+ *
39
+ * @since 1.0.0
40
+ */
41
+ export interface S3ClientAPI {
42
+ /**
43
+ * Download a file
44
+ *
45
+ * @param filename - The name/key of the file to download
46
+ * @returns Blob data of the file
47
+ *
48
+ * @example
49
+ * const result = await client.s3.download('documents/report.pdf');
50
+ * if (result.success) {
51
+ * const blob = result.data;
52
+ * const url = URL.createObjectURL(blob);
53
+ * window.open(url);
54
+ * }
55
+ *
56
+ * @since 1.0.0
57
+ */
58
+ download(filename: string): Promise<ClientResult<Blob>>;
59
+
60
+ /**
61
+ * Get metadata for a file
62
+ *
63
+ * @param key - The key of the file
64
+ * @returns File metadata
65
+ *
66
+ * @example
67
+ * const result = await client.s3.getMetadata('images/photo.jpg');
68
+ * if (result.success) {
69
+ * console.log('Size:', result.data.contentLength);
70
+ * console.log('Type:', result.data.contentType);
71
+ * }
72
+ *
73
+ * @since 1.0.0
74
+ */
75
+ getMetadata(key: string): Promise<ClientResult<S3Metadata>>;
76
+
77
+ /**
78
+ * Upload a file
79
+ *
80
+ * @param file - The file to upload (File or Blob)
81
+ * @returns Upload result containing key and URL
82
+ *
83
+ * @example
84
+ * const fileInput = document.querySelector('input[type="file"]');
85
+ * const file = fileInput.files[0];
86
+ *
87
+ * const result = await client.s3.upload(file);
88
+ * if (result.success) {
89
+ * console.log('File uploaded:', result.data.url);
90
+ * console.log('File key:', result.data.key);
91
+ * }
92
+ *
93
+ * @since 1.0.0
94
+ */
95
+ upload(file: File | Blob): Promise<ClientResult<UploadRes>>;
96
+ }
package/types/tts.d.ts ADDED
@@ -0,0 +1,88 @@
1
+ /**
2
+ * * Real-time text-to-speech synthesis using WebSocket connection.
3
+ *
4
+ * @module tts
5
+ */
6
+
7
+ /**
8
+ * TTS Client Configuration
9
+ *
10
+ */
11
+ export interface TTSClientConfig {
12
+
13
+ /** Voice name, default 'Cherry' */
14
+ voice?: string;
15
+
16
+ /** Auto play audio, default true */
17
+ autoPlay?: boolean;
18
+
19
+ /** Audio format, default 'pcm' */
20
+ audioFormat?: "pcm" | "mp3" | "wav" | "opus";
21
+
22
+ /** Sample rate, default 24000 */
23
+ sampleRate?: number;
24
+
25
+ /** Called when connection is ready */
26
+ onReady?: () => void;
27
+
28
+ /** Called when audio playback starts */
29
+ onAudioStart?: () => void;
30
+
31
+ /** Called when audio playback ends */
32
+ onAudioEnd?: () => void;
33
+
34
+ /**
35
+ * Called on each audio chunk received
36
+ * @param chunks - Array of base64-encoded audio chunks
37
+ */
38
+ onAudioChunk?: (chunks: string[]) => void;
39
+
40
+ /** Called on error */
41
+ onError?: (error: Error) => void;
42
+ }
43
+
44
+ /**
45
+ * TTS (Text-to-Speech) Client API
46
+ *
47
+ * Provides real-time text-to-speech synthesis via WebSocket.
48
+ *
49
+ * @since 1.0.0
50
+ */
51
+ export interface TTSClientAPI {
52
+ /**
53
+ * Connect to TTS service
54
+ *
55
+ * Establishes WebSocket connection to the text-to-speech service.
56
+ *
57
+ * @returns Promise that resolves when connected
58
+ *
59
+ */
60
+ connect(): Promise<void>;
61
+
62
+ /**
63
+ * Synthesize speech from text
64
+ *
65
+ * Converts text to speech and plays it (if autoPlay is enabled).
66
+ *
67
+ * @param text - Text to synthesize
68
+ * @returns Promise that resolves when synthesis starts
69
+ *
70
+ */
71
+ speak(text: string): Promise<void>;
72
+
73
+ /**
74
+ * Play audio from chunks
75
+ *
76
+ * Manually plays audio chunks when autoPlay is disabled.
77
+ *
78
+ */
79
+ play(): void;
80
+
81
+ /**
82
+ * Close connection
83
+ *
84
+ * Closes the WebSocket connection and releases resources.
85
+ *
86
+ */
87
+ close(): void;
88
+ }