@amaster.ai/client 1.1.0-beta.71 → 1.1.0-beta.72

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 CHANGED
@@ -16,21 +16,25 @@ function createClient(options) {
16
16
  const {
17
17
  baseURL,
18
18
  headers = {},
19
+ miniProgramRequest,
19
20
  onUnauthorized,
20
21
  onTokenExpired,
21
- autoHandleOAuthCallback
22
+ autoHandleOAuthCallback,
23
+ autoRedirectAfterLogin
22
24
  } = options;
23
25
  const baseHttpClient = httpClient.createHttpClient({
24
26
  baseURL,
25
- headers
27
+ headers,
28
+ miniProgramRequest
26
29
  });
27
30
  const auth = authClient.createAuthClient({
28
31
  baseURL,
29
32
  headers,
30
33
  onTokenExpired,
31
34
  onUnauthorized,
32
- autoHandleOAuthCallback
33
- });
35
+ autoHandleOAuthCallback,
36
+ autoRedirectAfterLogin
37
+ }, baseHttpClient);
34
38
  const createAuthenticatedHttpClient = () => {
35
39
  let isRefreshing = false;
36
40
  let refreshPromise = null;
@@ -57,6 +61,7 @@ function createClient(options) {
57
61
  return !!auth.getAccessToken();
58
62
  }
59
63
  return {
64
+ miniProgramRequest: baseHttpClient.miniProgramRequest,
60
65
  async request(config) {
61
66
  const token = auth.getAccessToken();
62
67
  const authHeaders = token ? { Authorization: `Bearer ${token}` } : {};
@@ -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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MAAM,MAA8CC,yBAAA,CAAgB;AAAA,IAClE,cAAA,EAAgB,MAAM,IAAA,CAAK,cAAA;AAAe,GAC3C,CAAA;AACD,EAAA,MAAM,UAA0DC,6BAAA,CAAoB;AAAA,IAClF,cAAA,EAAgB,MAAM,IAAA,CAAK,cAAA,EAAe;AAAA,IAC1C,IAAA,EAAM;AAAA,GACP,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 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"]}
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,kBAAA;AAAA,IACA,cAAA;AAAA,IACA,cAAA;AAAA,IACA,uBAAA;AAAA,IACA;AAAA,GACF,GAAI,OAAA;AAGJ,EAAA,MAAM,iBAAiBA,2BAAA,CAAiB;AAAA,IACtC,OAAA;AAAA,IACA,OAAA;AAAA,IACA;AAAA,GACD,CAAA;AAID,EAAA,MAAM,OAAmBC,2BAAA,CAAiB;AAAA,IACxC,OAAA;AAAA,IACA,OAAA;AAAA,IACA,cAAA;AAAA,IACA,cAAA;AAAA,IACA,uBAAA;AAAA,IACA;AAAA,KACC,cAAc,CAAA;AAGjB,EAAA,MAAM,gCAAgC,MAAkB;AAEtD,IAAA,IAAI,YAAA,GAAe,KAAA;AACnB,IAAA,IAAI,cAAA,GAA0C,IAAA;AAM9C,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AM,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 miniProgramRequest,\n onUnauthorized,\n onTokenExpired,\n autoHandleOAuthCallback,\n autoRedirectAfterLogin,\n } = options;\n\n // Create the base HTTP client\n const baseHttpClient = createHttpClient({\n baseURL,\n headers,\n miniProgramRequest,\n });\n\n // Create the auth client first using the same base HTTP implementation so\n // mini-program request handling stays consistent across all modules.\n const auth: AuthClient = createAuthClient({\n baseURL,\n headers,\n onTokenExpired,\n onUnauthorized,\n autoHandleOAuthCallback,\n autoRedirectAfterLogin,\n }, baseHttpClient);\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 miniProgramRequest: baseHttpClient.miniProgramRequest,\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.d.cts CHANGED
@@ -9,14 +9,14 @@ export { WorkflowFile, WorkflowInputValue, WorkflowRunRequest, WorkflowRunRespon
9
9
  import { ASRClientConfig, ASRClient, ASRHttpClientConfig, ASRHttpClient } from '@amaster.ai/asr-client';
10
10
  export { ASRClient, ASRClientConfig, ASRHttpClient, ASRHttpClientConfig, ASRLanguage } from '@amaster.ai/asr-client';
11
11
  import { CopilotClient } from '@amaster.ai/copilot-client';
12
- export { ChatMessage, ChatOptions, CopilotClient, FileContent, ImageContent, MessageContent, TextContent } from '@amaster.ai/copilot-client';
12
+ export { Conversation, ConversationController, ConversationControllerOptions, ConversationControllerSnapshot, CopilotClient, Role as CopilotRole, ErrorMessage, FileContent, ImageContent, MessageContent, MessagesItem, TextContent, TextMessage, ThoughtMessage, ToolMessage, UIRenderMessage } from '@amaster.ai/copilot-client';
13
13
  import { FunctionClient } from '@amaster.ai/function-client';
14
14
  export { FunctionClient } from '@amaster.ai/function-client';
15
15
  import { TTSClientConfig, TTSClient } from '@amaster.ai/tts-client';
16
16
  export { TTSClient, TTSClientConfig } from '@amaster.ai/tts-client';
17
17
  import { S3Client } from '@amaster.ai/s3-client';
18
18
  export { S3Client, S3Metadata, UploadRes } from '@amaster.ai/s3-client';
19
- import { HttpClient } from '@amaster.ai/http-client';
19
+ import { MiniProgramRequest, HttpClient } from '@amaster.ai/http-client';
20
20
  export { ClientError, ClientResult, HttpClient, RequestConfig } from '@amaster.ai/http-client';
21
21
 
22
22
  /**
@@ -37,6 +37,13 @@ interface AmasterClientOptions {
37
37
  * Optional custom headers to include in all requests
38
38
  */
39
39
  headers?: Record<string, string>;
40
+ /**
41
+ * Explicit mini-program request implementation, for example `Taro.request`.
42
+ *
43
+ * Prefer providing this in Taro applications instead of relying on runtime
44
+ * globals such as `tt.request` or `globalThis.Taro`.
45
+ */
46
+ miniProgramRequest?: MiniProgramRequest;
40
47
  /**
41
48
  * Callback function triggered when a 401 Unauthorized response is received
42
49
  * Useful for redirecting to login page or showing auth modal
@@ -69,6 +76,15 @@ interface AmasterClientOptions {
69
76
  * @default true
70
77
  */
71
78
  autoHandleOAuthCallback?: boolean;
79
+ /**
80
+ * Automatically redirect to the current page's `?redirect=...` target after any successful login
81
+ *
82
+ * This keeps password login, verification-code login, registration auto-login,
83
+ * and OAuth callback flows aligned by default.
84
+ *
85
+ * @default true
86
+ */
87
+ autoRedirectAfterLogin?: boolean;
72
88
  }
73
89
  /**
74
90
  * Unified Amaster Client
package/dist/index.d.ts CHANGED
@@ -9,14 +9,14 @@ export { WorkflowFile, WorkflowInputValue, WorkflowRunRequest, WorkflowRunRespon
9
9
  import { ASRClientConfig, ASRClient, ASRHttpClientConfig, ASRHttpClient } from '@amaster.ai/asr-client';
10
10
  export { ASRClient, ASRClientConfig, ASRHttpClient, ASRHttpClientConfig, ASRLanguage } from '@amaster.ai/asr-client';
11
11
  import { CopilotClient } from '@amaster.ai/copilot-client';
12
- export { ChatMessage, ChatOptions, CopilotClient, FileContent, ImageContent, MessageContent, TextContent } from '@amaster.ai/copilot-client';
12
+ export { Conversation, ConversationController, ConversationControllerOptions, ConversationControllerSnapshot, CopilotClient, Role as CopilotRole, ErrorMessage, FileContent, ImageContent, MessageContent, MessagesItem, TextContent, TextMessage, ThoughtMessage, ToolMessage, UIRenderMessage } from '@amaster.ai/copilot-client';
13
13
  import { FunctionClient } from '@amaster.ai/function-client';
14
14
  export { FunctionClient } from '@amaster.ai/function-client';
15
15
  import { TTSClientConfig, TTSClient } from '@amaster.ai/tts-client';
16
16
  export { TTSClient, TTSClientConfig } from '@amaster.ai/tts-client';
17
17
  import { S3Client } from '@amaster.ai/s3-client';
18
18
  export { S3Client, S3Metadata, UploadRes } from '@amaster.ai/s3-client';
19
- import { HttpClient } from '@amaster.ai/http-client';
19
+ import { MiniProgramRequest, HttpClient } from '@amaster.ai/http-client';
20
20
  export { ClientError, ClientResult, HttpClient, RequestConfig } from '@amaster.ai/http-client';
21
21
 
22
22
  /**
@@ -37,6 +37,13 @@ interface AmasterClientOptions {
37
37
  * Optional custom headers to include in all requests
38
38
  */
39
39
  headers?: Record<string, string>;
40
+ /**
41
+ * Explicit mini-program request implementation, for example `Taro.request`.
42
+ *
43
+ * Prefer providing this in Taro applications instead of relying on runtime
44
+ * globals such as `tt.request` or `globalThis.Taro`.
45
+ */
46
+ miniProgramRequest?: MiniProgramRequest;
40
47
  /**
41
48
  * Callback function triggered when a 401 Unauthorized response is received
42
49
  * Useful for redirecting to login page or showing auth modal
@@ -69,6 +76,15 @@ interface AmasterClientOptions {
69
76
  * @default true
70
77
  */
71
78
  autoHandleOAuthCallback?: boolean;
79
+ /**
80
+ * Automatically redirect to the current page's `?redirect=...` target after any successful login
81
+ *
82
+ * This keeps password login, verification-code login, registration auto-login,
83
+ * and OAuth callback flows aligned by default.
84
+ *
85
+ * @default true
86
+ */
87
+ autoRedirectAfterLogin?: boolean;
72
88
  }
73
89
  /**
74
90
  * Unified Amaster Client
package/dist/index.js CHANGED
@@ -14,21 +14,25 @@ function createClient(options) {
14
14
  const {
15
15
  baseURL,
16
16
  headers = {},
17
+ miniProgramRequest,
17
18
  onUnauthorized,
18
19
  onTokenExpired,
19
- autoHandleOAuthCallback
20
+ autoHandleOAuthCallback,
21
+ autoRedirectAfterLogin
20
22
  } = options;
21
23
  const baseHttpClient = createHttpClient({
22
24
  baseURL,
23
- headers
25
+ headers,
26
+ miniProgramRequest
24
27
  });
25
28
  const auth = createAuthClient({
26
29
  baseURL,
27
30
  headers,
28
31
  onTokenExpired,
29
32
  onUnauthorized,
30
- autoHandleOAuthCallback
31
- });
33
+ autoHandleOAuthCallback,
34
+ autoRedirectAfterLogin
35
+ }, baseHttpClient);
32
36
  const createAuthenticatedHttpClient = () => {
33
37
  let isRefreshing = false;
34
38
  let refreshPromise = null;
@@ -55,6 +59,7 @@ function createClient(options) {
55
59
  return !!auth.getAccessToken();
56
60
  }
57
61
  return {
62
+ miniProgramRequest: baseHttpClient.miniProgramRequest,
58
63
  async request(config) {
59
64
  const token = auth.getAccessToken();
60
65
  const authHeaders = token ? { Authorization: `Bearer ${token}` } : {};
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;AACl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,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"]}
1
+ {"version":3,"sources":["../src/client.ts"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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 miniProgramRequest,\n onUnauthorized,\n onTokenExpired,\n autoHandleOAuthCallback,\n autoRedirectAfterLogin,\n } = options;\n\n // Create the base HTTP client\n const baseHttpClient = createHttpClient({\n baseURL,\n headers,\n miniProgramRequest,\n });\n\n // Create the auth client first using the same base HTTP implementation so\n // mini-program request handling stays consistent across all modules.\n const auth: AuthClient = createAuthClient({\n baseURL,\n headers,\n onTokenExpired,\n onUnauthorized,\n autoHandleOAuthCallback,\n autoRedirectAfterLogin,\n }, baseHttpClient);\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 miniProgramRequest: baseHttpClient.miniProgramRequest,\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.71",
3
+ "version": "1.1.0-beta.72",
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/entity-client": "1.1.0-beta.71",
76
- "@amaster.ai/asr-client": "1.1.0-beta.71",
77
- "@amaster.ai/copilot-client": "1.1.0-beta.71",
78
- "@amaster.ai/http-client": "1.1.0-beta.71",
79
- "@amaster.ai/bpm-client": "1.1.0-beta.71",
80
- "@amaster.ai/function-client": "1.1.0-beta.71",
81
- "@amaster.ai/s3-client": "1.1.0-beta.71",
82
- "@amaster.ai/tts-client": "1.1.0-beta.71",
83
- "@amaster.ai/workflow-client": "1.1.0-beta.71",
84
- "@amaster.ai/auth-client": "1.1.0-beta.71"
75
+ "@amaster.ai/bpm-client": "1.1.0-beta.72",
76
+ "@amaster.ai/copilot-client": "1.1.0-beta.72",
77
+ "@amaster.ai/auth-client": "1.1.0-beta.72",
78
+ "@amaster.ai/entity-client": "1.1.0-beta.72",
79
+ "@amaster.ai/function-client": "1.1.0-beta.72",
80
+ "@amaster.ai/asr-client": "1.1.0-beta.72",
81
+ "@amaster.ai/http-client": "1.1.0-beta.72",
82
+ "@amaster.ai/tts-client": "1.1.0-beta.72",
83
+ "@amaster.ai/s3-client": "1.1.0-beta.72",
84
+ "@amaster.ai/workflow-client": "1.1.0-beta.72"
85
85
  },
86
86
  "peerDependencies": {
87
87
  "axios": "^1.11.0"
@@ -1,20 +1,15 @@
1
- import type {
2
- SendStreamingMessageResponse,
3
- CancelTaskResponse,
4
- GetTaskResponse,
5
- } from "@a2a-js/sdk";
6
- import type { ClientResult } from "./common";
7
-
8
1
  interface TextContent {
9
2
  type: "text";
10
3
  text: string;
11
4
  }
5
+
12
6
  interface ImageContent {
13
7
  type: "image";
14
8
  data?: string;
15
9
  url?: string;
16
10
  mimeType?: string;
17
11
  }
12
+
18
13
  interface FileContent {
19
14
  type: "file";
20
15
  data?: string;
@@ -22,57 +17,150 @@ interface FileContent {
22
17
  mimeType?: string;
23
18
  name?: string;
24
19
  }
20
+
25
21
  type MessageContent = TextContent | ImageContent | FileContent;
26
- interface ChatMessage {
27
- role: "system" | "user" | "assistant";
28
- content: string | MessageContent[];
22
+
23
+ type Role = "user" | "assistant" | "system";
24
+
25
+ interface BaseMessage {
26
+ messageId: string;
27
+ role?: Role;
28
+ kind: string;
29
+ timestamp?: string;
29
30
  }
30
- interface ChatOptions {
31
- taskId?: string;
31
+
32
+ interface TextMessage extends BaseMessage {
33
+ kind: "text-content" | "message";
34
+ content: string;
32
35
  }
33
- type CopilotClientAPI = {
34
- /**
35
- * Stream messages from Copilot Agent.
36
- *
37
- * @example
38
- * ```typescript
39
- * import { createCopilotClient, Data } from "@amaster.ai/copilot-client";
40
- *
41
- * const client = createCopilotClient();
42
- *
43
- * for await (const response of client.chat([{ role: "user", content: "Hello" }])) {
44
- * // deal response
45
- * }
46
- * ```
47
- */
48
- chat(
49
- messages: ChatMessage[],
50
- options?: ChatOptions
51
- ): AsyncGenerator<SendStreamingMessageResponse, void, unknown>;
52
- cancelChat(taskId: string): Promise<ClientResult<CancelTaskResponse>>;
53
- getChatStatus(taskId?: string): Promise<{
54
- working: boolean;
55
- taskId?: string;
56
- error?: string;
57
- }>;
58
- getHistory(
59
- limit?: number,
60
- next?: string
61
- ): Promise<
62
- | {
63
- messages: SendStreamingMessageResponse[];
64
- next: string;
65
- hasMore: boolean;
36
+
37
+ interface ErrorMessage extends BaseMessage {
38
+ kind: "error";
39
+ content: string;
40
+ }
41
+
42
+ interface ThoughtMessage extends BaseMessage {
43
+ kind: "thought";
44
+ thought: string;
45
+ }
46
+
47
+ interface ToolMessage extends BaseMessage {
48
+ kind: "tool";
49
+ toolName?: string;
50
+ toolStatus?: string;
51
+ toolDescription?: string;
52
+ response?: unknown;
53
+ }
54
+
55
+ interface UIRenderMessage extends BaseMessage {
56
+ kind: "ui-render";
57
+ spec: {
58
+ root: string;
59
+ elements: Record<
60
+ string,
61
+ {
62
+ type: string;
63
+ props?: Record<string, unknown>;
64
+ children?: string[];
66
65
  }
67
- | undefined
68
- >;
69
- newConversation(): Promise<void>;
66
+ >;
67
+ };
68
+ }
69
+
70
+ type MessagesItem =
71
+ | TextMessage
72
+ | ErrorMessage
73
+ | ThoughtMessage
74
+ | ToolMessage
75
+ | UIRenderMessage
76
+ | BaseMessage;
77
+
78
+ interface Conversation {
79
+ taskId: string;
80
+ status: "submitted" | "working" | "completed" | "error";
81
+ messages: MessagesItem[];
82
+ lastUpdated: string;
83
+ historyId?: string;
84
+ system?: {
85
+ level: "newConversation";
86
+ content?: string;
87
+ };
88
+ }
89
+
90
+ interface HistoryState {
91
+ next: string | null;
92
+ hasMore: boolean;
93
+ }
94
+
95
+ interface UpdateMessageInput {
96
+ taskId: string;
97
+ messageId: string;
98
+ content?: string;
99
+ partial?: boolean;
100
+ status?: string;
101
+ response?: unknown;
102
+ metadata?: Record<string, unknown>;
103
+ }
104
+
105
+ interface ConversationControllerSnapshot {
106
+ starting: boolean;
107
+ isLoading: boolean;
108
+ isLoadingHistory: boolean;
109
+ historyState: HistoryState;
110
+ conversations: Conversation[];
111
+ }
112
+
113
+ interface ConversationStrings {
114
+ thinking: string;
115
+ errorMessage: string;
116
+ cancelled: string;
117
+ }
118
+
119
+ interface ConversationControllerOptions {
120
+ strings: ConversationStrings;
121
+ mode?: "conversation" | "single-turn";
122
+ getContextId?: () => string;
123
+ loadHistoryOnInit?: boolean;
124
+ resumeOnInit?: boolean;
125
+ }
126
+
127
+ interface ConversationController {
128
+ getSnapshot(): ConversationControllerSnapshot;
129
+ subscribe(listener: (snapshot: ConversationControllerSnapshot) => void): () => void;
130
+ init(): Promise<void>;
131
+ destroy(): void;
132
+ sendMessage(userContent: string): Promise<void>;
133
+ abort(): void;
134
+ cancelChat(taskId?: string): Promise<void>;
135
+ resetConversation(greeting?: string): void;
136
+ startNewConversation(): Promise<void>;
137
+ loadHistory(limit?: number, next?: string): Promise<void>;
138
+ loadMoreHistory(): Promise<void>;
139
+ getConversation(taskId: string): Conversation | undefined;
140
+ clearConversation(taskId: string): void;
141
+ removeMessage(taskId: string, messageId: string): void;
142
+ updateMessage(input: UpdateMessageInput): void;
143
+ }
144
+
145
+ type CopilotClientAPI = {
146
+ createConversationController(options: ConversationControllerOptions): ConversationController;
70
147
  };
71
148
 
72
149
  export {
73
- type ChatMessage,
74
- type ChatOptions,
75
150
  type CopilotClientAPI,
151
+ type ConversationController,
152
+ type ConversationControllerOptions,
153
+ type ConversationControllerSnapshot,
154
+ type ConversationStrings,
155
+ type Conversation,
156
+ type MessagesItem,
157
+ type TextMessage,
158
+ type ErrorMessage,
159
+ type ThoughtMessage,
160
+ type ToolMessage,
161
+ type UIRenderMessage,
162
+ type Role,
163
+ type UpdateMessageInput,
76
164
  type FileContent,
77
165
  type ImageContent,
78
166
  type MessageContent,
package/types/http.d.ts CHANGED
@@ -21,6 +21,7 @@ type AdapterResponse = {
21
21
  headers?: unknown;
22
22
  };
23
23
  type HttpAdapter = (_config: RequestConfig) => Promise<AdapterResponse>;
24
+ type MiniProgramRequest = (_options: any) => any;
24
25
  type HttpClientOptions = {
25
26
  /**
26
27
  * HTTP adapter to use:
@@ -31,6 +32,10 @@ type HttpClientOptions = {
31
32
  * - function: custom adapter
32
33
  */
33
34
  adapter?: "taro" | "axios" | AxiosInstance | HttpAdapter;
35
+ /**
36
+ * Explicit mini-program request implementation, for example `Taro.request`.
37
+ */
38
+ miniProgramRequest?: MiniProgramRequest;
34
39
  /**
35
40
  * Base URL to prefix when `config.url` is relative (e.g. "/api/...").
36
41
  *
@@ -69,6 +74,7 @@ type HttpClientOptions = {
69
74
  };
70
75
  type HttpClient = {
71
76
  request<T>(_config: RequestConfig): Promise<ClientResult<T>>;
77
+ miniProgramRequest?: MiniProgramRequest;
72
78
  };
73
79
  /**
74
80
  * Create an HTTP client instance
@@ -92,4 +98,4 @@ type HttpClient = {
92
98
  */
93
99
  declare function createHttpClient(axiosInstanceOrOptions?: AxiosInstance | HttpClientOptions): HttpClient;
94
100
 
95
- export { type AdapterResponse, type ClientError, type ClientResult, type HttpAdapter, type HttpClient, type HttpClientOptions, type RequestConfig, createHttpClient };
101
+ export { type AdapterResponse, type ClientError, type ClientResult, type HttpAdapter, type HttpClient, type HttpClientOptions, type MiniProgramRequest, type RequestConfig, createHttpClient };
package/types/index.d.ts CHANGED
@@ -64,7 +64,7 @@ export interface AmasterClientOptions {
64
64
  * Base URL for the Amaster API
65
65
  *
66
66
  */
67
- baseURL: string;
67
+ baseURL?: string;
68
68
 
69
69
  /**
70
70
  * Optional custom headers to include in ALL requests
@@ -75,6 +75,11 @@ export interface AmasterClientOptions {
75
75
  */
76
76
  headers?: Record<string, string>;
77
77
 
78
+ /**
79
+ * Explicit mini-program request implementation, for example `Taro.request`.
80
+ */
81
+ miniProgramRequest?: import("./http").MiniProgramRequest;
82
+
78
83
  /**
79
84
  * Callback triggered when a 401 Unauthorized response is received
80
85
  *