@amaster.ai/client 1.1.0-beta.51 → 1.1.0-beta.53
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 +2 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/package.json +11 -11
- package/types/asr.d.ts +255 -167
- package/types/http.d.ts +95 -0
- package/types/index.d.ts +24 -1
- package/types/tts.d.ts +6 -0
package/dist/index.cjs
CHANGED
|
@@ -131,7 +131,8 @@ function createClient(options) {
|
|
|
131
131
|
getAccessToken: () => auth.getAccessToken()
|
|
132
132
|
});
|
|
133
133
|
const asrHttp = asrClient.createASRHttpClient({
|
|
134
|
-
getAccessToken: () => auth.getAccessToken()
|
|
134
|
+
getAccessToken: () => auth.getAccessToken(),
|
|
135
|
+
http: authenticatedHttpClient
|
|
135
136
|
});
|
|
136
137
|
const tts = ttsClient.createTTSClient({
|
|
137
138
|
getAccessToken: () => auth.getAccessToken()
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +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;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A,CAAK,cAAA;AAAe,GAC3C,CAAA;AACD,EAAA,MAAM,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"]}
|
|
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,IAAI,YAAA,GAAe,KAAA;AACnB,IAAA,IAAI,cAAA,GAA0C,IAAA;AAM9C,IAAA,SAAS,eAAe,MAAA,EAAwC;AAC9D,MAAA,IAAI,MAAA,CAAO,MAAA,KAAW,GAAA,EAAK,OAAO,KAAA;AAGlC,MAAA,IAAI,MAAA,CAAO,OAAO,OAAA,IAAW,UAAA,CAAW,KAAK,MAAA,CAAO,KAAA,CAAM,OAAO,CAAA,EAAG;AAClE,QAAA,OAAO,IAAA;AAAA,MACT;AAGA,MAAA,IAAI,MAAA,CAAO,OAAO,OAAA,EAA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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 http: authenticatedHttpClient,\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"]}
|
package/dist/index.js
CHANGED
|
@@ -129,7 +129,8 @@ function createClient(options) {
|
|
|
129
129
|
getAccessToken: () => auth.getAccessToken()
|
|
130
130
|
});
|
|
131
131
|
const asrHttp = createASRHttpClient({
|
|
132
|
-
getAccessToken: () => auth.getAccessToken()
|
|
132
|
+
getAccessToken: () => auth.getAccessToken(),
|
|
133
|
+
http: authenticatedHttpClient
|
|
133
134
|
});
|
|
134
135
|
const tts = createTTSClient({
|
|
135
136
|
getAccessToken: () => auth.getAccessToken()
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client.ts"],"names":[],"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,iBAAiB,gBAAA,CAAiB;AAAA,IACtC,OAAA;AAAA,IACA;AAAA,GACD,CAAA;AAGD,EAAA,MAAM,OAAmB,gBAAA,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,IAAI,YAAA,GAAe,KAAA;AACnB,IAAA,IAAI,cAAA,GAA0C,IAAA;AAM9C,IAAA,SAAS,eAAe,MAAA,EAAwC;AAC9D,MAAA,IAAI,MAAA,CAAO,MAAA,KAAW,GAAA,EAAK,OAAO,KAAA;AAGlC,MAAA,IAAI,MAAA,CAAO,OAAO,OAAA,IAAW,UAAA,CAAW,KAAK,MAAA,CAAO,KAAA,CAAM,OAAO,CAAA,EAAG;AAClE,QAAA,OAAO,IAAA;AAAA,MACT;AAGA,MAAA,IAAI,MAAA,CAAO,OAAO,OAAA,EAAS;AACzB,QAAA,MAAM,OAAA,GAAU,OAAO,KAAA,CAAM,OAAA;AAC7B,QAAA,IAAI,OAAO,OAAA,KAAY,QAAA,IAAY,U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gB,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.js","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"]}
|
|
1
|
+
{"version":3,"sources":["../src/client.ts"],"names":[],"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,iBAAiB,gBAAA,CA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AA,MAAM,MAA8C,eAAA,CAAgB;AAAA,IAClE,cAAA,EAAgB,MAAM,IAAA,CAAK,cAAA;AAAe,GAC3C,CAAA;AACD,EAAA,MAAM,UAA0D,mBAAA,CAAoB;AAAA,IAClF,cAAA,EAAgB,MAAM,IAAA,CAAK,cAAA,EAAe;AAAA,IAC1C,IAAA,EAAM;AAAA,GACP,CAAA;AACD,EAAA,MAAM,MAA8C,eAAA,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,EAAU,cAAA;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.js","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 http: authenticatedHttpClient,\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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@amaster.ai/client",
|
|
3
|
-
"version": "1.1.0-beta.
|
|
3
|
+
"version": "1.1.0-beta.53",
|
|
4
4
|
"description": "Unified API client for Amaster platform - All services in one package",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -72,16 +72,16 @@
|
|
|
72
72
|
"registry": "https://registry.npmjs.org/"
|
|
73
73
|
},
|
|
74
74
|
"dependencies": {
|
|
75
|
-
"@amaster.ai/
|
|
76
|
-
"@amaster.ai/
|
|
77
|
-
"@amaster.ai/
|
|
78
|
-
"@amaster.ai/
|
|
79
|
-
"@amaster.ai/
|
|
80
|
-
"@amaster.ai/
|
|
81
|
-
"@amaster.ai/
|
|
82
|
-
"@amaster.ai/
|
|
83
|
-
"@amaster.ai/
|
|
84
|
-
"@amaster.ai/
|
|
75
|
+
"@amaster.ai/auth-client": "1.1.0-beta.53",
|
|
76
|
+
"@amaster.ai/bpm-client": "1.1.0-beta.53",
|
|
77
|
+
"@amaster.ai/http-client": "1.1.0-beta.53",
|
|
78
|
+
"@amaster.ai/entity-client": "1.1.0-beta.53",
|
|
79
|
+
"@amaster.ai/function-client": "1.1.0-beta.53",
|
|
80
|
+
"@amaster.ai/copilot-client": "1.1.0-beta.53",
|
|
81
|
+
"@amaster.ai/workflow-client": "1.1.0-beta.53",
|
|
82
|
+
"@amaster.ai/s3-client": "1.1.0-beta.53",
|
|
83
|
+
"@amaster.ai/asr-client": "1.1.0-beta.53",
|
|
84
|
+
"@amaster.ai/tts-client": "1.1.0-beta.53"
|
|
85
85
|
},
|
|
86
86
|
"peerDependencies": {
|
|
87
87
|
"axios": "^1.11.0"
|
package/types/asr.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type{ HttpClient } from "./http";
|
|
1
2
|
/**
|
|
2
3
|
* ASR Realtime WebSocket Client for Qwen-ASR Realtime API
|
|
3
4
|
*
|
|
@@ -27,211 +28,298 @@
|
|
|
27
28
|
* await asrClient.close();
|
|
28
29
|
* ```
|
|
29
30
|
*/
|
|
30
|
-
export type ASRLanguage =
|
|
31
|
-
|
|
32
|
-
|
|
31
|
+
export type ASRLanguage =
|
|
32
|
+
| "zh"
|
|
33
|
+
| "yue"
|
|
34
|
+
| "en"
|
|
35
|
+
| "ja"
|
|
36
|
+
| "de"
|
|
37
|
+
| "ko"
|
|
38
|
+
| "ru"
|
|
39
|
+
| "fr"
|
|
40
|
+
| "pt"
|
|
41
|
+
| "ar"
|
|
42
|
+
| "it"
|
|
43
|
+
| "es"
|
|
44
|
+
| "hi"
|
|
45
|
+
| "id"
|
|
46
|
+
| "th"
|
|
47
|
+
| "tr"
|
|
48
|
+
| "uk"
|
|
49
|
+
| "vi"
|
|
50
|
+
| "cs"
|
|
51
|
+
| "da"
|
|
52
|
+
| "fil"
|
|
53
|
+
| "fi"
|
|
54
|
+
| "is"
|
|
55
|
+
| "ms"
|
|
56
|
+
| "no"
|
|
57
|
+
| "pl"
|
|
58
|
+
| "sv";
|
|
59
|
+
export type ClientEventType =
|
|
60
|
+
| "session.update"
|
|
61
|
+
| "input_audio_buffer.append"
|
|
62
|
+
| "input_audio_buffer.commit"
|
|
63
|
+
| "session.finish";
|
|
64
|
+
export type ServerEventType =
|
|
65
|
+
| "session.created"
|
|
66
|
+
| "session.updated"
|
|
67
|
+
| "input_audio_buffer.speech_started"
|
|
68
|
+
| "input_audio_buffer.speech_stopped"
|
|
69
|
+
| "input_audio_buffer.committed"
|
|
70
|
+
| "conversation.item.input_audio_transcription.text"
|
|
71
|
+
| "conversation.item.input_audio_transcription.completed"
|
|
72
|
+
| "session.finished"
|
|
73
|
+
| "error";
|
|
33
74
|
export interface BaseEvent {
|
|
34
|
-
|
|
35
|
-
|
|
75
|
+
event_id: string;
|
|
76
|
+
type: ClientEventType | ServerEventType;
|
|
36
77
|
}
|
|
37
78
|
export interface SessionUpdateEvent extends BaseEvent {
|
|
38
|
-
|
|
39
|
-
|
|
79
|
+
type: "session.update";
|
|
80
|
+
session: SessionConfig;
|
|
40
81
|
}
|
|
41
82
|
export interface InputAudioBufferAppendEvent extends BaseEvent {
|
|
42
|
-
|
|
43
|
-
|
|
83
|
+
type: "input_audio_buffer.append";
|
|
84
|
+
audio: string;
|
|
44
85
|
}
|
|
45
86
|
export interface InputAudioBufferCommitEvent extends BaseEvent {
|
|
46
|
-
|
|
87
|
+
type: "input_audio_buffer.commit";
|
|
47
88
|
}
|
|
48
89
|
export interface SessionFinishEvent extends BaseEvent {
|
|
49
|
-
|
|
90
|
+
type: "session.finish";
|
|
50
91
|
}
|
|
51
|
-
type ClientEvent =
|
|
92
|
+
type ClientEvent =
|
|
93
|
+
| SessionUpdateEvent
|
|
94
|
+
| InputAudioBufferAppendEvent
|
|
95
|
+
| InputAudioBufferCommitEvent
|
|
96
|
+
| SessionFinishEvent;
|
|
52
97
|
export interface SessionCreatedEvent extends BaseEvent {
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
98
|
+
type: "session.created";
|
|
99
|
+
session: {
|
|
100
|
+
id: string;
|
|
101
|
+
};
|
|
57
102
|
}
|
|
58
103
|
export interface SessionUpdatedEvent extends BaseEvent {
|
|
59
|
-
|
|
60
|
-
|
|
104
|
+
type: "session.updated";
|
|
105
|
+
session: SessionConfig;
|
|
61
106
|
}
|
|
62
107
|
export interface SpeechStartedEvent extends BaseEvent {
|
|
63
|
-
|
|
108
|
+
type: "input_audio_buffer.speech_started";
|
|
64
109
|
}
|
|
65
110
|
export interface SpeechStoppedEvent extends BaseEvent {
|
|
66
|
-
|
|
111
|
+
type: "input_audio_buffer.speech_stopped";
|
|
67
112
|
}
|
|
68
113
|
export interface InputAudioBufferCommittedEvent extends BaseEvent {
|
|
69
|
-
|
|
114
|
+
type: "input_audio_buffer.committed";
|
|
70
115
|
}
|
|
71
116
|
export interface TranscriptionTextEvent extends BaseEvent {
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
117
|
+
type: "conversation.item.input_audio_transcription.text";
|
|
118
|
+
text?: string;
|
|
119
|
+
stash?: string;
|
|
120
|
+
transcript?: string;
|
|
76
121
|
}
|
|
77
122
|
export interface TranscriptionCompletedEvent extends BaseEvent {
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
123
|
+
type: "conversation.item.input_audio_transcription.completed";
|
|
124
|
+
text?: string;
|
|
125
|
+
transcript?: string;
|
|
81
126
|
}
|
|
82
127
|
export interface SessionFinishedEvent extends BaseEvent {
|
|
83
|
-
|
|
128
|
+
type: "session.finished";
|
|
84
129
|
}
|
|
85
130
|
export interface ErrorEvent extends BaseEvent {
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
131
|
+
type: "error";
|
|
132
|
+
error: {
|
|
133
|
+
message: string;
|
|
134
|
+
code?: string;
|
|
135
|
+
};
|
|
91
136
|
}
|
|
92
|
-
export type ServerEvent =
|
|
137
|
+
export type ServerEvent =
|
|
138
|
+
| SessionCreatedEvent
|
|
139
|
+
| SessionUpdatedEvent
|
|
140
|
+
| SpeechStartedEvent
|
|
141
|
+
| SpeechStoppedEvent
|
|
142
|
+
| InputAudioBufferCommittedEvent
|
|
143
|
+
| TranscriptionTextEvent
|
|
144
|
+
| TranscriptionCompletedEvent
|
|
145
|
+
| SessionFinishedEvent
|
|
146
|
+
| ErrorEvent;
|
|
93
147
|
export interface TurnDetectionConfig {
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
148
|
+
type: "server_vad";
|
|
149
|
+
/** VAD检测阈值,推荐设为 0.0,默认值 0.2,范围 [-1, 1] */
|
|
150
|
+
threshold?: number;
|
|
151
|
+
/** VAD断句检测阈值(ms),推荐设为 400,默认值 800,范围 [200, 6000] */
|
|
152
|
+
silence_duration_ms?: number;
|
|
99
153
|
}
|
|
100
154
|
export interface InputAudioTranscriptionConfig {
|
|
101
|
-
|
|
155
|
+
language?: ASRLanguage;
|
|
102
156
|
}
|
|
103
157
|
export interface SessionConfig {
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
158
|
+
input_audio_format?: "pcm" | "opus";
|
|
159
|
+
sample_rate?: 16000 | 8000;
|
|
160
|
+
input_audio_transcription?: InputAudioTranscriptionConfig;
|
|
161
|
+
turn_detection?: TurnDetectionConfig | null;
|
|
108
162
|
}
|
|
109
163
|
export interface ASRClientConfig {
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
164
|
+
/**
|
|
165
|
+
* Audio format
|
|
166
|
+
* @default "pcm"
|
|
167
|
+
*/
|
|
168
|
+
audioFormat?: "pcm" | "opus";
|
|
169
|
+
/**
|
|
170
|
+
* Sample rate in Hz
|
|
171
|
+
* @default 16000
|
|
172
|
+
* @description 支持 16000 和 8000。设置为 8000 时,服务端会先升采样到16000Hz再进行识别,可能引入微小延迟。
|
|
173
|
+
*/
|
|
174
|
+
sampleRate?: 16000 | 8000;
|
|
175
|
+
/**
|
|
176
|
+
* Audio source language
|
|
177
|
+
* @default "zh"
|
|
178
|
+
* @description 支持多种语言,包括 zh(中文)、yue(粤语)、en(英文)、ja(日语)等
|
|
179
|
+
*/
|
|
180
|
+
language?: ASRLanguage;
|
|
181
|
+
/**
|
|
182
|
+
* Enable VAD (Voice Activity Detection) mode
|
|
183
|
+
* @default true
|
|
184
|
+
* @description true = VAD模式(服务端自动检测语音开始/结束),false = Manual模式(客户端手动控制)
|
|
185
|
+
*/
|
|
186
|
+
enableVAD?: boolean;
|
|
187
|
+
/**
|
|
188
|
+
* VAD detection threshold
|
|
189
|
+
* @default 0.2
|
|
190
|
+
* @description 推荐设为 0.0。取值范围 [-1, 1]。较低的阈值会提高 VAD 的灵敏度。
|
|
191
|
+
*/
|
|
192
|
+
vadThreshold?: number;
|
|
193
|
+
/**
|
|
194
|
+
* VAD silence duration threshold in milliseconds
|
|
195
|
+
* @default 800
|
|
196
|
+
* @description 推荐设为 400。取值范围 [200, 6000]。静音持续时长超过该阈值将被认为是语句结束。
|
|
197
|
+
*/
|
|
198
|
+
vadSilenceDurationMs?: number;
|
|
199
|
+
/**
|
|
200
|
+
* Get access token for WebSocket authentication
|
|
201
|
+
*/
|
|
202
|
+
getAccessToken?: () => string | null;
|
|
203
|
+
/**
|
|
204
|
+
* Called when connection is ready (session.created received and session.update sent)
|
|
205
|
+
*/
|
|
206
|
+
onReady?: () => void;
|
|
207
|
+
/**
|
|
208
|
+
* Called when speech is detected (VAD mode only)
|
|
209
|
+
*/
|
|
210
|
+
onSpeechStart?: () => void;
|
|
211
|
+
/**
|
|
212
|
+
* Called when speech stops (VAD mode only)
|
|
213
|
+
*/
|
|
214
|
+
onSpeechEnd?: () => void;
|
|
215
|
+
/**
|
|
216
|
+
* Called on transcript result
|
|
217
|
+
* @param text - Transcribed text
|
|
218
|
+
* @param isFinal - Whether this is the final result
|
|
219
|
+
*/
|
|
220
|
+
onTranscript?: (text: string, isFinal: boolean) => void;
|
|
221
|
+
/**
|
|
222
|
+
* Called when audio buffer is committed (non-VAD mode only)
|
|
223
|
+
*/
|
|
224
|
+
onAudioBufferCommitted?: () => void;
|
|
225
|
+
/**
|
|
226
|
+
* Called when session is finished
|
|
227
|
+
*/
|
|
228
|
+
onSessionFinished?: () => void;
|
|
229
|
+
/**
|
|
230
|
+
* Called on error
|
|
231
|
+
*/
|
|
232
|
+
onError?: (error: Error) => void;
|
|
233
|
+
/**
|
|
234
|
+
* Called on close
|
|
235
|
+
*/
|
|
236
|
+
onClose?: () => void;
|
|
183
237
|
}
|
|
184
238
|
export interface ASRClient {
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
}
|
|
208
|
-
declare const _default$1: (
|
|
239
|
+
/** Connect to ASR service and establish session */
|
|
240
|
+
connect(): Promise<void>;
|
|
241
|
+
/** Start recording from microphone */
|
|
242
|
+
startRecording(): Promise<void>;
|
|
243
|
+
/**
|
|
244
|
+
* Stop recording
|
|
245
|
+
* @description In non-VAD mode, this triggers recognition by sending input_audio_buffer.commit
|
|
246
|
+
*/
|
|
247
|
+
stopRecording(): Promise<void>;
|
|
248
|
+
/**
|
|
249
|
+
* Close connection gracefully
|
|
250
|
+
* @description Sends session.finish and waits for session.finished before closing
|
|
251
|
+
*/
|
|
252
|
+
close(): Promise<void>;
|
|
253
|
+
/**
|
|
254
|
+
* Check if currently recording
|
|
255
|
+
*/
|
|
256
|
+
isRecording(): boolean;
|
|
257
|
+
/**
|
|
258
|
+
* Check if connected to server
|
|
259
|
+
*/
|
|
260
|
+
isConnected(): boolean;
|
|
261
|
+
}
|
|
262
|
+
declare const _default$1: (
|
|
263
|
+
authConfig: Pick<ASRClientConfig, "getAccessToken">
|
|
264
|
+
) => (config: ASRClientConfig) => ASRClient;
|
|
265
|
+
|
|
266
|
+
export interface Recorder {
|
|
267
|
+
/** Start recording */
|
|
268
|
+
start(): Promise<void>;
|
|
269
|
+
/**
|
|
270
|
+
* Stop recording and get base64-encoded WAV audio data. You can use this data to call the ASR API.
|
|
271
|
+
*
|
|
272
|
+
* @returns Base64-encoded WAV audio data
|
|
273
|
+
*/
|
|
274
|
+
stop(): Promise<void>;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
export interface RecorderOptions {
|
|
278
|
+
/** Called when recording starts */
|
|
279
|
+
onStart?: () => void;
|
|
280
|
+
/**
|
|
281
|
+
* Called when recording stops, with base64-encoded WAV audio data. You can use this data to call the ASR API.
|
|
282
|
+
*
|
|
283
|
+
* @param base64 - Base64-encoded WAV audio data
|
|
284
|
+
* @returns void
|
|
285
|
+
*/
|
|
286
|
+
onStop?: (base64: string) => void;
|
|
287
|
+
onError?: (error: Error) => void;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export type ASRHttpStatus = "idle" | "recording" | "recognizing";
|
|
209
291
|
|
|
210
292
|
export interface ASRHttpClientConfig {
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
293
|
+
/** Get access token */
|
|
294
|
+
http?: HttpClient;
|
|
295
|
+
/** Get access token */
|
|
296
|
+
getAccessToken?(): string | null;
|
|
297
|
+
/** Create custom recorder */
|
|
298
|
+
createRecorder?(options?: RecorderOptions): Promise<Recorder>;
|
|
299
|
+
/** Language, default 'zh' */
|
|
300
|
+
language?: string;
|
|
301
|
+
/** Sample rate, default 16000 */
|
|
302
|
+
sampleRate?: number;
|
|
303
|
+
/** Called when recording starts */
|
|
304
|
+
onRecordingStart?: () => void;
|
|
305
|
+
/** Called when recording stops */
|
|
306
|
+
onRecordingStop?: () => void;
|
|
307
|
+
/** Called with recognition result */
|
|
308
|
+
onResult?: (text: string) => void;
|
|
309
|
+
/** Called on error */
|
|
310
|
+
onError?: (error: Error) => void;
|
|
311
|
+
/** Called when status changes */
|
|
312
|
+
onStatusChange?: (status: ASRHttpStatus) => void;
|
|
225
313
|
}
|
|
226
314
|
export interface ASRHttpClient {
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
}
|
|
315
|
+
/** Start recording (press-to-talk) */
|
|
316
|
+
startRecording(): Promise<void>;
|
|
317
|
+
/** Stop recording and get result */
|
|
318
|
+
stopRecording(): Promise<string>;
|
|
319
|
+
/** Record for specific duration then recognize */
|
|
320
|
+
recordAndRecognize(durationMs: number): Promise<string>;
|
|
321
|
+
/** Recognize audio file (File or Blob) */
|
|
322
|
+
recognizeFile(file: File | Blob): Promise<string>;
|
|
323
|
+
/** Recognize audio from URL */
|
|
324
|
+
recognizeUrl(audioUrl: string): Promise<string>;
|
|
325
|
+
}
|
package/types/http.d.ts
ADDED
|
@@ -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 };
|
package/types/index.d.ts
CHANGED
|
@@ -53,6 +53,7 @@ import type { CopilotClientAPI } from "./copilot";
|
|
|
53
53
|
import type { FunctionClientAPI } from "./function";
|
|
54
54
|
import type { TTSClientAPI } from "./tts";
|
|
55
55
|
import type { S3ClientAPI } from "./s3";
|
|
56
|
+
import type { HttpClient } from "./http";
|
|
56
57
|
|
|
57
58
|
/**
|
|
58
59
|
* Configuration options for creating an Amaster client
|
|
@@ -239,6 +240,27 @@ export interface AmasterClient {
|
|
|
239
240
|
*/
|
|
240
241
|
s3: S3ClientAPI;
|
|
241
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
|
+
|
|
242
264
|
/**
|
|
243
265
|
* Check if the user is currently authenticated
|
|
244
266
|
*
|
|
@@ -301,11 +323,12 @@ export type { AuthClientAPI } from "./auth";
|
|
|
301
323
|
export type { EntityClientAPI } from "./entity";
|
|
302
324
|
export type { BpmClientAPI } from "./bpm";
|
|
303
325
|
export type { WorkflowClientAPI } from "./workflow";
|
|
304
|
-
export type { ASRClient, ASRClientConfig, ASRHttpClient, ASRHttpClientConfig } from "./asr";
|
|
326
|
+
export type { ASRClient, ASRClientConfig, ASRHttpClient, ASRHttpClientConfig, Recorder, RecorderOptions } from "./asr";
|
|
305
327
|
export type { CopilotClientAPI } from "./copilot";
|
|
306
328
|
export type { FunctionClientAPI } from "./function";
|
|
307
329
|
export type { TTSClientAPI } from "./tts";
|
|
308
330
|
export type { S3ClientAPI } from "./s3";
|
|
331
|
+
export type { HttpClient } from "./http";
|
|
309
332
|
|
|
310
333
|
// For detailed types, import directly from submodules:
|
|
311
334
|
// import type { LoginParams, User } from '@amaster.ai/client/auth'
|